okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1#!/usr/bin/env python3 2"""The release-side tool for the update feed: keys, signed packages, archives, the signed feed. 3 4Nothing here runs on a user's PC. It runs on the owner's release machine, with the owner's private key, and writes files 5that are then uploaded (to a local folder or a local HTTP server while testing; to the real host only when the owner 6decides). Nothing is uploaded by this tool. 7 8Typical use (the owner's offline machine; replace ``KEYDIR`` with a folder that is NOT in a git checkout): 9 10python packaging/feed_tool.py keygen --out KEYDIR # once: feed-key.json (SECRET) + feed-key.pub.json 11python packaging/feed_tool.py sign-package <components>/engine/0.1.46-linux-x86_64-cuda --key KEYDIR/feed-key.json 12python packaging/feed_tool.py pack-engine <that folder> --out RELEASE/engine # archive + <name>.entry.json 13python packaging/feed_tool.py pack-control <control bundle folder> --version 0.1.46 --platform linux-x86_64 --out RELEASE/control 14python packaging/feed_tool.py build-feed --out RELEASE --sequence 12 --key KEYDIR/feed-key.json \ 15--engine RELEASE/engine --control RELEASE/control [--app-json tauri-latest.json] [--channel stable] [--expires-days 365] 16python packaging/feed_tool.py verify-feed RELEASE --pub KEYDIR/feed-key.pub.json 17 18A new model ships as a signed feed update with the optional `models` member (packaging/UPDATES.md): write one <id>.entry.json for each model in a folder 19(`model-files` prints the size and SHA-256 of the real files for it) and pass the folder as `build-feed --models FOLDER`; `verify-feed` lists the models and 20fails when Control would leave one out. 21 22``keygen`` never prints the secret and refuses to write inside a git checkout or over an existing file. The public file's 23entry goes into ``strata_control/update_keys.json`` (``keys``) once, in the commit that ships the first signed release. 24The Tauri updater key is a different key (minisign, made by ``tauri signer generate``); its public half goes in 25``tauri.conf.json`` and in ``update_keys.json`` as ``app_minisign_public``. 26""" 27 28from __future__import annotations 29 30import argparse 31import datetime as dt 32import hashlib 33import json 34import os 35import shutil 36import stat 37import sys 38import tarfile 39import zipfile 40import zlib 41from concurrent .futures import ThreadPoolExecutor 42from pathlib import Path 43 44ROOT = Path (__file__ ).resolve ().parents [1 ] 45sys .path .insert (0 ,str (ROOT )) 46 47from strata_control import engine_component as ec ,feed as feedmod ,signing # noqa: E402 48 49 50def _inside_git (path :Path )-> bool : 51for parent in [path .resolve (),* path .resolve ().parents ]: 52if (parent / ".git" ).exists (): 53return True 54return False 55 56 57def _sha256 (path :Path )-> str : 58digest = hashlib .sha256 () 59with path .open ("rb" )as stream : 60for block in iter (lambda :stream .read (1 << 20 ),b"" ): 61digest .update (block ) 62return digest .hexdigest () 63 64 65def _load_key (path :Path )-> dict : 66key = json .loads (path .read_text (encoding = "utf-8" )) 67if key .get ("alg" )!= signing .ALG or "seed" not in key : 68raise SystemExit (f" { path } is not a secret key file made by `feed_tool.py keygen`" ) 69return key 70 71 72def keygen (out :Path ,* ,allow_git :bool = False )-> dict : 73out = Path (out ) 74if _inside_git (out )and not allow_git : 75raise SystemExit (f" { out } is inside a git checkout; a private key must not be where it can be committed. Choose another folder." ) 76secret ,public = out / "feed-key.json" ,out / "feed-key.pub.json" 77if secret .exists ()or public .exists (): 78raise SystemExit (f" { secret } or { public } already exists; refusing to overwrite a key" ) 79out .mkdir (parents = True ,exist_ok = True ) 80key = signing .generate_key () 81fd = os .open (secret ,os .O_WRONLY | os .O_CREAT | os .O_EXCL ,0o600 ) 82with os .fdopen (fd ,"w" ,encoding = "utf-8" )as stream : 83json .dump (key ,stream ,indent = 1 ) 84stream .write ("\n" ) 85from strata_control import private_files 86private_files .restrict_to_current_user (secret ,directory = False )# 0600, or a protected ACL on Windows 87public .write_text (json .dumps ({"keys" : [signing .public_part (key )]},indent = 1 )+ "\n" ,encoding = "utf-8" ) 88return signing .public_part (key ) 89 90 91def sign_package (folder :Path ,key :dict )-> str : 92"""Put the signature into the package's manifest. Returns the manifest's SHA-256 afterwards (the feed names it).""" 93path = Path (folder )/ ec .MANIFEST 94manifest = json .loads (path .read_text (encoding = "utf-8-sig" )) 95manifest ["signature" ]= None 96payload = ec .signing_payload (manifest ) 97manifest ["signature" ]= signing .sign_bytes (key ,payload ) 98path .write_text (json .dumps (manifest ,indent = 1 )+ "\n" ,encoding = "utf-8" ) 99ec .read_manifest_any (Path (folder ))# still a valid manifest 100signing .verify_bytes ({key ["key_id" ]:__import__ ("base64" ).b64decode (key ["public" ])},payload ,manifest ["signature" ]) 101return _sha256 (path ) 102 103 104_NATIVE_MAGIC = (b"\x7fELF" ,b"\xcf\xfa\xed\xfe" ,b"\xca\xfe\xba\xbe" ,b"\xfe\xed\xfa\xcf" ,b"#!" )# ELF, Mach-O (64-bit, fat), script 105 106 107def _is_native_executable (path :Path )-> bool : 108try : 109with path .open ("rb" )as stream : 110head = stream .read (4 ) 111except OSError : 112return False 113return any (head .startswith (m )for m in _NATIVE_MAGIC ) 114 115 116def _mode (path :Path ,rel :str ,entrypoint :str | None )-> int : 117if rel == entrypoint : 118return 0o755 119try : 120if os .name == "nt" :# a Linux / Mac package packed on Windows has no execute bits: take them from the file's own header 121return 0o755 if _is_native_executable (path )else 0o644 122return 0o755 if path .stat ().st_mode & stat .S_IXUSR else 0o644 123except OSError : 124return 0o644 125 126 127GZIP_BLOCK = 4 << 20 # bytes of the tar per gzip member when several threads compress (_parallel_gzip) 128 129 130def gzip_threads ()-> int : 131"""How many threads compress a tar.gz: 1 (the single-stream gzip, byte for byte as before) unless STRATA_PACK_THREADS asks for more. OPT-IN 132(coordinator 11-10): a threaded archive is several gzip members, and every published client that unpacks a package must be shown to read 133those before this may become the default.""" 134raw = os .environ .get ("STRATA_PACK_THREADS" ,"" ).strip () 135if raw .isdigit ()and int (raw )>= 1 : 136return min (int (raw ),64 ) 137return 1 138 139 140def _parallel_gzip (src :Path ,dst :Path ,threads :int ,level :int = 9 )-> None : 141"""`src` (a plain tar) gzipped into `dst` by `threads` threads: GZIP_BLOCK-sized pieces, each a complete gzip member (RFC 1952 allows several in one 142file; Python's tarfile and gzip, GNU tar / gzip and bsdtar read them as one stream). zlib releases the GIL while it compresses, so the pieces run in 143parallel. The header carries no file name and mtime 0, so the same tar always gives the same bytes.""" 144def one (block :bytes )-> bytes : 145c = zlib .compressobj (level ,zlib .DEFLATED ,31 )# wbits 31: a gzip member (header, deflate, crc32 + size trailer) 146return c .compress (block )+ c .flush () 147 148def blocks (): 149with src .open ("rb" )as f : 150while True : 151block = f .read (GZIP_BLOCK ) 152if not block : 153return 154yield block 155 156with dst .open ("wb" )as out ,ThreadPoolExecutor (max_workers = threads )as pool : 157pending = [] 158for block in blocks ():# at most 2 x threads blocks in memory 159pending .append (pool .submit (one ,block )) 160if len (pending )>= 2 * threads : 161out .write (pending .pop (0 ).result ()) 162for fut in pending : 163out .write (fut .result ()) 164 165 166def _write_archive (files :list [tuple [str ,Path ]],archive :Path ,fmt :str ,entrypoint :str | None )-> None : 167archive .parent .mkdir (parents = True ,exist_ok = True ) 168if fmt == "zip" : 169with zipfile .ZipFile (archive ,"w" ,zipfile .ZIP_DEFLATED )as zf : 170for rel ,path in files : 171zf .write (path ,rel ) 172return 173threads = gzip_threads ()if fmt == "tar.gz" else 1 174if threads > 1 :# the tar first (uncompressed, beside the archive), then the parallel gzip 175plain = archive .with_name (archive .name + ".tar-part" ) 176try : 177_write_tar (files ,plain ,"w" ,entrypoint ) 178_parallel_gzip (plain ,archive ,threads ) 179finally : 180plain .unlink (missing_ok = True ) 181return 182_write_tar (files ,archive , {"tar.gz" :"w:gz" ,"tar.xz" :"w:xz" }[fmt ],entrypoint ) 183 184 185def _write_tar (files :list [tuple [str ,Path ]],archive :Path ,mode :str ,entrypoint :str | None )-> None : 186with tarfile .open (archive ,mode )as tar : 187for rel ,path in files : 188info = tar .gettarinfo (str (path ),arcname = rel ) 189info .uid = info .gid = 0 190info .uname = info .gname = "" 191info .mtime = 0 192if info .issym ():# a Control bundle's Python has relative symlinks; engines have none 193tar .addfile (info ) 194continue 195info .mode = _mode (path ,rel ,entrypoint ) 196with path .open ("rb" )as stream : 197tar .addfile (info ,stream ) 198 199 200def _tree (folder :Path ,* ,links :bool = False )-> list [tuple [str ,Path ]]: 201"""Regular files under `folder`; with `links` also the symbolic links, which must be relative and stay inside it.""" 202found = [] 203root = folder .resolve () 204for path in sorted (folder .rglob ("*" )): 205if path .is_symlink (): 206if not links : 207continue 208target = os .readlink (path ) 209if os .path .isabs (target )or not (path .parent / target ).resolve ().is_relative_to (root ): 210raise SystemExit (f" { path } is a symbolic link that leaves the package ( { target } ); a package may only link inside itself" ) 211found .append ((path .relative_to (folder ).as_posix (),path )) 212elif path .is_file (): 213found .append ((path .relative_to (folder ).as_posix (),path )) 214return found 215 216 217def pack_engine (folder :Path ,out :Path ,fmt :str = "tar.gz" ,* ,url_prefix :str = "engine/" ,prefix :str = "strata-engine" )-> dict : 218"""Archive a (signed) engine package folder and return its feed entry. The archive holds the folder's files at its root. The package of a model shape (package_engine.py --shape) 219gets its component's name as the archive prefix (strata-q4-lite-<version>-...) and its entry names the ``shape``: it goes into the feed member ``shape_engines``.""" 220folder = Path (folder ) 221component = ec .read_manifest_any (folder ) 222if component .shape and prefix == "strata-engine" : 223prefix = component .id 224files = _tree (folder ) 225installed = sum (p .stat ().st_size for _ ,p in files ) 226name = f" { prefix } - { folder . name } . { fmt } " 227archive = Path (out )/ name 228_write_archive (files ,archive ,fmt ,component .entrypoint ) 229entry = {"version" :component .version ,"platform" :component .platform ,"backend" :component .backend , 230"variant" :component .variant ,"archs" :list (component .archs ),"min_driver" :dict (component .min_driver ), 231"min_runtime" :component .min_runtime ,"build_id" :component .build_id ,"format" :fmt , 232"url" :f" { url_prefix } { name } " ,"size" :archive .stat ().st_size ,"sha256" :_sha256 (archive ), 233"manifest_sha256" :_sha256 (folder / ec .MANIFEST ),"installed_bytes" :installed ,"notes" :component .notes } 234if component .shape : 235entry ["shape" ]= component .shape 236 (Path (out )/ (name + ".entry.json" )).write_text (json .dumps (entry ,indent = 1 )+ "\n" ,encoding = "utf-8" ) 237return entry 238 239 240def pack_control (folder :Path ,out :Path ,* ,version :str ,platform :str ,fmt :str = "tar.gz" , 241entry_file :str = "strata.py" ,url_prefix :str = "control/" )-> dict : 242folder = Path (folder ) 243files = _tree (folder ,links = True ) 244installed = sum (p .stat ().st_size for _ ,p in files if not p .is_symlink ()) 245name = f"strata-control- { version } - { platform } . { fmt } " 246archive = Path (out )/ name 247_write_archive (files ,archive ,fmt ,entry_file ) 248entry = {"platform" :platform ,"format" :fmt ,"url" :f" { url_prefix } { name } " ,"size" :archive .stat ().st_size , 249"sha256" :_sha256 (archive ),"installed_bytes" :installed ,"entry" :entry_file ,"version" :version } 250 (Path (out )/ (name + ".entry.json" )).write_text (json .dumps (entry ,indent = 1 )+ "\n" ,encoding = "utf-8" ) 251return entry 252 253 254def pack_drafter (pack :Path ,out :Path ,* ,version :str ,backends :list [str ],url_prefix :str = "" ,base :str = "" ,licence :str = "" ,notes :str = "" )-> dict : 255"""Copy a DFlash2 drafter file into `out` (a flat release asset, as it is hosted) and write its feed entry (`<name>.entry.json`). The file is not an archive: the 256client checks its size and SHA-256 against the signed feed AND against the pin in strata_control/drafting.py.""" 257pack = Path (pack ) 258Path (out ).mkdir (parents = True ,exist_ok = True ) 259target = Path (out )/ pack .name 260if pack .resolve ()!= target .resolve (): 261shutil .copy2 (pack ,target ) 262entry = {"name" :pack .name ,"version" :version ,"url" :f" { url_prefix } { pack . name } " ,"size" :target .stat ().st_size ,"sha256" :_sha256 (target ), 263"backends" :list (backends ),"base" :base ,"licence" :licence ,"notes" :notes } 264 (Path (out )/ (pack .name + ".entry.json" )).write_text (json .dumps (entry ,indent = 1 )+ "\n" ,encoding = "utf-8" ) 265return entry 266 267 268def model_files (paths :list [Path ],repo_dir :str = "" )-> list [dict ]: 269"""The `files` pins of a models entry from the real files: name, exact size, SHA-256 (and `path` when they sit in a folder of the repository).""" 270out = [] 271for p in map (Path ,paths ): 272item = {"name" :p .name ,"size" :p .stat ().st_size ,"sha256" :_sha256 (p )} 273if repo_dir : 274item ["path" ]= f" { repo_dir . strip ( '/' ) } / { p . name } " 275out .append (item ) 276return out 277 278 279DSV41_BASE_EXAMPLE = "https://github.com/Niko1221/Strata/releases/download/<DSV41-TAG>/" 280 281 282def carried_dsv41 (previous_feed :Path ,base :str )-> dict : 283"""The ``dsv41`` member of a published feed, frozen (owner 11-11, "Keep frozen"): Strata 0.2.13 and earlier read it to keep their DeepSeek 284engine; this Strata never does. Every entry is kept as it was, except a relative ``url`` (a flat release asset, resolved against the feed's 285own release): it becomes ``base`` + url, the release that really holds the archive, because the new feed sits in a newer release that does 286not. Absolute https URLs are what those Controls accept (strata_control/transfer.py resolve_ref since 0.2.7). ``base`` must be a real https 287release folder: the placeholder in DSV41_BASE_EXAMPLE stops the build.""" 288if not isinstance (base ,str )or not base .startswith ("https://" )or "<" in base or ">" in base or not base .endswith ("/" ): 289raise SystemExit (f"--carry-dsv41-base must be the https folder of the release that holds the DeepSeek archives, ending in '/' " 290f"(like { DSV41_BASE_EXAMPLE } with the tag filled in), not { base !r } " ) 291doc = json .loads (Path (previous_feed ).read_text (encoding = "utf-8" )) 292member = doc .get ("dsv41" )if isinstance (doc ,dict )else None 293if not isinstance (member ,dict )or not isinstance (member .get ("packages" ),list )or not member ["packages" ]: 294raise SystemExit (f" { previous_feed } has no dsv41 packages to carry over" ) 295packages = [] 296for item in member ["packages" ]: 297item = dict (item ) 298url = str (item .get ("url" )or "" ) 299if not url or url .startswith (("http://" ,"file:" ))or ".." in url .split ("/" ): 300raise SystemExit (f" { previous_feed } : a dsv41 entry has an unusable url { url !r } " ) 301if not url .startswith ("https://" ): 302item ["url" ]= base + url .rsplit ("/" ,1 )[- 1 ]# (a local test feed's "dsv41/<name>": the release asset is the bare name) 303packages .append (item ) 304return {"packages" :packages } 305 306 307def build_feed (out :Path ,* ,key :dict ,sequence :int ,channel :str = "stable" ,engine_dir :Path | None = None , 308control_dir :Path | None = None ,app_json :Path | None = None ,expires_days :int | None = None , 309now :dt .datetime | None = None ,drafters_dir :Path | None = None ,models_dir :Path | None = None , 310shapes_dir :Path | None = None ,dsv41_member :dict | None = None )-> dict : 311now = now or dt .datetime .now (dt .timezone .utc ) 312install_manifest = "" 313document :dict = {"schema_version" :feedmod .SCHEMA_VERSION ,"feed" :"strata-updates" ,"channel" :channel , 314"sequence" :sequence ,"generated_at" :now .strftime ("%Y-%m-%dT%H:%M:%SZ" ), 315"expires_at" : (now + dt .timedelta (days = expires_days )).strftime ("%Y-%m-%dT%H:%M:%SZ" )if expires_days else None } 316if engine_dir : 317document ["engine" ]= {"packages" : [json .loads (p .read_text (encoding = "utf-8" )) 318for p in sorted (Path (engine_dir ).glob ("*.entry.json" ))]} 319if dsv41_member :# the frozen DeepSeek engine packages of Strata 0.2.13 and earlier (carried_dsv41) 320document ["dsv41" ]= dsv41_member 321if shapes_dir :# the engines of model shapes (feed member shape_engines): each entry must name a shape 322entries = [] 323for p in sorted (Path (shapes_dir ).glob ("*.entry.json" )): 324item = json .loads (p .read_text (encoding = "utf-8" )) 325if not item .get ("shape" ): 326raise SystemExit (f" { p . name } names no shape: pack it from a package made with package_engine.py --shape" ) 327entries .append (item ) 328document ["shape_engines" ]= {"packages" :entries } 329if drafters_dir : 330document ["drafters" ]= {"packages" : [json .loads (p .read_text (encoding = "utf-8" )) 331for p in sorted (Path (drafters_dir ).glob ("*.entry.json" ))]} 332if models_dir :# the model list (feed member models): every entry must be one Control will keep, or the build stops 333packages = [] 334for p in sorted (Path (models_dir ).glob ("*.entry.json" )): 335item = json .loads (p .read_text (encoding = "utf-8" )) 336if "[FILL" in json .dumps (item ):# a placeholder from make_model_release.py that nobody filled in would reach people's screens 337raise SystemExit (f" { p . name } : still has a [FILL: ...] value: fill it in first" ) 338try : 339feedmod ._model_entry (item ) 340except feedmod .FeedError as exc : 341raise SystemExit (f" { p . name } : { exc } " ) 342packages .append (item ) 343if len ({m ["id" ]for m in packages })!= len (packages ): 344raise SystemExit ("two model entries have the same id" ) 345document ["models" ]= {"packages" :packages } 346wanted = {m ["family" ][len ("qwen4exp_" ):]for m in (document .get ("models" )or {}).get ("packages" , [])if str (m .get ("family" ,"" )).startswith ("qwen4exp_" )} 347have = {e ["shape" ]for e in (document .get ("shape_engines" )or {}).get ("packages" , [])} 348if wanted - have :# a model of its own shape with no engine in the feed could be listed and never run 349raise SystemExit ("the feed lists a model for the shape " + ", " .join (sorted (wanted - have ))+ " but no engine for it (build-feed --shapes FOLDER, with the .entry.json " 350"that pack-engine wrote for a package made with package_engine.py --shape)" ) 351if control_dir : 352entries = [json .loads (p .read_text (encoding = "utf-8" ))for p in sorted (Path (control_dir ).glob ("*.entry.json" ))] 353versions = {e ["version" ]for e in entries } 354if len (versions )> 1 : 355raise SystemExit (f"the control packages are for different versions: { sorted ( versions ) } " ) 356if entries : 357document ["control" ]= {"version" :versions .pop (),"packages" : [{k :v for k ,v in e .items ()if k != "version" }for e in entries ]} 358for e in entries :# install.sh unpacks with tar -xzf, install.ps1 with Expand-Archive: a pack in the other format cannot be installed that way 359want = "zip" if e ["platform" ].startswith ("windows" )else "tar.gz" 360if e .get ("format" )!= want : 361f"note: the { e [ 'platform' ] } control package is { e . get ( 'format' ) } , so it is left out of install-manifest.txt " 362f"(the one-line installer needs { want } ; pack-control --format { want } )" ,file = sys .stderr ) 363continue 364install_manifest += f" { e [ 'platform' ] } { e [ 'version' ] } { e [ 'url' ] } { e [ 'sha256' ] } { e [ 'size' ] } \n" 365if app_json : 366document ["app" ]= json .loads (Path (app_json ).read_text (encoding = "utf-8" )) 367payload = (json .dumps (document ,indent = 1 ,sort_keys = True )+ "\n" ).encode ("utf-8" ) 368Path (out ).mkdir (parents = True ,exist_ok = True ) 369 (Path (out )/ feedmod .FEED_NAME ).write_bytes (payload ) 370signature = signing .sign_bytes (key ,payload ) 371 (Path (out )/ (feedmod .FEED_NAME + feedmod .SIGNATURE_SUFFIX )).write_text (json .dumps (signature )+ "\n" ,encoding = "utf-8" ) 372if install_manifest :# what install.sh / install.ps1 read: platform version url sha256 size, one line per Terminal (Control) package 373 (Path (out )/ "install-manifest.txt" ).write_text (install_manifest ,encoding = "utf-8" ,newline = "\n" ) 374if "app" in document :# the file the Tauri updater plugin reads 375latest = Path (out )/ "app" / "latest.json" 376latest .parent .mkdir (parents = True ,exist_ok = True ) 377latest .write_text (json .dumps ({k :v for k ,v in document ["app" ].items ()},indent = 1 )+ "\n" ,encoding = "utf-8" ) 378# a parse of what was written is the last check: a feed this tool makes must be a feed Control accepts 379checked = feedmod .verify_and_parse (payload ,json .dumps (signature ).encode (),source = str (Path (out )/ feedmod .FEED_NAME ), 380trusted = {key ["key_id" ]:__import__ ("base64" ).b64decode (key ["public" ])},now = now ) 381if checked .models_dropped or len (checked .models )!= len ((document .get ("models" )or {}).get ("packages" , [])): 382raise SystemExit ("the feed was written, but Control would leave out a model: " + " " .join (checked .models_dropped )) 383return document 384 385 386TAURI_TARGET_NAMES = tuple (feedmod .TAURI_TARGETS .values ()) 387 388 389def _default_app_pubkey ()-> str : 390conf = Path (__file__ ).resolve ().parents [1 ]/ "apps" / "desktop" / "src-tauri" / "tauri.conf.json" 391return json .loads (conf .read_text (encoding = "utf-8" ))["plugins" ]["updater" ]["pubkey" ] 392 393 394def _check_mac_archive (archive :Path )-> None : 395"""A Mac updater archive is a gzip tar with exactly one top-level ``<Name>.app`` folder (what Tauri's bundler makes).""" 396try : 397with tarfile .open (archive ,"r:gz" )as tar : 398tops = {m .name .lstrip ("./" ).split ("/" ,1 )[0 ]for m in tar .getmembers ()if m .name .lstrip ("./" )} 399names = set (tar .getnames ()) 400except (tarfile .TarError ,OSError )as exc : 401raise SystemExit (f" { archive . name } is not a readable .tar.gz ( { exc } )" ) 402if len (tops )!= 1 or not next (iter (tops )).endswith (".app" ): 403raise SystemExit (f" { archive . name } must hold one <Name>.app folder at its root; found { sorted ( tops )[: 5 ] } " ) 404app = next (iter (tops )) 405if not any (n .lstrip ("./" )== f" { app } /Contents/Info.plist" for n in names ): 406raise SystemExit (f" { archive . name } has no { app } /Contents/Info.plist" ) 407 408 409def set_app_platform (app_json :Path ,* ,target :str ,archive :Path ,signature_file :Path ,url :str ,version :str | None = None , 410notes :str | None = None ,pub_date :str | None = None ,pubkey :str | None = None , 411now :dt .datetime | None = None )-> dict : 412"""Add or replace one platform in the Tauri updater JSON (the file ``build-feed --app-json`` takes; it becomes ``latest.json``). 413 414The ``.sig`` is made by ``npx tauri signer sign`` (or by ``tauri build`` for the Windows / Linux installers) and is only READ here; 415this tool never touches the Tauri private key. It is checked against the public key in ``tauri.conf.json`` (or ``pubkey``) over the 416exact archive bytes, so a signature of an older or unsigned file, or one from another key, is refused before it can be published. 417``sha256`` and ``size`` are taken from the archive.""" 418if target not in TAURI_TARGET_NAMES : 419raise SystemExit (f"unknown target { target !r } ; use one of { ', ' . join ( TAURI_TARGET_NAMES ) } " ) 420archive ,signature_file = Path (archive ),Path (signature_file ) 421if target .startswith ("darwin-" ): 422_check_mac_archive (archive ) 423signature = signature_file .read_text (encoding = "utf-8" ).strip () 424try : 425with archive .open ("rb" )as stream : 426signing .minisign_verify (pubkey or _default_app_pubkey (),signature ,iter (lambda :stream .read (1 << 20 ),b"" )) 427except signing .SignatureError as exc : 428raise SystemExit (f" { signature_file . name } does not verify for { archive . name } : { exc } " ) 429document :dict = {} 430if Path (app_json ).exists (): 431document = json .loads (Path (app_json ).read_text (encoding = "utf-8" )) 432if version : 433if document .get ("version" )not in (None ,version ): 434raise SystemExit (f" { app_json } is for version { document [ 'version' ] } , not { version } " ) 435document ["version" ]= version 436if not document .get ("version" ): 437raise SystemExit ("a new app json needs --version" ) 438document .setdefault ("notes" ,notes or "" ) 439if notes : 440document ["notes" ]= notes 441document ["pub_date" ]= pub_date or document .get ("pub_date" )or (now or dt .datetime .now (dt .timezone .utc )).strftime ("%Y-%m-%dT%H:%M:%SZ" ) 442document .setdefault ("platforms" , {})[target ]= {"url" :url ,"signature" :signature ,"sha256" :_sha256 (archive ), 443"size" :archive .stat ().st_size } 444Path (app_json ).write_text (json .dumps (document ,indent = 1 )+ "\n" ,encoding = "utf-8" ) 445return document ["platforms" ][target ] 446 447 448def main (argv :list [str ]| None = None )-> int : 449ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 450sub = ap .add_subparsers (dest = "cmd" ,required = True ) 451k = sub .add_parser ("keygen" ) 452k .add_argument ("--out" ,type = Path ,required = True ) 453sp = sub .add_parser ("sign-package" ) 454sp .add_argument ("folder" ,type = Path ) 455sp .add_argument ("--key" ,type = Path ,required = True ) 456pe = sub .add_parser ("pack-engine" ) 457pe .add_argument ("folder" ,type = Path ) 458pe .add_argument ("--out" ,type = Path ,required = True ) 459pe .add_argument ("--format" ,choices = feedmod .FORMATS ,default = "tar.gz" ) 460pe .add_argument ("--url-prefix" ,default = "engine/" ,help = 'where the archive sits relative to the feed ("" for flat GitHub release assets)' ) 461pe .add_argument ("--prefix" ,default = "strata-engine" ,help = "archive name prefix" ) 462pd = sub .add_parser ("pack-drafter" ,help = "a DFlash2 drafter file as a feed entry (feed member drafters)" ) 463pd .add_argument ("pack" ,type = Path ) 464pd .add_argument ("--out" ,type = Path ,required = True ) 465pd .add_argument ("--version" ,required = True ) 466pd .add_argument ("--backends" ,required = True ,help = "comma-separated engine families it was measured on, e.g. metal" ) 467pd .add_argument ("--url-prefix" ,default = "" ,help = '"" for flat GitHub release assets' ) 468pd .add_argument ("--base" ,default = "" ) 469pd .add_argument ("--licence" ,default = "" ) 470pm = sub .add_parser ("model-files" ,help = "print the size and SHA-256 of model files as the `files` list of a feed models entry" ) 471pm .add_argument ("files" ,type = Path ,nargs = "+" ) 472pm .add_argument ("--repo-dir" ,default = "" ,help = "the folder of the Hugging Face repository the files sit in (becomes each file's path); default: the top" ) 473pc = sub .add_parser ("pack-control" ) 474pc .add_argument ("folder" ,type = Path ) 475pc .add_argument ("--out" ,type = Path ,required = True ) 476pc .add_argument ("--version" ,required = True ) 477pc .add_argument ("--platform" ,required = True ,choices = feedmod .PLATFORMS ) 478pc .add_argument ("--format" ,choices = feedmod .FORMATS ,default = "tar.gz" ) 479pc .add_argument ("--url-prefix" ,default = "control/" ) 480bf = sub .add_parser ("build-feed" ) 481bf .add_argument ("--out" ,type = Path ,required = True ) 482bf .add_argument ("--key" ,type = Path ,required = True ) 483bf .add_argument ("--sequence" ,type = int ,required = True ) 484bf .add_argument ("--channel" ,default = "stable" ) 485bf .add_argument ("--engine" ,type = Path ) 486bf .add_argument ("--carry-dsv41" ,type = Path ,metavar = "PREVIOUS-FEED" , 487help = "the last published strata-feed.json: its dsv41 member (the DeepSeek engine of Strata 0.2.13 and earlier) is carried over, frozen" ) 488bf .add_argument ("--carry-dsv41-base" ,metavar = "URL" ,help = "the https folder of the release that holds those archives, e.g. " + DSV41_BASE_EXAMPLE ) 489bf .add_argument ("--no-dsv41-carry" ,action = "store_true" ,help = "build the feed without the frozen DeepSeek member (a test feed, or the owner's choice)" ) 490bf .add_argument ("--shapes" ,type = Path ,help = "folder of the model-shape engines' .entry.json files (feed member shape_engines; pack-engine writes them for a package made with package_engine.py --shape)" ) 491bf .add_argument ("--models" ,type = Path ,help = "folder of the models' <id>.entry.json files (feed member models: the model list setup and the screens show after the built-in ones)" ) 492bf .add_argument ("--drafters" ,type = Path ,help = "folder of the DFlash2 drafters' .entry.json files (feed member drafters; pack-drafter writes them)" ) 493bf .add_argument ("--control" ,type = Path ) 494bf .add_argument ("--app-json" ,type = Path ) 495bf .add_argument ("--expires-days" ,type = int ) 496sa = sub .add_parser ("set-app-platform" ,help = "add one signed app installer to the Tauri updater json" ) 497sa .add_argument ("--app-json" ,type = Path ,required = True ,help = "the file to create or patch (what build-feed --app-json takes)" ) 498sa .add_argument ("--target" ,required = True ,help = "darwin-aarch64, darwin-x86_64, windows-x86_64 or linux-x86_64" ) 499sa .add_argument ("--archive" ,type = Path ,required = True ) 500sa .add_argument ("--sig" ,type = Path ,required = True ,help = "the .sig file made by tauri signer sign" ) 501sa .add_argument ("--url" ,help = "where the archive is published (default: the latest GitHub release)" ) 502sa .add_argument ("--version" ) 503sa .add_argument ("--notes" ) 504sa .add_argument ("--pub-date" ) 505sa .add_argument ("--pubkey" ,help = "the Tauri public key (default: tauri.conf.json plugins.updater.pubkey)" ) 506vf = sub .add_parser ("verify-feed" ) 507vf .add_argument ("source" ) 508vf .add_argument ("--pub" ,type = Path ,required = True ) 509a = ap .parse_args (argv ) 510if a .cmd == "keygen" : 511public = keygen (a .out ) 512f"wrote { a . out / 'feed-key.json' } (SECRET, keep it offline and backed up) and { a . out / 'feed-key.pub.json' } " ) 513f"key_id { public [ 'key_id' ] } " ) 514elif a .cmd == "sign-package" : 515"manifest sha256" ,sign_package (a .folder ,_load_key (a .key ))) 516elif a .cmd == "pack-engine" : 517entry = pack_engine (a .folder ,a .out ,a .format ,url_prefix = a .url_prefix ,prefix = a .prefix ) 518json .dumps ({k :entry [k ]for k in ("version" ,"backend" ,"variant" ,"size" ,"sha256" ,"manifest_sha256" )},indent = 1 )) 519elif a .cmd == "pack-drafter" : 520entry = pack_drafter (a .pack ,a .out ,version = a .version ,backends = [b for b in a .backends .split ("," )if b ],url_prefix = a .url_prefix ,base = a .base ,licence = a .licence ) 521json .dumps ({k :entry [k ]for k in ("name" ,"version" ,"size" ,"sha256" ,"backends" )},indent = 1 )) 522elif a .cmd == "model-files" : 523json .dumps (model_files (a .files ,a .repo_dir ),indent = 1 )) 524elif a .cmd == "pack-control" : 525entry = pack_control (a .folder ,a .out ,version = a .version ,platform = a .platform ,fmt = a .format ,url_prefix = a .url_prefix ) 526json .dumps ({k :entry [k ]for k in ("version" ,"platform" ,"size" ,"sha256" )},indent = 1 )) 527elif a .cmd == "build-feed" : 528if bool (a .carry_dsv41 )== bool (a .no_dsv41_carry ): 529raise SystemExit ("build-feed: say what happens to the frozen DeepSeek member: --carry-dsv41 <the last strata-feed.json> --carry-dsv41-base " 530f" { DSV41_BASE_EXAMPLE } (with the tag of the release that holds the archives), or --no-dsv41-carry" ) 531member = carried_dsv41 (a .carry_dsv41 ,a .carry_dsv41_base )if a .carry_dsv41 else None 532doc = build_feed (a .out ,key = _load_key (a .key ),sequence = a .sequence ,channel = a .channel ,engine_dir = a .engine , 533control_dir = a .control ,app_json = a .app_json ,expires_days = a .expires_days ,drafters_dir = a .drafters ,models_dir = a .models ,shapes_dir = a .shapes , 534dsv41_member = member ) 535f"wrote { a . out / feedmod . FEED_NAME } (+ .sig); engines { len (( doc . get ( 'engine' ) or {}). get ( 'packages' , [])) } , " 536f"frozen deepseek engines { len (( doc . get ( 'dsv41' ) or {}). get ( 'packages' , [])) } , shape engines { len (( doc . get ( 'shape_engines' ) or {}). get ( 'packages' , [])) } , drafters { len (( doc . get ( 'drafters' ) or {}). get ( 'packages' , [])) } , models { len (( doc . get ( 'models' ) or {}). get ( 'packages' , [])) } , control { 'yes' if 'control' in doc else 'no' } , app { 'yes' if 'app' in doc else 'no' } " ) 537elif a .cmd == "set-app-platform" : 538url = a .url or f"https://github.com/Niko1221/Strata/releases/latest/download/ { a . archive . name } " 539entry = set_app_platform (a .app_json ,target = a .target ,archive = a .archive ,signature_file = a .sig ,url = url ,version = a .version , 540notes = a .notes ,pub_date = a .pub_date ,pubkey = a .pubkey ) 541f" { a . app_json } : { a . target } -> { entry [ 'url' ] } ( { entry [ 'size' ] } bytes, sha256 { entry [ 'sha256' ][: 16 ] } ..., signature verified)" ) 542elif a .cmd == "verify-feed" : 543trusted = signing .load_trusted_keys (a .pub ,environ = {}) 544loaded = feedmod .fetch (a .source ,trusted ) 545f"ok: sequence { loaded . sequence } , channel { loaded . channel } , signed by { loaded . key_id } , " 546f" { len ( loaded . engine ) } engine packages, control { len ( loaded . control ) } , app { 'yes' if loaded . app else 'no' } " 547+ (f", { len ( loaded . shape_engines ) } shape engines ( { ', ' . join ( sorted ({ p . shape for p in loaded . shape_engines })) } )" if loaded .shape_engines else "" ) 548+ (f", { len ( loaded . models ) } models ( { ', ' . join ( m . id for m in loaded . models ) } )" if loaded .models else "" )) 549if loaded .models_dropped :# Control would skip these: a signed feed must not carry them 550* loaded .models_dropped ,sep = chr (10 ),file = sys .stderr ) 551return 3 552return 0 553 554 555if __name__ == "__main__" : 556raise SystemExit (main ())