@cydm/pie 4.3.7 → 4.3.12

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.
@@ -1,14 +1,15 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
- BoundedIdSet,
3
+ Type
4
+ } from "../../../chunks/chunk-XXGYUYXI.js";
5
+ import {
4
6
  DEFAULT_SEND_WAIT_MS,
5
7
  DISPATCH_PREFIX,
6
- FrameDecoder,
7
8
  HEARTBEAT_INTERVAL_MS,
8
9
  IPC_PROTOCOL_VERSION,
10
+ IpcTransport,
9
11
  MAX_BODY_CHARS,
10
12
  MAX_INBOX_MESSAGES,
11
- MAX_INFLIGHT_SENDS,
12
13
  MAX_STATUS_BODY_CHARS,
13
14
  MAX_STATUS_FILE_BYTES,
14
15
  assistantBodyText,
@@ -25,17 +26,14 @@ import {
25
26
  takeDispatchFrame,
26
27
  wrapInboundText,
27
28
  wrappedMessageMarker
28
- } from "../../../chunks/chunk-N3BWFAMZ.js";
29
- import {
30
- Type
31
- } from "../../../chunks/chunk-XXGYUYXI.js";
29
+ } from "../../../chunks/chunk-EGNGHINP.js";
32
30
  import "../../../chunks/chunk-LZQXQOPJ.js";
33
31
 
34
32
  // builtin/extensions/pie-ipc/index.ts
35
33
  import * as fs3 from "node:fs";
36
34
  import * as os from "node:os";
37
35
  import * as path4 from "node:path";
38
- import { randomUUID as randomUUID2 } from "node:crypto";
36
+ import { randomUUID } from "node:crypto";
39
37
 
40
38
  // builtin/extensions/pie-ipc/discovery.ts
41
39
  import * as fs2 from "node:fs";
@@ -529,257 +527,6 @@ function buildStatusFile(input) {
529
527
  };
530
528
  }
531
529
 
