Plan: a phone’s attachment lands on the box
Closes: #251. Branch: feat/remote-attach. Status: Done (2026-09-28) — shipped with this branch
Erratum (2026-09-28): a safe name has no leading dash either, as well as
no leading dot. The name-safety property found -, which a tool the agent
opens the file with (pdftotext, unzip) would read as an option.
TL;DR
The wire contract is pivot’s and fixed (#251):
device → box { type: "attach", id, name, mimeType, size, seq, data, last }
box → device { type: "response", command: "attach", id, success, error?, data?: { path?, bytes } }
pi-remote’s decisions, made here:
-
Where:
<agentDir>/gadhs-pi-remote/attachments/<sessionId>/(pi-remote’s own state dir,identity.tsstateDir), directories 0700, files 0600. Outside every project, beside pi’s own state, keyed by session, as pivot’s operator suggested. -
Names: the browser’s name is untrusted. Basename only,
[A-Za-z0-9.-]with everything else, no leading dot, 80 characters keeping the extension,filewhen nothing is left; unique by-2,-3… before the extension, and the final name is claimed withlink(2)(EEXIST), never a rename that could overwrite. -
Caps: one file 64 MiB (the device’s own bound), one piece 2 MiB decoded, one session 256 MiB in total. A refusal on the first piece when the declared
sizebreaks a cap, before any byte is written. -
Sweep: an unfinished file is a
.part-<random>beside its session dir. It is dropped when its device sends nothing for 120 s (checked on the nextattachfrom any device), when the same device starts another file, when its pieces go wrong, and at session shutdown. On the first link start of the process,.part-*older than an hour and session directories older than 7 days are removed. -
Mid-turn: a piece is accepted while a turn runs. It touches the disk, not the model; the prompt that names it follows with the delivery the user chose.
-
Reading it back: pi-modes ships a
readallow for/.pi/agent/gadhs-pi-remote/attachments/, so the agent’sreadof an image there needs no judge. A shell tool on the path (pdftotext,unzip -l) goes to the judge as any command outside the workspace does today.
Design
The command (mirror.ts, commands.ts)
PhoneCommand gains
{ kind: "attach"; type; id: string; piece: unknown }: parseCommand
recognises type === "attach" with a string id and hands the record on
whole, so a malformed piece is answered success:false with the fault
named, not dropped - a dropped piece costs the user the device’s 60 s
timeout. A record with no string id stays unknown, as today.
dispatch gains case "attach": host.attachments.piece(device, cmd)
returns { success, error?, data? } and response() wraps it. dispatch
and handleCommand take one more argument, origin: { device?: string }:
peer.ts passes its routingId; member.ts passes the peer the hub
named (hub.ts deliver always names it). A piece with no device is
refused (no device named).
CommandHost gains attachments: Attachments. The store lives on
RemoteState as attachments, built once in createRemote (index.ts,
beside log: deps.log ?? lifecycleLogger(agentDir)) from agentDir,
Date.now and state.log; hostOf hands state.attachments on, so the
hub’s and a member’s link starts share the one store. Building it touches
no disk: pi-remote’s promise is that a session which never gave
/remote-control leaves no trace (index.ts module header). sweep()
runs on the first link start of the process (startHub or startMember),
once, guarded by a flag on the store - the moment pi-remote already makes
its state dir.
The store (packages/pi-remote/attach.ts, new)
class Attachments over { root, now, log, fs? } (fs injectable for the
tests that need a failing disk; the default is node:fs). State:
open: Map<string, OpenFile> keyed ${device}\u0000${id}, and
done: Set<string> of the same keys, so a re-sent seq 0 for a finished
file is refused (already received) rather than landed twice.
piece(device, cmd):
-
sessionIdfromhost.ctx()?.sessionManager.getSessionId(); none → refuseno session. -
Validate the shape:
namestring,sizeinteger ≥ 0,seqinteger ≥ 0,datastring,lastboolean; else refusemalformed attach. -
seq === 0: caps (size> 64 MiB →over 64 MiB; session total +size> 256 MiB →this session holds N MiB of attachments; 256 MiB is the most); an open file for this device is abandoned first (its part unlinked,attach_abandonedlogged withwhy: superseded); then the session dir is made (0700) and the part file openedwx0600. -
seq > 0: no open file for the key → refuseno file open for this id;seq !== open.seq + 1→ refuseout of orderand abandon. -
data: strict base64 (length ≡ 0 mod 4, the alphabet only, padding at the end) → else refusebad base64and abandon; decoded length > 2 MiB →piece over 2 MiB, abandon;bytes + decoded > size→more than the declared size, abandon. Append;bytes += decoded;lastAt = now(). -
last:bytes !== size→ refuseshort: N of M bytes, abandon. Otherwise choose the unique final name,linkSync(part, final)(on EEXIST try the next suffix, bounded at 1000),unlinkSync(part),done.add(key), answer{ path: final, bytes }, logattach_done(bytes, the safe name, never the browser’s). -
Not last: answer
{ bytes }. -
Before any of it,
expireIdle(): every open file withnow() - lastAt > 120 sis abandoned (why: idle).
abandonDevice(device) and closeAll(): the first is for a peer whose
link ended (hub side: Peer.close → deps.attachments?.abandonDevice);
the second at session_shutdown. sweep(), once per store (see above):
under root,
.part-* older than 1 h and session directories whose mtime is older than
7 days, each removal logged attach_swept. Every function ≤ 40 lines;
name-safety, base64 and unique-name are their own pure functions
(safeName, decodePiece, claimName), exported for the tests.
The session total is the sum of sizes of the files completed in this process plus the open ones, held in memory; a resumed session starts at 0 against a directory that may already hold files. Accepted: the cap bounds a session’s run, not the disk for all time - the 7-day sweep bounds that.
Reading it back (pi-modes/modes.json)
Every mode with permission.read rules gains
"/.pi/agent/gadhs-pi-remote/attachments/": "allow". The existing
write/edit /.pi/: ask stands: the agent does not write there.
config.test.ts pins the rule in each mode; authorize.test.ts shows a
read of such a path allowed by rule with no judge call.
The contract from the phone’s side
-
One piece in flight per device: enforced by
seqorder; a device that sends two in parallel getsout of orderon one. -
A refusal ends the file: the part is gone; the next
seq 0starts over. -
pathis absolute, the safe name, on the last piece only. -
An older pi-remote drops
attach(60 s and a clear message on the phone, per pivot); this pi-remote answers every piece it can parse.
Scope
Code
-
packages/pi-remote/attach.ts- new (the source; its test is underpackages/pi-remote/test/, as every pi-remote test is). -
packages/pi-remote/mirror.ts-attachinPhoneCommand/parseCommand. -
packages/pi-remote/commands.ts-CommandHost.attachments,originondispatch/handleCommand,case "attach". -
packages/pi-remote/peer.ts,member.ts- pass the device;Peer.closeabandons its device’s open file. -
packages/pi-remote/index.ts-attachmentsonRemoteState, built increateRemotewith no disk access;sweep()on the first link start;hostOfpasses it;closeAllin thesession_shutdownhandler. -
packages/pi-modes/modes.json- the read allow.
Tests (vitest)
-
packages/pi-remote/test/attach.test.ts(new; temp dir; fake clock):-
property (fast-check): for any string
name,safeName(name)matches^[A-Za-z0-9_][A-Za-z0-9._-]{0,79}$, contains no/,\or.., and keeps a short extension; -
property: any byte array split into pieces of ≤ 2 MiB, sent in order, lands byte-identical at the answered
path; -
regression, the contract’s cases:
seq > 0with no open file refused; out of order refused and the part gone; short onlastrefused; over the declared size refused; bad base64 refused; a secondseq 0from the same device supersedes; a re-sent finished id refused; over 64 MiB refused on the first piece with nothing written; the session cap; two files of one name land asnameandname-2; an idle file abandoned after 120 s;sweepremoves an old part and an old session dir and keeps a fresh one; a disk that fails on write refuses with the error and abandons.
-
-
packages/pi-remote/test/commands.test.ts(contract):dispatchanswersattachthrough the store with the id echoed; no device → refused; malformed → refused, not thrown. -
packages/pi-remote/test/link.test.ts(integration, real wire): a paired device sends three pieces on the hub’s session and receives three responses, the last with apathwhose file holds the bytes; a device whose link ends mid-file leaves no part. -
packages/pi-remote/test/member.test.ts(contract): a member answersattachto the named peer. -
packages/pi-modes/test/config.test.ts(regression): every mode withreadrules carries the attachments allow;packages/pi-modes/test/authorize.test.ts(regression): areadof a path under it is allowed by rule with no judge call, and awritethere is still asked. -
Coverage bars hold (pi-remote 88 % branches).
Docs and release
-
docs/modules/ROOT/pages/remote.adoc§ "What the phone can send" (line 181):attach, where files land, the caps, the sweep, what the prompt then names. -
docs/modules/ROOT/pages/security.adoc§ "A paired device" (line 160): the one place a phone may write on the box, bounded and outside every project; names made safe; never overwritten; the agent reads it by rule, writes it never.modes.adoclists no path rules and is not touched. -
CHANGELOG.adoc== Unreleased(line 7): pi-remote minor (a new command), pi-modes minor (a new allow). -
MR
Closes #251; the merge note tells pivot the path shape and the caps.
Risks
| Risk | Mode | Mitigation |
|---|---|---|
A crafted name escapes the session directory or overwrites a file |
fail-open |
|
A device fills the disk |
fail-open |
64 MiB per file (refused on the first piece from |
Parts of unfinished files linger |
silent |
Abandoned on supersede, error, 120 s idle, peer close and shutdown; the sweep on the next link start catches a crash. Logged each time. |
The agent cannot read what landed (judge defers a "personal file") |
fail-closed (friction) |
The read allow rule; a shell tool on the path still goes to the judge, which is today’s behaviour for any path outside the workspace, and the pending queue means it no longer freezes. |
A piece is answered to the wrong phone |
fail-open |
Answers go where every command’s do: the hub’s own session to the peer
that sent it, a member’s to the |
The browser’s name reaches a log |
silent (privacy) |
Logs carry the safe name and byte counts only. |
Out of scope
-
Reading a PDF or an archive for the agent: its tools and skills do that, as the issue says.
-
Attachments from the desk, or to a member session’s disk other than the box’s own agent dir (all sessions of a box share one root).
-
A per-user or per-box cap across sessions: the 7-day sweep bounds it.