omp packages

@clothespin/pi-pippi0.1.0

pi extension that drives an M5Stack desk-pet pippi over BLE

clothespin Published 1 day ago MIT ~0 downloads/mo

Untested on omp

This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.

Did it work for you?

Result

One report per person. A new report replaces your old one.

Reports 0

No reports yet.

Readme

pi ↔ Pippi desk-pet bridge

A pi extension that streams a live pi session to an M5Stack desk pet over Bluetooth Low Energy, and turns the pet's A / B buttons into approve / deny for risky tool calls.

It speaks the agent-neutral protocol in REFERENCE.md, so the firmware needs no changes — this is the "pi" row in BRIDGES.md.

pi session ──events──▶ bridge.ts ──NDJSON──▶ ble.ts ──BLE──▶ M5StickS3
                          ▲  (in process)      │
                          │                     └──D-Bus──▶ BlueZ
                     {"cmd":"permission", …} ◀────────────────┘

Why the radio speaks D-Bus

pi runs in Node, and Node has no maintained cross-platform BLE stack that handles LE Secure Connections pairing + bonding. On Linux the answer is BlueZ, which is a system service: every radio call is a D-Bus method call. So rather than keep a second language alive for the length of one method call, bluez.ts marshals the D-Bus wire format itself — no native modules, no venv, nothing to install — and ble.ts turns that into a link. If the bus misbehaves the bridge degrades to "disconnected"; it never takes a pi session down with it.

transport.ts is the seam. simulate.ts is a pippi made of TypeScript that answers the same calls, which is what --simulate and the offline tests run against.

Install

Requirements: Node 20+ (pi itself) and, for a real pippi on Linux, BlueZ with D-Bus access. Nothing has to be installed for the radio — the desktop session is already talking to BlueZ.

# Register the extension (writes to ~/.pi/agent/settings.json)
pi install npm:@clothespin/pi-pippi

Then /reload inside pi (or start a new session) and run /pippi on. Check what pi has registered with pi list, and undo with pi remove npm:@clothespin/pi-pippi. Working from a checkout instead of npm? pi install ./bridges/pi loads it straight from the directory.

It loads in place rather than being copied, because package.json declares the entry point under pi.extensions — so editing these files and running /reload is the whole development loop. PI_PIPPI_DISABLE=1 loads the extension but keeps it off. For a single throwaway trial without touching settings, use -e:

pi -e ./bridges/pi

Use

/pippi scan                  find pippis (filters by NUS service UUID)
/pippi connect             → pick one, or: /pippi connect AA:BB:CC:DD:EE:FF
/pippi status              link, battery, encryption, tokens, last snapshot
/pippi approvals <policy>  off | dangerous | all
/pippi tag [name]          what this window is called on the pet
/pippi name <pet>          rename the pet on the device
/pippi owner [name]        whose desk this is (git user.name by default)
/pippi push <folder>       stream a GIF character pack to the device
/pippi ping                poll {"cmd":"status"} and print the reply
/pippi forget              unpair and stop auto-connecting
/pippi on | off            disable the bridge without unloading it

Nothing is sent until this session attaches. A session does not attach by starting — it attaches when you type in it (see Multiple pi sessions), or on /pippi connect / /pippi on. Once attached, the bridge pushes a snapshot on change, a keepalive every 10s, and polls status every 15s — the budgets REFERENCE.md asks for. The footer shows ● Pi-A3F2 · 81% · busy while linked, and ○ pippi: standby (Enter to attach) while it is waiting for you.

Approvals

approvals: dangerous (the default) is a deny-list, not a sandbox — pi still owns its own safety story. It gates bash calls matching a risky pattern (recursive delete, sudo/doas/pkexec, dd to a raw device, mkfs, shutdown/reboot, curl … | sh, git push --force, git reset --hard / clean -fd, chmod -R/777, writes under /etc or /usr, DELETE TRUNCATE TABLE, kubectl/terraform/helm apply-destroy, aws delete|terminate, …) plus write/edit/apply_patch calls that touch a sensitive file (.env, .ssh, .aws, .gnupg, .npmrc, .netrc, id_rsa, credentials, shell rc files) or a path that resolves outside the workspace. The lists live in approvals.ts and are meant to be edited. all gates every tool call; off disables the gate but keeps the pet animating.

