@cydm/pie 4.7.0 → 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.
@@ -2,6 +2,7 @@ import { createRequire as __createRequire } from "node:module"; const require =
2
2
  import {
3
3
  DISPATCH_PREFIX,
4
4
  IPC_PROTOCOL_VERSION,
5
+ IpcTransport,
5
6
  addressBookRoot,
6
7
  assistantForwardText,
7
8
  chunkKey,
@@ -12,6 +13,7 @@ import {
12
13
  configSnapshot,
13
14
  configurationIdentity,
14
15
  currentConsumer,
16
+ currentIpcRuntime,
15
17
  estimatePostRequestBytes,
16
18
  failureReason,
17
19
  hasConfigLayers,
@@ -28,11 +30,10 @@ import {
28
30
  resolveImForwardConfig,
29
31
  saveLocation,
30
32
  sessionLabel,
31
- signEnvelope,
32
33
  truncateMarkdown,
33
34
  tryClaimConsumer,
34
35
  writeConfig
35
- } from "../../../chunks/chunk-7UAUDXZW.js";
36
+ } from "../../../chunks/chunk-EGZ5TZRM.js";
36
37
  import {
37
38
  readProcessCommandLine
38
39
  } from "../../../chunks/chunk-7RJXKN7N.js";
@@ -382,7 +383,8 @@ function ipcDiscoveryRoot() {
382
383
  }
383
384
 
384
385
  // builtin/extensions/im-forward/panel-actions.ts
385
- import { spawn as spawn3 } from "node:child_process";
386
+ import { execFile, spawn as spawn3 } from "node:child_process";
387
+ import { randomBytes } from "node:crypto";
386
388
  import { StringDecoder as StringDecoder3 } from "node:string_decoder";
387
389
  import * as fs3 from "node:fs";
388
390
  import * as path4 from "node:path";
@@ -842,8 +844,10 @@ async function resolveUserName(openId, opts = {}) {
842
844
  try {
843
845
  const args = ["contact", "+get-user", "--user-id", openId, "--as", "bot"];
844
846
  if (opts.profile) args.push("--profile", opts.profile);
845
- const { stdout, error } = await runLarkCli(opts.binary ?? "lark-cli", args, 1e4);
846
- if (!error && stdout.trim()) {
847
+ const binary = resolveLaunchSpec(opts.binary, opts.cwd);
848
+ if (!binary) return fallbackName(openId);
849
+ const { stdout, error } = await runLarkCli(binary, args, 1e4, opts.cwd, { signal: opts.signal });
850
+ if (!opts.signal?.aborted && !error && stdout.trim()) {
847
851
  const parsed = JSON.parse(stdout);
848
852
  const name = typeof parsed?.data?.user?.name === "string" ? parsed.data.user.name : typeof parsed.name === "string" ? parsed.name : void 0;
849
853
  if (name) {
@@ -1162,12 +1166,14 @@ function interpreterFor(script) {
1162
1166
  if (ext === ".py") return { command: "python3", prefix: [script] };
1163
1167
  return { command: script, prefix: [] };
1164
1168
  }
1165
- function scriptEnv(req) {
1169
+ var ACTION_LAUNCH_ID_ENV = "PIE_ACTION_LAUNCH_ID";
1170
+ function scriptEnv(req, launchId) {
1166
1171
  const env = {};
1167
1172
  for (const key of ["PATH", "HOME", "LANG", "LC_ALL", "TERM", "TMPDIR", "USER", "LOGNAME", "SHELL"]) {
1168
1173
  const value = process.env[key];
1169
1174
  if (value !== void 0) env[key] = value;
1170
1175
  }
1176
+ env[ACTION_LAUNCH_ID_ENV] = launchId;
1171
1177
  env.PIE_ACTION_ID = req.action.id;
1172
1178
  env.PIE_ACTION_TRIGGER_NAME = req.trigger.name;
1173
1179
  if (req.trigger.openId) env.PIE_ACTION_TRIGGER_OPEN_ID = req.trigger.openId;
@@ -1184,6 +1190,48 @@ function scriptEnv(req) {
1184
1190
  }
1185
1191
  return env;
1186
1192
  }
1193
+ function execFileText(file, args) {
1194
+ return new Promise((resolve6) => {
1195
+ execFile(file, args, { encoding: "utf8", timeout: 1500, maxBuffer: 512 * 1024, windowsHide: true }, (error, stdout) => {
1196
+ resolve6(error ? void 0 : stdout);
1197
+ });
1198
+ });
1199
+ }
1200
+ async function processHasLaunchId(pid, launchId) {
1201
+ const marker = `${ACTION_LAUNCH_ID_ENV}=${launchId}`;
1202
+ if (process.platform === "linux") {
1203
+ let handle;
1204
+ try {
1205
+ handle = await fs3.promises.open(`/proc/${pid}/environ`, "r");
1206
+ const buf = Buffer.allocUnsafe(128 * 1024);
1207
+ const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
1208
+ const fields = buf.subarray(0, bytesRead).toString("utf8").split("\0");
1209
+ return fields.includes(marker);
1210
+ } catch (error) {
1211
+ if (error.code === "ENOENT") return false;
1212
+ return void 0;
1213
+ } finally {
1214
+ await handle?.close().catch(() => {
1215
+ });
1216
+ }
1217
+ }
1218
+ const out = await execFileText("ps", ["eww", "-p", String(pid), "-o", "command="]);
1219
+ return out === void 0 ? void 0 : out.split(/\s+/).includes(marker);
1220
+ }
1221
+ async function inspectPosixGroup(pgid, launchId) {
1222
+ const out = await execFileText("ps", ["-axo", "pid=,pgid=,stat="]);
1223
+ if (out === void 0) return "unknown";
1224
+ const members = [];
1225
+ for (const line of out.split("\n")) {
1226
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s+(\S+)/);
1227
+ if (!match || Number(match[2]) !== pgid) continue;
1228
+ members.push({ pid: Number(match[1]), zombie: match[3].startsWith("Z") });
1229
+ }
1230
+ const live = members.filter((member) => !member.zombie);
1231
+ if (live.length === 0) return "gone";
1232
+ const identities = await Promise.all(live.map((member) => processHasLaunchId(member.pid, launchId)));
1233
+ return identities.every((identity) => identity === true) ? "owned" : "unknown";
1234
+ }
1187
1235
  async function executeAction(req) {
1188
1236
  const started = Date.now();
1189
1237
  const { action } = req;
@@ -1247,13 +1295,19 @@ async function executeAction(req) {
1247
1295
  `started: ${new Date(started).toISOString()}`,
1248
1296
  "=".repeat(60)
1249
1297
  ].filter((line) => line !== void 0).join("\n") + "\n");
1298
+ const launchId = randomBytes(24).toString("hex");
1250
1299
  const exitCode = await new Promise((resolve6) => {
1300
+ if (req.signal?.aborted) {
1301
+ cancelled = true;
1302
+ resolve6(null);
1303
+ return;
1304
+ }
1251
1305
  const { command, prefix } = interpreterFor(script);
1252
1306
  let child;
1253
1307
  try {
1254
1308
  child = spawn3(command, prefix, {
1255
1309
  cwd,
1256
- env: scriptEnv(req),
1310
+ env: scriptEnv(req, launchId),
1257
1311
  detached: process.platform !== "win32",
1258
1312
  // own process group: timeout kills the TREE
1259
1313
  stdio: ["ignore", "pipe", "pipe"],
@@ -1296,14 +1350,20 @@ async function executeAction(req) {
1296
1350
  stderrTail = next.slice(-8e3);
1297
1351
  });
1298
1352
  let settled = false;
1353
+ let stopping = false;
1299
1354
  let killGrace;
1300
- let finalDeadline;
1355
+ let windowsFinalDeadline;
1356
+ let groupPoll;
1357
+ let termSent = false;
1358
+ let termProbeRunning = false;
1301
1359
  const settle = (code) => {
1302
1360
  if (settled) return;
1303
1361
  settled = true;
1304
1362
  clearTimeout(timeoutTimer);
1305
1363
  if (killGrace) clearTimeout(killGrace);
1306
- if (finalDeadline) clearTimeout(finalDeadline);
1364
+ if (windowsFinalDeadline) clearTimeout(windowsFinalDeadline);
1365
+ if (groupPoll) clearTimeout(groupPoll);
1366
+ req.signal?.removeEventListener("abort", abortRun);
1307
1367
  for (const stream of [child.stdout, child.stderr]) {
1308
1368
  stream?.removeAllListeners("data");
1309
1369
  try {
@@ -1330,31 +1390,108 @@ async function executeAction(req) {
1330
1390
  }
1331
1391
  resolve6(code);
1332
1392
  };
1393
+ const scheduleGroupProbe = (delayMs, probe) => {
1394
+ if (settled) return;
1395
+ if (groupPoll) clearTimeout(groupPoll);
1396
+ groupPoll = setTimeout(() => {
1397
+ groupPoll = void 0;
1398
+ void probe();
1399
+ }, delayMs);
1400
+ groupPoll.unref?.();
1401
+ };
1402
+ let escalate = false;
1403
+ const awaitOwnedGroupExit = async () => {
1404
+ if (settled || typeof child.pid !== "number") return;
1405
+ const state = escalate ? await signalPosixGroup("SIGKILL") : await inspectPosixGroup(child.pid, launchId);
1406
+ if (settled) return;
1407
+ if (state === "gone") {
1408
+ settle(null);
1409
+ return;
1410
+ }
1411
+ scheduleGroupProbe(state === "unknown" ? 1e3 : 100, awaitOwnedGroupExit);
1412
+ };
1413
+ const signalPosixGroup = async (signal) => {
1414
+ if (typeof child.pid !== "number") return "gone";
1415
+ const state = await inspectPosixGroup(child.pid, launchId);
1416
+ if (settled || state !== "owned") return settled ? "gone" : state;
1417
+ try {
1418
+ process.kill(-child.pid, signal);
1419
+ } catch (error) {
1420
+ if (error.code === "ESRCH") return "gone";
1421
+ return "unknown";
1422
+ }
1423
+ return "owned";
1424
+ };
1425
+ const attemptPosixTerm = async () => {
1426
+ if (settled || termSent || termProbeRunning) return;
1427
+ termProbeRunning = true;
1428
+ const state = await signalPosixGroup("SIGTERM");
1429
+ termProbeRunning = false;
1430
+ if (settled) return;
1431
+ if (state === "gone") {
1432
+ settle(null);
1433
+ return;
1434
+ }
1435
+ if (state === "unknown") {
1436
+ scheduleGroupProbe(1e3, attemptPosixTerm);
1437
+ return;
1438
+ }
1439
+ termSent = true;
1440
+ killGrace = setTimeout(() => {
1441
+ if (settled) return;
1442
+ logWrite("[panel-actions] verifying ownership before SIGKILL\n");
1443
+ escalate = true;
1444
+ void awaitOwnedGroupExit();
1445
+ }, KILL_GRACE_MS);
1446
+ killGrace.unref?.();
1447
+ };
1448
+ const beginStop = (reason) => {
1449
+ if (stopping || settled) return;
1450
+ stopping = true;
1451
+ if (reason === "timeout") timedOut = true;
1452
+ else cancelled = true;
1453
+ logWrite(`[panel-actions] ${reason === "timeout" ? `timeout ${timeoutMs}ms exceeded` : "runtime retired"}; verifying ownership before SIGTERM
1454
+ `);
1455
+ if (process.platform === "win32") {
1456
+ void stopOwnedTree(child, "SIGTERM").then(() => {
1457
+ if (settled) return;
1458
+ killGrace = setTimeout(() => {
1459
+ if (settled) return;
1460
+ void stopOwnedTree(child, "SIGKILL").then(() => {
1461
+ windowsFinalDeadline = setTimeout(() => settle(null), 2e3);
1462
+ windowsFinalDeadline.unref?.();
1463
+ });
1464
+ }, KILL_GRACE_MS);
1465
+ killGrace.unref?.();
1466
+ });
1467
+ return;
1468
+ }
1469
+ void attemptPosixTerm();
1470
+ };
1471
+ const abortRun = () => beginStop("retirement");
1333
1472
  child.on("error", (error) => {
1334
1473
  logWrite(`[spawn error] ${error.message}
1335
1474
  `);
1336
1475
  settle(null);
1337
1476
  });
1338
- child.on("close", (code) => settle(code));
1339
- const timeoutTimer = setTimeout(() => {
1340
- timedOut = true;
1341
- logWrite(`[panel-actions] timeout ${timeoutMs}ms exceeded; SIGTERM to the tree
1342
- `);
1343
- void stopOwnedTree(child, "SIGTERM").then(() => {
1344
- if (settled) return;
1345
- killGrace = setTimeout(() => {
1346
- if (settled) return;
1347
- logWrite("[panel-actions] SIGKILL\n");
1348
- void stopOwnedTree(child, "SIGKILL");
1349
- finalDeadline = setTimeout(() => settle(null), 2e3);
1350
- finalDeadline.unref?.();
1351
- }, KILL_GRACE_MS);
1352
- killGrace.unref?.();
1353
- });
1354
- }, timeoutMs);
1477
+ child.on("close", (code) => {
1478
+ if (!stopping && !cancelled) settle(code);
1479
+ else if (cancelled && !stopping && process.platform !== "win32") void awaitOwnedGroupExit();
1480
+ else if (process.platform === "win32") settle(code);
1481
+ else {
1482
+ if (termSent) void awaitOwnedGroupExit();
1483
+ else void attemptPosixTerm();
1484
+ }
1485
+ });
1486
+ const timeoutTimer = setTimeout(() => beginStop("timeout"), timeoutMs);
1355
1487
  timeoutTimer.unref?.();
1356
- if (cancelled) {
1357
- const cancelDeadline = setTimeout(() => settle(null), 3e3);
1488
+ if (req.signal?.aborted) abortRun();
1489
+ else req.signal?.addEventListener("abort", abortRun, { once: true });
1490
+ if (cancelled && !req.signal?.aborted) {
1491
+ const cancelDeadline = setTimeout(() => {
1492
+ if (process.platform === "win32") settle(null);
1493
+ else void awaitOwnedGroupExit();
1494
+ }, 3e3);
1358
1495
  cancelDeadline.unref?.();
1359
1496
  }
1360
1497
  });
@@ -1401,7 +1538,7 @@ function parsePanelCommand(text) {
1401
1538
  rest = next?.[2] ?? "";
1402
1539
  }
1403
1540
  if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.models" && cmd !== "panel.context" && cmd !== "panel.compact" && cmd !== "panel.upgrade" && cmd !== "panel.upgrade.confirm" && cmd !== "panel.help" && cmd !== "panel.actions" && cmd !== "\u9762\u677F") {
1404
- if (!/^panel\.model\.[A-Za-z0-9-]+\..+$/.test(cmd) && !/^panel\.(context|compact)\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.worker\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.action\.[a-z0-9][a-z0-9-]{0,31}$/.test(cmd)) return void 0;
1541
+ if (!/^panel\.model\.[A-Za-z0-9-]+\..+$/.test(cmd) && !/^panel\.(context|compact)\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.peek(?:\.refresh)?\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.worker\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.action\.[a-z0-9][a-z0-9-]{0,31}$/.test(cmd)) return void 0;
1405
1542
  }
1406
1543
  const leadingFlag = /^--restricted(?:\s+|$)/.exec(rest);
1407
1544
  const restricted = leadingFlag !== null;
@@ -1449,6 +1586,8 @@ function scanPeers() {
1449
1586
  sessionId: parsed.sessionId,
1450
1587
  state: typeof parsed.state === "string" ? parsed.state : "?",
1451
1588
  unattended: parsed.unattended === true,
1589
+ sessionControls: parsed.sessionControls === true,
1590
+ workerPeek: parsed.workerPeek === true,
1452
1591
  sessionTitle: typeof parsed.displaySessionName === "string" && parsed.displaySessionName.trim() ? parsed.displaySessionName.trim() : void 0,
1453
1592
  project: typeof parsed.cwd === "string" && parsed.cwd ? parsed.cwd.split("/").filter(Boolean).at(-1) : void 0,
1454
1593
  cwd: typeof parsed.cwd === "string" && parsed.cwd ? parsed.cwd : void 0,
@@ -1579,7 +1718,7 @@ ${rows.join("\n")}` : "_No live pie sessions_",
1579
1718
  }, patchOrigin: false };
1580
1719
  }
1581
1720
  if (input.cmd === "panel.context") {
1582
- const peers = scanPeers();
1721
+ const peers = scanPeers().filter((p) => p.sessionControls);
1583
1722
  const rows = peers.map((p) => `| ${p.sessionTitle ?? p.name} | ${p.model ?? "\u2014"} | ${p.state} |`);
1584
1723
  const actions = peers.map((p) => ({ id: `panel.context.${p.instanceId}`, label: `\u{1F4CA} ${p.name.slice(0, 12)}` })).slice(0, 18);
1585
1724
  return { spec: {
@@ -1589,15 +1728,15 @@ ${rows.join("\n")}` : "_No live pie sessions_",
1589
1728
  body: [
1590
1729
  peers.length > 0 ? `| Session | Model | State |
1591
1730
  |---|---|---|
1592
- ${rows.join("\n")}` : "_No live pie sessions_",
1731
+ ${rows.join("\n")}` : "_No live sessions advertise this control_",
1593
1732
  ``,
1594
- "Each button asks the target host for its context ESTIMATE (same figures the TUI /debugs/context report shows). TUI sessions may not support this control yet."
1733
+ "Each button asks the target host for its context ESTIMATE (same figures the TUI /debugs/context report shows). Only sessions advertising this control are listed."
1595
1734
  ].join("\n"),
1596
1735
  actions: actions.length > 0 ? actions : [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
1597
1736
  }, patchOrigin: false };
1598
1737
  }
1599
1738
  if (input.cmd === "panel.compact") {
1600
- const peers = scanPeers();
1739
+ const peers = scanPeers().filter((p) => p.sessionControls);
1601
1740
  const rows = peers.map((p) => `| ${p.sessionTitle ?? p.name} | ${p.model ?? "\u2014"} | ${p.state} |`);
1602
1741
  const actions = peers.map((p) => ({ id: `panel.compact.${p.instanceId}`, label: `\u{1F9F9} ${p.name.slice(0, 12)}`, requireAllowUsers: true })).slice(0, 18);
1603
1742
  return { spec: {
@@ -1607,7 +1746,7 @@ ${rows.join("\n")}` : "_No live pie sessions_",
1607
1746
  body: [
1608
1747
  peers.length > 0 ? `| Session | Model | State |
1609
1748
  |---|---|---|
1610
- ${rows.join("\n")}` : "_No live pie sessions_",
1749
+ ${rows.join("\n")}` : "_No live sessions advertise this control_",
1611
1750
  ``,
1612
1751
  "Compaction summarizes the session's history and keeps a retained tail. It runs on the target host through the same pipeline as /sessions/compact. **Refused while the session is working or has queued input** \u2014 retry when idle. The confirm requires allowUsers membership."
1613
1752
  ].join("\n"),
@@ -1657,6 +1796,14 @@ ${rows.join("\n")}` : '_No custom actions yet \u2014 ask the manager to build on
1657
1796
  }
1658
1797
  const wActions = workerActions(peer.name);
1659
1798
  const workerCtx = { worker: { name: peer.name, ref: peer.instanceId } };
1799
+ const peekCtx = { peek: { ref: peer.instanceId, session: peer.sessionId } };
1800
+ const fixedActions = [
1801
+ ...peer.workerPeek ? [{ id: `panel.peek.${peer.instanceId}`, label: "\u{1F440} Peek", payload: peekCtx }] : [],
1802
+ ...peer.sessionControls ? [
1803
+ { id: `panel.context.${peer.instanceId}`, label: "\u{1F4CA} Context" },
1804
+ { id: `panel.compact.${peer.instanceId}`, label: "\u{1F9F9} Compact", requireAllowUsers: true }
1805
+ ] : []
1806
+ ];
1660
1807
  const title = peer.sessionTitle ?? peer.name;
1661
1808
  const state = peer.state === "working" && peer.currentTool ? `working\xB7${peer.currentTool}` : peer.state;
1662
1809
  return { spec: {
@@ -1680,12 +1827,12 @@ ${wActions.map((a) => `| ${a.label} | ${a.runs} | ${a.lastRunBy ?? "\u2014"} |`)
1680
1827
  _\u6309\u94AE\u53D6\u524D 15 \u4E2A\u6700\u5E38\u7528\u7684\uFF1B\u5176\u4F59\u53EF\u590D\u5236\u547D\u4EE4\u89E6\u53D1\uFF08\u5E26\u7CBE\u786E worker \u5730\u5740\uFF09\uFF1A_
1681
1828
  ${wActions.slice(15).map((a) => `\`/card panel.action.${a.id} ${JSON.stringify({ worker: { ref: peer.instanceId } })}\``).join("\n")}` : ""}` : "_No worker actions yet \u2014 generic actions (scope=worker) appear on every worker card_"
1682
1829
  ].join("\n"),
1830
+ // Variable actions yield to fixed controls; Back is always slot 18.
1683
1831
  actions: [
1684
- { id: `panel.context.${peer.instanceId}`, label: "\u{1F4CA} Context" },
1685
- { id: `panel.compact.${peer.instanceId}`, label: "\u{1F9F9} Compact", requireAllowUsers: true },
1686
- ...wActions.slice(0, 15).map((a) => ({ id: `panel.action.${a.id}`, label: a.label.slice(0, 20), payload: workerCtx })),
1832
+ ...fixedActions,
1833
+ ...wActions.slice(0, Math.max(0, 17 - fixedActions.length)).map((a) => ({ id: `panel.action.${a.id}`, label: a.label.slice(0, 20), payload: workerCtx })),
1687
1834
  { id: "panel.summon", label: "\u21A9\uFE0F Back" }
1688
- ].slice(0, 18)
1835
+ ]
1689
1836
  }, patchOrigin: false };
1690
1837
  }
1691
1838
  if (input.cmd === "panel.upgrade") {
@@ -2027,8 +2174,12 @@ function liveManagerForBinding(binding) {
2027
2174
  }
2028
2175
  return false;
2029
2176
  }
2030
- async function applyPeerControl(peerRef, control, payload) {
2031
- const net2 = await import("node:net");
2177
+ async function applyPeerControl(peerRef, control, payload, expected) {
2178
+ const runtime = currentIpcRuntime(ipcDiscoveryRoot2());
2179
+ if (runtime) return runtime.sendBoundControl(peerRef, control, payload, expected, 6e3);
2180
+ return applyPeerControlDirect(peerRef, control, payload, expected);
2181
+ }
2182
+ async function applyPeerControlDirect(peerRef, control, payload, expected) {
2032
2183
  let target;
2033
2184
  try {
2034
2185
  const dir = ipcDiscoveryRoot2();
@@ -2048,54 +2199,71 @@ async function applyPeerControl(peerRef, control, payload) {
2048
2199
  } catch {
2049
2200
  }
2050
2201
  if (!target) return { ok: false, detail: `Session not found: ${peerRef}` };
2051
- const envelope = signEnvelope({
2052
- v: IPC_PROTOCOL_VERSION,
2053
- id: `panel-${control.replace(/\./g, "")}-${crypto.randomUUID()}`,
2054
- from: "pie-panel0000000",
2055
- to: target.instanceId,
2056
- kind: "control",
2057
- sessionId: target.sessionId,
2058
- createdAt: Date.now(),
2059
- text: JSON.stringify({ control, payload })
2060
- }, target.secret);
2061
- return await new Promise((resolve6) => {
2062
- let settled = false;
2063
- const finish = (ok, detail) => {
2064
- if (settled) return;
2065
- settled = true;
2066
- try {
2067
- sock.destroy();
2068
- } catch {
2069
- }
2070
- resolve6({ ok, detail });
2071
- };
2072
- const sock = net2.connect({ host: "127.0.0.1", port: target.port }, () => {
2073
- sock.write(JSON.stringify(envelope) + "\n");
2074
- });
2075
- sock.setTimeout(6e3, () => finish(false, "Peer gave no receipt within 6s (it may be restarting; the control frame is idempotent \u2014 resending is safe)"));
2076
- sock.on("error", (error) => finish(false, `Connection failed: ${error instanceof Error ? error.message : String(error)}`));
2077
- sock.on("close", () => {
2078
- if (!settled) finish(false, "Peer closed the connection (policy refusal or rejected frame; resending is safe)");
2079
- });
2080
- sock.on("data", (buffer) => {
2081
- for (const line of buffer.toString("utf8").split("\n")) {
2082
- if (!line.trim()) continue;
2083
- try {
2084
- const parsed = JSON.parse(line);
2085
- if (parsed.kind === "ack" || parsed.kind === "result") {
2086
- const refused = /"ok"\s*:\s*false|error|拒绝|invalid|unknown|refus|denied/i.test(parsed.text ?? "");
2087
- finish(!refused, `Peer receipt: ${parsed.text ?? "(empty)"}`);
2088
- return;
2089
- }
2090
- } catch {
2091
- }
2092
- }
2202
+ if (expected && (target.instanceId !== expected.instanceId || target.sessionId !== expected.sessionId)) {
2203
+ return { ok: false, detail: `Target session changed: ${peerRef} now serves ${target.sessionId}` };
2204
+ }
2205
+ const peer = target;
2206
+ const client = new IpcTransport({ instanceId: "pie-panel0000000", resolveSecret: () => peer.secret, onEnvelope() {
2207
+ } });
2208
+ try {
2209
+ const reply = await client.send(peer.instanceId, peer.port, "control", {
2210
+ sessionId: peer.sessionId,
2211
+ text: JSON.stringify({ control, payload }),
2212
+ awaitAck: true,
2213
+ waitMs: 6e3,
2214
+ replyKinds: /* @__PURE__ */ new Set(["ack"])
2093
2215
  });
2094
- });
2216
+ if (reply?.text) {
2217
+ const ack = JSON.parse(reply.text);
2218
+ if (typeof ack?.ok === "boolean") return { ok: ack.ok, detail: `Peer receipt: ${reply.text}` };
2219
+ }
2220
+ } catch {
2221
+ } finally {
2222
+ client.close();
2223
+ }
2224
+ return { ok: false, unknown: true, detail: "No verified receipt. The request may already have been applied." };
2095
2225
  }
2096
2226
  async function applyModelControl(peerRef, model) {
2097
2227
  return applyPeerControl(peerRef, "model.set", { model });
2098
2228
  }
2229
+ function renderPeekReceipt(peer, receipt) {
2230
+ if (!receipt.ok) return receipt.unknown ? `\u26A0\uFE0F ${peer}
2231
+
2232
+ No verified live response. The worker may still be healthy or busy; silence/timeout is not evidence that it is dead.` : `\u26A0\uFE0F ${peer}
2233
+
2234
+ ${receipt.detail}`;
2235
+ try {
2236
+ const ack = JSON.parse(receipt.detail.slice(receipt.detail.indexOf("{")));
2237
+ if (ack.ok !== true || typeof ack.message !== "string") throw new Error("bad ack");
2238
+ const report = JSON.parse(ack.message);
2239
+ const now = Date.now();
2240
+ const age = (at) => {
2241
+ if (typeof at !== "number" || !Number.isFinite(at)) return "age unknown";
2242
+ const seconds = Math.max(0, Math.floor((now - at) / 1e3));
2243
+ if (seconds < 2) return "now";
2244
+ if (seconds < 60) return `${seconds}s ago`;
2245
+ const minutes = Math.floor(seconds / 60);
2246
+ return minutes < 60 ? `${minutes}m ago` : `${Math.floor(minutes / 60)}h ago`;
2247
+ };
2248
+ const items = Array.isArray(report.items) ? report.items.filter((i) => (i.kind === "assistant" || i.kind === "tool") && typeof i.text === "string") : [];
2249
+ const live = items.map((i) => i.kind === "tool" ? `- \u{1F527} ${age(i.at)} \xB7 ${i.text}` : `**Assistant activity \xB7 ${age(i.at)}**
2250
+ ${i.text}`).join("\n\n");
2251
+ const last = typeof report.lastVisible?.text === "string" ? report.lastVisible.text : "";
2252
+ const repeatedIdleLast = !report.active && !!last && items.some((i) => i.kind === "assistant" && i.text === last);
2253
+ return [
2254
+ `**Live response:** ${report.active ? "working" : "idle"} \xB7 snapshot ${age(report.generatedAt)}${typeof report.turn === "number" ? ` \xB7 turn #${report.turn}` : ""}${report.startedAt ? ` started ${age(report.startedAt)}` : ""}`,
2255
+ live || "_(No user-displayable progress in the current/recent turn.)_",
2256
+ ...repeatedIdleLast ? [] : [`---
2257
+ **Last visible assistant output \xB7 ${age(report.lastVisible?.at)}:**
2258
+ ${last || "_(none captured in memory for this session)_"}`],
2259
+ "_Live authenticated snapshot; memory-only. No reasoning, tool arguments/results, or disk logs._"
2260
+ ].join("\n\n");
2261
+ } catch {
2262
+ return `\u26A0\uFE0F ${peer}
2263
+
2264
+ Malformed verified Peek response.`;
2265
+ }
2266
+ }
2099
2267
  function renderContextReceipt(peer, receipt) {
2100
2268
  if (!receipt.ok) return `\u26A0\uFE0F ${peer}
2101
2269
 
@@ -2131,6 +2299,10 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
2131
2299
  const key = (id) => JSON.stringify([cfg.provider, id]);
2132
2300
  const isManager = cfg.unattended === true && process.env.PIE_PROC_CURATED_NAME === "manager";
2133
2301
  const scopes = /* @__PURE__ */ new Set();
2302
+ const panelActionControllers = /* @__PURE__ */ new Set();
2303
+ const panelActionTasks = /* @__PURE__ */ new Set();
2304
+ let actionDeliveryOpen = true;
2305
+ const ACTION_RETIRE_DRAIN_MS = 7e3;
2134
2306
  let forwardingEnabled = cfg.enabled === true;
2135
2307
  let configurationFailed = false;
2136
2308
  function isForwardingEnabled() {
@@ -2928,6 +3100,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
2928
3100
  ctx.on("session:changed", (event) => {
2929
3101
  inputEpoch++;
2930
3102
  currentSessionId = event.sessionId;
3103
+ issuedWorkerCards.clear();
3104
+ peekCards.clear();
2931
3105
  if (event.sessionId) resolveSessionAnchor(event.sessionId);
2932
3106
  if (event.sessionId && !consumer && !consumerRecovering && !restartTimer && !terminated && !suspended) {
2933
3107
  ctx.log("im-forward: session bound, starting event consumer");
@@ -3006,6 +3180,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
3006
3180
  }
3007
3181
  }
3008
3182
  const panelCardOwners = /* @__PURE__ */ new Map();
3183
+ const peekCards = /* @__PURE__ */ new Map();
3184
+ const issuedWorkerCards = /* @__PURE__ */ new Map();
3009
3185
  const rememberPanelCard = (messageId, sessionId, chatId) => {
3010
3186
  if (!messageId) return;
3011
3187
  panelCardOwners.set(messageId, { sessionId, epoch: inputEpoch, chatId });
@@ -3014,13 +3190,15 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
3014
3190
  for (const k of oldest) panelCardOwners.delete(k);
3015
3191
  }
3016
3192
  };
3193
+ const peekAudienceIsDirect = (event) => event.chatType === "p2p" && (cfg.targetKind === "user" ? event.sender_id === cfg.targetId : event.chat_id === cfg.targetId) && (!cfg.allowUsers || !!event.sender_id && cfg.allowUsers.includes(event.sender_id));
3017
3194
  const runPanelCommand = async (panelCmd, event, sessionId, isCurrent) => {
3018
3195
  if (!isCurrent()) return;
3019
3196
  const started = Date.now();
3197
+ const freshRecipient = cfg.targetKind === "user" ? cfg.targetId : event.chat_id;
3020
3198
  if (panelCmd.restricted && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id))) {
3021
3199
  ctx.log(`im-forward: restricted panel action ${panelCmd.cmd} refused for ${event.sender_id ?? "unknown"} (not in allowUsers)`);
3022
3200
  try {
3023
- await connection.send(event.chat_id, "\u26D4\uFE0F This action requires admin rights (allowUsers).", `panel-refused-${event.event_id}`);
3201
+ await connection.send(freshRecipient, "\u26D4\uFE0F This action requires admin rights (allowUsers).", `panel-refused-${event.event_id}`);
3024
3202
  } catch {
3025
3203
  }
3026
3204
  return;
@@ -3039,14 +3217,79 @@ ${receipt.detail}`,
3039
3217
  };
3040
3218
  try {
3041
3219
  if (connection.sendCard) {
3042
- const sent = await connection.sendCard(event.chat_id, spec, `panel-model-${event.event_id}`);
3220
+ const sent = await connection.sendCard(freshRecipient, spec, `panel-model-${event.event_id}`);
3043
3221
  if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
3044
- } else await connection.send(event.chat_id, `**${spec.title}**
3222
+ } else await connection.send(freshRecipient, `**${spec.title}**
3045
3223
  ${spec.body}`, `panel-model-${event.event_id}`);
3046
3224
  } catch {
3047
3225
  }
3048
3226
  return;
3049
3227
  }
3228
+ const peekAction = /^panel\.peek(\.refresh)?\.([A-Za-z0-9-]+)$/.exec(panelCmd.cmd);
3229
+ if (peekAction) {
3230
+ const refresh = peekAction[1] === ".refresh";
3231
+ const ref = peekAction[2];
3232
+ const canReadSensitive = peekAudienceIsDirect(event);
3233
+ const peekRecipient = freshRecipient;
3234
+ const patchOnly = async (messageId, spec) => {
3235
+ if (!messageId || !connection.patch) {
3236
+ ctx.log("im-forward: Peek patch unavailable; no fallback send");
3237
+ return;
3238
+ }
3239
+ try {
3240
+ await connection.patch(messageId, spec);
3241
+ } catch {
3242
+ }
3243
+ };
3244
+ if (refresh) {
3245
+ const cardId = event.message_id;
3246
+ const binding2 = cardId ? peekCards.get(cardId) : void 0;
3247
+ const bindingMatches = () => !!cardId && !!binding2 && peekCards.get(cardId) === binding2 && binding2.ref === ref && binding2.chatId === event.chat_id && binding2.senderId === event.sender_id && binding2.ownerSession === currentSessionId && binding2.epoch === inputEpoch && isCurrent();
3248
+ if (!binding2 || !bindingMatches() || !canReadSensitive) return;
3249
+ const verifiedBinding = binding2;
3250
+ const run = verifiedBinding.chain.then(async () => {
3251
+ const receipt = await applyPeerControl(verifiedBinding.ref, "session.peek", {}, { instanceId: verifiedBinding.ref, sessionId: verifiedBinding.targetSession });
3252
+ if (!bindingMatches()) return;
3253
+ const spec = { title: "\u{1F440} Worker Peek", color: receipt.ok ? "green" : "red", body: renderPeekReceipt(verifiedBinding.ref, receipt), actions: [{ id: `panel.peek.refresh.${verifiedBinding.ref}`, label: "\u{1F504} Refresh", payload: { peek: { ref: verifiedBinding.ref, session: verifiedBinding.targetSession } } }, { id: "panel.summon", label: "\u21A9\uFE0F Back" }] };
3254
+ await patchOnly(cardId, spec);
3255
+ });
3256
+ verifiedBinding.chain = run.catch(() => void 0);
3257
+ await run;
3258
+ return;
3259
+ }
3260
+ if (!canReadSensitive) {
3261
+ const denied = { title: "Peek unavailable", color: "red", body: "\u26D4\uFE0F Peek is limited to the configured authorized direct-message audience. Group audience privacy cannot be proven.", actions: [{ id: "panel.summon", label: "\u21A9\uFE0F Back" }] };
3262
+ if (connection.sendCard) {
3263
+ const sent2 = await connection.sendCard(peekRecipient, denied, `panel-peek-denied-${event.event_id}`);
3264
+ if (isCurrent()) rememberPanelCard(sent2?.messageId, sessionId, event.chat_id);
3265
+ }
3266
+ return;
3267
+ }
3268
+ const wire = isRecord(panelCmd.payload) && isRecord(panelCmd.payload.peek) ? panelCmd.payload.peek : void 0;
3269
+ const issuedRef = wire && typeof wire.ref === "string" ? wire.ref : void 0;
3270
+ const issuedSession = wire && typeof wire.session === "string" ? wire.session : void 0;
3271
+ const issuedCard = event.message_id ? issuedWorkerCards.get(event.message_id) : void 0;
3272
+ if (!issuedCard || issuedCard.chatId !== event.chat_id || issuedCard.ref !== ref || issuedCard.targetSession !== issuedSession || issuedRef !== ref || !issuedSession) {
3273
+ if (connection.sendCard) await connection.sendCard(peekRecipient, { title: "Peek refused", color: "red", body: "Missing or forged worker/session binding. Reopen the worker from /panel.", actions: [{ id: "panel.summon", label: "\u21A9\uFE0F Back" }] }, `panel-peek-refused-${event.event_id}`);
3274
+ return;
3275
+ }
3276
+ if (!isCurrent() || !connection.sendCard) return;
3277
+ const sent = await connection.sendCard(peekRecipient, { title: "\u{1F440} Worker Peek", color: "blue", body: "Requesting a live authenticated snapshot\u2026", actions: [] }, `panel-peek-${event.event_id}`);
3278
+ if (!sent?.messageId || !isCurrent()) return;
3279
+ rememberPanelCard(sent.messageId, sessionId, event.chat_id);
3280
+ const binding = { ref, targetSession: issuedSession, chatId: event.chat_id, ...event.sender_id ? { senderId: event.sender_id } : {}, ownerSession: sessionId, epoch: inputEpoch, chain: Promise.resolve() };
3281
+ peekCards.set(sent.messageId, binding);
3282
+ if (peekCards.size > 100) for (const old of [...peekCards.keys()].slice(0, 25)) peekCards.delete(old);
3283
+ const initial = (async () => {
3284
+ const receipt = await applyPeerControl(ref, "session.peek", {}, { instanceId: ref, sessionId: issuedSession });
3285
+ if (!isCurrent() || inputEpoch !== binding.epoch || currentSessionId !== binding.ownerSession || peekCards.get(sent.messageId) !== binding) return;
3286
+ const spec = { title: "\u{1F440} Worker Peek", color: receipt.ok ? "green" : "red", body: renderPeekReceipt(ref, receipt), actions: [{ id: `panel.peek.refresh.${ref}`, label: "\u{1F504} Refresh", payload: { peek: { ref, session: issuedSession } } }, { id: "panel.summon", label: "\u21A9\uFE0F Back" }] };
3287
+ await patchOnly(sent.messageId, spec);
3288
+ })();
3289
+ binding.chain = initial.catch(() => void 0);
3290
+ await initial;
3291
+ return;
3292
+ }
3050
3293
  const contextAction = /^panel\.context\.([A-Za-z0-9-]+)$/.exec(panelCmd.cmd);
3051
3294
  if (contextAction) {
3052
3295
  const receipt = await applyPeerControl(contextAction[1], "session.context", {});
@@ -3058,9 +3301,9 @@ ${spec.body}`, `panel-model-${event.event_id}`);
3058
3301
  };
3059
3302
  try {
3060
3303
  if (connection.sendCard) {
3061
- const sent = await connection.sendCard(event.chat_id, spec, `panel-context-${event.event_id}`);
3304
+ const sent = await connection.sendCard(freshRecipient, spec, `panel-context-${event.event_id}`);
3062
3305
  if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
3063
- } else await connection.send(event.chat_id, `**${spec.title}**
3306
+ } else await connection.send(freshRecipient, `**${spec.title}**
3064
3307
  ${spec.body}`, `panel-context-${event.event_id}`);
3065
3308
  } catch {
3066
3309
  }
@@ -3071,7 +3314,7 @@ ${spec.body}`, `panel-context-${event.event_id}`);
3071
3314
  if (!cfg.allowUsers || !event.sender_id || !cfg.allowUsers.includes(event.sender_id)) {
3072
3315
  ctx.log(`im-forward: panel.compact refused for ${event.sender_id ?? "unknown"} (execution-sink gate: allowUsers membership required)`);
3073
3316
  try {
3074
- await connection.send(event.chat_id, "\u26D4\uFE0F Compacting a session requires admin rights (allowUsers).", `panel-refused-${event.event_id}`);
3317
+ await connection.send(freshRecipient, "\u26D4\uFE0F Compacting a session requires admin rights (allowUsers).", `panel-refused-${event.event_id}`);
3075
3318
  } catch {
3076
3319
  }
3077
3320
  return;
@@ -3079,12 +3322,12 @@ ${spec.body}`, `panel-context-${event.event_id}`);
3079
3322
  const receipt = await applyPeerControl(compactAction[1], "session.compact", {});
3080
3323
  if (!isCurrent()) return;
3081
3324
  const spec = {
3082
- title: receipt.ok ? "Compaction Submitted" : "Compaction Refused",
3325
+ title: receipt.ok ? "Compaction Submitted" : receipt.unknown ? "Compaction Status Unknown" : "Compaction Refused",
3083
3326
  body: `${receipt.ok ? "\u{1F9F9}" : "\u26A0\uFE0F"} ${compactAction[1]}
3084
3327
 
3085
3328
  ${receipt.detail}
3086
3329
 
3087
- ${receipt.ok ? "Compaction runs on the target host (LLM summary \u2014 may take a minute). Tap \u{1F4CA} Check context afterwards: the Last compact row shows the committed/failed outcome." : "Retry when the session is idle, or pick a different session."}`,
3330
+ ${receipt.ok ? "Compaction runs on the target host (LLM summary \u2014 may take a minute). Tap \u{1F4CA} Check context afterwards: the Last compact row shows the committed/failed outcome." : receipt.unknown ? "Check context before submitting again." : "Check the refusal reason before trying again."}`,
3088
3331
  actions: [
3089
3332
  { id: `panel.context.${compactAction[1]}`, label: "\u{1F4CA} Check context" },
3090
3333
  { id: "panel.compact", label: "\u21A9\uFE0F Back to compact list" }
@@ -3092,9 +3335,9 @@ ${receipt.ok ? "Compaction runs on the target host (LLM summary \u2014 may take
3092
3335
  };
3093
3336
  try {
3094
3337
  if (connection.sendCard) {
3095
- const sent = await connection.sendCard(event.chat_id, spec, `panel-compact-${event.event_id}`);
3338
+ const sent = await connection.sendCard(freshRecipient, spec, `panel-compact-${event.event_id}`);
3096
3339
  if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
3097
- } else await connection.send(event.chat_id, `**${spec.title}**
3340
+ } else await connection.send(freshRecipient, `**${spec.title}**
3098
3341
  ${spec.body}`, `panel-compact-${event.event_id}`);
3099
3342
  } catch {
3100
3343
  }
@@ -3104,7 +3347,7 @@ ${spec.body}`, `panel-compact-${event.event_id}`);
3104
3347
  if (!cfg.allowUsers || !event.sender_id || !cfg.allowUsers.includes(event.sender_id)) {
3105
3348
  ctx.log(`im-forward: panel.upgrade.confirm refused for ${event.sender_id ?? "unknown"} (execution-sink gate: allowUsers membership required)`);
3106
3349
  try {
3107
- await connection.send(event.chat_id, "\u26D4\uFE0F Upgrading pie requires admin rights (allowUsers).", `panel-refused-${event.event_id}`);
3350
+ await connection.send(freshRecipient, "\u26D4\uFE0F Upgrading pie requires admin rights (allowUsers).", `panel-refused-${event.event_id}`);
3108
3351
  } catch {
3109
3352
  }
3110
3353
  return;
@@ -3175,9 +3418,9 @@ IM pauses briefly during the restart; tap \u{1F504} Refresh afterwards \u2014 th
3175
3418
  };
3176
3419
  try {
3177
3420
  if (connection.sendCard) {
3178
- const sent = await connection.sendCard(event.chat_id, spec, `panel-upgrade-${event.event_id}`);
3421
+ const sent = await connection.sendCard(freshRecipient, spec, `panel-upgrade-${event.event_id}`);
3179
3422
  if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
3180
- } else await connection.send(event.chat_id, `**${spec.title}**
3423
+ } else await connection.send(freshRecipient, `**${spec.title}**
3181
3424
  ${spec.body}`, `panel-upgrade-${event.event_id}`);
3182
3425
  } catch {
3183
3426
  }
@@ -3187,16 +3430,17 @@ ${spec.body}`, `panel-upgrade-${event.event_id}`);
3187
3430
  if (actionMatch) {
3188
3431
  const actionId = actionMatch[1];
3189
3432
  const runtimeAlive = () => !terminated;
3433
+ const actionCanDeliver = () => actionDeliveryOpen;
3190
3434
  const sendActionCard = async (spec, key2, guard) => {
3191
3435
  if (!guard()) return void 0;
3192
3436
  try {
3193
3437
  if (connection.sendCard) {
3194
- const sent = await connection.sendCard(event.chat_id, spec, key2);
3438
+ const sent = await connection.sendCard(freshRecipient, spec, key2);
3195
3439
  if (guard()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
3196
3440
  return sent?.messageId;
3197
3441
  }
3198
- await connection.send(event.chat_id, `**${spec.title ?? "Action"}**
3199
- ${spec.body}`, key2);
3442
+ return (await connection.send(freshRecipient, `**${spec.title ?? "Action"}**
3443
+ ${spec.body}`, key2))?.messageId;
3200
3444
  } catch {
3201
3445
  }
3202
3446
  return void 0;
@@ -3264,25 +3508,31 @@ ${spec.body}`, key2);
3264
3508
  }
3265
3509
  const timeoutS = Math.round((action.timeoutMs ?? DEFAULT_TIMEOUT_MS) / 1e3);
3266
3510
  let ackMessageId;
3267
- const publishCancellation = async (body) => {
3268
- if (!runtimeAlive()) return;
3269
- const cancelSpec = {
3270
- title: `\u26A0\uFE0F ${action.label}`,
3271
- color: "red",
3272
- body,
3273
- actions: [{ id: `panel.action.${actionId}`, label: "\u{1F501} \u91CD\u8BD5", ...workerCtx ? { payload: { worker: { name: workerCtx.name, ...workerCtx.ref ? { ref: workerCtx.ref } : {} } } } : {} }, { id: "panel.summon", label: "\u21A9\uFE0F \u9762\u677F" }]
3274
- };
3275
- let patched = false;
3276
- if (ackMessageId && connection.patch) {
3511
+ const publishTerminal = async (spec, key2) => {
3512
+ if (!actionCanDeliver()) return;
3513
+ if (ackMessageId && connection.sendCard && connection.patch) {
3277
3514
  try {
3278
- patched = await connection.patch(ackMessageId, cancelSpec);
3515
+ if (await connection.patch(ackMessageId, spec)) return;
3279
3516
  } catch {
3280
- patched = false;
3281
3517
  }
3282
3518
  }
3283
- if (!patched) await sendActionCard(cancelSpec, `panel-action-cancel-${event.event_id}`, runtimeAlive);
3519
+ await sendActionCard(spec, key2, actionCanDeliver);
3284
3520
  };
3285
- try {
3521
+ const publishCancellation = (body) => publishTerminal({
3522
+ title: `\u26A0\uFE0F ${action.label}`,
3523
+ color: "red",
3524
+ body,
3525
+ actions: [{ id: `panel.action.${actionId}`, label: "\u{1F501} \u91CD\u8BD5", ...workerCtx ? { payload: { worker: { name: workerCtx.name, ...workerCtx.ref ? { ref: workerCtx.ref } : {} } } } : {} }, { id: "panel.summon", label: "\u21A9\uFE0F \u9762\u677F" }]
3526
+ }, `panel-action-cancel-${event.event_id}`);
3527
+ if (!runtimeAlive() || !isCurrent()) {
3528
+ lock.release();
3529
+ return;
3530
+ }
3531
+ const actionAbort = new AbortController();
3532
+ panelActionControllers.add(actionAbort);
3533
+ actionAbort.signal.addEventListener("abort", lock.release, { once: true });
3534
+ const initialAck = Promise.resolve().then(async () => {
3535
+ if (!runtimeAlive() || !isCurrent()) return false;
3286
3536
  ackMessageId = await sendActionCard({
3287
3537
  title: `\u{1F680} ${action.label}`,
3288
3538
  color: "blue",
@@ -3291,27 +3541,17 @@ ${spec.body}`, key2);
3291
3541
  \u5B8C\u6210\u540E\u672C\u5361\u81EA\u52A8\u66F4\u65B0\u4E3A\u7ED3\u679C\u3002`,
3292
3542
  actions: []
3293
3543
  }, `panel-action-${event.event_id}`, isCurrent);
3294
- if (!runtimeAlive()) {
3295
- lock.release();
3296
- return;
3297
- }
3298
- if (!lock.stillOwned()) {
3299
- await publishCancellation("\u786E\u8BA4\u5361\u53D1\u9001\u8017\u65F6\u8D85\u8FC7\u4E86\u6267\u884C\u69FD\u7684\u5B58\u6D3B\u671F\u9650\uFF0C\u672C\u6B21\u89E6\u53D1\u5DF2\u53D6\u6D88\uFF08\u672A\u6267\u884C\uFF09\u3002\u8BF7\u91CD\u8BD5\u3002");
3300
- lock.release();
3301
- return;
3302
- }
3303
- } catch (error) {
3304
- lock.release();
3305
- ctx.log(`im-forward: panel action ${actionId} ack failed: ${error instanceof Error ? error.message : String(error)}`);
3306
- return;
3307
- }
3308
- if (!lock.stillOwned()) {
3309
- await publishCancellation("\u6267\u884C\u69FD\u5728\u542F\u52A8\u524D\u6613\u4E3B\uFF0C\u672C\u6B21\u89E6\u53D1\u5DF2\u53D6\u6D88\uFF08\u672A\u6267\u884C\uFF09\u3002\u8BF7\u91CD\u8BD5\u3002");
3310
- lock.release();
3311
- return;
3312
- }
3313
- void (async () => {
3544
+ return true;
3545
+ });
3546
+ const actionTask = (async () => {
3314
3547
  try {
3548
+ if (!await initialAck) return;
3549
+ if (actionAbort.signal.aborted) {
3550
+ if (ackMessageId) await publishCancellation("\u8FD0\u884C\u65F6\u5DF2\u9000\u51FA\uFF0C\u672C\u6B21\u64CD\u4F5C\u672A\u6267\u884C\u3002");
3551
+ else ctx.log(`im-forward: panel action ${actionId} retired with no initial card receipt; script not started`);
3552
+ return;
3553
+ }
3554
+ actionAbort.signal.removeEventListener("abort", lock.release);
3315
3555
  if (!lock.rearm(action.timeoutMs ?? DEFAULT_TIMEOUT_MS)) {
3316
3556
  await publishCancellation("\u6267\u884C\u69FD\u5728\u542F\u52A8\u524D\u6613\u4E3B\uFF0C\u672C\u6B21\u89E6\u53D1\u5DF2\u53D6\u6D88\uFF08\u672A\u6267\u884C\uFF09\u3002\u8BF7\u91CD\u8BD5\u3002");
3317
3557
  return;
@@ -3322,7 +3562,8 @@ ${spec.body}`, key2);
3322
3562
  trigger: { name: triggerQuick, ...triggerOpenId ? { openId: triggerOpenId } : {} },
3323
3563
  chatId: event.chat_id,
3324
3564
  ...workerCtx ? { worker: workerCtx } : {},
3325
- onChildSpawn: (pid) => lock.announceChild(pid)
3565
+ onChildSpawn: (pid) => lock.announceChild(pid),
3566
+ signal: actionAbort.signal
3326
3567
  });
3327
3568
  if (result2.cancelled) {
3328
3569
  appendAudit({
@@ -3338,10 +3579,10 @@ ${spec.body}`, key2);
3338
3579
  ok: false,
3339
3580
  logFile: result2.logFile
3340
3581
  });
3341
- await publishCancellation("\u6267\u884C\u69FD\u5728\u811A\u672C\u542F\u52A8\u4E00\u523B\u6613\u4E3B\uFF0C\u672C\u6B21\u89E6\u53D1\u5DF2\u53D6\u6D88\uFF08\u811A\u672C\u5DF2\u5728\u542F\u52A8\u65F6\u7EC8\u6B62\uFF1B\u53EF\u80FD\u5DF2\u6709\u90E8\u5206\u8F93\u51FA\uFF09\u3002\u8BF7\u91CD\u8BD5\u3002");
3582
+ await publishCancellation(terminated ? "\u8FD0\u884C\u65F6\u5DF2\u9000\u51FA\uFF0C\u672C\u6B21\u64CD\u4F5C\u5DF2\u53D6\u6D88\u3002\u82E5\u811A\u672C\u6B64\u524D\u4EA7\u751F\u4E86\u8F93\u51FA\uFF0C\u8BF7\u5148\u6838\u5BF9\u7ED3\u679C\u518D\u91CD\u8BD5\u3002" : "\u6267\u884C\u69FD\u5728\u811A\u672C\u542F\u52A8\u4E00\u523B\u6613\u4E3B\uFF0C\u672C\u6B21\u89E6\u53D1\u5DF2\u53D6\u6D88\uFF08\u811A\u672C\u5DF2\u5728\u542F\u52A8\u65F6\u7EC8\u6B62\uFF1B\u53EF\u80FD\u5DF2\u6709\u90E8\u5206\u8F93\u51FA\uFF09\u3002\u8BF7\u91CD\u8BD5\u3002");
3342
3583
  return;
3343
3584
  }
3344
- const triggerName = await resolveUserName(triggerOpenId, { ...cfg.profile ? { profile: cfg.profile } : {}, ...cfg.larkCliPath ? { binary: cfg.larkCliPath } : {} });
3585
+ const triggerName = terminated ? triggerQuick : await resolveUserName(triggerOpenId, { signal: actionAbort.signal, cwd: ctx.cwd, ...cfg.profile ? { profile: cfg.profile } : {}, ...cfg.larkCliPath ? { binary: cfg.larkCliPath } : {} });
3345
3586
  bumpRunStats(actionId, triggerName);
3346
3587
  appendAudit({
3347
3588
  at: Date.now(),
@@ -3356,7 +3597,7 @@ ${spec.body}`, key2);
3356
3597
  ok: result2.ok,
3357
3598
  logFile: result2.logFile
3358
3599
  });
3359
- if (!runtimeAlive()) return;
3600
+ if (!actionCanDeliver()) return;
3360
3601
  const icon = result2.timedOut ? "\u23F1\uFE0F" : result2.ok ? "\u2705" : "\u274C";
3361
3602
  const statusLine = result2.timedOut ? `\u8D85\u65F6\uFF08>${timeoutS}s\uFF09\uFF0C\u5DF2\u7EC8\u6B62` : result2.ok ? `\u8017\u65F6 ${(result2.durationMs / 1e3).toFixed(1)}s` : `exit ${result2.exitCode ?? "?"} \xB7 \u8017\u65F6 ${(result2.durationMs / 1e3).toFixed(1)}s`;
3362
3603
  const outBody = truncateMarkdown(result2.stdout.trim() || (result2.ok ? "_(no output)_" : ""));
@@ -3379,32 +3620,24 @@ ${result2.stderrTail.trim().slice(0, 1500)}
3379
3620
  ].filter((line) => line !== "").join("\n"),
3380
3621
  actions: [{ id: `panel.action.${actionId}`, label: "\u{1F501} \u518D\u8DD1\u4E00\u6B21", ...workerCtx ? { payload: { worker: { name: workerCtx.name, ...workerCtx.ref ? { ref: workerCtx.ref } : {} } } } : {} }, { id: "panel.summon", label: "\u21A9\uFE0F \u9762\u677F" }]
3381
3622
  };
3382
- let patched = false;
3383
- if (ackMessageId && connection.patch) {
3384
- try {
3385
- patched = await connection.patch(ackMessageId, resultSpec);
3386
- } catch {
3387
- patched = false;
3388
- }
3389
- }
3390
- if (!patched && runtimeAlive()) await sendActionCard(resultSpec, `panel-action-result-${event.event_id}`, runtimeAlive);
3623
+ await publishTerminal(resultSpec, `panel-action-result-${event.event_id}`);
3391
3624
  } catch (error) {
3392
3625
  ctx.log(`im-forward: panel action ${actionId} execution error: ${error instanceof Error ? error.message : String(error)}`);
3393
- if (runtimeAlive()) {
3394
- try {
3395
- await sendActionCard({
3396
- title: `\u274C ${action.label}`,
3397
- color: "red",
3398
- body: `\u6267\u884C\u5668\u81EA\u8EAB\u51FA\u9519\uFF1A${error instanceof Error ? error.message : String(error)}`,
3399
- actions: [{ id: "panel.summon", label: "\u21A9\uFE0F \u9762\u677F" }]
3400
- }, `panel-action-error-${event.event_id}`, runtimeAlive);
3401
- } catch {
3402
- }
3403
- }
3626
+ await publishTerminal({
3627
+ title: `\u274C ${action.label}`,
3628
+ color: "red",
3629
+ body: `\u6267\u884C\u5668\u81EA\u8EAB\u51FA\u9519\uFF1A${error instanceof Error ? error.message : String(error)}`,
3630
+ actions: [{ id: "panel.summon", label: "\u21A9\uFE0F \u9762\u677F" }]
3631
+ }, `panel-action-error-${event.event_id}`);
3404
3632
  } finally {
3633
+ actionAbort.signal.removeEventListener("abort", lock.release);
3405
3634
  lock.release();
3635
+ panelActionControllers.delete(actionAbort);
3406
3636
  }
3407
3637
  })();
3638
+ panelActionTasks.add(actionTask);
3639
+ void actionTask.then(() => panelActionTasks.delete(actionTask), () => panelActionTasks.delete(actionTask));
3640
+ await initialAck;
3408
3641
  return;
3409
3642
  }
3410
3643
  const result = executePanelCommand({ ...panelCmd, senderId: event.sender_id, originCardId: event.message_id });
@@ -3420,11 +3653,19 @@ ${result2.stderrTail.trim().slice(0, 1500)}
3420
3653
  }
3421
3654
  if (!isCurrent()) return;
3422
3655
  if (connection.sendCard) {
3423
- const sent = await connection.sendCard(event.chat_id, result.spec, `panel-${event.event_id}`);
3424
- if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
3656
+ const sent = await connection.sendCard(freshRecipient, result.spec, `panel-${event.event_id}`);
3657
+ if (isCurrent()) {
3658
+ rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
3659
+ const peek = result.spec.actions.find((a) => /^panel\.peek\.[A-Za-z0-9-]+$/.test(a.id));
3660
+ const bound = peek && isRecord(peek.payload) && isRecord(peek.payload.peek) ? peek.payload.peek : void 0;
3661
+ if (sent?.messageId && bound && typeof bound.ref === "string" && typeof bound.session === "string") {
3662
+ issuedWorkerCards.set(sent.messageId, { ref: bound.ref, targetSession: bound.session, chatId: event.chat_id });
3663
+ if (issuedWorkerCards.size > 100) for (const old of [...issuedWorkerCards.keys()].slice(0, 25)) issuedWorkerCards.delete(old);
3664
+ }
3665
+ }
3425
3666
  ctx.log(`im-forward: panel card sent (${panelCmd.cmd})`);
3426
3667
  } else {
3427
- await connection.send(event.chat_id, `**${result.spec.title ?? "Panel"}**
3668
+ await connection.send(freshRecipient, `**${result.spec.title ?? "Panel"}**
3428
3669
  ${result.spec.body}`, `panel-${event.event_id}`);
3429
3670
  }
3430
3671
  } catch (error) {
@@ -3457,6 +3698,15 @@ ${result.spec.body}`, `panel-${event.event_id}`);
3457
3698
  }
3458
3699
  const messageId = event.message_id;
3459
3700
  if (!messageId) return;
3701
+ const peekAtGate = event.text?.startsWith("/card ") ? parsePanelCommand(event.text) : void 0;
3702
+ if (peekAtGate && /^panel\.peek\.[A-Za-z0-9-]+$/.test(peekAtGate.cmd) && !peekAudienceIsDirect(event)) {
3703
+ const recipient = cfg.targetKind === "user" ? cfg.targetId : event.chat_id;
3704
+ if (connection.sendCard) {
3705
+ const sent = await connection.sendCard(recipient, { title: "Peek unavailable", color: "red", body: "\u26D4\uFE0F Peek is limited to the configured authorized direct-message audience. Group audience privacy cannot be proven.", actions: [{ id: "panel.summon", label: "\u21A9\uFE0F Back" }] }, `panel-peek-denied-${event.event_id}`);
3706
+ if (sent?.messageId && currentSessionId) rememberPanelCard(sent.messageId, currentSessionId, event.chat_id);
3707
+ }
3708
+ return;
3709
+ }
3460
3710
  const owner = panelCardOwners.get(messageId);
3461
3711
  const nonBoundPanel = cfg.targetKind === "chat" && !!cfg.targetId && event.chat_id !== cfg.targetId;
3462
3712
  const fastEpoch = inputEpoch;
@@ -4131,6 +4381,25 @@ ${imagelessCaption || (imageKeys.length ? IM_INPUT_FALLBACK_CAPTION : "") || cap
4131
4381
  inFlightRetries.clear();
4132
4382
  if (restartTimer) clearTimeout(restartTimer);
4133
4383
  if (generation) generation.retired = true;
4384
+ for (const controller of panelActionControllers) controller.abort();
4385
+ if (panelActionTasks.size > 0) {
4386
+ let drainTimer;
4387
+ await Promise.race([
4388
+ Promise.allSettled([...panelActionTasks]).then(() => void 0),
4389
+ new Promise((resolve6) => {
4390
+ drainTimer = setTimeout(resolve6, ACTION_RETIRE_DRAIN_MS);
4391
+ drainTimer.unref?.();
4392
+ })
4393
+ ]);
4394
+ if (drainTimer) clearTimeout(drainTimer);
4395
+ }
4396
+ actionDeliveryOpen = false;
4397
+ if (panelActionTasks.size) {
4398
+ try {
4399
+ ctx.log(`im-forward: retirement drain expired with ${panelActionTasks.size} panel action(s) pending; terminal card delivery unconfirmed`);
4400
+ } catch {
4401
+ }
4402
+ }
4134
4403
  const results = await Promise.allSettled([
4135
4404
  ...resources.map(
4136
4405
  (scope) => Promise.resolve().then(() => scope.dispose())