Compare commits

..
Author SHA1 Message Date
jschoubben 0010b6bf21 ombi: adopt the Plex entry that plex itself answers for
ace's ombi holds one Plex entry, loaded from an older server and later
retyped to plex's public name: its stored machineIdentifier is not plex's,
while its address answers as plex. Matching by identifier alone would leave
it and add a second entry for the same server.

When no entry carries the server's identifier, each entry's own address is
asked for /identity, and an entry plex answers for is adopted: the bound
connection laid over, and the identifier corrected (ombi builds its "view in
Plex" links from it). Its name, libraries and every other choice stay. An
entry that cannot be asked, or answers as another server, is left alone;
nothing is guessed. Every call of the step is now bounded, since an entry may
name a host that no longer answers.
2026-09-30 13:14:12 +02:00
jschoubben b068a9d399 ombi: reach plex through the mesh, in the same step as the Servarr apps
ombi reached plex at its public name, typed into its settings screen, so it
depended on plex's public route and on nobody moving plex. ombi now requires
plex-api, and the run-once step that writes its Servarr connections writes
its Plex one too - renamed from `servarr` to `connections`, since it is no
longer only that.

ombi keeps several Plex servers. The entry this provision names is found by
the server's own machineIdentifier (plex answers it at /identity, and ombi
stored it when the server was loaded), and only its host, port, TLS, base
path and token are written, only when they differ. Another server's entry,
the selected libraries, whether Plex is enabled and every other choice are
left alone. An ombi with no entry for the server gets one.

The token is tried against plex first. Until the operator accepts the
server's X-Plex-Token for this pair the mesh delivers a value it minted,
which plex refuses (401, or 400 on a network it trusts); refused, nothing is
written and the step fails naming the secret accept, so a working token in
ombi is never replaced by a dead one.

Tests import the compiled step, as keycloak's do: the step imports its
sibling with the .js specifier the build needs, which type stripping does
not resolve. `npm test` builds first.
2026-09-30 12:59:12 +02:00
jschoubben f14c763463 ombi: reach sonarr, radarr and lidarr through the mesh
ombi keeps its Servarr connections in its own database, so the mesh has no
file to write them into. A run-once step reads the three bindings and pair
credentials and writes host, port, TLS, base path and key into ombi through
ombi's own API - only when they differ, and nothing else ombi keeps.

Until the operator accepts an app's key for this pair the mesh delivers a
value it minted, which no Servarr app accepts. The step tries the key against
the app first and, refused, writes nothing and fails naming the secret accept
that fixes it, so the old working key in ombi is never replaced by a dead one.

Declared last so its failing gates nothing else of ombi (ADR 0136), and
restart-on its six inputs so it runs again when a provider moves (ADR 0099).
2026-09-30 00:39:19 +02:00
jschoubben ab44ff02e1 sonarr, radarr, lidarr: provide their API to the mesh
A consumer on another machine (ombi first; jackett, bazarr and home-assistant
later) reached these by container name on HAL's shared network, which the mesh
does not have. Each app now provides <app>-api at mesh scope and serves the
software port, so the mesh tells a consumer where it is and redirects the
port to where the machine published it.

Named per app, not one servarr-api: a requirement is matched by name and
answered by exactly one provider per node, so a consumer cannot require one
name from three providers - and ombi's code is written against each app's
own API version (ADR 0027).

No grants and no provisioner: a Servarr instance has one API key, which the
mesh cannot mint. The operator accepts it as the pair credential for each
consumer (ADR 0092).
2026-09-30 00:39:19 +02:00
jschoubben c4c44efb1b Merge remote-tracking branch 'origin/fix/sidecars-dial-the-port-they-were-given' into feat/servarr-api-provision 2026-09-30 00:25:55 +02:00
jschoubben 5cc6258326 Sidecars dial the port they were given, not the software's
A host-network sidecar reaches its service over the machine's loopback, and
the mesh publishes that service on a machine port it assigns (ADR 0038) —
so dialling the software's port reaches whatever else holds it. On ace,
searxng's sidecar dialled 127.0.0.1:8080 and got unifi's inform port. The
same shape in bazarr, bookshelf, lidarr, nzbget, qbittorrent, radarr and
sonarr; each now asks with ${port:N} (hq 088). Found in review of ace's
module preparation.
2026-09-29 23:50:19 +02:00
jschoubben 21f5301268 ombi: its config is placed, its image is the one ace runs
ombi's definition named /services/ombi/config (a HAL machine path) in three
places and pinned an image older than the one ace runs. Ombi migrates its
own SQLite schema, so a take onto the older pin (v4.53.10-ls267) would start
it on a database the newer build (ls269) already touched.

- config is a pathless placed directory, mounted as ${dir:config}
- a state directory placed at the assignment root carries route.json
- image pinned to the digest ace runs today (v4.53.10-ls269)
- the sidecar reaches ombi on the machine port the mesh assigns
  (${port:3579}) rather than assuming 3579 is free
- the sidecar no longer mounts ombi's data directory: MESH_OMBI_CONFIG_DIR
  is read by no code, and the mount exposed the databases for nothing

Verified: catalogue tests (MESH_CATALOGUE set, 6 pass, none skipped); the
pinned image starts as PUID 1000 in a 0700 dir and answers /api/v1/Status
200; data owned 1001:2000 (ace's media ids) under a 1000:1000 dir is
re-owned by the image's init and serves 200; a minted ApiKey is refused
(401) - the api-key secret must be accepted from ombi's own settings.
2026-09-29 23:38:56 +02:00
830 changed files with 9240 additions and 109742 deletions
-103
View File
@@ -1,103 +0,0 @@
# adwaita
The desktop's theme as a module (novox/hq ADR 0208, research 026, to-be 42 phase 2, step 6): Adwaita
for GTK, Qt, the portal and the cursor, dark by default. It claims no seat, because themes coexist.
- **Packages:** `gnome-themes-extra` (Adwaita-dark for GTK 2 and 3), `adwaita-icon-theme`,
`adwaita-cursors`, `qt6ct`, `xdg-desktop-portal-gtk`.
- **Environment** (ADR 0203), the five words today's `~/.xinitrc` exported plus the cursor:
- `GTK_THEME=Adwaita:dark`;
- `GTK2_RC_FILES=/usr/share/themes/Adwaita-dark/gtk-2.0/gtkrc`;
- `QT_QPA_PLATFORMTHEME=qt6ct`;
- `QT_STYLE_OVERRIDE=Fusion`;
- `QT_SELECT=6`;
- `XCURSOR_THEME=Adwaita`, `XCURSOR_SIZE=24`.
- **Session code** (ADR 0208 §4):
- in the `xinitrc` slot `normal`, the GSettings keys the portal serves (dark, the GTK and icon theme,
the cursor, the UI and monospace fonts), set at every session start. This replaces the
predecessor's `~/scripts/xdg-appearance`;
- in the `xresources` slot `normal`, `Xcursor.theme` and `Xcursor.size`.
## What it owns
| path | class | from |
|---|---|---|
| `~/.config/gtk-3.0/settings.ini` | owned (the found file kept once) | [`config/gtk-settings.ini`](config/gtk-settings.ini) |
| `~/.config/gtk-4.0/settings.ini` | owned | the same file |
| `~/.config/qt6ct/qt6ct.conf` | owned | [`config/qt6ct.conf`](config/qt6ct.conf) |
| `~/.config/xdg-desktop-portal/portals.conf` | owned | [`config/portals.conf`](config/portals.conf) |
| `~/.icons/default/index.theme` | owned | [`config/cursor-index.theme`](config/cursor-index.theme): the cursor for programs that read neither `XCURSOR_THEME` nor the resources |
**`qt6ct.conf` is the mesh's now.** A change made in qt6ct's own window is replaced at the next push,
and the window's saved geometry goes with it. The theme is this module's to say. Settings will make it
the operator's (issue 168).
## What it improves
- **No package from the user repository.** Today's Qt style, `adwaita-dark` (`QT_STYLE_OVERRIDE` and
qt6ct's `Adwaita-Dark`), comes from the user repository's `adwaita-qt5`/`adwaita-qt6-git`, a
project that is no longer developed. The module uses Qt's own **Fusion** style with qt6ct's
**`darker`** palette, both shipped with Qt and qt6ct. **This is the one visible change:** Qt
programs keep a dark palette, drawn by Fusion instead of Adwaita-Qt.
- **One Qt tool.** `qt5ct` is gone (installed on the desktop only, with a configuration on both).
`QT_SELECT=6` and `qt6ct` cover the Qt 6 programs. A Qt 5 program gets Fusion through
`QT_STYLE_OVERRIDE`, but not the palette.
- **The fonts research 026/04 chose:** Inter 11 for GTK, Qt and GSettings' interface font, and
JetBrains Mono Nerd Font for Qt's fixed font and GSettings' monospace. Today these are Noto Sans 12,
Adwaita Sans 11 and nothing.
- **The cursor said everywhere**: GTK's settings, GSettings, `XCURSOR_*`, the X resources and the
default theme. Today only the resources and GSettings said it.
- **The portal answers secrets.** `portals.conf` routes `org.freedesktop.impl.portal.Secret` to
gnome-keyring. Today `adwaita_portal_check` shows no backend answering it: gtk does not implement
it, and gnome-keyring's backend names only GNOME.
## Tools
| tool | | what |
|---|---|---|
| `adwaita_appearance` | r/a | dark or light as each audience sees it (GSettings, the portal's own answer, the GTK files, Qt's style and palette, the theme words in the user manager). `mode` switches GSettings for the session, and the answer says what follows live (programs asking the portal) and what stays dark (GTK 3 under `GTK_THEME`, the declared files) |
| `adwaita_cursor` | r/a | the cursor in GSettings, the resources and the environment, and the cursor themes installed; set theme or size for new windows (GSettings, and the resources when a session runs) |
| `adwaita_icons` | r | icon themes installed (where, what each inherits, whether it has cursors), and the one GSettings, GTK and Qt use |
| `adwaita_portal_check` | r | the backends installed and what each implements, which `portals.conf` decides (the first that exists, in xdg-desktop-portal's order), the backend answering each interface, what runs on the bus, and the colour scheme the portal answers |
Each reaches GSettings, the portal and the user manager on the account's bus. Only the cursor's X
resources need the session. From the user manager it reads only the theme's own words.
**The appearance is a session's choice.** A persistent dark or light, for the files too, is a setting
and waits for issue 168. Until then the module's default is dark, and `mode` lasts until the next
login.
## What it leaves found
`~/.config/qt5ct/`, `~/.config/gtk-3.0/bookmarks` and everything else in those directories,
`~/scripts/xdg-appearance`, and the user repository's `adwaita-qt*` packages.
## The one-off migration (ADR 0182)
**Once `adwaita` is assigned:**
1. In `~/.xinitrc`, the theme exports and `~/scripts/xdg-appearance || true` go (see `xorg`'s list).
2. Delete `~/scripts/xdg-appearance`.
3. In `~/.Xresources`, delete the two `Xcursor` lines.
4. Delete `~/.config/qt5ct/`.
5. Remove the user repository's packages: `sudo pacman -Rns adwaita-qt5-git adwaita-qt6-git`
(laptop), `sudo pacman -Rns adwaita-qt5 adwaita-qt6-git adwaita-dark qt5ct` (desktop). Check first
that nothing else needs them (`pacman -Qi`).
## What changes when it is assigned
| | g14 | shanks |
|---|---|---|
| packages | none (all present) | the same |
| GTK settings, `portals.conf` | the found files kept once, then the module's: adds the cursor and Inter, keeps Adwaita dark; `portals.conf` adds the Secret line | the same |
| `qt6ct.conf` | Fusion with the `darker` palette, Inter and JetBrains Mono, instead of Adwaita-Dark with Noto Sans | the same |
| `~/.icons/default/index.theme` | new | new |
| environment | `QT_STYLE_OVERRIDE` becomes `Fusion`; `XCURSOR_*` added; the rest as `~/.xinitrc` exported them | the same |
| running programs | **nothing**: settings are read at a program's start, and GSettings is set at the next login | the same |
| next login | GSettings' fonts become Inter and JetBrains Mono. A secret request through the portal finds gnome-keyring | the same |
## Blockers
- **`fonts` first**, for Inter and JetBrains Mono. Without them, GTK and Qt fall back to the nearest
installed face.
- **Light is a session's choice only**, until settings (issue 168).
@@ -1,246 +0,0 @@
package main
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"adwaita/internal/desktop"
)
type manifest struct {
Capabilities []string `json:"capabilities"`
Claims []any `json:"claims"`
Tools []string `json:"tools"`
Environment struct {
Variables map[string]string `json:"variables"`
} `json:"environment"`
Shell []struct {
For, Slot, Code string
} `json:"shell"`
Resources []map[string]any `json:"resources"`
}
func readManifest(t *testing.T) manifest {
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
var m manifest
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatal(err)
}
return m
}
func TestItContributesTheThemesWordsAndClaimsNoSeat(t *testing.T) {
m := readManifest(t)
if m.Claims != nil {
t.Fatal("a theme is not a seat: several coexist")
}
want := map[string]string{"GTK_THEME": "Adwaita:dark", "GTK2_RC_FILES": "/usr/share/themes/Adwaita-dark/gtk-2.0/gtkrc",
"QT_QPA_PLATFORMTHEME": "qt6ct", "QT_STYLE_OVERRIDE": "Fusion", "QT_SELECT": "6", "XCURSOR_THEME": "Adwaita", "XCURSOR_SIZE": "24"}
if len(m.Environment.Variables) != len(want) {
t.Fatalf("%v", m.Environment.Variables)
}
for k, v := range want {
if m.Environment.Variables[k] != v {
t.Errorf("%s=%q", k, m.Environment.Variables[k])
}
}
served := map[string]bool{}
for _, tool := range tools(adwaita{}) {
served[tool.Name] = true
}
if len(served) != len(m.Tools) {
t.Fatalf("%v %v", served, m.Tools)
}
for _, n := range m.Tools {
if !served[n] {
t.Errorf("%s", n)
}
}
}
func TestTheSessionLinesSetGSettingsAndTheResourcesTheCursor(t *testing.T) {
m := readManifest(t)
if len(m.Shell) != 2 || m.Shell[0].For != "xresources" || m.Shell[1].For != "xinitrc" || m.Shell[0].Slot != "normal" || m.Shell[1].Slot != "normal" {
t.Fatalf("%+v", m.Shell)
}
if m.Shell[0].Code != "! adwaita: the cursor, for X programs that take it from the resources.\nXcursor.theme: Adwaita\nXcursor.size: 24\n" {
t.Fatalf("%q", m.Shell[0].Code)
}
x := m.Shell[1].Code
for _, want := range []string{"color-scheme 'prefer-dark'", "gtk-theme 'Adwaita'", "icon-theme 'Adwaita'", "cursor-theme 'Adwaita'", "font-name 'Inter 11'", "monospace-font-name 'JetBrainsMono Nerd Font 11'"} {
if !strings.Contains(x, want) {
t.Errorf("lacks %s", want)
}
}
for _, l := range strings.Split(strings.TrimSpace(x), "\n") {
if !strings.HasPrefix(l, "#") && !strings.HasSuffix(l, "|| true") {
t.Errorf("a session line that can stop the session's start: %q", l)
}
}
}
func TestItOwnsTheFilesItsSourcesHoldAndNoQt5Duplicate(t *testing.T) {
m := readManifest(t)
sources := map[string]string{"gtk3": "gtk-settings.ini", "gtk4": "gtk-settings.ini", "qt6ct": "qt6ct.conf", "portals": "portals.conf", "cursor": "cursor-index.theme"}
pkgs := []string{}
for _, r := range m.Resources {
id := r["id"].(string)
if r["type"] == "package" {
pkgs = append(pkgs, r["package"].(string))
continue
}
raw, _ := os.ReadFile(filepath.Join("..", "..", "config", sources[id]))
if r["content"] != string(raw) || r["into"] != nil || r["owner"] != "${machine:account}" {
t.Errorf("%s is not config/%s, whole and the account's", id, sources[id])
}
if strings.Contains(r["path"].(string), "qt5ct") {
t.Error("qt5ct: both workstations run Qt 6 programs through qt6ct; a second tool is a duplicate")
}
}
if strings.Join(pkgs, ",") != "gnome-themes-extra,adwaita-icon-theme,adwaita-cursors,qt6ct,xdg-desktop-portal-gtk" {
t.Fatalf("%v", pkgs)
}
qt := readINI(filepath.Join("..", "..", "config", "qt6ct.conf"))
if qt["Appearance"]["style"] != "Fusion" || qt["Appearance"]["custom_palette"] != "true" || !strings.Contains(qt["Fonts"]["general"], "Inter,11") {
t.Fatalf("%v", qt)
}
if _, err := os.Stat("/usr/share/qt6ct/colors"); err == nil {
if _, err := os.Stat(qt["Appearance"]["color_scheme_path"]); err != nil {
t.Fatalf("qt6ct ships no %s", qt["Appearance"]["color_scheme_path"])
}
}
gtk := readINI(filepath.Join("..", "..", "config", "gtk-settings.ini"))["Settings"]
if gtk["gtk-theme-name"] != "Adwaita" || gtk["gtk-application-prefer-dark-theme"] != "1" || gtk["gtk-font-name"] != "Inter 11" {
t.Fatalf("%v", gtk)
}
}
func TestKeyFilesAreReadWithTheirComments(t *testing.T) {
ini := ParseINI("# c\n[A]\nk = v\n; also a comment\n[B]\nx=1=2\n")
if ini["A"]["k"] != "v" || ini["B"]["x"] != "1=2" || len(ini) != 2 {
t.Fatalf("%v", ini)
}
}
func TestThePortalsAnswerIsResolvedAsXdgDesktopPortalDoes(t *testing.T) {
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "gtk.portal"), []byte("[portal]\nDBusName=org.freedesktop.impl.portal.desktop.gtk\nInterfaces=org.freedesktop.impl.portal.FileChooser;org.freedesktop.impl.portal.Settings;\nUseIn=gnome\n"), 0o644)
os.WriteFile(filepath.Join(dir, "gnome-keyring.portal"), []byte("[portal]\nDBusName=org.freedesktop.secrets\nInterfaces=org.freedesktop.impl.portal.Secret;\nUseIn=gnome\n"), 0o644)
os.WriteFile(filepath.Join(dir, "kde.portal"), []byte("[portal]\nDBusName=org.freedesktop.impl.portal.desktop.kde\nInterfaces=org.freedesktop.impl.portal.FileChooser;\nUseIn=KDE\n"), 0o644)
b := Backends([]string{dir})
if len(b) != 3 || b[0].Name != "gnome-keyring" || len(b[1].Interfaces) != 2 {
t.Fatalf("%+v", b)
}
got := Resolve(b, map[string]string{"default": "gtk", "org.freedesktop.impl.portal.Secret": "gnome-keyring"}, []string{"i3"})
if got["org.freedesktop.impl.portal.FileChooser"] != "gtk" || got["org.freedesktop.impl.portal.Secret"] != "gnome-keyring" || got["org.freedesktop.impl.portal.Settings"] != "gtk" {
t.Fatalf("%v", got)
}
got = Resolve(b, map[string]string{"default": "gtk"}, []string{"i3"})
if got["org.freedesktop.impl.portal.Secret"] != "(none)" {
t.Fatalf("gtk does not implement secrets: %v", got)
}
got = Resolve(b, map[string]string{"default": "none;gtk"}, nil)
if got["org.freedesktop.impl.portal.FileChooser"] != "(none)" {
t.Fatalf("none stops the list: %v", got)
}
got = Resolve(b, nil, []string{"KDE"})
if got["org.freedesktop.impl.portal.FileChooser"] != "kde" || got["org.freedesktop.impl.portal.Settings"] != "(none)" {
t.Fatalf("with no configuration, UseIn decides: %v", got)
}
c := PortalConfigs("/h", []string{"i3", "GNOME"})
if c[0] != "/h/.config/xdg-desktop-portal/i3-portals.conf" || c[1] != "/h/.config/xdg-desktop-portal/gnome-portals.conf" || c[2] != "/h/.config/xdg-desktop-portal/portals.conf" {
t.Fatalf("%v", c[:3])
}
}
func TestThemesAreFoundOnceEachWithCursorsAndIcons(t *testing.T) {
a, b := t.TempDir(), t.TempDir()
os.MkdirAll(filepath.Join(a, "Adwaita", "cursors"), 0o755)
os.MkdirAll(filepath.Join(b, "Adwaita"), 0o755)
os.WriteFile(filepath.Join(b, "Adwaita", "index.theme"), []byte("[Icon Theme]\nName=Adwaita\nInherits=hicolor\nDirectories=16x16\n"), 0o644)
os.MkdirAll(filepath.Join(b, "hicolor"), 0o755)
os.WriteFile(filepath.Join(b, "hicolor", "index.theme"), []byte("[Icon Theme]\nName=Hicolor\nDirectories=16x16\n"), 0o644)
os.MkdirAll(filepath.Join(b, "empty"), 0o755)
got := Themes([]string{a, b})
if len(got) != 2 || got[0].Name != "Adwaita" || !got[0].Cursors || got[0].Icons || got[0].Dir != filepath.Join(a, "Adwaita") || got[1].Name != "hicolor" {
t.Fatalf("the first directory's Adwaita hides the second's: %+v", got)
}
}
type fake struct {
ran []string
get map[string]string
}
func (f *fake) desk() desktop.Desk {
return desktop.Desk{
Find: func() (*desktop.Session, error) { return nil, &desktop.NoSession{Reason: "none"} },
Run: func(_ context.Context, env []string, _ []byte, name string, args ...string) desktop.Result {
line := strings.Join(append([]string{name}, args...), " ")
f.ran = append(f.ran, line)
switch {
case name == "gsettings" && args[0] == "get":
return desktop.Result{Stdout: "'" + f.get[args[2]] + "'\n"}
case name == "gsettings" && args[0] == "set":
f.get[args[2]] = args[3]
case name == "systemctl":
return desktop.Result{Stdout: "GTK_THEME=Adwaita:dark\nNPM_TOKEN=secret\nXDG_CURRENT_DESKTOP=i3\n"}
case name == "busctl" && args[1] == "call":
return desktop.Result{Stdout: "v u 1\n"}
}
return desktop.Result{}
},
}
}
func TestAppearanceSwitchesGSettingsAndSaysWhatFollowsAndWhatStays(t *testing.T) {
f := &fake{get: map[string]string{"color-scheme": "prefer-dark", "gtk-theme": "Adwaita"}}
a := adwaita{d: f.desk(), home: t.TempDir()}
got, err := a.appearance(context.Background(), desktop.Args{"mode": "light"})
if err != nil {
t.Fatal(err)
}
j := asJSON(got)
if f.get["color-scheme"] != "prefer-light" || !strings.Contains(j, `"switched":"light"`) || !strings.Contains(j, "GTK_THEME=Adwaita:dark") || !strings.Contains(j, `"lasts"`) {
t.Fatalf("%s", j)
}
if strings.Contains(j, "secret") || strings.Contains(j, "NPM_TOKEN") {
t.Fatal("only the theme's words are read back from the user manager")
}
if _, err := a.appearance(context.Background(), desktop.Args{"mode": "blue"}); err == nil {
t.Fatal("mode is dark or light")
}
got, _ = a.appearance(context.Background(), desktop.Args{})
if strings.Contains(asJSON(got), "switched") {
t.Fatal("reading changes nothing")
}
}
func TestACursorThemeMustBeInstalledAndWithoutASessionOnlyGSettingsChanges(t *testing.T) {
dir := t.TempDir()
os.MkdirAll(filepath.Join(dir, "Adwaita", "cursors"), 0o755)
f := &fake{get: map[string]string{}}
a := adwaita{d: f.desk(), home: t.TempDir(), iconDirs: []string{dir}}
if _, err := a.cursor(context.Background(), desktop.Args{"theme": "Bibata"}); err == nil {
t.Fatal("a theme that is not installed")
}
got, err := a.cursor(context.Background(), desktop.Args{"theme": "Adwaita", "size": float64(32)})
if err != nil {
t.Fatal(err)
}
if f.get["cursor-theme"] != "Adwaita" || f.get["cursor-size"] != "32" || !strings.Contains(asJSON(got), "no graphical session") {
t.Fatalf("%v %s", f.get, asJSON(got))
}
}
func asJSON(v any) string {
b, _ := json.Marshal(v)
return string(b)
}
-84
View File
@@ -1,84 +0,0 @@
// adwaita's tools (novox/hq ADR 0208, research 026/05): appearance (dark or light for GTK, Qt and the
// portal at once), cursor, icons and portal-check. The predecessor's appearance script is folded into
// the first, and into the module's session line.
//
// None needs the display except setting the cursor's X resources: GSettings, the portal and the user
// manager are reached on the account's own bus, which exists whenever the operator's user manager
// runs.
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
"adwaita/internal/desktop"
)
func main() {
home := desktop.Home()
a := adwaita{
d: desktop.Machine("i3", "sway"), home: home,
iconDirs: []string{filepath.Join(home, ".local", "share", "icons"), filepath.Join(home, ".icons"), "/usr/local/share/icons", "/usr/share/icons"},
portalDirs: []string{"/usr/share/xdg-desktop-portal/portals"},
uid: os.Getuid(),
}
if err := stdio.Serve("", tools(a)); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func call(run func(ctx context.Context, a desktop.Args) (any, error)) func(map[string]any) (any, error) {
return func(args map[string]any) (any, error) {
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
return run(ctx, desktop.Args(args))
}
}
func tools(a adwaita) []stdio.Tool {
return []stdio.Tool{
{
Name: "adwaita_appearance",
Description: "Dark or light, as each audience sees it now: GSettings (which the portal serves to " +
"Electron, Firefox and flatpaks), the portal's own answer, the GTK settings files, Qt's palette " +
"and the theme words in the user manager's environment. With mode, switch GSettings for the " +
"running session and answer which audiences follow live and which keep the module's dark " +
"default until it is a setting.",
Input: desktop.Schema(map[string]any{"mode": desktop.Enum("switch to (optional)", "dark", "light")}),
Run: call(a.appearance),
},
{
Name: "adwaita_cursor",
Description: "The cursor theme and size in force (GSettings, the X resources, XCURSOR_* in the user " +
"manager) and the cursor themes installed. With theme and/or size, set them for windows opened " +
"from now on; the module's defaults return at the next login.",
Input: desktop.Schema(map[string]any{
"theme": desktop.Str("an installed cursor theme"),
"size": desktop.Int("pixels, 8 to 256"),
}),
Run: call(a.cursor),
},
{
Name: "adwaita_icons",
Description: "The icon themes installed (name, where, what each inherits, whether it carries cursors) " +
"and the one GTK and Qt are set to use.",
Input: desktop.Schema(map[string]any{}),
Run: call(a.icons),
},
{
Name: "adwaita_portal_check",
Description: "Which xdg-desktop-portal backend answers which interface for this desktop: the backends " +
"installed and what they implement, the portals.conf that decides (and which one won), the " +
"resulting backend per interface, whether the portal and each backend are running on the " +
"account's bus, and the colour scheme the portal answers.",
Input: desktop.Schema(map[string]any{}),
Run: call(a.portalCheck),
},
}
}
-434
View File
@@ -1,434 +0,0 @@
package main
import (
"bufio"
"context"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"adwaita/internal/desktop"
)
type adwaita struct {
d desktop.Desk
home string
iconDirs []string
portalDirs []string
uid int
}
const iface = "org.gnome.desktop.interface"
// ParseINI reads a key file (GTK's settings.ini, qt6ct.conf, a .portal, index.theme): sections of
// key=value, `#` and `;` comments.
func ParseINI(text string) map[string]map[string]string {
out := map[string]map[string]string{}
section := ""
sc := bufio.NewScanner(strings.NewReader(text))
for sc.Scan() {
l := strings.TrimSpace(sc.Text())
if l == "" || strings.HasPrefix(l, "#") || strings.HasPrefix(l, ";") {
continue
}
if strings.HasPrefix(l, "[") && strings.HasSuffix(l, "]") {
section = l[1 : len(l)-1]
continue
}
if k, v, ok := strings.Cut(l, "="); ok {
if out[section] == nil {
out[section] = map[string]string{}
}
out[section][strings.TrimSpace(k)] = strings.TrimSpace(v)
}
}
return out
}
func readINI(path string) map[string]map[string]string {
b, err := os.ReadFile(path)
if err != nil {
return nil
}
return ParseINI(string(b))
}
// gsetting is one GSettings value, unquoted.
func (a adwaita) gsetting(ctx context.Context, schema, key string) (string, error) {
r := a.d.AsUser(ctx, "gsettings", "get", schema, key)
if !r.OK() {
return "", r.Err()
}
return strings.Trim(strings.TrimSpace(r.Stdout), "'"), nil
}
// themeWords are the words of the user manager's environment the theme is about; nothing else of it
// is read back.
var themeWords = []string{"GTK_THEME", "GTK2_RC_FILES", "QT_QPA_PLATFORMTHEME", "QT_STYLE_OVERRIDE", "QT_SELECT",
"XCURSOR_THEME", "XCURSOR_SIZE", "XDG_CURRENT_DESKTOP"}
func (a adwaita) userEnvironment(ctx context.Context) map[string]string {
r := a.d.AsUser(ctx, "systemctl", "--user", "show-environment")
all := desktop.ParseProperties(r.Stdout)
out := map[string]string{}
for _, w := range themeWords {
if v, ok := all[w]; ok {
out[w] = v
}
}
return out
}
var portalScheme = regexp.MustCompile(`^v u (\d)`)
// portalColourScheme asks the portal what it tells applications: 0 no preference, 1 dark, 2 light.
func (a adwaita) portalColourScheme(ctx context.Context) string {
r := a.d.AsUser(ctx, "busctl", "--user", "call", "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop",
"org.freedesktop.portal.Settings", "ReadOne", "ss", "org.freedesktop.appearance", "color-scheme")
m := portalScheme.FindStringSubmatch(strings.TrimSpace(r.Stdout))
if !r.OK() || m == nil {
return "unanswered"
}
return map[string]string{"0": "no-preference", "1": "dark", "2": "light"}[m[1]]
}
func (a adwaita) appearance(ctx context.Context, args desktop.Args) (any, error) {
mode := args.Opt("mode", "")
if mode != "" && mode != "dark" && mode != "light" {
return nil, fmt.Errorf("mode is dark or light")
}
if mode != "" {
scheme := map[string]string{"dark": "prefer-dark", "light": "prefer-light"}[mode]
if r := a.d.AsUser(ctx, "gsettings", "set", iface, "color-scheme", scheme); !r.OK() {
return nil, r.Err()
}
}
scheme, err := a.gsetting(ctx, iface, "color-scheme")
if err != nil {
return nil, fmt.Errorf("GSettings does not answer on the account's bus: %w", err)
}
gtkTheme, _ := a.gsetting(ctx, iface, "gtk-theme")
gtk3 := readINI(filepath.Join(a.home, ".config", "gtk-3.0", "settings.ini"))["Settings"]
gtk4 := readINI(filepath.Join(a.home, ".config", "gtk-4.0", "settings.ini"))["Settings"]
qt := readINI(filepath.Join(a.home, ".config", "qt6ct", "qt6ct.conf"))["Appearance"]
env := a.userEnvironment(ctx)
answer := map[string]any{
"gsettings": map[string]string{"color-scheme": scheme, "gtk-theme": gtkTheme},
"portal": a.portalColourScheme(ctx),
"gtk3": map[string]string{"theme": gtk3["gtk-theme-name"], "prefer-dark": gtk3["gtk-application-prefer-dark-theme"]},
"gtk4": map[string]string{"theme": gtk4["gtk-theme-name"], "prefer-dark": gtk4["gtk-application-prefer-dark-theme"]},
"qt": map[string]string{"style": qt["style"], "palette": filepath.Base(qt["color_scheme_path"])},
"environment": env,
}
if mode != "" {
var stays []string
if strings.HasSuffix(env["GTK_THEME"], ":dark") && mode == "light" {
stays = append(stays, "GTK 3 programs: GTK_THEME="+env["GTK_THEME"]+" in the environment pins them dark")
}
if mode == "light" {
stays = append(stays, "the GTK settings files and Qt's palette, which the module declares dark")
}
answer["switched"] = mode
answer["follows_live"] = "programs asking the portal: Electron, Chromium, Firefox, libadwaita and flatpaks"
if len(stays) > 0 {
answer["stays"] = stays
}
answer["lasts"] = "until the next login, which sets the module's default (dark) again; a persistent choice waits for settings (hq issue 168)"
}
return answer, nil
}
// Theme is one installed icon or cursor theme.
type Theme struct {
Name string `json:"name"`
Dir string `json:"dir"`
Title string `json:"title,omitempty"`
Inherits []string `json:"inherits,omitempty"`
Cursors bool `json:"cursors"`
Icons bool `json:"icons"`
}
// Themes lists the themes in dirs; a name found earlier hides the same name later, as lookups do.
func Themes(dirs []string) []Theme {
seen := map[string]bool{}
var out []Theme
for _, d := range dirs {
entries, _ := os.ReadDir(d)
for _, e := range entries {
if !e.IsDir() && e.Type()&os.ModeSymlink == 0 || seen[e.Name()] {
continue
}
dir := filepath.Join(d, e.Name())
t := Theme{Name: e.Name(), Dir: dir}
if info, err := os.Stat(filepath.Join(dir, "cursors")); err == nil && info.IsDir() {
t.Cursors = true
}
if ini := readINI(filepath.Join(dir, "index.theme")); ini != nil {
th := ini["Icon Theme"]
t.Title = th["Name"]
if th["Directories"] != "" {
t.Icons = true
}
for _, i := range strings.Split(th["Inherits"], ",") {
if i = strings.TrimSpace(i); i != "" {
t.Inherits = append(t.Inherits, i)
}
}
}
if !t.Cursors && !t.Icons && t.Title == "" {
continue
}
seen[e.Name()] = true
out = append(out, t)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
var cursorName = regexp.MustCompile(`^[A-Za-z0-9._ -]{1,64}$`)
func (a adwaita) cursor(ctx context.Context, args desktop.Args) (any, error) {
theme := args.Opt("theme", "")
size, err := args.Whole("size", 0, 8, 256)
if err != nil {
return nil, err
}
var cursors []string
installed := map[string]bool{}
for _, t := range Themes(a.iconDirs) {
if t.Cursors {
cursors = append(cursors, t.Name)
installed[t.Name] = true
}
}
changed := theme != "" || size != 0
if theme != "" && (!cursorName.MatchString(theme) || !installed[theme]) {
return nil, fmt.Errorf("%q is not an installed cursor theme; installed: %s", theme, strings.Join(cursors, ", "))
}
var resources []string
if theme != "" {
if r := a.d.AsUser(ctx, "gsettings", "set", iface, "cursor-theme", theme); !r.OK() {
return nil, r.Err()
}
resources = append(resources, "Xcursor.theme: "+theme)
}
if size != 0 {
if r := a.d.AsUser(ctx, "gsettings", "set", iface, "cursor-size", strconv.Itoa(size)); !r.OK() {
return nil, r.Err()
}
resources = append(resources, "Xcursor.size: "+strconv.Itoa(size))
}
answer := map[string]any{"installed": cursors}
gTheme, _ := a.gsetting(ctx, iface, "cursor-theme")
gSize, _ := a.gsetting(ctx, iface, "cursor-size")
answer["gsettings"] = map[string]string{"cursor-theme": gTheme, "cursor-size": gSize}
env := a.userEnvironment(ctx)
answer["environment"] = map[string]string{"XCURSOR_THEME": env["XCURSOR_THEME"], "XCURSOR_SIZE": env["XCURSOR_SIZE"]}
if s, err := a.d.Find(); err == nil {
senv := s.Env(a.d.Base)
if len(resources) > 0 {
if r := a.d.Run(ctx, senv, []byte(strings.Join(resources, "\n")+"\n"), "xrdb", "-nocpp", "-merge", "-"); !r.OK() {
return nil, r.Err()
}
}
q := a.d.Run(ctx, senv, nil, "xrdb", "-query")
x := map[string]string{}
for _, l := range strings.Split(q.Stdout, "\n") {
if k, v, ok := strings.Cut(l, ":"); ok && strings.HasPrefix(k, "Xcursor.") {
x[k] = strings.TrimSpace(v)
}
}
answer["x_resources"] = x
} else {
answer["x_resources"] = nil
if changed {
answer["note"] = "no graphical session: GSettings changed, the X resources not"
}
}
if changed {
answer["lasts"] = "for windows opened from now on, until the next login"
}
return answer, nil
}
func (a adwaita) icons(ctx context.Context, args desktop.Args) (any, error) {
var themes []Theme
for _, t := range Themes(a.iconDirs) {
if t.Icons {
themes = append(themes, t)
}
}
gtk3 := readINI(filepath.Join(a.home, ".config", "gtk-3.0", "settings.ini"))["Settings"]
qt := readINI(filepath.Join(a.home, ".config", "qt6ct", "qt6ct.conf"))["Appearance"]
g, _ := a.gsetting(ctx, iface, "icon-theme")
return map[string]any{
"installed": themes,
"in_use": map[string]string{"gsettings": g, "gtk": gtk3["gtk-icon-theme-name"], "qt": qt["icon_theme"]},
}, nil
}
// Backend is one installed portal backend.
type Backend struct {
Name string `json:"name"`
DBusName string `json:"dbus_name"`
Interfaces []string `json:"interfaces"`
UseIn []string `json:"use_in,omitempty"`
Running bool `json:"running"`
}
func splitList(v string) []string {
var out []string
for _, x := range strings.Split(v, ";") {
if x = strings.TrimSpace(x); x != "" {
out = append(out, x)
}
}
return out
}
// Backends reads the installed `.portal` files.
func Backends(dirs []string) []Backend {
var out []Backend
for _, d := range dirs {
files, _ := filepath.Glob(filepath.Join(d, "*.portal"))
sort.Strings(files)
for _, f := range files {
p := readINI(f)["portal"]
out = append(out, Backend{Name: strings.TrimSuffix(filepath.Base(f), ".portal"), DBusName: p["DBusName"],
Interfaces: splitList(p["Interfaces"]), UseIn: splitList(p["UseIn"])})
}
}
return out
}
// PortalConfigs are the files xdg-desktop-portal looks for, in its order (portals.conf(5)): for each
// directory, `<desktop>-portals.conf` for each of the desktops named, then `portals.conf`. The first
// that exists decides everything.
func PortalConfigs(home string, desktops []string) []string {
dirs := []string{
filepath.Join(home, ".config", "xdg-desktop-portal"), "/etc/xdg/xdg-desktop-portal", "/etc/xdg-desktop-portal",
filepath.Join(home, ".local", "share", "xdg-desktop-portal"), "/usr/local/share/xdg-desktop-portal", "/usr/share/xdg-desktop-portal",
}
var out []string
for _, d := range dirs {
for _, desk := range desktops {
out = append(out, filepath.Join(d, strings.ToLower(desk)+"-portals.conf"))
}
out = append(out, filepath.Join(d, "portals.conf"))
}
return out
}
// Resolve says which backend answers each interface the backends implement, given the deciding
// file's [preferred] section: an interface's own key first, else `default`; each a list of backend
// names, the first one that implements the interface wins; `none` answers nothing, `*` any.
// With no file, a backend whose UseIn names the desktop answers.
func Resolve(backends []Backend, preferred map[string]string, desktops []string) map[string]string {
out := map[string]string{}
implements := func(b Backend, i string) bool {
for _, x := range b.Interfaces {
if x == i {
return true
}
}
return false
}
var all []string
seen := map[string]bool{}
for _, b := range backends {
for _, i := range b.Interfaces {
if !seen[i] {
seen[i] = true
all = append(all, i)
}
}
}
sort.Strings(all)
for _, i := range all {
var want []string
if preferred != nil {
if v, ok := preferred[i]; ok {
want = splitList(v)
} else {
want = splitList(preferred["default"])
}
} else {
for _, b := range backends {
for _, u := range b.UseIn {
for _, d := range desktops {
if strings.EqualFold(u, d) {
want = append(want, b.Name)
}
}
}
}
}
out[i] = "(none)"
pick:
for _, w := range want {
if w == "none" {
break
}
for _, b := range backends {
if (w == "*" || w == b.Name) && implements(b, i) {
out[i] = b.Name
break pick
}
}
}
}
return out
}
func (a adwaita) portalCheck(ctx context.Context, args desktop.Args) (any, error) {
env := a.userEnvironment(ctx)
desktops := splitColon(env["XDG_CURRENT_DESKTOP"])
backends := Backends(a.portalDirs)
names := map[string]bool{}
if r := a.d.AsUser(ctx, "busctl", "--user", "list", "--no-legend", "--no-pager"); r.OK() {
for _, l := range strings.Split(r.Stdout, "\n") {
if f := strings.Fields(l); len(f) > 1 && f[1] != "-" {
names[f[0]] = true
}
}
}
for i := range backends {
backends[i].Running = names[backends[i].DBusName]
}
var decided string
var preferred map[string]string
looked := PortalConfigs(a.home, desktops)
for _, f := range looked {
if ini := readINI(f); ini != nil {
decided, preferred = f, ini["preferred"]
if preferred == nil {
preferred = map[string]string{}
}
break
}
}
return map[string]any{
"desktop": env["XDG_CURRENT_DESKTOP"],
"portal": map[string]bool{"running": names["org.freedesktop.portal.Desktop"]},
"backends": backends,
"decided_by": decided,
"preferred": preferred,
"answers": Resolve(backends, preferred, desktops),
"colour_scheme": a.portalColourScheme(ctx),
}, nil
}
func splitColon(v string) []string {
var out []string
for _, x := range strings.Split(v, ":") {
if x = strings.TrimSpace(x); x != "" {
out = append(out, x)
}
}
return out
}
@@ -1,5 +0,0 @@
# Written by the mesh (module adwaita, novox/hq ADR 0208): the default cursor theme, for programs that
# read neither XCURSOR_THEME nor the X resources.
[Icon Theme]
Name=Default
Inherits=Adwaita
-9
View File
@@ -1,9 +0,0 @@
# Written by the mesh (module adwaita, novox/hq ADR 0208), for GTK 3 and GTK 4 alike. Replaced at
# every push; adwaita_appearance switches dark and light for the running session.
[Settings]
gtk-theme-name=Adwaita
gtk-icon-theme-name=Adwaita
gtk-cursor-theme-name=Adwaita
gtk-cursor-theme-size=24
gtk-font-name=Inter 11
gtk-application-prefer-dark-theme=1
-11
View File
@@ -1,11 +0,0 @@
# Written by the mesh (module adwaita, novox/hq ADR 0208). Replaced at every push.
#
# Which portal backend answers each interface. i3 is not a desktop xdg-desktop-portal knows, so with
# no preference it uses whichever backend happens to be installed: fine while gtk is the only one,
# wrong the day another arrives as somebody else's dependency. Named instead. gtk also serves
# org.freedesktop.appearance (dark or light) from GSettings, which the session's start sets.
[preferred]
default=gtk
# Secrets for sandboxed programs come from the keyring's backend. Without this line no backend answers
# the interface: gtk does not implement it, and gnome-keyring's names only GNOME as its desktop.
org.freedesktop.impl.portal.Secret=gnome-keyring
-29
View File
@@ -1,29 +0,0 @@
[Appearance]
color_scheme_path=/usr/share/qt6ct/colors/darker.conf
custom_palette=true
icon_theme=Adwaita
standard_dialogs=default
style=Fusion
[Fonts]
fixed="JetBrainsMono Nerd Font,11,-1,5,50,0,0,0,0,0"
general="Inter,11,-1,5,50,0,0,0,0,0"
[Interface]
activate_item_on_single_click=1
buttonbox_layout=0
cursor_flash_time=1000
dialog_buttons_have_icons=1
double_click_interval=400
gui_effects=@Invalid()
keyboard_scheme=2
menus_have_icons=true
show_shortcuts_in_context_menus=true
stylesheets=@Invalid()
toolbutton_style=4
underline_shortcut=1
wheel_scroll_lines=3
[Troubleshooting]
force_raster_widgets=1
ignored_applications=@Invalid()
-5
View File
@@ -1,5 +0,0 @@
module adwaita
go 1.22
require git.novox.be/novox/mesh-sdk/go v0.1.7
-2
View File
@@ -1,2 +0,0 @@
git.novox.be/novox/mesh-sdk/go v0.1.7 h1:C0sTQmtTiyYH7bnqZb7PusXnqA37gKuT7Nqjn9gG47w=
git.novox.be/novox/mesh-sdk/go v0.1.7/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
-160
View File
@@ -1,160 +0,0 @@
package desktop
import (
"fmt"
"math"
"os"
"path/filepath"
"strings"
)
// Args reads a tool's arguments as JSON decoded them: strings, float64 numbers, booleans.
type Args map[string]any
// Text is a required string, trimmed.
func (a Args) Text(name string) (string, error) {
v, ok := a[name].(string)
if !ok || strings.TrimSpace(v) == "" {
return "", fmt.Errorf("%s is required, as text", name)
}
return strings.TrimSpace(v), nil
}
// Opt is an optional string, trimmed, or def.
func (a Args) Opt(name, def string) string {
if v, ok := a[name].(string); ok && strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
return def
}
// Has is whether the caller gave the argument at all.
func (a Args) Has(name string) bool {
v, ok := a[name]
return ok && v != nil
}
// Bool is an optional boolean: its value, and whether it was given.
func (a Args) Bool(name string) (bool, bool, error) {
v, ok := a[name]
if !ok || v == nil {
return false, false, nil
}
b, isBool := v.(bool)
if !isBool {
return false, false, fmt.Errorf("%s is true or false", name)
}
return b, true, nil
}
// Number is an optional number: its value, and whether it was given.
func (a Args) Number(name string) (float64, bool, error) {
v, ok := a[name]
if !ok || v == nil {
return 0, false, nil
}
f, isNum := v.(float64)
if !isNum || math.IsNaN(f) || math.IsInf(f, 0) {
return 0, false, fmt.Errorf("%s is a number", name)
}
return f, true, nil
}
// Whole is an optional whole number within [lo, hi], or def.
func (a Args) Whole(name string, def, lo, hi int) (int, error) {
f, given, err := a.Number(name)
if err != nil {
return 0, err
}
if !given {
return def, nil
}
if f != math.Trunc(f) || f < float64(lo) || f > float64(hi) {
return 0, fmt.Errorf("%s is a whole number from %d to %d", name, lo, hi)
}
return int(f), nil
}
// OneOf is an optional string that must be one of choices, or def.
func (a Args) OneOf(name, def string, choices ...string) (string, error) {
v := a.Opt(name, def)
for _, c := range choices {
if v == c {
return v, nil
}
}
return "", fmt.Errorf("%s is one of %s", name, strings.Join(choices, ", "))
}
// Strings is an optional list of strings.
func (a Args) Strings(name string) ([]string, error) {
v, ok := a[name]
if !ok || v == nil {
return nil, nil
}
list, isList := v.([]any)
if !isList {
return nil, fmt.Errorf("%s is a list of text", name)
}
out := make([]string, 0, len(list))
for _, x := range list {
s, isText := x.(string)
if !isText {
return nil, fmt.Errorf("%s is a list of text", name)
}
out = append(out, s)
}
return out, nil
}
// Home is the operator account's home: the runtime's word for it, else this process's.
func Home() string {
if h := os.Getenv("MESH_OPERATOR_HOME"); h != "" {
return h
}
if h, err := os.UserHomeDir(); err == nil {
return h
}
return "/"
}
// InHome resolves a path the caller gave: `~/x` and a relative path are under the home. A path
// that leaves the home through `..` is refused, so a tool that writes never writes outside it.
func InHome(path string) (string, error) {
home := Home()
switch {
case path == "~":
path = home
case strings.HasPrefix(path, "~/"):
path = filepath.Join(home, path[2:])
case !filepath.IsAbs(path):
path = filepath.Join(home, path)
}
path = filepath.Clean(path)
if path != home && !strings.HasPrefix(path, home+string(filepath.Separator)) {
return "", fmt.Errorf("%s is outside the account's home", path)
}
return path, nil
}
// Schema builds a tool's input schema from property descriptions; required names those that must
// be given. A property is a string unless its description object says otherwise.
func Schema(props map[string]any, required ...string) map[string]any {
s := map[string]any{"type": "object", "properties": props}
if len(required) > 0 {
s["required"] = required
}
return s
}
// Str, Num, Flag, List and Enum describe one property.
func Str(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} }
func Num(desc string) map[string]any { return map[string]any{"type": "number", "description": desc} }
func Int(desc string) map[string]any { return map[string]any{"type": "integer", "description": desc} }
func Flag(desc string) map[string]any { return map[string]any{"type": "boolean", "description": desc} }
func List(desc string) map[string]any {
return map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": desc}
}
func Enum(desc string, values ...string) map[string]any {
return map[string]any{"type": "string", "enum": values, "description": desc}
}
@@ -1,42 +0,0 @@
package desktop
import (
"bytes"
"os"
"path/filepath"
"testing"
)
// The desktop modules that carry this package. Each builds alone, so each has its own copy; this
// test, itself one of the copied files, holds them to one text wherever the siblings are present.
var carriers = []string{"xorg", "lemurs", "i3", "xterm", "adwaita"}
func TestEveryDesktopModuleCarriesTheSameCopy(t *testing.T) {
mine, err := filepath.Glob("*.go")
if err != nil || len(mine) == 0 {
t.Fatal("no files of this package found", err)
}
compared := 0
for _, module := range carriers {
dir := filepath.Join("..", "..", "..", module, "internal", "desktop")
if _, err := os.Stat(dir); err != nil {
continue
}
theirs, _ := filepath.Glob(filepath.Join(dir, "*.go"))
if len(theirs) != len(mine) {
t.Errorf("%s carries %d files of this package, this copy %d", module, len(theirs), len(mine))
continue
}
for _, f := range mine {
a, _ := os.ReadFile(f)
b, err := os.ReadFile(filepath.Join(dir, f))
if err != nil || !bytes.Equal(a, b) {
t.Errorf("%s's copy of %s differs from this one: change every copy together", module, f)
}
}
compared++
}
if compared == 0 {
t.Log("no sibling copies beside this module")
}
}
-232
View File
@@ -1,232 +0,0 @@
package desktop
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"os"
"os/exec"
"strings"
"syscall"
"time"
)
// Bounds on a command a tool runs: well below the runtime's 30 s call limit, and an answer that
// fits in a tool's reply.
const (
DefaultTimeout = 10 * time.Second
MostOutput = 256 << 10
)
// Result is what one command did.
type Result struct {
Command []string `json:"command"`
Code int `json:"exit_code"`
Stdout string `json:"stdout,omitempty"`
Stderr string `json:"stderr,omitempty"`
Truncated bool `json:"truncated,omitempty"`
TimedOut bool `json:"timed_out,omitempty"`
}
// OK is whether the command ran and exited 0.
func (r Result) OK() bool { return r.Code == 0 && !r.TimedOut }
// Err is the command's failure as an error naming it and what it said, or nil.
func (r Result) Err() error {
if r.OK() {
return nil
}
said := strings.TrimSpace(r.Stderr)
if said == "" {
said = strings.TrimSpace(r.Stdout)
}
if r.TimedOut {
return fmt.Errorf("%s did not finish in time", strings.Join(r.Command, " "))
}
return fmt.Errorf("%s exited %d: %s", strings.Join(r.Command, " "), r.Code, said)
}
// Runner runs a command with an environment and answers what it did. Tools take one, so their
// tests replace the machine with a table of answers.
type Runner func(ctx context.Context, env []string, stdin []byte, name string, args ...string) Result
// Exec is the machine's Runner: the command in its own process group, ended with everything it
// started at the deadline, each stream cut at MostOutput.
func Exec(ctx context.Context, env []string, stdin []byte, name string, args ...string) Result {
if _, ok := ctx.Deadline(); !ok {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, DefaultTimeout)
defer cancel()
}
res := Result{Command: append([]string{name}, args...)}
cmd := exec.Command(name, args...)
cmd.Env = env
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if stdin != nil {
cmd.Stdin = bytes.NewReader(stdin)
}
out, errb := &capped{}, &capped{}
cmd.Stdout, cmd.Stderr = out, errb
if err := cmd.Start(); err != nil {
res.Code = 127
res.Stderr = err.Error()
return res
}
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
var err error
select {
case err = <-done:
case <-ctx.Done():
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
err = <-done
res.TimedOut = true
}
res.Stdout, res.Stderr = out.String(), errb.String()
res.Truncated = out.cut || errb.cut
var exit *exec.ExitError
switch {
case err == nil:
case errors.As(err, &exit):
res.Code = exit.ExitCode()
if res.Code < 0 {
res.Code = 128
}
default:
res.Code = 1
if res.Stderr == "" {
res.Stderr = err.Error()
}
}
return res
}
// capped keeps the first MostOutput bytes written to it. Its buffer is a field, not embedded: an
// embedded bytes.Buffer brings ReadFrom along, and io.Copy would use it and never call Write.
type capped struct {
buf bytes.Buffer
cut bool
}
func (c *capped) Write(p []byte) (int, error) {
if room := MostOutput - c.buf.Len(); room < len(p) {
if room > 0 {
c.buf.Write(p[:room])
}
c.cut = true
return len(p), nil
}
return c.buf.Write(p)
}
func (c *capped) String() string { return c.buf.String() }
// Desk is what a desktop tool needs: how to find the session, and how to run a command.
type Desk struct {
Find func() (*Session, error)
Run Runner
// Base is the environment a command starts from, before the session's words.
Base []string
}
// Machine is the real Desk, preferring the named processes as the session's.
func Machine(prefer ...string) Desk {
return Desk{
Find: func() (*Session, error) { return Find(prefer...) },
Run: Exec,
Base: os.Environ(),
}
}
// InSession runs a command in the operator's session, or answers NoSession.
func (d Desk) InSession(ctx context.Context, name string, args ...string) (Result, *Session, error) {
s, err := d.Find()
if err != nil {
return Result{}, nil, err
}
return d.Run(ctx, s.Env(d.Base), nil, name, args...), s, nil
}
// InSessionWith is InSession with standard input.
func (d Desk) InSessionWith(ctx context.Context, stdin []byte, name string, args ...string) (Result, *Session, error) {
s, err := d.Find()
if err != nil {
return Result{}, nil, err
}
return d.Run(ctx, s.Env(d.Base), stdin, name, args...), s, nil
}
// Plain runs a command with the base environment: for what needs no session.
func (d Desk) Plain(ctx context.Context, name string, args ...string) Result {
return d.Run(ctx, d.Base, nil, name, args...)
}
// AsUser runs a command with the account's own runtime directory and bus, and no display.
func (d Desk) AsUser(ctx context.Context, name string, args ...string) Result {
return d.Run(ctx, UserEnv(d.Base, os.Getuid()), nil, name, args...)
}
// Launched is how a program was started in the session.
type Launched struct {
Unit string `json:"unit,omitempty"`
PID int `json:"pid,omitempty"`
How string `json:"how"`
}
// Launch starts a program in the operator's session that outlives the call and the runtime.
//
// **Not as a child of this process.** The runtime is a system service; everything it starts is in
// its control group, and the service manager ends that group whenever the runtime restarts — which
// is every push that changes it. So the program is handed to the account's own service manager as a
// transient unit (`systemd-run --user`), with the session's words set on it, and lives as long as the
// operator's user manager does. Without a user manager it is started detached as a last resort, and
// the answer says it will end with the runtime.
func (d Desk) Launch(ctx context.Context, s *Session, name string, argv ...string) (Launched, error) {
if len(argv) == 0 {
return Launched{}, errors.New("nothing to launch")
}
env := s.Env(d.Base)
unit := "mesh-" + name + "-" + token()
args := []string{"--user", "--collect", "--quiet", "--unit=" + unit}
for _, w := range []string{"DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "XDG_SESSION_TYPE", "XDG_CURRENT_DESKTOP", "XDG_SESSION_DESKTOP", "I3SOCK", "SWAYSOCK"} {
if v := lookup(env, w); v != "" {
args = append(args, "--setenv="+w+"="+v)
}
}
args = append(args, "--")
args = append(args, argv...)
res := d.Run(ctx, env, nil, "systemd-run", args...)
if res.OK() {
return Launched{Unit: unit, How: "a transient unit of the account's service manager; ends when it exits or when the operator logs out"}, nil
}
if s.Bus != "" {
return Launched{}, res.Err()
}
cmd := exec.Command(argv[0], argv[1:]...)
cmd.Env = env
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
if err := cmd.Start(); err != nil {
return Launched{}, err
}
pid := cmd.Process.Pid
go func() { _ = cmd.Wait() }()
return Launched{PID: pid, How: "detached from the runtime with no user manager to hand it to; it ends when the runtime restarts"}, nil
}
func lookup(env []string, name string) string {
for i := len(env) - 1; i >= 0; i-- {
if k, v, ok := strings.Cut(env[i], "="); ok && k == name {
return v
}
}
return ""
}
func token() string {
b := make([]byte, 4)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
-445
View File
@@ -1,445 +0,0 @@
// Package desktop is how a desktop module's tools act in the operator's graphical session
// (novox/hq ADR 0208, research 026/05).
//
// **One question, answered once for every desktop tool.** A tool runs inside the node's runtime: a
// process of node-tools.service, started by the system's service manager as the operator account,
// with no session around it — no DISPLAY, no XAUTHORITY, no session bus. The session it must act in
// was started elsewhere, by the login manager, and the only place its values are written down is
// the environment of the processes it started. So this package finds the session the way a person
// would: it looks at the operator account's own processes, takes the one that is plainly the
// session's (the window manager, or the oldest process carrying a display), confirms with logind
// that its session is a live local one, and checks that the display's socket is really there.
//
// **Only the session's own words are read.** A session's processes also carry whatever its start
// script exported — on the workstations that was a file of secrets — so the environment is filtered
// to a fixed list of names while it is read, and nothing else ever leaves /proc.
//
// The D-Bus address handed on is the user manager's socket, `unix:path=$XDG_RUNTIME_DIR/bus`,
// whenever it exists, because that is where the portal, the notifier and every user service
// listen. A session started on a private bus (a stale session, measured on one workstation) is
// reported as `session_bus` beside it, so the difference is visible rather than guessed at.
//
// The same copy of this package is vendored into every desktop module (xorg, lemurs, i3, xterm,
// adwaita); the catalogue builds each module alone, so it cannot be imported across them. Change
// every copy together — the modules' tests compare them.
package desktop
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"os/user"
"path/filepath"
"sort"
"strconv"
"strings"
"syscall"
"time"
)
// SessionWords are the only environment words read from a session's process: the ones that say
// where the session is. Everything else in that environment is the operator's, and is never read.
var SessionWords = []string{
"DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY",
"XDG_SESSION_ID", "XDG_SESSION_TYPE", "XDG_SESSION_DESKTOP", "XDG_CURRENT_DESKTOP",
"XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "XDG_SEAT", "XDG_VTNR",
"I3SOCK", "SWAYSOCK",
}
// Session is the operator's running graphical session, as a tool needs it.
type Session struct {
UID int `json:"uid"`
ID string `json:"session_id,omitempty"`
Type string `json:"type"`
Display string `json:"display,omitempty"`
WaylandDisplay string `json:"wayland_display,omitempty"`
XAuthority string `json:"xauthority,omitempty"`
RuntimeDir string `json:"runtime_dir"`
Bus string `json:"bus,omitempty"`
SessionBus string `json:"session_bus,omitempty"`
Desktop string `json:"desktop,omitempty"`
// FoundIn is the process whose environment named the session.
FoundIn Process `json:"found_in"`
// Active is logind's word on the session, when logind answered.
Active *bool `json:"active,omitempty"`
words map[string]string
}
// Process is one process the search looked at.
type Process struct {
PID int `json:"pid"`
Command string `json:"command"`
start uint64
}
// NoSession is the answer when there is no graphical session to act in. Its text is JSON, so a tool
// that returns it as its error still answers structured data.
type NoSession struct {
Reason string `json:"reason"`
Looked []string `json:"looked"`
}
func (e *NoSession) Error() string {
b, _ := json.Marshal(map[string]any{"error": "no-graphical-session", "reason": e.Reason, "looked": e.Looked})
return string(b)
}
// IsNoSession is whether err says there is no session.
func IsNoSession(err error) bool {
var n *NoSession
return errors.As(err, &n)
}
// Finder holds where the search looks, so a test can point it at a tree of its own.
type Finder struct {
Proc string // the process table: /proc
X11Sockets string // where X servers listen: /tmp/.X11-unix
RuntimeBase string // the parent of every XDG_RUNTIME_DIR: /run/user
UID int // whose session
// Prefer names the processes that are the session's own, best first: the session's holder.
Prefer []string
// Logind answers `loginctl show-session` for one id; nil skips the check.
Logind func(id string) (map[string]string, error)
}
// DefaultFinder is the machine's: the account this process runs as, or — when it runs as root — the
// operator account the runtime names (MESH_OPERATOR_ACCOUNT).
func DefaultFinder(prefer ...string) Finder {
uid := os.Getuid()
if uid == 0 {
if name := os.Getenv("MESH_OPERATOR_ACCOUNT"); name != "" {
if u, err := user.Lookup(name); err == nil {
if n, err := strconv.Atoi(u.Uid); err == nil {
uid = n
}
}
}
}
return Finder{
Proc: "/proc", X11Sockets: "/tmp/.X11-unix", RuntimeBase: "/run/user",
UID: uid, Prefer: prefer, Logind: loginctl,
}
}
// Find is the operator's session on this machine, preferring a process named in prefer.
func Find(prefer ...string) (*Session, error) {
return DefaultFinder(prefer...).Find()
}
type candidate struct {
proc Process
words map[string]string
rank int
logind map[string]string
}
// Find looks for the session.
func (f Finder) Find() (*Session, error) {
entries, err := os.ReadDir(f.Proc)
if err != nil {
return nil, &NoSession{Reason: "the process table cannot be read: " + err.Error(), Looked: []string{f.Proc}}
}
looked := []string{fmt.Sprintf("the processes of uid %d in %s", f.UID, f.Proc)}
var found []candidate
stale := 0
for _, e := range entries {
pid, err := strconv.Atoi(e.Name())
if err != nil {
continue
}
dir := filepath.Join(f.Proc, e.Name())
info, err := os.Stat(dir)
if err != nil {
continue
}
if st, ok := info.Sys().(*syscall.Stat_t); !ok || int(st.Uid) != f.UID {
continue
}
words := readWords(filepath.Join(dir, "environ"))
if words["DISPLAY"] == "" && words["WAYLAND_DISPLAY"] == "" {
continue
}
if !f.reachable(words) {
stale++
continue
}
found = append(found, candidate{proc: Process{PID: pid, Command: comm(dir), start: startTime(dir)}, words: words})
}
if len(found) == 0 {
reason := fmt.Sprintf("no process of uid %d carries a display", f.UID)
if stale > 0 {
reason = fmt.Sprintf("%d process(es) of uid %d name a display whose socket is gone: the session they belonged to has ended", stale, f.UID)
}
return nil, &NoSession{Reason: reason, Looked: append(looked, f.X11Sockets, f.RuntimeBase)}
}
// logind's word on each session the candidates name, asked once per session.
asked := map[string]map[string]string{}
for i := range found {
id := found[i].words["XDG_SESSION_ID"]
if f.Logind == nil || id == "" {
found[i].rank = 1
continue
}
props, done := asked[id]
if !done {
props, _ = f.Logind(id)
asked[id] = props
}
found[i].logind = props
switch {
case props == nil:
found[i].rank = 1
case props["Remote"] == "yes":
found[i].rank = 3
case props["Active"] == "yes" && props["State"] != "closing":
found[i].rank = 0
case props["State"] == "closing":
found[i].rank = 3
default:
found[i].rank = 2
}
}
if f.Logind != nil {
looked = append(looked, "logind's sessions")
}
preferred := func(c candidate) int {
for i, p := range f.Prefer {
if c.proc.Command == p {
return i
}
}
return len(f.Prefer)
}
sort.SliceStable(found, func(i, j int) bool {
a, b := found[i], found[j]
if a.rank != b.rank {
return a.rank < b.rank
}
if pa, pb := preferred(a), preferred(b); pa != pb {
return pa < pb
}
if a.proc.start != b.proc.start {
return a.proc.start < b.proc.start
}
return a.proc.PID < b.proc.PID
})
best := found[0]
if best.rank == 3 {
return nil, &NoSession{Reason: "the only sessions found are remote or closing", Looked: looked}
}
return f.session(best), nil
}
func (f Finder) session(c candidate) *Session {
w := c.words
s := &Session{
UID: f.UID, ID: w["XDG_SESSION_ID"], Display: w["DISPLAY"], WaylandDisplay: w["WAYLAND_DISPLAY"],
XAuthority: w["XAUTHORITY"], RuntimeDir: w["XDG_RUNTIME_DIR"], FoundIn: c.proc, words: w,
}
s.Desktop = w["XDG_CURRENT_DESKTOP"]
if s.Desktop == "" {
s.Desktop = w["XDG_SESSION_DESKTOP"]
}
switch {
case w["XDG_SESSION_TYPE"] != "":
s.Type = w["XDG_SESSION_TYPE"]
case s.WaylandDisplay != "":
s.Type = "wayland"
default:
s.Type = "x11"
}
if s.RuntimeDir == "" {
s.RuntimeDir = filepath.Join(f.RuntimeBase, strconv.Itoa(f.UID))
}
if isSocket(filepath.Join(s.RuntimeDir, "bus")) {
s.Bus = "unix:path=" + filepath.Join(s.RuntimeDir, "bus")
}
if own := w["DBUS_SESSION_BUS_ADDRESS"]; own != "" && own != s.Bus {
s.SessionBus = own
}
if c.logind != nil {
active := c.logind["Active"] == "yes"
s.Active = &active
}
return s
}
// reachable is whether the display a process names is still served: the X server's socket, or the
// Wayland compositor's. A process outliving its session still carries the session's words.
func (f Finder) reachable(w map[string]string) bool {
if d := w["WAYLAND_DISPLAY"]; d != "" {
path := d
if !filepath.IsAbs(d) {
dir := w["XDG_RUNTIME_DIR"]
if dir == "" {
dir = filepath.Join(f.RuntimeBase, strconv.Itoa(f.UID))
}
path = filepath.Join(dir, d)
}
if isSocket(path) {
return true
}
}
n, ok := DisplayNumber(w["DISPLAY"])
return ok && isSocket(filepath.Join(f.X11Sockets, "X"+strconv.Itoa(n)))
}
// DisplayNumber is the server number of a local X display (":1", ":1.0", "unix:1"); a display on
// another host — an ssh session's forwarded one — is not the local session and answers false.
func DisplayNumber(display string) (int, bool) {
host, rest, ok := strings.Cut(display, ":")
if !ok || (host != "" && host != "unix") {
return 0, false
}
num, _, _ := strings.Cut(rest, ".")
n, err := strconv.Atoi(num)
if err != nil || n < 0 {
return 0, false
}
return n, true
}
// Word is one of the session's words as its process had it ("" when it had none).
func (s *Session) Word(name string) string { return s.words[name] }
// Env is base with the session's words in place of whatever base said for them.
func (s *Session) Env(base []string) []string {
drop := map[string]bool{}
for _, w := range SessionWords {
drop[w] = true
}
out := make([]string, 0, len(base)+8)
for _, kv := range base {
k, _, _ := strings.Cut(kv, "=")
if !drop[k] {
out = append(out, kv)
}
}
bus := s.Bus
if bus == "" {
bus = s.SessionBus
}
for _, kv := range [][2]string{
{"DISPLAY", s.Display}, {"WAYLAND_DISPLAY", s.WaylandDisplay}, {"XAUTHORITY", s.XAuthority},
{"XDG_RUNTIME_DIR", s.RuntimeDir}, {"DBUS_SESSION_BUS_ADDRESS", bus},
{"XDG_SESSION_TYPE", s.Type}, {"XDG_SESSION_ID", s.ID},
{"XDG_CURRENT_DESKTOP", s.words["XDG_CURRENT_DESKTOP"]},
{"XDG_SESSION_DESKTOP", s.words["XDG_SESSION_DESKTOP"]},
{"I3SOCK", s.words["I3SOCK"]}, {"SWAYSOCK", s.words["SWAYSOCK"]},
} {
if kv[1] != "" {
out = append(out, kv[0]+"="+kv[1])
}
}
return out
}
// UserEnv is base with the account's own runtime directory and bus, for a tool that talks to the
// user manager or the session bus and needs no display — it works with no session at all.
func UserEnv(base []string, uid int) []string {
dir := filepath.Join("/run/user", strconv.Itoa(uid))
out := make([]string, 0, len(base)+2)
for _, kv := range base {
k, _, _ := strings.Cut(kv, "=")
if k != "XDG_RUNTIME_DIR" && k != "DBUS_SESSION_BUS_ADDRESS" {
out = append(out, kv)
}
}
return append(out, "XDG_RUNTIME_DIR="+dir, "DBUS_SESSION_BUS_ADDRESS=unix:path="+filepath.Join(dir, "bus"))
}
// readWords reads a process's environment and keeps only SessionWords.
func readWords(path string) map[string]string {
raw, err := os.ReadFile(path)
if err != nil {
return nil
}
keep := map[string]bool{}
for _, w := range SessionWords {
keep[w] = true
}
out := map[string]string{}
for _, kv := range bytes.Split(raw, []byte{0}) {
k, v, ok := bytes.Cut(kv, []byte{'='})
if ok && keep[string(k)] {
out[string(k)] = string(v)
}
}
return out
}
func comm(dir string) string {
b, err := os.ReadFile(filepath.Join(dir, "comm"))
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
// startTime is field 22 of /proc/<pid>/stat: when the process started, in clock ticks since boot.
// Read after the command's closing parenthesis, because the command may hold spaces.
func startTime(dir string) uint64 {
b, err := os.ReadFile(filepath.Join(dir, "stat"))
if err != nil {
return ^uint64(0)
}
i := bytes.LastIndexByte(b, ')')
if i < 0 {
return ^uint64(0)
}
fields := strings.Fields(string(b[i+1:]))
// fields[0] is the state, field 3 of the line; start time is field 22.
if len(fields) < 20 {
return ^uint64(0)
}
n, err := strconv.ParseUint(fields[19], 10, 64)
if err != nil {
return ^uint64(0)
}
return n
}
func isSocket(path string) bool {
info, err := os.Stat(path)
return err == nil && info.Mode()&os.ModeSocket != 0
}
// loginctl asks logind about one session, by its property lines.
func loginctl(id string) (map[string]string, error) {
cmd := exec.Command("loginctl", "show-session", id, "-p", "Active", "-p", "State", "-p", "Remote", "-p", "Type", "-p", "Class")
var out bytes.Buffer
cmd.Stdout = &out
done := make(chan error, 1)
if err := cmd.Start(); err != nil {
return nil, err
}
go func() { done <- cmd.Wait() }()
select {
case err := <-done:
if err != nil {
return nil, err
}
case <-time.After(3 * time.Second):
_ = cmd.Process.Kill()
return nil, errors.New("loginctl did not answer in 3s")
}
return ParseProperties(out.String()), nil
}
// ParseProperties reads `Key=Value` lines, as loginctl and systemctl show print them.
func ParseProperties(text string) map[string]string {
out := map[string]string{}
sc := bufio.NewScanner(strings.NewReader(text))
for sc.Scan() {
if k, v, ok := strings.Cut(sc.Text(), "="); ok {
out[k] = v
}
}
return out
}
@@ -1,255 +0,0 @@
package desktop
import (
"context"
"encoding/json"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
)
// A machine in a directory: a process table, the X servers' socket directory and a runtime base.
type fakeMachine struct {
t *testing.T
proc, x11, runtime string
uid int
}
func newMachine(t *testing.T) *fakeMachine {
root, err := os.MkdirTemp("", "desk")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(root) })
m := &fakeMachine{t: t, proc: filepath.Join(root, "p"), x11: filepath.Join(root, "x"), runtime: filepath.Join(root, "r"), uid: os.Getuid()}
for _, d := range []string{m.proc, m.x11, filepath.Join(m.runtime, strconv.Itoa(m.uid))} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
}
return m
}
func (m *fakeMachine) socket(path string) {
l, err := net.Listen("unix", path)
if err != nil {
m.t.Fatal(err)
}
m.t.Cleanup(func() { l.Close() })
}
func (m *fakeMachine) process(pid int, comm string, start int, env ...string) {
dir := filepath.Join(m.proc, strconv.Itoa(pid))
if err := os.MkdirAll(dir, 0o755); err != nil {
m.t.Fatal(err)
}
os.WriteFile(filepath.Join(dir, "environ"), []byte(strings.Join(env, "\x00")+"\x00"), 0o600)
os.WriteFile(filepath.Join(dir, "comm"), []byte(comm+"\n"), 0o644)
// pid (comm) state ppid pgrp session tty tpgid flags minflt cminflt majflt cmajflt utime stime
// cutime cstime priority nice threads itrealvalue starttime ...
stat := strconv.Itoa(pid) + " (" + comm + ") S 1 1 1 0 -1 0 0 0 0 0 0 0 0 0 20 0 1 0 " + strconv.Itoa(start) + " 0 0"
os.WriteFile(filepath.Join(dir, "stat"), []byte(stat), 0o644)
}
func (m *fakeMachine) finder(logind func(string) (map[string]string, error), prefer ...string) Finder {
return Finder{Proc: m.proc, X11Sockets: m.x11, RuntimeBase: m.runtime, UID: m.uid, Prefer: prefer, Logind: logind}
}
func active(id string) (map[string]string, error) {
return map[string]string{"Active": "yes", "State": "active", "Remote": "no", "Type": "x11"}, nil
}
func TestTheSessionIsFoundInTheWindowManagersEnvironmentAndOnlyItsWordsAreRead(t *testing.T) {
m := newMachine(t)
m.socket(filepath.Join(m.x11, "X1"))
run := filepath.Join(m.runtime, strconv.Itoa(m.uid))
m.socket(filepath.Join(run, "bus"))
m.process(100, "lemurs-child", 5, "DISPLAY=:1", "XDG_SESSION_ID=1")
m.process(200, "i3", 10, "DISPLAY=:1", "XAUTHORITY=/home/op/.Xauthority", "XDG_SESSION_ID=1",
"XDG_SESSION_TYPE=x11", "XDG_CURRENT_DESKTOP=i3", "XDG_RUNTIME_DIR="+run,
"DBUS_SESSION_BUS_ADDRESS=unix:path=/tmp/dbus-private", "NPM_TOKEN=secret", "OPENAI_API_KEY=secret")
m.process(300, "zsh", 50, "TERM=xterm") // no display: not a candidate
s, err := m.finder(active, "i3").Find()
if err != nil {
t.Fatal(err)
}
if s.FoundIn.PID != 200 || s.Display != ":1" || s.XAuthority != "/home/op/.Xauthority" || s.ID != "1" || s.Type != "x11" || s.Desktop != "i3" {
t.Fatalf("session: %+v", s)
}
if s.Bus != "unix:path="+filepath.Join(run, "bus") || s.SessionBus != "unix:path=/tmp/dbus-private" {
t.Fatalf("the user manager's bus first, the session's private one reported beside it: %q %q", s.Bus, s.SessionBus)
}
if s.Active == nil || !*s.Active {
t.Fatal("logind's word is carried")
}
env := strings.Join(s.Env([]string{"PATH=/usr/bin", "DISPLAY=:9", "HOME=/home/op"}), "\n")
for _, want := range []string{"PATH=/usr/bin", "HOME=/home/op", "DISPLAY=:1", "XAUTHORITY=/home/op/.Xauthority", "DBUS_SESSION_BUS_ADDRESS=unix:path=" + filepath.Join(run, "bus"), "XDG_RUNTIME_DIR=" + run} {
if !strings.Contains(env, want) {
t.Errorf("env lacks %s:\n%s", want, env)
}
}
if strings.Contains(env, ":9") || strings.Contains(env, "secret") || strings.Contains(env, "NPM_TOKEN") {
t.Fatalf("the base's display is replaced and no other word of the session's process passes:\n%s", env)
}
b, _ := json.Marshal(s)
if strings.Contains(string(b), "secret") {
t.Fatal("the answer carries a word outside the session's")
}
}
func TestWithoutAPreferenceTheOldestProcessOfTheLiveSessionWins(t *testing.T) {
m := newMachine(t)
m.socket(filepath.Join(m.x11, "X0"))
m.process(410, "xterm", 90, "DISPLAY=:0", "XDG_SESSION_ID=3")
m.process(400, "openbox", 20, "DISPLAY=:0", "XDG_SESSION_ID=3")
s, err := m.finder(nil).Find()
if err != nil || s.FoundIn.PID != 400 {
t.Fatalf("%+v %v", s, err)
}
if s.RuntimeDir != filepath.Join(m.runtime, strconv.Itoa(m.uid)) || s.Bus != "" {
t.Fatalf("an absent runtime directory word falls back to the account's, and no bus socket means no bus: %+v", s)
}
}
func TestALeftoverProcessOfAnEndedSessionIsNotTheSession(t *testing.T) {
m := newMachine(t)
m.process(500, "i3", 10, "DISPLAY=:2", "XDG_SESSION_ID=7") // no X2 socket
_, err := m.finder(active, "i3").Find()
if !IsNoSession(err) || !strings.Contains(err.Error(), "socket is gone") {
t.Fatalf("%v", err)
}
var answer map[string]any
if json.Unmarshal([]byte(err.Error()), &answer) != nil || answer["error"] != "no-graphical-session" {
t.Fatalf("the refusal is structured: %s", err)
}
}
func TestNoProcessWithADisplayIsAClearNoSession(t *testing.T) {
m := newMachine(t)
m.process(600, "sshd", 1, "SSH_CONNECTION=x")
_, err := m.finder(active).Find()
if !IsNoSession(err) || !strings.Contains(err.Error(), "no process of uid") {
t.Fatalf("%v", err)
}
}
func TestAnActiveLocalSessionBeatsAnInactiveOneAndARemoteOneIsRefused(t *testing.T) {
m := newMachine(t)
m.socket(filepath.Join(m.x11, "X0"))
m.socket(filepath.Join(m.x11, "X1"))
m.process(700, "i3", 5, "DISPLAY=:0", "XDG_SESSION_ID=a")
m.process(800, "i3", 9, "DISPLAY=:1", "XDG_SESSION_ID=b")
logind := func(id string) (map[string]string, error) {
if id == "a" {
return map[string]string{"Active": "no", "State": "online", "Remote": "no"}, nil
}
return map[string]string{"Active": "yes", "State": "active", "Remote": "no"}, nil
}
s, err := m.finder(logind, "i3").Find()
if err != nil || s.FoundIn.PID != 800 || s.Display != ":1" {
t.Fatalf("the active session: %+v %v", s, err)
}
remote := func(string) (map[string]string, error) {
return map[string]string{"Active": "yes", "Remote": "yes"}, nil
}
if _, err := m.finder(remote).Find(); !IsNoSession(err) {
t.Fatalf("a remote session is not the operator's desktop: %v", err)
}
}
func TestAWaylandSessionIsFoundByItsCompositorsSocket(t *testing.T) {
m := newMachine(t)
run := filepath.Join(m.runtime, strconv.Itoa(m.uid))
m.socket(filepath.Join(run, "wayland-1"))
m.process(900, "sway", 3, "WAYLAND_DISPLAY=wayland-1", "XDG_RUNTIME_DIR="+run, "SWAYSOCK=/run/x.sock")
s, err := m.finder(nil, "sway").Find()
if err != nil || s.Type != "wayland" || s.WaylandDisplay != "wayland-1" {
t.Fatalf("%+v %v", s, err)
}
if !strings.Contains(strings.Join(s.Env(nil), " "), "SWAYSOCK=/run/x.sock") {
t.Fatal("the compositor's socket word passes")
}
}
func TestADisplayOnAnotherHostIsNotTheLocalSession(t *testing.T) {
for d, want := range map[string]bool{":0": true, ":1.0": true, "unix:2": true, "localhost:10.0": false, "host:0": false, "": false, ":x": false} {
if _, ok := DisplayNumber(d); ok != want {
t.Errorf("%q: %v", d, ok)
}
}
}
func TestACommandIsBoundedAndItsFailureNamed(t *testing.T) {
r := Exec(context.Background(), os.Environ(), []byte("hello"), "cat")
if !r.OK() || r.Stdout != "hello" {
t.Fatalf("%+v", r)
}
r = Exec(context.Background(), os.Environ(), nil, "sh", "-c", "echo no >&2; exit 3")
if r.OK() || r.Code != 3 || !strings.Contains(r.Err().Error(), "exited 3: no") {
t.Fatalf("%+v", r)
}
r = Exec(context.Background(), os.Environ(), nil, "no-such-program-here")
if r.OK() || r.Code != 127 {
t.Fatalf("%+v", r)
}
r = Exec(context.Background(), os.Environ(), nil, "sh", "-c", "head -c 400000 /dev/zero")
if !r.Truncated || len(r.Stdout) != MostOutput {
t.Fatalf("cut at %d: %d %v", MostOutput, len(r.Stdout), r.Truncated)
}
}
func TestArgumentsAreReadStrictly(t *testing.T) {
a := Args{"name": " x ", "n": float64(3), "f": 1.5, "b": true, "l": []any{"a", "b"}}
if v, err := a.Text("name"); err != nil || v != "x" {
t.Fatal(v, err)
}
if _, err := a.Text("missing"); err == nil {
t.Fatal("a missing required text")
}
if n, err := a.Whole("n", 0, 1, 5); err != nil || n != 3 {
t.Fatal(n, err)
}
if _, err := a.Whole("f", 0, 0, 5); err == nil {
t.Fatal("1.5 is not whole")
}
if _, err := a.Whole("n", 0, 4, 5); err == nil {
t.Fatal("out of range")
}
if b, given, err := a.Bool("b"); !b || !given || err != nil {
t.Fatal("bool")
}
if _, _, err := a.Bool("name"); err == nil {
t.Fatal("text is not a bool")
}
if l, err := a.Strings("l"); err != nil || len(l) != 2 {
t.Fatal(l, err)
}
if _, err := a.OneOf("name", "", "y", "z"); err == nil {
t.Fatal("not one of")
}
}
func TestAPathIsKeptInsideTheHome(t *testing.T) {
t.Setenv("MESH_OPERATOR_HOME", "/home/op")
for in, want := range map[string]string{"~/a.png": "/home/op/a.png", "b/c": "/home/op/b/c", "/home/op/d": "/home/op/d", "~": "/home/op"} {
if got, err := InHome(in); err != nil || got != want {
t.Errorf("%s: %s %v", in, got, err)
}
}
for _, out := range []string{"/etc/passwd", "~/../other", "../x"} {
if _, err := InHome(out); err == nil {
t.Errorf("%s was accepted", out)
}
}
}
func TestPropertiesAreParsed(t *testing.T) {
p := ParseProperties("Active=yes\nState=active\nDisplay=\n")
if p["Active"] != "yes" || p["State"] != "active" || p["Display"] != "" {
t.Fatal(p)
}
}
-118
View File
@@ -1,118 +0,0 @@
{
"module": "adwaita",
"version": "1",
"capabilities": [
"package-manager"
],
"tools": [
"adwaita_appearance",
"adwaita_cursor",
"adwaita_icons",
"adwaita_portal_check"
],
"environment": {
"variables": {
"GTK_THEME": "Adwaita:dark",
"GTK2_RC_FILES": "/usr/share/themes/Adwaita-dark/gtk-2.0/gtkrc",
"QT_QPA_PLATFORMTHEME": "qt6ct",
"QT_STYLE_OVERRIDE": "Fusion",
"QT_SELECT": "6",
"XCURSOR_THEME": "Adwaita",
"XCURSOR_SIZE": "24"
}
},
"shell": [
{
"for": "xresources",
"slot": "normal",
"code": "! adwaita: the cursor, for X programs that take it from the resources.\nXcursor.theme: Adwaita\nXcursor.size: 24\n"
},
{
"for": "xinitrc",
"slot": "normal",
"code": "# The appearance (module adwaita): GSettings is where the portal reads dark or light, and the portal is\n# the only way it reaches Electron, Chromium, Firefox and flatpaks. Set at every session start to the\n# module's default; adwaita_appearance switches it for a session.\ngsettings set org.gnome.desktop.interface color-scheme 'prefer-dark' || true\ngsettings set org.gnome.desktop.interface gtk-theme 'Adwaita' || true\ngsettings set org.gnome.desktop.interface icon-theme 'Adwaita' || true\ngsettings set org.gnome.desktop.interface cursor-theme 'Adwaita' || true\ngsettings set org.gnome.desktop.interface cursor-size 24 || true\ngsettings set org.gnome.desktop.interface font-name 'Inter 11' || true\ngsettings set org.gnome.desktop.interface monospace-font-name 'JetBrainsMono Nerd Font 11' || true\n"
}
],
"resources": [
{
"id": "package-gnome-themes-extra",
"type": "package",
"package": "gnome-themes-extra"
},
{
"id": "package-adwaita-icon-theme",
"type": "package",
"package": "adwaita-icon-theme"
},
{
"id": "package-adwaita-cursors",
"type": "package",
"package": "adwaita-cursors"
},
{
"id": "package-qt6ct",
"type": "package",
"package": "qt6ct"
},
{
"id": "package-xdg-desktop-portal-gtk",
"type": "package",
"package": "xdg-desktop-portal-gtk"
},
{
"id": "gtk3",
"type": "file",
"path": "${machine:account-home}/.config/gtk-3.0/settings.ini",
"owner": "${machine:account}",
"mode": "0644",
"content": "# Written by the mesh (module adwaita, novox/hq ADR 0208), for GTK 3 and GTK 4 alike. Replaced at\n# every push; adwaita_appearance switches dark and light for the running session.\n[Settings]\ngtk-theme-name=Adwaita\ngtk-icon-theme-name=Adwaita\ngtk-cursor-theme-name=Adwaita\ngtk-cursor-theme-size=24\ngtk-font-name=Inter 11\ngtk-application-prefer-dark-theme=1\n"
},
{
"id": "gtk4",
"type": "file",
"path": "${machine:account-home}/.config/gtk-4.0/settings.ini",
"owner": "${machine:account}",
"mode": "0644",
"content": "# Written by the mesh (module adwaita, novox/hq ADR 0208), for GTK 3 and GTK 4 alike. Replaced at\n# every push; adwaita_appearance switches dark and light for the running session.\n[Settings]\ngtk-theme-name=Adwaita\ngtk-icon-theme-name=Adwaita\ngtk-cursor-theme-name=Adwaita\ngtk-cursor-theme-size=24\ngtk-font-name=Inter 11\ngtk-application-prefer-dark-theme=1\n"
},
{
"id": "qt6ct",
"type": "file",
"path": "${machine:account-home}/.config/qt6ct/qt6ct.conf",
"owner": "${machine:account}",
"mode": "0644",
"content": "[Appearance]\ncolor_scheme_path=/usr/share/qt6ct/colors/darker.conf\ncustom_palette=true\nicon_theme=Adwaita\nstandard_dialogs=default\nstyle=Fusion\n\n[Fonts]\nfixed=\"JetBrainsMono Nerd Font,11,-1,5,50,0,0,0,0,0\"\ngeneral=\"Inter,11,-1,5,50,0,0,0,0,0\"\n\n[Interface]\nactivate_item_on_single_click=1\nbuttonbox_layout=0\ncursor_flash_time=1000\ndialog_buttons_have_icons=1\ndouble_click_interval=400\ngui_effects=@Invalid()\nkeyboard_scheme=2\nmenus_have_icons=true\nshow_shortcuts_in_context_menus=true\nstylesheets=@Invalid()\ntoolbutton_style=4\nunderline_shortcut=1\nwheel_scroll_lines=3\n\n[Troubleshooting]\nforce_raster_widgets=1\nignored_applications=@Invalid()\n"
},
{
"id": "portals",
"type": "file",
"path": "${machine:account-home}/.config/xdg-desktop-portal/portals.conf",
"owner": "${machine:account}",
"mode": "0644",
"content": "# Written by the mesh (module adwaita, novox/hq ADR 0208). Replaced at every push.\n#\n# Which portal backend answers each interface. i3 is not a desktop xdg-desktop-portal knows, so with\n# no preference it uses whichever backend happens to be installed: fine while gtk is the only one,\n# wrong the day another arrives as somebody else's dependency. Named instead. gtk also serves\n# org.freedesktop.appearance (dark or light) from GSettings, which the session's start sets.\n[preferred]\ndefault=gtk\n# Secrets for sandboxed programs come from the keyring's backend. Without this line no backend answers\n# the interface: gtk does not implement it, and gnome-keyring's names only GNOME as its desktop.\norg.freedesktop.impl.portal.Secret=gnome-keyring\n"
},
{
"id": "cursor",
"type": "file",
"path": "${machine:account-home}/.icons/default/index.theme",
"owner": "${machine:account}",
"mode": "0644",
"content": "# Written by the mesh (module adwaita, novox/hq ADR 0208): the default cursor theme, for programs that\n# read neither XCURSOR_THEME nor the X resources.\n[Icon Theme]\nName=Default\nInherits=Adwaita\n"
}
],
"build": {
"artifacts": [
{
"name": "tools",
"kind": "bundle",
"language": "go",
"system": "arch",
"from": "cmd/adwaita-tools",
"binary": "adwaita-tools",
"loads": [
"adwaita-tools"
]
}
]
}
}
+22
View File
@@ -0,0 +1,22 @@
# anthropic-consumer's runtime: the tool runtime, carrying this module's compiled code.
#
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
# the base images, published like any other artifact — which is what makes this buildable by the
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
# happens to have the siblings.
#
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
ARG BUILD_BASE
ARG RUNTIME_BASE
FROM ${BUILD_BASE} AS build
WORKDIR /app/modules/anthropic-consumer
COPY . .
RUN node /app/node_modules/typescript/bin/tsc apply/index.ts usage/index.ts \
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
FROM ${RUNTIME_BASE}
COPY --from=build /app/modules/anthropic-consumer/dist /app/modules/anthropic-consumer/dist
# No serve-time entrypoints: every container of this module names its command (`run` on a
# schedule), so nothing here serves — deliberately no MESH_TOOL_MODULES.
+67 -30
View File
@@ -9,20 +9,29 @@
"model-access" "model-access"
], ],
"binds": { "binds": {
"model-access": "${dir:state}/model.json" "model-access": "/var/lib/anthropic-consumer/model.json"
}, },
"secrets": { "secrets": {
"model-access": "${dir:state}/access-token" "model-access": "/var/lib/anthropic-consumer/access-token"
},
"own-secrets": {
"broker": "/var/lib/mesh/anthropic-consumer/broker"
}, },
"emits": [ "emits": [
"usage.session" "usage.session"
], ],
"resources": [ "resources": [
{
"id": "mesh-state",
"type": "directory",
"path": "/var/lib/mesh/anthropic-consumer",
"mode": "0700"
},
{ {
"id": "state", "id": "state",
"type": "directory", "type": "directory",
"mode": "0700", "path": "/var/lib/anthropic-consumer",
"place": "." "mode": "0700"
}, },
{ {
"id": "claude-home", "id": "claude-home",
@@ -33,43 +42,71 @@
{ {
"id": "out", "id": "out",
"type": "directory", "type": "directory",
"path": "/var/lib/anthropic-consumer/out",
"mode": "0700" "mode": "0700"
}, },
{ {
"id": "apply", "id": "apply",
"type": "process", "type": "container",
"name": "anthropic-consumer-apply", "name": "mesh-anthropic-consumer-apply",
"artifact": "code", "network": "host",
"run": [
"node",
"apply/index.js"
],
"schedule": "*/5 * * * *", "schedule": "*/5 * * * *",
"args": [
"run",
"/app/modules/anthropic-consumer/dist/apply/index.js"
],
"volumes": [
"/var/lib/anthropic-consumer:/run/state"
],
"env": { "env": {
"MESH_MODEL_ACCESS_SECRET_FILE": "${dir:state}/access-token", "MESH_MODEL_ACCESS_SECRET_FILE": "/run/state/access-token",
"MESH_MODEL_ACCESS_BIND_FILE": "${dir:state}/model.json", "MESH_MODEL_ACCESS_BIND_FILE": "/run/state/model.json",
"MESH_CLAUDE_CREDENTIALS_FILE": "${dir:state}/claude/.credentials.json", "MESH_CLAUDE_CREDENTIALS_FILE": "/run/state/claude/.credentials.json",
"MESH_CLAUDE_IDENTITY_FILE": "${dir:state}/claude/.claude.json" "MESH_CLAUDE_IDENTITY_FILE": "/run/state/claude/.claude.json"
} },
"artifact": "runtime"
},
{
"id": "usage",
"type": "container",
"name": "mesh-anthropic-consumer-usage",
"network": "host",
"schedule": "*/5 * * * *",
"args": [
"run",
"/app/modules/anthropic-consumer/dist/usage/index.js"
],
"volumes": [
"/var/lib/mesh/anthropic-consumer/broker:/run/secrets/broker:ro",
"/var/lib/anthropic-consumer:/run/state"
],
"env": {
"MESH_BROKER_FILE": "/run/secrets/broker",
"MESH_CLAUDE_PROJECTS_DIR": "/run/state/claude/projects",
"MESH_ANTHROPIC_USAGE_OUT": "/run/state/out/session-usage.json",
"MESH_TOOLS_MAIN": "/app/dist/main.js"
},
"artifact": "runtime"
} }
], ],
"build": { "build": {
"on": [
{
"arg": "BUILD_BASE",
"module": "mesh-tools",
"artifact": "build"
},
{
"arg": "RUNTIME_BASE",
"module": "mesh-tools",
"artifact": "runtime"
}
],
"artifacts": [ "artifacts": [
{ {
"name": "code", "name": "runtime",
"kind": "bundle", "kind": "image",
"language": "typescript", "from": "Dockerfile"
"entrypoints": [
"apply/index.js",
"usage/index.js"
],
"loads": [
"usage/index.js"
],
"env": {
"MESH_CLAUDE_PROJECTS_DIR": "${dir:state}/claude/projects",
"MESH_ANTHROPIC_USAGE_OUT": "${dir:state}/out/session-usage.json"
}
} }
] ]
} }
+18 -19
View File
@@ -3,15 +3,12 @@
// per session. The consumer IS the (node,module) session's fixed binding, so no per-message account // per session. The consumer IS the (node,module) session's fixed binding, so no per-message account
// attribution is done — just the totals (port map "don't-map" #3). // attribution is done — just the totals (port map "don't-map" #3).
// //
// Runs in the node's runtime (novox/hq ADR 0198), every five minutes, so events are emitted through // Runs as `mesh-tools run` (no broker), so events are emitted best-effort via the sibling mesh-tools
// the runtime as this module; the totals are also written to a file so the reading is observable // `emit` primitive; the totals are also written to a file so the reading is observable without one.
// without one.
import { readdirSync, statSync, readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs"; import { readdirSync, statSync, readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
import { join, dirname } from "node:path"; import { join, dirname } from "node:path";
import { emit } from "@novox/mesh-sdk/events";
import { readSessionFile, type SessionUsage } from "../transcript.js"; import { readSessionFile, type SessionUsage } from "../transcript.js";
/** The vendor-neutral usage row ADR 0054 fixes — the shape the model-usage store upserts. Kept local /** The vendor-neutral usage row ADR 0054 fixes — the shape the model-usage store upserts. Kept local
@@ -119,20 +116,22 @@ function atomicWrite(path: string, content: string): void {
renameSync(tmp, path); renameSync(tmp, path);
} }
/** Emit best-effort through the runtime: a reading that could not be announced is still in the file. */ /** Emit best-effort via the sibling mesh-tools `emit`, which wires a broker a run step has none. */
async function emitUsage(body: Record<string, unknown>): Promise<void> { async function emitUsage(body: Record<string, unknown>): Promise<void> {
try { const main = process.env.MESH_TOOLS_MAIN ?? "/app/dist/main.js";
await emit("usage.session", body); const { spawn } = await import("node:child_process");
} catch (err) { await new Promise<void>((resolve) => {
console.error(`[anthropic-consumer] could not emit usage: ${err}`); const child = spawn(
} process.execPath,
[main, "emit", "usage.session", JSON.stringify(body)],
{ stdio: "inherit" },
);
child.on("exit", () => resolve());
child.on("error", (err) => {
console.error(`[anthropic-consumer] could not emit usage: ${err}`);
resolve();
});
});
} }
// The cadence the scheduled container had: once at start, then every five minutes. Not awaited, so the await main();
// runtime's handshake is answered while a long first reading is still under way.
const EVERY_MS = 5 * 60 * 1000;
const tick = (): void => {
void main().catch((err) => console.error(`[anthropic-consumer] usage reading failed: ${err}`));
};
tick();
setInterval(tick, EVERY_MS);
+8 -8
View File
@@ -9,13 +9,13 @@
"model-access" "model-access"
], ],
"binds": { "binds": {
"model-access": "${dir:mesh-state}/model.json" "model-access": "/var/lib/mesh/anthropic-manager/model.json"
}, },
"secrets": { "secrets": {
"model-access": "${dir:mesh-state}/refresh-token" "model-access": "/var/lib/mesh/anthropic-manager/refresh-token"
}, },
"own-secrets": { "own-secrets": {
"broker": "${dir:mesh-state}/broker" "broker": "/var/lib/mesh/anthropic-manager/broker"
}, },
"emits": [ "emits": [
"usage.read" "usage.read"
@@ -24,13 +24,13 @@
{ {
"id": "mesh-state", "id": "mesh-state",
"type": "directory", "type": "directory",
"mode": "0700", "path": "/var/lib/mesh/anthropic-manager",
"place": "mesh" "mode": "0700"
}, },
{ {
"id": "out", "id": "out",
"type": "directory", "type": "directory",
"path": "${dir:mesh-state}/out", "path": "/var/lib/mesh/anthropic-manager/out",
"mode": "0700" "mode": "0700"
}, },
{ {
@@ -45,8 +45,8 @@
"/app/modules/anthropic-manager/dist/refresh/index.js" "/app/modules/anthropic-manager/dist/refresh/index.js"
], ],
"volumes": [ "volumes": [
"${dir:mesh-state}/broker:/run/secrets/broker:ro", "/var/lib/mesh/anthropic-manager/broker:/run/secrets/broker:ro",
"${dir:mesh-state}:/run/state" "/var/lib/mesh/anthropic-manager:/run/state"
], ],
"env": { "env": {
"MESH_BROKER_FILE": "/run/secrets/broker", "MESH_BROKER_FILE": "/run/secrets/broker",
-362
View File
@@ -1,362 +0,0 @@
# asus-zephyrus-g14
The hardware module for the **ASUS ROG Zephyrus G14** laptop: its vendor daemon and platform
profiles, the hybrid GPU's mode and driver options, suspend, the lid and power key, low battery,
the backlights, the vendor keys and the touchpad (novox/hq research 027/03 *Power management on
the laptop*, research 026/05, to-be 42 phase 3).
## Why this name
A module is named after the hardware model, never the node (novox/hq ADR 0112; research 026/03:
no flavors, no machine names). `asus-zephyrus-g14` is the model family exactly as the firmware
reports it (`/sys/class/dmi/id/product_family` = `ROG Zephyrus G14`). The module's code checks that
value and its switcher does nothing on any other model, and `zephyrus_check` reports it.
A wider name such as `asus-rog-laptop` would promise what this module cannot keep. Its contents
belong to this family: the vendor-key scan codes, the eDP panel beside an NVIDIA dGPU, and the NVIDIA
D3 workaround. A second G14 is assigned the same module. Another ROG model gets its own.
Written against the GA403 (2024, Ryzen 8945HS, RTX 4070 Laptop, hybrid). Older G14 years have the same
daemons and probably the same keys. Their GPU options are unverified.
## What it owns
| | what | how |
|---|---|---|
| package | `asusctl` (asusd + client) | the distribution's package (`extra`). The machine was found with a local build of 6.4.0. The host only asserts *present*, so the switch to 6.5.0 from `extra` happens at the next `pacman -Syu` (or `pacman -S asusctl`). `zephyrus_check` flags a local build |
| package | `upower`, `playerctl` | what the low-battery drop-in and the media keys use. `xinput` is the `xorg` module's (one package, one module on a node) |
| service | `asusd` running (static unit: no boot state to declare), `supergfxd` running and enabled | |
| archive | `/usr/local/lib/asus-zephyrus-g14/bin/` | the module's scripts, from `files/bin` (below) |
| file ×2 | `~/.config/i3/config.d/10-asus.conf`, `20-g14.conf` | the laptop's lines in i3: the keys the firmware sends as ordinary presses (Fn+F6, Fn+F9), the keyboard-backlight notifier, the panel as primary, the touchpad key. The paths are adopted, because a second file binding the same keys makes i3's configuration check fail, and the `i3` module's watcher then reloads nothing |
| file ×4 | `asus-zephyrus-g14-touchpad-resume.service`, and a drop-in `asus-zephyrus-g14-touchpad.conf` on each sleep service | the touchpad's settings once more after a resume (below) |
| file | `/etc/modprobe.d/g14-nvidia-power.conf` | `NVreg_DynamicPowerManagement=0x00` (runtime D3 off: the ACPI D-Notifier hang) and `NVreg_PreserveVideoMemoryAllocations=1`. The path is adopted (ADR 0182) |
| file | `/etc/modprobe.d/video-brightness-switch.conf` | `video.brightness_switch_enabled=0`, so the ACPI video driver does not also move a backlight on the keys. The file was on the machine and owned by nothing |
| file ×3 | `systemd-{suspend,hibernate,suspend-then-hibernate}.service.d/asus-zephyrus-g14-nvidia.conf` | `Wants=` the matching `nvidia-*` sleep units and `nvidia-resume` (see *suspend units* below) |
| file | `nvidia-powerd.service.d/asus-zephyrus-g14.conf` | `ConditionKernelCommandLine=zephyrus.nvidia-powerd`: Dynamic Boost runs only when the operator opts in at boot |
| file | `/etc/systemd/logind.conf.d/power.conf` | the power key and the lid suspend, on battery, on mains and docked. `systemd-logind` is reloaded, never restarted |
| file | `/etc/udev/rules.d/90-backlight.rules` | backlights writable by the `video` group. `systemd-udevd` is reloaded |
| file | `triggerhappy.service.d/asus-zephyrus-g14.conf` | `thd … --user ${machine:account}`: the triggers run as the operator's account (below) |
| file | `/etc/triggerhappy/triggers.d/asus-g14.conf` | the vendor keys: media (`KEY_PROG1/3/4`), panel brightness, touchpad (`KEY_F21`). The path is adopted, because two trigger files would fire every key twice |
| file | `/etc/UPower/UPower.conf.d/50-asus-zephyrus-g14.conf` | low battery at 15/10/7 %; at 7 % **suspend**, not power off. A drop-in over the package's own file |
| file | `/etc/X11/xorg.conf.d/30-asus-zephyrus-g14-touchpad.conf` | tap to click, natural scrolling, acceleration 0.15, as an X input class |
**What it does not own, on purpose:**
- `/etc/asusd/*.ron` belong to asusd, which rewrites them whenever a setting changes. RON is not a
format the host writes into (ADR 0102 speaks JSON and marked blocks). Owning the file whole would
repeat the predecessor's freeze: the measured file already differs from the one the predecessor
shipped. The settings the module needs are set through asusd, by its code (below).
- `/etc/supergfxd.conf` and `/etc/modprobe.d/supergfxd.conf` belong to supergfxd, which writes both.
- The swap file, its unit and the swap partition are the machine's swap layout (research 027,
question 3). They are not this module's, nor `memory-pressure`'s.
- **Places.** The screen layouts for named places (`$mod+Alt+1…7`, `~/.screenlayout/`,
`~/scripts/.screenlayouts/@*.sh`) name where the operator works, which no module may (ADR 0112).
They are the operator's own lines until autorandr profiles replace them (the `xorg` module).
- **The monitor-hotplug wizard** (`/etc/udev/rules.d/91-monitor-hotplug.rules`,
`~/scripts/.screenlayouts/monitor-wizard.sh`) is any laptop's, not this model's. The predecessor said
so itself (its `laptop` flavor). It is the display server's to replace with autorandr's own hotplug
handling. Until then it stays as found, and it still calls the predecessor's `as-user`.
- **The screenshot script** (`~/.config/i3/scripts/screenshot.sh`) is any machine's. The `i3` module
binds it too. This module only binds the key the firmware sends for it.
- **The bar's battery block.** It belongs here (a block that follows this model's hardware), but the
bar has no way in yet (`i3status-rust` README). Once ADR 0210's contributions reach the bar seat,
this module contributes it.
**Requires `x11-display`.** The i3 lines and the session scripts need a display, so the module is
assigned where the display server is.
## Software outside the distribution (ADR 0205, research 027 question 1)
`supergfxctl` (5.2.7, from the asus-linux repository, which is no longer configured) and
`triggerhappy` (AUR) are **kept as found, and depended on**. The module declares no package for
either, because the host installs from the official repositories only. It declares their services
(`supergfxd` running, `triggerhappy` running), so on a machine without them the host refuses the
service by name: *does not exist on this machine*. The refusal is loud, never a silent pass.
`zephyrus_check` names both as foreign.
This module does not choose between the options of research 027 question 1. Under the starting
position (P2: the build machine builds AUR packages into a repository the mesh serves), both become
`package` resources here, and a fresh G14 installs them. **Until P2 exists, a fresh G14 is blocked
on installing these two by hand.** ADR 0205's vendored archive (P1) does not fit: supergfxctl is a
daemon with a system-bus policy and udev rules, and triggerhappy is C.
A later option for the keys: the module's own Go code could read the vendor keys from evdev, which
the operator's account may do through the `input` group. That would retire triggerhappy entirely.
It is not done here, because it would put the keys behind the node's runtime, and the runtime
restarts a bundle that dies only on its next call (below).
## The long-running code: the profile switcher (ADR 0198)
The module's Go bundle serves the tools and runs the platform-profile switcher in the same process.
The node's runtime launches the bundle at the runtime's start. It replaces the predecessor's
`auto-profile`, a user unit that woke every five seconds, on battery too.
- **Policy** (constants until settings exist, issue 168): battery → `Quiet`; mains → `Balanced`;
mains with the CPU at or above 50 % for 3 samples of 10 s → `Performance`, back to `Balanced` after
3 samples at or below 20 %. Between the lines nothing moves (hysteresis). iowait counts as idle.
- **Woken by events, not a poll.** The kernel's power-supply uevents (netlink, group 1) wake the
switcher. Any account may listen on that group, and it needs no daemon, bus client or dependency;
upower re-announces the same changes but would need a D-Bus client in the bundle. The CPU is
sampled only on mains, every 10 s, because only there does the answer depend on it. On battery,
a safety re-read every 5 minutes covers an event lost across a suspend. If the uevent socket
cannot be opened, the switcher polls every 10 s and says so in `zephyrus_profile_policy`.
- **The battery decides the source.** A battery that is *discharging* means battery, whatever any
adapter says. The predecessor took any `online` file reading 1 as mains, and on this model the USB-C
ports report `online`. Batteries of `scope=Device` (a mouse, a headset) are ignored.
- **It acts on a change of its decision, never to restore one.** A profile someone chose by hand (the
profile key, asusctl, `zephyrus_profile`) stays until the power source changes or the load crosses
a line. The predecessor re-asserted its choice every five seconds, which made the profile key
useless. **Starting is not a decision**: the runtime restarts the bundle on every push that changes
one, and a push must not reset the operator's profile.
- **A hold.** `zephyrus_profile` holds the profile it sets for 60 min (`hold_minutes`). A change of
power source ends the hold.
- **One assertion at start:** through asusctl, the charge limit (80 %) and asusd's own on-mains and
on-battery profiles (`Balanced`, `Quiet`), each read first and set only if it differs. asusd's own
switching on a change of power source then agrees with the switcher's. A limit set later with
`zephyrus_charge_limit` stands until the bundle next starts. For a one-off full charge, use its
`oneshot`.
- **Events:** `profile.switched` (`profile`, `from`, `reason`, `source`), published through the
runtime.
No root is involved. asusd's and supergfxd's bus policies admit the `users` and `wheel` groups, and the
runtime runs as the operator's account. The one write that may escalate is the panel's backlight,
when the udev rule has not run yet. It uses `sudo -n` and never prompts. Every command is bounded at
20 s.
**Known limit.** The runtime restarts a launched bundle that exits *on its next tool call*, not at
once (mesh-tools `launch.ts`), so a crashed switcher stays down until a tool is called. ADR 0198 §1
says *started again when it exits*. The switcher recovers from a panic and reports it in
`zephyrus_profile_policy` and `zephyrus_check`, but a crash of the process is the runtime's to restart.
## The vendor keys and the scripts
triggerhappy opens the input devices as root, then **drops to the operator's account with its groups**
(`initgroups`: `input`, `video`). The packaged unit already drops to `nobody`, and the module's drop-in
names the account instead. The predecessor replaced the packaged unit with one that ran every trigger
as root, then `su`-ed to a named person with a hard-coded uid and display, and sourced a file of
secrets on the way (research 027 question 2). Now:
- `zephyrus-session CMD…`: runs a command in the account's graphical session. It sets the account's
own bus (`/run/user/<uid>/bus`) and takes the display and its authority from the session's window
manager's own environment, as the desktop modules' session finder does. If i3 is not running, it
asks logind, and then any process of the account that has a display. Nothing is sourced.
triggerhappy's `--user` changes the user and its groups and nothing else: the triggers start with
the service's bare environment, which is why every key that needs the session goes through this.
- `zephyrus-media play-pause | next | previous`: the media keys through MPRIS, with a notification of
what happened and a lock against the key's own repeat.
- `zephyrus-display primary | order`: the internal panel as the primary output, and the display key's
workspace split (odd workspaces on the panel, even ones on the first external output). The panel is
found as the connected `eDP` output. The predecessor named `eDP-1` and used `jq`. This reads i3's
answer without it.
- `zephyrus-kbd-notify`: the keyboard backlight's level, shown when UPower says it changed. One
instance per session, because i3 runs its `exec` lines again on an in-place restart.
- `zephyrus-backlight + | - | N`: the panel in 5 % steps, never below 1 %. **The panel is the
backlight under the eDP connector**, because this model also registers `nvidia_0`, which moves
nothing. The predecessor named `amdgpu_bl1` literally.
- `zephyrus-notify ID TEXT`: one replacing notification, through `busctl` (the service manager's
client, so no libnotify).
- `zephyrus-touchpad reset | toggle`: bound to the touchpad key (`KEY_F21`).
**Media keys** go to MPRIS through `playerctl`. The predecessor's fallback to a media server's local
API needed a token from the secrets file, and is dropped until a module can be handed a secret
(research 027 question 2). A player that does not speak MPRIS is told as "Media: no player".
## The touchpad: an input class instead of a sleep hook
The predecessor re-ran `xinput` from `/etc/systemd/system-sleep/` after every resume, as a named person
on a guessed display, because settings made with `xinput` are lost when the device initialises again.
An X input class is applied by X **every time the device appears**: at login, on hotplug and after a
resume. So the cause is fixed. The class matches any touchpad on the machine, which is the model's, so it
holds across G14 years whose touchpads differ. It takes effect at the next X start.
`zephyrus-touchpad reset` stays as the manual form, on the touchpad key and `$mod+Shift+x`.
**And a backstop after resume.** A resume that does not initialise the device again does not make X
apply the class either, and the predecessor's i3 file says the touchpad "sometimes needs re-init after
sleep". So `asus-zephyrus-g14-touchpad-resume.service` runs `zephyrus-touchpad reset` as the account,
two seconds after the machine is awake. It is never enabled. Each sleep service `Wants=` it through a
drop-in, and it is ordered `After=` them, which is how `nvidia-resume` is started too.
`zephyrus_check` says whether the sleep wants it.
## Suspend units without enabling them
`nvidia-suspend`, `-hibernate`, `-suspend-then-hibernate` and `-resume` are enabled with links in the
sleep services' `.wants` directories. The mesh makes no links (ADR 0012). The host's service shape
cannot declare them either: it may only say *running* or *stopped*, and *running* on a one-shot that
last failed would start `nvidia-sleep.sh suspend` with the machine awake. So the module asks for them
from the other side: a drop-in on each sleep service that `Wants=` them. The units' own
`Before=`/`After=` order them. The found links stay and are harmless.
`suspend-then-hibernate` now also gets `nvidia-suspend-then-hibernate`, which the machine lacked.
The drop-ins take effect at the service manager's next `daemon-reload`. In the same apply, the restart
of `triggerhappy` (whose drop-in changes) performs one.
## Tools
| tool | r/a | what |
|---|---|---|
| `zephyrus_brightness` | r/a | panel (percent or ±step, floor 1 %) and keyboard (off/low/med/high, 0-3, ±) through asusd |
| `zephyrus_battery` | r | charge, energy in Wh, health (full ÷ design), cycles (the firmware reports 0, and this is said), limit, watts, hours left |
| `zephyrus_charge_limit` | r/a | 20-100 through asusd; `oneshot` |
| `zephyrus_gpu_mode` | r/a | mode, supported modes, dGPU power, the pending mode and action; says that asusd switches the mode on every change of power source |
| `zephyrus_profile` | r/a | active, on-mains and on-battery profile, kernel platform profile; set with a hold |
| `zephyrus_thermals` | r | every hwmon temperature and fan, the hottest, the dGPU's temperature **only when it is awake** (nvidia-smi wakes a suspended GPU) |
| `zephyrus_power_draw` | r | battery flow, APU package power (PPT), dGPU draw when awake, power source and why |
| `zephyrus_profile_policy` | r | what the switcher would choose now and why: source, recent load against the thresholds, decision, hold, last switch, what woke it, what it asserted at start, and whether the predecessor's switcher still runs |
| `zephyrus_fan_curves` | r | asusd's curves per profile and fan |
| `zephyrus_keys` | r | every custom key: each triggerhappy trigger, the module's i3 lines and the keys the firmware handles; what runs and the file it is in. Warns when one key is in two trigger files, which fires it twice |
| `zephyrus_check` | r | every expectation: model, packages (local or foreign), daemons, nvidia-powerd, sleep units, the NVIDIA options **in force** (`/proc/driver/nvidia/params`), charge limit, one authority each over the profile and the GPU mode, predecessor leftovers; the touchpad resume unit wanted by the sleep; triggerhappy running as the operator's account; any trigger, udev rule or sleep hook still naming `as-user`. It also lists what it did not check |
`profile` is a candidate verb for a future `node-power-profile` seat (research 027/03). That seat has
no record yet, so this is the module's own tool.
## Found on the laptop, 2026-10-04 (read-only)
- **Two authorities over the GPU mode.** `asusd.ron` has `ac_command: "supergfxctl -m Hybrid"` and
`bat_command: "supergfxctl -m Integrated"`, so asusd switches the GPU mode on every change of power
source. **supergfxd 5.2.7 cannot read logind's sessions** (`manager is an invalid variant`, every
boot), so a switch that needs a logout times out. `zephyrus_check` reports both. The fix is the
operator's, in asusd's file: clear both commands, or update supergfxctl once it can be packaged.
- **`brightness.conf` did nothing.** `HandleBrightnessKey` is not a logind key, and logind logs
*Unknown key … ignoring* at every start. The module does not carry it. The brightness keys were
always triggerhappy's, with the ACPI video switch off.
- **Two profile switchers** would run at once until `auto-profile` is stopped (below).
- **asusctl is a local build** (6.4.0, *Unknown Packager*) beside a foreign `asusctl-debug`.
## When assigned to the laptop: what changes
1. `/usr/local/lib/asus-zephyrus-g14/` appears (seven scripts).
2. Written over found files (each original kept once by the host): `g14-nvidia-power.conf` and
`video-brightness-switch.conf` (same options, so no change until the next boot either),
`logind.conf.d/power.conf` (same keys; logind reloaded), `90-backlight.rules` (same effect;
udevd reloaded), `triggers.d/asus-g14.conf` (now the module's scripts), and i3's `10-asus.conf` and
`20-g14.conf` (the module's lines; the `i3` module's watcher checks and reloads them).
3. New: the three sleep drop-ins (behaviour gained: `nvidia-suspend-then-hibernate`), the
nvidia-powerd drop-in (no effect while it is masked), the triggerhappy drop-in, the UPower drop-in
(same values as today), the touchpad input class (at the next X start), and the resume unit with
its three drop-ins.
4. `daemon-reload` and a `triggerhappy` restart. thd now runs as the account and the keys run the
module's scripts. `upower` restarts.
5. Packages, asusd and supergfxd: already as declared, so nothing changes. asusctl stays the local
6.4.0 until the next upgrade.
6. The node runtime restarts with the new bundle. The switcher asserts the limit (80, already) and
asusd's profiles (Balanced and Quiet, already), so it sets nothing. It takes the current decision
as applied and acts from the first event on.
## Predecessor files this module makes redundant — the operator removes them once (ADR 0182)
**On the laptop:**
1. `systemctl --user disable --now auto-profile.service`, then delete
`~/.config/systemd/user/auto-profile.service` and `~/scripts/auto-profile`. **Do this right after
the push**, or two switchers run at once.
2. **Before the push, keep the place layouts.** The module writes `20-g14.conf` over the found file,
and the found file carries the seven `$mod+Alt+1…7` layout bindings, which name places. Move them,
and the `exec … ~/.screenlayout/@default.sh` line, to a file of your own in the same directory,
e.g. `~/.config/i3/config.d/90-layouts.conf`. i3 reads it the same way, and it stays yours until
autorandr profiles replace it. The host keeps the found `20-g14.conf` once in any case.
3. `~/scripts/asus-bright`, `~/scripts/asusctl-kbd-bright`, `~/scripts/xrandr-bright`,
`~/scripts/media-control`, `~/scripts/xinput-reset-touchpad`,
`~/scripts/.screenlayouts/orden-workspaces.sh` and `~/.config/i3/scripts/kbd-brightness-notify.sh`:
no trigger and no line of the module's uses them any more.
**Keep `~/scripts/as-user`** while `/etc/udev/rules.d/91-monitor-hotplug.rules` exists: that rule
still runs the monitor wizard through it. `zephyrus_check` names every place that still calls it.
4. `/etc/systemd/system/triggerhappy.service`: the predecessor's replacement of the packaged unit. The
module's drop-in works over either, so delete it and `systemctl daemon-reload` to return to the
packaged unit (`Type=notify`, socket).
5. `/etc/systemd/logind.conf.d/brightness.conf`: the unknown key, which does nothing.
6. `/etc/systemd/system-sleep/xinput-reset-touchpad.sh`, if it is still there: replaced by the input
class and the resume unit. (It was already gone on 2026-10-04.)
7. `/etc/UPower/UPower.conf`: the predecessor's replacement of the package's file. Its values are now
the module's drop-in. Restore the package's copy (`rm` it, then `pacman -S upower`).
8. Optional: `systemctl disable nvidia-suspend nvidia-resume nvidia-hibernate` (the drop-ins carry them
now), `/etc/asusd/*.ron-old` and `fan_curves.ron.bak`, the foreign `asusctl-debug` package, and
`pacman -S asusctl` for the distribution's build.
**Stays the machine's:** `/swapfile` and `/etc/systemd/system/swapfile.swap` (the swap layout),
`/etc/udev/rules.d/91-monitor-hotplug.rules` (the display's, phase 2), and the place layouts.
**On the desktop** (the predecessor's G14 flavor reached it; part was removed on 2026-10-04): none of
this module applies there. Still present and to be deleted:
`/etc/systemd/logind.conf.d/brightness.conf`, `/etc/systemd/system-sleep/xinput-reset-touchpad.sh`,
`~/scripts/xinput-reset-touchpad`, `~/scripts/xrandr-bright` and
`~/.config/i3/scripts/kbd-brightness-notify.sh`.
## The predecessor, file by file
The predecessor carried this model in its desktop module's `g14` and `laptop` flavors, and in a
`g14-power` module. Every model-specific file of the desktop module, and where it is now:
| predecessor file | now |
|---|---|
| `i3-asus.conf` → `config.d/10-asus.conf` | **this module**, the same path; the scripts it calls are the module's |
| `i3-g14.conf` → `config.d/20-g14.conf` | **this module**, the same path. The place layouts in it are the operator's own file (migration, step 2) |
| `g14-triggerhappy-asus-g14.conf` | **this module**, the same path; the triggers run the module's scripts |
| `g14-triggerhappy.service` (a replacement of the packaged unit) | **retired**: a drop-in over the packaged unit (`--user`) |
| `as-user` | **retired**: thd runs as the account, and `zephyrus-session` finds the session. Kept on the machine while the monitor wizard's udev rule calls it |
| `asus-bright` | **this module**: `zephyrus-backlight`, the panel found by its connector |
| `media-control` (bound by the `g14` triggers) | **this module**: `zephyrus-media`, without the fallback that needed a secret |
| `xinput-reset-touchpad` | **this module**: the input class, `zephyrus-touchpad`, and the resume unit |
| `g14-system-sleep-xinput-reset-touchpad.sh` | **this module**: the input class, and the resume unit that the sleep services want |
| `kbd-brightness-notify.sh` | **this module**: `zephyrus-kbd-notify`, one instance per session |
| `asusctl-kbd-bright` | **retired**: the keyboard keys are the firmware's, and `zephyrus_brightness` sets it by hand |
| `xrandr-bright` | **retired**: a software dimming; the panel's backlight is `zephyrus-backlight` |
| `screenlayout-orden-workspaces.sh` | **this module**: `zephyrus-display order`, on Fn+F9 |
| `screenlayout-*.sh` (six named places) | **the operator's**, until autorandr profiles (the `xorg` module) replace them |
| `g14-90-backlight.rules` | **this module**, the same path |
| `g14-logind-brightness.conf` | **retired**: an unknown logind key that did nothing |
| `laptop-monitor-wizard.sh`, `laptop-91-monitor-hotplug.rules` | **any laptop's, not this module's**: kept as found, for the `xorg` module's autorandr to replace |
| `bottom-bar.g14.toml` (the battery block) | **waits**: this module's, once the bar takes contributions (ADR 0210) |
| `razer-basilisk-battery-percentage` | **not this model's**: a mouse. No module carries it (`i3status-rust` README) |
| `screenshot.sh` | **not this model's**: any machine's script, which the `i3` module binds too; this module binds Fn+F6 to it |
| package `triggerhappy` | **depended on, kept as found** (outside the distribution, above) |
`g14-power`'s pieces (the NVIDIA options, logind, UPower, the sleep units, `auto-profile`) are in
*What it owns* and the switcher above. Its memory guard is the `memory-pressure` module's.
## What the predecessor paid for, and what this module does about it
- **One file for every machine overwrote what each machine needed** (the predecessor's split of its i3
configuration into a base, an ASUS and a G14 layer, 2026-03). Here the model's lines are this
module's files, and nothing else writes them.
- **The layers silently stopped applying.** The predecessor's chain *laptop → g14* was stated in two
places, and the one its installer read lacked it. For weeks the G14 received only its 21
G14-tagged files, and the 49 base and laptop files were never seeded. Validation and the pipeline
both reported success (2026-08, found at a cutover). Here a module is one manifest. Its tests assert
that every trigger runs a script it ships, and `zephyrus_check` and `zephyrus_keys` read back what is
on the machine.
- **A hook wrote asusd's own files with sudo,** because configuration sync might not run on install
(2026-04), and froze them. asusd rewrites those files whenever a setting changes. Here the module
sets asusd through its client and never writes the RON files.
- **A profile daemon fought the profile key.** The predecessor turned asusd's own switching off and
re-asserted its choice every five seconds (2026-03). Here the switcher acts on a change of its
decision, never to restore one.
- **The overnight freeze** was an ACPI power-source event hanging the NVIDIA GPU in runtime D3
(2026-06). It is fixed by the driver options, which `zephyrus_check` reads from the running driver
rather than from the file.
- **A unit restarted about 73,000 times, unnoticed** (2026-06). Here every expectation is in
`zephyrus_check`, and so is a list of what it did not check.
- **The vendor keys ran as root and `su`-ed to a named person** on a guessed display, sourcing a file
of secrets. Here thd drops to the account, and nothing is sourced.
- **The touchpad lost its settings after a resume,** because `xinput` settings vanish when the device
initialises again. Here an input class re-applies them, with the resume unit as a backstop.
## Tests
`go test ./...` in this directory. Every tool runs against a tree standing in for `/sys`, `/proc` and
`/etc`, and an injected runner answering with what asusctl 6.4 and supergfxctl 5.2 said on the laptop.
The tests cover:
- the power-source rule;
- battery arithmetic from `charge_*`;
- the eDP panel choice;
- brightness bounds;
- the policy's sustain, relax and hysteresis, with iowait counted as idle;
- the switcher: no act at start, one switch per change of source, a published event, boost from
samples, holds, retry after failure, start-up assertions only where they differ, inert on another
model;
- the uevent filter;
- the manifest: tools listed equal tools served, no machine named, triggers exist, every key runs a
shipped executable script, every script passes `bash -n`;
- `zephyrus_keys` over the module's own triggers and i3 lines, and a key in two trigger files;
- the checks for `as-user`, triggerhappy's account and the resume unit.
@@ -1,264 +0,0 @@
package main
import (
"context"
"fmt"
"regexp"
"strconv"
"strings"
)
// The vendor daemons are reached through their own command-line clients, which speak to them on the
// system bus. Their bus policy admits the `users` and `wheel` groups, so none of this needs root.
// Profiles are the platform profiles asusd offers on this model, in its spelling.
var Profiles = []string{"Quiet", "Balanced", "Performance"}
// canonicalProfile accepts any case and answers asusd's spelling, or an error naming the choices.
func canonicalProfile(s string) (string, error) {
for _, p := range Profiles {
if strings.EqualFold(strings.TrimSpace(s), p) {
return p, nil
}
}
return "", fmt.Errorf("profile %q is not one of %s", s, strings.Join(Profiles, ", "))
}
// ProfileState is what asusd says about the platform profile.
type ProfileState struct {
Active string `json:"active"`
OnAC string `json:"on_ac,omitempty"`
Battery string `json:"on_battery,omitempty"`
Platform string `json:"platform_profile,omitempty"`
Choices string `json:"platform_profile_choices,omitempty"`
}
var (
activeProfile = regexp.MustCompile(`(?m)^Active profile:\s*(\S+)`)
acProfile = regexp.MustCompile(`(?m)^AC profile\s+(\S+)`)
batteryProfile = regexp.MustCompile(`(?m)^Battery profile\s+(\S+)`)
)
// ParseProfileGet reads `asusctl profile get`.
func ParseProfileGet(out string) (ProfileState, error) {
var p ProfileState
if m := activeProfile.FindStringSubmatch(out); m != nil {
p.Active = m[1]
} else {
return p, fmt.Errorf("asusctl profile get said no active profile: %q", strings.TrimSpace(out))
}
if m := acProfile.FindStringSubmatch(out); m != nil {
p.OnAC = m[1]
}
if m := batteryProfile.FindStringSubmatch(out); m != nil {
p.Battery = m[1]
}
return p, nil
}
// Profile reads the platform profile from asusd and the kernel.
func (m *Machine) Profile(ctx context.Context) (ProfileState, error) {
out, err := m.Run(ctx, "asusctl", "profile", "get")
if err != nil {
return ProfileState{}, vendor("asusctl", err)
}
p, err := ParseProfileGet(out)
if err != nil {
return p, err
}
p.Platform = m.read("/sys/firmware/acpi/platform_profile")
p.Choices = m.read("/sys/firmware/acpi/platform_profile_choices")
return p, nil
}
// SetProfile has asusd switch the active profile.
func (m *Machine) SetProfile(ctx context.Context, profile string) error {
_, err := m.Run(ctx, "asusctl", "profile", "set", profile)
return vendor("asusctl", err)
}
var chargeLimit = regexp.MustCompile(`charge limit:\s*(\d+)\s*%`)
// ChargeLimit is the battery's charge limit as asusd reports it.
func (m *Machine) ChargeLimit(ctx context.Context) (int, error) {
out, err := m.Run(ctx, "asusctl", "battery", "info")
if err != nil {
return 0, vendor("asusctl", err)
}
g := chargeLimit.FindStringSubmatch(out)
if g == nil {
return 0, fmt.Errorf("asusctl battery info said no limit: %q", strings.TrimSpace(out))
}
n, _ := strconv.Atoi(g[1])
return n, nil
}
// Keyboard backlight levels in asusd's spelling, index = the kernel's brightness value.
var KeyboardLevels = []string{"off", "low", "med", "high"}
var ledLevel = regexp.MustCompile(`(?i)brightness:\s*(off|low|med|high)`)
// ParseLeds reads `asusctl leds get`.
func ParseLeds(out string) (string, error) {
g := ledLevel.FindStringSubmatch(out)
if g == nil {
return "", fmt.Errorf("asusctl leds get said no level: %q", strings.TrimSpace(out))
}
return strings.ToLower(g[1]), nil
}
// FanCurve is one fan's curve in one profile: eight points of temperature (°C) and duty (0-255).
type FanCurve struct {
Fan string `json:"fan"`
Enabled bool `json:"enabled"`
Temp []int `json:"temp_c"`
PWM []int `json:"pwm"`
}
var (
fanBlock = regexp.MustCompile(`(?s)fan:\s*(\w+),\s*pwm:\s*\(([^)]*)\),\s*temp:\s*\(([^)]*)\),\s*enabled:\s*(true|false)`)
)
// ParseFanCurves reads `asusctl fan-curve --mod-profile <p>`.
func ParseFanCurves(out string) []FanCurve {
var curves []FanCurve
for _, g := range fanBlock.FindAllStringSubmatch(out, -1) {
curves = append(curves, FanCurve{Fan: g[1], PWM: ints(g[2]), Temp: ints(g[3]), Enabled: g[4] == "true"})
}
return curves
}
func ints(list string) []int {
var out []int
for _, f := range strings.Split(list, ",") {
if n, err := strconv.Atoi(strings.TrimSpace(f)); err == nil {
out = append(out, n)
}
}
return out
}
// GPUState is what supergfxd says about the hybrid GPU.
type GPUState struct {
Mode string `json:"mode"`
Supported []string `json:"supported"`
Power string `json:"dgpu_power,omitempty"`
PendingAction string `json:"pending_action,omitempty"`
PendingMode string `json:"pending_mode,omitempty"`
Vendor string `json:"dgpu_vendor,omitempty"`
}
// ParseSupported reads `supergfxctl -s`: `[Integrated, Hybrid, AsusMuxDgpu]`.
func ParseSupported(out string) []string {
out = strings.Trim(strings.TrimSpace(out), "[]")
var modes []string
for _, f := range strings.Split(out, ",") {
if f = strings.TrimSpace(f); f != "" {
modes = append(modes, f)
}
}
return modes
}
// GPU reads supergfxd.
func (m *Machine) GPU(ctx context.Context) (GPUState, error) {
var g GPUState
mode, err := m.Run(ctx, "supergfxctl", "-g")
if err != nil {
return g, vendor("supergfxctl", err)
}
g.Mode = strings.TrimSpace(mode)
if s, err := m.Run(ctx, "supergfxctl", "-s"); err == nil {
g.Supported = ParseSupported(s)
}
if s, err := m.Run(ctx, "supergfxctl", "-S"); err == nil {
g.Power = strings.TrimSpace(s)
}
if s, err := m.Run(ctx, "supergfxctl", "-p"); err == nil {
g.PendingAction = strings.TrimSpace(s)
}
if s, err := m.Run(ctx, "supergfxctl", "-P"); err == nil {
g.PendingMode = strings.TrimSpace(s)
}
if s, err := m.Run(ctx, "supergfxctl", "-V"); err == nil {
g.Vendor = strings.TrimSpace(s)
}
return g, nil
}
// vendor names a vendor client that is not installed, rather than passing on "executable file not
// found". asusctl is in the distribution's repositories; supergfxctl is not, and the module keeps it as
// it was found until the mesh can build packages from the user repository (research 027, question 1).
func vendor(name string, err error) error {
if err == nil {
return nil
}
if notInstalled(err) {
switch name {
case "supergfxctl":
return fmt.Errorf("supergfxctl is not installed: it is not in the distribution's repositories, " +
"and this module keeps the copy it finds rather than install one (novox/hq research 027, question 1)")
default:
return fmt.Errorf("%s is not installed; the module's package resource installs it", name)
}
}
return err
}
// AsusdConfig is the few settings of asusd's own file that decide what this module's code does. The
// file is asusd's: it rewrites it whenever a setting changes, so the module reads it and never writes
// it.
type AsusdConfig struct {
ChargeLimit *int `json:"charge_control_end_threshold,omitempty"`
ProfileOnAC string `json:"platform_profile_on_ac,omitempty"`
ProfileOnBattery string `json:"platform_profile_on_battery,omitempty"`
ChangesProfileOnAC *bool `json:"change_platform_profile_on_ac,omitempty"`
ChangesProfileOnBatt *bool `json:"change_platform_profile_on_battery,omitempty"`
ACCommand string `json:"ac_command,omitempty"`
BatteryCommand string `json:"bat_command,omitempty"`
DisablesPowerdOnBatt *bool `json:"disable_nvidia_powerd_on_battery,omitempty"`
}
var ronField = regexp.MustCompile(`(?m)^\s{4}([a-z_]+):\s*(.*?),?\s*$`)
// ParseAsusdRon reads the top-level scalar fields of asusd.ron. RON is not a format the mesh
// speaks; these are one line each, and nothing nested is read.
func ParseAsusdRon(text string) AsusdConfig {
var c AsusdConfig
for _, g := range ronField.FindAllStringSubmatch(text, -1) {
key, value := g[1], strings.TrimSuffix(strings.TrimSpace(g[2]), ",")
unquoted := strings.Trim(value, `"`)
boolean := func() *bool { b := value == "true"; return &b }
switch key {
case "charge_control_end_threshold":
if n, err := strconv.Atoi(value); err == nil {
c.ChargeLimit = &n
}
case "platform_profile_on_ac":
c.ProfileOnAC = unquoted
case "platform_profile_on_battery":
c.ProfileOnBattery = unquoted
case "change_platform_profile_on_ac":
c.ChangesProfileOnAC = boolean()
case "change_platform_profile_on_battery":
c.ChangesProfileOnBatt = boolean()
case "ac_command":
c.ACCommand = unquoted
case "bat_command":
c.BatteryCommand = unquoted
case "disable_nvidia_powerd_on_battery":
c.DisablesPowerdOnBatt = boolean()
}
}
return c
}
// Asusd reads asusd's file; nil when it is not there.
func (m *Machine) Asusd() *AsusdConfig {
text := m.read("/etc/asusd/asusd.ron")
if text == "" {
return nil
}
c := ParseAsusdRon(text)
return &c
}
@@ -1,146 +0,0 @@
package main
import (
"context"
"strings"
"testing"
)
// What asusctl 6.4 and supergfxctl 5.2 said on the laptop on 2026-10-04.
const fanCurveQuiet = `
Fan curves for Quiet
[
(
fan: CPU,
pwm: (2, 0, 10, 20, 35, 55, 80, 100),
temp: (35, 45, 50, 55, 60, 65, 70, 80),
enabled: true,
),
(
fan: GPU,
pwm: (0, 0, 10, 20, 35, 65, 90, 115),
temp: (35, 45, 50, 55, 60, 65, 70, 80),
enabled: false,
),
]
`
const asusdRon = `(
charge_control_end_threshold: 80,
base_charge_control_end_threshold: 0,
disable_nvidia_powerd_on_battery: true,
ac_command: "supergfxctl -m Hybrid",
bat_command: "supergfxctl -m Integrated",
platform_profile_linked_epp: true,
platform_profile_on_battery: Quiet,
change_platform_profile_on_battery: true,
platform_profile_on_ac: Balanced,
change_platform_profile_on_ac: true,
ac_profile_tunings: {
Quiet: (
enabled: false,
group: {},
),
},
)`
func TestAsusctlsAnswersAreRead(t *testing.T) {
p, err := ParseProfileGet(profileGetBalanced)
if err != nil || p.Active != "Balanced" || p.OnAC != "Balanced" || p.Battery != "Quiet" {
t.Fatalf("%+v %v", p, err)
}
if _, err := ParseProfileGet("something else"); err == nil {
t.Fatal("an answer with no profile was read as one")
}
if l, err := ParseLeds("Current keyboard led brightness: High\n"); err != nil || l != "high" {
t.Fatalf("%q %v", l, err)
}
curves := ParseFanCurves(fanCurveQuiet)
if len(curves) != 2 || curves[0].Fan != "CPU" || curves[0].PWM[7] != 100 || curves[0].Temp[0] != 35 || curves[1].Enabled {
t.Fatalf("%+v", curves)
}
if got := ParseSupported("[Integrated, Hybrid, AsusMuxDgpu]\n"); strings.Join(got, ",") != "Integrated,Hybrid,AsusMuxDgpu" {
t.Fatalf("%v", got)
}
}
func TestAsusdsFileIsReadForWhatDecidesTheModulesCodeAndNothingNested(t *testing.T) {
c := ParseAsusdRon(asusdRon)
if *c.ChargeLimit != 80 || c.ProfileOnAC != "Balanced" || c.ProfileOnBattery != "Quiet" ||
c.ACCommand != "supergfxctl -m Hybrid" || c.BatteryCommand != "supergfxctl -m Integrated" ||
!*c.ChangesProfileOnAC || !*c.DisablesPowerdOnBatt {
t.Fatalf("%+v", c)
}
}
func TestAMissingVendorClientIsNamedWithWhyItIsMissing(t *testing.T) {
f := newFake(t)
f.fails["supergfxctl"] = notFound
_, err := f.machine().GPU(context.Background())
if err == nil || !strings.Contains(err.Error(), "research 027") {
t.Fatalf("%v", err)
}
f.fails["asusctl"] = notFound
_, err = f.machine().Profile(context.Background())
if err == nil || !strings.Contains(err.Error(), "package resource installs it") {
t.Fatalf("%v", err)
}
}
func TestAGPUModeIsSetOnlyWhenTheMachineSupportsItAndAsusdsSwitchingIsSaid(t *testing.T) {
f := newFake(t)
f.answers["supergfxctl -g"] = "Hybrid\n"
f.answers["supergfxctl -s"] = "[Integrated, Hybrid, AsusMuxDgpu]\n"
f.file("/etc/asusd/asusd.ron", asusdRon)
m := f.machine()
if _, err := GPUModeTool(context.Background(), m, map[string]any{"mode": "Vfio"}); err == nil {
t.Fatal("an unsupported mode was accepted")
}
out, err := GPUModeTool(context.Background(), m, map[string]any{"mode": "integrated"})
if err != nil {
t.Fatal(err)
}
if !f.called("supergfxctl -m Integrated") {
t.Fatalf("calls %v", f.calls)
}
if _, said := out.(map[string]any)["asusd_switches_it"]; !said {
t.Fatalf("asusd's own switching of the mode was not said: %+v", out)
}
}
func TestTheChargeLimitIsBoundedAndSetThroughAsusd(t *testing.T) {
f := newFake(t)
f.answers["asusctl battery info"] = "Current battery charge limit: 60%\n"
m := f.machine()
for _, bad := range []any{float64(10), float64(101), "x", 55.5} {
if _, err := ChargeLimitTool(context.Background(), m, map[string]any{"limit": bad}); err == nil {
t.Errorf("limit %v was accepted", bad)
}
}
out, err := ChargeLimitTool(context.Background(), m, map[string]any{"limit": float64(60)})
if err != nil || !f.called("asusctl battery limit 60") || out.(map[string]any)["asusd_limit_percent"] != 60 {
t.Fatalf("%+v %v %v", out, err, f.calls)
}
}
func TestAProfileSetByToolIsHeldAndAnUnknownOneRefused(t *testing.T) {
f := newFake(t)
f.onMains()
f.answers["asusctl profile get"] = profileGetBalanced
m := f.machine()
sw := NewSwitcher(m, nil)
if _, err := ProfileTool(context.Background(), m, sw, map[string]any{"profile": "Turbo"}); err == nil {
t.Fatal("an unknown profile was accepted")
}
out, err := ProfileTool(context.Background(), m, sw, map[string]any{"profile": "performance", "hold_minutes": float64(30)})
if err != nil || !f.called("asusctl profile set Performance") {
t.Fatalf("%v %v", err, f.calls)
}
if _, held := out.(map[string]any)["held_until"]; !held {
t.Fatalf("not held: %+v", out)
}
if r := sw.Report(); r.Held != "Performance" {
t.Fatalf("%+v", r)
}
}
@@ -1,200 +0,0 @@
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
)
// Check is one thing the module expects of the machine, and whether it holds.
type Check struct {
Name string `json:"name"`
OK bool `json:"ok"`
Detail string `json:"detail"`
}
// CheckReport is what zephyrus_check answers. NotChecked says what it did not look at, because a
// check that reads as clean while skipping something is the predecessor's verifier again.
type CheckReport struct {
Model string `json:"model"`
Checks []Check `json:"checks"`
Failing int `json:"failing"`
NotChecked []string `json:"not_checked"`
}
var (
pacmanVersion = regexp.MustCompile(`(?m)^Version\s*:\s*(\S+)`)
pacmanPackager = regexp.MustCompile(`(?m)^Packager\s*:\s*(.+)$`)
nvidiaParam = regexp.MustCompile(`(?m)^(\w+):\s*(\S+)`)
)
// ParseNvidiaParams reads /proc/driver/nvidia/params.
func ParseNvidiaParams(text string) map[string]string {
out := map[string]string{}
for _, g := range nvidiaParam.FindAllStringSubmatch(text, -1) {
out[g[1]] = g[2]
}
return out
}
// predecessorProcess finds a running process whose command line names the predecessor's script.
func (m *Machine) predecessorProcess(name string) (int, bool) {
for _, dir := range m.glob("/proc/[0-9]*") {
cmd := strings.ReplaceAll(m.read(dir+"/cmdline"), "\x00", " ")
if strings.Contains(cmd, "/"+name) && !strings.Contains(cmd, "zephyrus") {
var pid int
fmt.Sscanf(filepath.Base(dir), "%d", &pid)
return pid, true
}
}
return 0, false
}
func (m *Machine) unitIs(ctx context.Context, verb, unit string) string {
out, _ := m.Run(ctx, "systemctl", verb, unit)
return strings.TrimSpace(out)
}
// Check reads every expectation and reports each.
func (m *Machine) Check(ctx context.Context, sw *Switcher) CheckReport {
r := CheckReport{Model: m.Model(), NotChecked: []string{
"the fan curves (asusd's own, read them with zephyrus_fan_curves)",
"whether the initramfs carries the NVIDIA options (they are read from the running driver instead)",
"the vendor keys themselves (press them)",
}}
add := func(name string, ok bool, format string, a ...any) {
r.Checks = append(r.Checks, Check{Name: name, OK: ok, Detail: fmt.Sprintf(format, a...)})
if !ok {
r.Failing++
}
}
add("model", m.ThisModel(), "the firmware reports %q; this module is for %q", r.Model, ModelFamily)
// asusctl: present, and from the distribution rather than a local build.
if info, err := m.Run(ctx, "pacman", "-Qi", "asusctl"); err != nil {
add("asusctl package", false, "not installed: %v", err)
} else {
v, p := "", ""
if g := pacmanVersion.FindStringSubmatch(info); g != nil {
v = g[1]
}
if g := pacmanPackager.FindStringSubmatch(info); g != nil {
p = strings.TrimSpace(g[1])
}
local := p == "Unknown Packager"
add("asusctl package", !local, "version %s, packager %s%s", v, p,
map[bool]string{true: "; a local build — the distribution's package replaces it at the next upgrade (pacman -S asusctl)", false: ""}[local])
}
for _, foreign := range []string{"supergfxctl", "triggerhappy"} {
_, err := m.Run(ctx, "pacman", "-Q", foreign)
add(foreign+" package", err == nil, "%s; not in the distribution's repositories, kept as found (novox/hq research 027, question 1)",
map[bool]string{true: "installed", false: "NOT installed"}[err == nil])
}
for _, unit := range []string{"asusd.service", "supergfxd.service", "triggerhappy.service"} {
state := m.unitIs(ctx, "is-active", unit)
add(unit, state == "active", "%s", state)
}
powerd := m.unitIs(ctx, "is-enabled", "nvidia-powerd.service")
add("nvidia-powerd.service", powerd == "masked" || powerd == "disabled" || powerd == "" || strings.Contains(powerd, "not-found"),
"%s; the module's drop-in keeps it from starting unless the kernel command line says zephyrus.nvidia-powerd", orNone(powerd))
wants, _ := m.Run(ctx, "systemctl", "show", "-p", "Wants", "systemd-suspend.service")
add("nvidia suspend and resume", strings.Contains(wants, "nvidia-suspend.service") && strings.Contains(wants, "nvidia-resume.service"),
"systemd-suspend.service %s", strings.TrimSpace(wants))
add("touchpad after resume", strings.Contains(wants, "asus-zephyrus-g14-touchpad-resume.service"),
"systemd-suspend.service wants asus-zephyrus-g14-touchpad-resume.service: %v (a daemon-reload makes a new drop-in count)",
strings.Contains(wants, "asus-zephyrus-g14-touchpad-resume.service"))
if uid := m.triggerhappyUID(); uid < 0 {
add("triggerhappy as the account", false, "no thd process runs: the vendor keys do nothing")
} else {
add("triggerhappy as the account", uid == operatorUID(), "thd runs as uid %d; the operator's account is %d (the module's drop-in passes --user)", uid, operatorUID())
}
refs := m.asUserReferences()
add("no as-user", len(refs) == 0, "%s", orNone(map[bool]string{true: "", false: "the predecessor's as-user is still named in " + strings.Join(refs, ", ") +
": it su-s to a named person on a guessed display and sources a file of secrets"}[len(refs) == 0]))
params := ParseNvidiaParams(m.read("/proc/driver/nvidia/params"))
if len(params) == 0 {
add("nvidia options", false, "the NVIDIA driver is not loaded (no /proc/driver/nvidia/params)")
} else {
add("nvidia options", params["PreserveVideoMemoryAllocations"] == "1" && params["DynamicPowerManagement"] == "0",
"PreserveVideoMemoryAllocations=%s DynamicPowerManagement=%s (want 1 and 0; a change applies when the driver loads again)",
params["PreserveVideoMemoryAllocations"], params["DynamicPowerManagement"])
}
for _, b := range m.Batteries() {
ok := b.LimitPercent != nil && *b.LimitPercent == ChargeLimitPercent
have := "unknown"
if b.LimitPercent != nil {
have = fmt.Sprintf("%d%%", *b.LimitPercent)
}
add("charge limit", ok, "%s is %s, the module's is %d%%", b.Name, have, ChargeLimitPercent)
}
if c := m.Asusd(); c != nil && (c.ACCommand != "" || c.BatteryCommand != "") {
add("one authority over the GPU mode", false,
"asusd runs %q on mains and %q on battery: it switches the GPU mode on every change of power source, "+
"so a mode set with zephyrus_gpu_mode lasts until the next one. Clear ac_command and bat_command in /etc/asusd/asusd.ron (asusd's file) to make it the operator's alone",
c.ACCommand, c.BatteryCommand)
}
if out, err := m.Run(ctx, "journalctl", "-b", "-u", "supergfxd.service", "-g", "invalid variant", "-n", "1", "-q", "-o", "cat"); err == nil && strings.TrimSpace(out) != "" {
add("supergfxd and logind", false, "supergfxd cannot read logind's sessions this boot (%s): a mode change that needs a logout times out", strings.TrimSpace(out))
}
if pid, ok := m.predecessorProcess("auto-profile"); ok {
add("one profile switcher", false, "the predecessor's auto-profile still runs (pid %d) and switches the profile every five seconds; "+
"stop it: systemctl --user disable --now auto-profile.service", pid)
} else {
add("one profile switcher", true, "no predecessor auto-profile is running")
}
if sw != nil {
rep := sw.Report()
add("profile switcher", rep.Running, "%s", orNone(firstNonEmpty(rep.Disabled, rep.LastError, "woken by "+rep.Watching)))
}
if home := os.Getenv("MESH_OPERATOR_HOME"); home != "" {
var left []string
for _, p := range PredecessorHomeFiles {
if _, err := os.Stat(filepath.Join(m.Root, home, p)); err == nil {
left = append(left, "~/"+p)
}
}
add("predecessor files in the home", len(left) == 0, "%s", orNone(strings.Join(left, ", ")))
} else {
r.NotChecked = append(r.NotChecked, "the predecessor's files in the operator's home (MESH_OPERATOR_HOME is not set)")
}
return r
}
// PredecessorHomeFiles are what the predecessor placed in the operator's home for this model and this
// module replaces. The mesh removes nothing it did not make (novox/hq ADR 0182): the operator does,
// once, and this list is how the check knows.
var PredecessorHomeFiles = []string{
"scripts/auto-profile",
".config/systemd/user/auto-profile.service",
"scripts/asus-bright",
"scripts/asusctl-kbd-bright",
"scripts/xrandr-bright",
"scripts/media-control",
"scripts/xinput-reset-touchpad",
".config/i3/scripts/kbd-brightness-notify.sh",
"scripts/.screenlayouts/orden-workspaces.sh",
}
func orNone(s string) string {
if strings.TrimSpace(s) == "" {
return "none"
}
return s
}
func firstNonEmpty(ss ...string) string {
for _, s := range ss {
if s != "" {
return s
}
}
return ""
}
@@ -1,202 +0,0 @@
package main
import (
"context"
"fmt"
"math"
"os"
"path"
"sort"
"strconv"
"strings"
)
// MinPanelPercent is the floor a brightness change never goes below: a panel at zero is a black
// screen that looks like a dead machine, and the keys cannot be seen to bring it back.
const MinPanelPercent = 1
// Panel is the internal display's backlight.
type Panel struct {
Device string `json:"device"`
Percent float64 `json:"percent"`
Raw int64 `json:"raw"`
Max int64 `json:"max"`
Others []string `json:"other_backlights,omitempty"`
}
// panelDevice chooses the backlight that drives the internal panel.
//
// **This model registers two.** In hybrid mode the integrated GPU drives the panel (amdgpu_bl1,
// beneath the eDP connector) and the discrete GPU's driver registers one of its own (nvidia_0) that
// moves nothing. The predecessor's scripts named amdgpu_bl1 literally, which is right until the GPU
// mode puts the panel on the other GPU. The one that sits under an eDP connector is the panel's; failing
// that, the kernel's own preference: firmware, then platform, then raw.
func (m *Machine) panelDevice() (string, []string, error) {
all := m.glob("/sys/class/backlight/*")
if len(all) == 0 {
return "", nil, fmt.Errorf("this machine has no backlight in /sys/class/backlight")
}
names := make([]string, 0, len(all))
for _, d := range all {
names = append(names, path.Base(d))
}
sort.Strings(names)
rank := func(name string) int {
dir := "/sys/class/backlight/" + name
if target, err := os.Readlink(m.path(dir)); err == nil && strings.Contains(target, "-eDP-") {
return 0
}
switch m.read(dir + "/type") {
case "firmware":
return 1
case "platform":
return 2
}
return 3
}
best := names[0]
for _, n := range names[1:] {
if rank(n) < rank(best) {
best = n
}
}
var others []string
for _, n := range names {
if n != best {
others = append(others, n)
}
}
return best, others, nil
}
// PanelBrightness reads the panel.
func (m *Machine) PanelBrightness() (Panel, error) {
dev, others, err := m.panelDevice()
if err != nil {
return Panel{}, err
}
dir := "/sys/class/backlight/" + dev
raw, ok1 := m.readInt(dir + "/brightness")
max, ok2 := m.readInt(dir + "/max_brightness")
if !ok1 || !ok2 || max <= 0 {
return Panel{}, fmt.Errorf("%s does not say its brightness", dir)
}
return Panel{Device: dev, Raw: raw, Max: max, Percent: round1(float64(raw) / float64(max) * 100), Others: others}, nil
}
// PanelTarget turns a request — "40", "40%", "+5", "-10" — into the percentage to set, clamped to
// [MinPanelPercent, 100].
func PanelTarget(current float64, request string) (float64, error) {
r := strings.TrimSuffix(strings.TrimSpace(request), "%")
if r == "" {
return 0, fmt.Errorf("panel needs a percentage (40) or a step (+5, -5)")
}
n, err := strconv.ParseFloat(r, 64)
if err != nil || math.IsNaN(n) || math.IsInf(n, 0) {
return 0, fmt.Errorf("panel %q is not a percentage or a step", request)
}
target := n
if strings.HasPrefix(r, "+") || strings.HasPrefix(r, "-") {
target = current + n
}
return math.Max(MinPanelPercent, math.Min(100, target)), nil
}
// SetPanel sets the panel to a percentage.
func (m *Machine) SetPanel(ctx context.Context, request string) (Panel, error) {
p, err := m.PanelBrightness()
if err != nil {
return p, err
}
target, err := PanelTarget(p.Percent, request)
if err != nil {
return p, err
}
raw := int64(math.Round(target / 100 * float64(p.Max)))
if raw < 1 {
raw = 1
}
if err := m.write(ctx, "/sys/class/backlight/"+p.Device+"/brightness", strconv.FormatInt(raw, 10)); err != nil {
return p, err
}
return m.PanelBrightness()
}
// Keyboard is the keyboard's backlight.
type Keyboard struct {
Device string `json:"device"`
Level string `json:"level"`
Value int64 `json:"value"`
Max int64 `json:"max"`
}
// KeyboardBrightness reads the keyboard backlight from the kernel.
func (m *Machine) KeyboardBrightness() (Keyboard, error) {
found := m.glob("/sys/class/leds/*kbd_backlight*")
if len(found) == 0 {
return Keyboard{}, fmt.Errorf("this machine has no keyboard backlight in /sys/class/leds")
}
dir := found[0]
v, ok1 := m.readInt(dir + "/brightness")
max, ok2 := m.readInt(dir + "/max_brightness")
if !ok1 || !ok2 {
return Keyboard{}, fmt.Errorf("%s does not say its brightness", dir)
}
k := Keyboard{Device: path.Base(dir), Value: v, Max: max}
if max == int64(len(KeyboardLevels)-1) && v >= 0 && v <= max {
k.Level = KeyboardLevels[v]
}
return k, nil
}
// KeyboardTarget turns a request — off/low/med/high, 0-3, "+", "-" — into asusd's level name.
func KeyboardTarget(current int64, request string) (string, error) {
r := strings.ToLower(strings.TrimSpace(request))
switch r {
case "medium":
r = "med"
case "+", "up":
r = strconv.FormatInt(min64(current+1, int64(len(KeyboardLevels)-1)), 10)
case "-", "down":
r = strconv.FormatInt(max64(current-1, 0), 10)
}
for _, l := range KeyboardLevels {
if r == l {
return l, nil
}
}
if n, err := strconv.Atoi(r); err == nil && n >= 0 && n < len(KeyboardLevels) {
return KeyboardLevels[n], nil
}
return "", fmt.Errorf("keyboard %q is not one of off, low, med, high, 0-3, + or -", request)
}
// SetKeyboard has asusd set the keyboard backlight, so its own record of the level stays true.
func (m *Machine) SetKeyboard(ctx context.Context, request string) (Keyboard, error) {
k, err := m.KeyboardBrightness()
if err != nil {
return k, err
}
level, err := KeyboardTarget(k.Value, request)
if err != nil {
return k, err
}
if _, err := m.Run(ctx, "asusctl", "leds", "set", level); err != nil {
return k, vendor("asusctl", err)
}
return m.KeyboardBrightness()
}
func min64(a, b int64) int64 {
if a < b {
return a
}
return b
}
func max64(a, b int64) int64 {
if a > b {
return a
}
return b
}
@@ -1,91 +0,0 @@
package main
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
)
// backlight makes a backlight the way sysfs does: a link from /sys/class/backlight into the device
// tree, which is where the eDP connector shows.
func (f *fake) backlight(name, device string, raw, max string) {
dev := "/sys/devices/" + device + "/" + name
f.file(dev+"/brightness", raw)
f.file(dev+"/max_brightness", max)
f.file(dev+"/type", "raw")
link := filepath.Join(f.root, "/sys/class/backlight", name)
os.MkdirAll(filepath.Dir(link), 0o755)
if err := os.Symlink(filepath.Join(f.root, dev), link); err != nil {
f.t.Fatal(err)
}
}
func TestThePanelIsTheBacklightUnderTheEDPConnectorNotTheDiscreteGPUs(t *testing.T) {
f := newFake(t)
f.backlight("amdgpu_bl1", "pci0000:00/0000:65:00.0/drm/card1/card1-eDP-1", "199500", "399000")
f.backlight("nvidia_0", "pci0000:00/0000:01:00.0/backlight", "100", "100")
p, err := f.machine().PanelBrightness()
if err != nil {
t.Fatal(err)
}
if p.Device != "amdgpu_bl1" || p.Percent != 50 || len(p.Others) != 1 || p.Others[0] != "nvidia_0" {
t.Fatalf("%+v", p)
}
}
func TestAPanelRequestIsAPercentageOrAStepAndNeverGoesDark(t *testing.T) {
for _, c := range []struct {
cur float64
req string
want float64
}{{50, "40", 40}, {50, "40%", 40}, {50, "+5", 55}, {50, "-10", 40}, {3, "-10", 1}, {98, "+5", 100}, {50, "0", 1}} {
got, err := PanelTarget(c.cur, c.req)
if err != nil || got != c.want {
t.Errorf("%v %q: %v %v, want %v", c.cur, c.req, got, err, c.want)
}
}
for _, bad := range []string{"", "bright", "NaN"} {
if _, err := PanelTarget(50, bad); err == nil {
t.Errorf("%q was accepted", bad)
}
}
}
func TestSettingThePanelWritesTheRawValue(t *testing.T) {
f := newFake(t)
f.backlight("amdgpu_bl1", "card1-eDP-1", "399000", "399000")
p, err := f.machine().SetPanel(context.Background(), "25")
if err != nil {
t.Fatal(err)
}
raw, _ := os.ReadFile(filepath.Join(f.root, "/sys/devices/card1-eDP-1/amdgpu_bl1/brightness"))
if strings.TrimSpace(string(raw)) != "99750" || p.Percent != 25 {
t.Fatalf("wrote %q, read back %+v", raw, p)
}
}
func TestTheKeyboardIsSetThroughAsusdByLevel(t *testing.T) {
f := newFake(t)
f.file("/sys/class/leds/asus::kbd_backlight/brightness", "1")
f.file("/sys/class/leds/asus::kbd_backlight/max_brightness", "3")
k, err := f.machine().KeyboardBrightness()
if err != nil || k.Level != "low" {
t.Fatalf("%+v %v", k, err)
}
if _, err := f.machine().SetKeyboard(context.Background(), "+"); err != nil {
t.Fatal(err)
}
if !f.called("asusctl leds set med") {
t.Fatalf("calls: %v", f.calls)
}
for req, want := range map[string]string{"high": "high", "0": "off", "medium": "med", "-": "off"} {
if got, err := KeyboardTarget(1, req); err != nil || got != want {
t.Errorf("%q: %q %v", req, got, err)
}
}
if _, err := KeyboardTarget(1, "7"); err == nil {
t.Error("level 7 was accepted")
}
}
@@ -1,103 +0,0 @@
package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
)
// fake is a machine for a test: a tree standing in for /, and a runner answering from a table and
// recording every command it was asked to run.
type fake struct {
t *testing.T
root string
mu sync.Mutex
answers map[string]string
fails map[string]error
calls []string
}
func newFake(t *testing.T) *fake {
t.Helper()
return &fake{t: t, root: t.TempDir(), answers: map[string]string{}, fails: map[string]error{}}
}
func (f *fake) machine() *Machine { return &Machine{Root: f.root, Run: f.run} }
func (f *fake) run(_ context.Context, name string, args ...string) (string, error) {
line := strings.TrimSpace(name + " " + strings.Join(args, " "))
f.mu.Lock()
defer f.mu.Unlock()
f.calls = append(f.calls, line)
if err, ok := f.fails[line]; ok {
return "", err
}
if out, ok := f.answers[line]; ok {
return out, nil
}
if err, ok := f.fails[name]; ok {
return "", err
}
return "", nil
}
func (f *fake) called(line string) bool {
f.mu.Lock()
defer f.mu.Unlock()
for _, c := range f.calls {
if c == line {
return true
}
}
return false
}
func (f *fake) callsLike(prefix string) []string {
f.mu.Lock()
defer f.mu.Unlock()
var out []string
for _, c := range f.calls {
if strings.HasPrefix(c, prefix) {
out = append(out, c)
}
}
return out
}
// file writes a file under the fake root.
func (f *fake) file(path, content string) {
f.t.Helper()
full := filepath.Join(f.root, path)
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
f.t.Fatal(err)
}
if err := os.WriteFile(full, []byte(content), 0o644); err != nil {
f.t.Fatal(err)
}
}
// supply writes one power supply's attributes.
func (f *fake) supply(name string, attrs map[string]string) {
for k, v := range attrs {
f.file("/sys/class/power_supply/"+name+"/"+k, v+"\n")
}
}
// onMains and onBattery are this model's two states as measured on 2026-10-04.
func (f *fake) onMains() {
f.supply("ACAD", map[string]string{"type": "Mains", "online": "1"})
f.supply("BAT1", map[string]string{"type": "Battery", "status": "Not charging", "capacity": "80"})
}
func (f *fake) onBattery() {
f.supply("ACAD", map[string]string{"type": "Mains", "online": "0"})
f.supply("BAT1", map[string]string{"type": "Battery", "status": "Discharging", "capacity": "79"})
}
var notFound = &exec.Error{Name: "x", Err: exec.ErrNotFound}
const profileGetBalanced = "Active profile: Balanced\n\nAC profile Balanced\nBattery profile Quiet\n"
@@ -1,156 +0,0 @@
package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
)
// Key is one custom key on the laptop: what it is, what runs, and where that is defined.
type Key struct {
Key string `json:"key"`
Physical string `json:"physical,omitempty"`
When string `json:"when,omitempty"`
Runs string `json:"runs"`
From string `json:"from"`
}
// KeysReport is what zephyrus_keys answers.
type KeysReport struct {
Keys []Key `json:"keys"`
Warnings []string `json:"warnings"`
NotRead []string `json:"not_read"`
}
// TriggerDir is triggerhappy's directory of trigger files; the module owns one file in it.
const TriggerDir = "/etc/triggerhappy/triggers.d"
// I3Fragments are the module's own files in i3's include directory, relative to the account's home.
var I3Fragments = []string{".config/i3/config.d/10-asus.conf", ".config/i3/config.d/20-g14.conf"}
// physicalKeys names the key behind an evdev code, as far as it is known on this model. The media
// codes are the M4 key and Fn+F4/F5 together; which code is which key was not recorded.
var physicalKeys = map[string]string{
"KEY_PROG1": "a media key (M4, Fn+F4 or Fn+F5)",
"KEY_PROG3": "a media key (M4, Fn+F4 or Fn+F5)",
"KEY_PROG4": "a media key (M4, Fn+F4 or Fn+F5)",
"KEY_BRIGHTNESSDOWN": "Fn+F7",
"KEY_BRIGHTNESSUP": "Fn+F8",
"KEY_F21": "Fn+F10 (touchpad)",
"$mod+Shift+s": "Fn+F6 (screenshot; the firmware sends Super+Shift+S)",
"$mod+p": "Fn+F9 (display; the firmware sends Super+P)",
}
// firmwareKeys are handled below any configuration file.
var firmwareKeys = []Key{
{Key: "Fn+F2 / Fn+F3", Physical: "keyboard backlight", Runs: "the firmware and asusd; zephyrus-kbd-notify shows the level", From: "firmware"},
}
var (
triggerLine = regexp.MustCompile(`^(\S+)\s+([0-9]+)\s+(.+)$`)
i3Bind = regexp.MustCompile(`^bindsym\s+((?:--\S+\s+)*)(\S+)\s+(.+)$`)
i3Exec = regexp.MustCompile(`^exec(?:_always)?\s+(?:--no-startup-id\s+)?(.+)$`)
)
var triggerWhen = map[string]string{"0": "released", "1": "pressed", "2": "held (repeat)"}
// Keys lists the laptop's custom keys: every triggerhappy trigger, the module's i3 lines and the keys
// the firmware handles itself.
func (m *Machine) Keys() KeysReport {
r := KeysReport{Keys: []Key{}, Warnings: []string{}, NotRead: []string{}}
seen := map[string][]string{}
files := m.glob(TriggerDir + "/*.conf")
sort.Strings(files)
if len(files) == 0 {
r.Warnings = append(r.Warnings, "no trigger file in "+TriggerDir+": the vendor keys do nothing")
}
for _, f := range files {
for _, line := range strings.Split(m.read(f), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
g := triggerLine.FindStringSubmatch(line)
if g == nil {
continue
}
r.Keys = append(r.Keys, Key{Key: g[1], Physical: physicalKeys[g[1]], When: triggerWhen[g[2]], Runs: g[3], From: f})
id := g[1] + " " + g[2]
seen[id] = append(seen[id], f)
}
}
for id, fs := range seen {
if len(fs) > 1 {
r.Warnings = append(r.Warnings, fmt.Sprintf("%s is bound in %d places (%s): it fires every one", id, len(fs), strings.Join(fs, ", ")))
}
}
home := os.Getenv("MESH_OPERATOR_HOME")
if home == "" {
r.NotRead = append(r.NotRead, "the module's i3 lines (MESH_OPERATOR_HOME is not set)")
}
for _, rel := range I3Fragments {
if home == "" {
break
}
p := filepath.Join(home, rel)
text := m.read(p)
if text == "" {
r.Warnings = append(r.Warnings, "~/"+rel+" is missing or empty")
continue
}
for _, line := range strings.Split(text, "\n") {
line = strings.TrimSpace(line)
if g := i3Bind.FindStringSubmatch(line); g != nil {
when := "pressed"
if strings.Contains(g[1], "--release") {
when = "released"
}
r.Keys = append(r.Keys, Key{Key: g[2], Physical: physicalKeys[g[2]], When: when, Runs: strings.TrimPrefix(strings.TrimPrefix(g[3], "exec "), "--no-startup-id "), From: "~/" + rel})
} else if g := i3Exec.FindStringSubmatch(line); g != nil {
r.Keys = append(r.Keys, Key{Key: "(session start)", When: "at login", Runs: g[1], From: "~/" + rel})
}
}
}
r.Keys = append(r.Keys, firmwareKeys...)
sort.Strings(r.Warnings)
return r
}
// asUserReferences finds the predecessor's as-user wrapper still named in a trigger, a udev rule or
// the module's i3 lines.
func (m *Machine) asUserReferences() []string {
var at []string
for _, pattern := range []string{TriggerDir + "/*.conf", "/etc/udev/rules.d/*.rules", "/etc/systemd/system-sleep/*"} {
for _, f := range m.glob(pattern) {
if strings.Contains(m.read(f), "as-user") {
at = append(at, f)
}
}
}
sort.Strings(at)
return at
}
// triggerhappyUID is the real user id the running thd has, or -1 when none runs.
func (m *Machine) triggerhappyUID() int {
for _, dir := range m.glob("/proc/[0-9]*") {
if strings.TrimSpace(m.read(dir+"/comm")) != "thd" {
continue
}
for _, line := range strings.Split(m.read(dir+"/status"), "\n") {
if f := strings.Fields(line); len(f) >= 2 && f[0] == "Uid:" {
var uid int
if _, err := fmt.Sscanf(f[1], "%d", &uid); err == nil {
return uid
}
}
}
}
return -1
}
// operatorUID is the account the module's code runs as: the runtime runs it as the operator's.
var operatorUID = os.Getuid
@@ -1,106 +0,0 @@
package main
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
func put(t *testing.T, root, p, content string) {
t.Helper()
full := filepath.Join(root, p)
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(full, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
// The module's shipped triggers and i3 lines, read back as keys: what each runs and where.
func TestKeysListsTriggersI3LinesAndFirmwareKeys(t *testing.T) {
f := newFake(t)
m := readManifest(t)
content := map[string]string{}
for _, r := range m.Resources {
if c, ok := r["content"].(string); ok {
content[r["id"].(string)] = c
}
}
put(t, f.root, TriggerDir+"/asus-g14.conf", content["vendor-keys"])
home := "/home/operator"
t.Setenv("MESH_OPERATOR_HOME", home)
put(t, f.root, home+"/"+I3Fragments[0], content["i3-vendor-keys"])
put(t, f.root, home+"/"+I3Fragments[1], content["i3-model"])
r := f.machine().Keys()
got := map[string]Key{}
for _, k := range r.Keys {
got[k.Key+"|"+k.When] = k
}
if k := got["KEY_F21|pressed"]; !strings.Contains(k.Runs, "zephyrus-touchpad reset") || k.Physical == "" {
t.Errorf("touchpad key: %+v", k)
}
if k := got["KEY_PROG1|pressed"]; !strings.Contains(k.Runs, "zephyrus-media play-pause") {
t.Errorf("media key: %+v", k)
}
if k := got["$mod+Shift+s|released"]; !strings.Contains(k.Runs, "screenshot") || !strings.Contains(k.Physical, "Fn+F6") {
t.Errorf("screenshot key: %+v", k)
}
if k := got["$mod+p|pressed"]; !strings.Contains(k.Runs, "zephyrus-display order") {
t.Errorf("display key: %+v", k)
}
if k := got["(session start)|at login"]; k.Runs == "" {
t.Errorf("no session-start line read")
}
if k := got["Fn+F2 / Fn+F3|"]; k.From != "firmware" {
t.Errorf("firmware keys missing: %+v", r.Keys)
}
if len(r.Warnings) != 0 || len(r.NotRead) != 0 {
t.Errorf("warnings %v, not read %v", r.Warnings, r.NotRead)
}
if _, err := json.Marshal(r); err != nil {
t.Fatal(err)
}
}
// A key bound in two trigger files fires twice, which is said.
func TestKeysWarnsAboutAKeyInTwoTriggerFiles(t *testing.T) {
f := newFake(t)
put(t, f.root, TriggerDir+"/asus-g14.conf", "KEY_F21\t1\t/x reset\n")
put(t, f.root, TriggerDir+"/old.conf", "KEY_F21\t1\t/y reset\n")
t.Setenv("MESH_OPERATOR_HOME", "")
r := f.machine().Keys()
if len(r.Warnings) != 1 || !strings.Contains(r.Warnings[0], "KEY_F21") || len(r.NotRead) != 1 {
t.Errorf("warnings %v, not read %v", r.Warnings, r.NotRead)
}
}
// The check names what still calls as-user, and whether triggerhappy runs as the account.
func TestCheckFindsAsUserAndTriggerhappysAccount(t *testing.T) {
f := newFake(t)
put(t, f.root, "/etc/udev/rules.d/91-monitor-hotplug.rules", `RUN+="/x/scripts/as-user setsid wizard"`)
put(t, f.root, "/proc/4242/comm", "thd\n")
put(t, f.root, "/proc/4242/status", "Name:\tthd\nUid:\t0\t0\t0\t0\n")
was := operatorUID
operatorUID = func() int { return 1000 }
defer func() { operatorUID = was }()
t.Setenv("MESH_OPERATOR_HOME", "")
r := f.machine().Check(context.Background(), nil)
by := map[string]Check{}
for _, c := range r.Checks {
by[c.Name] = c
}
if c := by["no as-user"]; c.OK || !strings.Contains(c.Detail, "91-monitor-hotplug.rules") {
t.Errorf("as-user: %+v", c)
}
if c := by["triggerhappy as the account"]; c.OK || !strings.Contains(c.Detail, "uid 0") {
t.Errorf("triggerhappy: %+v", c)
}
if c := by["touchpad after resume"]; c.OK {
t.Errorf("resume: %+v", c)
}
}
@@ -1,124 +0,0 @@
package main
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
)
// CommandTimeout bounds every command a tool or the switcher runs: a vendor daemon that hangs on its
// bus must cost a tool call twenty seconds, never the runtime's thirty.
const CommandTimeout = 20 * time.Second
// Runner runs one command and answers its standard output. It is injected so that every tool is
// tested against recorded answers rather than this machine's daemons.
type Runner func(ctx context.Context, name string, args ...string) (string, error)
// ExecRunner runs a command on the machine, bounded by CommandTimeout. A failure carries what the
// command said on stderr, because "exit status 1" names nothing.
func ExecRunner(ctx context.Context, name string, args ...string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, CommandTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, name, args...)
var stdout, stderr bytes.Buffer
cmd.Stdout, cmd.Stderr = &stdout, &stderr
err := cmd.Run()
if ctx.Err() == context.DeadlineExceeded {
return stdout.String(), fmt.Errorf("%s did not answer within %s", name, CommandTimeout)
}
if err != nil {
said := strings.TrimSpace(stderr.String())
if said == "" {
said = strings.TrimSpace(stdout.String())
}
if said != "" {
return stdout.String(), fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, said)
}
return stdout.String(), fmt.Errorf("%s %s: %w", name, strings.Join(args, " "), err)
}
return stdout.String(), nil
}
// Machine is what the module reads and acts on: a filesystem root (the real one, or a test's tree of
// /sys and /proc and /etc) and a way to run commands.
type Machine struct {
Root string
Run Runner
}
// Here is the machine this process runs on.
func Here() *Machine { return &Machine{Root: "/", Run: ExecRunner} }
func (m *Machine) path(p string) string { return filepath.Join(m.Root, p) }
// read is a file's content, trimmed; "" when it cannot be read.
func (m *Machine) read(p string) string {
b, err := os.ReadFile(m.path(p))
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
// readInt is a file holding one integer; ok false when it is absent or not a number.
func (m *Machine) readInt(p string) (int64, bool) {
s := m.read(p)
if s == "" {
return 0, false
}
n, err := strconv.ParseInt(s, 10, 64)
return n, err == nil
}
func (m *Machine) glob(pattern string) []string {
found, _ := filepath.Glob(m.path(pattern))
out := make([]string, 0, len(found))
for _, f := range found {
rel, err := filepath.Rel(m.Root, f)
if err != nil {
continue
}
out = append(out, "/"+filepath.ToSlash(rel))
}
return out
}
// write puts a value into a file of the kernel's (a backlight). Where the account may not write it
// — the udev rule that gives the video group the panel has not run yet — it escalates with `sudo -n`,
// which never prompts: the operator's account may escalate without one, and when it may not, the
// tool says so in sudo's words.
func (m *Machine) write(ctx context.Context, p, value string) error {
err := os.WriteFile(m.path(p), []byte(value), 0)
if err == nil {
return nil
}
if !errors.Is(err, os.ErrPermission) {
return err
}
if _, serr := m.Run(ctx, "sudo", "-n", "sh", "-c", `printf '%s' "$1" > "$2"`, "sh", value, m.path(p)); serr != nil {
return fmt.Errorf("%s is not writable by this account and sudo -n refused: %v", p, serr)
}
return nil
}
// notInstalled says a command failed because it is not on this machine at all.
func notInstalled(err error) bool { return errors.Is(err, exec.ErrNotFound) }
// round to one decimal, for watts and percentages a person reads.
func round1(f float64) float64 {
return float64(int64(f*10+sign(f)*0.5)) / 10
}
func sign(f float64) float64 {
if f < 0 {
return -1
}
return 1
}
@@ -1,25 +0,0 @@
// The asus-zephyrus-g14 module's Go bundle (novox/hq ADR 0188, ADR 0193, ADR 0198): one process the
// node's runtime launches, serving the module's tools over MCP on stdio and running its long-running
// code — the platform-profile switcher — beside them.
package main
import (
"context"
"fmt"
"os"
stdio "git.novox.be/novox/mesh-sdk/go"
)
func main() {
m := Here()
sw := NewSwitcher(m, func(eventType string, body any) error { return stdio.Emit(eventType, body) })
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sw.Run(ctx)
// An empty name serves as the module the runtime names (MESH_SERVED_MODULE).
if err := stdio.Serve("", Tools(m, sw)); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
@@ -1,110 +0,0 @@
package main
import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"testing"
)
type manifest struct {
Module string `json:"module"`
Tools []string `json:"tools"`
Emits []string `json:"emits"`
Resources []map[string]any `json:"resources"`
}
func readManifest(t *testing.T) manifest {
t.Helper()
raw, err := os.ReadFile("../../module.json")
if err != nil {
t.Fatal(err)
}
var m manifest
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatal(err)
}
return m
}
func TestTheManifestNamesExactlyTheToolsTheBundleServes(t *testing.T) {
m := readManifest(t)
var served []string
for _, tool := range Tools(&Machine{Root: t.TempDir(), Run: newFake(t).run}, nil) {
served = append(served, tool.Name)
}
sort.Strings(served)
listed := append([]string(nil), m.Tools...)
sort.Strings(listed)
if strings.Join(served, ",") != strings.Join(listed, ",") {
t.Fatalf("served %v, listed %v", served, listed)
}
if len(m.Emits) != 1 || m.Emits[0] != "profile.switched" {
t.Fatalf("emits %v", m.Emits)
}
}
// The module names the model, never a node, a person or a user id (novox/hq ADR 0112), and every
// trigger it names a service restart or reload on is one of its own resources.
func TestTheManifestNamesNoMachineAndItsTriggersExist(t *testing.T) {
m := readManifest(t)
ids := map[string]bool{}
for _, r := range m.Resources {
ids[r["id"].(string)] = true
}
raw, _ := os.ReadFile("../../module.json")
for _, banned := range []string{"jochen", "/home/", "/run/user/1000", "\"g14\"", "shanks"} {
if strings.Contains(string(raw), banned) {
t.Errorf("the manifest says %q", banned)
}
}
for _, r := range m.Resources {
for _, key := range []string{"restart-on", "reload-on"} {
list, _ := r[key].([]any)
for _, id := range list {
if !ids[id.(string)] {
t.Errorf("%s %s names %v, which is not a resource", r["id"], key, id)
}
}
}
}
}
// Every trigger runs a script the module ships, and every script parses.
func TestTheVendorKeysRunTheModulesOwnScriptsAndTheyParse(t *testing.T) {
m := readManifest(t)
var triggers string
for _, r := range m.Resources {
if r["id"] == "vendor-keys" {
triggers = r["content"].(string)
}
}
if triggers == "" {
t.Fatal("no vendor-keys resource")
}
for _, line := range strings.Split(triggers, "\n") {
f := strings.Split(line, "\t")
if strings.HasPrefix(line, "#") || len(f) < 3 {
continue
}
script := strings.Fields(f[2])[0]
local := filepath.Join("../../files/bin", filepath.Base(script))
if !strings.HasPrefix(script, "/usr/local/lib/asus-zephyrus-g14/bin/") {
t.Errorf("%s runs %s, which the module does not ship", f[0], script)
} else if st, err := os.Stat(local); err != nil || st.Mode()&0o111 == 0 {
t.Errorf("%s: %s is missing or not executable", f[0], local)
}
}
scripts, _ := filepath.Glob("../../files/bin/*")
if len(scripts) == 0 {
t.Fatal("no scripts")
}
for _, s := range scripts {
if out, err := exec.Command("bash", "-n", s).CombinedOutput(); err != nil {
t.Errorf("%s: %v %s", s, err, out)
}
}
}
@@ -1,137 +0,0 @@
package main
import (
"fmt"
"strconv"
"strings"
"time"
)
// The policy, as constants until the mesh has settings a module can read (novox/hq issue 168). The
// values are the predecessor's, made explicit, and two of its behaviours are changed on purpose:
//
// - **Sustained, not momentary.** The predecessor boosted on one five-second sample above 50 %: a
// compile's first second, a browser's tab restore. Here the load must stay above the line for
// SustainSamples samples in a row, and below the lower line as long, before the profile moves.
// - **Waiting on a disk is not load.** iowait is counted as idle: a machine stalled on its SSD does
// not get faster with a higher power limit, only hotter.
const (
ProfileOnBattery = "Quiet"
ProfileOnAC = "Balanced"
ProfileUnderLoad = "Performance"
CPUHighPercent = 50.0 // on mains, sustained at or above this boosts to ProfileUnderLoad
CPULowPercent = 20.0 // and sustained at or below this goes back to ProfileOnAC
SampleEvery = 10 * time.Second // CPU is sampled only on mains; on battery nothing is sampled
SustainSamples = 3 // 30 s above CPUHighPercent to boost
RelaxSamples = 3 // 30 s below CPULowPercent to relax
// SafetyRecheck is how often the power source is read when no event has said it changed: the
// kernel's event is the trigger, and this only covers one lost across a suspend.
SafetyRecheck = 5 * time.Minute
// DefaultHold is how long a profile chosen through the profile tool is kept before the switcher
// may move it again. A change of power source ends a hold at once.
DefaultHold = 60 * time.Minute
// ChargeLimitPercent is the battery charge limit the module asserts through asusd at start.
ChargeLimitPercent = 80
)
// Policy is the switcher's memory of recent load: how many samples in a row were above the upper line
// or below the lower one, and whether it is boosted.
type Policy struct {
Boosted bool `json:"boosted"`
Above int `json:"samples_above"`
Below int `json:"samples_below"`
Recent []float64 `json:"recent_cpu_percent"`
BoostedSince time.Time `json:"boosted_since,omitempty"`
}
// Observe takes one CPU sample (busy percent since the previous one) taken on mains.
func (p *Policy) Observe(cpu float64, at time.Time) {
p.Recent = append(p.Recent, round1(cpu))
if len(p.Recent) > 6 {
p.Recent = p.Recent[len(p.Recent)-6:]
}
switch {
case cpu >= CPUHighPercent:
p.Above++
p.Below = 0
if !p.Boosted && p.Above >= SustainSamples {
p.Boosted = true
p.BoostedSince = at
}
case cpu <= CPULowPercent:
p.Below++
p.Above = 0
if p.Boosted && p.Below >= RelaxSamples {
p.Boosted = false
p.BoostedSince = time.Time{}
}
default:
// Between the lines: no direction is sustained, and the profile stays where it is.
p.Above, p.Below = 0, 0
}
}
// Reset forgets the load, for a change of power source.
func (p *Policy) Reset() { *p = Policy{} }
// Decision is what the switcher would choose, and why.
type Decision struct {
Profile string `json:"profile"`
Reason string `json:"reason"`
}
// Decide is the policy: battery → ProfileOnBattery; mains → ProfileOnAC, or ProfileUnderLoad while
// boosted.
func (p *Policy) Decide(src Source) Decision {
if !src.OnAC {
return Decision{ProfileOnBattery, "on battery (" + src.Reason + ")"}
}
if p.Boosted {
return Decision{ProfileUnderLoad, fmt.Sprintf("on mains (%s) and CPU load sustained at or above %s%% for %d samples of %s",
src.Reason, strconv.FormatFloat(CPUHighPercent, 'f', -1, 64), SustainSamples, SampleEvery)}
}
return Decision{ProfileOnAC, fmt.Sprintf("on mains (%s), and CPU load not sustained at or above %s%%",
src.Reason, strconv.FormatFloat(CPUHighPercent, 'f', -1, 64))}
}
// CPUTimes is the first line of /proc/stat: total and idle jiffies (iowait counted as idle).
type CPUTimes struct{ Total, Idle uint64 }
// ParseProcStat reads the aggregate cpu line of /proc/stat.
func ParseProcStat(text string) (CPUTimes, error) {
line := strings.SplitN(text, "\n", 2)[0]
f := strings.Fields(line)
if len(f) < 6 || f[0] != "cpu" {
return CPUTimes{}, fmt.Errorf("/proc/stat does not start with the cpu line")
}
var t CPUTimes
for i, s := range f[1:] {
if i >= 8 { // user nice system idle iowait irq softirq steal; guest is already in user
break
}
n, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return CPUTimes{}, fmt.Errorf("/proc/stat: %v", err)
}
t.Total += n
if i == 3 || i == 4 {
t.Idle += n
}
}
return t, nil
}
// Busy is the percentage of time not idle between two readings.
func Busy(before, after CPUTimes) (float64, bool) {
if after.Total <= before.Total {
return 0, false
}
total := float64(after.Total - before.Total)
idle := float64(after.Idle - before.Idle)
return (total - idle) / total * 100, true
}
@@ -1,180 +0,0 @@
package main
import (
"path"
"sort"
"strings"
)
// Supply is one entry of /sys/class/power_supply as the kernel reports it.
type Supply struct {
Name string `json:"name"`
Type string `json:"type"`
Scope string `json:"scope,omitempty"`
Status string `json:"status,omitempty"`
Online *bool `json:"online,omitempty"`
}
// Supplies is every power supply the kernel knows, sorted by name.
func (m *Machine) Supplies() []Supply {
var out []Supply
for _, dir := range m.glob("/sys/class/power_supply/*") {
s := Supply{
Name: path.Base(dir),
Type: m.read(dir + "/type"),
Scope: m.read(dir + "/scope"),
Status: m.read(dir + "/status"),
}
if v, ok := m.readInt(dir + "/online"); ok {
on := v == 1
s.Online = &on
}
out = append(out, s)
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
// system is a supply that powers this machine. A mouse's or a headset's battery reports scope
// Device, and it says nothing about whether the laptop is on mains.
func (s Supply) system() bool { return !strings.EqualFold(s.Scope, "Device") }
// Source is where the machine draws its power from, and why that was concluded.
type Source struct {
OnAC bool `json:"on_ac"`
Source string `json:"source"`
Reason string `json:"reason"`
}
// PowerSource decides mains or battery.
//
// **A battery that says it is discharging wins over any adapter that says it is online.** The
// predecessor's script took any `online` file reading 1 as mains, and a USB-C port reports `online`
// for things that do not power the machine. The battery's own status is the one fact that cannot be
// misread: it discharges exactly when nothing outside is carrying the load. Only when no battery says
// so are the adapters asked, and a machine with no system battery at all is on mains.
func PowerSource(supplies []Supply) Source {
batteries := 0
for _, s := range supplies {
if s.Type == "Battery" && s.system() {
batteries++
if strings.EqualFold(s.Status, "Discharging") {
return Source{OnAC: false, Source: "battery", Reason: s.Name + " is discharging"}
}
}
}
for _, s := range supplies {
if (s.Type == "Mains" || strings.HasPrefix(s.Type, "USB")) && s.system() && s.Online != nil && *s.Online {
return Source{OnAC: true, Source: "ac", Reason: s.Name + " (" + s.Type + ") is online"}
}
}
if batteries == 0 {
return Source{OnAC: true, Source: "ac", Reason: "this machine has no system battery"}
}
return Source{OnAC: false, Source: "battery", Reason: "no mains or USB supply is online"}
}
// Battery is what the battery tool answers.
type Battery struct {
Name string `json:"name"`
Status string `json:"status"`
ChargePercent *int64 `json:"charge_percent,omitempty"`
EnergyWh *float64 `json:"energy_wh,omitempty"`
FullWh *float64 `json:"full_wh,omitempty"`
DesignWh *float64 `json:"design_wh,omitempty"`
HealthPercent *float64 `json:"health_percent,omitempty"`
Cycles *int64 `json:"cycles"`
CyclesNote string `json:"cycles_note,omitempty"`
LimitPercent *int64 `json:"charge_limit_percent,omitempty"`
PowerW *float64 `json:"power_w,omitempty"`
HoursRemaining *float64 `json:"hours_remaining,omitempty"`
Technology string `json:"technology,omitempty"`
Model string `json:"model,omitempty"`
Manufacturer string `json:"manufacturer,omitempty"`
}
// Batteries reads every system battery.
func (m *Machine) Batteries() []Battery {
var out []Battery
for _, s := range m.Supplies() {
if s.Type != "Battery" || !s.system() {
continue
}
out = append(out, m.battery(s))
}
return out
}
func (m *Machine) battery(s Supply) Battery {
dir := "/sys/class/power_supply/" + s.Name
b := Battery{
Name: s.Name, Status: s.Status,
Technology: m.read(dir + "/technology"),
Model: m.read(dir + "/model_name"),
Manufacturer: strings.TrimSpace(m.read(dir + "/manufacturer")),
}
if v, ok := m.readInt(dir + "/capacity"); ok {
b.ChargePercent = &v
}
// Energy in Wh: energy_* (µWh) where the firmware reports it, else charge_* (µAh) times the
// design minimum voltage, which is how upower converts it too.
wh := func(energy, charge string) *float64 {
if v, ok := m.readInt(dir + "/" + energy); ok {
f := round1(float64(v) / 1e6)
return &f
}
c, okc := m.readInt(dir + "/" + charge)
volts, okv := m.readInt(dir + "/voltage_min_design")
if okc && okv {
f := round1(float64(c) * float64(volts) / 1e12)
return &f
}
return nil
}
b.EnergyWh = wh("energy_now", "charge_now")
b.FullWh = wh("energy_full", "charge_full")
b.DesignWh = wh("energy_full_design", "charge_full_design")
if b.FullWh != nil && b.DesignWh != nil && *b.DesignWh > 0 {
h := round1(*b.FullWh / *b.DesignWh * 100)
b.HealthPercent = &h
}
if v, ok := m.readInt(dir + "/cycle_count"); ok && v > 0 {
b.Cycles = &v
} else {
b.CyclesNote = "the firmware does not report a cycle count (it reads 0)"
}
if v, ok := m.readInt(dir + "/charge_control_end_threshold"); ok {
b.LimitPercent = &v
}
if w := m.batteryWatts(dir); w != nil {
b.PowerW = w
if strings.EqualFold(s.Status, "Discharging") && b.EnergyWh != nil && *w > 0.5 {
h := round1(*b.EnergyWh / *w)
b.HoursRemaining = &h
}
}
return b
}
// batteryWatts is how much the battery is giving or taking, in watts, unsigned: power_now where the
// firmware reports it, else current times voltage.
func (m *Machine) batteryWatts(dir string) *float64 {
if v, ok := m.readInt(dir + "/power_now"); ok {
f := round1(abs(float64(v)) / 1e6)
return &f
}
i, oki := m.readInt(dir + "/current_now")
u, oku := m.readInt(dir + "/voltage_now")
if oki && oku {
f := round1(abs(float64(i)) * float64(u) / 1e12)
return &f
}
return nil
}
func abs(f float64) float64 {
if f < 0 {
return -f
}
return f
}
@@ -1,73 +0,0 @@
package main
import "testing"
func on(b bool) *bool { return &b }
func TestADischargingBatteryWinsOverAnAdapterThatSaysOnline(t *testing.T) {
got := PowerSource([]Supply{
{Name: "BAT1", Type: "Battery", Status: "Discharging"},
{Name: "ucsi-source-psy-USBC000:001", Type: "USB", Scope: "System", Online: on(true)},
})
if got.OnAC {
t.Fatalf("a USB-C port reporting online while the battery discharges was read as mains: %+v", got)
}
}
func TestMainsOnlineIsAC(t *testing.T) {
got := PowerSource([]Supply{
{Name: "ACAD", Type: "Mains", Online: on(true)},
{Name: "BAT1", Type: "Battery", Status: "Not charging"},
})
if !got.OnAC || got.Reason != "ACAD (Mains) is online" {
t.Fatalf("%+v", got)
}
}
func TestAPeripheralsBatteryDecidesNothing(t *testing.T) {
got := PowerSource([]Supply{
{Name: "hidpp_battery_0", Type: "Battery", Scope: "Device", Status: "Discharging"},
{Name: "ACAD", Type: "Mains", Online: on(true)},
{Name: "BAT1", Type: "Battery", Status: "Charging"},
})
if !got.OnAC {
t.Fatalf("a mouse's discharging battery put the laptop on battery: %+v", got)
}
}
func TestNoSupplyOnlineWithABatteryIsBatteryAndNoBatteryIsMains(t *testing.T) {
if got := PowerSource([]Supply{{Name: "ACAD", Type: "Mains", Online: on(false)}, {Name: "BAT1", Type: "Battery", Status: "Unknown"}}); got.OnAC {
t.Fatalf("%+v", got)
}
if got := PowerSource(nil); !got.OnAC {
t.Fatalf("a machine with no battery is on mains: %+v", got)
}
}
func TestTheBatteryIsReadInWattHoursFromChargeAndHealthAgainstDesign(t *testing.T) {
f := newFake(t)
// The laptop's own battery, as measured: charge_* in µAh, no energy_* and no power_now.
f.supply("BAT1", map[string]string{
"type": "Battery", "status": "Discharging", "capacity": "80",
"charge_now": "3073000", "charge_full": "3865000", "charge_full_design": "4580000",
"voltage_min_design": "15939000", "current_now": "1000000", "voltage_now": "16000000",
"cycle_count": "0", "charge_control_end_threshold": "80", "manufacturer": "ASUS ",
})
bs := f.machine().Batteries()
if len(bs) != 1 {
t.Fatalf("%+v", bs)
}
b := bs[0]
if *b.EnergyWh != 49 || *b.FullWh != 61.6 || *b.DesignWh != 73 || *b.HealthPercent != 84.4 {
t.Fatalf("energy %v full %v design %v health %v", *b.EnergyWh, *b.FullWh, *b.DesignWh, *b.HealthPercent)
}
if b.Cycles != nil || b.CyclesNote == "" {
t.Fatal("a cycle count of 0 is the firmware not reporting one, and said so")
}
if *b.LimitPercent != 80 || *b.PowerW != 16 || b.HoursRemaining == nil || *b.HoursRemaining != 3.1 {
t.Fatalf("limit %v power %v hours %v", *b.LimitPercent, *b.PowerW, b.HoursRemaining)
}
if b.Manufacturer != "ASUS" {
t.Fatalf("manufacturer %q", b.Manufacturer)
}
}
@@ -1,303 +0,0 @@
package main
import (
"context"
"fmt"
"os"
"strconv"
"strings"
"sync"
"time"
)
// The module's long-running code (novox/hq ADR 0198): the profile switcher, launched with the tools
// by the node's runtime and running beside them in the same process.
//
// It replaces the predecessor's `auto-profile`, a user unit that woke every five seconds for ever —
// read the adapters, read /proc/stat, maybe call asusctl — on battery too, where its only possible
// answer was the one it had already given. Here the kernel's power-supply event is the trigger; the
// CPU is sampled only on mains, where the answer depends on it; and on battery the process sleeps
// until the adapter comes back.
//
// **It acts on a change of its decision, never to restore one.** A profile chosen by hand — the
// vendor's profile key, asusctl in a terminal, the profile tool — stays until the power source
// changes or the load crosses a line. The predecessor re-asserted its choice every five seconds and so
// made the profile key useless on battery.
// Emitter publishes an event as the module; nil when the process is not under the runtime.
type Emitter func(eventType string, body any) error
// Switcher is the switcher's state, shared with the tools that report it.
type Switcher struct {
m *Machine
now func() time.Time
emit Emitter
mu sync.Mutex
policy Policy
source *Source
decision *Decision
applied string
appliedAt time.Time
lastError string
holdUntil time.Time
holdOf string
watching string
cpuPrev *CPUTimes
disabled string
asserted []string
}
func NewSwitcher(m *Machine, emit Emitter) *Switcher {
return &Switcher{m: m, now: time.Now, emit: emit}
}
// Model is the machine's product family as its firmware reports it.
func (m *Machine) Model() string { return m.read("/sys/class/dmi/id/product_family") }
// ModelFamily is the family this module is written for.
const ModelFamily = "ROG Zephyrus G14"
// ThisModel says whether the machine is the model this module is written for.
func (m *Machine) ThisModel() bool { return strings.EqualFold(m.Model(), ModelFamily) }
// sampleCPU reads /proc/stat and answers the busy percentage since the previous reading.
func (s *Switcher) sampleCPU() (float64, bool) {
t, err := ParseProcStat(s.m.read("/proc/stat"))
if err != nil {
return 0, false
}
prev := s.cpuPrev
s.cpuPrev = &t
if prev == nil {
return 0, false
}
return Busy(*prev, t)
}
// Evaluate reads the power source, takes a CPU sample when asked and on mains, decides, and applies
// the decision when it changed. It is the whole of one wake-up and what the tests drive.
func (s *Switcher) Evaluate(ctx context.Context, sample bool) {
if body := s.evaluate(ctx, sample); body != nil && s.emit != nil {
// Outside the lock: publishing waits for the bus, and the tools that report the switcher
// must not wait with it.
if err := s.emit("profile.switched", body); err != nil {
fmt.Fprintf(os.Stderr, "profile.switched not published: %v\n", err)
}
}
}
// evaluate is Evaluate under the lock; it answers the event to publish when it switched.
func (s *Switcher) evaluate(ctx context.Context, sample bool) map[string]any {
s.mu.Lock()
defer s.mu.Unlock()
if s.disabled != "" {
return nil
}
src := PowerSource(s.m.Supplies())
now := s.now()
first := s.source == nil
if first || s.source.OnAC != src.OnAC {
// A new power source: what was learnt about load on the other one says nothing here, and a
// hold was for the source it was asked on.
s.policy.Reset()
s.cpuPrev = nil
s.holdUntil = time.Time{}
s.holdOf = ""
s.sampleCPU() // the first reading on this source, so the next sample is a difference
} else if sample && src.OnAC {
if busy, ok := s.sampleCPU(); ok {
s.policy.Observe(busy, now)
}
}
s.source = &src
d := s.policy.Decide(src)
s.decision = &d
// **Starting is not a reason to switch.** The runtime starts this process on every push that
// changes a bundle; at boot and at every change of power source asusd has already applied its own
// profile for the source, which AssertVendorSettings made the policy's. So the first decision is
// taken as applied, and a profile someone chose by hand survives a push.
if first {
s.applied = d.Profile
return nil
}
// Compared with what the switcher itself last applied, never with the profile in force: a profile
// someone chose by hand is not a reason to act, a new decision is.
if d.Profile == s.applied || now.Before(s.holdUntil) {
return nil
}
from := s.applied
if err := s.m.SetProfile(ctx, d.Profile); err != nil {
s.lastError = err.Error() // and tried again at the next wake-up, since applied did not move
return nil
}
s.lastError = ""
s.applied, s.appliedAt = d.Profile, now
body := map[string]any{"profile": d.Profile, "reason": d.Reason, "source": src.Source}
if from != "" {
body["from"] = from
}
return body
}
// Hold keeps a profile chosen through the tool for a while: the switcher does not move it until the
// hold ends or the power source changes.
func (s *Switcher) Hold(profile string, d time.Duration) time.Time {
s.mu.Lock()
defer s.mu.Unlock()
if d <= 0 {
s.holdUntil, s.holdOf = time.Time{}, ""
return time.Time{}
}
s.holdUntil, s.holdOf = s.now().Add(d), profile
return s.holdUntil
}
// Run is the switcher's life: assert asusd's settings once, then wake on each power-supply event, on
// each CPU sample while on mains, and at SafetyRecheck otherwise.
func (s *Switcher) Run(ctx context.Context) {
defer func() {
if r := recover(); r != nil {
s.mu.Lock()
s.disabled = fmt.Sprintf("the switcher stopped on a fault: %v", r)
s.mu.Unlock()
fmt.Fprintln(os.Stderr, s.disabled)
}
}()
if !s.m.ThisModel() {
s.mu.Lock()
s.disabled = fmt.Sprintf("this machine reports %q, not %q: the switcher does not act on another model",
s.m.Model(), ModelFamily)
s.mu.Unlock()
fmt.Fprintln(os.Stderr, s.disabled)
return
}
s.AssertVendorSettings(ctx)
events, err := listenPowerSupply(ctx)
s.mu.Lock()
if err != nil {
s.watching = "polling every " + SampleEvery.String() + ": " + err.Error()
} else {
s.watching = "the kernel's power-supply events"
}
s.mu.Unlock()
s.Evaluate(ctx, false)
timer := time.NewTimer(s.interval(err != nil))
defer timer.Stop()
for {
select {
case <-ctx.Done():
return
case _, open := <-events:
if !open {
events = nil
s.mu.Lock()
s.watching = "polling every " + SampleEvery.String() + ": the uevent socket closed"
s.mu.Unlock()
err = fmt.Errorf("closed")
continue
}
// Settle: an adapter change arrives as several events within a moment.
time.Sleep(time.Second)
s.Evaluate(ctx, false)
case <-timer.C:
s.Evaluate(ctx, true)
timer.Reset(s.interval(err != nil))
}
}
}
// interval is how long to sleep: a CPU sample's period on mains (or with no events to wake on), the
// safety recheck on battery.
func (s *Switcher) interval(polling bool) time.Duration {
s.mu.Lock()
defer s.mu.Unlock()
if polling || s.source == nil || s.source.OnAC {
return SampleEvery
}
return SafetyRecheck
}
// AssertVendorSettings puts asusd's own settings where the module wants them, once at start: the
// battery charge limit, and the profiles asusd itself switches to on mains and on battery, so that the
// vendor daemon's own switching and this module's never disagree. Each is read first and set only if
// it differs. A value changed later with a tool stands until the next start.
func (s *Switcher) AssertVendorSettings(ctx context.Context) []string {
var said []string
if limit, err := s.m.ChargeLimit(ctx); err != nil {
said = append(said, "charge limit not read: "+err.Error())
} else if limit != ChargeLimitPercent {
if _, err := s.m.Run(ctx, "asusctl", "battery", "limit", strconv.Itoa(ChargeLimitPercent)); err != nil {
said = append(said, "charge limit not set: "+vendor("asusctl", err).Error())
} else {
said = append(said, fmt.Sprintf("charge limit %d%% → %d%%", limit, ChargeLimitPercent))
}
} else {
said = append(said, fmt.Sprintf("charge limit already %d%%", ChargeLimitPercent))
}
p, err := s.m.Profile(ctx)
if err != nil {
said = append(said, "asusd's profiles not read: "+err.Error())
} else {
for _, want := range []struct{ flag, have, want, what string }{
{"-a", p.OnAC, ProfileOnAC, "on mains"},
{"-b", p.Battery, ProfileOnBattery, "on battery"},
} {
if want.have == "" || strings.EqualFold(want.have, want.want) {
continue
}
if _, err := s.m.Run(ctx, "asusctl", "profile", "set", want.flag, want.want); err != nil {
said = append(said, "asusd's profile "+want.what+" not set: "+err.Error())
} else {
said = append(said, fmt.Sprintf("asusd's profile %s %s → %s", want.what, want.have, want.want))
}
}
}
s.mu.Lock()
s.asserted = said
s.mu.Unlock()
for _, line := range said {
fmt.Fprintln(os.Stderr, line)
}
return said
}
// SwitcherReport is the switcher's state as the profile-policy tool shows it.
type SwitcherReport struct {
Running bool `json:"running"`
Disabled string `json:"disabled,omitempty"`
Watching string `json:"woken_by,omitempty"`
Source *Source `json:"source,omitempty"`
Decision *Decision `json:"decision,omitempty"`
Load Policy `json:"load"`
LastApplied string `json:"last_applied,omitempty"`
LastAppliedAt *time.Time `json:"last_applied_at,omitempty"`
LastError string `json:"last_error,omitempty"`
HeldUntil *time.Time `json:"held_until,omitempty"`
Held string `json:"held_profile,omitempty"`
AssertedAtStart []string `json:"asserted_at_start,omitempty"`
}
func (s *Switcher) Report() SwitcherReport {
s.mu.Lock()
defer s.mu.Unlock()
r := SwitcherReport{
Running: s.watching != "" && s.disabled == "", Disabled: s.disabled, Watching: s.watching,
Source: s.source, Decision: s.decision, Load: s.policy, LastApplied: s.applied,
LastAppliedAt: when(s.appliedAt), LastError: s.lastError, AssertedAtStart: s.asserted,
}
if s.now().Before(s.holdUntil) {
r.HeldUntil, r.Held = when(s.holdUntil), s.holdOf
}
return r
}
// when is a time for a report: absent rather than the zero time.
func when(t time.Time) *time.Time {
if t.IsZero() {
return nil
}
return &t
}
@@ -1,190 +0,0 @@
package main
import (
"context"
"errors"
"strconv"
"testing"
"time"
)
func TestTheLoadMustBeSustainedToBoostAndToRelaxAndBetweenTheLinesNothingMoves(t *testing.T) {
var p Policy
at := time.Now()
mains := Source{OnAC: true, Reason: "ACAD (Mains) is online"}
for i := 0; i < SustainSamples-1; i++ {
p.Observe(90, at)
}
if p.Decide(mains).Profile != ProfileOnAC {
t.Fatal("boosted before the load was sustained")
}
p.Observe(35, at) // between the lines breaks the run
p.Observe(90, at)
if p.Boosted {
t.Fatal("a broken run still counted")
}
for i := 0; i < SustainSamples; i++ {
p.Observe(CPUHighPercent, at)
}
if d := p.Decide(mains); d.Profile != ProfileUnderLoad {
t.Fatalf("%+v", d)
}
p.Observe(35, at)
if !p.Boosted {
t.Fatal("load between the lines relaxed the boost")
}
for i := 0; i < RelaxSamples; i++ {
p.Observe(5, at)
}
if p.Decide(mains).Profile != ProfileOnAC {
t.Fatal("did not relax after a sustained low")
}
p.Boosted = true
if d := p.Decide(Source{OnAC: false, Reason: "BAT1 is discharging"}); d.Profile != ProfileOnBattery {
t.Fatalf("battery: %+v", d)
}
}
func TestIOWaitIsIdle(t *testing.T) {
a, err := ParseProcStat("cpu 100 0 100 700 100 0 0 0 0 0\ncpu0 1 2 3\n")
if err != nil {
t.Fatal(err)
}
b, _ := ParseProcStat("cpu 150 0 150 700 200 0 0 0 0 0\n")
busy, ok := Busy(a, b)
if !ok || busy != 50 {
t.Fatalf("%v %v", busy, ok)
}
if _, ok := Busy(b, b); ok {
t.Fatal("no time passed and a load was answered")
}
if _, err := ParseProcStat("intr 1 2"); err == nil {
t.Fatal("a file without the cpu line was read")
}
}
func switcherOn(t *testing.T) (*fake, *Switcher, *[]map[string]any) {
f := newFake(t)
f.onMains()
f.file("/proc/stat", "cpu 0 0 0 0 0 0 0 0\n")
var emitted []map[string]any
sw := NewSwitcher(f.machine(), func(_ string, body any) error {
emitted = append(emitted, body.(map[string]any))
return nil
})
return f, sw, &emitted
}
func TestStartingIsNotAReasonToSwitch(t *testing.T) {
f, sw, emitted := switcherOn(t)
sw.Evaluate(context.Background(), false)
if calls := f.callsLike("asusctl profile set"); len(calls) != 0 || len(*emitted) != 0 {
t.Fatalf("the first decision acted: %v %v", calls, *emitted)
}
}
func TestAChangeOfPowerSourceSwitchesOnceAndPublishesIt(t *testing.T) {
f, sw, emitted := switcherOn(t)
ctx := context.Background()
sw.Evaluate(ctx, false)
f.onBattery()
sw.Evaluate(ctx, false)
sw.Evaluate(ctx, true) // nothing changed: nothing done, and on battery nothing sampled
if calls := f.callsLike("asusctl profile set"); len(calls) != 1 || calls[0] != "asusctl profile set Quiet" {
t.Fatalf("%v", calls)
}
if len(*emitted) != 1 || (*emitted)[0]["profile"] != "Quiet" || (*emitted)[0]["from"] != "Balanced" {
t.Fatalf("%v", *emitted)
}
f.onMains()
sw.Evaluate(ctx, false)
if calls := f.callsLike("asusctl profile set"); len(calls) != 2 || calls[1] != "asusctl profile set Balanced" {
t.Fatalf("%v", calls)
}
}
func TestSustainedLoadOnMainsBoostsFromSamples(t *testing.T) {
f, sw, _ := switcherOn(t)
ctx := context.Background()
sw.Evaluate(ctx, false)
var user int
for i := 1; i <= SustainSamples; i++ {
user += 90
f.file("/proc/stat", "cpu "+itoa(user)+" 0 0 "+itoa(i*10)+" 0 0 0 0\n")
sw.Evaluate(ctx, true)
}
if !f.called("asusctl profile set Performance") {
t.Fatalf("%v", f.calls)
}
}
func TestAHoldKeepsTheProfileUntilItEndsAndAFailureIsTriedAgain(t *testing.T) {
f, sw, _ := switcherOn(t)
ctx := context.Background()
now := time.Now()
sw.now = func() time.Time { return now }
sw.Evaluate(ctx, false)
f.onBattery()
sw.Evaluate(ctx, false) // source change ends any hold; switches to Quiet
sw.Hold("Performance", time.Hour)
f.fails["asusctl profile set Balanced"] = errors.New("asusd is restarting")
f.onMains()
sw.Evaluate(ctx, false) // a change of source: the hold ends, the switch is attempted and fails
if r := sw.Report(); r.LastError == "" || r.Held != "" {
t.Fatalf("%+v", r)
}
delete(f.fails, "asusctl profile set Balanced")
sw.Evaluate(ctx, false)
if r := sw.Report(); r.LastApplied != "Balanced" || r.LastError != "" {
t.Fatalf("not tried again: %+v", r)
}
// A hold on the same source keeps a new decision from acting until it ends.
sw.Hold("Quiet", time.Hour)
sw.policy.Boosted = true
sw.Evaluate(ctx, false)
if f.called("asusctl profile set Performance") {
t.Fatal("switched during a hold")
}
now = now.Add(2 * time.Hour)
sw.Evaluate(ctx, false)
if !f.called("asusctl profile set Performance") {
t.Fatal("did not act once the hold ended")
}
}
func TestAsusdsSettingsAreSetOnlyWhereTheyDiffer(t *testing.T) {
f := newFake(t)
f.answers["asusctl battery info"] = "Current battery charge limit: 100%\n"
f.answers["asusctl profile get"] = "Active profile: Balanced\nAC profile Performance\nBattery profile Quiet\n"
sw := NewSwitcher(f.machine(), nil)
sw.AssertVendorSettings(context.Background())
if !f.called("asusctl battery limit 80") || !f.called("asusctl profile set -a Balanced") || f.called("asusctl profile set -b Quiet") {
t.Fatalf("%v", f.calls)
}
}
func TestTheSwitcherDoesNotActOnAnotherModel(t *testing.T) {
f := newFake(t)
f.file("/sys/class/dmi/id/product_family", "ROG Strix\n")
sw := NewSwitcher(f.machine(), nil)
done := make(chan struct{})
go func() { sw.Run(context.Background()); close(done) }()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("the switcher ran on another model")
}
if r := sw.Report(); r.Running || r.Disabled == "" || len(f.calls) != 0 {
t.Fatalf("%+v %v", r, f.calls)
}
}
func TestOnlyPowerSupplyUeventsWake(t *testing.T) {
yes := []byte("change@/devices/LNXSYSTM:00/ACPI0003:00/power_supply/ACAD\x00ACTION=change\x00SUBSYSTEM=power_supply\x00POWER_SUPPLY_ONLINE=0\x00")
no := []byte("change@/devices/virtual/net/wlan0\x00ACTION=change\x00SUBSYSTEM=net\x00")
if !powerSupplyEvent(yes) || powerSupplyEvent(no) {
t.Fatal("the uevent filter")
}
}
func itoa(n int) string { return strconv.Itoa(n) }
@@ -1,168 +0,0 @@
package main
import (
"context"
"path"
"sort"
"strconv"
"strings"
)
// Sensor is one temperature, fan or power reading from hwmon.
type Sensor struct {
Chip string `json:"chip"`
Label string `json:"label"`
Value float64 `json:"value"`
}
// DGPU is the discrete GPU as the PCI bus and its driver see it.
type DGPU struct {
Address string `json:"pci_address"`
Runtime string `json:"runtime_status"`
Name string `json:"name,omitempty"`
TempC *float64 `json:"temp_c,omitempty"`
PowerW *float64 `json:"power_w,omitempty"`
PState string `json:"pstate,omitempty"`
Note string `json:"note,omitempty"`
}
// hwmon reads every hwmon reading of one kind: "temp" (°C), "fan" (RPM) or "power" (W).
func (m *Machine) hwmon(kind string) []Sensor {
var out []Sensor
for _, dir := range m.glob("/sys/class/hwmon/hwmon*") {
chip := m.read(dir + "/name")
inputs := m.glob(dir + "/" + kind + "*_input")
if kind == "power" {
inputs = append(inputs, m.glob(dir+"/power*_average")...)
}
for _, in := range inputs {
v, ok := m.readInt(in)
if !ok {
continue
}
base := path.Base(in)
stem := base[:strings.LastIndex(base, "_")]
label := m.read(dir + "/" + stem + "_label")
if label == "" {
label = base
} else if strings.HasSuffix(base, "_average") {
label += " (average)"
}
value := float64(v)
switch kind {
case "temp":
value = round1(value / 1000)
case "power":
value = round1(value / 1e6)
}
out = append(out, Sensor{Chip: chip, Label: label, Value: value})
}
}
sort.Slice(out, func(i, j int) bool {
if out[i].Chip != out[j].Chip {
return out[i].Chip < out[j].Chip
}
return out[i].Label < out[j].Label
})
return out
}
// dgpu finds the NVIDIA display controller and, only when it is already awake, asks its driver for
// its temperature and draw. **Asking wakes it**: nvidia-smi brings a suspended GPU out of D3, which
// is the power a reading of power draw should not cost.
func (m *Machine) dgpu(ctx context.Context) *DGPU {
for _, dir := range m.glob("/sys/bus/pci/devices/*") {
if m.read(dir+"/vendor") != "0x10de" || !strings.HasPrefix(m.read(dir+"/class"), "0x03") {
continue
}
g := &DGPU{Address: path.Base(dir), Runtime: m.read(dir + "/power/runtime_status")}
if g.Runtime != "active" {
g.Note = "the discrete GPU is " + g.Runtime + "; not woken to be read"
return g
}
out, err := m.Run(ctx, "nvidia-smi", "--query-gpu=name,temperature.gpu,power.draw,pstate", "--format=csv,noheader,nounits")
if err != nil {
g.Note = "nvidia-smi: " + err.Error()
return g
}
f := strings.Split(strings.TrimSpace(strings.SplitN(out, "\n", 2)[0]), ",")
if len(f) >= 4 {
g.Name = strings.TrimSpace(f[0])
if t, err := strconv.ParseFloat(strings.TrimSpace(f[1]), 64); err == nil {
g.TempC = &t
}
if w, err := strconv.ParseFloat(strings.TrimSpace(f[2]), 64); err == nil {
w = round1(w)
g.PowerW = &w
}
g.PState = strings.TrimSpace(f[3])
}
return g
}
return nil
}
// Thermals is what the thermals tool answers.
type Thermals struct {
Temperatures []Sensor `json:"temperatures_c"`
Fans []Sensor `json:"fans_rpm"`
DGPU *DGPU `json:"dgpu,omitempty"`
Profile string `json:"platform_profile,omitempty"`
Hottest *Sensor `json:"hottest,omitempty"`
}
func (m *Machine) Thermals(ctx context.Context) Thermals {
t := Thermals{Temperatures: m.hwmon("temp"), Fans: m.hwmon("fan"), DGPU: m.dgpu(ctx),
Profile: m.read("/sys/firmware/acpi/platform_profile")}
if t.Temperatures == nil {
t.Temperatures = []Sensor{}
}
if t.Fans == nil {
t.Fans = []Sensor{}
}
for i := range t.Temperatures {
if t.Hottest == nil || t.Temperatures[i].Value > t.Hottest.Value {
h := t.Temperatures[i]
t.Hottest = &h
}
}
return t
}
// PowerDraw is what the power-draw tool answers.
type PowerDraw struct {
Source Source `json:"source"`
BatteryW *float64 `json:"battery_w,omitempty"`
BatteryFlow string `json:"battery_flow,omitempty"`
CPUPackageW *float64 `json:"apu_package_w,omitempty"`
DGPU *DGPU `json:"dgpu,omitempty"`
Note string `json:"note"`
}
func (m *Machine) PowerDraw(ctx context.Context) PowerDraw {
p := PowerDraw{Source: PowerSource(m.Supplies()), DGPU: m.dgpu(ctx),
Note: "on battery, battery_w is what the whole machine draws; on mains it is only what the battery takes or gives"}
for _, b := range m.Batteries() {
if b.PowerW != nil {
w := *b.PowerW
p.BatteryW = &w
switch strings.ToLower(b.Status) {
case "discharging":
p.BatteryFlow = "discharging"
case "charging":
p.BatteryFlow = "charging"
default:
p.BatteryFlow = strings.ToLower(b.Status)
}
break
}
}
// The integrated GPU's hwmon reports the whole APU's package power (PPT) on this model.
for _, s := range m.hwmon("power") {
if s.Chip == "amdgpu" && s.Label == "PPT" {
w := s.Value
p.CPUPackageW = &w
}
}
return p
}
@@ -1,315 +0,0 @@
package main
import (
"context"
"fmt"
"math"
"strconv"
"strings"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// Tools is the module's tools, over one machine and its switcher.
func Tools(m *Machine, sw *Switcher) []stdio.Tool {
ctx := context.Background
return []stdio.Tool{
{
Name: "zephyrus_brightness",
Description: "Read or set the internal panel's and the keyboard's backlight. With no argument, reads both. " +
"panel is a percentage (40) or a step (+5, -10), never below 1 %; keyboard is off, low, med, high, 0-3, + or -.",
Input: map[string]any{
"panel": map[string]any{"type": "string", "description": "percentage or step, e.g. 40, +5, -10"},
"keyboard": map[string]any{"type": "string", "description": "off, low, med, high, 0-3, + or -"},
},
Run: func(args map[string]any) (any, error) {
out := map[string]any{}
if p := str(args, "panel"); p != "" {
got, err := m.SetPanel(ctx(), p)
if err != nil {
return nil, err
}
out["panel"] = got
} else if got, err := m.PanelBrightness(); err == nil {
out["panel"] = got
} else {
out["panel_error"] = err.Error()
}
if k := str(args, "keyboard"); k != "" {
got, err := m.SetKeyboard(ctx(), k)
if err != nil {
return nil, err
}
out["keyboard"] = got
} else if got, err := m.KeyboardBrightness(); err == nil {
out["keyboard"] = got
} else {
out["keyboard_error"] = err.Error()
}
return out, nil
},
},
{
Name: "zephyrus_battery",
Description: "The battery: charge, energy, health (full against design), cycles, the charge limit, the power it gives or takes, and time left when discharging.",
Run: func(map[string]any) (any, error) {
return map[string]any{"source": PowerSource(m.Supplies()), "batteries": orEmpty(m.Batteries())}, nil
},
},
{
Name: "zephyrus_charge_limit",
Description: fmt.Sprintf("Read or set the battery charge limit through asusd. limit is 20-100; oneshot charges to full once "+
"and goes back to the limit. The module asserts %d %% again when its process next starts.", ChargeLimitPercent),
Input: map[string]any{
"limit": map[string]any{"type": "integer", "description": "20-100"},
"oneshot": map[string]any{"type": "boolean", "description": "charge to full once, keeping the limit"},
},
Run: func(args map[string]any) (any, error) { return ChargeLimitTool(ctx(), m, args) },
},
{
Name: "zephyrus_gpu_mode",
Description: "Read or set the hybrid GPU's mode through supergfxd: Integrated, Hybrid or AsusMuxDgpu as the machine supports. " +
"Answers the mode, the discrete GPU's power state, any pending mode and the action it waits for (a logout, a reboot), " +
"and whether asusd will switch it again on the next change of power source.",
Input: map[string]any{
"mode": map[string]any{"type": "string", "description": "a supported mode, e.g. Integrated or Hybrid"},
},
Run: func(args map[string]any) (any, error) { return GPUModeTool(ctx(), m, args) },
},
{
Name: "zephyrus_profile",
Description: "Read or set the platform profile (Quiet, Balanced, Performance) through asusd. A profile set here is held " +
fmt.Sprintf("for hold_minutes (default %d, 0 for none) before the module's switcher may move it; a change of power source ends the hold.", int(DefaultHold.Minutes())),
Input: map[string]any{
"profile": map[string]any{"type": "string", "enum": Profiles},
"hold_minutes": map[string]any{"type": "integer", "description": "how long the switcher leaves it (default 60, at most 1440)"},
},
Run: func(args map[string]any) (any, error) { return ProfileTool(ctx(), m, sw, args) },
},
{
Name: "zephyrus_thermals",
Description: "Every temperature and fan the hardware reports (°C, RPM), the hottest, the platform profile, and the discrete GPU's temperature when it is awake (it is not woken to be read).",
Run: func(map[string]any) (any, error) { return m.Thermals(ctx()), nil },
},
{
Name: "zephyrus_power_draw",
Description: "What the machine draws: the battery's flow in watts, the APU's package power, the discrete GPU's draw when awake, and the power source with the reason it was decided.",
Run: func(map[string]any) (any, error) { return m.PowerDraw(ctx()), nil },
},
{
Name: "zephyrus_profile_policy",
Description: "What the module's profile switcher would choose now and why: the power source, recent CPU load against the thresholds, " +
"the decision, the profile in force, any hold, what woke it, and what it asserted in asusd at start.",
Run: func(map[string]any) (any, error) { return PolicyTool(ctx(), m, sw), nil },
},
{
Name: "zephyrus_fan_curves",
Description: "The fan curves asusd holds for each profile (or one profile): per fan, eight points of temperature and duty.",
Input: map[string]any{
"profile": map[string]any{"type": "string", "enum": Profiles},
},
Run: func(args map[string]any) (any, error) { return FanCurvesTool(ctx(), m, args) },
},
{
Name: "zephyrus_keys",
Description: "Every custom key on the laptop: each triggerhappy trigger (the vendor keys that reach no X client), the module's own i3 lines " +
"(keys the firmware sends as ordinary presses, and what starts with the session), and the keys the firmware handles itself — " +
"what each runs and the file it is defined in. Warns when one key is bound in two trigger files, which fires it twice.",
Run: func(map[string]any) (any, error) { return m.Keys(), nil },
},
{
Name: "zephyrus_check",
Description: "Check what this module expects of the machine: the model, the vendor packages and daemons, the NVIDIA options in force, " +
"suspend and resume, the charge limit, one authority each over the profile and the GPU mode, and the predecessor's leftovers. Says what it did not check.",
Run: func(map[string]any) (any, error) { return m.Check(ctx(), sw), nil },
},
}
}
// ChargeLimitTool reads or sets the limit.
func ChargeLimitTool(ctx context.Context, m *Machine, args map[string]any) (any, error) {
out := map[string]any{"module_limit_percent": ChargeLimitPercent}
if v, given := args["limit"]; given && v != nil {
n, err := whole(v, "limit")
if err != nil {
return nil, err
}
if n < 20 || n > 100 {
return nil, fmt.Errorf("limit %d is outside 20-100", n)
}
if _, err := m.Run(ctx, "asusctl", "battery", "limit", strconv.Itoa(n)); err != nil {
return nil, vendor("asusctl", err)
}
out["set"] = n
}
if b, _ := args["oneshot"].(bool); b {
if _, err := m.Run(ctx, "asusctl", "battery", "oneshot"); err != nil {
return nil, vendor("asusctl", err)
}
out["oneshot"] = "charging to full once; the limit returns after"
}
if n, err := m.ChargeLimit(ctx); err == nil {
out["asusd_limit_percent"] = n
} else {
out["asusd_error"] = err.Error()
}
for _, b := range m.Batteries() {
if b.LimitPercent != nil {
out["kernel_limit_percent"] = *b.LimitPercent
}
}
return out, nil
}
// GPUModeTool reads or sets the GPU mode.
func GPUModeTool(ctx context.Context, m *Machine, args map[string]any) (any, error) {
g, err := m.GPU(ctx)
if err != nil {
return nil, err
}
out := map[string]any{}
if want := str(args, "mode"); want != "" {
mode := ""
for _, s := range g.Supported {
if strings.EqualFold(s, want) {
mode = s
}
}
if mode == "" {
return nil, fmt.Errorf("mode %q is not one this machine supports (%s)", want, strings.Join(g.Supported, ", "))
}
said, err := m.Run(ctx, "supergfxctl", "-m", mode)
if err != nil {
return nil, vendor("supergfxctl", err)
}
out["requested"] = mode
if s := strings.TrimSpace(said); s != "" {
out["supergfxctl_said"] = s
}
if g, err = m.GPU(ctx); err != nil {
return nil, err
}
}
out["gpu"] = g
if c := m.Asusd(); c != nil && (c.ACCommand != "" || c.BatteryCommand != "") {
out["asusd_switches_it"] = map[string]string{"on_ac": c.ACCommand, "on_battery": c.BatteryCommand,
"note": "asusd runs these on every change of power source, so a mode set here lasts until the next one"}
}
return out, nil
}
// ProfileTool reads or sets the profile.
func ProfileTool(ctx context.Context, m *Machine, sw *Switcher, args map[string]any) (any, error) {
out := map[string]any{}
if want := str(args, "profile"); want != "" {
p, err := canonicalProfile(want)
if err != nil {
return nil, err
}
hold := DefaultHold
if v, given := args["hold_minutes"]; given && v != nil {
n, err := whole(v, "hold_minutes")
if err != nil {
return nil, err
}
if n < 0 {
return nil, fmt.Errorf("hold_minutes must not be negative")
}
hold = time.Duration(min(n, 1440)) * time.Minute
}
if err := m.SetProfile(ctx, p); err != nil {
return nil, err
}
out["set"] = p
if sw != nil {
if until := sw.Hold(p, hold); !until.IsZero() {
out["held_until"] = until
}
}
}
state, err := m.Profile(ctx)
if err != nil {
return nil, err
}
out["profile"] = state
return out, nil
}
// PolicyTool reports the switcher and, independently of it, what the policy says now.
func PolicyTool(ctx context.Context, m *Machine, sw *Switcher) any {
out := map[string]any{
"thresholds": map[string]any{
"on_battery": ProfileOnBattery, "on_ac": ProfileOnAC, "under_load": ProfileUnderLoad,
"cpu_high_percent": CPUHighPercent, "cpu_low_percent": CPULowPercent,
"sample_every": SampleEvery.String(), "sustain_samples": SustainSamples, "relax_samples": RelaxSamples,
"set_by": "constants until settings exist (novox/hq issue 168)",
},
}
if sw != nil {
out["switcher"] = sw.Report()
} else {
var p Policy
out["decision_now"] = p.Decide(PowerSource(m.Supplies()))
}
if state, err := m.Profile(ctx); err == nil {
out["in_force"] = state
} else {
out["in_force_error"] = err.Error()
}
if pid, ok := m.predecessorProcess("auto-profile"); ok {
out["second_switcher"] = fmt.Sprintf("the predecessor's auto-profile still runs (pid %d) and overrides this every five seconds", pid)
}
return out
}
// FanCurvesTool reads asusd's fan curves.
func FanCurvesTool(ctx context.Context, m *Machine, args map[string]any) (any, error) {
profiles := Profiles
if want := str(args, "profile"); want != "" {
p, err := canonicalProfile(want)
if err != nil {
return nil, err
}
profiles = []string{p}
}
out := map[string]any{}
for _, p := range profiles {
said, err := m.Run(ctx, "asusctl", "fan-curve", "--mod-profile", strings.ToLower(p))
if err != nil {
return nil, vendor("asusctl", err)
}
out[p] = orEmpty(ParseFanCurves(said))
}
return out, nil
}
func str(args map[string]any, key string) string {
s, _ := args[key].(string)
return strings.TrimSpace(s)
}
// whole is an integer argument given as a JSON number or a numeric string.
func whole(v any, key string) (int, error) {
switch n := v.(type) {
case float64:
if n != math.Trunc(n) {
return 0, fmt.Errorf("%s must be a whole number, not %v", key, n)
}
return int(n), nil
case string:
i, err := strconv.Atoi(strings.TrimSpace(n))
if err != nil {
return 0, fmt.Errorf("%s must be a whole number, not %q", key, n)
}
return i, nil
}
return 0, fmt.Errorf("%s must be a whole number", key)
}
func orEmpty[T any](s []T) []T {
if s == nil {
return []T{}
}
return s
}
@@ -1,72 +0,0 @@
package main
import (
"bytes"
"context"
"fmt"
"syscall"
)
// The kernel announces every change of a power supply — an adapter plugged or pulled, a battery
// starting or stopping to discharge — as a uevent on a netlink socket that any account may listen
// on. That is the event the switcher reacts to: no daemon, no bus client, no polling.
//
// upower re-announces the same changes on the system bus, and listening there would need a D-Bus
// client in the bundle; udev's re-broadcast (netlink group 2) carries a libudev header. The kernel's
// own group (1) is the source both of them read.
// powerSupplyEvent says whether a uevent is about a power supply.
func powerSupplyEvent(msg []byte) bool {
for _, field := range bytes.Split(msg, []byte{0}) {
if bytes.Equal(field, []byte("SUBSYSTEM=power_supply")) {
return true
}
}
return false
}
// listenPowerSupply opens the kernel's uevent socket and sends on the channel for each power-supply
// event, never blocking: a burst of events is one wake-up. It stops when ctx ends.
func listenPowerSupply(ctx context.Context) (<-chan struct{}, error) {
fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW|syscall.SOCK_CLOEXEC, syscall.NETLINK_KOBJECT_UEVENT)
if err != nil {
return nil, fmt.Errorf("opening the kernel's uevent socket: %w", err)
}
if err := syscall.Bind(fd, &syscall.SockaddrNetlink{Family: syscall.AF_NETLINK, Groups: 1}); err != nil {
syscall.Close(fd)
return nil, fmt.Errorf("joining the kernel's uevent group: %w", err)
}
events := make(chan struct{}, 1)
go func() {
<-ctx.Done()
syscall.Close(fd)
}()
go func() {
defer close(events)
buf := make([]byte, 64*1024)
for {
n, _, err := syscall.Recvfrom(fd, buf, 0)
if err != nil {
if err == syscall.EINTR || err == syscall.ENOBUFS {
// ENOBUFS: events were dropped. Treat it as one, since a dropped one may have
// been the adapter.
if err == syscall.ENOBUFS {
select {
case events <- struct{}{}:
default:
}
}
continue
}
return
}
if powerSupplyEvent(buf[:n]) {
select {
case events <- struct{}{}:
default:
}
}
}
}()
return events, nil
}
@@ -1,33 +0,0 @@
#!/bin/bash
# zephyrus-backlight + | - | PERCENT — step or set the internal panel's backlight, never below 1 %.
# Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
#
# The panel is the backlight beneath the eDP connector, not a name: in hybrid mode this model also
# registers the discrete GPU's backlight (nvidia_0), which moves nothing. Writable by the video group
# through the module's udev rule, so the vendor-key trigger needs no root.
set -u
STEP=5
dev=""
for d in /sys/class/backlight/*; do
[ -e "$d" ] || continue
case "$(readlink -f "$d")" in *-eDP-*) dev=$d; break ;; esac
done
if [ -z "$dev" ]; then
for d in /sys/class/backlight/*; do [ -e "$d" ] && { dev=$d; break; }; done
fi
[ -n "$dev" ] || { echo "zephyrus-backlight: no backlight" >&2; exit 1; }
cur=$(cat "$dev/brightness")
max=$(cat "$dev/max_brightness")
pct=$(( cur * 100 / max ))
case "${1:-}" in
+|up|Up) pct=$(( pct + STEP )) ;;
-|down|Down) pct=$(( pct - STEP )) ;;
''|*[!0-9]*) echo "usage: zephyrus-backlight + | - | PERCENT" >&2; exit 2 ;;
*) pct=$1 ;;
esac
(( pct < 1 )) && pct=1
(( pct > 100 )) && pct=100
new=$(( max * pct / 100 ))
(( new < 1 )) && new=1
printf '%s' "$new" >"$dev/brightness" || exit 1
exec "$(dirname "$0")/zephyrus-notify" 5555 "Brightness: ${pct}%"
@@ -1,41 +0,0 @@
#!/bin/bash
# zephyrus-display primary | order — the laptop's internal panel among the outputs.
# Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
#
# primary makes the internal panel X's primary output, where the bars' tray goes.
# order the display key (Fn+F9, which the firmware sends as Super+P): odd workspaces to the
# internal panel, even ones to the first external output, or all to the panel when it
# is alone. The predecessor's orden-workspaces.
#
# The panel is found, not named: the connected output whose name starts with eDP. The predecessor
# wrote eDP-1, which is what this model calls it today and not a promise.
set -u
here=$(dirname "$0")
panel=$(xrandr --query 2>/dev/null | awk '$2 == "connected" && $1 ~ /^eDP/ { print $1; exit }')
[ -n "$panel" ] || { echo "zephyrus-display: no internal panel connected" >&2; exit 1; }
case "${1:-}" in
primary)
exec xrandr --output "$panel" --primary
;;
order)
external=$(xrandr --listmonitors 2>/dev/null | awk -v p="$panel" 'NR > 1 && $NF != p { print $NF; exit }')
[ -n "$external" ] || external=$panel
# i3's workspace list, one object per workspace; num and output read from each. No jq: the
# fields are flat strings and numbers, and rect, the only nested value, holds neither name.
i3-msg -t get_workspaces 2>/dev/null | sed 's/},{"id"/}\n{"id"/g' |
while read -r ws; do
num=$(printf '%s' "$ws" | grep -o '"num":-\?[0-9]*' | cut -d: -f2)
out=$(printf '%s' "$ws" | grep -o '"output":"[^"]*"' | cut -d'"' -f4)
[ -n "$num" ] && [ "$num" -ge 0 ] || continue
if [ $((num % 2)) -eq 0 ]; then dest=$external; else dest=$panel; fi
[ "$out" = "$dest" ] && continue
i3-msg "workspace number $num; move workspace to output $dest" >/dev/null
done
if [ "$external" = "$panel" ]; then
"$here/zephyrus-notify" 7780 "Workspaces: all on the panel"
else
"$here/zephyrus-notify" 7780 "Workspaces: odd on the panel, even on $external"
fi
;;
*) echo "usage: zephyrus-display primary | order" >&2; exit 2 ;;
esac
@@ -1,20 +0,0 @@
#!/bin/bash
# zephyrus-kbd-notify — shows the keyboard backlight's level when it changes. The level itself is set
# by the firmware and asusd (Fn+F2/F3), which tell UPower; this only listens and notifies. Started once
# per session from the module's i3 fragment. Shipped by the mesh's asus-zephyrus-g14 module.
#
# One instance per session: i3 runs its `exec` lines again on an in-place restart, and the
# predecessor's listener ran twice after one, showing every change twice.
set -u
here=$(dirname "$0")
lock="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/zephyrus-kbd-notify.lock"
exec 9>"$lock"
flock -n 9 || exit 0
levels=(Off Low Med High)
dbus-monitor --system "type='signal',interface='org.freedesktop.UPower.KbdBacklight',member='BrightnessChanged'" 2>/dev/null |
while read -r line; do
if [[ $line =~ int32\ ([0-9]+) ]]; then
v=${BASH_REMATCH[1]}
"$here/zephyrus-notify" 5556 "Keyboard: ${levels[$v]:-$v}"
fi
done
@@ -1,27 +0,0 @@
#!/bin/bash
# zephyrus-media play-pause | next | previous — the media keys, through MPRIS (playerctl), with a short
# notification of what happened. Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
#
# From the predecessor's media-control, kept: the lock against a double fire (the vendor keys can
# repeat), and the notification. Dropped: its fallback to a media server's local API, which needed a
# token from a file of secrets (novox/hq research 027 question 2). A player that speaks MPRIS is
# reached; one that does not says so.
set -u
here=$(dirname "$0")
action=${1:-play-pause}
case "$action" in play-pause | next | previous) ;; *) echo "usage: zephyrus-media play-pause | next | previous" >&2; exit 2 ;; esac
lock="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/zephyrus-media.lock"
exec 9>"$lock"
flock -n 9 || exit 0
if ! playerctl status >/dev/null 2>&1; then
"$here/zephyrus-notify" 7777 "Media: no player"
exit 0
fi
playerctl "$action" 2>/dev/null
if [ "$action" = play-pause ]; then
sleep 0.2
[ "$(playerctl status 2>/dev/null)" = Playing ] && label=Playing || label=Paused
else
label=${action^}
fi
"$here/zephyrus-notify" 7777 "Media: $label"
@@ -1,12 +0,0 @@
#!/bin/bash
# zephyrus-notify ID SUMMARY — a short desktop notification that replaces the previous one with the
# same ID, through the session's notification service on its bus. busctl is the service manager's
# own client, so nothing is installed for it. Shipped by the mesh's asus-zephyrus-g14 module.
set -u
id=${1:-0}
summary=${2:-}
uid=$(id -u)
DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${uid}/bus" \
busctl --user call org.freedesktop.Notifications /org/freedesktop/Notifications \
org.freedesktop.Notifications Notify susssasa{sv}i \
asus-zephyrus-g14 "$id" "" "$summary" "" 0 1 urgency y 0 1500 >/dev/null 2>&1 || true
@@ -1,46 +0,0 @@
#!/bin/bash
# zephyrus-session COMMAND [ARG...] — run a command in the operator's graphical session from outside
# it: from a vendor-key trigger, which triggerhappy runs as the operator's account but with none of
# the session's environment. Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
#
# What it replaces: the predecessor's `as-user`, which triggerhappy ran as root and which `su`-ed to
# a named person with a hard-coded user id and display, and sourced a file of secrets on the way.
# Here the account is whoever runs it, the bus is that account's, and the display is the one the
# account's own session uses. Nothing is sourced.
set -u
uid=$(id -u)
export XDG_RUNTIME_DIR="/run/user/${uid}"
export DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus"
home=$(getent passwd "$uid" | cut -d: -f6)
[ -n "$home" ] && export HOME="$home"
# The session's own window manager says best which display and authority the session uses: read
# them from its environment, as the desktop modules' session finder does. Then logind, then any
# process of this account that has a display.
from_environ() {
env=$(tr '\0' '\n' <"/proc/$1/environ" 2>/dev/null) || return 1
d=$(printf '%s\n' "$env" | sed -n 's/^DISPLAY=//p' | head -n1)
[ -n "$d" ] || return 1
export DISPLAY="$d"
a=$(printf '%s\n' "$env" | sed -n 's/^XAUTHORITY=//p' | head -n1)
[ -n "$a" ] && export XAUTHORITY="$a"
return 0
}
if [ -z "${DISPLAY:-}" ]; then
for pid in $(pgrep -xu "$uid" i3 2>/dev/null); do
from_environ "$pid" && break
done
fi
if [ -z "${DISPLAY:-}" ]; then
for s in $(loginctl list-sessions --no-legend 2>/dev/null | awk -v u="$uid" '$2 == u { print $1 }'); do
d=$(loginctl show-session "$s" -p Display --value 2>/dev/null)
if [ -n "$d" ]; then export DISPLAY="$d"; break; fi
done
fi
if [ -z "${DISPLAY:-}" ]; then
for pid in $(pgrep -u "$uid" 2>/dev/null); do
from_environ "$pid" && break
done
fi
: "${XAUTHORITY:=${HOME}/.Xauthority}"
export XAUTHORITY
exec "$@"
@@ -1,29 +0,0 @@
#!/bin/bash
# zephyrus-touchpad reset | toggle — apply the touchpad's settings again, or switch it on or off.
# Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
#
# The settings themselves are an X input class (/etc/X11/xorg.conf.d/30-asus-zephyrus-g14-touchpad.conf),
# which X applies every time the device appears — after a resume too, which is what the predecessor's
# sleep hook existed for. This is the manual form, bound to the touchpad key.
set -u
here=$(dirname "$0")
name=$("$here/zephyrus-session" xinput list --name-only 2>/dev/null | grep -m1 -i 'touchpad')
[ -n "$name" ] || { echo "zephyrus-touchpad: no touchpad in this session" >&2; exit 1; }
x() { "$here/zephyrus-session" xinput "$@"; }
case "${1:-reset}" in
reset)
x set-prop "$name" "libinput Tapping Enabled" 1
x set-prop "$name" "libinput Natural Scrolling Enabled" 1
x set-prop "$name" "libinput Accel Speed" 0.15
x enable "$name"
"$here/zephyrus-session" "$here/zephyrus-notify" 7779 "Touchpad: reset"
;;
toggle)
if x list-props "$name" | grep -q 'Device Enabled ([0-9]*):[[:space:]]*1'; then
x disable "$name"; "$here/zephyrus-session" "$here/zephyrus-notify" 7779 "Touchpad: off"
else
x enable "$name"; "$here/zephyrus-session" "$here/zephyrus-notify" 7779 "Touchpad: on"
fi
;;
*) echo "usage: zephyrus-touchpad reset | toggle" >&2; exit 2 ;;
esac
-5
View File
@@ -1,5 +0,0 @@
module asuszephyrusg14
go 1.22
require git.novox.be/novox/mesh-sdk/go v0.1.6
-2
View File
@@ -1,2 +0,0 @@
git.novox.be/novox/mesh-sdk/go v0.1.6 h1:9qzdYONYbJdWcu6sxQcq9v1LI0JxcfkiKYkMUzJSkVQ=
git.novox.be/novox/mesh-sdk/go v0.1.6/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
-301
View File
@@ -1,301 +0,0 @@
{
"module": "asus-zephyrus-g14",
"version": "1",
"capabilities": [
"package-manager",
"service-manager"
],
"requires": [
"x11-display"
],
"emits": [
"profile.switched"
],
"tools": [
"zephyrus_brightness",
"zephyrus_battery",
"zephyrus_charge_limit",
"zephyrus_gpu_mode",
"zephyrus_profile",
"zephyrus_thermals",
"zephyrus_power_draw",
"zephyrus_profile_policy",
"zephyrus_fan_curves",
"zephyrus_keys",
"zephyrus_check"
],
"resources": [
{
"id": "asusctl",
"type": "package",
"package": "asusctl"
},
{
"id": "playerctl",
"type": "package",
"package": "playerctl"
},
{
"id": "asusd",
"type": "service",
"unit": "asusd.service",
"state": "running"
},
{
"id": "supergfxd",
"type": "service",
"unit": "supergfxd.service",
"state": "running",
"boot": "enabled"
},
{
"id": "scripts",
"type": "archive",
"path": "/usr/local/lib/asus-zephyrus-g14",
"artifact": "scripts"
},
{
"id": "nvidia-options",
"type": "file",
"path": "/etc/modprobe.d/g14-nvidia-power.conf",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The discrete GPU's driver options on the ROG Zephyrus G14 (GA403, RTX 40 series, hybrid graphics).\n#\n# NVreg_DynamicPowerManagement=0x00 turns runtime D3 off. With it on, a change of power source sends\n# the driver an ACPI notification it fails to handle on this model (\"RmHandleDNotifierEvent: Failed to\n# handle ACPI D-Notifier event, status=0x62\"), and the GPU stops making progress until the machine is\n# powered off. Off costs a few idle watts in hybrid mode and keeps the machine up.\n#\n# NVreg_PreserveVideoMemoryAllocations=1 saves video memory across suspend, so what used the GPU still\n# works after waking. It needs nvidia-suspend, -hibernate and -resume to run around a sleep, which this\n# module's drop-ins on the sleep services ask for.\n#\n# A change here applies when the driver next loads: at the next boot.\noptions nvidia NVreg_PreserveVideoMemoryAllocations=1\noptions nvidia NVreg_DynamicPowerManagement=0x00\n"
},
{
"id": "video-options",
"type": "file",
"path": "/etc/modprobe.d/video-brightness-switch.conf",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The ACPI video driver does not change the backlight itself on the brightness keys: on this model it\n# moves the wrong one. The keys are triggerhappy's (see /etc/triggerhappy/triggers.d/asus-g14.conf).\n# Applies when the module next loads: at the next boot.\noptions video brightness_switch_enabled=0\n"
},
{
"id": "suspend-drop-ins",
"type": "directory",
"path": "/etc/systemd/system/systemd-suspend.service.d",
"mode": "0755"
},
{
"id": "nvidia-on-suspend",
"type": "file",
"path": "/etc/systemd/system/systemd-suspend.service.d/asus-zephyrus-g14-nvidia.conf",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The NVIDIA driver's own sleep actions, asked for by the sleep itself rather than enabled as\n# links: the mesh declares files and never makes links (novox/hq ADR 0012), and the host's service\n# shape must not start these units by hand, which would put the GPU to sleep with the machine awake.\n[Unit]\nWants=nvidia-suspend.service nvidia-resume.service\n"
},
{
"id": "hibernate-drop-ins",
"type": "directory",
"path": "/etc/systemd/system/systemd-hibernate.service.d",
"mode": "0755"
},
{
"id": "nvidia-on-hibernate",
"type": "file",
"path": "/etc/systemd/system/systemd-hibernate.service.d/asus-zephyrus-g14-nvidia.conf",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The NVIDIA driver's own sleep actions, asked for by the sleep itself rather than enabled as\n# links: the mesh declares files and never makes links (novox/hq ADR 0012), and the host's service\n# shape must not start these units by hand, which would put the GPU to sleep with the machine awake.\n[Unit]\nWants=nvidia-hibernate.service nvidia-resume.service\n"
},
{
"id": "suspend-then-hibernate-drop-ins",
"type": "directory",
"path": "/etc/systemd/system/systemd-suspend-then-hibernate.service.d",
"mode": "0755"
},
{
"id": "nvidia-on-suspend-then-hibernate",
"type": "file",
"path": "/etc/systemd/system/systemd-suspend-then-hibernate.service.d/asus-zephyrus-g14-nvidia.conf",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The NVIDIA driver's own sleep actions, asked for by the sleep itself rather than enabled as\n# links: the mesh declares files and never makes links (novox/hq ADR 0012), and the host's service\n# shape must not start these units by hand, which would put the GPU to sleep with the machine awake.\n[Unit]\nWants=nvidia-suspend-then-hibernate.service nvidia-resume.service\n"
},
{
"id": "powerd-drop-ins",
"type": "directory",
"path": "/etc/systemd/system/nvidia-powerd.service.d",
"mode": "0755"
},
{
"id": "powerd-opt-in",
"type": "file",
"path": "/etc/systemd/system/nvidia-powerd.service.d/asus-zephyrus-g14.conf",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# nvidia-powerd (Dynamic Boost) was the first error in the chain that hung this model's GPU on a change\n# of power source, and asusd starts it on mains. It runs only when the kernel command line says\n# zephyrus.nvidia-powerd — an explicit opt-in, at boot.\n[Unit]\nConditionKernelCommandLine=zephyrus.nvidia-powerd\n"
},
{
"id": "logind-drop-ins",
"type": "directory",
"path": "/etc/systemd/logind.conf.d",
"mode": "0755"
},
{
"id": "logind-power",
"type": "file",
"path": "/etc/systemd/logind.conf.d/power.conf",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The power key and the lid suspend, on battery, on mains and docked alike.\n[Login]\nHandlePowerKey=suspend\nHandleLidSwitch=suspend\nHandleLidSwitchExternalPower=suspend\nHandleLidSwitchDocked=suspend\n"
},
{
"id": "logind",
"type": "service",
"unit": "systemd-logind.service",
"reload-on": [
"logind-power"
]
},
{
"id": "backlight-rule",
"type": "file",
"path": "/etc/udev/rules.d/90-backlight.rules",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The backlights are writable by the video group, so the brightness keys and the module's brightness tool\n# move the panel without root.\nACTION==\"add\", SUBSYSTEM==\"backlight\", RUN+=\"/usr/bin/chgrp video /sys/class/backlight/%k/brightness\", RUN+=\"/usr/bin/chmod g+w /sys/class/backlight/%k/brightness\"\n"
},
{
"id": "udev",
"type": "service",
"unit": "systemd-udevd.service",
"reload-on": [
"backlight-rule"
]
},
{
"id": "triggerhappy-drop-ins",
"type": "directory",
"path": "/etc/systemd/system/triggerhappy.service.d",
"mode": "0755"
},
{
"id": "triggerhappy-as-account",
"type": "file",
"path": "/etc/systemd/system/triggerhappy.service.d/asus-zephyrus-g14.conf",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# triggerhappy runs the vendor-key triggers as the operator's account, not as root: it opens the input\n# devices first and then drops to the account with its groups (input, video), so the triggers reach the\n# account's own session bus and the panel through the video group, with no su and no hard-coded user.\n[Service]\nExecStart=\nExecStart=/usr/bin/thd --triggers /etc/triggerhappy/triggers.d/ --socket /run/thd.socket --user ${machine:account} --deviceglob /dev/input/event*\n"
},
{
"id": "vendor-keys",
"type": "file",
"path": "/etc/triggerhappy/triggers.d/asus-g14.conf",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The ROG Zephyrus G14's vendor keys, which reach no X client. Run as the operator's account (see the\n# module's drop-in on triggerhappy.service).\nKEY_PROG1\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-session /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-media play-pause\nKEY_PROG3\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-session /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-media previous\nKEY_PROG4\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-session /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-media next\nKEY_BRIGHTNESSDOWN\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-backlight -\nKEY_BRIGHTNESSDOWN\t2\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-backlight -\nKEY_BRIGHTNESSUP\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-backlight +\nKEY_BRIGHTNESSUP\t2\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-backlight +\nKEY_F21\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-touchpad reset\n"
},
{
"id": "triggerhappy",
"type": "service",
"unit": "triggerhappy.service",
"state": "running",
"boot": "enabled",
"restart-on": [
"triggerhappy-as-account",
"vendor-keys",
"scripts",
"touchpad-on-resume",
"touchpad-after-suspend",
"touchpad-after-hibernate",
"touchpad-after-suspend-then-hibernate"
]
},
{
"id": "upower-package",
"type": "package",
"package": "upower"
},
{
"id": "upower-drop-ins",
"type": "directory",
"path": "/etc/UPower/UPower.conf.d",
"mode": "0755"
},
{
"id": "low-battery",
"type": "file",
"path": "/etc/UPower/UPower.conf.d/50-asus-zephyrus-g14.conf",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# On low battery the machine suspends rather than powering off, at 7 % — s2idle still draws a little,\n# so it leaves headroom. A drop-in over the package's own UPower.conf, which stays the package's.\n[UPower]\nUsePercentageForPolicy=true\nPercentageLow=15.0\nPercentageCritical=10.0\nPercentageAction=7.0\nCriticalPowerAction=Suspend\nAllowRiskyCriticalPowerAction=true\n"
},
{
"id": "upower",
"type": "service",
"unit": "upower.service",
"state": "running",
"boot": "enabled",
"restart-on": [
"low-battery"
]
},
{
"id": "xorg-drop-ins",
"type": "directory",
"path": "/etc/X11/xorg.conf.d",
"mode": "0755"
},
{
"id": "touchpad",
"type": "file",
"path": "/etc/X11/xorg.conf.d/30-asus-zephyrus-g14-touchpad.conf",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The touchpad's settings, applied by X every time the device appears — at login and after every\n# resume, when the device is initialised again. This replaces the predecessor's sleep hook, which ran\n# xinput after a resume as a named person on a guessed display.\nSection \"InputClass\"\n Identifier \"asus-zephyrus-g14 touchpad\"\n MatchIsTouchpad \"on\"\n Option \"Tapping\" \"on\"\n Option \"NaturalScrolling\" \"true\"\n Option \"AccelSpeed\" \"0.15\"\nEndSection\n"
},
{
"id": "touchpad-on-resume",
"type": "file",
"path": "/etc/systemd/system/asus-zephyrus-g14-touchpad-resume.service",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# After a resume, the touchpad's settings once more in the operator's session. X applies the module's\n# input class whenever the device appears, which covers a resume that initialises the device again;\n# this covers one that does not, as the predecessor's sleep hook did. Started by the sleep services\n# themselves (their asus-zephyrus-g14-touchpad.conf drop-ins), never enabled, and ordered after them,\n# so it runs once the machine is awake.\n[Unit]\nDescription=Touchpad settings after resume (asus-zephyrus-g14)\nAfter=systemd-suspend.service systemd-hibernate.service systemd-suspend-then-hibernate.service\n\n[Service]\nType=oneshot\nUser=${machine:account}\nExecStartPre=/bin/sleep 2\nExecStart=/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-touchpad reset\n"
},
{
"id": "touchpad-after-suspend",
"type": "file",
"path": "/etc/systemd/system/systemd-suspend.service.d/asus-zephyrus-g14-touchpad.conf",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The touchpad's settings again once the machine is awake (asus-zephyrus-g14-touchpad-resume.service).\n[Unit]\nWants=asus-zephyrus-g14-touchpad-resume.service\n"
},
{
"id": "touchpad-after-hibernate",
"type": "file",
"path": "/etc/systemd/system/systemd-hibernate.service.d/asus-zephyrus-g14-touchpad.conf",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The touchpad's settings again once the machine is awake (asus-zephyrus-g14-touchpad-resume.service).\n[Unit]\nWants=asus-zephyrus-g14-touchpad-resume.service\n"
},
{
"id": "touchpad-after-suspend-then-hibernate",
"type": "file",
"path": "/etc/systemd/system/systemd-suspend-then-hibernate.service.d/asus-zephyrus-g14-touchpad.conf",
"mode": "0644",
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The touchpad's settings again once the machine is awake (asus-zephyrus-g14-touchpad-resume.service).\n[Unit]\nWants=asus-zephyrus-g14-touchpad-resume.service\n"
},
{
"id": "i3-vendor-keys",
"type": "file",
"path": "${machine:account-home}/.config/i3/config.d/10-asus.conf",
"owner": "${machine:account}",
"mode": "0644",
"content": "# The laptop's own lines in i3 (module asus-zephyrus-g14, novox/hq ADR 0208, ADR 0210). Owned by the\n# mesh: replaced at every push. Once the controller places contributions to node-display-session\n# (ADR 0210), these become the module's contribution instead of a file in i3's directory.\n#\n# The keys the firmware turns into ordinary key presses. The vendor keys that reach no X client are\n# triggerhappy's (/etc/triggerhappy/triggers.d/asus-g14.conf): M4 and Fn+F4/F5 for media, Fn+F7/F8 for\n# the panel, Fn+F10 for the touchpad. The keyboard backlight (Fn+F2/F3) is the firmware's and asusd's.\n\n# Fn+F6, the screenshot key: the firmware sends Super+Shift+S. Released before it runs, because the\n# screenshot grabs the pointer to select a region, which fails while the key is still held.\nbindsym --release $mod+Shift+s exec --no-startup-id $XDG_CONFIG_HOME/i3/scripts/screenshot.sh\n\n# Fn+F9, the display key: the firmware sends Super+P. Odd workspaces to the panel, even ones to the\n# external output.\nbindsym $mod+p exec --no-startup-id /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-display order\n\n# The keyboard backlight's level, shown when it changes.\nexec --no-startup-id /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-kbd-notify\n"
},
{
"id": "i3-model",
"type": "file",
"path": "${machine:account-home}/.config/i3/config.d/20-g14.conf",
"owner": "${machine:account}",
"mode": "0644",
"content": "# The laptop's own lines in i3 (module asus-zephyrus-g14, novox/hq ADR 0208, ADR 0210). Owned by the\n# mesh: replaced at every push. Once the controller places contributions to node-display-session\n# (ADR 0210), these become the module's contribution instead of a file in i3's directory.\n#\n# The model's panel and touchpad.\n\n# The internal panel is the primary output, where the bars' tray goes. Which monitors are on and where\n# is the display server's (autorandr, run at every session start).\nexec --no-startup-id /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-display primary\n\n# The touchpad's settings again, by hand. X applies them itself whenever the device appears.\nbindsym $mod+Shift+x exec --no-startup-id /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-touchpad reset\n"
}
],
"build": {
"artifacts": [
{
"name": "tools-go",
"kind": "bundle",
"language": "go",
"system": "arch",
"from": "cmd/zephyrus",
"binary": "zephyrus",
"loads": [
"zephyrus"
]
},
{
"name": "scripts",
"kind": "archive",
"from": "files"
}
]
}
}
+33
View File
@@ -0,0 +1,33 @@
# audit-logger's runtime: the shared runtime image, carrying this module's compiled code.
#
# **Built from this module's own directory and nothing else.** The toolkit is in the base image, so
# nothing is copied out of a neighbouring checkout — which is what lets the mesh build this from a
# repository and a path (novox/hq ADR 0069) rather than only on a workstation that happens to have
# the siblings laid out beside it.
# Two bases, named rather than pinned: the image this is COMPILED in, and the image it RUNS in.
# They are different images on purpose — the first carries a compiler and the second must not, or
# every running container would carry one it never invokes. The mesh answers both with the copies it
# holds, because a fingerprint written here would name one particular copy and no other mesh has it
# (novox/hq issue 044). Declared in module.json's `build.on`; deliberately no defaults, so a build
# nobody told stops here and says which module to build first.
ARG BUILD_BASE
ARG RUNTIME_BASE
FROM ${BUILD_BASE} AS build
# Compiled under /app/modules so `@novox/mesh-sdk` resolves upward into the base's own
# node_modules — the module is compiled against exactly the toolkit it will run against.
WORKDIR /app/modules/audit-logger
COPY . .
# The compiler is invoked by its real path rather than through node_modules/.bin, whose entries are
# symlinks to a launcher that requires its library relatively — resolved away when the base image
# was assembled.
RUN node /app/node_modules/typescript/bin/tsc audit.ts index.ts \
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
FROM ${RUNTIME_BASE}
COPY --from=build /app/modules/audit-logger/dist /app/modules/audit-logger/dist
# **Served, not run.** This subscribes on import, and the serve mode binds the broker before it
# imports anything — `run` exists for a step that works offline and exits, and would leave this
# with nothing to subscribe to.
ENV MESH_TOOL_MODULES=/app/modules/audit-logger/dist/index.js
+36 -14
View File
@@ -5,21 +5,27 @@
"consumes": [ "consumes": [
"**" "**"
], ],
"own-secrets": {
"broker": "/var/lib/audit-logger/broker"
},
"build": { "build": {
"on": [
{
"arg": "BUILD_BASE",
"module": "mesh-tools",
"artifact": "build"
},
{
"arg": "RUNTIME_BASE",
"module": "mesh-tools",
"artifact": "runtime"
}
],
"artifacts": [ "artifacts": [
{ {
"name": "code", "name": "runtime",
"kind": "bundle", "kind": "image",
"language": "typescript", "from": "Dockerfile"
"entrypoints": [
"index.js"
],
"loads": [
"index.js"
],
"env": {
"AUDIT_LOG": "${dir:trail}/audit.log"
}
} }
] ]
}, },
@@ -27,13 +33,29 @@
{ {
"id": "state", "id": "state",
"type": "directory", "type": "directory",
"mode": "0700", "path": "/var/lib/audit-logger",
"place": "." "mode": "0700"
}, },
{ {
"id": "trail", "id": "trail",
"type": "directory", "type": "directory",
"path": "/var/lib/audit-logger/trail",
"mode": "0700" "mode": "0700"
},
{
"id": "run",
"type": "container",
"name": "mesh-audit-logger",
"network": "host",
"volumes": [
"/var/lib/audit-logger/broker:/run/secrets/broker:ro",
"/var/lib/audit-logger/trail:/trail"
],
"env": {
"MESH_BROKER_FILE": "/run/secrets/broker",
"AUDIT_LOG": "/trail/audit.log"
},
"artifact": "runtime"
} }
], ],
"capabilities": [ "capabilities": [
+2 -4
View File
@@ -15,7 +15,7 @@ test("audit-logger records every event to the trail as one line each", async ()
const path = join(dir, "audit.log"); const path = join(dir, "audit.log");
// The audit-logger's whole behaviour: consume everything, record it. // The audit-logger's whole behaviour: consume everything, record it.
await on("#", async (event) => record(event, path)); // the pattern index.ts subscribes await on("**", async (event) => record(event, path));
process.env.MESH_MODULE = "umami"; process.env.MESH_MODULE = "umami";
process.env.MESH_NODE = "anchor"; process.env.MESH_NODE = "anchor";
@@ -24,9 +24,7 @@ test("audit-logger records every event to the trail as one line each", async ()
const lines = (await readFile(path, "utf8")).trim().split("\n").map((l) => JSON.parse(l)); const lines = (await readFile(path, "utf8")).trim().split("\n").map((l) => JSON.parse(l));
assert.equal(lines.length, 2); assert.equal(lines.length, 2);
// A module names its events locally (design 29); the module is the `source`, which together with assert.deepEqual(lines.map((l) => l.type), ["umami.site.created", "node.anchor.joined"]);
// the type says whose event it was. This broker does no namespacing, so the type is as emitted.
assert.deepEqual(lines.map((l) => l.type), ["site.created", "node.anchor.joined"]);
assert.equal(lines[0].source, "umami"); assert.equal(lines[0].source, "umami");
assert.equal(lines[0].node, "anchor"); assert.equal(lines[0].node, "anchor");
assert.equal(lines[0].body.domain, "my-app"); assert.equal(lines[0].body.domain, "my-app");
-42
View File
@@ -1,42 +0,0 @@
# avahi
The local network's name and service discovery (mDNS/DNS-SD) as a module (novox/hq to-be 42 Phase 1,
research 027).
## What it owns
- The `avahi` package.
- `avahi-daemon.service`, running and enabled.
## What it improves
It was on all four machines and owned by none. It is now declared, and its tools show why discovery
does not work today:
- **The packet filter drops mDNS.** The mesh's filter has no rule for inbound UDP 5353 on any of the
four machines, so avahi announces this machine but hears no other machine's answers. A browse
finds nothing, and resolving even the machine's own `.local` name times out. A module's `listens`
can reach the private network, this machine or anywhere, but not the local link. Opening the port
to anywhere would answer the internet on a public machine, so the module opens nothing. This needs
a decision in novox/hq: a local-link source scope for `listens`. Until then, `avahi_status` reports
`inbound_mdns_accepted: false`, and browse and resolve say so whenever they hear nothing.
## What it leaves found
- **`nss-mdns` and `/etc/nsswitch.conf`.** An ordinary lookup reaches avahi only through the
`hosts:` line. That line is one ordered list shared by every name source: containers, files, DNS,
mDNS and the resolver daemon. The host can write a marked block into a file, but it cannot add a
member to a line. Owning the whole file would make this module the owner of every machine's name
resolution. On 2026-10-04 all four machines had the same file, with `mdns4_minimal` wired by hand
and nss-mdns installed. Both are left as found, and `avahi_status` reports the wiring.
- `/etc/avahi/avahi-daemon.conf`, including each workstation's hand-set `allow-interfaces`, which
names that machine's own network interface.
## Tools
| tool | | answers |
|---|---|---|
| `avahi_status` | r | the daemon, its version and configuration, the `hosts:` line and whether mdns is on it, nss-mdns, whether the filter accepts inbound 5353, systemd-resolved beside it, and notes |
| `avahi_browse` | r | every service announced in a few seconds (`avahi-browse -prt`), resolved where possible, narrowed to a type |
| `avahi_resolve` | r | a `.local` name through avahi and through the name service side by side, or an address to its name |
| `avahi_services` | r | what this machine publishes from `/etc/avahi/services` |
-353
View File
@@ -1,353 +0,0 @@
package main
// Avahi, the local network's name and service discovery (mDNS/DNS-SD), as a module (novox/hq to-be 42
// Phase 1, research 027: "on all four, owned by none"). The module declares the package and the
// daemon. Two things it does not declare, and these tools report instead:
//
// - **The name service switch.** nss-mdns is what lets an ordinary lookup answer `<host>.local`, and
// it works only through the `hosts:` line of /etc/nsswitch.conf. That line is one ordered list
// shared by every name source on the machine (containers, files, DNS, mDNS, the resolver daemon),
// the host can write a marked block into a file but not a member into a line, and owning the whole
// file would make this module the owner of every machine's name resolution. So both stay as found
// (wired by hand, identically, on all four machines on 2026-10-04) and `avahi_status` says whether
// the wiring is there.
// - **The packet filter.** mDNS is multicast to UDP 5353 on the local link. The mesh's filter has no
// source scope for "the local link" — a module's `listens` reach the private network, this machine
// or anywhere — so it drops what other machines announce, and a browse hears nothing. Opening it to
// anywhere would answer the internet on a public machine. `avahi_status` reports whether inbound
// 5353 is accepted; browse and resolve say so when they hear nothing.
import (
"fmt"
"net"
"regexp"
"sort"
"strconv"
"strings"
)
// The files avahi and the name service read.
const (
DaemonConf = "/etc/avahi/avahi-daemon.conf"
ServicesDir = "/etc/avahi/services"
NSSwitch = "/etc/nsswitch.conf"
Daemon = "avahi-daemon.service"
)
// Status is the daemon, its configuration, the name service's wiring and the filter.
type Status struct {
Daemon map[string]string `json:"daemon"`
Version string `json:"version,omitempty"`
Config map[string]map[string]string `json:"config"`
HostsLine string `json:"nsswitch_hosts"`
MDNSWired bool `json:"nss_mdns_wired"`
NSSMDNS string `json:"nss_mdns_package,omitempty"`
InboundMDNS *bool `json:"inbound_mdns_accepted"`
FilterError string `json:"filter_error,omitempty"`
ResolvedOn bool `json:"systemd_resolved_active"`
Notes []string `json:"notes"`
}
// ParseINI reads avahi-daemon.conf's sections and their set keys; commented keys are defaults.
func ParseINI(text string) map[string]map[string]string {
out := map[string]map[string]string{}
section := ""
for _, l := range lines(text) {
l = strings.TrimSpace(l)
switch {
case strings.HasPrefix(l, "#") || strings.HasPrefix(l, ";"):
case strings.HasPrefix(l, "[") && strings.HasSuffix(l, "]"):
section = strings.Trim(l, "[]")
out[section] = map[string]string{}
default:
if k, v, ok := strings.Cut(l, "="); ok && section != "" {
out[section][strings.TrimSpace(k)] = strings.TrimSpace(v)
}
}
}
return out
}
// HostsLine is the `hosts:` line of nsswitch.conf, and whether an mdns source is on it.
func HostsLine(text string) (string, bool) {
for _, l := range lines(text) {
l = strings.TrimSpace(l)
if !strings.HasPrefix(l, "hosts:") {
continue
}
for _, f := range strings.Fields(strings.TrimPrefix(l, "hosts:")) {
if strings.HasPrefix(f, "mdns") {
return l, true
}
}
return l, false
}
return "", false
}
var mdnsAccept = regexp.MustCompile(`(?m)\budp dport (?:\{[^}\n]*\b(?:5353|mdns)\b[^}\n]*\}|(?:5353|mdns)\b)[^\n]*\baccept\b`)
// InboundMDNS is whether a ruleset accepts UDP 5353 coming in.
func InboundMDNS(ruleset string) bool { return mdnsAccept.MatchString(ruleset) }
// GetStatus reads the daemon, its configuration, the name service and the packet filter.
func (m *Machine) GetStatus() (Status, error) {
s := Status{Config: map[string]map[string]string{}, Notes: []string{}}
d, err := m.unitProps(Daemon, "LoadState", "ActiveState", "SubState", "UnitFileState", "MainPID")
if err != nil {
return s, err
}
s.Daemon = d
if v, err := m.Out("avahi-daemon", "--version"); err == nil {
s.Version = strings.TrimSpace(v)
}
if text, err := m.ReadFile(DaemonConf); err == nil {
s.Config = ParseINI(string(text))
}
if text, err := m.ReadFile(NSSwitch); err == nil {
s.HostsLine, s.MDNSWired = HostsLine(string(text))
}
if r := m.Run(bg(), "pacman", "-Q", "nss-mdns"); r.Status == 0 && r.Err == "" {
s.NSSMDNS = strings.TrimSpace(r.Stdout)
}
if rs, err := m.Root("nft", "list", "ruleset"); err == nil {
open := InboundMDNS(rs)
s.InboundMDNS = &open
if !open {
s.Notes = append(s.Notes, "the packet filter drops inbound UDP 5353: this machine announces itself but hears no other machine's mDNS")
}
} else {
s.FilterError = err.Error()
}
if p, err := m.unitProps("systemd-resolved.service", "ActiveState"); err == nil {
s.ResolvedOn = p["ActiveState"] == "active"
}
if s.MDNSWired && s.NSSMDNS == "" {
s.Notes = append(s.Notes, "nsswitch names mdns and nss-mdns is not installed: those lookups fail")
}
if !s.MDNSWired {
s.Notes = append(s.Notes, "nsswitch does not name mdns: ordinary lookups never ask avahi")
}
return s, nil
}
// Service is one service a browse found.
type Service struct {
Interface string `json:"interface"`
Protocol string `json:"protocol"`
Name string `json:"name"`
Type string `json:"type"`
Domain string `json:"domain"`
Host string `json:"host,omitempty"`
Address string `json:"address,omitempty"`
Port int `json:"port,omitempty"`
TXT []string `json:"txt,omitempty"`
Resolved bool `json:"resolved"`
}
// unescape undoes avahi-browse -p's escaping: a special byte as a backslash and three decimals, any
// other character after a backslash as itself. Decoded as bytes, so a name in UTF-8 stays whole.
func unescape(s string) string {
out := make([]byte, 0, len(s))
for i := 0; i < len(s); i++ {
if s[i] == '\\' {
if d := s[i+1 : min(i+4, len(s))]; len(d) == 3 && isDigits(d) {
n, _ := strconv.Atoi(d)
out = append(out, byte(n))
i += 3
continue
}
if i+1 < len(s) {
out = append(out, s[i+1])
i++
continue
}
}
out = append(out, s[i])
}
return string(out)
}
func isDigits(s string) bool {
for _, c := range s {
if c < '0' || c > '9' {
return false
}
}
return true
}
var txtItem = regexp.MustCompile(`"((?:[^"\\]|\\.)*)"`)
// ParseBrowse reads `avahi-browse -p -r`: `+` lines found, `=` lines resolved; a found service
// that resolved is answered once, resolved.
func ParseBrowse(out string) []Service {
byKey := map[string]int{}
services := []Service{}
for _, l := range lines(out) {
f := strings.Split(l, ";")
if len(f) < 6 || (f[0] != "+" && f[0] != "=") {
continue
}
s := Service{Interface: f[1], Protocol: f[2], Name: unescape(f[3]), Type: f[4], Domain: f[5]}
if f[0] == "=" && len(f) >= 9 {
s.Resolved, s.Host, s.Address = true, f[6], f[7]
s.Port, _ = strconv.Atoi(f[8])
if len(f) >= 10 {
for _, t := range txtItem.FindAllStringSubmatch(strings.Join(f[9:], ";"), -1) {
s.TXT = append(s.TXT, t[1])
}
}
}
key := strings.Join([]string{s.Interface, s.Protocol, s.Name, s.Type, s.Domain}, "\x00")
if i, seen := byKey[key]; seen {
if s.Resolved {
services[i] = s
}
continue
}
byKey[key] = len(services)
services = append(services, s)
}
sort.SliceStable(services, func(i, j int) bool {
if services[i].Type != services[j].Type {
return services[i].Type < services[j].Type
}
return services[i].Name < services[j].Name
})
return services
}
var serviceType = regexp.MustCompile(`^_[A-Za-z0-9-]+\._(tcp|udp)$`)
// Browse listens for a few seconds and answers every service announced, resolved where it could be.
func (m *Machine) Browse(seconds int, kind string) (map[string]any, error) {
args := []string{strconv.Itoa(seconds), "avahi-browse", "-p", "-r", "-t"}
if kind == "" {
args = append(args, "-a")
} else {
if !serviceType.MatchString(kind) {
return nil, fmt.Errorf("%q is not a service type such as _ssh._tcp", kind)
}
args = append(args, kind)
}
r := m.Run(bg(), "timeout", args...)
// timeout's 124 is the listening time ending, which is how a browse that keeps hearing ends.
if r.Err != "" || (r.Status != 0 && r.Status != 124) {
return nil, failure("avahi-browse", "avahi-browse", r)
}
services := ParseBrowse(r.Stdout)
out := map[string]any{"seconds": seconds, "count": len(services), "services": services}
if len(services) == 0 {
out["note"] = m.silenceNote()
}
return out, nil
}
// silenceNote says why nothing may have been heard, from the packet filter when it can be read.
func (m *Machine) silenceNote() string {
if rs, err := m.Root("nft", "list", "ruleset"); err == nil && !InboundMDNS(rs) {
return "nothing was heard, and this machine's packet filter drops inbound UDP 5353 (mDNS): other machines' answers do not reach avahi"
}
return "nothing was heard on the local network"
}
// Resolve asks avahi for a name's address (or an address's name), and the name service the same,
// so an answer avahi has and an ordinary lookup does not shows the switch unwired.
func (m *Machine) Resolve(name, address string) (map[string]any, error) {
if (name == "") == (address == "") {
return nil, fmt.Errorf("give a name or an address")
}
out := map[string]any{}
var r Ran
if name != "" {
if !strings.HasSuffix(name, ".local") {
name += ".local"
}
out["name"] = name
r = m.Run(bg(), "avahi-resolve", "-n", name)
} else {
if net.ParseIP(address) == nil {
return nil, fmt.Errorf("%q is not an address", address)
}
out["address"] = address
r = m.Run(bg(), "avahi-resolve", "-a", address)
}
if r.Err != "" {
return nil, failure("avahi-resolve", "avahi-resolve", r)
}
// avahi-resolve says a failure on stderr and exits 0.
avahi := map[string]any{"answers": []string{}}
for _, l := range lines(r.Stdout) {
if f := strings.Fields(l); len(f) >= 2 {
avahi["answers"] = append(avahi["answers"].([]string), f[1])
}
}
if said := firstLine(r.Stderr); said != "" {
avahi["error"] = said
}
avahi["resolved"] = len(avahi["answers"].([]string)) > 0
out["avahi"] = avahi
if name != "" {
nss := map[string]any{"answers": []string{}}
g := m.Run(bg(), "getent", "hosts", name)
for _, l := range lines(g.Stdout) {
if f := strings.Fields(l); len(f) >= 1 {
nss["answers"] = append(nss["answers"].([]string), f[0])
}
}
nss["resolved"] = len(nss["answers"].([]string)) > 0
out["name_service"] = nss
}
if avahi["resolved"] == false {
out["note"] = m.silenceNote()
}
return out, nil
}
// Published is one service this machine announces from a file of /etc/avahi/services.
type Published struct {
File string `json:"file"`
Name string `json:"name,omitempty"`
Types []string `json:"types"`
Ports []int `json:"ports"`
}
var (
xmlName = regexp.MustCompile(`<name[^>]*>([^<]*)</name>`)
xmlType = regexp.MustCompile(`<type>([^<]*)</type>`)
xmlPort = regexp.MustCompile(`<port>(\d+)</port>`)
)
// Services is what this machine publishes from its service files.
func (m *Machine) Services() (map[string]any, error) {
r := m.Run(bg(), "find", ServicesDir, "-mindepth", "1", "-maxdepth", "1", "-name", "*.service", "-printf", "%f\n")
if r.Err != "" || r.Status != 0 {
if strings.Contains(r.Stderr, "No such file") {
return map[string]any{"directory": ServicesDir, "published": []Published{}}, nil
}
return nil, failure("find", "find", r)
}
pub := []Published{}
names := lines(r.Stdout)
sort.Strings(names)
for _, n := range names {
text, err := m.ReadFile(ServicesDir + "/" + n)
if err != nil {
return nil, err
}
p := Published{File: n, Types: []string{}, Ports: []int{}}
if x := xmlName.FindStringSubmatch(string(text)); x != nil {
p.Name = x[1]
}
for _, t := range xmlType.FindAllStringSubmatch(string(text), -1) {
p.Types = append(p.Types, t[1])
}
for _, x := range xmlPort.FindAllStringSubmatch(string(text), -1) {
port, _ := strconv.Atoi(x[1])
p.Ports = append(p.Ports, port)
}
pub = append(pub, p)
}
return map[string]any{"directory": ServicesDir, "published": pub}, nil
}
-165
View File
@@ -1,165 +0,0 @@
package main
import (
"strings"
"testing"
)
const browse = `+;enp6s0;IPv4;home\032server;_ssh._tcp;local
+;enp6s0;IPv4;Printer\046Co;_ipp._tcp;local
=;enp6s0;IPv4;home\032server;_ssh._tcp;local;home-server.local;192.168.1.10;22;
=;enp6s0;IPv4;Printer\046Co;_ipp._tcp;local;printer.local;192.168.1.20;631;"txtvers=1" "rp=ipp/print"
+;enp6s0;IPv6;Kitchen;_spotify-connect._tcp;local
`
func TestABrowseIsReadResolvedOnceAndUnescaped(t *testing.T) {
s := ParseBrowse(browse)
if len(s) != 3 {
t.Fatalf("%+v", s)
}
by := map[string]Service{}
for _, x := range s {
by[x.Name] = x
}
ssh := by["home server"]
if !ssh.Resolved || ssh.Address != "192.168.1.10" || ssh.Port != 22 || ssh.Host != "home-server.local" {
t.Fatalf("%+v", ssh)
}
ipp := by["Printer.Co"]
if strings.Join(ipp.TXT, ",") != "txtvers=1,rp=ipp/print" {
t.Fatalf("%+v", ipp)
}
if k := by["Kitchen"]; k.Resolved || k.Type != "_spotify-connect._tcp" {
t.Fatalf("%+v", k)
}
if unescape(`caf\195\169`) != "café" || unescape(`a\.b`) != "a.b" {
t.Fatal("unescape")
}
}
func TestABrowseThatHearsNothingSaysTheFilterDropsMDNS(t *testing.T) {
var calls []call
m := machine(fake(func(c call) Ran {
switch c.String() {
case "timeout 5 avahi-browse -p -r -t -a":
return Ran{Status: 124}
case "sudo -n nft list ruleset":
return Ran{Stdout: "table inet mesh {\n chain input {\n type filter hook input priority filter; policy drop;\n tcp dport 22 accept\n }\n}\n"}
}
return Ran{Status: 99}
}, &calls), 1000)
r, err := m.Browse(5, "")
if err != nil || r["count"] != 0 || !strings.Contains(r["note"].(string), "drops inbound UDP 5353") {
t.Fatalf("%v %v", r, err)
}
if _, err := m.Browse(5, "ssh; rm"); err == nil {
t.Fatal("not a service type")
}
}
func TestTheFilterIsReadForAnAcceptedInboundMDNS(t *testing.T) {
for rs, want := range map[string]bool{
"\t\tudp dport 5353 accept\n": true,
"\t\tiifname \"enp6s0\" udp dport { 53, 5353 } accept\n": true,
"\t\tudp dport mdns accept\n": true,
"\t\tudp dport 53 accept\n": false,
"\t\tudp dport 5353 drop\n": false,
"\t\tip saddr 10.0.0.0/8 udp dport 15353 accept\n": false,
} {
if InboundMDNS(rs) != want {
t.Errorf("%q: %v", rs, !want)
}
}
}
func TestStatusNamesTheSwitchTheFilterAndTheDaemon(t *testing.T) {
m := machine(fake(func(c call) Ran {
switch {
case c.name == "systemctl" && c.args[1] == Daemon:
return Ran{Stdout: "LoadState=loaded\nActiveState=active\nUnitFileState=enabled\n"}
case c.name == "systemctl":
return Ran{Stdout: "ActiveState=inactive\n"}
case c.String() == "avahi-daemon --version":
return Ran{Stdout: "avahi-daemon 0.9-rc5\n"}
case c.String() == "pacman -Q nss-mdns":
return Ran{Stdout: "nss-mdns 0.15.1-2\n"}
case c.String() == "sudo -n nft list ruleset":
return Ran{Stdout: "udp dport 53 accept\n"}
}
return Ran{Status: 99}
}, nil), 1000)
files := map[string]string{
DaemonConf: "[server]\nuse-ipv4=yes\n#host-name=foo\nallow-interfaces=enp6s0\n[publish]\npublish-hinfo=no\n",
NSSwitch: "passwd: files\nhosts: mymachines files dns mdns4_minimal [NOTFOUND=return] resolve [!UNAVAIL=return]\n",
}
m.ReadFile = func(p string) ([]byte, error) {
if s, ok := files[p]; ok {
return []byte(s), nil
}
return nil, errNoFile
}
s, err := m.GetStatus()
if err != nil {
t.Fatal(err)
}
if !s.MDNSWired || s.NSSMDNS != "nss-mdns 0.15.1-2" || s.InboundMDNS == nil || *s.InboundMDNS || s.Version != "avahi-daemon 0.9-rc5" {
t.Fatalf("%+v", s)
}
if s.Config["server"]["allow-interfaces"] != "enp6s0" || s.Config["server"]["host-name"] != "" || s.Daemon["ActiveState"] != "active" {
t.Fatalf("%+v", s.Config)
}
if len(s.Notes) != 1 || !strings.Contains(s.Notes[0], "drops inbound UDP 5353") {
t.Fatalf("%v", s.Notes)
}
if _, wired := HostsLine("hosts: files dns\n"); wired {
t.Fatal("no mdns on the line")
}
}
func TestResolveAsksAvahiAndTheNameServiceAndReadsAFailureFromStderr(t *testing.T) {
m := machine(byLine(map[string]Ran{
"avahi-resolve -n printer.local": {Stdout: "printer.local\t192.168.1.20\n"},
"getent hosts printer.local": {Status: 2},
"avahi-resolve -n nowhere.local": {Stderr: "Failed to resolve host name 'nowhere.local': Timeout reached\n"},
"getent hosts nowhere.local": {Status: 2},
"sudo -n nft list ruleset": {Stdout: "udp dport 5353 accept\n"},
"avahi-resolve -a 192.168.1.20": {Stdout: "192.168.1.20\tprinter.local\n"},
}, nil), 1000)
r, err := m.Resolve("printer", "")
if err != nil {
t.Fatal(err)
}
if r["avahi"].(map[string]any)["resolved"] != true || r["name_service"].(map[string]any)["resolved"] != false {
t.Fatalf("%v", r)
}
r, _ = m.Resolve("nowhere.local", "")
if a := r["avahi"].(map[string]any); a["resolved"] != false || !strings.Contains(a["error"].(string), "Timeout reached") || r["note"] != "nothing was heard on the local network" {
t.Fatalf("%v", r)
}
r, _ = m.Resolve("", "192.168.1.20")
if r["avahi"].(map[string]any)["answers"].([]string)[0] != "printer.local" {
t.Fatalf("%v", r)
}
for _, bad := range [][2]string{{"", ""}, {"a", "1.2.3.4"}, {"", "not-an-ip"}} {
if _, err := m.Resolve(bad[0], bad[1]); err == nil {
t.Errorf("%v accepted", bad)
}
}
}
func TestPublishedServicesAreReadFromTheirFiles(t *testing.T) {
m := machine(byLine(map[string]Ran{
"find /etc/avahi/services -mindepth 1 -maxdepth 1 -name *.service -printf %f\n": {Stdout: "ssh.service\n"},
}, nil), 1000)
m.ReadFile = func(string) ([]byte, error) {
return []byte(`<service-group><name replace-wildcards="yes">%h</name><service><type>_ssh._tcp</type><port>22</port></service></service-group>`), nil
}
r, err := m.Services()
if err != nil {
t.Fatal(err)
}
p := r["published"].([]Published)
if len(p) != 1 || p[0].Name != "%h" || p[0].Types[0] != "_ssh._tcp" || p[0].Ports[0] != 22 {
t.Fatalf("%+v", p)
}
}
-289
View File
@@ -1,289 +0,0 @@
package main
// The commands this bundle runs on its machine, and who runs them.
//
// Who asks. The node's tool runtime runs as the operator account, not root (novox/hq ADR 0175 §4),
// and launches this binary as a process of its own (ADR 0188, ADR 0193) with the runtime's words —
// HOME, a PATH, MESH_OPERATOR_ACCOUNT — and no session words. Reading needs nothing more; what only
// root may do goes through `sudo -n`, as the packet filter's, the service manager's and the
// intrusion prevention's tools do (to-be 38 WP4), and the `sudo` module is what declares that the
// account may (to-be 42, research 027). A refusal is named by how it failed, never read as an
// empty answer.
//
// The runner is injected, so every tool is tested over a fake one without the machine.
import (
"bytes"
"context"
"errors"
"fmt"
"io/fs"
"os"
"os/exec"
"strings"
"time"
)
// Ran is what one command did: its output, its exit status, and why it never ran to an answer.
type Ran struct {
Stdout string
Stderr string
Status int
// Err is "ENOENT" when the program is not there, or that it was ended for taking too long.
Err string
}
// Runner runs one command, so the tools can be tested without the machine.
type Runner func(ctx context.Context, name string, args ...string) Ran
// CallTimeout is how long one command may take: below the runtime's thirty-second call limit, so a
// command that hangs is answered as such rather than as a call the runtime gave up on.
const CallTimeout = 20 * time.Second
// outputLimit bounds what one command may hand back, so a runaway listing cannot exhaust the
// process; well above anything a tool answers.
const outputLimit = 16 << 20
type bounded struct {
bytes.Buffer
cut bool
}
func (b *bounded) Write(p []byte) (int, error) {
if room := outputLimit - b.Len(); room < len(p) {
if room > 0 {
b.Buffer.Write(p[:room])
}
b.cut = true
return len(p), nil
}
return b.Buffer.Write(p)
}
// ExecRunner runs a command on this machine, in the C locale so what is parsed is one language.
func ExecRunner(ctx context.Context, name string, args ...string) Ran {
ctx, cancel := context.WithTimeout(ctx, CallTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, name, args...)
cmd.Env = append(os.Environ(), "LC_ALL=C")
var out, errb bounded
cmd.Stdout, cmd.Stderr = &out, &errb
err := cmd.Run()
r := Ran{Stdout: out.String(), Stderr: errb.String()}
if ctx.Err() == context.DeadlineExceeded {
r.Status, r.Err = 124, fmt.Sprintf("no answer within %d s", int(CallTimeout.Seconds()))
return r
}
var exit *exec.ExitError
switch {
case err == nil:
case errors.As(err, &exit):
r.Status = exit.ExitCode()
case errors.Is(err, exec.ErrNotFound) || errors.Is(err, fs.ErrNotExist):
r.Status, r.Err = 127, "ENOENT"
default:
r.Status, r.Err = 126, err.Error()
}
return r
}
// Escalated is the command as it is run: as given when this process is root, else through sudo
// without a prompt.
func Escalated(uid int, name string, args ...string) (string, []string) {
if uid == 0 {
return name, args
}
return "sudo", append([]string{"-n", name}, args...)
}
// Machine is this machine as the tools see it: a runner, who this process is, and its files.
type Machine struct {
Run Runner
UID int
User string
Account string
ReadFile func(path string) ([]byte, error)
Now func() time.Time
Sleep func(time.Duration)
}
// ThisMachine is the machine the runtime launched this bundle on.
func ThisMachine() *Machine {
user := os.Getenv("USER")
if user == "" {
user = os.Getenv("LOGNAME")
}
account := strings.TrimSpace(os.Getenv("MESH_OPERATOR_ACCOUNT"))
if account == "" {
account = user
}
return &Machine{Run: ExecRunner, UID: os.Getuid(), User: user, Account: account, ReadFile: os.ReadFile, Now: time.Now, Sleep: time.Sleep}
}
// Out runs a command that only reads, and fails with what went wrong named.
func (m *Machine) Out(name string, args ...string) (string, error) {
r := m.Run(context.Background(), name, args...)
if r.Status == 0 && r.Err == "" {
return r.Stdout, nil
}
return r.Stdout, failure(name, name, r)
}
// Root runs a command that needs root, escalated when this process is not.
func (m *Machine) Root(name string, args ...string) (string, error) {
program, argv := Escalated(m.UID, name, args...)
r := m.Run(context.Background(), program, argv...)
if r.Status == 0 && r.Err == "" {
return r.Stdout, nil
}
return r.Stdout, failure(name, program, r)
}
// RootRan is Root's raw answer, for a command whose non-zero status is itself an answer.
func (m *Machine) RootRan(name string, args ...string) (Ran, error) {
program, argv := Escalated(m.UID, name, args...)
r := m.Run(context.Background(), program, argv...)
if r.Err != "" || (program == "sudo" && sudoRefused(r)) {
return r, failure(name, program, r)
}
return r, nil
}
func sudoRefused(r Ran) bool {
return strings.HasPrefix(strings.TrimSpace(r.Stderr), "sudo:")
}
// failure names what failed by how it failed: the program missing is a spawn error, sudo missing
// or refusing speaks for itself, and the rest is the command's own first line.
func failure(cmd, program string, r Ran) error {
said := strings.TrimSpace(r.Stderr + "\n" + r.Stdout)
if r.Err == "ENOENT" {
if program == "sudo" {
return fmt.Errorf("%s needs root for this, and sudo is not installed here for the runtime's account to escalate with", cmd)
}
return fmt.Errorf("%s is not installed on this machine", cmd)
}
if r.Err != "" {
return fmt.Errorf("%s did not answer: %s", cmd, r.Err)
}
if program == "sudo" && sudoRefused(r) {
if strings.Contains(said, "command not found") {
return fmt.Errorf("%s is not installed on this machine", cmd)
}
return fmt.Errorf("%s needs root for this and the runtime's account may not run it without a prompt: %s", cmd, firstLine(said))
}
if line := firstLine(said); line != "" {
return fmt.Errorf("%s failed (%d): %s", cmd, r.Status, line)
}
return fmt.Errorf("%s failed with status %d", cmd, r.Status)
}
func firstLine(text string) string {
for _, l := range strings.Split(text, "\n") {
if l = strings.TrimSpace(l); l != "" {
return l
}
}
return ""
}
func lines(text string) []string {
var out []string
for _, l := range strings.Split(text, "\n") {
if l = strings.TrimRight(l, "\r"); strings.TrimSpace(l) != "" {
out = append(out, l)
}
}
return out
}
// text is a string argument; required says whether it may be absent. It is never something a
// command would read as an option, which under sudo would be root's option.
func text(args map[string]any, key string, required bool) (string, error) {
raw, present := args[key]
if !present || raw == nil {
if required {
return "", fmt.Errorf("%s is required", key)
}
return "", nil
}
s, ok := raw.(string)
if !ok {
return "", fmt.Errorf("%s must be a string", key)
}
s = strings.TrimSpace(s)
if required && s == "" {
return "", fmt.Errorf("%s is required", key)
}
if strings.HasPrefix(s, "-") || strings.ContainsRune(s, 0) || strings.ContainsAny(s, "\n\r") {
return "", fmt.Errorf("%s %q is not a value this tool passes on", key, s)
}
return s, nil
}
// whole is a whole-number argument with a default, kept within bounds.
func whole(args map[string]any, key string, def, least, most int) (int, error) {
raw, present := args[key]
if !present || raw == nil {
return def, nil
}
f, ok := raw.(float64)
if !ok || f != float64(int(f)) {
return 0, fmt.Errorf("%s must be a whole number", key)
}
n := int(f)
if n < least {
return 0, fmt.Errorf("%s must be at least %d", key, least)
}
if n > most {
n = most
}
return n, nil
}
// flag is a boolean argument, false when absent.
func flag(args map[string]any, key string) (bool, error) {
raw, present := args[key]
if !present || raw == nil {
return false, nil
}
b, ok := raw.(bool)
if !ok {
return false, fmt.Errorf("%s must be true or false", key)
}
return b, nil
}
// schema is a tool's input: its properties and the ones it requires.
func schema(properties map[string]any, required ...string) map[string]any {
s := map[string]any{"type": "object", "properties": properties}
if len(required) > 0 {
s["required"] = required
}
return s
}
// unitProps reads a unit's properties as systemctl shows them.
func (m *Machine) unitProps(unit string, props ...string) (map[string]string, error) {
args := []string{"show", unit, "--no-pager"}
for _, p := range props {
args = append(args, "--property="+p)
}
out, err := m.Out("systemctl", args...)
if err != nil {
return nil, err
}
return keyValues(out, "="), nil
}
// keyValues reads `key<sep>value` lines; a line without the separator is skipped.
func keyValues(out, sep string) map[string]string {
kv := map[string]string{}
for _, l := range strings.Split(out, "\n") {
k, v, ok := strings.Cut(l, sep)
if ok {
kv[strings.TrimSpace(k)] = strings.TrimSpace(v)
}
}
return kv
}
@@ -1,107 +0,0 @@
package main
import (
"context"
"strings"
"testing"
"time"
)
// call is one command a fake runner was asked to run.
type call struct {
name string
args []string
}
func (c call) String() string {
if len(c.args) == 0 {
return c.name
}
return c.name + " " + strings.Join(c.args, " ")
}
// fake is a runner answering by the command line it is given, recording every call.
func fake(answer func(c call) Ran, calls *[]call) Runner {
return func(_ context.Context, name string, args ...string) Ran {
c := call{name, append([]string(nil), args...)}
if calls != nil {
*calls = append(*calls, c)
}
return answer(c)
}
}
// byLine answers from a table keyed by the whole command line, and refuses anything else as a
// command the test did not expect.
func byLine(table map[string]Ran, calls *[]call) Runner {
return fake(func(c call) Ran {
if r, ok := table[c.String()]; ok {
return r
}
return Ran{Status: 99, Stderr: "unexpected command: " + c.String()}
}, calls)
}
func machine(run Runner, uid int) *Machine {
return &Machine{Run: run, UID: uid, User: "operator", Account: "operator",
ReadFile: func(string) ([]byte, error) { return nil, errNoFile },
Now: func() time.Time { return time.Date(2026, 10, 4, 12, 0, 0, 0, time.UTC) },
Sleep: func(time.Duration) {}}
}
type noFile struct{}
func (noFile) Error() string { return "no such file" }
var errNoFile = noFile{}
func TestAnActNeedingRootGoesThroughSudoWithoutAPromptUnlessThisIsRoot(t *testing.T) {
if p, a := Escalated(1000, "visudo", "-c"); p != "sudo" || strings.Join(a, " ") != "-n visudo -c" {
t.Fatalf("not root: %s %v", p, a)
}
if p, a := Escalated(0, "visudo", "-c"); p != "visudo" || strings.Join(a, " ") != "-c" {
t.Fatalf("root: %s %v", p, a)
}
}
func TestFailuresAreNamedNeverReadAsEmpty(t *testing.T) {
cases := []struct {
r Ran
want string
}{
{Ran{Status: 127, Err: "ENOENT"}, "sudo is not installed here"},
{Ran{Status: 1, Stderr: "sudo: a password is required\n"}, "may not run it without a prompt: sudo: a password is required"},
{Ran{Status: 124, Err: "no answer within 20 s"}, "did not answer: no answer within 20 s"},
{Ran{Status: 2, Stderr: "boom\nmore"}, "failed (2): boom"},
}
for _, c := range cases {
m := machine(fake(func(call) Ran { return c.r }, nil), 1000)
if _, err := m.Root("thing"); err == nil || !strings.Contains(err.Error(), c.want) {
t.Errorf("%+v: %v, want %q", c.r, err, c.want)
}
}
m := machine(fake(func(call) Ran { return Ran{Status: 127, Err: "ENOENT"} }, nil), 1000)
if _, err := m.Out("thing"); err == nil || !strings.Contains(err.Error(), "thing is not installed") {
t.Errorf("a missing program: %v", err)
}
}
func TestAnArgumentIsNeverAnOption(t *testing.T) {
for _, bad := range []any{"-rf", "a\nb", 3.0} {
if _, err := text(map[string]any{"x": bad}, "x", true); err == nil {
t.Errorf("%v was accepted", bad)
}
}
if s, err := text(map[string]any{"x": " ok "}, "x", true); err != nil || s != "ok" {
t.Errorf("a plain value: %q %v", s, err)
}
if _, err := text(map[string]any{}, "x", true); err == nil {
t.Error("a missing required value was accepted")
}
if n, _ := whole(map[string]any{"n": 10000.0}, "n", 5, 1, 100); n != 100 {
t.Errorf("not bounded: %d", n)
}
if _, err := whole(map[string]any{"n": 0.0}, "n", 5, 1, 100); err == nil {
t.Error("below the least was accepted")
}
}
-85
View File
@@ -1,85 +0,0 @@
// avahi's tools bundle (novox/hq to-be 42 Phase 1, research 026/05): a process the node's runtime
// launches and speaks MCP over stdio to, through the Go SDK (ADR 0188, ADR 0193). It reads the
// daemon, the name service's wiring and the packet filter's view of mDNS, browses the local network
// for services, resolves a name, and lists what the machine publishes. It changes nothing.
package main
import (
"context"
"fmt"
"os"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// binaryName is what the build names this bundle's executable: the manifest's `binary`.
const binaryName = "avahi-tools"
func bg() context.Context { return context.Background() }
func main() {
// An empty name serves as the module the runtime names (MESH_SERVED_MODULE): avahi.
if err := stdio.Serve("", tools(ThisMachine())); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func tools(m *Machine) []stdio.Tool {
return []stdio.Tool{
{
Name: "avahi_status",
Description: "The daemon's state and version, its configuration as set, the name service switch's hosts line and whether mdns is on it, " +
"whether nss-mdns is installed, whether the packet filter accepts inbound mDNS (UDP 5353), whether systemd-resolved runs beside it, " +
"and notes naming what keeps discovery from working.",
Input: schema(map[string]any{}),
Run: func(map[string]any) (any, error) { return m.GetStatus() },
},
{
Name: "avahi_browse",
Description: "Listen on the local network for a few seconds (avahi-browse -prt) and answer every service announced, with interface, " +
"protocol, name, type, host, address, port and TXT where it resolved; narrowed to one service type when given. Hearing nothing says why it may be.",
Input: schema(map[string]any{
"seconds": map[string]any{"type": "integer", "description": "how long to listen (default 5, at most 15)"},
"type": map[string]any{"type": "string", "description": "one service type, e.g. _ssh._tcp (optional)"},
}),
Run: func(args map[string]any) (any, error) {
n, err := whole(args, "seconds", 5, 1, 15)
if err != nil {
return nil, err
}
kind, err := text(args, "type", false)
if err != nil {
return nil, err
}
return m.Browse(n, kind)
},
},
{
Name: "avahi_resolve",
Description: "Resolve a .local name to its addresses through avahi, and through the name service (getent) beside it, or an address to its name. " +
"An answer from avahi that the name service lacks shows nsswitch unwired; no answer says why it may be.",
Input: schema(map[string]any{
"name": map[string]any{"type": "string", "description": "a host name; .local is added when missing"},
"address": map[string]any{"type": "string", "description": "an address to name instead"},
}),
Run: func(args map[string]any) (any, error) {
name, err := text(args, "name", false)
if err != nil {
return nil, err
}
address, err := text(args, "address", false)
if err != nil {
return nil, err
}
return m.Resolve(name, address)
},
},
{
Name: "avahi_services",
Description: "What this machine publishes from /etc/avahi/services: each file with the service's name, types and ports.",
Input: schema(map[string]any{}),
Run: func(map[string]any) (any, error) { return m.Services() },
},
}
}
@@ -1,26 +0,0 @@
package main
// The module's shape (novox/hq to-be 42 Phase 1, research 027): the package and the daemon, and
// nothing written into the name service switch or opened in the packet filter — avahi.go says why
// neither can be declared safely today, and the tools report both instead.
import "testing"
func TestItDeclaresThePackageAndTheDaemonOnly(t *testing.T) {
m := manifest(t)
if p := m.resource(t, "package"); p["package"] != "avahi" {
t.Fatalf("%v", p)
}
d := m.resource(t, "daemon")
if d["unit"] != Daemon || d["state"] != "running" || d["boot"] != "enabled" {
t.Fatalf("%v", d)
}
for _, r := range m.Resources {
if r["path"] == NSSwitch || r["package"] == "nss-mdns" {
t.Fatalf("%v: the name service switch is left as found", r["id"])
}
}
if len(m.Resources) != 2 {
t.Fatalf("%v", m.Resources)
}
}
@@ -1,80 +0,0 @@
package main
import (
"encoding/json"
"os"
"testing"
)
type resource map[string]any
type manifestShape struct {
Module string `json:"module"`
Version string `json:"version"`
Capabilities []string `json:"capabilities"`
Claims []map[string]any `json:"claims"`
Tools []string `json:"tools"`
Resources []resource `json:"resources"`
Build struct {
Artifacts []map[string]any `json:"artifacts"`
} `json:"build"`
}
func manifest(t *testing.T) manifestShape {
t.Helper()
raw, err := os.ReadFile("../../module.json")
if err != nil {
t.Fatal(err)
}
var m manifestShape
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatal(err)
}
return m
}
func (m manifestShape) resource(t *testing.T, id string) resource {
t.Helper()
for _, r := range m.Resources {
if r["id"] == id {
return r
}
}
t.Fatalf("no resource %s", id)
return nil
}
// TestToolsAreTheManifests holds the served tools and the manifest's list to one another, and the
// bundle to the shape the builder compiles and the runtime loads.
func TestToolsAreTheManifests(t *testing.T) {
m := manifest(t)
names := map[string]bool{}
for _, tool := range tools(machine(nil, 1000)) {
if names[tool.Name] {
t.Errorf("%s is served twice", tool.Name)
}
names[tool.Name] = true
}
for _, want := range m.Tools {
if !names[want] {
t.Errorf("the manifest lists %s and the bundle does not serve it", want)
}
delete(names, want)
}
if len(names) != 0 {
t.Errorf("served and not listed: %v", names)
}
var tools map[string]any
for _, a := range m.Build.Artifacts {
if a["name"] == "tools" {
tools = a
}
}
if tools == nil || tools["kind"] != "bundle" || tools["language"] != "go" || tools["system"] != "arch" ||
tools["from"] != "cmd/"+binaryName || tools["binary"] != binaryName {
t.Fatalf("the tools artifact: %v", tools)
}
if loads, _ := tools["loads"].([]any); len(loads) != 1 || loads[0] != binaryName {
t.Fatalf("loads: %v", tools["loads"])
}
}
-5
View File
@@ -1,5 +0,0 @@
module avahi
go 1.22
require git.novox.be/novox/mesh-sdk/go v0.1.6
-2
View File
@@ -1,2 +0,0 @@
git.novox.be/novox/mesh-sdk/go v0.1.6 h1:9qzdYONYbJdWcu6sxQcq9v1LI0JxcfkiKYkMUzJSkVQ=
git.novox.be/novox/mesh-sdk/go v0.1.6/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
-43
View File
@@ -1,43 +0,0 @@
{
"module": "avahi",
"version": "1",
"capabilities": [
"package-manager",
"service-manager"
],
"tools": [
"avahi_status",
"avahi_browse",
"avahi_resolve",
"avahi_services"
],
"resources": [
{
"id": "package",
"type": "package",
"package": "avahi"
},
{
"id": "daemon",
"type": "service",
"unit": "avahi-daemon.service",
"state": "running",
"boot": "enabled"
}
],
"build": {
"artifacts": [
{
"name": "tools",
"kind": "bundle",
"language": "go",
"system": "arch",
"from": "cmd/avahi-tools",
"binary": "avahi-tools",
"loads": [
"avahi-tools"
]
}
]
}
}
+24
View File
@@ -0,0 +1,24 @@
# baserow's runtime: the tool runtime, carrying this module's compiled code.
#
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
# the base images, published like any other artifact — which is what makes this buildable by the
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
# happens to have the siblings.
#
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
ARG BUILD_BASE
ARG RUNTIME_BASE
FROM ${BUILD_BASE} AS build
WORKDIR /app/modules/baserow
COPY . .
RUN node /app/node_modules/typescript/bin/tsc client.ts tools/index.ts \
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
FROM ${RUNTIME_BASE}
COPY --from=build /app/modules/baserow/dist /app/modules/baserow/dist
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
# the convention novox/hq issues 060/061 settled.
ENV MESH_TOOL_MODULES=/app/modules/baserow/dist/tools/index.js
+24 -55
View File
@@ -2,15 +2,12 @@
// module's tools and anything else baserow-specific import it; nothing outside baserow does. // module's tools and anything else baserow-specific import it; nothing outside baserow does.
// //
// Baserow authenticates a person with email + password, exchanged for a JWT at /api/user/token-auth/. // Baserow authenticates a person with email + password, exchanged for a JWT at /api/user/token-auth/.
// The standard image creates no admin from env, so the account is one a person made in Baserow: its // Those credentials are the mesh's own: a person signs up in Baserow (the standard image creates no
// password is the module's `admin` secret, accepted from the operator, and its email and the public // admin from env), and the credential is placed in the runtime config file the mesh mounts. Until
// host Baserow answers to reach the runtime config file the mesh mounts (the email from the // that happens fromEnv throws and the module simply exposes no tools — the same dormant-until-
// assignment's settings). Until both are there fromEnv throws and the module exposes no tools — the // configured shape gitea uses for its token.
// same dormant-until-configured shape gitea uses for its token.
import { readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import { request as httpRequest } from "node:http";
import { request as httpsRequest } from "node:https";
export interface BaserowApplication { export interface BaserowApplication {
id: number; id: number;
@@ -71,63 +68,35 @@ export class BaserowClient {
return h; return h;
} }
/** /** Exchange email + password for a JWT, caching it for the client's lifetime. Handles both the
* One HTTP exchange. Not `fetch`: Node's fetch drops a caller's Host header and sends the URL's
* own, and Baserow answers only the host of its BASEROW_PUBLIC_URL — any other Host is looked up
* as a published builder site and gets 404, `/api/_health/` included. A co-located caller reaching
* it by container name must present the public host, so the request is made with node:http, which
* sends the Host it is given.
*/
private send(path: string, method: string, headers: Record<string, string>, body?: string): Promise<{ status: number; text: string }> {
const url = new URL(`${this.baseUrl}${path}`);
const request = url.protocol === "https:" ? httpsRequest : httpRequest;
// A length, never chunked: Baserow's server reads a chunked body as empty.
const sent = body === undefined ? headers : { ...headers, "Content-Length": String(Buffer.byteLength(body)) };
return new Promise((resolve, reject) => {
const req = request(url, { method, headers: sent }, (res) => {
let text = "";
res.setEncoding("utf8");
res.on("data", (chunk: string) => (text += chunk));
res.on("end", () => resolve({ status: res.statusCode ?? 0, text }));
res.on("error", reject);
});
req.on("error", reject);
if (body !== undefined) req.write(body);
req.end();
});
}
/** Exchange email + password for a JWT, caching it until Baserow refuses it. Handles both the
* older `{ token }` and the newer `{ access_token }` response shapes. */ * older `{ token }` and the newer `{ access_token }` response shapes. */
async authenticate(): Promise<string> { async authenticate(): Promise<string> {
if (this.token) return this.token; if (this.token) return this.token;
const res = await this.send( const res = await fetch(`${this.baseUrl}/api/user/token-auth/`, {
"/api/user/token-auth/", method: "POST",
"POST", headers: this.headers(),
this.headers(), body: JSON.stringify({ email: this.email, password: this.password }),
JSON.stringify({ email: this.email, password: this.password }), });
); if (!res.ok) throw new Error(`baserow auth failed: ${res.status} ${await res.text()}`);
if (res.status < 200 || res.status >= 300) throw new Error(`baserow auth failed: ${res.status} ${res.text}`); const data = (await res.json()) as { token?: string; access_token?: string };
const data = JSON.parse(res.text) as { token?: string; access_token?: string };
const token = data.access_token ?? data.token; const token = data.access_token ?? data.token;
if (!token) throw new Error("baserow auth returned no token"); if (!token) throw new Error("baserow auth returned no token");
this.token = token; this.token = token;
return token; return token;
} }
/** An authenticated GET. A refused token is dropped and the call made once more with a fresh one: private async authed<T>(path: string, options: RequestInit = {}): Promise<T> {
* Baserow's access tokens expire after minutes, and the runtime lives for weeks. */ const token = await this.authenticate();
private async authed<T>(path: string): Promise<T> { const res = await fetch(`${this.baseUrl}${path}`, {
for (let attempt = 0; ; attempt++) { ...options,
const token = await this.authenticate(); headers: this.headers({
const res = await this.send(path, "GET", this.headers({ Authorization: `JWT ${token}` })); Authorization: `JWT ${token}`,
if (res.status === 401 && attempt === 0) { ...(options.headers as Record<string, string> | undefined),
this.token = null; }),
continue; });
} if (!res.ok) throw new Error(`baserow ${path}: ${res.status} ${await res.text()}`);
if (res.status < 200 || res.status >= 300) throw new Error(`baserow ${path}: ${res.status} ${res.text}`); const text = await res.text();
return (res.text ? JSON.parse(res.text) : null) as T; return (text ? JSON.parse(text) : null) as T;
}
} }
/** The applications (databases) the account can see, across all its workspaces. */ /** The applications (databases) the account can see, across all its workspaces. */
+54 -31
View File
@@ -18,14 +18,15 @@
} }
}, },
"binds": { "binds": {
"postgres-database": "${dir:state}/database.json", "postgres-database": "/var/lib/baserow/database.json",
"route": "${dir:state}/route.json" "route": "/var/lib/baserow/route.json"
}, },
"secrets": { "secrets": {
"postgres-database": "${dir:state}/database.secret" "postgres-database": "/var/lib/baserow/database.secret"
}, },
"own-secrets": { "own-secrets": {
"admin": "${dir:state}/admin.secret" "secret-key": "/var/lib/baserow/secret-key.secret",
"broker": "/var/lib/mesh/baserow/broker"
}, },
"listens": [ "listens": [
{ {
@@ -33,34 +34,35 @@
"port": 80, "port": 80,
"protocol": "tcp", "protocol": "tcp",
"from": "mesh", "from": "mesh",
"why": "the Baserow web UI and REST API, served by the image's own Caddy; a public name is the route's" "why": "the Baserow web UI and REST API; a public name is a route grant later"
} }
], ],
"resources": [ "resources": [
{ {
"id": "mesh-state", "id": "mesh-state",
"type": "directory", "type": "directory",
"mode": "0700", "path": "/var/lib/mesh/baserow",
"place": "mesh" "mode": "0700"
}, },
{ {
"id": "state", "id": "state",
"type": "directory", "type": "directory",
"mode": "0700", "path": "/var/lib/baserow",
"place": "." "mode": "0700"
}, },
{ {
"id": "data", "id": "data",
"type": "directory", "type": "directory",
"path": "/services/baserow/data",
"mode": "0755", "mode": "0755",
"owner": "9999:9999" "owner": "9999:9999"
}, },
{ {
"id": "server-env", "id": "server-env",
"type": "file", "type": "file",
"path": "${dir:state}/server.env", "path": "/var/lib/baserow/server.env",
"mode": "0600", "mode": "0600",
"content": "DATABASE_HOST=${bound:postgres-database:at}\nDATABASE_PORT=${bound:postgres-database:port}\nDATABASE_NAME=${bound:postgres-database:as}\nDATABASE_USER=${bound:postgres-database:as}\nDATABASE_PASSWORD_FILE=/run/secrets/database\nDISABLE_EMBEDDED_PSQL=true\nBASEROW_PUBLIC_URL=https://${bound:route:name}\n" "content": "DATABASE_HOST=${bound:postgres-database:at}\nDATABASE_PORT=${bound:postgres-database:port}\nDATABASE_NAME=${bound:postgres-database:as}\nDATABASE_USER=${bound:postgres-database:as}\nDATABASE_PASSWORD=${secret:postgres-database}\nSECRET_KEY=${secret:secret-key}\nBASEROW_PUBLIC_URL=http://localhost\n"
}, },
{ {
"id": "net", "id": "net",
@@ -71,44 +73,65 @@
"id": "server", "id": "server",
"type": "container", "type": "container",
"name": "baserow", "name": "baserow",
"image": "baserow/baserow@sha256:263ea6c4b72c9eccabcd975ffe9fdebf23913a293a514bec6a3897a5e0a5a080", "image": "baserow/baserow@sha256:834424a10413798567f76428f255dc259445b7f8dcec56598c05b4073bb2a124",
"network": "baserow", "network": "baserow",
"env-file": [ "env-file": [
"${dir:state}/server.env" "/var/lib/baserow/server.env"
], ],
"ports": [ "ports": [
"80" "80"
], ],
"volumes": [ "volumes": [
"${dir:data}:/baserow/data", "/services/baserow/data:/baserow/data"
"${dir:state}/database.secret:/run/secrets/database:ro" ],
] "secrets-in-environment": "baserow reads DATABASE_PASSWORD and SECRET_KEY with os.getenv and has no _FILE twin (settings/base.py); not convertible"
}, },
{ {
"id": "runtime-config", "id": "runtime-config",
"type": "file", "type": "file",
"path": "${dir:mesh-state}/config.json", "path": "/var/lib/mesh/baserow/config.json",
"mode": "0600", "mode": "0600",
"content": "{\n \"password\": \"${secret:admin}\",\n \"host\": \"${bound:route:name}\"\n}\n", "content": "{}\n",
"merge": "json" "merge": "json"
},
{
"id": "runtime",
"type": "container",
"name": "mesh-baserow",
"network": "baserow",
"volumes": [
"/var/lib/mesh/baserow/broker:/run/secrets/broker:ro",
"/var/lib/mesh/baserow/config.json:/run/config/config.json:ro"
],
"env": {
"MESH_BROKER_FILE": "/run/secrets/broker",
"MESH_BASEROW_URL": "http://baserow:80",
"MESH_BASEROW_CONFIG_FILE": "/run/config/config.json"
},
"restart-on": [
"runtime-config"
],
"artifact": "runtime"
} }
], ],
"build": { "build": {
"on": [
{
"arg": "BUILD_BASE",
"module": "mesh-tools",
"artifact": "build"
},
{
"arg": "RUNTIME_BASE",
"module": "mesh-tools",
"artifact": "runtime"
}
],
"artifacts": [ "artifacts": [
{ {
"name": "tools", "name": "runtime",
"kind": "bundle", "kind": "image",
"language": "typescript", "from": "Dockerfile"
"entrypoints": [
"tools/index.js"
],
"loads": [
"tools/index.js"
],
"env": {
"MESH_BASEROW_URL": "http://127.0.0.1:${port:80}",
"MESH_BASEROW_CONFIG_FILE": "${dir:mesh-state}/config.json"
}
} }
] ]
} }
+24
View File
@@ -0,0 +1,24 @@
# bazarr's runtime: the tool runtime, carrying this module's compiled code.
#
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
# the base images, published like any other artifact — which is what makes this buildable by the
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
# happens to have the siblings.
#
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
ARG BUILD_BASE
ARG RUNTIME_BASE
FROM ${BUILD_BASE} AS build
WORKDIR /app/modules/bazarr
COPY . .
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts \
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
FROM ${RUNTIME_BASE}
COPY --from=build /app/modules/bazarr/dist /app/modules/bazarr/dist
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
# the convention novox/hq issues 060/061 settled.
ENV MESH_TOOL_MODULES=/app/modules/bazarr/dist/index.js,/app/modules/bazarr/dist/tools/index.js
+173
View File
@@ -0,0 +1,173 @@
// The Bazarr API client — bazarr's own code, living in the module (novox/hq ADR 0039). Bazarr
// manages subtitles for a Sonarr/Radarr library: it tracks which episodes and movies are still
// missing subtitles, searches providers for them, and records what it downloaded. This client
// talks its /api surface (keyed by an X-API-KEY header); bazarr's tools and events import it.
import { readFileSync } from "node:fs";
export interface WantedSubtitle {
kind: "episode" | "movie";
title: string; // series + episode, or movie title
path?: string;
seriesId?: number; // sonarr series id (episodes)
episodeId?: number; // sonarr episode id (episodes)
radarrId?: number; // radarr movie id (movies)
missing: string[]; // language names still missing
}
export interface ProviderSubtitle {
provider: string;
language: string;
hearingImpaired: boolean;
forced: boolean;
score?: number;
release?: string;
subtitle: string; // the opaque token Bazarr uses to download this exact result
}
export interface HistoryEntry {
kind: "episode" | "movie";
id: string; // stable dedup key across polls
title: string;
language?: string;
provider?: string;
path?: string;
timestamp?: string;
description?: string;
}
/** The settings-merged config the mesh delivers (novox/hq ADR 0046): { url, apiKey, token, password, user, ... }. */
function meshConfig(file?: string): Record<string, string> {
if (!file) return {};
try { return JSON.parse(readFileSync(file, "utf8")) as Record<string, string>; }
catch { return {}; }
}
/** Read a secret the mesh mounted at a file path (an own-secret delivered by `secret accept`);
* absent or unreadable yields undefined so callers fall back rather than crash. */
function readSecret(file?: string): string | undefined {
if (!file) return undefined;
try { return readFileSync(file, "utf8").trim(); }
catch { return undefined; }
}
export class BazarrClient {
readonly baseUrl: string;
constructor(
url: string,
private readonly apiKey: string,
) {
this.baseUrl = url.replace(/\/$/, "");
}
/** Build from the module's resolved environment. Bazarr's API is keyed; without URL and key
* there is nothing to talk to, so this throws rather than run half-configured. */
static fromEnv(env: NodeJS.ProcessEnv = process.env): BazarrClient {
const cfg = meshConfig(env.MESH_BAZARR_CONFIG_FILE);
const url = cfg.url ?? env.MESH_BAZARR_URL;
const apiKey = cfg.apiKey ?? readSecret(env.MESH_BAZARR_API_KEY_FILE) ?? env.MESH_BAZARR_API_KEY;
if (!url) throw new Error("no Bazarr URL — set MESH_BAZARR_URL");
if (!apiKey) throw new Error("no Bazarr API key — set MESH_BAZARR_API_KEY");
return new BazarrClient(url, apiKey);
}
private async request(method: string, path: string, params: Record<string, string> = {}): Promise<any> {
const url = new URL(`${this.baseUrl}/api${path}`);
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
const res = await fetch(url.toString(), { method, headers: { "X-API-KEY": this.apiKey, Accept: "application/json" } });
if (!res.ok) throw new Error(`Bazarr API ${method} ${path}: ${res.status} ${await res.text()}`);
// Downloads/patches return an empty body; only GETs carry JSON.
const text = await res.text();
return text ? JSON.parse(text) : {};
}
private get(path: string, params?: Record<string, string>): Promise<any> {
return this.request("GET", path, params);
}
private languageNames(missing: any[]): string[] {
return (missing ?? []).map((m: any) => m?.name ?? m?.code2 ?? m?.code3).filter(Boolean);
}
/** Episodes and movies still missing subtitles — Bazarr's core "what's left to do" list. */
async getWanted(limit = 50): Promise<WantedSubtitle[]> {
const [eps, movies] = await Promise.all([
this.get("/episodes/wanted", { start: "0", length: String(limit) }),
this.get("/movies/wanted", { start: "0", length: String(limit) }),
]);
const episodes: WantedSubtitle[] = (eps?.data ?? []).map((e: any) => ({
kind: "episode" as const,
title: `${e.seriesTitle ?? e.series ?? "Unknown"} — ${e.episodeTitle ?? e.episode_title ?? ""}`.trim(),
path: e.path,
seriesId: e.sonarrSeriesId,
episodeId: e.sonarrEpisodeId,
missing: this.languageNames(e.missing_subtitles),
}));
const films: WantedSubtitle[] = (movies?.data ?? []).map((m: any) => ({
kind: "movie" as const,
title: m.title ?? "Unknown",
path: m.path,
radarrId: m.radarrId,
missing: this.languageNames(m.missing_subtitles),
}));
return [...episodes, ...films];
}
/** Ask providers what subtitles are available for one wanted episode — a manual search. */
async searchEpisode(episodeId: number): Promise<ProviderSubtitle[]> {
const raw = await this.get("/providers/episodes", { episodeid: String(episodeId) });
return this.mapProviderResults(raw);
}
/** Ask providers what subtitles are available for one movie — a manual search. */
async searchMovie(radarrId: number): Promise<ProviderSubtitle[]> {
const raw = await this.get("/providers/movies", { radarrid: String(radarrId) });
return this.mapProviderResults(raw);
}
private mapProviderResults(raw: any): ProviderSubtitle[] {
const list = Array.isArray(raw) ? raw : (raw?.data ?? []);
return list.map((r: any) => ({
provider: r.provider,
language: r.language?.name ?? r.language ?? "unknown",
hearingImpaired: Boolean(r.hearing_impaired ?? r.hi),
forced: Boolean(r.forced),
score: r.score,
release: r.release_info?.[0] ?? r.release_info,
subtitle: r.subtitle,
}));
}
/** Recent subtitle-download history, episodes and movies together, newest first. Each entry
* carries a stable id so the events poller can tell a fresh download from one already seen. */
async getHistory(limit = 40): Promise<HistoryEntry[]> {
const [eps, movies] = await Promise.all([
this.get("/episodes/history", { start: "0", length: String(limit) }),
this.get("/movies/history", { start: "0", length: String(limit) }),
]);
const key = (kind: string, r: any): string =>
`${kind}:${r.timestamp ?? r.parsed_timestamp ?? ""}:${r.subtitles_path ?? r.path ?? ""}:${r.language?.code3 ?? r.language ?? ""}`;
const episodes: HistoryEntry[] = (eps?.data ?? []).map((r: any) => ({
kind: "episode" as const,
id: key("episode", r),
title: `${r.seriesTitle ?? "Unknown"} — ${r.episodeTitle ?? ""}`.trim(),
language: r.language?.name ?? r.language,
provider: r.provider,
path: r.subtitles_path,
timestamp: r.timestamp,
description: r.description,
}));
const films: HistoryEntry[] = (movies?.data ?? []).map((r: any) => ({
kind: "movie" as const,
id: key("movie", r),
title: r.title ?? "Unknown",
language: r.language?.name ?? r.language,
provider: r.provider,
path: r.subtitles_path,
timestamp: r.timestamp,
description: r.description,
}));
return [...episodes, ...films];
}
}
+47
View File
@@ -0,0 +1,47 @@
// bazarr's events. The tool runtime imports this once the broker is bound. Bazarr's one genuinely
// observable thing is a subtitle arriving: it works away in the background, searching providers for
// the missing-subtitle list, and when it succeeds a subtitle appears in its history. That is worth
// announcing to the mesh.
//
// Emits (novox/hq ADR 0041/0042):
// module.bazarr.subtitle.downloaded — a subtitle was fetched for an episode or movie
//
// Bazarr has nothing on the mesh it usefully reacts to (a download completing is Sonarr/Radarr's
// business, and they trigger Bazarr directly), so it consumes nothing — a pure emitter.
//
// The event is observation-based: poll history and diff. Primed silently on the first look, or a
// restart would re-announce the whole recent history as freshly downloaded.
import { emit } from "@novox/mesh-sdk/events";
import { BazarrClient } from "./client.js";
const bazarr = BazarrClient.fromEnv();
const seen = new Set<string>();
let primed = false;
async function pollHistory(): Promise<void> {
const entries = await bazarr.getHistory(40);
for (const entry of entries) {
if (seen.has(entry.id)) continue;
if (primed) {
await emit("subtitle.downloaded", {
kind: entry.kind,
title: entry.title,
language: entry.language,
provider: entry.provider,
path: entry.path,
});
}
seen.add(entry.id);
}
primed = true;
}
const tick = (fn: () => Promise<void>, everyMs: number): void => {
const run = (): void => void fn().catch((err) => console.error(`[bazarr] ${err}`));
setInterval(run, everyMs);
run();
};
tick(pollHistory, 60_000);
console.log("[bazarr] watching subtitle-download history");
+141
View File
@@ -0,0 +1,141 @@
{
"module": "bazarr",
"version": "1",
"capabilities": [
"container-runtime"
],
"emits": [
"subtitle.downloaded"
],
"own-secrets": {
"broker": "/var/lib/mesh/bazarr/broker",
"api-key": "/var/lib/mesh/bazarr/api-key"
},
"listens": [
{
"name": "web",
"port": 6767,
"protocol": "tcp",
"from": "mesh",
"why": "managing subtitles"
}
],
"accesses": [
{
"path": "/services/media/movies",
"mode": "read-write"
},
{
"path": "/services/media/series",
"mode": "read-write"
},
{
"path": "/services/media/anime",
"mode": "read-write"
},
{
"path": "/services/media/downloads",
"mode": "read"
}
],
"resources": [
{
"id": "mesh-state",
"type": "directory",
"path": "/var/lib/mesh/bazarr",
"mode": "0700"
},
{
"id": "config",
"type": "directory",
"path": "/services/bazarr/config",
"mode": "0700",
"owner": "1000:1000"
},
{
"id": "server",
"type": "container",
"name": "bazarr",
"image": "lscr.io/linuxserver/bazarr@sha256:3a820372f19fcb2981ea19fe4b5382934d67414afaba974bce831ddda0a64a02",
"env": {
"PUID": "1000",
"PGID": "1000",
"TZ": "Etc/UTC"
},
"ports": [
"6767"
],
"volumes": [
"/services/bazarr/config:/config",
"/services/media/movies:/movies",
"/services/media/series:/series",
"/services/media/anime:/anime",
"/services/media/downloads:/downloads"
]
},
{
"id": "runtime-config",
"type": "file",
"path": "/var/lib/mesh/bazarr/config.json",
"mode": "0600",
"content": "{}\n",
"merge": "json"
},
{
"id": "runtime",
"type": "container",
"name": "mesh-bazarr",
"network": "host",
"volumes": [
"/var/lib/mesh/bazarr/broker:/run/secrets/broker:ro",
"/var/lib/mesh/bazarr/api-key:/run/secrets/api-key:ro",
"/var/lib/mesh/bazarr/config.json:/run/config/config.json:ro",
"/services/bazarr/config:/var/lib/bazarr/config:ro"
],
"env": {
"MESH_BROKER_FILE": "/run/secrets/broker",
"MESH_BAZARR_URL": "http://127.0.0.1:${port:6767}",
"MESH_BAZARR_API_KEY_FILE": "/run/secrets/api-key",
"MESH_BAZARR_CONFIG_FILE": "/run/config/config.json",
"MESH_BAZARR_CONFIG_DIR": "/var/lib/bazarr/config"
},
"restart-on": [
"runtime-config"
],
"artifact": "runtime"
}
],
"requires": [
"route"
],
"contributes": {
"route": {
"label": "subs",
"endpoint": "web"
}
},
"binds": {
"route": "/var/lib/mesh/bazarr/route.json"
},
"build": {
"on": [
{
"arg": "BUILD_BASE",
"module": "mesh-tools",
"artifact": "build"
},
{
"arg": "RUNTIME_BASE",
"module": "mesh-tools",
"artifact": "runtime"
}
],
"artifacts": [
{
"name": "runtime",
"kind": "image",
"from": "Dockerfile"
}
]
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"name": "@novox/module-bazarr",
"version": "0.1.0",
"description": "bazarr — subtitle management. Its API client, tools and events live here (novox/hq ADR 0039).",
"type": "module",
"private": true,
"dependencies": {
"@novox/mesh-sdk": "^0.1.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
"typescript": "^5.6.0"
}
}
+57
View File
@@ -0,0 +1,57 @@
// bazarr's tools — its own code (novox/hq ADR 0039), importing bazarr's client. They return
// structured data; the mesh serves them through the sdk's tool harness.
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
import { BazarrClient } from "../client.js";
export function getBazarrTools(bazarr: BazarrClient): ToolDefinition[] {
return [
{
name: "bazarr_wanted",
description: "Episodes and movies still missing subtitles, with the languages each still needs.",
input: { limit: { type: "number", description: "max items per kind (default 50)" } },
run: async (args) => {
const wanted = await bazarr.getWanted(args.limit ? Number(args.limit) : 50);
return { count: wanted.length, wanted };
},
},
{
name: "bazarr_search_subtitles",
description: "Manually search subtitle providers for one wanted item — pass an episodeId or a radarrId.",
input: {
episodeId: { type: "number", description: "a Sonarr episode id (from bazarr_wanted)" },
radarrId: { type: "number", description: "a Radarr movie id (from bazarr_wanted)" },
},
run: async (args) => {
if (args.episodeId !== undefined) {
const results = await bazarr.searchEpisode(Number(args.episodeId));
return { kind: "episode", episodeId: Number(args.episodeId), count: results.length, results };
}
if (args.radarrId !== undefined) {
const results = await bazarr.searchMovie(Number(args.radarrId));
return { kind: "movie", radarrId: Number(args.radarrId), count: results.length, results };
}
throw new Error("pass either episodeId or radarrId");
},
},
{
name: "bazarr_history",
description: "Recent subtitle-download history — what was downloaded, for which title, from which provider.",
input: { limit: { type: "number", description: "max entries per kind (default 40)" } },
run: async (args) => {
const history = await bazarr.getHistory(args.limit ? Number(args.limit) : 40);
return { count: history.length, history };
},
},
];
}
// Exposed only when Bazarr is configured; otherwise bazarr contributes no tools rather than
// failing the whole runtime.
registerModuleTools("bazarr", (env) => {
try {
return getBazarrTools(BazarrClient.fromEnv(env));
} catch {
return [];
}
});
@@ -8,8 +8,5 @@
"skipLibCheck": true, "skipLibCheck": true,
"noEmit": true "noEmit": true
}, },
"include": [ "include": ["client.ts", "index.ts", "tools/index.ts"]
"tools/index.ts",
"client.ts"
]
} }
-53
View File
@@ -1,53 +0,0 @@
# bluetooth
Bluetooth on the two workstations (novox/hq research 027/02, to-be 42 phase 2 step 9).
## Owns
| what | where |
|---|---|
| the Bluetooth stack and its daemon | package `bluez` |
| `bluetoothctl`, which the tools speak through | package `bluez-utils` |
| the daemon, running and enabled | `bluetooth.service` |
All official. `/etc/bluetooth/main.conf` is the package's file, unchanged on both workstations
(every setting commented out). The module states nothing in it, so it declares nothing there.
## Improves
- **The stack is declared, not a dependency of something else.** On both workstations `bluez` is
installed only as a dependency. Removing the applet that pulled it in would have left it an orphan
for the next clean-up to take, and Bluetooth with it.
- **An owner for the daemon**, running and enabled on both today with nothing recording why.
- **Headphones from the mesh.** `bluetooth_connect` and `bluetooth_devices` (with battery) answer from
any machine, without the applet.
## Tools
All answer JSON; `(r)` reads, `(a)` acts. They run as the operator account. bluez's bus policy lets
the account act; if it ever refuses (`AccessDenied`), the act is repeated through `sudo -n`. An act
whose output says it failed (`Failed to …`, `org.bluez.Error…`, `not available`) is an error, whatever
bluetoothctl's exit status.
| tool | what |
|---|---|
| `bluetooth_controller` (r) | address, name, powered, discoverable, pairable, discovering |
| `bluetooth_power` (r/a) | read, or switch the controller on or off |
| `bluetooth_devices` (r) | all, paired, connected or trusted devices: kind, paired, bonded, trusted, blocked, connected, battery where reported |
| `bluetooth_scan` (r) | discover for 1 to 15 s (default 8); the unpaired devices found, strongest signal first |
| `bluetooth_connect` / `bluetooth_disconnect` (a) | one device; connect waits up to 15 s |
| `bluetooth_trust` (a) | trust, or untrust |
| `bluetooth_pair` (a) | pair with an agent that confirms nothing (headphones, speakers), then trust. A device that shows a code is paired from the desktop |
| `bluetooth_remove` (a) | forget a device |
## What changes when it is assigned
Nothing on disk on either workstation: both packages are installed, and the service is enabled and
running. `bluez` becomes explicitly the mesh's.
## Leaves as found
- The paired devices and their keys under `/var/lib/bluetooth` (bluez's state).
- `blueman` on both workstations, and its applet, which the window manager's configuration starts.
That line is the `i3` module's to keep or drop.
- `bluez-obex` and the AUR terminal client `bluetuith-bin` (with its `-debug`) on the laptop.
@@ -1,281 +0,0 @@
package main
import (
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
var macAddress = regexp.MustCompile(`^[0-9A-Fa-f]{2}(:[0-9A-Fa-f]{2}){5}$`)
func addressOf(args map[string]any) (string, error) {
a, err := text(args, "address")
if err != nil {
return "", err
}
if !macAddress.MatchString(a) {
return "", fmt.Errorf("%q is not a Bluetooth address (six hex pairs separated by colons)", a)
}
return strings.ToUpper(a), nil
}
var ansi = regexp.MustCompile(`\x1b\[[0-9;]*[A-Za-z]|\x01|\x02`)
// btFailed are the words bluetoothctl uses for an act that did not happen, whatever its exit status.
var btFailed = regexp.MustCompile(`(?m)(Failed to \w+|not available|org\.bluez\.Error\.\w+|No default controller available)`)
// bt runs bluetoothctl once, non-interactively, as the account; bluez's bus policy lets the
// account act, and if it refuses, the act is run through sudo -n.
func bt(timeout time.Duration, args ...string) (string, error) {
c := Cmd{Name: "bluetoothctl", Args: args, Timeout: timeout}
r := run(c)
if strings.Contains(r.Stdout+r.Stderr, "AccessDenied") || strings.Contains(r.Stdout+r.Stderr, "Not authorized") {
c.Root = true
r = run(c)
}
out := ansi.ReplaceAllString(r.Stdout+"\n"+r.Stderr, "")
if r.Error != "" {
return out, failure(c, r)
}
if strings.Contains(out, "No default controller available") {
return out, fmt.Errorf("this machine has no Bluetooth controller bluez can use: none is present, it is blocked (rfkill), or bluetooth.service is not running")
}
if m := btFailed.FindString(out); m != "" || r.Status != 0 {
said := strings.TrimSpace(out)
if said == "" {
said = fmt.Sprintf("exit status %d", r.Status)
}
return out, fmt.Errorf("bluetoothctl %s: %s", strings.Join(args, " "), tail(said, 1000))
}
return out, nil
}
// fields reads bluetoothctl's "\tKey: value" lines; a key seen twice keeps its first value.
func fields(s string) map[string]string {
out := map[string]string{}
for _, l := range strings.Split(s, "\n") {
if !strings.HasPrefix(l, "\t") {
continue
}
k, v, ok := strings.Cut(strings.TrimSpace(l), ":")
if !ok {
continue
}
if _, seen := out[k]; !seen {
out[k] = strings.TrimSpace(v)
}
}
return out
}
func yes(v string) bool { return v == "yes" }
// ControllerAnswer is what bluetooth_controller answers.
type ControllerAnswer struct {
Address string `json:"address"`
Name string `json:"name"`
Alias string `json:"alias"`
Powered bool `json:"powered"`
PowerState string `json:"power_state,omitempty"`
Discoverable bool `json:"discoverable"`
Pairable bool `json:"pairable"`
Discovering bool `json:"discovering"`
}
// Controller answers the default controller.
func Controller() (ControllerAnswer, error) {
out, err := bt(CallTimeout, "show")
if err != nil {
return ControllerAnswer{}, err
}
c := ControllerAnswer{}
for _, l := range strings.Split(out, "\n") {
if f := strings.Fields(l); len(f) >= 2 && f[0] == "Controller" {
c.Address = f[1]
break
}
}
if c.Address == "" {
return ControllerAnswer{}, fmt.Errorf("bluetoothctl show answered no controller: %s", tail(strings.TrimSpace(out), 500))
}
f := fields(out)
c.Name, c.Alias, c.PowerState = f["Name"], f["Alias"], f["PowerState"]
c.Powered, c.Discoverable, c.Pairable, c.Discovering = yes(f["Powered"]), yes(f["Discoverable"]), yes(f["Pairable"]), yes(f["Discovering"])
return c, nil
}
// Power switches the controller on or off.
func Power(on bool) (map[string]any, error) {
word := "off"
if on {
word = "on"
}
if _, err := bt(CallTimeout, "power", word); err != nil {
return nil, err
}
c, err := Controller()
if err != nil {
return nil, err
}
return map[string]any{"powered": c.Powered, "asked": word}, nil
}
// Device is one device bluez knows.
type Device struct {
Address string `json:"address"`
Name string `json:"name"`
Icon string `json:"kind,omitempty"`
Paired bool `json:"paired"`
Bonded bool `json:"bonded"`
Trusted bool `json:"trusted"`
Blocked bool `json:"blocked"`
Connected bool `json:"connected"`
Battery *int `json:"battery_percent,omitempty"`
RSSI *int `json:"rssi,omitempty"`
}
var inParens = regexp.MustCompile(`\((-?[0-9]+)\)`)
// number reads "0x50 (80)" or "-62" as a number.
func number(v string) *int {
if m := inParens.FindStringSubmatch(v); m != nil {
v = m[1]
}
n, err := strconv.Atoi(strings.TrimSpace(v))
if err != nil {
return nil
}
return &n
}
// deviceInfo asks bluez for one device.
func deviceInfo(address string) (Device, error) {
out, err := bt(CallTimeout, "info", address)
if err != nil {
return Device{}, err
}
f := fields(out)
d := Device{Address: address, Name: f["Name"], Icon: f["Icon"], Paired: yes(f["Paired"]), Bonded: yes(f["Bonded"]),
Trusted: yes(f["Trusted"]), Blocked: yes(f["Blocked"]), Connected: yes(f["Connected"])}
if d.Name == "" {
d.Name = f["Alias"]
}
if v, ok := f["Battery Percentage"]; ok {
d.Battery = number(v)
}
if v, ok := f["RSSI"]; ok {
d.RSSI = number(v)
}
return d, nil
}
// listed reads "Device <address> <name>" lines.
func listed(out string) []string {
seen := map[string]bool{}
addrs := []string{}
for _, l := range strings.Split(out, "\n") {
f := strings.Fields(strings.TrimSpace(l))
if len(f) >= 2 && f[0] == "Device" && macAddress.MatchString(f[1]) && !seen[f[1]] {
seen[f[1]] = true
addrs = append(addrs, f[1])
}
}
return addrs
}
// Devices answers the devices bluez knows, with each one's state.
func Devices(which string) (map[string]any, error) {
if err := oneOf("which", which, "all", "paired", "connected", "trusted"); err != nil {
return nil, err
}
args := []string{"devices"}
if which != "all" {
args = append(args, strings.ToUpper(which[:1])+which[1:])
}
out, err := bt(CallTimeout, args...)
if err != nil {
return nil, err
}
devices := []Device{}
for _, a := range listed(out) {
d, err := deviceInfo(a)
if err != nil {
return nil, err
}
devices = append(devices, d)
}
sort.SliceStable(devices, func(i, k int) bool {
if devices[i].Connected != devices[k].Connected {
return devices[i].Connected
}
return devices[i].Name < devices[k].Name
})
return map[string]any{"which": which, "count": len(devices), "devices": devices}, nil
}
// Scan discovers for a while and answers the devices found that are not paired.
func Scan(seconds int) (map[string]any, error) {
// bluetoothctl's own --timeout ends the scan; the command's bound is a little longer.
limit := time.Duration(seconds+4) * time.Second
if _, err := bt(limit, "--timeout", strconv.Itoa(seconds), "scan", "on"); err != nil {
return nil, err
}
out, err := bt(CallTimeout, "devices")
if err != nil {
return nil, err
}
found := []Device{}
for _, a := range listed(out) {
// A device seen a moment ago may have gone out of reach: it is skipped, not a failure.
d, err := deviceInfo(a)
if err != nil {
continue
}
if !d.Paired {
found = append(found, d)
}
}
sort.SliceStable(found, func(i, k int) bool {
ri, rk := -1000, -1000
if found[i].RSSI != nil {
ri = *found[i].RSSI
}
if found[k].RSSI != nil {
rk = *found[k].RSSI
}
return ri > rk
})
return map[string]any{"seconds": seconds, "count": len(found), "found": found}, nil
}
// Act runs one act on a device and answers the device's state afterwards.
func Act(verb, address string) (map[string]any, error) {
limit := CallTimeout
if verb == "connect" {
// A connect waits for the device; bluetoothctl's own timeout ends it first.
if _, err := bt(limit, "--timeout", "15", verb, address); err != nil {
return nil, err
}
} else if _, err := bt(limit, verb, address); err != nil {
return nil, err
}
if verb == "remove" {
return map[string]any{"act": verb, "address": address, "removed": true}, nil
}
d, err := deviceInfo(address)
if err != nil {
return nil, err
}
return map[string]any{"act": verb, "device": d}, nil
}
// Pair pairs a device with an agent that confirms nothing, then trusts it.
func Pair(address string) (map[string]any, error) {
if _, err := bt(CallTimeout, "--agent", "NoInputNoOutput", "--timeout", "15", "pair", address); err != nil {
return nil, err
}
return Act("trust", address)
}
@@ -1,163 +0,0 @@
package main
import (
"strings"
"testing"
)
func TestTheManifestIsTheStackItsToolsAndTheDaemon(t *testing.T) {
m := readManifest(t)
holdsTheBundle(t, m, "bluetooth")
if got := strings.Join(m.packages(), ","); got != "bluez,bluez-utils" {
t.Errorf("packages %s: the applet and the TUI are the operator's", got)
}
s := m.services()["bluetooth.service"]
if s == nil || s["state"] != "running" || s["boot"] != "enabled" {
t.Errorf("%v", s)
}
if len(m.Resources) != 3 {
t.Errorf("no configuration file: /etc/bluetooth/main.conf is the package's, unchanged on both workstations: %v", m.Resources)
}
}
const show = "Controller 4C:82:A9:97:01:8E (public)\n\tName: g14\n\tAlias: g14\n\tPowered: yes\n\tPowerState: on\n\tDiscoverable: no\n\tPairable: yes\n\tUUID: Headset (00001108-0000-1000-8000-00805f9b34fb)\n\tDiscovering: no\n"
func headphones(connected bool) string {
c := "no"
extra := ""
if connected {
c, extra = "yes", "\tBattery Percentage: 0x50 (80)\n"
}
return "Device 80:99:E7:C2:29:DA (public)\n\tName: WH-1000XM4\n\tAlias: WH-1000XM4\n\tIcon: audio-headset\n\tPaired: yes\n\tBonded: yes\n\tTrusted: yes\n\tBlocked: no\n\tConnected: " + c + "\n" + extra + "\tUUID: Headset (00001108-0000-1000-8000-00805f9b34fb)\n"
}
func TestControllerReadsShow(t *testing.T) {
using(t, func(string, Cmd) Result { return ok("\x1b[0;94m" + show) })
c, err := Controller()
if err != nil || c.Address != "4C:82:A9:97:01:8E" || c.Name != "g14" || !c.Powered || c.Discoverable || !c.Pairable {
t.Fatalf("%+v %v", c, err)
}
using(t, func(string, Cmd) Result { return ok("No default controller available\n") })
if _, err := Controller(); err == nil || !strings.Contains(err.Error(), "no Bluetooth controller") {
t.Fatalf("%v", err)
}
}
func TestDevicesAskEachOneAndReportBatteryWhereGiven(t *testing.T) {
f := using(t, func(line string, c Cmd) Result {
switch line {
case "bluetoothctl devices Paired":
return ok("Device 80:99:E7:C2:29:DA WH-1000XM4\nDevice 2C:41:A1:E4:EC:86 Earmuffs\n")
case "bluetoothctl info 80:99:E7:C2:29:DA":
return ok(headphones(true))
}
return ok("Device 2C:41:A1:E4:EC:86 (public)\n\tName: Earmuffs\n\tPaired: yes\n\tConnected: no\n")
})
got, err := Devices("paired")
devices := got["devices"].([]Device)
if err != nil || got["count"] != 2 || !devices[0].Connected || devices[0].Battery == nil || *devices[0].Battery != 80 || devices[1].Battery != nil {
t.Fatalf("%+v %v", got, err)
}
if f.lines()[0] != "bluetoothctl devices Paired" {
t.Errorf("%v", f.lines())
}
if _, err := Devices("nearby"); err == nil {
t.Error("an unknown which")
}
}
func TestAnActThatFailsIsAnErrorWhateverTheExitStatus(t *testing.T) {
using(t, func(line string, c Cmd) Result {
return ok("Attempting to connect to 80:99:E7:C2:29:DA\nFailed to connect: org.bluez.Error.Failed br-connection-page-timeout\n")
})
if _, err := Act("connect", "80:99:E7:C2:29:DA"); err == nil || !strings.Contains(err.Error(), "page-timeout") {
t.Fatalf("%v", err)
}
using(t, func(string, Cmd) Result { return Result{Status: 1, Stdout: "Device 00:11:22:33:44:55 not available\n"} })
if _, err := Act("trust", "00:11:22:33:44:55"); err == nil || !strings.Contains(err.Error(), "not available") {
t.Fatalf("%v", err)
}
}
func TestConnectWaitsWithBluetoothctlsOwnTimeoutAndAnswersTheState(t *testing.T) {
f := using(t, func(line string, c Cmd) Result {
if strings.Contains(line, "connect") {
return ok("Attempting to connect\n[CHG] Device Connected: yes\nConnection successful\n")
}
return ok(headphones(true))
})
got, err := Act("connect", "80:99:E7:C2:29:DA")
if err != nil || !got["device"].(Device).Connected {
t.Fatalf("%v %v", got, err)
}
if f.lines()[0] != "bluetoothctl --timeout 15 connect 80:99:E7:C2:29:DA" || f.asked[0].Timeout != CallTimeout {
t.Errorf("%v", f.lines())
}
}
func TestAnActBluezRefusesTheAccountIsRetriedThroughSudo(t *testing.T) {
f := using(t, func(line string, c Cmd) Result {
if strings.HasPrefix(line, "sudo") {
return ok("Changing power off succeeded\n" + show)
}
return ok("Failed to set power off: org.freedesktop.DBus.Error.AccessDenied\n")
})
if _, err := Power(false); err != nil {
t.Fatal(err)
}
if l := f.lines(); l[0] != "bluetoothctl power off" || l[1] != "sudo -n bluetoothctl power off" {
t.Errorf("%v", l)
}
}
func TestScanIsBoundedAndAnswersUnpairedDevicesStrongestFirst(t *testing.T) {
f := using(t, func(line string, c Cmd) Result {
switch {
case strings.Contains(line, "scan on"):
return ok("Discovery started\n[NEW] Device AA:BB:CC:DD:EE:01 Speaker\n")
case line == "bluetoothctl devices":
return ok("Device 80:99:E7:C2:29:DA WH-1000XM4\nDevice AA:BB:CC:DD:EE:01 Speaker\nDevice AA:BB:CC:DD:EE:02 Phone\nDevice AA:BB:CC:DD:EE:03 Gone\n")
case strings.HasSuffix(line, "EE:01"):
return ok("Device AA:BB:CC:DD:EE:01\n\tName: Speaker\n\tPaired: no\n\tRSSI: 0xffffffc4 (-60)\n")
case strings.HasSuffix(line, "EE:02"):
return ok("Device AA:BB:CC:DD:EE:02\n\tName: Phone\n\tPaired: no\n\tRSSI: -40\n")
case strings.HasSuffix(line, "EE:03"):
return Result{Status: 1, Stdout: "Device AA:BB:CC:DD:EE:03 not available\n"}
}
return ok(headphones(false))
})
got, err := Scan(8)
found := got["found"].([]Device)
if err != nil || len(found) != 2 || found[0].Name != "Phone" || *found[1].RSSI != -60 {
t.Fatalf("%+v %v", got, err)
}
if f.lines()[0] != "bluetoothctl --timeout 8 scan on" || f.asked[0].Timeout.Seconds() != 12 {
t.Errorf("%v %v", f.lines()[0], f.asked[0].Timeout)
}
}
func TestPairUsesAnAgentThatConfirmsNothingAndThenTrusts(t *testing.T) {
f := using(t, func(line string, c Cmd) Result {
if strings.Contains(line, " pair ") {
return ok("Pairing successful\n")
}
return ok(headphones(false))
})
if _, err := Pair("80:99:e7:c2:29:da"); err != nil {
t.Fatal(err)
}
if l := f.lines(); l[0] != "bluetoothctl --agent NoInputNoOutput --timeout 15 pair 80:99:e7:c2:29:da" || l[1] != "bluetoothctl trust 80:99:e7:c2:29:da" {
t.Errorf("%v", l)
}
}
func TestAnAddressIsSixHexPairs(t *testing.T) {
for _, bad := range []string{"", "80:99:E7:C2:29", "80:99:E7:C2:29:DA; rm", "--help", "GG:99:E7:C2:29:DA"} {
if _, err := addressOf(map[string]any{"address": bad}); err == nil {
t.Errorf("%q accepted", bad)
}
}
if a, err := addressOf(map[string]any{"address": "80:99:e7:c2:29:da"}); err != nil || a != "80:99:E7:C2:29:DA" {
t.Errorf("%s %v", a, err)
}
}
@@ -1,352 +0,0 @@
package main
// kit.go is the same file in each of the workstations' tool bundles (fonts, docker-compose, snapd,
// flatpak, cups, bluetooth, xclip, dmenu): how a tool runs a command, escalates, bounds what it
// keeps, and names a failure. A module is built from its own directory, so the file is copied rather
// than shared; a change to one copy is made to all eight.
//
// The rules it holds (novox/hq research 026/05, to-be 38 WP4):
// - the node's tool runtime runs as the operator account, not root (ADR 0175 §4); a command that
// needs root goes through `sudo -n`, never a prompt, and a refusal is named as such;
// - one command gets 20 s, below the runtime's 30 s call limit, and is ended with everything it
// started when it takes longer;
// - each stream is kept to 256 KiB, and the answer says when it was cut;
// - a failure is an error with what went wrong in it, never an empty answer.
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strings"
"syscall"
"time"
)
// Bounds every command is held to.
const (
CallTimeout = 20 * time.Second
MostOutput = 256 << 10
)
// Cmd is one command a tool runs.
type Cmd struct {
Name string
Args []string
// Stdin is written to the command's standard input when not empty.
Stdin string
// Env is added to this process's own environment.
Env []string
// Root says the command needs root: it is run through `sudo -n` when this process is not root.
Root bool
// Timeout replaces CallTimeout; only a background job (jobs.go) asks for longer.
Timeout time.Duration
// Detached is for a program that forks a child which outlives it, as xclip does to keep the
// selection: its streams go to files, because a pipe the child inherits would hold the call open
// until the child exits.
Detached bool
}
// Result is what a command did.
type Result struct {
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
Status int `json:"status"`
// Error is why it did not run to an answer: "not-found" when the program is not there,
// "timeout" when it was ended for taking too long, else the spawn error.
Error string `json:"error,omitempty"`
Truncated bool `json:"truncated,omitempty"`
}
// Runner runs a command. Tests replace it; nothing else does.
type Runner func(Cmd) Result
var (
run Runner = execRun
euid = os.Geteuid
)
// argv is the command as it is run: through sudo without a prompt when it needs root and this
// process is not root.
func argv(c Cmd) (string, []string) {
if c.Root && euid() != 0 {
return "sudo", append([]string{"-n", c.Name}, c.Args...)
}
return c.Name, c.Args
}
// bounded keeps the first MostOutput bytes written to it and notes that more came.
type bounded struct {
b bytes.Buffer
cut bool
}
func (w *bounded) Write(p []byte) (int, error) {
room := MostOutput - w.b.Len()
if room <= 0 {
w.cut = w.cut || len(p) > 0
return len(p), nil
}
if len(p) > room {
w.b.Write(p[:room])
w.cut = true
return len(p), nil
}
return w.b.Write(p)
}
func execRun(c Cmd) Result {
timeout := c.Timeout
if timeout <= 0 {
timeout = CallTimeout
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
name, args := argv(c)
cmd := exec.CommandContext(ctx, name, args...)
cmd.Env = append(append(os.Environ(), "LC_ALL=C"), c.Env...)
if !c.Detached {
// Its own process group, so that ending it on a timeout ends what it started too.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
if cmd.Process != nil {
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
return nil
}
}
cmd.WaitDelay = 2 * time.Second
if c.Stdin != "" {
cmd.Stdin = strings.NewReader(c.Stdin)
}
var out, errs bounded
var outFile, errFile *os.File
if c.Detached {
var err error
if outFile, err = os.CreateTemp("", "mesh-tool-out-*"); err != nil {
return Result{Status: 127, Error: err.Error()}
}
defer os.Remove(outFile.Name())
defer outFile.Close()
if errFile, err = os.CreateTemp("", "mesh-tool-err-*"); err != nil {
return Result{Status: 127, Error: err.Error()}
}
defer os.Remove(errFile.Name())
defer errFile.Close()
cmd.Stdout, cmd.Stderr = outFile, errFile
} else {
cmd.Stdout, cmd.Stderr = &out, &errs
}
err := cmd.Run()
if c.Detached {
for _, f := range []struct {
file *os.File
into *bounded
}{{outFile, &out}, {errFile, &errs}} {
if _, e := f.file.Seek(0, io.SeekStart); e == nil {
_, _ = io.Copy(f.into, f.file)
}
}
}
r := Result{Stdout: out.b.String(), Stderr: errs.b.String(), Truncated: out.cut || errs.cut}
var exit *exec.ExitError
switch {
case err == nil:
case ctx.Err() == context.DeadlineExceeded:
r.Status, r.Error = 124, "timeout"
case errors.Is(err, exec.ErrNotFound) || errors.Is(err, os.ErrNotExist):
r.Status, r.Error = 127, "not-found"
case errors.As(err, &exit):
r.Status = exit.ExitCode()
default:
r.Status, r.Error = 127, err.Error()
}
return r
}
// call runs a command and answers its result, or an error naming what went wrong.
func call(c Cmd) (Result, error) {
r := run(c)
if r.Status == 0 && r.Error == "" {
return r, nil
}
return r, failure(c, r)
}
// failure names how a command failed: not installed, refused escalation, too slow, or its exit
// status with the end of what it said.
func failure(c Cmd, r Result) error {
program, _ := argv(c)
switch {
case r.Error == "not-found" && program == "sudo":
return fmt.Errorf("%s needs root, and sudo is not installed here for the runtime's account to escalate with", c.Name)
case r.Error == "not-found":
if hint, ok := providedBy[c.Name]; ok {
return fmt.Errorf("%s is not installed on this machine (%s)", c.Name, hint)
}
return fmt.Errorf("%s is not installed on this machine", c.Name)
case r.Error == "timeout":
limit := c.Timeout
if limit <= 0 {
limit = CallTimeout
}
return fmt.Errorf("%s gave no answer within %s and was ended", c.Name, limit)
case r.Error != "":
return fmt.Errorf("%s did not run: %s", c.Name, r.Error)
case program == "sudo" && strings.Contains(r.Stderr, "command not found"):
if hint, ok := providedBy[c.Name]; ok {
return fmt.Errorf("%s is not installed on this machine (%s)", c.Name, hint)
}
return fmt.Errorf("%s is not installed on this machine", c.Name)
case program == "sudo" && strings.HasPrefix(strings.TrimSpace(r.Stderr), "sudo:"):
return fmt.Errorf("%s needs root, and sudo -n refused the runtime's account: %s (the escalation is the sudo module's to declare)",
c.Name, firstLine(r.Stderr))
}
said := tail(strings.TrimSpace(r.Stderr), 2000)
if said == "" {
said = tail(strings.TrimSpace(r.Stdout), 2000)
}
if said == "" {
said = "and said nothing"
}
return fmt.Errorf("%s %s exited %d: %s", c.Name, strings.Join(c.Args, " "), r.Status, said)
}
func firstLine(s string) string {
s = strings.TrimSpace(s)
if i := strings.IndexByte(s, '\n'); i >= 0 {
return s[:i]
}
return s
}
func tail(s string, n int) string {
if len(s) <= n {
return s
}
return "…" + s[len(s)-n:]
}
// lines are a command's output lines, blank ones dropped.
func lines(s string) []string {
out := []string{}
for _, l := range strings.Split(s, "\n") {
if strings.TrimSpace(l) != "" {
out = append(out, strings.TrimRight(l, "\r"))
}
}
return out
}
// Arguments, read the way a tool's JSON arguments arrive.
func text(args map[string]any, key string) (string, error) {
v, ok := args[key]
if !ok || v == nil {
return "", fmt.Errorf("%s is required", key)
}
s, ok := v.(string)
if !ok {
return "", fmt.Errorf("%s must be a string", key)
}
if strings.TrimSpace(s) == "" {
return "", fmt.Errorf("%s must not be empty", key)
}
return s, nil
}
func optText(args map[string]any, key, def string) (string, error) {
v, ok := args[key]
if !ok || v == nil {
return def, nil
}
s, ok := v.(string)
if !ok {
return "", fmt.Errorf("%s must be a string", key)
}
if strings.TrimSpace(s) == "" {
return def, nil
}
return s, nil
}
// optWhole reads a whole number, defaulted, refused below least and held to most.
func optWhole(args map[string]any, key string, def, least, most int) (int, error) {
v, ok := args[key]
if !ok || v == nil {
return def, nil
}
f, ok := v.(float64)
if !ok {
if i, isInt := v.(int); isInt {
f = float64(i)
} else {
return 0, fmt.Errorf("%s must be a number", key)
}
}
if f != float64(int(f)) {
return 0, fmt.Errorf("%s must be a whole number", key)
}
n := int(f)
if n < least {
return 0, fmt.Errorf("%s must be at least %d", key, least)
}
if n > most {
n = most
}
return n, nil
}
func optFlag(args map[string]any, key string, def bool) (bool, error) {
v, ok := args[key]
if !ok || v == nil {
return def, nil
}
b, ok := v.(bool)
if !ok {
return false, fmt.Errorf("%s must be true or false", key)
}
return b, nil
}
func optList(args map[string]any, key string) ([]string, error) {
v, ok := args[key]
if !ok || v == nil {
return nil, nil
}
items, ok := v.([]any)
if !ok {
return nil, fmt.Errorf("%s must be a list of strings", key)
}
out := make([]string, 0, len(items))
for _, it := range items {
s, ok := it.(string)
if !ok || strings.TrimSpace(s) == "" {
return nil, fmt.Errorf("%s must be a list of non-empty strings", key)
}
out = append(out, s)
}
return out, nil
}
// oneOf refuses a value outside a closed set.
func oneOf(key, value string, allowed ...string) error {
for _, a := range allowed {
if value == a {
return nil
}
}
return fmt.Errorf("%s must be one of %s, not %q", key, strings.Join(allowed, ", "), value)
}
// plainName refuses a name that could be read as an option or carries a path or a space: package,
// snap, application and printer names never do.
func plainName(key, value string) error {
if strings.HasPrefix(value, "-") || strings.ContainsAny(value, " \t\n/\\") {
return fmt.Errorf("%s %q is not a plain name", key, value)
}
return nil
}
@@ -1,147 +0,0 @@
package main
// Tests of kit.go, the same in each workstation module.
import (
"strings"
"testing"
"time"
)
// fake records the commands asked and answers each from a function of the command line.
type fake struct {
asked []Cmd
answer func(line string, c Cmd) Result
}
func (f *fake) runner() Runner {
return func(c Cmd) Result {
f.asked = append(f.asked, c)
name, args := argv(c)
line := strings.TrimSpace(name + " " + strings.Join(args, " "))
if f.answer == nil {
return Result{}
}
return f.answer(line, c)
}
}
func (f *fake) lines() []string {
out := []string{}
for _, c := range f.asked {
name, args := argv(c)
out = append(out, strings.TrimSpace(name+" "+strings.Join(args, " ")))
}
return out
}
// using installs a fake runner and a non-root uid for one test.
func using(t *testing.T, answer func(line string, c Cmd) Result) *fake {
t.Helper()
f := &fake{answer: answer}
wasRun, wasUID := run, euid
run, euid = f.runner(), func() int { return 1000 }
t.Cleanup(func() { run, euid = wasRun, wasUID })
return f
}
func ok(stdout string) Result { return Result{Stdout: stdout} }
func TestKitAnActThatNeedsRootGoesThroughSudoWithoutAPromptUnlessAlreadyRoot(t *testing.T) {
was := euid
defer func() { euid = was }()
euid = func() int { return 1000 }
if name, args := argv(Cmd{Name: "x", Args: []string{"a"}, Root: true}); name != "sudo" || strings.Join(args, " ") != "-n x a" {
t.Fatalf("not root: %s %v", name, args)
}
if name, _ := argv(Cmd{Name: "x"}); name != "x" {
t.Fatalf("a read is run as the account: %s", name)
}
euid = func() int { return 0 }
if name, _ := argv(Cmd{Name: "x", Root: true}); name != "x" {
t.Fatalf("as root no sudo: %s", name)
}
}
func TestKitAFailureIsNamedByHowItFailed(t *testing.T) {
was := euid
defer func() { euid = was }()
euid = func() int { return 1000 }
cases := []struct {
c Cmd
r Result
want string
}{
{Cmd{Name: "nothere"}, Result{Status: 127, Error: "not-found"}, "not installed"},
{Cmd{Name: "x", Root: true}, Result{Status: 127, Error: "not-found"}, "sudo is not installed"},
{Cmd{Name: "x", Root: true}, Result{Status: 1, Stderr: "sudo: a password is required\n"}, "sudo -n refused"},
{Cmd{Name: "x", Root: true}, Result{Status: 1, Stderr: "sudo: x: command not found\n"}, "x is not installed"},
{Cmd{Name: "x"}, Result{Status: 124, Error: "timeout"}, "within 20s"},
{Cmd{Name: "x", Args: []string{"y"}}, Result{Status: 3, Stderr: "boom\n"}, "x y exited 3: boom"},
{Cmd{Name: "x"}, Result{Status: 3}, "said nothing"},
}
for _, k := range cases {
err := failure(k.c, k.r)
if err == nil || !strings.Contains(err.Error(), k.want) {
t.Errorf("%+v: %v, want %q", k.r, err, k.want)
}
}
}
func TestKitOutputIsBoundedAndSaysSo(t *testing.T) {
var w bounded
big := strings.Repeat("a", MostOutput+10)
n, _ := w.Write([]byte(big))
if n != len(big) || w.b.Len() != MostOutput || !w.cut {
t.Fatalf("kept %d of %d, cut %v", w.b.Len(), len(big), w.cut)
}
}
func TestKitTheRealRunnerRunsEndsAndReportsAMissingProgram(t *testing.T) {
r := execRun(Cmd{Name: "sh", Args: []string{"-c", "echo out; echo err >&2; exit 3"}})
if r.Status != 3 || strings.TrimSpace(r.Stdout) != "out" || strings.TrimSpace(r.Stderr) != "err" {
t.Fatalf("%+v", r)
}
r = execRun(Cmd{Name: "sh", Args: []string{"-c", "sleep 5 & sleep 5"}, Timeout: 200 * time.Millisecond})
if r.Error != "timeout" {
t.Fatalf("a slow command: %+v", r)
}
r = execRun(Cmd{Name: "no-such-program-anywhere"})
if r.Error != "not-found" {
t.Fatalf("a missing program: %+v", r)
}
r = execRun(Cmd{Name: "cat", Stdin: "given"})
if r.Stdout != "given" {
t.Fatalf("stdin: %+v", r)
}
start := time.Now()
r = execRun(Cmd{Name: "sh", Args: []string{"-c", "echo kept; (sleep 3 &) ; exit 0"}, Detached: true})
if r.Status != 0 || strings.TrimSpace(r.Stdout) != "kept" || time.Since(start) > 2*time.Second {
t.Fatalf("a detached command returns when it exits, not when its child does: %+v after %s", r, time.Since(start))
}
}
func TestKitArgumentsAreReadStrictly(t *testing.T) {
args := map[string]any{"s": "x", "n": float64(5), "f": 1.5, "b": true, "l": []any{"a", "b"}}
if _, err := text(args, "missing"); err == nil {
t.Error("a missing required string")
}
if n, _ := optWhole(args, "n", 1, 1, 3); n != 3 {
t.Errorf("held to most: %d", n)
}
if _, err := optWhole(args, "n", 1, 6, 9); err == nil {
t.Error("below least")
}
if _, err := optWhole(args, "f", 1, 0, 9); err == nil {
t.Error("a fraction")
}
if l, _ := optList(args, "l"); len(l) != 2 {
t.Errorf("list: %v", l)
}
if b, _ := optFlag(args, "b", false); !b {
t.Error("flag")
}
if err := plainName("name", "--all"); err == nil {
t.Error("an option as a name")
}
}
@@ -1,135 +0,0 @@
// The bluetooth module's tools (novox/hq research 027/02, 026/05): the controller, the devices with
// their state and battery, scanning, and pairing, connecting, trusting and forgetting a device. A Go
// bundle the node's runtime launches over stdio (ADR 0188, ADR 0193); it runs as the operator
// account, and speaks to bluez through bluetoothctl.
package main
import (
"fmt"
"os"
stdio "git.novox.be/novox/mesh-sdk/go"
)
var providedBy = map[string]string{
"bluetoothctl": "the bluez-utils package, which this module installs",
}
func main() {
if err := stdio.Serve("", tools()); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
var addressArg = map[string]any{"type": "string", "description": "the device's address, such as 80:99:E7:C2:29:DA, as bluetooth_devices answers it"}
func withAddress(f func(string) (any, error)) func(map[string]any) (any, error) {
return func(args map[string]any) (any, error) {
a, err := addressOf(args)
if err != nil {
return nil, err
}
return f(a)
}
}
func tools() []stdio.Tool {
return []stdio.Tool{
{
Name: "bluetooth_controller",
Description: "The machine's Bluetooth controller: address, name, powered, discoverable, pairable, discovering. (r)",
Input: map[string]any{},
Run: func(map[string]any) (any, error) { return Controller() },
},
{
Name: "bluetooth_power",
Description: "Whether the controller is powered; with on, switch it on or off. (r/a)",
Input: map[string]any{"on": map[string]any{"type": "boolean", "description": "power the controller on (true) or off (false)"}},
Run: func(args map[string]any) (any, error) {
if _, given := args["on"]; !given {
c, err := Controller()
if err != nil {
return nil, err
}
return map[string]any{"powered": c.Powered}, nil
}
on, err := optFlag(args, "on", true)
if err != nil {
return nil, err
}
return Power(on)
},
},
{
Name: "bluetooth_devices",
Description: "The devices bluez knows: every one, or only the paired, connected or trusted. Each with its " +
"name, kind, paired, bonded, trusted, blocked, connected, and its battery where the device reports it. (r)",
Input: map[string]any{"which": map[string]any{"type": "string", "enum": []string{"all", "paired", "connected", "trusted"}, "description": "which devices (default all)"}},
Run: func(args map[string]any) (any, error) {
which, err := optText(args, "which", "all")
if err != nil {
return nil, err
}
return Devices(which)
},
},
{
Name: "bluetooth_scan",
Description: "Discover devices nearby for a few seconds (default 8, at most 15), and answer the ones not " +
"paired, with their signal strength. (r)",
Input: map[string]any{"seconds": map[string]any{"type": "integer", "description": "how long to scan (default 8, at most 15)"}},
Run: func(args map[string]any) (any, error) {
s, err := optWhole(args, "seconds", 8, 1, 15)
if err != nil {
return nil, err
}
return Scan(s)
},
},
{
Name: "bluetooth_connect",
Description: "Connect a paired device, such as headphones. Answers its state afterwards. (a)",
Input: map[string]any{"address": addressArg},
Run: withAddress(func(a string) (any, error) { return Act("connect", a) }),
},
{
Name: "bluetooth_disconnect",
Description: "Disconnect a device. (a)",
Input: map[string]any{"address": addressArg},
Run: withAddress(func(a string) (any, error) { return Act("disconnect", a) }),
},
{
Name: "bluetooth_trust",
Description: "Trust a device, so it may connect by itself; or with trusted false, stop trusting it. (a)",
Input: map[string]any{"address": addressArg, "trusted": map[string]any{"type": "boolean", "description": "trust (default) or untrust"}},
Run: func(args map[string]any) (any, error) {
a, err := addressOf(args)
if err != nil {
return nil, err
}
trusted, err := optFlag(args, "trusted", true)
if err != nil {
return nil, err
}
if trusted {
return Act("trust", a)
}
return Act("untrust", a)
},
},
{
Name: "bluetooth_pair",
Description: "Pair a device found by a scan, and trust it. Works for a device that needs no code to be " +
"confirmed, such as headphones; one that shows a code is paired from the desktop. (a)",
Input: map[string]any{"address": addressArg},
Run: withAddress(func(a string) (any, error) { return Pair(a) }),
},
{
Name: "bluetooth_remove",
Description: "Forget a device: unpair it and drop what bluez knows of it. (a)",
Input: map[string]any{"address": addressArg},
Run: withAddress(func(a string) (any, error) { return Act("remove", a) }),
},
}
}
@@ -1,107 +0,0 @@
package main
// manifest_kit_test.go is the same file in each workstation module: it reads the module's
// definition so the module's own tests can hold it to what it says.
import (
"encoding/json"
"os"
"path/filepath"
"sort"
"strings"
"testing"
)
type manifest struct {
Module string `json:"module"`
Capabilities []string `json:"capabilities"`
Claims []any `json:"claims"`
Seats []any `json:"seats"`
Tools []string `json:"tools"`
Resources []map[string]any `json:"resources"`
Build struct {
Artifacts []map[string]any `json:"artifacts"`
} `json:"build"`
}
func readManifest(t *testing.T) manifest {
t.Helper()
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
var m manifest
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatalf("module.json: %v", err)
}
return m
}
func (m manifest) resource(id string) map[string]any {
for _, r := range m.Resources {
if r["id"] == id {
return r
}
}
return nil
}
// packages are the packages the module installs, sorted.
func (m manifest) packages() []string {
out := []string{}
for _, r := range m.Resources {
if r["type"] == "package" && r["absent"] != true {
out = append(out, r["package"].(string))
}
}
sort.Strings(out)
return out
}
// services are the units the module declares, by unit name.
func (m manifest) services() map[string]map[string]any {
out := map[string]map[string]any{}
for _, r := range m.Resources {
if r["type"] == "service" {
out[r["unit"].(string)] = r
}
}
return out
}
// holdsTheBundle holds the manifest to the Go bundle this directory builds: every tool registered
// is listed and nothing else, each named <prefix>_…, and the artifact builds this command.
func holdsTheBundle(t *testing.T, m manifest, prefix string) {
t.Helper()
registered := []string{}
for _, tool := range tools() {
registered = append(registered, tool.Name)
if !strings.HasPrefix(tool.Name, prefix+"_") {
t.Errorf("tool %s is not named %s_…", tool.Name, prefix)
}
if tool.Description == "" || tool.Run == nil || tool.Input == nil {
t.Errorf("tool %s is not described, runnable and given an input schema", tool.Name)
}
}
if strings.Join(registered, ",") != strings.Join(m.Tools, ",") {
t.Errorf("registered %v, listed %v", registered, m.Tools)
}
if len(m.Build.Artifacts) != 1 {
t.Fatalf("one artifact, got %d", len(m.Build.Artifacts))
}
cwd, _ := os.Getwd()
binary := filepath.Base(cwd)
a := m.Build.Artifacts[0]
want := map[string]any{"kind": "bundle", "language": "go", "system": "arch", "from": "cmd/" + binary, "binary": binary}
for k, v := range want {
if a[k] != v {
t.Errorf("artifact %s = %v, want %v", k, a[k], v)
}
}
if loads, _ := a["loads"].([]any); len(loads) != 1 || loads[0] != binary {
t.Errorf("artifact loads %v, want [%s]", a["loads"], binary)
}
if m.Claims != nil || m.Seats != nil {
t.Errorf("claims %v, seats %v: this module holds no seat", m.Claims, m.Seats)
}
}
-5
View File
@@ -1,5 +0,0 @@
module bluetooth
go 1.22
require git.novox.be/novox/mesh-sdk/go v0.1.6
-2
View File
@@ -1,2 +0,0 @@
git.novox.be/novox/mesh-sdk/go v0.1.6 h1:9qzdYONYbJdWcu6sxQcq9v1LI0JxcfkiKYkMUzJSkVQ=
git.novox.be/novox/mesh-sdk/go v0.1.6/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
-53
View File
@@ -1,53 +0,0 @@
{
"module": "bluetooth",
"version": "1",
"capabilities": [
"package-manager",
"service-manager"
],
"tools": [
"bluetooth_controller",
"bluetooth_power",
"bluetooth_devices",
"bluetooth_scan",
"bluetooth_connect",
"bluetooth_disconnect",
"bluetooth_trust",
"bluetooth_pair",
"bluetooth_remove"
],
"resources": [
{
"id": "stack",
"type": "package",
"package": "bluez"
},
{
"id": "utilities",
"type": "package",
"package": "bluez-utils"
},
{
"id": "daemon",
"type": "service",
"unit": "bluetooth.service",
"state": "running",
"boot": "enabled"
}
],
"build": {
"artifacts": [
{
"name": "tools",
"kind": "bundle",
"language": "go",
"system": "arch",
"from": "cmd/bluetooth-tools",
"binary": "bluetooth-tools",
"loads": [
"bluetooth-tools"
]
}
]
}
}
+24
View File
@@ -0,0 +1,24 @@
# bookshelf's runtime: the tool runtime, carrying this module's compiled code.
#
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
# the base images, published like any other artifact — which is what makes this buildable by the
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
# happens to have the siblings.
#
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
ARG BUILD_BASE
ARG RUNTIME_BASE
FROM ${BUILD_BASE} AS build
WORKDIR /app/modules/bookshelf
COPY . .
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts \
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
FROM ${RUNTIME_BASE}
COPY --from=build /app/modules/bookshelf/dist /app/modules/bookshelf/dist
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
# the convention novox/hq issues 060/061 settled.
ENV MESH_TOOL_MODULES=/app/modules/bookshelf/dist/index.js,/app/modules/bookshelf/dist/tools/index.js
+136
View File
@@ -0,0 +1,136 @@
// The Bookshelf API client — bookshelf's own code, living in the module (novox/hq ADR 0039).
// Ported from the shared hal `arr` client, but self-contained: in nox each Servarr app owns its own
// copy, so a change to Bookshelf's API rebuilds only bookshelf and nothing else. Both this module's
// tools and its events entrypoint import it, and nothing outside bookshelf does.
//
// Bookshelf is a Readarr fork (ghcr.io/pennydreadful/bookshelf). It speaks the Servarr v1 API; its
// content is "book". Unlike Sonarr/Radarr it exposes no calendar endpoint, so there is no calendar
// tool here — matching hal, which excluded bookshelf from its calendar-capable apps.
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
// Bookshelf speaks the v1 API; its content is "book".
const API_VERSION = "v1";
const CONTENT_ENDPOINT = "book";
const APP_NAME = "Bookshelf";
export interface BookshelfQueueItem {
/** The queue record id — stable while the item is in the queue, so events can diff on it. */
id: number;
title: string;
status: string;
size: string;
sizeleft: string;
timeleft?: string;
}
export interface BookshelfContentItem {
title: string;
author?: string;
year?: number;
status?: string;
monitored: boolean;
}
export class BookshelfClient {
readonly baseUrl: string;
constructor(
url: string,
private readonly apiKey: string,
) {
this.baseUrl = url.replace(/\/$/, "");
}
/**
* Build from the module's resolved environment. The URL defaults to the server on this node (the
* runtime shares its network), and the API key is read from MESH_BOOKSHELF_API_KEY or, failing
* that, discovered from the server's own config.xml under MESH_BOOKSHELF_CONFIG_DIR — the same
* file Bookshelf writes it to, so a running server needs nothing configured by hand. Throws when
* no key can be found, so the tools/events simply do not load (the harness treats the throw as
* "exposes nothing").
*/
static fromEnv(env: NodeJS.ProcessEnv = process.env): BookshelfClient {
const url = env.MESH_BOOKSHELF_URL ?? `http://127.0.0.1:${env.MESH_BOOKSHELF_PORT ?? "8787"}`;
const configDir = env.MESH_BOOKSHELF_CONFIG_DIR ?? "/config";
const apiKey = env.MESH_BOOKSHELF_API_KEY ?? BookshelfClient.detectApiKey(configDir);
if (!apiKey) {
throw new Error("Bookshelf not configured — set MESH_BOOKSHELF_API_KEY or make the config dir readable");
}
return new BookshelfClient(url, apiKey);
}
/** Discover the API key from the server's config.xml, falling back to null. Every Servarr app
* writes <ApiKey> into config.xml at the root of its config directory. */
static detectApiKey(configDir: string): string | null {
const config = join(configDir, "config.xml");
if (existsSync(config)) {
const match = readFileSync(config, "utf8").match(/<ApiKey>([^<]+)<\/ApiKey>/);
if (match) return match[1];
}
return null;
}
private async get(endpoint: string, params?: Record<string, string>): Promise<unknown> {
const url = new URL(`${this.baseUrl}/api/${API_VERSION}/${endpoint}`);
if (params) {
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
}
const res = await fetch(url.toString(), { headers: { "X-Api-Key": this.apiKey } });
if (!res.ok) throw new Error(`${APP_NAME} API /${endpoint}: ${res.status} ${await res.text()}`);
return res.json();
}
async getStatus(): Promise<{ appName: string; version: string }> {
const data = (await this.get("system/status")) as { appName?: string; version?: string };
return { appName: data.appName || APP_NAME, version: data.version ?? "unknown" };
}
async getContent(limit?: number): Promise<BookshelfContentItem[]> {
const data = await this.get(CONTENT_ENDPOINT);
const items: any[] = Array.isArray(data) ? data : ((data as any)?.records ?? []);
const mapped = items.map((item) => ({
title: item.title ?? "Unknown",
author: item.author?.authorName ?? item.authorName,
year: item.releaseDate ? new Date(item.releaseDate).getFullYear() : item.year,
status: item.status,
monitored: item.monitored ?? true,
}));
return limit ? mapped.slice(0, limit) : mapped;
}
/** Library search is a filter over existing content, not an indexer lookup — same as hal's. */
async searchContent(term: string): Promise<BookshelfContentItem[]> {
const all = await this.getContent();
const lower = term.toLowerCase();
return all.filter(
(item) =>
item.title.toLowerCase().includes(lower) ||
(item.author?.toLowerCase().includes(lower) ?? false),
);
}
async getQueue(): Promise<{ totalRecords: number; items: BookshelfQueueItem[] }> {
const data = (await this.get("queue", { pageSize: "50" })) as { totalRecords?: number; records?: any[] };
const records = data.records ?? [];
return {
totalRecords: data.totalRecords ?? records.length,
items: records.map((r) => ({
id: r.id,
title: r.title ?? r.book?.title ?? r.author?.authorName ?? "Unknown",
status: r.status ?? "unknown",
size: formatBytes(r.size ?? 0),
sizeleft: formatBytes(r.sizeleft ?? 0),
timeleft: r.timeleft,
})),
};
}
}
function formatBytes(bytes: number): string {
if (bytes === 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;
}
+74
View File
@@ -0,0 +1,74 @@
// bookshelf's events. The tool runtime imports this once the broker is bound. It watches the
// download queue and turns its comings and goings into mesh events — the same mechanism radarr uses,
// applied to a Servarr book manager.
//
// Emits (novox/hq ADR 0041/0042):
// module.bookshelf.book.grabbed — a release entered the queue (Bookshelf grabbed it)
// module.bookshelf.download.completed — a release left the queue, imported. This routing key is
// what the plex module consumes (module.*.download.completed)
// to rescan, so a new audiobook becomes a visible item.
// Consumes: none.
//
// NOTE: the hal bookshelf module emitted no events (its hooks only did install-time provisioning).
// This queue watcher is new in nox, modelled exactly on radarr's — bookshelf is a Servarr app with
// the same queue semantics, so the diff-and-emit pattern carries over unchanged.
//
// The queue is polled and diffed, primed silently on the first look (like plex's index.ts) so a
// restart mid-download does not re-announce everything already in flight as freshly grabbed.
import { emit } from "@novox/mesh-sdk/events";
import { BookshelfClient, type BookshelfQueueItem } from "./client.js";
// Building the client throws when Bookshelf has no URL/key yet. Like the tools (see tools/index.ts),
// the events entrypoint must not crash the runtime for that — it stays idle until configured.
function buildClient(): BookshelfClient | null {
try {
return BookshelfClient.fromEnv();
} catch {
return null;
}
}
const bookshelf = buildClient();
// Bookshelf removes an item from the queue once it has been imported; a "warning"/"failed" status is
// how a stuck or broken grab shows itself, so we do not call those a completion when they vanish.
const FAILED_STATUSES = new Set(["failed", "warning"]);
const inQueue = new Map<number, BookshelfQueueItem>();
let primed = false;
async function pollQueue(bookshelf: BookshelfClient): Promise<void> {
const { items } = await bookshelf.getQueue();
const now = new Map(items.map((i) => [i.id, i]));
if (primed) {
// Entered the queue since last look — Bookshelf grabbed a release.
for (const [id, item] of now) {
if (!inQueue.has(id)) await emit("book.grabbed", { title: item.title, status: item.status });
}
// Left the queue — imported and done, unless it was last seen failing.
for (const [id, item] of inQueue) {
if (!now.has(id) && !FAILED_STATUSES.has(item.status)) {
await emit("download.completed", { title: item.title });
}
}
}
inQueue.clear();
for (const [id, item] of now) inQueue.set(id, item);
primed = true;
}
const tick = (fn: () => Promise<void>, everyMs: number): void => {
const run = (): void => void fn().catch((err) => console.error(`[bookshelf] ${err}`));
setInterval(run, everyMs);
run();
};
if (bookshelf) {
tick(() => pollQueue(bookshelf), 30_000);
console.log("[bookshelf] watching the download queue, emitting grabs and completions");
} else {
console.log("[bookshelf] not configured — events idle until an API key is available");
}
+118
View File
@@ -0,0 +1,118 @@
{
"module": "bookshelf",
"version": "1",
"slug": "books",
"capabilities": [
"container-runtime"
],
"emits": [
"book.grabbed",
"download.completed"
],
"consumes": [],
"own-secrets": {
"broker": "/var/lib/mesh/bookshelf/broker"
},
"listens": [
{
"name": "web",
"port": 8787,
"protocol": "tcp",
"from": "mesh",
"why": "managing the ebook/audiobook library"
}
],
"accesses": [
{
"path": "/services/media/books",
"mode": "read-write"
},
{
"path": "/services/media/downloads",
"mode": "read-write"
}
],
"resources": [
{
"id": "mesh-state",
"type": "directory",
"path": "/var/lib/mesh/bookshelf",
"mode": "0700"
},
{
"id": "config",
"type": "directory",
"path": "/services/bookshelf/config",
"mode": "0700",
"owner": "1000:1000"
},
{
"id": "server",
"type": "container",
"name": "bookshelf",
"image": "ghcr.io/pennydreadful/bookshelf@sha256:388eecc94362580eae31ee0a454be6af516f8a311f8432a521c202fb475f4359",
"env": {
"PUID": "1000",
"PGID": "1000",
"TZ": "Etc/UTC"
},
"ports": [
"8787"
],
"volumes": [
"/services/bookshelf/config:/config",
"/services/media/books:/books",
"/services/media/downloads:/downloads"
]
},
{
"id": "runtime",
"type": "container",
"name": "mesh-bookshelf",
"network": "host",
"volumes": [
"/var/lib/mesh/bookshelf/broker:/run/secrets/broker:ro",
"/services/bookshelf/config:/var/lib/bookshelf/config:ro"
],
"env": {
"MESH_BROKER_FILE": "/run/secrets/broker",
"MESH_BOOKSHELF_URL": "http://127.0.0.1:${port:8787}",
"MESH_BOOKSHELF_CONFIG_DIR": "/var/lib/bookshelf/config"
},
"artifact": "runtime"
}
],
"requires": [
"route"
],
"contributes": {
"route": {
"label": "books",
"endpoint": "web"
}
},
"binds": {
"route": "/var/lib/mesh/bookshelf/route.json"
},
"build": {
"on": [
{
"arg": "BUILD_BASE",
"module": "mesh-tools",
"artifact": "build"
},
{
"arg": "RUNTIME_BASE",
"module": "mesh-tools",
"artifact": "runtime"
}
],
"artifacts": [
{
"name": "runtime",
"kind": "image",
"from": "Dockerfile"
}
]
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"name": "@novox/module-bookshelf",
"version": "0.1.0",
"description": "bookshelf — ebook/audiobook management (Readarr fork). Its API client, tools and events live here (novox/hq ADR 0039).",
"type": "module",
"private": true,
"dependencies": {
"@novox/mesh-sdk": "^0.1.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
"typescript": "^5.6.0"
}
}
+69
View File
@@ -0,0 +1,69 @@
// bookshelf's tools — ported from the shared hal `arr` sdk (novox/hq ADR 0039), importing
// bookshelf's own client. They return structured data (not the pre-formatted text hal returned); the
// mesh serves them through the sdk's tool harness. Bookshelf has no calendar endpoint, so there is
// no calendar tool — matching hal, which excluded it from its calendar-capable apps.
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
import { BookshelfClient } from "../client.js";
export function getBookshelfTools(bookshelf: BookshelfClient): ToolDefinition[] {
return [
{
name: "bookshelf_status",
description: "Bookshelf status overview: version, book count, monitored count, queue size.",
input: {},
run: async () => {
const [status, content, queue] = await Promise.all([
bookshelf.getStatus(),
bookshelf.getContent(),
bookshelf.getQueue(),
]);
return {
app: status.appName,
version: status.version,
books: content.length,
monitored: content.filter((c) => c.monitored).length,
queue: queue.totalRecords,
};
},
},
{
name: "bookshelf_library",
description: "List books from the Bookshelf library.",
input: { limit: { type: "number", description: "max items to return (default 50)" } },
run: async (args) => {
const items = await bookshelf.getContent(args.limit ? Number(args.limit) : 50);
return { count: items.length, books: items };
},
},
{
name: "bookshelf_search",
description:
"Search the Bookshelf library for books by title or author (filters existing content, not indexers).",
input: { query: { type: "string", description: "the search term" } },
run: async (args) => {
const query = String(args.query);
return { query, results: await bookshelf.searchContent(query) };
},
},
{
name: "bookshelf_queue",
description: "Show the Bookshelf download queue — what is downloading and how far along.",
input: {},
run: async () => {
const queue = await bookshelf.getQueue();
return { count: queue.totalRecords, items: queue.items };
},
},
];
}
// The tools exist only when Bookshelf is configured; without a URL and key, bookshelf contributes
// none rather than failing the whole runtime.
registerModuleTools("bookshelf", (env) => {
try {
return getBookshelfTools(BookshelfClient.fromEnv(env));
} catch {
return [];
}
});
@@ -8,8 +8,5 @@
"skipLibCheck": true, "skipLibCheck": true,
"noEmit": true "noEmit": true
}, },
"include": [ "include": ["client.ts", "index.ts", "tools/index.ts"]
"shell.ts",
"tools/index.ts"
]
} }
-15
View File
@@ -1,15 +0,0 @@
# build-agent
The mesh's build machine as a role every machine can hold (novox/hq ADR 0190). It holds the node seat
`node-build-agent`: every holder pulls one build at a time from the role's one work queue when it is
idle, so a tier of many images is built by as many machines as hold the seat and are online, and a
machine that is off builds nothing and blocks nothing. The controller asks the role, never a machine;
the outcome names the machine that built it.
What a holding machine needs is what the builder always needed, said here once: a container runtime
(the socket is mounted), the artifact store and the package registry as provisions, a workspace, and
the bus credential. The code is `cmd/mesh-builder` in the mesh-controller repository, compiled from
that repository's main (`build.artifacts[].context`); this module ships the packaging.
Assign it to every machine with a container runtime. It replaces `builder`, the one-holder form of the
same thing; retire that once this is assigned where it was.
@@ -1,6 +1,6 @@
ARG GO_BASE ARG GO_BASE
ARG ALPINE_BASE ARG ALPINE_BASE
# build-agent's image: the build machine itself, compiled into a container (novox/hq ADR 0190). # builder's own image: the build machine itself, compiled into a container.
# #
# **The source is not vendored here.** builder's actual code — cmd/mesh-builder, internal/builder, # **The source is not vendored here.** builder's actual code — cmd/mesh-builder, internal/builder,
# internal/catalogue — lives in the mesh-controller repository, the same control plane it is one # internal/catalogue — lives in the mesh-controller repository, the same control plane it is one
@@ -1,14 +1,13 @@
{ {
"module": "build-agent", "module": "builder",
"version": "1", "version": "1",
"slug": "agent",
"capabilities": [ "capabilities": [
"container-runtime" "container-runtime"
], ],
"claims": [ "claims": [
{ {
"name": "node-build-agent", "name": "mesh-build-machine",
"scope": "node" "scope": "mesh"
} }
], ],
"requires": [ "requires": [
@@ -16,48 +15,49 @@
"npm-package-registry" "npm-package-registry"
], ],
"binds": { "binds": {
"npm-package-registry": "${dir:mesh-state}/package-registry.json" "npm-package-registry": "/var/lib/mesh/builder/package-registry.json"
}, },
"secrets": { "secrets": {
"npm-package-registry": "${dir:mesh-state}/package-registry.secret" "npm-package-registry": "/var/lib/mesh/builder/package-registry.secret"
}, },
"own-secrets": { "own-secrets": {
"broker": "${dir:mesh-state}/broker" "broker": "/var/lib/mesh/builder/broker"
}, },
"resources": [ "resources": [
{ {
"id": "mesh-state", "id": "mesh-state",
"type": "directory", "type": "directory",
"mode": "0700", "path": "/var/lib/mesh/builder",
"place": "mesh" "mode": "0700"
}, },
{ {
"id": "workspace", "id": "workspace",
"type": "directory", "type": "directory",
"path": "/var/lib/builder/workspace",
"mode": "0700" "mode": "0700"
}, },
{ {
"id": "agent-env", "id": "builder-env",
"type": "file", "type": "file",
"path": "${dir:mesh-state}/build-agent.env", "path": "/var/lib/mesh/builder/builder.env",
"mode": "0600", "mode": "0600",
"content": "MESH_BROKER_FILE=/run/mesh/broker\nMESH_NODE=${machine:name}\nMESH_REGISTRY=${bound:artifact-store:at}:${bound:artifact-store:port}\nMESH_PACKAGE_BINDING=/run/mesh/package-registry.json\nMESH_NPM_TOKEN_FILE=/run/mesh/package-registry.secret\nMESH_WORKSPACE=${dir:workspace}\n" "content": "MESH_BROKER_FILE=/run/mesh/broker\nMESH_NODE=${machine:name}\nMESH_REGISTRY=${bound:artifact-store:at}:${bound:artifact-store:port}\nMESH_PACKAGE_BINDING=/run/mesh/package-registry.json\nMESH_NPM_TOKEN_FILE=/run/mesh/package-registry.secret\nMESH_WORKSPACE=/var/lib/builder/workspace\n"
}, },
{ {
"id": "server", "id": "server",
"type": "container", "type": "container",
"name": "mesh-build-agent", "name": "mesh-builder",
"artifact": "server", "artifact": "server",
"env-file": [ "env-file": [
"${dir:mesh-state}/build-agent.env" "/var/lib/mesh/builder/builder.env"
], ],
"volumes": [ "volumes": [
"${dir:mesh-state}:/run/mesh:ro", "/var/lib/mesh/builder:/run/mesh:ro",
"${dir:workspace}:${dir:workspace}", "/var/lib/builder/workspace:/var/lib/builder/workspace",
"/var/run/docker.sock:/var/run/docker.sock" "/var/run/docker.sock:/var/run/docker.sock"
], ],
"restart-on": [ "restart-on": [
"agent-env" "builder-env"
], ],
"network": "host" "network": "host"
} }
@@ -69,8 +69,7 @@
"kind": "image", "kind": "image",
"from": "Dockerfile", "from": "Dockerfile",
"context": { "context": {
"seat": "git", "repository": "https://git.novox.be/novox/mesh-controller.git",
"repository": "novox/mesh-controller",
"ref": "main" "ref": "main"
} }
} }
-81
View File
@@ -1,81 +0,0 @@
# claude-code
The operator's agent on a machine (novox/hq design 36): its package, its machine-wide managed
configuration, and the consumer side of the Anthropic licence manager (design 39, ADR 0183).
## What it owns
Two directories, declared, so the mesh refuses a second module owning either:
- `/etc/claude-code`, the agent's machine-wide managed directory, root's, `0755`.
- `~/.claude` under the operator account's home, the operator's, `0700`. The module owns the directory —
that it exists, who owns it, its mode — and of what is inside only what it writes. Everything else
in it (memory, history, projects, local settings, a person's own rules and skills) is the person's
and is never read or written (hq ADR 0182). Unassigned, the module leaves the directory: the host
removes a directory only when it is empty.
## What it writes
Under the agent's managed directory, `/etc/claude-code`, owned whole by this module and rewritten
whenever the node's tool runtime collects the module's tools:
| file | holds |
|---|---|
| `managed-mcp.json` | the tool servers every session loads: the mesh's console as `mesh`, and the servers set in this module's `mcp_servers` setting. **Exclusive**: a server not listed here does not load — not one added with `claude mcp add`, not a project's `.mcp.json`, not a plugin's |
| `managed-settings.json` | the repositories' attribution convention, the claude.ai connectors kept beside the managed servers, and the key-helper while the node holds an API-key licence |
| `CLAUDE.md` | how a session on this mesh works, this node's name and role, the conventions |
Under the operator's home, only `~/.claude/.credentials.json`, and only when the licence manager hands
this node a subscription token. Nothing else under the home is read or written.
## Over NATS
Everything between this module and the rest of the mesh is NATS, in three kinds: an **event** says that
something happened and carries no secret, because a stream keeps it; a **request** carries a token,
because nothing keeps it (hq design 32 §10); and **state** is the current value of something every node
must see, a node that joins later included — kept, so it carries no secret either (hq ADR 0201).
| what | how |
|---|---|
| what this node holds | the module's `holdings` state, one key for this node — the account, the kind, fingerprints and expiries, never a token — written at start and whenever the credentials file changes (hq ADR 0206) |
| a person ran `/login` here | the credentials file gains a refresh token this module never writes; its next report shows it, and the licence manager asks `claude_code_grant` for it, giving its key — the one time a refresh token leaves the node, for the manager to adopt by refreshing it |
| what this node should hold | the licence manager's `bindings` state, this node's key; on a newer generation this module asks `anthropic-licence-manager.current` for its token, sealed to the key it sends, and writes it access-token-only — so the agent here never refreshes. A node that was off reads its key when it is back |
| an MCP server registered through this module | a key in the module's `servers` state — `all.<server>` for every node, `<node>.<server>` for one; every node watches it and renders what applies to it, a node's own entry over the one for every node. A node that joins later, or was off, reads the whole current set at start; unregistering is a delete. An entry with a secret in its `env` or `headers` is refused by the runtime |
## Tools
`claude_code_status`, `claude_code_render`, `claude_code_pull`, `claude_code_grant` (for the licence
manager), `claude_code_mcp_list`,
`claude_code_mcp_register` (this node by default; `nodes: "all"` or a list for more — called for this
node alone, its answer names the other nodes running claude-code), `claude_code_mcp_unregister`.
## Settings
Per node or for the whole mesh, through `mesh-controller.settings module=claude-code`:
- `role` — what this node is, in a few words; shown to every session.
- `mcp_servers` — extra tool servers, set by the operator for the mesh or a node, beside the ones
registered through the tools; keyed by name, in the vendor's `.mcp.json` entry shape
(`{"type":"http","url":…}` or `{"type":"stdio","command":…,"args":[…]}`). The name `mesh` is the
module's own and cannot be set. Put a person's own servers here, or they stop loading.
## On a machine that carried the predecessor
Remove these by hand, once; the mesh removes nothing it did not make (ADR 0182):
- `~/.claude/CLAUDE.md`
- `~/.claude/rules/00-hal-mesh.md`, `~/.claude/rules/conventions.md`
- `~/.claude/skills/cleanup/`, `~/.claude/skills/hal-switch-license/`
- the hand-made console entry in `~/.claude.json` under `mcpServers` — it is ignored now anyway
## Escalation
Writing `/etc/claude-code` needs root. The runtime runs as the operator account, and the module uses
that account's passwordless `sudo`; on a machine without it, `claude_code_render` says so and nothing
is written.
## Code
Go, one binary (`cmd/claude-code`) the node's runtime launches. Tested with `go test ./...`; the managed
instruction file is held to the TypeScript renderer it replaced (`testdata/rendered-by-typescript.json`),
and the sealed box is the licence manager's own format.
@@ -1,401 +0,0 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
)
var now = time.Now().UnixMilli()
func node(t *testing.T, name string) (Paths, map[string]string) {
t.Helper()
root := t.TempDir()
p := Paths{State: filepath.Join(root, "state"), Facts: filepath.Join(root, "state", "facts.json"),
Settings: filepath.Join(root, "state", "settings.json"), Home: filepath.Join(root, "home"), Node: name}
_ = os.MkdirAll(p.State, 0o700)
_ = os.MkdirAll(filepath.Join(p.Home, ".claude"), 0o700)
_ = os.WriteFile(p.Facts, []byte(`{"node":"`+name+`","console":"http://127.0.0.1:4270/mcp"}`), 0o600)
_ = os.WriteFile(p.Settings, []byte(`{"role":"","mcp_servers":{}}`), 0o600)
return p, map[string]string{}
}
func writer(w map[string]string) WriteManaged {
return func(name, content string) (string, error) { w[name] = content; return name + ": written", nil }
}
func writeFile(t *testing.T, path, content string) {
t.Helper()
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
}
func creds(t *testing.T, p Paths) map[string]any {
t.Helper()
var c map[string]any
raw, _ := os.ReadFile(p.credentials())
if err := json.Unmarshal(raw, &c); err != nil {
t.Fatal(err)
}
return c["claudeAiOauth"].(map[string]any)
}
// ---- the renderer, held to the TypeScript it replaced -------------------------------------------------
func TestTheRendererWritesWhatTheTypeScriptOneWrote(t *testing.T) {
raw, err := os.ReadFile("testdata/rendered-by-typescript.json")
if err != nil {
t.Fatal(err)
}
var f struct {
Facts Facts `json:"facts"`
Settings Settings `json:"settings"`
Registered Servers `json:"registered"`
WithKey map[string]string `json:"withKey"`
Plain map[string]string `json:"plain"`
}
if err := json.Unmarshal(raw, &f); err != nil {
t.Fatal(err)
}
same := func(label string, got, want map[string]string) {
if got["CLAUDE.md"] != want["CLAUDE.md"] {
t.Errorf("%s: CLAUDE.md differs from the TypeScript's:\n--- go\n%s\n--- typescript\n%s", label, got["CLAUDE.md"], want["CLAUDE.md"])
}
for _, file := range []string{"managed-mcp.json", "managed-settings.json"} {
var a, b any
_ = json.Unmarshal([]byte(got[file]), &a)
_ = json.Unmarshal([]byte(want[file]), &b)
if !reflect.DeepEqual(a, b) {
t.Errorf("%s: %s means something else:\n--- go\n%s\n--- typescript\n%s", label, file, got[file], want[file])
}
}
}
same("with an API key", Render(f.Facts, f.Settings, &Binding{Licence: "api", Kind: "api-key"}, "/state/api-key-helper", f.Registered), f.WithKey)
same("plain", Render(f.Facts, Settings{}, nil, "/h", Servers{}), f.Plain)
}
func TestASettingCannotReplaceTheMeshsOwnEntryAndABadNameIsLeftOut(t *testing.T) {
out := Render(Facts{Node: "w", Console: "http://127.0.0.1:4270/mcp"},
Settings{MCPServers: map[string]map[string]any{"mesh": {"type": "http", "url": "http://evil"}, "bad name": {}}}, nil, "/h", nil)
var mcp struct {
MCPServers map[string]map[string]any `json:"mcpServers"`
}
_ = json.Unmarshal([]byte(out["managed-mcp.json"]), &mcp)
if mcp.MCPServers["mesh"]["url"] != "http://127.0.0.1:4270/mcp" || mcp.MCPServers["bad name"] != nil {
t.Fatalf("%v", mcp.MCPServers)
}
if !reflect.DeepEqual(Render(Facts{Console: "x"}, Settings{}, nil, "/h", nil), Render(Facts{Console: "x"}, Settings{}, nil, "/h", nil)) {
t.Fatal("rendering is not deterministic")
}
}
// ---- the credentials file -----------------------------------------------------------------------------
func i64(v int64) *int64 { return &v }
func TestTheLineageRules(t *testing.T) {
const hour = 3_600_000
g := func(at string, exp int64, rtExp int64) Grant {
return Grant{AccessToken: at, ExpiresAt: exp, RefreshTokenExpiresAt: i64(rtExp)}
}
month := now + 30*24*hour
if d := DecideApply(&Grant{AccessToken: "A", ExpiresAt: now + hour, RefreshTokenExpiresAt: i64(month)}, g("B", now+2*hour, month), false); !d.Apply {
t.Fatal("a newer rotation was refused")
}
if d := DecideApply(&Grant{AccessToken: "new", ExpiresAt: now + 2*hour, RefreshTokenExpiresAt: i64(month)}, g("old", now+hour, month), false); d.Apply || d.Reason != "not-newer" {
t.Fatalf("a late older rotation: %+v", d)
}
if d := DecideApply(&Grant{AccessToken: "A", ExpiresAt: now + 8*hour, RefreshTokenExpiresAt: i64(month)}, g("re", now+hour, now+5*24*hour), false); !d.Apply || !d.Reissued {
t.Fatalf("a re-issued grant: %+v", d)
}
if d := DecideApply(&Grant{AccessToken: "A", ExpiresAt: now + 8*hour}, g("other", now+hour, month), true); !d.Apply {
t.Fatal("a switch was refused")
}
if d := DecideApply(&Grant{AccessToken: "A"}, Grant{AccessToken: "A"}, true); d.Apply || d.Reason != "already-current" {
t.Fatalf("the same token: %+v", d)
}
}
func TestALoginIsSeenAndStrippedWhenTheNodesOwnGrantIsWritten(t *testing.T) {
p, _ := node(t, "laptop")
writeFile(t, p.credentials(), `{"claudeAiOauth":{"accessToken":"at-login","refreshToken":"rt-login","expiresAt":1700000000000},"other":1}`)
login := ReadCredentials(p.credentials())
if !HoldsLogin(login) {
t.Fatal("a login was not seen")
}
if err := WriteCredentials(p.credentials(), WithGrant(login, Grant{AccessToken: "at-mesh", ExpiresAt: 1, Scopes: []string{"user:inference"}})); err != nil {
t.Fatal(err)
}
back := ReadCredentials(p.credentials())
raw, _ := os.ReadFile(p.credentials())
info, _ := os.Stat(p.credentials())
if HoldsLogin(back) || GrantOf(back).AccessToken != "at-mesh" || back["other"] == nil || strings.Contains(string(raw), "rt-login") || info.Mode().Perm() != 0o600 {
t.Fatalf("written %s (mode %v)", raw, info.Mode())
}
}
func TestTheAccountIsReadFromTheAgentsStateFileAndNeverGuessed(t *testing.T) {
p, _ := node(t, "laptop")
writeFile(t, p.account(), `{"oauthAccount":{"accountUuid":"u-1","emailAddress":"a@example.org"},"other":2}`)
if id := ReadIdentity(p.account()); id == nil || id.AccountUUID != "u-1" || id.EmailAddress != "a@example.org" {
t.Fatalf("%+v", id)
}
if ReadIdentity("/nonexistent/.claude.json") != nil {
t.Fatal("an identity from nothing")
}
writeFile(t, p.account(), `{}`)
if ReadIdentity(p.account()) != nil {
t.Fatal("an identity from an empty file")
}
}
// ---- the licence, ADR 0206 ----------------------------------------------------------------------------
func TestWhatANodeHoldsIsReportedWithFingerprintsAndItsAccountNeverAToken(t *testing.T) {
p, _ := node(t, "laptop")
writeFile(t, p.credentials(), `{"claudeAiOauth":{"accessToken":"at-secret","refreshToken":"rt-secret","expiresAt":2000,"refreshTokenExpiresAt":9000}}`)
writeFile(t, p.account(), `{"oauthAccount":{"accountUuid":"u-1","emailAddress":"a@example.org"}}`)
h := HoldingsOf(p)
if h.Node != "laptop" || h.Identity.AccountUUID != "u-1" || *h.Kind != "subscription" || !h.Refresh.Present ||
!strings.HasPrefix(*h.Refresh.Fingerprint, "sha256:") || h.Access.ExpiresAt != 2000 || h.ChangedAt == nil {
t.Fatalf("%+v", h)
}
raw, _ := json.Marshal(h)
if strings.Contains(string(raw), "at-secret") || strings.Contains(string(raw), "rt-secret") {
t.Fatalf("a token is in the report: %s", raw)
}
var keys map[string]any
_ = json.Unmarshal(raw, &keys)
for k := range keys {
if strings.Contains(strings.ToLower(k), "token") || strings.Contains(strings.ToLower(k), "secret") {
t.Fatalf("a field the runtime would refuse: %s", k)
}
}
// The manager reads exactly this shape.
if _, err := time.Parse(time.RFC3339Nano, *h.ChangedAt); err != nil {
t.Fatalf("the manager cannot read the report's time: %v", err)
}
}
func TestTheGrantAnswersOnlyAWaitingLoginSealedToTheManagersKey(t *testing.T) {
p, _ := node(t, "laptop")
manager, _ := GenerateKeyPair()
if a, _ := GrantFor(p, manager.PublicKey); a.Sealed != nil || a.Waiting == nil || *a.Waiting {
t.Fatalf("%+v", a)
}
writeFile(t, p.credentials(), `{"claudeAiOauth":{"accessToken":"at","refreshToken":"rt-login","expiresAt":1}}`)
writeFile(t, p.account(), `{"oauthAccount":{"accountUuid":"u-9"}}`)
a, err := GrantFor(p, manager.PublicKey)
if err != nil || a.Identity.AccountUUID != "u-9" {
t.Fatalf("%+v %v", a, err)
}
plain, _ := Open(*a.Sealed, manager.PrivateKey)
if !strings.Contains(plain, `"refreshToken":"rt-login"`) {
t.Fatalf("opened %s", plain)
}
raw, _ := json.Marshal(a)
if strings.Contains(string(raw), "rt-login") {
t.Fatal("the refresh token crossed in the clear")
}
}
// seat answers `current` as the manager does: the grant sealed to the key the node sent.
func seat(t *testing.T, licence, token string, gen int64, asked *[]string) Ask {
return func(address string, args any) (json.RawMessage, error) {
*asked = append(*asked, address)
key := args.(map[string]any)["public_key"].(string)
g, _ := json.Marshal(Grant{AccessToken: token, ExpiresAt: now + 3_600_000})
box, err := Seal(string(g), key)
if err != nil {
t.Fatal(err)
}
return json.Marshal(Current{Licence: licence, Kind: "subscription", Generation: gen, Sealed: &box})
}
}
func TestANewerGenerationFetchesTheTokenOnceByTheSeatsVerb(t *testing.T) {
p, w := node(t, "laptop")
var asked []string
ask := seat(t, "personal", "at-1", 3, &asked)
if _, err := OnBinding(p, &BindingState{Licence: "personal", Kind: "subscription", Generation: 3}, ask, writer(w)); err != nil {
t.Fatal(err)
}
if len(asked) != 1 || asked[0] != "seat:anthropic-licence-manager.current" || creds(t, p)["accessToken"] != "at-1" {
t.Fatalf("asked %v, credentials %v", asked, creds(t, p))
}
if done, _ := OnBinding(p, &BindingState{Licence: "personal", Kind: "subscription", Generation: 3}, ask, writer(w)); done != "" || len(asked) != 1 {
t.Fatal("an equal generation asked again")
}
if HoldingsOf(p).Generation != 3 || w["managed-mcp.json"] == "" {
t.Fatal("the generation or the managed files were not written")
}
}
func TestTheTokenANodeIsHandedReplacesALoginsGrantAndLeavesNoRefreshToken(t *testing.T) {
p, w := node(t, "laptop")
writeFile(t, p.credentials(), `{"claudeAiOauth":{"accessToken":"at-old","refreshToken":"rt-spent","expiresAt":`+
strings.TrimSpace(string(mustJSON(now+7_200_000)))+`}}`)
var asked []string
out, err := Pull(p, seat(t, "personal", "at-new", 1, &asked), writer(w))
if err != nil || out["applied"] != true {
t.Fatalf("%v %v", out, err)
}
c := creds(t, p)
if c["accessToken"] != "at-new" || c["refreshToken"] != nil || HoldingsOf(p).Refresh.Present {
t.Fatalf("%v", c)
}
}
func mustJSON(v any) []byte { b, _ := json.Marshal(v); return b }
// ---- MCP servers in state, ADR 0201 -------------------------------------------------------------------
// bus is the `servers` state as every node in a test shares it, with each node's watch.
type bus struct {
kept map[string]map[string]any
watchers []func(ServerChange)
}
func (b *bus) Put(key string, value any) error {
v := value.(map[string]any)
b.kept[key] = v
for _, w := range b.watchers {
w(ServerChange{Key: key, Op: "put", Value: v})
}
return nil
}
func (b *bus) Delete(key string) error {
delete(b.kept, key)
for _, w := range b.watchers {
w(ServerChange{Key: key, Op: "delete"})
}
return nil
}
func (b *bus) Keys() ([]string, error) {
var out []string
for k := range b.kept {
out = append(out, k)
}
return out, nil
}
// join is a node joining: its view takes the current state, then every change.
func (b *bus) join(p Paths, w map[string]string) *ServerView {
v := NewServerView(p)
for k, val := range b.kept {
_, _ = OnServerChange(v, ServerChange{Key: k, Op: "put", Value: val}, p, writer(w))
}
b.watchers = append(b.watchers, func(c ServerChange) { _, _ = OnServerChange(v, c, p, writer(w)) })
return v
}
func noOthers() ([]string, error) { return nil, nil }
func TestRegisteringHerePutsItUnderThisNodesKeyAndAsksAboutTheOthers(t *testing.T) {
p, w := node(t, "laptop")
b := &bus{kept: map[string]map[string]any{}}
v := b.join(p, w)
r, err := RegisterServer(p, Registration{Name: "search", Entry: map[string]any{"type": "http", "url": "https://s.example/mcp"}}, b, v, writer(w),
func() ([]string, error) { return []string{"laptop", "server", "desktop"}, nil })
if err != nil || r["here"] != "changed" || !strings.Contains(r["also"].(string), "server, desktop") || b.kept["laptop.search"] == nil {
t.Fatalf("%v %v %v", r, err, b.kept)
}
if !strings.Contains(w["managed-mcp.json"], `"search"`) {
t.Fatal("not rendered")
}
}
func TestEveryNodeRegistrationReachesTheOthersAndALateNodeReadsIt(t *testing.T) {
a, wa := node(t, "laptop")
s, ws := node(t, "server")
b := &bus{kept: map[string]map[string]any{}}
va := b.join(a, wa)
b.join(s, ws)
_, _ = RegisterServer(a, Registration{Name: "docs", Entry: map[string]any{"type": "stdio", "command": "docs-mcp"}, Nodes: []string{"all"}}, b, va, writer(wa), noOthers)
if Registered(s)["docs"] == nil || !strings.Contains(ws["managed-mcp.json"], "docs-mcp") {
t.Fatalf("the other node did not take it: %v", Registered(s))
}
late, wl := node(t, "desktop")
b.join(late, wl)
if Registered(late)["docs"] == nil {
t.Fatal("a node joining later did not read the current set")
}
_, _ = RegisterServer(a, Registration{Name: "docs", Nodes: []string{"all"}}, b, va, writer(wa), noOthers)
if Registered(s)["docs"] != nil || Registered(late)["docs"] != nil {
t.Fatal("an unregistration did not reach every node")
}
}
func TestANodesOwnRegistrationOverridesTheOneForEveryNode(t *testing.T) {
a, wa := node(t, "laptop")
s, ws := node(t, "server")
b := &bus{kept: map[string]map[string]any{}}
va := b.join(a, wa)
b.join(s, ws)
_, _ = RegisterServer(a, Registration{Name: "x", Entry: map[string]any{"type": "http", "url": "https://all"}, Nodes: []string{"all"}}, b, va, writer(wa), noOthers)
_, _ = RegisterServer(a, Registration{Name: "x", Entry: map[string]any{"type": "http", "url": "https://laptop"}}, b, va, writer(wa), noOthers)
if Registered(a)["x"]["url"] != "https://laptop" || Registered(s)["x"]["url"] != "https://all" {
t.Fatalf("%v %v", Registered(a), Registered(s))
}
r, _ := RegisterServer(a, Registration{Name: "x"}, b, va, writer(wa), noOthers)
if !strings.Contains(r["still"].(string), "still applies here") || Registered(a)["x"]["url"] != "https://all" {
t.Fatalf("%v", r)
}
}
func TestABadEntryIsRefusedBeforeAnythingIsPut(t *testing.T) {
p, w := node(t, "laptop")
b := &bus{kept: map[string]map[string]any{}}
v := b.join(p, w)
r, _ := RegisterServer(p, Registration{Name: "mesh", Entry: map[string]any{"type": "http", "url": "https://x"}}, b, v, writer(w), noOthers)
if r["registered"] != false || len(b.kept) != 0 {
t.Fatalf("%v %v", r, b.kept)
}
if done, _ := OnServerChange(v, ServerChange{Key: "server.b", Op: "put", Value: map[string]any{"type": "http", "url": "https://b"}}, p, writer(w)); done != "" {
t.Fatal("another node's key changed this one")
}
}
// An API key goes to the manager sealed to its key, never in the clear, and its file is gone afterwards.
func TestAnAPIKeyIsHandedOverSealedAndItsFileRemoved(t *testing.T) {
p, _ := node(t, "laptop")
manager, _ := GenerateKeyPair()
file := filepath.Join(p.Home, "api-key")
writeFile(t, file, "sk-ant-api03-secret\n")
var sent []string
ask := func(address string, args any) (json.RawMessage, error) {
raw, _ := json.Marshal(args)
sent = append(sent, address+" "+string(raw))
switch address {
case "seat:anthropic-licence-manager.public-key":
return json.Marshal(map[string]any{"public_key": manager.PublicKey})
case "seat:anthropic-licence-manager.adopt":
box := args.(map[string]any)["sealed"].(SealedBox)
if key, err := Open(box, manager.PrivateKey); err != nil || key != "sk-ant-api03-secret" {
t.Fatalf("the manager opened %q, %v", key, err)
}
return json.Marshal(map[string]any{"adopted": true})
case "seat:anthropic-licence-manager.switch":
return json.Marshal(map[string]any{"licence": "api"})
}
t.Fatalf("asked %s", address)
return nil, nil
}
out, err := AddAPIKey(p, "api", file, true, ask)
if err != nil || out["file"] != "removed" || out["switched"] == nil {
t.Fatalf("%v %v", out, err)
}
if _, err := os.Stat(file); !os.IsNotExist(err) {
t.Fatal("the key file is still there")
}
if strings.Contains(strings.Join(sent, "\n"), "sk-ant") {
t.Fatalf("the key crossed in the clear: %v", sent)
}
}
@@ -1,198 +0,0 @@
package main
// The agent's credentials file, and whether an offered grant may replace what it holds (novox/hq ADR 0183,
// ADR 0206, design 36 §5). Pure where it decides, so the rules are tested without a file.
//
// The file is the vendor's: `{ claudeAiOauth: { accessToken, expiresAt, refreshTokenExpiresAt?, scopes?,
// subscriptionType?, rateLimitTier? }, ... }`. A node bound to a licence never holds a refresh token, so
// the one this module writes never carries one; a refresh token found there is a person's login.
//
// The lineage rule is the predecessor's, with the incidents that earned it: a rotation of the same licence
// is applied only if newer; a grant re-issued by a login is adopted whatever its expiry; a switch to another
// licence is applied regardless, because across licences the expiries are unrelated numbers.
import (
"bytes"
"encoding/json"
"math"
"os"
"path/filepath"
)
// Grant is what the manager hands a node: an access token and its expiries, never a refresh token.
type Grant struct {
AccessToken string `json:"accessToken"`
ExpiresAt int64 `json:"expiresAt"`
RefreshTokenExpiresAt *int64 `json:"refreshTokenExpiresAt,omitempty"`
Scopes []string `json:"scopes,omitempty"`
SubscriptionType string `json:"subscriptionType,omitempty"`
RateLimitTier string `json:"rateLimitTier,omitempty"`
}
// Decision is whether a handed grant is applied, and why not.
type Decision struct {
Apply bool
Reissued bool
Reason string // already-current | not-newer
}
// generationTolerance: two refresh-token expiries within a day are one lineage; a login starts a fresh
// window weeks away.
const generationTolerance = 24 * 60 * 60 * 1000
func sameGeneration(a, b *int64) bool {
if a == nil || b == nil {
return true
}
return math.Abs(float64(*a-*b)) <= generationTolerance
}
// DecideApply says whether an offered grant replaces the one held; switch is a move to another licence.
func DecideApply(local *Grant, offered Grant, switching bool) Decision {
if local == nil || local.AccessToken == "" {
return Decision{Apply: true}
}
if local.AccessToken == offered.AccessToken {
return Decision{Reason: "already-current"}
}
reissued := !sameGeneration(local.RefreshTokenExpiresAt, offered.RefreshTokenExpiresAt)
if !switching && !reissued && local.ExpiresAt >= offered.ExpiresAt {
return Decision{Reason: "not-newer"}
}
return Decision{Apply: true, Reissued: reissued}
}
// Credentials is the file as found, every key kept — the vendor's other keys are not this module's.
type Credentials map[string]any
func (c Credentials) oauth() map[string]any {
o, _ := c["claudeAiOauth"].(map[string]any)
return o
}
// ReadCredentials reads the file, keeping numbers as written; nil when there is none.
func ReadCredentials(path string) Credentials {
raw, err := os.ReadFile(path)
if err != nil {
return nil
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
var c Credentials
if dec.Decode(&c) != nil {
return nil
}
return c
}
func number(v any) (int64, bool) {
switch n := v.(type) {
case json.Number:
i, err := n.Int64()
if err != nil {
f, err := n.Float64()
return int64(f), err == nil
}
return i, true
case float64:
return int64(n), true
case int64:
return n, true
}
return 0, false
}
// GrantOf is the grant the file holds, or nil.
func GrantOf(c Credentials) *Grant {
o := c.oauth()
at, _ := o["accessToken"].(string)
if at == "" {
return nil
}
g := &Grant{AccessToken: at}
g.ExpiresAt, _ = number(o["expiresAt"])
if v, ok := number(o["refreshTokenExpiresAt"]); ok {
g.RefreshTokenExpiresAt = &v
}
return g
}
// HoldsLogin says the file holds a refresh token — which this module never writes, so a person's login.
func HoldsLogin(c Credentials) bool {
rt, _ := c.oauth()["refreshToken"].(string)
return rt != ""
}
// RefreshTokenOf is the refresh token a login left, or "".
func RefreshTokenOf(c Credentials) string {
rt, _ := c.oauth()["refreshToken"].(string)
return rt
}
// WithGrant lays the handed grant over what is there, and deletes any refresh token.
func WithGrant(local Credentials, g Grant) Credentials {
next := Credentials{}
for k, v := range local {
next[k] = v
}
oauth := map[string]any{}
for k, v := range local.oauth() {
oauth[k] = v
}
oauth["accessToken"] = g.AccessToken
oauth["expiresAt"] = g.ExpiresAt
if g.RefreshTokenExpiresAt != nil {
oauth["refreshTokenExpiresAt"] = *g.RefreshTokenExpiresAt
}
if len(g.Scopes) > 0 {
oauth["scopes"] = g.Scopes
}
if g.SubscriptionType != "" {
oauth["subscriptionType"] = g.SubscriptionType
}
if g.RateLimitTier != "" {
oauth["rateLimitTier"] = g.RateLimitTier
}
delete(oauth, "refreshToken")
next["claudeAiOauth"] = oauth
return next
}
// ReplacedBy is the handed grant in place of the old licence's, whole — scopes and subscription included;
// only keys outside the grant stay. No refresh token survives.
func ReplacedBy(local Credentials, g Grant) Credentials {
next := Credentials{}
for k, v := range local {
if k != "claudeAiOauth" {
next[k] = v
}
}
return WithGrant(next, g)
}
// WriteCredentials writes atomically at 0600: a partial credentials file must never be read as a whole one.
func WriteCredentials(path string, c Credentials) error {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
raw, err := indented(c)
if err != nil {
return err
}
tmp := path + ".mesh-tmp"
if err := os.WriteFile(tmp, raw, 0o600); err != nil {
return err
}
return os.Rename(tmp, path)
}
// indented is JSON as the agent's own files are written: two-space indent, a trailing newline, nothing
// escaped that need not be.
func indented(v any) ([]byte, error) {
var b bytes.Buffer
enc := json.NewEncoder(&b)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
err := enc.Encode(v)
return b.Bytes(), err
}
@@ -1,84 +0,0 @@
package main
// Which account the agent is logged in as (novox/hq ADR 0183): not in the token, but in the agent's own
// state file beside the home, `~/.claude.json` → `oauthAccount`. Read to report and attribute a login;
// written, three keys and nothing else, when a licence is switched, so the account Claude Code shows is
// the one whose token it now holds.
import (
"bytes"
"encoding/json"
"os"
)
// Identity is an account as the agent's state file names it.
type Identity struct {
AccountUUID string `json:"accountUuid"`
EmailAddress string `json:"emailAddress,omitempty"`
OrganizationUUID string `json:"organizationUuid,omitempty"`
}
func readState(path string) (map[string]any, bool) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, false
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
var m map[string]any
if dec.Decode(&m) != nil || m == nil {
return nil, false
}
return m, true
}
// ReadIdentity is the account the state file names, or nil — never a guess.
func ReadIdentity(path string) *Identity {
m, ok := readState(path)
if !ok {
return nil
}
a, _ := m["oauthAccount"].(map[string]any)
uuid, _ := a["accountUuid"].(string)
if uuid == "" {
return nil
}
id := &Identity{AccountUUID: uuid}
id.EmailAddress, _ = a["emailAddress"].(string)
id.OrganizationUUID, _ = a["organizationUuid"].(string)
return id
}
// WriteIdentity points the state file's account at id, keeping every other key as found; answers whether
// the file changed. A file that is there and cannot be read as an object is left alone.
func WriteIdentity(path string, id Identity) (bool, error) {
m, ok := readState(path)
if !ok {
if _, err := os.Stat(path); err == nil {
return false, nil
}
m = map[string]any{}
}
current, _ := m["oauthAccount"].(map[string]any)
if current == nil {
current = map[string]any{}
}
e, _ := current["emailAddress"].(string)
o, _ := current["organizationUuid"].(string)
if current["accountUuid"] == id.AccountUUID && e == id.EmailAddress && o == id.OrganizationUUID {
return false, nil
}
current["accountUuid"] = id.AccountUUID
current["emailAddress"] = id.EmailAddress
current["organizationUuid"] = id.OrganizationUUID
m["oauthAccount"] = current
raw, err := indented(m)
if err != nil {
return false, err
}
tmp := path + ".mesh-tmp"
if err := os.WriteFile(tmp, raw, 0o600); err != nil {
return false, err
}
return true, os.Rename(tmp, path)
}
@@ -1,12 +0,0 @@
package main
// instructionsText is the managed instruction file, generated from the TypeScript renderer it replaced so
// the file under the agent's managed directory did not change by a byte when the module moved to Go;
// a test holds it to that renderer's own output (testdata/rendered-by-typescript.json).
func instructionsText(node, role string) string {
return "# This machine is a node of a Novox mesh\n\nWritten by the mesh's `claude-code` module. Edit the module's settings or the catalogue, never this file:\nit is rewritten whenever the module renders.\n\n## Who this node is\n\n- **Node:** `" +
node +
"`\n- **Role:** " +
role +
"\n- The other nodes, their roles and what runs where: ask the controller (`mesh-controller.nodes`,\n `mesh-controller.node`). Nothing here lists them, because a copy drifts.\n\n## How a session on this mesh works\n\nThe console is the only way to the mesh: the MCP server named `mesh`. It offers five tools, and\neverything else is an address you find and call through them:\n\n- `mesh_search` — words in, matching addresses out. `mesh_describe` — one address's arguments.\n- `mesh_call` — call an address. A seat the mesh holds once is `<seat>.<verb>` (the mesh's own verbs\n are `mesh-controller.<verb>`: `status`, `plan`, `node`, `assign`, `push`, `settings`);\n a module on a machine is `<node>/<module>.<tool>`.\n- `mesh_overview` and `mesh_machine` — the mesh's seats and machines, and what one machine runs.\n\n- **Symptom first.** For an error, a failing service or anything unexpected, search the record with the\n literal text before forming a hypothesis: the records module's `records_search`, then\n `records_read`.\n- **Ask the mesh before changing it**, and change it through the controller's verbs or the catalogue.\n- **A licence** through the `anthropic-licence-manager` seat's verbs. Never edit the agent's credentials\n file by hand, never print or ask for a token.\n\n## Hard rules\n\n- A file the mesh manages is changed through the verb or the catalogue that owns it, never on disk. If\n unsure, `mesh-controller.plan` for the node says what the mesh writes there.\n- Never write to a store's database by hand; schema changes are numbered migrations.\n- Never push to a main branch: a branch, a pull request, and a human approval for every merge.\n- The mesh creates no symlinks, and nobody else does either.\n- A package is declared in a module, never installed by hand.\n\n## Conventions\n\n- Commit messages are concise, in the imperative, about why.\n- Test before pushing: nodes update unattended.\n- The playbooks in the record say how research, decisions, designs, issues and hand-offs are done.\n"
}
-384
View File
@@ -1,384 +0,0 @@
// claude-code's bundle (novox/hq design 36, ADR 0183, ADR 0206): a binary the node's runtime launches over
// stdio as the operator account (ADR 0193) and is the bus for (ADR 0198). It is given its state directory
// and two files the mesh renders into it (ADR 0192), beside the runtime's own words.
//
// At start it renders the agent's managed directory, reports what this node holds as the module's
// `holdings` state and again whenever the credentials file changes, watches the licence manager's
// `bindings` state for this node and fetches the token when it says so, and watches the module's
// `servers` state — every node's MCP server registrations (ADR 0201). node.go holds the logic.
//
// stdout is the MCP channel; everything this module says, it says on stderr.
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
)
func say(format string, args ...any) {
fmt.Fprintf(os.Stderr, "[claude-code] "+format+"\n", args...)
}
// writeManaged writes one managed file as root, only when its content changed. From a staged file, never
// /dev/stdin: a child's input may be a socket, which /dev/stdin cannot open (found on the first assignment).
func writeManaged(name, content string) (string, error) {
path := filepath.Join(ManagedDir, name)
if was, err := os.ReadFile(path); err == nil && string(was) == content {
return name + ": unchanged", nil
}
staged, err := os.MkdirTemp("", "claude-code-")
if err != nil {
return "", err
}
defer os.RemoveAll(staged)
source := filepath.Join(staged, name)
if err := os.WriteFile(source, []byte(content), 0o644); err != nil {
return "", err
}
args := []string{"install", "-D", "-m", "0644", source, path}
if os.Geteuid() != 0 {
args = append([]string{"sudo", "-n"}, args...)
}
if out, err := exec.Command(args[0], args[1:]...).CombinedOutput(); err != nil {
return "", fmt.Errorf("%s: could not be written to %s (%s); the module writes there through the operator account's passwordless sudo",
name, ManagedDir, strings.TrimSpace(string(out)))
}
return name + ": written", nil
}
// ask is a tool on the bus, through the runtime: its answer is the tool's value.
func ask(address string, args any) (json.RawMessage, error) { return stdio.Ask(address, args) }
// stateOf adapts the SDK's state to what node.go asks of one.
type stateOf struct{ s stdio.KeptState }
func (s stateOf) Put(key string, value any) error { _, err := s.s.Put(key, value); return err }
func (s stateOf) Delete(key string) error { return s.s.Delete(key) }
func (s stateOf) Keys() ([]string, error) { return s.s.Keys() }
// nodesRunningMe is the nodes claude-code runs on, from the controller's list of modules — for the register
// tool's question.
func nodesRunningMe() ([]string, error) {
raw, err := ask("seat:mesh-controller.modules", map[string]any{})
if err != nil {
return nil, err
}
var answer struct {
Output string `json:"output"`
}
text := string(raw)
if json.Unmarshal(raw, &answer) == nil && answer.Output != "" {
text = answer.Output
}
for _, line := range strings.Split(text, "\n") {
if !strings.HasPrefix(line, "claude-code ") {
continue
}
_, on, ok := strings.Cut(line, " on ")
if !ok || strings.TrimSpace(on) == "nothing" {
return nil, nil
}
var out []string
for _, n := range strings.Split(on, ",") {
if n = strings.TrimSpace(n); n != "" {
out = append(out, n)
}
}
return out, nil
}
return nil, nil
}
func fingerprintOfFile(path string) any {
raw, err := os.ReadFile(path)
if err != nil {
return nil
}
return Fingerprint(string(raw))
}
func status(p Paths) map[string]any {
creds := ReadCredentials(p.credentials())
var token any
if g := GrantOf(creds); g != nil {
token = map[string]any{"fingerprint": Fingerprint(g.AccessToken), "expiresAt": stamp(g.ExpiresAt), "loginWaiting": HoldsLogin(creds)}
}
var managed []map[string]any
for _, f := range []string{"managed-mcp.json", "managed-settings.json", "CLAUDE.md"} {
path := filepath.Join(ManagedDir, f)
managed = append(managed, map[string]any{"file": path, "fingerprint": fingerprintOfFile(path)})
}
var licence any
var b Binding
if readJSON(p.binding(), &b) {
licence = b
}
names := []string{}
for n := range Registered(p) {
names = append(names, n)
}
return map[string]any{"node": p.Node, "licence": licence, "token": token, "holdings": HoldingsOf(p),
"managed": managed, "registered": names}
}
func str(description string) map[string]any {
return map[string]any{"type": "string", "description": description}
}
// nodesOf reads the tools' `nodes` argument: absent is this node, "all" every node, else a list.
func nodesOf(v any) []string {
s, _ := v.(string)
s = strings.TrimSpace(s)
switch s {
case "":
return nil
case "all":
return []string{"all"}
}
var out []string
for _, n := range strings.Split(s, ",") {
if n = strings.TrimSpace(n); n != "" {
out = append(out, n)
}
}
return out
}
func tools(p Paths, servers ServerState, view *ServerView) []stdio.Tool {
nodesArg := str(`more nodes: "all" for every node running claude-code, or a comma-separated list; absent is this node only`)
return []stdio.Tool{
{Name: "claude_code_status",
Description: "Claude Code on this machine as the mesh configured it: the licence it holds and when its token expires, what it reports holding, the managed files, the MCP servers registered here. Fingerprints only, never a token.",
Run: func(map[string]any) (any, error) { return status(p), nil }},
{Name: "claude_code_render",
Description: "Write Claude Code's managed directory now, from the mesh's facts, this module's settings and the servers registered here.",
Run: func(map[string]any) (any, error) {
out, err := RenderNow(p, writeManaged)
return map[string]any{"rendered": out}, err
}},
{Name: "claude_code_pull",
Description: "Ask the licence manager for this node's current token now and apply it, rather than waiting for its binding to change.",
Run: func(map[string]any) (any, error) { return Pull(p, ask, writeManaged) }},
{Name: "claude_code_grant",
Description: "For the licence manager (ADR 0206): the full grant in this node's credentials file — a login made here — sealed to the public key given, with the account it belongs to. Nothing when no login is waiting. Never answers a token in the clear.",
Input: map[string]any{"public_key": str("the manager's public key, PEM; the grant opens only with its private half")},
Run: func(a map[string]any) (any, error) {
key, _ := a["public_key"].(string)
if !strings.Contains(key, "PUBLIC KEY") {
return nil, errors.New("claude_code_grant seals to a public key, and none was given")
}
return GrantFor(p, key)
}},
{Name: "claude_code_add_api_key",
Description: "Add an Anthropic API key as a licence (ADR 0209): read from a file on this machine — never typed as an argument — sealed to the licence manager's key, handed over, and the file removed once taken. With use_here, this machine switches to it at once; other machines move with the manager's `switch`.",
Input: map[string]any{
"name": str("the licence's name, e.g. api"),
"file": str("a file on this machine holding the key, e.g. ~/api-key (removed once the manager has it)"),
"use_here": map[string]any{"type": "boolean", "description": "switch this machine to the new licence"},
},
Run: func(a map[string]any) (any, error) {
name, _ := a["name"].(string)
file, _ := a["file"].(string)
if strings.TrimSpace(name) == "" || strings.TrimSpace(file) == "" {
return nil, errors.New("name and file are required")
}
if strings.HasPrefix(file, "~/") {
file = filepath.Join(p.Home, file[2:])
}
useHere, _ := a["use_here"].(bool)
return AddAPIKey(p, strings.TrimSpace(name), file, useHere, ask)
}},
{Name: "claude_code_mcp_list",
Description: "The MCP servers registered through this module: those that apply on this node (beside the console, `mesh`, and those set in the module's settings), and every registration on the mesh, by key — `all.<server>` for every node, `<node>.<server>` for one.",
Run: func(map[string]any) (any, error) {
keys, err := servers.Keys()
return map[string]any{"here": Registered(p), "everywhere": keys}, err
}},
{Name: "claude_code_mcp_register",
Description: "Register an MCP server with Claude Code on this node, every node, or a list — an http/sse server by url, or a stdio server by command. Kept on the bus, so a node that joins later takes it too. Never put a secret in env or headers: the mesh refuses one.",
Input: map[string]any{
"name": str("the server's name: letters, digits, - and _"),
"type": str("http, sse or stdio (default stdio when a command is given, http when a url is)"),
"url": str("an http or sse server's url"),
"command": str("a stdio server's program"),
"args": map[string]any{"type": "array", "description": "a stdio server's arguments"},
"env": map[string]any{"type": "object", "description": "a stdio server's environment"},
"headers": map[string]any{"type": "object", "description": "an http server's headers"},
"nodes": nodesArg,
},
Run: func(a map[string]any) (any, error) {
entry := map[string]any{}
if t, _ := a["type"].(string); t != "" {
entry["type"] = t
} else if _, hasURL := a["url"]; hasURL {
entry["type"] = "http"
} else {
entry["type"] = "stdio"
}
for _, k := range []string{"url", "command", "args", "env", "headers"} {
if v, ok := a[k]; ok {
entry[k] = v
}
}
name, _ := a["name"].(string)
return RegisterServer(p, Registration{Name: name, Entry: entry, Nodes: nodesOf(a["nodes"])}, servers, view, writeManaged, nodesRunningMe)
}},
{Name: "claude_code_mcp_unregister",
Description: "Remove an MCP server registered through this module, on this node or more.",
Input: map[string]any{"name": str("the server's name"), "nodes": nodesArg},
Run: func(a map[string]any) (any, error) {
name, _ := a["name"].(string)
return RegisterServer(p, Registration{Name: name, Nodes: nodesOf(a["nodes"])}, servers, view, writeManaged, nodesRunningMe)
}},
}
}
// persist asks the state again until it answers: its bucket or the bus's grant may arrive after the module.
func persist(what string, attempt func() error, done func(refusals int)) {
waits := []time.Duration{2 * time.Second, 5 * time.Second, 10 * time.Second, 30 * time.Second}
for n := 0; ; n++ {
err := attempt()
if err == nil {
done(n)
return
}
pause := time.Minute
if n < len(waits) {
pause = waits[n]
}
say("%s not yet (%v); asking again in %s", what, err, pause)
time.Sleep(pause)
}
}
func main() {
p, launched := PathsFrom(os.Getenv)
if !launched {
// Outside a launch — a build, a check — it serves nothing and says why.
say("not launched by the runtime with this module's words; serving no tools")
if err := stdio.Serve("", nil); err != nil {
os.Exit(1)
}
return
}
if _, err := Keypair(p); err != nil {
say("this module's key: %v", err)
}
if out, err := RenderNow(p, writeManaged); err != nil {
say("%v", err)
} else {
for _, line := range out {
if !strings.HasSuffix(line, "unchanged") {
say("%s", line)
}
}
}
servers := stateOf{stdio.State("servers")}
view := NewServerView(p)
go run(p, view)
if err := stdio.Serve("", tools(p, servers, view)); err != nil {
say("%v", err)
os.Exit(1)
}
}
// run is the module's long-running half, beside the tools (ADR 0198).
func run(p Paths, view *ServerView) {
// Every node's MCP servers: the whole current set first, then each change (ADR 0201).
go persist("watching the MCP servers", func() error {
return stdio.State("servers").Watch("", func(c stdio.StateChange) error {
var value map[string]any
_ = json.Unmarshal(c.Value, &value)
if done, err := OnServerChange(view, ServerChange{Key: c.Key, Op: c.Op, Value: value}, p, writeManaged); err != nil {
say("taking %s %s: %v", c.Op, c.Key, err) // the view took it; the next render writes it
} else if done != "" {
say("%s", done)
}
return nil
})
}, func(n int) { say("watching the MCP servers%s", refusals(n)) })
// What this node holds (ADR 0206): at start — a node already logged in is reported at once — and on
// every change of the credentials file, polled, because the file is replaced by rename and a watch on
// the old inode would go quiet. Fingerprints and expiries only.
holdings := stdio.State("holdings")
reported := ""
report := func() {
now := HoldingsOf(p)
raw, _ := json.Marshal(now)
if string(raw) == reported {
return
}
persist("reporting what this node holds", func() error { _, err := holdings.Put(p.Node, now); return err }, func(int) {
reported = string(raw)
account := "no account"
if now.Identity != nil && now.Identity.EmailAddress != "" {
account = now.Identity.EmailAddress
}
line := "reported: " + account
if now.Kind != nil {
line += ", " + *now.Kind
}
if now.Refresh.Present {
line += ", a login waiting"
}
if now.Licence != nil {
line += fmt.Sprintf(", licence %s g%d", *now.Licence, now.Generation)
}
say("%s", line)
})
}
// What this node should hold (ADR 0206): the manager's `bindings` key for this node; a newer
// generation is fetched with the seat's `current`, sealed to this module's key.
go persist("watching this node's licence binding", func() error {
return stdio.State(Manager+".bindings").Watch(p.Node, func(c stdio.StateChange) error {
if c.Key != p.Node {
return nil
}
var b *BindingState
if c.Op == "put" {
b = &BindingState{}
if err := json.Unmarshal(c.Value, b); err != nil {
return nil
}
}
if done, err := OnBinding(p, b, ask, writeManaged); err != nil {
say("fetching this node's token failed: %v", err)
} else if done != "" {
say("%s", done)
}
go report()
return nil
})
}, func(n int) { say("watching this node's licence binding%s", refusals(n)) })
report()
var last string
for range time.Tick(5 * time.Second) {
info, err := os.Stat(p.credentials())
now := "absent"
if err == nil {
now = fmt.Sprintf("%d/%d", info.ModTime().UnixNano(), info.Size())
}
if now != last {
last = now
report()
}
}
}
func refusals(n int) string {
if n == 0 {
return ""
}
return fmt.Sprintf(" (after %d refusal(s))", n)
}

Some files were not shown because too many files have changed in this diff Show More