Paths are resolved, not string-compared. resolve(cwd, target) plus a structural containing check, so ../other-repo/x.ts gates the same as /home/you/other-repo/x.ts, and a sibling whose name merely starts with the workspace's name is not mistaken for a descendant. ~ is never expanded. An apply_patch body is read for its targets too — both dialects (*** Update File:, and --- a//+++ b//diff --git headers) — under exactly the rules write uses, so a patch cannot reach where write could not, and its device prompt names the files instead of showing 80 bytes of body. A body we cannot parse stays ungated, as it always did: this is a deny-list, and inventing a target we cannot read is not how anybody learns to trust the prompt.

Scratch space is not "outside". /tmp, /var/tmp and os.tmpdir() are throwaways; a write there never gates on location. Sensitive-file rules still apply, because /tmp/.env is a secret file in a scratch directory. Recursive deletes are exempt there too, but only when every operand of every rm in the command is a child of a scratch directory — never the scratch root itself — owned by the user running the bridge, and not a symlink pointing out of scratch. The ownership half is load-bearing: /tmp is world-writable, so what lives there is not necessarily yours. Glob and $var operands stay gated, because resolving them means behaving like a shell, and so does sudo rm -rf, which is no longer a plain rm. rm -rf /tmp always asks.

When a call is gated you get both prompts at once: pi's confirm dialog in the terminal and prompt:{id,tool,hint} on the device. Whichever answers first wins and the other is dismissed, so the device is usable as the only interface (/pippi dialogs notwithstanding). No answer within 60s blocks the tool call with an explanation; set PI_PIPPI_APPROVAL_TIMEOUT=0 to wait forever, or PI_PIPPI_ON_TIMEOUT=allow to fail open. The 60s is one number and it bounds both surfaces: the pet's dialog is cleared by the host when it expires (the device counts up and turns red at 10s, but nothing on it dismisses a question), and the terminal dialog now closes on the same clock rather than waiting out a human who has left the desk. An expired dialog is not a denial -- it is the absence of an answer, and the call stays blocked either way.

If this session cannot ask the human, the call is not silently allowed. A session that does not hold the pippi falls back to pi's confirm dialog in that session's terminal, which is still ours. Only when there is no terminal to ask in either (headless pi -p, no --mode UI) does the call go through, with a warning, rather than deadlock pi.

A link that drops mid-approval does not fall back at all: the question stays open. The panel keeps showing a dialog it was never told to clear -- the snapshot that would clear it had nowhere to go -- so calling the question off the instant the radio wobbled meant the human pressed A, watched the pet acknowledge it, and the answer arrived for a question this session had stopped tracking. The tool call then waited in a terminal for a decision they were sure they had already given, and the log line said nothing a human could act on. So the prompt outlives the drop (promptLinkGraceMs, default 20s), keeps its id, and goes back to the panel when the link does -- which is what makes the answer match. Two things still end the wait: the grace, which reports unavailable (undeliverable, not unanswered) if the pippi has not come back; and the approval timeout, which is the human's clock and keeps running because a second of Bluetooth is not extra time to answer in. A question that was on the panel for less than a second when the link went is treated as never drawn -- nobody could have answered it yet, and that case must report immediately rather than after a grace nobody could use. And when a decision does arrive for a question this session is not holding, it is logged at error with the outcome that closed the last one, because that is the only sign there is that a button was pressed and thrown away.

One gated turn is one claim, and one failure is one message. pi runs the tool calls of an assistant turn concurrently, so five gated calls arrive at once and each one wants the pippi; they now share a single claim. They used not to, and the result was a wall of connect and disconnect lines in the terminal: five Disconnects at a device that was connected to nobody, five dials each torn down by the next, and a failure logged for every teardown. Same on the radio side -- a claim checks whether BlueZ thinks the device is connected before hanging anybody up, and a dial that fails backs off (1s to 15s) instead of asking the adapter once a second forever, because a pippi that is off will stay off through all of them.

Multiple pi sessions

One pippi, many pi windows, no daemon and no lock file. The pet belongs to whichever session the human typed in last. Pressing Enter in a window claims it from whatever window had it; the previous session lets go and stops trying to get it back until you type there.

