@cydm/pie 2.8.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +8 -4
  2. package/dist/builtin/extensions/changelog/index.js +2 -2
  3. package/dist/builtin/extensions/cron/index.js +295 -33
  4. package/dist/builtin/extensions/document-attachments/index.js +1 -1
  5. package/dist/builtin/extensions/herdr-agent-state/index.js +2 -2
  6. package/dist/builtin/extensions/im-forward/README.md +20 -5
  7. package/dist/builtin/extensions/im-forward/index.js +415 -142
  8. package/dist/builtin/extensions/memory/index.js +83 -30
  9. package/dist/builtin/extensions/pie-ipc/README.md +2 -2
  10. package/dist/builtin/extensions/pie-ipc/index.js +269 -30
  11. package/dist/builtin/extensions/pie-proc/README.md +93 -0
  12. package/dist/builtin/extensions/pie-proc/index.js +630 -0
  13. package/dist/builtin/extensions/pie-proc/package.json +11 -0
  14. package/dist/builtin/extensions/plan-mode/index.js +4 -4
  15. package/dist/builtin/extensions/subagent/index.js +6 -6
  16. package/dist/builtin/extensions/todo/index.js +4 -4
  17. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +106 -2
  18. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-cli.js +1 -0
  19. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  20. package/dist/builtin/skills/chrome-devtools-axi/{chunk-BNSAEVRT.js → chunk-WOGAQ4P5.js} +2 -2
  21. package/dist/builtin/skills/chrome-devtools-axi/{cli-AO2ZTPRM.js → cli-CHC7XYFU.js} +27 -3
  22. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +2 -2
  23. package/dist/builtin/skills/computer-use-axi/computer-use-axi-cli.js +1 -0
  24. package/dist/builtin/skills/computer-use-axi/scripts/setup-helper.mjs +6 -2
  25. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +179 -9
  26. package/dist/chunks/{chunk-PK72LVWQ.js → chunk-FDLLNPIE.js} +143 -53
  27. package/dist/chunks/{chunk-3BC5KGDQ.js → chunk-JQRZLVPY.js} +12 -1
  28. package/dist/chunks/{chunk-GH4VW2OT.js → chunk-NCP264ZE.js} +8 -2
  29. package/dist/chunks/{chunk-YRR6C43W.js → chunk-QX6WS73C.js} +1 -1
  30. package/dist/chunks/{chunk-3NHP7HK5.js → chunk-TDKNKNPL.js} +6 -5
  31. package/dist/chunks/{chunk-GDIYSMTS.js → chunk-UOZHQ73X.js} +25 -17
  32. package/dist/chunks/{chunk-RSL7E4R7.js → chunk-WK4N5HT5.js} +66 -23
  33. package/dist/chunks/chunk-X6LBWHK3.js +37 -0
  34. package/dist/chunks/concierge-cli-PIOGXKDR.js +939 -0
  35. package/dist/chunks/{model-registry-LI5THXV4.js → model-registry-YA6U366L.js} +2 -2
  36. package/dist/chunks/{src-BPSQMSSC.js → src-AB7PLORG.js} +6 -4
  37. package/dist/chunks/{src-YG5M2H44.js → src-ODLT57PQ.js} +2 -2
  38. package/dist/chunks/{src-66XSMIAM.js → src-XSLD2IQ2.js} +1 -1
  39. package/dist/chunks/{src-OPPYTPWG.js → src-ZZZO4HSR.js} +11 -3
  40. package/dist/chunks/{test-stream-JBWXKOQA.js → test-stream-GIUD5JWS.js} +1 -1
  41. package/dist/cli.js +1433 -235
  42. package/package.json +105 -105
@@ -6,6 +6,7 @@ import "../../../chunks/chunk-LZQXQOPJ.js";
6
6
 
7
7
  // builtin/extensions/pie-ipc/index.ts
8
8
  import * as fs3 from "node:fs";
9
+ import * as os from "node:os";
9
10
  import * as path4 from "node:path";
10
11
  import { randomUUID as randomUUID2 } from "node:crypto";
11
12
 
