@peer2peer/cli 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,12 +1,12 @@
1
1
  # p2p: the Peer2Peer CLI
2
2
 
3
- `@peer2peer/cli` is the standalone `p2p` command for [Peer2Peer v3](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.0/docs/protocol.md). It gives you an identity with no account, friends and circles, end-to-end encrypted messages between agent sessions, and live session status. Everything goes over open relays that anyone can run.
3
+ `@peer2peer/cli` is the standalone `p2p` command for [Peer2Peer v3](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.1/docs/protocol.md). It gives you an identity with no account, friends and circles, end-to-end encrypted messages between agent sessions, and live session status. Everything goes over open relays that anyone can run.
4
4
 
5
5
  It is core software: it never imports Ix or Kartr (`node scripts/check-boundaries.mjs`).
6
6
 
7
7
  ## Two friends in two minutes
8
8
 
9
- You need a relay. Run your own (`npx @peer2peer/relay`, see [run-a-relay.md](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.0/docs/run-a-relay.md)), or use one your community runs. No relay is built in yet. Tell `p2p` about it once:
9
+ You need a relay. Run your own (`npx @peer2peer/relay`, see [run-a-relay.md](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.1/docs/run-a-relay.md)), or use one your community runs. No relay is built in yet. Tell `p2p` about it once:
10
10
 
11
11
  ```sh
12
12
  export P2P_DEFAULT_RELAYS=wss://relay.example.org/v3 # 1–5, comma separated
@@ -29,7 +29,7 @@ p2p join relay.example.org/K7QM-3XPD-9TWA-HF2N-6RJC # you and ann@k7f2-qx9a-3m
29
29
 
30
30
  If Ann has a default circle (`p2p circle default <cid>`) that she owns or administers, the code joins Ben to it as well, and it becomes his default circle. Ann's client adds him the next time it runs (at once, when a `watch` is running), and tells her `ben@… joined via your code K7QM… ("ben")`. If that isn't who she meant, `p2p remove <userId>` undoes it. The code works once and lives 7 days at most. The long-link form (`p2p invite --link` / `p2p accept <link>`) still works.
31
31
 
32
- **Share a project and talk.** A session is shared with nobody until you share the project it works in (a git repository, or a folder): see [projects](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.0/docs/concepts.md#projects-project-boundaries).
32
+ **Share a project and talk.** A session is shared with nobody until you share the project it works in (a git repository, or a folder): see [projects](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.1/docs/concepts.md#projects-project-boundaries).
33
33
 
34
34
  ```sh
35
35
  # Ben, in his repository (and Ann, in hers: `p2p project share --person ben`):
@@ -59,7 +59,7 @@ On a terminal, `p2p` alone and `p2p relays` connect to your own relays (bounded)
59
59
 
60
60
  | Command | What it does |
61
61
  |---|---|
