Skip to content

Scripts

The Scripts pane (Infra › Scripts in the default layout: 0 then > twice) is a built-in Python script runner: browse, edit, and execute short scripts against the currently active API context, right from the TUI. It's also the same convention used by custom panes and by init_scripts (below) — one script format, three ways to trigger it.

Scripts

Built-in vs. user scripts

Kind Location Editable?
Built-in shipped with virtufin-tui (examples/ in the package) No — read-only in the editor
User ~/.config/virtufin/tui/examples/ Yes

Both show up in the same list, built-ins first. Press a to create a new user script (seeded from the built-in template, see below); press s to save edits to a user script. See Views → Scripts for the full key reference.

The env-var contract

Every script — built-in, user, or a custom pane's .py — is run as a subprocess of the TUI's own Python interpreter (so virtufin-api and virtufin_tui import, even when the TUI is an installed tool and the python3 on your PATH is another one), with the built-in examples/ first on PYTHONPATH (so from _rpc import ... works from a script anywhere), and receives the active context as environment variables. Your script doesn't set these or read them from a config file itself; whatever ran the script (the Scripts pane, a custom pane, or init_scripts at startup) sets them right before spawning the subprocess:

Variable Meaning
VIRTUFIN_TUI_API_HOST virtufin-api host (default localhost)
VIRTUFIN_TUI_API_PORT virtufin-api gRPC port (default 5002)
VIRTUFIN_TUI_API_TLS "true"/"false" — TLS for the above
VIRTUFIN_TUI_API_KEY x-api-key, if the active context uses key auth (empty string otherwise)
VIRTUFIN_TUI_WORKER_API_HOST / VIRTUFIN_TUI_WORKER_API_PORT workmanager's worker-facing API, for scripts that talk to it directly
VIRTUFIN_TUI_FORM_DATA JSON dict of submitted form fields — only set when the script has a paired .form.json (see below)
VIRTUFIN_TUI_OPERATIONS_SOCKET Where the TUI answers the script's vf operation calls (a Unix socket in a private temporary directory, open while the script runs; see Calling operations)

This is the same mechanism regardless of trigger: screens/_script_runner.py's run_script_subprocess builds the env and streams output back to a log, whether that log is the Scripts pane's output panel, a custom pane's, or (for init_scripts) the app's own tui.log (~/.local/state/virtufin/tui/tui.log).

Writing a script

New user scripts (a) start from the built-in template, which shows the contract above in comments and calls the platform through vf (below):

from virtufin_tui import vf

async def run():
    result = await vf.workmanager.ListWorkers({})
    print(f"Workers: {len(result.get('workers', []))}")

A script can also open its own connection: _rpc.py's api_client() builds a client from the VIRTUFIN_TUI_API_* env vars above, and invoke()/invoke_no_response() call any virtufin-api RPC by service/method name via gRPC reflection; or use virtufin.api.ApiClient directly (see system_startdate.py under Automatic startup scripts below). Writes over a script's own connection are not confirmed on a protected context and not recorded on Infra › Changes; vf calls are.

Calling operations (vf)

vf.<name>(input) runs an operation in the TUI that started the script, with its client (openspec operations, Writes Through the Write Gate and Reflected Operations):

from virtufin_tui import vf

workers = await vf.workers.list()                         # an operation of the catalog
answer = await vf.workmanager.ListWorkers({})             # a backend method, from reflection
await vf.call("workmanager.UpdateWorkerTags", {"id": wid, "set": {"owner": "me"}})

async for e in vf.topics.follow({"topic": "sys.workmanager.worker.lifecycle"}):
    print(e["type"])                                      # a stream: looped over
    break                                                 # leaving the loop ends it
  • The name is a hand-written operation of the catalog first (workers.list, triggers.schedule, ...; The TUI's API), else a backend method <service>.<Method> from reflection. vf.call(name, input) is the same call with the name as a string (for a service with dots in its name, e.g. grpc.health.v1.Health.Check); vf.stream(name, input) is the same for a stream.
  • Streams are looped over (async for m in vf.<name>(input)), never awaited: the catalog's streams (topics.follow) and every server-streaming backend method (Gateway.InvokeJsonStream, e.g. vf.workmanager.Watch({"service": ""})). Leaving the loop ends the stream (its subscription or backend call). Awaiting a stream fails with ... is a stream: loop over it ..., looping over anything else with ... is not a stream: await it ....
  • Reflected operations: every unary method of every backend the gateway lists (Gateway.ListServices, ListMethods), run through Gateway.InvokeJson with the proto field names (code_source, mime_type); the answer is the parsed JSON. Server-streaming methods are streams (above); client-streaming and bidirectional ones are not offered. Whether a call reads or writes is the gateway's word (ListMethods' MethodInfo.kind), never guessed from the method name; a gateway that does not say makes it a write. The gateway checks the input (unknown fields are refused).
  • Writes pass the TUI's write gate like the panes' writes: on a protected context the TUI asks first (one yes covers the next 5 s), and each write is recorded on Infra › Changes (workmanager UpdateWorkerTags <id>, done, failed or declined). Reads never ask.
  • Refused: the kill switch (people only); a name that is neither (no operation ...). Any failure raises vf.OperationFailed with the reason, e.g. workmanager.UpdateWorkerTags: not done (declined on the protected context).
  • vf works in a script the TUI started (the Scripts pane, a script pane, init_scripts); run elsewhere it raises ... vf runs operations only in a script started by the TUI.
  • Reflected operations are not offered to the AI and are not form choices (Choices).

