pi-link 0.6.0 → 0.7.0

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/CHANGELOG.md CHANGED
@@ -6,6 +6,48 @@ This changelog is based on the git history from `2026-03-21` (initial commit) th
6
6
 
7
7
  ---
8
8
 
9
+ ## 0.7.0 — 2026-11-16
10
+
11
+ ### Added
12
+
13
+ - **Tab completion for `/link-name` groups.** While connected, press Tab after `@` to choose from every group with a terminal currently on the link, excluding the implicit group of plain names. Choices are sorted and narrowed by the group prefix you type; the local part of your name is preserved.
14
+
15
+ ### Changed
16
+
17
+ - **Pi 0.85.0 or later is required.** The local compaction gate now relies on `ctx.isIdle()` covering Pi's own compactions, which earlier versions did not. There is no compatibility fallback; on Pi 0.84.2–0.84.4, pin `pi-link@0.6.1`.
18
+
19
+ ### Fixed
20
+
21
+ - **Failed or cancelled manual compactions release held messages when Pi becomes idle.** A separate 500 ms check clears the local gate once Pi reports idle; status and normal inbox batching recover when no remote gate remains. The five-minute fallback is removed: elapsed time no longer releases a compaction that still reports busy. The check survives `/link-disconnect` and stops at shutdown; remote outcomes still come only from their result callbacks. See the README's Inbox section for the known Pi 1.5.2 limitation when another extension handles compaction failures.
22
+
23
+ - **Warn once when the link can neither join nor host.** The first double failure of an outage shows the listen error and says pi-link keeps retrying. Further failed retries stay quiet until a connection is established or `/link-disconnect` is used. Cancelled or superseded attempts show no warning; retry timing and election order are unchanged.
24
+
25
+ - **Disconnect keeps a running remote compaction's inbox held.** `/link-disconnect` no longer clears `compactRunning` before the compaction reports its result, so a held batch cannot start a turn during the window before `session_before_compact`. Waiting requests are still dropped on disconnect; session shutdown still discards the inbox.
26
+
27
+ ---
28
+
29
+ ## 0.6.1 — 2026-11-02
30
+
31
+ ### Fixed
32
+
33
+ - **✗ for host errors in `link_send` and `link_compact` results.** When the host rejects a call before pi-link runs it, such as a failed argument validation, a blocked call or an abort, or when the call throws, the result row now shows ✗ instead of ✓. Pi marks these errors in the render context, and Oh My Pi in the result (from source reading; not tested under Oh My Pi). pi-link's own errors keep ✗ and successes keep ✓. Only the icon changes: results, the wire and the skill are unchanged.
34
+
35
+ - **`pi-link <name>` rejects `--session-id`.** Pi's `--session-id` opens or creates a session by ID, so it passed through and either failed against the `--session` the wrapper adds or bypassed the lookup by name under the link name `<name>`. It now fails like the other session flags, with `Error: --session-id is managed by pi-link. Remove it.`
36
+
37
+ - **`pi-link <name> --` no longer lets session and link-name flags through.** The wrapper drops its own `--` and passes the rest to Pi, so a flag after it, such as `pi-link foo -- --session-id abc`, still reached Pi as a flag and bypassed the session lookup or the link name. Tokens after `--` are now refused like the ones before it, in any position, including after Pi's own `--`, because the wrapper cannot tell where Pi's options end. A prompt that only begins with a flag name, as in `pi-link foo -- -- "--session-id explained"`, still passes.
38
+
39
+ - **The CLI reads a `settings.json` that starts with a BOM.** `pi-link` ignored such a file with a warning and dropped its `sessionDir`, while Pi strips the BOM and uses it, so `--list`, `--resolve` and `pi-link <name>` could look in the default directory instead of Pi's. It now drops one leading BOM before parsing, as Pi does; a file that is still invalid JSON keeps the warning and is ignored.
40
+
41
+ ### Changed
42
+
43
+ - **A target no longer answers `unsupported`.** The `compact_request` branch that declined with it when the target had no context or no compaction capability was unreachable on every supported host, and is removed. A requester still reads `unsupported` from a target on an earlier version as `not done: compaction unavailable on target`.
44
+
45
+ - **Consistent CLI messages.** `pi-link --help`, `-h` and `pi-link` with no arguments now print the usage to stdout, as Pi does, so it can be piped or saved; exit codes are unchanged. The settings warning reads `Warning: Ignored <path>: <reason>` instead of `pi-link: ignored <path>: <reason>`. Prose after `Error: ` or `Warning: ` starts with a capital letter unless it begins with a literal token such as a flag, a quoted command or `pi-link`, as in `Error: Cannot combine --list and --resolve.`; sentences end with a period, and commands embedded in prose use double quotes, as in `"pi-link list" was removed. Use "pi-link --list".` The `--link-name` rejection now reads `Error: --link-name is not accepted by pi-link.` and points to `pi-link <name>` to open the named session on the link, or `pi --link-name <name>` to set only the link name.
46
+
47
+ - **Consistent extension messages.** The `link_compact` self-target result reads `Cannot compact yourself`, without a period, like `link_send`'s `Cannot send to yourself`; `/link` when disconnected warns `Not connected to the link`, the text the tools return, instead of `Link: not connected`.
48
+
49
+ ---
50
+
9
51
  ## 0.6.0 — 2026-10-25
10
52
 
11
53
  ### Changed
package/README.md CHANGED
@@ -31,7 +31,7 @@ Questions, ideas? There's a [pi-link thread](https://discord.com/channels/145680
31
31
 
32
32
  ## Prerequisites
33
33
 