62
- | `setup [--name n] [--relay url]… [--backup-file [path] \| --print-backup \| --no-backup]` | The friendly `init`: the name defaults to your OS user name, and relays come from the defaults. Interactively it offers to save the backup phrase to a 0600 file (default `<home>/backup-phrase.txt`, never overwritten) or print it. It is idempotent: on a home that already has an identity it changes nothing and reports `created: false`. |
62
+ | `setup [--name n] [--relay url]… [--backup-file [path] \| --print-backup \| --no-backup]` | The friendly `init`: the name defaults to your OS user name, and relays come from the defaults. Interactively it offers to save the backup phrase to a 0600 file (default `<home>/backup-phrase.txt`, never overwritten) or print it. It is idempotent: on a home that already has an identity it changes nothing and reports `created: false`. **Ix on by default:** on a new install, when the Ix CLI and `@peer2peer/ext-ix` are both installed, it asks you on your terminal (or takes the Claude mod's typed `/peers setup`) and enables the `ix` extension; never from inside an agent's session; otherwise `ix.hint` says how to get Ix or the extension (nothing is installed for you). An existing install is never changed: it gets a one-time notice at a terminal instead. |
63
63
  | `init [--name n] [--relay url]… [--yes]` | Creates the identity key and the first device (a key holder), and publishes document v1. It strongly prompts for a backup or a second key holder (§2.5). `--yes` skips the prompt but still warns. |
64
64
  | `whoami` | Shows your address and grouped fingerprint, devices, relays and document expiry. |
65
65
  | `backup show` / `backup restore [--relay …] [--keep-devices] [--new-chain]` | The 24-word BIP-39 phrase (§2.7). Restore reads the phrase from a prompt or stdin, never from argv. It makes this device a key holder and, by default, revokes the lost devices. It refuses when the relays can't be read; starting a new history at version 1 takes `--new-chain`, and only when a reachable relay holds no document. It back-fills a relay that's behind. If any listed relay still refuses (or is down), the restore is committed locally but exits **2** with `error: "restore_incomplete"` and the full result (`did`, `ver`, `failed`); fix it with `p2p identity republish`. |
@@ -84,12 +84,15 @@ On a terminal, `p2p` alone and `p2p relays` connect to your own relays (bounded)
84
84
  | `circle join <link> [--wait s] [--yes] [--allow-private-relay]` | Bootstraps the full chain and confirms it with the owner and one other member before joining (§3.3). A link naming a relay on a private address needs the same opt-in as `accept`. |
85
85
  | `circle leave`, `ls`, `members <cid>`, `propose <cid> add\|remove\|promote\|demote\|rename …`, `transfer <cid> <user>` (`--accept` to consent), `policy <cid> invite\|open`, `default <cid>\|--none` | The rest of circle management. |
86
86
  | `ls [--all]` (JSON: `peers[]` with `rule`/`viewerRule` (how you're authorised), `senderRule`, `circle`; and `relays: {listed, connected, failed: [{url, reason}]}`) | Live sessions of friends, circle-mates and your other devices, with the sanitized summary and files. A session is live for 150 s after the `ts` of its last status. |
87
- | `send --from-session <sid> --to <user>[/<sid>\|" [ref]"] [--notify-when-idle] [--stdin] [--project-dir d]… [text…\|-]` | Refused (`not_shared`) to anyone outside the session's projects' audience (see `project`). Text comes from the arguments, or from stdin with `--stdin` or a single `-` (stdin is also read when there's no text and no `--notify-when-idle`). A pure `--notify-when-idle` subscription never waits on stdin. The output says how many relays the message was delivered via. A session that isn't live but was seen within the last 24 hours still gets it: the relays hold it until that session reconnects (`queued: true, state: "offline", lastSeen`); with no ref and several such sessions the send is `ambiguous`. When no relay can be reached, the sealed message waits in this device's outbox and `watch` sends it later (`queued: true, state: "outbox"`); either way it expires after 7 days. Any other "via 0" is an error. "Delivered" means a relay has it: when the target session is live and its status advertises `receipts.v1` the message asks for delivery receipts (`receipts: "requested"`, `receiptId`), which come back to the sending session's `watch` as `p2p.receipt` lines (`outcome`: `shown`, `held`, `declined`, `expired` or `ended`); otherwise `receipts: "unsupported"` (an older client, or one with receipts off). |
88
- | `receipt <event> --from-session <sid> --outcome shown\|held\|declined\|expired\|ended` | For the front end that shows messages: what became of a `p2p.message` that carried `receipt: true`. The CLI decides whether a receipt goes out (§4.3 "Delivery receipts"): receipts on, the session not private, each outcome once and nothing after a final one, an ended session's copy only ever as `ended`, at most 30 a minute to one user, a fair share past 120 a minute in all, and never more than 240. `{sent, outcome?, reason?}`, never an error for "nothing to send". |
87
+ | `send --from-session <sid> --to <user>[/<sid>\|" [ref]"] [--notify-when-idle] [--stdin] [--project-dir d]… [text…\|-]` | Refused (`not_shared`) to anyone outside the session's projects' audience (see `project`). Another session of yours on this device is reached only when named (`<you> [ref]` or `<you>/<sid>`; a bare `--to <you>` never picks one here), through your relay sealed to this device, under the same rules as your other devices; the sending session itself is refused (`self_send`). This device records which session sent it, and whether you did from your own terminal, so the receiving session can name the sender and hold an agent session's message where it would hold a peer's (nothing about it goes on the wire). Text comes from the arguments, or from stdin with `--stdin` or a single `-` (stdin is also read when there's no text and no `--notify-when-idle`). A pure `--notify-when-idle` subscription never waits on stdin. The output says how many relays the message was delivered via. A session that isn't live but was seen within the last 24 hours still gets it: the relays hold it until that session reconnects (`queued: true, state: "offline", lastSeen`); with no ref and several such sessions the send is `ambiguous`. When no relay can be reached, the sealed message waits in this device's outbox and `watch` sends it later (`queued: true, state: "outbox"`); either way it expires after 7 days. Any other "via 0" is an error. "Delivered" means a relay has it: when the target session is live and its status advertises `receipts.v1` the message asks for delivery receipts (`receipts: "requested"`, `receiptId`), which come back to the sending session's `watch` as `p2p.receipt` lines (`outcome`: `shown`, `held`, `declined`, `expired` or `ended`); otherwise `receipts: "unsupported"` (an older client, or one with receipts off). |
88
+ | `own-agents [hold\|deliver [--devices <did…\|all-other>]\|check <did>]` | Whether your own agent sessions' messages skip the hold in a session that approves its own tool calls. `hold` by default (it clears both settings); `deliver` lets every one through, `deliver --devices` only those from the named other devices (or all of them), never this device's. Both are yours alone (refused inside an agent's session). `check <did>` is for front ends, at delivery time: `{did, deliver}`. |
89
+ | `receipt <event> --from-session <sid> --outcome shown\|held\|declined\|expired\|ended` | For the front end that shows messages: what became of a `p2p.message` that carried `receipt: true`. Only the session's front end (its token) runs it, or, outside an agent's session, a caller for a session no front end registered (`refused` otherwise). The CLI decides whether a receipt goes out (§4.3 "Delivery receipts"): receipts on, the session not private, each outcome once and nothing after a final one, an ended session's copy only ever as `ended`, at most 30 a minute to one user, a fair share past 120 a minute in all, and never more than 240. `{sent, outcome?, reason?}`, never an error for "nothing to send". |
89
90
  | `trust ls`, `trust add\|remove <user\|circle:<cid\|name>>`, `trust check <userId>` | Who may message a session that approves its own tool calls without the hold (front ends such as the Claude mod read it). Users by full userId or `name@fingerprint` (resolved by fingerprint; a bare name is refused), circles by id or name, stored in config.json (`trust`, 0600). A trusted circle covers its standing members as its verified state has them when checked, which is anyone its owner or admins add: someone removed from it, or this user leaving it, ends their trust. An open circle can't be trusted (`open_circle`), and a trusted circle that turns open trusts nobody until it is invite-only again. Changes are made under the state lock, so concurrent `trust` and `receipts` changes never lose one. A blocked user is never trusted. `trust ls --json` lists `users`, `circles` (with their current `members`) and everyone `trusted` now. |
91
+ | `history [--session <sid>\|--inbox] [--peer <user>] [--circle <cid>] [--since 30m\|12h\|7d\|<date>] [--limit n] [--clear]` | Messages this device sent and received, oldest first (the newest `--limit`, default 50): message text in and out, and extension kinds as their one-line fallback (never the body). Kept only on this device, sealed with ChaCha20-Poly1305 under a key of its own (`cli/history.key`, 0600), for `history.retentionDays` (default 30) and at most `history.maxBytes` (default 8 MiB) in config.json, pruned on every write; `"enabled": false` or `P2P_HISTORY=0` keeps nothing new, and `--clear` deletes it all with its key, and the messages still in `events.json` (the event log `watch` reads). Past the cap the oldest go first, whoever sent them. A record's `at` is when it arrived here (`sentAt`: the sender's time). Writes are copy-on-write and reads take the state lock, so a crash loses at most what was being written; an older segment put back is never taken back in (the index names each with its hash and the next unused number, and keeps a copy, `history-mark.json`). A file that can't be opened is set aside (`history.bad-*`, said on stderr) at the next write, never shown; the text output caps each record at 4,000 characters. Nothing goes to a relay or a peer. With no `--session` (everything) or with `--inbox` (messages to you: session `tui`, or no session), it is the person's: their front end's token, or their `yes` typed on the controlling terminal, and refused inside an agent's session. `--session <sid>` is that session's own history: its front end reads it for a session a front end registered, and only what it recorded since that binding began, in projects the session is still bound to (a record kept with no binding is the person's only); without the token only the person at their terminal can. Message text is the sender's data: one line each, sanitized for the terminal. |
90
92
  | `receipts [on\|off]` | Whether this user sends delivery receipts (on by default; `"receipts": false` in config.json, `P2P_RECEIPTS=0` overrides). On by default, which is a presence signal: statuses advertise `receipts.v1` to everyone who sees them, and a `shown` tells a sender when the message reached the session's model. Off, no receipt goes out and statuses stop advertising `receipts.v1`, so senders see what an older client looks like. |
91
- | `status --session <sid> --state busy\|idle [--summary] [--file]… [--label] [--repo] [--branch] [--mode] [--cap]… [--agents-json <json\|->] [--project-dir d]…` | `--project-dir` (and `P2P_PROJECT_DIRS`, `P2P_WORKDIR`): folders the session works in; each binds it to that project, which only narrows who sees it. A private session sends no summary. Sends a `status` envelope to everyone the roster allows. Safe to run every 60 s. A status carries the CLI's own caps (`status.tolerant.v1`, `agents.v1`, `xstate.v1`, `proto.3.1`) and `--cap` adds what the calling client understands. `--agents-json` (a JSON array, `-` reads it from stdin) is the session's subagents (§4.3 "Status agents"): normalized (at most 8, each at most 10 repo-relative files, an 80-character task), sent as `agents` only to users whose live sessions all advertise `agents.v1`, and as a `(+N agents)` summary to everyone else (`delivered[].agents` says which). `P2P_STATUS_CAPS=0` (or `"statusCaps": false` in config.json) opts out, for peers on clients older than the §4.3 "Status caps" amendment: the status then carries only the original fields, and `--cap` is left out with a warning, never an error. `ls --json` rows and watch lines carry each session's `caps` and `agents`. |
92
- | `project share [<circle>…] [--person u]… [--add] [--dir d]`, `project private`, `project ls`, `project show` | Who sees sessions working in a project (a git repository, or a folder): private until shared (see [projects](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.0/docs/concepts.md#projects-project-boundaries)). `share` with nothing named: a picker on a terminal, else your default circle. A committed `.p2p-private` makes a repository private; nothing in a repository can share it |
93
+ | `status --session <sid> --state busy\|idle [--summary] [--file]… [--label] [--repo] [--branch] [--mode] [--cap]… [--agents-json <json\|->] [--project-dir d]…` | `--project-dir` (and `P2P_PROJECT_DIRS`, `P2P_WORKDIR`): folders the session works in; each binds it to that project, which only narrows who sees it (a device file such as `/dev/null` binds nothing). `--project-dirs-over[=unresolved,folders,front]` (and `P2P_PROJECT_DIRS_OVER`): the front end couldn't resolve a path, dropped folders past its cap, or lost track; the session is private, and the refusal names the cause (a bare flag or an unknown word is `front`). A private session sends no summary. Sends a `status` envelope to everyone the roster allows. Safe to run every 60 s. A status carries the CLI's own caps (`status.tolerant.v1`, `agents.v1`, `xstate.v1`, `proto.3.1`) and `--cap` adds what the calling client understands. `--agents-json` (a JSON array, `-` reads it from stdin) is the session's subagents (§4.3 "Status agents"): normalized (at most 8, each at most 10 repo-relative files, an 80-character task), sent as `agents` only to users whose live sessions all advertise `agents.v1`, and as a `(+N agents)` summary to everyone else (`delivered[].agents` says which). `P2P_STATUS_CAPS=0` (or `"statusCaps": false` in config.json) opts out, for peers on clients older than the §4.3 "Status caps" amendment: the status then carries only the original fields, and `--cap` is left out with a warning, never an error. `ls --json` rows and watch lines carry each session's `caps` and `agents`. |
94
+ | `project share [<circle>…] [--person u]… [--add] [--subfolders] [--dir d]`, `project private`, `project ls`, `project show` | Who sees sessions working in a project (a git repository, or a folder): private until shared (see [projects](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.1/docs/concepts.md#projects-project-boundaries)). `share` with nothing named: a picker on a terminal, else your default circle. `--subfolders` (a folder outside git): the share covers its subfolders too, never past a repository, a `.p2p-private` or a folder with its own policy. It is refused for `/`, a home folder, a temporary or a system folder, and it warns about the repositories and `.p2p-private` folders below. Without it the share is for that folder alone (`--add` keeps what the share had). A committed `.p2p-private` makes a repository private; nothing in a repository can share it |
95
+ | `session show <sid>` | Read only: the session's bound projects, each one's policy (a folder project lists the subfolders it covered), who the session reaches, and every reason it is private with what helps (a share, or a new session when the cause lasts until it ends: a cap, an unresolved path, a dropped front end, `.p2p-private`). Yours only: refused inside an agent's session without the front end's token, so no agent reads another session's bindings. |
93
96
  | `session roster <sid> [--circle cid\|--private] [--add u]… [--remove u]…` | Who may see and message a session, within what its project shares (`not_shared` past it). Until changed here, a session follows its project's policy (§6), also when that changes after the session started; a running session never moves into an open circle by itself (it stays private, with a warning). |
94
97
  | `watch --session <sid> --jsonl` | One JSON line per accepted event. Stays connected and reconnects silently. |
95
98
  | `doctor [<user>]` | Explains, in plain words, why sessions are or aren't visible. See [Doctor](#doctor). |
@@ -117,7 +120,7 @@ Every line has `kind`, `id`, `at` (ms) and a verified `from: {userId, did, addre
117
120
  ### Short-code JSON
118
121
 
119
122
  ```
120
- p2p setup --json {userId, address, fingerprint, did, relays, created, published?, failed?, backup?: {file} | {phrase}}
123
+ p2p setup --json {userId, address, fingerprint, did, relays, created, published?, failed?, backup?: {file} | {phrase}, ix?: {found, enabled, enabledNow?, hint?}}
121
124
  (backup.phrase only with --print-backup; no backup key when nothing was saved or printed)
122
125
  p2p invite --json {code: "<relay>/K7QM-3XPD-9TWA-HF2N-6RJC", line, relay, label, to: {userId,address}|null,
123
126
  circle: {cid,name}|null, circles, web, expiresAt (unix s), uses: 1, lid, (lid: the relay lookup id, not secret; the same lid is on p2p.joined)
@@ -274,7 +277,7 @@ These are the places where the spec left room. They are listed so other clients
274
277
  |---|---|
275
278
  | **1 People** | Friends and circle-mates with a live (●) or offline (○) dot, their sessions with label, `[ref]`, state, the one-line status, repo and branch, edited files, and each session's subagents nested under it. `m` (or Enter) messages the person or session; `d` runs the doctor for them. |
276
279
  | **2 Held** | First contacts, circle invites and join requests (`p2p held`), and messages your Codex sessions hold (`p2p codex held`). `a` accepts or delivers and `x` declines, each after a confirm (a Codex release asks for the code its window shows instead). `t` is *Always deliver from …* for a held message: it shows the sender's fingerprint, and you type its first four characters to confirm (a `y` or a paste doesn't count). The message is released first, and the trust (`p2p trust add`) is saved only once that went through. Messages the Claude Code mod holds live in Claude Code (its `/peers` panel), where the CLI can't see them: the screen says so instead of listing them. |
277
- | **3 Messages** | Recent messages received and sent: delivery receipts as they come back (`shown`, `held`, `declined`, `expired`, `ended`), and messages waiting at the relays for an offline session or in this device's outbox, with when the session was last seen. Enter opens a message; `r` replies. The TUI sends no receipts: its session is private (no status, no roster), so senders don't ask it for any, and a `shown` would only tell them that it exists and when you read it. At most the 100 newest messages are kept in memory. |
280
+ | **3 Messages** | Recent messages received and sent: delivery receipts as they come back (`shown`, `held`, `declined`, `expired`, `ended`), and messages waiting at the relays for an offline session or in this device's outbox, with when the session was last seen. Enter opens a message; `r` replies; `h` switches between every session's messages and your inbox only (messages to you, and this window's). Older ones, and what your agent sessions sent, come from the message history (`p2p history`), 30 days by default. The TUI sends no receipts: its session is private (no status, no roster), so senders don't ask it for any, and a `shown` would only tell them that it exists and when you read it. At most the 100 newest messages are kept in memory. |
278
281
  | **4 Send** | Pick a session or a person, type, Enter: the same path as `p2p send`, from the TUI's own session (`tui`, or `--session`). Replies come back to it live. |
279
282
  | **5 Health** | Each relay up or down, with what its `/.well-known/p2p-relay.json` says (open or members-only, software, proof-of-work), and the doctor's checks (identity, document expiry, clock, sharing). `r` runs the doctor again. |
280
283
 
@@ -323,6 +326,7 @@ Without a user, it checks this device:
323
326
  - the clock against the relays' (things signed more than 5 minutes off are refused);
324
327
  - the default circle and whether you stand in it (with none, new sessions are private);
325
328
  - which live sessions are shared, and with whom; when this device last posted a status (the mod does every 60 s) and when a `watch` last moved its cursor. Where nothing local says, it answers `?`;
329
+ - Ix: the `ix` binary and its version, whether the Ix extension is enabled, the local backend (`<endpoint>/v1/health` reachable), whether the project here is mapped (`ix status`), and the **graph target** of the project here and of each project with a policy: `local only` today (see the threat model's "Graph targets"). Without Ix nothing here is a failure. `ix` runs by absolute path with an allowlisted environment and the local endpoint pinned (Ix's default, or a loopback `ixEndpoint` in config.json; never `IX_ENDPOINT`/`IX_PAT` from the environment);
326
330
  - the CLI's version against the one the Claude mod bundles (found from `P2P_MOD_ROOT`, which the mod sets, or the plugin folder around a bundled `p2p.mjs`).
327
331
 
328
332
  With `<user>` (an address, petname, name or userId), it checks whether you can see them: friendship or the circles you both stand in; their identity document, fetched now and fresh; the relays they list and whether you share one you reach; whether you hold a capability for their relays and they hold one from you for yours (as far as this device's records tell); when anything last arrived from them; whether they're blocked, suspended (a contested key move) or held; and whether the sessions they shared include you, and are live. It then lists each of their devices with its protocol minor (and exact client version only when the device publishes one in `dinfo`) and the caps it advertises (from its identity document entry, else its latest status), and the features unavailable between you, in words, never as a failure (docs/compatibility.md); `--json` adds `devices` and `unavailable`.
package/dist/app.d.ts CHANGED
@@ -307,6 +307,11 @@ export declare class App {
307
307
  extraCaps?: readonly string[];
308
308
  hint?: readonly string[];
309
309
  onlyDevices?: readonly string[];
310
+ /** Called with each copy's device and seq once they are known, before any copy goes out. */
311
+ beforeSend?: (copies: {
312
+ did: string;
313
+ seq: number;
314
+ }[]) => Promise<void>;
310
315
  }): Promise<Delivery>;
311
316
  /** Delivers to our other devices, when there are any (sync, §4.3). */
312
317
  syncOwn(body: Record<string, unknown>): Promise<Delivery | undefined>;
package/dist/app.js CHANGED
@@ -948,7 +948,9 @@ export class App {
948
948
  const view = to === this.userId ? await this.ownView() : await this.viewFor(to, { refresh: opts.refresh, hint: opts.hint });
949
949
  if (!view)
950
950
  throw new CliError("unknown_user", `no identity document for ${to}: can't find their devices or relays`);
951
- const devices = view.devices.filter((d) => !(to === this.userId && d === this.did) && (!opts.onlyDevices || opts.onlyDevices.includes(d)));
951
+ // This device only when named in onlyDevices (a message to another session of ours here, or a
952
+ // receipt for one): sealed to itself and sent through a relay like any other copy.
953
+ const devices = view.devices.filter((d) => (to !== this.userId || d !== this.did || opts.onlyDevices?.includes(d) === true) && (!opts.onlyDevices || opts.onlyDevices.includes(d)));
952
954
  const relays = orderRelays(view.head.relays, view.relays).slice(0, 3);
953
955
  const caps = await this.capsFor(to, kind, opts.extraCaps);
954
956
  const resolveCert = storeCertResolver(this.store);
@@ -971,6 +973,8 @@ export class App {
971
973
  }
972
974
  }
973
975
  const seqs = ready.length > 0 ? await this.state.nextSeqs(session.own, session.sid, ready.length) : [];
976
+ if (opts.beforeSend && ready.length > 0)
977
+ await opts.beforeSend(ready.map((r, i) => ({ did: r.d, seq: seqs[i] })));
974
978
  const targets = relays.map((r) => ({ relay: r, cap: caps.get(r) })).filter((t) => t.cap !== undefined || kind === "contact");
975
979
  const outgoing = [];
976
980
  for (const [i, { d, kpk }] of ready.entries()) {
package/dist/cli.d.ts CHANGED
@@ -25,16 +25,28 @@ export declare const realOps: {
25
25
  sessionDirs(env: Record<string, string | undefined>): {
26
26
  dirs: string[];
27
27
  over: boolean;
28
+ why: projects.OverWhy[];
28
29
  };
30
+ overWhys(v: unknown): projects.OverWhy[];
31
+ pseudoPath(p: string): boolean;
32
+ braceChoice(c: string): boolean;
33
+ dirProjectId(root: string): string;
29
34
  normalizeRemote(url: string): string | undefined;
30
- projectOf(dir: string): projects.ProjectRef;
35
+ projectOf(dir: string, doc?: projects.ProjectsDoc): projects.ProjectRef;
31
36
  projectsDoc(app: App): Promise<projects.ProjectsDoc>;
32
37
  shareOf(doc: projects.ProjectsDoc, id: string): projects.ProjectShare;
33
38
  projectView(app: App, ref: Pick<projects.ProjectRef, "id" | "name" | "kind" | "root" | "remote" | "repoPrivate">, doc?: projects.ProjectsDoc): Promise<projects.ProjectView>;
39
+ broadRoot(root: string, env?: Record<string, string | undefined>): string | undefined;
40
+ nestedBoundaries(root: string): {
41
+ repos: string[];
42
+ private: string[];
43
+ capped: boolean;
44
+ };
34
45
  shareProject(app: App, dir: string, targets: {
35
46
  circles?: string[];
36
47
  people?: string[];
37
48
  add?: boolean;
49
+ subfolders?: boolean;
38
50
  }): Promise<{
39
51
  project: projects.ProjectView;
40
52
  warnings: string[];
@@ -44,7 +56,7 @@ export declare const realOps: {
44
56
  showProject(app: App, dir: string): Promise<projects.ProjectView>;
45
57
  bindSession(app: App, sid: string, dirs: readonly string[], o?: {
46
58
  person?: boolean;
47
- over?: boolean;
59
+ over?: boolean | readonly projects.OverWhy[];
48
60
  constraint?: projects.ProjectShare;
49
61
  inbound?: boolean;
50
62
  }): Promise<projects.SessionBinding | undefined>;
@@ -56,11 +68,15 @@ export declare const realOps: {
56
68
  takePersonToken(env: Record<string, string | undefined>, home: string | undefined): boolean;
57
69
  assertPersonForWidening(app: Pick<App, "env"> & {
58
70
  front?: boolean;
59
- }, what: string, confirm: projects.ConfirmTty): Promise<void>;
71
+ }, what: string, confirm: projects.ConfirmTty, why?: string): Promise<void>;
72
+ assertSpeaksFor(app: App, sid: string): Promise<void>;
60
73
  personHere(app: Pick<App, "env"> & {
61
74
  front?: boolean;
62
75
  }): boolean;
63
76
  sessionBinding(app: App, sid: string): Promise<projects.SessionBinding | undefined>;
77
+ privateReasons(doc: projects.ProjectsDoc, b: projects.SessionBinding): projects.PrivateReason[];
78
+ privateRemedy(causes: readonly projects.PrivateCause[], names: string[]): string;
79
+ stickyPrivate(c: projects.Ceiling): boolean;
64
80
  sessionCeiling(app: App, sid: string, binding?: projects.SessionBinding | null): Promise<projects.Ceiling>;
65
81
  ceilingAudience(app: App, c: projects.Ceiling): Promise<Set<string> | undefined>;
66
82
  shareHint(names: string[]): string;
@@ -70,7 +86,27 @@ export declare const realOps: {
70
86
  }): Promise<void>;
71
87
  friendIds(app: App): Promise<Set<string>>;
72
88
  sessionProjectView(app: App, sid: string): Promise<projects.SessionProjectView>;
89
+ showSession(app: App, sid: string): Promise<projects.SessionShow>;
73
90
  defaultCircleNotice(app: App, sid: string): Promise<string | undefined>;
91
+ isLoopbackEndpoint(url: unknown): url is string;
92
+ normalizeLoopbackEndpoint(url: unknown): string | undefined;
93
+ localGraphEndpoint(_env: Record<string, string | undefined>, file?: {
94
+ ixEndpoint?: unknown;
95
+ }): string;
96
+ graphTargetOf(inputs: readonly projects.GraphShareInput[], o: {
97
+ local: string;
98
+ sharedGraphs?: ReadonlyMap<string, string>;
99
+ }): projects.GraphTarget;
100
+ normalizeSharedEndpoint(url: unknown): string | undefined;
101
+ graphTarget(app: App, o?: {
102
+ sid?: string;
103
+ dirs?: readonly string[];
104
+ paths?: readonly string[];
105
+ over?: boolean;
106
+ }, sharedGraphs?: ReadonlyMap<string, string>): Promise<projects.GraphTarget>;
107
+ projectGraphTarget(app: Pick<App, "env" | "file">, ref: Pick<projects.ProjectRef, "id" | "name" | "repoPrivate">, doc: projects.ProjectsDoc): projects.GraphTarget;
108
+ describeGraphTarget(t: projects.GraphTarget): string;
109
+ graphPinnedEnv(env: Record<string, string | undefined>, target: projects.GraphTarget, base?: Record<string, string | undefined>): Record<string, string | undefined>;
74
110
  PERSON_SESSION: "tui";
75
111
  PRIVATE_MARKER: ".p2p-private";
76
112
  MAX_SESSION_DIRS: 512;
@@ -78,9 +114,18 @@ export declare const realOps: {
78
114
  SESSION_BINDING_TTL_MS: number;
79
115
  MAX_PROJECT_SHARES: 32;
80
116
  MAX_SESSION_CONSTRAINTS: 16;
117
+ MAX_UNDER: 64;
118
+ NESTED_SCAN_DEPTH: 4;
119
+ NESTED_SCAN_ENTRIES: 2000;
81
120
  AGENT_ENV_VARS: readonly string[];
82
121
  isAgentProcess: typeof projects.isAgentProcess;
83
122
  PROJECT_NOTICE_PREFIX: "project boundaries:";
123
+ GRAPH_LOCAL_ONLY: "local only";
124
+ DEFAULT_IX_ENDPOINT: "http://localhost:8090";
125
+ SHARED_GRAPHS: ReadonlyMap<string, string>;
126
+ MAX_GRAPH_PATHS: 64;
127
+ IX_CLOUD_ENV: readonly string[];
128
+ IX_KEEP: readonly string[];
84
129
  readRotationState(home: string): Promise<rotation.RotationState | undefined>;
85
130
  adoptHome(app: App, src: string, tag: string): Promise<string>;
86
131
  raiseRotationAlert(app: App, r: import("@peer2peer/core/v3").VerifiedRotation, by?: string): Promise<boolean>;
@@ -234,6 +279,7 @@ export declare const realOps: {
234
279
  user: string;
235
280
  pick?: string;
236
281
  };
282
+ tuiTaintNote(app: App, toUserId: string, now?: number): Promise<string | undefined>;
237
283
  sendSharing(app: App, o: sessions.SendOpts): Promise<{
238
284
  result: sessions.SendResult;
239
285
  shared?: {
@@ -246,7 +292,7 @@ export declare const realOps: {
246
292
  onSessionEnvelope(app: App, env: string, r: import("@peer2peer/core/v3").AcceptedMessageV3): Promise<import("./inbound.js").NewEvent[]>;
247
293
  bindFromEnv(app: App, sid: string, extra?: readonly string[], o?: {
248
294
  person?: boolean;
249
- over?: boolean;
295
+ over?: projects.OverWhy[];
250
296
  }): Promise<void>;
251
297
  sessionsWithin(app: App, b: import("@peer2peer/core/v3").ProjectBound, now?: number): Promise<string[]>;
252
298
  bindBound(app: App, sid: string, bound: unknown): Promise<projects.SessionProjectView>;
@@ -265,6 +311,9 @@ export declare const realOps: {
265
311
  OPEN_CIRCLE_NO_FOLLOW: "kept private: your default circle is open (anyone its owner admits can see what's shared there), so a session already running doesn't move into it by itself; share it with `p2p session roster <sid> --circle <cid>` (or /peers circle <cid>)";
266
312
  STATUS_FANOUT: 8;
267
313
  OFFLINE_TARGET_MS: number;
314
+ LOCAL_SEND_TTL_MS: number;
315
+ LOCAL_SENDS_MAX: 4096;
316
+ TUI_TAINT_MS: number;
268
317
  MAX_EXT_PLAINTEXT_BYTES: number;
269
318
  resolveCircle(app: App, input: string): Promise<import("@peer2peer/core/v3").LoadedCircle>;
270
319
  encodeCircleLink(head: string, hint: circles.CircleHint | undefined, web?: boolean): string;
package/dist/cli.js CHANGED
@@ -12,7 +12,7 @@ import { resolve } from "node:path";
12
12
  import * as codex from "@peer2peer/codex-bridge";
13
13
  import { Command, CommanderError, Option } from "commander";
14
14
  import { App } from "./app.js";
15
- import { readFileConfig, resolveHome, updateFileConfigField } from "./config.js";
15
+ import { ownAgentsDeliver, ownAgentsDeliverFrom, ownDevicesDeliver, readFileConfig, resolveHome, updateFileConfigField } from "./config.js";
16
16
  import { receiptsSetting, sendReceipt } from "./receipts.js";
17
17
  import * as trustOps from "./trust.js";
18
18
  import { CliError, toErrorJson } from "./errors.js";
@@ -27,6 +27,9 @@ import { receiving } from "./inbound.js";
27
27
  import * as rotation from "./rotation.js";
28
28
  import * as sessions from "./sessions.js";
29
29
  import * as projects from "./projects.js";
30
+ import { isDid } from "@peer2peer/core/v3";
31
+ import * as ixLocal from "./ix-local.js";
32
+ import * as history from "./history.js";
30
33
  import { confirmOnTty } from "./tty-confirm.js";
31
34
  import * as social from "./social.js";
32
35
  import { watch } from "./watch.js";
@@ -185,6 +188,12 @@ export function buildProgram(deps) {
185
188
  deps.io.out(pretty.safePretty(out.pretty(deps.io.pretty)));
186
189
  else if (out.human)
187
190
  io.out(safeTerminal(out.human));
191
+ // Ix on by default for new installs; an existing one hears it once, at a terminal, from the person (ix-local.ts).
192
+ if (!json && !opts.readOnly && app.keys && deps.io.prompt && projects.personHere(app) && cmd.name() !== "setup") {
193
+ const n = await ixLocal.ixNotice(app).catch(() => undefined);
194
+ if (n)
195
+ io.err(`p2p: ${n}`);
196
+ }
188
197
  }
189
198
  catch (e) {
190
199
  const j = toErrorJson(e);
@@ -312,6 +321,12 @@ export function buildProgram(deps) {
312
321
  lines.push(`\nWrite these 24 words down and keep them offline. Anyone with them is you:\n\n${r.backup.phrase}\n`);
313
322
  if (r.created && !r.backup)
314
323
  io.err("warning: no backup yet: if you lose this device, the identity is gone. Run `p2p backup show`.");
324
+ if (r.ix?.enabledNow)
325
+ lines.push(" ix Ix found: the Ix extension is on (`p2p extensions disable ix` turns it off). Ix calls stay on this machine (graph: local only)");
326
+ else if (r.ix?.enabled)
327
+ lines.push(" ix the Ix extension is on (graph: local only)");
328
+ else if (r.ix?.hint)
329
+ lines.push(` ix ${r.ix.hint}`);
315
330
  lines.push("", "Invite someone: p2p invite <their name> Join with a code: p2p join <code>");
316
331
  return { json: r, human: lines.join("\n") };
317
332
  },
@@ -1098,11 +1113,11 @@ export function buildProgram(deps) {
1098
1113
  .command("send [text...]")
1099
1114
  .description("Send a message to a peer session (text from args or stdin)")
1100
1115
  .option("--from-session <sid>", "Your session id (on a terminal: default tui, as `p2p tui` sends)")
1101
- .option("--to <address>", "name@fingerprint, userId or petname, optionally \"[ref]\" or /sid (on a terminal: picked from a list)")
1116
+ .option("--to <address>", "name@fingerprint, userId or petname, optionally \"[ref]\" or /sid; another session of yours on this device only by \"[ref]\" or /sid, never the sending session itself (on a terminal: picked from a list)")
1102
1117
  .option("--notify-when-idle", "Tell this session when the target next goes idle")
1103
1118
  .option("--stdin", "Read the text from stdin (also: a single `-` as the text)")
1104
1119
  .option("--project-dir <dir>", "Another folder the session works in (repeatable): binds it to that project too, which only ever narrows who it may reach", collect)
1105
- .option("--project-dirs-over", "The front end dropped folders past its cap: the session is private")
1120
+ .option("--project-dirs-over [why]", "The front end dropped folders past its cap or couldn't resolve a path: the session is private (why: unresolved, folders or front, comma-separated; use the = form)")
1106
1121
  .option("--json", "JSON output")
1107
1122
  .action(async (text, o, cmd) => {
1108
1123
  // Without a picker these stay required, with commander's own error (as before they were requiredOption).
@@ -1174,7 +1189,7 @@ export function buildProgram(deps) {
1174
1189
  shared = `shared session tui with ${s.shared.address}\n`;
1175
1190
  }
1176
1191
  else
1177
- r = await ops.sendMessage(app, { fromSession: o.fromSession, to: o.to, text: body, notifyWhenIdle: o.notifyWhenIdle, ...(o.projectDir ? { projectDirs: o.projectDir } : {}), ...(o.projectDirsOver ? { projectDirsOver: true } : {}), ...(person ? { person: true } : {}) });
1192
+ r = await ops.sendMessage(app, { fromSession: o.fromSession, to: o.to, text: body, notifyWhenIdle: o.notifyWhenIdle, ...(o.projectDir ? { projectDirs: o.projectDir } : {}), ...(o.projectDirsOver !== undefined && o.projectDirsOver !== false ? { projectDirsOver: o.projectDirsOver === true || o.projectDirsOver === "" ? true : [o.projectDirsOver] } : {}), ...(person ? { person: true } : {}) });
1178
1193
  const tail = r.notifyWhenIdle ? `; will notify when ${r.to.address} [${r.to.ref}] is idle` : "";
1179
1194
  const where = r.to.own === r.to.userId ? `${r.to.address} [${r.to.ref}]` : `${r.to.address} (in your session ${r.to.sid})`;
1180
1195
  const ago = (ms) => {
@@ -1185,7 +1200,8 @@ export function buildProgram(deps) {
1185
1200
  // The person's own sends cross no project boundary, but say which one this folder has (projects.ts).
1186
1201
  const here = person ? await ops.showProject(app, projects.sessionWorkdir(app.env)).catch(() => undefined) : undefined;
1187
1202
  const boundary = here ? `\nproject ${here.name} here is ${here.policy === "private" ? "private (agent sessions in it reach only your own devices)" : "shared"}; this send was yours, from your terminal` : "";
1188
- const from = fromTui ? `\nsent from session tui; replies show in \`p2p tui\`${boundary}` : "";
1203
+ const taint = fromTui ? await ops.tuiTaintNote(app, r.to.userId).catch(() => undefined) : undefined;
1204
+ const from = fromTui ? `\nsent from session tui; replies show in \`p2p tui\`${boundary}${taint ? `\nnote: ${taint}` : ""}` : "";
1189
1205
  if (r.queued && r.state === "outbox") {
1190
1206
  return { json: r, human: `${shared}Queued for ${where}: this device can't reach a relay right now; it goes out when one is back (${until(r.expiresAt)})${tail}.${from}` };
1191
1207
  }
@@ -1201,9 +1217,58 @@ export function buildProgram(deps) {
1201
1217
  .requiredOption("--outcome <outcome>", "shown | held | declined | expired | ended")
1202
1218
  .option("--json", "JSON output")
1203
1219
  .action(run(async (app, event, o) => {
1204
- const r = await sendReceipt(app, { eventId: event, fromSession: sessions.checkSid(o.fromSession, "--from-session"), outcome: o.outcome });
1220
+ const sid = sessions.checkSid(o.fromSession, "--from-session");
1221
+ // Only the session's front end (or, outside an agent, a caller for an unregistered session) reports for it.
1222
+ await projects.assertSpeaksFor(app, sid);
1223
+ const r = await sendReceipt(app, { eventId: event, fromSession: sid, outcome: o.outcome });
1205
1224
  return { json: r, human: r.sent ? `Receipt sent: ${r.outcome}.` : `No receipt sent (${r.reason}).` };
1206
1225
  }));
1226
+ program
1227
+ .command("own-agents [state] [did]")
1228
+ .description("Whether messages from your own agent sessions skip the hold in a session that approves its own tool calls: `hold` (the default), `deliver` (you only; `--devices <did…|all-other>` for only your other devices' sessions), or `check <did>` (a front end, at delivery)")
1229
+ .option("--devices <devices...>", "With deliver: only messages from these other devices of yours (their device ids, or all-other); this device's agent sessions stay held")
1230
+ .option("--json", "JSON output")
1231
+ .action(run(async (app, state, did, o) => {
1232
+ if (state !== undefined && state !== "hold" && state !== "deliver" && state !== "check")
1233
+ throw new CliError("usage", "p2p own-agents [hold|deliver [--devices <did…|all-other>]|check <did>]");
1234
+ if (state === "check") {
1235
+ if (!did || !isDid(did))
1236
+ throw new CliError("usage", "p2p own-agents check <did>: a v3 device id");
1237
+ return { json: { did, deliver: ownAgentsDeliverFrom(app.home, did, app.did) }, human: ownAgentsDeliverFrom(app.home, did, app.did) ? "deliver" : "hold" };
1238
+ }
1239
+ if (did !== undefined)
1240
+ throw new CliError("usage", "p2p own-agents [hold|deliver [--devices <did…|all-other>]]");
1241
+ const devices = o.devices?.flatMap((d) => d.split(",")).map((d) => d.trim()).filter(Boolean);
1242
+ if (devices !== undefined && state !== "deliver")
1243
+ throw new CliError("usage", "--devices goes with deliver");
1244
+ if (devices !== undefined && !(devices.length === 1 && devices[0] === "all-other") && !devices.every((d) => isDid(d) && d !== app.did)) {
1245
+ throw new CliError("usage", "--devices takes your other devices' ids (p2p devices) or all-other, never this device");
1246
+ }
1247
+ // Turning the hold off widens what drives a session: the person only, never an agent. Turning it back on never asks.
1248
+ if (state === "deliver")
1249
+ await projects.assertPersonForWidening(app, devices ? "own-agents deliver --devices" : "own-agents deliver", app.confirmTty);
1250
+ if (state === "hold") {
1251
+ await updateFileConfigField(app, "ownAgentsDeliver", () => ({ next: false, result: undefined }));
1252
+ await updateFileConfigField(app, "ownDevicesDeliver", () => ({ next: [], result: undefined }));
1253
+ }
1254
+ else if (state === "deliver" && devices) {
1255
+ await updateFileConfigField(app, "ownDevicesDeliver", () => ({ next: devices.length === 1 && devices[0] === "all-other" ? "all-other" : devices, result: undefined }));
1256
+ }
1257
+ else if (state === "deliver") {
1258
+ await updateFileConfigField(app, "ownAgentsDeliver", () => ({ next: true, result: undefined }));
1259
+ }
1260
+ const on = ownAgentsDeliver(app.home);
1261
+ const list = ownDevicesDeliver(app.home);
1262
+ const some = list === "all-other" ? "all your other devices" : list.length > 0 ? `your devices ${list.join(", ")}` : undefined;
1263
+ return {
1264
+ json: { ownAgents: on ? "deliver" : "hold", devices: list },
1265
+ human: on
1266
+ ? "Messages from your own agent sessions reach a session that approves its own tool calls without the hold."
1267
+ : `Messages from your own agent sessions wait for Deliver in a session that approves its own tool calls (your own terminal's here are delivered)${some ? `, except those from ${some}` : ""}.`,
1268
+ };
1269
+ },
1270
+ // `check` and `--devices` need this device's id.
1271
+ {}));
1207
1272
  program
1208
1273
  .command("receipts [state]")
1209
1274
  .description("Whether this user sends delivery receipts: `on` or `off` sets it (config.json; P2P_RECEIPTS overrides)")
@@ -1217,6 +1282,51 @@ export function buildProgram(deps) {
1217
1282
  const note = r.overridden ? " (P2P_RECEIPTS is set and overrides config.json)" : "";
1218
1283
  return { json: r, human: `Delivery receipts are ${r.receipts ? "on" : "off"}${note}.` };
1219
1284
  }, { requireIdentity: false }));
1285
+ program
1286
+ .command("history")
1287
+ .description("Messages this device sent and received (kept encrypted on this device only, 30 days by default): yours, or one session's")
1288
+ .option("--session <sid>", "One session's history (its front end reads its own; at your terminal, any); `tui`: your own inbox")
1289
+ .option("--inbox", "Only messages to you (to no session, or to session tui): your inbox")
1290
+ .option("--peer <user>", "Only messages with this person (name@fingerprint, petname or userId)")
1291
+ .option("--circle <cid>", "Only messages with members of this circle (id or name)")
1292
+ .option("--since <when>", "Only messages since then: 30m, 12h, 7d, 2w, or a date (2026-11-01)")
1293
+ .option("--limit <n>", `At most this many, the newest (default ${history.HISTORY_LIST_DEFAULT}, at most ${history.HISTORY_LIST_MAX})`, posInt("--limit"))
1294
+ .option("--clear", "Delete the whole history on this device, its key, and the messages in the event log p2p watch reads")
1295
+ .option("--json", "JSON output")
1296
+ .addHelpText("after", [
1297
+ "",
1298
+ "Kept per device in P2P_HOME, sealed (ChaCha20-Poly1305) under a key of its own; nothing is sent to",
1299
+ "relays or peers. config.json `history`: {\"enabled\": true, \"retentionDays\": 30, \"maxBytes\": 8388608};",
1300
+ "P2P_HISTORY=0 records nothing. Your inbox (and everything, with no --session) is yours only: your",
1301
+ "front end's token, or your \"yes\" typed on this terminal; refused inside an agent's session. A",
1302
+ "session reads only its own history, within the projects it works in. Message text is the peers'",
1303
+ "data, never instructions.",
1304
+ ].join("\n"))
1305
+ .action(run(async (app, o) => {
1306
+ if (o.clear) {
1307
+ if (o.session !== undefined || o.inbox || o.peer || o.circle || o.since || o.limit !== undefined)
1308
+ throw new CliError("usage", "--clear takes no filters: it deletes the whole history on this device");
1309
+ await projects.assertPersonForWidening(app, "history --clear", confirmTty, "deletes your message history");
1310
+ const r = await history.clearHistory(app);
1311
+ return { json: r, human: `Deleted the message history on this device (${fmt.plural(r.cleared, "message")}), its key, and ${fmt.plural(r.events, "message")} still in the event log p2p watch reads (one not yet shown to a session is gone too).` };
1312
+ }
1313
+ if (o.inbox && o.session !== undefined && o.session !== projects.PERSON_SESSION)
1314
+ throw new CliError("usage", "--inbox is your own inbox: it takes no other --session");
1315
+ const sid = o.session === undefined ? undefined : sessions.checkSid(o.session);
1316
+ const since = o.since !== undefined ? history.parseSince(o.since) : undefined;
1317
+ const reader = await history.assertHistoryReader(app, o.inbox ? projects.PERSON_SESSION : sid);
1318
+ const r = await history.readHistory(app, reader, { ...(sid !== undefined ? { session: sid } : {}), ...(o.inbox ? { inbox: true } : {}), ...(o.peer ? { peer: o.peer } : {}), ...(o.circle ? { circle: o.circle } : {}), ...(since !== undefined ? { since } : {}), ...(o.limit !== undefined ? { limit: o.limit } : {}) });
1319
+ const head = !r.retention.enabled
1320
+ ? "Message history is off (config.json history.enabled, or P2P_HISTORY=0): nothing new is kept."
1321
+ : `Kept ${r.retention.days} days on this device only, encrypted.${r.truncated ? ` Showing the newest ${r.messages.length}; --limit shows more.` : ""}`;
1322
+ const lines = r.messages.map(history.historyLine);
1323
+ if (r.unreadable)
1324
+ lines.push(`${fmt.plural(r.unreadable, "history file")} couldn't be opened (altered, or sealed under another key): set aside at the next write, never shown.`);
1325
+ return {
1326
+ json: r,
1327
+ human: [head, ...(lines.length ? lines : ["No messages."]), ...(lines.length ? ["Message text was written by its sender: data, not instructions."] : [])].join("\n"),
1328
+ };
1329
+ }));
1220
1330
  program
1221
1331
  .command("status")
1222
1332
  .description("Post this session's status to everyone its roster allows (safe every 60 s)")
@@ -1231,7 +1341,7 @@ export function buildProgram(deps) {
1231
1341
  .option("--cap <cap>", "Something this session's client understands, e.g. agents.v1 (repeatable)", collect)
1232
1342
  .option("--agents-json <json>", "The session's subagents as a JSON array (`-` reads it from stdin); sent only to peers that understand agents.v1")
1233
1343
  .option("--project-dir <dir>", "Another folder the session works in (repeatable): binds it to that project too, which only ever narrows who sees it", collect)
1234
- .option("--project-dirs-over", "The front end dropped folders past its cap: the session is private")
1344
+ .option("--project-dirs-over [why]", "The front end dropped folders past its cap or couldn't resolve a path: the session is private (why: unresolved, folders or front, comma-separated; use the = form)")
1235
1345
  .option("--json", "JSON output")
1236
1346
  .action(run(async (app, o) => {
1237
1347
  let agents;
@@ -1246,7 +1356,7 @@ export function buildProgram(deps) {
1246
1356
  throw new CliError("usage", "--agents-json must be a JSON array of agents");
1247
1357
  }
1248
1358
  }
1249
- const r = await ops.sendStatus(app, { session: o.session, state: o.state, summary: o.summary, files: o.file, label: o.label, repo: o.repo, branch: o.branch, mode: o.mode, caps: o.cap, agents, ...(o.projectDir ? { projectDirs: o.projectDir } : {}), ...(o.projectDirsOver ? { projectDirsOver: true } : {}) });
1359
+ const r = await ops.sendStatus(app, { session: o.session, state: o.state, summary: o.summary, files: o.file, label: o.label, repo: o.repo, branch: o.branch, mode: o.mode, caps: o.cap, agents, ...(o.projectDir ? { projectDirs: o.projectDir } : {}), ...(o.projectDirsOver !== undefined && o.projectDirsOver !== false ? { projectDirsOver: o.projectDirsOver === true || o.projectDirsOver === "" ? true : [o.projectDirsOver] } : {}) });
1250
1360
  for (const w of r.warnings ?? [])
1251
1361
  io.err(`p2p: ${w}`);
1252
1362
  const n = r.delivered.length;
@@ -1281,13 +1391,15 @@ export function buildProgram(deps) {
1281
1391
  `nothing in a repository can widen them (a committed ${projects.PRIVATE_MARKER} can only make it private).`,
1282
1392
  ].join("\n"));
1283
1393
  const projectView = (v) => {
1284
- const lines = [`${v.name} ${v.policy === "private" ? "private" : "shared"}${v.kind === "git" ? (v.remote ? ` (${v.remote})` : " (git, no remote)") : " (folder)"}`, ` ${v.root}`];
1394
+ const lines = [`${v.name} ${v.policy === "private" ? "private" : "shared"}${v.kind === "git" ? (v.remote ? ` (${v.remote})` : " (git, no remote)") : v.covers ? " (folder, and its subfolders)" : " (folder)"}`, ` ${v.root}`];
1285
1395
  if (v.policy === "private")
1286
1396
  lines.push(` only your own devices see its sessions${v.why === "unmapped" ? " (never shared: `p2p project share <circle>` in it)" : v.why ? ` (${v.why})` : ""}`);
1287
1397
  for (const c of v.circles)
1288
1398
  lines.push(` circle ${c.name ?? c.cid} (${c.cid})${c.open ? ", open: anyone its owner admits" : ""}${c.joined ? "" : ", not joined: ignored"}`);
1289
1399
  for (const p of v.people)
1290
1400
  lines.push(` ${p.address}`);
1401
+ if (v.graph)
1402
+ lines.push(` graph: ${projects.describeGraphTarget(v.graph)}${v.graph.kind === "local" && v.graph.why ? `: ${v.graph.why}` : ""}`);
1291
1403
  return lines.join("\n");
1292
1404
  };
1293
1405
  project
@@ -1295,6 +1407,7 @@ export function buildProgram(deps) {
1295
1407
  .description("Share the project here with circles you joined (and friends with --person); on a terminal with none named, pick them")
1296
1408
  .option("--person <user>", "A friend to share it with too (repeatable)", collect)
1297
1409
  .option("--add", "Keep what it is shared with already (default: replace it)")
1410
+ .option("--subfolders", "A folder outside git: the share covers its subfolders too (never past a repository, a .p2p-private or a folder with its own policy; refused for a home, temporary or system folder). Without it, the share is for that folder alone")
1298
1411
  .option("--dir <path>", "The project's folder (default: P2P_WORKDIR, else the current directory)")
1299
1412
  .option("--json", "JSON output")
1300
1413
  .action(run(async (app, named, o) => {
@@ -1324,7 +1437,7 @@ export function buildProgram(deps) {
1324
1437
  throw new CliError("usage", "name a circle (or --person <friend>) to share this project with");
1325
1438
  circlesIn = [def];
1326
1439
  }
1327
- const r = await ops.shareProject(app, dir, { circles: circlesIn, people, ...(o.add ? { add: true } : {}) });
1440
+ const r = await ops.shareProject(app, dir, { circles: circlesIn, people, ...(o.add ? { add: true } : {}), ...(o.subfolders ? { subfolders: true } : {}) });
1328
1441
  for (const w of r.warnings)
1329
1442
  io.err(`p2p: warning: ${w}`);
1330
1443
  return { json: { project: r.project, ...(r.warnings.length ? { warnings: r.warnings } : {}) }, human: `Shared. Sessions in ${r.project.name} are seen by:\n${projectView(r.project)}` };
@@ -1355,6 +1468,30 @@ export function buildProgram(deps) {
1355
1468
  const v = await ops.showProject(app, o.dir ?? projects.sessionWorkdir(app.env));
1356
1469
  return { json: { project: v }, human: projectView(v) };
1357
1470
  }));
1471
+ session
1472
+ .command("show <sid>")
1473
+ .description("A session's bound projects, who each is shared with, and every reason it is private (read only; yours: refused inside an agent's session)")
1474
+ .option("--json", "JSON output")
1475
+ .action(run(async (app, sid) => {
1476
+ const v = await ops.showSession(app, sessions.checkSid(sid, "sid"));
1477
+ const lines = [`session ${v.sid}: ${v.policy === "none" ? "not bound to any project" : v.policy}`];
1478
+ if (v.reasons.length)
1479
+ lines.push(" private because:", ...v.reasons.map((r) => ` - ${r.why}`));
1480
+ if (v.remedy)
1481
+ lines.push(` ${v.remedy.charAt(0).toUpperCase()}${v.remedy.slice(1)}`);
1482
+ if (v.policy === "shared")
1483
+ lines.push(` reaches: ${[...(v.circles ?? []).map((c) => `circle ${c}`), ...(v.people ?? [])].join(", ") || "nobody"}`);
1484
+ if (v.constraints)
1485
+ lines.push(` ${fmt.plural(v.constraints, "bound")} from messages your other sessions sent it`);
1486
+ for (const p of v.projects) {
1487
+ lines.push("", ...projectView(p).split("\n"));
1488
+ if (p.underOver)
1489
+ lines.push(" covering many of its subfolders");
1490
+ else if (p.under?.length)
1491
+ lines.push(` covering ${p.under.join(", ")}`);
1492
+ }
1493
+ return { json: { session: v }, human: lines.join("\n") };
1494
+ }));
1358
1495
  session
1359
1496
  .command("bound <sid>")
1360
1497
  .description("Bind a session to the bound an own-session message it took carried (front ends call it on Deliver; narrowing only)")
package/dist/config.d.ts CHANGED
@@ -15,7 +15,54 @@ export interface FileConfig {
15
15
  };
16
16
  /** Publish this device's caps and version in the identity document (`dinfo`); off until step 2 (docs/compatibility.md). P2P_DEVICE_INFO wins. */
17
17
  deviceInfo?: boolean;
18
+ /** The local Ix backend (projects.ts localGraphEndpoint): honoured only as a loopback URL. Default http://localhost:8090. */
19
+ ixEndpoint?: string;
20
+ /**
21
+ * Trust a root-owned listener on the local Ix endpoint's port (ext-ix listener.ts): Docker's port
22
+ * proxy on Linux runs as root whoever started the container, so on a machine whose Docker others
23
+ * use too it may be a teammate's backend. Off by default; only this file turns it on (hand-edited:
24
+ * no command writes it, and no environment variable overrides it).
25
+ */
26
+ ixTrustRootListener?: boolean;
27
+ /** Message history (history.ts): on by default, kept `retentionDays` (30) and at most `maxBytes` (8 MiB). P2P_HISTORY=0 turns recording off. */
28
+ history?: {
29
+ enabled?: boolean;
30
+ retentionDays?: number;
31
+ maxBytes?: number;
32
+ };
33
+ /** Graph memory (graph-memory.ts): this device's sessions' context into the local Ix graph; on by default with the Ix extension, `false` turns it off. P2P_IX_MEMORY=0 turns it off too. */
34
+ ixMemory?: boolean;
35
+ /**
36
+ * Messages from your own agent sessions skip the hold in a session that approves its own tool calls
37
+ * (`p2p own-agents deliver`, person only). Off by default: they are held like a peer's. No variable
38
+ * overrides it, so nothing an agent sets in its environment turns it on.
39
+ */
40
+ ownAgentsDeliver?: boolean;
41
+ /**
42
+ * Narrower (`p2p own-agents deliver --devices <did…|all-other>`, person only): messages from your own
43
+ * sessions on these other devices skip the hold, while this device's agent sessions stay held. Another
44
+ * device can't say whether you typed a message (that needs the wire field of RFC #48), so this trusts
45
+ * every session there.
46
+ */
47
+ ownDevicesDeliver?: string[] | "all-other";
18
48
  }
49
+ /**
50
+ * Whether `p2p watch` writes this device's sessions' context into the local Ix graph (graph-memory.ts):
51
+ * on by default (it needs the Ix extension and an Ix with the OSS `ix note`). `"ixMemory": false` in
52
+ * config.json turns it off, and so does P2P_IX_MEMORY=0 (or `false`). The environment can only turn it
53
+ * off: it never overrides the person's `false`.
54
+ */
55
+ export declare function graphMemoryEnabled(env: Env, home: string): boolean;
56
+ /** Whether your own agent sessions' messages skip the hold (FileConfig.ownAgentsDeliver). */
57
+ export declare function ownAgentsDeliver(home: string): boolean;
58
+ /** The other devices whose sessions skip the hold (FileConfig.ownDevicesDeliver): none, a list, or every other one. */
59
+ export declare function ownDevicesDeliver(home: string): string[] | "all-other";
60
+ /**
61
+ * Whether a message from one of your own agent sessions on device `did` skips the hold now (read at
62
+ * delivery time, never stamped on an event): `own-agents deliver`, or `--devices` naming that device
63
+ * (another device than this one).
64
+ */
65
+ export declare function ownAgentsDeliverFrom(home: string, did: string, thisDevice: string): boolean;
19
66
  /**
20
67
  * Whether this device puts its caps and client version in the identity document (`dinfo`).
21
68
  * Off by default in this release: pre-release clients from before protocol 3.1 refuse