@cydm/pie 4.7.0 → 4.9.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 (49) hide show
  1. package/README.md +51 -27
  2. package/dist/builtin/extensions/ask-user/index.js +4 -4
  3. package/dist/builtin/extensions/cron/index.js +916 -162
  4. package/dist/builtin/extensions/im-forward/README.md +24 -7
  5. package/dist/builtin/extensions/im-forward/index.js +6823 -3683
  6. package/dist/builtin/extensions/memory/index.js +76 -28
  7. package/dist/builtin/extensions/pie-ipc/README.md +2 -2
  8. package/dist/builtin/extensions/pie-ipc/index.js +421 -27
  9. package/dist/builtin/extensions/pie-proc/README.md +7 -7
  10. package/dist/builtin/extensions/pie-proc/index.js +453 -97
  11. package/dist/builtin/extensions/plan-mode/index.js +5 -5
  12. package/dist/builtin/extensions/subagent/index.js +8 -8
  13. package/dist/builtin/extensions/todo/index.js +4 -4
  14. package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +35 -24
  15. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +391 -123
  16. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chunk-HAUDUMDO.js +795 -0
  18. package/dist/builtin/skills/chrome-devtools-axi/{cli-NLPMVDGG.js → cli-K7ESY3XD.js} +1437 -231
  19. package/dist/builtin/skills/computer-use-axi/SKILL.md +26 -8
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +465 -83
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +75 -22
  22. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +451 -43
  23. package/dist/chunks/{chunk-3W3SXVPB.js → chunk-4UIUMTHG.js} +993 -371
  24. package/dist/chunks/chunk-6WKBQZWM.js +19 -0
  25. package/dist/chunks/{chunk-5KI4Y4LA.js → chunk-BA4Z27XT.js} +4 -3
  26. package/dist/chunks/{chunk-BLDI2GRF.js → chunk-DBDU3RRN.js} +1364 -446
  27. package/dist/chunks/{chunk-LAJXWOKS.js → chunk-EEC5PJTC.js} +11 -9
  28. package/dist/chunks/chunk-IZKHSUNQ.js +30 -0
  29. package/dist/chunks/{chunk-Y3I2UV5Y.js → chunk-LRHNAG4V.js} +349 -288
  30. package/dist/chunks/chunk-OU33ROFD.js +717 -0
  31. package/dist/chunks/{chunk-Z2FKA2ZH.js → chunk-PN6B54VT.js} +104 -22
  32. package/dist/chunks/{chunk-NHV2CALB.js → chunk-WYXUF4MP.js} +388 -32
  33. package/dist/chunks/{chunk-4PR34UZF.js → chunk-Z5KL6AO2.js} +159 -145
  34. package/dist/chunks/{host-image-fallback-N7RHNPYN.js → host-image-fallback-RASJSVZY.js} +1 -1
  35. package/dist/chunks/{manager-cli-NEZA46M5.js → manager-cli-Y6HM3MHA.js} +5 -5
  36. package/dist/chunks/{model-registry-3XAHXXTA.js → model-registry-5TLYILYR.js} +2 -2
  37. package/dist/chunks/{read-file-understanding-FMPXR6EJ.js → read-file-understanding-VPKDBV23.js} +5 -5
  38. package/dist/chunks/{src-B44QWSGM.js → src-2XI5P62J.js} +2 -2
  39. package/dist/chunks/{src-EGXFJ3WA.js → src-6QGGDHIW.js} +3 -3
  40. package/dist/chunks/{src-Q7LU27C2.js → src-CCEENRKC.js} +31 -1
  41. package/dist/chunks/{src-CLE5ILN4.js → src-DI4MCAGT.js} +20 -4
  42. package/dist/chunks/{test-stream-OR3EJBNF.js → test-stream-SYVWIPPW.js} +2 -2
  43. package/dist/cli.js +1918 -1489
  44. package/models.schema.json +271 -0
  45. package/package.json +2 -2
  46. package/dist/builtin/skills/chrome-devtools-axi/chunk-WOGAQ4P5.js +0 -399
  47. package/dist/chunks/chunk-7UAUDXZW.js +0 -1425
  48. package/dist/chunks/{chunk-CGSFBWOM.js → chunk-WBL73KRI.js} +3 -3
  49. package/dist/chunks/{manager-upgrade-CTU3ISCW.js → manager-upgrade-LSTOHBUV.js} +3 -3
@@ -20,12 +20,12 @@ import {
20
20
  parseStatusFile,
21
21
  peerHealth,
22
22
  peerLabel,
23
+ registerIpcRuntime,
23
24
  resolveIpcConfig,
24
25
  takeDispatchFrame,
25
26
  wrapInboundText,
26
27
  wrappedMessageMarker
27
- } from "../../../chunks/chunk-7UAUDXZW.js";
28
- import "../../../chunks/chunk-ZPJ3BNQB.js";
28
+ } from "../../../chunks/chunk-OU33ROFD.js";
29
29
  import {
30
30
  Type
31
31
  } from "../../../chunks/chunk-XXGYUYXI.js";
