pi-link 0.5.2 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.ts CHANGED
@@ -34,7 +34,10 @@ import { WebSocket, WebSocketServer } from "ws";
34
34
  const MIN_PI_VERSION = [0, 84, 2];
35
35
 
36
36
  const DEFAULT_PORT = 9900;
37
+ // Backstop for the manual-compaction delivery gate; see setCompacting().
37
38
  const COMPACT_TIMEOUT_MS = 300_000;
39
+ // How often a target holding a remote compaction request checks whether it can start.
40
+ const COMPACT_WAIT_CHECK_MS = 500;
38
41
  const RECONNECT_DELAY_MS = 2000;
39
42
  // Bounds the HTTP Upgrade only. Without it `ws` waits forever, so a listener that
40
43
  // accepts the socket and never answers leaves the terminal offline with no retry.
@@ -107,7 +110,7 @@ interface CompactResponseMsg {
107
110
  from: string;
108
111
  to: string;
109
112
  ok: boolean;
110
- reason?: string; // "busy" | "not_found" | "unsupported" | error text; absent on success
113
+ reason?: string; // a code compactReasonText() reads, or error text; absent on success
111
114
  }
112
115
 
113
116
  type LinkStatus =
@@ -144,6 +147,29 @@ function piVersionSupported(version: string): boolean {
144
147
  return true; // exactly the floor
145
148
  }
146
149
 
150
+ /**
151
+ * The reason a `compact_response` gives, as the requester shows it. The wire keeps
152
+ * 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)
154
+ * or `unsupported`.
155
+ */
156
+ function compactReasonText(reason: string | undefined): string {
157
+ switch (reason) {
158
+ case "busy":
159
+ return "target busy";
160
+ case "not_found":
161
+ return "target not found";
162
+ case "unsupported":
163
+ return "compaction unavailable on target";
164
+ case "already_requested":
165
+ return "target already has a compaction request waiting or running";
166
+ case "tree_navigated":
167
+ return "target navigated its session tree while the request waited";
168
+ default:
169
+ return reason ?? "failed";
170
+ }
171
+ }
172
+
147
173
  // keyText is empty when app.tools.expand has no binding, and the native hint would then
148
174
  // read " to expand" with no key in it, naming nothing the reader can press.