@@ -73,6 +74,8 @@ function parseEnvelope(raw) {
73
74
  if (record.sessionId !== void 0 && (typeof record.sessionId !== "string" || record.sessionId.length > 256)) return null;
74
75
  if (record.replyTo !== void 0 && (typeof record.replyTo !== "string" || !/^[a-zA-Z0-9:-]{1,128}$/.test(record.replyTo))) return null;
75
76
  if (record.waitMs !== void 0 && (typeof record.waitMs !== "number" || !Number.isFinite(record.waitMs) || record.waitMs < 0 || record.waitMs > 6e5)) return null;
77
+ if (record.notifyCompletion !== void 0 && typeof record.notifyCompletion !== "boolean") return null;
78
+ if (record.subscriberSession !== void 0 && (typeof record.subscriberSession !== "string" || record.subscriberSession.length > 256)) return null;
76
79
  if (typeof record.kind !== "string" || !ENVELOPE_KINDS.has(record.kind)) return null;
77
80
  if (typeof record.createdAt !== "number" || !Number.isSafeInteger(record.createdAt) || record.createdAt < 0) return null;
78
81
  const envelope = {
@@ -88,6 +91,8 @@ function parseEnvelope(raw) {
88
91
  if (typeof record.text === "string") envelope.text = record.text;
89
92
  if (typeof record.replyTo === "string") envelope.replyTo = record.replyTo;
90
93
  if (typeof record.waitMs === "number" && Number.isFinite(record.waitMs)) envelope.waitMs = record.waitMs;
94
+ if (record.notifyCompletion === true) envelope.notifyCompletion = true;
95
+ if (typeof record.subscriberSession === "string") envelope.subscriberSession = record.subscriberSession;
91
96
  return envelope;
92
97
  }
93
98
  var FrameTooLargeError = class extends Error {
@@ -301,6 +306,10 @@ function resolveIpcConfig(configLayers) {
301
306
  if (typeof merged.displayName === "string" && merged.displayName.trim()) {
302
307
  config.displayName = merged.displayName.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 60);
303
308
  }
309
+ const envName = process.env.PIE_IPC_DISPLAY_NAME;
310
+ if (typeof envName === "string" && envName.trim()) {
311
+ config.displayName = envName.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 60);
312
+ }
304
313
  if (Array.isArray(merged.allowPeers)) {
305
314
  config.allowPeers = merged.allowPeers.filter((id) => typeof id === "string" && (id === "*" || isValidInstanceId(id))).slice(0, 1e3);
306
315
  } else if (merged.allowPeers !== void 0) {
@@ -828,7 +837,7 @@ import { createHmac, randomBytes as randomBytes4, randomUUID, timingSafeEqual }
828
837
  import { StringDecoder } from "node:string_decoder";
829
838
  var CLOSE_FLUSH_TIMEOUT_MS = 1e3;
830
839
  function signEnvelope(e, secret) {
831
- 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];
840
+ 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.subscriberSession ?? null];
832
841
  return { ...e, auth: createHmac("sha256", secret).update(JSON.stringify(payload)).digest("hex") };
833
842
  }
834
843
  function verified(e, secret) {
@@ -863,7 +872,7 @@ var IpcTransport = class {
863
872
  }
864
873
  listen() {
865
874
  if (this.closed) return Promise.reject(new Error("closed"));
866
- return new Promise((resolve, reject) => {
875
+ return new Promise((resolve2, reject) => {
867
876
  const cancel = () => {
868
877
  this.cancels.delete(cancel);
869
878
  reject(new Error("closed"));
@@ -888,7 +897,7 @@ var IpcTransport = class {
888
897
  return;
889
898
  }
890
899
  this.port = address.port;
891
- resolve(address.port);
900
+ resolve2(address.port);
892
901
  });
893
902
  });
894
903
  }
@@ -984,6 +993,16 @@ var IpcTransport = class {
984
993
  }
985
994
  }, 6e4);
986
995
  }