@@ -856,6 +856,231 @@ function resultJson(payload) {
856
856
  throw new Error("result payload exceeds envelope body cap");
857
857
  }
858
858
 
859
+ // builtin/extensions/pie-ipc/peek-projection.ts
860
+ var DEFAULT_PEEK_CHAR_BUDGET = 1e3;
861
+ var MIN_PEEK_CHAR_BUDGET = 300;
862
+ var MAX_PEEK_CHAR_BUDGET = 2e3;
863
+ var MAX_ENTRIES_PER_PAGE = 12;
864
+ var ENTRY_PACK_OVERHEAD = 40;
865
+ function extractSafeToolProgress(partial) {
866
+ if (!partial || typeof partial !== "object") return void 0;
867
+ const p = partial;
868
+ if (!p.details || typeof p.details !== "object" || !("increment" in p.details) || !Array.isArray(p.content)) return void 0;
869
+ 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();
870
+ return text ? text.slice(0, 500) : void 0;
871
+ }
872
+ function clampPeekCharBudget(value) {
873
+ if (typeof value !== "number" || !Number.isFinite(value)) return DEFAULT_PEEK_CHAR_BUDGET;
874
+ return Math.min(MAX_PEEK_CHAR_BUDGET, Math.max(MIN_PEEK_CHAR_BUDGET, Math.floor(value)));
875
+ }
876
+ function normalizePeekPage(value) {
877
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 1) return 1;
878
+ return Math.floor(value);
879
+ }
880
+ function stripInternalUserHeaders(raw) {
881
+ let text = raw.replace(/\u0000/g, "").trim();
882
+ if (!text) return { text: "" };
883
+ if (text.startsWith("[im-forward-dispatch]")) return { text: "" };
884
+ let tag;
885
+ for (let i = 0; i < 4; i++) {
886
+ const next = text.replace(/^\[pie-ipc\][^\n]*says:\s*(?:\r?\n)?/, "");
887
+ if (next === text) break;
888
+ text = next.trim();
889
+ if (text.startsWith("[im-forward-dispatch]")) return { text: "" };
890
+ }
891
+ if (text.startsWith("[ipc-done]")) {
892
+ tag = "ipc-done";
893
+ text = text.replace(/^\[ipc-done\][^\n]*(?:\r?\n)?/, "").trim();
894
+ } else if (text.startsWith("[ipc-done-check]") || text.startsWith("[ipc-check]")) {
895
+ tag = "ipc-check";
896
+ text = text.replace(/^\[ipc-(?:done-)?check\]\s*/, "").trim();
897
+ }
898
+ text = text.replace(/^\[(?:Feishu|Lark|Slack|Telegram|Discord|IM)\]\s*(?:\r?\n)?/, "").trim();
899
+ if (text.startsWith("[im-forward-dispatch]")) return { text: "" };
900
+ text = text.replace(/^(?:<at\b[^>]*>[^<]*<\/at>\s*)+/, "");
901
+ text = text.replace(/<at\b[^>]*>([^<]*)<\/at>/g, (_, name) => {
902
+ const trimmed = name.trim();
903
+ return trimmed ? `@${trimmed}` : "";
904
+ });
905
+ text = text.replace(/\r\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
906
+ return tag ? { text, tag } : { text };
907
+ }
908
+ function extractTextFromContent(content) {
909
+ if (typeof content === "string") return content;
910
+ if (!Array.isArray(content)) return "";
911
+ return content.map(
912
+ (block) => block && typeof block === "object" && block.type === "text" && typeof block.text === "string" ? String(block.text) : ""
913
+ ).join("");
914
+ }
915
+ function contentHasToolCall(content) {
916
+ if (!Array.isArray(content)) return false;
917
+ return content.some((block) => Boolean(block && typeof block === "object" && block.type === "toolCall"));
918
+ }
919
+ function extractCalmEntries(messages) {
920
+ const out = [];
921
+ for (const raw of messages) {
922
+ if (!raw || typeof raw !== "object") continue;
923
+ const msg = raw;
924
+ const at = typeof msg.timestamp === "number" && Number.isFinite(msg.timestamp) ? msg.timestamp : void 0;
925
+ if (msg.role === "user") {
926
+ const cleaned = stripInternalUserHeaders(extractTextFromContent(msg.content));
927
+ if (cleaned.text) {
928
+ out.push({ role: "user", text: cleaned.text, ...at !== void 0 ? { at } : {}, ...cleaned.tag ? { tag: cleaned.tag } : {} });
929
+ }
930
+ continue;
931
+ }
932
+ if (msg.role === "assistant") {
933
+ const stopReason = typeof msg.stopReason === "string" ? msg.stopReason : void 0;
934
+ const failed = stopReason === "error" || stopReason === "aborted";
935
+ if (contentHasToolCall(msg.content) && !failed) continue;
936
+ const text = extractTextFromContent(msg.content).replace(/\u0000/g, "").replace(/\r\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
937
+ if (text) {
938
+ out.push({ role: "assistant", text, ...at !== void 0 ? { at } : {}, ...failed && stopReason ? { tag: stopReason } : {} });
939
+ } else if (failed && stopReason) {
940
+ const err = typeof msg.errorMessage === "string" && msg.errorMessage.trim() ? `: ${msg.errorMessage.trim().slice(0, 180)}` : "";
941
+ out.push({ role: "assistant", text: `[${stopReason}${err}]`, ...at !== void 0 ? { at } : {}, tag: stopReason });
942
+ }
943
+ }
944
+ }
945
+ return out;
946
+ }
947
+ function isHighSurrogate(code) {
948
+ return code >= 55296 && code <= 56319;
949
+ }
950
+ function isLowSurrogate(code) {
951
+ return code >= 56320 && code <= 57343;
952
+ }
953
+ function safeHeadSlice(text, maxUnits) {
954
+ if (maxUnits <= 0) return "";
955
+ if (text.length <= maxUnits) return text;
956
+ let end = maxUnits;
957
+ if (end > 0 && isHighSurrogate(text.charCodeAt(end - 1))) end -= 1;
958
+ return text.slice(0, end);
959
+ }
960
+ function safeTailSlice(text, maxUnits) {
961
+ if (maxUnits <= 0) return "";
962
+ if (text.length <= maxUnits) return text;
963
+ let start = text.length - maxUnits;
964
+ if (start < text.length && isLowSurrogate(text.charCodeAt(start))) start += 1;
965
+ return text.slice(start);
966
+ }
967
+ function closeDanglingCodeFence(text) {
968
+ const fences = text.match(/```/g);
969
+ return fences && fences.length % 2 === 1 ? `${text}
970
+ \`\`\`` : text;
971
+ }
972
+ function clipEntryText(role, text, maxChars) {
973
+ if (text.length <= maxChars) return closeDanglingCodeFence(text);
974
+ if (maxChars <= 16) return safeHeadSlice(text, Math.max(1, maxChars));
975
+ if (role === "user") {
976
+ return closeDanglingCodeFence(`${safeHeadSlice(text, maxChars - 1).trimEnd()}\u2026`);
977
+ }
978
+ const sep = "\n\u2026\n";
979
+ const avail = maxChars - sep.length;
980
+ const headLen = Math.floor(avail * 0.45);
981
+ const tailLen = avail - headLen;
982
+ return closeDanglingCodeFence(`${safeHeadSlice(text, headLen).trimEnd()}${sep}${safeTailSlice(text, tailLen).trimStart()}`);
983
+ }
984
+ function paginateCalmEntries(entries, opts = {}) {
985
+ const charBudget = clampPeekCharBudget(opts.charBudget);
986
+ const reqPage = normalizePeekPage(opts.page);
987
+ if (entries.length === 0) {
988
+ return { page: 1, totalPages: 1, totalEntries: 0, charBudget, entries: [] };
989
+ }
990
+ const multiEntryCap = Math.max(200, Math.floor(charBudget * 0.65));
991
+ const pages = [];
992
+ let currentRaw = [];
993
+ let currentChars = 0;
994
+ const flushPage = () => {
995
+ if (currentRaw.length === 0) return;
996
+ const ordered = currentRaw.reverse();
997
+ const cap = ordered.length === 1 ? charBudget : multiEntryCap;
998
+ pages.push(ordered.map((entry) => ({
999
+ ...entry,
1000
+ text: clipEntryText(entry.role, entry.text, cap)
1001
+ })));
1002
+ currentRaw = [];
1003
+ currentChars = 0;
1004
+ };
1005
+ for (let i = entries.length - 1; i >= 0; i--) {
1006
+ const entry = entries[i];
1007
+ const effectiveLen = Math.min(entry.text.length, multiEntryCap) + ENTRY_PACK_OVERHEAD;
1008
+ if (currentRaw.length > 0 && (currentRaw.length >= MAX_ENTRIES_PER_PAGE || currentChars + effectiveLen > charBudget)) {
1009
+ flushPage();
1010
+ }
1011
+ currentRaw.push(entry);
1012
+ currentChars += effectiveLen;
1013
+ }
1014
+ flushPage();
1015
+ const totalPages = Math.max(1, pages.length);
1016
+ const page = Math.min(reqPage, totalPages);
1017
+ return {
1018
+ page,
1019
+ totalPages,
1020
+ totalEntries: entries.length,
1021
+ charBudget,
1022
+ entries: pages[page - 1] ?? []
1023
+ };
1024
+ }
1025
+ function fitPeekSnapshotToFrame(snapshot, frameBytes, maxBytes = 8e3) {
1026
+ const encode = () => JSON.stringify({ ok: true, message: JSON.stringify(snapshot) });
1027
+ if (snapshot.turns && snapshot.turns.entries.length > 0 && (!snapshot.active || snapshot.turns.page > 1)) {
1028
+ snapshot.items = [];
1029
+ delete snapshot.lastVisible;
1030
+ }
1031
+ const newest = snapshot.items.at(-1);
1032
+ if (!snapshot.active && newest?.kind === "assistant" && snapshot.lastVisible?.text === newest.text) {
1033
+ delete snapshot.lastVisible;
1034
+ }
1035
+ if (typeof snapshot.model === "string" && snapshot.model.length > 120) {
1036
+ snapshot.model = safeHeadSlice(snapshot.model, 120);
1037
+ }
1038
+ let text = encode();
1039
+ while (frameBytes(text) > maxBytes) {
1040
+ if (snapshot.turns && snapshot.lastVisible) {
1041
+ if (snapshot.lastVisible.text.length > 256) {
1042
+ snapshot.lastVisible.text = safeTailSlice(snapshot.lastVisible.text, Math.max(256, snapshot.lastVisible.text.length - 512));
1043
+ } else {
1044
+ delete snapshot.lastVisible;
1045
+ }
1046
+ } else if (snapshot.turns && snapshot.items.length > 1) {
1047
+ snapshot.items.shift();
1048
+ } else if (snapshot.turns && snapshot.items.length === 1 && snapshot.items[0].text.length > 256) {
1049
+ snapshot.items[0].text = safeTailSlice(snapshot.items[0].text, Math.max(256, snapshot.items[0].text.length - 512));
1050
+ } else if (snapshot.turns && snapshot.items.length === 1) {
1051
+ snapshot.items.shift();
1052
+ } else if (snapshot.turns && snapshot.turns.entries.length > 1) {
1053
+ snapshot.turns.entries.shift();
1054
+ } else if (snapshot.turns && snapshot.turns.entries.length === 1) {
1055
+ const sole = snapshot.turns.entries[0];
1056
+ if (sole.text.length > 128) {
1057
+ sole.text = clipEntryText(sole.role, sole.text, Math.max(128, sole.text.length - 256));
1058
+ } else {
1059
+ delete snapshot.turns;
1060
+ }
1061
+ } else if (snapshot.lastVisible && snapshot.lastVisible.text.length > 512 && snapshot.items.length > 1) {
1062
+ snapshot.lastVisible.text = safeTailSlice(snapshot.lastVisible.text, Math.max(512, snapshot.lastVisible.text.length - 512));
1063
+ } else if (snapshot.items.length > 1) {
1064
+ snapshot.items.shift();
1065
+ } else {
1066
+ const item = snapshot.items[0];
1067
+ const visible = snapshot.lastVisible;
1068
+ if (visible && visible.text.length > 128 && (snapshot.active || !item || visible.text.length >= item.text.length)) {
1069
+ visible.text = safeTailSlice(visible.text, Math.max(128, visible.text.length - 256));
1070
+ } else if (item?.text.length) {
1071
+ if (item.text.length <= 128) snapshot.items.shift();
1072
+ else item.text = safeTailSlice(item.text, Math.max(128, item.text.length - 256));
1073
+ } else if (visible) {
1074
+ delete snapshot.lastVisible;
1075
+ } else if (snapshot.model) {
1076
+ delete snapshot.model;
1077
+ } else break;
1078
+ }
1079
+ text = encode();
1080
+ }
1081
+ return text;
1082
+ }
1083
+
859
1084
  // builtin/extensions/pie-ipc/index.ts
860
1085
  var DEFAULT_NOTIFY_FALLBACK_MS = 6e5;
861
1086
  var FALLBACK_RENEWAL_CAP = 4;
@@ -912,6 +1137,15 @@ var Runtime = class {
912
1137
  results = new RequestResultStore();
913
1138
  executionFailure;
914
1139
  active = false;
1140
+ /** Bounded, memory-only display projection for worker Peek. It deliberately
1141
+ * stores only assistant text blocks and tool names/status — never thinking,
1142
+ * args, results, user input, or session-log data. */
1143
+ peekTurn = 0;
1144
+ peekStartedAt;
1145
+ peekItems = [];
1146
+ peekAssistantIndex;
1147
+ peekLastVisible;
1148
+ peekPendingVisible;
915
1149
  polledInputs = /* @__PURE__ */ new Map();
916
1150
  /** Server readiness gate: no status writes before the listener is up. */
917
1151
  serverReady = false;
@@ -959,6 +1193,8 @@ var Runtime = class {
959
1193
  if (typeof liveName === "string") this.sessionName = liveName;
960
1194
  const displaySessionName = this.ctx.getSessionDisplayName?.() ?? liveName;
961
1195
  const model = this.ctx.getCurrentModel?.();
1196
+ const thinkingLevel = this.ctx.getThinkingLevel?.();
1197
+ const thinkingStatus = this.ctx.getThinkingStatus?.();
962
1198
  const snapshot = this.projection.snapshot({
963
1199
  ...this.statusBase,
964
1200
  displayName: this.displayName,
@@ -966,28 +1202,31 @@ var Runtime = class {
966
1202
  sessionName: this.sessionName,
967
1203
  ...displaySessionName ? { displaySessionName } : {},
968
1204
  ...typeof model === "string" && model ? { model } : {},
1205
+ ...typeof thinkingLevel === "string" && thinkingLevel ? { thinkingLevel } : {},
1206
+ ...thinkingStatus ? { effectiveThinkingLevel: thinkingStatus.effective, supportedThinkingLevels: thinkingStatus.supportedLevels } : {},
969
1207
  isManager: this.ctx.capabilities?.unattended === true && process.env.PIE_PROC_CURATED_NAME === "manager",
1208
+ sessionControls: this.ctx.capabilities?.interactiveUI === false && this.ctx.capabilities.editorInjection === true,
1209
+ workerPeek: this.ctx.capabilities?.unattended === true,
970
1210
  imBinding: currentImBinding()
971
1211
  });
972
1212
  return { ...snapshot, allowPeers: [...this.allowPolicy.snapshot()], undeliveredInjections: this.delivery?.undeliveredInjections ?? snapshot.undeliveredInjections ?? 0 };
973
1213
  }
974
1214
  writeStatus() {
975
- if (!this.serverReady) return false;
1215
+ if (this.disposed || !this.serverReady) return false;
976
1216
  return writeStatusFile(this.discoveryDir, { ...this.currentStatus(), updatedAt: Date.now() }, (message) => this.ctx.log(message));
977
1217
  }
978
1218
  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
- };
1219
+ const replyEnvelope = (kind, text) => ({
1220
+ v: IPC_PROTOCOL_VERSION,
1221
+ id: `${envelope.id}:r`,
1222
+ from: this.instanceId,
1223
+ to: envelope.from,
1224
+ kind,
1225
+ createdAt: Date.now(),
1226
+ replyTo: envelope.id,
1227
+ ...text !== void 0 ? { text } : {}
1228
+ });
1229
+ const reply = (kind, text) => respond(replyEnvelope(kind, text));
991
1230
  switch (envelope.kind) {
992
1231
  case "control": {
993
1232
  if (this.sessionId === null) {
@@ -1008,12 +1247,24 @@ var Runtime = class {
1008
1247
  reply("ack", JSON.stringify({ ok: false, message: "invalid control frame" }));
1009
1248
  return;
1010
1249
  }
1250
+ if (parsed.control === "session.peek") {
1251
+ if (this.ctx.capabilities?.unattended !== true) {
1252
+ reply("ack", JSON.stringify({ ok: false, message: "host does not advertise Peek" }));
1253
+ return;
1254
+ }
1255
+ const base = replyEnvelope("ack");
1256
+ const peekOpts = parsed.payload && typeof parsed.payload === "object" && !Array.isArray(parsed.payload) ? parsed.payload : {};
1257
+ const text = this.boundedPeekAckText((candidate) => Buffer.byteLength(JSON.stringify({ ...base, text: candidate, auth: "0".repeat(64) }) + "\n"), peekOpts);
1258
+ respond({ ...base, text });
1259
+ return;
1260
+ }
1011
1261
  const applier = this.ctx.applyIpcControl;
1012
1262
  if (!applier) {
1013
1263
  reply("ack", JSON.stringify({ ok: false, message: "host does not support control frames" }));
1014
1264
  return;
1015
1265
  }
1016
1266
  const receipt = await applier(parsed.control, parsed.payload);
1267
+ if (receipt?.ok && (parsed.control === "model.set" || parsed.control === "thinking.set")) this.writeStatus();
1017
1268
  try {
1018
1269
  this.ctx.appendEntry?.("pie.ipc.control", {
1019
1270
  from: envelope.from,
@@ -1137,16 +1388,112 @@ var Runtime = class {
1137
1388
  return readStatusFile(this.discoveryDir, peerInstanceId)?.displayName;
1138
1389
  }
1139
1390
  // ---- lifecycle events ----
1391
+ trimPeek() {
1392
+ while (this.peekItems.length > 40 || this.peekItems.reduce((n, item) => n + item.text.length + (item.progress?.length ?? 0), 0) > 8e3) {
1393
+ if (this.peekItems.length === 1) {
1394
+ const item = this.peekItems[0];
1395
+ item.text = item.text.slice(-4e3);
1396
+ if (item.progress) item.progress = item.progress.slice(-500);
1397
+ break;
1398
+ }
1399
+ this.peekItems.shift();
1400
+ if (this.peekAssistantIndex !== void 0) this.peekAssistantIndex = this.peekAssistantIndex === 0 ? void 0 : this.peekAssistantIndex - 1;
1401
+ }
1402
+ }
1403
+ addPeekAssistant(text, delta = false) {
1404
+ const clean = text.replace(/\u0000/g, "");
1405
+ if (!clean || !delta && !clean.trim()) return;
1406
+ if (delta && this.peekAssistantIndex !== void 0 && this.peekItems[this.peekAssistantIndex]?.kind === "assistant") {
1407
+ const item = this.peekItems[this.peekAssistantIndex];
1408
+ item.text = (item.text + clean).slice(-4e3);
1409
+ item.at = Date.now();
1410
+ } else {
1411
+ const display = delta ? clean : clean.trim();
1412
+ this.peekItems.push({ at: Date.now(), kind: "assistant", text: display.slice(-4e3) });
1413
+ this.peekAssistantIndex = this.peekItems.length - 1;
1414
+ }
1415
+ const visible = { at: Date.now(), text: this.peekItems[this.peekAssistantIndex].text };
1416
+ if (this.active) this.peekPendingVisible = visible;
1417
+ else this.peekLastVisible = visible;
1418
+ this.trimPeek();
1419
+ }
1420
+ peekSnapshot(opts = {}) {
1421
+ const now = Date.now();
1422
+ const items = this.peekItems.map(({ toolCallId: _id, startedAt, done, failed, progress, ...item }) => item.kind === "tool" && startedAt !== void 0 ? { ...item, text: `${done ? failed ? "Failed" : "Finished" : "Running"} ${item.text} \xB7 ${Math.max(0, Math.floor(((done ? item.at : now) - startedAt) / 1e3))}s${progress ? ` \xB7 ${progress}` : ""}` } : item);
1423
+ let rawMessages = [];
1424
+ try {
1425
+ const fetched = this.ctx.getMessages?.();
1426
+ if (Array.isArray(fetched)) rawMessages = fetched;
1427
+ } catch {
1428
+ }
1429
+ const calmEntries = extractCalmEntries(rawMessages);
1430
+ const turns = calmEntries.length > 0 ? paginateCalmEntries(calmEntries, opts) : void 0;
1431
+ const model = (() => {
1432
+ try {
1433
+ return this.ctx.getCurrentModel?.();
1434
+ } catch {
1435
+ return void 0;
1436
+ }
1437
+ })();
1438
+ const isManager = this.ctx.capabilities?.unattended === true && process.env.PIE_PROC_CURATED_NAME === "manager";
1439
+ return {
1440
+ active: this.active,
1441
+ turn: this.peekTurn,
1442
+ ...this.peekStartedAt ? { startedAt: this.peekStartedAt } : {},
1443
+ generatedAt: now,
1444
+ ...typeof model === "string" && model ? { model } : {},
1445
+ ...isManager ? { isManager: true } : {},
1446
+ items,
1447
+ ...this.peekLastVisible ? { lastVisible: { ...this.peekLastVisible } } : {},
1448
+ ...turns ? { turns } : {}
1449
+ };
1450
+ }
1451
+ boundedPeekAckText(frameBytes, opts = {}) {
1452
+ return fitPeekSnapshotToFrame(this.peekSnapshot(opts), frameBytes, 8e3);
1453
+ }
1140
1454
  onEvent(event) {
1141
1455
  switch (event.type) {
1142
1456
  case "turn:start": {
1457
+ if (!this.active) {
1458
+ this.peekTurn++;
1459
+ this.peekStartedAt = Date.now();
1460
+ this.peekItems = [];
1461
+ this.peekPendingVisible = void 0;
1462
+ }
1463
+ this.peekAssistantIndex = void 0;
1143
1464
  this.executionFailure = void 0;
1144
1465
  this.active = true;
1145
1466
  if (this.projection.updateFromEvent(event)) this.writeStatus();
1146
1467
  return;
1147
1468
  }
1148
- case "tool:execution:start":
1469
+ case "assistant:display-delta": {
1470
+ if (typeof event.delta === "string") this.addPeekAssistant(event.delta, true);
1471
+ return;
1472
+ }
1473
+ case "tool:execution:start": {
1474
+ this.peekAssistantIndex = void 0;
1475
+ 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() });
1476
+ this.trimPeek();
1477
+ if (this.projection.updateFromEvent(event)) this.writeStatus();
1478
+ return;
1479
+ }
1480
+ case "tool:execution:update": {
1481
+ const item = event.toolCallId ? this.peekItems.find((i) => i.toolCallId === event.toolCallId) : void 0;
1482
+ const progress = extractSafeToolProgress(event.partialResult);
1483
+ if (item && !item.done && progress) {
1484
+ item.progress = progress;
1485
+ item.at = Date.now();
1486
+ this.trimPeek();
1487
+ }
1488
+ return;
1489
+ }
1149
1490
  case "tool:execution:end": {
1491
+ const item = event.toolCallId ? this.peekItems.find((i) => i.toolCallId === event.toolCallId) : void 0;
1492
+ if (item && !item.done) {
1493
+ item.done = true;
1494
+ if (event.isError === true) item.failed = true;
1495
+ item.at = Date.now();
1496
+ }
1150
1497
  if (this.projection.updateFromEvent(event)) this.writeStatus();
1151
1498
  return;
1152
1499
  }
@@ -1156,6 +1503,8 @@ var Runtime = class {
1156
1503
  case "agent:end":
1157
1504
  case "turn:failed":
1158
1505
  case "turn:cancelled": {
1506
+ if (event.type === "agent:end" && !this.executionFailure && this.peekPendingVisible) this.peekLastVisible = this.peekPendingVisible;
1507
+ this.peekPendingVisible = void 0;
1159
1508
  if (this.projection.updateFromEvent(event)) this.writeStatus();
1160
1509
  this.answerAwaitingPeers(event.type !== "agent:end" || Boolean(this.executionFailure));
1161
1510
  this.active = false;
@@ -1171,6 +1520,11 @@ var Runtime = class {
1171
1520
  this.clearNotifyFallbacks();
1172
1521
  this.notifyGeneration++;
1173
1522
  this.projection.resetSessionState();
1523
+ this.peekTurn = 0;
1524
+ this.peekStartedAt = void 0;
1525
+ this.peekItems = [];
1526
+ this.peekLastVisible = void 0;
1527
+ this.peekPendingVisible = void 0;
1174
1528
  this.executionFailure = void 0;
1175
1529
  this.active = false;
1176
1530
  this.writeStatus();
@@ -1189,6 +1543,13 @@ var Runtime = class {
1189
1543
  }
1190
1544
  }
1191
1545
  } else {
1546
+ if (message?.role === "assistant" && Array.isArray(message.content)) {
1547
+ const visible = message.content.map((block) => block && typeof block === "object" && block.type === "text" && typeof block.text === "string" ? String(block.text) : "").join("");
1548
+ if (visible) {
1549
+ const streamed = this.peekAssistantIndex !== void 0 ? this.peekItems[this.peekAssistantIndex]?.text : void 0;
1550
+ if (streamed !== visible) this.addPeekAssistant(visible);
1551
+ }
1552
+ }
1192
1553
  if (message?.role === "assistant") {
1193
1554
  const outcome = message;
1194
1555
  if (outcome.stopReason === "error" || outcome.stopReason === "aborted") this.executionFailure = outcome.stopReason;
@@ -1562,6 +1923,34 @@ ${outcome.text}`
1562
1923
  return ` ${label} [${file.state}]${sid}`;
1563
1924
  }).join("\n");
1564
1925
  }
1926
+ /** Panel controls originate from this process's real advertised IPC identity (supports self + peers). */
1927
+ async sendBoundControl(peerRef, control, payload, expected, waitMs = 6e3) {
1928
+ const ref = peerRef.trim().toLowerCase();
1929
+ const selfStatus = () => readStatusFile(this.discoveryDir, this.instanceId) ?? (this.transport?.listenPort ? { ...this.currentStatus(), port: this.transport.listenPort } : null);
1930
+ const target = expected ? readStatusFile(this.discoveryDir, expected.instanceId) : ref === "self" || ref === this.instanceId.toLowerCase() ? selfStatus() : this.resolvePeer(peerRef);
1931
+ if (!target || !target.port) return { ok: false, detail: `Session not found: ${peerRef}` };
1932
+ if (expected && (target.instanceId !== expected.instanceId || target.sessionId !== expected.sessionId))
1933
+ return { ok: false, detail: "Worker instance or session no longer matches the issued card. Reopen it from /panel." };
1934
+ if (!this.allowPolicy.allows(target.instanceId)) return { ok: false, detail: "Denied by manager sender allow policy." };
1935
+ if (!(target.allowPeers?.includes("*") || target.allowPeers?.includes(this.instanceId)))
1936
+ return { ok: false, detail: "Denied by worker recipient allow policy." };
1937
+ if (!this.transport) return { ok: false, unknown: true, detail: "Manager IPC transport is unavailable." };
1938
+ try {
1939
+ const reply = await this.transport.send(target.instanceId, target.port, "control", {
1940
+ sessionId: target.sessionId ?? "",
1941
+ text: JSON.stringify({ control, payload }),
1942
+ awaitAck: true,
1943
+ waitMs,
1944
+ replyKinds: /* @__PURE__ */ new Set(["ack"])
1945
+ });
1946
+ if (reply?.text) {
1947
+ const ack = JSON.parse(reply.text);
1948
+ if (typeof ack?.ok === "boolean") return { ok: ack.ok, detail: `Peer receipt: ${reply.text}` };
1949
+ }
1950
+ } catch {
1951
+ }
1952
+ return { ok: false, unknown: true, detail: "No verified receipt. The request may already have been applied." };
1953
+ }
1565
1954
  /** MULTI-AGENT IM v2 Phase 2.3 — send an enumerated CONTROL frame to a
1566
1955
  * peer (first control: model.set). Returns the peer's receipt (the ack
1567
1956
  * envelope text, a small JSON object). The frame bypasses the target's
@@ -1585,7 +1974,7 @@ ${outcome.text}`
1585
1974
  waitMs,
1586
1975
  replyKinds: /* @__PURE__ */ new Set(["ack"])
1587
1976
  });
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 };
1977
+ 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
1978
  return { content: [{ type: "text", text: reply.text ?? "(empty receipt)" }] };
1590
1979
  }
1591
1980
  async sendToPeer(peerRef, text, _wait, _waitMs, context, notify = false, fallbackMs = DEFAULT_NOTIFY_FALLBACK_MS) {
@@ -1746,8 +2135,9 @@ ${message.text}`).join("\n---\n");
1746
2135
  } });
1747
2136
  return result.content[0]?.text ?? "(no result)";
1748
2137
  }
1749
- dispose() {
2138
+ async dispose() {
1750
2139
  this.disposed = true;
2140
+ this.serverReady = false;
1751
2141
  this.stopHeartbeat?.();
1752
2142
  this.stopImBinding();
1753
2143
  this.delivery?.resetSessionState();
@@ -1760,8 +2150,8 @@ ${message.text}`).join("\n---\n");
1760
2150
  this.ctx.ui.setStatus?.("pie-ipc-peers", void 0);
1761
2151
  } catch {
1762
2152
  }
1763
- this.transport?.close();
1764
2153
  removeStatusFile(this.discoveryDir, this.instanceId);
2154
+ await this.transport?.closeAndFlush();
1765
2155
  }
1766
2156
  };
1767
2157
  function loadConfig(ctx, configDir) {
@@ -1814,6 +2204,7 @@ function pieIpcExtension(ctx) {
1814
2204
  }
1815
2205
  }
1816
2206
  const runtime = new Runtime(ctx, config, discoveryDir);
2207
+ const unregisterRuntime = registerIpcRuntime(discoveryDir, runtime);
1817
2208
  const serverEligible = ctx.capabilities.eventSink && ctx.capabilities.longLived;
1818
2209
  ctx.log(`pie-ipc: enabled as ${runtime.instanceId} (${serverEligible ? "server+client (starting listener)" : "client-only"})`);
1819
2210
  if (serverEligible) {
@@ -1856,7 +2247,9 @@ function pieIpcExtension(ctx) {
1856
2247
  "turn:completed",
1857
2248
  "turn:failed",
1858
2249
  "turn:cancelled",
2250
+ "assistant:display-delta",
1859
2251
  "tool:execution:start",
2252
+ "tool:execution:update",
1860
2253
  "tool:execution:end",
1861
2254
  "session:changed",
1862
2255
  "message:end"
@@ -1923,11 +2316,11 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1923
2316
  ctx.registerTool({
1924
2317
  name: "ipc_control_notify",
1925
2318
  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. 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 means started \u2014 observe the result via session.context). Receipt (success or structured refusal) returns as this tool's result. Controls are idempotent: re-sending after an uncertain outcome is safe.",
2319
+ 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
2320
  parameters: Type.Object({
1928
2321
  to: Type.String({ description: "Peer display name or instance id (see ipc_list_peers)" }),
1929
2322
  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)" }),
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'}; session.context/session.compact take an empty payload" })),
2323
+ 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|max'}; session.context/session.compact take an empty payload" })),
1931
2324
  waitMs: Type.Optional(Type.Number({ description: "Receipt wait budget in ms (default 120000, max 600000)", minimum: 100, maximum: 6e5 }))
1932
2325
  }),
1933
2326
  risk: { ...risk, riskClass: "session_mutation", concurrencySafe: false },
@@ -1945,7 +2338,7 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1945
2338
  }
1946
2339
  if (args.control === "thinking.set") {
1947
2340
  const payload = args.payload ?? {};
1948
- const valid = ["off", "minimal", "low", "medium", "high", "xhigh"];
2341
+ const valid = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
1949
2342
  if (typeof payload.level !== "string" || !valid.includes(payload.level))
1950
2343
  return { content: [{ type: "text", text: `thinking.set requires payload.level as one of ${valid.join("|")}.` }], isError: true };
1951
2344
  }
@@ -1956,10 +2349,10 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1956
2349
  ctx.registerTool({
1957
2350
  name: "self_control",
1958
2351
  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. '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. Controls are idempotent: re-sending after an uncertain outcome is safe.",
2352
+ 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
2353
  parameters: Type.Object({
1961
2354
  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
- 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'}" })),
2355
+ 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|max'}" })),
1963
2356
  waitMs: Type.Optional(Type.Number({ description: "Receipt wait budget in ms (default 120000, max 600000)", minimum: 100, maximum: 6e5 }))
1964
2357
  }),
1965
2358
  risk: { ...risk, riskClass: "session_mutation", concurrencySafe: false },
@@ -1977,7 +2370,7 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1977
2370
  }
1978
2371
  if (args.control === "thinking.set") {
1979
2372
  const payload = args.payload ?? {};
1980
- const valid = ["off", "minimal", "low", "medium", "high", "xhigh"];
2373
+ const valid = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
1981
2374
  if (typeof payload.level !== "string" || !valid.includes(payload.level))
1982
2375
  return { content: [{ type: "text", text: `thinking.set requires payload.level as one of ${valid.join("|")}.` }], isError: true };
1983
2376
  }
@@ -2109,8 +2502,9 @@ Usage: /tools/ipc name <new-name>`;
2109
2502
  ctx.ui.notify(output, "info");
2110
2503
  }
2111
2504
  });
2112
- ctx.registerCleanup?.(() => {
2113
- runtime.dispose();
2505
+ ctx.registerCleanup?.(async () => {
2506
+ unregisterRuntime();
2507
+ await runtime.dispose();
2114
2508
  });
2115
2509
  }
2116
2510
  function getConfigDirSafe(_ctx) {