okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
67a48427b
main
1"""Shared status/monitor grammar for the source launcher and portable client. 2 3This module and the one-shot status path use only Python's standard library. 4Textual is imported only when an interactive monitor actually starts. 5""" 6 7from __future__import annotations 8 9import argparse 10import contextlib 11import io 12import json 13import os 14import sys 15 16from strata_cli .client import ClientError ,Endpoint 17from strata_cli import connections 18 19 20def _connection (p :argparse .ArgumentParser )-> None : 21p .add_argument ("--url" ,help = "Strata server root; remote connections require HTTPS" ) 22p .add_argument ("--connection" ,metavar = "NAME" ,help = "saved read-only connection" ) 23p .add_argument ("--credential-env" ,metavar = "NAME" , 24help = "environment variable containing the server credential" ) 25p .add_argument ("--timeout" ,type = float ,help = "bounded request timeout in seconds (default 3)" ) 26 27 28def add_status (sp :argparse ._SubParsersAction )-> None : 29status = sp .add_parser ("status" ,help = "one read-only telemetry snapshot" ) 30_connection (status ) 31status .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 32status .add_argument ("--json" ,action = "store_true" ,help = "alias for --output json" ) 33status .add_argument ("--quiet" ,action = "store_true" ,help = "suppress human informational output" ) 34 35 36def running_launch ()-> dict | None : 37"""The server a `strata launch` has running (address and its key), when no address was given: so `strata monitor` needs no --url. 38Nothing is read when a connection, STRATA_URL or STRATA_CONNECTION names the server, and a thin monitor bundle has no launch code.""" 39if os .environ .get ("STRATA_URL" )or os .environ .get ("STRATA_CONNECTION" ): 40return None 41try : 42from strata_cli .launch .cmd import launch_info 43info = launch_info () 44except Exception :# noqa: BLE001 - no launch code, no profiles: use the default address 45return None 46return info if info and info .get ("running" )and info .get ("url" )else None 47 48 49def add_monitor (sp :argparse ._SubParsersAction )-> None : 50monitor = sp .add_parser ("monitor" ,help = "read-only terminal monitor: seven views (Overview ... Logs, Connect), the same as the one strata launch opens" ) 51_connection (monitor ) 52monitor .add_argument ("--once" ,action = "store_true" ,help = "print one snapshot without starting the TUI" ) 53monitor .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 54monitor .add_argument ("--json" ,action = "store_true" ,help = "alias for --output json with --once" ) 55monitor .add_argument ("--quiet" ,action = "store_true" ,help = "suppress one-shot human output" ) 56monitor .add_argument ("--theme" ,choices = ("auto" ,"dark" ,"light" ,"terminal" ),default = "auto" ) 57monitor .add_argument ("--color" ,choices = ("auto" ,"always" ,"never" ),default = "auto" ) 58monitor .add_argument ("--glyphs" ,choices = ("auto" ,"unicode" ,"braille" ,"ascii" ),default = "auto" ) 59monitor .add_argument ("--interval" ,type = float ,default = 1.0 ) 60monitor .add_argument ("--requests" ,type = int ,default = 12 ) 61 62 63def add_logs (sp :argparse ._SubParsersAction )-> None : 64logs = sp .add_parser ("logs" ,help = "bounded redacted request activity (read only)" ) 65_connection (logs ) 66logs .add_argument ("--source" ,choices = ("runtime" ,"harness" ),default = "runtime" ) 67logs .add_argument ("--follow" ,action = "store_true" ,help = "poll for new transitions until Ctrl+C" ) 68logs .add_argument ("--interval" ,type = float ,default = 2.0 , 69help = "follow poll interval in seconds (0.5–30; default 2)" ) 70logs .add_argument ("--output" ,choices = ("human" ,"json" ,"jsonl" ),default = "human" ) 71logs .add_argument ("--json" ,action = "store_true" ,help = "alias for --output json without --follow" ) 72logs .add_argument ("--quiet" ,action = "store_true" ,help = "suppress human progress text" ) 73 74 75def add_connections (sp :argparse ._SubParsersAction )-> None : 76connection = sp .add_parser ("connection" ,help = "save monitor endpoints without storing credential values" ) 77actions = connection .add_subparsers (dest = "connection_command" ,required = True ) 78create = actions .add_parser ("create" ,help = "save a named server endpoint" ) 79create .add_argument ("name" ) 80create .add_argument ("--url" ,required = True ) 81create .add_argument ("--prefix" ,default = "" ,help = "reverse-proxy path prefix, e.g. /strata" ) 82create .add_argument ("--credential-env" ,default = "STRATA_TELEMETRY_KEY" ) 83show = actions .add_parser ("show" ,help = "show a saved connection without its credential" ) 84show .add_argument ("name" ) 85actions .add_parser ("list" ,help = "list saved connections" ) 86set_command = actions .add_parser ("set" ,help = "edit one URL, prefix or credential reference" ) 87set_command .add_argument ("name" ) 88set_command .add_argument ("assignment" ,metavar = "KEY=VALUE" ) 89set_command .add_argument ("--plan" ,action = "store_true" ) 90set_command .add_argument ("--if-revision" ,metavar = "REVISION" ) 91for command in (create ,show ,actions .choices ["list" ],set_command ): 92command .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 93command .add_argument ("--json" ,action = "store_true" ,help = "alias for --output json" ) 94command .add_argument ("--quiet" ,action = "store_true" ,help = "suppress human informational output" ) 95 96config = sp .add_parser ("config" ,help = "inspect effective client connection settings" ) 97config_actions = config .add_subparsers (dest = "config_command" ,required = True ) 98effective = config_actions .add_parser ("show" ,help = "show connection and credential origins" ) 99effective .add_argument ("--effective" ,action = "store_true" ,help = "show resolved settings (default)" ) 100_connection (effective ) 101effective .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 102effective .add_argument ("--json" ,action = "store_true" ,help = "alias for --output json" ) 103effective .add_argument ("--quiet" ,action = "store_true" ,help = "suppress human informational output" ) 104 105 106def parser ()-> argparse .ArgumentParser : 107ap = argparse .ArgumentParser (prog = "strata-monitor" ,description = "Read-only Strata serving client" ) 108sp = ap .add_subparsers (dest = "command" ,required = True ) 109add_status (sp ) 110add_monitor (sp ) 111add_logs (sp ) 112add_connections (sp ) 113return ap 114 115 116def _file_words (exc :BaseException )-> str : 117try : 118from strata_control import longpath 119except ImportError :# the standalone monitor bundle does not carry strata_control 120return f"local file operation failed ( { type ( exc ). __name__ } )" 121return longpath .file_words (exc ) 122 123 124def _error (message :str ,code :int ,machine :bool )-> int : 125if machine : 126json .dumps ({"schema_version" :1 ,"ok" :False ,"error" : {"code" :code ,"message" :message }})) 127else : 128f"strata: { message } " ,file = sys .stderr ) 129return code 130 131 132def _local_command (a :argparse .Namespace ,machine :bool )-> int : 133if a .command == "config" : 134resolved = connections .resolve (url = a .url ,connection = a .connection , 135credential_env = a .credential_env ,timeout = a .timeout ) 136payload = {"schema_version" :1 ,"ok" :True ,"effective" :resolved } 137json .dumps (payload if machine else resolved ,indent = None if machine else 2 , 138ensure_ascii = False )) 139return 0 140action = a .connection_command 141if action == "list" : 142rows = connections .list_connections () 143payload = {"schema_version" :1 ,"ok" :True ,"connections" :rows } 144elif action == "show" : 145value ,revision = connections .load (a .name ) 146payload = {"schema_version" :1 ,"ok" :True ,"connection" :value ,"revision" :revision } 147elif action == "create" : 148value ,revision = connections .create (a .name ,a .url ,prefix = a .prefix , 149credential_env = a .credential_env ) 150payload = {"schema_version" :1 ,"ok" :True ,"connection" :value ,"revision" :revision } 151else : 152value ,revision = connections .propose (a .name ,a .assignment ) 153if a .if_revision is not None and a .if_revision != revision : 154raise connections .ConnectionError ("connection changed since preview; inspect it again" ,6 ) 155if a .plan : 156payload = {"schema_version" :1 ,"ok" :True ,"connection" :value , 157"revision" :revision ,"would_save" :value != connections .load (a .name )[0 ]} 158else : 159saved ,new_revision = connections .save (a .name ,value ,expected_revision = revision ) 160payload = {"schema_version" :1 ,"ok" :True ,"connection" :saved , 161"previous_revision" :revision ,"revision" :new_revision } 162json .dumps (payload if machine else {k :v for k ,v in payload .items ()if k not in ("schema_version" ,"ok" )}, 163indent = None if machine else 2 ,ensure_ascii = False )) 164return 0 165 166 167def run (a :argparse .Namespace )-> int : 168machine = a .output in ("json" ,"jsonl" )or getattr (a ,"json" ,False ) 169quiet = bool (getattr (a ,"quiet" ,False )and not machine ) 170try : 171if a .command in ("connection" ,"config" ): 172if quiet : 173with contextlib .redirect_stdout (io .StringIO ()): 174return _local_command (a ,machine ) 175return _local_command (a ,machine ) 176if a .command == "logs" : 177if not 0.5 <= a .interval <= 30 : 178return _error ("--interval must be 0.5–30 seconds" ,2 ,machine ) 179if a .json : 180if a .follow or a .output == "jsonl" : 181return _error ("--json is one-shot only; use --follow --output jsonl" ,2 ,machine ) 182a .output = "json" 183if a .follow and a .output == "json" : 184return _error ("--follow requires human or jsonl output" ,2 ,machine ) 185if not a .follow and a .output == "jsonl" : 186return _error ("jsonl output requires --follow" ,2 ,machine ) 187if a .source == "harness" : 188return _error ("shared local harness activity is unavailable; use --source runtime" ,5 ,machine ) 189if a .command == "monitor" and (a .interval < 0.5 or a .interval > 30 or not 1 <= a .requests <= 50 ): 190return _error ("--interval must be 0.5–30 seconds and --requests must be 1–50" ,2 ,machine ) 191if a .command == "monitor" and (a .json or a .output == "json" )and not a .once : 192return _error ("JSON monitor output requires --once; interactive monitor uses a terminal" ,2 ,machine ) 193if a .command == "monitor" and not a .once and not sys .stdout .isatty (): 194return _error ("interactive monitor needs a terminal; use --once or strata status --json" ,2 ,machine ) 195found = running_launch ()if a .command in ("monitor" ,"status" ,"logs" )and not (a .url or a .connection )else None 196resolved = connections .resolve (url = found ["url" ]if found else a .url ,connection = a .connection , 197credential_env = a .credential_env ,timeout = a .timeout ) 198endpoint = Endpoint (resolved ["url" ],os .environ .get (resolved ["credential_env" ])or (found or {}).get ("key" ), 199resolved ["timeout_s" ],resolved ["prefix" ]) 200if a .command == "logs" : 201from strata_cli .logs import run as run_logs 202return run_logs (endpoint ,follow = a .follow ,output = a .output ,interval = a .interval ,quiet = quiet ) 203if machine or a .command == "status" or a .once : 204snapshot = endpoint .snapshot () 205if machine : 206json .dumps ({"schema_version" :1 ,"ok" :True ,"snapshot" :snapshot }, 207ensure_ascii = False ,allow_nan = False )) 208return 0 209if a .command == "status" or a .once : 210from strata_cli .render import render_view 211if not quiet : 212render_view (snapshot ,"overview" ,width = 80 ,height = 24 )) 213return 0 214try : 215from strata_cli .launch .monitor_ext import LaunchMonitor 216except ImportError : 217# the portable monitor bundle carries the read-only client only (no launch/Connect view): run the plain Monitor 218try : 219from strata_cli .monitor import MonitorApp 220except ImportError : 221return _error ("monitor component missing; install the optional terminal UI dependency" ,5 ,machine ) 222MonitorApp (endpoint ,None ,interval = a .interval ,requests = a .requests , 223theme = a .theme ,color = a .color ,glyphs = a .glyphs ).run () 224return 0 225# the one monitor, with the same seven views as the one `strata launch` opens (Connect is key 7 and works against this --url 226# server); q just detaches here: nothing was started by this command, so there is nothing to stop 227LaunchMonitor (endpoint ,None ,info = {"url" :endpoint .base_url ,"urls" : [endpoint .base_url ],"key" :endpoint .credential or "" ,"model" :"" , 228"profile" :None ,"name" :None },ask_quit = False ,interval = a .interval ,requests = a .requests , 229theme = a .theme ,color = a .color ,glyphs = a .glyphs ).run () 230return 0 231except ClientError as e : 232return _error (str (e ),e .exit_code ,machine ) 233except connections .ConnectionError as e : 234return _error (str (e ),e .exit_code ,machine ) 235except ValueError as e : 236return _error (str (e ),2 ,machine ) 237except BrokenPipeError : 238return 0 239except OSError as e : 240return _error (_file_words (e ),6 ,machine ) 241except KeyboardInterrupt : 242if a .command == "logs" and a .follow : 243return 0 244return _error ("interrupted; operation completion may be unknown" ,130 ,machine ) 245 246 247def main (argv :list [str ]| None = None )-> int : 248return run (parser ().parse_args (argv ))