149
175
  function expansionHint(dim: (text: string) => string): string {
@@ -201,14 +227,14 @@ export default function (pi: ExtensionAPI) {
201
227
  }
202
228
 
203
229
  pi.registerFlag("link", {
204
- description: "Connect to link on startup",
230
+ description: "Connect to the link on startup",
205
231
  type: "boolean",
206
232
  default: false,
207
233
  });
208
234
 
209
235
  pi.registerFlag("link-name", {
210
236
  description:
211
- "Set the pi-link terminal name on startup (link identity only; does not affect session)",
237
+ "Set the link name on startup (link identity only; does not affect session)",
212
238
  type: "string",
213
239
  });
214
240
 
@@ -229,8 +255,12 @@ export default function (pi: ExtensionAPI) {
229
255
 
230
256
  // Status tracking (local truth)
231
257
  let agentRunning = false; // agent_start until agent_settled, not until agent_end
232
- let compactRunning = false; // true while compacting for a remote request
233
- let localCompacting = false; // true while compacting for a human /compact
258
+ let compactRunning = false; // gate held while running a remote compaction request
259
+ // The one remote compaction request this terminal holds, from receipt until it is
260
+ // answered. compactWaitTimer is set exactly while it waits to start.
261
+ let remoteCompact: CompactRequestMsg | null = null;
262
+ let compactWaitTimer: ReturnType<typeof setTimeout> | undefined;
263
+ let localCompacting = false; // gate set by Pi's manual-reason hook (human or remote)
234
264
  let compactDeadline: ReturnType<typeof setTimeout> | undefined;
235
265
  let wasCompactionGated = false; // gate state syncCompactionStatus() last acted on
236
266
  // toolCallId → toolName. Pi runs tools in parallel by default and both tool
@@ -267,21 +297,16 @@ export default function (pi: ExtensionAPI) {
267
297
  };
268
298
  let connectionAttempt: ConnectionAttempt | null = null;
269
299
 
270
- // Pending compact responses (sender waiting for remote compaction to finish)
271
- const pendingCompactResponses = new Map<
272
- string,
273
- {
274
- resolve: (result: {
275
- content: { type: "text"; text: string }[];
276
- details: Record<string, unknown>;
277
- }) => void;
278
- targetName: string;
279
- timeout: ReturnType<typeof setTimeout>;
280
- }
281
- >();
300
+ // link_compact requests this terminal sent and still tracks: request ID → requested
301
+ // target. The first outcome reported ends tracking; a response arriving after that
302
+ // is ignored. There is no deadline, because a target may wait indefinitely before
303
+ // it starts.
304
+ const pendingCompactResponses = new Map<string, string>();
282
305
 
283
- // Inbox: fixed-window batching; every batch is delivered to the receiver's model
284
- const inbox: { from: string; content: string }[] = [];
306
+ // Inbox: fixed-window batching; every batch is delivered to the receiver's model.
307
+ // Each entry is one rendered block: a received chat, or the outcome of a
308
+ // link_compact this terminal requested.
309
+ const inbox: string[] = [];
285
310
  let flushTimer: ReturnType<typeof setTimeout> | null = null;
286
311
 
287
312
  // ── Helpers ──────────────────────────────────────────────────────────────
@@ -320,7 +345,7 @@ export default function (pi: ExtensionAPI) {
320
345
  // the same condition rather than two that can disagree. In reachable states it
321
346
  // competes only with "idle" — a compaction runs with no tool and no agent run —
322
347
  // but where it could overlap, the gate is the more actionable fact: work sent
323
- // here waits, and link_compact declines.
348
+ // here waits, and so does a link_compact request.
324
349
  if (compactionGated()) return { kind: "compacting", since: stateSince };
325
350
  const tool = displayedTool();
326
351
  if (tool) return { kind: "tool", toolName: tool, since: stateSince };
@@ -488,9 +513,9 @@ export default function (pi: ExtensionAPI) {
488
513
  if (inbox.length === 0) return;
489
514
  if (!ctx) return;
490
515
 
491
- // Compacting: hold everything and return WITHOUT rescheduling. setCompacting()
492
- // drains on release, so polling a compaction that may run to the 300s ceiling
493
- // would be ~1500 wakeups for no information.
516
+ // 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.
494
519
  if (compactionGated()) return;
495
520
 
496
521
  // Select batch: up to BATCH_MAX_ITEMS, ~BATCH_MAX_CHARS total (soft cap —
@@ -498,8 +523,7 @@ export default function (pi: ExtensionAPI) {
498
523
  const batch: string[] = [];
499
524
  let totalChars = 0;
500
525
  for (let i = 0; i < inbox.length && batch.length < BATCH_MAX_ITEMS; i++) {
501
- const item = inbox[i];
502
- const text = `From "${item.from}":\n${item.content}`;
526
+ const text = inbox[i];
503
527
  if (batch.length > 0 && totalChars + text.length > BATCH_MAX_CHARS) break;
504
528
  batch.push(text);
505
529
  totalChars += text.length;
@@ -526,14 +550,16 @@ export default function (pi: ExtensionAPI) {
526
550
  * True exactly while delivery is deferred. Also what the terminal reports as its
527
551
  * status, so availability and delivery cannot disagree.
528
552
  *
529
- * The two flags are not duplication. compactRunning is set synchronously by the
530
- * compact_request handler before it calls ctx.compact(), covering the window
531
- * before session_before_compact arrives; localCompacting covers a human /compact,
532
- * which pi-link never initiates.
553
+ * The two flags are not duplication. compactRunning is set synchronously when a
554
+ * remote request starts, before ctx.compact() is called, covering the window
555
+ * before session_before_compact arrives. localCompacting is set by that hook for
556
+ * reason "manual", whether initiated by a human or a remote request that reaches
557
+ * the hook. It can survive a failed compaction, so a gate is not proof of a live
558
+ * compaction process.
533
559
  *
534
560
  * Both are load-bearing because Pi will not save us here: AgentSession.prompt()
535
- * refuses to run during compaction, but sendCustomMessage reaches _runAgentPrompt
536
- * directly and is not covered by that guard.
561
+ * refuses to run during compaction, but sendCustomMessage starts a run directly,
562
+ * bypassing prompt()'s guard.
537
563
  */
538
564
  function compactionGated() {
539
565
  return localCompacting || compactRunning;
@@ -560,14 +586,15 @@ export default function (pi: ExtensionAPI) {
560
586
  }
561
587
 
562
588
  /**
563
- * Drain the inbox once NO gate remains. Call after clearing either flag.
589
+ * Schedule inbox delivery once NO gate remains. Call after clearing either flag.
564
590
  *
565
- * Both gates must be checked together, because a remote compact sets both:
566
- * ctx.compact() reaches Pi's compact(), which reports reason "manual", so
567
- * session_before_compact sets localCompacting on top of compactRunning. Pi emits
568
- * session_compact strictly before it resolves and fires onComplete, so releasing
569
- * on either flag alone can arm a flush that finds the other flag still standing,
570
- * returns without rescheduling, and strands the inbox with no release left.
591
+ * Both gates must be checked together, because a remote compact can set both:
592
+ * ctx.compact() reaches Pi's compact(), which reports reason "manual". If it reaches
593
+ * session_before_compact, that hook sets localCompacting on top of compactRunning;
594
+ * an early rejection may never reach the hook. Pi emits session_compact strictly
595
+ * before it resolves and fires onComplete, so releasing on either flag alone can
596
+ * arm a flush that finds the other flag still standing, returns without
597
+ * rescheduling, and strands the inbox with no release left.
571
598
  */
572
599
  function releaseInbox() {
573
600
  if (!localCompacting && !compactRunning && inbox.length > 0) {
@@ -576,7 +603,7 @@ export default function (pi: ExtensionAPI) {
576
603
  }
577
604
 
578
605
  /**
579
- * Gate and release inbox delivery around a local manual compaction.
606
+ * Gate and release inbox delivery for Pi's manual-reason compaction hook.
580
607
  *
581
608
  * The deadline is the only backstop pi-link uses. Pi 0.84.3+ reports failure and
582
609
  * abort through `session_compact_failed`, which pi-link does not handle (see
@@ -584,9 +611,6 @@ export default function (pi: ExtensionAPI) {
584
611
  * compaction-ending event it handles. The timer handle must be explicit
585
612
  * and cleared on every transition: a bare setTimeout outlives its own
586
613
  * compaction and would release a *later* compaction's flag.
587
- *
588
- * COMPACT_TIMEOUT_MS also bounds the remote-request wait. The two share a
589
- * value, not a meaning: nothing here depends on their being equal.
590
614
  */
591
615
  function setCompacting(on: boolean) {
592
616
  localCompacting = on;
@@ -594,7 +618,7 @@ export default function (pi: ExtensionAPI) {
594
618
  compactDeadline = on
595
619
  ? setTimeout(() => setCompacting(false), COMPACT_TIMEOUT_MS)
596
620
  : undefined;
597
- // Release drains; it never polls. Nothing else wakes a waiting inbox.
621
+ // Release schedules delivery; it never polls.
598
622
  if (!on) releaseInbox();
599
623
  syncCompactionStatus();
600
624
  }
@@ -611,12 +635,119 @@ export default function (pi: ExtensionAPI) {
611
635
 
612
636
  // ── Pending compact helpers ──────────────────────────────────────────────
613
637
 
614
- function cleanupPendingCompact(requestId: string) {
615
- const pending = pendingCompactResponses.get(requestId);
616
- if (!pending) return null;
617
- clearTimeout(pending.timeout);
638
+ /**
639
+ * End tracking of a link_compact request and report its outcome to this terminal's
640
+ * model through the inbox, so it is delivered like a received message. The line
641
+ * names the requested target, never a response's `from`: a hub-synthesized
642
+ * not_found comes from the hub. It carries no `From` header, because the outcome
643
+ * may come from the hub or from this terminal rather than from the target.
644
+ */
645
+ function reportCompact(requestId: string, outcome: string) {
646
+ const targetName = pendingCompactResponses.get(requestId);
647
+ if (targetName === undefined) return;
618
648
  pendingCompactResponses.delete(requestId);
619
- return pending;
649
+ inbox.push(`link_compact "${targetName}" [${requestId}]: ${outcome}`);
650
+ scheduleFlush(FLUSH_DELAY_MS);
651
+ }
652
+
653
+ // ── Remote compaction requests (target side) ─────────────────────────────
654
+
655
+ function answerCompact(
656
+ request: CompactRequestMsg,
657
+ ok: boolean,
658
+ reason?: string,
659
+ ) {
660
+ routeMessage({
661
+ type: "compact_response",
662
+ id: request.id,
663
+ from: terminalName,
664
+ to: request.from,
665
+ ok,
666
+ reason,
667
+ });
668
+ }
669
+
670
+ /**
671
+ * Whether a remote request has to wait before it starts. Pi's idle state is the
672
+ * authority on whether this terminal is working; agentRunning is not: Pi may still
673
+ * 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.
678
+ */
679
+ function remoteCompactMustWait(context: ExtensionContext) {
680
+ return !context.isIdle() || compactionGated();
681
+ }
682
+
683
+ /**
684
+ * Start the held remote request once the terminal is free, checking again every
685
+ * COMPACT_WAIT_CHECK_MS until then. Polling, because no Pi event marks every
686
+ * 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
689
+ * messages are still delivered, and one delivered into Pi's work keeps the
690
+ * terminal busy. One still in the inbox's batching window does not: it can lose
691
+ * to the start, and is then held until the compaction ends.
692
+ *
693
+ * Observing idle and then calling ctx.compact() is not atomic: work another
694
+ * extension or Pi itself starts in between can still be aborted by compact().
695
+ * A request served on arrival has always had the same window.
696
+ */
697
+ function startRemoteCompactWhenFree(
698
+ request: CompactRequestMsg,
699
+ context: ExtensionContext,
700
+ ) {
701
+ if (remoteCompactMustWait(context)) {
702
+ compactWaitTimer = setTimeout(
703
+ () => startRemoteCompactWhenFree(request, context),
704
+ COMPACT_WAIT_CHECK_MS,
705
+ );
706
+ return;
707
+ }
708
+ compactWaitTimer = undefined;
709
+ let finished = false;
710
+ const finish = (ok: boolean, reason?: string) => {
711
+ if (finished) return;
712
+ finished = true;
713
+ remoteCompact = null;
714
+ compactRunning = false;
715
+ releaseInbox(); // last gate may clear here, after session_compact already fired
716
+ // Only reverts status if localCompacting is also clear. A failure after
717
+ // session_before_compact leaves it standing, so the terminal keeps
718
+ // reporting the hold as compacting until the deadline, agent_start,
719
+ // or a later successful compaction.
720
+ syncCompactionStatus();
721
+ answerCompact(request, ok, reason);
722
+ };
723
+ compactRunning = true;
724
+ syncCompactionStatus();
725
+ // Pi reports the compaction's outcome through these callbacks once compact()
726
+ // settles; finish() clears compactRunning and answers the request, once. A
727
+ // failure is answered, not retried.
728
+ try {
729
+ context.compact({
730
+ customInstructions: request.instructions,
731
+ onComplete: () => finish(true),
732
+ onError: (e) =>
733
+ finish(false, e instanceof Error ? e.message : String(e)),
734
+ });
735
+ } catch (e) {
736
+ finish(false, e instanceof Error ? e.message : String(e));
737
+ }
738
+ }
739
+
740
+ /**
741
+ * End the held remote request if it is still waiting, and return it. A running
742
+ * one is left to finish.
743
+ */
744
+ function dropWaitingRemoteCompact() {
745
+ if (compactWaitTimer === undefined) return null;
746
+ clearTimeout(compactWaitTimer);
747
+ compactWaitTimer = undefined;
748
+ const request = remoteCompact;
749
+ remoteCompact = null;
750
+ return request;
620
751
  }
621
752
 
622
753
  function allTerminalNames(): Set<string> {
@@ -718,9 +849,9 @@ export default function (pi: ExtensionAPI) {
718
849
 
719
850
  /**
720
851
  * Route a message to its destination. Works in both hub and client roles.
721
- * Returns true if the message was delivered (or sent to the hub for routing).
722
- * For the hub, this is authoritative. For clients, it's optimistic (hub may
723
- * still reject via protocol-level error responses).
852
+ * Returns true after local handling or handoff to a connection, not a receipt ACK.
853
+ * The hub resolves the recipient locally; a client hands routing to the hub,
854
+ * which may still reject via protocol-level error responses.
724
855
  */
725
856
  function routeMessage(
726
857
  msg: ChatMsg | CompactRequestMsg | CompactResponseMsg,
@@ -754,7 +885,7 @@ export default function (pi: ExtensionAPI) {
754
885
 
755
886
  if (msg.from === terminalName) {
756
887
  // For compact_request, deliver the error response locally so the
757
- // matching pending map resolves. For chat, skip — the tool result
888
+ // pending request reports it. For chat, skip — the tool result
758
889
  // (via return false) is sufficient; no extra UI toast.
759
890
  if (errorMsg.type === "compact_response") handleIncoming(errorMsg);
760
891
  } else {
@@ -798,7 +929,7 @@ export default function (pi: ExtensionAPI) {
798
929
  }
799
930
  updateStatus();
800
931
  notify(
801
- `Joined link as "${terminalName}" (${visibleTerminals().length} online)`,
932
+ `Joined the link as "${terminalName}" (${visibleTerminals().length} online)`,
802
933
  "info",
803
934
  );
804
935
  pushStatus(true);
@@ -819,17 +950,10 @@ export default function (pi: ExtensionAPI) {
819
950
  terminalStatuses.delete(msg.name);
820
951
  terminalCwds.delete(msg.name);
821
952
  terminalContexts.delete(msg.name);
822
- // Fail any pending compact request to the departed terminal
823
- for (const [id, pending] of pendingCompactResponses) {
824
- if (pending.targetName === msg.name) {
825
- cleanupPendingCompact(id);
826
- pending.resolve(
827
- textResult(`Terminal "${msg.name}" disconnected`, {
828
- to: msg.name,
829
- error: "disconnected",
830
- }),
831
- );
832
- }
953
+ // A departed target can no longer answer; whether it compacted is unknown.
954
+ for (const [id, targetName] of pendingCompactResponses) {
955
+ if (targetName === msg.name)
956
+ reportCompact(id, "left the link before answering; result unknown");
833
957
  }
834
958
  updateStatus();
835
959
  if (groupOf(msg.name) === groupOf(terminalName))
@@ -845,95 +969,38 @@ export default function (pi: ExtensionAPI) {
845
969
 
846
970
  // ── Chat message ──
847
971
  case "chat":
848
- inbox.push({ from: msg.from, content: msg.content });
972
+ inbox.push(`From "${msg.from}":\n${msg.content}`);
849
973
  scheduleFlush(FLUSH_DELAY_MS);
850
974
  break;
851
975
 
852
976
  // ── Another terminal asks us to compact our context ──
853
977
  case "compact_request": {
854
- const { id, from } = msg;
855
- const respond = (ok: boolean, reason?: string) =>
856
- routeMessage({
857
- type: "compact_response",
858
- id,
859
- from: terminalName,
860
- to: from,
861
- ok,
862
- reason,
863
- });
864
- // Answered before the busy question, and not through finish(): no capability
865
- // and no context are refusals of a request we never took on, so nothing here
866
- // owns the gate to clear or the inbox to release.
867
- if (!ctx || !ctx.compact) {
868
- respond(false, "unsupported");
978
+ // A second request is refused at once rather than queued, merged or
979
+ // allowed to replace the held one.
980
+ if (remoteCompact) {
981
+ answerCompact(msg, false, "already_requested");
869
982
  break;
870
983
  }
871
- // Pi's idle state is the authority on whether this terminal is working.
872
- // agentRunning is not: Pi may still retry, run an automatic compaction, or
873
- // drain a queued continuation inside a run whose agent_end already fired, and
874
- // compact() would abort that work and compact the same branch a second time.
875
- // compactionGated() adds what Pi's idle flag cannot cover — a manual
876
- // compaction is not an agent run — and keeps declining while either gate
877
- // stands, so we never touch a compaction we did not start.
878
- if (!ctx.isIdle() || compactionGated()) {
879
- respond(false, "busy");
880
- break;
881
- }
882
- let finished = false;
883
- const finish = (ok: boolean, reason?: string) => {
884
- if (finished) return;
885
- finished = true;
886
- compactRunning = false;
887
- releaseInbox(); // last gate may clear here, after session_compact already fired
888
- // Only reverts status if localCompacting is also clear. A failure after
889
- // session_before_compact leaves it standing, so the terminal truthfully
890
- // keeps reporting compacting until the deadline or agent_start.
891
- syncCompactionStatus();
892
- respond(ok, reason);
893
- };
894
- compactRunning = true;
895
- syncCompactionStatus();
896
- notify(`"${from}" requested compact`, "info");
897
- // compact() aborts the current turn first, so the idle guard above
898
- // keeps us from interrupting active work. Pi reports the compaction's
899
- // outcome through these callbacks once compact() settles; finish() clears
900
- // compactRunning and answers the request.
901
- try {
902
- ctx.compact({
903
- customInstructions: msg.instructions,
904
- onComplete: () => finish(true),
905
- onError: (e) =>
906
- finish(false, e instanceof Error ? e.message : String(e)),
907
- });
908
- } catch (e) {
909
- finish(false, e instanceof Error ? e.message : String(e));
910
- }
984
+ // Messages are handled only while isRuntimeLive(), which requires ctx.
985
+ const context = ctx!;
986
+ remoteCompact = msg;
987
+ notify(
988
+ remoteCompactMustWait(context)
989
+ ? `"${msg.from}" asked this terminal to compact; waiting until it is idle`
990
+ : `"${msg.from}" asked this terminal to compact`,
991
+ "info",
992
+ );
993
+ startRemoteCompactWhenFree(msg, context);
911
994
  break;
912
995
  }
913
996
 
914
997
  // ── Response to a compact we requested ──
915
- case "compact_response": {
916
- const pending = cleanupPendingCompact(msg.id);
917
- if (pending) {
918
- // Use the requested target, not msg.from: a hub-synthesized
919
- // not_found response comes from the hub, not the target.
920
- const target = pending.targetName;
921
- if (msg.ok) {
922
- pending.resolve(
923
- textResult(`Compacted "${target}"`, { to: target }),
924
- );
925
- } else {
926
- const reason = msg.reason ?? "failed";
927
- pending.resolve(
928
- textResult(`Compact on "${target}" not done: ${reason}`, {
929
- to: target,
930
- error: reason,
931
- }),
932
- );
933
- }
934
- }
998
+ case "compact_response":
999
+ reportCompact(
1000
+ msg.id,
1001
+ msg.ok ? "compacted" : `not done: ${compactReasonText(msg.reason)}`,
1002
+ );
935
1003
  break;
936
- }
937
1004
 
938
1005
  case "error":
939
1006
  notify(`Link: ${msg.message}`, "error");
@@ -1115,7 +1182,7 @@ export default function (pi: ExtensionAPI) {
1115
1182
  });
1116
1183
 
1117
1184
  server.on("error", () => {
1118
- // Port in use → someone else is the hub
1185
+ // Listen failed; a port conflict is possible, but does not prove another hub.
1119
1186
  settle(false);
1120
1187
  });
1121
1188
 
@@ -1193,7 +1260,7 @@ export default function (pi: ExtensionAPI) {
1193
1260
  updateStatus();
1194
1261
 
1195
1262
  if (!manuallyDisconnected) {
1196
- notify("Disconnected from link hub", "warning");
1263
+ notify("Disconnected from the link hub; reconnecting...", "warning");
1197
1264
  scheduleReconnect();
1198
1265
  }
1199
1266
  });
@@ -1243,7 +1310,8 @@ export default function (pi: ExtensionAPI) {
1243
1310
  if (await startHub(attempt)) return;
1244
1311
  if (!attemptIsCurrent(attempt)) return;
1245
1312
 
1246
- // Port busy but couldn't connect (rare race). Retry after delay.
1313
+ // Establishment failed (e.g. a race, port conflict, or other listen failure).
1314
+ // Retry after delay.
1247
1315
  scheduleReconnect();
1248
1316
  } finally {
1249
1317
  // Only while still the owner: an attempt cancelled mid-flight must not clear
@@ -1297,15 +1365,22 @@ export default function (pi: ExtensionAPI) {
1297
1365
  // This also clears the reconnect and startup timers.
1298
1366
  cancelConnectionAttempt();
1299
1367
 
1300
- // Clear link-owned remote compaction state; a local /compact survives disconnect.
1368
+ // A remote request still waiting is dropped unanswered: the link it would answer
1369
+ // 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.
1372
+ dropWaitingRemoteCompact();
1301
1373
  compactRunning = false;
1302
1374
  // Runs before role is cleared, so peers still get a final status; more to the
1303
1375
  // point, the local gate record stays honest for the reconnect.
1304
1376
  syncCompactionStatus();
1305
- for (const [id, pending] of pendingCompactResponses) {
1306
- cleanupPendingCompact(id);
1307
- pending.resolve(
1308
- textResult("Link disconnected", { error: "disconnected" }),
1377
+ // A response could only arrive over the link being closed. The inbox survives
1378
+ // disconnect, so these are delivered once no gate holds it; on shutdown,
1379
+ // cleanup() clears them with the rest of the inbox.
1380
+ for (const id of pendingCompactResponses.keys()) {
1381
+ reportCompact(
1382
+ id,
1383
+ "link disconnected before an answer; result unknown, the target may still be compacting",
1309
1384
  );
1310
1385
  }
1311
1386
 
@@ -1333,7 +1408,7 @@ export default function (pi: ExtensionAPI) {
1333
1408
  lastPushedStatus = null;
1334
1409
  updateStatus();
1335
1410
 
1336
- // Inbox survives disconnect; flush unless a local /compact still gates it.
1411
+ // Inbox survives disconnect; schedule delivery unless localCompacting still holds it.
1337
1412
  releaseInbox();
1338
1413
  }
1339
1414
 
@@ -1448,14 +1523,14 @@ export default function (pi: ExtensionAPI) {
1448
1523
  // There is deliberately no abort listener: event.signal firing is not an ending.
1449
1524
  // Pi passes that signal into the summarizer and its compaction controller lives
1450
1525
  // until the catch/finally, so releasing on abort would re-open delivery while the
1451
- // aborted compaction is still unwinding. A cancelled compaction is released by
1452
- // the user's next run (agent_start) or by the deadline.
1526
+ // 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.
1453
1528
  //
1454
- // Accepted gap: compact() aborts, authorises and prepares *before* emitting this
1529
+ // Accepted gap: compact() aborts and prepares *before* emitting this
1455
1530
  // event, so a flush in that window can still start a turn against context about
1456
1531
  // to be rebuilt. The message itself survives — it is persisted and restored — so
1457
1532
  // only the turn is wasted. No heuristics to guess at the window. This is a
1458
- // manual-compaction limit only; remote compaction is already gated by
1533
+ // human /compact limit only; remote compaction is already gated by
1459
1534
  // compactRunning, set before ctx.compact() is ever called.
1460
1535
  if (event.reason === "manual") setCompacting(true);
1461
1536
  });
@@ -1471,6 +1546,11 @@ export default function (pi: ExtensionAPI) {
1471
1546
  });
1472
1547
 
1473
1548
  pi.on("session_tree", async () => {
1549
+ // A completed navigation moved the session off the branch a waiting request
1550
+ // was made for. Only a waiting request is ended; a running one is left to
1551
+ // finish and answer.
1552
+ const waiting = dropWaitingRemoteCompact();
1553
+ if (waiting) answerCompact(waiting, false, "tree_navigated");
1474
1554
  pushStatus(true); // context usage belongs to the active branch
1475
1555
  });
1476
1556
 
@@ -1518,7 +1598,7 @@ export default function (pi: ExtensionAPI) {
1518
1598
  }
1519
1599
 
1520
1600
  function notConnectedResult() {
1521
- return textResult("Not connected to link", { error: "not_connected" });
1601
+ return textResult("Not connected to the link", { error: "not_connected" });
1522
1602
  }
1523
1603
 
1524
1604
  // Collapsed one-line preview for the two outgoing tools. Whitespace is normalized so a
@@ -1555,14 +1635,26 @@ export default function (pi: ExtensionAPI) {
1555
1635
  );
1556
1636
  }
1557
1637
 
1558
- // Shared ✓/✗ result renderer for link_send and link_compact.
1638
+ // Shared ✓/✗ result renderer for link_send and link_compact. Host errors
1639
+ // (a failed validation, a blocked call, a throw) need not set details.error: Pi
1640
+ // flags them in the render context, Oh My Pi in result.isError, where the fourth
1641
+ // argument is the call's arguments instead.
1559
1642
  function renderIconResult(
1560
- result: { content: { type: string; text?: string }[]; details?: unknown },
1643
+ result: {
1644
+ content: { type: string; text?: string }[];
1645
+ details?: unknown;
1646
+ isError?: boolean;
1647
+ },
1561
1648
  theme: { fg(role: string, text: string): string },
1649
+ context?: { isError?: boolean },
1562
1650
  ) {
1563
1651
  const txt = result.content[0];
1564
1652
  const details = result.details as Record<string, unknown> | undefined;
1565
- const icon = details?.error
1653
+ const failed =
1654
+ context?.isError === true ||
1655
+ result.isError === true ||
1656
+ Boolean(details?.error);
1657
+ const icon = failed
1566
1658
  ? theme.fg("error", "✗ ")
1567
1659
  : theme.fg("success", "✓ ");
1568
1660
  return new Text(icon + (txt?.type === "text" ? txt.text : ""), 0, 0);
@@ -1575,8 +1667,10 @@ export default function (pi: ExtensionAPI) {
1575
1667
  name: "link_send",
1576
1668
  label: "Link Send",
1577
1669
  description: [
1578
- "Send a message to one other Pi terminal on the link.",
1670
+ "Send a message to one other Pi terminal on the link, using its exact name from link_list.",
1579
1671
  "The message always acts: it steers a busy receiver at its next safe boundary, or starts a turn on an idle one.",
1672
+ "To reply to a chat, use link_send to the sender in that chat's From block, even if it arrived while you were busy or alongside other chats in a batch; an ordinary reply stays local.",
1673
+ "Replies and compaction outcomes start a turn if you are idle, so no polling or sleeping is needed to receive them; link_list reports status, not replies or outcomes.",
1580
1674
  ].join(" "),
1581
1675
  promptSnippet:
1582
1676
  "Send a message to another Pi terminal on the local link network",
@@ -1606,12 +1700,16 @@ export default function (pi: ExtensionAPI) {
1606
1700
 
1607
1701
  const target = `"${params.to}"`;
1608
1702
  if (!delivered) {
1609
- return textResult(`Failed to send to ${target}`, {
1703
+ // The hub found no reachable target; a client's hub connection is not open.
1704
+ const reason =
1705
+ role === "hub" ? "target not found" : "connection to the link hub is not open";
1706
+ return textResult(`Failed to send to ${target}: ${reason}`, {
1610
1707
  to: params.to,
1611
1708
  error: "not_delivered",
1612
1709
  });
1613
1710
  }
1614
- // Hub delivery is authoritative; client delivery is optimistic (hub routes)
1711
+ // The hub hands off to the target connection; clients hand routing to the hub.
1712
+ // Neither transport handoff confirms receipt.
1615
1713
  const verb = role === "hub" ? "Sent to" : "Sent to hub for delivery to";
1616
1714
  return textResult(`${verb} ${target}`, { to: params.to });
1617
1715
  },
@@ -1632,7 +1730,8 @@ export default function (pi: ExtensionAPI) {
1632
1730
  return new Text(text, 0, 0);
1633
1731
  },
1634
1732
 
1635
- renderResult: (result, _options, theme) => renderIconResult(result, theme),
1733
+ renderResult: (result, _options, theme, context) =>
1734
+ renderIconResult(result, theme, context),
1636
1735
  });
1637
1736
 
1638
1737
  pi.registerTool({
@@ -1640,8 +1739,10 @@ export default function (pi: ExtensionAPI) {
1640
1739
  name: "link_compact",
1641
1740
  label: "Link Compact",
1642
1741
  description: [
1643
- "Ask another Pi terminal to compact its context window and wait until it finishes.",
1644
- "A target declines unless Pi reports its session idle and no compaction holds its gate, so an active run, retry, automatic compaction, queued continuation or reported `compacting` all decline.",
1742
+ "Ask another Pi terminal to compact its context window.",
1743
+ "Returns as soon as the request is sent, with its request ID; the outcome arrives later as a link notification naming the target and that ID.",
1744
+ "The target waits, with no deadline, until Pi reports its session idle and no compaction holds its gate, then compacts; an active run, retry, automatic compaction, queued continuation or reported `compacting` delays it, and the outcome can take that long.",
1745
+ "A target holds one request at a time and declines another while one waits or runs.",
1645
1746
  ].join(" "),
1646
1747
  promptSnippet: "Ask another Pi terminal to compact its context window",
1647
1748
  parameters: Type.Object({
@@ -1664,7 +1765,7 @@ export default function (pi: ExtensionAPI) {
1664
1765
  if (role === "disconnected") return notConnectedResult();
1665
1766
 
1666
1767
  if (params.to === terminalName) {
1667
- return textResult("Cannot compact yourself.", {
1768
+ return textResult("Cannot compact yourself", {
1668
1769
  to: params.to,
1669
1770
  error: "self_target",
1670
1771
  });
@@ -1674,62 +1775,31 @@ export default function (pi: ExtensionAPI) {
1674
1775
  if (miss) return miss;
1675
1776
 
1676
1777
  const requestId = crypto.randomUUID();
1778
+ // Tracked before routing, because the hub can synthesize a response in this
1779
+ // same stack. From here on the request belongs to the extension, not to this
1780
+ // call: the signal is not consulted again, and there is no remote cancel.
1781
+ pendingCompactResponses.set(requestId, params.to);
1677
1782
 
1678
- return new Promise((resolve) => {
1679
- const timeout = setTimeout(() => {
1680
- const pending = cleanupPendingCompact(requestId);
1681
- if (pending) {
1682
- pending.resolve(
1683
- textResult(
1684
- `Compact request to "${params.to}" timed out after ${COMPACT_TIMEOUT_MS / 1000}s; the target may still be compacting.`,
1685
- { to: params.to, error: "timeout" },
1686
- ),
1687
- );
1688
- }
1689
- }, COMPACT_TIMEOUT_MS);
1690
-
1691
- pendingCompactResponses.set(requestId, {
1692
- resolve,
1693
- targetName: params.to,
1694
- timeout,
1695
- });
1783
+ const delivered = routeMessage({
1784
+ type: "compact_request",
1785
+ id: requestId,
1786
+ from: terminalName,
1787
+ to: params.to,
1788
+ instructions: params.instructions,
1789
+ });
1696
1790
 
1697
- signal?.addEventListener(
1698
- "abort",
1699
- () => {
1700
- const pending = cleanupPendingCompact(requestId);
1701
- if (pending) {
1702
- pending.resolve(
1703
- textResult("Compact request aborted", {
1704
- to: params.to,
1705
- error: "aborted",
1706
- }),
1707
- );
1708
- }
1709
- },
1710
- { once: true },
1791
+ // Still tracked means it was never handed on. No longer tracked means it was
1792
+ // answered in this stack, and that outcome is already in the inbox.
1793
+ if (!delivered && pendingCompactResponses.delete(requestId)) {
1794
+ return textResult(
1795
+ `Failed to request compact on "${params.to}": connection to the link hub is not open`,
1796
+ { to: params.to, error: "not_delivered" },
1711
1797
  );
1712
-
1713
- const delivered = routeMessage({
1714
- type: "compact_request",
1715
- id: requestId,
1716
- from: terminalName,
1717
- to: params.to,
1718
- instructions: params.instructions,
1719
- });
1720
-
1721
- if (!delivered) {
1722
- const pending = cleanupPendingCompact(requestId);
1723
- if (pending) {
1724
- pending.resolve(
1725
- textResult(`Failed to request compact on "${params.to}"`, {
1726
- to: params.to,
1727
- error: "not_delivered",
1728
- }),
1729
- );
1730
- }
1731
- }
1732
- });
1798
+ }
1799
+ return textResult(
1800
+ `Compact request sent to "${params.to}" [${requestId}]; the result will arrive as a link notification.`,
1801
+ { to: params.to, id: requestId },
1802
+ );
1733
1803
  },
1734
1804
 
1735
1805
  renderCall(args, theme, context) {
@@ -1745,7 +1815,8 @@ export default function (pi: ExtensionAPI) {
1745
1815
  return new Text(text, 0, 0);
1746
1816
  },
1747
1817
 
1748
- renderResult: (result, _options, theme) => renderIconResult(result, theme),
1818
+ renderResult: (result, _options, theme, context) =>
1819
+ renderIconResult(result, theme, context),
1749
1820
  });
1750
1821
 
1751
1822
  pi.registerTool({
@@ -1810,7 +1881,8 @@ export default function (pi: ExtensionAPI) {
1810
1881
 
1811
1882
  let text = theme.fg("toolTitle", theme.bold("link "));
1812
1883
  text += theme.fg("muted", `(${details.role}) `);
1813
- text += theme.fg("accent", `${details.terminals.length} terminal(s)`);
1884
+ const count = details.terminals.length;
1885
+ text += theme.fg("accent", `${count} terminal${count !== 1 ? "s" : ""}`);
1814
1886
  for (const name of details.terminals) {
1815
1887
  const isSelf = name === details.self;
1816
1888
  const status = details.statuses?.[name] ?? "";
@@ -1834,7 +1906,7 @@ export default function (pi: ExtensionAPI) {
1834
1906
  description: "Show link status",
1835
1907
  handler: async (_args, _ctx) => {
1836
1908
  if (role === "disconnected") {
1837
- _ctx.ui.notify("Link: not connected", "warning");
1909
+ _ctx.ui.notify("Not connected to the link", "warning");
1838
1910
  return;
1839
1911
  }
1840
1912
  const visible = visibleTerminals();
@@ -1857,7 +1929,7 @@ export default function (pi: ExtensionAPI) {
1857
1929
  });
1858
1930
 
1859
1931
  pi.registerCommand("link-name", {
1860
- description: "Change link name. No arg = use session name",
1932
+ description: "Change link name (without an argument, use the session name)",
1861
1933
  handler: async (args, _ctx) => {
1862
1934
  let newName = normalizeName(args) ?? "";
1863
1935
  if (!newName) {
@@ -1946,15 +2018,17 @@ export default function (pi: ExtensionAPI) {
1946
2018
  handler: async (_args, _ctx) => {
1947
2019
  pi.appendEntry("link-active", { active: false });
1948
2020
  manuallyDisconnected = true;
1949
- if (role === "disconnected") {
1950
- // Nothing is established, but a startup or reconnect attempt may still be
1951
- // dialing or binding; persisted intent has to win over it too.
1952
- cancelConnectionAttempt();
1953
- _ctx.ui.notify("Link disconnected", "info");
1954
- return;
1955
- }
2021
+ // Also when nothing is established: a startup or reconnect attempt may still
2022
+ // be dialing or binding, and compact requests sent before the hub was lost are
2023
+ // still tracked. Persisted intent has to win over both.
2024
+ const wasConnected = role !== "disconnected";
1956
2025
  disconnect();
1957
- _ctx.ui.notify("Disconnected from link", "info");
2026
+ _ctx.ui.notify(
2027
+ wasConnected
2028
+ ? "Disconnected from the link; automatic reconnect disabled"
2029
+ : "Already disconnected; automatic reconnect disabled",
2030
+ "info",
2031
+ );
1958
2032
  },
1959
2033
  });
1960
2034
 
@@ -1977,10 +2051,11 @@ export default function (pi: ExtensionAPI) {
1977
2051
  // ── Message renderer ─────────────────────────────────────────────────────
1978
2052
 
1979
2053
  pi.registerMessageRenderer("link", (message, options, theme) => {
1980
- const from =
1981
- (message.details as Record<string, unknown> | undefined)?.from ?? "link";
2054
+ // Only messages restored from older sessions carry a sender in details.from. A
2055
+ // current batch has none: its content already opens with `[Link: ...]`.
2056
+ const from = (message.details as Record<string, unknown> | undefined)?.from;
1982
2057
  const text =
1983
- theme.fg("accent", `⚡ [${from}] `) +
2058
+ theme.fg("accent", from === undefined ? "⚡ " : `⚡ [${from}] `) +
1984
2059
  theme.fg("text", String(message.content));
1985
2060
  const content = new Text(text, 0, 0);
1986
2061
  // The same panel Pi draws around extension messages by default: returning our own