@cydm/pie 4.6.1 → 4.8.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.
@@ -1,7 +1,4 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
- import {
3
- Type
4
- } from "../../../chunks/chunk-XXGYUYXI.js";
5
2
  import {
6
3
  DEFAULT_SEND_WAIT_MS,
7
4
  DISPATCH_PREFIX,
@@ -23,12 +20,16 @@ import {
23
20
  parseStatusFile,
24
21
  peerHealth,
25
22
  peerLabel,
23
+ registerIpcRuntime,
26
24
  resolveIpcConfig,
27
25
  takeDispatchFrame,
28
26
  wrapInboundText,
29
27
  wrappedMessageMarker
30
- } from "../../../chunks/chunk-2CJIENLY.js";
28
+ } from "../../../chunks/chunk-EGZ5TZRM.js";
31
29
  import "../../../chunks/chunk-ZPJ3BNQB.js";
30
+ import {
31
+ Type
32
+ } from "../../../chunks/chunk-XXGYUYXI.js";
32
33
  import "../../../chunks/chunk-LZQXQOPJ.js";
33
34
 
34
35
  // builtin/extensions/pie-ipc/index.ts
@@ -912,6 +913,15 @@ var Runtime = class {
912
913
  results = new RequestResultStore();
913
914
  executionFailure;
914
915
  active = false;
916
+ /** Bounded, memory-only display projection for worker Peek. It deliberately
917
+ * stores only assistant text blocks and tool names/status — never thinking,
918
+ * args, results, user input, or session-log data. */
919
+ peekTurn = 0;
920
+ peekStartedAt;
921
+ peekItems = [];
922
+ peekAssistantIndex;
923
+ peekLastVisible;
924
+ peekPendingVisible;
915
925
  polledInputs = /* @__PURE__ */ new Map();
916
926
  /** Server readiness gate: no status writes before the listener is up. */
917
927
  serverReady = false;
@@ -967,6 +977,8 @@ var Runtime = class {
967
977
  ...displaySessionName ? { displaySessionName } : {},
968
978
  ...typeof model === "string" && model ? { model } : {},
969
979
  isManager: this.ctx.capabilities?.unattended === true && process.env.PIE_PROC_CURATED_NAME === "manager",
980
+ sessionControls: this.ctx.capabilities?.interactiveUI === false && this.ctx.capabilities.editorInjection === true,
981
+ workerPeek: this.ctx.capabilities?.unattended === true && process.env.PIE_PROC_CURATED_NAME !== "manager",
970
982
  imBinding: currentImBinding()
971
983
  });
972
984
  return { ...snapshot, allowPeers: [...this.allowPolicy.snapshot()], undeliveredInjections: this.delivery?.undeliveredInjections ?? snapshot.undeliveredInjections ?? 0 };
@@ -976,18 +988,17 @@ var Runtime = class {
976
988
  return writeStatusFile(this.discoveryDir, { ...this.currentStatus(), updatedAt: Date.now() }, (message) => this.ctx.log(message));
977
989
  }