532
- // builtin/extensions/pie-ipc/transport.ts
533
- import * as net from "node:net";
534
- import { createHmac, randomBytes as randomBytes3, randomUUID, timingSafeEqual } from "node:crypto";
535
- import { StringDecoder } from "node:string_decoder";
536
- var CLOSE_FLUSH_TIMEOUT_MS = 1e3;
537
- function signEnvelope(e, secret) {
538
- const payload = [e.v, e.id, e.from, e.to, e.kind, e.createdAt, e.sessionId ?? null, e.text ?? null, e.replyTo ?? null, e.waitMs ?? null, e.notifyCompletion ?? null, e.control ?? null, e.userAssigned ?? null, e.subscriberSession ?? null];
539
- return { ...e, auth: createHmac("sha256", secret).update(JSON.stringify(payload)).digest("hex") };
540
- }
541
- function verified(e, secret) {
542
- if (!e.auth || !/^[a-f0-9]{64}$/.test(e.auth)) return false;
543
- return timingSafeEqual(Buffer.from(e.auth, "hex"), Buffer.from(signEnvelope(e, secret).auth, "hex"));
544
- }
545
- var IpcTransport = class {
546
- constructor(host) {
547
- this.host = host;
548
- this.instanceId = host.instanceId;
549
- this.secret = host.secret ?? randomBytes3(32).toString("hex");
550
- this.server = net.createServer((socket) => this.accept(socket));
551
- this.server.on("error", () => {
552
- });
553
- this.server.unref();
554
- }
555
- host;
556
- instanceId;
557
- secret;
558
- server;
559
- sockets = /* @__PURE__ */ new Set();
560
- cancels = /* @__PURE__ */ new Set();
561
- seen = new BoundedIdSet();
562
- closed = false;
563
- inflight = 0;
564
- inbound = 0;
565
- rateWindow = Date.now();
566
- rateCount = 0;
567
- port = null;
568
- get listenPort() {
569
- return this.port;
570
- }
571
- listen() {
572
- if (this.closed) return Promise.reject(new Error("closed"));
573
- return new Promise((resolve2, reject) => {
574
- const cancel = () => {
575
- this.cancels.delete(cancel);
576
- reject(new Error("closed"));
577
- };
578
- this.cancels.add(cancel);
579
- const error = (e) => {
580
- this.cancels.delete(cancel);
581
- reject(e);
582
- };
583
- this.server.once("error", error);
584
- this.server.listen(0, "127.0.0.1", () => {
585
- this.server.off("error", error);
586
- this.cancels.delete(cancel);
587
- if (this.closed) {
588
- this.server.close();
589
- reject(new Error("closed"));
590
- return;
591
- }
592
- const address = this.server.address();
593
- if (!address || typeof address === "string") {
594
- reject(new Error("closed"));
595
- return;
596
- }
597
- this.port = address.port;
598
- resolve2(address.port);
599
- });
600
- });
601
- }
602
- write(socket, envelope, secret) {
603
- if (socket.destroyed) return false;
604
- const data = JSON.stringify(signEnvelope(envelope, secret)) + "\n";
605
- if (socket.writableLength + Buffer.byteLength(data) > 512 * 1024) {
606
- socket.destroy();
607
- return false;
608
- }
609
- try {
610
- socket.write(data);
611
- return true;
612
- } catch {
613
- socket.destroy();
614
- return false;
615
- }
616
- }
617
- read(socket, receive, idleMs) {
618
- const decoder = new FrameDecoder();
619
- const utf8 = new StringDecoder("utf8");
620
- let frameTimer;
621
- let frames = 0;
622
- socket.setTimeout(idleMs, () => socket.destroy());
623
- socket.on("error", () => socket.destroy());
624
- socket.on("close", () => {
625
- if (frameTimer) clearTimeout(frameTimer);
626
- this.sockets.delete(socket);
627
- });
628
- socket.on("data", (chunk) => {
629
- try {
630
- frames += chunk.reduce((n, b) => n + (b === 10 ? 1 : 0), 0);
631
- if (frames > 128) {
632
- socket.destroy();
633
- return;
634
- }
635
- const envelopes = decoder.push(utf8.write(chunk));
636
- const partial = decoder.partial || chunk.at(-1) !== 10;
637
- if (frameTimer && (!partial || chunk.includes(10))) {
638
- clearTimeout(frameTimer);
639
- frameTimer = void 0;
640
- }
641
- if (partial && !frameTimer) {
642
- frameTimer = setTimeout(() => socket.destroy(), 15e3);
643
- frameTimer.unref();
644
- }
645
- for (const e of envelopes) {
646
- if (socket.destroyed) break;
647
- receive(e);
648
- }
649
- } catch {
650
- socket.destroy();
651
- }
652
- });
653
- }
654
- accept(socket) {
655
- if (this.closed || this.inbound >= 16) {
656
- socket.destroy();
657
- return;
658
- }
659
- this.inbound++;
660
- this.sockets.add(socket);
661
- socket.setNoDelay(true);
662
- socket.once("close", () => {
663
- this.inbound--;
664
- });
665
- const lifecycle = new AbortController();
666
- socket.once("close", () => lifecycle.abort());
667
- let sender;
668
- this.read(socket, (e) => {
669
- if (e.to !== this.instanceId || !verified(e, this.secret) || sender && sender !== e.from) {
670
- socket.destroy();
671
- return;
672
- }
673
- sender = e.from;
674
- if (Date.now() - this.rateWindow >= 1e3) {
675
- this.rateWindow = Date.now();
676
- this.rateCount = 0;
677
- }
678
- if (++this.rateCount > 128) {
679
- socket.destroy();
680
- return;
681
- }
682
- if (e.waitMs) socket.setTimeout(Math.max(6e4, e.waitMs + 1e3));
683
- if (!this.seen.add(`${e.from}:${e.id}`)) return;
684
- try {
685
- if (this.closed) return;
686
- void Promise.resolve(this.host.onEnvelope(e, (reply) => {
687
- if (reply.from === this.instanceId && reply.to === e.from && reply.replyTo === e.id) this.write(socket, reply, this.secret);
688
- }, lifecycle.signal)).catch(() => socket.destroy());
689
- } catch {
690
- socket.destroy();
691
- }
692
- }, 6e4);
693
- }
694
- /** Synchronous CAPACITY probe (review r3): transport.send is async, so a
695
- * capacity rejection still yields a truthy Promise resolving null — callers
696
- * distinguishing 'never left the process' from 'sent, outcome unknown' must
697
- * check this BEFORE awaiting send. Scope: closed/inflight ONLY (capacity &
698
- * lifecycle), NOT send()'s full validation (signal/secret/port/waitMs can
699
- * still null-reject after a true probe — those are peer/discovery outcomes,
700
- * covered by the best-effort contract). */
701
- canSendNow() {
702
- return !this.closed && this.inflight < MAX_INFLIGHT_SENDS;
703
- }
704
- async send(peerInstanceId, port, kind, options = {}) {
705
- if (this.closed || options.signal?.aborted || this.inflight >= MAX_INFLIGHT_SENDS) return null;
706
- let secret;
707
- try {
708
- secret = this.host.resolveSecret?.(peerInstanceId);
709
- } catch {
710
- return null;
711
- }
712
- if (!secret || !/^[a-f0-9]{64}$/.test(secret) || !Number.isInteger(port) || port < 1 || port > 65535) return null;
713
- const waitMs = options.waitMs ?? DEFAULT_SEND_WAIT_MS;
714
- if (!Number.isFinite(waitMs) || waitMs < 0 || waitMs > 6e5) return null;
715
- const holdOpen = options.expectReply === true || options.awaitAck === true;
716
- this.inflight++;
717
- return new Promise((resolve2) => {
718
- const socket = new net.Socket();
719
- this.sockets.add(socket);
720
- const envelope = { v: IPC_PROTOCOL_VERSION, id: options.requestId ?? randomUUID(), from: this.instanceId, to: peerInstanceId, kind, createdAt: Date.now(), ...options.text !== void 0 ? { text: clipBody(options.text) } : {}, ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {}, ...options.replyTo ? { replyTo: options.replyTo } : {}, waitMs: options.expectReply ? waitMs : 0, ...options.notifyCompletion === true ? { notifyCompletion: true } : {}, ...options.subscriberSession !== void 0 ? { subscriberSession: options.subscriberSession } : {}, ...options.userAssigned === true ? { userAssigned: true } : {} };
721
- let done = false;
722
- const finish = (value) => {
723
- if (done) return;
724
- done = true;
725
- clearTimeout(timer);
726
- clearTimeout(dialTimer);
727
- options.signal?.removeEventListener("abort", abort);
728
- this.cancels.delete(abort);
729
- this.inflight--;
730
- socket.destroy();
731
- resolve2(value);
732
- };
733
- const abort = () => finish(null);
734
- const timer = setTimeout(abort, holdOpen ? waitMs : 3e3);
735
- const dialTimer = setTimeout(abort, 3e3);
736
- this.cancels.add(abort);
737
- options.signal?.addEventListener("abort", abort, { once: true });
738
- socket.once("close", abort);
739
- this.read(socket, (e) => {
740
- if (e.to !== this.instanceId || e.from !== peerInstanceId || e.replyTo !== envelope.id || !verified(e, secret)) {
741
- finish(null);
742
- return;
743
- }
744
- if ((options.replyKinds ?? /* @__PURE__ */ new Set(["result", "ack", "state"])).has(e.kind)) finish(e);
745
- }, Math.max(waitMs, 3e3));
746
- socket.once("connect", () => {
747
- clearTimeout(dialTimer);
748
- if (done || options.signal?.aborted || this.closed) {
749
- finish(null);
750
- return;
751
- }
752
- if (!this.write(socket, envelope, secret)) {
753
- finish(null);
754
- return;
755
- }
756
- if (!holdOpen) {
757
- socket.end(() => finish(envelope));
758
- }
759
- });
760
- try {
761
- socket.connect(port, "127.0.0.1");
762
- } catch {
763
- finish(null);
764
- }
765
- });
766
- }
767
- close() {
768
- if (this.closed) return;
769
- this.closed = true;
770
- for (const cancel of [...this.cancels]) cancel();
771
- for (const socket of this.sockets) {
772
- if (socket.destroyed) continue;
773
- socket.end();
774
- const timer = setTimeout(() => socket.destroy(), CLOSE_FLUSH_TIMEOUT_MS);
775
- timer.unref();
776
- }
777
- this.sockets.clear();
778
- this.server.close();
779
- this.port = null;
780
- }
781
- };
782
-
783
530
  // builtin/extensions/pie-ipc/delivery.ts