34
- - [Pi coding agent](https://github.com/badlogic/pi-mono), version **0.84.2 or later** (for pi-link 0.3+), stable releases only, reported as `x.y.z` without a prerelease or build suffix. On Pi 0.74–0.84.1, pin `pi-link@0.2.x`; on Pi ≤0.73, pin `pi-link@0.1.14`.
34
+ - [Pi coding agent](https://github.com/badlogic/pi-mono), version **0.85.0 or later**, stable releases only, reported as `x.y.z` without a prerelease or build suffix. On Pi 0.84.2–0.84.4, pin `pi-link@0.6.1`; on Pi 0.74–0.84.1, pin `pi-link@0.2.x`; on Pi ≤0.73, pin `pi-link@0.1.14`.
35
35
  - Node.js (LTS recommended)
36
36
 
37
37
  Pi's package installation does not check the host version, so `pi install` succeeds on an older Pi. pi-link then refuses to initialize instead of half-running: it throws before registering anything, and Pi reports it under **[Extension issues]** with the required minimum and the version it detected.
@@ -134,6 +134,8 @@ Terminal 1 calls `link_send` and returns immediately. The message enters Termina
134
134
 
135
135
  With two projects open, you may not want their terminals to see each other. Put a group after `@` in the name — `pi --link-name builder@frontend`, or `/link-name builder@frontend` from inside — and that terminal lists, messages and compacts only names ending in the same `@frontend`; a plain `builder` elsewhere no longer appears. The hub still serves everyone, and `pi-link --status` shows all groups. Full rule under [Configuration](#configuration).
136
136
 
137
+ Type `/link-name builder@` and press Tab to complete the group. The choices include every group with a terminal currently connected, not just your own; the implicit group of plain names is omitted. Type part of the group after `@` to narrow the choices. Completion needs a link connection.
138
+
137
139
  ---
138
140
 
139
141
  ## LLM Tools
@@ -243,7 +245,7 @@ The tool's parameters are:
243
245
  - **Success** — `compacted`. Compaction finished, but this does not reserve the target: it may be busy again by the next request.
244
246
  - **Already requested** — `not done: target already has a compaction request waiting or running`. A target holds one request at a time, from any requester; another one is declined rather than queued, merged or allowed to replace it.
245
247
  - **Navigation** — `not done: target navigated its session tree while the request waited`. Completing a `/tree` navigation on the target ends a request that has not started. A running compaction is unaffected, and other session changes, such as new messages or a session rename, end nothing.
246
- - **Other declines or errors** — `not done: compaction unavailable on target` if the target has no compaction available when the request arrives, or `not done: target not found` if the target cannot be found when the request is routed. The wire carries the codes `already_requested`, `tree_navigated`, `unsupported` and `not_found`; the requester shows them as this text. Pi may report a reason such as `Nothing to compact (session too small)` or `Already compacted`; runtime errors and cancellations also appear after `not done: `.
248
+ - **Other declines or errors** — `not done: target not found` if the target cannot be found when the request is routed. The wire carries the codes `already_requested`, `tree_navigated`, `not_found` and `unsupported`; the requester shows them as this text, and `unsupported`, which only earlier versions send, as `not done: compaction unavailable on target`. Pi may report a reason such as `Nothing to compact (session too small)` or `Already compacted`; runtime errors and cancellations also appear after `not done: `.
247
249
  - **Earlier target** — `not done: target busy`. A target on an earlier pi-link version declines at once while busy instead of waiting.
248
250
  - **Departure** — `left the link before answering; result unknown`. The target may or may not have compacted. A target that disconnects or ends its session drops a request it has not started, so this is also how such a request ends.
249
251
  - **Disconnect** — `/link-disconnect` in the requesting terminal reports outstanding requests as `link disconnected before an answer; result unknown, the target may still be compacting`.
@@ -263,7 +265,7 @@ For the tool-result fields and implementation behind these behaviors, see [Remot
263
265
  | Command | Purpose |
264
266
  | ------------------- | ------------------------------------------------------------------------------------------------------------------------ |
265
267
  | `/link` | Show link status (name, role, online count, agent status, context usage, and cwd per terminal) |
266
- | `/link-name [name]` | Rename and save as this session's preferred link name. With no argument, adopts the Pi session name. Restored on resume. A name with `@` also sets your group. |
268
+ | `/link-name [name]` | Rename and save as this session's preferred link name. With no argument, adopts the Pi session name. Restored on resume. A name with `@` also sets your group; while connected, Tab after `@` completes groups. |
267
269
  | `/link-connect` | Connect to Pi Link (works anytime, with or without `--link`) |
268
270
  | `/link-disconnect` | Disconnect from Pi Link and suppress auto-reconnect (overrides `--link`) |
269
271
 
@@ -350,7 +352,7 @@ Lookup is **scoped to the current cwd by default**; pass `--global` (`-g`) to co
350
352
  - **One match in scope** → resumes that session
351
353
  - **No match in scope** → creates a new session in the current cwd, and advises `--global` without claiming a session exists elsewhere.
352
354
  - **Multiple matches in scope** → prints candidates to stderr, exits 1
353
- - **Conflicting flags** (`--session`, `--continue`, `--resume`, `--fork`, etc.) → rejected with an error
355
+ - **Conflicting flags** (`--session`, `--session-id`, `--continue`, `--resume`, `--fork`, etc.) → rejected with an error
354
356
 
355
357
  ### Discovering sessions
356
358
 
@@ -483,7 +485,7 @@ Finally, `--status` and `--json` belong to the wrapper only until a session name
483
485
 
484
486
  ### Port 9900 is already in use
485
487
 
486
- If another process occupies port 9900, the terminal can't become the hub. It tries to connect as a client first, and that attempt fails within 5 seconds even against a listener that accepts the connection and never speaks WebSocket - so the terminal falls back to trying the hub role and then retries after 2-5 seconds, rather than sitting offline indefinitely. Free the port or modify `DEFAULT_PORT` in `index.ts` - see [Limitations](#limitations--design-decisions).
488
+ If another process occupies port 9900, the terminal can't become the hub. It tries to connect as a client first, and that attempt fails within 5 seconds even against a listener that accepts the connection and never speaks WebSocket - so the terminal falls back to trying the hub role and then retries after 2-5 seconds instead of leaving a stalled handshake pending. If neither phase succeeds, one warning includes the listen error and says pi-link keeps retrying. Later failed retries stay quiet until a connection is established or you run `/link-disconnect`; a new double failure can then warn again. Free the port or modify `DEFAULT_PORT` in `index.ts` - see [Limitations](#limitations--design-decisions).
487
489
 
488
490
  ### `link_compact` has no outcome yet
489
491
 
@@ -491,7 +493,7 @@ A `link_compact` request does not interrupt work the target is still doing: it w
491
493
 
492
494
  ### I sent a message but got no reply
493
495
 
494
- A successful send is not a confirmation. On a client it means the message was handed to the hub connection, not that the target received it or acted on it — and replies are ordinary messages the other agent chooses to send, so nothing produces one automatically. Run `/link`, or ask your model to call `link_list`, and check the target: confirm the name is still exactly right, and note that a target in the `compacting` state holds messages that reach it until that state clears. Otherwise silence may mean the work is still running or that no reply was sent. If the target cancelled a `/compact`, pi-link cannot see that, so its messages may stay held until its next run or up to five minutes — see [Remote compaction](#remote-compaction).
496
+ A successful send is not a confirmation. On a client it means the message was handed to the hub connection, not that the target received it or acted on it — and replies are ordinary messages the other agent chooses to send, so nothing produces one automatically. Run `/link`, or ask your model to call `link_list`, and check the target: confirm the name is still exactly right, and note that a target in the `compacting` state holds messages that reach it until that state clears. Otherwise silence may mean the work is still running or that no reply was sent. After a failed or cancelled `/compact`, the next 500 ms check that sees Pi idle releases the local hold; delivery then uses the normal inbox window (about 200 ms). A session that remains busy keeps the hold — see [Inbox](#inbox).
495
497
 
496
498
  ### `pi-link --status` reports no hub, or an unsupported one
497
499
 
@@ -568,7 +570,9 @@ The sequence is a simple fallback:
568
570
 
569
571
  1. Attempt to connect as a **client** to `127.0.0.1:9900`. The WebSocket opening handshake is bounded at **5 seconds**; a listener that accepts the connection but never completes the upgrade fails the attempt instead of holding it open.
570
572
  2. If connection fails → become the **hub** (start a WebSocket server on that port).
571
- 3. If both fail (rare race condition) → retry after a randomized 2-5 second backoff.
573
+ 3. If both fail → warn once with the listen error and retry after a randomized 2-5 second backoff. A listen error does not prove another hub exists.
574
+
575
+ If two terminals race to bind, the loser can show this warning before joining the winner on its retry. Cancelled or superseded attempts do not warn.
572
576
 
573
577
  Only **one attempt runs at a time**, across both steps. Startup, a retry and `/link-connect` arriving while an attempt is in flight all join that attempt rather than opening a second connection, so a terminal cannot register twice or leave a second socket behind.
574
578
 
@@ -661,7 +665,7 @@ Default names are random 4-character hex IDs: `t-a1b2`, `t-c3d4`, etc.
661
665
  | `currentCwd` | `string` | Current working directory reported to peers on connect |
662
666
  | `inbox` | `array` | Queued incoming messages and compact outcomes awaiting delivery |
663
667
  | `flushTimer` | `Timer \| null` | Pending inbox flush; armed by the first queued message and not moved afterwards |
664
- | `compactDeadline` | `Timer \| undefined` | Backstop releasing the inbox if no ending pi-link handles arrives |
668
+ | `compactIdleTimer` | `Timer \| undefined` | Next idle check for the local manual-compaction gate; survives disconnect, cancelled on shutdown |
665
669
  | `pendingCompactResponses` | `Map` | Request ID → requested target, for each compact request still awaiting an outcome; no deadline |
666
670
  | `disposed` | `boolean` | Set on shutdown; guards WebSocket callbacks against stale context |
667
671
  | `startupConnectTimer` | `Timer \| null` | Deferred startup connect so Pi's startup cycle completes first |
@@ -678,8 +682,8 @@ Default names are random 4-character hex IDs: `t-a1b2`, `t-c3d4`, etc.
678
682
 
679
683
  Internally, teardown is split into two functions:
680
684
 
681
- - **`disconnect()`** - closes sockets, clears connection state, reports each outstanding compact request as unknown, and drops unanswered a remote request still waiting here. Used by `/link-disconnect` and called internally by `cleanup()`.
682
- - **`cleanup()`** - sets `disposed = true`, then calls `disconnect()` and clears `ctx`. Used on `session_shutdown`.
685
+ - **`disconnect()`** - closes sockets, clears connection state, reports each outstanding compact request as unknown, and drops unanswered a remote request still waiting here. A running remote compaction keeps its inbox gate until it reports a result; a local gate keeps its idle check. Used by `/link-disconnect` and called internally by `cleanup()`.
686
+ - **`cleanup()`** - sets `disposed = true`, then calls `disconnect()`, clears `ctx`, discards the inbox and cancels its flush and local idle check. Used on `session_shutdown`.
683
687
 
684
688
  Three helpers protect WebSocket callbacks from stale extension context:
685
689
 
@@ -706,7 +710,7 @@ The extension hooks into Pi's agent lifecycle events:
706
710
  - **`session_compact`** → Clears the local compaction gate and force-pushes a `status_update` so peers see the new (post-compaction) context usage immediately.
707
711
  - **`model_select`** → Force-pushes a `status_update`: the context window, and so the usage percentage, belongs to the model.
708
712
  - **`session_tree`** → Ends a remote request still waiting here, answering `tree_navigated`, and force-pushes a `status_update`: context usage belongs to the active branch.
709
- - **`session_shutdown`** → Full cleanup via `cleanup()`: closes all sockets, ends tracking of outstanding compact requests, drops a remote request still waiting here, drops the inbox (their outcomes included) and its flush timer so no turn is started, and disposes the extension.
713
+ - **`session_shutdown`** → Full cleanup via `cleanup()`: closes all sockets, ends tracking of outstanding compact requests, drops a remote request still waiting here, drops the inbox (their outcomes included), cancels its flush and local idle check so no turn is started, and disposes the extension.
710
714
 
711
715
  The five agent and tool handlers — `agent_start`, `agent_end`, `agent_settled` (when Pi still reports the session idle), `tool_execution_start` and `tool_execution_end` — each recompute the status and hand it to `pushStatus()`, which publishes only when the display identity changed since the last publish: a second concurrent tool starting behind the one already shown is silent, and so is a mutation that leaves a raised compaction gate on display. The session handlers keep the separate paths described in their own bullets, and `session_shutdown` cleans up rather than pushing. `disconnect()` is the only thing that clears the stored baseline, and `pushStatus()` returns immediately while the terminal is disconnected, so handler events in that interval restore nothing; once connected again, either a client's forced `welcome` push or the first of those ordinary handler events restores it. `session_compact`, `model_select` and `session_tree` always push, whether the identity changed or not — including while a remote request's gate still holds the displayed identity.
712
716
 
@@ -724,27 +728,31 @@ The flush pipeline:
724
728
  4. **Deliver** - one `pi.sendMessage()` call with a `[Link: N message(s) received]` block. Pi reads the receiver's state at this point — not at send time — to decide whether the batch steers a running agent or starts a turn.
725
729
  5. **Drain** - if the inbox still has items, reschedule.
726
730
 
727
- Delivery is held while a `manual`-reason compaction holds this terminal's gate, because a message delivered mid-compaction would be reasoned about against context that is being rebuilt. Two flags gate it: `compactRunning` for a compaction serving a remote `link_compact`, and `localCompacting`, set from `session_before_compact`; a remote request raises `compactRunning` first and adds `localCompacting` only if its compaction reaches that hook, since Pi reports its own reason as `manual` either way. Automatic (threshold/overflow) compaction is deliberately **not** gated: it runs inside the agent run, where Pi already queues steered messages and drains them afterwards. Because a gated flush does not reschedule, the release path is load-bearing: `releaseInbox()` runs after either flag clears and schedules a flush only when neither gate remains, and `compactDeadline` is the backstop for a `localCompacting` left raised, since pi-link does not handle Pi's failure event, `session_compact_failed`, and so no ending event it listens to clears the gate after a failure.
731
+ Delivery is held while a `manual`-reason compaction holds this terminal's gate, because a message delivered mid-compaction would be reasoned about against context that is being rebuilt. Two flags gate it: `compactRunning` for a compaction serving a remote `link_compact`, and `localCompacting`, set from `session_before_compact`; a remote request raises `compactRunning` first and adds `localCompacting` only if its compaction reaches that hook, since Pi reports its own reason as `manual` either way. Automatic (threshold/overflow) compaction is deliberately **not** gated: it runs inside the agent run, where Pi already queues steered messages and drains them afterwards. Because a gated flush does not reschedule, the release path is load-bearing: `releaseInbox()` runs after either flag clears and schedules a flush only when neither gate remains.
732
+
733
+ While `localCompacting` is raised, a separate timer checks `ctx.isIdle()` every 500 ms. The first check that sees Pi idle clears that gate through `setCompacting(false)`, updating status and scheduling inbox delivery if no remote gate remains. This recovers from failure or cancellation without waiting for another turn. There is no time limit: a session that keeps reporting busy stays held, even beyond five minutes. Success still clears the gate through `session_compact`, and `agent_start` retains its clear with the deployment caveat described above. The check survives `/link-disconnect` and stops when the gate clears or the session shuts down.
734
+
735
+ **Known Pi 1.5.2 limitation:** if another extension registers a slow `session_compact_failed` handler and a second `compact()` arrives during a manual compaction, Pi can lose the second attempt's controller and report idle while it is still running. The idle check then lowers the local gate too early. This is a Pi defect; the old deadline did not prevent it either. pi-link deliberately does not register that event: even a no-op handler exposes the controller-ownership bug.
728
736
 
729
737
  | Constant | Value | Purpose |
730
738
  | ----------------------- | ------- | ------------------------------------------------------------- |
731
739
  | `FLUSH_DELAY_MS` | 200 | Batching window, from the first queued message |
732
740
  | `BATCH_MAX_ITEMS` | 20 | Max messages per batch |
733
741
  | `BATCH_MAX_CHARS` | 16 000 | Soft cap on batch text size (~4K tokens) |
734
- | `COMPACT_TIMEOUT_MS` | 300 000 | Backstop releasing a manual compaction's gate |
742
+ | `COMPACT_IDLE_CHECK_MS` | 500 | How often the local compaction gate checks whether Pi is idle |
735
743
  | `COMPACT_WAIT_CHECK_MS` | 500 | How often a waiting remote request checks whether to start |
736
744
 
737
745
  ### Remote compaction
738
746
 
739
- The tool returns the request ID in `details.id` as well as in its sent text. Failures before sending return immediately without a later outcome: `not_connected`, `self_target` (`Cannot compact yourself.`), `not_found` for a target absent from the requester's group list, `aborted` for an already-aborted call, or `not_delivered` if routing could not hand the request on. These tool-result errors are distinct from a later `not done: <reason>` notification.
747
+ The tool returns the request ID in `details.id` as well as in its sent text. Failures before sending return immediately without a later outcome: `not_connected`, `self_target` (`Cannot compact yourself`), `not_found` for a target absent from the requester's group list, `aborted` for an already-aborted call, or `not_delivered` if routing could not hand the request on. These tool-result errors are distinct from a later `not done: <reason>` notification.
740
748
 
741
- A `compact_request` is answered at once with `unsupported` if the target has no compaction capability, and with `already_requested` if another request holds the target's one slot. Otherwise it takes that slot, `remoteCompact`, and starts at once if Pi reports the session idle and no compaction gate stands. If not, a single `setTimeout` checks again every `COMPACT_WAIT_CHECK_MS` while it waits; there is no deadline, and waiting raises no gate. Polling is deliberate: Pi emits `session_compact` before it clears its own compacting state, and a gate left by a failed compaction is released by its backstop or the next run, so no event marks every moment the target becomes free. Each check reads local state only. A request is served by calling `ctx.compact()` — the same operation as `/compact`. The requester is answered with a `compact_response` carrying its request ID when the runtime reports a result through `onComplete`/`onError`, once; a failure is not retried. A waiting request is dropped unanswered by `disconnect()` and teardown, and answered with `tree_navigated` after a completed tree navigation; a running one keeps its slot until its compaction ends. Each call targets one terminal, independent requests can be outstanding concurrently, and link participants are cooperating peers: nothing here is privileged.
749
+ A `compact_request` is answered at once with `already_requested` if another request holds the target's one slot. Otherwise it takes that slot, `remoteCompact`, and starts at once if Pi reports the session idle and no compaction gate stands. If not, a single `setTimeout` checks again every `COMPACT_WAIT_CHECK_MS` while it waits; there is no deadline, and waiting raises no gate. Polling is deliberate: Pi emits `session_compact` before it clears its own compacting state, and a gate left by a failed compaction is released by its idle check or the next run, so no event marks every moment the target becomes free. Each check reads local state only. A request is served by calling `ctx.compact()` — the same operation as `/compact`. The requester is answered with a `compact_response` carrying its request ID when the runtime reports a result through `onComplete`/`onError`, once; a failure is not retried. A waiting request is dropped unanswered by `disconnect()` and teardown, and answered with `tree_navigated` after a completed tree navigation; a running one keeps its slot and `compactRunning` gate across disconnect until its compaction reports an outcome. Each call targets one terminal, independent requests can be outstanding concurrently, and link participants are cooperating peers: nothing here is privileged.
742
750
 
743
751
  Serving a request raises the inbox gates in order, and not always both. `compactRunning` is set synchronously before `ctx.compact()` is called; `localCompacting` rises only if execution reaches the manual `session_before_compact` hook, so a runtime that refuses early — nothing to compact, already compacted, or another preparation failure — returns through `onError` without the local gate ever going up. When the compaction does succeed, `session_compact` clears the local gate first, and the later `finish()` clears `compactRunning` and calls `releaseInbox()`, which is what drains the inbox.
744
752
 
745
- What a failure hides is the ending, not the failure itself. A remote compaction reports its error through `onError`, which runs `finish()` and answers the requester, so `compactRunning` always comes back down. But `session_compact` is a success-only ending and pi-link does not listen to Pi's `session_compact_failed`, so a `localCompacting` already raised by the hook stays up until the target's next agent run (`agent_start`), a later successful compaction, or the `compactDeadline` backstop 300 seconds after that gate rose. A human `/compact` has no result callback at all, so those three are its only release paths.
753
+ A remote compaction reports its error through `onError`, which runs `finish()`, clears `compactRunning` and answers the requester once. If the manual hook raised `localCompacting`, its idle check clears that gate separately. Either can clear first; delivery waits until both are down. The check neither answers the request nor clears `compactRunning`. A human `/compact` has no result callback, but the same idle check recovers its local gate after failure or cancellation.
746
754
 
747
- The 300 seconds of `COMPACT_TIMEOUT_MS` bound only that gate backstop; the requester has no deadline. Aborting the call before the request goes out leaves the target untouched; once it is sent, the request belongs to the extension rather than the call, so a later abort changes nothing — there is no remote cancel, and the target's compaction, once started, runs to its own end.
755
+ Neither the gate nor the requester's wait has a deadline. Aborting the call before the request goes out leaves the target untouched; once it is sent, the request belongs to the extension rather than the call, so a later abort changes nothing — there is no remote cancel, and the target's compaction, once started, runs to its own end.
748
756
 
749
757
  ### Rendering
750
758
 
package/bin/pi-link.mjs CHANGED
@@ -39,9 +39,10 @@ function readSessionDirFromSettings(settingsPath) {
39
39
  if (!existsSync(settingsPath)) return undefined;
40
40
  let parsed;
41
41
  try {
42
- parsed = JSON.parse(readFileSync(settingsPath, "utf-8"));
42
+ // Like Pi's stripBom, drop one leading BOM before parsing.
43
+ parsed = JSON.parse(readFileSync(settingsPath, "utf-8").replace(/^\uFEFF/, ""));
43
44
  } catch (err) {
44
- console.error(`pi-link: ignored ${settingsPath}: ${err.message}`);
45
+ console.error(`Warning: Ignored ${settingsPath}: ${err.message}`);
45
46
  return undefined;
46
47
  }
47
48
  const value = parsed?.sessionDir;
@@ -193,7 +194,7 @@ async function scanSessions(dir, isCustom, scopeCwd) {
193
194
  entries = await readdir(dir, { withFileTypes: true });
194
195
  } catch (err) {
195
196
  if (err.code === "ENOENT") return [];
196
- fail(`cannot read session directory: ${err.message}`);
197
+ fail(`Cannot read session directory: ${err.message}`);
197
198
  }
198
199
 
199
200
  const tasks = [];
@@ -278,13 +279,13 @@ function rejectManagedFlag(token) {
278
279
  const key = token.split("=")[0];
279
280
  if (key === "--link-name") {
280
281
  console.error(
281
- "Error: --link-name is not accepted by the pi-link wrapper.\n" +
282
- " Use 'pi-link <name>' for combined link+session,\n" +
283
- " or run 'pi --link-name <name>' directly to set link name without session resolution.",
282
+ "Error: --link-name is not accepted by pi-link.\n" +
283
+ ' Use "pi-link <name>" to open the named session on the link,\n' +
284
+ ' or "pi --link-name <name>" to set only the link name.',
284
285
  );
285
286
  process.exit(1);
286
287
  }
287
- if (["--session", "--continue", "-c", "--resume", "-r", "--fork", "--no-session", "--session-dir"].includes(key)) {
288
+ if (["--session", "--continue", "-c", "--resume", "-r", "--fork", "--no-session", "--session-dir", "--session-id"].includes(key)) {
288
289
  console.error(`Error: ${key} is managed by pi-link. Remove it.`);
289
290
  process.exit(1);
290
291
  }
@@ -306,15 +307,15 @@ function fail(msg) {
306
307
  }
307
308
 
308
309
  function printHelp() {
309
- console.error("Usage: pi-link <name> [--global|-g] [pi flags...]");
310
- console.error(" pi-link --list [--global|-g]");
311
- console.error(" pi-link --status [--json]");
312
- console.error(" pi-link --resolve <name> [--global|-g]");
313
- console.error(" pi-link --version");
314
- console.error("");
315
- console.error("By default, name lookup is scoped to the current cwd.");
316
- console.error("--global / -g widens the search to sessions in any cwd.");
317
- console.error("--list reads saved sessions; --status asks the running hub who is connected.");
310
+ console.log("Usage: pi-link <name> [--global|-g] [pi flags...]");
311
+ console.log(" pi-link --list [--global|-g]");
312
+ console.log(" pi-link --status [--json]");
313
+ console.log(" pi-link --resolve <name> [--global|-g]");
314
+ console.log(" pi-link --version");
315
+ console.log("");
316
+ console.log("By default, name lookup is scoped to the current cwd.");
317
+ console.log("--global / -g widens the search to sessions in any cwd.");
318
+ console.log("--list reads saved sessions; --status asks the running hub who is connected.");
318
319
  }
319
320
 
320
321
  function printVersion() {
@@ -322,9 +323,9 @@ function printVersion() {
322
323
  try {
323
324
  pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf-8"));
324
325
  } catch (err) {
325
- fail(`cannot read pi-link's package.json: ${err.message}`);
326
+ fail(`Cannot read pi-link's package.json: ${err.message}`);
326
327
  }
327
- if (!pkg.version) fail("pi-link's package.json has no version");
328
+ if (!pkg.version) fail("pi-link's package.json has no version.");
328
329
  console.log(pkg.version);
329
330
  }
330
331
 
@@ -360,7 +361,7 @@ const state = {
360
361
 
361
362
  function setMode(mode) {
362
363
  if (state.mode !== null && state.mode !== mode) {
363
- fail(`cannot combine ${describeMode(state.mode)} and ${describeMode(mode)}`);
364
+ fail(`Cannot combine ${describeMode(state.mode)} and ${describeMode(mode)}.`);
364
365
  }
365
366
  state.mode = mode;
366
367
  }
@@ -387,10 +388,13 @@ for (let i = 0; i < rawArgs.length; i++) {
387
388
  if (a === "--") {
388
389
  // `--` only meaningful in launcher mode (separates pi flags from positionals).
389
390
  if (state.mode !== "launcher") {
390
- fail(`-- is only valid after a session name`);
391
+ fail(`-- is only valid after a session name.`);
391
392
  }
392
- for (let j = i + 1; j < rawArgs.length; j++) {
393
- state.piPassthrough.push(rawArgs[j]);
393
+ // The wrapper drops its own `--`, so the tokens after it still reach pi and can
394
+ // be options. Managed flags are refused in any position, as before the `--`.
395
+ for (const token of rawArgs.slice(i + 1)) {
396
+ rejectManagedFlag(token);
397
+ state.piPassthrough.push(token);
394
398
  }
395
399
  i = rawArgs.length;
396
400
  break;
@@ -417,13 +421,13 @@ for (let i = 0; i < rawArgs.length; i++) {
417
421
  }
418
422
  if (a.startsWith("--resolve=")) {
419
423
  setMode("resolve");
420
- if (state.resolveName !== null) fail(`--resolve specified more than once`);
424
+ if (state.resolveName !== null) fail(`--resolve specified more than once.`);
421
425
  state.resolveName = a.slice("--resolve=".length);
422
426
  continue;
423
427
  }
424
428
  if (a === "--resolve") {
425
429
  setMode("resolve");
426
- if (state.resolveName !== null) fail(`--resolve specified more than once`);
430
+ if (state.resolveName !== null) fail(`--resolve specified more than once.`);
427
431
  const next = rawArgs[i + 1];
428
432
  if (next === undefined || next.startsWith("-")) {
429
433
  fail(`--resolve requires a name argument.\n Usage: pi-link --resolve <name> [--global|-g]`);
@@ -441,7 +445,7 @@ for (let i = 0; i < rawArgs.length; i++) {
441
445
  fail(`--version does not accept arguments: ${a}`);
442
446
  }
443
447
  if (state.mode === "list") {
444
- fail(`--list does not accept argument: ${a}\n Usage: pi-link --list [--global|-g]`);
448
+ fail(`--list does not accept arguments: ${a}\n Usage: pi-link --list [--global|-g]`);
445
449
  }
446
450
  if (state.mode === "status") {
447
451
  fail(`--status does not accept arguments: ${a}\n Usage: pi-link --status [--json]`);
@@ -458,7 +462,7 @@ for (let i = 0; i < rawArgs.length; i++) {
458
462
  fail(`Unknown argument: ${a}\n Usage: pi-link <name> [--global|-g] [pi flags...]`);
459
463
  }
460
464
  if (a === "list" || a === "resolve") {
461
- fail(`'pi-link ${a}' was removed. Use 'pi-link --${a}'.`);
465
+ fail(`"pi-link ${a}" was removed. Use "pi-link --${a}".`);
462
466
  }
463
467
  state.mode = "launcher";
464
468
  state.launcherName = a;
@@ -498,15 +502,15 @@ if (state.mode === "resolve") {
498
502
  // `--status` reads one running hub, so a cwd scope is meaningless rather than
499
503
  // merely unused: silently ignoring `-g` would imply a filter that cannot exist.
500
504
  if (state.mode === "status" && state.global) {
501
- fail(`cannot combine --status and --global`);
505
+ fail(`Cannot combine --status and --global.`);
502
506
  }
503
507
  if (state.json && state.mode !== "status") {
504
- fail(`--json is only valid with --status`);
508
+ fail(`--json is only valid with --status.`);
505
509
  }
506
510
  if (state.mode === "launcher") {
507
511
  const normalized = normalizeName(state.launcherName);
508
512
  if (!normalized) {
509
- fail(`session name cannot be empty.\n Usage: pi-link <name> [--global|-g] [pi flags...]`);
513
+ fail(`Session name cannot be empty.\n Usage: pi-link <name> [--global|-g] [pi flags...]`);
510
514
  }
511
515
  state.launcherName = normalized;
512
516
  }
@@ -534,7 +538,7 @@ switch (state.mode) {
534
538
  await runLauncher(state);
535
539
  break;
536
540
  default:
537
- fail(`internal error: unknown mode ${state.mode}`);
541
+ fail(`Internal error: unknown mode ${state.mode}`);
538
542
  }
539
543
 
540
544
  // ── Mode handlers ──────────────────────────────────────────────────────────
package/index.ts CHANGED
@@ -27,15 +27,14 @@ import { WebSocket, WebSocketServer } from "ws";
27
27
 
28
28
  // ─── Constants ───────────────────────────────────────────────────────────────
29
29
 
30
- // Pi 0.84.2 is the floor: `agent_settled` and `ctx.isIdle()` are the whole basis of
31
- // the settled lifecycle and the remote-compaction guard below, and there is one code
32
- // path for them. Package installation does not check the host version, so an older
33
- // Pi installs pi-link successfully and must be refused at load.
34
- const MIN_PI_VERSION = [0, 84, 2];
30
+ // Pi 0.85.0 is the floor: ctx.isIdle() must include Pi's own compactions so a
31
+ // failed manual compaction's gate can clear when Pi reports idle. Installation
32
+ // does not check the host version, so older Pi must be refused at load.
33
+ const MIN_PI_VERSION = [0, 85, 0];
35
34
 
36
35
  const DEFAULT_PORT = 9900;
37
- // Backstop for the manual-compaction delivery gate; see setCompacting().
38
- const COMPACT_TIMEOUT_MS = 300_000;
36
+ // How often a manual compaction's gate checks whether Pi has become idle.
37
+ const COMPACT_IDLE_CHECK_MS = 500;
39
38
  // How often a target holding a remote compaction request checks whether it can start.
40
39
  const COMPACT_WAIT_CHECK_MS = 500;
41
40
  const RECONNECT_DELAY_MS = 2000;
@@ -150,7 +149,8 @@ function piVersionSupported(version: string): boolean {
150
149
  /**
151
150
  * The reason a `compact_response` gives, as the requester shows it. The wire keeps
152
151
  * the codes; anything else, such as a runtime's own message, is shown as sent.
153
- * Only targets on earlier versions answer `busy`: they declined instead of waiting.
152
+ * Only targets on earlier versions answer `busy` (they declined instead of waiting)
153
+ * or `unsupported`.
154
154
  */
155
155
  function compactReasonText(reason: string | undefined): string {
156
156
  switch (reason) {
@@ -221,7 +221,8 @@ export default function (pi: ExtensionAPI) {
221
221
  if (!piVersionSupported(PI_VERSION)) {
222
222
  throw new Error(
223
223
  `pi-link requires Pi >=${MIN_PI_VERSION.join(".")} in x.y.z format, without suffixes ` +
224
- `(detected ${PI_VERSION || "unknown"}); pi-link 0.2.x supports Pi 0.74–0.84.1.`,
224
+ `(detected ${PI_VERSION || "unknown"}); pi-link 0.6.1 supports Pi 0.84.2–0.84.4; ` +
225
+ `pi-link 0.2.x supports Pi 0.74–0.84.1.`,
225
226
  );
226
227
  }
227
228
 
@@ -249,6 +250,8 @@ export default function (pi: ExtensionAPI) {
249
250
  let ctx: ExtensionContext | undefined;
250
251
  let disposed = false;
251
252
  let manuallyDisconnected = false;
253
+ // One double-failure warning per outage; establishment or explicit disconnect resets it.
254
+ let connectionFailureReported = false;
252
255
  let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
253
256
  let startupConnectTimer: ReturnType<typeof setTimeout> | null = null;
254
257
 
@@ -260,7 +263,7 @@ export default function (pi: ExtensionAPI) {
260
263
  let remoteCompact: CompactRequestMsg | null = null;
261
264
  let compactWaitTimer: ReturnType<typeof setTimeout> | undefined;
262
265
  let localCompacting = false; // gate set by Pi's manual-reason hook (human or remote)
263
- let compactDeadline: ReturnType<typeof setTimeout> | undefined;
266
+ let compactIdleTimer: ReturnType<typeof setTimeout> | undefined;
264
267
  let wasCompactionGated = false; // gate state syncCompactionStatus() last acted on
265
268
  // toolCallId → toolName. Pi runs tools in parallel by default and both tool
266
269
  // events carry the call id, so one slot per call is the only way an end can clear
@@ -293,6 +296,7 @@ export default function (pi: ExtensionAPI) {
293
296
  socket: WebSocket | null; // dialing, not yet `ws`
294
297
  server: WebSocketServer | null; // binding, not yet `wss`
295
298
  httpServer: HttpServer | null; // binding, not yet `hubHttpServer`
299
+ listenError?: Error; // cause retained until runAttempt checks ownership
296
300
  };
297
301
  let connectionAttempt: ConnectionAttempt | null = null;
298
302
 
@@ -513,8 +517,8 @@ export default function (pi: ExtensionAPI) {
513
517
  if (!ctx) return;
514
518
 
515
519
  // Compacting: hold everything and return WITHOUT rescheduling. releaseInbox()
516
- // schedules delivery once both gates clear, so polling a hold that may last
517
- // to the 300s ceiling would be ~1500 wakeups for no information.
520
+ // schedules delivery once both gates clear; retrying this flush would learn
521
+ // nothing while either gate still holds.
518
522
  if (compactionGated()) return;
519
523
 
520
524
  // Select batch: up to BATCH_MAX_ITEMS, ~BATCH_MAX_CHARS total (soft cap —
@@ -604,24 +608,31 @@ export default function (pi: ExtensionAPI) {
604
608
  /**
605
609
  * Gate and release inbox delivery for Pi's manual-reason compaction hook.
606
610
  *
607
- * The deadline is the only backstop pi-link uses. Pi 0.84.3+ reports failure and
608
- * abort through `session_compact_failed`, which pi-link does not handle (see
609
- * REPORT-session-compact-failed.md); `session_compact` is the only
610
- * compaction-ending event it handles. The timer handle must be explicit
611
- * and cleared on every transition: a bare setTimeout outlives its own
612
- * compaction and would release a *later* compaction's flag.
611
+ * Success clears it through session_compact; after failure or cancellation,
612
+ * polling Pi's idle state supplies the missing ending. No elapsed-time limit
613
+ * releases a busy compaction. The timer survives disconnect, but is cancelled
614
+ * when the gate clears or the session shuts down.
615
+ *
616
+ * Do not register session_compact_failed: on Pi 1.5.2 even a no-op handler
617
+ * exposes a controller-ownership bug when two manual compactions overlap.
613
618
  */
614
619
  function setCompacting(on: boolean) {
615
620
  localCompacting = on;
616
- clearTimeout(compactDeadline);
617
- compactDeadline = on
618
- ? setTimeout(() => setCompacting(false), COMPACT_TIMEOUT_MS)
621
+ clearTimeout(compactIdleTimer);
622
+ compactIdleTimer = on
623
+ ? setTimeout(checkLocalCompaction, COMPACT_IDLE_CHECK_MS)
619
624
  : undefined;
620
625
  // Release schedules delivery; it never polls.
621
626
  if (!on) releaseInbox();
622
627
  syncCompactionStatus();
623
628
  }
624
629
 
630
+ function checkLocalCompaction() {
631
+ // The hook rejects disposed instances; cleanup cancels checks already armed.
632
+ if (ctx!.isIdle()) setCompacting(false);
633
+ else compactIdleTimer = setTimeout(checkLocalCompaction, COMPACT_IDLE_CHECK_MS);
634
+ }
635
+
625
636
  // ── Connection intent ──────────────────────────────────────────────────
626
637
 
627
638
  function shouldConnect(): boolean {
@@ -670,10 +681,9 @@ export default function (pi: ExtensionAPI) {
670
681
  * Whether a remote request has to wait before it starts. Pi's idle state is the
671
682
  * authority on whether this terminal is working; agentRunning is not: Pi may still
672
683
  * retry, run an automatic compaction, or drain a queued continuation inside a run
673
- * whose agent_end already fired, and compact() would abort that work. Pi 1.2's
674
- * idle flag also covers its own compactions; at the 0.84.2 floor it covers only
675
- * the agent run. Our gates extend beyond that: a manual compaction's
676
- * localCompacting can remain after a failure, until its backstop.
684
+ * whose agent_end already fired, and compact() would abort that work. Pi's idle
685
+ * flag also covers its own compactions. Our gates can outlast that work: a failed
686
+ * manual compaction's local gate remains until its next idle check.
677
687
  */
678
688
  function remoteCompactMustWait(context: ExtensionContext) {
679
689
  return !context.isIdle() || compactionGated();
@@ -683,8 +693,8 @@ export default function (pi: ExtensionAPI) {
683
693
  * Start the held remote request once the terminal is free, checking again every
684
694
  * COMPACT_WAIT_CHECK_MS until then. Polling, because no Pi event marks every
685
695
  * moment the terminal becomes free: session_compact fires before Pi clears its
686
- * compacting state, and a gate left by a failed compaction is released by its
687
- * backstop or the next run. There is no deadline. Waiting raises no gate, so
696
+ * compacting state, and a failed compaction's local gate clears on an idle check
697
+ * or the next run. There is no deadline. Waiting raises no gate, so
688
698
  * messages are still delivered, and one delivered into Pi's work keeps the
689
699
  * terminal busy. One still in the inbox's batching window does not: it can lose
690
700
  * to the start, and is then held until the compaction ends.
@@ -714,7 +724,7 @@ export default function (pi: ExtensionAPI) {
714
724
  releaseInbox(); // last gate may clear here, after session_compact already fired
715
725
  // Only reverts status if localCompacting is also clear. A failure after
716
726
  // session_before_compact leaves it standing, so the terminal keeps
717
- // reporting the hold as compacting until the deadline, agent_start,
727
+ // reporting the hold as compacting until its next idle check, agent_start,
718
728
  // or a later successful compaction.
719
729
  syncCompactionStatus();
720
730
  answerCompact(request, ok, reason);
@@ -974,25 +984,22 @@ export default function (pi: ExtensionAPI) {
974
984
 
975
985
  // ── Another terminal asks us to compact our context ──
976
986
  case "compact_request": {
977
- // Answered at once, without taking the request on: with no capability or no
978
- // context there is nothing to wait for, and a second request is refused
979
- // rather than queued, merged or allowed to replace the held one.
980
- if (!ctx || !ctx.compact) {
981
- answerCompact(msg, false, "unsupported");
982
- break;
983
- }
987
+ // A second request is refused at once rather than queued, merged or
988
+ // allowed to replace the held one.
984
989
  if (remoteCompact) {
985
990
  answerCompact(msg, false, "already_requested");
986
991
  break;
987
992
  }
993
+ // Messages are handled only while isRuntimeLive(), which requires ctx.
994
+ const context = ctx!;
988
995
  remoteCompact = msg;
989
996
  notify(
990
- remoteCompactMustWait(ctx)
997
+ remoteCompactMustWait(context)
991
998
  ? `"${msg.from}" asked this terminal to compact; waiting until it is idle`
992
999
  : `"${msg.from}" asked this terminal to compact`,
993
1000
  "info",
994
1001
  );
995
- startRemoteCompactWhenFree(msg, ctx);
1002
+ startRemoteCompactWhenFree(msg, context);
996
1003
  break;
997
1004
  }
998
1005
 
@@ -1137,12 +1144,13 @@ export default function (pi: ExtensionAPI) {
1137
1144
  const server = new WebSocketServer({ server: httpServer });
1138
1145
  attempt.server = server;
1139
1146
 
1140
- // The phase settles once. `error` and a pre-listen `close` both report the
1141
- // same failure, and closing a cancelled server reports it a third time.
1147
+ // The phase settles once. A listen error keeps its cause on this attempt;
1148
+ // cancellation can close the server without a listen error.
1142
1149
  let settled = false;
1143
- const settle = (established: boolean) => {
1150
+ const settle = (established: boolean, listenError?: Error) => {
1144
1151
  if (settled) return;
1145
1152
  settled = true;
1153
+ attempt.listenError = listenError;
1146
1154
  if (attempt.server === server) attempt.server = null;
1147
1155
  if (attempt.httpServer === httpServer) attempt.httpServer = null;
1148
1156
  resolve(established);
@@ -1164,6 +1172,7 @@ export default function (pi: ExtensionAPI) {
1164
1172
  if (pendingClientRename && preferredName) terminalName = preferredName;
1165
1173
  pendingClientRename = false;
1166
1174
  role = "hub";
1175
+ connectionFailureReported = false;
1167
1176
  connectedTerminals = [terminalName];
1168
1177
  updateStatus();
1169
1178
  notify(
@@ -1183,9 +1192,10 @@ export default function (pi: ExtensionAPI) {
1183
1192
  hubHandleClient(clientWs);
1184
1193
  });
1185
1194
 
1186
- server.on("error", () => {
1187
- // Listen failed; a port conflict is possible, but does not prove another hub.
1188
- settle(false);
1195
+ server.on("error", (error) => {
1196
+ // A port conflict is possible, but does not prove another hub. runAttempt
1197
+ // warns only after checking that this attempt still owns establishment.
1198
+ settle(false, error);
1189
1199
  });
1190
1200
 
1191
1201
  server.on("close", () => {
@@ -1227,6 +1237,7 @@ export default function (pi: ExtensionAPI) {
1227
1237
  // socket that is neither.
1228
1238
  ws = socket;
1229
1239
  role = "client";
1240
+ connectionFailureReported = false;
1230
1241
  // Register with preferred name if available, otherwise current name
1231
1242
  socket.send(
1232
1243
  JSON.stringify({
@@ -1308,12 +1319,20 @@ export default function (pi: ExtensionAPI) {
1308
1319
  if (await connectAsClient(attempt)) return;
1309
1320
  if (!attemptIsCurrent(attempt)) return;
1310
1321
 
1311
- // No hub found — become the hub
1322
+ // Could not join — try becoming the hub
1312
1323
  if (await startHub(attempt)) return;
1313
1324
  if (!attemptIsCurrent(attempt)) return;
1314
1325
 
1315
- // Establishment failed (e.g. a race, port conflict, or other listen failure).
1316
- // Retry after delay.
1326
+ // Report the first double failure of this outage, including an election race.
1327
+ // Later retries stay quiet. A still-current failed bind reaches here through
1328
+ // the server's error event, which populated the optional listenError field.
1329
+ if (!connectionFailureReported && attempt.listenError) {
1330
+ connectionFailureReported = true;
1331
+ notify(
1332
+ `Could neither join nor host the link on :${DEFAULT_PORT}. Retrying. Listen error: ${attempt.listenError.message}`,
1333
+ "warning",
1334
+ );
1335
+ }
1317
1336
  scheduleReconnect();
1318
1337
  } finally {
1319
1338
  // Only while still the owner: an attempt cancelled mid-flight must not clear
@@ -1369,13 +1388,10 @@ export default function (pi: ExtensionAPI) {
1369
1388
 
1370
1389
  // A remote request still waiting is dropped unanswered: the link it would answer
1371
1390
  // over is closing, and its requester sees this terminal leave. A running one
1372
- // keeps its slot until it finishes. Clear the remote-request gate; the
1373
- // manual-reason hook's gate survives disconnect.
1391
+ // keeps its slot and gate until finish() handles the result, even before the
1392
+ // manual-reason hook raises its own gate. Disconnect cancels neither compaction
1393
+ // nor its inbox hold.
1374
1394
  dropWaitingRemoteCompact();
1375
- compactRunning = false;
1376
- // Runs before role is cleared, so peers still get a final status; more to the
1377
- // point, the local gate record stays honest for the reconnect.
1378
- syncCompactionStatus();
1379
1395
  // A response could only arrive over the link being closed. The inbox survives
1380
1396
  // disconnect, so these are delivered once no gate holds it; on shutdown,
1381
1397
  // cleanup() clears them with the rest of the inbox.
@@ -1410,7 +1426,7 @@ export default function (pi: ExtensionAPI) {
1410
1426
  lastPushedStatus = null;
1411
1427
  updateStatus();
1412
1428
 
1413
- // Inbox survives disconnect; schedule delivery unless localCompacting still holds it.
1429
+ // Inbox survives disconnect; schedule delivery only when neither gate holds it.
1414
1430
  releaseInbox();
1415
1431
  }
1416
1432
 
@@ -1419,8 +1435,7 @@ export default function (pi: ExtensionAPI) {
1419
1435
  // disconnect() cancels the attempt in flight, including the startup timer.
1420
1436
  disconnect();
1421
1437
  ctx = undefined;
1422
- // Full teardown: clear inbox and both timers. The compaction deadline runs to
1423
- // 300s, so it would otherwise outlive the extension and fire after teardown.
1438
+ // Full teardown: discard the inbox and cancel its flush and local idle check.
1424
1439
  inbox.length = 0;
1425
1440
  if (flushTimer) {
1426
1441
  clearTimeout(flushTimer);
@@ -1435,6 +1450,37 @@ export default function (pi: ExtensionAPI) {
1435
1450
  ctx = _ctx;
1436
1451
  currentCwd = _ctx.cwd;
1437
1452
 
1453
+ // Tab forces completion, and Pi skips getArgumentCompletions when forced,
1454
+ // so use a provider for both Tab and typing. Wait for @: an open list makes
1455
+ // Enter select instead of submit, blocking plain names without Esc.
1456
+ // Offer all groups on the link, unlike visibleTerminals, so users can join one.
1457
+ _ctx.ui.addAutocompleteProvider((current) => ({
1458
+ getSuggestions(lines, cursorLine, cursorCol, options) {
1459
+ const beforeCursor = lines[cursorLine].slice(0, cursorCol).trimStart();
1460
+ const match = beforeCursor.match(/^\/link-name (.*@.*)$/);
1461
+ if (match) {
1462
+ const prefix = match[1];
1463
+ const at = prefix.indexOf("@");
1464
+ const groupPrefix = prefix.slice(at + 1);
1465
+ const groups = [...new Set(connectedTerminals.map(groupOf))]
1466
+ .filter((group) => group !== "" && group.startsWith(groupPrefix))
1467
+ .sort();
1468
+ const items = groups.map((group) => ({
1469
+ value: prefix.slice(0, at + 1) + group,
1470
+ label: group,
1471
+ }));
1472
+ if (items.length > 0) return { items, prefix };
1473
+ }
1474
+ return current.getSuggestions(lines, cursorLine, cursorCol, options);
1475
+ },
1476
+ applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
1477
+ return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
1478
+ },
1479
+ shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
1480
+ return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
1481
+ },
1482
+ }));
1483
+
1438
1484
  // Resolve terminal name. Precedence:
1439
1485
  // --link-name flag > PI_LINK_NAME env > saved link-name > session name > random
1440
1486
  //
@@ -1517,6 +1563,10 @@ export default function (pi: ExtensionAPI) {
1517
1563
  });
1518
1564
 
1519
1565
  pi.on("session_before_compact", async (event) => {
1566
+ // Pi can emit this after shutdown if compact() was still awaiting abort().
1567
+ // Do not raise a gate or arm a check against the cleared context.
1568
+ if (disposed) return;
1569
+
1520
1570
  // Manual only. Automatic (threshold/overflow) compaction runs inside the agent
1521
1571
  // run, so a delivered message takes Pi's steering arm and _runAutoCompaction
1522
1572
  // returns hasQueuedMessages() to drain it afterwards. Gating it would replace a
@@ -1526,7 +1576,7 @@ export default function (pi: ExtensionAPI) {
1526
1576
  // Pi passes that signal into the summarizer and its compaction controller lives
1527
1577
  // until the catch/finally, so releasing on abort would re-open delivery while the
1528
1578
  // aborted compaction is still unwinding. A cancelled compaction's gate is released
1529
- // by the next run (agent_start), the deadline, or a later successful compaction.
1579
+ // when Pi reports idle, by the next run (agent_start), or by session_compact.
1530
1580
  //
1531
1581
  // Accepted gap: compact() aborts and prepares *before* emitting this
1532
1582
  // event, so a flush in that window can still start a turn against context about
@@ -1637,14 +1687,26 @@ export default function (pi: ExtensionAPI) {
1637
1687
  );
1638
1688
  }
1639
1689
 
1640
- // Shared ✓/✗ result renderer for link_send and link_compact.
1690
+ // Shared ✓/✗ result renderer for link_send and link_compact. Host errors
1691
+ // (a failed validation, a blocked call, a throw) need not set details.error: Pi
1692
+ // flags them in the render context, Oh My Pi in result.isError, where the fourth
1693
+ // argument is the call's arguments instead.
1641
1694
  function renderIconResult(
1642
- result: { content: { type: string; text?: string }[]; details?: unknown },
1695
+ result: {
1696
+ content: { type: string; text?: string }[];
1697
+ details?: unknown;
1698
+ isError?: boolean;
1699
+ },
1643
1700
  theme: { fg(role: string, text: string): string },
1701
+ context?: { isError?: boolean },
1644
1702
  ) {
1645
1703
  const txt = result.content[0];
1646
1704
  const details = result.details as Record<string, unknown> | undefined;
1647
- const icon = details?.error
1705
+ const failed =
1706
+ context?.isError === true ||
1707
+ result.isError === true ||
1708
+ Boolean(details?.error);
1709
+ const icon = failed
1648
1710
  ? theme.fg("error", "✗ ")
1649
1711
  : theme.fg("success", "✓ ");
1650
1712
  return new Text(icon + (txt?.type === "text" ? txt.text : ""), 0, 0);
@@ -1720,7 +1782,8 @@ export default function (pi: ExtensionAPI) {
1720
1782
  return new Text(text, 0, 0);
1721
1783
  },
1722
1784
 
1723
- renderResult: (result, _options, theme) => renderIconResult(result, theme),
1785
+ renderResult: (result, _options, theme, context) =>
1786
+ renderIconResult(result, theme, context),
1724
1787
  });
1725
1788
 
1726
1789
  pi.registerTool({
@@ -1754,7 +1817,7 @@ export default function (pi: ExtensionAPI) {
1754
1817
  if (role === "disconnected") return notConnectedResult();
1755
1818
 
1756
1819
  if (params.to === terminalName) {
1757
- return textResult("Cannot compact yourself.", {
1820
+ return textResult("Cannot compact yourself", {
1758
1821
  to: params.to,
1759
1822
  error: "self_target",
1760
1823
  });
@@ -1804,7 +1867,8 @@ export default function (pi: ExtensionAPI) {
1804
1867
  return new Text(text, 0, 0);
1805
1868
  },
1806
1869
 
1807
- renderResult: (result, _options, theme) => renderIconResult(result, theme),
1870
+ renderResult: (result, _options, theme, context) =>
1871
+ renderIconResult(result, theme, context),
1808
1872
  });
1809
1873
 
1810
1874
  pi.registerTool({
@@ -1894,7 +1958,7 @@ export default function (pi: ExtensionAPI) {
1894
1958
  description: "Show link status",
1895
1959
  handler: async (_args, _ctx) => {
1896
1960
  if (role === "disconnected") {
1897
- _ctx.ui.notify("Link: not connected", "warning");
1961
+ _ctx.ui.notify("Not connected to the link", "warning");
1898
1962
  return;
1899
1963
  }
1900
1964
  const visible = visibleTerminals();
@@ -2006,6 +2070,7 @@ export default function (pi: ExtensionAPI) {
2006
2070
  handler: async (_args, _ctx) => {
2007
2071
  pi.appendEntry("link-active", { active: false });
2008
2072
  manuallyDisconnected = true;
2073
+ connectionFailureReported = false;
2009
2074
  // Also when nothing is established: a startup or reconnect attempt may still
2010
2075
  // be dialing or binding, and compact requests sent before the hub was lost are
2011
2076
  // still tracked. Persisted intent has to win over both.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-link",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "WebSocket-based inter-terminal communication for Pi. Connect multiple Pi terminals over a local link network.",
5
5
  "author": "alvivar",
6
6
  "license": "MIT",