okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1"""The Strata Monitor as `strata launch` opens it: the same monitor plus a Connect view and a quit question. 2 3Everything about the monitor itself (the views, colours, polling, key hints) is `strata_cli.monitor.MonitorApp`, unchanged. 4This subclass adds 5* the seventh view, Connect (key 7, and the arrow keys reach it like any other view: Overview ... Logs, Connect, then round to Overview): the 6address, the API key hint and copy-ready setup for each app, with `c` copy, `w` write the config for you after a backup, `h` check that the 7app's settings reach a server that answers a prompt and a tool call correctly; 8* q: asks whether to keep serving in the background or stop (stopping frees the graphics memory). 9 10The list says two different things about each app and keeps them apart: what its maker's version was tested with ("Vendor tested", fixed 11history), and whether THIS server answered the app's prompt and tool call just now ("This server": Not checked / Checking / Passed / Failed). 12""" 13 14from __future__import annotations 15 16import textwrap 17import threading 18 19from rich .text import Text 20from textual .widgets import Static 21 22from strata_cli import nav 23from strata_cli .launch import check ,harness 24from strata_cli .launch .screens import ConfirmScreen 25from strata_cli .launch .widgets import DARK ,LIGHT ,Glyphs 26from strata_cli .monitor import MonitorApp 27 28CONNECT = 6 # the index of the Connect view (the seventh) 29 30 31def connect_palette (theme :str ,color :bool ): 32"""The colours of the Connect view for the monitor's theme: dark, light (readable on white), or the terminal's own (no colours set).""" 33if not color or theme == "terminal" : 34return None 35return LIGHT if theme == "light" else DARK 36 37 38class LaunchMonitor (MonitorApp ): 39def __init__ (self ,endpoint ,snapshot ,* ,info :dict ,ask_quit :bool = True ,** kw )-> None : 40super ().__init__ (endpoint ,snapshot ,** kw ) 41self .info = info 42self .ask_quit = ask_quit # False: plain `strata monitor` (q detaches, nothing to stop) 43self .connect_enabled = True 44self .connect_index = 0 45self .show_key = False 46self .check_results :dict [str ,list [check .Check ]| str ]= {} 47self .glyphs = Glyphs () 48self .stop_requested = False 49self .notice = "" 50self .view_before_connect = 0 51self .quiet_note :str | None = None # "New engine X is available. Press u to update." (from the last check; local file only) 52self .updating = False 53 54# ---- a newer engine: one quiet line, and u to update (strata_control/engine_update.py) 55def on_mount (self )-> None : 56super ().on_mount () 57self ._note_refresh () 58if self .info .get ("daily_check" ): 59try : 60from strata_control import engine_update 61engine_update .start_daily_check (on_done = self ._note_from_thread )# a thread of its own; offline it ends without a word 62except Exception :# noqa: BLE001 - never a message 63pass 64 65def _note_refresh (self )-> None : 66try : 67from strata_control import engine_update 68self .quiet_note = engine_update .monitor_note () 69except Exception :# noqa: BLE001 70self .quiet_note = None 71if self .is_mounted and self .view < 6 : 72self ._paint () 73 74def _note_from_thread (self )-> None : 75try : 76self .call_from_thread (self ._note_refresh ) 77except Exception :# noqa: BLE001 - the monitor may be closing 78pass 79 80def action_update_engine (self )-> None : 81if self .updating or self .closing : 82return 83self .updating = True 84threading .Thread (target = self ._update_worker ,name = "strata-engine-update" ,daemon = True ).start () 85 86def _say_line (self ,text :str )-> None : 87def show ()-> None : 88self .selection_notice = text 89self ._paint () 90try : 91self .call_from_thread (show ) 92except Exception :# noqa: BLE001 93pass 94 95def _ask_from_thread (self ,question :str ,default :bool )-> bool : 96box :dict = {} 97done = threading .Event () 98 99def show ()-> None : 100def got (choice :str | None )-> None : 101box ["yes" ]= choice == "yes" 102done .set () 103self .push_screen (ConfirmScreen (question ,"An engine update needs the model stopped first. Nothing is changed unless you choose Yes." , 104 [("yes" ,"Yes" ), ("no" ,"No" )]),got ) 105self .call_from_thread (show ) 106done .wait () 107return bool (box .get ("yes" ,default )) 108 109def _update_worker (self )-> None : 110from strata_control import engine_update ,updater 111try : 112self ._say_line ("Checking for a newer engine..." ) 113out = engine_update .run_flow (ask = self ._ask_from_thread ,say = self ._say_line ) 114text = engine_update .summary (out ) 115except updater .UpdateError as exc : 116text = str (exc ) 117except Exception as exc :# noqa: BLE001 - a sentence, never a trace 118text = f"The update did not run: { exc } " 119self .updating = False 120 121def finish ()-> None : 122self .selection_notice = text 123self .next_poll_at = 0.0 # the model may be back: look again now 124self ._note_refresh () 125try : 126self .call_from_thread (finish ) 127except Exception :# noqa: BLE001 128pass 129 130@property 131def connect_open (self )-> bool : 132return self .view == CONNECT 133 134# ---- quit asks 135def action_quit (self )-> None : 136if self .closing : 137return 138if not self .ask_quit : 139return super ().action_quit () 140 141def done (choice :str | None )-> None : 142if choice == "keep" : 143self .closing = True 144self .exit () 145elif choice == "stop" : 146self .stop_requested = True 147self .closing = True 148self .exit () 149 150self .push_screen (ConfirmScreen ("Leave the monitor?" ,"Keeping it serving lets your apps go on using the model. " 151"Stopping unloads the model and frees the graphics memory." , 152 [("keep" ,"Keep serving in the background" ), ("stop" ,"Stop serving and free the memory" ), 153 ("cancel" ,"Stay in the monitor" )]),done ) 154 155# ---- the Connect view is the seventh view 156def _harness (self )-> harness .Harness : 157return harness .HARNESSES [self .connect_index % len (harness .HARNESSES )] 158 159def action_connect (self )-> None : 160self ._set_view (CONNECT ) 161 162def _set_view (self ,index :int )-> None : 163if index != CONNECT and self .view == CONNECT : 164self .notice = "" 165if index == CONNECT and self .view != CONNECT : 166self .view_before_connect = self .view 167self .notice = "" 168super ()._set_view (index ) 169 170def action_next_row (self )-> None : 171if self .connect_open : 172self .connect_index = (self .connect_index + 1 )% len (harness .HARNESSES ) 173self .notice = "" 174self ._paint () 175else : 176super ().action_next_row () 177 178def action_previous_row (self )-> None : 179if self .connect_open : 180self .connect_index = (self .connect_index - 1 )% len (harness .HARNESSES ) 181self .notice = "" 182self ._paint () 183else : 184super ().action_previous_row () 185 186def action_filter_clear (self )-> None : 187if self .connect_open : 188self ._set_view (self .view_before_connect )# Esc leaves the Connect view for the one you came from 189else : 190super ().action_filter_clear () 191 192def action_request_detail (self )-> None : 193if not self .connect_open : 194super ().action_request_detail () 195 196def on_key (self ,event )-> None : 197if event .key == "u" : 198self .action_update_engine () 199event .stop () 200return 201if not self .connect_open : 202return 203key = event .key 204if key == "c" : 205self ._copy () 206elif key == "w" : 207self ._write () 208elif key == "k" : 209self .show_key = not self .show_key 210self ._paint () 211elif key == "h" : 212self ._check () 213else : 214return 215event .stop () 216 217def _rendered (self )-> dict : 218h = self ._harness () 219key = self .info .get ("key" )or "" 220if not self .info .get ("model" ): 221self .info ["model" ]= ((self .latest or {}).get ("model" )or {}).get ("id" )or "strata" 222return harness .render (h ,harness .target (self .info ["url" ],key ,self .info .get ("model" )or ((self .latest or {}).get ("model" )or {}).get ("id" )or "strata" ,self .info .get ("context" ))) 223 224def _copy (self )-> None : 225out = self ._rendered () 226text = "\n\n" .join (f"# { f [ 'path' ] } \n { f [ 'text' ] } " for f in out ["files" ]) 227if out ["env" ]: 228text += "\n\n" + "\n" .join (f" { k } = { v } " for k ,v in out ["env" ].items ()) 229try : 230self .copy_to_clipboard (text ) 231self .notice = "Copied (if your terminal allows it)." 232except Exception :# noqa: BLE001 233self .notice = "! Your terminal does not allow copying; use: strata connect " + self ._harness ().id 234self ._paint () 235 236def _write (self )-> None : 237h = self ._harness () 238out = self ._rendered () 239if not out ["files" ]: 240self .notice = "! Nothing to write for this app." 241self ._paint () 242return 243 244def done (choice :str | None )-> None : 245if choice != "write" : 246return 247lines = [] 248for f in out ["files" ]: 249try : 250r = harness .write_file (f ) 251lines .append (f" { r [ 'action' ] } { r [ 'path' ] } " + (f" (backup { r [ 'backup' ] } )" if r ["backup" ]else "" )) 252except OSError as e : 253lines .append (f"could not write { f [ 'path' ] } : { e } " ) 254self .notice = "; " .join (lines ) 255self ._paint () 256 257self .push_screen (ConfirmScreen (f"Write { h . title } 's settings?" ,"A file that exists is copied to a backup first.\n" 258+ "\n" .join (f" { f [ 'path' ] } " for f in out ["files" ]), 259 [("write" ,"Write it" ), ("no" ,"Not now" )]),done ) 260 261def _check (self )-> None : 262h = self ._harness () 263self .check_results [h .id ]= "running" 264self .notice = "Checking: one prompt and one tool call. This can take a minute on a big model." 265self ._paint () 266key = self .info .get ("key" )or "" 267url = self .info ["url" ] 268model = self .info .get ("model" )or "strata" 269 270def work ()-> None : 271res = check .run_checks (h .id ,url ,key ,model ) 272self .check_results [h .id ]= res 273self .notice = "Checked: " + ("both worked." if all (c .ok for c in res )else "something did not work; see the lines below the setup." ) 274try : 275self .call_from_thread (self ._paint ) 276except Exception :# noqa: BLE001 277pass 278 279threading .Thread (target = work ,daemon = True ).start () 280 281# ---- painting 282def _paint (self ,size = None )-> None : 283if not self .connect_open : 284super ()._paint (size ) 285if self .ask_quit and not self .error and not self .selection_notice and self .connection_state == "connected" and not self .frozen : 286try : 287msg = "Read only | q asks: keep serving or stop | 7 connect an app" 288width = (size or self .screen .size ).width 289if width < 78 : 290msg = "q asks: keep serving or stop | 7 connect" 291if self .quiet_note :# a newer engine: the one quiet line replaces the hints it has no room beside 292msg = self .quiet_note + (" | q asks: keep serving or stop" if width >= 110 else "" ) 293self .query_one ("#message" ,Static ).update (msg ) 294except Exception :# noqa: BLE001 295pass 296return 297size = self .screen .size if size is None else size 298width = max (30 ,size .width - 2 ) 299self .query_one ("#content" ,Static ).update (self .connect_text (width ,size .height - 2 )) 300pal = connect_palette (self .theme_choice ,self .color_choice != "never" ) 301idle = ("c copy w write it for me (keeps a backup) h check it k key Esc back " if width >= 100 else "c copy w write h check Esc back " )+ \ 302f" { nav . keys ( True ) } views q quit" 303msg = self .notice or idle 304mute = pal .mute if pal else "" 305self .query_one ("#message" ,Static ).update (Text (msg ,style = (pal .warn if pal else "" )if msg .startswith ("!" )else mute ,no_wrap = False )) 306self .query_one ("#message" ,Static ).styles .height = 2 if len (msg )> width else 1 307 308# ---- what each app's row says 309@staticmethod 310def vendor_tested (h :harness .Harness )-> str : 311"""What the app's maker's version was tested with (fixed history, nothing to do with this server).""" 312return "built into Strata" if h .built_in else (h .tested or "not tested" ) 313 314def server_state (self ,h :harness .Harness )-> tuple [str ,str ]: 315"""(words, kind) for THIS server and this app: Not checked / Checking / Passed (n/n) / Failed (n/n); kind is none | run | ok | bad.""" 316res = self .check_results .get (h .id ) 317if res == "running" : 318return "Checking..." ,"run" 319if isinstance (res ,list )and res : 320okn = sum (1 for c in res if c .ok ) 321return (f"Passed ( { okn } / { len ( res ) } )" ,"ok" )if okn == len (res )else (f"Failed ( { okn } / { len ( res ) } )" ,"bad" ) 322return "Not checked" ,"none" 323 324 325@staticmethod 326def fit (text :str ,width :int )-> str : 327"""One line, cut with an ellipsis instead of wrapping onto the next row.""" 328return text if len (text )<= width else text [:max (1 ,width - 1 )]+ "…" 329 330def connect_text (self ,width :int ,height :int | None = None )-> Text : 331g = self .glyphs 332height = max (8 ,height if height is not None else self .screen .size .height ) 333compact = height < 24 or width < 70 334pal = connect_palette (self .theme_choice ,self .color_choice != "never" ) 335accent = pal .accent if pal else "" 336mute = pal .mute if pal else "dim" 337warn_style = pal .warn if pal else "bold" 338bad_style = pal .bad if pal else "bold" 339sel_bg = f" on { pal . sel } " if pal else " reverse" 340bold_accent = f"bold { accent } " .strip () 341state = {"connected" :"[LIVE]" ,"stale" :"[STALE]" ,"connecting" :"[CONNECTING]" ,"disconnected" :"[DISCONNECTED]" , 342"auth_required" :"[AUTH REQUIRED]" }.get (self .connection_state ,"[LIVE]" ) 343t = Text (no_wrap = True ,overflow = "crop" ) 344head = f"STRATA Connect { self . info [ 'url' ] } " 345if len (head )+ len (state )+ 2 <= width : 346t .append (head ,style = bold_accent ) 347t .append (" " * max (2 ,width - len (head )- len (state ))+ state + "\n" ,style = bold_accent ) 348else : 349t .append (self .fit (head ,width )+ "\n" ,style = bold_accent ) 350t .append_text (nav .styled (CONNECT ,width ,True ,accent = accent ,color = pal is not None )) 351t .append ("\n" ) 352t .append (g .rule * min (width ,100 )+ "\n" ,style = mute ) 353key = self .info .get ("key" )or "" 354shown = key if self .show_key else (key [:10 ]+ g .mask * 4 if key else "off" ) 355if compact : 356t .append (self .fit (f"Connect an app { self . info [ 'url' ] } /v1 key { shown } (k { 'hide' if self . show_key else 'show' } )" ,width )+ "\n" ,style = bold_accent ) 357else : 358t .append ("Connect an app" ,style = bold_accent ) 359line = f" URL { self . info [ 'url' ] } /v1 model { self . info . get ( 'model' ) or 'strata' } key { shown } " 360if len (line )> width - 9 :# too long for the line: the model name goes, the address and the key stay 361line = f" URL { self . info [ 'url' ] } /v1 key { shown } " 362t .append (self .fit (line ,width - 9 )) 363t .append ("(k hide)" if self .show_key else "(k show)" ,style = mute ) 364t .append ("\n" ) 365t .append (self .fit (f" Claude Code and other Anthropic apps use { self . info [ 'url' ] } (no /v1)" ,width )+ "\n" ,style = mute ) 366for u in self .info .get ("urls" , [])[1 :]: 367t .append (self .fit (f" also reachable at { u } /v1" ,width )+ "\n" ,style = mute ) 368# columns by width: App | Works with | Vendor tested | This server (the narrow ones drop "Works with", then "Vendor tested") 369show_speaks ,show_tested = width >= 80 ,width >= 57 370cols = [("App" ,17 )]+ ([("Works with" ,18 )]if show_speaks else [])+ ([("Vendor tested" ,24 )]if show_tested else [])+ [("This server" ,0 )] 371t .append (("" if compact else "\n" )+ " " + "" .join (name .ljust (w )if w else name for name ,w in cols )+ "\n" ,style = "bold" ) 372for i ,h in enumerate (harness .HARNESSES ): 373sel = i == self .connect_index % len (harness .HARNESSES ) 374words ,kind = self .server_state (h ) 375style = {"run" :warn_style ,"ok" :accent ,"bad" :bad_style ,"none" :"" }[kind ] 376cells = [h .title [:16 ]]+ ([h .speaks ]if show_speaks else [])+ ([self .vendor_tested (h )[:23 ]]if show_tested else []) 377row = " " + (g .cursor + " " if sel else " " ) 378for cell , (_n ,w )in zip (cells ,cols ): 379row += cell .ljust (w ) 380row += words 381t .append (self .fit (row ,width - 1 ).ljust (width - 1 )+ "\n" ,style = (f" { bold_accent } { sel_bg } " .strip ()if sel else style )) 382if not compact : 383note = ("Vendor tested = the app version its maker tested this setup with. This server = whether YOUR server answered the app's " 384"prompt and tool call (press h)." if width >= 100 else 385"Vendor tested: a past test of the app version. This server: press h to check yours." ) 386t .append (self .fit (note ,width )+ "\n" ,style = mute ) 387h = self ._harness () 388out = self ._rendered () 389used = t .plain .count ("\n" )+ 1 390room = height - used - 3 391if room < 5 :# no room for the app's setup text: the list and the keys are what matter here 392return t 393t .append ("\n" ) 394paths = ", " .join (f ["path" ]for f in out ["files" ])or ("built into the Strata app" if h .built_in else "" ) 395t .append (f" { h . title } setup" ,style = bold_accent ) 396t .append (self .fit (f" { paths } " ,width - len (h .title )- 6 )+ "\n" ,style = mute ) 397room -= 2 398limit_lines :list [str ]= [] 399for n in out ["limits" ]: 400wrapped = textwrap .wrap (n ,max (30 ,width - 6 ))or [n ] 401limit_lines += [" - " + wrapped [0 ]]+ [" " + w for w in wrapped [1 :]] 402code :list [str ]= [] 403for f in out ["files" ][:1 ]: 404body = f ["text" ]if self .show_key else harness .mask (f ["text" ],key ) 405code += [" " + ln for ln in body .splitlines ()] 406for k ,v in out ["env" ].items (): 407code .append (f" { k } = { v if self . show_key else harness . mask ( v , key ) } " ) 408res = self .check_results .get (h .id ) 409res_lines = ([f" { g . tick if c . ok else 'x' } { c . name } : { c . detail } " for c in res ]if isinstance (res ,list )else []) 410want_code = min (len (code ),max (3 ,room - min (len (limit_lines ),6 )- len (res_lines )- 1 )) 411for ln in code [:want_code ]: 412t .append (self .fit (ln ,width )+ "\n" ) 413if len (code )> want_code : 414t .append (f" ... { len ( code ) - want_code } more lines (c copies all)\n" ,style = mute ) 415left = max (0 ,room - want_code - (1 if len (code )> want_code else 0 )- len (res_lines )) 416if limit_lines : 417t .append ("Good to know\n" ,style = bold_accent ) 418for ln in limit_lines [:max (2 ,left )]: 419t .append (self .fit (ln ,width )+ "\n" ,style = warn_style if ln .lstrip ().startswith ("- WARNING" )else mute ) 420if isinstance (res ,list ): 421for c ,ln in zip (res ,res_lines ): 422t .append (self .fit (ln ,width )+ "\n" ,style = accent if c .ok else bad_style ) 423return t