784
531
  var AllowPolicy = class {
785
532
  /**
@@ -1361,12 +1108,14 @@ var Runtime = class {
1361
1108
  const liveName = this.ctx.getSessionName?.();
1362
1109
  if (typeof liveName === "string") this.sessionName = liveName;
1363
1110
  const displaySessionName = this.ctx.getSessionDisplayName?.() ?? liveName;
1111
+ const model = this.ctx.getCurrentModel?.();
1364
1112
  const snapshot = this.projection.snapshot({
1365
1113
  ...this.statusBase,
1366
1114
  displayName: this.displayName,
1367
1115
  sessionId: this.sessionId,
1368
1116
  sessionName: this.sessionName,
1369
- ...displaySessionName ? { displaySessionName } : {}
1117
+ ...displaySessionName ? { displaySessionName } : {},
1118
+ ...typeof model === "string" && model ? { model } : {}
1370
1119
  });
1371
1120
  return { ...snapshot, allowPeers: [...this.allowPolicy.snapshot()], undeliveredInjections: this.delivery?.undeliveredInjections ?? snapshot.undeliveredInjections ?? 0 };
1372
1121
  }
@@ -1821,17 +1570,47 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1821
1570
  (live query returned unparsable payload)`;
1822
1571
  }
1823
1572
  }
1824
- /** Resolve a peer by display name, name prefix, or instance id. */
1573
+ /** Resolve a peer by a degraded chain: instance id → displayName →
1574
+ * sessionName/displaySessionName → sessionId prefix (11-15 stale-peer
1575
+ * fix). A restart mints a NEW instanceId and displayName tail, but the
1576
+ * logical identity (sessionName, or the sessionId when one exists)
1577
+ * survives it — resolving through those keys unblocks senders holding a
1578
+ * stale reference without another ipc_list_peers round-trip. Ambiguous
1579
+ * matches at any tier resolve to null (same as before); dead-pid entries
1580
+ * are skipped at every tier except the exact instanceId tier (which
1581
+ * keeps the file-view behavior of statusOf on a dying peer). */
1825
1582
  resolvePeer(peerRef) {
1826
1583
  const listings = listPeers(this.discoveryDir, { selfId: this.instanceId, pruneDead: false });
1827
1584
  const ref = peerRef.trim().toLowerCase();
1828
1585
  if (!ref) return null;
1829
- const exact = listings.find(({ file }) => file.instanceId.toLowerCase() === ref);
1830
- if (exact) return exact.file;
1831
- const names = listings.filter(({ file }) => file.displayName.toLowerCase() === ref);
1832
- if (names.length) return names.length === 1 ? names[0].file : null;
1833
- const matches = listings.filter(({ file }) => file.instanceId.toLowerCase().startsWith(ref) || file.displayName.toLowerCase().startsWith(ref));
1834
- return matches.length === 1 ? matches[0].file : null;
1586
+ const alive = listings.filter(({ health }) => health !== "dead");
1587
+ const legacyExact = alive.filter(({ file }) => file.instanceId.toLowerCase() === ref || file.displayName.toLowerCase() === ref);
1588
+ if (legacyExact.length === 1) return legacyExact[0].file;
1589
+ if (legacyExact.length > 1) return null;
1590
+ const legacyPrefix = alive.filter(({ file }) => file.instanceId.toLowerCase().startsWith(ref) || file.displayName.toLowerCase().startsWith(ref));
1591
+ if (legacyPrefix.length === 1) return legacyPrefix[0].file;
1592
+ const exactInstance = listings.filter(({ file }) => file.instanceId.toLowerCase() === ref);
1593
+ if (exactInstance.length === 1) return exactInstance[0].file;
1594
+ const sessionName = alive.filter(({ file }) => (file.sessionName ?? file.displaySessionName ?? "").toLowerCase() === ref || (file.displaySessionName ?? file.sessionName ?? "").toLowerCase() === ref);
1595
+ if (sessionName.length === 1) return sessionName[0].file;
1596
+ if (sessionName.length > 1) return null;
1597
+ const sessionPrefix = alive.filter(({ file }) => typeof file.sessionId === "string" && file.sessionId.toLowerCase().startsWith(ref) && ref.length >= 6);
1598
+ if (sessionPrefix.length === 1) return sessionPrefix[0].file;
1599
+ if (sessionPrefix.length > 1) return null;
1600
+ return null;
1601
+ }
1602
+ /** Compact live-peer digest for "Peer not found" errors: lets the
1603
+ * caller self-correct in ONE step instead of a separate list call. */
1604
+ livePeerHint() {
1605
+ const listings = listPeers(this.discoveryDir, { selfId: this.instanceId, pruneDead: false }).filter(({ health }) => health !== "dead").slice(0, 5);
1606
+ if (listings.length === 0) return " (no live peers discovered)";
1607
+ return "\nLive peers:\n" + listings.map(({ file }) => {
1608
+ const fileRecord = file;
1609
+ const humanName = typeof fileRecord.displaySessionName === "string" && fileRecord.displaySessionName.trim() ? fileRecord.displaySessionName.trim() : void 0;
1610
+ const label = humanName ?? peerLabel(file.instanceId, file.displayName);
1611
+ const sid = file.sessionId ? ` session=${file.sessionId.slice(0, 8)}` : "";
1612
+ return ` ${label} [${file.state}]${sid}`;
1613
+ }).join("\n");
1835
1614
  }
1836
1615
  /** MULTI-AGENT IM v2 Phase 2.3 — send an enumerated CONTROL frame to a
1837
1616
  * peer (first control: model.set). Returns the peer's receipt (the ack
@@ -1840,7 +1619,7 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1840
1619
  * it directly. Awaits the ack (bounded); null means unreachable/timeout. */
1841
1620
  async sendControl(peerRef, control, payload, waitMs) {
1842
1621
  const target = this.resolvePeer(peerRef);
1843
- if (!target) return { content: [{ type: "text", text: `Peer not found: ${peerRef}. Call ipc_list_peers first.` }], isError: true };
1622
+ if (!target) return { content: [{ type: "text", text: `Peer not found: ${peerRef}. Call ipc_list_peers first.${this.livePeerHint()}` }], isError: true };
1844
1623
  if (!target.port) return { content: [{ type: "text", text: `${peerLabel(target.instanceId, target.displayName)} is not listening.` }], isError: true };
1845
1624
  if (!this.transport) return { content: [{ type: "text", text: "IPC transport is unavailable." }], isError: true };
1846
1625
  const body = JSON.stringify({ control, ...payload !== void 0 ? { payload } : {} });
@@ -1857,7 +1636,7 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1857
1636
  async sendToPeer(peerRef, text, wait, waitMs, context, notify = false, fallbackMs = DEFAULT_NOTIFY_FALLBACK_MS) {
1858
1637
  const target = this.resolvePeer(peerRef);
1859
1638
  if (!target) {
1860
- return { content: [{ type: "text", text: `Peer not found: ${peerRef}. Call ipc_list_peers first.` }], isError: true };
1639
+ return { content: [{ type: "text", text: `Peer not found: ${peerRef}. Call ipc_list_peers first.${this.livePeerHint()}` }], isError: true };
1861
1640
  }
1862
1641
  if (!target.port) {
1863
1642
  return { content: [{ type: "text", text: `${peerLabel(target.instanceId, target.displayName)} is not listening (client-only or headless host).` }], isError: true };
@@ -1866,7 +1645,7 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1866
1645
  return { content: [{ type: "text", text: "IPC transport is unavailable (server startup failed or instance disposed)." }], isError: true };
1867
1646
  }
1868
1647
  const body = clipBody(text, this.config.maxBodyChars);
1869
- const requestId = randomUUID2();
1648
+ const requestId = randomUUID();
1870
1649
  const notifyMode = notify && !wait;
1871
1650
  const sendGeneration = this.notifyGeneration;
1872
1651
  let userAssigned = false;
@@ -1925,7 +1704,7 @@ ${snapshot}` }],
1925
1704
  }
1926
1705
  async resultOf(peerRef, requestId, limit, context) {
1927
1706
  const target = this.resolvePeer(peerRef);
1928
- if (!target) return { content: [{ type: "text", text: `Peer not found: ${peerRef}. Call ipc_list_peers first.` }], isError: true };
1707
+ if (!target) return { content: [{ type: "text", text: `Peer not found: ${peerRef}. Call ipc_list_peers first.${this.livePeerHint()}` }], isError: true };
1929
1708
  if (!target.port || !this.transport) return { content: [{ type: "text", text: `${peerLabel(target.instanceId, target.displayName)} has no live listener for result queries.` }], isError: true };
1930
1709
  const reply = await this.transport.send(target.instanceId, target.port, "result.get", {
1931
1710
  text: JSON.stringify({ ...requestId ? { requestId } : {}, limit: Math.max(1, Math.min(20, Math.floor(limit))) }),
@@ -2001,6 +1780,7 @@ function safeRead(file) {
2001
1780
  throw error;
2002
1781
  }
2003
1782
  }
1783
+ var __runtimeForTests = (ctx, config, discoveryDir) => new Runtime(ctx, config, discoveryDir);
2004
1784
  function pieIpcExtension(ctx) {
2005
1785
  const rawConfigDir = process.env.PIE_IPC_CONFIG_DIR ?? getConfigDirSafe(ctx);
2006
1786
  const configDir = process.platform === "win32" ? rawConfigDir : path4.resolve(rawConfigDir === "~" ? homeDir() : rawConfigDir.startsWith("~/") ? path4.join(homeDir(), rawConfigDir.slice(2)) : rawConfigDir);
@@ -2089,114 +1869,134 @@ function pieIpcExtension(ctx) {
2089
1869
  allowedForSubagentByDefault: false,
2090
1870
  concurrencySafe: false
2091
1871
  };
2092
- ctx.registerTool({
2093
- name: "ipc_list_peers",
2094
- label: "List Pie IPC peers",
2095
- description: "List other Pie processes on this machine that advertise pie-ipc. Each line: name [health] state (working/idle/blocked), current tool, blocked duration, session, port, instance id. Local read only; use ipc_status for a live query.",
2096
- parameters: Type.Object({}),
2097
- risk: { ...risk, riskClass: "read_only", externalSideEffect: false, requiresPermission: false, readsNetwork: false, writesNetwork: false, concurrencySafe: true },
2098
- renderHint: {
2099
- summary: () => "list peers"
2100
- },
2101
- execute: async () => ({ content: [{ type: "text", text: await runtime.listPeers() }] })
2102
- });
2103
- ctx.registerTool({
2104
- name: "ipc_send_notify",
2105
- label: "Send a message to a Pie peer and get notified when it finishes",
2106
- 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.`,
2107
- parameters: Type.Object({
2108
- to: Type.String({ description: "Peer display name or instance id (see ipc_list_peers)" }),
2109
- text: Type.String({ description: "Message body for the peer" }),
2110
- 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." })),
2111
- wait: Type.Optional(Type.Boolean({ description: "Block this call until the peer's reply (one-shot hosts only; prefer the default notify flow)" })),
2112
- waitMs: Type.Optional(Type.Number({ description: "Reply wait budget in ms (default 120000, max 600000)", minimum: 100, maximum: 6e5 })),
2113
- 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 }))
2114
- }),
2115
- risk,
2116
- renderHint: {
2117
- summary: (args) => {
2118
- const record = args ?? {};
2119
- return `\u2192 ${record.to ?? "?"}: ${(record.text ?? "").slice(0, 60)}`;
2120
- }
2121
- },
2122
- 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))
2123
- });
2124
- ctx.registerTool({
2125
- name: "ipc_control_notify",
2126
- label: "Send a control frame to a Pie peer",
2127
- description: "Send an enumerated CONTROL frame to another Pie process (multi-agent IM v2). The frame is applied by the peer's host DIRECTLY \u2014 it never enters the peer's turn or session history. First control: 'model.set' with payload {model: 'provider/modelId'} switches the peer's model for its subsequent turns (same validation as the peer's own /model). Receipt (success or structured refusal) returns as this tool's result. Controls are idempotent: re-sending after an uncertain outcome is safe.",
2128
- parameters: Type.Object({
2129
- to: Type.String({ description: "Peer display name or instance id (see ipc_list_peers)" }),
2130
- control: Type.Union([Type.Literal("model.set")], { description: "Control to apply (enumerated whitelist)" }),
2131
- payload: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Control payload. model.set requires {model: 'provider/modelId'}" })),
2132
- waitMs: Type.Optional(Type.Number({ description: "Receipt wait budget in ms (default 120000, max 600000)", minimum: 100, maximum: 6e5 }))
2133
- }),
2134
- risk: { ...risk, riskClass: "session_mutation", concurrencySafe: false },
2135
- renderHint: {
2136
- summary: (args) => {
2137
- const record = args ?? {};
2138
- return `control ${record.control ?? "?"} \u2192 ${record.to ?? "?"}`;
2139
- }
2140
- },
2141
- execute: async (args) => {
2142
- if (args.control === "model.set") {
2143
- const payload = args.payload ?? {};
2144
- if (typeof payload.model !== "string" || !/^[^/\s]+\/[^/\s]+$/.test(payload.model))
2145
- return { content: [{ type: "text", text: "model.set requires payload.model as 'provider/modelId'." }], isError: true };
2146
- }
2147
- return runtime.sendControl(args.to, args.control, args.payload, Math.min(args.waitMs ?? 12e4, 6e5));
2148
- }
2149
- });
2150
- ctx.registerTool({
2151
- name: "ipc_result",
2152
- label: "Query a Pie request result",
2153
- description: "Query a result by the requestId returned from ipc_send_notify, or omit requestId to list recent results from this sender. Results are read without deletion. Status is accepted, running, done, failed, or unknown. Unknown does not prove the peer never received the request; inspect before resending.",
2154
- parameters: Type.Object({
2155
- to: Type.String({ description: "Peer display name or instance id prefix" }),
2156
- requestId: Type.Optional(Type.String({ description: "Request id returned by ipc_send_notify" })),
2157
- limit: Type.Optional(Type.Number({ description: "Recent result count when requestId is omitted (default 5, max 20)", minimum: 1, maximum: 20 }))
2158
- }),
2159
- risk: { ...risk, riskClass: "network", requiresPermission: false, externalSideEffect: false, writesNetwork: false },
2160
- renderHint: {
2161
- summary: (args) => {
2162
- const record = args ?? {};
2163
- return `result ${record.to ?? "?"}${record.requestId ? ` ${record.requestId}` : " (recent)"}`;
2164
- }
2165
- },
2166
- execute: async (args, context) => runtime.resultOf(args.to, args.requestId, args.limit ?? 5, context)
2167
- });
2168
- ctx.registerTool({
2169
- name: "ipc_status",
2170
- label: "Query a peer's live status",
2171
- description: "Live-query a Pie peer's status over its socket: lifecycle state, current tool, blocked duration, undelivered injections, truncated last body text. Falls back to the status-file view when the peer is unreachable. unapproved askers get a restricted summary.",
2172
- parameters: Type.Object({
2173
- peer: Type.String({ description: "Peer display name or instance id prefix" })
2174
- }),
2175
- risk: { ...risk, riskClass: "network", requiresPermission: false, externalSideEffect: false, writesNetwork: false },
2176
- renderHint: {
2177
- summary: (args) => {
2178
- const record = args ?? {};
2179
- return `status ${record.peer ?? "?"}`;
2180
- }
2181
- },
2182
- execute: async (args) => ({ content: [{ type: "text", text: await runtime.statusOf(args.peer) }] })
2183
- });
2184
- ctx.registerTool({
2185
- name: "ipc_poll",
2186
- label: "Poll inbound IPC inbox",
2187
- 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.",
2188
- parameters: Type.Object({
2189
- limit: Type.Optional(Type.Number({ description: "Max messages to drain (default 20)", minimum: 1, maximum: 100 }))
2190
- }),
2191
- risk: { ...risk, riskClass: "session_mutation", externalSideEffect: false, requiresPermission: false, readsNetwork: false, writesNetwork: false, concurrencySafe: false },
2192
- renderHint: {
2193
- summary: (args) => {
2194
- const record = args ?? {};
2195
- return `poll inbox${record.limit ? ` (limit ${record.limit})` : ""}`;
1872
+ const unattendedHost = ctx.capabilities?.unattended === true;
1873
+ const isManagerRole = unattendedHost && process.env.PIE_PROC_CURATED_NAME === "manager";
1874
+ const workerHost = unattendedHost && !isManagerRole;
1875
+ const oneShotHost = true;
1876
+ const registerRoleTool = (tool, register, allowed) => {
1877
+ if (allowed) register();
1878
+ else ctx.log(`pie-ipc: tool "${tool.name}" not registered (role-pruned for ${isManagerRole ? "manager" : workerHost ? "worker" : "tui"} host)`);
1879
+ };
1880
+ registerRoleTool({ name: "ipc_list_peers" }, () => {
1881
+ ctx.registerTool({
1882
+ name: "ipc_list_peers",
1883
+ label: "List Pie IPC peers",
1884
+ description: "List other Pie processes on this machine that advertise pie-ipc. Each line: name [health] state (working/idle/blocked), current tool, blocked duration, session, port, instance id. Local read only; use ipc_status for a live query.",
1885
+ parameters: Type.Object({}),
1886
+ risk: { ...risk, riskClass: "read_only", externalSideEffect: false, requiresPermission: false, readsNetwork: false, writesNetwork: false, concurrencySafe: true },
1887
+ renderHint: {
1888
+ summary: () => "list peers"
1889
+ },
1890
+ execute: async () => ({ content: [{ type: "text", text: await runtime.listPeers() }] })
1891
+ });
1892
+ }, true);
1893
+ registerRoleTool({ name: "ipc_send_notify" }, () => {
1894
+ ctx.registerTool({
1895
+ name: "ipc_send_notify",
1896
+ 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.`,
1898
+ parameters: Type.Object({
1899
+ to: Type.String({ description: "Peer display name or instance id (see ipc_list_peers)" }),
1900
+ text: Type.String({ description: "Message body for the peer" }),
1901
+ 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." })),
1902
+ wait: Type.Optional(Type.Boolean({ description: "Block this call until the peer's reply (one-shot hosts only; prefer the default notify flow)" })),
1903
+ waitMs: Type.Optional(Type.Number({ description: "Reply wait budget in ms (default 120000, max 600000)", minimum: 100, maximum: 6e5 })),
1904
+ 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 }))
1905
+ }),
1906
+ risk,
1907
+ renderHint: {
1908
+ summary: (args) => {
1909
+ const record = args ?? {};
1910
+ return `\u2192 ${record.to ?? "?"}: ${(record.text ?? "").slice(0, 60)}`;
1911
+ }
1912
+ },
1913
+ 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))
1914
+ });
1915
+ }, true);
1916
+ registerRoleTool({ name: "ipc_control_notify" }, () => {
1917
+ ctx.registerTool({
1918
+ name: "ipc_control_notify",
1919
+ label: "Send a control frame to a Pie peer",
1920
+ description: "Send an enumerated CONTROL frame to another Pie process (multi-agent IM v2). The frame is applied by the peer's host DIRECTLY \u2014 it never enters the peer's turn or session history. First control: 'model.set' with payload {model: 'provider/modelId'} switches the peer's model for its subsequent turns (same validation as the peer's own /model). Receipt (success or structured refusal) returns as this tool's result. Controls are idempotent: re-sending after an uncertain outcome is safe.",
1921
+ parameters: Type.Object({
1922
+ to: Type.String({ description: "Peer display name or instance id (see ipc_list_peers)" }),
1923
+ control: Type.Union([Type.Literal("model.set")], { description: "Control to apply (enumerated whitelist)" }),
1924
+ payload: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Control payload. model.set requires {model: 'provider/modelId'}" })),
1925
+ waitMs: Type.Optional(Type.Number({ description: "Receipt wait budget in ms (default 120000, max 600000)", minimum: 100, maximum: 6e5 }))
1926
+ }),
1927
+ risk: { ...risk, riskClass: "session_mutation", concurrencySafe: false },
1928
+ renderHint: {
1929
+ summary: (args) => {
1930
+ const record = args ?? {};
1931
+ return `control ${record.control ?? "?"} \u2192 ${record.to ?? "?"}`;
1932
+ }
1933
+ },
1934
+ execute: async (args) => {
1935
+ if (args.control === "model.set") {
1936
+ const payload = args.payload ?? {};
1937
+ if (typeof payload.model !== "string" || !/^[^/\s]+\/[^/\s]+$/.test(payload.model))
1938
+ return { content: [{ type: "text", text: "model.set requires payload.model as 'provider/modelId'." }], isError: true };
1939
+ }
1940
+ return runtime.sendControl(args.to, args.control, args.payload, Math.min(args.waitMs ?? 12e4, 6e5));
2196
1941
  }
2197
- },
2198
- execute: async (args) => ({ content: [{ type: "text", text: runtime.drainInbox(args.limit ?? 20) }] })
2199
- });
1942
+ });
1943
+ }, isManagerRole);
1944
+ registerRoleTool({ name: "ipc_result" }, () => {
1945
+ ctx.registerTool({
1946
+ name: "ipc_result",
1947
+ label: "Query a Pie request result",
1948
+ description: "Query a result by the requestId returned from ipc_send_notify, or omit requestId to list recent results from this sender. Results are read without deletion. Status is accepted, running, done, failed, or unknown. Unknown does not prove the peer never received the request; inspect before resending.",
1949
+ parameters: Type.Object({
1950
+ to: Type.String({ description: "Peer display name or instance id prefix" }),
1951
+ requestId: Type.Optional(Type.String({ description: "Request id returned by ipc_send_notify" })),
1952
+ limit: Type.Optional(Type.Number({ description: "Recent result count when requestId is omitted (default 5, max 20)", minimum: 1, maximum: 20 }))
1953
+ }),
1954
+ risk: { ...risk, riskClass: "network", requiresPermission: false, externalSideEffect: false, writesNetwork: false },
1955
+ renderHint: {
1956
+ summary: (args) => {
1957
+ const record = args ?? {};
1958
+ return `result ${record.to ?? "?"}${record.requestId ? ` ${record.requestId}` : " (recent)"}`;
1959
+ }
1960
+ },
1961
+ execute: async (args, context) => runtime.resultOf(args.to, args.requestId, args.limit ?? 5, context)
1962
+ });
1963
+ }, isManagerRole || oneShotHost);
1964
+ registerRoleTool({ name: "ipc_status" }, () => {
1965
+ ctx.registerTool({
1966
+ name: "ipc_status",
1967
+ label: "Query a peer's live status",
1968
+ description: "Live-query a Pie peer's status over its socket: lifecycle state, current tool, blocked duration, undelivered injections, truncated last body text. Falls back to the status-file view when the peer is unreachable. unapproved askers get a restricted summary.",
1969
+ parameters: Type.Object({
1970
+ peer: Type.String({ description: "Peer display name or instance id prefix" })
1971
+ }),
1972
+ risk: { ...risk, riskClass: "network", requiresPermission: false, externalSideEffect: false, writesNetwork: false },
1973
+ renderHint: {
1974
+ summary: (args) => {
1975
+ const record = args ?? {};
1976
+ return `status ${record.peer ?? "?"}`;
1977
+ }
1978
+ },
1979
+ execute: async (args) => ({ content: [{ type: "text", text: await runtime.statusOf(args.peer) }] })
1980
+ });
1981
+ }, isManagerRole);
1982
+ registerRoleTool({ name: "ipc_poll" }, () => {
1983
+ ctx.registerTool({
1984
+ name: "ipc_poll",
1985
+ label: "Poll inbound IPC inbox",
1986
+ 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.",
1987
+ parameters: Type.Object({
1988
+ limit: Type.Optional(Type.Number({ description: "Max messages to drain (default 20)", minimum: 1, maximum: 100 }))
1989
+ }),
1990
+ risk: { ...risk, riskClass: "session_mutation", externalSideEffect: false, requiresPermission: false, readsNetwork: false, writesNetwork: false, concurrencySafe: false },
1991
+ renderHint: {
1992
+ summary: (args) => {
1993
+ const record = args ?? {};
1994
+ return `poll inbox${record.limit ? ` (limit ${record.limit})` : ""}`;
1995
+ }
1996
+ },
1997
+ execute: async (args) => ({ content: [{ type: "text", text: runtime.drainInbox(args.limit ?? 20) }] })
1998
+ });
1999
+ }, true);
2200
2000
  ctx.registerCommand({
2201
2001
  path: ["tools", "ipc"],
2202
2002
  description: "Pie IPC peers: /tools/ipc peers|send|result|poll|status|name|mute|allow",
@@ -2273,5 +2073,6 @@ function homeDir() {
2273
2073
  return process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
2274
2074
  }
2275
2075
  export {
2076
+ __runtimeForTests,
2276
2077
  pieIpcExtension as default
2277
2078
  };