That is the whole policy, and it holds up because there is one human: two claims cannot be in flight at once, so there is nothing to arbitrate. Concretely:

  • Only typed input claims. pi.on("input") with source === "interactive". Agent activity, tool events, timers, pi -p, and pi instances driven over RPC or by other extensions never claim, so a busy background agent cannot win the pet away from the window you are typing in — and a scripted pi cannot take it at all.

  • A claim takes the link over, and the board -- not the radio -- decides who had it. A BlueZ connection belongs to the adapter, not the process, and a connected peripheral stops advertising, so a pippi held by another window is not busy but unreachable. claim asks BlueZ to drop the old link first (ble.ts:releaseLink). What the adapter does not do is make that exclusive: with one window already holding the pippi, a second one's Connect was answered with success on the same ACL, the first window saw no drop at all, and both of their status requests were served -- by two interleaved replies, which is what a non-JSON from device warning is. Two sessions on one link is not a fight someone loses; it is a pippi whose answers nobody can read. So nothing here is enforced by the radio: the board below is the only arbiter, and a claim without checking it is a claim on your own session's data.

  • A drop nobody asked for is chased back. A reset, a flash, a battery swapped, a walk out of range: the link dies and no human decided anything, so waiting for Enter asks you to fix something you did not do. The bridge takes the pippi back by itself: first try 2s after the drop, then doubling to a 20s cap, for 2 minutes (PI_PIPPI_RECLAIM; 0 never chases), and the status line reads reconnecting… while it runs. Measured on hardware: forced drop, link back in 6s, nobody touched anything. A chase is not free, though -- it may only spend what the human last gave it, which is the next bullet.

  • Who may claim the pippi is a directory, not a guess. The board is $PI_PIPPI_CLAIM_DIR (/tmp/pi-pippi-claims by default) holding one empty file per session pid:

    touch $BOARD/$PPID   # on human input, unconditionally
    # before claiming:   am I the newest stamp in there?
    

    A session that was never typed into has no stamp, so it is last in line and cannot take the pet off the window you are in -- opening a second pi costs nothing. Typing in a window is the entire remedy for anything the board decides, in every window. Stamps are the state, so nothing is handed back, no lease expires, and a crash needs no cleanup: a dead process cannot touch its file again, and a stamp older than five minutes stops counting even if its pid got recycled. Being derived from the directory is what makes the claim agreeable: every session reading it gets the same answer, so there is one claimant at a time without a negotiation. That is worth stating as a rule, because it is easy to break from the radio side -- nothing that is not a human decision may move a stamp, and no part of ble.ts does. A reconnect that re-dated its own claim would find itself the newest claimant every time it looked, in every window independently, which is the livelock two bullets down.

  • Why a directory, when the radio is right there. Because a scan answers "is anyone holding this" and never "who did the human last ask for", and a chase driven off the first question takes the pet off the window the human is in. Measured between two windows on one machine before the board existed: nine hand-overs in 56s, held 3s, stolen, repeat, both sides logging pippi back after 11s and neither able to see that it is the one being stolen from. Not two windows disagreeing about a decision -- both were obeying their own retry, and a retry that acts on the radio instead of on the board re-awards the pippi to whoever is doing it. Asking the directory before every attempt is what turns nine exchanges into one: the window the human left stands down, logs which pid beat it, and stops.

  • A dial that never lands is stopped, and said once. Between "the pippi is asleep" and "the machine it lives on is powered off" the radio looks identical, and a retry ladder cannot tell them apart -- so the ladder has a budget (90s). Spending it ends the loop with one sentence, pippi did not answer in Ns; press Enter here to try again, and leaves not reachable in the state for the status line. An unbounded retry is not patience: it is a process quietly talking to a device no human is waiting for, showing "connecting" forever when the true answer is "I can't reach it". Enter restarts the budget from nothing, because the person pressing it has news the loop does not.

  • A link we no longer own is let go, even when nothing dropped. The keepalive is the only moment a session looks at the world on a schedule, and this is the one thing it cannot otherwise notice. A BlueZ connection belongs to the adapter, not to whoever opened it -- measured, not theorized: with one window holding the link, a second window's claim succeeded, the two sessions' replies arrived interleaved out of order, and the first window never saw a disconnect. It kept reporting an attached pet, writing snapshots to a device that had moved on, and queueing approval prompts that would never be read on it. So each keepalive asks the board the same question a claim would, and a newer stamp anywhere means this session closes the link it no longer owns and says who has it. A mask is deliberately not a takeover: another window holding a question is not holding the pet, and standing down for it would hand the pippi to whoever asked first.

  • An approval outranks the board, and masks it. A tool call blocked on an answer is worth interrupting another window for, so it stamps the board and claims -- and then writes $BOARD/APPROVAL, which is not a stamp. A stamp says who the human left last; the mask says a question is on the screen, and while one is, claims stop everywhere: other windows queue rather than seize the pet away from a dialog they cannot see. It is written once and never refreshed, because its mtime is when the question started and every party decides whether that question still exists by the same subtraction:

    [ $(($(date +%s) - $(stat -c %Y "$BOARD/APPROVAL"))) -gt $PI_PIPPI_APPROVAL_TIMEOUT ]
    

    One constant, no negotiation, nothing to hand back: a session that died mid-question stops being a question by arithmetic and the pippi comes back around by itself. The terminal dialog this session falls back to is bounded by that same constant -- it used to have no deadline at all, which is how an AFK human ended up with an approval arriving an hour later on a tool call pi had long since given up on. If the claim fails the failure cools off for 15s, because a background session working through a list of gated commands would otherwise stall on every one and keep yanking the link.

  • A running session can go dark, on purpose. Once you type elsewhere, the other session's animations stop arriving; its tool calls still work, and so do its approvals (they seize). "Latest activity wins" was the alternative, and it flaps constantly.

