@cydm/pie 2.7.15 → 2.7.17

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.
@@ -7,6 +7,7 @@ import "../../../chunks/chunk-LZQXQOPJ.js";
7
7
  // builtin/extensions/pie-ipc/index.ts
8
8
  import * as fs3 from "node:fs";
9
9
  import * as path4 from "node:path";
10
+ import { randomUUID as randomUUID2 } from "node:crypto";
10
11
 
11
12
  // builtin/extensions/pie-ipc/pure.ts
12
13
  import { randomBytes } from "node:crypto";
@@ -51,7 +52,8 @@ var ENVELOPE_KINDS = /* @__PURE__ */ new Set([
51
52
  "ack",
52
53
  "result",
53
54
  "state.get",
54
- "state"
55
+ "state",
56
+ "result.get"
55
57
  ]);
56
58
  var LIFECYCLE_STATES = /* @__PURE__ */ new Set(["working", "idle", "blocked"]);
57
59
  function parseEnvelope(raw) {
@@ -273,6 +275,7 @@ function foldLifecycleEvent(current, event, now = Date.now()) {
273
275
  }
274
276
  function resolveIpcConfig(configLayers) {
275
277
  const problems = [];
278
+ let invalidConfig = false;
276
279
  const merged = {};
277
280
  for (const layer of configLayers) {
278
281
  if (layer.content === void 0) continue;
@@ -280,14 +283,20 @@ function resolveIpcConfig(configLayers) {
280
283
  const parsed = JSON.parse(layer.content);
281
284
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
282
285
  problems.push(`${layer.file}: root is not an object`);
286
+ invalidConfig = true;
283
287
  continue;
284
288
  }
285
289
  Object.assign(merged, parsed);
286
290
  } catch (error) {
287
291
  problems.push(`${layer.file}: ${error instanceof Error ? error.message : String(error)}`);
292
+ invalidConfig = true;
288
293
  }
289
294
  }
290
- if (merged.enabled !== true) return { config: null, problems };
295
+ if (merged.enabled !== void 0 && typeof merged.enabled !== "boolean") {
296
+ problems.push("pie-ipc: enabled must be a boolean");
297
+ invalidConfig = true;
298
+ }
299
+ if (invalidConfig || merged.enabled === false) return { config: null, problems };
291
300
  const config = { enabled: true };
292
301
  if (typeof merged.displayName === "string" && merged.displayName.trim()) {
293
302
  config.displayName = merged.displayName.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 60);
@@ -815,6 +824,7 @@ function buildStatusFile(input) {
815
824
  import * as net from "node:net";
816
825
  import { createHmac, randomBytes as randomBytes4, randomUUID, timingSafeEqual } from "node:crypto";
817
826
  import { StringDecoder } from "node:string_decoder";
827
+ var CLOSE_FLUSH_TIMEOUT_MS = 1e3;
818
828
  function signEnvelope(e, secret) {
819
829
  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];
820
830
  return { ...e, auth: createHmac("sha256", secret).update(JSON.stringify(payload)).digest("hex") };
@@ -963,6 +973,7 @@ var IpcTransport = class {
963
973
  if (e.waitMs) socket.setTimeout(Math.max(6e4, e.waitMs + 1e3));
964
974
  if (!this.seen.add(`${e.from}:${e.id}`)) return;
965
975
  try {
976
+ if (this.closed) return;
966
977
  this.host.onEnvelope(e, (reply) => {
967
978
  if (reply.from === this.instanceId && reply.to === e.from && reply.replyTo === e.id) this.write(socket, reply, this.secret);
968
979
  }, lifecycle.signal);
@@ -986,7 +997,7 @@ var IpcTransport = class {
986
997
  return new Promise((resolve) => {
987
998
  const socket = new net.Socket();
988
999
  this.sockets.add(socket);
989
- const envelope = { v: IPC_PROTOCOL_VERSION, id: 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 };
1000
+ 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 };
990
1001
  let done = false;
991
1002
  const finish = (value) => {
992
1003
  if (done) return;
@@ -1037,7 +1048,12 @@ var IpcTransport = class {
1037
1048
  if (this.closed) return;
1038
1049
  this.closed = true;
1039
1050
  for (const cancel of [...this.cancels]) cancel();
1040
- for (const socket of this.sockets) socket.destroy();
1051
+ for (const socket of this.sockets) {
1052
+ if (socket.destroyed) continue;
1053
+ socket.end();
1054
+ const timer = setTimeout(() => socket.destroy(), CLOSE_FLUSH_TIMEOUT_MS);
1055
+ timer.unref();
1056
+ }
1041
1057
  this.sockets.clear();
1042
1058
  this.server.close();
1043
1059
  this.port = null;
@@ -1357,6 +1373,154 @@ var StatusProjection = class {
1357
1373
  }
1358
1374
  };
1359
1375
 
1376
+ // builtin/extensions/pie-ipc/results.ts
1377
+ var REQUEST_RESULT_RETENTION_MS = 6e5;
1378
+ var MAX_REQUEST_RESULTS = 100;
1379
+ var MAX_RECENT_RESULTS = 20;
1380
+ var RESULT_TEXT_CHARS = 7e3;
1381
+ function copy(record) {
1382
+ return { ...record };
1383
+ }
1384
+ var RequestResultStore = class {
1385
+ records = /* @__PURE__ */ new Map();
1386
+ prune(now) {
1387
+ for (const [id, record] of this.records) {
1388
+ if (record.completedAt !== void 0 && now - record.completedAt > REQUEST_RESULT_RETENTION_MS) this.records.delete(id);
1389
+ }
1390
+ while (this.records.size > MAX_REQUEST_RESULTS) {
1391
+ const completed = [...this.records.entries()].filter(([, record]) => record.completedAt !== void 0).sort((a, b) => a[1].completedAt - b[1].completedAt)[0];
1392
+ const oldest = completed ?? this.records.entries().next().value;
1393
+ if (!oldest) break;
1394
+ this.records.delete(oldest[0]);
1395
+ }
1396
+ }
1397
+ accept(senderId, requestId, sessionId, now = Date.now()) {
1398
+ this.prune(now);
1399
+ const id = `${senderId}:${requestId}`;
1400
+ if (this.records.has(id)) return;
1401
+ if (this.records.size >= MAX_REQUEST_RESULTS) {
1402
+ const completed = [...this.records.entries()].filter(([, record]) => record.completedAt !== void 0).sort((a, b) => a[1].completedAt - b[1].completedAt)[0];
1403
+ const oldest = completed ?? this.records.entries().next().value;
1404
+ if (oldest) this.records.delete(oldest[0]);
1405
+ }
1406
+ this.records.set(id, { requestId, senderId, sessionId, status: "accepted", createdAt: now });
1407
+ }
1408
+ markRunning(id, now = Date.now()) {
1409
+ const record = this.records.get(id);
1410
+ if (!record || record.status !== "accepted") return;
1411
+ record.status = "running";
1412
+ record.startedAt = now;
1413
+ }
1414
+ captureBody(text) {
1415
+ if (!text) return;
1416
+ for (const record of this.records.values()) {
1417
+ if (record.status === "running") record.text = clipBody(text, RESULT_TEXT_CHARS);
1418
+ }
1419
+ }
1420
+ finishRunning(text, failed, now = Date.now()) {
1421
+ for (const record of this.records.values()) {
1422
+ if (record.status !== "running") continue;
1423
+ record.status = failed ? "failed" : "done";
1424
+ record.text = clipBody(failed ? text : record.text || text, RESULT_TEXT_CHARS);
1425
+ record.completedAt = now;
1426
+ }
1427
+ this.prune(now);
1428
+ }
1429
+ get(senderId, requestId, sessionId, now = Date.now()) {
1430
+ this.prune(now);
1431
+ const record = this.records.get(`${senderId}:${requestId}`);
1432
+ if (!record || record.senderId !== senderId || record.sessionId !== sessionId) return void 0;
1433
+ return copy(record);
1434
+ }
1435
+ recent(senderId, sessionId, limit = 5, now = Date.now()) {
1436
+ this.prune(now);
1437
+ const bounded = Math.max(1, Math.min(MAX_RECENT_RESULTS, Math.floor(limit)));
1438
+ return [...this.records.values()].filter((record) => record.senderId === senderId && record.sessionId === sessionId).sort((a, b) => b.createdAt - a.createdAt).slice(0, bounded).map((record) => ({ ...copy(record), text: record.text ? clipBody(record.text, 120) : void 0 }));
1439
+ }
1440
+ remove(id) {
1441
+ this.records.delete(id);
1442
+ }
1443
+ clear() {
1444
+ this.records.clear();
1445
+ }
1446
+ get size() {
1447
+ return this.records.size;
1448
+ }
1449
+ };
1450
+ function resultPayload(record) {
1451
+ return {
1452
+ requestId: record.requestId,
1453
+ sessionId: record.sessionId,
1454
+ status: record.status,
1455
+ ...record.text !== void 0 ? { text: clipBody(record.text, RESULT_TEXT_CHARS) } : {},
1456
+ createdAt: record.createdAt,
1457
+ ...record.startedAt !== void 0 ? { startedAt: record.startedAt } : {},
1458
+ ...record.completedAt !== void 0 ? { completedAt: record.completedAt } : {}
1459
+ };
1460
+ }
1461
+ function recentResultPayload(record) {
1462
+ return {
1463
+ requestId: record.requestId,
1464
+ status: record.status,
1465
+ ...record.text !== void 0 ? { preview: record.text } : {},
1466
+ createdAt: record.createdAt,
1467
+ ...record.startedAt !== void 0 ? { startedAt: record.startedAt } : {},
1468
+ ...record.completedAt !== void 0 ? { completedAt: record.completedAt } : {}
1469
+ };
1470
+ }
1471
+ function isRecord(value) {
1472
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1473
+ }
1474
+ function resultJson(payload) {
1475
+ const direct = JSON.stringify(payload);
1476
+ if (direct.length <= MAX_BODY_CHARS) return direct;
1477
+ if (!isRecord(payload)) throw new Error("result payload exceeds envelope body cap");
1478
+ if (Array.isArray(payload.results)) {
1479
+ const clone = {
1480
+ ...payload,
1481
+ results: payload.results.map((item) => isRecord(item) ? { ...item } : item)
1482
+ };
1483
+ let serialized = direct;
1484
+ while (serialized.length > MAX_BODY_CHARS) {
1485
+ const items = clone.results;
1486
+ let longest;
1487
+ for (const value of items) {
1488
+ if (!isRecord(value)) continue;
1489
+ for (const key of ["preview", "text"]) {
1490
+ if (typeof value[key] === "string" && value[key].length > (longest?.length ?? 0)) longest = { item: value, key, length: value[key].length };
1491
+ }
1492
+ }
1493
+ clone.truncated = true;
1494
+ if (longest) {
1495
+ const current = longest.item[longest.key];
1496
+ const nextLength = Math.floor(current.length / 2);
1497
+ if (nextLength === 0) delete longest.item[longest.key];
1498
+ else longest.item[longest.key] = current.slice(0, nextLength);
1499
+ } else if (items.length > 0) {
1500
+ items.pop();
1501
+ } else {
1502
+ throw new Error("result payload exceeds envelope body cap");
1503
+ }
1504
+ serialized = JSON.stringify(clone);
1505
+ }
1506
+ return serialized;
1507
+ }
1508
+ if (typeof payload.text === "string") {
1509
+ const clone = { ...payload };
1510
+ let serialized = direct;
1511
+ while (serialized.length > MAX_BODY_CHARS) {
1512
+ const current = clone.text;
1513
+ const nextLength = Math.floor(current.length / 2);
1514
+ clone.truncated = true;
1515
+ if (nextLength === 0) delete clone.text;
1516
+ else clone.text = current.slice(0, nextLength);
1517
+ serialized = JSON.stringify(clone);
1518
+ }
1519
+ return serialized;
1520
+ }
1521
+ throw new Error("result payload exceeds envelope body cap");
1522
+ }
1523
+
1360
1524
  // builtin/extensions/pie-ipc/index.ts
1361
1525
  var Runtime = class {
1362
1526
  constructor(ctx, config, discoveryDir) {
@@ -1378,6 +1542,7 @@ var Runtime = class {
1378
1542
  allowPolicy;
1379
1543
  /** Inbound messages we accepted for a turn; answered on turn settle. */
1380
1544
  awaitingReply = /* @__PURE__ */ new Map();
1545
+ results = new RequestResultStore();
1381
1546
  executionFailure;
1382
1547
  active = false;
1383
1548
  polledInputs = /* @__PURE__ */ new Map();
@@ -1435,7 +1600,7 @@ var Runtime = class {
1435
1600
  }
1436
1601
  writeStatus() {
1437
1602
  if (!this.serverReady) return;
1438
- writeStatusFile(this.discoveryDir, this.currentStatus(), (message) => this.ctx.log(message));
1603
+ writeStatusFile(this.discoveryDir, { ...this.currentStatus(), updatedAt: Date.now() }, (message) => this.ctx.log(message));
1439
1604
  }
1440
1605
  handleEnvelope(envelope, respond, signal) {
1441
1606
  const reply = (kind, text) => {
@@ -1473,6 +1638,34 @@ var Runtime = class {
1473
1638
  }));
1474
1639
  return;
1475
1640
  }
1641
+ case "result.get": {
1642
+ const respond2 = (payload) => reply("result", resultJson(payload));
1643
+ if (envelope.sessionId !== (this.sessionId ?? "")) {
1644
+ respond2({ status: "unknown", reason: "target session changed" });
1645
+ return;
1646
+ }
1647
+ if (!this.allowPolicy.allows(envelope.from)) {
1648
+ respond2({ status: "unknown", reason: "restricted by local allow policy" });
1649
+ return;
1650
+ }
1651
+ try {
1652
+ const query = JSON.parse(envelope.text ?? "{}");
1653
+ if (query.requestId !== void 0) {
1654
+ if (typeof query.requestId !== "string" || !/^[a-zA-Z0-9:-]{1,128}$/.test(query.requestId)) {
1655
+ respond2({ status: "unknown", reason: "invalid requestId" });
1656
+ return;
1657
+ }
1658
+ const record = this.results.get(envelope.from, query.requestId, this.sessionId ?? "");
1659
+ respond2(record ? resultPayload(record) : { requestId: query.requestId, status: "unknown" });
1660
+ return;
1661
+ }
1662
+ const limit = typeof query.limit === "number" && Number.isFinite(query.limit) ? query.limit : 5;
1663
+ respond2({ results: this.results.recent(envelope.from, this.sessionId ?? "", limit).map(recentResultPayload) });
1664
+ } catch {
1665
+ respond2({ status: "unknown", reason: "invalid result query" });
1666
+ }
1667
+ return;
1668
+ }
1476
1669
  case "message": {
1477
1670
  if (envelope.sessionId !== (this.sessionId ?? "")) {
1478
1671
  reply("result", "rejected: target session changed");
@@ -1494,8 +1687,16 @@ var Runtime = class {
1494
1687
  }
1495
1688
  signal?.addEventListener("abort", disconnected, { once: true });
1496
1689
  }
1690
+ if (!this.allowPolicy.allows(envelope.from)) {
1691
+ this.delivery?.routeMessage({ ...envelope, id: deliveryId }, this.displayNameOf(envelope.from));
1692
+ this.finishReply(deliveryId, "denied: not on this peer's allow list (/ipc allow)");
1693
+ if (!envelope.waitMs) reply("result", "denied: not allowed");
1694
+ return;
1695
+ }
1696
+ this.results.accept(envelope.from, envelope.id, this.sessionId ?? "");
1497
1697
  const decision = this.delivery?.routeMessage({ ...envelope, id: deliveryId }, this.displayNameOf(envelope.from));
1498
1698
  if (decision === "denied") {
1699
+ this.results.remove(deliveryId);
1499
1700
  this.finishReply(deliveryId, "denied: not on this peer's allow list (/ipc allow)");
1500
1701
  if (!envelope.waitMs) reply("result", "denied: not allowed");
1501
1702
  return;
@@ -1542,6 +1743,7 @@ var Runtime = class {
1542
1743
  this.sessionName = this.ctx.getSessionName?.();
1543
1744
  this.delivery?.resetSessionState();
1544
1745
  this.polledInputs.clear();
1746
+ this.results.clear();
1545
1747
  this.projection.resetSessionState();
1546
1748
  this.executionFailure = void 0;
1547
1749
  for (const id of [...this.awaitingReply.keys()]) this.finishReply(id, "cancelled: target session changed");
@@ -1568,7 +1770,8 @@ var Runtime = class {
1568
1770
  }
1569
1771
  const body = message && !this.executionFailure ? assistantBodyText(message) : "";
1570
1772
  if (body) {
1571
- for (const waiter of this.awaitingReply.values()) if (waiter.consumed) waiter.body = body;
1773
+ for (const [id, waiter] of this.awaitingReply) if (waiter.consumed) waiter.body = body;
1774
+ this.results.captureBody(body);
1572
1775
  }
1573
1776
  }
1574
1777
  return;
@@ -1585,6 +1788,7 @@ var Runtime = class {
1585
1788
  markConsumed(id) {
1586
1789
  const waiter = this.awaitingReply.get(id);
1587
1790
  if (waiter && this.active) waiter.consumed = true;
1791
+ if (this.active) this.results.markRunning(id);
1588
1792
  }
1589
1793
  finishReply(id, text) {
1590
1794
  const waiter = this.awaitingReply.get(id);
@@ -1601,6 +1805,7 @@ var Runtime = class {
1601
1805
  for (const [id, waiter] of [...this.awaitingReply]) {
1602
1806
  if (waiter.consumed) this.finishReply(id, failed ? "(peer turn failed or was cancelled)" : waiter.body || "(empty reply)");
1603
1807
  }
1808
+ this.results.finishRunning(failed ? "(peer turn failed or was cancelled)" : "(empty reply)", failed);
1604
1809
  }
1605
1810
  // ---- mutations from commands ----
1606
1811
  mutations() {
@@ -1643,16 +1848,17 @@ var Runtime = class {
1643
1848
  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}`;
1644
1849
  if (!this.allowPolicy.allows(target.instanceId) || !(target.allowPeers?.includes("*") || target.allowPeers?.includes(this.instanceId))) return `${staticView}
1645
1850
  (content restricted by local allow policy)`;
1646
- if (target.lastBodyText) return `${staticView}
1647
- last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}`;
1648
- if (!target.port || !this.transport) return `${staticView}
1851
+ const snapshot = `${staticView}${target.lastBodyText ? `
1852
+ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}`;
1853
+ if (!target.port || !this.transport) return `${snapshot}
1649
1854
  (no live listener; file view only)`;
1650
1855
  const reply = await this.transport.send(target.instanceId, target.port, "state.get", { expectReply: true, waitMs: 3e3 });
1651
- if (!reply || reply.kind !== "state") return `${staticView}
1856
+ if (!reply || reply.kind !== "state") return `${snapshot}
1652
1857
  (live query failed or timed out)`;
1653
1858
  try {
1654
1859
  const parsed = JSON.parse(reply.text ?? "{}");
1655
- const lines = [staticView];
1860
+ const liveState = typeof parsed.state === "string" ? parsed.state : target.state;
1861
+ const lines = [`${peerLabel(target.instanceId, target.displayName)} [alive] ${liveState}`, `observed at: ${(/* @__PURE__ */ new Date()).toISOString()}`];
1656
1862
  if (parsed.currentTool) lines.push(`current tool: ${String(parsed.currentTool)}`);
1657
1863
  if (typeof parsed.blockedSince === "number") lines.push(`blocked for ${Math.max(0, Math.round((Date.now() - parsed.blockedSince) / 1e3))}s`);
1658
1864
  if (typeof parsed.undeliveredInjections === "number" && parsed.undeliveredInjections > 0) lines.push(`undelivered injections: ${parsed.undeliveredInjections}`);
@@ -1688,7 +1894,9 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}`;
1688
1894
  return { content: [{ type: "text", text: "IPC transport is unavailable (server startup failed or instance disposed)." }], isError: true };
1689
1895
  }
1690
1896
  const body = clipBody(text, this.config.maxBodyChars);
1897
+ const requestId = randomUUID2();
1691
1898
  const reply = await this.transport.send(target.instanceId, target.port, "message", {
1899
+ requestId,
1692
1900
  text: body,
1693
1901
  sessionId: target.sessionId ?? "",
1694
1902
  expectReply: wait,
@@ -1699,20 +1907,37 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}`;
1699
1907
  replyKinds: /* @__PURE__ */ new Set(["result"])
1700
1908
  });
1701
1909
  if (!wait) {
1702
- if (!reply) return { content: [{ type: "text", text: `Send failed: ${peerLabel(target.instanceId, target.displayName)} unreachable.` }], isError: true };
1703
- return { content: [{ type: "text", text: `Sent to ${peerLabel(target.instanceId, target.displayName)} (no wait; receipt/consumption not confirmed).` }] };
1910
+ if (!reply) return { content: [{ type: "text", text: `Send failed: ${peerLabel(target.instanceId, target.displayName)} unreachable. requestId=${requestId}` }], isError: true, details: { requestId } };
1911
+ return { content: [{ type: "text", text: `Sent to ${peerLabel(target.instanceId, target.displayName)} (no wait; receipt/consumption not confirmed). requestId=${requestId}` }], details: { requestId } };
1704
1912
  }
1705
1913
  if (!reply) {
1706
- if (context.signal?.aborted) return { content: [{ type: "text", text: "Wait cancelled; already accepted peer input is not cancelled." }] };
1914
+ if (context.signal?.aborted) return { content: [{ type: "text", text: `Wait cancelled; already accepted peer input is not cancelled. requestId=${requestId}` }], isError: true, details: { requestId } };
1707
1915
  const snapshot = await this.statusOf(peerRef);
1708
1916
  return {
1709
- content: [{ type: "text", text: `No reply from ${peerLabel(target.instanceId, target.displayName)} within ${waitMs}ms (or aborted).
1917
+ content: [{ type: "text", text: `No reply from ${peerLabel(target.instanceId, target.displayName)} within ${waitMs}ms (or aborted). requestId=${requestId}
1918
+ Use ipc_result with this requestId before resending; accepted work is not cancelled.
1710
1919
  Peer status:
1711
1920
  ${snapshot}` }],
1712
- isError: false
1921
+ isError: true,
1922
+ details: { requestId }
1713
1923
  };
1714
1924
  }
1715
- return { content: [{ type: "text", text: reply.text ?? "(empty reply)" }] };
1925
+ return { content: [{ type: "text", text: reply.text ?? "(empty reply)" }], details: { requestId } };
1926
+ }
1927
+ async resultOf(peerRef, requestId, limit, context) {
1928
+ const target = this.resolvePeer(peerRef);
1929
+ if (!target) return { content: [{ type: "text", text: `Peer not found: ${peerRef}. Call ipc_list_peers first.` }], isError: true };
1930
+ if (!target.port || !this.transport) return { content: [{ type: "text", text: `${peerLabel(target.instanceId, target.displayName)} has no live listener for result queries.` }], isError: true };
1931
+ const reply = await this.transport.send(target.instanceId, target.port, "result.get", {
1932
+ text: JSON.stringify({ ...requestId ? { requestId } : {}, limit: Math.max(1, Math.min(20, Math.floor(limit))) }),
1933
+ sessionId: target.sessionId ?? "",
1934
+ expectReply: true,
1935
+ waitMs: 3e3,
1936
+ signal: context.signal,
1937
+ replyKinds: /* @__PURE__ */ new Set(["result"])
1938
+ });
1939
+ if (!reply?.text) return { content: [{ type: "text", text: `Result query failed or timed out for ${peerLabel(target.instanceId, target.displayName)}.` }], isError: true };
1940
+ return { content: [{ type: "text", text: reply.text }] };
1716
1941
  }
1717
1942
  drainInbox(limit, modelTool = true) {
1718
1943
  const messages = this.delivery?.drainInbox(limit) ?? [];
@@ -1740,6 +1965,7 @@ ${message.text}`).join("\n---\n");
1740
1965
  for (const id of [...this.awaitingReply.keys()]) this.finishReply(id, "cancelled: peer disposed");
1741
1966
  this.delivery?.resetSessionState();
1742
1967
  this.polledInputs.clear();
1968
+ this.results.clear();
1743
1969
  try {
1744
1970
  this.ctx.ui.setStatus?.("pie-ipc-peers", void 0);
1745
1971
  } catch {
@@ -1851,7 +2077,7 @@ function pieIpcExtension(ctx) {
1851
2077
  ctx.registerTool({
1852
2078
  name: "ipc_send",
1853
2079
  label: "Send a message to a Pie peer",
1854
- description: `Send text to another Pie process (interactive peer) addressed by display name or instance id prefix. wait=false (default): fire-and-forget \u2014 the peer receives it as user input. wait=true: hold until the peer's reply arrives (bounded by waitMs, default ${DEFAULT_SEND_WAIT_MS}ms); on timeout the peer's last known status is attached. Inbound messages from peers arrive as user input or in ipc_poll.`,
2080
+ 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.`,
1855
2081
  parameters: Type.Object({
1856
2082
  to: Type.String({ description: "Peer display name or instance id (see ipc_list_peers)" }),
1857
2083
  text: Type.String({ description: "Message body for the peer" }),
@@ -1867,6 +2093,24 @@ function pieIpcExtension(ctx) {
1867
2093
  },
1868
2094
  execute: async (args, context) => runtime.sendToPeer(args.to, args.text, args.wait ?? false, Math.min(args.waitMs ?? DEFAULT_SEND_WAIT_MS, 6e5), context)
1869
2095
  });
2096
+ ctx.registerTool({
2097
+ name: "ipc_result",
2098
+ label: "Query a Pie request result",
2099
+ 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.",
2100
+ parameters: Type.Object({
2101
+ to: Type.String({ description: "Peer display name or instance id prefix" }),
2102
+ requestId: Type.Optional(Type.String({ description: "Request id returned by ipc_send" })),
2103
+ limit: Type.Optional(Type.Number({ description: "Recent result count when requestId is omitted (default 5, max 20)", minimum: 1, maximum: 20 }))
2104
+ }),
2105
+ risk: { ...risk, riskClass: "network", requiresPermission: false, externalSideEffect: false, writesNetwork: false },
2106
+ renderHint: {
2107
+ summary: (args) => {
2108
+ const record = args ?? {};
2109
+ return `result ${record.to ?? "?"}${record.requestId ? ` ${record.requestId}` : " (recent)"}`;
2110
+ }
2111
+ },
2112
+ execute: async (args, context) => runtime.resultOf(args.to, args.requestId, args.limit ?? 5, context)
2113
+ });
1870
2114
  ctx.registerTool({
1871
2115
  name: "ipc_status",
1872
2116
  label: "Query a peer's live status",
@@ -1901,7 +2145,7 @@ function pieIpcExtension(ctx) {
1901
2145
  });
1902
2146
  ctx.registerCommand({
1903
2147
  path: ["ipc"],
1904
- description: "Pie IPC peers: /ipc peers|send|poll|status|name|mute|allow",
2148
+ description: "Pie IPC peers: /ipc peers|send|result|poll|status|name|mute|allow",
1905
2149
  handler: async (_extensionCtx, args) => {
1906
2150
  const [sub, ...rest] = (args ?? "").trim().split(/\s+/);
1907
2151
  const mutations = runtime.mutations();
@@ -1916,6 +2160,14 @@ function pieIpcExtension(ctx) {
1916
2160
  if (!peerRef || words.length === 0) return "Usage: /ipc send <peer> <text>";
1917
2161
  return runtime.drainReplyAfterSend(peerRef, words.join(" "));
1918
2162
  }
2163
+ case "result": {
2164
+ const [peerRef, requestId] = rest;
2165
+ if (!peerRef) return "Usage: /ipc result <peer> [requestId]";
2166
+ const result = await runtime.resultOf(peerRef, requestId, 5, { toolCallId: "ipc-command", cwd: _extensionCtx.cwd, log: () => {
2167
+ }, reportProgress: () => {
2168
+ } });
2169
+ return result.content[0]?.text ?? "(no result)";
2170
+ }
1919
2171
  case "poll":
1920
2172
  return runtime.drainInbox(20, false);
1921
2173
  case "status": {
@@ -1940,7 +2192,7 @@ Usage: /ipc name <new-name>`;
1940
2192
  return `Allowed peer: ${id}`;
1941
2193
  }
1942
2194
  default:
1943
- return "Usage: /ipc peers|send <peer> <text>|poll|status <peer>|name <name>|mute [off]|allow <id>";
2195
+ return "Usage: /ipc peers|send <peer> <text>|result <peer> [requestId]|poll|status <peer>|name <name>|mute [off]|allow <id>";
1944
2196
  }
1945
2197
  };
1946
2198
  const output = await run();
@@ -6,9 +6,9 @@ import {
6
6
  extractPlanTodoItems,
7
7
  markCompletedPlanSteps,
8
8
  restoreExecutionState
9
- } from "../../../chunks/chunk-C5UTDL3S.js";
10
- import "../../../chunks/chunk-TDHVB2FH.js";
11
- import "../../../chunks/chunk-NM2JLPJ6.js";
9
+ } from "../../../chunks/chunk-UDCGB3LZ.js";
10
+ import "../../../chunks/chunk-2H2DD22Z.js";
11
+ import "../../../chunks/chunk-X7UO6BA6.js";
12
12
  import {
13
13
  Type
14
14
  } from "../../../chunks/chunk-XXGYUYXI.js";
@@ -6,15 +6,15 @@ import {
6
6
  formatTransportLifecycle,
7
7
  getConfigDir,
8
8
  logTransportLifecycle
9
- } from "../../../chunks/chunk-CLEPSTWH.js";
9
+ } from "../../../chunks/chunk-TGCI5M6R.js";
10
10
  import {
11
11
  SUBAGENT_SESSION_RECORD_VERSION,
12
12
  createPolicyEnforcedTools,
13
13
  createSharedFileSystemTools,
14
14
  createSubagentCapability
15
- } from "../../../chunks/chunk-C5UTDL3S.js";
16
- import "../../../chunks/chunk-TDHVB2FH.js";
17
- import "../../../chunks/chunk-NM2JLPJ6.js";
15
+ } from "../../../chunks/chunk-UDCGB3LZ.js";
16
+ import "../../../chunks/chunk-2H2DD22Z.js";
17
+ import "../../../chunks/chunk-X7UO6BA6.js";
18
18
  import "../../../chunks/chunk-XXGYUYXI.js";
19
19
  import "../../../chunks/chunk-LZQXQOPJ.js";
20
20
 
@@ -8,9 +8,9 @@ import {
8
8
  executeManageTodoList,
9
9
  executionStateToTodos,
10
10
  restoreExecutionState
11
- } from "../../../chunks/chunk-C5UTDL3S.js";
12
- import "../../../chunks/chunk-TDHVB2FH.js";
13
- import "../../../chunks/chunk-NM2JLPJ6.js";
11
+ } from "../../../chunks/chunk-UDCGB3LZ.js";
12
+ import "../../../chunks/chunk-2H2DD22Z.js";
13
+ import "../../../chunks/chunk-X7UO6BA6.js";
14
14
  import "../../../chunks/chunk-XXGYUYXI.js";
15
15
  import "../../../chunks/chunk-LZQXQOPJ.js";
16
16
 
@@ -4,7 +4,7 @@ import {
4
4
  disposeModelTransports,
5
5
  streamSimple,
6
6
  validateToolArguments
7
- } from "./chunk-NM2JLPJ6.js";
7
+ } from "./chunk-X7UO6BA6.js";
8
8
 
9
9
  // ../../packages/agent-core/src/failure.ts
10
10
  function getAgentFailureMetadata(error) {
@@ -850,6 +850,7 @@ var Agent = class {
850
850
  convertToLlm: this.convertToLlm,
851
851
  transformContext: this.transformContext,
852
852
  beforeToolContinuation: beforeToolContinuation ? async () => {
853
+ if (!ownsRun() || runController.signal.aborted) throw new Error("Request was aborted");
853
854
  await new Promise((resolve) => {
854
855
  acknowledgeToolTurn = resolve;
855
856
  });
@@ -7,12 +7,12 @@ import {
7
7
  defaultShellKindForPlatform,
8
8
  interpretShellExit,
9
9
  requestInteraction
10
- } from "./chunk-C5UTDL3S.js";
10
+ } from "./chunk-UDCGB3LZ.js";
11
11
  import {
12
12
  EMPTY_ASSISTANT_CONTENT_ERROR,
13
13
  OPENAI_COMPAT_PROTOCOL_ERROR_CODE,
14
14
  getLogger
15
- } from "./chunk-NM2JLPJ6.js";
15
+ } from "./chunk-X7UO6BA6.js";
16
16
  import {
17
17
  Type
18
18
  } from "./chunk-XXGYUYXI.js";
@@ -4,7 +4,7 @@ import {
4
4
  createAgentOperationError,
5
5
  getAgentFailureMetadata,
6
6
  getToolCallerIdentity
7
- } from "./chunk-TDHVB2FH.js";
7
+ } from "./chunk-2H2DD22Z.js";
8
8
  import {
9
9
  AssistantMessageEventStream,
10
10
  FileSystemGateway,
@@ -14,7 +14,7 @@ import {
14
14
  getPlatformConfig,
15
15
  hashText,
16
16
  streamSimple
17
- } from "./chunk-NM2JLPJ6.js";
17
+ } from "./chunk-X7UO6BA6.js";
18
18
  import {
19
19
  Type
20
20
  } from "./chunk-XXGYUYXI.js";
@@ -8199,6 +8199,13 @@ var SessionTraceSnapshotWriter = class {
8199
8199
  if (this.cachedSessionId === sessionId && this.cachedController) {
8200
8200
  return this.cachedController;
8201
8201
  }
8202
+ const pending = this.pendingFlushes.get(sessionId);
8203
+ if (pending) {
8204
+ this.flush();
8205
+ this.cachedSessionId = sessionId;
8206
+ this.cachedController = pending;
8207
+ return pending;
8208
+ }
8202
8209
  this.flush();
8203
8210
  let controller;
8204
8211
  try {
@@ -1528,7 +1528,7 @@ function getSystemIO() {
1528
1528
  return CS.System.IO;
1529
1529
  }
1530
1530
  function looksLikeBase64(value) {
1531
- return value.length > 0 && value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value);
1531
+ return value.length === 0 || value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value);
1532
1532
  }
1533
1533
  function getPieFileBridge() {
1534
1534
  if (typeof CS === "undefined" || !CS?.Pie?.PieFileBridge) {
@@ -8,8 +8,8 @@ import {
8
8
  createToolCallerIdentity,
9
9
  getAgentFailureMetadata,
10
10
  getToolCallerIdentity
11
- } from "./chunk-TDHVB2FH.js";
12
- import "./chunk-NM2JLPJ6.js";
11
+ } from "./chunk-2H2DD22Z.js";
12
+ import "./chunk-X7UO6BA6.js";
13
13
  import "./chunk-XXGYUYXI.js";
14
14
  import "./chunk-LZQXQOPJ.js";
15
15
  export {
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  EventStream
4
- } from "./chunk-NM2JLPJ6.js";
4
+ } from "./chunk-X7UO6BA6.js";
5
5
  import "./chunk-XXGYUYXI.js";
6
6
  import "./chunk-LZQXQOPJ.js";
7
7