pi-link 0.6.1 → 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.
Files changed (4) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +22 -14
  3. package/index.ts +99 -46
  4. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -6,6 +6,26 @@ 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
+
9
29
  ## 0.6.1 — 2026-11-02
10
30
 
11
31
  ### Fixed
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
@@ -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
 
@@ -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
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 `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/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;
@@ -222,7 +221,8 @@ export default function (pi: ExtensionAPI) {
222
221
  if (!piVersionSupported(PI_VERSION)) {
223
222
  throw new Error(
224
223
  `pi-link requires Pi >=${MIN_PI_VERSION.join(".")} in x.y.z format, without suffixes ` +
225
- `(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.`,
226
226
  );
227
227
  }
228
228
 
@@ -250,6 +250,8 @@ export default function (pi: ExtensionAPI) {
250
250
  let ctx: ExtensionContext | undefined;
251
251
  let disposed = false;
252
252
  let manuallyDisconnected = false;
253
+ // One double-failure warning per outage; establishment or explicit disconnect resets it.
254
+ let connectionFailureReported = false;
253
255
  let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
254
256
  let startupConnectTimer: ReturnType<typeof setTimeout> | null = null;
255
257
 
@@ -261,7 +263,7 @@ export default function (pi: ExtensionAPI) {
261
263
  let remoteCompact: CompactRequestMsg | null = null;
262
264
  let compactWaitTimer: ReturnType<typeof setTimeout> | undefined;
263
265
  let localCompacting = false; // gate set by Pi's manual-reason hook (human or remote)
264
- let compactDeadline: ReturnType<typeof setTimeout> | undefined;
266
+ let compactIdleTimer: ReturnType<typeof setTimeout> | undefined;
265
267
  let wasCompactionGated = false; // gate state syncCompactionStatus() last acted on
266
268
  // toolCallId → toolName. Pi runs tools in parallel by default and both tool
267
269
  // events carry the call id, so one slot per call is the only way an end can clear
@@ -294,6 +296,7 @@ export default function (pi: ExtensionAPI) {
294
296
  socket: WebSocket | null; // dialing, not yet `ws`
295
297
  server: WebSocketServer | null; // binding, not yet `wss`
296
298
  httpServer: HttpServer | null; // binding, not yet `hubHttpServer`
299
+ listenError?: Error; // cause retained until runAttempt checks ownership
297
300
  };
298
301
  let connectionAttempt: ConnectionAttempt | null = null;
299
302
 
@@ -514,8 +517,8 @@ export default function (pi: ExtensionAPI) {
514
517
  if (!ctx) return;
515
518
 
516
519
  // Compacting: hold everything and return WITHOUT rescheduling. releaseInbox()
517
- // schedules delivery once both gates clear, so polling a hold that may last
518
- // 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.
519
522
  if (compactionGated()) return;
520
523
 
521
524
  // Select batch: up to BATCH_MAX_ITEMS, ~BATCH_MAX_CHARS total (soft cap —
@@ -605,24 +608,31 @@ export default function (pi: ExtensionAPI) {
605
608
  /**
606
609
  * Gate and release inbox delivery for Pi's manual-reason compaction hook.
607
610
  *
608
- * The deadline is the only backstop pi-link uses. Pi 0.84.3+ reports failure and
609
- * abort through `session_compact_failed`, which pi-link does not handle (see
610
- * REPORT-session-compact-failed.md); `session_compact` is the only
611
- * compaction-ending event it handles. The timer handle must be explicit
612
- * and cleared on every transition: a bare setTimeout outlives its own
613
- * 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.
614
618
  */
615
619
  function setCompacting(on: boolean) {
616
620
  localCompacting = on;
617
- clearTimeout(compactDeadline);
618
- compactDeadline = on
619
- ? setTimeout(() => setCompacting(false), COMPACT_TIMEOUT_MS)
621
+ clearTimeout(compactIdleTimer);
622
+ compactIdleTimer = on
623
+ ? setTimeout(checkLocalCompaction, COMPACT_IDLE_CHECK_MS)
620
624
  : undefined;
621
625
  // Release schedules delivery; it never polls.
622
626
  if (!on) releaseInbox();
623
627
  syncCompactionStatus();
624
628
  }
625
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
+
626
636
  // ── Connection intent ──────────────────────────────────────────────────
627
637
 
628
638
  function shouldConnect(): boolean {
@@ -671,10 +681,9 @@ export default function (pi: ExtensionAPI) {
671
681
  * Whether a remote request has to wait before it starts. Pi's idle state is the
672
682
  * authority on whether this terminal is working; agentRunning is not: Pi may still
673
683
  * retry, run an automatic compaction, or drain a queued continuation inside a run
674
- * whose agent_end already fired, and compact() would abort that work. Pi 1.2's
675
- * idle flag also covers its own compactions; at the 0.84.2 floor it covers only
676
- * the agent run. Our gates extend beyond that: a manual compaction's
677
- * 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.
678
687
  */
679
688
  function remoteCompactMustWait(context: ExtensionContext) {
680
689
  return !context.isIdle() || compactionGated();
@@ -684,8 +693,8 @@ export default function (pi: ExtensionAPI) {
684
693
  * Start the held remote request once the terminal is free, checking again every
685
694
  * COMPACT_WAIT_CHECK_MS until then. Polling, because no Pi event marks every
686
695
  * moment the terminal becomes free: session_compact fires before Pi clears its
687
- * compacting state, and a gate left by a failed compaction is released by its
688
- * 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
689
698
  * messages are still delivered, and one delivered into Pi's work keeps the
690
699
  * terminal busy. One still in the inbox's batching window does not: it can lose
691
700
  * to the start, and is then held until the compaction ends.
@@ -715,7 +724,7 @@ export default function (pi: ExtensionAPI) {
715
724
  releaseInbox(); // last gate may clear here, after session_compact already fired
716
725
  // Only reverts status if localCompacting is also clear. A failure after
717
726
  // session_before_compact leaves it standing, so the terminal keeps
718
- // reporting the hold as compacting until the deadline, agent_start,
727
+ // reporting the hold as compacting until its next idle check, agent_start,
719
728
  // or a later successful compaction.
720
729
  syncCompactionStatus();
721
730
  answerCompact(request, ok, reason);
@@ -1135,12 +1144,13 @@ export default function (pi: ExtensionAPI) {
1135
1144
  const server = new WebSocketServer({ server: httpServer });
1136
1145
  attempt.server = server;
1137
1146
 
1138
- // The phase settles once. `error` and a pre-listen `close` both report the
1139
- // 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.
1140
1149
  let settled = false;
1141
- const settle = (established: boolean) => {
1150
+ const settle = (established: boolean, listenError?: Error) => {
1142
1151
  if (settled) return;
1143
1152
  settled = true;
1153
+ attempt.listenError = listenError;
1144
1154
  if (attempt.server === server) attempt.server = null;
1145
1155
  if (attempt.httpServer === httpServer) attempt.httpServer = null;
1146
1156
  resolve(established);
@@ -1162,6 +1172,7 @@ export default function (pi: ExtensionAPI) {
1162
1172
  if (pendingClientRename && preferredName) terminalName = preferredName;
1163
1173
  pendingClientRename = false;
1164
1174
  role = "hub";
1175
+ connectionFailureReported = false;
1165
1176
  connectedTerminals = [terminalName];
1166
1177
  updateStatus();
1167
1178
  notify(
@@ -1181,9 +1192,10 @@ export default function (pi: ExtensionAPI) {
1181
1192
  hubHandleClient(clientWs);
1182
1193
  });
1183
1194
 
1184
- server.on("error", () => {
1185
- // Listen failed; a port conflict is possible, but does not prove another hub.
1186
- 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);
1187
1199
  });
1188
1200
 
1189
1201
  server.on("close", () => {
@@ -1225,6 +1237,7 @@ export default function (pi: ExtensionAPI) {
1225
1237
  // socket that is neither.
1226
1238
  ws = socket;
1227
1239
  role = "client";
1240
+ connectionFailureReported = false;
1228
1241
  // Register with preferred name if available, otherwise current name
1229
1242
  socket.send(
1230
1243
  JSON.stringify({
@@ -1306,12 +1319,20 @@ export default function (pi: ExtensionAPI) {
1306
1319
  if (await connectAsClient(attempt)) return;
1307
1320
  if (!attemptIsCurrent(attempt)) return;
1308
1321
 
1309
- // No hub found — become the hub
1322
+ // Could not join — try becoming the hub
1310
1323
  if (await startHub(attempt)) return;
1311
1324
  if (!attemptIsCurrent(attempt)) return;
1312
1325
 
1313
- // Establishment failed (e.g. a race, port conflict, or other listen failure).
1314
- // 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
+ }
1315
1336
  scheduleReconnect();
1316
1337
  } finally {
1317
1338
  // Only while still the owner: an attempt cancelled mid-flight must not clear
@@ -1367,13 +1388,10 @@ export default function (pi: ExtensionAPI) {
1367
1388
 
1368
1389
  // A remote request still waiting is dropped unanswered: the link it would answer
1369
1390
  // over is closing, and its requester sees this terminal leave. A running one
1370
- // keeps its slot until it finishes. Clear the remote-request gate; the
1371
- // 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.
1372
1394
  dropWaitingRemoteCompact();
1373
- compactRunning = false;
1374
- // Runs before role is cleared, so peers still get a final status; more to the
1375
- // point, the local gate record stays honest for the reconnect.
1376
- syncCompactionStatus();
1377
1395
  // A response could only arrive over the link being closed. The inbox survives
1378
1396
  // disconnect, so these are delivered once no gate holds it; on shutdown,
1379
1397
  // cleanup() clears them with the rest of the inbox.
@@ -1408,7 +1426,7 @@ export default function (pi: ExtensionAPI) {
1408
1426
  lastPushedStatus = null;
1409
1427
  updateStatus();
1410
1428
 
1411
- // Inbox survives disconnect; schedule delivery unless localCompacting still holds it.
1429
+ // Inbox survives disconnect; schedule delivery only when neither gate holds it.
1412
1430
  releaseInbox();
1413
1431
  }
1414
1432
 
@@ -1417,8 +1435,7 @@ export default function (pi: ExtensionAPI) {
1417
1435
  // disconnect() cancels the attempt in flight, including the startup timer.
1418
1436
  disconnect();
1419
1437
  ctx = undefined;
1420
- // Full teardown: clear inbox and both timers. The compaction deadline runs to
1421
- // 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.
1422
1439
  inbox.length = 0;
1423
1440
  if (flushTimer) {
1424
1441
  clearTimeout(flushTimer);
@@ -1433,6 +1450,37 @@ export default function (pi: ExtensionAPI) {
1433
1450
  ctx = _ctx;
1434
1451
  currentCwd = _ctx.cwd;
1435
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
+
1436
1484
  // Resolve terminal name. Precedence:
1437
1485
  // --link-name flag > PI_LINK_NAME env > saved link-name > session name > random
1438
1486
  //
@@ -1515,6 +1563,10 @@ export default function (pi: ExtensionAPI) {
1515
1563
  });
1516
1564
 
1517
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
+
1518
1570
  // Manual only. Automatic (threshold/overflow) compaction runs inside the agent
1519
1571
  // run, so a delivered message takes Pi's steering arm and _runAutoCompaction
1520
1572
  // returns hasQueuedMessages() to drain it afterwards. Gating it would replace a
@@ -1524,7 +1576,7 @@ export default function (pi: ExtensionAPI) {
1524
1576
  // Pi passes that signal into the summarizer and its compaction controller lives
1525
1577
  // until the catch/finally, so releasing on abort would re-open delivery while the
1526
1578
  // aborted compaction is still unwinding. A cancelled compaction's gate is released
1527
- // 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.
1528
1580
  //
1529
1581
  // Accepted gap: compact() aborts and prepares *before* emitting this
1530
1582
  // event, so a flush in that window can still start a turn against context about
@@ -2018,6 +2070,7 @@ export default function (pi: ExtensionAPI) {
2018
2070
  handler: async (_args, _ctx) => {
2019
2071
  pi.appendEntry("link-active", { active: false });
2020
2072
  manuallyDisconnected = true;
2073
+ connectionFailureReported = false;
2021
2074
  // Also when nothing is established: a startup or reconnect attempt may still
2022
2075
  // be dialing or binding, and compact requests sent before the hub was lost are
2023
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.1",
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",