Worth knowing: /pippi scan finds nothing while the pippi is attached, because a connected peripheral stops advertising — that is Bluetooth, not a bug.

Which window is asking

Because several windows can hold the pippi, an approval can arrive from a session you are not looking at. Each one sends a short tag with its prompt and the pet draws it beside the timer: approve? 12s [m5sta]. The default is the working directory's name, so two windows in two projects tell themselves apart for free; /pippi tag <name> renames this one, and PI_PIPPI_TAG does it from the shell for people who script tmux layouts. /pippi tag with no argument reports the current name, which is how you find out which window is [m5sta] without walking around the desk.

Seven printable ASCII characters, because that is what fits beside a timer on a 240px panel and the device's field is char[8]. A name the font cannot draw is refused with a message rather than silently dropped, and a tag is never persisted: one that followed you into every window would read the same everywhere and tell you nothing. Two windows open in the same project do show the same tag — the wire has nothing better to say about them unless you name them.

Configuration

Environment variables (all optional; every one is read at session start):

Variable Default Meaning
PI_PIPPI_DISABLE — 1 loads the extension but keeps it off
PI_PIPPI_TRANSPORT ble ble | simulate | null
PI_PIPPI_DEVICE saved device address to auto-connect
PI_PIPPI_APPROVALS dangerous off | dangerous | all
PI_PIPPI_APPROVAL_TIMEOUT 60 seconds; 0 waits forever
PI_PIPPI_ON_TIMEOUT block block | allow
PI_PIPPI_RECLAIM 120 seconds to chase a pippi that dropped by itself; 0 never chases
PI_PIPPI_CLAIM_DIR /tmp/pi-pippi-claims the claim board: who may take the pippi, by whose keystroke, newest stamp wins. Two windows must share one directory, so relocate it together with PI_PIPPI_STATE_DIR if you relocate that
PI_PIPPI_OWNER git user, else $USER shown by the owner command
PI_PIPPI_TAG working directory's name shown beside an approval on the pet
PI_PIPPI_PROVIDER the session's model provider whose mark to wear beside the pet
PI_PIPPI_TURN_EVENTS off also send {"evt":"turn"} messages
PI_PIPPI_WIRE_LOG — append every tx/rx line to a file
PI_PIPPI_STATE_DIR $XDG_CACHE_HOME/pi-pippi where the device address, owner and daily token counter live
PI_PIPPI_USAGE_INTERVAL 300 seconds between usage queries; 0 leaves the usage rows off
PI_PIPPI_USAGE_LOW 5 percentage under which a usage bar blinks red
PI_PIPPI_USAGE_SPEC — draw these meters instead of asking a provider — see below

PI_PIPPI_USAGE_SPEC exists because there are sessions whose usage cannot be asked about and layouts that cannot be seen without it: a model served by a local backend has no subscription and no balance to draw down, and the second quota window of an account that has only used one takes a week of real use to produce. It takes a report, not a conclusion — 5h=83,7d=21 are percentages left, $balance= 12.50 is a wallet — and feeds it through the same normalisation and the same clamps as a provider's own, so what it shows you is the real layout with invented numbers. What it does not test is the query itself: the service on the event bus is bypassed entirely, and the log says so once per distinct spec, because a bar that looks ordinary and is not is the one failure mode this feature cannot afford.

