# Local agent communication

`intercom` is always available with the package. There is no `load_intercom`,
child-only supervisor tool, peer overlay, topic registry, or separate extension
to install. Ordinary and delegated sessions use the same messaging tool.

Background failures appear as native notifications when a UI is active and on
stderr in print or JSON mode, including during headless shutdown. In UI sessions,
failures during shutdown or after the UI context is unavailable are recorded in
`intercom/background-errors.log` under `PI_CODING_AGENT_DIR` (normally `~/.pi/agent`).
If that directory is not writable, the fallback cannot record them. Repeated
identical failures are reported once until the affected operation recovers.

## Discovery and groups

```js
intercom({ action: "list" });
intercom({ action: "list", children: true });
intercom({ action: "list", scope: "project" });
intercom({ action: "list", to: "reviewer" });
intercom({ action: "list", device: "all" });
intercom({ action: "claim", message: "PSA-203 session visibility" });
intercom({ action: "claim", message: "" });
intercom({ action: "status" });
```

Default discovery includes every eligible connected session under the same OS
user, across cwd, Git worktrees, projects, HOME settings, and Pi agent directories.
`scope:"project"` is an optional convenience filter, not an authority boundary.
The list does not enumerate all OS processes or disconnected native sessions.
With `device`, `list` prints the main sessions of the owner's
[other devices](#main-sessions-on-other-devices) instead.

`list` and `status` print the current session and then two blocks:

1. **Main sessions.** One line per main with its name, target, cwd, model and
   state, including `git: <repo> (<branch>)` when the peer is in a Git repository
   (branch name or detached short SHA; omitted outside Git repos),
   `working_on:<note>` when the peer advertised a claim, `worker_started:<age>`
   for its current worker process, and `last_turn_error:<error>` when its latest
   assistant turn on the active branch failed. Sessions of one repository and its
   worktrees sit together: the block is sorted by project, then by name.
2. **Child sessions of the caller's group.** One line in total: how many there
   are, counted by state, and the call that prints their rows.
   `list` with `children: true` prints one line per child instead.

Use `intercom({ action: "claim", message: "..." })` to advertise a short 1-line
`workingOn` note on your broker presence record without waking any peer. Pass an
empty `message` (`""`) to clear it; disconnecting or starting a fresh session
also clears it automatically. Whitespace and control characters collapse to spaces,
and surrounding spaces are trimmed. If the result exceeds 256 UTF-16 code units,
the claim fails and the previous note stays in place.

Every child is a valid target by name or ID whether or not its row is printed.
With `to`, `list` keeps the sessions whose name or ID contains that text, ignoring
case. It filters both blocks, says how many sessions each block holds in total,
and prints every matching child row. The delivery guidance is printed once after
the blocks.

| Caller                | First block      | Second block                   |
| --------------------- | ---------------- | ------------------------------ |
| Main with children    | Every other main | Its own children, as a count   |
| Main without children | Every other main | Absent                         |
| Child                 | Its main         | The other children, as a count |

A bridge identity is a main: it is a row in the first block of every main. It
reads the mains through the bridge's own `list` route, not through this tool.

A main session and its children form a collaboration group. Main↔child and
sibling↔sibling communication works in both directions. Across groups, only
main↔main communication is allowed. A child cannot discover, message, or read
another group's main or children—even using a known exact ID. Only mains spawn;
there is one child level. These are broker-enforced coordination rules, not an OS
security sandbox against arbitrary code running as the same user.

Registration pins `rootSessionId` and optional `parentSessionId`. Both are native
Pi session IDs, not cwd or display names. A main uses its own ID as root, without
a parent. A child uses its main's ID for both. An offline parent does not erase
sibling membership. Presence updates cannot change the registered group. Legacy
or remote peers without lineage are standalone mains.

Pi launches a child with both `PI_INTERCOM_ROOT_SESSION_ID` and
`PI_INTERCOM_PARENT_SESSION_ID` set to its main's exact native ID. With neither
set, the session is a main. Any other combination (one missing, empty, padded
with whitespace, or different values) stops the package from loading, so that
session gets neither delegation nor Intercom. Values are never trimmed into a
different identity.

### Identity and targeting

Use a target returned by `list`. Native peer IDs are `pi-` plus the first 32
hexadecimal SHA-256 characters of the native session ID. Reconnecting normally
reuses that identity. A simultaneous live collision gets a different ID; it never
merges with or evicts the first connection.

Names are mutable and nonunique. Exact IDs take precedence; otherwise names and
sufficiently long ID prefixes must resolve unambiguously. Displayed targets grow
when needed to distinguish collisions. A project-filtered peer can still be
addressed by its known target; a topology-forbidden peer cannot. A hidden peer
does not leak through duplicate-name ambiguity or disconnect notifications.

### Conditional native context targeting

Ordinary `intercom` targeting is unchanged. Integrations can negotiate
guarded-delivery version 1 with the native broker client. Discovery then exposes
`rootSessionId`, `incarnation`, `guardedDelivery:1` and the optional opaque
`applicationGuard`. The lifecycle mints the incarnation on native startup, reload
or session replacement, not on transport reconnect. Peer IDs still belong to
the broker. Two current mains for one root make guarded sends ambiguous.

A guarded send requires an exact peer ID, a caller-recorded original message ID,
and
`guard:{rootSessionId,peerId,incarnation,applicationGuard}`. The broker checks
the complete binding before routing; the native recipient checks again before
initial admission, before its first checkpoint or immediate placement. Children
are not guarded command targets. Missing capability, stale context, changed
consent or an ambiguous root fails closed for new admission, never selecting a
similarly named main. A broker acceptance still does not prove
recipient admission. Lost responses remain uncertain; no automatic replay is added.
The supported non-model package client below uses these same native protocols.

Withdrawing the guard stops new admission; it does not cancel already-admitted
input. The original native session remains the recovery owner after a checkpoint,
including across reload or process recovery. A fork or new root cannot adopt its
pending inputs. Native queueing or placement is not proof of model consumption.

An original-main companion uses the existing process-local `pi.events` bus:

- Emit `pi-intercom:context-query` with `{version:1,respond(snapshot)}` for late
  attachment. Unknown versions return `{error:"unsupported_version"}`.
- Observe `pi-intercom:context-state` for subsequent lifecycle, connection and
  application-guard changes. Snapshots contain `version:1`, exact root, optional
  parent, actual `peerId`, `incarnation`, `connected`, negotiated
  `guardedDelivery:1|null`, and optional `applicationGuard`. Unavailable identities
  are null. Query after subscribing; state events are not replayed.
- Emit `pi-intercom:application-guard` with
  `{version:1,target:{rootSessionId,peerId,incarnation},revision,respond(result)}`.
  The companion owns this opaque nonempty string revision; null withdraws it.
  A stale target returns `{error:"context_changed"}`. It is cleared on context
  replacement and retained on transport reconnect. This handshake is not consent
  itself, does not persist a policy, and grants no human-origin authority.

Callbacks are process-local, synchronous observations. They are not socket frames
or a generic registry. Old owners have no handshake; treat them as unsupported.
Old brokers do not acknowledge guarded delivery, so updated clients refuse before
sending. Old ordinary clients and recipients continue using ordinary messages;
they are not advertised as conditional targets.

Guarded nonblocking messages may include
`replyHint:{tool,commandId,commandFingerprint?}`. Tool names are validated identifiers and command IDs
are immutable UUIDs supplied by the sender. An optional lowercase SHA-256
`commandFingerprint` is opaque to Intercom; its caller owns the fingerprint
contract. The native message renders a generic
publication hint. No product-specific tool is
hard-coded, and a hint does not prove a reply exists.

## Main sessions on other devices

```js
intercom({ action: "list", device: "all" });
intercom({ action: "list", device: "laptop" });
intercom({ action: "list", device: "laptop", to: "review" });
intercom({ action: "send", to: "api-fix@laptop", message: "The schema change is merged." });
```

A main session can list the main sessions on the owner's other devices and send a
message to one of them. For a list, `device` is
one configured device name, or `all` for every configured device. The answer has
one block per device and no session of this device:

```text
**Main sessions on laptop (2):**
• api-fix@laptop (pi-7e8f9@laptop) — Native session cwd: /work/api (model-b) [idle, state:idle, last_intercom_activity:none, last_seen:2h ago, worker_started:2h ago]
• web-build@laptop (pi-0a1b2@laptop) — Native session cwd: /work/web (model-a) [tool:bash, state:busy, last_intercom_activity:none, last_seen:5s ago, worker_started:20m ago]

**Main sessions on desk (0):** no Pi session is connected there.

**phone:** unreachable (connect to host phone port 22: Operation timed out)

**old-box:** not listed: its pi-subagents has no cross-device command; update pi-subagents there

**Other devices:** send reaches a main there by its target above, which ends in @device. last reads only the sessions of this device.
```

- A row has the fields of a local main row. Its name and its ID end in `@device`.
  Ages are measured on the clock of the listed device.
- Pi main sessions and authenticated bridge mailboxes are listed. Child
  sessions and transient command peers are left out.
- `to` keeps the sessions whose name or ID contains that text, as in a local
  list. A text copied from a row can keep its `@device` ending: it matches that
  row on that device. `scope` and `children` cannot be combined with `device`.
- The name and the ID of a row are targets for `send`. `last` reads
  only the sessions of this device.
- Only a main session can contact another device. A child can qualify a local
  target with this device's configured alias, subject to the usual group rules.
- Without `device` and without a `name@device` target, the tool contacts no
  other device.

| Block text                                                 | Meaning                                                                                              |
| ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `(0): no Pi session is connected there`                    | The device answered. No broker runs there, or no Pi main is connected to it.                         |
| `unreachable (…)`                                          | `ssh` could not connect or log in. The text in parentheses is the last line that `ssh` printed.      |
| `not listed: its pi-subagents has no cross-device command` | The device answered. This package is not installed there, or its version is older than this command. |
| `not listed: node is not on the PATH of its SSH commands`  | The device answered. Its shell did not find `node` for a command that `ssh` runs without a terminal. |
| `not listed: …`                                            | Any other failure, with the last line of its error text.                                             |

### Send to a main on another device

`to` is a name or an ID from a device list, with its `@device` ending. The text
after the last `@` selects a configured device, ignoring letter case. This
device's configured alias resolves locally without SSH.
On either device, Intercom resolves the part before `@` by name, ID, or ID
prefix of at least 8 characters and uses the usual visibility rules. A
recognized device suffix takes precedence over a local name containing `@`.

```text
Message sent to api-fix@laptop (wakes idle recipients and steers active recipients at the next tool boundary)
```

The recipient reads the sender as `<session name>@<sender's device>`, with the
sender's working directory. That name is the target for a message back:

```text
**📨 From web-build@desk** (Native session cwd: /work/web)

The schema change is merged.
```

- **Send.** The answer is the receipt of the other device's broker: accepted,
  delivered or queued (for a parked child), as for a local send. Attachments
  work as for a local target, and delivery always steers a busy recipient or
  wakes an idle one.
- **What stays on the device.** Human origin, application guards and reply
  hints never cross a device.

A failure says whether the message left this device:

| Text                                                                                            | Meaning                                                                                                                           |
| ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `Not sent to <device>: unreachable (…)`                                                         | `ssh` could not connect or log in. Nothing was sent.                                                                              |
| `Not sent to <device>: its pi-subagents has no cross-device command; update pi-subagents there` | The device answered. This package is not installed there, or it has no cross-device command. Nothing was sent.                    |
| `Not sent to <device>: its pi-subagents is older than this command; update pi-subagents there`  | The device answered. Its package lists sessions and does not send yet. Nothing was sent.                                          |
| `Not sent to <device>: no Pi session is connected there`                                        | The device answered. No broker runs there. Nothing was sent.                                                                      |
| `Message to "<target>" was not delivered: …`                                                    | The other device has no connected session for that target, or refused it. Nothing was sent.                                       |
| `Target "<target>" is too short` or `matches multiple sessions`                                 | The other device found more than one session. The text lists the targets to use, each with its `@device` ending.                  |
| `Delivery unknown: <device> gave no answer after the request was handed over (…)`               | The connection was lost after the device had the request. The message may have arrived. Check the recipient before sending again. |
| `Cancelled`                                                                                     | The tool call was cancelled. The details say whether the message was accepted, was not sent, or is unknown.                       |

"Not sent" is certain: the device answers with one line before the request is
written to it, and a device that did not answer received nothing.
Failed `send` tool calls that include structured recovery
actions append a second line with concrete guidance matching
`details.nextActions`.

### Device names

Device names come from `intercom/config.json` under `PI_CODING_AGENT_DIR`
(normally `~/.pi/agent/intercom/config.json`):

```json
{
  "device": "desk",
  "otherDevices": ["laptop", "phone"]
}
```

| Key            | Value                                                                                                                                                      |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `device`       | The name of this device: the SSH alias that the other devices use for it.                                                                                  |
| `otherDevices` | The other devices: the SSH aliases that this device uses for them. An entry equal to `device` is skipped, so the same list can be written on every device. |

A device alias consists of letters, digits, `.`, `_` and `-`, and starts with a
letter or a digit. Set both keys to contact another device: a recipient needs
the sender's device in its own `otherDevices` to send a message back. Local
qualification with this device's configured alias works without `otherDevices`.
A session reads the file when it starts or reloads.

### How a device is reached

For each list of a device and each send, the tool runs one `ssh`
command. With `all`, the list commands run at the same time.

```sh
ssh -o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=5 -o ServerAliveCountMax=2 <device> '<command>'
```

`<command>` is the same for every device and every request. It prints an empty
line, runs the first installed copy of this package's
`dist/pi-intercom/remote-cli.js` under the home directory, and exits with status
44 when there is none. The tool writes the request only after that first line:

```sh
echo; test -f ~/.pi/agent/git/github.com/fitchmultz/pi-subagents/dist/pi-intercom/remote-cli.js && exec node ~/.pi/agent/git/github.com/fitchmultz/pi-subagents/dist/pi-intercom/remote-cli.js; test -f ~/.pi/agent/npm/node_modules/@fitchmultz/pi-subagents/dist/pi-intercom/remote-cli.js && exec node ~/.pi/agent/npm/node_modules/@fitchmultz/pi-subagents/dist/pi-intercom/remote-cli.js; exit 44
```

The other device needs:

- SSH login with a key and without a prompt, under the alias in `otherDevices`.
- This package, installed by Pi from Git or from npm in the default agent
  directory `~/.pi/agent`.
- `node` on the `PATH` of a command that `ssh` runs without a terminal.

`remote-cli.js` reads one JSON request from stdin and prints its JSON reply as
the last line on stdout. The replies are wrapped here for reading:

```json
{ "version": 1, "command": "list", "origin": "desk" }
```

```json
{
  "version": 1,
  "now": 1794350610543,
  "sessions": [
    {
      "id": "pi-…",
      "name": "api-fix",
      "cwd": "/work/api",
      "model": "model-b",
      "status": "idle",
      "startedAt": 1794343410000,
      "lastSeen": 1794343410543
    }
  ]
}
```

A send carries the sending main as its own broker lists it, the
target without its `@device` ending, and the message:

```json
{
  "version": 1,
  "command": "send",
  "origin": "desk",
  "device": "laptop",
  "from": { "id": "pi-…", "name": "web-build", "cwd": "/work/web" },
  "nativeSender": true,
  "to": "api-fix",
  "message": { "text": "The schema change is merged.", "messageId": "…" },
  "timeoutMs": 8000
}
```

```json
{
  "version": 1,
  "receipt": { "id": "…", "accepted": true, "delivered": true }
}
```

A failure is `{ "version": 1, "error": "…" }` with exit status 1. A package
that lacks a command answers `Unsupported command "<command>".`

The command joins the running broker of its device as a main, does its work,
and leaves. It never starts a broker: without a running broker it answers a list
with an empty list and a message with "no Pi session is connected there". No
listener, service or port is added on any device.

- For a list, the main is named `intercom-list@<origin>`.
- For a message, the main is named `<sender name>@<origin>`, with the sender's
  working directory. Native Intercom sends include `nativeSender: true` at the
  top level of the request. The command keeps that flag on the registered
  `remote-cli` peer to distinguish native sends from forwards. Its ID is `remote-` and a
  hash of the origin and the sender's ID, so sequential commands of one sender
  are the same peer to the recipient. An overlapping command from that sender
  fails before sending a message; wait for the connected command to finish.
  Device lists leave these command peers out and include authenticated bridge
  mailboxes.

For each listed main, these fields leave its device, inside the SSH connection:
ID, name, cwd, model, project ID, `gitRepo`, `gitBranch`, `workingOn`, status,
`startedAt`, `lastSeen`, `lastIntercomActivity`
and `lastTurnError`.

### Forward a notice with a return address

An automation calling `remote-cli.js` directly leaves `nativeSender` unset.
A forwarding `send` can set `message.returnAddress` to an exact mailbox name
on the receiving device. For example, put this object in `message`:

```json
{
  "text": "The PR review found a missing test.",
  "messageId": "review-notice-123",
  "returnAddress": "grok-bot-fitch-os"
}
```

Use an unqualified name starting with a letter or digit and containing only
letters, digits, `.`, `_`, or `-`. The command rejects the send if the name does
not resolve to a connected [durable bridge mailbox](intercom-bridge.md).
Pi and Antigravity recipients see `Reply via intercom send to …` and can send a
new message to that mailbox. The receiving device's command, Pi extension, and
bridge must support return addresses.

Without that field, an unmarked send reads `Forwarded by … · no Intercom reply
address`. Older native senders do not set `nativeSender`; update both ends to
keep native sender labeling during cross-device sends.

## Sending messages

```js
intercom({ action: "send", to: "reviewer", message: "Check refresh-token rotation." });
```

Every Intercom `send` uses **steer** delivery: it wakes a dormant or idle
recipient or reaches busy work at the next tool boundary. Print-mode recipients
use the same rule. Inbound native messages display both the sender's name and
exact peer ID (or `name@device` for cross-device sends) in the header so a peer
that needs to respond can call `intercom({ action: "send", to: "...", message: "..." })`
directly.
There are no passive, queued, or replace delivery modes anywhere on Intercom;
broker and bridge handlers ignore unknown legacy JSON fields if an older remote
peer sends them and deliver every message as immediate steering.

Do not send acknowledgements, thanks or receipts that need no action, and do not
reply to a message that needs none. A send to an idle recipient costs it a full
model request. Send only what the recipient must act on or must know to avoid a
mistake. When you need an answer from another session, send your question and end
your turn (or continue independent work); the peer sends its answer back with
`send`, waking or steering you when ready.

`send` is non-blocking. Its response means broker acceptance, not
recipient journal persistence, model consumption, reply, or task completion. A
lost transport response can be uncertain; do not blindly replay side effects.

When a local transport send loses its acknowledgement, the tool error retains the
original `messageId` and reports `deliveryUnknown:true`. It omits `accepted` and
`delivered` because neither outcome is confirmed. Local validation failures before
dispatch report `deliveryUnknown:false`, `accepted:false`, and `delivered:false`.
Neither path retries the message automatically.

Messages accepted for a parked child remain queued until it returns. If its
owner reports a failed wake, inspect the child's run for its last recorded wake
failure before resending. A later active message requests another wake.

## Read the last response without waking

```js
intercom({ action: "last", to: "reviewer" });
// Follow the returned entryId/nextOffset for large responses:
intercom({ action: "last", to: "<exact-peer-id>", entryId: "<entry-id>", offset: 16384 });
```

The native owner reads the last completed assistant response on its active
branch. This is original assistant text, not a run-status summary. No direct
message, prompt, or model turn is created. Empty history is reported explicitly.
When `entryId` is omitted and a newer assistant turn on the active branch ended
in error (or the only assistant turn failed), the metadata block adds
`Latest turn failed (<entryId>): <error>` and `details.latestTurnError` carries
`{ entryId, error }` so an earlier completed reply is not mistaken for the
peer's latest turn.

Pages are bounded to 16,384 UTF-16 code units. Keep `entryId` for stable paging and
use the returned next offset; do not calculate byte offsets. A newer response
does not silently replace the requested entry halfway through retrieval. Missing
or no-longer-readable entries fail explicitly. Tool output and thought blocks are
not substituted for completed assistant text.

The broker assigns request tokens and verifies the answering peer and page
identity. Reads settle on response, disconnect, or timeout. Old peers/brokers
without the capability report unsupported reads instead of receiving unknown
message frames. Broker correlation does not grant access to another group.

## Native-owned receipts and publication provenance

Receipt reads are non-waking and distinct from `last`. The native client
negotiates `receiptReads:1` with the broker, which also checks the recipient's
capability before forwarding `{rootSessionId,messageId}`. Old brokers or owners
are unavailable, not a reason to send an unknown frame or parse their journals.
Receipt and last reads share the broker's private token, answering-peer,
timeout and disconnect owner. A receipt response must match the exact requested
native root and message ID. No model-facing receipt action is added.

A companion in the original main emits `pi-intercom:provenance-query` on
`pi.events` with `{version:1,rootSessionId,messageId,respond(result)}`. The loaded
Intercom owner reads its own readonly native SessionManager and responds
synchronously with `{receipt}` or `{error}`. Unknown versions, an inactive owner
or a different root return `publication_unavailable`. An absent checkpoint
returns `receipt_not_found`, which proves neither no effect nor task success.
Missing handlers are unsupported; there is no packaged parser fallback.

The version-1 receipt contains the exact root and message ID, original sender
peer/root/incarnation where recorded, received timestamp,
checkpoint entry ID, selected guard and publication-hint fields, and
`textSha256`. That hash is lowercase SHA-256 of the exact raw sender text encoded
as UTF-8, before banners, hints, or newline/Unicode normalization. It is computed
independently of the caller's opaque `commandFingerprint`. No input text,
attachments, thoughts, cwd, model settings or native journal path is returned.

Facts remain separate:

- `checkpointEntryId` observes the original owner's appended delivery record.
  It is not a per-entry fsync or power-loss durability receipt.
- `queued` records an observed extension staging checkpoint.
- `nativeHandoff` records the native-handoff checkpoint, written before calling
  Pi's send API. It does not prove that call succeeded or the provider accepted
  input.
- `placementEntryId` identifies the actual native custom-message entry, or null
  when no placement was observed. Placement is not semantic model consumption.
- `discarded` records an explicit discard checkpoint when one exists.

These are historical positive observations, not a claim that an input is still
queued. Provider-input admission and model consumption remain unknown. Finals,
settlement and ordinary replies are not fabricated command publications.

Receipt reads inspect the exact original session's journal, including its other
branches. They retain the immutable original sender after ordinary departure,
reload, compaction and cold reopen.
Copied history in a fork/new root cannot attest the original root's checkpoint.
This is separate from `last`, which remains active-branch-only and keeps pinned
entry paging semantics.

## Supported non-model client

Install this package as a normal Node.js dependency and import its supported
subpath. Pi and TypeBox peers are optional; a companion needs neither them nor
provider credentials. Importing this entry does not load the extension, CLI,
TUI, session manager, journal parser or model SDK.

```js
import { connectIntercom } from "@fitchmultz/pi-subagents/intercom-client";

const client = await connectIntercom({
  spawn: false,
  session: {
    name: "my-companion",
    cwd: process.cwd(),
    model: "non-model-client", // A registration label, not a model to initialize.
    rootSessionId: savedSenderRoot,
    incarnation: savedSenderIncarnation,
  },
});
try {
  const peers = await client.listSessions();
  // Join selected consent to one exact advertised main; do not select by name.
  const target = peers.find((peer) => peer.id === savedTarget.peerId);
  if (!target) throw new Error("Original target unavailable");
  const result = await client.send(savedTarget.peerId, {
    messageId: savedMessageId,
    text: savedText,
    guard: savedTarget, // rootSessionId, peerId, incarnation, applicationGuard
    replyHint: {
      tool: "my_publication_tool",
      commandId: savedCommandId,
      commandFingerprint: savedCommandFingerprint,
    },
  });
  // result describes broker acceptance, not native or provider admission.
  const receipt = await client.receipt(savedTarget.peerId, {
    rootSessionId: savedTarget.rootSessionId,
    messageId: savedMessageId,
  });
  const page = await client.last(savedTarget.peerId, { limit: 16384 });
  // Keep page.entryId and page.nextOffset for subsequent pages.
} finally {
  await client.disconnect();
}
```

The example's saved values belong to the caller's immutable command record, not
to this client. Persist that record and the actual `client.sessionId` before the
attempt. `requestedId` is optional and can collide; only the returned current
identity attests this connection. The client creates no ledger, consent, second
session or model loop. Registration does not grant human-origin authority.

`connectIntercom` requires literal `spawn:false` and never starts a missing or
old broker. It uses the normal same-user namespace or the caller's explicit
`PI_INTERCOM_RUNTIME_DIR`; it does not change global Pi configuration or infer a
fallback namespace. Connection failure rejects. `sendTimeoutMs` and
`listTimeoutMs` bound native requests; optional `onError(error)` observes socket
errors. Outstanding operations reject on loss. `isConnected()` and `sessionId`
report current transport state, not recipient activity or successful work.
`disconnect()` closes this socket and joins its cleanup; reconnect explicitly
with a new `connectIntercom` call. There are no reconnect or resend timers.

Public sends require an original message ID
and the complete exact guard. Concurrent sends with one pending ID reject rather
than replacing its acknowledgement waiter. Invalid inputs, old capability
negotiation, stale consent/context and ambiguous roots never downgrade to an
ordinary send. The generic hint and opaque fingerprint are optional native
metadata, not a guaranteed reply.

After any unconfirmed send, keep the original ID and target. Reconcile only with
`receipt`; never generate another UUID, reroute or assume that missing means
unsent. A later explicit new operation is the caller's decision, not an automatic
retry. Receipt facts retain the original sender after departure. Unsupported old
brokers or owners fail closed; `publication_unavailable` and `receipt_not_found`
do not establish no effects. `last` is separately non-waking and pinned by entry
ID; it is not a correlated command reply. Ordinary local Intercom name resolution
and topology are unchanged.

Only `./intercom-client` and `./package.json` are public package subpaths.
Private transport, broker, extension and parser paths are not supported imports.
The Pi resource manifest still loads its compiled extension independently.

## Persistence and lifecycle

Inbound state is checkpointed in the recipient's native session journal. Native
publication/consumption receipts govern replay; broker writes alone do not.
Queued, admitted, and consumed are distinct states. Reload, compaction,
branch changes, shutdown, and fresh-process recovery must not fabricate receipts
or adopt another native session's pending messages.

An already-admitted message ID cannot publish a second copy. The same applies to deliberately
discarded queued messages, including native journal restoration. A new ID
is a new input even if its text is identical. This recipient-side deduplication is
not an end-to-end exactly-once guarantee for arbitrary tool side effects.

Idle recovery preserves admission order within the backlog and wakes
once on its last item.
A busy recipient's steer is handed to Pi's native
queue and consumed at its next tool boundary; no extension probe asks another
tool to give up the turn.

Shutdown joins admitted inbound work before detaching its native owner. Stale
runtime generations must not checkpoint or deliver into a replacement session.
Context state is inactive, live with its session and incarnation, or invalidated
while transport cleanup retains the session ID. Clearing cleanup drops that ID;
transport connection and native tool activity remain separate from context validity.
The native tests own these contracts; neither a timer nor a source-string test is
publication evidence.

## Shared broker and migration

Default files on macOS/Linux:

- `/tmp/pi-intercom-<uid>/broker.sock`
- `/tmp/pi-intercom-<uid>/broker.pid`
- `/tmp/pi-intercom-<uid>/broker.spawn.lock`

Native Android/Termux uses `$PREFIX/tmp/pi-intercom-<uid>` instead of `/tmp`.
This is shared across the app's sessions, not derived from a session's HOME,
agent directory, or TMPDIR. Android without a Termux PREFIX uses Node's native
temporary directory. The separate read-only child observation endpoints use
the same runtime-root policy.

The runtime directory is owned by the OS user, nonsymlink, and mode 0700; the
socket is mode 0600. The broker starts on first use and exits after five seconds
without connected sessions, unless a parked child still holds admitted input; that
input waits for its main to return and wake the child. Concurrent publication uses
the shared spawn lock, held by the broker process before it checks or changes
endpoint files. Starters only launch detached candidates and wait for a healthy
endpoint. A delayed candidate must acquire the same claim before publishing, even
if its starter has exited or timed out. The broker releases its claim only after
bind and PID publication finish (or startup fails).

`PI_INTERCOM_RUNTIME_DIR` explicitly selects an isolated deployment. It must be
an absolute private directory with a socket path within 100 UTF-8 bytes. Invalid
configuration fails without falling back to another namespace. Set it consistently
for every process intended to share that isolated broker. Tests must always use
an owned isolated directory, never the user's ordinary shared socket.

Old releases used agent-directory-specific brokers. Updated sessions join the
new shared namespace; old sessions stay on their old brokers until they load the
updated extension. Startup warns when it detects an old broker for the current
agent directory. It does not kill, modify, take over, or silently route back to
that broker. During migration, old and new peers may therefore be invisible to
each other. Finish accepted work before upgrading; do not force broker shutdown
to make discovery appear complete. During an authorized cutover, inventory and
reload every participating Pi session on that Mac before resuming bridge traffic,
then verify the expected exact peers from both mains and the helper. The warning
only detects old brokers for the current agent directory; it cannot certify that
all old sessions elsewhere have migrated.

The predictable macOS/Linux `/tmp` namespace is independent of caller HOME/TMPDIR, which is
needed for same-user discovery across differently configured sessions. A foreign
user who pre-creates that path can deny availability, but cannot be adopted as the
broker owner: startup refuses foreign or symlink directories. It must not delete
or take over the path to recover. On shared hosts, an operator can pre-provision
a short private directory under an owned non-writable parent and consistently set
`PI_INTERCOM_RUNTIME_DIR` for every participating Pi session and helper. This is
an explicit deployment choice, not an automatic fallback to a split namespace.

An unresponsive or missing socket is not permission to kill a possibly live
owner. PID checks are conservative, including permission-denied cases. Linux
records include native boot/namespace/start identity to reject proven PID reuse.
macOS records use the shared process-group birth identity and a UTC birth strictly
after the observed record publication time; Android uses the shared boot-qualified
monotonic clock and conservative elapsed-age bound, never wall time;
ambiguous legacy numeric PIDs remain blocking. A process is never killed merely
to recover broker startup.

Startup distinguishes absent, live and uncertain ownership. An unreadable or
invalid PID record is uncertain, not permission to launch another broker.
A startup claim stays owned while its process is live, regardless of age.
Only a proven exited or replaced owner permits reclaiming it. Claims carry
the same native process identity and Android clock as broker PID records. Legacy or incomparable
identities remain blocking; a timestamp alone cannot prove PID reuse.
Each broker keeps the claim's file descriptor open and releases only the same
device/inode, leaving a replacement claim untouched. Shutdown likewise removes
only the socket inode it bound and the PID inode it published; a successor's
endpoint files remain intact.

Broker PID records end with `version <semver>` (0.52.88 and later). All starters
(Pi sessions, `agy` peers, durable bridge presence, and `--upgrade`) read
`brokerCommand` and `brokerArgs` from `<PI_CODING_AGENT_DIR>/intercom/config.json`.
When the configured `brokerCommand` resolves to the running Node binary
(`process.execPath`), session startup and durable presence automatically upgrade
an older versioned broker in place, preserving `brokerArgs`. When a custom
`brokerCommand` is configured, automatic startup attaches to the existing broker
and emits a one-time warning instead of overriding the configured launcher;
run `node dist/pi-intercom/broker/broker.js --upgrade` to upgrade explicitly
under the configured `brokerCommand` and `brokerArgs`. Pre-version brokers
(0.52.87 and earlier) lack live handoff support, so automatic startup leaves
them running until idle or drained and replaced via `--upgrade`.

In-place versioned upgrades bind a candidate socket (`c<pid>`) and stage a PID
record (`broker.pid.<pid>.tmp`) under `broker.spawn.lock`, ask the incumbent to
freeze admissions (`prepare_upgrade`), stream parked children and queued mail
over the local socket, atomically `rename` `c<pid>` onto `broker.sock` and
`broker.pid.<pid>.tmp` onto `broker.pid` (rolling back via hardlink backups if
commit fails), and only then broadcast `{ type: "reconnect" }` so native, `agy`,
and bridge clients cut over in 0 ms without backoff. A plain stop-then-restart
with a shutdown disk dump is deliberately avoided: unlinking `broker.sock`
before a replacement listener is bound causes `bridge-session.ts` to fail active
`/v1/inbox` long-polls and in-flight requests with `503 broker_disconnected`,
and lets any connected session still running an older extension win
`broker.spawn.lock` during the `ENOENT` gap and respawn the older broker.

Remote authenticated mail is separate. A rejected bridge webhook can stop waking a receiver without removing the message from its inbox. See [rejected wake requests and re-arm](intercom-bridge.md#rejected-wake-requests).

## Antigravity (`agy`) peer adapter

Main Antigravity sessions join the same local `pi-intercom` broker as main
peers (`agy-<conversationId>`) and receive `intercom`, `delegate`, and
`agent_runs` through the bundled MCP server.

- **MCP server (`dist/pi-intercom/agy/mcp-server.js`)**: Runs over stdio under
  the Antigravity Language Server, exposes `intercom` (`list`, `status`,
  `send`, `last`, `claim`, including cross-device `device` and `name@device`),
  `delegate`, and `agent_runs` (`list`, `inspect`, `continue`, `stop`),
  identifies the caller from Antigravity's
  `_meta["antigravity.google/conversation_id"]`, and stops owned child runs and
  unregisters cleanly when `agy` exits.
- **Native Pi delegation (`delegate` and `agent_runs`)**: Spawns real native Pi
  child runs scoped to `owner = agy-<conversationId>` (same run storage, IDs,
  `readOnly`, `cwd` defaulting to the Antigravity workspace directory, `model`,
  `thinking`, `name`, Overseer checkpoints when configured in Pi settings, and
  Intercom group membership so `intercom({ action: "list" })` counts and lists
  the session's children). Because Antigravity sessions are external IDE
  conversations without a native Pi `.jsonl` journal, `context: "fork"` is
  refused with an explicit error; pass `context: "fresh"` or omit `context`.
- **Lifecycle hooks (`dist/pi-intercom/agy/hook-cli.js`)**: Connects over a
  private per-Language-Server Unix socket (`ls-<ppid>.sock` under the
  `-agy` sibling of the Intercom runtime directory) to auto-register on
  `SessionStart`, keep presence updated (`working` / `idle`), drain fallback
  queued messages on `PreInvocation`/`PostInvocation`/`Stop`, and skip internal
  `agy` subagents. Control sockets and conversation index files are
  inode-owned: startup never steals a live owner's socket, and shutdown removes
  only the exact `(dev, ino)` it created.
- **Inbound wake (`agentapi`)**: When a wake environment file exists at
  `${PI_CODING_AGENT_DIR:-~/.pi/agent}/intercom/agy-wake/<conversationId>.env`
  (containing loopback `ANTIGRAVITY_LS_ADDRESS`, `ANTIGRAVITY_CSRF_TOKEN`, and
  optional `ANTIGRAVITY_AGENTAPI_EXE` from a shell `run_command`), inbound
  `send` messages, child-run completions, and Overseer checkpoint pauses call
  `agentapi send-message` to wake idle `agy` sessions and steer active ones at
  the next tool boundary. Non-blocking Overseer heads-up notes queue without
  waking an idle session. The wake file is
  owned by the shell session, not the MCP server, so MCP restarts leave live
  wake credentials intact. Without wake
  credentials, messages and child notifications queue for hook delivery on the
  session's next turn boundary, with durable receipts under the owner directory
  preventing duplicate delivery across scans and MCP reconnects.
- **Zero-turn `last`**: Answers `intercom({ action: "last", to: "<agy>" })`
  directly from `transcript.jsonl` (falling back to sibling
  `transcript_full.jsonl` when `truncated_fields` includes `"content"`), with
  the same UTF-16 offset/limit pagination as Pi sessions.
- **Title sync**: Passing `agy`'s `title` hook JSON into
  `node dist/pi-intercom/agy/hook-cli.js title` updates the peer's Intercom
  display name when Antigravity generates a title or the user runs `/rename`.
