@cydm/pie 4.4.1 → 4.4.2

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.
@@ -31,7 +31,7 @@ import {
31
31
  truncateMarkdown,
32
32
  tryClaimConsumer,
33
33
  writeConfig
34
- } from "../../../chunks/chunk-AKXEZH7K.js";
34
+ } from "../../../chunks/chunk-OFLKAWI4.js";
35
35
  import {
36
36
  detectImageMime,
37
37
  readImageFormat
@@ -10,7 +10,6 @@ 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,
@@ -26,7 +25,7 @@ import {
26
25
  takeDispatchFrame,
27
26
  wrapInboundText,
28
27
  wrappedMessageMarker
29
- } from "../../../chunks/chunk-AKXEZH7K.js";
28
+ } from "../../../chunks/chunk-OFLKAWI4.js";
30
29
  import "../../../chunks/chunk-RZGYXAJU.js";
31
30
 
32
31
  // builtin/extensions/pie-ipc/index.ts
@@ -434,80 +433,6 @@ function startHeartbeat(discoveryDir, file, intervalMs, write = (next) => writeS
434
433
  timer.unref?.();
435
434
  return () => clearInterval(timer);
436
435
  }
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
436
  function buildStatusFile(input) {
512
437
  return {
513
438
  schema: 1,
@@ -567,8 +492,6 @@ var InboundDelivery = class {
567
492
  this.host = host;
568
493
  this.options = options;
569
494
  this.autoInject = options.autoInject;
570
- this.degradeAfterMisses = options.degradeAfterMisses ?? 3;
571
- this.verifyDeadlineMs = options.verifyDeadlineMs ?? 3e4;
572
495
  }
573
496
  host;
574
497
  options;
@@ -576,22 +499,14 @@ var InboundDelivery = class {
576
499
  pending = /* @__PURE__ */ new Map();
577
500
  droppedCount = { value: 0 };
578
501
  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
502
  get effectiveAutoInject() {
587
- return this.autoInject && !this.degraded;
503
+ return this.autoInject;
588
504
  }
505
+ /** Mute toggle (/tools/ipc mute): the only inject control left — the
506
+ * degrade machinery is gone (astra audit #1), so this is purely the
507
+ * user's explicit choice. */
589
508
  setAutoInject(enabled) {
590
509
  this.autoInject = enabled;
591
- if (enabled) {
592
- this.degraded = false;
593
- this.consecutiveMisses = 0;
594
- }
595
510
  }
596
511
  /** Route one inbound message envelope. Returns the routing decision. */
597
512
  routeMessage(envelope, displayName) {
@@ -607,7 +522,6 @@ var InboundDelivery = class {
607
522
  return "denied";
608
523
  }
609
524
  if (!this.options.allowPolicy.allows(envelope.from)) {
610
- this.counters.denied += 1;
611
525
  this.host.notify?.(`pie-ipc: message from unapproved peer ${peerLabel(envelope.from, displayName)} \u2014 run /tools/ipc allow`, "warning");
612
526
  return "denied";
613
527
  }
@@ -623,7 +537,6 @@ var InboundDelivery = class {
623
537
  if (this.options.onProtocolFrame && this.options.protocolFramePrefix && message.text.trimStart().startsWith(this.options.protocolFramePrefix)) {
624
538
  try {
625
539
  if (this.options.onProtocolFrame(message.text)) {
626
- this.counters.injected += 1;
627
540
  return "injected";
628
541
  }
629
542
  } catch (error) {
@@ -650,42 +563,25 @@ var InboundDelivery = class {
650
563
  inject(message) {
651
564
  const wrapped = wrapInboundText(message.fromLabel, message.text, message.receivedAt, message.id);
652
565
  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;
566
+ this.pending.set(marker, { marker, message });
667
567
  try {
668
568
  this.host.sendUserMessage(wrapped);
669
569
  } catch {
670
- clearTimeout(entry.timer);
671
570
  if (this.pending.has(marker)) this.enqueueInbox(message);
672
571
  }
673
- this.updateStatus();
674
572
  }
675
573
  enqueueInbox(message) {
676
574
  this.inbox.push(message);
677
- this.counters.queued += 1;
678
575
  if (this.inbox.length > MAX_INBOX_MESSAGES) {
679
576
  this.inbox.shift();
680
577
  this.droppedCount.value += 1;
681
- this.counters.dropped += 1;
682
578
  this.host.notify?.("pie-ipc: inbox full; oldest message dropped", "warning");
683
579
  }
684
- this.updateStatus();
685
580
  }
686
581
  /**
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.
582
+ * Called on user message:end — confirm CONSUMPTION of pending injections
583
+ * against the settled user text (the result-ledger axis: onConsumed moves
584
+ * the sender's record accepted→running and arms the completion push).
689
585
  */
690
586
  onUserMessageEnd(message) {
691
587
  const text = deliveredUserText(message);
@@ -696,41 +592,23 @@ var InboundDelivery = class {
696
592
  if (!entry) return;
697
593
  const recovered = this.inbox.findIndex((item) => item.id === entry.message.id);
698
594
  if (recovered >= 0) this.inbox.splice(recovered, 1);
699
- this.options.onConsumed?.(entry.message.id);
700
- clearTimeout(entry.timer);
701
595
  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();
596
+ this.options.onConsumed?.(entry.message.id);
597
+ this.host.log("pie-ipc: injection consumed");
718
598
  }
719
599
  /** Drain the inbox (ipc_poll). Messages leave the inbox permanently. */
720
600
  drainInbox(limit = 20) {
721
601
  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;
602
+ return this.inbox.splice(0, Math.max(0, Math.min(100, Math.floor(limit))));
725
603
  }
726
604
  get inboxSize() {
727
605
  return this.inbox.length;
728
606
  }
729
607
  /** 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). */
608
+ * Mirrors routeMessage's live decision — auto-inject mode and pending
609
+ * capacity — so consumers (the notify fallback) act on EFFECTIVE
610
+ * delivery, not host capability (a muted TUI queues like an embedded
611
+ * host). */
734
612
  willInjectNow() {
735
613
  return this.hasUIInjection() && this.effectiveAutoInject && this.pending.size < MAX_INBOX_MESSAGES;
736
614
  }
@@ -747,46 +625,17 @@ var InboundDelivery = class {
747
625
  get overflowDropped() {
748
626
  return this.droppedCount.value;
749
627
  }
750
- /** Clear inbox + verification state on session switch. */
628
+ /** Clear inbox + consumption state on session switch. */
751
629
  resetSessionState() {
752
630
  this.inbox.length = 0;
753
- for (const entry of this.pending.values()) {
754
- clearTimeout(entry.timer);
755
- }
756
631
  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
632
  }
776
633
  };
777
634
 
778
635
  // builtin/extensions/pie-ipc/status.ts
779
636
  var StatusProjection = class {
780
- constructor(host) {
781
- this.host = host;
782
- }
783
- host;
784
637
  shape = { state: "idle" };
785
- lastBodyText = "";
786
- lastBodyAt = 0;
787
- undelivered = 0;
788
638
  tools = /* @__PURE__ */ new Map();
789
- bodyStart = 0;
790
639
  get state() {
791
640
  return this.shape.state;
792
641
  }
@@ -812,40 +661,10 @@ var StatusProjection = class {
812
661
  const after = this.shape.state + (this.shape.blockedSince ?? "") + (this.shape.currentTool ?? "");
813
662
  return before !== after;
814
663
  }
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. */
664
+ /** Session switch: lifecycle state does not carry over. */
838
665
  resetSessionState() {
839
666
  this.shape = { state: "idle" };
840
667
  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
668
  }
850
669
  snapshot(base) {
851
670
  return {
@@ -854,9 +673,10 @@ var StatusProjection = class {
854
673
  currentTool: this.shape.currentTool,
855
674
  blockedSince: this.shape.blockedSince,
856
675
  turnStartedAt: this.shape.turnStartedAt,
857
- undeliveredInjections: this.undelivered,
858
- lastBodyText: this.lastBodyText || void 0,
859
- lastBodyAt: this.lastBodyAt || void 0
676
+ // The delivery engine's pending count is the live undelivered figure;
677
+ // the projection's own counter was dead (astra audit) — currentStatus
678
+ // overwrites this field from delivery before publication anyway.
679
+ undeliveredInjections: 0
860
680
  };
861
681
  }
862
682
  };
@@ -1011,6 +831,8 @@ function resultJson(payload) {
1011
831
 
1012
832
  // builtin/extensions/pie-ipc/index.ts
1013
833
  var DEFAULT_NOTIFY_FALLBACK_MS = 6e5;
834
+ var FALLBACK_RENEWAL_CAP = 4;
835
+ var PROBE_CACHE_MS = 2e3;
1014
836
  var Runtime = class {
1015
837
  constructor(ctx, config, discoveryDir) {
1016
838
  this.ctx = ctx;
@@ -1018,7 +840,7 @@ var Runtime = class {
1018
840
  this.discoveryDir = discoveryDir;
1019
841
  this.displayName = config.displayName ?? peerLabel(this.instanceId);
1020
842
  this.allowPolicy = new AllowPolicy(config.allowPeers ? [...config.allowPeers] : ["*"]);
1021
- this.projection = new StatusProjection({ getMessages: () => ctx.getMessages() });
843
+ this.projection = new StatusProjection();
1022
844
  }
1023
845
  ctx;
1024
846
  config;
@@ -1029,8 +851,6 @@ var Runtime = class {
1029
851
  projection;
1030
852
  /** Shared allow policy: /tools/ipc allow affects delivery AND state.get gates. */
1031
853
  allowPolicy;
1032
- /** Inbound messages we accepted for a turn; answered on turn settle. */
1033
- awaitingReply = /* @__PURE__ */ new Map();
1034
854
  /** Completion subscriptions (notifyCompletion senders): deliveryId ->
1035
855
  * { peer, requestId }. One best-effort push per entry when the consuming
1036
856
  * turn settles (success/failure/cancel); entries never outlive the ledger
@@ -1042,12 +862,18 @@ var Runtime = class {
1042
862
  * if the peer's push never arrives, wake ourselves once to check
1043
863
  * ipc_result. Cleared when the notification (or its inbox delivery)
1044
864
  * lands, so a delivered notification never double-wakes. */
1045
- notifyFallbacks = /* @__PURE__ */ new Map();
865
+ /** Query-first fallback OPERATIONS by requestId (review r4): one record
866
+ * owns the whole lifecycle (armed timer + in-flight query + renewals).
867
+ * Keyed like the old timer map so capacity counting and completion
868
+ * cancellation cover the async query window too. */
869
+ fallbackOps = /* @__PURE__ */ new Map();
1046
870
  /** Notify-mode sends whose completion push already landed — including the
1047
871
  * completion-BEFORE-ack window (the reverse push can win the race). Bounded
1048
872
  * by the same retention discipline as the fallbacks: entries leave with
1049
873
  * their timer or when the check hint fires. */
1050
874
  completedNotifies = /* @__PURE__ */ new Set();
875
+ /** Fresh pre-send probes by peer instance id (plan v2-A rate budget). */
876
+ probeCache = /* @__PURE__ */ new Map();
1051
877
  /** Session/lifecycle generation for outbound notify continuations (review
1052
878
  * r4): sendToPeer awaits transport.send across session switches; a late
1053
879
  * null/ack continuation must not arm fallback state (or later fire its
@@ -1068,7 +894,6 @@ var Runtime = class {
1068
894
  sessionName;
1069
895
  statusBase;
1070
896
  stopHeartbeat = null;
1071
- stopWatch = null;
1072
897
  /** Server role: listen, advertise, watch peers. Publishes only after the
1073
898
  * listener is up (headless instances never publish). */
1074
899
  async startServer() {
@@ -1100,9 +925,6 @@ var Runtime = class {
1100
925
  listPeers(this.discoveryDir, { selfId: this.instanceId, pruneDead: true });
1101
926
  return this.currentStatus();
1102
927
  }, 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
928
  }
1107
929
  currentStatus() {
1108
930
  const liveName = this.ctx.getSessionName?.();
@@ -1137,9 +959,6 @@ var Runtime = class {
1137
959
  });
1138
960
  };
1139
961
  switch (envelope.kind) {
1140
- case "ping":
1141
- reply("ack", "pong");
1142
- return;
1143
962
  case "control": {
1144
963
  if (!this.allowPolicy.allows(envelope.from)) {
1145
964
  reply("ack", JSON.stringify({ ok: false, message: "denied by local allow policy" }));
@@ -1174,11 +993,7 @@ var Runtime = class {
1174
993
  currentTool: status.currentTool,
1175
994
  blockedSince: status.blockedSince,
1176
995
  turnStartedAt: status.turnStartedAt,
1177
- undeliveredInjections: status.undeliveredInjections,
1178
- lastBodyText: status.lastBodyText,
1179
- lastBodyAt: status.lastBodyAt,
1180
- sessionId: status.sessionId,
1181
- displayName: status.displayName
996
+ undeliveredInjections: status.undeliveredInjections
1182
997
  }));
1183
998
  return;
1184
999
  }
@@ -1224,30 +1039,18 @@ var Runtime = class {
1224
1039
  const stampedDone = /^\[ipc-done\] requestId=[a-zA-Z0-9:-]{1,128} (?:outcome=\S+ )?(?:\([^)]*\) )?user_assigned=true(?:\s|$)/.test((envelope.text ?? "").split("\n")[0] ?? "");
1225
1040
  this.completeNotify(doneMatch[1], stampedDone);
1226
1041
  }
1227
- if (envelope.waitMs && this.awaitingReply.size >= 100) {
1228
- reply("result", "rejected: reply capacity reached");
1042
+ if (envelope.waitMs && envelope.waitMs > 0) {
1043
+ reply("result", "rejected: wait=true is no longer supported; resend without wait, or subscribe (default) and pull via ipc_result");
1229
1044
  return;
1230
1045
  }
1231
1046
  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
1047
  if (!this.allowPolicy.allows(envelope.from)) {
1244
1048
  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");
1049
+ reply("result", "denied: not on this peer's allow list (/tools/ipc allow)");
1247
1050
  return;
1248
1051
  }
1249
1052
  this.results.accept(envelope.from, envelope.id, this.sessionId ?? "");
1250
- if (envelope.notifyCompletion && !envelope.waitMs) {
1053
+ if (envelope.notifyCompletion) {
1251
1054
  if (this.completionWatchers.size >= 100) {
1252
1055
  const oldest = this.completionWatchers.keys().next().value;
1253
1056
  if (oldest !== void 0) {
@@ -1262,8 +1065,7 @@ var Runtime = class {
1262
1065
  if (decision === "denied") {
1263
1066
  this.results.remove(deliveryId);
1264
1067
  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");
1068
+ reply("result", "denied: not on this peer's allow list (/tools/ipc allow)");
1267
1069
  return;
1268
1070
  }
1269
1071
  reply("ack", decision);
@@ -1282,7 +1084,6 @@ var Runtime = class {
1282
1084
  case "turn:start": {
1283
1085
  this.executionFailure = void 0;
1284
1086
  this.active = true;
1285
- this.projection.onTurnStarted();
1286
1087
  if (this.projection.updateFromEvent(event)) this.writeStatus();
1287
1088
  return;
1288
1089
  }
@@ -1297,7 +1098,6 @@ var Runtime = class {
1297
1098
  case "agent:end":
1298
1099
  case "turn:failed":
1299
1100
  case "turn:cancelled": {
1300
- this.projection.onTurnSettled();
1301
1101
  if (this.projection.updateFromEvent(event)) this.writeStatus();
1302
1102
  this.answerAwaitingPeers(event.type !== "agent:end" || Boolean(this.executionFailure));
1303
1103
  this.active = false;
@@ -1314,7 +1114,6 @@ var Runtime = class {
1314
1114
  this.notifyGeneration++;
1315
1115
  this.projection.resetSessionState();
1316
1116
  this.executionFailure = void 0;
1317
- for (const id of [...this.awaitingReply.keys()]) this.finishReply(id, "cancelled: target session changed");
1318
1117
  this.active = false;
1319
1118
  this.writeStatus();
1320
1119
  return;
@@ -1338,7 +1137,6 @@ var Runtime = class {
1338
1137
  }
1339
1138
  const body = message && !this.executionFailure ? assistantBodyText(message) : "";
1340
1139
  if (body) {
1341
- for (const [id, waiter] of this.awaitingReply) if (waiter.consumed) waiter.body = body;
1342
1140
  this.results.captureBody(body);
1343
1141
  }
1344
1142
  }
@@ -1348,31 +1146,13 @@ var Runtime = class {
1348
1146
  return;
1349
1147
  }
1350
1148
  }
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
- */
1149
+ /** Consumption (message:end of the injected marker) moves the sender's
1150
+ * ledger record accepted->running; the completion push fires at turn
1151
+ * settlement through the ledger, not through held sockets. */
1356
1152
  markConsumed(id) {
1357
- const waiter = this.awaitingReply.get(id);
1358
- if (waiter && this.active) waiter.consumed = true;
1359
1153
  if (this.active) this.results.markRunning(id);
1360
1154
  }
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
1155
  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
1156
  this.results.finishRunning(failed ? "(peer turn failed or was cancelled)" : "(empty reply)", failed);
1377
1157
  this.pushCompletionNotifications();
1378
1158
  }
@@ -1425,40 +1205,146 @@ ${body}` : ""}`;
1425
1205
  }).catch(() => void 0);
1426
1206
  this.ctx.log(`pie-ipc: completion notification sent to ${watcher.peer} for ${watcher.requestId} (${outcome})`);
1427
1207
  }
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) {
1208
+ /** Arm the local fallback check for a notify-mode send. QUERY-FIRST
1209
+ * (plan v2-B): on expiry the timer PULLS the peer's result ledger over
1210
+ * the socket first; only an unresolvable pull (unknown/peer gone, or
1211
+ * renewals exhausted on a still-working peer) injects the [ipc-check]
1212
+ * wake. The wake goes through the normal inbound path (sendUserMessage),
1213
+ * which the interactive host queues when busy and the embedded host
1214
+ * emits as a user.message event. */
1215
+ armNotifyFallback(requestId, fallbackMs, peerName, userAssigned = false, peerRef, targetIdentity) {
1433
1216
  if (this.completedNotifies.has(requestId)) {
1434
1217
  this.completedNotifies.delete(requestId);
1435
1218
  return true;
1436
1219
  }
1437
- if (this.notifyFallbacks.size >= 20) {
1438
- this.ctx.log(`pie-ipc: fallback budget exhausted (${this.notifyFallbacks.size} outstanding); no timer for ${requestId}`);
1220
+ if (this.fallbackOps.size >= 20) {
1221
+ this.ctx.log(`pie-ipc: fallback budget exhausted (${this.fallbackOps.size} outstanding); no timer for ${requestId}`);
1439
1222
  return false;
1440
1223
  }
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 {
1224
+ this.fallbackOps.get(requestId)?.finish?.();
1225
+ this.completedNotifies.delete(requestId);
1226
+ const budgetMs = Math.max(5e3, Math.min(fallbackMs, 6e5));
1227
+ const armGeneration = this.notifyGeneration;
1228
+ const op = { cancelled: false };
1229
+ this.fallbackOps.set(requestId, op);
1230
+ let renewals = 0;
1231
+ const finishOp = () => {
1232
+ op.cancelled = true;
1233
+ if (op.timer) {
1234
+ clearTimeout(op.timer);
1235
+ op.timer = void 0;
1236
+ }
1237
+ if (this.fallbackOps.get(requestId) === op) this.fallbackOps.delete(requestId);
1238
+ };
1239
+ op.finish = finishOp;
1240
+ const alive = () => !this.disposed && !op.cancelled && this.notifyGeneration === armGeneration;
1241
+ const fire = () => {
1242
+ op.timer = void 0;
1243
+ if (!alive()) {
1244
+ finishOp();
1245
+ return;
1456
1246
  }
1457
- }, Math.max(5e3, Math.min(fallbackMs, 6e5)));
1247
+ void this.fallbackCheckResult(requestId, peerRef ?? peerName, targetIdentity).then((outcome) => {
1248
+ if (!alive()) {
1249
+ finishOp();
1250
+ return;
1251
+ }
1252
+ if (this.completedNotifies.has(requestId)) {
1253
+ finishOp();
1254
+ return;
1255
+ }
1256
+ if (outcome === "terminal") {
1257
+ this.ctx.log(`pie-ipc: fallback pull recovered a terminal result for ${requestId} (push was lost); no wake injected`);
1258
+ finishOp();
1259
+ return;
1260
+ }
1261
+ if (outcome === "running" && renewals < FALLBACK_RENEWAL_CAP) {
1262
+ renewals += 1;
1263
+ const again = setTimeout(fire, budgetMs);
1264
+ again.unref?.();
1265
+ op.timer = again;
1266
+ this.ctx.log(`pie-ipc: fallback pull shows the peer still working on ${requestId}; silent renewal ${renewals}/${FALLBACK_RENEWAL_CAP}`);
1267
+ return;
1268
+ }
1269
+ finishOp();
1270
+ this.wakeModelForFallback(requestId, peerName, userAssigned, outcome === "running" ? `renewal budget exhausted (${FALLBACK_RENEWAL_CAP}) while the peer still reports working` : void 0);
1271
+ }).catch(() => {
1272
+ if (!alive()) {
1273
+ finishOp();
1274
+ return;
1275
+ }
1276
+ finishOp();
1277
+ this.wakeModelForFallback(requestId, peerName, userAssigned);
1278
+ });
1279
+ };
1280
+ const timer = setTimeout(fire, budgetMs);
1458
1281
  timer.unref();
1459
- this.notifyFallbacks.set(requestId, timer);
1282
+ op.timer = timer;
1460
1283
  return true;
1461
1284
  }
1285
+ /** One fallback pull: query the peer's result ledger over the socket and
1286
+ * classify the outcome for the query-first timer. Never throws — a
1287
+ * transport failure IS the "unknown" answer that warrants a wake.
1288
+ * REQUEST OWNERSHIP (review r4-P2): when the caller captured the original
1289
+ * send's target identity, the query binds to THAT instance (falling back
1290
+ * to a live re-resolve only for legacy callers) — a peer restart or name
1291
+ * transfer must not redirect the authoritative ledger lookup to a
1292
+ * different instance. */
1293
+ async fallbackCheckResult(requestId, peerRef, targetIdentity) {
1294
+ let instanceId = targetIdentity?.instanceId;
1295
+ let port;
1296
+ let sessionId = targetIdentity?.sessionId;
1297
+ if (instanceId) {
1298
+ const snapshot = readStatusFile(this.discoveryDir, instanceId);
1299
+ if (!snapshot?.port) return "unknown";
1300
+ port = snapshot.port;
1301
+ sessionId = snapshot.sessionId ?? "";
1302
+ } else {
1303
+ const target = this.resolvePeer(peerRef);
1304
+ if (!target?.port) return "unknown";
1305
+ instanceId = target.instanceId;
1306
+ port = target.port;
1307
+ sessionId = target.sessionId ?? "";
1308
+ }
1309
+ if (!this.transport) return "unknown";
1310
+ try {
1311
+ const reply = await this.transport.send(instanceId, port, "result.get", {
1312
+ text: JSON.stringify({ requestId }),
1313
+ sessionId,
1314
+ expectReply: true,
1315
+ waitMs: 3e3,
1316
+ replyKinds: /* @__PURE__ */ new Set(["result"])
1317
+ });
1318
+ if (!reply?.text) return "unknown";
1319
+ const parsed = JSON.parse(reply.text);
1320
+ if (parsed.status === "done" || parsed.status === "failed") {
1321
+ if (this.completedNotifies.size > 200) this.completedNotifies.clear();
1322
+ this.completedNotifies.add(requestId);
1323
+ return "terminal";
1324
+ }
1325
+ if (parsed.status === "accepted" || parsed.status === "running") return "running";
1326
+ return "unknown";
1327
+ } catch {
1328
+ return "unknown";
1329
+ }
1330
+ }
1331
+ /** The one remaining wake path for the fallback timer: the pull could not
1332
+ * resolve the request (peer gone, ledger evicted, session switched, or
1333
+ * renewals exhausted on a wedged peer). Injects the [ipc-check] hint via
1334
+ * the same draft-preserving submission the old timer used. */
1335
+ wakeModelForFallback(requestId, peerName, userAssigned, extra) {
1336
+ 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.`;
1337
+ const hint = wrapInboundText(`local-recovery (${peerName})`, hintBody);
1338
+ try {
1339
+ const scope = this.ctx.beginUserInput?.();
1340
+ if (scope) {
1341
+ scope.submit(hint).then(() => scope.dispose(), () => scope.dispose());
1342
+ } else {
1343
+ this.ctx.sendUserMessage(hint);
1344
+ }
1345
+ } catch {
1346
+ }
1347
+ }
1462
1348
  /** A completion notification (or its inbox delivery) landed for our send.
1463
1349
  * Observability-aware (final audit): an INJECTING host shows the message
1464
1350
  * to the model the moment it lands — the fallback timer dies (single
@@ -1474,35 +1360,29 @@ ${body}` : ""}`;
1474
1360
  }
1475
1361
  if (this.completedNotifies.size > 200) this.completedNotifies.clear();
1476
1362
  this.completedNotifies.add(requestId);
1477
- const timer = this.notifyFallbacks.get(requestId);
1478
- if (timer) {
1479
- clearTimeout(timer);
1480
- this.notifyFallbacks.delete(requestId);
1481
- }
1363
+ this.fallbackOps.get(requestId)?.finish?.();
1482
1364
  if (this.disposed) return;
1483
1365
  try {
1484
1366
  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.`;
1367
+ 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
1368
  this.ctx.sendUserMessage(wrapInboundText("local-inbox-wake", body));
1487
1369
  } catch {
1488
1370
  }
1489
1371
  }
1490
1372
  /** 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. */
1373
+ * destroy the fallback OPERATION so the model is woken exactly once —
1374
+ * including a query-in-flight fallback (review r4-P1): finishOp cancels
1375
+ * the in-flight continuation, which then exits without renewing or
1376
+ * waking. Also records completion for sends whose push arrived BEFORE
1377
+ * the ack did — armNotifyFallback then arms nothing. */
1494
1378
  clearNotifyFallback(requestId) {
1495
1379
  if (this.completedNotifies.size > 200) this.completedNotifies.clear();
1496
1380
  this.completedNotifies.add(requestId);
1497
- const timer = this.notifyFallbacks.get(requestId);
1498
- if (timer) {
1499
- clearTimeout(timer);
1500
- this.notifyFallbacks.delete(requestId);
1501
- }
1381
+ this.fallbackOps.get(requestId)?.finish?.();
1502
1382
  }
1503
1383
  clearNotifyFallbacks() {
1504
- for (const timer of this.notifyFallbacks.values()) clearTimeout(timer);
1505
- this.notifyFallbacks.clear();
1384
+ for (const op of this.fallbackOps.values()) op.finish?.();
1385
+ this.fallbackOps.clear();
1506
1386
  this.completedNotifies.clear();
1507
1387
  }
1508
1388
  // ---- mutations from commands ----
@@ -1548,8 +1428,7 @@ ${body}` : ""}`;
1548
1428
  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
1429
  if (!this.allowPolicy.allows(target.instanceId) || !(target.allowPeers?.includes("*") || target.allowPeers?.includes(this.instanceId))) return `${staticView}
1550
1430
  (content restricted by local allow policy)`;
1551
- const snapshot = `${staticView}${target.lastBodyText ? `
1552
- last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}`;
1431
+ const snapshot = staticView;
1553
1432
  if (!target.port || !this.transport) return `${snapshot}
1554
1433
  (no live listener; file view only)`;
1555
1434
  const reply = await this.transport.send(target.instanceId, target.port, "state.get", { expectReply: true, waitMs: 3e3 });
@@ -1563,7 +1442,6 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1563
1442
  if (typeof parsed.blockedSince === "number") lines.push(`blocked for ${Math.max(0, Math.round((Date.now() - parsed.blockedSince) / 1e3))}s`);
1564
1443
  if (typeof parsed.undeliveredInjections === "number" && parsed.undeliveredInjections > 0) lines.push(`undelivered injections: ${parsed.undeliveredInjections}`);
1565
1444
  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
1445
  return lines.join("\n");
1568
1446
  } catch {
1569
1447
  return `${staticView}
@@ -1633,7 +1511,10 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1633
1511
  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
1512
  return { content: [{ type: "text", text: reply.text ?? "(empty receipt)" }] };
1635
1513
  }
1636
- async sendToPeer(peerRef, text, wait, waitMs, context, notify = false, fallbackMs = DEFAULT_NOTIFY_FALLBACK_MS) {
1514
+ async sendToPeer(peerRef, text, _wait, _waitMs, context, notify = false, fallbackMs = DEFAULT_NOTIFY_FALLBACK_MS) {
1515
+ if (_wait) {
1516
+ 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 };
1517
+ }
1637
1518
  const target = this.resolvePeer(peerRef);
1638
1519
  if (!target) {
1639
1520
  return { content: [{ type: "text", text: `Peer not found: ${peerRef}. Call ipc_list_peers first.${this.livePeerHint()}` }], isError: true };
@@ -1646,8 +1527,23 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1646
1527
  }
1647
1528
  const body = clipBody(text, this.config.maxBodyChars);
1648
1529
  const requestId = randomUUID();
1649
- const notifyMode = notify && !wait;
1530
+ const notifyMode = notify;
1650
1531
  const sendGeneration = this.notifyGeneration;
1532
+ let congestion = "";
1533
+ {
1534
+ const now = Date.now();
1535
+ const cached2 = this.probeCache.get(target.instanceId);
1536
+ if (cached2 && now - cached2.at < PROBE_CACHE_MS) {
1537
+ congestion = this.describePeerCongestion(cached2.probe);
1538
+ } else {
1539
+ const probe = await this.probePeerLiveState(target);
1540
+ this.probeCache.set(target.instanceId, { at: Date.now(), probe });
1541
+ if (this.notifyGeneration !== sendGeneration) {
1542
+ 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 } };
1543
+ }
1544
+ congestion = this.describePeerCongestion(probe);
1545
+ }
1546
+ }
1651
1547
  let userAssigned = false;
1652
1548
  if (notifyMode) {
1653
1549
  userAssigned = isTurnUserImDriven();
@@ -1656,12 +1552,12 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1656
1552
  requestId,
1657
1553
  text: body,
1658
1554
  sessionId: target.sessionId ?? "",
1659
- expectReply: wait,
1660
- waitMs,
1555
+ expectReply: false,
1556
+ waitMs: DEFAULT_SEND_WAIT_MS,
1661
1557
  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"]),
1558
+ // Non-waiting sends resolve on the informational ack (or a terminal
1559
+ // denial result); the completion push rides its own envelope.
1560
+ replyKinds: /* @__PURE__ */ new Set(["result", "ack"]),
1665
1561
  ...notifyMode ? { notifyCompletion: true, awaitAck: true, subscriberSession: this.sessionId ?? "", ...userAssigned ? { userAssigned: true } : {} } : {}
1666
1562
  });
1667
1563
  if (notifyMode) {
@@ -1670,9 +1566,10 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1670
1566
  }
1671
1567
  if (!reply) {
1672
1568
  const peerName2 = peerLabel(target.instanceId, target.displayName);
1673
- const armed2 = this.armNotifyFallback(requestId, fallbackMs, peerName2, userAssigned);
1569
+ const armed2 = this.armNotifyFallback(requestId, fallbackMs, peerName2, userAssigned, peerRef, { instanceId: target.instanceId, sessionId: target.sessionId ?? void 0 });
1674
1570
  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."}` }],
1571
+ 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 ? `
1572
+ ${congestion}` : ""}` }],
1676
1573
  isError: true,
1677
1574
  details: { requestId }
1678
1575
  };
@@ -1681,26 +1578,62 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1681
1578
  return { content: [{ type: "text", text: reply.text ?? "(empty reply)" }], isError: true, details: { requestId } };
1682
1579
  }
1683
1580
  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 } };
1581
+ const armed = this.armNotifyFallback(requestId, fallbackMs, peerName, userAssigned, peerRef, { instanceId: target.instanceId, sessionId: target.sessionId ?? void 0 });
1582
+ 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 ? `
1583
+ ${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 ? `
1584
+ ${congestion}` : ""} requestId=${requestId}` }], details: { requestId } };
1686
1585
  }
1687
- if (!wait) {
1586
+ if (!notifyMode) {
1688
1587
  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);
1588
+ if (reply.kind === "result") {
1589
+ return { content: [{ type: "text", text: reply.text ?? "(empty reply)" }], isError: true, details: { requestId } };
1590
+ }
1591
+ return { content: [{ type: "text", text: `Sent to ${peerLabel(target.instanceId, target.displayName)} (no wait; receipt/consumption not confirmed).${congestion ? `
1592
+ ${congestion}` : ""} requestId=${requestId}` }], details: { requestId } };
1593
+ }
1594
+ return { content: [{ type: "text", text: reply?.text ?? "(empty reply)" }], details: { requestId } };
1595
+ }
1596
+ /** Live pre-send probe of one peer's host state (plan v2-A). Reads the
1597
+ * same state.get control frame ipc_status uses, but returns STRUCTURED
1598
+ * fields for the congestion advisory — never rendered raw. Failure is
1599
+ * soft: a probe that cannot complete returns unknown and the send
1600
+ * proceeds exactly as before (the probe must never block delivery). */
1601
+ async probePeerLiveState(target) {
1602
+ if (!this.transport || !target.port) return { live: false };
1603
+ try {
1604
+ const reply = await this.transport.send(target.instanceId, target.port, "state.get", { expectReply: true, waitMs: 3e3 });
1605
+ if (!reply || reply.kind !== "state") return { live: false };
1606
+ const parsed = JSON.parse(reply.text ?? "{}");
1694
1607
  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 }
1608
+ live: true,
1609
+ state: typeof parsed.state === "string" ? parsed.state : void 0,
1610
+ turnStartedAt: typeof parsed.turnStartedAt === "number" ? parsed.turnStartedAt : void 0,
1611
+ undeliveredInjections: typeof parsed.undeliveredInjections === "number" ? parsed.undeliveredInjections : void 0
1701
1612
  };
1702
- }
1703
- return { content: [{ type: "text", text: reply.text ?? "(empty reply)" }], details: { requestId } };
1613
+ } catch {
1614
+ return { live: false };
1615
+ }
1616
+ }
1617
+ /** Human/model-readable congestion advisory from a probe result (plan
1618
+ * v2-A). Empty string when there is nothing worth saying: an idle peer,
1619
+ * a normally-busy peer with no backlog, or an unreachable probe (the
1620
+ * transport send below will surface unreachability with its own error).
1621
+ * Only two shapes carry a warning: a peer mid-turn for a LONG time, and
1622
+ * a peer with undelivered injections piling up — the exact signature of
1623
+ * the 2026-11-16 queue incident (full-report messages queued for 8h). */
1624
+ describePeerCongestion(probe) {
1625
+ if (!probe.live) return "";
1626
+ const busyMs = typeof probe.turnStartedAt === "number" ? Date.now() - probe.turnStartedAt : void 0;
1627
+ const busyHours = typeof busyMs === "number" ? busyMs / 36e5 : void 0;
1628
+ const backlog = probe.undeliveredInjections ?? 0;
1629
+ const longTurn = typeof busyHours === "number" && busyHours >= 0.5;
1630
+ if (!longTurn && backlog === 0) return "";
1631
+ const bits = [];
1632
+ if (typeof busyHours === "number") {
1633
+ bits.push(`peer is ${probe.state ?? "busy"}${busyMs !== void 0 && busyMs >= 6e4 ? ` (current turn running ${Math.round(busyMs / 6e4)}m)` : ""}`);
1634
+ }
1635
+ if (backlog > 0) bits.push(`${backlog} undelivered injection${backlog === 1 ? "" : "s"} queued ahead`);
1636
+ 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
1637
  }
1705
1638
  async resultOf(peerRef, requestId, limit, context) {
1706
1639
  const target = this.resolvePeer(peerRef);
@@ -1730,7 +1663,7 @@ ${message.text}`).join("\n---\n");
1730
1663
  return text;
1731
1664
  }
1732
1665
  /** /tools/ipc send: deliver text, then surface the result without waiting. */
1733
- async drainReplyAfterSend(peerRef, text) {
1666
+ async sendFromCommand(peerRef, text) {
1734
1667
  const result = await this.sendToPeer(peerRef, text, false, 0, { toolCallId: "ipc-command", cwd: this.ctx.cwd, log: () => {
1735
1668
  }, reportProgress: () => {
1736
1669
  } });
@@ -1739,8 +1672,6 @@ ${message.text}`).join("\n---\n");
1739
1672
  dispose() {
1740
1673
  this.disposed = true;
1741
1674
  this.stopHeartbeat?.();
1742
- this.stopWatch?.();
1743
- for (const id of [...this.awaitingReply.keys()]) this.finishReply(id, "cancelled: peer disposed");
1744
1675
  this.delivery?.resetSessionState();
1745
1676
  this.polledInputs.clear();
1746
1677
  this.results.clear();
@@ -1813,9 +1744,7 @@ function pieIpcExtension(ctx) {
1813
1744
  editorInjection: ctx.capabilities.editorInjection,
1814
1745
  sendUserMessage: (text) => ctx.sendUserMessage(text),
1815
1746
  appendEntry: (type, data) => ctx.appendEntry?.(type, data) ?? "",
1816
- setStatus: (key, text) => ctx.ui.setStatus?.(key, text),
1817
1747
  notify: (message, type) => ctx.ui.notify(message, type),
1818
- getMessages: () => ctx.getMessages(),
1819
1748
  log: (message) => ctx.log(message)
1820
1749
  },
1821
1750
  {
@@ -1872,7 +1801,6 @@ function pieIpcExtension(ctx) {
1872
1801
  const unattendedHost = ctx.capabilities?.unattended === true;
1873
1802
  const isManagerRole = unattendedHost && process.env.PIE_PROC_CURATED_NAME === "manager";
1874
1803
  const workerHost = unattendedHost && !isManagerRole;
1875
- const oneShotHost = true;
1876
1804
  const registerRoleTool = (tool, register, allowed) => {
1877
1805
  if (allowed) register();
1878
1806
  else ctx.log(`pie-ipc: tool "${tool.name}" not registered (role-pruned for ${isManagerRole ? "manager" : workerHost ? "worker" : "tui"} host)`);
@@ -1894,15 +1822,13 @@ function pieIpcExtension(ctx) {
1894
1822
  ctx.registerTool({
1895
1823
  name: "ipc_send_notify",
1896
1824
  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.
1825
+ 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
1826
 
1899
1827
  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
1828
  parameters: Type.Object({
1901
1829
  to: Type.String({ description: "Peer display name or instance id (see ipc_list_peers)" }),
1902
1830
  text: Type.String({ description: "Message body for the peer" }),
1903
1831
  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
1832
  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
1833
  }),
1908
1834
  risk,
@@ -1912,7 +1838,7 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1912
1838
  return `\u2192 ${record.to ?? "?"}: ${(record.text ?? "").slice(0, 60)}`;
1913
1839
  }
1914
1840
  },
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))
1841
+ 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
1842
  });
1917
1843
  }, true);
1918
1844
  registerRoleTool({ name: "ipc_control_notify" }, () => {
@@ -1962,7 +1888,7 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1962
1888
  },
1963
1889
  execute: async (args, context) => runtime.resultOf(args.to, args.requestId, args.limit ?? 5, context)
1964
1890
  });
1965
- }, isManagerRole || oneShotHost);
1891
+ }, true);
1966
1892
  registerRoleTool({ name: "ipc_status" }, () => {
1967
1893
  ctx.registerTool({
1968
1894
  name: "ipc_status",
@@ -1985,7 +1911,7 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1985
1911
  ctx.registerTool({
1986
1912
  name: "ipc_poll",
1987
1913
  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.",
1914
+ 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
1915
  parameters: Type.Object({
1990
1916
  limit: Type.Optional(Type.Number({ description: "Max messages to drain (default 20)", minimum: 1, maximum: 100 }))
1991
1917
  }),
@@ -2014,7 +1940,7 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
2014
1940
  case "send": {
2015
1941
  const [peerRef, ...words] = rest;
2016
1942
  if (!peerRef || words.length === 0) return "Usage: /tools/ipc send <peer> <text>";
2017
- return runtime.drainReplyAfterSend(peerRef, words.join(" "));
1943
+ return runtime.sendFromCommand(peerRef, words.join(" "));
2018
1944
  }
2019
1945
  case "result": {
2020
1946
  const [peerRef, requestId] = rest;
@@ -561,7 +561,6 @@ var MAX_STATUS_FILE_BYTES = 128 * 1024;
561
561
  var MAX_DISPLAY_NAME_CHARS = 64;
562
562
  var MAX_STATUS_TEXT_FIELD_CHARS = 4096;
563
563
  var MAX_BODY_CHARS = 8e3;
564
- var MAX_STATUS_BODY_CHARS = 2e3;
565
564
  var STATUS_FILE_STALE_MS = 12e4;
566
565
  var HEARTBEAT_INTERVAL_MS = 2e4;
567
566
  var DEFAULT_SEND_WAIT_MS = 12e4;
@@ -589,9 +588,6 @@ function peerLabel(instanceId, displayName) {
589
588
  return instanceId.length > 12 ? instanceId.slice(0, 12) : instanceId;
590
589
  }
591
590
  var ENVELOPE_KINDS = /* @__PURE__ */ new Set([
592
- "hello",
593
- "bye",
594
- "ping",
595
591
  "message",
596
592
  "ack",
597
593
  "result",
@@ -780,8 +776,6 @@ function parseStatusFile(raw) {
780
776
  if (typeof record.blockedSince === "number" && Number.isSafeInteger(record.blockedSince) && record.blockedSince >= 0) file.blockedSince = record.blockedSince;
781
777
  if (typeof record.turnStartedAt === "number" && Number.isSafeInteger(record.turnStartedAt) && record.turnStartedAt >= 0) file.turnStartedAt = record.turnStartedAt;
782
778
  if (typeof record.undeliveredInjections === "number" && Number.isFinite(record.undeliveredInjections)) file.undeliveredInjections = Math.min(100, Math.max(0, Math.floor(record.undeliveredInjections)));
783
- if (typeof record.lastBodyText === "string" && record.lastBodyText.length <= MAX_STATUS_TEXT_FIELD_CHARS && !/[\u0000-\u0008\u000b-\u001f\u007f]/.test(record.lastBodyText)) file.lastBodyText = record.lastBodyText;
784
- if (typeof record.lastBodyAt === "number" && Number.isSafeInteger(record.lastBodyAt) && record.lastBodyAt >= 0) file.lastBodyAt = record.lastBodyAt;
785
779
  if (typeof record.port === "number" && Number.isInteger(record.port) && record.port > 0 && record.port <= 65535) file.port = record.port;
786
780
  return file;
787
781
  }
@@ -1414,7 +1408,6 @@ export {
1414
1408
  IPC_PROTOCOL_VERSION,
1415
1409
  MAX_STATUS_FILE_BYTES,
1416
1410
  MAX_BODY_CHARS,
1417
- MAX_STATUS_BODY_CHARS,
1418
1411
  HEARTBEAT_INTERVAL_MS,
1419
1412
  DEFAULT_SEND_WAIT_MS,
1420
1413
  MAX_INBOX_MESSAGES,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cydm/pie",
3
- "version": "4.4.1",
3
+ "version": "4.4.2",
4
4
  "description": "Pie AI Agent CLI",
5
5
  "type": "module",
6
6
  "bin": {