Compare commits

...
28 Commits
Author SHA1 Message Date
Ziad Arafat d3b9e0d333 Preflight the rootless podman subuid/subgid ranges in dot boxes
A fedora-toolbox pull dies inside the user namespace ('requested 998:998
for /var/lib/unbound') when the user has no /etc/subuid and /etc/subgid
range, and distrobox only shows podman's unpack error. dot boxes now
checks both files and prints the usermod + podman system migrate fix
before pulling; dot doctor reports the same condition.
tests/boxes-subid.sh covers range summing, small ranges and the hint.
2026-12-02 12:38:40 -07:00
Ziad Arafat 12258063ce remote-browser: make 'cli' a true passthrough and say so
cli used to share the flag parser with the built-in verbs, so a playwright-cli
argument that looked like ours could be swallowed. After 'cli' the args now go
through untouched, '--' is honoured, and the skill documents that the built-ins
are a convenience layer rather than a subset: goto/click/storage/tracing/route/
run-code/pdf/webmcp all work in the attached session with exit codes intact.
2026-12-02 12:29:47 -07:00
Ziad Arafat a21791c630 remote-browser: generalise deck-browser to any device, add a setup workflow
deck-browser assumed one host. remote-browser takes a profile per device
(transport ssh or direct, host, port, ws path, inspect URL) and gains
'profiles', 'setup' and 'check': check walks ssh -> port -> websocket
handshake -> attach -> tabs and prints the first failure instead of a
generic 'could not attach'. The skill ships references/setup.md, a checklist
for onboarding a device with the user, including per-browser toggle URLs, the
Chrome <136 fallback, and a symptom->cause table.
2026-12-02 12:25:45 -07:00
Ziad Arafat 8999c687f9 deck-browser: drive playwright-cli instead of a hand-rolled CDP client
Playwright documents connectOverCDP with a ws:// endpoint, and
playwright-cli attach --cdp=ws://127.0.0.1:9222/devtools/browser works against
the Deck's chrome://inspect toggle. That makes the 270-line stdlib CDP client
redundant: the wrapper is now 130 lines of bash that opens the tunnel, attaches
once and maps tabs/text/html/shot onto playwright-cli (plus a 'cli' passthrough
so agents can reach console, network and the rest without new code).
2026-12-02 12:20:43 -07:00
Ziad Arafat d306474f95 deck-browser: read the Deck's Chrome from arceus over CDP
The user browses on the Steam Deck; agents run on arceus. Chrome's per-instance
remote debugging (chrome://inspect toggle) exposes CDP only as a WebSocket at
/devtools/browser, so playwright attach cannot use it and the HTTP /json paths
return 403. bin/deck-browser speaks CDP directly with the standard library:
tabs, text, html, shot, status, plus an opt-in unsafe-eval. Read-only by design -
no click, type or navigate - because driving authenticated sessions is what gets
accounts restricted. Opens the SSH tunnel itself and reuses an existing one.

Registers the skill for every harness and tells agents it exists.
2026-12-02 12:18:08 -07:00
Ziad Arafat acb8191f13 Explain user-systemd noise instead of only repeating it
Home Manager's reloadSystemd reports the whole user manager before it
reloads anything, so one failed distro unit (xdg-desktop-portal* on a
host with no display, dbus-activated by an agent CLI) makes every
switch look broken. It starts none of those units.

dot doctor now prints the user session state, the failed units with a
reset-failed hint (--fix runs it), restart-looping units, and the units
in ~/.config/systemd/user that no home-manager generation owns. README
gains 'What belongs in dotfiles': the four gated units this repo
declares, the pi-workers file that is tracked but wired by hand, and
why portal and root units must stay out.

tests/doctor-systemd.sh covers the report and the --fix path.
2026-12-02 12:08:29 -07:00
Ziad Arafat 7ca1845213 Add dot sync for dotfiles-only updates
dot update also upgrades Flatpak apps, mise tools, Claude and checks for
missing apps, which is slow for a one-file change. dot sync pulls the
checkout with --ff-only and switches, nothing else; dot update
--switch-only is an alias. Serialise concurrent home-manager runs on
~/.config/dotfiles/switch.lock so two switches cannot fight over the Nix
store, and cover the path with tests/sync.sh.
2026-12-02 11:57:19 -07:00
Ziad Arafat c78b9a751d Package secretctl in every dotfiles profile 2026-12-02 10:56:09 -07:00
Ziad Arafat 769f43ab36 Split secretctl snapshots below the vault note limit 2026-12-02 10:41:54 -07:00
Ziad Arafat 9fdd63a6eb Add Bitwarden backup and restore for secretctl stores 2026-12-02 10:36:38 -07:00
Ziad Arafat 4b6d1a36fc Allow Chrome Flatpak to install web apps during setup 2026-12-02 10:32:04 -07:00
Ziad Arafat 74b24a267b Document required Authentik SSO for personal Vaultwarden 2026-12-02 10:17:46 -07:00
Ziad Arafat c9d7974d16 Document current Vaultwarden CLI setup 2026-12-02 10:10:27 -07:00
Ziad Arafat ea6b7ded17 Configure the Bitwarden server noninteractively 2026-12-02 09:50:06 -07:00
Ziad Arafat 86aed12d40 Select Bitwarden server by dotfiles profile 2026-12-02 09:48:36 -07:00
ziadarafat a69f108c27 Merge remote-tracking branch 'origin/main' 2026-12-02 09:20:38 -07:00
ziadarafat 50153a9a8e Save Pi worker and model configuration 2026-12-02 09:20:37 -07:00
Ziad cde0fd97fe bin/pi-spark: pi-lens covers post-edit checks, make verify-on-write opt-in 2026-12-01 15:57:59 -07:00
Ziad 665806b2cd bin/pi-spark: load pi-verify-on-write when the checkout is present 2026-12-01 15:32:25 -07:00
Ziad 3618086af0 pi-spark: seed small-model operating rules, raise Spark context to 64k
Baseline test: the 4B model made zero tool calls and invented mise syntax.
With an APPEND_SYSTEM of tool-first rules plus a golang-mise skill it built,
tested and ran a working CLI in 36 tool calls. Rules now live in
config/pi/small-model-APPEND_SYSTEM.md and are seeded per project; Ollama
serves 64k context, which measured equal or faster than 32k.
2026-12-01 15:07:19 -07:00
Ziad ffc0d6d83d bin/pi-spark: launch the pi agent against the local Spark model in tmux
Spark only implements thinking low/high, and pi's default reasoning level
(medium) makes its chat template raise, so the launcher pins the level and
drops the free-pi session env so pi reads ~/.pi/agent.
2026-12-01 11:56:23 -07:00
Ziad b70572b269 pi agent: spark models and a working wiki/lapis MCP set
- models.json: add spark:ablit and spark:4b from the local Ollama endpoint
  (OLLAMA_CONTEXT_LENGTH is now 32k on yveltal so long prompts fit)
- mcp.json: replace the stale ETV wikijs entry and WIKI_BEARER_TOKEN with
  the homelab wiki over _mcp and WIKI3_MCP_TOKEN, and add LaPis memory
2026-12-01 11:42:55 -07:00
Ziad Arafat c6199ec824 free-pi mcp: authenticate the wiki server with WIKI3_MCP_TOKEN
The wiki header looked up WIKI_BEARER_TOKEN, which does not exist in
secrets.txt, so free-pi reported 'wiki: failed' and the wiki tools were
missing from every session. Point the header at the secret the wiki-mcp
bridge and the skills already use.
2026-11-30 17:46:19 -07:00
Ziad Arafat e246c1328c Add Kontroll to Moonlander skill 2026-11-30 15:07:11 -07:00
Ziad Arafat 7bc67e42ac Add ZSA Moonlander skill for Riolu 2026-11-30 15:04:19 -07:00
Ziad Arafat b888fa5bc7 Verify Roku HDMI selection through active input status 2026-11-29 00:42:39 -07:00
Ziad Arafat df631c921c Add agent tool and skill for Roku TV HDMI-CEC 2026-11-29 00:37:15 -07:00
Ziad Arafat 632ae00711 fix(pi): use non-strict Cohere tools in free profile 2026-11-28 20:12:21 -07:00
29 changed files with 2495 additions and 82 deletions

No files matched your search

+199 -6
View File
@@ -41,15 +41,115 @@ curl -fsSL -H "Authorization: token $GITEA_TOKEN" \
| `DOTFILES_SKIP_SYSTEM=1` | Never call sudo. Everything in `$HOME` still works. |
| `DOTFILES_DIR` | Checkout location (default `~/.dotfiles`). |
On the personal desktop, `dot apps` gives the Chrome Flatpak user-scoped
write access to the two host directories used for web app launchers and
icons. Re-run `dot apps` to apply it to an existing installation, then quit
and reopen Chrome.
On SteamOS, the one sudo prompt makes `/nix` owned by `deck`. Nix then runs in single-user mode, with no daemon and no units in `/etc`.
Then, once per machine (`bw` already points at `https://vault.etvamerica.com`; override with `BW_SERVER=...`):
### Set up the Bitwarden CLI
Run these steps in the same terminal. If `bw` or `dot` is missing after
bootstrap, open a new terminal to pick up the installed tools.
1. Run `dot profile` and `bw status`. Check the server URL before signing in.
| Profile | Vaultwarden server |
| --- | --- |
| `full`, `headless` | `https://vault.godemperordoge.org` |
| `full-work` | `https://vault.etvamerica.com` |
If the server is wrong and the CLI is already signed in, run `bw logout`
and `unset BW_SESSION`. Then configure the matching URL. For example, on a
personal machine:
```bash
bw --nointeraction config server https://vault.godemperordoge.org
bw status
```
For a custom instance, set `BW_SERVER` to the same URL in the shell where
you run `dot secrets`.
2. Sign in using the method your vault requires. The **personal Vaultwarden
requires Authentik SSO**. Run this from a local desktop terminal so your
browser can complete the CLI's sign-in:
```bash
bw login --sso &&
BW_SESSION="$(bw unlock --raw)" && export BW_SESSION
```
If the personal vault prompts for an organization identifier, enter
`vaultwarden`. It is a placeholder for the self-hosted server's single
identity provider. For a work vault that requires SSO, use the identifier
supplied by your organization. Sign into the browser first, then use your
**vault master password** to unlock the CLI. If password login reports
**SSO sign-in is required**, use this SSO flow.
For a server that allows password login, capture the session without
printing it:
```bash
BW_SESSION="$(bw login 'your-vault-email@example.com' --raw)" && export BW_SESSION
```
If your server permits personal API-key login, you can use
`bw login --apikey` and then `bw unlock --raw`. The personal API key is
available under **Settings → Security → Keys** in the web vault.
If `bw status` already shows `locked`, skip login and run only
`BW_SESSION="$(bw unlock --raw)" && export BW_SESSION`. If it shows
`unlocked` in this terminal and the server is correct, continue.
3. Check that `bw status` shows `unlocked` and the expected server. Import
the dotfiles secrets, then lock the vault when finished.
```bash
dot secrets pull
bw lock
unset BW_SESSION
```
Use `dot secrets pull --wireguard` in place of `dot secrets pull` only if
you also want to import the saved WireGuard connections into NetworkManager.
The session key belongs in the current terminal only. See the
[Bitwarden CLI guide](https://bitwarden.com/help/cli/) for login and unlock
details, and [Git authentication](docs/git-auth.md) for the separate Git
credential sessions.
#### Back up and restore the secretctl store
With `bw` unlocked on the intended vault, run this on the source machine:
```bash
bw login && export BW_SESSION=$(bw unlock --raw)
dot secrets pull # ~/.ssh/id_ed25519, secrets.env, Claude/pi MCP config
dot secrets pull --wireguard # also import WireGuard connections into NetworkManager (sudo)
dot boxes # distrobox: general (Fedora), etv (AlmaLinux 10)
dot secrets push-secretctl
```
This saves all entries as encrypted secure-note parts to stay below
Bitwarden’s Notes limit. The manifest points to the newest complete
snapshot. Older parts stay in the vault. Restore also accepts the original
single-note backup format.
On the destination machine, unlock the same vault and restore the snapshot:
```bash
dot secrets pull-secretctl
secretctl check
```
The default file is `~/secrets.txt` (or `$SECRETCTL_FILE`, if set). Restore
creates a validated `0600` file and refuses to replace an existing file.
To restore separately for review, run
`dot secrets pull-secretctl "$HOME/secrets-restored.txt"` and validate it
with `secretctl --file "$HOME/secrets-restored.txt" check`.
These commands keep the secretctl entries separate from `dot secrets pull`
and its shell-sourced `secrets.env`.
After importing your secrets:
```bash
dot boxes # create the general and etv Distrobox containers
dot doctor
```
@@ -108,9 +208,11 @@ For a fresh installation, set `DOTFILES_PROFILE=full-work`. `headless` remains t
| Command | What |
|---|---|
| `dot sync` | `git pull --ff-only` then switch — apply small dotfiles edits without upgrading anything (see below) |
| `dot update` | `git pull`, switch, `flatpak update`, `mise upgrade`, `claude update` |
| `dot update --inputs` | same, plus bump `flake.lock` (nixpkgs, home-manager, plasma-manager, konsole_daynight) |
| `dot switch` | apply after editing Nix files |
| `dot update --switch-only` | alias for `dot sync` |
| `dot switch` | apply after editing Nix files, without pulling first |
| `dot profile headless` / `full` / `full-work` / `auto` | switch layers; then `dot switch` |
| `dot secrets push` | upload this machine's secrets.env, SSH keys and WireGuard configs to Bitwarden |
| `dot defguard` | preconfigure the Defguard VPN app for the home lab (see below) |
@@ -118,6 +220,38 @@ For a fresh installation, set `DOTFILES_PROFILE=full-work`. `headless` remains t
| `dot sounds` | build the Portal 2 sound theme from your Steam install |
| `dot doctor` | what's installed or missing |
### `dot update` versus `dot sync`
`dot update` is a maintenance run: process upgrades for Flatpak, mise and Claude
Code, a missing-app check (`dot apps`) and, with `--inputs`, a `flake.lock` bump.
That is slow and unnecessary when you only changed a dotfiles file — a secretctl
edit or a new package does not touch `flake.lock`.
`dot sync` does the small-change path and nothing else:
```bash
dot sync # git -C ~/.dotfiles pull --ff-only, then home-manager switch
dot sync headless # same, switching to another profile
dot update --switch-only # alias for dot sync
```
It never runs `flatpak update`, `mise upgrade`, `claude update`, `dot apps` or
`nix flake update`; `dot sync --inputs` is refused rather than ignored. Two
exceptions worth knowing:
- **A newly added package is still built once.** `secretctl` comes from `pkgs/`
and is compiled from source, so the first build may fetch a Go toolchain and
build dependencies far bigger than the tool. Later syncs reuse the store path.
If that build prints `git-minimal`/store-lock timeouts, another
Home Manager run is in progress — see the next point.
- **Switches are serialised.** `dot switch`, `dot sync` and `dot update` take
`$HOME/.config/dotfiles/switch.lock`; a second run prints the running pid and
waits instead of competing for the Nix store. Nothing needs to be started in a
second terminal — start one and let it finish. If you did start two, cancel the
newer one in its own terminal.
Run `bash tests/sync.sh` to check that the sync path stays upgrade-free.
`dot doctor` checks Nix startup, store/database access, broken profile links,
daemon versus single-user setup, `nix-command` and flakes, and the checkout's
flake files. This catches interrupted installers and feature overrides before
@@ -161,6 +295,53 @@ Apps that write their own settings (Claude Code, pi, Vesktop, Konsole profiles,
- **Defguard VPN** (home lab, `vpn.godemperordoge.org`): the desktop client is repackaged from the official `.deb` in `pkgs/defguard-client.nix`, so it runs natively on SteamOS (no WebKitGTK 4.1 there). `dot system` installs its root service (`config/defguard/defguard-service.service`, group `defguard`, a `resolvconf` → `resolvectl` shim where needed). Setup tokens are single-use and expire in 24 h, so Bitwarden holds a Defguard **API token** instead: create one in Defguard (your profile → *API tokens*) once, `dot secrets set DEFGUARD_API_TOKEN`, then on each new machine run `dot defguard` from home or over the VPN. It mints a fresh token and writes `~/.local/share/net.defguard/provisioning.json`, and the app sets itself up on its next start; you only sign in with Doge Home Lab.
- **Sounds:** `dot sounds` extracts Portal 2 sounds from your local Steam install (game assets stay out of git) into `~/.local/share/sounds/portal2`. Mapping: `config/sounds/portal2.json`.
## What belongs in dotfiles (and what does not)
`home-manager switch` links files and reloads the **user** systemd manager. It does
not own everything that manager runs, so anything it reports about units may be
about the host, not about this repository.
| Declared here (`systemd.user.*`) | Where | Profile | Why it belongs |
|---|---|---|---|
| `handoff`, `handoff-probe` + timer | `home/agents.nix` | all | ship `bin/handoff`/`bin/free-agent` from this repo |
| `fix-container-desktop-files` (path + oneshot) | `home/gui/apps.nix` | gui only | runs this repo's launcher rewriter |
| `konsole-daynight`, `daynight-hooks` | `home/gui/daynight.nix` | gui only | wrap the `konsole_daynight` flake input |
| `notification-sounds` | `home/gui/sounds.nix` | gui only | plays the sound theme `dot sounds` builds |
| `pi-workers` | `config/systemd/user/` | linked by hand | **not** installed by home-manager; wire it with `home.file` or drop it |
Everything else under `~/.config/systemd/user` on a machine (edge metrics, relays,
study timers) is a hand-written one-off. `dot doctor` lists those separately.
Two classes of unit must stay **out** of dotfiles:
- **Desktop-session units** the distro or the desktop environment owns, above all
`xdg-desktop-portal*`. Nix cannot know whether a session has a display, the
distro already defines them in `/usr/lib/systemd/user`, and shadowing them breaks
the desktop. Dotfiles' job on those is at most to mask them on headless hosts.
- **Root/system units** (netbird, Defguard, podman). `dot system` puts those in
`/etc`; they are not user-manager state and cannot be switched per profile.
### "The user systemd session is degraded"
Home Manager's `reloadSystemd` step asks `systemctl --user is-system-running`
*before* reloading and prints every failed unit. It starts none of them and cannot
clear them, so the same two lines reappear on every `dot switch` until the state is
reset. On a headless machine the usual cause is a portal unit: something asks D-Bus
for `org.freedesktop.portal.Desktop` (an agent CLI with notification support, an
Electron app), systemd starts the distro's `xdg-desktop-portal-gtk`, that process
has no display, and it times out into a failed state.
```bash
dot doctor # session state, failed units, restart loops, unmanaged units
dot doctor --fix # reset-failed the units it found (the session stops looking degraded)
systemctl --user mask xdg-desktop-portal xdg-desktop-portal-gtk # headless: stop the retries
```
`warning: unknown setting 'eval-cores'` / `'lazy-trees'` during activation is the
same kind of noise: those keys are Determinate Nix settings in `/etc/nix/nix.conf`,
while this repo pins `nix.package = pkgs.nix` (upstream) so the same flake works on
SteamOS and in containers. The warnings are harmless.
## Custom Pokémon rules
Reusable rules live in [`config/pokefetch`](config/pokefetch/README.md), including the Arceus holiday/weather preset and the Lugia day/night example. Add future presets there and enable one from your machine-local settings.
@@ -227,3 +408,15 @@ WEBTOP=1 tests/container-test.sh lscr.io/linuxserver/webtop:fedora-kde full webt
- Plasma only applies panel changes from plasma-manager at the next login. Its panel script deletes `plasma-org.kde.plasma.desktop-appletsrc` first, so `daynight-hooks` re-applies the wallpapers 20 s after login.
- Sensor IDs in the panel monitors are regexes. Avoid backslashes in them: KConfig unescapes them, and the JSON list then fails to parse.
- Managed browser policies show "Managed by your organization" in Chrome and Edge. That's expected.
- `dot boxes` fails mid-pull with `potentially insufficient UIDs or GIDs available in
user namespace (requested 998:998 for /var/lib/unbound)` when rootless podman has no
`/etc/subuid`/`/etc/subgid` range for you: the fedora-toolbox image contains uid 998
and the layer unpack cannot map it. `dot boxes` preflights this and `dot doctor`
reports it, but the fix is root:
```bash
grep -E "^$(id -un):" /etc/subuid /etc/subgid # empty or a tiny range?
sudo usermod --add-subuids 100000-165535 --add-subgids 100000-165535 "$(id -un)"
podman system migrate # rebuild the mapping; keeps images
```
If the store was created without a mapping, `podman system reset` (deletes images and
containers) then `dot boxes` again.
+225 -10
View File
@@ -149,8 +149,22 @@ cmd_nix() {
}
# ---------------------------------------------------------------- home-manager
# Two home-manager runs in one home fight over the Nix store (git-minimal lock)
# and over ~/.local/state/nix/profiles. Serialise them instead of racing.
switch_lock() {
local lock="$STATE_DIR/switch.lock"
have flock || return 0
exec 9>>"$lock" || return 0
if ! flock -n 9; then
warn "another dot switch/update is running (pid $(cat "$lock" 2>/dev/null || echo '?')); waiting for it to finish"
flock 9 || die "cannot lock $lock"
fi
printf '%s\n' "$$" >"$lock"
}
cmd_switch() {
[ -n "${1:-}" ] && cmd_profile "$1"
switch_lock
source_nix || die "nix missing: run dot nix"
ensure_nix_features
local attr backup_ext; attr="$(flake_attr)"
@@ -324,6 +338,11 @@ cmd_apps() {
done
[ ${#failed[@]} -eq 0 ] || warn "Flatpaks failed: ${failed[*]}"
ok "Flatpaks: $(( ${#missing[@]} - ${#failed[@]} )) installed, rest already present"
if [ "$(profile)" = full ] && flatpak_has com.google.Chrome; then
flatpak override --user '--filesystem=~/.local/share/applications:create' \
'--filesystem=~/.local/share/icons:create' com.google.Chrome ||
warn "Could not configure Chrome web app permissions"
fi
seed_xpipe
fi
@@ -348,26 +367,71 @@ seed_xpipe() {
ok "XPipe set to sync from RustyRaptor/xpipe-sync (enter the GitHub token on first launch)"
}
# Rootless podman unpacks each image layer inside a user namespace. Without
# /etc/subuid and /etc/subgid ranges for this user, every pull dies in the middle
# with "potentially insufficient UIDs or GIDs available in user namespace".
subid_count() {
local file="$1" total=0 name start count
[ -r "$file" ] || { echo 0; return 0; }
while IFS=: read -r name start count; do
[ "$name" = "$(id -un)" ] || continue
case "$count" in ''|*[!0-9]*) continue ;; esac
total=$(( total + count ))
done <"$file"
echo "$total"
}
podman_subid_ok() {
[ "$(subid_count "${SUBUID_FILE:-/etc/subuid}")" -ge 65536 ] &&
[ "$(subid_count "${SUBGID_FILE:-/etc/subgid}")" -ge 65536 ]
}
podman_subid_hint() {
local me; me="$(id -un)"
warn "rootless podman has no subuid/subgid range for $me"
warn " ${SUBUID_FILE:-/etc/subuid} has $(subid_count "${SUBUID_FILE:-/etc/subuid}") ids, ${SUBGID_FILE:-/etc/subgid} has $(subid_count "${SUBGID_FILE:-/etc/subgid}") (65536 needed)"
warn " fix: sudo usermod --add-subuids 100000-165535 --add-subgids 100000-165535 $me && podman system migrate"
warn " last resort (deletes images/containers): podman system reset"
}
cmd_boxes() {
if in_container; then ok "skipping distrobox inside a container"; return; fi
have distrobox || die "distrobox missing (dot system)"
if have podman && [ "$(id -u)" != 0 ] && ! podman_subid_ok; then podman_subid_hint; fi
distrobox assemble create --file "$HOME/.config/distrobox/distrobox.ini"
}
# ---------------------------------------------------------------- secrets (Bitwarden)
BW_PREFIX="dotfiles"
BW_SERVER="${BW_SERVER:-https://vault.etvamerica.com}"
bw_target_server() {
if [ -n "${BW_SERVER:-}" ]; then
printf '%s\n' "$BW_SERVER"
elif [ "$(profile)" = full-work ]; then
echo https://vault.etvamerica.com
else
echo https://vault.godemperordoge.org
fi
}
# Point bw at the Vaultwarden instance (only possible while logged out).
# Bitwarden only accepts a server change when logged out.
bw_server() {
have bw || return 0
[ "$(bw config server 2>/dev/null)" = "$BW_SERVER" ] && return 0
[ "$(bw status | jq -r .status)" = unauthenticated ] && bw config server "$BW_SERVER" >/dev/null && ok "bw server → $BW_SERVER"
local target state current status
target="$(bw_target_server)"
state="$(bw status)" || return 1
current="$(jq -r '.serverUrl // empty' <<<"$state")" || return 1
status="$(jq -r '.status // empty' <<<"$state")" || return 1
[ "${current%/}" = "${target%/}" ] && return 0
if [ "$status" != unauthenticated ]; then
warn "bw must be logged out before switching to $target (run: bw logout, then retry)"
return 1
fi
bw --nointeraction config server "$target" </dev/null >/dev/null && ok "bw server → $target"
}
bw_ready() {
have bw || die "bitwarden-cli missing (dot switch)"
bw_server
bw_server || die "Bitwarden server does not match the selected profile"
local status; status="$(bw status | jq -r .status)"
case "$status" in
unlocked) return 0 ;;
@@ -387,7 +451,7 @@ bw_put_note() { # name, notes-file
bw get template item | jq --arg name "$name" --rawfile n "$file" \
'.type = 2 | .secureNote = {type: 0} | .name = $name | .notes = $n | .login = null' \
| bw encode | bw create item >/dev/null
fi
fi || return 1
ok "bitwarden: $name"
}
@@ -516,6 +580,82 @@ secrets_render() {
# Do not write a plaintext ~/.git-credentials or modify an existing one.
}
# Keep the secretctl snapshot out of secrets.env, which is shell-sourced.
secrets_push_secretctl() (
[ "$#" -le 1 ] || die "usage: dot secrets push-secretctl [SOURCE]"
have secretctl || die "secretctl is required"
local src="${1:-${SECRETCTL_FILE:-$HOME/secrets.txt}}" keys key stage jq_bin part generation checksum
local -a parts
keys="$(secretctl --file "$src" list)" || die "Could not list secrets"
[ -n "$keys" ] || die "No secrets to upload"
jq_bin="$(command -v jq)" || die "jq is required"
bw_ready
bw sync >/dev/null
umask 077
stage="$(mktemp -d)"
trap 'rm -rf -- "$stage"' EXIT
generation="${stage##*/}"
while IFS= read -r key; do
secretctl --file "$src" get "$key" -- "$jq_bin" -jn --arg key "$key" 'env[$key]' |
secretctl --file "$stage/store" add "$key" --allow-empty >/dev/null ||
die "Could not export secretctl entry $key"
done <<<"$keys"
# Leave room for encryption overhead and split only ASCII base64 text.
base64 -w0 "$stage/store" | split -b 6000 -d -a 6 - "$stage/part."
parts=("$stage"/part.*)
for part in "${parts[@]}"; do
bw_put_note "$BW_PREFIX/secretctl/$generation/${part##*.}" "$part" ||
die "Could not upload snapshot part"
done
checksum="$(sha256sum <"$stage/store")"
jq -n --arg generation "$generation" --argjson parts "${#parts[@]}" \
--arg sha256 "${checksum%% *}" '{version:1,generation:$generation,parts:$parts,sha256:$sha256}' >"$stage/manifest"
# Publish the manifest last so a partial upload leaves the prior backup usable.
bw_put_note "$BW_PREFIX/secretctl/manifest" "$stage/manifest"
)
secrets_pull_secretctl() (
[ "$#" -le 1 ] || die "usage: dot secrets pull-secretctl [DESTINATION]"
have secretctl || die "secretctl is required"
local dest="${1:-${SECRETCTL_FILE:-$HOME/secrets.txt}}" stage manifest generation count checksum actual index part
if [ -e "$dest" ] || [ -L "$dest" ]; then
die "$dest already exists; choose a new destination"
fi
bw_ready
bw sync >/dev/null
umask 077
stage="$(mktemp -- "$(dirname -- "$dest")/.secretctl-import.XXXXXXXX")"
trap 'rm -f -- "$stage"' EXIT
manifest="$(bw_find "$BW_PREFIX/secretctl/manifest")" || die "Could not look up the snapshot manifest"
if [ -z "$manifest" ]; then
bw_find "$BW_PREFIX/secretctl" |
jq -je 'select(.type == 2) | .notes | select(type == "string" and length > 0)' >"$stage" ||
die "No valid secretctl backup in this vault"
else
manifest="$(jq -er 'select(.type == 2) | .notes | fromjson |
select(.version == 1 and (.generation | test("^tmp[.][a-zA-Z0-9]+$")) and
(.parts | type == "number" and . >= 1 and . <= 1000000 and floor == .) and
(.sha256 | test("^[a-f0-9]{64}$")))' <<<"$manifest")" ||
die "Invalid secretctl snapshot manifest"
generation="$(jq -r .generation <<<"$manifest")"
count="$(jq -r .parts <<<"$manifest")"
checksum="$(jq -r .sha256 <<<"$manifest")"
{
for ((index = 0; index < count; index++)); do
printf -v part '%06d' "$index"
bw_find "$BW_PREFIX/secretctl/$generation/$part" |
jq -je 'select(.type == 2) | .notes | select(test("^[A-Za-z0-9+/=]+$"))' ||
exit 1
done
} | base64 -d >"$stage" || die "Snapshot is missing a part or is corrupt"
actual="$(sha256sum <"$stage")"
[ "${actual%% *}" = "$checksum" ] || die "Snapshot integrity check failed"
fi
secretctl --file "$stage" check >/dev/null 2>&1 || die "Vault snapshot failed secretctl validation"
ln -T -- "$stage" "$dest" || die "Could not create $dest without overwriting"
ok "Secretctl file restored at $dest (0600)"
)
cmd_secrets() {
local sub="${1:-}"; shift || true
case "$sub" in
@@ -525,7 +665,9 @@ cmd_secrets() {
add) secrets_add "$@" ;;
set) secrets_set "$@" ;;
render) secrets_render ;;
*) die "usage: dot secrets status|push [--wireguard]|pull [--wireguard]|add FILE...|set KEY [VALUE]|render" ;;
push-secretctl) secrets_push_secretctl "$@" ;;
pull-secretctl) secrets_pull_secretctl "$@" ;;
*) die "usage: dot secrets status|push [--wireguard]|pull [--wireguard]|add FILE...|set KEY [VALUE]|render|push-secretctl [SOURCE]|pull-secretctl [DESTINATION]" ;;
esac
}
@@ -671,7 +813,32 @@ cmd_sounds() {
}
# ---------------------------------------------------------------- update / doctor
# Pull the checkout and apply it: no package/tool/app upgrades, no flake input bump.
# A newly added package still gets built once here, which can take a while.
cmd_sync() {
case " ${*:-} " in
*" --inputs "*) die "dot sync never bumps flake inputs; use: dot update --inputs" ;;
esac
step "pull dotfiles"
git -C "$DOTFILES_DIR" pull --ff-only || warn "git pull failed; continuing with local tree"
cmd_switch "$@"
ok "dotfiles synced (no app, tool or flake-input upgrades)"
}
cmd_update() {
local args=() a sync_only=0
for a in "$@"; do
case "$a" in
--switch-only) sync_only=1 ;;
*) args+=("$a") ;;
esac
done
if [ "$sync_only" = 1 ]; then
step "dot update --switch-only → dot sync"
cmd_sync ${args[@]+"${args[@]}"}
return
fi
set -- ${args[@]+"${args[@]}"}
step "pull dotfiles"
git -C "$DOTFILES_DIR" pull --rebase --autostash || warn "git pull failed; continuing with local tree"
if [ "${1:-}" = --inputs ]; then
@@ -685,8 +852,52 @@ cmd_update() {
cmd_apps
}
# Home Manager's reloadSystemd step reports the state of the *whole* user manager
# before it reloads anything, so one failed third-party unit (a portal service on a
# display-less host) makes every switch print a wall of warnings. It never starts
# those units, and it cannot clear them. Diagnose them here, on demand.
systemd_user_report() {
local fix="${1:-0}" state units oneline flapping u portals=() unmanaged=() path real
has_systemd || return 0
state="$(systemctl --user is-system-running 2>/dev/null || true)"
printf 'user systemd: %s\n' "${state:-unknown}"
units="$(systemctl --user --no-pager --no-legend --plain --state=failed list-units 2>/dev/null | awk 'NF{print $1}')"
if [ -n "${units// /}" ]; then
oneline="$(echo $units)"
warn "failed user units (Home Manager repeats these on every switch):"
printf ' %s\n' $units
for u in $units; do case "$u" in xdg-desktop-portal*) portals+=("$u");; esac; done
if [ "$fix" = 1 ]; then
# shellcheck disable=SC2086
systemctl --user reset-failed $units 2>/dev/null && ok "cleared failed state: $oneline"
else
printf ' clear the state: systemctl --user reset-failed %s\n' "$oneline"
fi
[ ${#portals[@]} -eq 0 ] || printf ' no display here: any app asking D-Bus for org.freedesktop.portal.Desktop starts\n %s, which cannot open a display and times out. Masking stops the\n retries: systemctl --user mask %s\n' "$(echo "${portals[*]}")" "$(echo "${portals[*]}")"
fi
flapping="$(systemctl --user --no-pager --no-legend --plain --state=activating list-units 2>/dev/null | awk '$4 == "auto-restart" {print $1}')"
[ -z "${flapping// /}" ] || { warn "restart-looping user units (each retry writes to the journal):"; printf ' %s\n' $flapping; printf ' inspect: systemctl --user status <unit> / stop: systemctl --user stop <unit>\n'; }
# Units in ~/.config/systemd/user that no home-manager generation owns. Tracked
# files wired by hand, and one-off units written straight into the home.
for path in "$HOME/.config/systemd/user"/*.service "$HOME/.config/systemd/user"/*.timer; do
[ -e "$path" ] || continue
real="$(readlink -f "$path" 2>/dev/null || true)"
case "$real" in
/nix/store/*) continue ;;
"$DOTFILES_DIR"/*) unmanaged+=("$(basename "$path") [git, wired by hand]") ;;
*) unmanaged+=("$(basename "$path") [not in dotfiles]") ;;
esac
done
if [ ${#unmanaged[@]} -gt 0 ]; then
warn "user units outside home-manager (neither 'dot switch' nor git clean-up covers these):"
printf ' %s\n' "${unmanaged[@]}"
printf ' move the ones you want to keep into home/<module>.nix (systemd.user.services) and delete the file\n'
fi
}
cmd_doctor() {
local p; p="$(profile)"
local p fix=0; [ "${1:-}" = --fix ] && fix=1
p="$(profile)"
printf 'os=%s profile=%s container=%s systemd=%s\n' "$(os_id)" "$p" "$(in_container && echo yes || echo no)" "$(has_systemd && echo yes || echo no)"
chk() { if eval "$2" >/dev/null 2>&1; then ok "$1"; else warn "$1 — $3"; fi; }
# Diagnose interrupted installs and disabled features independently, without
@@ -708,6 +919,7 @@ cmd_doctor() {
chk "claude" "[ -x ~/.local/bin/claude ]" "dot apps"
if ! in_container; then
chk "podman" "have podman" "dot system"
chk "podman subuid/subgid" "podman_subid_ok" "dot boxes explains the usermod fix"
chk "distrobox" "have distrobox" "dot system"
fi
chk "ssh key" "[ -f ~/.ssh/id_ed25519 ]" "dot secrets pull"
@@ -738,6 +950,7 @@ cmd_doctor() {
chk "day/night daemons (XDG autostart)" "pgrep -f daynight-hooks" "log in to Plasma"
fi
fi
systemd_user_report "$fix"
}
cmd_bootstrap() {
@@ -767,24 +980,26 @@ dot — portable dev environment
dot bootstrap first-time setup (nix → system → switch → apps)
dot update [--inputs] pull repo, (bump flake inputs), switch, update flatpaks/mise/claude
dot sync [profile] pull repo (--ff-only) and switch only — no upgrades, no flake input bump
dot switch [profile] apply the home-manager config
dot profile [full|full-work|headless|auto]
dot system [--netbird] [--defguard] sudo layer: distro packages, browser PWA policies, netbird, Defguard VPN service, login shell
dot nix install Nix if missing
dot apps [--native] profile apps (native on Fedora containers), mise tools, Claude Code
dot secrets status|push|pull|add|set|render Bitwarden-backed tokens, keys, files, WireGuard
dot secrets push-secretctl|pull-secretctl Back up or restore a secretctl file
dot defguard [--force] preconfigure the Defguard VPN app (one-time token minted with DEFGUARD_API_TOKEN)
dot wallpapers [--push] sort wallpapers into light/dark (or clone them)
dot sounds [build|test|notify] Portal 2 sound theme: build it, play every sound, or fire a test notification
dot boxes create distroboxes from distrobox.ini
dot doctor check what's installed
dot doctor [--fix] check what's installed; --fix clears failed user units
EOF
}
main() {
local cmd="${1:-help}"; shift || true
case "$cmd" in
bootstrap|update|switch|profile|system|nix|apps|secrets|defguard|wallpapers|sounds|boxes|doctor) "cmd_$cmd" "$@" ;;
bootstrap|update|sync|switch|profile|system|nix|apps|secrets|defguard|wallpapers|sounds|boxes|doctor) "cmd_$cmd" "$@" ;;
help|-h|--help) usage ;;
*) usage; exit 1 ;;
esac
Executable
+43
View File
@@ -0,0 +1,43 @@
#!/bin/sh
# pi-spark — run the pi coding agent against the local Spark model in tmux.
#
# The Spark models live on yveltal (Ollama behind the gpu-broker). Spark only
# implements thinking levels low and high, so medium breaks its chat template:
# the launcher defaults to low. Everything else comes from ~/.pi/agent:
# skills, the wiki + lapis MCP servers and the LaPis memory layer.
#
# pi-spark attach, or create the session
# PI_SPARK_MODEL=ollama/spark:4b pi-spark
set -eu
SESSION=${PI_SPARK_SESSION:-pi-spark}
MODEL=${PI_SPARK_MODEL:-ollama/spark:ablit}
THINKING=${PI_SPARK_THINKING:-low}
DIR=${PI_SPARK_DIR:-$HOME/Projects/pi-spark}
if tmux has-session -t "$SESSION" 2>/dev/null; then
if [ -t 1 ]; then exec tmux attach -t "$SESSION"; fi
echo "session $SESSION already running: tmux attach -t $SESSION"
exit 0
fi
# pi-lens (npm:pi-lens) already injects language-server findings after an edit,
# so the home-grown verify-on-write extension is opt-in only: PI_SPARK_VERIFY=1.
EXTRA=""
VERIFY_EXT="$HOME/Projects/pi-verify-on-write/src/index.ts"
if [ -n "${PI_SPARK_VERIFY:-}" ] && [ -f "$VERIFY_EXT" ]; then
EXTRA="--extension $VERIFY_EXT"
fi
mkdir -p "$DIR/.pi"
# Small models need explicit tool-first rules; seed them into a new project.
if [ ! -f "$DIR/.pi/APPEND_SYSTEM.md" ] && [ -f "$HOME/.dotfiles/config/pi/small-model-APPEND_SYSTEM.md" ]; then
cp "$HOME/.dotfiles/config/pi/small-model-APPEND_SYSTEM.md" "$DIR/.pi/APPEND_SYSTEM.md"
echo "seeded $DIR/.pi/APPEND_SYSTEM.md (small-model rules)"
fi
# Drop the free-pi session environment so pi uses ~/.pi/agent, not the free-pi agent dir.
tmux new-session -d -s "$SESSION" -x "${PI_SPARK_COLS:-210}" -y "${PI_SPARK_ROWS:-50}" -c "$DIR" \
"env -u PI_CODING_AGENT_DIR -u PI_SESSION_FILE -u PI_SESSION_ID -u PI_MODEL -u PI_PROVIDER -u PI_REASONING_LEVEL PI_SKIP_VERSION_CHECK=1 pi --model $MODEL --thinking $THINKING $EXTRA"
if [ -t 1 ]; then exec tmux attach -t "$SESSION"; fi
echo "session $SESSION ready with $MODEL (thinking $THINKING): tmux attach -t $SESSION"
Executable
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
export PATH="$HOME/.local/bin:$HOME/.nix-profile/bin:/usr/bin:/bin"
root="${XDG_STATE_HOME:-$HOME/.local/state}/pi-workers"
self="$(realpath "$0")"
profiles="$(dirname "$self")/../config/free-pi/models.json"
mkdir -p "$root"
case "${2:-}" in
cohere|local) provider=$2 ;;
*) echo 'Usage: pi-worker {start|serve} {cohere|local} | pi-worker submit {cohere|local} REPO TASK.md' >&2; exit 2 ;;
esac
queue="$root/$provider"
mkdir -p "$queue"
case "$1" in
start)
if ! tmux has-session -t "=pi-worker-$provider" 2>/dev/null; then
tmux new-session -d -s "pi-worker-$provider" -- "$self" serve "$provider"
tmux set-option -w -t "pi-worker-$provider:" remain-on-exit on
fi
;;
stop)
tmux kill-session -t "=pi-worker-$provider"
;;
submit)
[[ $# == 4 && -s "$4" ]]
task=$(realpath "$4")
job=$(mktemp -d "$queue/job-XXXXXXXX")
git -C "$3" worktree add --detach "$job/work" HEAD >&2
cp -- "$task" "$job/task.md"
touch "$job/ready"
printf '%s\n' "$job"
;;
serve)
exec 9>"$queue/worker.lock"
flock -n 9
shopt -s nullglob
trap 'exit 0' TERM INT
printf 'Waiting for %s jobs in %s\n' "$provider" "$queue"
for marker in "$queue"/job-*/running; do
job=${marker%/running}
printf '125\n' >"$job/exit-code"
mv -- "$marker" "$job/done"
done
while true; do
for ready in "$queue"/job-*/ready; do
job=${ready%/ready}
mv -- "$ready" "$job/running"
printf 'Running %s\n' "${job##*/}"
code=0
"$self" run "$provider" "$job" >"$job/result.txt" 2>&1 || code=$?
printf '%s\n' "$code" >"$job/exit-code"
mv -- "$job/running" "$job/done"
printf '%s finished with status %s\n' "${job##*/}" "$code"
done
sleep 3
done
;;
run)
job=$3
[[ "$job" == "$queue"/job-* && -f "$job/running" ]]
pi_path=$(mise which pi)
node_path=$(mise which node)
modules=$(dirname "$(dirname "$pi_path")")
mkdir -p "$job/profile"
if [[ "$provider" == cohere ]]; then
model=cohere/command-a-03-2025
jq '{providers: {cohere: (.providers.cohere | .apiKey = "$COHERE_API_KEY")}}' "$profiles" > "$job/profile/models.json"
else
model=ollama/gemma4-12b-qat-64k
jq '{providers: {ollama: (.providers.ollama | .apiKey = "ollama")}}' "$profiles" > "$job/profile/models.json"
fi
sandbox=(bwrap --die-with-parent --unshare-user --unshare-pid --unshare-ipc
--proc /proc --dev /dev --tmpfs /tmp
--ro-bind /usr /usr --ro-bind /nix/store /nix/store
--symlink usr/bin /bin --symlink usr/lib /lib --symlink usr/lib64 /lib64
--ro-bind /etc/resolv.conf /etc/resolv.conf --ro-bind /etc/ssl/certs /etc/ssl/certs
--ro-bind "$modules" /runtime/node_modules --ro-bind "$node_path" /runtime/node
--bind "$job/profile" /profile --ro-bind "$job/task.md" /task.md
--bind "$job/work" /work --tmpfs /home --chdir /work)
while IFS= read -r name; do
sandbox+=(--unsetenv "$name")
done < <(compgen -e | sed '/^COHERE_API_KEY$/d')
sandbox+=(--setenv HOME /home --setenv PATH /usr/bin:/bin --setenv PI_CODING_AGENT_DIR /profile)
sandbox+=(/runtime/node /runtime/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js
--no-session --no-extensions --no-mcp --tools read,edit,write,grep,find,ls
--model "$model" --print @/task.md)
if [[ "$provider" == cohere ]]; then
exec timeout -k 10 300 secretctl get COHERE_API_KEY -- "${sandbox[@]}"
fi
exec timeout -k 10 300 "${sandbox[@]}"
;;
*) exit 2 ;;
esac
+332
View File
@@ -0,0 +1,332 @@
#!/usr/bin/env bash
# remote-browser — read a Chromium browser running on another machine, over CDP.
#
# Works for any host the agent can reach (an SSH alias, or a direct address) whose
# browser exposes a CDP endpoint. Chrome-family browsers expose one when the user ticks
# chrome://inspect/#remote-debugging → "Allow remote debugging for this browser instance"
# which serves ONLY ws://127.0.0.1:<port>/devtools/browser (HTTP /json/* returns 403).
# Playwright attaches to a ws:// endpoint directly, so this is a thin wrapper that opens
# the tunnel and drives `playwright-cli`. Setup for a new device: see references/setup.md
# in the remote-browser skill, and run `remote-browser check`.
#
# remote-browser profiles list configured devices
# remote-browser setup --name deck --host deck [--port 9222] [--transport ssh]
# remote-browser check [--profile deck] step-by-step readiness test
# remote-browser tabs | status | text | html | shot
# remote-browser cli <playwright-cli args> full passthrough to playwright-cli
# (console, requests, storage, tracing,
# run-code, pdf, tab-*, goto/click…);
# ours flags are not parsed after `cli`
# remote-browser cli -- <args> explicit end-of-options form
#
# Options: --profile/-p NAME, --index N, --match SUBSTR, --limit CHARS, --out FILE.
# Read-only by intent: no click/type/navigate helper exists, because driving an
# authenticated session is what gets accounts restricted.
#
# Env: REMOTE_BROWSER_PROFILE (default profile), REMOTE_BROWSER_DIR (config dir).
set -euo pipefail
CONF_DIR=${REMOTE_BROWSER_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/remote-browser}
PROFILE_DIR="$CONF_DIR/profiles"
PN=$(basename "$0")
die() { echo "$PN: $*" >&2; exit 1; }
info() { echo " $*" >&2; }
usage() { sed -n '2,24p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; }
# --- argument parsing ---------------------------------------------------------
PROFILE=${REMOTE_BROWSER_PROFILE:-}
CMD=""
ARGS=()
while [ $# -gt 0 ]; do
if [ -n "$CMD" ] && [ "$CMD" = cli ]; then
# `cli` is a full passthrough: everything after it belongs to playwright-cli,
# including flags that look like ours.
ARGS+=("$1"); shift; continue
fi
case "$1" in
--profile|-p) PROFILE=${2:-}; shift 2 ;;
-h|--help) usage; exit 0 ;;
--) shift; if [ -z "$CMD" ]; then CMD=${1:-}; shift; fi
while [ $# -gt 0 ]; do ARGS+=("$1"); shift; done ;;
*) if [ -z "$CMD" ]; then CMD=$1; else ARGS+=("$1"); fi; shift ;;
esac
done
# --- profiles -----------------------------------------------------------------
profile_file() { echo "$PROFILE_DIR/$1.env"; }
load_profile() {
[ -n "$PROFILE" ] || die "no profile given (use --profile NAME, or set REMOTE_BROWSER_PROFILE). Try: $PN profiles"
local f; f=$(profile_file "$PROFILE")
[ -f "$f" ] || die "unknown profile '$PROFILE' ($f missing). Try: $PN profiles"
# shellcheck disable=SC1090
. "$f"
: "${RB_HOST:?profile $f has no RB_HOST}"
RB_PORT=${RB_PORT:-9222}
RB_TRANSPORT=${RB_TRANSPORT:-ssh}
RB_WS_PATH=${RB_WS_PATH:-/devtools/browser}
RB_INSPECT_URL=${RB_INSPECT_URL:-chrome://inspect/#remote-debugging}
SESSION="rb-$PROFILE"
if [ "$RB_TRANSPORT" = ssh ]; then
WS="ws://127.0.0.1:${RB_PORT}${RB_WS_PATH}"
else
WS="ws://${RB_HOST}:${RB_PORT}${RB_WS_PATH}"
fi
}
list_profiles() {
[ -d "$PROFILE_DIR" ] || { echo "no profiles yet — create one with: $PN setup --name <name> --host <host>"; return 0; }
shopt -s nullglob
local found=0 f
for f in "$PROFILE_DIR"/*.env; do
found=1
( . "$f"
printf '%-12s %-6s %-24s %s:%s\n' \
"$(basename "$f" .env)" "${RB_TRANSPORT:-ssh}" "${RB_HOST:-?}" "${RB_HOST:-?}" "${RB_PORT:-9222}" )
done
[ $found -eq 1 ] || echo "no profiles yet — create one with: $PN setup --name <name> --host <host>"
}
# --- transport ----------------------------------------------------------------
port_open() { (exec 3<>"/dev/tcp/${1}/${2}") 2>/dev/null; }
host_reachable() {
case "$RB_TRANSPORT" in
ssh) ssh -o BatchMode=yes -o ConnectTimeout=6 "$RB_HOST" true >/dev/null 2>&1 ;;
direct) port_open "$RB_HOST" "$RB_PORT" ;;
*) return 1 ;;
esac
}
ensure_tunnel() {
if [ "$RB_TRANSPORT" = direct ]; then
port_open "$RB_HOST" "$RB_PORT" || die "cannot reach ${RB_HOST}:${RB_PORT} (transport=direct)"
return 0
fi
port_open 127.0.0.1 "$RB_PORT" && return 0
ssh -o BatchMode=yes -o ExitOnForwardFailure=yes -f -N \
-L "${RB_PORT}:127.0.0.1:${RB_PORT}" "$RB_HOST" 2>/dev/null \
|| die "cannot open SSH tunnel to ${RB_HOST} — is it awake and is your key authorised?"
for _ in $(seq 1 25); do port_open 127.0.0.1 "$RB_PORT" && return 0; sleep 0.2; done
die "tunnel up but nothing listening on 127.0.0.1:${RB_PORT}.
On ${RB_HOST}, open ${RB_INSPECT_URL} and tick
'Allow remote debugging for this browser instance', then retry."
}
ws_handshake() { # prints HTTP status line of a WS upgrade attempt
python3 - "${1}" <<'PY' 2>/dev/null || echo "no-response"
import base64, os, socket, sys, urllib.parse as up
url = up.urlparse(sys.argv[1])
s = socket.create_connection((url.hostname, url.port or 80), timeout=5)
key = base64.b64encode(os.urandom(16)).decode()
s.sendall((f"GET {url.path or '/'} HTTP/1.1\r\nHost: {url.hostname}:{url.port}\r\n"
"Upgrade: websocket\r\nConnection: Upgrade\r\n"
f"Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n").encode())
print(s.recv(256).decode(errors="replace").split("\r\n")[0].strip() or "no-response")
s.close()
PY
}
ensure_attached() {
ensure_tunnel
playwright-cli -s="$SESSION" eval '1' >/dev/null 2>&1 && return 0
playwright-cli -s="$SESSION" attach --cdp="$WS" >/dev/null 2>&1 \
|| die "playwright-cli could not attach to ${WS}.
On ${RB_HOST}: open ${RB_INSPECT_URL} and tick
'Allow remote debugging for this browser instance'."
}
# --- helpers ------------------------------------------------------------------
# tab_list → "INDEX<TAB>TITLE<TAB>URL"
tab_list() {
playwright-cli -s="$SESSION" tab-list 2>/dev/null \
| sed -n 's/^- \([0-9]\+\): \(.*\)\[\(.*\)\](\(.*\))$/\1\t\3\t\4/p'
}
resolve_tab() {
local idx="" match=""
while [ $# -gt 0 ]; do
case "$1" in
--index) idx=${2:-}; shift 2 ;;
--match) match=${2:-}; shift 2 ;;
*) shift ;;
esac
done
if [ -n "$match" ]; then
idx=$(tab_list | awk -F'\t' -v m="$(printf '%s' "$match" | tr 'A-Z' 'a-z')" \
'tolower($0) ~ m {print $1; exit}')
[ -n "$idx" ] || die "no tab matching '$match'"
fi
printf '%s' "${idx:-}"
}
json_unquote() {
python3 -c '
import json, sys
for line in sys.stdin.read().splitlines():
line = line.strip()
if line[:1] == chr(34) and line[-1:] == chr(34):
try:
sys.stdout.write(json.loads(line)); break
except Exception:
pass
'
}
# --- commands -----------------------------------------------------------------
cmd_setup() {
local name="" host="" port=9222 transport=ssh path=/devtools/browser inspect=""
local url_default
while [ $# -gt 0 ]; do
case "$1" in
--name) name=${2:-}; shift 2 ;;
--host) host=${2:-}; shift 2 ;;
--port) port=${2:-}; shift 2 ;;
--transport) transport=${2:-}; shift 2 ;;
--ws-path) path=${2:-}; shift 2 ;;
--inspect-url) inspect=${2:-}; shift 2 ;;
*) die "setup: unexpected argument '$1'" ;;
esac
done
[ -n "$name" ] || die "setup: --name is required (a short label, e.g. deck, laptop)"
[ -n "$host" ] || die "setup: --host is required (ssh alias or address)"
case "$transport" in ssh|direct) ;; *) die "setup: --transport must be ssh or direct" ;; esac
mkdir -p "$PROFILE_DIR"
local f; f=$(profile_file "$name")
if [ -f "$f" ]; then
info "updating existing profile $name ($f)"
fi
cat > "$f" <<EOF
# remote-browser profile created $(date -Iseconds) by \`$PN setup\`
# transport=ssh forwards the remote loopback port to 127.0.0.1 locally.
# transport=direct talks to RB_HOST:RB_PORT as-is (no tunnel).
RB_TRANSPORT=$transport
RB_HOST=$host
RB_PORT=$port
RB_WS_PATH=$path
RB_INSPECT_URL=${inspect:-chrome://inspect/#remote-debugging}
EOF
chmod 600 "$f"
echo "wrote $f"
echo
echo "Next: on $host, open ${inspect:-chrome://inspect/#remote-debugging} and tick"
echo " 'Allow remote debugging for this browser instance', then run:"
echo " $PN check --profile $name"
}
cmd_check() {
load_profile
local failures=0
say() { printf '%s %s\n' "$1" "$2"; }
[ -n "$PROFILE" ] && printf 'profile: %s (transport=%s host=%s port=%s)\n\n' "$PROFILE" "$RB_TRANSPORT" "$RB_HOST" "$RB_PORT"
if [ "$RB_TRANSPORT" = ssh ]; then
if ssh -o BatchMode=yes -o ConnectTimeout=6 "$RB_HOST" true >/dev/null 2>&1; then
say "✓" "ssh to $RB_HOST works"
else
say "✗" "ssh to $RB_HOST failed — add an ssh config entry and key, or use --transport direct"
failures=$((failures+1))
fi
fi
if ensure_tunnel 2>/dev/null; then
say "✓" "cdp port reachable at $( [ "$RB_TRANSPORT" = ssh ] && echo "127.0.0.1:$RB_PORT via tunnel" || echo "$RB_HOST:$RB_PORT" )"
else
say "✗" "cdp port not reachable — is the browser running with remote debugging enabled?"
say " " " on $RB_HOST: open $RB_INSPECT_URL and tick the box"
failures=$((failures+1))
fi
if [ $failures -eq 0 ]; then
local status; status=$(ws_handshake "$WS")
case "$status" in
*" 101"*) say "✓" "websocket handshake on ${RB_WS_PATH} accepted" ;;
*) say "✗" "websocket handshake returned '${status}'"
say " " " expected 101; a 403/404 means the endpoint is not the CDP socket"
failures=$((failures+1)) ;;
esac
fi
if [ $failures -eq 0 ] && ensure_attached 2>/dev/null; then
say "✓" "playwright attached (session $SESSION)"
local ua; ua=$(playwright-cli -s="$SESSION" eval 'navigator.userAgent' 2>/dev/null | json_unquote)
say "✓" "browser: ${ua:-unknown}"
local n; n=$(tab_list | wc -l)
if [ "$n" -gt 0 ]; then
say "✓" "$n tab(s) visible — try: $PN tabs --profile $PROFILE"
else
say "!" "attached but no tabs found (open a page in that browser)"
fi
elif [ $failures -eq 0 ]; then
say "✗" "playwright could not attach to $WS"
failures=$((failures+1))
fi
echo
if [ $failures -eq 0 ]; then
echo "ready. Read-only commands: tabs, text, html, shot, status, cli."
return 0
fi
echo "$failures check(s) failed."
return 1
}
case "$CMD" in
""|-h|--help) usage; exit 0 ;;
profiles) list_profiles ;;
setup) cmd_setup "${ARGS[@]+"${ARGS[@]}"}" ;;
check) cmd_check ;;
tabs)
load_profile; ensure_attached
tab_list | awk -F'\t' '{printf "%2s %-52s %s\n", $1, substr($2,1,52), $3}'
;;
status)
load_profile; ensure_attached
playwright-cli -s="$SESSION" eval 'navigator.userAgent' | json_unquote
;;
text|html)
LIMIT=8000; tabargs=()
while [ ${#ARGS[@]} -gt 0 ]; do
case "${ARGS[0]}" in
--limit) LIMIT=${ARGS[1]:-8000}; ARGS=("${ARGS[@]:2}") ;;
*) tabargs+=("${ARGS[0]}"); ARGS=("${ARGS[@]:1}") ;;
esac
done
load_profile; ensure_attached
idx=$(resolve_tab "${tabargs[@]+"${tabargs[@]}"}")
[ -n "$idx" ] && playwright-cli -s="$SESSION" tab-select "$idx" >/dev/null
if [ "$CMD" = text ]; then expr='document.body.innerText'; else expr='document.documentElement.outerHTML'; fi
out=$(playwright-cli -s="$SESSION" eval "$expr" | json_unquote)
printf '%s' "$out" | head -c "$LIMIT"
[ "${#out}" -gt "$LIMIT" ] && printf '\n[truncated %s more characters]\n' "$(( ${#out} - LIMIT ))"
echo
;;
shot)
OUT=/tmp/remote-browser-$(date +%s).png; tabargs=()
while [ ${#ARGS[@]} -gt 0 ]; do
case "${ARGS[0]}" in
--out) OUT=${ARGS[1]:-$OUT}; ARGS=("${ARGS[@]:2}") ;;
*) tabargs+=("${ARGS[0]}"); ARGS=("${ARGS[@]:1}") ;;
esac
done
load_profile; ensure_attached
idx=$(resolve_tab "${tabargs[@]+"${tabargs[@]}"}")
[ -n "$idx" ] && playwright-cli -s="$SESSION" tab-select "$idx" >/dev/null
playwright-cli -s="$SESSION" screenshot --filename="$OUT" >/dev/null
echo "$OUT"
;;
cli)
load_profile; ensure_attached
playwright-cli -s="$SESSION" "${ARGS[@]+"${ARGS[@]}"}"
;;
*)
die "unknown command '$CMD'. Try: $PN --help"
;;
esac
Executable
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
printf '%s\n' 'Usage: roku-tv {status|kodi|standby}' \
' status Read TV power and the reported HDMI-CEC source' \
' kodi Wake the TV and select Bounsweet (Kodi)' \
' standby Send standby to the TV'
}
if [[ $# != 1 ]]; then
usage >&2
exit 2
fi
case "$1" in
-h|--help) usage; exit 0 ;;
status|kodi|standby) ;;
*) usage >&2; exit 2 ;;
esac
timeout 20 ssh -T -o BatchMode=yes -o ConnectTimeout=5 bounsweet sh -s -- "$1" <<'REMOTE'
set -eu
cec() {
cec-ctl -d /dev/cec0 "$@"
}
address=$(cec | awk '/Physical Address[[:space:]]*:/ {print $NF; exit}')
case "$address" in
[1-9a-e].[0-9a-f].[0-9a-f].[0-9a-f]) ;;
*) echo 'Bounsweet has no usable HDMI-CEC address' >&2; exit 1 ;;
esac
status() {
power_reply=$(cec --to 0 --give-device-power-status)
source_reply=$(cec --request-active-source)
power=$(printf '%s\n' "$power_reply" | awk -F': ' '/pwr-state:/ {sub(/ \(.*$/, "", $2); print $2; exit}')
source=$(printf '%s\n' "$source_reply" | awk '/phys-addr:/ {print $NF; exit}')
printf 'tv_power=%s\nactive_source=%s\nkodi_source=%s\n' "${power:-unknown}" "${source:-unknown}" "$address"
}
roku_reports_kodi() {
case "$address" in
[1-4].0.0.0) input="tvinput.hdmi${address%%.*}" ;;
*) return 1 ;;
esac
active_app=$(curl -fsS --max-time 4 http://10.56.5.46:8060/query/active-app 2>/dev/null) || return 1
printf '%s\n' "$active_app" | grep -Fq "<app id=\"$input\""
}
send() {
reply=$(cec "$@")
if printf '%s\n' "$reply" | grep -qi 'Tx, Not OK'; then
printf '%s\n' 'HDMI-CEC transmit failed.' >&2
exit 1
fi
}
case "$1" in
status)
status
;;
kodi)
send --to 0 --image-view-on
sleep 1
send --active-source "phys-addr=$address"
printf 'requested_source=%s\n' "$address"
sleep 1
status
if [ "${source:-unknown}" = "$address" ]; then
printf '%s\n' 'source_verified_by=cec'
elif roku_reports_kodi; then
printf '%s\n' 'source_verified_by=roku_active_app'
else
echo 'Kodi source selection could not be confirmed.' >&2
exit 1
fi
;;
standby)
send --to 0 --standby
printf '%s\n' 'requested_power=standby'
status
;;
esac
REMOTE
+6
View File
@@ -11,6 +11,12 @@ Locate, outline, then read a window — never paste a file body you have not nar
- `context-guard` blocks unbounded large reads; follow its hint rather than retrying.
- Full playbook: `/skill:context-discipline`. Policies: `/skill:homelab-policies`.
## Reaching the user's browser
The user browses on their own machines (a Steam Deck, a laptop), not on this host. `remote-browser` reads their
browser (tabs, page text, screenshots) over CDP through a tunnel they enable per session — read-only, and set up per
device with the user. Details: `/skill:remote-browser`.
## Document every change in the Wiki.js homelab docs
After any infrastructure, service, application or configuration change, write it up in the wiki — every time, without being asked again.
+1 -1
View File
@@ -4,7 +4,7 @@
"url": "https://wiki.godemperordoge.org/_mcp",
"description": "Wiki.js homelab docs at godemperordoge.org: search, browse, read and update pages.",
"headers": {
"Authorization": "!secretctl get WIKI_BEARER_TOKEN -- sh -c 'printf \"Bearer %s\" \"$WIKI_BEARER_TOKEN\"'"
"Authorization": "!secretctl get WIKI3_MCP_TOKEN -- sh -c 'printf \"Bearer %s\" \"$WIKI3_MCP_TOKEN\"'"
},
"exposure": "codemode",
"toolExposure": {
+1
View File
@@ -37,3 +37,4 @@ Load the skill that matches the task instead of asking for it up front:
| memory, secrets, host safety, forges, codemode, stack defaults | `/skill:homelab-policies` |
| delegate a well-specified task to free models, then review it | `/skill:cli/handoff` |
| runtimes and project tools | `/skill:mise-cli` |
| reading the user's browser on another machine | `/skill:remote-browser` |
+3 -3
View File
@@ -6,7 +6,7 @@
},
"fallback": {
"provider": "ollama",
"model": "gemma4-12b-qat-128k",
"thinking": "low"
"model": "gemma4-26b-a4b-qat-128k",
"thinking": "high"
}
}
}
+13 -58
View File
@@ -1,66 +1,21 @@
{
"mcpServers": {
"websearch-simple": {
"url": "https://RivalSearchMCP.fastmcp.app/mcp",
"exposure": "direct"
},
"wiki": {
"command": "npx",
"args": [
"-y",
"@yowu-dev/requarks-wiki-mcp@latest"
],
"env": {
"WIKI_BASE_URL": "https://wikijs.etvamerica.com/",
"WIKI_API_TOKEN": "${WIKI_API_TOKEN}",
"WIKI_MUTATIONS_ENABLED": "true",
"WIKI_MUTATION_DRY_RUN": "false"
"url": "https://wiki.godemperordoge.org/_mcp",
"description": "Wiki.js homelab docs at godemperordoge.org: search, browse, read and update pages.",
"headers": {
"Authorization": "!secretctl get WIKI3_MCP_TOKEN -- sh -c 'printf \"Bearer %s\" \"$WIKI3_MCP_TOKEN\"'"
},
"exposure": "direct"
},
"mise-en-place": {
"command": "${HOME}/.nix-profile/bin/mise",
"args": [
"mcp"
],
"env": {
"MISE_EXPERIMENTAL": "1"
},
"exposure": "direct"
},
"playwright-browser-automation": {
"command": "npx",
"args": [
"@playwright/mcp@latest",
"--extension"
],
"env": {
"PLAYWRIGHT_MCP_EXECUTABLE_PATH": "${HOME}/chrome.sh",
"PLAYWRIGHT_MCP_EXTENSION_TOKEN": "${PLAYWRIGHT_MCP_EXTENSION_TOKEN}"
},
"exposure": "direct"
},
"web-search-advanced": {
"command": "uvx",
"args": [
"--from",
"git+https://github.com/Shelpuk-AI-Technology-Consulting/kindly-web-search-mcp-server",
"kindly-web-search-mcp-server",
"start-mcp-server"
],
"env": {
"SEARXNG_BASE_URL": "https://google.godemperordoge.org/",
"SEARXNG_USER_AGENT": "Mozilla/5.0 ..."
"exposure": "codemode",
"toolExposure": {
"get_page": "direct"
}
},
"gitea": {
"command": "${HOME}/.nix-profile/bin/gitea-mcp",
"args": [
"-H",
"https://gitea.etvamerica.com",
"-T",
"${ETV_GITEA_TOKEN}"
]
"lapis": {
"command": "sh",
"args": ["-c", "exec \"$HOME/.dotfiles/bin/mcp-lapis\""],
"description": "LaPis persistent memory (SQLite ~/.pi/memory/memory.db): memory-save, memory-search, memory-get, memory-code and memory-doc for the current project.",
"exposure": "codemode"
}
}
}
}
+20
View File
@@ -5,6 +5,26 @@
"api": "openai-completions",
"apiKey": "ollama",
"models": [
{
"id": "spark:ablit",
"name": "Spark-X2.6-4B abliterated (GTX 1080)",
"contextWindow": 65536,
"maxTokens": 8192,
"reasoning": true,
"input": [
"text"
]
},
{
"id": "spark:4b",
"name": "Spark-X2.6-4B official (GTX 1080)",
"contextWindow": 65536,
"maxTokens": 8192,
"reasoning": true,
"input": [
"text"
]
},
{
"id": "gemma4-12b-qat-64k:latest",
"contextWindow": 65536,
+3 -2
View File
@@ -5,7 +5,8 @@
"npm:@juicesharp/rpiv-ask-user-question",
"npm:pi-background-tasks",
"npm:context-mode",
"npm:pi-auto-models"
"npm:pi-auto-models",
"npm:pi-lens"
],
"extensionChangelogVersions": {
"{\"source\":\"git:github.com/GeneGulanesJr/LaPis\",\"scope\":\"user\"}": "1.4.0"
@@ -25,4 +26,4 @@
"ollama/gemma4-26b-a4b-qat:latest",
"ollama/gemma4-12b-qat-uncensored-64k:latest"
]
}
}
+14
View File
@@ -0,0 +1,14 @@
# Working rules (small-model session)
Text you write is not the work — tool calls are the work.
1. **Act with tools.** Create or change files with `write`/`edit`. Never paste file contents or commands as prose.
2. **One step at a time.** One tool call, read the result, then the next. Do not plan more than two steps ahead.
3. **Verify before you deliberate.** After writing code, run the build or test immediately. Decide design questions from the command output, not from memory.
4. **Read a file at most once per task.** Use `edit` with a unique anchor instead of re-reading.
5. **Keep output small.** Pipe long output through `| tail -20` or `| head -20`; prefer `-count`, `-q` and `--json` flags. Your context is limited.
6. **Do not invent syntax.** Unsure of a command or file format? Run `--help`, `ls-remote`, or read the relevant skill.
7. **Cap deliberation.** If two options are acceptable, take the first and continue; the test result decides.
8. **Stop with evidence.** When acceptance criteria are met, run the final verification command and report the exact commands and their output. Nothing else.
Go projects: use the `golang-mise` skill for the exact `mise.toml` format and command list.
+67
View File
@@ -0,0 +1,67 @@
---
name: remote-browser
description: Read a Chromium browser running on another machine (Steam Deck, laptop, desktop) over CDP — list tabs, dump page text/HTML, take screenshots. Use when the user says "look at my browser", "what's on my screen", "read this page I have open", or when a page they can see on another device is unreachable from this host. Includes a setup workflow for onboarding a new device. Read-only; never drive authenticated sessions.
---
# Reading someone else's browser
The user browses on their **own machine** (a Steam Deck, a laptop); agents usually run somewhere else. When they say
"look at my browser" or "the page I have open", `remote-browser` shows it to you: it opens a tunnel to that machine
and drives `playwright-cli` against the browser's CDP endpoint.
Underneath it is Playwright — `playwright-cli attach --cdp=ws://…` (`connectOverCDP` accepts a `ws://` URL) — plus a
tunnel. The wrapper exists to save you from re-deriving that every time.
**New device? Follow [`references/setup.md`](references/setup.md)** with the user. It is a checklist with the exact
commands, the per-browser switch, and a failure→fix table. Then confirm with `remote-browser check`. Do not invent
your own procedure: the failure modes below cost hours.
## Everyday use
```bash
remote-browser profiles # what is configured
remote-browser check --profile deck # readiness test (run this first when something feels off)
remote-browser tabs --profile deck # index, title, url
remote-browser text --profile deck --match linkedin --limit 4000
remote-browser html --profile deck --index 3 --limit 20000
remote-browser shot --profile deck --index 3 --out /tmp/x.png
remote-browser --profile deck cli console # full playwright-cli passthrough
```
Profile defaults to `$REMOTE_BROWSER_PROFILE`, so a single-device setup needs no flag.
### `cli` is not a subset
The built-in verbs are a convenience layer. `remote-browser --profile X cli <anything>` runs that exact
`playwright-cli` command in the **attached** session — `goto`, `click`, `fill`, `console`, `requests`, `storage`
(`state-save`, `cookie-list`, `localstorage-*`), `tracing-start/stop`, `video-start/stop`, `route` mocking,
`run-code`, `pdf`, `tab-*`, `webmcp-list`, `resize`, and the rest of `playwright-cli --help`. Nothing is filtered or
re-implemented, and exit codes propagate.
Two contract details:
- Everything after `cli` is passed through untouched, so put the profile **before** it:
`remote-browser --profile deck cli console`. (`--profile` after a built-in verb, e.g. `remote-browser tabs --profile
deck`, is still parsed by us; after `cli` it is not.)
- `run-code` wants a function: `cli run-code '() => page.title()'`, not `'page.title()'`.
## Rules
- **Read-only by default, not by force.** No click/type/navigate helper is wrapped, because driving an
authenticated session (LinkedIn, Gmail, banking) risks the account being restricted and the user ruled LinkedIn
automation out. The capability is still reachable through `cli` — use it for the user's own pages only when they
ask for it, and say what you are about to do first.
- **Screenshots may contain private data.** Write to `/tmp`, never a Git repo; name the path; never restate
credentials, tokens, cookies or payment details you see in a capture.
- `chrome://` / `edge://` tabs (newtab, apps, inspect) return little text — Chrome blocks script there. Use `shot`.
- Prefer `--match` over `--index`: tabs reorder between calls.
- If attach fails mid-task the user probably unticked the debugging box: re-run `check`, and ask rather than
flipping chrome settings for them.
- Teardown when finished: `pkill -f "ssh -N -L <port>:127.0.0.1:<port>"` and ask them to untick the box.
## The one background fact worth remembering
Chrome ≥136 ignores `--remote-debugging-port` on a normal profile; the `chrome://inspect/#remote-debugging` toggle is
the only way in on a browser the user is already using. That endpoint serves **only**
`ws://127.0.0.1:<port>/devtools/browser` — HTTP `/json/version` and `/json/list` return 403/404, which is why the URL
handed to Playwright must be `ws://`, not `http://`.
@@ -0,0 +1,89 @@
# Setting up a new device
Run this **with the user**, top to bottom. Each step has a check you can perform; do not skip ahead to "try it" when a
check fails — the failures look identical (`attach failed`) for three different causes.
Ask at the start, in one message:
1. **Which machine and which browser?** (Chrome, Chromium, Brave, Edge — not Firefox)
2. **Do I have SSH to it?** `ssh -o BatchMode=yes -o ConnectTimeout=6 <host> true` — if that fails, either ask them
to add a key/entry for their agent host, or use `--transport direct` on a trusted LAN.
3. **Which port?** Default `9222` unless they already run something there (`ss -ltn | grep 9222`).
## Step 1 — create the profile
```bash
remote-browser setup --name <label> --host <ssh-alias-or-address> [--port 9222] [--transport ssh|direct]
remote-browser profiles # confirm the row
```
Profiles live in `~/.config/remote-browser/profiles/<label>.env`, mode 600, and hold no secrets — only transport,
host, port, websocket path and the inspect URL used in error messages. Use `--inspect-url` for non-Chrome browsers
(`edge://inspect/#remote-debugging`, `brave://inspect/#remote-debugging`).
## Step 2 — turn on remote debugging in their browser (user does this)
| Browser | What to open | What to tick |
| --- | --- | --- |
| Chrome / Chromium | `chrome://inspect/#remote-debugging` | "Allow remote debugging for this browser instance" |
| Brave | `brave://inspect/#remote-debugging` | same |
| Edge | `edge://inspect/#remote-debugging` | same |
| Chrome < 136 (or a browser with no toggle) | launch with `--remote-debugging-port=9222 --user-data-dir=<separate dir>` | n/a — separate profile, no logins |
| Firefox | — | not supported (no CDP); offer a PDF/paste route instead |
They keep their logins either way. Chrome prints `Server running at: 127.0.0.1:9222` when the toggle is on.
**Never** set `--remote-debugging-address=0.0.0.0` or open the port on the LAN: CDP is equivalent to handing over the
browser's cookies. Loopback plus an SSH tunnel, or nothing.
## Step 3 — confirm the port on their side
```bash
ssh <host> 'ss -ltn | grep -E "9222|LISTEN"' # Linux
ssh <host> 'lsof -nP -iTCP:9222 -sTCP:LISTEN' # macOS
# Windows: netstat -an | findstr 9222
```
Expect `127.0.0.1:9222`. If it is absent, the toggle is off or the browser was restarted.
## Step 4 — run the readiness test
```bash
remote-browser check --profile <label>
```
It checks, in order: SSH reachability → port reachable through the tunnel → websocket handshake returns 101 →
Playwright attaches → tab count. Read the first ✗ only; later steps are skipped because they cannot pass.
| Symptom | Cause | Fix |
| --- | --- | --- |
| `ssh to <host> failed` | no key, no config entry, host asleep | fix SSH first; or `--transport direct` on a trusted network |
| `cdp port not reachable` | toggle off, browser restarted, different port | re-tick in the browser, check `ss -ltn`, confirm `--port` |
| `websocket handshake returned 403/404` | wrong path, or an HTTP endpoint | profile must use `/devtools/browser`; the URL given to Playwright must be `ws://` |
| `playwright could not attach` | `playwright-cli` missing or too old | `playwright-cli --version`; it must support `attach --cdp=` with a `ws://` value |
| `attached but no tabs found` | browser window has no pages | open any page |
## Step 5 — smoke test, then hand back
```bash
remote-browser tabs --profile <label>
remote-browser text --profile <label> --index 0 --limit 200 # any visible text
remote-browser shot --profile <label> --index 0 --out /tmp/rb-smoke.png
ls -l /tmp/rb-smoke.png # a few hundred KB, not 0
```
Tell the user plainly: what now works, that it is read-only (no clicks, no navigation), that the tunnel can be closed
with `pkill -f "ssh -N -L 9222:127.0.0.1"`, and that unticking the box in their browser disables it entirely.
## Step 6 — record it
- Wiki: add the device and profile to the remote-browser page (host, port, transport, how the toggle was enabled).
- Memory: save one entry naming the profile, the transport, and anything surprising about that device.
- If a step needed a workaround, add it to the table above — the next agent reads this file, not your conversation.
## Housekeeping worth knowing
- One tunnel per port. Two devices both on 9222 collide; give the second profile `--port 9333` and forward that.
- Playwright sessions are named `rb-<profile>`, so parallel devices do not fight over one session.
- `remote-browser cli --profile <label> console` (or `requests`, `cookie-list`) is available when reading page text is
not enough — but treat cookie and storage output as secret, never echo it.
+14
View File
@@ -0,0 +1,14 @@
---
name: roku-tv
description: Control the homelab Roku TV over HDMI-CEC through Bounsweet, the LibreELEC Kodi Raspberry Pi. Use for TV power, checking the HDMI source, or switching the TV to Kodi.
---
Run `~/.dotfiles/bin/roku-tv` on a machine with the configured `bounsweet` SSH alias.
- `roku-tv status` reports the TV's power state, the active CEC source if a device answers, and Kodi's physical address.
- `roku-tv kodi` asks the TV to wake and selects Bounsweet's HDMI input.
- `roku-tv standby` sends standby directly to the TV. Use when the user asks to turn off the TV.
Use the action that matches the user's request. An active source matching `kodi_source` confirms CEC source selection. A successful switch reports `source_verified_by=cec` or `source_verified_by=roku_active_app`. The latter uses a read-only Roku LAN query when the CEC broadcast does not confirm the switch. If the command fails, report that source selection was unconfirmed. If the Roku still reports `0.0.0.0`, check **Settings → System → Control other devices (CEC) → 1-touch play** on the TV before retrying. CEC does not provide Roku Home navigation or app launching via this tool.
[Hardware and troubleshooting notes](https://wiki.godemperordoge.org/homelab/reference/clients/kodi-bounsweet#roku-tv-hdmi-cec)
+20
View File
@@ -0,0 +1,20 @@
---
name: zsa-moonlander
description: Use ZSA Kontroll for live Moonlander control and Zapp for firmware from Arceus via Riolu. Use for Moonlander firmware, Oryx layout revisions, QMK tap-hold tuning and flash detection or recovery.
---
The physical Moonlander normally plugs into Arceus USB 9-2. Proxmox VM 141 (Riolu) owns this port, including bootloader re-enumeration. Run Kontroll and Zapp in Riolu through the existing Arceus handoff SSH config.
```bash
ssh -F ~/handoffs/homelab/lucario/riolu/ssh-config riolu-bootstrap '~/.local/bin/kontroll status; ~/.local/bin/zapp devices --skip-bluetooth'
```
Kontroll 2.0.0 talks directly to the keyboard over USB. Use `kontroll list` or `kontroll status` for read-only discovery, and inspect `--help` before changing the layer, RGB, or brightness. Riolu grants the `zsa-moonlander` group access specifically to Moonlander hidraw interface `01`. Status identified the device and firmware but reported protocol and current layer as unknown on the installed firmware.
Zapp 1.2.0 is installed for `svc`. The guest's `70-zsa-moonlander.rules` grants that account USB access through the `zsa-moonlander` group. Runtime Moonlander is `3297:1969`. The STM32 DFU bootloader is `0483:df11`. If Zapp cannot see the device, check `qm monitor` USB inventory on Arceus and the USB tree in Riolu. When flashing directly on the Deck, confirm the Deck itself sees the DFU device before investigating browser or Flatpak access.
Use Oryx to edit or clone the layout and Zapp to fetch and flash a compiled revision. Retain the last known-good revision or binary and confirm the exact Moonlander target at the time of flashing. Review published artifacts at [ZSA Downloads](https://downloads.zsa.io/zapp/) and check the archive SHA-256. `zapp flash <local .bin or Oryx revision URL>` writes firmware. `zapp update` can immediately fetch and flash the latest Oryx revision, so use `devices` for discovery.
For Shift/Ctrl/Alt tap-hold changes, preserve the assignments and start with one key or a cloned layout. Test an intentional chord and rapid ordinary typing. See [ZSA tap-hold guidance](https://blog.zsa.io/tap-hold-explained/) and [QMK per-key options](https://docs.qmk.fm/tap_hold).
A DFU cycle can detach the input devices from Riolu's static Xorg configuration. Keep the Deck's local controls available. If input is missing after the keyboard returns in normal USB mode, stop `riolu-deskflow`, restart `riolu-xorg`, then start `riolu-deskflow` in Riolu. Confirm both input devices reopen and the Deck reconnects. See the [Riolu Wiki notes](https://wiki.godemperordoge.org/homelab/reference/virtualization/cachyos-gaming-gtx1080#5-moonlander-and-mouse-switching).
+15
View File
@@ -0,0 +1,15 @@
[Unit]
Description=Start the Pi task worker tmux sessions
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=%h/.dotfiles/bin/pi-worker start cohere
ExecStart=%h/.dotfiles/bin/pi-worker start local
ExecStop=-%h/.dotfiles/bin/pi-worker stop cohere
ExecStop=-%h/.dotfiles/bin/pi-worker stop local
[Install]
WantedBy=default.target
+2 -1
View File
@@ -8,7 +8,8 @@ let
# through codemode, the CLI flavour through the mcp bridge (no sandbox).
sharedSkills = [
"git" "gt" "mise-cli" "secrets_man" "searxng" "playwright-cli"
"context-discipline" "homelab-policies" "memory-layer"
"context-discipline" "homelab-policies" "memory-layer" "roku-tv" "zsa-moonlander"
"remote-browser"
];
cliSkills = [ "infra-change" "wiki-update" "wiki-view" "lapis-memory" "handoff" ];
allSkills = sharedSkills ++ cliSkills;
+9 -1
View File
@@ -1,11 +1,19 @@
{ config, lib, pkgs, ... }:
let
secretctl = pkgs.buildGoModule {
pname = "secretctl";
version = "1.0.0";
src = ../tools/secretctl;
vendorHash = "sha256-kp9Y6eG6YiFc+/3hCKYlm147JW/pWZ/dQ8Ds+m2fA34=";
};
in
{
home.packages = with pkgs; [
# everyday CLI
curl wget jq yq-go ripgrep fd tree unzip zip file which rsync tmux
nmap rclone gnupg
# forges and secrets
tea gh bitwarden-cli gitea-mcp-server
tea gh bitwarden-cli gitea-mcp-server secretctl
# VPN client; `dot system` installs its root daemon unit
netbird
# nix tooling
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# Rootless podman needs /etc/subuid and /etc/subgid ranges; without them every
# image pull fails inside the user namespace, which is what `dot boxes` preflights.
set -euo pipefail
cd "$(dirname "$0")/.."
fixture="$(mktemp -d)"
trap 'rm -rf "$fixture"' EXIT
export HOME="$fixture/home"
mkdir -p "$HOME/.config/dotfiles" "$fixture/repo"
DOTFILES_DIR="$fixture/repo"
export DOTFILES_DIR
source <(sed '$d' bin/dot)
STATE_DIR="$HOME/.config/dotfiles"
me="$(id -un)"
# Counts only this user's ranges, and sums several lines.
{
echo "someoneelse:100000:65536"
echo "$me:100000:65536"
echo "$me:1000000:65536"
} >"$fixture/subuid"
[ "$(subid_count "$fixture/subuid")" = 131072 ] || { echo "FAIL: range sum"; exit 1; }
[ "$(subid_count "$fixture/missing")" = 0 ] || { echo "FAIL: missing file"; exit 1; }
# Empty file means no mapping for us.
: >"$fixture/empty"
SUBUID_FILE="$fixture/empty" SUBGID_FILE="$fixture/empty"
export SUBUID_FILE SUBGID_FILE
if podman_subid_ok; then echo "FAIL: empty subid files reported as ok"; exit 1; fi
SUBUID_FILE="$fixture/subuid" SUBGID_FILE="$fixture/subuid"
if ! podman_subid_ok; then echo "FAIL: sufficient ranges rejected"; exit 1; fi
# A too-small range is the failure mode from the bug report.
printf '%s\n' "$me:100000:1024" >"$fixture/small"
SUBUID_FILE="$fixture/small" SUBGID_FILE="$fixture/small"
if podman_subid_ok; then echo "FAIL: 1024 ids accepted"; exit 1; fi
# dot boxes warns before the pull instead of dying mid-unpack, and still runs.
have() { case "$1" in distrobox|podman) return 0;; *) return 1;; esac; }
in_container() { return 1; }
distrobox() { printf 'distrobox %s\n' "$*"; }
out="$(cmd_boxes 2>&1)"
grep -q 'usermod --add-subuids 100000-165535' <<<"$out" || { echo "FAIL: no fix hint"; echo "$out"; exit 1; }
grep -q '^distrobox assemble create' <<<"$out" || { echo "FAIL: assemble skipped"; echo "$out"; exit 1; }
SUBUID_FILE="$fixture/subuid" SUBGID_FILE="$fixture/subuid"
out="$(cmd_boxes 2>&1)"
if grep -q 'usermod' <<<"$out"; then echo "FAIL: warned with sufficient ranges"; exit 1; fi
echo "ok dot boxes subid preflight"
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env bash
# dot doctor's user-systemd report: it must explain, not just repeat, the units
# Home Manager prints at switch time.
set -euo pipefail
cd "$(dirname "$0")/.."
fixture="$(mktemp -d)"
trap 'rm -rf "$fixture"' EXIT
export HOME="$fixture/home"
mkdir -p "$HOME/.config/dotfiles" "$HOME/.config/systemd/user" "$fixture/repo"
DOTFILES_DIR="$fixture/repo"
export DOTFILES_DIR
source <(sed '$d' bin/dot)
STATE_DIR="$HOME/.config/dotfiles"
has_systemd() { return 0; }
profile() { echo headless; }
reset_calls="$fixture/reset.log"
: >"$reset_calls"
systemctl() {
case "$*" in
"--user is-system-running") echo degraded ;;
*"--state=failed list-units"*)
printf 'xdg-desktop-portal-gtk.service loaded failed failed Portal service (GTK)\n'
printf 'xdg-desktop-portal.service loaded failed failed Portal service\n' ;;
*"--state=activating list-units"*)
printf 'relay.service loaded activating auto-restart Temporary relay\n' ;;
*reset-failed*) printf '%s\n' "${*: -2}" >>"$reset_calls" ;;
esac
}
# A unit tracked in git but wired by hand, and one that lives only in the home.
printf '[Unit]\nDescription=x\n' >"$DOTFILES_DIR/pi-workers.service"
ln -s "$DOTFILES_DIR/pi-workers.service" "$HOME/.config/systemd/user/pi-workers.service"
printf '[Unit]\nDescription=y\n' >"$HOME/.config/systemd/user/edge-metrics.service"
out="$(systemd_user_report 0)"
grep -q 'user systemd: degraded' <<<"$out" || { echo "FAIL: session state missing"; exit 1; }
grep -q 'systemctl --user reset-failed xdg-desktop-portal-gtk.service xdg-desktop-portal.service' <<<"$out" \
|| { echo "FAIL: reset hint missing or wrapped"; echo "$out"; exit 1; }
grep -q 'no display here' <<<"$out" || { echo "FAIL: portal explanation missing"; exit 1; }
grep -q 'relay.service' <<<"$out" || { echo "FAIL: restart loop not reported"; exit 1; }
grep -q 'pi-workers.service \[git, wired by hand\]' <<<"$out" || { echo "FAIL: tracked-by-hand unit not reported"; exit 1; }
grep -q 'edge-metrics.service \[not in dotfiles\]' <<<"$out" || { echo "FAIL: unmanaged unit not reported"; exit 1; }
[ -s "$reset_calls" ] && { echo "FAIL: --fix not requested but reset-failed was called"; exit 1; }
systemd_user_report 1 >/dev/null
grep -q 'xdg-desktop-portal.service' "$reset_calls" || { echo "FAIL: --fix did not reset the failed units"; exit 1; }
echo "ok dot doctor systemd report"
Executable
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# dot sync: pull --ff-only + switch only. No upgrades, no flake input bump.
set -euo pipefail
cd "$(dirname "$0")/.."
fixture="$(mktemp -d)"
trap 'rm -rf "$fixture"' EXIT
export HOME="$fixture/home"
mkdir -p "$HOME/.config/dotfiles" "$fixture/repo"
DOTFILES_DIR="$fixture/repo"
export DOTFILES_DIR
# Load the CLI without running main().
source <(sed '$d' bin/dot)
STATE_DIR="$HOME/.config/dotfiles"
log="$fixture/calls.log"
: >"$log"
git() { printf 'git %s\n' "$*" >>"$log"; }
cmd_switch() { printf 'switch %s\n' "${*:-}" >>"$log"; }
flatpak() { printf 'flatpak %s\n' "$*" >>"$log"; }
mise() { printf 'mise %s\n' "$*" >>"$log"; }
claude() { printf 'claude %s\n' "$*" >>"$log"; }
cmd_apps() { printf 'apps\n' >>"$log"; }
have() { case "$1" in git|flatpak|mise|claude) return 0;; *) return 1;; esac; }
cmd_sync
grep -q '^git -C .* pull --ff-only$' "$log" || { echo "FAIL: no ff-only pull"; cat "$log"; exit 1; }
grep -q '^switch' "$log" || { echo "FAIL: no switch"; cat "$log"; exit 1; }
for unwanted in flatpak mise claude apps; do
if grep -qi "^$unwanted" "$log"; then echo "FAIL: dot sync ran $unwanted"; cat "$log"; exit 1; fi
done
# --inputs is refused rather than silently ignored.
: >"$log"
if ( cmd_sync --inputs ) 2>/dev/null; then echo "FAIL: dot sync accepted --inputs"; exit 1; fi
[ -s "$log" ] && { echo "FAIL: dot sync --inputs still pulled"; cat "$log"; exit 1; }
# `dot sync <profile>` passes the profile through to the switch.
: >"$log"
cmd_sync headless
grep -q '^switch headless$' "$log" || { echo "FAIL: profile not forwarded"; cat "$log"; exit 1; }
# The concurrency guard serialises a second run instead of racing it.
exec 8>>"$STATE_DIR/switch.lock"
flock 8
switch_lock_ok=0
if flock -n "$STATE_DIR/switch.lock" 2>/dev/null; then switch_lock_ok=1; fi
[ "$switch_lock_ok" = 0 ] || { echo "FAIL: lock not held by a concurrent run"; exit 1; }
echo "ok dot sync"
+7
View File
@@ -0,0 +1,7 @@
module secretctl
go 1.21
require golang.org/x/term v0.18.0
require golang.org/x/sys v0.18.0 // indirect
+4
View File
@@ -0,0 +1,4 @@
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.18.0 h1:FcHjZXDMxI8mM3nwhX9HlKop4C0YQvCVCdwYl2wOtE8=
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
+205
View File
@@ -0,0 +1,205 @@
package main
import (
"io"
"os"
"regexp"
)
func regexpQuote(s string) string { return regexp.QuoteMeta(s) }
func compileRegexp(p string) (*regexp.Regexp, error) { return regexp.Compile(p) }
func printHelp(w io.Writer) {
io.WriteString(w, `secretctl — keep secrets out of sight and out of argv
secretctl manages environment variables stored in a plain-text file
(default ~/secrets.txt) and injects them into child processes. Secret
values are never printed, never stored in argv, and never logged.
USAGE
secretctl [global flags] <command> [command flags] [arguments]
COMMANDS
list List secret names (values are never shown).
search [-i] [-F] <pattern> List secret names matching a regular expression.
-F literal match -i case-insensitive
get <KEY>... -- <cmd> ... Run <cmd> with the named secrets injected into
its environment. Values are never printed.
run --all -- <cmd> ... Run <cmd> with every secret injected. Use
sparingly; the child can read all secrets.
add <KEY> Add a new secret. The value is read from the
terminal without echo, or from stdin if piped.
set <KEY> Change the value of an existing secret.
rm <KEY> Remove a secret.
check Verify file permissions and syntax.
help [command] Show help for a command.
version Print the version.
GLOBAL FLAGS
-f, --file <path> Secrets file to use (default: ~/secrets.txt, or
$SECRETCTL_FILE if set).
-h, --help Show this help.
--version Print the version.
EXAMPLES
secretctl list
secretctl search 'GIT.*TOKEN'
secretctl get GITEA_DOGE_TOKEN -- git push
secretctl run --all -- make deploy
secretctl add GITEA_DOGE_TOKEN
printf '%s' "$VAL" | secretctl add API_KEY
secretctl set GITEA_DOGE_TOKEN
secretctl rm OLD_TOKEN
secretctl check
FILE FORMAT
One KEY=value pair per line. Blank lines and lines starting with "#"
are ignored, as is an optional leading "export ". Values may be
double-quoted ("...", with \n \t \r \" \\ escapes) or single-quoted
('...'); unquoted values are trimmed and may end with a " #" comment.
secretctl quotes values on write only when necessary and preserves
comments and ordering.
SECURITY
* Values travel only through the environment of a child process.
secretctl has no command that prints a value.
* Values are never accepted as command-line arguments (argv is visible
in ps and shell history); add/set read stdin or a hidden prompt.
* The file is written atomically with mode 0600.
* Prefer "get KEY -- cmd" over "run --all -- cmd": a child should see
only the secrets it needs.
* Run "secretctl check" if you suspect the file permissions drifted.
`)
}
func printListHelp() {
io.WriteString(os.Stdout, `secretctl list — list secret names
USAGE
secretctl list
Prints the name of every secret in the file, one per line, in file order.
Values are never shown.
`)
}
func printSearchHelp() {
io.WriteString(os.Stdout, `secretctl search — find secret names
USAGE
secretctl search [-i] [-F] <pattern>
Prints the names of secrets whose name matches <pattern>. Values are never
shown.
FLAGS
-F, --fixed Treat <pattern> as a literal string instead of a regexp.
-i Case-insensitive match.
EXAMPLES
secretctl search TOKEN
secretctl search '^GIT.*_(TOKEN|PAT)$'
secretctl search -i -F 'github'
`)
}
func printGetHelp() {
io.WriteString(os.Stdout, `secretctl get — run a command with secrets injected
USAGE
secretctl get <KEY> [KEY...] -- <command> [args...]
Runs <command> with the named secrets added to its environment. The values
are never printed and never appear in argv.
The "--" separator is required. Everything after it is the command and its
arguments and is not interpreted by secretctl.
EXAMPLES
secretctl get GITEA_DOGE_TOKEN -- git push origin main
secretctl get DB_PASSWORD API_KEY -- ./server --debug
secretctl get GITEA_DOGE_TOKEN -- sh -c 'curl -H "Authorization: token $GITEA_DOGE_TOKEN" ...'
EXIT STATUS
The exit status of <command>, or 1 if secretctl fails before starting it.
`)
}
func printRunHelp() {
io.WriteString(os.Stdout, `secretctl run — run a command with multiple secrets injected
USAGE
secretctl run --all -- <command> [args...]
secretctl run -e <KEY> [-e <KEY>...] -- <command> [args...]
Like "get", but convenient for selecting many secrets. --all injects every
secret in the file; the child can then read all of them, so prefer "get"
or "-e" when a command needs only a few.
EXAMPLES
secretctl run -e DB_HOST -e DB_PASSWORD -- psql
secretctl run --all -- ./deploy.sh
`)
}
func printAddHelp() {
io.WriteString(os.Stdout, `secretctl add — add a new secret
USAGE
secretctl add <KEY> [--allow-empty]
The value is read from the terminal without echo (entered twice for
confirmation). If stdin is not a terminal, the value is read from stdin
until EOF, so multi-line values (e.g. private keys) work.
Values are never accepted as command-line arguments, because argv is
visible to other users (ps) and recorded in shell history.
FLAGS
--allow-empty Store an empty value.
EXAMPLES
secretctl add GITEA_DOGE_TOKEN
printf '%s' "$TOKEN" | secretctl add GITEA_DOGE_TOKEN
pbpaste | secretctl add SIGNING_KEY
`)
}
func printSetHelp() {
io.WriteString(os.Stdout, `secretctl set — change the value of an existing secret
USAGE
secretctl set <KEY> [--allow-empty]
Reads the new value the same way "add" does (hidden prompt or stdin) and
replaces the existing value. Use "add" to create a new secret.
EXAMPLES
secretctl set GITEA_DOGE_TOKEN
op read op://private/gitea/token | secretctl set GITEA_DOGE_TOKEN
`)
}
func printRmHelp() {
io.WriteString(os.Stdout, `secretctl rm — remove a secret
USAGE
secretctl rm <KEY>
Deletes the named secret from the file. Comments and other secrets are
preserved.
`)
}
func printCheckHelp() {
io.WriteString(os.Stdout, `secretctl check — verify the secrets file
USAGE
secretctl check
Checks that the file exists, parses without errors, has no duplicate names,
and is readable only by you (mode 0600). Exits non-zero if anything is
wrong.
`)
}
+569
View File
@@ -0,0 +1,569 @@
// Command secretctl manages environment variables stored in ~/secrets.txt and
// injects them into child processes without ever printing their values.
package main
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"golang.org/x/term"
)
const version = "1.0.0"
var (
errHelp = errors.New("help requested")
errVersion = errors.New("version requested")
)
type exitError struct{ code int }
func (e *exitError) Error() string { return fmt.Sprintf("exit status %d", e.code) }
type globals struct{ file string }
func main() {
g, rest, err := parseGlobals(os.Args[1:])
switch {
case errors.Is(err, errHelp):
printHelp(os.Stdout)
return
case errors.Is(err, errVersion):
fmt.Println("secretctl " + version)
return
case err != nil:
fatal(err)
}
if len(rest) == 0 {
printHelp(os.Stdout)
return
}
cmd, args := rest[0], rest[1:]
var runErr error
switch cmd {
case "help":
runErr = cmdHelp(args)
case "version":
fmt.Println("secretctl " + version)
case "list", "ls":
runErr = cmdList(g, args)
case "search", "find":
runErr = cmdSearch(g, args)
case "get":
runErr = cmdGet(g, args)
case "run", "exec":
runErr = cmdRun(g, args)
case "add":
runErr = cmdAdd(g, args)
case "set", "change":
runErr = cmdSet(g, args)
case "rm", "remove", "delete":
runErr = cmdRm(g, args)
case "check":
runErr = cmdCheck(g, args)
default:
runErr = fmt.Errorf("unknown command %q (see \"secretctl --help\")", cmd)
}
if runErr != nil {
var ee *exitError
if errors.As(runErr, &ee) {
os.Exit(ee.code)
}
fatal(runErr)
}
}
func fatal(err error) {
fmt.Fprintf(os.Stderr, "secretctl: %v\n", err)
os.Exit(1)
}
// ---- global flags ----------------------------------------------------------
func defaultPath() string {
if p := os.Getenv("SECRETCTL_FILE"); p != "" {
return p
}
home, err := os.UserHomeDir()
if err != nil {
return "secrets.txt"
}
return filepath.Join(home, "secrets.txt")
}
func expandPath(p string) string {
if p == "~" || strings.HasPrefix(p, "~/") {
if home, err := os.UserHomeDir(); err == nil {
return filepath.Join(home, p[1:])
}
}
return p
}
func parseGlobals(args []string) (*globals, []string, error) {
g := &globals{file: defaultPath()}
i := 0
for i < len(args) {
a := args[i]
if a == "--" {
i++
break
}
if !strings.HasPrefix(a, "-") || a == "-" {
break
}
switch {
case a == "-h" || a == "--help":
return g, nil, errHelp
case a == "--version":
return g, nil, errVersion
case a == "-f" || a == "--file":
if i+1 >= len(args) {
return g, nil, fmt.Errorf("flag %s requires a value", a)
}
g.file = args[i+1]
i += 2
case strings.HasPrefix(a, "--file="):
g.file = strings.TrimPrefix(a, "--file=")
i++
case strings.HasPrefix(a, "-f="):
g.file = strings.TrimPrefix(a, "-f=")
i++
default:
return g, nil, fmt.Errorf("unknown flag %q (global flags go before the command; see secretctl --help)", a)
}
}
g.file = expandPath(g.file)
return g, args[i:], nil
}
func isHelpArg(a string) bool { return a == "-h" || a == "--help" }
// ---- process injection -----------------------------------------------------
// mergeEnv returns base with any keys present in extra replaced.
func mergeEnv(base []string, extra map[string]string) []string {
out := make([]string, 0, len(base)+len(extra))
for _, kv := range base {
k := kv
if i := strings.IndexByte(kv, '='); i >= 0 {
k = kv[:i]
}
if _, ok := extra[k]; ok {
continue
}
out = append(out, kv)
}
for k, v := range extra {
out = append(out, k+"="+v)
}
return out
}
// execWithEnv runs argv with the extra environment and propagates its exit code.
func execWithEnv(extra map[string]string, argv []string) error {
cmd := exec.Command(argv[0], argv[1:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = mergeEnv(os.Environ(), extra)
if err := cmd.Run(); err != nil {
var ee *exec.ExitError
if errors.As(err, &ee) {
code := ee.ExitCode()
if code < 0 {
code = 1
}
return &exitError{code: code}
}
return err
}
return nil
}
// readValueFor reads a secret. On a TTY it prompts twice without echo; when
// piped it consumes stdin (so multi-line values such as private keys work).
func readValueFor(prompt string, allowEmpty bool) (string, error) {
var v string
if term.IsTerminal(int(os.Stdin.Fd())) {
fmt.Fprint(os.Stderr, prompt)
b, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Fprintln(os.Stderr)
if err != nil {
return "", err
}
fmt.Fprint(os.Stderr, "Repeat: ")
b2, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Fprintln(os.Stderr)
if err != nil {
return "", err
}
if string(b) != string(b2) {
return "", errors.New("values did not match; nothing was saved")
}
v = string(b)
} else {
data, err := io.ReadAll(os.Stdin)
if err != nil {
return "", err
}
v = strings.TrimRight(string(data), "\r\n")
}
if v == "" && !allowEmpty {
return "", errors.New("empty value; nothing was saved (pass --allow-empty to store an empty value)")
}
return v, nil
}
// ---- commands --------------------------------------------------------------
func cmdList(g *globals, args []string) error {
if len(args) > 0 && isHelpArg(args[0]) {
printListHelp()
return nil
}
if len(args) > 0 {
return errors.New("list takes no arguments")
}
s, err := load(g.file, false)
if err != nil {
return err
}
entries := s.entries()
if len(entries) == 0 {
fmt.Fprintln(os.Stderr, "secretctl: no secrets defined")
return nil
}
for _, e := range entries {
fmt.Println(e.Key)
}
return nil
}
func cmdSearch(g *globals, args []string) error {
ci, fixed := false, false
for len(args) > 0 {
a := args[0]
if a == "--" {
args = args[1:]
break
}
if isHelpArg(a) {
printSearchHelp()
return nil
}
if a == "-i" {
ci = true
args = args[1:]
continue
}
if a == "-F" || a == "--fixed" {
fixed = true
args = args[1:]
continue
}
if strings.HasPrefix(a, "-") && len(a) > 1 {
return fmt.Errorf("unknown flag %q", a)
}
break
}
if len(args) != 1 {
return errors.New("usage: secretctl search [-i] [-F] <pattern>")
}
pattern := args[0]
if fixed {
pattern = regexpQuote(pattern)
}
if ci {
pattern = "(?i)" + pattern
}
re, err := compileRegexp(pattern)
if err != nil {
return fmt.Errorf("invalid regular expression (use -F for a literal search): %v", err)
}
s, err := load(g.file, false)
if err != nil {
return err
}
for _, e := range s.entries() {
if re.MatchString(e.Key) {
fmt.Println(e.Key)
}
}
return nil
}
func cmdGet(g *globals, args []string) error {
if len(args) > 0 && isHelpArg(args[0]) {
printGetHelp()
return nil
}
dash := -1
for i, a := range args {
if a == "--" {
dash = i
break
}
}
if dash < 0 {
return errors.New("missing \"--\" separator\n" +
"secretctl never prints secret values; give it a command to inject them into:\n" +
" secretctl get <KEY> [KEY...] -- <command> [args...]")
}
keys, cmdArgs := args[:dash], args[dash+1:]
if len(keys) == 0 {
return errors.New("no secret names given\nusage: secretctl get <KEY> [KEY...] -- <command> [args...]")
}
if len(cmdArgs) == 0 {
return errors.New("no command given after \"--\"")
}
for _, k := range keys {
if !validKey(k) {
return fmt.Errorf("invalid secret name %q", k)
}
}
s, err := load(g.file, false)
if err != nil {
return err
}
env := make(map[string]string, len(keys))
var missing []string
for _, k := range keys {
if l := s.find(k); l != nil {
env[k] = l.entry.Value
} else {
missing = append(missing, k)
}
}
if len(missing) > 0 {
return fmt.Errorf("undefined secret(s): %s (see \"secretctl list\")", strings.Join(missing, ", "))
}
return execWithEnv(env, cmdArgs)
}
func cmdRun(g *globals, args []string) error {
all := false
var only []string
loop:
for len(args) > 0 {
a := args[0]
switch {
case a == "--":
args = args[1:]
break loop
case isHelpArg(a):
printRunHelp()
return nil
case a == "-a" || a == "--all":
all = true
args = args[1:]
case a == "-e" || a == "--env":
if len(args) < 2 {
return fmt.Errorf("flag %s requires a value", a)
}
only = append(only, args[1])
args = args[2:]
case strings.HasPrefix(a, "-"):
return fmt.Errorf("unknown flag %q before \"--\"", a)
default:
return fmt.Errorf("unexpected argument %q before \"--\"", a)
}
}
if len(args) == 0 {
return errors.New("no command given\nusage: secretctl run [--all | -e KEY ...] -- <command> [args...]")
}
if all && len(only) > 0 {
return errors.New("--all and -e are mutually exclusive")
}
if !all && len(only) == 0 {
return errors.New("nothing to inject; pass -e KEY or --all")
}
s, err := load(g.file, false)
if err != nil {
return err
}
env := map[string]string{}
if all {
for _, e := range s.entries() {
env[e.Key] = e.Value
}
} else {
var missing []string
for _, k := range only {
if !validKey(k) {
return fmt.Errorf("invalid secret name %q", k)
}
if l := s.find(k); l != nil {
env[k] = l.entry.Value
} else {
missing = append(missing, k)
}
}
if len(missing) > 0 {
return fmt.Errorf("undefined secret(s): %s", strings.Join(missing, ", "))
}
}
return execWithEnv(env, args)
}
func cmdAdd(g *globals, args []string) error {
allowEmpty := false
var pos []string
for _, a := range args {
switch {
case isHelpArg(a):
printAddHelp()
return nil
case a == "--allow-empty":
allowEmpty = true
case strings.HasPrefix(a, "-") && len(a) > 1:
return fmt.Errorf("unknown flag %q", a)
default:
pos = append(pos, a)
}
}
if len(pos) != 1 {
return errors.New("usage: secretctl add <KEY> [--allow-empty]")
}
key := pos[0]
if !validKey(key) {
return fmt.Errorf("invalid variable name %q (must match [A-Za-z_][A-Za-z0-9_]*)", key)
}
s, err := load(g.file, true)
if err != nil {
return err
}
if s.find(key) != nil {
return fmt.Errorf("%s already exists; use \"secretctl set %s\" to change it", key, key)
}
val, err := readValueFor(fmt.Sprintf("Value for %s: ", key), allowEmpty)
if err != nil {
return err
}
s.add(key, val)
if err := s.save(); err != nil {
return err
}
fmt.Fprintf(os.Stderr, "added %s to %s\n", key, g.file)
return nil
}
func cmdSet(g *globals, args []string) error {
allowEmpty := false
var pos []string
for _, a := range args {
switch {
case isHelpArg(a):
printSetHelp()
return nil
case a == "--allow-empty":
allowEmpty = true
case strings.HasPrefix(a, "-") && len(a) > 1:
return fmt.Errorf("unknown flag %q", a)
default:
pos = append(pos, a)
}
}
if len(pos) != 1 {
return errors.New("usage: secretctl set <KEY> [--allow-empty]")
}
key := pos[0]
s, err := load(g.file, false)
if err != nil {
return err
}
if s.find(key) == nil {
return fmt.Errorf("%s not found; use \"secretctl add %s\" to create it", key, key)
}
val, err := readValueFor(fmt.Sprintf("New value for %s: ", key), allowEmpty)
if err != nil {
return err
}
s.set(key, val)
if err := s.save(); err != nil {
return err
}
fmt.Fprintf(os.Stderr, "updated %s in %s\n", key, g.file)
return nil
}
func cmdRm(g *globals, args []string) error {
if len(args) > 0 && isHelpArg(args[0]) {
printRmHelp()
return nil
}
if len(args) != 1 {
return errors.New("usage: secretctl rm <KEY>")
}
key := args[0]
s, err := load(g.file, false)
if err != nil {
return err
}
if !s.remove(key) {
return fmt.Errorf("%s not found", key)
}
if err := s.save(); err != nil {
return err
}
fmt.Fprintf(os.Stderr, "removed %s from %s\n", key, g.file)
return nil
}
func cmdCheck(g *globals, args []string) error {
if len(args) > 0 && isHelpArg(args[0]) {
printCheckHelp()
return nil
}
if len(args) > 0 {
return errors.New("check takes no arguments")
}
info, err := os.Stat(g.file)
if err != nil {
return fmt.Errorf("%s: %v", g.file, err)
}
s, err := load(g.file, false)
if err != nil {
return err
}
mode := info.Mode().Perm()
if mode&0o077 != 0 {
return fmt.Errorf("%s has permissions %04o; it should be 0600\n run: chmod 600 %s", g.file, mode, g.file)
}
fmt.Printf("%s: ok, %d secret(s), permissions %04o\n", g.file, len(s.entries()), mode)
return nil
}
func cmdHelp(args []string) error {
if len(args) == 0 {
printHelp(os.Stdout)
return nil
}
switch args[0] {
case "list":
printListHelp()
case "search":
printSearchHelp()
case "get":
printGetHelp()
case "run":
printRunHelp()
case "add":
printAddHelp()
case "set":
printSetHelp()
case "rm":
printRmHelp()
case "check":
printCheckHelp()
default:
return fmt.Errorf("unknown command %q", args[0])
}
return nil
}
+302
View File
@@ -0,0 +1,302 @@
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
)
// Entry is a single KEY=value pair in the secrets file.
type Entry struct {
Key string
Value string
Line int
}
type line struct {
raw string
entry *Entry
}
// Store is the parsed contents of a secrets file.
type Store struct {
path string
lines []line
}
var keyRE = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
func validKey(s string) bool { return keyRE.MatchString(s) }
// load parses the secrets file. When allowMissing is true a missing file
// yields an empty store (used by "add").
func load(path string, allowMissing bool) (*Store, error) {
s := &Store{path: path}
data, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
if allowMissing {
return s, nil
}
return nil, fmt.Errorf("secrets file not found: %s\n create it with: secretctl add MY_SECRET", path)
}
return nil, err
}
warnPerms(path)
text := strings.ReplaceAll(string(data), "\r\n", "\n")
if text == "" {
return s, nil
}
raws := strings.Split(text, "\n")
if raws[len(raws)-1] == "" { // drop artifact of the trailing newline
raws = raws[:len(raws)-1]
}
seen := map[string]int{}
for i, raw := range raws {
l, err := parseLine(raw, i+1)
if err != nil {
return nil, err
}
if l.entry != nil {
if prev, ok := seen[l.entry.Key]; ok {
return nil, fmt.Errorf("line %d: duplicate variable %q (first defined on line %d)",
i+1, l.entry.Key, prev)
}
seen[l.entry.Key] = i + 1
}
s.lines = append(s.lines, l)
}
return s, nil
}
func warnPerms(path string) {
if runtime.GOOS == "windows" {
return
}
info, err := os.Stat(path)
if err != nil {
return
}
if mode := info.Mode().Perm(); mode&0o077 != 0 {
fmt.Fprintf(os.Stderr,
"secretctl: warning: %s has permissions %04o (should be 0600); run: chmod 600 %s\n",
path, mode, path)
}
}
// parseLine never echoes file content in its errors — the line might hold a
// secret we failed to understand.
func parseLine(raw string, no int) (line, error) {
trimmed := strings.TrimSpace(raw)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
return line{raw: raw}, nil
}
body := trimmed
if strings.HasPrefix(body, "export ") {
body = strings.TrimSpace(body[len("export "):])
}
eq := strings.IndexByte(body, '=')
if eq < 0 {
return line{}, fmt.Errorf("line %d: expected KEY=value", no)
}
key := strings.TrimSpace(body[:eq])
if !validKey(key) {
return line{}, fmt.Errorf("line %d: invalid variable name (must match [A-Za-z_][A-Za-z0-9_]*)", no)
}
val, err := parseValue(body[eq+1:])
if err != nil {
return line{}, fmt.Errorf("line %d: %v", no, err)
}
return line{raw: raw, entry: &Entry{Key: key, Value: val, Line: no}}, nil
}
func parseValue(s string) (string, error) {
if s == "" {
return "", nil
}
switch s[0] {
case '"':
var b strings.Builder
for i := 1; i < len(s); {
c := s[i]
if c == '\\' && i+1 < len(s) {
switch s[i+1] {
case 'n':
b.WriteByte('\n')
case 'r':
b.WriteByte('\r')
case 't':
b.WriteByte('\t')
case '"':
b.WriteByte('"')
case '\\':
b.WriteByte('\\')
default:
b.WriteByte('\\')
b.WriteByte(s[i+1])
}
i += 2
continue
}
if c == '"' {
if err := checkTrailer(s[i+1:]); err != nil {
return "", err
}
return b.String(), nil
}
b.WriteByte(c)
i++
}
return "", errors.New("unterminated double-quoted value")
case '\'':
for i := 1; i < len(s); i++ {
if s[i] == '\'' {
if err := checkTrailer(s[i+1:]); err != nil {
return "", err
}
return s[1:i], nil
}
}
return "", errors.New("unterminated single-quoted value")
default:
v := s
if i := strings.Index(v, " #"); i >= 0 {
v = v[:i]
}
if i := strings.Index(v, "\t#"); i >= 0 {
v = v[:i]
}
return strings.TrimRight(v, " \t"), nil
}
}
func checkTrailer(rest string) error {
rest = strings.TrimSpace(rest)
if rest == "" || strings.HasPrefix(rest, "#") {
return nil
}
return errors.New("unexpected characters after closing quote")
}
var plainSafe = regexp.MustCompile(`^[A-Za-z0-9_@%+=:,./-]*$`)
func formatValue(v string) string {
if plainSafe.MatchString(v) {
return v
}
var b strings.Builder
b.WriteByte('"')
for _, r := range v {
switch r {
case '\\':
b.WriteString(`\\`)
case '"':
b.WriteString(`\"`)
case '\n':
b.WriteString(`\n`)
case '\r':
b.WriteString(`\r`)
case '\t':
b.WriteString(`\t`)
default:
b.WriteRune(r)
}
}
b.WriteByte('"')
return b.String()
}
func (s *Store) entries() []*Entry {
out := make([]*Entry, 0, len(s.lines))
for i := range s.lines {
if s.lines[i].entry != nil {
out = append(out, s.lines[i].entry)
}
}
return out
}
func (s *Store) find(key string) *line {
for i := range s.lines {
if s.lines[i].entry != nil && s.lines[i].entry.Key == key {
return &s.lines[i]
}
}
return nil
}
func (s *Store) add(key, val string) {
s.lines = append(s.lines, line{
raw: key + "=" + formatValue(val),
entry: &Entry{Key: key, Value: val},
})
}
func (s *Store) set(key, val string) bool {
for i := range s.lines {
if s.lines[i].entry != nil && s.lines[i].entry.Key == key {
s.lines[i].entry.Value = val
s.lines[i].raw = key + "=" + formatValue(val)
return true
}
}
return false
}
func (s *Store) remove(key string) bool {
for i := range s.lines {
if s.lines[i].entry != nil && s.lines[i].entry.Key == key {
s.lines = append(s.lines[:i], s.lines[i+1:]...)
return true
}
}
return false
}
// save writes the file atomically with mode 0600.
func (s *Store) save() error {
var b strings.Builder
for i, l := range s.lines {
if i > 0 {
b.WriteByte('\n')
}
b.WriteString(l.raw)
}
out := b.String()
if out != "" && !strings.HasSuffix(out, "\n") {
out += "\n"
}
dir := filepath.Dir(s.path)
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
tmp, err := os.CreateTemp(dir, ".secrets-*")
if err != nil {
return err
}
tmpName := tmp.Name()
defer os.Remove(tmpName)
if err := tmp.Chmod(0o600); err != nil {
tmp.Close()
return err
}
if _, err := tmp.WriteString(out); err != nil {
tmp.Close()
return err
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(tmpName, s.path)
}