@cydm/pie 4.4.1 → 4.4.3

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 (47) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +6 -6
  2. package/dist/builtin/extensions/changelog/index.js +1 -1
  3. package/dist/builtin/extensions/cron/index.js +55 -7
  4. package/dist/builtin/extensions/document-attachments/index.js +1 -1
  5. package/dist/builtin/extensions/herdr-agent-state/index.js +1 -1
  6. package/dist/builtin/extensions/im-forward/README.md +3 -1
  7. package/dist/builtin/extensions/im-forward/index.js +98 -41
  8. package/dist/builtin/extensions/init/index.js +1 -1
  9. package/dist/builtin/extensions/mcp-adapter/index.js +2 -2
  10. package/dist/builtin/extensions/memory/index.js +9 -11
  11. package/dist/builtin/extensions/pie-ipc/index.js +306 -353
  12. package/dist/builtin/extensions/pie-proc/index.js +18 -12
  13. package/dist/builtin/extensions/plan-mode/index.js +6 -6
  14. package/dist/builtin/extensions/subagent/index.js +9 -11
  15. package/dist/builtin/extensions/todo/index.js +6 -6
  16. package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +24 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +86 -21
  18. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-cli.js +6 -1
  19. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  20. package/dist/builtin/skills/chrome-devtools-axi/{cli-CHC7XYFU.js → cli-NLPMVDGG.js} +32 -4
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +220 -22
  22. package/dist/chunks/{auth-storage-RABPRJ6T.js → auth-storage-C3FZMT7J.js} +3 -3
  23. package/dist/chunks/{chunk-R7VO46EK.js → chunk-3W3SXVPB.js} +5 -4
  24. package/dist/chunks/{chunk-IPLMGAML.js → chunk-5KI4Y4LA.js} +1 -1
  25. package/dist/chunks/{chunk-YNTIOWCD.js → chunk-BLDI2GRF.js} +5 -5
  26. package/dist/chunks/{chunk-UCKOXAME.js → chunk-CBDQJMUI.js} +9 -44
  27. package/dist/chunks/chunk-CGSFBWOM.js +100 -0
  28. package/dist/chunks/{chunk-AKXEZH7K.js → chunk-JMKLTTZQ.js} +89 -107
  29. package/dist/chunks/{chunk-7LTQLJJF.js → chunk-LAJXWOKS.js} +15 -10
  30. package/dist/chunks/{chunk-RZGYXAJU.js → chunk-LZQXQOPJ.js} +1 -12
  31. package/dist/chunks/{chunk-EQOI6RZV.js → chunk-NHV2CALB.js} +3 -5
  32. package/dist/chunks/{chunk-OV7SLSHR.js → chunk-SW2E33UL.js} +2 -4
  33. package/dist/chunks/{chunk-BPSCGGVF.js → chunk-XXGYUYXI.js} +1 -1
  34. package/dist/chunks/{chunk-XO3NM7BB.js → chunk-Y3I2UV5Y.js} +3 -3
  35. package/dist/chunks/{chunk-IZDNZW3S.js → chunk-Z2FKA2ZH.js} +8 -8
  36. package/dist/chunks/chunk-ZPJ3BNQB.js +126 -0
  37. package/dist/chunks/{config-HF2PDLN5.js → config-4EOI5NOU.js} +2 -4
  38. package/dist/chunks/{manager-cli-BYCF4RKN.js → manager-cli-WEHNUV5T.js} +3 -5
  39. package/dist/chunks/{model-registry-7FNIUYPF.js → model-registry-3XAHXXTA.js} +5 -5
  40. package/dist/chunks/{src-OVWRBWKU.js → src-B44QWSGM.js} +4 -4
  41. package/dist/chunks/{src-A5YI46OD.js → src-CLE5ILN4.js} +6 -6
  42. package/dist/chunks/{src-OA3TP6DS.js → src-EGXFJ3WA.js} +5 -5
  43. package/dist/chunks/{src-TF2RAGRU.js → src-Q7LU27C2.js} +3 -3
  44. package/dist/chunks/{test-stream-7YZDGBPO.js → test-stream-OR3EJBNF.js} +3 -3
  45. package/dist/cli.js +128 -132
  46. package/package.json +3 -3
  47. package/dist/chunks/chunk-7KLWHWZD.js +0 -164
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  Type
4
- } from "../../../chunks/chunk-BPSCGGVF.js";
4
+ } from "../../../chunks/chunk-XXGYUYXI.js";
5
5
  import {
6
6
  DEFAULT_SEND_WAIT_MS,
7
7
  DISPATCH_PREFIX,
@@ -10,15 +10,16 @@ import {
10
10
  IpcTransport,
11
11
  MAX_BODY_CHARS,
12
12
  MAX_INBOX_MESSAGES,
13
- MAX_STATUS_BODY_CHARS,
14
13
  MAX_STATUS_FILE_BYTES,
15
14
  assistantBodyText,
16
15
  clipBody,
16
+ currentImBinding,
17
17
  foldLifecycleEvent,
18
18
  generateInstanceId,
19
19
  isTurnUserImDriven,
20
20
  isValidInstanceId,
21
21
  isWrappedInboundText,
22
+ onImBindingChanged,
22
23
  parseStatusFile,
23
24
  peerHealth,
24
25
  peerLabel,
@@ -26,8 +27,9 @@ import {
26
27
  takeDispatchFrame,
27
28
  wrapInboundText,
28
29
  wrappedMessageMarker
29
- } from "../../../chunks/chunk-AKXEZH7K.js";
30
- import "../../../chunks/chunk-RZGYXAJU.js";
30
+ } from "../../../chunks/chunk-JMKLTTZQ.js";
31
+ import "../../../chunks/chunk-ZPJ3BNQB.js";
32
+ import "../../../chunks/chunk-LZQXQOPJ.js";
31
33
 
32
34
  // builtin/extensions/pie-ipc/index.ts
33
35
  import * as fs3 from "node:fs";
@@ -434,80 +436,6 @@ function startHeartbeat(discoveryDir, file, intervalMs, write = (next) => writeS
434
436
  timer.unref?.();
435
437
  return () => clearInterval(timer);
436
438
  }
437
- function watchDiscoveryDir(discoveryDir, onChange) {
438
- let watcher = null;
439
- let closed = false;
440
- const lastEvents = /* @__PURE__ */ new Map();
441
- let identity = "";
442
- const directoryIdentity = () => {
443
- const stats = fs2.lstatSync(discoveryDir);
444
- return `${stats.dev}:${stats.ino}`;
445
- };
446
- const attach = () => {
447
- if (closed) return;
448
- try {
449
- const attachWatch = () => fs2.watch(discoveryDir, (_event, filename) => {
450
- const name = String(filename ?? "");
451
- if (!name.endsWith(".json")) return;
452
- const now = Date.now();
453
- const id = name.slice(0, -".json".length);
454
- if (!isValidInstanceId(id) || now - (lastEvents.get(name) ?? 0) < 50) return;
455
- if (lastEvents.size >= 1024) lastEvents.clear();
456
- lastEvents.set(name, now);
457
- if (!readStatusFile(discoveryDir, id)) return;
458
- try {
459
- onChange(id);
460
- } catch {
461
- }
462
- });
463
- const verifiedAttach = () => {
464
- identity = directoryIdentity();
465
- return attachWatch();
466
- };
467
- watcher = process.platform === "win32" ? windowsSecurity().pin(discoveryDir, false, verifiedAttach) : verifiedAttach();
468
- for (const { file } of listPeers(discoveryDir, { pruneDead: false })) {
469
- try {
470
- onChange(file.instanceId);
471
- } catch {
472
- }
473
- }
474
- } catch {
475
- watcher?.close();
476
- watcher = null;
477
- }
478
- const attached = watcher;
479
- const detached = () => {
480
- if (watcher === attached) watcher = null;
481
- };
482
- attached?.on("error", () => {
483
- attached.close();
484
- detached();
485
- });
486
- attached?.on("close", detached);
487
- watcher?.unref?.();
488
- };
489
- attach();
490
- const retry = setInterval(() => {
491
- if (closed) return;
492
- if (watcher) {
493
- try {
494
- if (directoryIdentity() === identity) return;
495
- } catch {
496
- }
497
- const stale = watcher;
498
- watcher = null;
499
- stale.close();
500
- }
501
- attach();
502
- }, 500);
503
- retry.unref?.();
504
- return () => {
505
- closed = true;
506
- clearInterval(retry);
507
- watcher?.close();
508
- watcher = null;
509
- };
510
- }
511
439
  function buildStatusFile(input) {
512
440
  return {
513
441
  schema: 1,
@@ -567,8 +495,6 @@ var InboundDelivery = class {
567
495
  this.host = host;
568
496
  this.options = options;
569
497
  this.autoInject = options.autoInject;
570
- this.degradeAfterMisses = options.degradeAfterMisses ?? 3;
571
- this.verifyDeadlineMs = options.verifyDeadlineMs ?? 3e4;
572
498
  }
573
499
  host;
574
500
  options;
@@ -576,22 +502,14 @@ var InboundDelivery = class {
576
502
  pending = /* @__PURE__ */ new Map();
577
503
  droppedCount = { value: 0 };
578
504
  autoInject;
579
- consecutiveMisses = 0;
580
- degradeAfterMisses;
581
- verifyDeadlineMs;
582
- /** Degraded = autoInject force-disabled after repeated delivery misses. */
583
- degraded = false;
584
- /** Counters surfaced by /tools/ipc status. */
585
- counters = { injected: 0, queued: 0, dropped: 0, denied: 0, degradedAt: 0, recovered: 0 };
586
505
  get effectiveAutoInject() {
587
- return this.autoInject && !this.degraded;
506
+ return this.autoInject;
588
507
  }
508
+ /** Mute toggle (/tools/ipc mute): the only inject control left — the
509
+ * degrade machinery is gone (astra audit #1), so this is purely the
510
+ * user's explicit choice. */
589
511
  setAutoInject(enabled) {
590
512
  this.autoInject = enabled;
591
- if (enabled) {
592
- this.degraded = false;
593
- this.consecutiveMisses = 0;
594
- }
595
513
  }
596
514
  /** Route one inbound message envelope. Returns the routing decision. */
597
515
  routeMessage(envelope, displayName) {
@@ -607,7 +525,6 @@ var InboundDelivery = class {
607
525
  return "denied";
608
526
  }
609
527
  if (!this.options.allowPolicy.allows(envelope.from)) {
610
- this.counters.denied += 1;
611
528
  this.host.notify?.(`pie-ipc: message from unapproved peer ${peerLabel(envelope.from, displayName)} \u2014 run /tools/ipc allow`, "warning");
612
529
  return "denied";
613
530
  }
@@ -623,7 +540,6 @@ var InboundDelivery = class {
623
540
  if (this.options.onProtocolFrame && this.options.protocolFramePrefix && message.text.trimStart().startsWith(this.options.protocolFramePrefix)) {
624
541
  try {
625
542
  if (this.options.onProtocolFrame(message.text)) {
626
- this.counters.injected += 1;
627
543
  return "injected";
628
544
  }
629
545
  } catch (error) {
@@ -650,42 +566,25 @@ var InboundDelivery = class {
650
566
  inject(message) {
651
567
  const wrapped = wrapInboundText(message.fromLabel, message.text, message.receivedAt, message.id);
652
568
  const marker = wrappedMessageMarker(wrapped) ?? message.id;
653
- const entry = {
654
- marker,
655
- message,
656
- injectedAt: Date.now(),
657
- timer: setTimeout(() => {
658
- try {
659
- this.noteMiss(message);
660
- } catch {
661
- }
662
- }, this.verifyDeadlineMs)
663
- };
664
- entry.timer.unref?.();
665
- this.pending.set(marker, entry);
666
- this.counters.injected += 1;
569
+ this.pending.set(marker, { marker, message });
667
570
  try {
668
571
  this.host.sendUserMessage(wrapped);
669
572
  } catch {
670
- clearTimeout(entry.timer);
671
573
  if (this.pending.has(marker)) this.enqueueInbox(message);
672
574
  }
673
- this.updateStatus();
674
575
  }
675
576
  enqueueInbox(message) {
676
577
  this.inbox.push(message);
677
- this.counters.queued += 1;
678
578
  if (this.inbox.length > MAX_INBOX_MESSAGES) {
679
579
  this.inbox.shift();
680
580
  this.droppedCount.value += 1;
681
- this.counters.dropped += 1;
682
581
  this.host.notify?.("pie-ipc: inbox full; oldest message dropped", "warning");
683
582
  }
684
- this.updateStatus();
685
583
  }
686
584
  /**
687
- * Called on user message:end — verify pending injections against the
688
- * settled user text. Timeout alone never moves a queued input to the inbox.
585
+ * Called on user message:end — confirm CONSUMPTION of pending injections
586
+ * against the settled user text (the result-ledger axis: onConsumed moves
587
+ * the sender's record accepted→running and arms the completion push).
689
588
  */
690
589
  onUserMessageEnd(message) {
691
590
  const text = deliveredUserText(message);
@@ -696,41 +595,23 @@ var InboundDelivery = class {
696
595
  if (!entry) return;
697
596
  const recovered = this.inbox.findIndex((item) => item.id === entry.message.id);
698
597
  if (recovered >= 0) this.inbox.splice(recovered, 1);
699
- this.options.onConsumed?.(entry.message.id);
700
- clearTimeout(entry.timer);
701
598
  this.pending.delete(marker);
702
- this.consecutiveMisses = 0;
703
- this.host.log("pie-ipc: injection delivery verified");
704
- this.updateStatus();
705
- }
706
- noteMiss(message) {
707
- this.consecutiveMisses += 1;
708
- this.host.log(`pie-ipc: injection ${message.id} not observed (miss ${this.consecutiveMisses})`);
709
- if (this.consecutiveMisses >= this.degradeAfterMisses) {
710
- this.degraded = true;
711
- this.counters.degradedAt = Date.now();
712
- this.host.notify?.(
713
- `pie-ipc: injected messages stopped landing ${this.consecutiveMisses}x \u2014 auto-inject disabled, messages now wait in the inbox (/tools/ipc poll)`,
714
- "warning"
715
- );
716
- }
717
- this.updateStatus();
599
+ this.options.onConsumed?.(entry.message.id);
600
+ this.host.log("pie-ipc: injection consumed");
718
601
  }
719
602
  /** Drain the inbox (ipc_poll). Messages leave the inbox permanently. */
720
603
  drainInbox(limit = 20) {
721
604
  if (this.inbox.length === 0) return [];
722
- const drained = this.inbox.splice(0, Math.max(0, Math.min(100, Math.floor(limit))));
723
- this.updateStatus();
724
- return drained;
605
+ return this.inbox.splice(0, Math.max(0, Math.min(100, Math.floor(limit))));
725
606
  }
726
607
  get inboxSize() {
727
608
  return this.inbox.length;
728
609
  }
729
610
  /** Would an inbound message be INJECTED right now (vs inbox-queued)?
730
- * Mirrors routeMessage's live decision — auto-inject mode, degradation,
731
- * and pending capacity — so consumers (the notify fallback) act on
732
- * EFFECTIVE delivery, not host capability (a muted TUI queues like an
733
- * embedded host). */
611
+ * Mirrors routeMessage's live decision — auto-inject mode and pending
612
+ * capacity — so consumers (the notify fallback) act on EFFECTIVE
613
+ * delivery, not host capability (a muted TUI queues like an embedded
614
+ * host). */
734
615
  willInjectNow() {
735
616
  return this.hasUIInjection() && this.effectiveAutoInject && this.pending.size < MAX_INBOX_MESSAGES;
736
617
  }
@@ -747,46 +628,17 @@ var InboundDelivery = class {
747
628
  get overflowDropped() {
748
629
  return this.droppedCount.value;
749
630
  }
750
- /** Clear inbox + verification state on session switch. */
631
+ /** Clear inbox + consumption state on session switch. */
751
632
  resetSessionState() {
752
633
  this.inbox.length = 0;
753
- for (const entry of this.pending.values()) {
754
- clearTimeout(entry.timer);
755
- }
756
634
  this.pending.clear();
757
- this.degraded = false;
758
- this.consecutiveMisses = 0;
759
- this.updateStatus();
760
- }
761
- updateStatus() {
762
- try {
763
- if (!this.host.setStatus) return;
764
- if (this.inbox.length > 0) {
765
- const suffix = this.degraded ? " (degraded)" : "";
766
- this.host.setStatus("pie-ipc", `ipc inbox ${this.inbox.length}${suffix}`);
767
- } else if (this.degraded) {
768
- this.host.setStatus("pie-ipc", "ipc auto-inject degraded; /tools/ipc poll");
769
- } else {
770
- this.host.setStatus("pie-ipc", void 0);
771
- }
772
- } catch (error) {
773
- this.host.log(`pie-ipc: status update failed: ${error instanceof Error ? error.message : String(error)}`);
774
- }
775
635
  }
776
636
  };
777
637
 
778
638
  // builtin/extensions/pie-ipc/status.ts
779
639
  var StatusProjection = class {
780
- constructor(host) {
781
- this.host = host;
782
- }
783
- host;
784
640
  shape = { state: "idle" };
785
- lastBodyText = "";
786
- lastBodyAt = 0;
787
- undelivered = 0;
788
641
  tools = /* @__PURE__ */ new Map();
789
- bodyStart = 0;
790
642
  get state() {
791
643
  return this.shape.state;
792
644
  }
@@ -812,40 +664,10 @@ var StatusProjection = class {
812
664
  const after = this.shape.state + (this.shape.blockedSince ?? "") + (this.shape.currentTool ?? "");
813
665
  return before !== after;
814
666
  }
815
- /** A turn settled: harvest the final body text from the tail. */
816
- onTurnSettled() {
817
- const messages = this.host.getMessages();
818
- for (let index = messages.length - 1; index >= this.bodyStart; index -= 1) {
819
- const text = assistantBodyText(messages[index]);
820
- if (text) {
821
- this.lastBodyText = clipBody(text, MAX_STATUS_BODY_CHARS);
822
- this.lastBodyAt = Date.now();
823
- return;
824
- }
825
- }
826
- }
827
- /** Called when an injection may not have been consumed yet. */
828
- noteInjectionDelivered() {
829
- this.undelivered += 1;
830
- }
831
- /** Called at turn:start — queued injections are being consumed now. */
832
- onTurnStarted() {
833
- this.undelivered = 0;
834
- this.bodyStart = this.host.getMessages().length;
835
- this.shape = { ...this.shape, currentTool: void 0 };
836
- }
837
- /** Session switch: lifecycle and answer state do not carry over. */
667
+ /** Session switch: lifecycle state does not carry over. */
838
668
  resetSessionState() {
839
669
  this.shape = { state: "idle" };
840
670
  this.tools.clear();
841
- this.bodyStart = this.host.getMessages().length;
842
- this.lastBodyText = "";
843
- this.lastBodyAt = 0;
844
- this.undelivered = 0;
845
- }
846
- /** Body text used to answer waiting ipc_send_notify peers. */
847
- lastBodyForReply() {
848
- return this.lastBodyText;
849
671
  }
850
672
  snapshot(base) {
851
673
  return {
@@ -854,9 +676,10 @@ var StatusProjection = class {
854
676
  currentTool: this.shape.currentTool,
855
677
  blockedSince: this.shape.blockedSince,
856
678
  turnStartedAt: this.shape.turnStartedAt,
857
- undeliveredInjections: this.undelivered,
858
- lastBodyText: this.lastBodyText || void 0,
859
- lastBodyAt: this.lastBodyAt || void 0
679
+ // The delivery engine's pending count is the live undelivered figure;
680
+ // the projection's own counter was dead (astra audit) — currentStatus
681
+ // overwrites this field from delivery before publication anyway.
682
+ undeliveredInjections: 0
860
683
  };
861
684
  }
862
685
  };
@@ -1011,6 +834,8 @@ function resultJson(payload) {
1011
834
 
1012
835
  // builtin/extensions/pie-ipc/index.ts
1013
836
  var DEFAULT_NOTIFY_FALLBACK_MS = 6e5;
837
+ var FALLBACK_RENEWAL_CAP = 4;
838
+ var PROBE_CACHE_MS = 2e3;
1014
839
  var Runtime = class {
1015
840
  constructor(ctx, config, discoveryDir) {
1016
841
  this.ctx = ctx;
@@ -1018,7 +843,8 @@ var Runtime = class {
1018
843
  this.discoveryDir = discoveryDir;
1019
844
  this.displayName = config.displayName ?? peerLabel(this.instanceId);
1020
845
  this.allowPolicy = new AllowPolicy(config.allowPeers ? [...config.allowPeers] : ["*"]);
1021
- this.projection = new StatusProjection({ getMessages: () => ctx.getMessages() });
846
+ this.projection = new StatusProjection();
847
+ this.stopImBinding = onImBindingChanged(() => this.writeStatus());
1022
848
  }
1023
849
  ctx;
1024
850
  config;
@@ -1029,8 +855,6 @@ var Runtime = class {
1029
855
  projection;
1030
856
  /** Shared allow policy: /tools/ipc allow affects delivery AND state.get gates. */
1031
857
  allowPolicy;
1032
- /** Inbound messages we accepted for a turn; answered on turn settle. */
1033
- awaitingReply = /* @__PURE__ */ new Map();
1034
858
  /** Completion subscriptions (notifyCompletion senders): deliveryId ->
1035
859
  * { peer, requestId }. One best-effort push per entry when the consuming
1036
860
  * turn settles (success/failure/cancel); entries never outlive the ledger
@@ -1042,12 +866,17 @@ var Runtime = class {
1042
866
  * if the peer's push never arrives, wake ourselves once to check
1043
867
  * ipc_result. Cleared when the notification (or its inbox delivery)
1044
868
  * lands, so a delivered notification never double-wakes. */
1045
- notifyFallbacks = /* @__PURE__ */ new Map();
1046
- /** Notify-mode sends whose completion push already landed — including the
1047
- * completion-BEFORE-ack window (the reverse push can win the race). Bounded
1048
- * by the same retention discipline as the fallbacks: entries leave with
1049
- * their timer or when the check hint fires. */
869
+ /** Query-first fallback OPERATIONS by requestId (review r4): one record
870
+ * owns the whole lifecycle (armed timer + in-flight query + renewals).
871
+ * Keyed like the old timer map so capacity counting and completion
872
+ * cancellation cover the async query window too. */
873
+ fallbackOps = /* @__PURE__ */ new Map();
874
+ /** Bounded completion tombstones shared by push and fallback recovery,
875
+ * including completion-before-ack. Retained after ack to suppress late
876
+ * pushes; cleared on session change/disposal or capacity rollover. */
1050
877
  completedNotifies = /* @__PURE__ */ new Set();
878
+ /** Fresh pre-send probes by peer instance id (plan v2-A rate budget). */
879
+ probeCache = /* @__PURE__ */ new Map();
1051
880
  /** Session/lifecycle generation for outbound notify continuations (review
1052
881
  * r4): sendToPeer awaits transport.send across session switches; a late
1053
882
  * null/ack continuation must not arm fallback state (or later fire its
@@ -1068,7 +897,7 @@ var Runtime = class {
1068
897
  sessionName;
1069
898
  statusBase;
1070
899
  stopHeartbeat = null;
1071
- stopWatch = null;
900
+ stopImBinding;
1072
901
  /** Server role: listen, advertise, watch peers. Publishes only after the
1073
902
  * listener is up (headless instances never publish). */
1074
903
  async startServer() {
@@ -1100,9 +929,6 @@ var Runtime = class {
1100
929
  listPeers(this.discoveryDir, { selfId: this.instanceId, pruneDead: true });
1101
930
  return this.currentStatus();
1102
931
  }, HEARTBEAT_INTERVAL_MS, void 0, (message) => this.ctx.log(message));
1103
- this.stopWatch = watchDiscoveryDir(this.discoveryDir, () => {
1104
- this.ctx.ui.setStatus?.("pie-ipc-peers", void 0);
1105
- });
1106
932
  }
1107
933
  currentStatus() {
1108
934
  const liveName = this.ctx.getSessionName?.();
@@ -1115,7 +941,9 @@ var Runtime = class {
1115
941
  sessionId: this.sessionId,
1116
942
  sessionName: this.sessionName,
1117
943
  ...displaySessionName ? { displaySessionName } : {},
1118
- ...typeof model === "string" && model ? { model } : {}
944
+ ...typeof model === "string" && model ? { model } : {},
945
+ isManager: this.ctx.capabilities?.unattended === true && process.env.PIE_PROC_CURATED_NAME === "manager",
946
+ imBinding: currentImBinding()
1119
947
  });
1120
948
  return { ...snapshot, allowPeers: [...this.allowPolicy.snapshot()], undeliveredInjections: this.delivery?.undeliveredInjections ?? snapshot.undeliveredInjections ?? 0 };
1121
949
  }
@@ -1137,10 +965,15 @@ var Runtime = class {
1137
965
  });
1138
966
  };
1139
967
  switch (envelope.kind) {
1140
- case "ping":
1141
- reply("ack", "pong");
1142
- return;
1143
968
  case "control": {
969
+ if (this.sessionId === null) {
970
+ reply("ack", JSON.stringify({ ok: false, message: "session binding in progress; retry shortly" }));
971
+ return;
972
+ }
973
+ if (envelope.sessionId !== this.sessionId) {
974
+ reply("ack", JSON.stringify({ ok: false, message: "target session changed" }));
975
+ return;
976
+ }
1144
977
  if (!this.allowPolicy.allows(envelope.from)) {
1145
978
  reply("ack", JSON.stringify({ ok: false, message: "denied by local allow policy" }));
1146
979
  return;
@@ -1174,11 +1007,7 @@ var Runtime = class {
1174
1007
  currentTool: status.currentTool,
1175
1008
  blockedSince: status.blockedSince,
1176
1009
  turnStartedAt: status.turnStartedAt,
1177
- undeliveredInjections: status.undeliveredInjections,
1178
- lastBodyText: status.lastBodyText,
1179
- lastBodyAt: status.lastBodyAt,
1180
- sessionId: status.sessionId,
1181
- displayName: status.displayName
1010
+ undeliveredInjections: status.undeliveredInjections
1182
1011
  }));
1183
1012
  return;
1184
1013
  }
@@ -1221,33 +1050,25 @@ var Runtime = class {
1221
1050
  }
1222
1051
  const doneMatch = /^\[ipc-done\] requestId=([a-zA-Z0-9:-]{1,128}) /.exec(envelope.text ?? "");
1223
1052
  if (doneMatch && this.allowPolicy.allows(envelope.from)) {
1053
+ if (this.completedNotifies.has(doneMatch[1])) {
1054
+ reply("ack", "completion already delivered");
1055
+ return;
1056
+ }
1224
1057
  const stampedDone = /^\[ipc-done\] requestId=[a-zA-Z0-9:-]{1,128} (?:outcome=\S+ )?(?:\([^)]*\) )?user_assigned=true(?:\s|$)/.test((envelope.text ?? "").split("\n")[0] ?? "");
1225
1058
  this.completeNotify(doneMatch[1], stampedDone);
1226
1059
  }
1227
- if (envelope.waitMs && this.awaitingReply.size >= 100) {
1228
- reply("result", "rejected: reply capacity reached");
1060
+ if (envelope.waitMs && envelope.waitMs > 0) {
1061
+ reply("result", "rejected: wait=true is no longer supported; resend without wait, or subscribe (default) and pull via ipc_result");
1229
1062
  return;
1230
1063
  }
1231
1064
  const deliveryId = `${envelope.from}:${envelope.id}`;
1232
- if (envelope.waitMs && envelope.waitMs > 0) {
1233
- const timer = setTimeout(() => this.finishReply(deliveryId, "expired: input not answered within waitMs"), envelope.waitMs);
1234
- timer.unref();
1235
- const disconnected = () => this.finishReply(deliveryId, "cancelled: requester disconnected");
1236
- this.awaitingReply.set(deliveryId, { reply: (text) => reply("result", text), timer, consumed: false, body: "", detach: () => signal?.removeEventListener("abort", disconnected) });
1237
- if (signal?.aborted) {
1238
- this.finishReply(deliveryId, "cancelled: requester disconnected");
1239
- return;
1240
- }
1241
- signal?.addEventListener("abort", disconnected, { once: true });
1242
- }
1243
1065
  if (!this.allowPolicy.allows(envelope.from)) {
1244
1066
  this.delivery?.routeMessage({ ...envelope, id: deliveryId }, this.displayNameOf(envelope.from));
1245
- this.finishReply(deliveryId, "denied: not on this peer's allow list (/tools/ipc allow)");
1246
- if (!envelope.waitMs) reply("result", "denied: not allowed");
1067
+ reply("result", "denied: not on this peer's allow list (/tools/ipc allow)");
1247
1068
  return;
1248
1069
  }
1249
1070
  this.results.accept(envelope.from, envelope.id, this.sessionId ?? "");
1250
- if (envelope.notifyCompletion && !envelope.waitMs) {
1071
+ if (envelope.notifyCompletion) {
1251
1072
  if (this.completionWatchers.size >= 100) {
1252
1073
  const oldest = this.completionWatchers.keys().next().value;
1253
1074
  if (oldest !== void 0) {
@@ -1262,8 +1083,7 @@ var Runtime = class {
1262
1083
  if (decision === "denied") {
1263
1084
  this.results.remove(deliveryId);
1264
1085
  this.completionWatchers.delete(deliveryId);
1265
- this.finishReply(deliveryId, "denied: not on this peer's allow list (/tools/ipc allow)");
1266
- if (!envelope.waitMs) reply("result", "denied: not allowed");
1086
+ reply("result", "denied: not on this peer's allow list (/tools/ipc allow)");
1267
1087
  return;
1268
1088
  }
1269
1089
  reply("ack", decision);
@@ -1282,7 +1102,6 @@ var Runtime = class {
1282
1102
  case "turn:start": {
1283
1103
  this.executionFailure = void 0;
1284
1104
  this.active = true;
1285
- this.projection.onTurnStarted();
1286
1105
  if (this.projection.updateFromEvent(event)) this.writeStatus();
1287
1106
  return;
1288
1107
  }
@@ -1297,7 +1116,6 @@ var Runtime = class {
1297
1116
  case "agent:end":
1298
1117
  case "turn:failed":
1299
1118
  case "turn:cancelled": {
1300
- this.projection.onTurnSettled();
1301
1119
  if (this.projection.updateFromEvent(event)) this.writeStatus();
1302
1120
  this.answerAwaitingPeers(event.type !== "agent:end" || Boolean(this.executionFailure));
1303
1121
  this.active = false;
@@ -1314,7 +1132,6 @@ var Runtime = class {
1314
1132
  this.notifyGeneration++;
1315
1133
  this.projection.resetSessionState();
1316
1134
  this.executionFailure = void 0;
1317
- for (const id of [...this.awaitingReply.keys()]) this.finishReply(id, "cancelled: target session changed");
1318
1135
  this.active = false;
1319
1136
  this.writeStatus();
1320
1137
  return;
@@ -1338,7 +1155,6 @@ var Runtime = class {
1338
1155
  }
1339
1156
  const body = message && !this.executionFailure ? assistantBodyText(message) : "";
1340
1157
  if (body) {
1341
- for (const [id, waiter] of this.awaitingReply) if (waiter.consumed) waiter.body = body;
1342
1158
  this.results.captureBody(body);
1343
1159
  }
1344
1160
  }
@@ -1348,31 +1164,13 @@ var Runtime = class {
1348
1164
  return;
1349
1165
  }
1350
1166
  }
1351
- /**
1352
- * When a turn settles, every peer message that opened (or queued into)
1353
- * this turn gets the assistant body as its awaited result. Failed/cancelled
1354
- * turns answer with an explanatory text instead.
1355
- */
1167
+ /** Consumption (message:end of the injected marker) moves the sender's
1168
+ * ledger record accepted->running; the completion push fires at turn
1169
+ * settlement through the ledger, not through held sockets. */
1356
1170
  markConsumed(id) {
1357
- const waiter = this.awaitingReply.get(id);
1358
- if (waiter && this.active) waiter.consumed = true;
1359
1171
  if (this.active) this.results.markRunning(id);
1360
1172
  }
1361
- finishReply(id, text) {
1362
- const waiter = this.awaitingReply.get(id);
1363
- if (!waiter) return;
1364
- this.awaitingReply.delete(id);
1365
- clearTimeout(waiter.timer);
1366
- waiter.detach();
1367
- try {
1368
- waiter.reply(clipBody(text));
1369
- } catch {
1370
- }
1371
- }
1372
1173
  answerAwaitingPeers(failed) {
1373
- for (const [id, waiter] of [...this.awaitingReply]) {
1374
- if (waiter.consumed) this.finishReply(id, failed ? "(peer turn failed or was cancelled)" : waiter.body || "(empty reply)");
1375
- }
1376
1174
  this.results.finishRunning(failed ? "(peer turn failed or was cancelled)" : "(empty reply)", failed);
1377
1175
  this.pushCompletionNotifications();
1378
1176
  }
@@ -1425,40 +1223,154 @@ ${body}` : ""}`;
1425
1223
  }).catch(() => void 0);
1426
1224
  this.ctx.log(`pie-ipc: completion notification sent to ${watcher.peer} for ${watcher.requestId} (${outcome})`);
1427
1225
  }
1428
- /** Arm the local fallback check for a notify-mode send: on expiry, inject a
1429
- * hint so the model checks ipc_result itself. The wake goes through the
1430
- * normal inbound path (sendUserMessage), which the interactive host queues
1431
- * when busy and the embedded host emits as a user.message event. */
1432
- armNotifyFallback(requestId, fallbackMs, peerName, userAssigned = false) {
1433
- if (this.completedNotifies.has(requestId)) {
1434
- this.completedNotifies.delete(requestId);
1435
- return true;
1436
- }
1437
- if (this.notifyFallbacks.size >= 20) {
1438
- this.ctx.log(`pie-ipc: fallback budget exhausted (${this.notifyFallbacks.size} outstanding); no timer for ${requestId}`);
1226
+ /** Arm the local fallback check for a notify-mode send. QUERY-FIRST
1227
+ * (plan v2-B): on expiry the timer PULLS the peer's result ledger over
1228
+ * the socket first; only an unresolvable pull (unknown/peer gone, or
1229
+ * renewals exhausted on a still-working peer) injects the [ipc-check]
1230
+ * wake. The wake goes through the normal inbound path (sendUserMessage),
1231
+ * which the interactive host queues when busy and the embedded host
1232
+ * emits as a user.message event. */
1233
+ armNotifyFallback(requestId, fallbackMs, peerName, userAssigned = false, peerRef, targetIdentity) {
1234
+ if (this.completedNotifies.has(requestId)) return true;
1235
+ if (this.fallbackOps.size >= 20) {
1236
+ this.ctx.log(`pie-ipc: fallback budget exhausted (${this.fallbackOps.size} outstanding); no timer for ${requestId}`);
1439
1237
  return false;
1440
1238
  }
1441
- this.clearNotifyFallback(requestId);
1442
- const timer = setTimeout(() => {
1443
- this.notifyFallbacks.delete(requestId);
1444
- this.completedNotifies.delete(requestId);
1445
- if (this.disposed) return;
1446
- const hintBody = `[ipc-check] No completion notification arrived for requestId=${requestId}${userAssigned ? " user_assigned=true" : ""} (peer ${peerName}) within ${Math.round(fallbackMs / 1e3)}s. Query ipc_result for the authoritative status; accepted/running means the peer is still working \u2014 keep waiting or check again later, and never resend while a result is pending.`;
1447
- const hint = wrapInboundText(`local-recovery (${peerName})`, hintBody);
1448
- try {
1449
- const scope = this.ctx.beginUserInput?.();
1450
- if (scope) {
1451
- scope.submit(hint).then(() => scope.dispose(), () => scope.dispose());
1452
- } else {
1453
- this.ctx.sendUserMessage(hint);
1454
- }
1455
- } catch {
1239
+ this.fallbackOps.get(requestId)?.finish?.();
1240
+ this.completedNotifies.delete(requestId);
1241
+ const budgetMs = Math.max(5e3, Math.min(fallbackMs, 6e5));
1242
+ const armGeneration = this.notifyGeneration;
1243
+ const op = { cancelled: false };
1244
+ this.fallbackOps.set(requestId, op);
1245
+ let renewals = 0;
1246
+ const finishOp = () => {
1247
+ op.cancelled = true;
1248
+ if (op.timer) {
1249
+ clearTimeout(op.timer);
1250
+ op.timer = void 0;
1456
1251
  }
1457
- }, Math.max(5e3, Math.min(fallbackMs, 6e5)));
1252
+ if (this.fallbackOps.get(requestId) === op) this.fallbackOps.delete(requestId);
1253
+ };
1254
+ op.finish = finishOp;
1255
+ const alive = () => !this.disposed && !op.cancelled && this.notifyGeneration === armGeneration;
1256
+ const fire = () => {
1257
+ op.timer = void 0;
1258
+ if (!alive()) {
1259
+ finishOp();
1260
+ return;
1261
+ }
1262
+ void this.fallbackCheckResult(requestId, peerRef ?? peerName, targetIdentity).then((outcome) => {
1263
+ if (!alive()) {
1264
+ finishOp();
1265
+ return;
1266
+ }
1267
+ if (this.completedNotifies.has(requestId)) {
1268
+ finishOp();
1269
+ return;
1270
+ }
1271
+ if (typeof outcome === "object") {
1272
+ void this.handleEnvelope({
1273
+ v: IPC_PROTOCOL_VERSION,
1274
+ id: `notify-${outcome.peer}-${requestId}`,
1275
+ from: outcome.peer,
1276
+ to: this.instanceId,
1277
+ kind: "message",
1278
+ createdAt: Date.now(),
1279
+ sessionId: this.sessionId ?? "",
1280
+ text: `[ipc-done] requestId=${requestId} outcome=${outcome.status}${userAssigned ? " user_assigned=true" : ""}
1281
+ ${outcome.text}`
1282
+ }, () => {
1283
+ });
1284
+ this.ctx.log(`pie-ipc: fallback pull recovered a terminal result for ${requestId}`);
1285
+ finishOp();
1286
+ return;
1287
+ }
1288
+ if (outcome === "running" && renewals < FALLBACK_RENEWAL_CAP) {
1289
+ renewals += 1;
1290
+ const again = setTimeout(fire, budgetMs);
1291
+ again.unref?.();
1292
+ op.timer = again;
1293
+ this.ctx.log(`pie-ipc: fallback pull shows the peer still working on ${requestId}; silent renewal ${renewals}/${FALLBACK_RENEWAL_CAP}`);
1294
+ return;
1295
+ }
1296
+ finishOp();
1297
+ this.wakeModelForFallback(requestId, peerName, userAssigned, outcome === "running" ? `renewal budget exhausted (${FALLBACK_RENEWAL_CAP}) while the peer still reports working` : void 0);
1298
+ }).catch(() => {
1299
+ if (!alive()) {
1300
+ finishOp();
1301
+ return;
1302
+ }
1303
+ finishOp();
1304
+ this.wakeModelForFallback(requestId, peerName, userAssigned);
1305
+ });
1306
+ };
1307
+ const timer = setTimeout(fire, budgetMs);
1458
1308
  timer.unref();
1459
- this.notifyFallbacks.set(requestId, timer);
1309
+ op.timer = timer;
1460
1310
  return true;
1461
1311
  }
1312
+ /** One fallback pull: query the peer's result ledger over the socket and
1313
+ * classify the outcome for the query-first timer. Never throws — a
1314
+ * transport failure IS the "unknown" answer that warrants a wake.
1315
+ * REQUEST OWNERSHIP (review r4-P2): when the caller captured the original
1316
+ * send's target identity, the query binds to THAT instance (falling back
1317
+ * to a live re-resolve only for legacy callers) — a peer restart or name
1318
+ * transfer must not redirect the authoritative ledger lookup to a
1319
+ * different instance. */
1320
+ async fallbackCheckResult(requestId, peerRef, targetIdentity) {
1321
+ let instanceId = targetIdentity?.instanceId;
1322
+ let port;
1323
+ let sessionId = targetIdentity?.sessionId;
1324
+ if (instanceId) {
1325
+ const snapshot = readStatusFile(this.discoveryDir, instanceId);
1326
+ if (!snapshot?.port) return "unknown";
1327
+ port = snapshot.port;
1328
+ sessionId = targetIdentity?.sessionId ?? "";
1329
+ } else {
1330
+ const target = this.resolvePeer(peerRef);
1331
+ if (!target?.port) return "unknown";
1332
+ instanceId = target.instanceId;
1333
+ port = target.port;
1334
+ sessionId = target.sessionId ?? "";
1335
+ }
1336
+ if (!this.transport) return "unknown";
1337
+ try {
1338
+ const reply = await this.transport.send(instanceId, port, "result.get", {
1339
+ text: JSON.stringify({ requestId }),
1340
+ sessionId,
1341
+ expectReply: true,
1342
+ waitMs: 3e3,
1343
+ replyKinds: /* @__PURE__ */ new Set(["result"])
1344
+ });
1345
+ if (!reply?.text) return "unknown";
1346
+ const parsed = JSON.parse(reply.text);
1347
+ if (parsed.status === "done" || parsed.status === "failed") {
1348
+ if (parsed.requestId !== requestId || parsed.sessionId !== sessionId || !this.allowPolicy.allows(instanceId)) return "unknown";
1349
+ return { peer: instanceId, status: parsed.status, text: typeof parsed.text === "string" ? parsed.text : "" };
1350
+ }
1351
+ if (parsed.status === "accepted" || parsed.status === "running") return "running";
1352
+ return "unknown";
1353
+ } catch {
1354
+ return "unknown";
1355
+ }
1356
+ }
1357
+ /** The one remaining wake path for the fallback timer: the pull could not
1358
+ * resolve the request (peer gone, ledger evicted, session switched, or
1359
+ * renewals exhausted on a wedged peer). Injects the [ipc-check] hint via
1360
+ * the same draft-preserving submission the old timer used. */
1361
+ wakeModelForFallback(requestId, peerName, userAssigned, extra) {
1362
+ const hintBody = `[ipc-check] No completion notification arrived for requestId=${requestId}${userAssigned ? " user_assigned=true" : ""} (peer ${peerName}).${extra ? ` ${extra}.` : " The result pull returned unknown \u2014 the peer may be gone or its session changed."} Query ipc_result for the authoritative status; accepted/running means the peer is still working \u2014 keep waiting or check again later, and never resend while a result is pending.`;
1363
+ const hint = wrapInboundText(`local-recovery (${peerName})`, hintBody);
1364
+ try {
1365
+ const scope = this.ctx.beginUserInput?.();
1366
+ if (scope) {
1367
+ scope.submit(hint).then(() => scope.dispose(), () => scope.dispose());
1368
+ } else {
1369
+ this.ctx.sendUserMessage(hint);
1370
+ }
1371
+ } catch {
1372
+ }
1373
+ }
1462
1374
  /** A completion notification (or its inbox delivery) landed for our send.
1463
1375
  * Observability-aware (final audit): an INJECTING host shows the message
1464
1376
  * to the model the moment it lands — the fallback timer dies (single
@@ -1474,35 +1386,29 @@ ${body}` : ""}`;
1474
1386
  }
1475
1387
  if (this.completedNotifies.size > 200) this.completedNotifies.clear();
1476
1388
  this.completedNotifies.add(requestId);
1477
- const timer = this.notifyFallbacks.get(requestId);
1478
- if (timer) {
1479
- clearTimeout(timer);
1480
- this.notifyFallbacks.delete(requestId);
1481
- }
1389
+ this.fallbackOps.get(requestId)?.finish?.();
1482
1390
  if (this.disposed) return;
1483
1391
  try {
1484
1392
  const stamped = userAssigned ? " user_assigned=true" : "";
1485
- const body = `[ipc-done-check] The completion notification for requestId=${requestId}${stamped} is waiting in the ipc inbox (this host is not auto-injecting right now \u2014 muted, degraded, or embedded). Call ipc_poll to read it; the outcome line starts with [ipc-done]. Do not resend.`;
1393
+ const body = `[ipc-done-check] The completion notification for requestId=${requestId}${stamped} is waiting in the ipc inbox (this host is not auto-injecting right now \u2014 muted or embedded). Call ipc_poll to read it; the outcome line starts with [ipc-done]. Do not resend.`;
1486
1394
  this.ctx.sendUserMessage(wrapInboundText("local-inbox-wake", body));
1487
1395
  } catch {
1488
1396
  }
1489
1397
  }
1490
1398
  /** A completion notification (or its inbox delivery) landed for our send:
1491
- * destroy the fallback timer so the model is woken exactly once. Also
1492
- * records completion for sends whose push arrived BEFORE the ack did —
1493
- * armNotifyFallback then arms nothing. */
1399
+ * destroy the fallback OPERATION so the model is woken exactly once —
1400
+ * including a query-in-flight fallback (review r4-P1): finishOp cancels
1401
+ * the in-flight continuation, which then exits without renewing or
1402
+ * waking. Also records completion for sends whose push arrived BEFORE
1403
+ * the ack did — armNotifyFallback then arms nothing. */
1494
1404
  clearNotifyFallback(requestId) {
1495
1405
  if (this.completedNotifies.size > 200) this.completedNotifies.clear();
1496
1406
  this.completedNotifies.add(requestId);
1497
- const timer = this.notifyFallbacks.get(requestId);
1498
- if (timer) {
1499
- clearTimeout(timer);
1500
- this.notifyFallbacks.delete(requestId);
1501
- }
1407
+ this.fallbackOps.get(requestId)?.finish?.();
1502
1408
  }
1503
1409
  clearNotifyFallbacks() {
1504
- for (const timer of this.notifyFallbacks.values()) clearTimeout(timer);
1505
- this.notifyFallbacks.clear();
1410
+ for (const op of this.fallbackOps.values()) op.finish?.();
1411
+ this.fallbackOps.clear();
1506
1412
  this.completedNotifies.clear();
1507
1413
  }
1508
1414
  // ---- mutations from commands ----
@@ -1548,8 +1454,7 @@ ${body}` : ""}`;
1548
1454
  const staticView = `${peerLabel(target.instanceId, target.displayName)} [${listPeers(this.discoveryDir, { selfId: this.instanceId, pruneDead: false }).find((entry) => entry.file.instanceId === target.instanceId)?.health ?? "unknown"}] ${target.state}`;
1549
1455
  if (!this.allowPolicy.allows(target.instanceId) || !(target.allowPeers?.includes("*") || target.allowPeers?.includes(this.instanceId))) return `${staticView}
1550
1456
  (content restricted by local allow policy)`;
1551
- const snapshot = `${staticView}${target.lastBodyText ? `
1552
- last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}`;
1457
+ const snapshot = staticView;
1553
1458
  if (!target.port || !this.transport) return `${snapshot}
1554
1459
  (no live listener; file view only)`;
1555
1460
  const reply = await this.transport.send(target.instanceId, target.port, "state.get", { expectReply: true, waitMs: 3e3 });
@@ -1563,7 +1468,6 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1563
1468
  if (typeof parsed.blockedSince === "number") lines.push(`blocked for ${Math.max(0, Math.round((Date.now() - parsed.blockedSince) / 1e3))}s`);
1564
1469
  if (typeof parsed.undeliveredInjections === "number" && parsed.undeliveredInjections > 0) lines.push(`undelivered injections: ${parsed.undeliveredInjections}`);
1565
1470
  if (parsed.restricted) lines.push("(peer restricts details for unapproved askers)");
1566
- if (typeof parsed.lastBodyText === "string" && parsed.lastBodyText) lines.push(`last body: ${clipBody(parsed.lastBodyText, 400)}`);
1567
1471
  return lines.join("\n");
1568
1472
  } catch {
1569
1473
  return `${staticView}
@@ -1633,7 +1537,10 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1633
1537
  if (!reply) return { content: [{ type: "text", text: `No receipt from ${peerLabel(target.instanceId, target.displayName)} within ${waitMs}ms \u2014 the control may or may not have landed; re-send is safe (controls are idempotent by contract).` }], isError: true };
1634
1538
  return { content: [{ type: "text", text: reply.text ?? "(empty receipt)" }] };
1635
1539
  }
1636
- async sendToPeer(peerRef, text, wait, waitMs, context, notify = false, fallbackMs = DEFAULT_NOTIFY_FALLBACK_MS) {
1540
+ async sendToPeer(peerRef, text, _wait, _waitMs, context, notify = false, fallbackMs = DEFAULT_NOTIFY_FALLBACK_MS) {
1541
+ if (_wait) {
1542
+ return { content: [{ type: "text", text: "wait=true is no longer supported: subscription mode (the default) plus ipc_result covers it \u2014 a held socket can never survive a long peer turn, which is exactly what subscription was built for." }], isError: true };
1543
+ }
1637
1544
  const target = this.resolvePeer(peerRef);
1638
1545
  if (!target) {
1639
1546
  return { content: [{ type: "text", text: `Peer not found: ${peerRef}. Call ipc_list_peers first.${this.livePeerHint()}` }], isError: true };
@@ -1646,8 +1553,23 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1646
1553
  }
1647
1554
  const body = clipBody(text, this.config.maxBodyChars);
1648
1555
  const requestId = randomUUID();
1649
- const notifyMode = notify && !wait;
1556
+ const notifyMode = notify;
1650
1557
  const sendGeneration = this.notifyGeneration;
1558
+ let congestion = "";
1559
+ {
1560
+ const now = Date.now();
1561
+ const cached2 = this.probeCache.get(target.instanceId);
1562
+ if (cached2 && now - cached2.at < PROBE_CACHE_MS) {
1563
+ congestion = this.describePeerCongestion(cached2.probe);
1564
+ } else {
1565
+ const probe = await this.probePeerLiveState(target);
1566
+ this.probeCache.set(target.instanceId, { at: Date.now(), probe });
1567
+ if (this.notifyGeneration !== sendGeneration) {
1568
+ return { content: [{ type: "text", text: `Local session changed during the pre-send probe \u2014 send aborted before any envelope left. Re-send in the new session if still needed. requestId=${requestId}` }], isError: true, details: { requestId } };
1569
+ }
1570
+ congestion = this.describePeerCongestion(probe);
1571
+ }
1572
+ }
1651
1573
  let userAssigned = false;
1652
1574
  if (notifyMode) {
1653
1575
  userAssigned = isTurnUserImDriven();
@@ -1656,12 +1578,12 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1656
1578
  requestId,
1657
1579
  text: body,
1658
1580
  sessionId: target.sessionId ?? "",
1659
- expectReply: wait,
1660
- waitMs,
1581
+ expectReply: false,
1582
+ waitMs: DEFAULT_SEND_WAIT_MS,
1661
1583
  signal: context.signal,
1662
- // Waiting sends resolve only on the peer's turn-settling result (or
1663
- // its terminal denied answer); the receipt ack stays informational.
1664
- replyKinds: wait ? /* @__PURE__ */ new Set(["result"]) : /* @__PURE__ */ new Set(["result", "ack"]),
1584
+ // Non-waiting sends resolve on the informational ack (or a terminal
1585
+ // denial result); the completion push rides its own envelope.
1586
+ replyKinds: /* @__PURE__ */ new Set(["result", "ack"]),
1665
1587
  ...notifyMode ? { notifyCompletion: true, awaitAck: true, subscriberSession: this.sessionId ?? "", ...userAssigned ? { userAssigned: true } : {} } : {}
1666
1588
  });
1667
1589
  if (notifyMode) {
@@ -1670,9 +1592,10 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1670
1592
  }
1671
1593
  if (!reply) {
1672
1594
  const peerName2 = peerLabel(target.instanceId, target.displayName);
1673
- const armed2 = this.armNotifyFallback(requestId, fallbackMs, peerName2, userAssigned);
1595
+ const armed2 = this.armNotifyFallback(requestId, fallbackMs, peerName2, userAssigned, peerRef, { instanceId: target.instanceId, sessionId: target.sessionId ?? void 0 });
1674
1596
  return {
1675
- content: [{ type: "text", text: `Receipt UNCONFIRMED \u2014 the request may already be accepted by ${peerName2} (accepted work is never cancelled). Query ipc_result with requestId=${requestId} before resending. ${armed2 ? `A fallback check is armed for ${Math.round(fallbackMs / 1e3)}s if the peer's completion push never arrives.` : "No automatic wake is armed (fallback budget exhausted) \u2014 check ipc_result yourself."}` }],
1597
+ content: [{ type: "text", text: `Receipt UNCONFIRMED \u2014 the request may already be accepted by ${peerName2} (accepted work is never cancelled). Query ipc_result with requestId=${requestId} before resending. ${armed2 ? `A fallback check is armed for ${Math.round(fallbackMs / 1e3)}s if the peer's completion push never arrives.` : "No automatic wake is armed (fallback budget exhausted) \u2014 check ipc_result yourself."}${congestion ? `
1598
+ ${congestion}` : ""}` }],
1676
1599
  isError: true,
1677
1600
  details: { requestId }
1678
1601
  };
@@ -1681,26 +1604,62 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1681
1604
  return { content: [{ type: "text", text: reply.text ?? "(empty reply)" }], isError: true, details: { requestId } };
1682
1605
  }
1683
1606
  const peerName = peerLabel(target.instanceId, target.displayName);
1684
- const armed = this.armNotifyFallback(requestId, fallbackMs, peerName, userAssigned);
1685
- return { content: [{ type: "text", text: armed ? `Sent to ${peerName} with completion subscription (receipt acked as ${reply.kind}; the peer pushes one [ipc-done] notification when its turn settles). If no notification arrives within ${Math.round(fallbackMs / 1e3)}s, check ipc_result with this requestId; do not resend on a pending result. requestId=${requestId}` : `Sent to ${peerName} with completion subscription (receipt acked). The local fallback-wake budget is exhausted (${this.notifyFallbacks.size} outstanding checks), so NO automatic wake is armed for this request \u2014 check ipc_result yourself when you need its result. requestId=${requestId}` }], details: { requestId } };
1607
+ const armed = this.armNotifyFallback(requestId, fallbackMs, peerName, userAssigned, peerRef, { instanceId: target.instanceId, sessionId: target.sessionId ?? void 0 });
1608
+ return { content: [{ type: "text", text: armed ? `Sent to ${peerName} with completion subscription (receipt acked as ${reply.kind}; the peer pushes one [ipc-done] notification when its turn settles). If no notification arrives within ${Math.round(fallbackMs / 1e3)}s, check ipc_result with this requestId; do not resend on a pending result.${congestion ? `
1609
+ ${congestion}` : ""} requestId=${requestId}` : `Sent to ${peerName} with completion subscription (receipt acked). The local fallback-wake budget is exhausted (${this.fallbackOps.size} outstanding checks), so NO automatic wake is armed for this request \u2014 check ipc_result yourself when you need its result.${congestion ? `
1610
+ ${congestion}` : ""} requestId=${requestId}` }], details: { requestId } };
1686
1611
  }
1687
- if (!wait) {
1612
+ if (!notifyMode) {
1688
1613
  if (!reply) return { content: [{ type: "text", text: `Send failed: ${peerLabel(target.instanceId, target.displayName)} unreachable. requestId=${requestId}` }], isError: true, details: { requestId } };
1689
- return { content: [{ type: "text", text: `Sent to ${peerLabel(target.instanceId, target.displayName)} (no wait; receipt/consumption not confirmed). requestId=${requestId}` }], details: { requestId } };
1690
- }
1691
- if (!reply) {
1692
- if (context.signal?.aborted) return { content: [{ type: "text", text: `Wait cancelled; already accepted peer input is not cancelled. requestId=${requestId}` }], isError: true, details: { requestId } };
1693
- const snapshot = await this.statusOf(peerRef);
1614
+ if (reply.kind === "result") {
1615
+ return { content: [{ type: "text", text: reply.text ?? "(empty reply)" }], isError: true, details: { requestId } };
1616
+ }
1617
+ return { content: [{ type: "text", text: `Sent to ${peerLabel(target.instanceId, target.displayName)} (no wait; receipt/consumption not confirmed).${congestion ? `
1618
+ ${congestion}` : ""} requestId=${requestId}` }], details: { requestId } };
1619
+ }
1620
+ return { content: [{ type: "text", text: reply?.text ?? "(empty reply)" }], details: { requestId } };
1621
+ }
1622
+ /** Live pre-send probe of one peer's host state (plan v2-A). Reads the
1623
+ * same state.get control frame ipc_status uses, but returns STRUCTURED
1624
+ * fields for the congestion advisory — never rendered raw. Failure is
1625
+ * soft: a probe that cannot complete returns unknown and the send
1626
+ * proceeds exactly as before (the probe must never block delivery). */
1627
+ async probePeerLiveState(target) {
1628
+ if (!this.transport || !target.port) return { live: false };
1629
+ try {
1630
+ const reply = await this.transport.send(target.instanceId, target.port, "state.get", { expectReply: true, waitMs: 3e3 });
1631
+ if (!reply || reply.kind !== "state") return { live: false };
1632
+ const parsed = JSON.parse(reply.text ?? "{}");
1694
1633
  return {
1695
- content: [{ type: "text", text: `No reply from ${peerLabel(target.instanceId, target.displayName)} within ${waitMs}ms (or aborted). requestId=${requestId}
1696
- Use ipc_result with this requestId before resending; accepted work is not cancelled.
1697
- Peer status:
1698
- ${snapshot}` }],
1699
- isError: true,
1700
- details: { requestId }
1634
+ live: true,
1635
+ state: typeof parsed.state === "string" ? parsed.state : void 0,
1636
+ turnStartedAt: typeof parsed.turnStartedAt === "number" ? parsed.turnStartedAt : void 0,
1637
+ undeliveredInjections: typeof parsed.undeliveredInjections === "number" ? parsed.undeliveredInjections : void 0
1701
1638
  };
1702
- }
1703
- return { content: [{ type: "text", text: reply.text ?? "(empty reply)" }], details: { requestId } };
1639
+ } catch {
1640
+ return { live: false };
1641
+ }
1642
+ }
1643
+ /** Human/model-readable congestion advisory from a probe result (plan
1644
+ * v2-A). Empty string when there is nothing worth saying: an idle peer,
1645
+ * a normally-busy peer with no backlog, or an unreachable probe (the
1646
+ * transport send below will surface unreachability with its own error).
1647
+ * Only two shapes carry a warning: a peer mid-turn for a LONG time, and
1648
+ * a peer with undelivered injections piling up — the exact signature of
1649
+ * the 2026-11-16 queue incident (full-report messages queued for 8h). */
1650
+ describePeerCongestion(probe) {
1651
+ if (!probe.live) return "";
1652
+ const busyMs = typeof probe.turnStartedAt === "number" ? Date.now() - probe.turnStartedAt : void 0;
1653
+ const busyHours = typeof busyMs === "number" ? busyMs / 36e5 : void 0;
1654
+ const backlog = probe.undeliveredInjections ?? 0;
1655
+ const longTurn = typeof busyHours === "number" && busyHours >= 0.5;
1656
+ if (!longTurn && backlog === 0) return "";
1657
+ const bits = [];
1658
+ if (typeof busyHours === "number") {
1659
+ bits.push(`peer is ${probe.state ?? "busy"}${busyMs !== void 0 && busyMs >= 6e4 ? ` (current turn running ${Math.round(busyMs / 6e4)}m)` : ""}`);
1660
+ }
1661
+ if (backlog > 0) bits.push(`${backlog} undelivered injection${backlog === 1 ? "" : "s"} queued ahead`);
1662
+ return `[Delivery advisory: ${bits.join(", ")}. Your message may sit unconsumed behind this. Consider ipc_result for pull-style updates or retrying once the peer settles; sending is NOT blocked.]`;
1704
1663
  }
1705
1664
  async resultOf(peerRef, requestId, limit, context) {
1706
1665
  const target = this.resolvePeer(peerRef);
@@ -1730,7 +1689,7 @@ ${message.text}`).join("\n---\n");
1730
1689
  return text;
1731
1690
  }
1732
1691
  /** /tools/ipc send: deliver text, then surface the result without waiting. */
1733
- async drainReplyAfterSend(peerRef, text) {
1692
+ async sendFromCommand(peerRef, text) {
1734
1693
  const result = await this.sendToPeer(peerRef, text, false, 0, { toolCallId: "ipc-command", cwd: this.ctx.cwd, log: () => {
1735
1694
  }, reportProgress: () => {
1736
1695
  } });
@@ -1739,8 +1698,7 @@ ${message.text}`).join("\n---\n");
1739
1698
  dispose() {
1740
1699
  this.disposed = true;
1741
1700
  this.stopHeartbeat?.();
1742
- this.stopWatch?.();
1743
- for (const id of [...this.awaitingReply.keys()]) this.finishReply(id, "cancelled: peer disposed");
1701
+ this.stopImBinding();
1744
1702
  this.delivery?.resetSessionState();
1745
1703
  this.polledInputs.clear();
1746
1704
  this.results.clear();
@@ -1813,9 +1771,7 @@ function pieIpcExtension(ctx) {
1813
1771
  editorInjection: ctx.capabilities.editorInjection,
1814
1772
  sendUserMessage: (text) => ctx.sendUserMessage(text),
1815
1773
  appendEntry: (type, data) => ctx.appendEntry?.(type, data) ?? "",
1816
- setStatus: (key, text) => ctx.ui.setStatus?.(key, text),
1817
1774
  notify: (message, type) => ctx.ui.notify(message, type),
1818
- getMessages: () => ctx.getMessages(),
1819
1775
  log: (message) => ctx.log(message)
1820
1776
  },
1821
1777
  {
@@ -1872,7 +1828,6 @@ function pieIpcExtension(ctx) {
1872
1828
  const unattendedHost = ctx.capabilities?.unattended === true;
1873
1829
  const isManagerRole = unattendedHost && process.env.PIE_PROC_CURATED_NAME === "manager";
1874
1830
  const workerHost = unattendedHost && !isManagerRole;
1875
- const oneShotHost = true;
1876
1831
  const registerRoleTool = (tool, register, allowed) => {
1877
1832
  if (allowed) register();
1878
1833
  else ctx.log(`pie-ipc: tool "${tool.name}" not registered (role-pruned for ${isManagerRole ? "manager" : workerHost ? "worker" : "tui"} host)`);
@@ -1894,15 +1849,13 @@ function pieIpcExtension(ctx) {
1894
1849
  ctx.registerTool({
1895
1850
  name: "ipc_send_notify",
1896
1851
  label: "Send a message to a Pie peer and get notified when it finishes",
1897
- description: `Send text to another Pie process (interactive peer) and SUBSCRIBE to its completion \u2014 the name is the contract: fire-and-forget sending requires an explicit notify:false. Default behavior: returns right after the receipt ack with a requestId; when the peer's turn settles (success, failure, or cancellation) it pushes one [ipc-done] notification as inbound input, and a local fallback timer (fallbackMs, default 600000ms) wakes a result check if that push is lost \u2014 you will be called back, do not poll in a loop and never resend while a result is pending. wait=true: hold the tool call open instead (bounded by waitMs) \u2014 one-shot hosts only. notify:false: explicit fire-and-forget (return after socket submission; receipt/consumption not confirmed; no wake). Inbound messages from peers arrive as user input or in ipc_poll.
1852
+ description: `Send text to another Pie process (interactive peer) and SUBSCRIBE to its completion \u2014 the name is the contract: fire-and-forget sending requires an explicit notify:false. Default behavior: returns right after the receipt ack with a requestId; when the peer's turn settles (success, failure, or cancellation) it pushes one [ipc-done] notification as inbound input, and a local fallback timer (fallbackMs, default 600000ms) first PULLS the peer's result over the socket and only wakes you if the pull cannot resolve it (peer gone, or still working past the renewal budget) \u2014 you will be called back when action is needed, do not poll in a loop and never resend while a result is pending. Before every send the peer's live state is probed; if it is mid-turn for a long time or has undelivered injections queued, the receipt carries a delivery advisory \u2014 read it and consider ipc_result pull-style updates or deferring instead of piling messages onto a busy peer. notify:false: explicit fire-and-forget (return after socket submission; receipt/consumption not confirmed; no wake). Inbound messages from peers arrive as user input or in ipc_poll.
1898
1853
 
1899
1854
  SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's conversation as a user input and triggers one full model turn on the peer (cost + side effects there). If the user only asked you to observe (\u770B\u770B/\u67E5\u67E5/\u4E86\u89E3\u4E00\u4E0B a peer), do NOT use this tool: read ipc_list_peers/ipc_status or the peer's session files instead. Use this tool to dispatch work or ask a peer only when the user explicitly authorized contacting that peer.`,
1900
1855
  parameters: Type.Object({
1901
1856
  to: Type.String({ description: "Peer display name or instance id (see ipc_list_peers)" }),
1902
1857
  text: Type.String({ description: "Message body for the peer" }),
1903
1858
  notify: Type.Optional(Type.Boolean({ description: "Default TRUE (completion subscription, per the tool name). Set false ONLY for explicit fire-and-forget where you will never need the result." })),
1904
- wait: Type.Optional(Type.Boolean({ description: "Block this call until the peer's reply (one-shot hosts only; prefer the default notify flow)" })),
1905
- waitMs: Type.Optional(Type.Number({ description: "Reply wait budget in ms (default 120000, max 600000)", minimum: 100, maximum: 6e5 })),
1906
1859
  fallbackMs: Type.Optional(Type.Number({ description: "Notify fallback window in ms: wake to check ipc_result if no push arrived (default 600000)", minimum: 5e3, maximum: 6e5 }))
1907
1860
  }),
1908
1861
  risk,
@@ -1912,7 +1865,7 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1912
1865
  return `\u2192 ${record.to ?? "?"}: ${(record.text ?? "").slice(0, 60)}`;
1913
1866
  }
1914
1867
  },
1915
- execute: async (args, context) => runtime.sendToPeer(args.to, args.text, args.wait ?? false, Math.min(args.waitMs ?? DEFAULT_SEND_WAIT_MS, 6e5), context, args.notify !== false, Math.min(args.fallbackMs ?? DEFAULT_NOTIFY_FALLBACK_MS, 6e5))
1868
+ execute: async (args, context) => runtime.sendToPeer(args.to, args.text, false, 0, context, args.notify !== false, Math.min(args.fallbackMs ?? DEFAULT_NOTIFY_FALLBACK_MS, 6e5))
1916
1869
  });
1917
1870
  }, true);
1918
1871
  registerRoleTool({ name: "ipc_control_notify" }, () => {
@@ -1962,7 +1915,7 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1962
1915
  },
1963
1916
  execute: async (args, context) => runtime.resultOf(args.to, args.requestId, args.limit ?? 5, context)
1964
1917
  });
1965
- }, isManagerRole || oneShotHost);
1918
+ }, true);
1966
1919
  registerRoleTool({ name: "ipc_status" }, () => {
1967
1920
  ctx.registerTool({
1968
1921
  name: "ipc_status",
@@ -1985,7 +1938,7 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1985
1938
  ctx.registerTool({
1986
1939
  name: "ipc_poll",
1987
1940
  label: "Poll inbound IPC inbox",
1988
- description: "Drain undelivered inbound peer messages from the local inbox (mute mode, or while auto-inject is degraded). Messages leave the inbox permanently. Returns 'Inbox empty.' when there is nothing pending.",
1941
+ description: "Drain undelivered inbound peer messages from the local inbox (mute mode, or while this host cannot inject). Messages leave the inbox permanently. Returns 'Inbox empty.' when there is nothing pending.",
1989
1942
  parameters: Type.Object({
1990
1943
  limit: Type.Optional(Type.Number({ description: "Max messages to drain (default 20)", minimum: 1, maximum: 100 }))
1991
1944
  }),
@@ -2014,7 +1967,7 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
2014
1967
  case "send": {
2015
1968
  const [peerRef, ...words] = rest;
2016
1969
  if (!peerRef || words.length === 0) return "Usage: /tools/ipc send <peer> <text>";
2017
- return runtime.drainReplyAfterSend(peerRef, words.join(" "));
1970
+ return runtime.sendFromCommand(peerRef, words.join(" "));
2018
1971
  }
2019
1972
  case "result": {
2020
1973
  const [peerRef, requestId] = rest;