The badge is the other thing the model is read for. model_select carries the provider, and ctx.model is read at session_start because restoring a session does not fire model_select — a resumed window would otherwise show no mark until you cycled models. pi's name for a provider is not always the name of the company whose account it is, so openai-codex is sent as openai and Kimi For Coding as moonshot; a proxy pi knows nothing about — llama-swap, my-box-lan — goes through as it came and the pet draws a square coloured from a hash of it with its initial on top, which is the designed answer and not a missing logo. Set PI_PIPPI_PROVIDER=anthropic when you know better than the endpoint: llama-swap serving Claude should wear Claude's mark, and only you have configured the box.

Settings that persist across sessions (state.ts): the paired address, the approvals policy, on/off, and the token counter — which resets at local midnight so the pet's "tokens today" matches a day of work, not a week. An explicit PI_PIPPI_APPROVALS / PI_PIPPI_DEVICE for one run wins over what was saved. The session tag is the one setting that deliberately does not persist.

Development

cd bridges/pi
node --test tests/                                   # 210 tests, no radio
node dev-run.mjs --smoke                             # end-to-end against the simulator

tests/simulate.test.ts drives the scripted pippi (simulate.ts: acks, scans, connect failures, chunk accounting), and tests/ble.test.ts runs the real BlueZ code path against a fake D-Bus — including the tree recorded from a live adapter in tests/fixtures/bluez_gatt_tree.json, because a fake built from memory hides exactly the hardware-only bug class. dev-run.mjs is the manual harness:

node dev-run.mjs                       # simulator: snapshots + a self-answered prompt
node dev-run.mjs --ble --scan          # real radio: scan
node dev-run.mjs --ble --target AA:BB:CC:DD:EE:FF --keep
PI_PIPPI_WIRE_LOG=/tmp/wire.log node dev-run.mjs

To type-check against pi's real declarations:

npm install
npx tsc --noEmit --strict --target ES2022 --module nodenext \
  --moduleResolution nodenext --allowImportingTsExtensions index.ts

The three devDependencies are build-time only: pi-coding-agent for the extension API's types, typescript for the check above, @types/node for node --test. Nothing here is imported at runtime -- pi provides the host package, and the radio is BlueZ over D-Bus, which this directory speaks itself (bluez.ts) -- so npm install is never needed to run the extension.

Notes and known gaps

  • Protocol limits are enforced locally. REFERENCE.md caps a device line at 1024 bytes, so protocol.ts trims msg, drops oldest transcript entries, and finally refuses to send rather than emit a line the firmware would drop mid-parse. Folder pushes use 256-byte base64 chunks, matching src/xfer.h.
  • Turn events are off by default. Current firmware ignores {"evt":"turn"}; the flag exists for a firmware that grows a use for it.
  • Discovery is by service UUID, not name. The firmware advertises Pi-XXXX, but the bridge never keys on that: it filters on the Nordic UART UUID and offers --name-prefix if you want to narrow a noisy scan.
  • Pairing. LE Secure Connections uses a passkey the device shows; type it in the OS pairing prompt. Bonding is recommended — the pet re-pairs on every boot otherwise. /pippi forget unpairs.
  • Daily token counter counts output tokens only, since that is what pi reports per assistant message.
  • A chase cannot repair a pairing. It asks whether the pippi is free, not whether it will accept the bond. If the two sides no longer share one — the device's bonds were cleared, or /pippi forget ran on either side — every attempt fails exactly the way it did before this existed, and the give-up line points at Enter. Re-pair from the device's reset menu.
  • Throughput is timed by the bridge, not the provider. The pet's prefill and decode rows are token counts divided by the bridge's own clock: prefill is every prompt token (cache reads included) over time-to-first-token from message_start, decode is output tokens over the streaming window. So prefill includes request setup and whatever the provider queues before the first token — it is the wait you feel, not a tokenizer benchmark. Rates are a mean of the last five responses, windows under 50ms are refused as noise, and nothing is sent until one response has been timed (the rows read n/a until then, never 0/s).
  • Headless pi (-p, --mode json) still drives the pet, including snapshots and running/waiting state, but there is no terminal dialog to race, so gated calls wait for the device or the timeout.