The list in the Scripts pane: under the scripts, Operations lists the catalog by group (list · read) and env, secret the two entry calls; From reflection (collapsed) reads the backends' methods when you open it and lists them by service with their kind (workmanager (22) › UpdateWorkerTags · write, Watch · read · stream). Opening a method reads its input fields (Gateway.GetMethodSchema, once: id: String, filters: repeated virtufin.TagFilter). Highlighting a row shows the call and what it does in the status line. The filter above the list narrows the reflected methods by name. After a context switch the group is read again.

Your variables and secrets (vf.env, vf.secret)

A script reads your personal environment variables and secrets (Config › Environment variables and Config › Secrets) by name:

from virtufin_tui import vf

region = vf.env("REGION")         # a personal variable, or None
key = vf.secret("BINANCE_KEY")    # a personal secret, or None

Both read ~/.config/virtufin/tui/env.toml and secrets.toml when they are called and return None for a name that is not set (a secret's name is not a variable, and the other way round). A secret reaches the script only when it asks for it by name; the TUI never shows it, but whatever the script prints shows in its output, so don't print it. The values are not in the script's environment.

Script + form pairs

Drop a <name>.form.json next to <name>.py (same stem) and the Scripts pane renders the form instead of jumping straight to running the script — press e to toggle between the form and the code editor. A file that is not a form is shown as the list of its problems, each at its JSON Pointer.

The format is the script form format both operator clients read (the web app keeps the same JSON in a script's Form tab): a flat JSON Schema object with properties (text, multi-line text, secret, whole number, number, yes / no, one of, some of, date, date and time), required, checks (minimum, maximum, minLength, maxLength, pattern), display hints (title, description, default, x-placeholder, x-enumLabels, x-widget, x-submit), x-visibleIf, and choices (x-options, see Choices).

Submitting the form runs the script with the values as JSON in VIRTUFIN_TUI_FORM_DATA: each shown, non-empty field typed as the schema says (numbers as numbers, yes / no as true / false, some-of as a list); hidden and empty fields are left out. A shown field that does not fit is marked and the script does not start. See create_worker.py / create_worker.form.json in examples/ for a full example, and Custom panes → Script + form pane for the same convention embedded as its own pane instead of run from the Scripts list.

Choices

x-options on a text field, or on a some-of field's items in place of enum, offers a list to pick from: fixed, or read from a catalog operation. The keys are described on domain-devkit's Script forms, Choices page (openspec operations, Script Form Choices and Reading Script Form Choices).

x-options The field in the TUI
{"values": ["fast", "slow"], "labels": ["Fast", "Slow"]} A select of the labels, strict: only these values.
{"values": [...], "free": true} A text input that suggests the values as you type; any value is taken.
{"from": {"operation": "workers.list", "value": "/id", "label": "/name"}} A select, read when the form is shown: the workers by name, their id passed.
{"from": {"operation": "topics.list", "input": {"prefix": {"field": "prefix"}}}, "free": true} A text input suggesting the topics; read again 0.3 s after the prefix field last changed.
on a some-of field's items A selection list of the choices (Space picks).
  • Select (strict): Enter or a click opens the list; typing jumps to the first choice that starts with what was typed. A value the field holds that is not a choice (a default before the list arrives) is shown as the select's prompt until a choice is picked.
  • Text input (free): the first choice that starts with the typed text (any case) is suggested in gray; → (right arrow) takes it.
  • Selection list (some-of): a pick that is no longer a choice stays listed and picked, so it can be unpicked.
  • from.operation is a read of the TUI's catalog (the one virtufin_tui.operations implements, see The TUI's API), run through the active context. A write or a people-only operation fails that field (... is a write; choices come only from reads) and is never called; the rest of the form still works. Choices come only from the catalog, not from the reflected operations: a <service>.<Method> name fails the field with no operation ....
  • Under the field: Reading the choices from ..., then N choices from ... with Refresh, or why reading failed with Retry. The choices are read again when a field the input refers to changes (an empty one is left out of the input), when the field is shown again, and after a context switch.
  • A strict field takes only a listed value: while the list loads, or after it failed, a value in it keeps the script from starting (options are loading, options unavailable); a value the list does not have is marked not one of the choices. A free field is checked only by its text checks (minLength, maxLength, pattern).

The built-in examples stop_workers_by_status (some-of workers from workers.list) and next_events_of_a_topic (a free topic from topics.list, narrowed by a prefix field) use both kinds; they are the web app's examples of the same names.

Automatic startup scripts (init_scripts)

init_scripts in ~/.config/virtufin/tui/config.toml names scripts to run once, automatically, shortly after the TUI connects to a context (at startup and after each switch on the Config page) — no keypress needed:

init_scripts = ["system_startdate.py"]

Each entry is a bare filename resolved against ~/.config/virtufin/tui/scripts/ — a separate directory from the Scripts pane's ~/.config/virtufin/tui/examples/. The distinction is deliberate: examples/ holds scripts you browse and run on demand from the Scripts pane; scripts/ holds scripts meant to run unattended, once per launch, with nothing to review or click first.

Behavior:

  • Scripts run in the order listed, each via the same run_script_subprocess used everywhere else — same env-var contract as above (VIRTUFIN_TUI_FORM_DATA is never set, since there's no form).
  • They run after the dashboard is already shown (fire-and-forget), so a slow or hung init script never delays startup.
  • A missing file is logged to tui.log and skipped — not fatal.
  • Output goes to tui.log, not a visible pane (there's no pane to show it in yet at that point in startup).

The shipped example, system_startdate.py, writes a cfg.tui.startdate state entry (visible on the States pane) with the current UTC time on every launch — a minimal template for "run something once per session" init scripts.