996
+ /** Synchronous CAPACITY probe (review r3): transport.send is async, so a
997
+ * capacity rejection still yields a truthy Promise resolving null — callers
998
+ * distinguishing 'never left the process' from 'sent, outcome unknown' must
999
+ * check this BEFORE awaiting send. Scope: closed/inflight ONLY (capacity &
1000
+ * lifecycle), NOT send()'s full validation (signal/secret/port/waitMs can
1001
+ * still null-reject after a true probe — those are peer/discovery outcomes,
1002
+ * covered by the best-effort contract). */
1003
+ canSendNow() {
1004
+ return !this.closed && this.inflight < MAX_INFLIGHT_SENDS;
1005
+ }
987
1006
  async send(peerInstanceId, port, kind, options = {}) {
988
1007
  if (this.closed || options.signal?.aborted || this.inflight >= MAX_INFLIGHT_SENDS) return null;
989
1008
  let secret;
@@ -995,11 +1014,12 @@ var IpcTransport = class {
995
1014
  if (!secret || !/^[a-f0-9]{64}$/.test(secret) || !Number.isInteger(port) || port < 1 || port > 65535) return null;
996
1015
  const waitMs = options.waitMs ?? DEFAULT_SEND_WAIT_MS;
997
1016
  if (!Number.isFinite(waitMs) || waitMs < 0 || waitMs > 6e5) return null;
1017
+ const holdOpen = options.expectReply === true || options.awaitAck === true;
998
1018
  this.inflight++;
999
- return new Promise((resolve) => {
1019
+ return new Promise((resolve2) => {
1000
1020
  const socket = new net.Socket();
1001
1021
  this.sockets.add(socket);
1002
- 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 };
1022
+ 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 } : {} };
1003
1023
  let done = false;
1004
1024
  const finish = (value) => {
1005
1025
  if (done) return;
@@ -1010,10 +1030,10 @@ var IpcTransport = class {
1010
1030
  this.cancels.delete(abort);
1011
1031
  this.inflight--;
1012
1032
  socket.destroy();
1013
- resolve(value);
1033
+ resolve2(value);
1014
1034
  };
1015
1035
  const abort = () => finish(null);
1016
- const timer = setTimeout(abort, options.expectReply ? waitMs : 3e3);
1036
+ const timer = setTimeout(abort, holdOpen ? waitMs : 3e3);
1017
1037
  const dialTimer = setTimeout(abort, 3e3);
1018
1038
  this.cancels.add(abort);
1019
1039
  options.signal?.addEventListener("abort", abort, { once: true });
@@ -1035,7 +1055,7 @@ var IpcTransport = class {
1035
1055
  finish(null);
1036
1056
  return;
1037
1057
  }
1038
- if (!options.expectReply) {
1058
+ if (!holdOpen) {
1039
1059
  socket.end(() => finish(envelope));
1040
1060
  }
1041
1061
  });
@@ -1165,12 +1185,12 @@ var InboundDelivery = class {
1165
1185
  } catch (error) {
1166
1186
  this.host.log(`pie-ipc: audit entry failed: ${error instanceof Error ? error.message : String(error)}`);
1167
1187
  }
1168
- if (this.host.hasUI && this.effectiveAutoInject && this.pending.size < MAX_INBOX_MESSAGES) {
1188
+ if (this.host.editorInjection && this.effectiveAutoInject && this.pending.size < MAX_INBOX_MESSAGES) {
1169
1189
  this.inject(message);
1170
1190
  return "injected";
1171
1191
  }
1172
1192
  this.enqueueInbox(message);
1173
- return this.host.hasUI ? "queued" : "headless-queued";
1193
+ return this.host.editorInjection ? "queued" : "headless-queued";
1174
1194
  }
1175
1195
  inject(message) {
1176
1196
  const wrapped = wrapInboundText(message.fromLabel, message.text, message.receivedAt, message.id);
@@ -1251,6 +1271,17 @@ var InboundDelivery = class {
1251
1271
  get inboxSize() {
1252
1272
  return this.inbox.length;
1253
1273
  }
1274
+ /** Would an inbound message be INJECTED right now (vs inbox-queued)?
1275
+ * Mirrors routeMessage's live decision — auto-inject mode, degradation,
1276
+ * and pending capacity — so consumers (the notify fallback) act on
1277
+ * EFFECTIVE delivery, not host capability (a muted TUI queues like an
1278
+ * embedded host). */
1279
+ willInjectNow() {
1280
+ return this.hasUIInjection() && this.effectiveAutoInject && this.pending.size < MAX_INBOX_MESSAGES;
1281
+ }
1282
+ hasUIInjection() {
1283
+ return this.host.editorInjection;
1284
+ }
1254
1285
  get pendingInjections() {
1255
1286
  return this.pending.size;
1256
1287
  }
@@ -1357,7 +1388,7 @@ var StatusProjection = class {
1357
1388
  this.lastBodyAt = 0;
1358
1389
  this.undelivered = 0;
1359
1390
  }
1360
- /** Body text used to answer waiting ipc_send peers. */
1391
+ /** Body text used to answer waiting ipc_send_notify peers. */
1361
1392
  lastBodyForReply() {
1362
1393
  return this.lastBodyText;
1363
1394
  }
@@ -1524,6 +1555,7 @@ function resultJson(payload) {
1524
1555
  }
1525
1556
 
1526
1557
  // builtin/extensions/pie-ipc/index.ts
1558
+ var DEFAULT_NOTIFY_FALLBACK_MS = 6e5;
1527
1559
  var Runtime = class {
1528
1560
  constructor(ctx, config, discoveryDir) {
1529
1561
  this.ctx = ctx;
@@ -1544,6 +1576,31 @@ var Runtime = class {
1544
1576
  allowPolicy;
1545
1577
  /** Inbound messages we accepted for a turn; answered on turn settle. */
1546
1578
  awaitingReply = /* @__PURE__ */ new Map();
1579
+ /** Completion subscriptions (notifyCompletion senders): deliveryId ->
1580
+ * { peer, requestId }. One best-effort push per entry when the consuming
1581
+ * turn settles (success/failure/cancel); entries never outlive the ledger
1582
+ * record they mirror — session change, dispose, and ledger eviction all
1583
+ * drop them. In-memory by design: a restarted peer re-learns through
1584
+ * ipc_result (the authoritative pull path). */
1585
+ completionWatchers = /* @__PURE__ */ new Map();
1586
+ /** Local fallback timers for OUR notify-mode sends (requestId -> timer):
1587
+ * if the peer's push never arrives, wake ourselves once to check
1588
+ * ipc_result. Cleared when the notification (or its inbox delivery)
1589
+ * lands, so a delivered notification never double-wakes. */
1590
+ notifyFallbacks = /* @__PURE__ */ new Map();
1591
+ /** Notify-mode sends whose completion push already landed — including the
1592
+ * completion-BEFORE-ack window (the reverse push can win the race). Bounded
1593
+ * by the same retention discipline as the fallbacks: entries leave with
1594
+ * their timer or when the check hint fires. */
1595
+ completedNotifies = /* @__PURE__ */ new Set();
1596
+ /** Session/lifecycle generation for outbound notify continuations (review
1597
+ * r4): sendToPeer awaits transport.send across session switches; a late
1598
+ * null/ack continuation must not arm fallback state (or later fire its
1599
+ * [ipc-check] injection) into the NEW session. Incremented on session
1600
+ * change and dispose; captured before the await and re-checked in the
1601
+ * send continuations. Timers are cleared synchronously in the same
1602
+ * session-change handler, so no callback can outlive its session. */
1603
+ notifyGeneration = 0;
1547
1604
  results = new RequestResultStore();
1548
1605
  executionFailure;
1549
1606
  active = false;
@@ -1582,7 +1639,7 @@ var Runtime = class {
1582
1639
  });
1583
1640
  this.statusBase.secret = this.transport.secret;
1584
1641
  this.serverReady = true;
1585
- this.writeStatus();
1642
+ if (!this.writeStatus()) this.ctx.log("pie-ipc: initial status publication failed; heartbeat will retry");
1586
1643
  this.stopHeartbeat = startHeartbeat(this.discoveryDir, () => {
1587
1644
  listPeers(this.discoveryDir, { selfId: this.instanceId, pruneDead: true });
1588
1645
  return this.currentStatus();
@@ -1601,8 +1658,8 @@ var Runtime = class {
1601
1658
  return { ...snapshot, allowPeers: [...this.allowPolicy.snapshot()], undeliveredInjections: this.delivery?.undeliveredInjections ?? snapshot.undeliveredInjections ?? 0 };
1602
1659
  }
1603
1660
  writeStatus() {
1604
- if (!this.serverReady) return;
1605
- writeStatusFile(this.discoveryDir, { ...this.currentStatus(), updatedAt: Date.now() }, (message) => this.ctx.log(message));
1661
+ if (!this.serverReady) return false;
1662
+ return writeStatusFile(this.discoveryDir, { ...this.currentStatus(), updatedAt: Date.now() }, (message) => this.ctx.log(message));
1606
1663
  }
1607
1664
  handleEnvelope(envelope, respond, signal) {
1608
1665
  const reply = (kind, text) => {
@@ -1669,10 +1726,16 @@ var Runtime = class {
1669
1726
  return;
1670
1727
  }
1671
1728
  case "message": {
1729
+ if (this.sessionId === null) {
1730
+ reply("result", "rejected: session binding in progress; retry shortly");
1731
+ return;
1732
+ }
1672
1733
  if (envelope.sessionId !== (this.sessionId ?? "")) {
1673
1734
  reply("result", "rejected: target session changed");
1674
1735
  return;
1675
1736
  }
1737
+ const doneMatch = /^\[ipc-done\] requestId=([a-zA-Z0-9:-]{1,128}) /.exec(envelope.text ?? "");
1738
+ if (doneMatch && this.allowPolicy.allows(envelope.from)) this.completeNotify(doneMatch[1]);
1676
1739
  if (envelope.waitMs && this.awaitingReply.size >= 100) {
1677
1740
  reply("result", "rejected: reply capacity reached");
1678
1741
  return;
@@ -1696,9 +1759,21 @@ var Runtime = class {
1696
1759
  return;
1697
1760
  }
1698
1761
  this.results.accept(envelope.from, envelope.id, this.sessionId ?? "");
1762
+ if (envelope.notifyCompletion && !envelope.waitMs) {
1763
+ if (this.completionWatchers.size >= 100) {
1764
+ const oldest = this.completionWatchers.keys().next().value;
1765
+ if (oldest !== void 0) {
1766
+ const retired = this.completionWatchers.get(oldest);
1767
+ this.completionWatchers.delete(oldest);
1768
+ this.sendCompletionNotification(retired, "unknown", void 0);
1769
+ }
1770
+ }
1771
+ this.completionWatchers.set(deliveryId, { peer: envelope.from, requestId: envelope.id, subscriberSession: envelope.subscriberSession ?? "" });
1772
+ }
1699
1773
  const decision = this.delivery?.routeMessage({ ...envelope, id: deliveryId }, this.displayNameOf(envelope.from));
1700
1774
  if (decision === "denied") {
1701
1775
  this.results.remove(deliveryId);
1776
+ this.completionWatchers.delete(deliveryId);
1702
1777
  this.finishReply(deliveryId, "denied: not on this peer's allow list (/tools/ipc allow)");
1703
1778
  if (!envelope.waitMs) reply("result", "denied: not allowed");
1704
1779
  return;
@@ -1717,7 +1792,7 @@ var Runtime = class {
1717
1792
  onEvent(event) {
1718
1793
  switch (event.type) {
1719
1794
  case "turn:start": {
1720
- if (!this.active) this.executionFailure = void 0;
1795
+ this.executionFailure = void 0;
1721
1796
  this.active = true;
1722
1797
  this.projection.onTurnStarted();
1723
1798
  if (this.projection.updateFromEvent(event)) this.writeStatus();
@@ -1746,6 +1821,9 @@ var Runtime = class {
1746
1821
  this.delivery?.resetSessionState();
1747
1822
  this.polledInputs.clear();
1748
1823
  this.results.clear();
1824
+ this.completionWatchers.clear();
1825
+ this.clearNotifyFallbacks();
1826
+ this.notifyGeneration++;
1749
1827
  this.projection.resetSessionState();
1750
1828
  this.executionFailure = void 0;
1751
1829
  for (const id of [...this.awaitingReply.keys()]) this.finishReply(id, "cancelled: target session changed");
@@ -1808,6 +1886,133 @@ var Runtime = class {
1808
1886
  if (waiter.consumed) this.finishReply(id, failed ? "(peer turn failed or was cancelled)" : waiter.body || "(empty reply)");
1809
1887
  }
1810
1888
  this.results.finishRunning(failed ? "(peer turn failed or was cancelled)" : "(empty reply)", failed);
1889
+ this.pushCompletionNotifications();
1890
+ }
1891
+ /** One best-effort push per completion watcher whose request reached a
1892
+ * TERMINAL state (done/failed): a fresh `message` envelope back to the
1893
+ * subscribing peer, delivered through its own inbound path (editor
1894
+ * injection / inbox / stdout eventSink). Failure is silent — the
1895
+ * watcher's ipc_result pull remains authoritative. Never awaits: settle
1896
+ * handlers must not block the host turn loop.
1897
+ * Non-terminal records (accepted — e.g. the input is still queued behind
1898
+ * an unrelated busy turn) KEEP their watcher: an unrelated turn settling
1899
+ * must not report a still-pending request as finished and retire the
1900
+ * sender's fallback timer on a lie. Evicted records push once with the
1901
+ * unknown hint (the pull path is the only truth left). */
1902
+ pushCompletionNotifications() {
1903
+ if (this.completionWatchers.size === 0 || !this.transport || this.disposed) return;
1904
+ for (const [deliveryId, watcher] of [...this.completionWatchers.entries()]) {
1905
+ const record = this.results.get(watcher.peer, watcher.requestId, this.sessionId ?? "");
1906
+ if (record && record.status !== "done" && record.status !== "failed") continue;
1907
+ this.completionWatchers.delete(deliveryId);
1908
+ this.sendCompletionNotification(watcher, record?.status ?? "unknown", record?.text, deliveryId);
1909
+ }
1910
+ }
1911
+ /** Best-effort reverse push of one terminal (or eviction-unknown) outcome.
1912
+ * Shared by turn settlement and watcher-cap retirement. Failure is
1913
+ * silent — the sender's ipc_result pull stays authoritative.
1914
+ * ADMISSION-AWARE (rename review r2): the transport admits at most 8
1915
+ * concurrent sends; a settlement completing more subscriptions than that
1916
+ * previously deleted the watcher and logged 'sent' even when the local
1917
+ * admission returned null — those completions were LOST until the
1918
+ * sender's 10-minute fallback. On admission failure the watcher is now
1919
+ * RE-QUEUED for the next settle event instead of retired. */
1920
+ sendCompletionNotification(watcher, outcome, body, deliveryId) {
1921
+ const notification = `[ipc-done] requestId=${watcher.requestId} outcome=${outcome}${outcome === "unknown" ? " (result evicted; query ipc_result)" : body !== void 0 ? `
1922
+ ${body}` : ""}`;
1923
+ const statusFile = readStatusFile(this.discoveryDir, watcher.peer);
1924
+ if (!statusFile?.port) return;
1925
+ if (!this.transport.canSendNow()) {
1926
+ if (deliveryId !== void 0) this.completionWatchers.set(deliveryId, watcher);
1927
+ this.ctx.log(`pie-ipc: completion push deferred (transport busy) for ${watcher.requestId}`);
1928
+ return;
1929
+ }
1930
+ void this.transport.send(watcher.peer, statusFile.port, "message", {
1931
+ requestId: `notify-${this.instanceId}-${watcher.requestId}`,
1932
+ text: notification,
1933
+ // Address the ORIGINATING subscription session (r5), falling back to the
1934
+ // current advertisement only for legacy watchers without one.
1935
+ sessionId: watcher.subscriberSession || statusFile.sessionId || "",
1936
+ expectReply: false
1937
+ }).catch(() => void 0);
1938
+ this.ctx.log(`pie-ipc: completion notification sent to ${watcher.peer} for ${watcher.requestId} (${outcome})`);
1939
+ }
1940
+ /** Arm the local fallback check for a notify-mode send: on expiry, inject a
1941
+ * hint so the model checks ipc_result itself. The wake goes through the
1942
+ * normal inbound path (sendUserMessage), which the interactive host queues
1943
+ * when busy and the embedded host emits as a user.message event. */
1944
+ armNotifyFallback(requestId, fallbackMs, peerName) {
1945
+ if (this.completedNotifies.has(requestId)) {
1946
+ this.completedNotifies.delete(requestId);
1947
+ return true;
1948
+ }
1949
+ if (this.notifyFallbacks.size >= 20) {
1950
+ this.ctx.log(`pie-ipc: fallback budget exhausted (${this.notifyFallbacks.size} outstanding); no timer for ${requestId}`);
1951
+ return false;
1952
+ }
1953
+ this.clearNotifyFallback(requestId);
1954
+ const timer = setTimeout(() => {
1955
+ this.notifyFallbacks.delete(requestId);
1956
+ this.completedNotifies.delete(requestId);
1957
+ if (this.disposed) return;
1958
+ const hint = `[ipc-check] No completion notification arrived for requestId=${requestId} (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.`;
1959
+ try {
1960
+ const scope = this.ctx.beginUserInput?.();
1961
+ if (scope) {
1962
+ scope.submit(hint).then(() => scope.dispose(), () => scope.dispose());
1963
+ } else {
1964
+ this.ctx.sendUserMessage(hint);
1965
+ }
1966
+ } catch {
1967
+ }
1968
+ }, Math.max(5e3, Math.min(fallbackMs, 6e5)));
1969
+ timer.unref();
1970
+ this.notifyFallbacks.set(requestId, timer);
1971
+ return true;
1972
+ }
1973
+ /** A completion notification (or its inbox delivery) landed for our send.
1974
+ * Observability-aware (final audit): an INJECTING host shows the message
1975
+ * to the model the moment it lands — the fallback timer dies (single
1976
+ * wake). An INBOX-ONLY host (embedded) has no scheduler: inbox landing is
1977
+ * not observation, so instead of silently cancelling the only wake, the
1978
+ * fallback fires IMMEDIATELY as a [ipc-done-check] hint carrying the
1979
+ * outcome — every host kind surfaces the completion exactly once. */
1980
+ completeNotify(requestId) {
1981
+ const willInject = this.delivery?.willInjectNow() ?? this.ctx.capabilities.editorInjection;
1982
+ if (willInject) {
1983
+ this.clearNotifyFallback(requestId);
1984
+ return;
1985
+ }
1986
+ if (this.completedNotifies.size > 200) this.completedNotifies.clear();
1987
+ this.completedNotifies.add(requestId);
1988
+ const timer = this.notifyFallbacks.get(requestId);
1989
+ if (timer) {
1990
+ clearTimeout(timer);
1991
+ this.notifyFallbacks.delete(requestId);
1992
+ }
1993
+ if (this.disposed) return;
1994
+ try {
1995
+ this.ctx.sendUserMessage(`[ipc-done-check] The completion notification for requestId=${requestId} 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.`);
1996
+ } catch {
1997
+ }
1998
+ }
1999
+ /** A completion notification (or its inbox delivery) landed for our send:
2000
+ * destroy the fallback timer so the model is woken exactly once. Also
2001
+ * records completion for sends whose push arrived BEFORE the ack did —
2002
+ * armNotifyFallback then arms nothing. */
2003
+ clearNotifyFallback(requestId) {
2004
+ if (this.completedNotifies.size > 200) this.completedNotifies.clear();
2005
+ this.completedNotifies.add(requestId);
2006
+ const timer = this.notifyFallbacks.get(requestId);
2007
+ if (timer) {
2008
+ clearTimeout(timer);
2009
+ this.notifyFallbacks.delete(requestId);
2010
+ }
2011
+ }
2012
+ clearNotifyFallbacks() {
2013
+ for (const timer of this.notifyFallbacks.values()) clearTimeout(timer);
2014
+ this.notifyFallbacks.clear();
2015
+ this.completedNotifies.clear();
1811
2016
  }
1812
2017
  // ---- mutations from commands ----
1813
2018
  mutations() {
@@ -1884,7 +2089,7 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1884
2089
  const matches = listings.filter(({ file }) => file.instanceId.toLowerCase().startsWith(ref) || file.displayName.toLowerCase().startsWith(ref));
1885
2090
  return matches.length === 1 ? matches[0].file : null;
1886
2091
  }
1887
- async sendToPeer(peerRef, text, wait, waitMs, context) {
2092
+ async sendToPeer(peerRef, text, wait, waitMs, context, notify = false, fallbackMs = DEFAULT_NOTIFY_FALLBACK_MS) {
1888
2093
  const target = this.resolvePeer(peerRef);
1889
2094
  if (!target) {
1890
2095
  return { content: [{ type: "text", text: `Peer not found: ${peerRef}. Call ipc_list_peers first.` }], isError: true };
@@ -1897,6 +2102,8 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1897
2102
  }
1898
2103
  const body = clipBody(text, this.config.maxBodyChars);
1899
2104
  const requestId = randomUUID2();
2105
+ const notifyMode = notify && !wait;
2106
+ const sendGeneration = this.notifyGeneration;
1900
2107
  const reply = await this.transport.send(target.instanceId, target.port, "message", {
1901
2108
  requestId,
1902
2109
  text: body,
@@ -1906,8 +2113,29 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
1906
2113
  signal: context.signal,
1907
2114
  // Waiting sends resolve only on the peer's turn-settling result (or
1908
2115
  // its terminal denied answer); the receipt ack stays informational.
1909
- replyKinds: /* @__PURE__ */ new Set(["result"])
2116
+ replyKinds: wait ? /* @__PURE__ */ new Set(["result"]) : /* @__PURE__ */ new Set(["result", "ack"]),
2117
+ ...notifyMode ? { notifyCompletion: true, awaitAck: true, subscriberSession: this.sessionId ?? "" } : {}
1910
2118
  });
2119
+ if (notifyMode) {
2120
+ if (sendGeneration !== this.notifyGeneration) {
2121
+ return { content: [{ type: "text", text: `Receipt unconfirmed and the local session changed mid-send \u2014 no automatic wake armed for the new session. Query ipc_result with requestId=${requestId} if still relevant.` }], isError: true, details: { requestId } };
2122
+ }
2123
+ if (!reply) {
2124
+ const peerName2 = peerLabel(target.instanceId, target.displayName);
2125
+ const armed2 = this.armNotifyFallback(requestId, fallbackMs, peerName2);
2126
+ return {
2127
+ 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."}` }],
2128
+ isError: true,
2129
+ details: { requestId }
2130
+ };
2131
+ }
2132
+ if (reply.kind === "result") {
2133
+ return { content: [{ type: "text", text: reply.text ?? "(empty reply)" }], isError: true, details: { requestId } };
2134
+ }
2135
+ const peerName = peerLabel(target.instanceId, target.displayName);
2136
+ const armed = this.armNotifyFallback(requestId, fallbackMs, peerName);
2137
+ 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 } };
2138
+ }
1911
2139
  if (!wait) {
1912
2140
  if (!reply) return { content: [{ type: "text", text: `Send failed: ${peerLabel(target.instanceId, target.displayName)} unreachable. requestId=${requestId}` }], isError: true, details: { requestId } };
1913
2141
  return { content: [{ type: "text", text: `Sent to ${peerLabel(target.instanceId, target.displayName)} (no wait; receipt/consumption not confirmed). requestId=${requestId}` }], details: { requestId } };
@@ -1968,6 +2196,9 @@ ${message.text}`).join("\n---\n");
1968
2196
  this.delivery?.resetSessionState();
1969
2197
  this.polledInputs.clear();
1970
2198
  this.results.clear();
2199
+ this.completionWatchers.clear();
2200
+ this.clearNotifyFallbacks();
2201
+ this.notifyGeneration++;
1971
2202
  try {
1972
2203
  this.ctx.ui.setStatus?.("pie-ipc-peers", void 0);
1973
2204
  } catch {
@@ -2002,7 +2233,8 @@ function safeRead(file) {
2002
2233
  }
2003
2234
  }
2004
2235
  function pieIpcExtension(ctx) {
2005
- const configDir = process.env.PIE_IPC_CONFIG_DIR ?? getConfigDirSafe(ctx);
2236
+ const rawConfigDir = process.env.PIE_IPC_CONFIG_DIR ?? getConfigDirSafe(ctx);
2237
+ const configDir = process.platform === "win32" ? rawConfigDir : path4.resolve(rawConfigDir === "~" ? homeDir() : rawConfigDir.startsWith("~/") ? path4.join(homeDir(), rawConfigDir.slice(2)) : rawConfigDir);
2006
2238
  let discoveryDir;
2007
2239
  try {
2008
2240
  discoveryDir = ipcDiscoveryDir(configDir);
@@ -2024,11 +2256,12 @@ function pieIpcExtension(ctx) {
2024
2256
  }
2025
2257
  }
2026
2258
  const runtime = new Runtime(ctx, config, discoveryDir);
2027
- ctx.log(`pie-ipc: enabled as ${runtime.instanceId} (${ctx.hasUI ? "server+client" : "client-only"})`);
2028
- if (ctx.hasUI) {
2259
+ const serverEligible = ctx.capabilities.eventSink && ctx.capabilities.longLived;
2260
+ ctx.log(`pie-ipc: enabled as ${runtime.instanceId} (${serverEligible ? "server+client (starting listener)" : "client-only"})`);
2261
+ if (serverEligible) {
2029
2262
  runtime.delivery = new InboundDelivery(
2030
2263
  {
2031
- hasUI: ctx.hasUI,
2264
+ editorInjection: ctx.capabilities.editorInjection,
2032
2265
  sendUserMessage: (text) => ctx.sendUserMessage(text),
2033
2266
  appendEntry: (type, data) => ctx.appendEntry?.(type, data) ?? "",
2034
2267
  setStatus: (key, text) => ctx.ui.setStatus?.(key, text),
@@ -2038,7 +2271,9 @@ function pieIpcExtension(ctx) {
2038
2271
  },
2039
2272
  { autoInject: config.autoInject ?? true, allowPolicy: runtime.allowPolicy, onConsumed: (id) => runtime.markConsumed(id) }
2040
2273
  );
2041
- void runtime.startServer().catch((error) => {
2274
+ void runtime.startServer().then(() => {
2275
+ ctx.log(`pie-ipc: listening + advertised as ${runtime.instanceId}`);
2276
+ }).catch((error) => {
2042
2277
  ctx.log(`pie-ipc: server start failed: ${error instanceof Error ? error.message : String(error)}`);
2043
2278
  });
2044
2279
  } else {
@@ -2088,14 +2323,16 @@ function pieIpcExtension(ctx) {
2088
2323
  execute: async () => ({ content: [{ type: "text", text: await runtime.listPeers() }] })
2089
2324
  });
2090
2325
  ctx.registerTool({
2091
- name: "ipc_send",
2092
- label: "Send a message to a Pie peer",
2093
- description: `Send text to another Pie process (interactive peer) addressed by display name or instance id prefix. Every send returns a requestId for ipc_result. wait=false (default): return after socket submission, without claiming receipt or consumption. wait=true: hold until the peer's reply arrives (bounded by waitMs, default ${DEFAULT_SEND_WAIT_MS}ms); on timeout, use ipc_result before resending because accepted work is not cancelled. Inbound messages from peers arrive as user input or in ipc_poll.`,
2326
+ name: "ipc_send_notify",
2327
+ label: "Send a message to a Pie peer and get notified when it finishes",
2328
+ 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.`,
2094
2329
  parameters: Type.Object({
2095
2330
  to: Type.String({ description: "Peer display name or instance id (see ipc_list_peers)" }),
2096
2331
  text: Type.String({ description: "Message body for the peer" }),
2097
- wait: Type.Optional(Type.Boolean({ description: "Wait for the peer's reply text (default false)" })),
2098
- waitMs: Type.Optional(Type.Number({ description: "Reply wait budget in ms (default 120000, max 600000)", minimum: 100, maximum: 6e5 }))
2332
+ 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." })),
2333
+ wait: Type.Optional(Type.Boolean({ description: "Block this call until the peer's reply (one-shot hosts only; prefer the default notify flow)" })),
2334
+ waitMs: Type.Optional(Type.Number({ description: "Reply wait budget in ms (default 120000, max 600000)", minimum: 100, maximum: 6e5 })),
2335
+ 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 }))
2099
2336
  }),
2100
2337
  risk,
2101
2338
  renderHint: {
@@ -2104,15 +2341,15 @@ function pieIpcExtension(ctx) {
2104
2341
  return `\u2192 ${record.to ?? "?"}: ${(record.text ?? "").slice(0, 60)}`;
2105
2342
  }
2106
2343
  },
2107
- execute: async (args, context) => runtime.sendToPeer(args.to, args.text, args.wait ?? false, Math.min(args.waitMs ?? DEFAULT_SEND_WAIT_MS, 6e5), context)
2344
+ 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))
2108
2345
  });
2109
2346
  ctx.registerTool({
2110
2347
  name: "ipc_result",
2111
2348
  label: "Query a Pie request result",
2112
- description: "Query a result by the requestId returned from ipc_send, 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.",
2349
+ 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.",
2113
2350
  parameters: Type.Object({
2114
2351
  to: Type.String({ description: "Peer display name or instance id prefix" }),
2115
- requestId: Type.Optional(Type.String({ description: "Request id returned by ipc_send" })),
2352
+ requestId: Type.Optional(Type.String({ description: "Request id returned by ipc_send_notify" })),
2116
2353
  limit: Type.Optional(Type.Number({ description: "Recent result count when requestId is omitted (default 5, max 20)", minimum: 1, maximum: 20 }))
2117
2354
  }),
2118
2355
  risk: { ...risk, riskClass: "network", requiresPermission: false, externalSideEffect: false, writesNetwork: false },
@@ -2227,6 +2464,8 @@ function getConfigDirSafe(_ctx) {
2227
2464
  return path4.join(homeDir(), ".pie");
2228
2465
  }
2229
2466
  function homeDir() {
2467
+ const osHome = os.homedir();
2468
+ if (osHome) return osHome;
2230
2469
  return process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
2231
2470
  }
2232
2471
  export {
@@ -0,0 +1,93 @@
1
+ # pie-proc — controlled worker-process lifecycle
2
+
3
+ The concierge plan's S5 guardrail layer: create and retire pie worker
4
+ processes WITHOUT raw shell access. Bounded shapes, allowlisted working
5
+ directories, isolated agent dirs, caps, TTL sweeping, and an audit ledger.
6
+
7
+ ## Host gating
8
+
9
+ Activates on `longLived` (interactive TUI and resident json-events hosts —
10
+ the concierge). One-shot print hosts never own workers.
11
+
12
+ ## Tool: `pie_proc`
13
+
14
+ - **spawn** `{name, cwd, kind?, task?, ttlMs?, imForward?}`
15
+ - `kind:"resident"` (default): `pie --json-events --idle --session-id pie-proc-<name>-<generation>`
16
+ with cwd = the given directory and `PIE_CODING_AGENT_DIR` = a per-worker
17
+ isolated agent dir (own models/config sessions; im-forward settings from
18
+ `imForward` — identity fields only — are written there as the worker's
19
+ own user-layer config). Dispatch work with `ipc_send_notify` addressed
20
+ to the worker's PEER DISPLAY NAME (`<name>`); the per-launch session
21
+ token is an identity marker, not an address. The worker's stdout events
22
+ stream to `~/.pie/pie-proc/logs/<name>.jsonl`.
23
+ - `kind:"oneshot"`: the task travels in the `PIE_PROC_ONESHOT_TASK` env
24
+ var; argv carries only `--session-id <token>` (the CLI entry routes the
25
+ child role into print mode). Process exit IS the completion.
26
+ - `cwd` must CANONICALLY resolve (realpath, symlink-safe) inside an
27
+ `allowCwd` root.
28
+ - `ttlMs` retires an idle RESIDENT automatically (graceful SIGTERM; busy
29
+ state is read from the worker's pie-ipc status — a "working" worker is
30
+ never reaped; the entry is retained until death is confirmed).
31
+ - Names: `[a-z0-9-_]`, ≤48 chars, unique among alive workers.
32
+ - Admission reserves the name/cap slot durably (a pending registry entry
33
+ carrying the spawning process's pid) BEFORE the child exists; another
34
+ process's spawn sees the reservation and refuses.
35
+ - **kill** `{name, force?}`: SIGTERM with bounded identity-verified
36
+ escalation; the registry entry is removed ONLY when death is confirmed —
37
+ a signalled-but-unconfirmed worker keeps its record (cap slot included)
38
+ with an isError result saying so. `force:true` skips grace.
39
+ - **list**: workers with pid / session token / cwd / kind / liveness
40
+ (alive/dead/unknown) / idle seconds / TTL / IM binding.
41
+
42
+ ## Configuration `~/.pie/pie-proc.json`
43
+
44
+ ```json
45
+ {
46
+ "allowCwd": ["~/Documents/AIProjects"],
47
+ "maxWorkers": 5,
48
+ "killGraceMs": 15000,
49
+ "defaultTtlMs": 0
50
+ }
51
+ ```
52
+
53
+ - `allowCwd` (REQUIRED for spawn; everything else defaults): absolute or `~/`
54
+ roots; a spawn cwd must canonically equal or live under one of them.
55
+ - `maxWorkers`: simultaneous alive-worker cap (spawn refuses beyond).
56
+ - `killGraceMs`: force-kill escalation window after SIGTERM.
57
+ - `defaultTtlMs`: idle TTL applied when a spawn omits `ttlMs` (0 = never).
58
+
59
+ ## Registry v2 & audit
60
+
61
+ `~/.pie/pie-proc/` holds a LOCK-FREE compare-and-swap registry: each
62
+ mutation writes a fully-formed candidate to `workers.r<N>.json` and
63
+ publishes it atomically with link(); EEXIST means a concurrent writer won —
64
+ the mutation re-reads and retries. There is no lock file to go stale and
65
+ no takeover race. Revision slots are APPEND-ONLY and never reclaimed
66
+ (r14: reclaiming a slot let a paused stale writer publish into it). Records
67
+ carry name / session token / generation / pid / cwd / pieDir / kind /
68
+ spawnedAt / lastActiveAt / ttl / imForward, plus `reserverPid` on pending
69
+ (pid 0) entries. Liveness is STRICT: the worker's unique argv token must
70
+ appear in the process command line (wmic → PowerShell Get-CimInstance
71
+ fallback on Windows 11+); a probe failure is `unknown`, and unknown is
72
+ never signalled. A v1 registry (records without generation) fails CLOSED
73
+ with a migration error. Abandoned pending reservations are reaped only
74
+ when their reserver process is confirmed dead (same-process aborted spawns
75
+ are retried by the sweep). Every spawn/kill/TTL reap goes to the extension
76
+ log (verbose mode / host transcript).
77
+
78
+ ## Design notes
79
+
80
+ - No arbitrary argv: the shapes are exactly the two documented above; the
81
+ model cannot inject flags (the oneshot task never enters argv). This is
82
+ the deliberate replacement for teaching the concierge to spawn processes
83
+ through the shell tool.
84
+ - Workers do NOT inherit the parent's agent dir: each gets
85
+ `~/.pie/pie-proc/agents/<name>/` (own models.json etc., inherited from the
86
+ parent on first creation). The cwd allowlist, not the PIE dir, scopes
87
+ file access. Workers DO inherit the parent's IPC discovery root
88
+ (PIE_IPC_CONFIG_DIR is set to the parent's effective config dir) so the
89
+ concierge can address them by peer name via ipc_send_notify; their peer
90
+ name travels in PIE_IPC_DISPLAY_NAME — never by writing a shared ipc.json.
91
+ - The im field is written before spawn (only when absent) as a plain
92
+ user-layer im-forward.json inside the worker's PIE dir — the same
93
+ layered-config contract any pie reads; no new IM code path.