pi-link 0.1.15 → 0.1.16

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,650 +1,682 @@
1
- # pi-link
2
-
3
- A WebSocket-based inter-terminal communication system that creates a local network between multiple Pi coding agent terminals. Enables terminals to discover each other, exchange messages, and orchestrate work across agents - all automatically on `localhost`.
4
-
5
- > Self-contained TypeScript in a single `index.ts` file. Start Pi with `--link` to enable, or use `pi-link <name>` to resume/create named sessions
6
-
7
- ---
8
-
9
- ## Table of Contents
10
-
11
- - [Why?](#why)
12
- - [Prerequisites](#prerequisites)
13
- - [Quick Start](#quick-start)
14
- - [Walkthrough](#walkthrough)
15
- - [Configuration](#configuration)
16
- - [LLM Tools](#llm-tools)
17
- - [Slash Commands](#slash-commands)
18
- - [Architecture](#architecture)
19
- - [Troubleshooting](#troubleshooting)
20
- - [Limitations & Design Decisions](#limitations--design-decisions)
21
- - [Dependencies](#dependencies)
22
- - [Internals](#internals)
23
-
24
- ---
25
-
26
- ## Why?
27
-
28
- A single Pi terminal is powerful. Multiple terminals working together unlock new patterns:
29
-
30
- - **Research + Build** - one terminal investigates APIs, docs, or logs while another writes code based on the findings.
31
- - **Fan-out** - split a large task across agents (e.g., "terminal A handles the backend, terminal B handles the frontend") and collect results.
32
- - **Orchestrator / Worker** - designate one terminal as a coordinator that delegates subtasks to others via `link_prompt` and assembles the final output.
33
- - **Review pipeline** - one terminal writes code, another reviews it, back and forth until both are satisfied.
34
-
35
- ---
36
-
37
- ## Prerequisites
38
-
39
- - [Pi coding agent](https://github.com/badlogic/pi-mono), version **0.74 or later** (for pi-link 0.1.15+). On Pi ≤0.73, pin `pi-link@0.1.14`.
40
- - Node.js (LTS recommended)
41
-
42
- ---
43
-
44
- ## Quick Start
45
-
46
- ### Install
47
-
48
- The minimum install — enables every in-Pi feature (`/link`, `link_send`, `link_prompt`, `/link-connect`, `--link` flag, auto-resume, all LLM tools):
49
-
50
- ```bash
51
- pi install npm:pi-link
52
- ```
53
-
54
- That's it. For most users this is all you need.
55
-
56
- #### Optional: shell launcher
57
-
58
- If you also want the `pi-link <name>` shell command to start named sessions from a terminal prompt (e.g. `pi-link builder` in one window, `pi-link reviewer` in another), install the CLI globally as well:
59
-
60
- ```bash
61
- npm i -g pi-link
62
- ```
63
-
64
- Or install both in one line:
65
-
66
- ```bash
67
- pi install npm:pi-link && npm i -g pi-link
68
- ```
69
-
70
- The shell launcher is convenience-only — you can always reach the same functionality from inside Pi via `/link-connect <name>` and `/link-name <name>`.
71
-
72
- > **Why two installs?** Pi 0.75 installs Pi packages into a private npm root (`~/.pi/agent/npm/`) for safer permission handling ([pi-mono#4587](https://github.com/earendil-works/pi-mono/issues/4587)). That's where the Pi extension lives, but it means the `pi-link` shell command is no longer on system PATH. `npm i -g pi-link` puts it on PATH separately. Both installs are safe to use together.
73
-
74
- ### Uninstall
75
-
76
- ```bash
77
- pi uninstall npm:pi-link # Remove Pi extension
78
- npm uninstall -g pi-link # Remove CLI launcher (if you installed it)
79
- ```
80
-
81
- ### Usage
82
-
83
- Link is **off by default**. Start Pi with `--link` to auto-connect on startup:
84
-
85
- ```
86
- Terminal 1 Terminal 2
87
- ---------- ----------
88
- $ pi --link $ pi --link
89
- ✓ Link hub started on :9900 as "t-a1b2" ✓ Joined link as "t-c3d4" (2 online)
90
- ```
91
-
92
- Use `pi-link <name>` to connect with a meaningful name and session resume:
93
-
94
- ```
95
- $ pi-link builder $ pi-link reviewer
96
- ✓ Link hub started on :9900 as "builder" ✓ Joined link as "reviewer" (2 online)
97
- ```
98
-
99
- See [Session Resume](#session-resume) for details.
100
-
101
- Already in a session? Connect mid-session with `/link-connect`.
102
-
103
- Use `/link` in any terminal to check status, or let the LLM tools handle cross-terminal coordination.
104
-
105
- ---
106
-
107
- ## Walkthrough
108
-
109
- Here's a concrete example of two terminals collaborating. Open two separate `pi --link` sessions.
110
-
111
- **Terminal 1** - rename and check status:
112
-
113
- ```
114
- > /link-name builder
115
- ✓ Renamed to "builder"
116
-
117
- > /link
118
- ⚡ Link: builder (hub) · 2 online
119
- builder: idle (5s)
120
- cwd: ~/my-project
121
- researcher: idle (12s)
122
- cwd: ~/my-project
123
- ```
124
-
125
- **Terminal 2** - rename it too:
126
-
127
- ```
128
- > /link-name researcher
129
- ✓ Reconnecting, requesting "researcher" (hub may assign a different name if taken)...
130
- ```
131
-
132
- **Now ask Terminal 1's LLM to delegate work:**
133
-
134
- In Terminal 1, type a normal prompt:
135
-
136
- ```
137
- > Use link_prompt to ask "researcher" to summarize the contents of README.md in this directory
138
- ```
139
-
140
- The LLM in Terminal 1 calls `link_prompt` → Terminal 2's LLM receives the prompt, reads the file, and sends back a summary → Terminal 1's LLM presents the result to you.
141
-
142
- **Or broadcast a message to all terminals:**
143
-
144
- ```
145
- > /link-broadcast starting the deployment pipeline
146
- ✓ Broadcast sent
147
- ```
148
-
149
- Every other terminal sees:
150
-
151
- ```
152
- ⚡ [builder] starting the deployment pipeline
153
- ```
154
-
155
- ---
156
-
157
- ## Configuration
158
-
159
- Link is **off by default**. Without `--link`, `--link-name`, or `pi-link`, the extension is completely silent — no status bar, no connections, no warnings.
160
-
161
- | Method | When | Auto-reconnect? |
162
- | ----------------------- | ---------------------------------------------------------------- | -------------------------------- |
163
- | `pi-link <name>` | Resume/create named session | Yes |
164
- | `pi --link-name <name>` | Connect with a specific link name; Pi session behavior unchanged | Yes |
165
- | `pi --link` | Connect on startup (random name) | Yes |
166
- | `/link-connect` | Opt-in mid-session (no flag needed) | Yes |
167
- | `/link-disconnect` | Opt-out mid-session | Suppressed until `/link-connect` |
168
-
169
- `pi --link-name <name>` sets only the pi-link terminal name; Pi's session selection/resume runs as normal. Use this when you want a stable link identity without coupling it to a same-named session. Use `pi-link <name>` when you want the combined session-by-name + link-name workflow. The `pi-link` wrapper itself does not accept `--link-name`.
170
-
171
- **Name precedence:** `pi --link-name` > `pi-link <name>` > saved `/link-name` > Pi session name > random `t-xxxx`.
172
-
173
- `/link-connect` and `/link-disconnect` save their intent to the session — resume later and the connection state is restored without needing the flag. Explicit user intent takes precedence over `--link`.
174
-
175
- Once connected, terminals discover each other on `127.0.0.1:9900`. See [Limitations](#limitations--design-decisions) for the hardcoded port.
176
-
177
- ### Session Resume
178
-
179
- Pi's `--session` flag requires a file path, not a display name. `pi-link` bridges this — it resolves a session by name and launches Pi directly:
180
-
181
- ```bash
182
- pi-link worker-1 # resume or create session "worker-1"
183
- pi-link worker-1 --model sonnet # with extra Pi flags
184
- ```
185
-
186
- How it works: `pi-link worker-1` scans Pi's session directory, finds the session named "worker-1", and spawns `pi --session <path> --link`. Session-dir resolution matches Pi's lookup order: `PI_CODING_AGENT_SESSION_DIR` env > `<cwd>/.pi/settings.json` `sessionDir` > `<agentDir>/settings.json` `sessionDir` > default `<agentDir>/sessions/`. `<agentDir>` follows `PI_CODING_AGENT_DIR` and defaults to `~/.pi/agent/`.
187
-
188
- Lookup is **scoped to the current cwd by default**; pass `--global` (`-g`) to consider sessions in any cwd.
189
-
190
- - **One match in scope** → resumes that session
191
- - **No match in scope** → creates a new session in the current cwd. If matches exist outside the scope, prints a hint pointing at `--global`.
192
- - **Multiple matches in scope** → prints candidates to stderr, exits 1
193
- - **Conflicting flags** (`--session`, `--continue`, `--resume`, `--fork`, etc.) → rejected with an error
194
-
195
- ### Discovering sessions
196
-
197
- `pi-link --list` shows pi-link sessions in the current cwd; `pi-link --list --global` (or `-g`) lists them across all directories. Sorted by last activity — starting a session with the same name it already has does not bump recency; only real activity (messages, tool calls, edits, name changes) does.
198
-
199
- ```
200
- $ pi-link --list
201
- NAME MODIFIED MESSAGES ID
202
- opus@pi-link 2m ago 4632 6332faab
203
- gpt@pi-link 5m ago 1493 20d43841
204
-
205
- Resume: pi-link <name>
206
- ```
207
-
208
- With `--global`:
209
-
210
- ```
211
- $ pi-link --list --global
212
- NAME CWD MODIFIED MESSAGES ID
213
- opus@pi-link ~/my-project 2m ago 4632 6332faab
214
- gpt@pi-link ~/other-project 5m ago 1493 20d43841
215
-
216
- Resume: pi-link <name>
217
- ```
218
-
219
- `--global` adds a `CWD` column with `~` substituted for `$HOME`. Output is plain when piped (`NO_COLOR` honored).
220
-
221
- `pi-link <name>` and `pi-link --resolve <name>` follow the same scoping: local cwd by default, `--global` (or `-g`) widens. When `pi-link <name>` finds no local match but matches exist elsewhere, it warns and points at `--global` instead of silently jumping cwds.
222
-
223
- For scripting, `pi-link --resolve <name>` prints just the session path (machine-readable, no other output). Exit codes: `0` on single match, `1` if ambiguous (multiple matches printed to stderr), `2` if not found.
224
-
225
- > The legacy subcommand forms `pi-link list` and `pi-link resolve <name>` still work but print a stderr deprecation warning and will be removed in a future release. Switch to the flag forms above.
226
-
227
- ---
228
-
229
- ## LLM Tools
230
-
231
- The extension registers three tools that the LLM can invoke during agent runs. pi-link also ships with a bundled **pi-link-coordination** skill that gives agents on-demand guidance for tool selection, delegation patterns, and avoiding common coordination mistakes.
232
-
233
- ### Which tool should I use?
234
-
235
- | Tool | Behavior | Returns |
236
- | ------------- | ---------------------------------------------------- | ----------------------------------------- |
237
- | `link_send` | Send a message; optionally trigger the remote LLM | Send/delivery status only |
238
- | `link_prompt` | Run a prompt on a remote terminal and wait for reply | The remote terminal's assistant response |
239
- | `link_list` | List currently connected terminals | Terminal list with roles, status, and cwd |
240
-
241
- **If you need the other terminal's answer back, use `link_prompt`.** Use `link_send` to notify or steer without waiting.
242
-
243
- ### `link_send`
244
-
245
- Send a fire-and-forget chat message to a specific terminal or broadcast to all.
246
-
247
- | Parameter | Type | Description |
248
- | ------------- | --------- | ---------------------------------------------------- |
249
- | `to` | `string` | Target terminal name, or `"*"` for broadcast |
250
- | `message` | `string` | Message content |
251
- | `triggerTurn` | `boolean` | If `true`, the receiver's LLM responds automatically |
252
-
253
- When `triggerTurn` is enabled, the message is queued in the receiver's local inbox. Nearby arrivals are coalesced (200ms debounce), and delivery is gated on the receiving agent being idle - ensuring it starts a clean new turn. Messages arrive as a single `[Link: N message(s) received]` block at the top of a fresh turn, not mid-run. When `triggerTurn` is `false` or omitted, delivery is immediate fire-and-forget.
254
-
255
- Note: `triggerTurn` does **not** cause the response to come back to the caller - use `link_prompt` for that.
256
-
257
- > **Broadcast note:** Sending to `"*"` delivers to **all other terminals** - the sender is excluded.
258
-
259
- Pre-validates the target name against the local terminal list before sending, catching typos early. See [Message Routing](#message-routing--error-handling) for delivery semantics.
260
-
261
- ### `link_prompt`
262
-
263
- Send a prompt to a remote terminal and **wait** for the LLM's response (synchronous RPC pattern).
264
-
265
- | Parameter | Type | Description |
266
- | --------- | -------- | -------------------- |
267
- | `to` | `string` | Target terminal name |
268
- | `prompt` | `string` | Prompt text to send |
269
-
270
- - The remote terminal processes the prompt via `pi.sendUserMessage()` - as if a user typed it.
271
- - Returns the remote terminal's actual assistant reply text as the tool result.
272
- - **Self-target rejection** - prompting yourself (`to` equals your own name) returns an immediate error.
273
- - **Heartbeat-based timeout** - no short fixed deadline. The target sends keepalives every 30s while working. The sender resets a 90-second inactivity timer on each keepalive. A 30-minute hard ceiling acts as a safety net against broken-but-chatty targets. A 10-minute task with regular activity never times out; a genuinely dead target times out in 90 seconds of silence.
274
- - **Immediate failure on disconnect** - if the target leaves the network (`terminal_left`), pending prompts to that target fail immediately instead of waiting for the inactivity timeout.
275
- - **Early failure detection** - if the message can't be delivered (e.g., target not found), the tool resolves immediately with an error instead of waiting for the timeout.
276
- - Supports abort signals.
277
- - Targets **one terminal at a time** (no broadcast mode).
278
- - Only **one remote prompt** can execute at a time per target terminal. Concurrent requests are rejected with `"Terminal is busy"`.
279
-
280
- ### `link_list`
281
-
282
- Lists all connected terminals with role info, live agent status, working directory, and self-identification. Takes no parameters.
283
-
284
- Each terminal reports its current working directory on connect. `link_list` shows the full absolute path so agents can choose the right target, use explicit paths when terminals differ, and catch wrong-project mistakes early.
285
-
286
- Each terminal's status is derived automatically from Pi lifecycle events - agents can't set it manually. Three states:
287
-
288
- | Status | Meaning |
289
- | ----------------- | ----------------------- |
290
- | `idle (2m)` | Waiting for user input |
291
- | `thinking (3s)` | LLM is generating |
292
- | `tool:bash (12s)` | Running a specific tool |
293
-
294
- Durations are computed at render time from a `since` timestamp - no timer traffic over the wire. Terminals that just joined with no status data yet render as blank, not fake idle.
295
-
296
- Working directories use full absolute paths in tool output. In the TUI (`/link`), paths are shortened to `~/...` when possible to keep the display compact.
297
-
298
- **Example output:**
299
-
300
- ```
301
- Connected terminals:
302
- • opus@pi-link (you) idle (12s)
303
- cwd: C:\Users\andre\.pi
304
- • gpt@pi-link thinking (3s)
305
- cwd: C:\Users\andre\.pi
306
- • docs@pi-link idle (1m)
307
- cwd: C:\Users\andre\.pi
308
- ```
309
-
310
- ---
311
-
312
- ## Slash Commands
313
-
314
- | Command | Purpose |
315
- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------ |
316
- | `/link` | Show link status (name, role, online count, agent status, and cwd per terminal) |
317
- | `/link-name [name]` | Rename and save as this session's preferred link name. With no argument, adopts the Pi session name. Restored on resume. |
318
- | `/link-broadcast <msg>` | Broadcast a chat message to all other terminals |
319
- | `/link-connect` | Connect to Pi Link (works anytime, with or without `--link`) |
320
- | `/link-disconnect` | Disconnect from Pi Link and suppress auto-reconnect (overrides `--link`) |
321
-
322
- ### Examples
323
-
324
- ```
325
- > /link
326
- ⚡ Link: builder (hub) · 3 online
327
- builder: idle (12s)
328
- cwd: ~/my-project
329
- worker-1: thinking (3s)
330
- cwd: ~/my-project
331
- worker-2: tool:bash (5s)
332
- cwd: ~/other-project
333
-
334
- > /link-name orchestrator
335
- ✓ Renamed to "orchestrator"
336
-
337
- > /link-name
338
- ✓ Renamed to "my-session"
339
-
340
- > /link-broadcast starting the build pipeline
341
- ✓ Broadcast sent
342
-
343
- > /link-disconnect
344
- ✓ Disconnected from link
345
-
346
- > /link-connect
347
- ✓ Joined link as "orchestrator" (3 online)
348
- ```
349
-
350
- With no argument, `/link-name` adopts the Pi session name. `/link-connect` joins an existing hub if one is running; otherwise it starts the hub.
351
-
352
- **Name persistence:** `/link-name` saves your preferred name to the session. Resume later and it's restored automatically. If the name is taken, the hub assigns a variant (e.g., `"builder-2"`), but your preferred name stays saved for the next reconnect. See [Name Uniqueness & Persistence](#name-uniqueness--persistence) for details.
353
-
354
- See [Configuration](#configuration) for details on `--link`, `/link-connect`, and `/link-disconnect` behavior.
355
-
356
- ---
357
-
358
- ## Architecture
359
-
360
- ### Hub-Spoke Topology
361
-
362
- The network topology is **hub-spoke (star)**:
363
-
364
- ```
365
- +-----------+
366
- | Hub |
367
- | :9900 |
368
- +-----+-----+
369
- |
370
- +--------------+--------------+
371
- | | |
372
- +---+---+ +---+---+ +---+---+
373
- | pi-2 | | pi-3 | | pi-4 |
374
- |client | |client | |client |
375
- +-------+ +-------+ +-------+
376
- ```
377
-
378
- - The **first terminal** to start becomes the **hub** - it runs a `WebSocketServer` on `127.0.0.1:9900`.
379
- - **Subsequent terminals** connect as **clients** via plain WebSocket.
380
- - All messages route **through the hub**; clients never talk directly to each other.
381
-
382
- ### Auto-Discovery Protocol
383
-
384
- The discovery sequence runs on startup (with `--link` or `pi-link`) or when `/link-connect` is used. See [Configuration](#configuration) for details.
385
-
386
- The sequence is a simple fallback:
387
-
388
- 1. Attempt to connect as a **client** to `127.0.0.1:9900`.
389
- 2. If connection fails → become the **hub** (start a WebSocket server on that port).
390
- 3. If both fail (rare race condition) → retry after a randomized 2-5 second backoff.
391
-
392
- ### Hub Promotion
393
-
394
- When the hub disconnects, clients detect the WebSocket close event, enter `"disconnected"` state, and call `scheduleReconnect()`. The **first terminal to retry** becomes the new hub via the same initialize-or-fallback flow.
395
-
396
- There is **no explicit leader election** - promotion is race-based.
397
-
398
- ---
399
-
400
- ## Troubleshooting
401
-
402
- ### Port 9900 is already in use
403
-
404
- If another process occupies port 9900, the terminal can't become the hub. It will attempt to connect as a client instead (which also fails if there's no real hub), then retry after 2-5 seconds. Free the port or modify `DEFAULT_PORT` in `index.ts` - see [Limitations](#limitations--design-decisions).
405
-
406
- ### "Terminal is busy" rejections
407
-
408
- Each terminal can only execute **one remote prompt at a time**. If a `link_prompt` arrives while the agent is already running (either from a local user or another remote prompt), it's immediately rejected with `"Terminal is busy"`. There is no queuing. Solutions:
409
-
410
- - Wait for the target terminal to finish its current task.
411
- - Spread prompts across multiple worker terminals.
412
- - Have the sender retry after a delay.
413
-
414
- ### Terminals don't see each other
415
-
416
- - Verify both terminals are on the same machine (the link only works on `127.0.0.1`).
417
- - Run `/link` in each terminal to check status.
418
- - Ensure port 9900 isn't blocked or occupied by a non-link process.
419
-
420
- ### Hub promotion loses state
421
-
422
- When the hub goes down and a client promotes itself, terminal names and in-flight prompts from the old hub session are lost. All surviving clients reconnect and re-register. This is by design - see [Limitations](#limitations--design-decisions).
423
-
424
- ---
425
-
426
- ## Limitations & Design Decisions
427
-
428
- | # | Decision | Rationale / Impact |
429
- | --- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
430
- | 1 | **No authentication** | Any localhost process can connect to port 9900. Acceptable for local dev; don't expose the port externally. |
431
- | 2 | **Hardcoded port (9900)** | Not configurable without editing `DEFAULT_PORT` in `index.ts`. Could conflict with other services on the same port. |
432
- | 3 | **Race-based hub promotion** | Non-deterministic. Terminal state (names, in-flight prompts) is lost during promotion. Simple but imperfect. |
433
- | 4 | **Single remote prompt per terminal** | No queuing - immediate rejection if busy. See [`link_prompt`](#link_prompt) and [Troubleshooting](#terminal-is-busy-rejections). |
434
- | 5 | **No message persistence** | Purely ephemeral WebSocket frames. Messages are lost if the recipient is offline. |
435
- | 6 | **Client rename triggers full reconnect** | Changing a client's name requires a new `register` message, so the client disconnects and reconnects. Hub renames are handled in-place with collision checks. |
436
- | 7 | **Single-machine / localhost-only** | Link only binds to `127.0.0.1`; terminals on different machines cannot join. |
437
- | 8 | **Rename during prompt loses keepalives** | If the target renames mid-prompt, keepalive resets stop working (pending requests track by name). The final response can still succeed by request ID, but inactivity may false-fire on long tasks after rename. |
438
-
439
- ---
440
-
441
- ## Dependencies
442
-
443
- ### Runtime (installed by `pi install`)
444
-
445
- | Package | Version | Purpose |
446
- | ------- | ------- | ----------------------------------- |
447
- | `ws` | ^8.20.0 | WebSocket library (server + client) |
448
-
449
- ### Development
450
-
451
- | Package | Version | Purpose |
452
- | ----------- | ------- | --------------------------- |
453
- | `@types/ws` | ^8.18.1 | TypeScript type definitions |
454
-
455
- ### Provided by Pi (no install needed)
456
-
457
- | Package | Purpose |
458
- | --------------------------------- | ------------------------------------------------ |
459
- | `@earendil-works/pi-coding-agent` | Pi SDK types (ExtensionAPI, ExtensionContext) |
460
- | `@earendil-works/pi-tui` | TUI Text widget for custom message rendering |
461
- | `typebox` | JSON Schema type definitions for tool parameters |
462
-
463
- > **Pi version requirement:** pi-link 0.1.15+ requires Pi 0.74 or later (the `@earendil-works/*` namespace). Users on Pi 0.73 or earlier should pin `pi-link@0.1.14`.
464
-
465
- ### `package.json`
466
-
467
- ```json
468
- {
469
- "name": "pi-link",
470
- "bin": {
471
- "pi-link": "./bin/pi-link.mjs"
472
- },
473
- "dependencies": {
474
- "ws": "^8.20.0"
475
- },
476
- "devDependencies": {
477
- "@types/ws": "^8.18.1"
478
- },
479
- "pi": {
480
- "extensions": ["./index.ts"],
481
- "skills": ["./skills"]
482
- }
483
- }
484
- ```
485
-
486
- `pi.extensions` tells Pi which files to load as extensions. `pi.skills` registers bundled skill directories. `bin` exposes the `pi-link` CLI (see [Configuration](#configuration)).
487
-
488
- ---
489
-
490
- ## Internals
491
-
492
- > This section covers implementation details for contributors and developers who want to understand or modify the extension's internals.
493
-
494
- ### Protocol
495
-
496
- The wire protocol consists of **9 message types**, all serialized as JSON over WebSocket frames. Cwd-related fields are optional.
497
-
498
- | Type | Direction | Purpose |
499
- | ----------------- | --------------- | ----------------------------------------------------------------------- |
500
- | `register` | Client → Hub | First message after connecting; requests a name, optionally reports cwd |
501
- | `welcome` | Hub → Client | Confirms assigned name, terminal list + status/cwd snapshots |
502
- | `terminal_joined` | Hub → All | Broadcast when a terminal joins; may include cwd |
503
- | `terminal_left` | Hub → All | Broadcast when a terminal disconnects |
504
- | `chat` | Any → Any/All | Fire-and-forget message; optionally triggers LLM turn |
505
- | `prompt_request` | Any → Any | Request a remote terminal to execute a prompt |
506
- | `prompt_response` | Any → Any | Response carrying the remote prompt result |
507
- | `status_update` | Any → Hub → All | Terminal broadcasts its agent status change |
508
- | `error` | Hub → Client | Error notification |
509
-
510
- ### Message Flow Examples
511
-
512
- **Joining the link:**
513
-
514
- ```
515
- Client Hub
516
- | |
517
- | register {name:"builder", |
518
- | cwd:"C:\\Users\\..."} |
519
- |---------------------------->|
520
- | |
521
- | welcome {name, terminals, |
522
- | statuses, cwds} |
523
- |<----------------------------|
524
- | |
525
- ```
526
-
527
- Hub then broadcasts `terminal_joined` to the other connected terminals. The `welcome` message includes status and cwd snapshots for all connected terminals (fields omitted above for brevity). `terminal_joined` also includes the new terminal's optional cwd.
528
-
529
- **Sending a chat message:**
530
-
531
- ```
532
- Client A Hub Client B
533
- | | |
534
- | chat {to:pi-2} | |
535
- |----------------->| |
536
- | | chat {from:A} |
537
- | |----------------->|
538
- | | |
539
- ```
540
-
541
- **Remote prompt (synchronous RPC):**
542
-
543
- ```
544
- Client A Hub Client B
545
- | | |
546
- | prompt_request | |
547
- |----------------->| |
548
- | | prompt_request |
549
- | |----------------->|
550
- | | (LLM runs) |
551
- | |<-----------------|
552
- | prompt_response | |
553
- |<-----------------| |
554
- ```
555
-
556
- ### Name Uniqueness & Persistence
557
-
558
- The hub enforces unique terminal names via a `uniqueName()` function. If `"builder"` is already taken, the next terminal requesting that name is assigned `"builder-2"`, then `"builder-3"`, and so on.
559
-
560
- Default names are random 4-character hex IDs: `t-a1b2`, `t-c3d4`, etc.
561
-
562
- **Persistence:** `/link-name` saves the preferred name to the session via `pi.appendEntry("link-name", { name })`. On session resume, the saved name is restored and requested from the hub. Only explicit `/link-name` calls persist - hub-assigned variants like `"builder-2"` are not saved. On reconnect, the terminal always requests the preferred name, not the last runtime name.
563
-
564
- **Rename guards:**
565
-
566
- - If you're already using the requested name, `/link-name` returns early (`"Already using..."`).
567
- - On the hub, renaming checks if the name is taken by another connected client before accepting the change.
568
- - On a client, the rename triggers a reconnect; the hub enforces uniqueness during re-registration and may assign a different name if taken.
569
-
570
- **Unregistered client guard:** The hub ignores all non-`register` messages from clients that haven't completed registration, preventing protocol violations from malformed or out-of-order messages.
571
-
572
- ### State Management
573
-
574
- | State Field | Type | Purpose |
575
- | ------------------------ | ------------------------------------- | ------------------------------------------------------------------------------------------- |
576
- | `role` | `"hub" \| "client" \| "disconnected"` | Current network role |
577
- | `agentRunning` | `boolean` | Whether an agent run is active; blocks incoming remote prompts |
578
- | `activeToolName` | `string \| null` | Name of the currently executing tool (drives `tool:<name>` status) |
579
- | `stateSince` | `number` | Timestamp of last status change (used for duration display) |
580
- | `currentCwd` | `string` | Current working directory reported to peers on connect |
581
- | `inbox` | `array` | Queued `triggerTurn:true` messages awaiting idle-gated flush |
582
- | `flushTimer` | `Timer \| null` | Pending inbox flush (debounce or busy-retry) |
583
- | `disposed` | `boolean` | Set on `session_shutdown`; guards all WebSocket callbacks against stale context |
584
- | `startupConnectTimer` | `Timer \| null` | Deferred startup connect (`setTimeout(0)`) so Pi's startup cycle completes first |
585
- | `manuallyDisconnected` | `boolean` | Set by `/link-disconnect`; suppresses auto-reconnect |
586
- | `pendingRemotePrompt` | `object \| null` | Tracks the single in-flight remote prompt execution |
587
- | `pendingPromptResponses` | `Map` | Outstanding prompt RPCs awaiting responses (includes inactivity + ceiling timers per entry) |
588
-
589
- ### Message Routing & Error Handling
590
-
591
- `routeMessage()` returns a `boolean` indicating delivery status:
592
-
593
- - **Hub** - delivery is authoritative. If the target terminal isn't connected, the hub sends a protocol-level error back to the sender. For `prompt_request` messages to unknown targets, the hub sends a `prompt_response` with an error field so the sender's pending promise resolves immediately rather than timing out.
594
- - **Client** - delivery is optimistic (`true` means "sent to hub"). The hub handles routing and errors via the protocol.
595
-
596
- ### Connection Lifecycle
597
-
598
- Internally, teardown is split into two functions:
599
-
600
- - **`disconnect()`** - closes sockets, clears connection state, resolves pending promises. Used by `/link-disconnect` and called internally by `cleanup()`.
601
- - **`cleanup()`** - calls `disconnect()`, sets `disposed = true`, clears `ctx`. Used on `session_shutdown`.
602
-
603
- Three helpers protect WebSocket callbacks from stale extension context:
604
-
605
- - **`getUi()`** - safely accesses `ctx.ui`, returns `null` if the context is invalidated.
606
- - **`notify()`** - wraps `getUi()?.notify()` for safe notification delivery.
607
- - **`isRuntimeLive()`** - returns `false` if `disposed` or context is stale; checked before processing any incoming WebSocket message.
608
-
609
- Startup connect is deferred via `scheduleStartupConnect()` (`setTimeout(0)`) so Pi's startup cycle completes and the extension context is fully valid before WebSocket work begins.
610
-
611
- The `manuallyDisconnected` flag distinguishes user-initiated disconnects (`/link-disconnect`) from connection loss. When set, `scheduleReconnect()` is suppressed - the terminal stays offline until `/link-connect` is explicitly called.
612
-
613
- ### Agent Lifecycle Integration
614
-
615
- The extension hooks into Pi's agent lifecycle events:
616
-
617
- - **`agent_start`** → Sets `agentRunning = true`, blocking incoming remote prompts. Broadcasts `status_update` (`thinking`).
618
- - **`agent_end`** → Wakes up the inbox flush (idle-gated delivery for `triggerTurn:true` messages). Checks if a remote prompt was running; if so, extracts the last assistant response from `event.messages` and sends back a `prompt_response`. Broadcasts `status_update` (`idle`).
619
- - **`tool_execution_start`** → Broadcasts `status_update` (`tool:<name>`).
620
- - **`tool_execution_end`** → Clears tool status; broadcasts `status_update` (`thinking`) while the agent run continues.
621
- - **`session_shutdown`** → Full cleanup via `cleanup()`: closes all sockets, resolves pending promises, and disposes the extension.
622
-
623
- Status updates are push-based: each terminal broadcasts changes to the hub, which fans them out. New joiners receive a status snapshot for all terminals in the `welcome` message.
624
-
625
- While executing a remote prompt, the target sends a forced `status_update` every 30 seconds as a keepalive - reusing the existing status push mechanism. On the sender side, each incoming `status_update` from the target resets the 90-second inactivity timer. All resolution paths (response, inactivity, ceiling, abort, disconnect, delivery failure) go through a single `cleanupPending()` helper to prevent double-resolution races.
626
-
627
- ### Idle-Gated Inbox
628
-
629
- When a `chat` message arrives with `triggerTurn:true`, it goes into a local inbox instead of calling `pi.sendMessage()` immediately. This avoids a Pi platform race where steering messages sent mid-agent-run can be stranded (see `REPORT-sendMessage-race.md`).
630
-
631
- The flush pipeline:
632
-
633
- 1. **Debounce** - `scheduleFlush(FLUSH_DELAY_MS)` coalesces burst arrivals (200ms window).
634
- 2. **Idle gate** - `flushInbox()` checks `ctx.isIdle()`. If busy, retries every 500ms.
635
- 3. **Batch** - up to 20 messages or ~16 000 chars per delivery (soft cap - the first item is always included even if oversized).
636
- 4. **Deliver** - one `pi.sendMessage({ triggerTurn: true })` call with a `[Link: N message(s) received]` block.
637
- 5. **Drain** - if the inbox still has items, reschedule.
638
-
639
- On `agent_end`, the inbox flush is kicked via `scheduleFlush(0)` - deferred to the next macrotask, by which time `ctx.isIdle()` returns `true`.
640
-
641
- | Constant | Value | Purpose |
642
- | ----------------- | ------ | ---------------------------------------- |
643
- | `FLUSH_DELAY_MS` | 200 | Burst debounce window |
644
- | `IDLE_RETRY_MS` | 500 | Busy-retry polling interval |
645
- | `BATCH_MAX_ITEMS` | 20 | Max messages per batch |
646
- | `BATCH_MAX_CHARS` | 16 000 | Soft cap on batch text size (~4K tokens) |
647
-
648
- ### Rendering
649
-
650
- Incoming link chat messages render with a styled `⚡ [sender]` prefix using the theme's accent color. The link status text in Pi's footer uses `theme.fg("dim", ...)` to match Pi's standard footer styling.
1
+ # pi-link
2
+
3
+ A WebSocket-based inter-terminal communication system that creates a local network between multiple Pi coding agent terminals. Enables terminals to discover each other, exchange messages, and orchestrate work across agents - all automatically on `localhost`.
4
+
5
+ > Three patterns out of the box: ask another agent for an answer (`link_prompt`), delegate async work (`link_send` with `triggerTurn:true`), or broadcast to every other terminal (`/link-broadcast`). Start two Pi terminals with `--link` — they find each other automatically.
6
+
7
+ ---
8
+
9
+ ## Table of Contents
10
+
11
+ - [Why?](#why)
12
+ - [Prerequisites](#prerequisites)
13
+ - [Quick Start](#quick-start)
14
+ - [Walkthrough](#walkthrough)
15
+ - [Configuration](#configuration)
16
+ - [LLM Tools](#llm-tools)
17
+ - [Slash Commands](#slash-commands)
18
+ - [Architecture](#architecture)
19
+ - [Troubleshooting](#troubleshooting)
20
+ - [Limitations & Design Decisions](#limitations--design-decisions)
21
+ - [Dependencies](#dependencies)
22
+ - [Internals](#internals)
23
+
24
+ ---
25
+
26
+ ## Why?
27
+
28
+ A single Pi terminal is powerful. Multiple terminals working together unlock new patterns:
29
+
30
+ - **Research + Build** - one terminal investigates APIs, docs, or logs while another writes code based on the findings.
31
+ - **Fan-out** - split a large task across agents (e.g., "terminal A handles the backend, terminal B handles the frontend") and collect results.
32
+ - **Orchestrator / Worker** - designate one terminal as a coordinator that delegates subtasks to others via `link_prompt` and assembles the final output.
33
+ - **Review pipeline** - one terminal writes code, another reviews it, back and forth until both are satisfied.
34
+
35
+ ---
36
+
37
+ ## Prerequisites
38
+
39
+ - [Pi coding agent](https://github.com/badlogic/pi-mono), version **0.74 or later** (for pi-link 0.1.15+). On Pi ≤0.73, pin `pi-link@0.1.14`.
40
+ - Node.js (LTS recommended)
41
+
42
+ ---
43
+
44
+ ## Quick Start
45
+
46
+ ### Install
47
+
48
+ The minimum install — enables every in-Pi feature (`/link`, `link_send`, `link_prompt`, `/link-connect`, `--link` flag, auto-resume, all LLM tools):
49
+
50
+ ```bash
51
+ pi install npm:pi-link
52
+ ```
53
+
54
+ That's it. For most users this is all you need.
55
+
56
+ #### Optional: shell launcher
57
+
58
+ If you also want the `pi-link <name>` shell command to start named sessions from a terminal prompt (e.g. `pi-link builder` in one window, `pi-link reviewer` in another), install the CLI globally as well:
59
+
60
+ ```bash
61
+ npm i -g pi-link
62
+ ```
63
+
64
+ Or install both in one line:
65
+
66
+ ```bash
67
+ pi install npm:pi-link && npm i -g pi-link
68
+ ```
69
+
70
+ The shell launcher is convenience-only — you can always reach the same functionality from inside Pi via `/link-connect` and `/link-name <name>`.
71
+
72
+ ### Uninstall
73
+
74
+ ```bash
75
+ pi uninstall npm:pi-link # Remove Pi extension
76
+ npm uninstall -g pi-link # Remove CLI launcher (if you installed it)
77
+ ```
78
+
79
+ ### Usage
80
+
81
+ Link is **off by default**. Two ways to start:
82
+
83
+ ```bash
84
+ pi --link # try it now, random name like t-a3f9
85
+ pi-link mybot # named session you can resume by name
86
+ ```
87
+
88
+ Already in a session? Use `/link-connect`. Use `/link` any time to check status, or let the LLM tools handle cross-terminal coordination. See [Session Resume](#session-resume) for `pi-link <name>` details.
89
+
90
+ ### Notes on installation
91
+
92
+ **Why two installs?** Pi 0.75 installs Pi packages into a private npm root (`~/.pi/agent/npm/`) for safer permission handling ([pi-mono#4587](https://github.com/earendil-works/pi-mono/issues/4587)). That's where the Pi extension lives, but it means the `pi-link` shell command is no longer on system PATH. `npm i -g pi-link` puts it on PATH separately. Both installs are safe to use together.
93
+
94
+ ---
95
+
96
+ ## Walkthrough
97
+
98
+ Here's a concrete example of two terminals collaborating. Open two separate `pi --link` sessions.
99
+
100
+ **Terminal 1** - rename and check status:
101
+
102
+ ```
103
+ > /link-name builder
104
+ ✓ Renamed to "builder"
105
+
106
+ > /link
107
+ ⚡ Link: builder (hub) · 2 online
108
+ builder: idle (5s) · 45K/272K (17%)
109
+ cwd: ~/my-project
110
+ researcher: idle (12s) · 80K/272K (29%)
111
+ cwd: ~/my-project
112
+ ```
113
+
114
+ **Terminal 2** - rename it too:
115
+
116
+ ```
117
+ > /link-name researcher
118
+ ✓ Reconnecting, requesting "researcher" (hub may assign a different name if taken)...
119
+ ```
120
+
121
+ **Now ask Terminal 1's LLM to delegate work:**
122
+
123
+ In Terminal 1, type a normal prompt:
124
+
125
+ ```
126
+ > Use link_prompt to ask "researcher" to summarize the contents of README.md in this directory
127
+ ```
128
+
129
+ The LLM in Terminal 1 calls `link_prompt` → Terminal 2's LLM receives the prompt, reads the file, and sends back a summary → Terminal 1's LLM presents the result to you.
130
+
131
+ **Or broadcast a message to all terminals:**
132
+
133
+ ```
134
+ > /link-broadcast starting the deployment pipeline
135
+ ✓ Broadcast sent
136
+ ```
137
+
138
+ Every other terminal sees:
139
+
140
+ ```
141
+ ⚡ [builder] starting the deployment pipeline
142
+ ```
143
+
144
+ ---
145
+
146
+ ## Configuration
147
+
148
+ Link is **off by default**. Without `--link`, `--link-name`, or `pi-link`, the extension is completely silent — no status bar, no connections, no warnings.
149
+
150
+ **Naming concepts**
151
+
152
+ - **link name** — identity used on the network (visible in `link_list`, `/link`, prompts).
153
+ - **Pi session name** — identity Pi gives the session itself; lives in the session JSONL's latest `session_info` entry.
154
+ - **saved link name** — the link name persisted to the session, restored on resume. Set by `/link-name`, `pi-link <name>`, or `pi --link-name <name>`.
155
+ - **`--link-name` flag vs `/link-name` command** — same concept (the link name) at different times (startup vs mid-session).
156
+
157
+ | What you want | Use |
158
+ | ------------------------------------ | ----------------------- |
159
+ | Resume/create a named session | `pi-link <name>` |
160
+ | Stable link identity, normal Pi flow | `pi --link-name <name>` |
161
+ | Quick try, random name | `pi --link` |
162
+ | Already in a session | `/link-connect` |
163
+ | Disconnect mid-session | `/link-disconnect` |
164
+
165
+ `pi-link <name>` resumes/creates a session AND sets your link identity in one step. `pi --link-name <name>` sets only the link identity, leaving Pi's normal session selection (latest in cwd, or fresh) untouched.
166
+
167
+ **Name normalization:** Link names are normalized — leading/trailing whitespace removed and internal whitespace runs collapsed to a single space. `/link-name "build lead"` saves and shows as `build lead`.
168
+
169
+ **Name precedence:** `pi --link-name` > `pi-link <name>` > saved `/link-name` > Pi session name > random `t-xxxx`. _(The `pi-link` wrapper itself does not accept `--link-name`; pick one or the other.)_
170
+
171
+ `/link-connect` and `/link-disconnect` save their intent to the session — resume later and the connection state is restored without needing the flag. Explicit user intent takes precedence over `--link`.
172
+
173
+ Once connected, terminals discover each other on `127.0.0.1:9900`. See [Limitations](#limitations--design-decisions) for the hardcoded port.
174
+
175
+ ### Session Resume
176
+
177
+ Pi's `--session` flag requires a file path, not a display name. `pi-link` bridges this — it resolves a session by name and launches Pi directly:
178
+
179
+ ```bash
180
+ pi-link worker-1 # resume or create session "worker-1"
181
+ pi-link worker-1 --model sonnet # with extra Pi flags
182
+ ```
183
+
184
+ How it works: `pi-link worker-1` scans Pi's session directory, finds the session named "worker-1", and spawns `pi --session <path> --link`. Session-dir resolution matches Pi's lookup order: `PI_CODING_AGENT_SESSION_DIR` env > `<cwd>/.pi/settings.json` `sessionDir` > `<agentDir>/settings.json` `sessionDir` > default `<agentDir>/sessions/`. `<agentDir>` follows `PI_CODING_AGENT_DIR` and defaults to `~/.pi/agent/`.
185
+
186
+ Lookup is **scoped to the current cwd by default**; pass `--global` (`-g`) to consider sessions in any cwd.
187
+
188
+ - **One match in scope** → resumes that session
189
+ - **No match in scope** → creates a new session in the current cwd. If matches exist outside the scope, prints a hint pointing at `--global`.
190
+ - **Multiple matches in scope** → prints candidates to stderr, exits 1
191
+ - **Conflicting flags** (`--session`, `--continue`, `--resume`, `--fork`, etc.) → rejected with an error
192
+
193
+ ### Discovering sessions
194
+
195
+ `pi-link --list` shows pi-link sessions in the current cwd; `pi-link --list --global` (or `-g`) lists them across all directories. Sorted by last activity — starting a session with the same name it already has does not bump recency; only real activity (messages, tool calls, edits, name changes) does.
196
+
197
+ ```
198
+ $ pi-link --list
199
+ NAME MODIFIED MESSAGES ID
200
+ opus@pi-link 2m ago 4632 6332faab
201
+ gpt@pi-link 5m ago 1493 20d43841
202
+
203
+ Resume: pi-link <name>
204
+ ```
205
+
206
+ With `--global`:
207
+
208
+ ```
209
+ $ pi-link --list --global
210
+ NAME CWD MODIFIED MESSAGES ID
211
+ opus@pi-link ~/my-project 2m ago 4632 6332faab
212
+ gpt@pi-link ~/other-project 5m ago 1493 20d43841
213
+
214
+ Resume: pi-link <name>
215
+ ```
216
+
217
+ `--global` adds a `CWD` column with `~` substituted for `$HOME`. Output is plain when piped (`NO_COLOR` honored).
218
+
219
+ `pi-link <name>` and `pi-link --resolve <name>` follow the same scoping: local cwd by default, `--global` (or `-g`) widens. When `pi-link <name>` finds no local match but matches exist elsewhere, it warns and points at `--global` instead of silently jumping cwds.
220
+
221
+ For scripting, `pi-link --resolve <name>` prints just the session path (machine-readable, no other output). Exit codes: `0` on single match, `1` if ambiguous (multiple matches printed to stderr), `2` if not found.
222
+
223
+ > The legacy subcommand forms `pi-link list` and `pi-link resolve <name>` still work but print a stderr deprecation warning and will be removed in a future release. Switch to the flag forms above.
224
+
225
+ ---
226
+
227
+ ## LLM Tools
228
+
229
+ The extension registers four tools that the LLM can invoke during agent runs. pi-link also ships with a bundled **pi-link-coordination** skill that gives agents on-demand guidance for tool selection, delegation patterns, and avoiding common coordination mistakes.
230
+
231
+ ### Which tool should I use?
232
+
233
+ | Tool | Behavior | Returns |
234
+ | -------------- | ---------------------------------------------------- | --------------------------------------------------- |
235
+ | `link_send` | Send a message; optionally trigger the remote LLM | Send/delivery status only |
236
+ | `link_prompt` | Run a prompt on a remote terminal and wait for reply | The remote terminal's assistant response |
237
+ | `link_list` | List currently connected terminals | Terminal list with roles, status, cwd, and context |
238
+ | `link_compact` | Ask another terminal to compact its context window | Waits for completion; returns compacted or an error |
239
+
240
+ **If you need the other terminal's answer back, use `link_prompt`.** Use `link_send` to notify or steer without waiting.
241
+
242
+ ### `link_send`
243
+
244
+ Send a fire-and-forget chat message to a specific terminal or broadcast to all.
245
+
246
+ | Parameter | Type | Description |
247
+ | ------------- | --------- | ---------------------------------------------------- |
248
+ | `to` | `string` | Target terminal name, or `"*"` for broadcast |
249
+ | `message` | `string` | Message content |
250
+ | `triggerTurn` | `boolean` | If `true`, the receiver's LLM responds automatically |
251
+
252
+ When `triggerTurn` is enabled, the message is queued in the receiver's local inbox. Nearby arrivals are coalesced (200ms debounce), and delivery is gated on the receiving agent being idle - ensuring it starts a clean new turn. Messages arrive as a single `[Link: N message(s) received]` block at the top of a fresh turn, not mid-run. When `triggerTurn` is `false` or omitted, delivery is immediate fire-and-forget.
253
+
254
+ Note: `triggerTurn` does **not** cause the response to come back to the caller - use `link_prompt` for that.
255
+
256
+ > **Broadcast note:** Sending to `"*"` delivers to **all other terminals** - the sender is excluded.
257
+
258
+ Pre-validates the target name against the local terminal list before sending, catching typos early. See [Message Routing](#message-routing--error-handling) for delivery semantics.
259
+
260
+ ### `link_prompt`
261
+
262
+ Send a prompt to a remote terminal and **wait** for the LLM's response (synchronous RPC pattern).
263
+
264
+ | Parameter | Type | Description |
265
+ | --------- | -------- | -------------------- |
266
+ | `to` | `string` | Target terminal name |
267
+ | `prompt` | `string` | Prompt text to send |
268
+
269
+ - The remote terminal processes the prompt via `pi.sendUserMessage()` - as if a user typed it.
270
+ - Returns the remote terminal's actual assistant reply text as the tool result.
271
+ - **Self-target rejection** - prompting yourself (`to` equals your own name) returns an immediate error.
272
+ - **Heartbeat-based timeout** - no short fixed deadline. The target sends keepalives every 30s while working. The sender resets a 90-second inactivity timer on each keepalive. A 30-minute hard ceiling acts as a safety net against broken-but-chatty targets. A 10-minute task with regular activity never times out; a genuinely dead target times out in 90 seconds of silence.
273
+ - **Immediate failure on disconnect** - if the target leaves the network (`terminal_left`), pending prompts to that target fail immediately instead of waiting for the inactivity timeout.
274
+ - **Early failure detection** - if the message can't be delivered (e.g., target not found), the tool resolves immediately with an error instead of waiting for the timeout.
275
+ - Supports abort signals.
276
+ - Targets **one terminal at a time** (no broadcast mode).
277
+ - Only **one remote prompt** can execute at a time per target terminal. Concurrent requests are rejected with `"Terminal is busy"`.
278
+
279
+ ### `link_list`
280
+
281
+ Lists all connected terminals with role info, live agent status, working directory, context usage, and self-identification. Takes no parameters.
282
+
283
+ Each terminal reports its current working directory on connect. `link_list` shows the full absolute path so agents can choose the right target, use explicit paths when terminals differ, and catch wrong-project mistakes early.
284
+
285
+ Each terminal also reports its current LLM context usage, rendered as `45K/272K (17%)` — tokens used over the context window, with percent. Briefly after compaction it shows as `?/272K` until the next live token count arrives. Treat it as an advisory signal when choosing a worker; prefer a less-loaded terminal for context-heavy delegation.
286
+
287
+ Each terminal's status is derived automatically from Pi lifecycle events - agents can't set it manually. Three states:
288
+
289
+ | Status | Meaning |
290
+ | ----------------- | ----------------------- |
291
+ | `idle (2m)` | Waiting for user input |
292
+ | `thinking (3s)` | LLM is generating |
293
+ | `tool:bash (12s)` | Running a specific tool |
294
+
295
+ Durations are computed at render time from a `since` timestamp - no timer traffic over the wire. Terminals that just joined with no status data yet render as blank, not fake idle.
296
+
297
+ Working directories use full absolute paths in tool output. In the TUI (`/link`), paths are shortened to `~/...` when possible to keep the display compact.
298
+
299
+ **Example output:**
300
+
301
+ ```
302
+ Connected terminals:
303
+ • opus@pi-link (you) idle (12s) · 45K/272K (17%)
304
+ cwd: C:\Users\andre\.pi
305
+ • gpt@pi-link thinking (3s) · ?/272K
306
+ cwd: C:\Users\andre\.pi
307
+ • docs@pi-link idle (1m) · 90K/272K (33%)
308
+ cwd: C:\Users\andre\.pi
309
+ ```
310
+
311
+ ### `link_compact`
312
+
313
+ Ask another terminal to compact its context window and **wait** until it finishes — so the very next call can dispatch new work to the freshly trimmed worker without a busy bounce.
314
+
315
+ | Parameter | Type | Description |
316
+ | -------------- | -------- | ------------------------------------------------------ |
317
+ | `to` | `string` | Target terminal name |
318
+ | `instructions` | `string` | Optional custom compaction instructions for the target |
319
+
320
+ - The remote terminal runs `ctx.compact()` — the same code path as `/compact`. The call returns once the runtime reports completion.
321
+ - **Success** result: `Compacted "<name>"`. The worker is now idle with a trimmed context, ready for the next dispatch.
322
+ - **Busy decline** — if the target is mid-turn or already compacting, it declines immediately with `reason: "busy"`. `link_compact` will **not** interrupt active work; retry when `link_list` shows the worker idle.
323
+ - **Self-target rejection** — calling `link_compact` on yourself returns an error pointing at `/compact`.
324
+ - **Flat 180-second timeout** — compaction typically takes 5–60s; if the target stops responding mid-compaction the call resolves with a timeout error.
325
+ - Supports abort signals.
326
+ - Targets **one terminal at a time** (no broadcast mode). To compact several workers concurrently, issue parallel tool calls.
327
+ - **No consent or capability gate** — any connected terminal can request compaction on any other; link participants are cooperating peers.
328
+
329
+ ### Coordination recipes
330
+
331
+ The four tools compose into coordination shapes worth naming:
332
+
333
+ - **Fan-out** - split independent subtasks across several terminals with `link_send(triggerTurn: true)`, keep working, then synthesize the callbacks. Parallelizes work that doesn't share a sequence. If a worker's context (visible in `link_list`) runs high, `link_compact` trims it and returns when the worker is idle — feed it the next subtask immediately.
334
+ - **Adversarial review** - have one terminal produce or edit work, then `link_prompt` another to critique it. Because `link_prompt` blocks on a reply from a separate session, the critique lands in the same turn; feed it back or revise locally.
335
+ - **Independent cross-check** - send the same verification question to two terminals without sharing their answers, then reconcile - or ask a third to resolve disagreements. Separate contexts mean neither anchors on the other.
336
+
337
+ ---
338
+
339
+ ## Slash Commands
340
+
341
+ | Command | Purpose |
342
+ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------ |
343
+ | `/link` | Show link status (name, role, online count, agent status, context usage, and cwd per terminal) |
344
+ | `/link-name [name]` | Rename and save as this session's preferred link name. With no argument, adopts the Pi session name. Restored on resume. |
345
+ | `/link-broadcast <msg>` | Broadcast a chat message to all other terminals |
346
+ | `/link-connect` | Connect to Pi Link (works anytime, with or without `--link`) |
347
+ | `/link-disconnect` | Disconnect from Pi Link and suppress auto-reconnect (overrides `--link`) |
348
+
349
+ ### Examples
350
+
351
+ ```
352
+ > /link
353
+ ⚡ Link: builder (hub) · 3 online
354
+ builder: idle (12s) · 45K/272K (17%)
355
+ cwd: ~/my-project
356
+ worker-1: thinking (3s) · ?/272K
357
+ cwd: ~/my-project
358
+ worker-2: tool:bash (5s) · 180K/272K (66%)
359
+ cwd: ~/other-project
360
+
361
+ > /link-name orchestrator
362
+ ✓ Renamed to "orchestrator"
363
+
364
+ > /link-name
365
+ ✓ Renamed to "my-session"
366
+
367
+ > /link-broadcast starting the build pipeline
368
+ ✓ Broadcast sent
369
+
370
+ > /link-disconnect
371
+ ✓ Disconnected from link
372
+
373
+ > /link-connect
374
+ ✓ Joined link as "orchestrator" (3 online)
375
+ ```
376
+
377
+ With no argument, `/link-name` adopts the Pi session name. `/link-connect` joins an existing hub if one is running; otherwise it starts the hub.
378
+
379
+ **Name persistence:** `/link-name` saves your preferred name to the session. Resume later and it's restored automatically. If the name is taken, the hub assigns a variant (e.g., `"builder-2"`), but your preferred name stays saved for the next reconnect. See [Name Uniqueness & Persistence](#name-uniqueness--persistence) for details.
380
+
381
+ See [Configuration](#configuration) for details on `--link`, `/link-connect`, and `/link-disconnect` behavior.
382
+
383
+ ---
384
+
385
+ ## Architecture
386
+
387
+ ### Hub-Spoke Topology
388
+
389
+ The network topology is **hub-spoke (star)**:
390
+
391
+ ```
392
+ +-----------+
393
+ | Hub |
394
+ | :9900 |
395
+ +-----+-----+
396
+ |
397
+ +--------------+--------------+
398
+ | | |
399
+ +---+---+ +---+---+ +---+---+
400
+ | pi-2 | | pi-3 | | pi-4 |
401
+ |client | |client | |client |
402
+ +-------+ +-------+ +-------+
403
+ ```
404
+
405
+ - The **first terminal** to start becomes the **hub** - it runs a `WebSocketServer` on `127.0.0.1:9900`.
406
+ - **Subsequent terminals** connect as **clients** via plain WebSocket.
407
+ - All messages route **through the hub**; clients never talk directly to each other.
408
+
409
+ ### Auto-Discovery Protocol
410
+
411
+ The discovery sequence runs on startup (with `--link` or `pi-link`) or when `/link-connect` is used. See [Configuration](#configuration) for details.
412
+
413
+ The sequence is a simple fallback:
414
+
415
+ 1. Attempt to connect as a **client** to `127.0.0.1:9900`.
416
+ 2. If connection fails → become the **hub** (start a WebSocket server on that port).
417
+ 3. If both fail (rare race condition) → retry after a randomized 2-5 second backoff.
418
+
419
+ ### Hub Promotion
420
+
421
+ When the hub disconnects, clients detect the WebSocket close event, enter `"disconnected"` state, and call `scheduleReconnect()`. The **first terminal to retry** becomes the new hub via the same initialize-or-fallback flow.
422
+
423
+ There is **no explicit leader election** - promotion is race-based.
424
+
425
+ ---
426
+
427
+ ## Troubleshooting
428
+
429
+ ### Port 9900 is already in use
430
+
431
+ If another process occupies port 9900, the terminal can't become the hub. It will attempt to connect as a client instead (which also fails if there's no real hub), then retry after 2-5 seconds. Free the port or modify `DEFAULT_PORT` in `index.ts` - see [Limitations](#limitations--design-decisions).
432
+
433
+ ### "Terminal is busy" rejections
434
+
435
+ Each terminal handles **one remote operation at a time** — a local agent run, an incoming `link_prompt`, or a `link_compact` all block the others. If a `link_prompt` arrives while the terminal is busy, it's immediately rejected with `"Terminal is busy"`. There is no queuing. Solutions:
436
+
437
+ - Wait for the target terminal to finish its current task.
438
+ - Spread prompts across multiple worker terminals.
439
+ - Have the sender retry after a delay.
440
+
441
+ A `link_compact` to a busy target behaves the same way — the call resolves with `Compact on "<target>" not done: busy` instead of interrupting active work. Retry when `link_list` shows the worker idle.
442
+
443
+ ### Terminals don't see each other
444
+
445
+ - Verify both terminals are on the same machine (the link only works on `127.0.0.1`).
446
+ - Run `/link` in each terminal to check status.
447
+ - Ensure port 9900 isn't blocked or occupied by a non-link process.
448
+
449
+ ### Hub promotion loses state
450
+
451
+ When the hub goes down and a client promotes itself, terminal names and in-flight prompts from the old hub session are lost. All surviving clients reconnect and re-register. This is by design - see [Limitations](#limitations--design-decisions).
452
+
453
+ ---
454
+
455
+ ## Limitations & Design Decisions
456
+
457
+ | # | Decision | Rationale / Impact |
458
+ | --- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
459
+ | 1 | **No authentication** | Any localhost process can connect to port 9900. Acceptable for local dev; don't expose the port externally. |
460
+ | 2 | **Hardcoded port (9900)** | Not configurable without editing `DEFAULT_PORT` in `index.ts`. Could conflict with other services on the same port. |
461
+ | 3 | **Race-based hub promotion** | Non-deterministic. Terminal state (names, in-flight prompts) is lost during promotion. Simple but imperfect. |
462
+ | 4 | **Single remote prompt per terminal** | No queuing - immediate rejection if busy. See [`link_prompt`](#link_prompt) and [Troubleshooting](#terminal-is-busy-rejections). |
463
+ | 5 | **No message persistence** | Purely ephemeral WebSocket frames. Messages are lost if the recipient is offline. |
464
+ | 6 | **Client rename triggers full reconnect** | Changing a client's name requires a new `register` message, so the client disconnects and reconnects. Hub renames are handled in-place with collision checks. |
465
+ | 7 | **Single-machine / localhost-only** | Link only binds to `127.0.0.1`; terminals on different machines cannot join. |
466
+ | 8 | **Rename during prompt loses keepalives** | If the target renames mid-prompt, keepalive resets stop working (pending requests track by name). The final response can still succeed by request ID, but inactivity may false-fire on long tasks after rename. |
467
+
468
+ ---
469
+
470
+ ## Dependencies
471
+
472
+ ### Runtime (installed by `pi install`)
473
+
474
+ | Package | Version | Purpose |
475
+ | ------- | ------- | ----------------------------------- |
476
+ | `ws` | ^8.20.0 | WebSocket library (server + client) |
477
+
478
+ ### Development
479
+
480
+ | Package | Version | Purpose |
481
+ | ----------- | ------- | --------------------------- |
482
+ | `@types/ws` | ^8.18.1 | TypeScript type definitions |
483
+
484
+ ### Provided by Pi (no install needed)
485
+
486
+ | Package | Purpose |
487
+ | --------------------------------- | ------------------------------------------------ |
488
+ | `@earendil-works/pi-coding-agent` | Pi SDK types (ExtensionAPI, ExtensionContext) |
489
+ | `@earendil-works/pi-tui` | TUI Text widget for custom message rendering |
490
+ | `typebox` | JSON Schema type definitions for tool parameters |
491
+
492
+ > **Pi version requirement:** pi-link 0.1.15+ requires Pi 0.74 or later (the `@earendil-works/*` namespace). Users on Pi 0.73 or earlier should pin `pi-link@0.1.14`.
493
+
494
+ ### `package.json`
495
+
496
+ ```json
497
+ {
498
+ "name": "pi-link",
499
+ "bin": {
500
+ "pi-link": "./bin/pi-link.mjs"
501
+ },
502
+ "dependencies": {
503
+ "ws": "^8.20.0"
504
+ },
505
+ "devDependencies": {
506
+ "@types/ws": "^8.18.1"
507
+ },
508
+ "pi": {
509
+ "extensions": ["./index.ts"],
510
+ "skills": ["./skills"]
511
+ }
512
+ }
513
+ ```
514
+
515
+ `pi.extensions` tells Pi which files to load as extensions. `pi.skills` registers bundled skill directories. `bin` exposes the `pi-link` CLI (see [Configuration](#configuration)).
516
+
517
+ ---
518
+
519
+ ## Internals
520
+
521
+ > This section covers implementation details for contributors and developers who want to understand or modify the extension's internals.
522
+
523
+ ### Protocol
524
+
525
+ The wire protocol consists of **11 message types**, all serialized as JSON over WebSocket frames. Cwd and context fields are optional.
526
+
527
+ | Type | Direction | Purpose |
528
+ | ------------------ | --------------- | ----------------------------------------------------------------------------------- |
529
+ | `register` | Client → Hub | First message after connecting; requests a name, optionally reports cwd and context |
530
+ | `welcome` | Hub → Client | Confirms assigned name, terminal list + status/cwd/context snapshots |
531
+ | `terminal_joined` | Hub → All | Broadcast when a terminal joins; may include cwd and context |
532
+ | `terminal_left` | Hub → All | Broadcast when a terminal disconnects |
533
+ | `chat` | Any → Any/All | Fire-and-forget message; optionally triggers LLM turn |
534
+ | `prompt_request` | Any → Any | Request a remote terminal to execute a prompt |
535
+ | `prompt_response` | Any → Any | Response carrying the remote prompt result |
536
+ | `compact_request` | Any → Any | Request a remote terminal to compact its context; awaits a response |
537
+ | `compact_response` | Any → Any | Completion/failure response for a compact_request |
538
+ | `status_update` | Any → Hub → All | Terminal broadcasts agent status change; carries updated context |
539
+ | `error` | Hub → Client | Error notification |
540
+
541
+ ### Message Flow Examples
542
+
543
+ **Joining the link:**
544
+
545
+ ```
546
+ Client Hub
547
+ | |
548
+ | register {name:"builder", |
549
+ | cwd:"C:\\Users\\..."} |
550
+ |---------------------------->|
551
+ | |
552
+ | welcome {name, terminals, |
553
+ | statuses, cwds} |
554
+ |<----------------------------|
555
+ | |
556
+ ```
557
+
558
+ Hub then broadcasts `terminal_joined` to the other connected terminals. The `welcome` message includes status, cwd, and context snapshots for all connected terminals (fields omitted above for brevity). `terminal_joined` also includes the new terminal's optional cwd and context.
559
+
560
+ **Sending a chat message:**
561
+
562
+ ```
563
+ Client A Hub Client B
564
+ | | |
565
+ | chat {to:pi-2} | |
566
+ |----------------->| |
567
+ | | chat {from:A} |
568
+ | |----------------->|
569
+ | | |
570
+ ```
571
+
572
+ **Remote prompt (synchronous RPC):**
573
+
574
+ ```
575
+ Client A Hub Client B
576
+ | | |
577
+ | prompt_request | |
578
+ |----------------->| |
579
+ | | prompt_request |
580
+ | |----------------->|
581
+ | | (LLM runs) |
582
+ | |<-----------------|
583
+ | prompt_response | |
584
+ |<-----------------| |
585
+ ```
586
+
587
+ ### Name Uniqueness & Persistence
588
+
589
+ The hub enforces unique terminal names via a `uniqueName()` function. If `"builder"` is already taken, the next terminal requesting that name is assigned `"builder-2"`, then `"builder-3"`, and so on.
590
+
591
+ Default names are random 4-character hex IDs: `t-a1b2`, `t-c3d4`, etc.
592
+
593
+ **Persistence:** `/link-name` saves the preferred name to the session via `pi.appendEntry("link-name", { name })`. On session resume, the saved name is restored and requested from the hub. Only explicit `/link-name` calls persist - hub-assigned variants like `"builder-2"` are not saved. On reconnect, the terminal always requests the preferred name, not the last runtime name.
594
+
595
+ **Rename guards:**
596
+
597
+ - If you're already using the requested name, `/link-name` returns early (`"Already using..."`).
598
+ - On the hub, renaming checks if the name is taken by another connected client before accepting the change.
599
+ - On a client, the rename triggers a reconnect; the hub enforces uniqueness during re-registration and may assign a different name if taken.
600
+
601
+ **Unregistered client guard:** The hub ignores all non-`register` messages from clients that haven't completed registration, preventing protocol violations from malformed or out-of-order messages.
602
+
603
+ ### State Management
604
+
605
+ | State Field | Type | Purpose |
606
+ | ------------------------ | ------------------------------------- | ------------------------------------------------------------------------------------------- |
607
+ | `role` | `"hub" \| "client" \| "disconnected"` | Current network role |
608
+ | `agentRunning` | `boolean` | Whether an agent run is active; blocks incoming remote prompts |
609
+ | `activeToolName` | `string \| null` | Name of the currently executing tool (drives `tool:<name>` status) |
610
+ | `stateSince` | `number` | Timestamp of last status change (used for duration display) |
611
+ | `currentCwd` | `string` | Current working directory reported to peers on connect |
612
+ | `inbox` | `array` | Queued `triggerTurn:true` messages awaiting idle-gated flush |
613
+ | `flushTimer` | `Timer \| null` | Pending inbox flush (debounce or busy-retry) |
614
+ | `disposed` | `boolean` | Set on `session_shutdown`; guards all WebSocket callbacks against stale context |
615
+ | `startupConnectTimer` | `Timer \| null` | Deferred startup connect (`setTimeout(0)`) so Pi's startup cycle completes first |
616
+ | `manuallyDisconnected` | `boolean` | Set by `/link-disconnect`; suppresses auto-reconnect |
617
+ | `pendingRemotePrompt` | `object \| null` | Tracks the single in-flight remote prompt execution |
618
+ | `pendingPromptResponses` | `Map` | Outstanding prompt RPCs awaiting responses (includes inactivity + ceiling timers per entry) |
619
+
620
+ ### Message Routing & Error Handling
621
+
622
+ `routeMessage()` returns a `boolean` indicating delivery status:
623
+
624
+ - **Hub** - delivery is authoritative. If the target terminal isn't connected, the hub sends a protocol-level error back to the sender. For `prompt_request` messages to unknown targets, the hub sends a `prompt_response` with an error field so the sender's pending promise resolves immediately rather than timing out. Likewise, a `compact_request` to an unknown target gets a synthesized `compact_response` (`ok: false`, `reason: "not_found"`), so a remote-compact call fails fast instead of waiting out its 180-second timeout.
625
+ - **Client** - delivery is optimistic (`true` means "sent to hub"). The hub handles routing and errors via the protocol.
626
+
627
+ ### Connection Lifecycle
628
+
629
+ Internally, teardown is split into two functions:
630
+
631
+ - **`disconnect()`** - closes sockets, clears connection state, resolves pending promises. Used by `/link-disconnect` and called internally by `cleanup()`.
632
+ - **`cleanup()`** - calls `disconnect()`, sets `disposed = true`, clears `ctx`. Used on `session_shutdown`.
633
+
634
+ Three helpers protect WebSocket callbacks from stale extension context:
635
+
636
+ - **`getUi()`** - safely accesses `ctx.ui`, returns `null` if the context is invalidated.
637
+ - **`notify()`** - wraps `getUi()?.notify()` for safe notification delivery.
638
+ - **`isRuntimeLive()`** - returns `false` if `disposed` or context is stale; checked before processing any incoming WebSocket message.
639
+
640
+ Startup connect is deferred via `scheduleStartupConnect()` (`setTimeout(0)`) so Pi's startup cycle completes and the extension context is fully valid before WebSocket work begins.
641
+
642
+ The `manuallyDisconnected` flag distinguishes user-initiated disconnects (`/link-disconnect`) from connection loss. When set, `scheduleReconnect()` is suppressed - the terminal stays offline until `/link-connect` is explicitly called.
643
+
644
+ ### Agent Lifecycle Integration
645
+
646
+ The extension hooks into Pi's agent lifecycle events:
647
+
648
+ - **`agent_start`** → Sets `agentRunning = true`, blocking incoming remote prompts. Broadcasts `status_update` (`thinking`).
649
+ - **`agent_end`** → Wakes up the inbox flush (idle-gated delivery for `triggerTurn:true` messages). Checks if a remote prompt was running; if so, extracts the last assistant response from `event.messages` and sends back a `prompt_response`. Broadcasts `status_update` (`idle`).
650
+ - **`tool_execution_start`** → Broadcasts `status_update` (`tool:<name>`).
651
+ - **`tool_execution_end`** → Clears tool status; broadcasts `status_update` (`thinking`) while the agent run continues.
652
+ - **`session_compact`** → Force-pushes a `status_update` so peers see the new (post-compaction) context usage immediately.
653
+ - **`session_shutdown`** → Full cleanup via `cleanup()`: closes all sockets, resolves pending promises, and disposes the extension.
654
+
655
+ Status updates are push-based: each terminal broadcasts changes to the hub, which fans them out. New joiners receive a status snapshot for all terminals in the `welcome` message.
656
+
657
+ While executing a remote prompt, the target sends a forced `status_update` every 30 seconds as a keepalive - reusing the existing status push mechanism. On the sender side, each incoming `status_update` from the target resets the 90-second inactivity timer. All resolution paths (response, inactivity, ceiling, abort, disconnect, delivery failure) go through a single `cleanupPending()` helper to prevent double-resolution races.
658
+
659
+ ### Idle-Gated Inbox
660
+
661
+ When a `chat` message arrives with `triggerTurn:true`, it goes into a local inbox instead of calling `pi.sendMessage()` immediately. This avoids a Pi platform race where steering messages sent mid-agent-run can be stranded (see `REPORT-sendMessage-race.md`).
662
+
663
+ The flush pipeline:
664
+
665
+ 1. **Debounce** - `scheduleFlush(FLUSH_DELAY_MS)` coalesces burst arrivals (200ms window).
666
+ 2. **Idle gate** - `flushInbox()` checks `ctx.isIdle()`. If busy, retries every 500ms.
667
+ 3. **Batch** - up to 20 messages or ~16 000 chars per delivery (soft cap - the first item is always included even if oversized).
668
+ 4. **Deliver** - one `pi.sendMessage({ triggerTurn: true })` call with a `[Link: N message(s) received]` block.
669
+ 5. **Drain** - if the inbox still has items, reschedule.
670
+
671
+ On `agent_end`, the inbox flush is kicked via `scheduleFlush(0)` - deferred to the next macrotask, by which time `ctx.isIdle()` returns `true`.
672
+
673
+ | Constant | Value | Purpose |
674
+ | ----------------- | ------ | ---------------------------------------- |
675
+ | `FLUSH_DELAY_MS` | 200 | Burst debounce window |
676
+ | `IDLE_RETRY_MS` | 500 | Busy-retry polling interval |
677
+ | `BATCH_MAX_ITEMS` | 20 | Max messages per batch |
678
+ | `BATCH_MAX_CHARS` | 16 000 | Soft cap on batch text size (~4K tokens) |
679
+
680
+ ### Rendering
681
+
682
+ Incoming link chat messages render with a styled `⚡ [sender]` prefix using the theme's accent color. The link status text in Pi's footer uses `theme.fg("dim", ...)` to match Pi's standard footer styling.