978
990
  async handleEnvelope(envelope, respond, signal) {
979
- const reply = (kind, text) => {
980
- respond({
981
- v: IPC_PROTOCOL_VERSION,
982
- id: `${envelope.id}:r`,
983
- from: this.instanceId,
984
- to: envelope.from,
985
- kind,
986
- createdAt: Date.now(),
987
- replyTo: envelope.id,
988
- ...text !== void 0 ? { text } : {}
989
- });
990
- };
991
+ const replyEnvelope = (kind, text) => ({
992
+ v: IPC_PROTOCOL_VERSION,
993
+ id: `${envelope.id}:r`,
994
+ from: this.instanceId,
995
+ to: envelope.from,
996
+ kind,
997
+ createdAt: Date.now(),
998
+ replyTo: envelope.id,
999
+ ...text !== void 0 ? { text } : {}
1000
+ });
1001
+ const reply = (kind, text) => respond(replyEnvelope(kind, text));
991
1002
  switch (envelope.kind) {
992
1003
  case "control": {
993
1004
  if (this.sessionId === null) {
@@ -1008,6 +1019,16 @@ var Runtime = class {
1008
1019
  reply("ack", JSON.stringify({ ok: false, message: "invalid control frame" }));
1009
1020
  return;
1010
1021
  }
1022
+ if (parsed.control === "session.peek") {
1023
+ if (!(this.ctx.capabilities?.unattended === true && process.env.PIE_PROC_CURATED_NAME !== "manager")) {
1024
+ reply("ack", JSON.stringify({ ok: false, message: "host does not advertise worker Peek" }));
1025
+ return;
1026
+ }
1027
+ const base = replyEnvelope("ack");
1028
+ const text = this.boundedPeekAckText((candidate) => Buffer.byteLength(JSON.stringify({ ...base, text: candidate, auth: "0".repeat(64) }) + "\n"));
1029
+ respond({ ...base, text });
1030
+ return;
1031
+ }
1011
1032
  const applier = this.ctx.applyIpcControl;
1012
1033
  if (!applier) {
1013
1034
  reply("ack", JSON.stringify({ ok: false, message: "host does not support control frames" }));
@@ -1137,16 +1158,119 @@ var Runtime = class {
1137
1158
  return readStatusFile(this.discoveryDir, peerInstanceId)?.displayName;
1138
1159
  }
1139
1160
  // ---- lifecycle events ----
1161
+ trimPeek() {
1162
+ while (this.peekItems.length > 40 || this.peekItems.reduce((n, item) => n + item.text.length + (item.progress?.length ?? 0), 0) > 8e3) {
1163
+ if (this.peekItems.length === 1) {
1164
+ const item = this.peekItems[0];
1165
+ item.text = item.text.slice(-4e3);
1166
+ if (item.progress) item.progress = item.progress.slice(-500);
1167
+ break;
1168
+ }
1169
+ this.peekItems.shift();
1170
+ if (this.peekAssistantIndex !== void 0) this.peekAssistantIndex = this.peekAssistantIndex === 0 ? void 0 : this.peekAssistantIndex - 1;
1171
+ }
1172
+ }
1173
+ addPeekAssistant(text, delta = false) {
1174
+ const clean = text.replace(/\u0000/g, "");
1175
+ if (!clean || !delta && !clean.trim()) return;
1176
+ if (delta && this.peekAssistantIndex !== void 0 && this.peekItems[this.peekAssistantIndex]?.kind === "assistant") {
1177
+ const item = this.peekItems[this.peekAssistantIndex];
1178
+ item.text = (item.text + clean).slice(-4e3);
1179
+ item.at = Date.now();
1180
+ } else {
1181
+ const display = delta ? clean : clean.trim();
1182
+ this.peekItems.push({ at: Date.now(), kind: "assistant", text: display.slice(-4e3) });
1183
+ this.peekAssistantIndex = this.peekItems.length - 1;
1184
+ }
1185
+ const visible = { at: Date.now(), text: this.peekItems[this.peekAssistantIndex].text };
1186
+ if (this.active) this.peekPendingVisible = visible;
1187
+ else this.peekLastVisible = visible;
1188
+ this.trimPeek();
1189
+ }
1190
+ safeProgress(partial) {
1191
+ if (!partial || typeof partial !== "object") return void 0;
1192
+ const p = partial;
1193
+ if (!p.details || typeof p.details !== "object" || !("increment" in p.details) || !Array.isArray(p.content)) return void 0;
1194
+ const text = p.content.map((block) => block && typeof block === "object" && block.type === "text" && typeof block.text === "string" ? block.text : "").filter(Boolean).at(-1)?.replace(/\u0000/g, "").trim();
1195
+ return text ? text.slice(0, 500) : void 0;
1196
+ }
1197
+ peekSnapshot() {
1198
+ const now = Date.now();
1199
+ const items = this.peekItems.map(({ toolCallId: _id, startedAt, done, progress, ...item }) => item.kind === "tool" && startedAt !== void 0 ? { ...item, text: `${done ? "Finished" : "Running"} ${item.text} \xB7 ${Math.max(0, Math.floor(((done ? item.at : now) - startedAt) / 1e3))}s${progress ? ` \xB7 ${progress}` : ""}` } : item);
1200
+ return {
1201
+ active: this.active,
1202
+ turn: this.peekTurn,
1203
+ ...this.peekStartedAt ? { startedAt: this.peekStartedAt } : {},
1204
+ generatedAt: now,
1205
+ items,
1206
+ ...this.peekLastVisible ? { lastVisible: { ...this.peekLastVisible } } : {}
1207
+ };
1208
+ }
1209
+ boundedPeekAckText(frameBytes) {
1210
+ const snapshot = this.peekSnapshot();
1211
+ const encode = () => JSON.stringify({ ok: true, message: JSON.stringify(snapshot) });
1212
+ const newest = snapshot.items.at(-1);
1213
+ if (!snapshot.active && newest?.kind === "assistant" && snapshot.lastVisible?.text === newest.text) delete snapshot.lastVisible;
1214
+ let text = encode();
1215
+ while (frameBytes(text) > 8e3) {
1216
+ if (snapshot.items.length > 1) {
1217
+ snapshot.items.shift();
1218
+ } else {
1219
+ const item = snapshot.items[0];
1220
+ const visible = snapshot.lastVisible;
1221
+ if (visible && visible.text.length > 128 && (snapshot.active || !item || visible.text.length >= item.text.length)) {
1222
+ visible.text = visible.text.slice(-Math.max(128, visible.text.length - 256));
1223
+ } else if (item?.text.length) {
1224
+ if (item.text.length <= 128) snapshot.items.shift();
1225
+ else item.text = item.text.slice(-Math.max(128, item.text.length - 256));
1226
+ } else if (visible) {
1227
+ delete snapshot.lastVisible;
1228
+ } else break;
1229
+ }
1230
+ text = encode();
1231
+ }
1232
+ return text;
1233
+ }
1140
1234
  onEvent(event) {
1141
1235
  switch (event.type) {
1142
1236
  case "turn:start": {
1237
+ this.peekTurn++;
1238
+ this.peekStartedAt = Date.now();
1239
+ this.peekItems = [];
1240
+ this.peekAssistantIndex = void 0;
1241
+ this.peekPendingVisible = void 0;
1143
1242
  this.executionFailure = void 0;
1144
1243
  this.active = true;
1145
1244
  if (this.projection.updateFromEvent(event)) this.writeStatus();
1146
1245
  return;
1147
1246
  }
1148
- case "tool:execution:start":
1247
+ case "assistant:display-delta": {
1248
+ if (typeof event.delta === "string") this.addPeekAssistant(event.delta, true);
1249
+ return;
1250
+ }
1251
+ case "tool:execution:start": {
1252
+ this.peekAssistantIndex = void 0;
1253
+ if (event.toolName && event.toolCallId) this.peekItems.push({ at: Date.now(), kind: "tool", text: event.toolName.slice(0, 120), toolCallId: event.toolCallId, startedAt: Date.now() });
1254
+ this.trimPeek();
1255
+ if (this.projection.updateFromEvent(event)) this.writeStatus();
1256
+ return;
1257
+ }
1258
+ case "tool:execution:update": {
1259
+ const item = event.toolCallId ? this.peekItems.find((i) => i.toolCallId === event.toolCallId) : void 0;
1260
+ const progress = this.safeProgress(event.partialResult);
1261
+ if (item && !item.done && progress) {
1262
+ item.progress = progress;
1263
+ item.at = Date.now();
1264
+ this.trimPeek();
1265
+ }
1266
+ return;
1267
+ }
1149
1268
  case "tool:execution:end": {
1269
+ const item = event.toolCallId ? this.peekItems.find((i) => i.toolCallId === event.toolCallId) : void 0;
1270
+ if (item && !item.done) {
1271
+ item.done = true;
1272
+ item.at = Date.now();
1273
+ }
1150
1274
  if (this.projection.updateFromEvent(event)) this.writeStatus();
1151
1275
  return;
1152
1276
  }
@@ -1156,6 +1280,8 @@ var Runtime = class {
1156
1280
  case "agent:end":
1157
1281
  case "turn:failed":
1158
1282
  case "turn:cancelled": {
1283
+ if (event.type === "agent:end" && !this.executionFailure && this.peekPendingVisible) this.peekLastVisible = this.peekPendingVisible;
1284
+ this.peekPendingVisible = void 0;
1159
1285
  if (this.projection.updateFromEvent(event)) this.writeStatus();
1160
1286
  this.answerAwaitingPeers(event.type !== "agent:end" || Boolean(this.executionFailure));
1161
1287
  this.active = false;
@@ -1171,6 +1297,11 @@ var Runtime = class {
1171
1297
  this.clearNotifyFallbacks();
1172
1298
  this.notifyGeneration++;
1173
1299
  this.projection.resetSessionState();
1300
+ this.peekTurn = 0;
1301
+ this.peekStartedAt = void 0;
1302
+ this.peekItems = [];
1303
+ this.peekLastVisible = void 0;
1304
+ this.peekPendingVisible = void 0;
1174
1305
  this.executionFailure = void 0;
1175
1306
  this.active = false;
1176
1307
  this.writeStatus();
@@ -1189,6 +1320,13 @@ var Runtime = class {
1189
1320
  }
1190
1321
  }
1191
1322
  } else {
1323
+ if (message?.role === "assistant" && Array.isArray(message.content)) {
1324
+ const visible = message.content.map((block) => block && typeof block === "object" && block.type === "text" && typeof block.text === "string" ? String(block.text) : "").join("");
1325
+ if (visible) {
1326
+ const streamed = this.peekAssistantIndex !== void 0 ? this.peekItems[this.peekAssistantIndex]?.text : void 0;
1327
+ if (streamed !== visible) this.addPeekAssistant(visible);
1328
+ }
1329
+ }
1192
1330
  if (message?.role === "assistant") {
1193
1331
  const outcome = message;
1194
1332
  if (outcome.stopReason === "error" || outcome.stopReason === "aborted") this.executionFailure = outcome.stopReason;
@@ -1562,6 +1700,34 @@ ${outcome.text}`
1562
1700
  return ` ${label} [${file.state}]${sid}`;
1563
1701
  }).join("\n");
1564
1702
  }
1703
+ /** Panel controls must originate from this process's real advertised IPC
1704
+ * identity. Besides the authenticated target gate, enforce both advertised
1705
+ * directions before exposing transcript-like data. */
1706
+ async sendBoundControl(peerRef, control, payload, expected, waitMs = 6e3) {
1707
+ const target = expected ? readStatusFile(this.discoveryDir, expected.instanceId) : this.resolvePeer(peerRef);
1708
+ if (!target || !target.port) return { ok: false, detail: `Session not found: ${peerRef}` };
1709
+ if (expected && (target.instanceId !== expected.instanceId || target.sessionId !== expected.sessionId))
1710
+ return { ok: false, detail: "Worker instance or session no longer matches the issued card. Reopen it from /panel." };
1711
+ if (!this.allowPolicy.allows(target.instanceId)) return { ok: false, detail: "Denied by manager sender allow policy." };
1712
+ if (!(target.allowPeers?.includes("*") || target.allowPeers?.includes(this.instanceId)))
1713
+ return { ok: false, detail: "Denied by worker recipient allow policy." };
1714
+ if (!this.transport) return { ok: false, unknown: true, detail: "Manager IPC transport is unavailable." };
1715
+ try {
1716
+ const reply = await this.transport.send(target.instanceId, target.port, "control", {
1717
+ sessionId: target.sessionId ?? "",
1718
+ text: JSON.stringify({ control, payload }),
1719
+ awaitAck: true,
1720
+ waitMs,
1721
+ replyKinds: /* @__PURE__ */ new Set(["ack"])
1722
+ });
1723
+ if (reply?.text) {
1724
+ const ack = JSON.parse(reply.text);
1725
+ if (typeof ack?.ok === "boolean") return { ok: ack.ok, detail: `Peer receipt: ${reply.text}` };
1726
+ }
1727
+ } catch {
1728
+ }
1729
+ return { ok: false, unknown: true, detail: "No verified receipt. The request may already have been applied." };
1730
+ }
1565
1731
  /** MULTI-AGENT IM v2 Phase 2.3 — send an enumerated CONTROL frame to a
1566
1732
  * peer (first control: model.set). Returns the peer's receipt (the ack
1567
1733
  * envelope text, a small JSON object). The frame bypasses the target's
@@ -1585,7 +1751,7 @@ ${outcome.text}`
1585
1751
  waitMs,
1586
1752
  replyKinds: /* @__PURE__ */ new Set(["ack"])
1587
1753
  });
1588
- if (!reply) return { content: [{ type: "text", text: `No receipt from ${peerLabel(target.instanceId, target.displayName)} within ${waitMs}ms \u2014 the control may or may not have landed; re-send is safe (controls are idempotent by contract).` }], isError: true };
1754
+ if (!reply) return { content: [{ type: "text", text: `No receipt from ${peerLabel(target.instanceId, target.displayName)} within ${waitMs}ms \u2014 the control may or may not have landed. ${control === "session.compact" ? "Check session.context before submitting again." : "Check the target state before retrying."}` }], isError: true };
1589
1755
  return { content: [{ type: "text", text: reply.text ?? "(empty receipt)" }] };
1590
1756
  }
1591
1757
  async sendToPeer(peerRef, text, _wait, _waitMs, context, notify = false, fallbackMs = DEFAULT_NOTIFY_FALLBACK_MS) {
@@ -1814,6 +1980,7 @@ function pieIpcExtension(ctx) {
1814
1980
  }
1815
1981
  }
1816
1982
  const runtime = new Runtime(ctx, config, discoveryDir);
1983
+ const unregisterRuntime = registerIpcRuntime(discoveryDir, runtime);
1817
1984
  const serverEligible = ctx.capabilities.eventSink && ctx.capabilities.longLived;
1818
1985
  ctx.log(`pie-ipc: enabled as ${runtime.instanceId} (${serverEligible ? "server+client (starting listener)" : "client-only"})`);
1819
1986
  if (serverEligible) {
@@ -1856,7 +2023,9 @@ function pieIpcExtension(ctx) {
1856
2023
  "turn:completed",
1857
2024
  "turn:failed",
1858
2025
  "turn:cancelled",
2026
+ "assistant:display-delta",
1859
2027
  "tool:execution:start",
2028
+ "tool:execution:update",
1860
2029
  "tool:execution:end",
1861
2030
  "session:changed",
1862
2031
  "message:end"
@@ -1923,11 +2092,11 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1923
2092
  ctx.registerTool({
1924
2093
  name: "ipc_control_notify",
1925
2094
  label: "Send a control frame to a Pie peer",
1926
- 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.",
2095
+ 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. Controls: 'model.set' with payload {model: 'provider/modelId'} switches the peer's model; 'thinking.set' with payload {level: '...'} switches the peer's thinking level; 'session.context' (payload {}) reads the peer's context estimate (headless hosts only \u2014 the receipt message is JSON with estimatedTokens/contextWindow/percent/autoCompact figures); 'session.compact' (payload {}) requests a MANUAL compaction on the peer (headless hosts only; accepted confirms submission, not that compaction started or completed \u2014 read compactionRunning and lastCompactOutcome via session.context). Receipt (success or structured refusal) returns as this tool's result. If the session.compact receipt is uncertain, do not replay it: check session.context before submitting again.",
1927
2096
  parameters: Type.Object({
1928
2097
  to: Type.String({ description: "Peer display name or instance id (see ipc_list_peers)" }),
1929
- control: Type.Union([Type.Literal("model.set"), Type.Literal("thinking.set")], { description: "Control to apply (enumerated whitelist)" }),
1930
- payload: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Control payload. model.set requires {model: 'provider/modelId'}; thinking.set requires {level: 'off|minimal|low|medium|high|xhigh'}" })),
2098
+ control: Type.Union([Type.Literal("model.set"), Type.Literal("thinking.set"), Type.Literal("session.context"), Type.Literal("session.compact")], { description: "Control to apply (enumerated whitelist)" }),
2099
+ payload: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Control payload. model.set requires {model: 'provider/modelId'}; thinking.set requires {level: 'off|minimal|low|medium|high|xhigh'}; session.context/session.compact take an empty payload" })),
1931
2100
  waitMs: Type.Optional(Type.Number({ description: "Receipt wait budget in ms (default 120000, max 600000)", minimum: 100, maximum: 6e5 }))
1932
2101
  }),
1933
2102
  risk: { ...risk, riskClass: "session_mutation", concurrencySafe: false },
@@ -1956,9 +2125,9 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1956
2125
  ctx.registerTool({
1957
2126
  name: "self_control",
1958
2127
  label: "Send a control frame to this session's host",
1959
- description: "Send an enumerated CONTROL frame to THIS session's own host (the process running you). The host applies it directly \u2014 it never enters the turn pipeline or session history. Controls: 'model.set' with payload {model: 'provider/modelId'} switches YOUR model (same validation as the user's /model); 'thinking.set' with payload {level: 'off|minimal|low|medium|high|xhigh'} switches YOUR thinking level (same path as the user's /think; a sensible self-tuning knob \u2014 low for cheap lookups, high for hard reasoning). Both apply from the host's NEXT agent execution \u2014 the current execution (including tool-continuation rounds) finishes on the settings it started with. Receipt (success or structured refusal) returns as this tool's result. Controls are idempotent: re-sending after an uncertain outcome is safe.",
2128
+ description: "Send an enumerated CONTROL frame to THIS session's own host (the process running you). The host applies it directly \u2014 it never enters the turn pipeline or session history. Controls: 'model.set' with payload {model: 'provider/modelId'} switches YOUR model (same validation as the user's /model); 'thinking.set' with payload {level: 'off|minimal|low|medium|high|xhigh'} switches YOUR thinking level (same path as the user's /think; a sensible self-tuning knob \u2014 low for cheap lookups, high for hard reasoning). Both apply from the host's NEXT agent execution \u2014 the current execution (including tool-continuation rounds) finishes on the settings it started with. 'session.context' (payload {}) reads YOUR host's context estimate (headless hosts; receipt message is JSON); 'session.compact' (payload {}) requests a MANUAL compaction of THIS session \u2014 **refused while a turn is streaming (you are always mid-turn when you call this, so expect a refusal; the IM panel is the intended entry)**. Receipt (success or structured refusal) returns as this tool's result. If the session.compact receipt is uncertain, do not replay it: check session.context before submitting again.",
1960
2129
  parameters: Type.Object({
1961
- control: Type.Union([Type.Literal("model.set"), Type.Literal("thinking.set")], { description: "Control to apply (enumerated host whitelist)" }),
2130
+ control: Type.Union([Type.Literal("model.set"), Type.Literal("thinking.set"), Type.Literal("session.context"), Type.Literal("session.compact")], { description: "Control to apply (enumerated host whitelist)" }),
1962
2131
  payload: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Control payload. model.set requires {model: 'provider/modelId'}; thinking.set requires {level: 'off|minimal|low|medium|high|xhigh'}" })),
1963
2132
  waitMs: Type.Optional(Type.Number({ description: "Receipt wait budget in ms (default 120000, max 600000)", minimum: 100, maximum: 6e5 }))
1964
2133
  }),
@@ -2110,6 +2279,7 @@ Usage: /tools/ipc name <new-name>`;
2110
2279
  }
2111
2280
  });
2112
2281
  ctx.registerCleanup?.(() => {
2282
+ unregisterRuntime();
2113
2283
  runtime.dispose();
2114
2284
  });
2115
2285
  }