@cydm/pie 4.4.2 → 4.5.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.
- package/dist/builtin/extensions/ask-user/index.js +6 -6
- package/dist/builtin/extensions/changelog/index.js +1 -1
- package/dist/builtin/extensions/cron/index.js +55 -7
- package/dist/builtin/extensions/document-attachments/index.js +1 -1
- package/dist/builtin/extensions/herdr-agent-state/index.js +1 -1
- package/dist/builtin/extensions/im-forward/README.md +3 -1
- package/dist/builtin/extensions/im-forward/index.js +364 -118
- package/dist/builtin/extensions/init/index.js +1 -1
- package/dist/builtin/extensions/mcp-adapter/index.js +2 -2
- package/dist/builtin/extensions/memory/index.js +9 -11
- package/dist/builtin/extensions/pie-ipc/index.js +70 -19
- package/dist/builtin/extensions/pie-proc/index.js +27 -13
- package/dist/builtin/extensions/plan-mode/index.js +6 -6
- package/dist/builtin/extensions/subagent/index.js +9 -11
- package/dist/builtin/extensions/todo/index.js +6 -6
- package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +24 -1
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +86 -21
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-cli.js +6 -1
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
- package/dist/builtin/skills/chrome-devtools-axi/{cli-CHC7XYFU.js → cli-NLPMVDGG.js} +32 -4
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +220 -22
- package/dist/chunks/{auth-storage-RABPRJ6T.js → auth-storage-C3FZMT7J.js} +3 -3
- package/dist/chunks/{chunk-OFLKAWI4.js → chunk-2CJIENLY.js} +90 -100
- package/dist/chunks/{chunk-R7VO46EK.js → chunk-3W3SXVPB.js} +5 -4
- package/dist/chunks/{chunk-IPLMGAML.js → chunk-5KI4Y4LA.js} +1 -1
- package/dist/chunks/{chunk-YNTIOWCD.js → chunk-BLDI2GRF.js} +5 -5
- package/dist/chunks/{chunk-UCKOXAME.js → chunk-CBDQJMUI.js} +9 -44
- package/dist/chunks/chunk-CGSFBWOM.js +100 -0
- package/dist/chunks/{chunk-7LTQLJJF.js → chunk-LAJXWOKS.js} +15 -10
- package/dist/chunks/{chunk-RZGYXAJU.js → chunk-LZQXQOPJ.js} +1 -12
- package/dist/chunks/{chunk-EQOI6RZV.js → chunk-NHV2CALB.js} +3 -5
- package/dist/chunks/{chunk-OV7SLSHR.js → chunk-SW2E33UL.js} +2 -4
- package/dist/chunks/{chunk-BPSCGGVF.js → chunk-XXGYUYXI.js} +1 -1
- package/dist/chunks/{chunk-XO3NM7BB.js → chunk-Y3I2UV5Y.js} +3 -3
- package/dist/chunks/{chunk-IZDNZW3S.js → chunk-Z2FKA2ZH.js} +8 -8
- package/dist/chunks/chunk-ZPJ3BNQB.js +126 -0
- package/dist/chunks/{config-HF2PDLN5.js → config-4EOI5NOU.js} +2 -4
- package/dist/chunks/{manager-cli-BYCF4RKN.js → manager-cli-2ATPC47M.js} +35 -5
- package/dist/chunks/manager-upgrade-5CPKTRJ7.js +562 -0
- package/dist/chunks/{model-registry-7FNIUYPF.js → model-registry-3XAHXXTA.js} +5 -5
- package/dist/chunks/{src-OVWRBWKU.js → src-B44QWSGM.js} +4 -4
- package/dist/chunks/{src-A5YI46OD.js → src-CLE5ILN4.js} +6 -6
- package/dist/chunks/{src-OA3TP6DS.js → src-EGXFJ3WA.js} +5 -5
- package/dist/chunks/{src-TF2RAGRU.js → src-Q7LU27C2.js} +3 -3
- package/dist/chunks/{test-stream-7YZDGBPO.js → test-stream-OR3EJBNF.js} +3 -3
- package/dist/cli.js +173 -136
- package/package.json +3 -3
- package/dist/chunks/chunk-7KLWHWZD.js +0 -164
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
readLiveConfig,
|
|
21
21
|
readLiveEnabled,
|
|
22
22
|
registerDispatchReceiver,
|
|
23
|
+
registerImBinding,
|
|
23
24
|
registerTurnImDriver,
|
|
24
25
|
resolveAddress,
|
|
25
26
|
resolveConfig,
|
|
@@ -31,17 +32,18 @@ import {
|
|
|
31
32
|
truncateMarkdown,
|
|
32
33
|
tryClaimConsumer,
|
|
33
34
|
writeConfig
|
|
34
|
-
} from "../../../chunks/chunk-
|
|
35
|
+
} from "../../../chunks/chunk-2CJIENLY.js";
|
|
35
36
|
import {
|
|
36
37
|
detectImageMime,
|
|
37
38
|
readImageFormat
|
|
38
39
|
} from "../../../chunks/chunk-F7EBZTZO.js";
|
|
39
|
-
import "../../../chunks/chunk-
|
|
40
|
+
import "../../../chunks/chunk-ZPJ3BNQB.js";
|
|
41
|
+
import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
40
42
|
|
|
41
43
|
// builtin/extensions/im-forward/runtime.ts
|
|
42
44
|
import * as crypto from "node:crypto";
|
|
43
45
|
import * as fs6 from "node:fs";
|
|
44
|
-
import { basename, join as pathJoin, resolve as pathResolve, join as join7 } from "node:path";
|
|
46
|
+
import { basename, join as pathJoin, resolve as pathResolve, join as join7, dirname as pathDirname } from "node:path";
|
|
45
47
|
import * as os3 from "node:os";
|
|
46
48
|
|
|
47
49
|
// builtin/extensions/im-forward/thread-registry.ts
|
|
@@ -331,6 +333,7 @@ function threadOwner(input) {
|
|
|
331
333
|
import * as fs2 from "node:fs";
|
|
332
334
|
import * as os2 from "node:os";
|
|
333
335
|
import * as path3 from "node:path";
|
|
336
|
+
import { fileURLToPath } from "node:url";
|
|
334
337
|
|
|
335
338
|
// builtin/extensions/im-forward/discovery.ts
|
|
336
339
|
import * as os from "node:os";
|
|
@@ -359,7 +362,7 @@ function parsePanelCommand(text) {
|
|
|
359
362
|
cmd = next?.[1] ?? "";
|
|
360
363
|
rest = next?.[2] ?? "";
|
|
361
364
|
}
|
|
362
|
-
if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.models" && cmd !== "panel.help" && cmd !== "\u9762\u677F") {
|
|
365
|
+
if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.models" && cmd !== "panel.upgrade" && cmd !== "panel.upgrade.confirm" && cmd !== "panel.help" && cmd !== "\u9762\u677F") {
|
|
363
366
|
if (!/^panel\.model\.[A-Za-z0-9-]+\..+$/.test(cmd)) return void 0;
|
|
364
367
|
}
|
|
365
368
|
const leadingFlag = /^--restricted(?:\s+|$)/.exec(rest);
|
|
@@ -398,7 +401,8 @@ function scanPeers() {
|
|
|
398
401
|
sessionTitle: typeof parsed.displaySessionName === "string" && parsed.displaySessionName.trim() ? parsed.displaySessionName.trim() : void 0,
|
|
399
402
|
project: typeof parsed.cwd === "string" && parsed.cwd ? parsed.cwd.split("/").filter(Boolean).at(-1) : void 0,
|
|
400
403
|
currentTool: typeof parsed.currentTool === "string" && parsed.currentTool ? parsed.currentTool : void 0,
|
|
401
|
-
model: typeof parsed.model === "string" && parsed.model ? parsed.model : void 0
|
|
404
|
+
model: typeof parsed.model === "string" && parsed.model ? parsed.model : void 0,
|
|
405
|
+
version: typeof parsed.version === "string" && parsed.version ? parsed.version : void 0
|
|
402
406
|
});
|
|
403
407
|
} catch {
|
|
404
408
|
}
|
|
@@ -412,32 +416,67 @@ function composePanel() {
|
|
|
412
416
|
const rows = peers.map((p) => {
|
|
413
417
|
const title = p.sessionTitle ?? p.name;
|
|
414
418
|
const state = p.state === "working" && p.currentTool ? `working\xB7${p.currentTool}` : p.state;
|
|
415
|
-
const project = p.project && p.project !== title ?
|
|
416
|
-
return `| ${title}${project} | ${p.model ?? "\u2014"} | ${state} |
|
|
417
|
-
| \u21B3 ${p.name} | | |`;
|
|
419
|
+
const project = p.project && p.project !== title ? ` (${p.project})` : "";
|
|
420
|
+
return `| ${title}${project} | ${p.model ?? "\u2014"} | ${state} | ${p.version ?? "\u2014"} |
|
|
421
|
+
| \u21B3 ${p.name} | | | |`;
|
|
418
422
|
});
|
|
423
|
+
const upgradeLine = upgradeSummaryLine();
|
|
419
424
|
const body = [
|
|
420
|
-
peers.length > 0 ? `|
|
|
421
|
-
|
|
422
|
-
${rows.join("\n")}` : "
|
|
425
|
+
peers.length > 0 ? `| Session | Model | State | Ver |
|
|
426
|
+
|---|---|---|---|
|
|
427
|
+
${rows.join("\n")}` : "_No live pie sessions_",
|
|
423
428
|
``,
|
|
424
|
-
|
|
425
|
-
|
|
429
|
+
upgradeLine,
|
|
430
|
+
`${peers.length} session(s) \xB7 ${(/* @__PURE__ */ new Date()).toLocaleTimeString("en-GB", { hour12: false })}`
|
|
431
|
+
].filter((line) => line !== void 0).join("\n");
|
|
426
432
|
return {
|
|
427
|
-
title: "Pie
|
|
428
|
-
subtitle: `${os2.hostname()} \xB7 ${peers.length} \
|
|
433
|
+
title: "Pie Panel",
|
|
434
|
+
subtitle: `${os2.hostname()} \xB7 ${peers.length} session(s) \xB7 pie ${pieVersion()}`,
|
|
429
435
|
color: "blue",
|
|
430
436
|
body,
|
|
431
437
|
// r1-P2: only REGISTERED commands get buttons — unmapped ids would fall
|
|
432
438
|
// through to an LLM turn (a button press must never spend a model turn).
|
|
433
439
|
actions: [
|
|
434
|
-
{ id: "panel.refresh", label: "\u{1F504}
|
|
435
|
-
{ id: "panel.summon", label: "\u{1F4CB}
|
|
436
|
-
{ id: "panel.models", label: "\u{1F39A}
|
|
437
|
-
{ id: "panel.
|
|
440
|
+
{ id: "panel.refresh", label: "\u{1F504} Refresh" },
|
|
441
|
+
{ id: "panel.summon", label: "\u{1F4CB} Resummon" },
|
|
442
|
+
{ id: "panel.models", label: "\u{1F39A} Model" },
|
|
443
|
+
{ id: "panel.upgrade", label: "\u2B06\uFE0F Upgrade" },
|
|
444
|
+
{ id: "panel.help", label: "\u2753 Help" }
|
|
438
445
|
]
|
|
439
446
|
};
|
|
440
447
|
}
|
|
448
|
+
function pieVersion() {
|
|
449
|
+
try {
|
|
450
|
+
const here = path3.dirname(fileURLToPath(import.meta.url));
|
|
451
|
+
for (const up of [3, 4, 5, 6]) {
|
|
452
|
+
const pkgPath = path3.resolve(here, ...Array(up).fill(".."), "package.json");
|
|
453
|
+
if (!fs2.existsSync(pkgPath)) continue;
|
|
454
|
+
const parsed = JSON.parse(fs2.readFileSync(pkgPath, "utf8"));
|
|
455
|
+
if (parsed.name === "@cydm/pie" && typeof parsed.version === "string") return parsed.version;
|
|
456
|
+
}
|
|
457
|
+
} catch {
|
|
458
|
+
}
|
|
459
|
+
return "unknown";
|
|
460
|
+
}
|
|
461
|
+
function readUpgradeSnapshot() {
|
|
462
|
+
try {
|
|
463
|
+
const configRoot = path3.dirname(path3.dirname(ipcDiscoveryRoot()));
|
|
464
|
+
return JSON.parse(fs2.readFileSync(path3.join(configRoot, "manager", "upgrade.json"), "utf8"));
|
|
465
|
+
} catch {
|
|
466
|
+
return void 0;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
function upgradeSummaryLine() {
|
|
470
|
+
const snap = readUpgradeSnapshot();
|
|
471
|
+
if (!snap) return `pie ${pieVersion()} \xB7 no upgrade yet`;
|
|
472
|
+
const when = typeof snap.at === "number" ? new Date(snap.at).toLocaleString("en-GB", { hour12: false }) : "?";
|
|
473
|
+
if (snap.ok === true) {
|
|
474
|
+
const recycled = snap.workersRecycled?.length ?? 0;
|
|
475
|
+
const skipped = snap.workersSkipped?.length ?? 0;
|
|
476
|
+
return `pie ${pieVersion()} \xB7 upgraded ${snap.fromVersion ?? "?"} \u2192 ${snap.toVersion ?? "?"} at ${when} (workers: ${recycled} recycled, ${skipped} left busy)`;
|
|
477
|
+
}
|
|
478
|
+
return `pie ${pieVersion()} \xB7 last upgrade FAILED at ${snap.stage ?? "?"} (${when}): ${snap.detail ?? "unknown"}`;
|
|
479
|
+
}
|
|
441
480
|
function candidateModels() {
|
|
442
481
|
const out = /* @__PURE__ */ new Set();
|
|
443
482
|
try {
|
|
@@ -461,26 +500,51 @@ function executePanelCommand(input) {
|
|
|
461
500
|
(p) => models.map((m) => ({ id: `panel.model.${p.instanceId}.${m}`, label: `${p.name.slice(0, 10)}\u2192${m.split("/")[1]?.slice(0, 14) ?? m}` }))
|
|
462
501
|
).slice(0, 18);
|
|
463
502
|
return { spec: {
|
|
464
|
-
title: "
|
|
465
|
-
subtitle: `${peers.length}
|
|
503
|
+
title: "Switch Model",
|
|
504
|
+
subtitle: `${peers.length} session(s) \xD7 ${models.length} candidates`,
|
|
466
505
|
color: "violet",
|
|
467
506
|
body: [
|
|
468
|
-
peers.length > 0 ? `|
|
|
507
|
+
peers.length > 0 ? `| Session | Model |
|
|
469
508
|
|---|---|
|
|
470
|
-
${rows.join("\n")}` : "
|
|
509
|
+
${rows.join("\n")}` : "_No live pie sessions_",
|
|
510
|
+
``,
|
|
511
|
+
`Candidates: ${models.join(" \xB7 ") || "(models.json unreadable)"}`,
|
|
512
|
+
``,
|
|
513
|
+
"Each button maps a session to a model. Tapping sends a model.set control frame (zero LLM, nothing enters the peer history)."
|
|
514
|
+
].join("\n"),
|
|
515
|
+
actions: actions.length > 0 ? actions : [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
|
|
516
|
+
}, patchOrigin: false };
|
|
517
|
+
}
|
|
518
|
+
if (input.cmd === "panel.upgrade") {
|
|
519
|
+
const snap = readUpgradeSnapshot();
|
|
520
|
+
const current = pieVersion();
|
|
521
|
+
const when = snap && typeof snap.at === "number" ? new Date(snap.at).toLocaleString("en-GB", { hour12: false }) : void 0;
|
|
522
|
+
const last = snap ? snap.ok === true ? `Last upgrade: ${snap.fromVersion ?? "?"} \u2192 ${snap.toVersion ?? "?"} at ${when} \u2713` : `Last upgrade FAILED at "${snap.stage ?? "?"}" (${when}): ${snap.detail ?? "unknown"}` : "No upgrade has run on this machine yet.";
|
|
523
|
+
return { spec: {
|
|
524
|
+
title: "Upgrade Pie",
|
|
525
|
+
subtitle: `current ${current} \xB7 target latest`,
|
|
526
|
+
color: "violet",
|
|
527
|
+
body: [
|
|
528
|
+
`Current: **${current}** \xB7 Target: **latest** (resolved by npm at run time)`,
|
|
471
529
|
``,
|
|
472
|
-
|
|
530
|
+
last,
|
|
473
531
|
``,
|
|
474
|
-
"
|
|
532
|
+
"Upgrade = `npm install -g @cydm/pie@latest` + restart the manager resident (IM pauses ~15s). Idle workers are recycled; busy ones keep running. Desktop TUI sessions keep their code until you restart them.",
|
|
533
|
+
"The confirm button requires allowUsers membership."
|
|
475
534
|
].join("\n"),
|
|
476
|
-
actions:
|
|
535
|
+
actions: [
|
|
536
|
+
// requireAllowUsers: the compiled callback carries --restricted; a
|
|
537
|
+
// non-allowlisted clicker is refused by runPanelCommand's gate.
|
|
538
|
+
{ id: "panel.upgrade.confirm", label: "\u2B06\uFE0F Install latest + restart", style: "primary", requireAllowUsers: true },
|
|
539
|
+
{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }
|
|
540
|
+
]
|
|
477
541
|
}, patchOrigin: false };
|
|
478
542
|
}
|
|
479
543
|
if (input.cmd === "panel.help") {
|
|
480
544
|
return { spec: {
|
|
481
|
-
title: "
|
|
482
|
-
body: "`/panel`
|
|
483
|
-
actions: [{ id: "panel.summon", label: "
|
|
545
|
+
title: "Panel Commands",
|
|
546
|
+
body: "`/panel` summons the status panel. Card buttons: \u{1F504} Refresh (in-place update), \u{1F4CB} Resummon, \u{1F39A} Model, \u2B06\uFE0F Upgrade (npm install + manager restart), \u2753 Help. Any group member may tap; `--restricted` actions require the allowUsers whitelist.",
|
|
547
|
+
actions: [{ id: "panel.summon", label: "Back to panel" }]
|
|
484
548
|
}, patchOrigin: false };
|
|
485
549
|
}
|
|
486
550
|
return { spec: composePanel(), patchOrigin: input.cmd === "panel.refresh" && input.originCardId !== void 0 };
|
|
@@ -525,12 +589,40 @@ function findOwnerInstance(sessionId) {
|
|
|
525
589
|
candidates.sort((a, b) => b.startedAt - a.startedAt);
|
|
526
590
|
return candidates[0].file;
|
|
527
591
|
}
|
|
592
|
+
function findNamedOwnerInstance(name, binding) {
|
|
593
|
+
let entries;
|
|
594
|
+
try {
|
|
595
|
+
entries = fs3.readdirSync(discoveryDir()).filter((entry) => entry.endsWith(".json"));
|
|
596
|
+
} catch {
|
|
597
|
+
return void 0;
|
|
598
|
+
}
|
|
599
|
+
if (entries.length > 256) return void 0;
|
|
600
|
+
const matches = [];
|
|
601
|
+
for (const entry of entries) {
|
|
602
|
+
try {
|
|
603
|
+
const peer = JSON.parse(fs3.readFileSync(path4.join(discoveryDir(), entry), "utf8"));
|
|
604
|
+
if (peer.sessionName?.trim() !== name || !pidAlive2(peer.pid)) continue;
|
|
605
|
+
matches.push(peer);
|
|
606
|
+
} catch {
|
|
607
|
+
return void 0;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
if (matches.length !== 1) return void 0;
|
|
611
|
+
const owner = matches[0];
|
|
612
|
+
if (owner.imBinding !== binding || owner.protocol !== IPC_PROTOCOL_VERSION || !/^pie-[a-z0-9]{12}$/.test(owner.instanceId) || !entries.includes(`${owner.instanceId}.json`) || typeof owner.sessionId !== "string" || !owner.sessionId || !Number.isInteger(owner.port) || !owner.port || owner.port < 1 || owner.port > 65535 || typeof owner.secret !== "string") return void 0;
|
|
613
|
+
return owner;
|
|
614
|
+
}
|
|
615
|
+
async function dispatchEventToName(name, binding, eventText) {
|
|
616
|
+
const owner = findNamedOwnerInstance(name, binding);
|
|
617
|
+
if (!owner?.port || !owner.secret) return void 0;
|
|
618
|
+
return await deliverOnce(owner.port, owner.secret, eventText, owner.sessionId, owner.instanceId) ? owner.instanceId : void 0;
|
|
619
|
+
}
|
|
528
620
|
var SYNTHETIC_SENDER = (() => {
|
|
529
621
|
const hex = randomUUID2().replace(/-/g, "");
|
|
530
622
|
return `pie-${hex.slice(0, 12)}`;
|
|
531
623
|
})();
|
|
532
624
|
function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
|
|
533
|
-
return new Promise((
|
|
625
|
+
return new Promise((resolve5) => {
|
|
534
626
|
const id = randomUUID2();
|
|
535
627
|
const envelope = {
|
|
536
628
|
v: IPC_PROTOCOL_VERSION,
|
|
@@ -558,7 +650,7 @@ function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
|
|
|
558
650
|
settled = true;
|
|
559
651
|
clearTimeout(timer);
|
|
560
652
|
socket.destroy();
|
|
561
|
-
|
|
653
|
+
resolve5(ok);
|
|
562
654
|
};
|
|
563
655
|
const timer = setTimeout(() => finish(false), 5e3);
|
|
564
656
|
socket.once("error", () => finish(false));
|
|
@@ -704,7 +796,7 @@ var RESTART_BACKOFF_MIN_MS = 5e3;
|
|
|
704
796
|
var RESTART_BACKOFF_MAX_MS = 6e4;
|
|
705
797
|
var SEND_FAILURE_NOTIFY_THROTTLE_MS = 5 * 60 * 1e3;
|
|
706
798
|
var CHUNK_RETRY_DELAY_MS = 2e3;
|
|
707
|
-
var delay = (ms) => new Promise((
|
|
799
|
+
var delay = (ms) => new Promise((resolve5) => setTimeout(resolve5, ms));
|
|
708
800
|
var MAX_INBOUND_RETRIES = 3;
|
|
709
801
|
var DEFAULT_INBOUND_RETRY_BACKOFF_MS = 5e3;
|
|
710
802
|
var MAX_PENDING_IM_INPUTS = 50;
|
|
@@ -742,6 +834,26 @@ function ipcDiscoveryRoot2() {
|
|
|
742
834
|
const configDir = process.platform === "win32" ? raw : pathResolve(raw === "~" ? home : raw.startsWith("~/") ? pathJoin(home, raw.slice(2)) : raw);
|
|
743
835
|
return pathJoin(configDir, "run", "ipc");
|
|
744
836
|
}
|
|
837
|
+
function liveManagerForBinding(binding) {
|
|
838
|
+
try {
|
|
839
|
+
for (const file of fs6.readdirSync(ipcDiscoveryRoot2())) {
|
|
840
|
+
if (!file.endsWith(".json")) continue;
|
|
841
|
+
try {
|
|
842
|
+
const peer = JSON.parse(fs6.readFileSync(pathJoin(ipcDiscoveryRoot2(), file), "utf8"));
|
|
843
|
+
if (peer.pid === process.pid || peer.isManager !== true || peer.imBinding !== binding || !Number.isInteger(peer.pid) || !peer.pid || peer.pid <= 0) continue;
|
|
844
|
+
try {
|
|
845
|
+
process.kill(peer.pid, 0);
|
|
846
|
+
return true;
|
|
847
|
+
} catch (error) {
|
|
848
|
+
if (error.code !== "ESRCH") return true;
|
|
849
|
+
}
|
|
850
|
+
} catch {
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
} catch {
|
|
854
|
+
}
|
|
855
|
+
return false;
|
|
856
|
+
}
|
|
745
857
|
async function applyModelControl(peerRef, model) {
|
|
746
858
|
const net2 = await import("node:net");
|
|
747
859
|
let target;
|
|
@@ -749,7 +861,7 @@ async function applyModelControl(peerRef, model) {
|
|
|
749
861
|
const dir = ipcDiscoveryRoot2();
|
|
750
862
|
for (const file of fs6.readdirSync(dir).filter((f) => f.endsWith(".json"))) {
|
|
751
863
|
const parsed = JSON.parse(fs6.readFileSync(join7(dir, file), "utf8"));
|
|
752
|
-
if (!parsed.port || !parsed.secret || typeof parsed.pid !== "number" || !parsed.instanceId) continue;
|
|
864
|
+
if (!parsed.port || !parsed.secret || typeof parsed.pid !== "number" || !parsed.instanceId || typeof parsed.sessionId !== "string" || !parsed.sessionId) continue;
|
|
753
865
|
const match = parsed.instanceId === peerRef || parsed.instanceId.startsWith(peerRef) || parsed.displayName === peerRef;
|
|
754
866
|
if (!match) continue;
|
|
755
867
|
try {
|
|
@@ -757,22 +869,23 @@ async function applyModelControl(peerRef, model) {
|
|
|
757
869
|
} catch {
|
|
758
870
|
continue;
|
|
759
871
|
}
|
|
760
|
-
target = { port: parsed.port, secret: parsed.secret, instanceId: parsed.instanceId };
|
|
872
|
+
target = { port: parsed.port, secret: parsed.secret, instanceId: parsed.instanceId, sessionId: parsed.sessionId };
|
|
761
873
|
break;
|
|
762
874
|
}
|
|
763
875
|
} catch {
|
|
764
876
|
}
|
|
765
|
-
if (!target) return { ok: false, detail:
|
|
877
|
+
if (!target) return { ok: false, detail: `Session not found: ${peerRef}` };
|
|
766
878
|
const envelope = signEnvelope({
|
|
767
879
|
v: IPC_PROTOCOL_VERSION,
|
|
768
880
|
id: `panel-model-${Date.now()}`,
|
|
769
881
|
from: "pie-panel0000000",
|
|
770
882
|
to: target.instanceId,
|
|
771
883
|
kind: "control",
|
|
884
|
+
sessionId: target.sessionId,
|
|
772
885
|
createdAt: Date.now(),
|
|
773
886
|
text: JSON.stringify({ control: "model.set", payload: { model } })
|
|
774
887
|
}, target.secret);
|
|
775
|
-
return await new Promise((
|
|
888
|
+
return await new Promise((resolve5) => {
|
|
776
889
|
let settled = false;
|
|
777
890
|
const finish = (ok, detail) => {
|
|
778
891
|
if (settled) return;
|
|
@@ -781,15 +894,15 @@ async function applyModelControl(peerRef, model) {
|
|
|
781
894
|
sock.destroy();
|
|
782
895
|
} catch {
|
|
783
896
|
}
|
|
784
|
-
|
|
897
|
+
resolve5({ ok, detail });
|
|
785
898
|
};
|
|
786
899
|
const sock = net2.connect({ host: "127.0.0.1", port: target.port }, () => {
|
|
787
900
|
sock.write(JSON.stringify(envelope) + "\n");
|
|
788
901
|
});
|
|
789
|
-
sock.setTimeout(6e3, () => finish(false, "\
|
|
790
|
-
sock.on("error", (error) => finish(false,
|
|
902
|
+
sock.setTimeout(6e3, () => finish(false, "Peer gave no receipt within 6s (it may be restarting; the control frame is idempotent \u2014 resending is safe)"));
|
|
903
|
+
sock.on("error", (error) => finish(false, `Connection failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
791
904
|
sock.on("close", () => {
|
|
792
|
-
if (!settled) finish(false, "
|
|
905
|
+
if (!settled) finish(false, "Peer closed the connection (policy refusal or rejected frame; resending is safe)");
|
|
793
906
|
});
|
|
794
907
|
sock.on("data", (buffer) => {
|
|
795
908
|
for (const line of buffer.toString("utf8").split("\n")) {
|
|
@@ -798,7 +911,7 @@ async function applyModelControl(peerRef, model) {
|
|
|
798
911
|
const parsed = JSON.parse(line);
|
|
799
912
|
if (parsed.kind === "ack" || parsed.kind === "result") {
|
|
800
913
|
const refused = /"ok"\s*:\s*false|error|拒绝|invalid|unknown|refus|denied/i.test(parsed.text ?? "");
|
|
801
|
-
finish(!refused,
|
|
914
|
+
finish(!refused, `Peer receipt: ${parsed.text ?? "(empty)"}`);
|
|
802
915
|
return;
|
|
803
916
|
}
|
|
804
917
|
} catch {
|
|
@@ -874,7 +987,7 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
|
874
987
|
busStale = next;
|
|
875
988
|
if (next) {
|
|
876
989
|
ctx.log("im-forward: event bus cloud websocket stale (aged disconnect without reconnect); card callbacks will not arrive until `lark-cli event stop --force` + restart");
|
|
877
|
-
ctx.ui.notify("IM
|
|
990
|
+
ctx.ui.notify("IM forward: the event-bus cloud connection looks aged (panel buttons may not respond). Fix: lark-cli event stop --force, then restart.", "warning");
|
|
878
991
|
}
|
|
879
992
|
updateFooterTag();
|
|
880
993
|
}
|
|
@@ -1238,9 +1351,9 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1238
1351
|
const attribution = resolveOutboundAttribution(sessionId);
|
|
1239
1352
|
const deliverTf = /* @__PURE__ */ new Map();
|
|
1240
1353
|
if (!outboundRoleAllows(attribution, deliverTf)) return;
|
|
1241
|
-
const recoveryHint =
|
|
1354
|
+
const recoveryHint = `Your input is still in the session \u2014 reply "\u91CD\u7B54\u4E0A\u4E00\u6761" (redo the last one) to answer from it again without resending the original request.`;
|
|
1242
1355
|
void forwardMessage(
|
|
1243
|
-
`\u26A0\uFE0F
|
|
1356
|
+
`\u26A0\uFE0F Task failed: ${reason} (retries exhausted)
|
|
1244
1357
|
${recoveryHint}`,
|
|
1245
1358
|
sessionId,
|
|
1246
1359
|
sequence,
|
|
@@ -1260,7 +1373,7 @@ ${recoveryHint}`,
|
|
|
1260
1373
|
const deliverTc = /* @__PURE__ */ new Map();
|
|
1261
1374
|
if (!outboundRoleAllows(attribution, deliverTc)) return;
|
|
1262
1375
|
void forwardMessage(
|
|
1263
|
-
`\u26D4\uFE0F
|
|
1376
|
+
`\u26D4\uFE0F Task cancelled: ${event.reason}`,
|
|
1264
1377
|
sessionId,
|
|
1265
1378
|
sequence,
|
|
1266
1379
|
attribution?.caption,
|
|
@@ -1310,8 +1423,8 @@ ${recoveryHint}`,
|
|
|
1310
1423
|
};
|
|
1311
1424
|
const claimStake = () => {
|
|
1312
1425
|
let release;
|
|
1313
|
-
const token = new Promise((
|
|
1314
|
-
release =
|
|
1426
|
+
const token = new Promise((resolve5) => {
|
|
1427
|
+
release = resolve5;
|
|
1315
1428
|
});
|
|
1316
1429
|
token.release = release;
|
|
1317
1430
|
anchorStakeFlights.set(sessionId, token);
|
|
@@ -1471,7 +1584,7 @@ ${recoveryHint}`,
|
|
|
1471
1584
|
"send notice",
|
|
1472
1585
|
() => connection.send(
|
|
1473
1586
|
cfg.targetId,
|
|
1474
|
-
`\u2026(
|
|
1587
|
+
`\u2026(chunked delivery failed after part ${index}/${chunks.length}; full content is in the terminal)`,
|
|
1475
1588
|
chunkKey(baseKey, index, "fail"),
|
|
1476
1589
|
anchor
|
|
1477
1590
|
)
|
|
@@ -1524,12 +1637,12 @@ ${recoveryHint}`,
|
|
|
1524
1637
|
}
|
|
1525
1638
|
if (failedFiles.length > 0 && !terminated && isForwardingEnabled()) {
|
|
1526
1639
|
const names = failedFiles.slice(0, 5).map((name) => name.replace(/[\r\n]/g, " ").slice(0, 80)).join("\u3001");
|
|
1527
|
-
const extra = failedFiles.length > 5 ?
|
|
1640
|
+
const extra = failedFiles.length > 5 ? ` (+${failedFiles.length - 5} more)` : "";
|
|
1528
1641
|
await providerCall(
|
|
1529
1642
|
"send attachment notice",
|
|
1530
1643
|
() => connection.send(
|
|
1531
1644
|
cfg.targetId,
|
|
1532
|
-
|
|
1645
|
+
`Attachment upload failed: ${names}${extra}. Check the files in the terminal.`,
|
|
1533
1646
|
chunkKey(baseKey, files.length, "fail"),
|
|
1534
1647
|
anchor
|
|
1535
1648
|
)
|
|
@@ -1677,7 +1790,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1677
1790
|
if (panelCmd.restricted && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id))) {
|
|
1678
1791
|
ctx.log(`im-forward: restricted panel action ${panelCmd.cmd} refused for ${event.sender_id ?? "unknown"} (not in allowUsers)`);
|
|
1679
1792
|
try {
|
|
1680
|
-
await connection.send(event.chat_id, "\u26D4\uFE0F
|
|
1793
|
+
await connection.send(event.chat_id, "\u26D4\uFE0F This action requires admin rights (allowUsers).", `panel-refused-${event.event_id}`);
|
|
1681
1794
|
} catch {
|
|
1682
1795
|
}
|
|
1683
1796
|
return;
|
|
@@ -1688,11 +1801,11 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1688
1801
|
const receipt = await applyModelControl(peerRef, model);
|
|
1689
1802
|
if (!isCurrent()) return;
|
|
1690
1803
|
const spec = {
|
|
1691
|
-
title: "
|
|
1804
|
+
title: "Model Switch Result",
|
|
1692
1805
|
body: `${receipt.ok ? "\u2705" : "\u26A0\uFE0F"} ${model} \u2192 ${peerRef}
|
|
1693
1806
|
|
|
1694
1807
|
${receipt.detail}`,
|
|
1695
|
-
actions: [{ id: "panel.models", label: "\u21A9\uFE0F
|
|
1808
|
+
actions: [{ id: "panel.models", label: "\u21A9\uFE0F Back to model panel" }]
|
|
1696
1809
|
};
|
|
1697
1810
|
try {
|
|
1698
1811
|
if (connection.sendCard) {
|
|
@@ -1704,6 +1817,89 @@ ${spec.body}`, `panel-model-${event.event_id}`);
|
|
|
1704
1817
|
}
|
|
1705
1818
|
return;
|
|
1706
1819
|
}
|
|
1820
|
+
if (panelCmd.cmd === "panel.upgrade.confirm") {
|
|
1821
|
+
if (!cfg.allowUsers || !event.sender_id || !cfg.allowUsers.includes(event.sender_id)) {
|
|
1822
|
+
ctx.log(`im-forward: panel.upgrade.confirm refused for ${event.sender_id ?? "unknown"} (execution-sink gate: allowUsers membership required)`);
|
|
1823
|
+
try {
|
|
1824
|
+
await connection.send(event.chat_id, "\u26D4\uFE0F Upgrading pie requires admin rights (allowUsers).", `panel-refused-${event.event_id}`);
|
|
1825
|
+
} catch {
|
|
1826
|
+
}
|
|
1827
|
+
return;
|
|
1828
|
+
}
|
|
1829
|
+
const spawn5 = await import("node:child_process");
|
|
1830
|
+
const started2 = Date.now();
|
|
1831
|
+
let actorOk = false;
|
|
1832
|
+
let actorDetail = "";
|
|
1833
|
+
try {
|
|
1834
|
+
const entry = process.argv[1] ? pathResolve(process.argv[1]) : "";
|
|
1835
|
+
if (!entry) throw new Error("cannot resolve the pie entry point");
|
|
1836
|
+
const configRoot = pathDirname(pathDirname(ipcDiscoveryRoot2()));
|
|
1837
|
+
const logFile = join7(configRoot, "manager", "upgrade-actor.log");
|
|
1838
|
+
let out;
|
|
1839
|
+
try {
|
|
1840
|
+
fs6.mkdirSync(pathDirname(logFile), { recursive: true });
|
|
1841
|
+
out = fs6.openSync(logFile, "a");
|
|
1842
|
+
} catch {
|
|
1843
|
+
out = void 0;
|
|
1844
|
+
}
|
|
1845
|
+
const child = spawn5.spawn(process.execPath, [entry, "manager", "upgrade"], {
|
|
1846
|
+
cwd: process.cwd(),
|
|
1847
|
+
detached: true,
|
|
1848
|
+
stdio: out !== void 0 ? ["ignore", out, out] : "ignore",
|
|
1849
|
+
windowsHide: true,
|
|
1850
|
+
env: process.env
|
|
1851
|
+
});
|
|
1852
|
+
const spawnOutcome = await new Promise((resolve5) => {
|
|
1853
|
+
let settled = false;
|
|
1854
|
+
const settle = (v) => {
|
|
1855
|
+
if (!settled) {
|
|
1856
|
+
settled = true;
|
|
1857
|
+
resolve5(v);
|
|
1858
|
+
}
|
|
1859
|
+
};
|
|
1860
|
+
child.once("spawn", () => settle("spawned"));
|
|
1861
|
+
child.once("error", (error) => {
|
|
1862
|
+
ctx.log(`im-forward: upgrade actor spawn error: ${error instanceof Error ? error.message : String(error)}`);
|
|
1863
|
+
settle("error");
|
|
1864
|
+
});
|
|
1865
|
+
setTimeout(() => settle("timeout"), 3e3).unref?.();
|
|
1866
|
+
});
|
|
1867
|
+
child.unref();
|
|
1868
|
+
if (out !== void 0) {
|
|
1869
|
+
try {
|
|
1870
|
+
fs6.closeSync(out);
|
|
1871
|
+
} catch {
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
if (spawnOutcome === "error") {
|
|
1875
|
+
actorDetail = "the actor process failed to spawn (see the manager log)";
|
|
1876
|
+
} else {
|
|
1877
|
+
actorOk = true;
|
|
1878
|
+
actorDetail = `actor pid ${child.pid}${spawnOutcome === "timeout" ? " (spawn unconfirmed \u2014 will report via /panel)" : ""} \xB7 log ${logFile}`;
|
|
1879
|
+
}
|
|
1880
|
+
} catch (error) {
|
|
1881
|
+
actorDetail = error instanceof Error ? error.message : String(error);
|
|
1882
|
+
}
|
|
1883
|
+
ctx.log(`im-forward: panel.upgrade.confirm actor spawn ${actorOk ? "ok" : "failed"} (${actorDetail}, runtimeMs=${Date.now() - started2})`);
|
|
1884
|
+
const spec = {
|
|
1885
|
+
title: actorOk ? "Upgrade Started" : "Upgrade Failed to Start",
|
|
1886
|
+
body: actorOk ? `\u2B06\uFE0F npm install + manager restart running in the background.
|
|
1887
|
+
|
|
1888
|
+
${actorDetail}
|
|
1889
|
+
|
|
1890
|
+
IM pauses briefly during the restart; tap \u{1F504} Refresh afterwards \u2014 the panel's footer line shows the outcome (old \u2192 new version).` : `Could not spawn the upgrade actor: ${actorDetail}`,
|
|
1891
|
+
actions: actorOk ? [{ id: "panel.refresh", label: "\u{1F504} Refresh" }] : [{ id: "panel.upgrade", label: "\u21A9\uFE0F Back to upgrade card" }]
|
|
1892
|
+
};
|
|
1893
|
+
try {
|
|
1894
|
+
if (connection.sendCard) {
|
|
1895
|
+
const sent = await connection.sendCard(event.chat_id, spec, `panel-upgrade-${event.event_id}`);
|
|
1896
|
+
if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
|
|
1897
|
+
} else await connection.send(event.chat_id, `**${spec.title}**
|
|
1898
|
+
${spec.body}`, `panel-upgrade-${event.event_id}`);
|
|
1899
|
+
} catch {
|
|
1900
|
+
}
|
|
1901
|
+
return;
|
|
1902
|
+
}
|
|
1707
1903
|
const result = executePanelCommand({ ...panelCmd, senderId: event.sender_id, originCardId: event.message_id });
|
|
1708
1904
|
try {
|
|
1709
1905
|
if (result.patchOrigin && connection.patch && event.message_id) {
|
|
@@ -1721,7 +1917,7 @@ ${spec.body}`, `panel-model-${event.event_id}`);
|
|
|
1721
1917
|
if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
|
|
1722
1918
|
ctx.log(`im-forward: panel card sent (${panelCmd.cmd})`);
|
|
1723
1919
|
} else {
|
|
1724
|
-
await connection.send(event.chat_id, `**${result.spec.title ?? "
|
|
1920
|
+
await connection.send(event.chat_id, `**${result.spec.title ?? "Panel"}**
|
|
1725
1921
|
${result.spec.body}`, `panel-${event.event_id}`);
|
|
1726
1922
|
}
|
|
1727
1923
|
} catch (error) {
|
|
@@ -1729,8 +1925,13 @@ ${result.spec.body}`, `panel-${event.event_id}`);
|
|
|
1729
1925
|
}
|
|
1730
1926
|
};
|
|
1731
1927
|
async function handleInboundEventInner(event, retry) {
|
|
1928
|
+
let nonBoundGroup = false;
|
|
1732
1929
|
const isGroup = event.chatType === "group";
|
|
1733
1930
|
if (isGroup) {
|
|
1931
|
+
nonBoundGroup = cfg.targetKind === "chat" && !!cfg.targetId && event.chat_id !== cfg.targetId;
|
|
1932
|
+
if (nonBoundGroup) {
|
|
1933
|
+
ctx.log(`im-forward: group event from non-bound chat ${event.chat_id} (owned-thread dispatch only)`);
|
|
1934
|
+
}
|
|
1734
1935
|
if (cfg.groupAccess === "off") {
|
|
1735
1936
|
ctx.log("im-forward: group event refused (off)");
|
|
1736
1937
|
return;
|
|
@@ -1761,7 +1962,21 @@ ${result.spec.body}`, `panel-${event.event_id}`);
|
|
|
1761
1962
|
}
|
|
1762
1963
|
const address = resolveInboundAddress(event.text);
|
|
1763
1964
|
if (address.kind === "other") {
|
|
1764
|
-
|
|
1965
|
+
if (isGroup && (nonBoundGroup || event.isBotMentioned === false)) {
|
|
1966
|
+
const meta = await fetchMessageMeta(messageId).catch(() => void 0);
|
|
1967
|
+
if (nonBoundGroup || !meta?.threadId) {
|
|
1968
|
+
ctx.log("im-forward: group address outside the bound chat or without bot mention/thread; ignoring");
|
|
1969
|
+
return;
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
if (consumerLock) {
|
|
1973
|
+
const epoch2 = inputEpoch;
|
|
1974
|
+
const session = currentSessionId;
|
|
1975
|
+
const payload = `${DISPATCH_PREFIX} ${JSON.stringify({ v: 1, binding: bindingKey(), event })}`;
|
|
1976
|
+
if (terminated || suspended || !isForwardingEnabled() || inputEpoch !== epoch2 || currentSessionId !== session) return;
|
|
1977
|
+
const owner2 = await dispatchEventToName(address.name, bindingKey(), payload);
|
|
1978
|
+
ctx.log(owner2 ? `im-forward: explicit address "${address.name}" dispatched to ${owner2}` : `im-forward: explicit address "${address.name}" has no deliverable unique owner`);
|
|
1979
|
+
}
|
|
1765
1980
|
return;
|
|
1766
1981
|
}
|
|
1767
1982
|
if (address.kind === "ambiguous") {
|
|
@@ -1795,6 +2010,11 @@ ${result.spec.body}`, `panel-${event.event_id}`);
|
|
|
1795
2010
|
releaseInvalidatedEvent();
|
|
1796
2011
|
return;
|
|
1797
2012
|
}
|
|
2013
|
+
if (isGroup && event.isBotMentioned === false && !meta.threadId) {
|
|
2014
|
+
ctx.log("im-forward: group message without bot mention outside any thread; ignoring");
|
|
2015
|
+
releaseInvalidatedEvent();
|
|
2016
|
+
return;
|
|
2017
|
+
}
|
|
1798
2018
|
const pinnedSession = event.event_id ? retrySessionIds.get(key(event.event_id)) : void 0;
|
|
1799
2019
|
if (pinnedSession !== void 0 && pinnedSession !== sessionId) {
|
|
1800
2020
|
ctx.log(`im-forward: retry crossed a session switch (${pinnedSession} -> ${sessionId}); releasing for redelivery`);
|
|
@@ -1815,7 +2035,7 @@ ${result.spec.body}`, `panel-${event.event_id}`);
|
|
|
1815
2035
|
return;
|
|
1816
2036
|
}
|
|
1817
2037
|
const unanchored = !meta.replyTo && !meta.threadId;
|
|
1818
|
-
if (isManager && unanchored) {
|
|
2038
|
+
if (isManager && unanchored && !nonBoundGroup) {
|
|
1819
2039
|
const residentRoute = {
|
|
1820
2040
|
messageId: "",
|
|
1821
2041
|
threadId: meta.threadId ?? null,
|
|
@@ -1849,7 +2069,7 @@ ${result.spec.body}`, `panel-${event.event_id}`);
|
|
|
1849
2069
|
ctx.log(`im-forward: thread ownership unreadable for ${messageId}; dropping (fail closed)`);
|
|
1850
2070
|
return;
|
|
1851
2071
|
}
|
|
1852
|
-
if (isManager && meta.threadId && (event.chatType === "group" || event.chatType === "p2p")) {
|
|
2072
|
+
if (isManager && meta.threadId && !nonBoundGroup && (event.chatType === "group" || event.chatType === "p2p")) {
|
|
1853
2073
|
if (!scope.isCurrent()) {
|
|
1854
2074
|
releaseInvalidatedEvent();
|
|
1855
2075
|
return;
|
|
@@ -1879,6 +2099,11 @@ ${result.spec.body}`, `panel-${event.event_id}`);
|
|
|
1879
2099
|
releaseInvalidatedEvent();
|
|
1880
2100
|
return;
|
|
1881
2101
|
}
|
|
2102
|
+
if (nonBoundGroup) {
|
|
2103
|
+
ctx.log(`im-forward: non-bound-group message ${messageId} resolves locally; staying quiet after re-bind`);
|
|
2104
|
+
releaseInvalidatedEvent();
|
|
2105
|
+
return;
|
|
2106
|
+
}
|
|
1882
2107
|
await acceptRoutedMessage(route, event, meta, scope, address, sessionId);
|
|
1883
2108
|
} finally {
|
|
1884
2109
|
scopes.delete(scope);
|
|
@@ -1915,7 +2140,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1915
2140
|
}
|
|
1916
2141
|
if (currentAfterSubmit) {
|
|
1917
2142
|
const rejectReason = scope.lastRejectReason;
|
|
1918
|
-
const notice = rejectReason ? `\u26A0\uFE0F
|
|
2143
|
+
const notice = rejectReason ? `\u26A0\uFE0F Message not submitted: ${rejectReason}` : `\u26A0\uFE0F Message intake failed; the task was not submitted. ${imageKeys.length ? "Check the attachments and retry." : "Please retry."}`;
|
|
1919
2144
|
ctx.ui.notify(
|
|
1920
2145
|
"im-forward: message was not accepted; no input submitted.",
|
|
1921
2146
|
"warning"
|
|
@@ -1976,7 +2201,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1976
2201
|
const boundSession = retrySessionIds.get(eventId);
|
|
1977
2202
|
retrySessionIds.delete(eventId);
|
|
1978
2203
|
void forwardMessage(
|
|
1979
|
-
`\u26A0\uFE0F
|
|
2204
|
+
`\u26A0\uFE0F Message intake failed (retries exhausted). Check the Pie terminal logs.`,
|
|
1980
2205
|
boundSession ?? currentSessionId ?? "",
|
|
1981
2206
|
++forwardCounter,
|
|
1982
2207
|
void 0,
|
|
@@ -2088,12 +2313,15 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
2088
2313
|
function stopGeneration(gen) {
|
|
2089
2314
|
if (gen.startup) clearTimeout(gen.startup);
|
|
2090
2315
|
return gen.stopping ??= Promise.resolve().then(() => gen.handle?.stop()).catch(() => {
|
|
2316
|
+
gen.stopFailed = true;
|
|
2091
2317
|
ctx.log(`im-forward: ${cfg.provider} consumer stop failed`);
|
|
2092
2318
|
}).then(() => {
|
|
2093
2319
|
gen.retired = true;
|
|
2094
2320
|
});
|
|
2095
2321
|
}
|
|
2096
2322
|
let consumerLock;
|
|
2323
|
+
let consumerSlotRetiring = false;
|
|
2324
|
+
let releaseImBinding;
|
|
2097
2325
|
let resolvedBindingKey;
|
|
2098
2326
|
function bindingKey() {
|
|
2099
2327
|
return resolvedBindingKey ?? `${cfg.provider}:${cfg.appId ?? (cfg.profile ? `profile:${cfg.profile}` : cfg.targetId)}`;
|
|
@@ -2115,28 +2343,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
2115
2343
|
}
|
|
2116
2344
|
let consumerStartupInFlight = false;
|
|
2117
2345
|
function residentAliveSomewhere() {
|
|
2118
|
-
|
|
2119
|
-
try {
|
|
2120
|
-
const dir = ipcDiscoveryRoot2();
|
|
2121
|
-
const entries = fs6.readdirSync(dir);
|
|
2122
|
-
for (const name of entries) {
|
|
2123
|
-
if (!name.endsWith(".json")) continue;
|
|
2124
|
-
try {
|
|
2125
|
-
const parsed = JSON.parse(fs6.readFileSync(pathJoin(dir, name), "utf8"));
|
|
2126
|
-
const unattended = parsed.unattended === true;
|
|
2127
|
-
if (unattended && typeof parsed.pid === "number" && parsed.pid > 0) {
|
|
2128
|
-
try {
|
|
2129
|
-
process.kill(parsed.pid, 0);
|
|
2130
|
-
return true;
|
|
2131
|
-
} catch {
|
|
2132
|
-
}
|
|
2133
|
-
}
|
|
2134
|
-
} catch {
|
|
2135
|
-
}
|
|
2136
|
-
}
|
|
2137
|
-
} catch {
|
|
2138
|
-
}
|
|
2139
|
-
return false;
|
|
2346
|
+
return !isManager && liveManagerForBinding(bindingKey());
|
|
2140
2347
|
}
|
|
2141
2348
|
function needsCanonicalResolution() {
|
|
2142
2349
|
return !resolvedBindingKey && !cfg.appId && !!cfg.profile && connection.canonicalAppId !== void 0;
|
|
@@ -2153,6 +2360,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
2153
2360
|
return resolved ? acquireClaimedSlot(resolved) : false;
|
|
2154
2361
|
}
|
|
2155
2362
|
function acquireClaimedSlot(binding) {
|
|
2363
|
+
if (!releaseImBinding) releaseImBinding = registerImBinding(binding);
|
|
2156
2364
|
if (consumerLock) return true;
|
|
2157
2365
|
if (!isManager && residentAliveSomewhere()) {
|
|
2158
2366
|
if (!dispatchMode) {
|
|
@@ -2166,17 +2374,26 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
2166
2374
|
const claim = tryClaimConsumer(
|
|
2167
2375
|
binding,
|
|
2168
2376
|
`pie-${currentSessionId ?? "unknown"}`,
|
|
2169
|
-
() => {
|
|
2170
|
-
|
|
2377
|
+
async () => {
|
|
2378
|
+
consumerSlotRetiring = true;
|
|
2379
|
+
ctx.log("im-forward: retiring event-hub consumer before releasing slot");
|
|
2380
|
+
if (restartTimer) clearTimeout(restartTimer);
|
|
2381
|
+
const retiringGeneration = generation;
|
|
2382
|
+
if (retiringGeneration) {
|
|
2383
|
+
await stopGeneration(retiringGeneration);
|
|
2384
|
+
if (retiringGeneration.stopFailed) throw new Error("Consumer stop failed; retaining slot");
|
|
2385
|
+
}
|
|
2386
|
+
consumer = null;
|
|
2387
|
+
consumerRecovering = false;
|
|
2388
|
+
consumerReady = false;
|
|
2171
2389
|
consumerLock = void 0;
|
|
2172
|
-
if (
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2390
|
+
if (!terminated) {
|
|
2391
|
+
restartTimer = setTimeout(() => {
|
|
2392
|
+
consumerSlotRetiring = false;
|
|
2393
|
+
void spawnConsumer();
|
|
2394
|
+
}, 15e3);
|
|
2395
|
+
restartTimer.unref?.();
|
|
2177
2396
|
}
|
|
2178
|
-
restartTimer = setTimeout(spawnConsumer, 15e3);
|
|
2179
|
-
restartTimer.unref?.();
|
|
2180
2397
|
},
|
|
2181
2398
|
// STAND-IN GAP FIX part 2 (dogfood 11-13): the claim-time gate alone was
|
|
2182
2399
|
// not enough — a TUI that had ALREADY claimed kept the feed while a
|
|
@@ -2206,14 +2423,14 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
2206
2423
|
async function spawnConsumer() {
|
|
2207
2424
|
restartTimer = void 0;
|
|
2208
2425
|
restartDueAt = void 0;
|
|
2209
|
-
if (terminated || suspended || consumer || consumerRecovering) return;
|
|
2426
|
+
if (terminated || suspended || consumerSlotRetiring || generation?.stopFailed || consumer || consumerRecovering) return;
|
|
2210
2427
|
if (needsCanonicalResolution()) {
|
|
2211
2428
|
if (consumerStartupInFlight) return;
|
|
2212
2429
|
consumerStartupInFlight = true;
|
|
2213
2430
|
let key2;
|
|
2214
2431
|
try {
|
|
2215
2432
|
key2 = await resolveBindingKey();
|
|
2216
|
-
if (terminated || suspended || consumer || consumerRecovering) return;
|
|
2433
|
+
if (terminated || suspended || consumerSlotRetiring || generation?.stopFailed || consumer || consumerRecovering) return;
|
|
2217
2434
|
} finally {
|
|
2218
2435
|
consumerStartupInFlight = false;
|
|
2219
2436
|
}
|
|
@@ -2247,7 +2464,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
2247
2464
|
const recover = () => {
|
|
2248
2465
|
if (!gen.installed) return;
|
|
2249
2466
|
void stopGeneration(gen).then(() => {
|
|
2250
|
-
if (generation !== gen) return;
|
|
2467
|
+
if (generation !== gen || gen.stopFailed || consumerSlotRetiring) return;
|
|
2251
2468
|
consumer = null;
|
|
2252
2469
|
consumerRecovering = false;
|
|
2253
2470
|
if (terminated || suspended) return;
|
|
@@ -2325,6 +2542,8 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
2325
2542
|
};
|
|
2326
2543
|
inputEpoch++;
|
|
2327
2544
|
suspended = true;
|
|
2545
|
+
releaseImBinding?.();
|
|
2546
|
+
releaseImBinding = void 0;
|
|
2328
2547
|
const gen = generation;
|
|
2329
2548
|
if (restartTimer) {
|
|
2330
2549
|
suspendedRestartInMs = restartDueAt !== void 0 ? Math.max(0, restartDueAt - Date.now()) : 0;
|
|
@@ -2366,12 +2585,13 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
2366
2585
|
ctx.registerCleanup?.(async () => {
|
|
2367
2586
|
inputEpoch++;
|
|
2368
2587
|
terminated = true;
|
|
2588
|
+
releaseImBinding?.();
|
|
2589
|
+
releaseImBinding = void 0;
|
|
2369
2590
|
clearInterval(busHealthTimer);
|
|
2370
2591
|
clearInterval(dispatchTagTimer);
|
|
2371
2592
|
registerDispatchReceiver(void 0);
|
|
2372
2593
|
registerTurnImDriver(void 0);
|
|
2373
|
-
|
|
2374
|
-
consumerLock = void 0;
|
|
2594
|
+
consumerSlotRetiring = true;
|
|
2375
2595
|
const resources = [...scopes];
|
|
2376
2596
|
scopes.clear();
|
|
2377
2597
|
for (const { timer } of retryTimers.values()) clearTimeout(timer);
|
|
@@ -2388,6 +2608,10 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
2388
2608
|
Promise.resolve().then(() => connection.dispose?.()),
|
|
2389
2609
|
generation ? stopGeneration(generation) : Promise.resolve()
|
|
2390
2610
|
]);
|
|
2611
|
+
if (!generation?.stopFailed && !results.some((result) => result.status === "rejected")) {
|
|
2612
|
+
consumerLock?.release();
|
|
2613
|
+
consumerLock = void 0;
|
|
2614
|
+
}
|
|
2391
2615
|
consumer = null;
|
|
2392
2616
|
if (results.some((result) => result.status === "rejected"))
|
|
2393
2617
|
ctx.log(`im-forward: ${cfg.provider} resource cleanup failed`);
|
|
@@ -2493,12 +2717,12 @@ async function probeCardActionSubscription(ctx, cwd, binaryOverride, profile) {
|
|
|
2493
2717
|
const { spawn: spawn5 } = await import("node:child_process");
|
|
2494
2718
|
const binary = binaryOverride ?? await settingsProbeBinary();
|
|
2495
2719
|
if (!binary) return;
|
|
2496
|
-
await new Promise((
|
|
2720
|
+
await new Promise((resolve5) => {
|
|
2497
2721
|
let settled = false;
|
|
2498
2722
|
const done = () => {
|
|
2499
2723
|
if (!settled) {
|
|
2500
2724
|
settled = true;
|
|
2501
|
-
|
|
2725
|
+
resolve5();
|
|
2502
2726
|
}
|
|
2503
2727
|
};
|
|
2504
2728
|
const timer = setTimeout(() => {
|
|
@@ -2607,7 +2831,7 @@ function stopOwnedTreeInner(child, signal) {
|
|
|
2607
2831
|
}
|
|
2608
2832
|
}
|
|
2609
2833
|
}
|
|
2610
|
-
return new Promise((
|
|
2834
|
+
return new Promise((resolve5) => {
|
|
2611
2835
|
let done = false;
|
|
2612
2836
|
let killer;
|
|
2613
2837
|
const finish = (ok) => {
|
|
@@ -2620,7 +2844,7 @@ function stopOwnedTreeInner(child, signal) {
|
|
|
2620
2844
|
} catch {
|
|
2621
2845
|
}
|
|
2622
2846
|
}
|
|
2623
|
-
|
|
2847
|
+
resolve5(ok);
|
|
2624
2848
|
};
|
|
2625
2849
|
const timer = setTimeout(() => {
|
|
2626
2850
|
try {
|
|
@@ -2675,14 +2899,14 @@ function shutdownConsumer(child) {
|
|
|
2675
2899
|
}
|
|
2676
2900
|
async function shutdownConsumerInner(child) {
|
|
2677
2901
|
let closed = false;
|
|
2678
|
-
const close = new Promise((
|
|
2902
|
+
const close = new Promise((resolve5) => child.once("close", () => {
|
|
2679
2903
|
closed = true;
|
|
2680
|
-
|
|
2904
|
+
resolve5();
|
|
2681
2905
|
}));
|
|
2682
2906
|
const wait = async (ms) => {
|
|
2683
2907
|
let timer;
|
|
2684
|
-
await Promise.race([close, new Promise((
|
|
2685
|
-
timer = setTimeout(
|
|
2908
|
+
await Promise.race([close, new Promise((resolve5) => {
|
|
2909
|
+
timer = setTimeout(resolve5, ms);
|
|
2686
2910
|
})]);
|
|
2687
2911
|
clearTimeout(timer);
|
|
2688
2912
|
};
|
|
@@ -2706,9 +2930,9 @@ async function shutdownConsumerInner(child) {
|
|
|
2706
2930
|
|
|
2707
2931
|
// builtin/extensions/im-forward/lark-cli.ts
|
|
2708
2932
|
async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
|
|
2709
|
-
return new Promise((
|
|
2933
|
+
return new Promise((resolve5) => {
|
|
2710
2934
|
if (options.signal?.aborted) {
|
|
2711
|
-
|
|
2935
|
+
resolve5({ stdout: "", error: "cancelled" });
|
|
2712
2936
|
return;
|
|
2713
2937
|
}
|
|
2714
2938
|
let child;
|
|
@@ -2723,7 +2947,7 @@ async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
|
|
|
2723
2947
|
...cwd ? { cwd } : {}
|
|
2724
2948
|
});
|
|
2725
2949
|
} catch {
|
|
2726
|
-
|
|
2950
|
+
resolve5({ stdout: "", error: "spawn failed" });
|
|
2727
2951
|
return;
|
|
2728
2952
|
}
|
|
2729
2953
|
let stdout = "";
|
|
@@ -2741,7 +2965,7 @@ async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
|
|
|
2741
2965
|
clearTimeout(killTimer);
|
|
2742
2966
|
clearTimeout(closeTimer);
|
|
2743
2967
|
options.signal?.removeEventListener("abort", abort);
|
|
2744
|
-
|
|
2968
|
+
resolve5(result);
|
|
2745
2969
|
};
|
|
2746
2970
|
const terminatedResult = () => ({ stdout: termination?.startsWith("timeout") ? stdout : "", error: termination });
|
|
2747
2971
|
const stop = (signal) => {
|
|
@@ -2951,7 +3175,7 @@ async function openBrowser(url, signal, seam = {}) {
|
|
|
2951
3175
|
if (signal.aborted || !/^https:\/\/[^\s\x00-\x1f\x7f]+$/.test(url)) return "failed";
|
|
2952
3176
|
const spec = browserLaunch(seam.platform);
|
|
2953
3177
|
if (!spec) return "failed";
|
|
2954
|
-
return new Promise((
|
|
3178
|
+
return new Promise((resolve5) => {
|
|
2955
3179
|
let child;
|
|
2956
3180
|
let settled = false;
|
|
2957
3181
|
let stopping = false;
|
|
@@ -2966,7 +3190,7 @@ async function openBrowser(url, signal, seam = {}) {
|
|
|
2966
3190
|
child?.stdin?.destroy();
|
|
2967
3191
|
child?.stdout?.destroy();
|
|
2968
3192
|
child?.stderr?.destroy();
|
|
2969
|
-
|
|
3193
|
+
resolve5(result);
|
|
2970
3194
|
};
|
|
2971
3195
|
const stop = () => {
|
|
2972
3196
|
if (settled || stopping) return;
|
|
@@ -3501,7 +3725,8 @@ ${detect.error ?? ""}`);
|
|
|
3501
3725
|
}
|
|
3502
3726
|
|
|
3503
3727
|
// builtin/extensions/im-forward/providers/feishu/index.ts
|
|
3504
|
-
|
|
3728
|
+
var selfEchoDrops = { count: 0 };
|
|
3729
|
+
function normalizeEvent(line, botOpenId) {
|
|
3505
3730
|
let raw;
|
|
3506
3731
|
try {
|
|
3507
3732
|
raw = JSON.parse(line);
|
|
@@ -3514,13 +3739,17 @@ function normalizeEvent(line) {
|
|
|
3514
3739
|
const mentions = Array.isArray(raw.mentions) ? raw.mentions.filter((m) => isRecord(m)).map((m) => ({ id: typeof m.id === "string" ? m.id : void 0, name: typeof m.name === "string" ? m.name : void 0 })) : void 0;
|
|
3515
3740
|
let text = extractInboundText(raw.content).replace(/\[Image:\s*img_[A-Za-z0-9_-]+\]/g, "").trim();
|
|
3516
3741
|
const chatType = raw.chat_type === void 0 ? void 0 : typeof raw.chat_type === "string" ? raw.chat_type : "invalid";
|
|
3517
|
-
if (
|
|
3518
|
-
|
|
3519
|
-
if (
|
|
3520
|
-
|
|
3521
|
-
text = text.replace(new RegExp(`^(?:[^\\n]*\\n)?@${esc}\\s*`), "").trim();
|
|
3522
|
-
}
|
|
3742
|
+
if (botOpenId && typeof raw.sender_id === "string" && raw.sender_id === botOpenId) {
|
|
3743
|
+
selfEchoDrops.count += 1;
|
|
3744
|
+
if (selfEchoDrops.count <= 3) console.warn(`[im-forward] dropped self-echo event (message_id=${String(id ?? "?")}); subscription delivers our own messages`);
|
|
3745
|
+
return null;
|
|
3523
3746
|
}
|
|
3747
|
+
const selfMention = botOpenId ? mentions?.find((m) => m.id === botOpenId) : mentions?.[0];
|
|
3748
|
+
if (chatType === "group" && selfMention?.name) {
|
|
3749
|
+
const esc = selfMention.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
3750
|
+
text = text.replace(new RegExp(`^(?:[^\\n]*\\n)?@${esc}\\s*`), "").trim();
|
|
3751
|
+
}
|
|
3752
|
+
const isBotMentioned = chatType === "group" ? botOpenId ? mentions?.some((m) => m.id === botOpenId) === true : Boolean(mentions?.length) : void 0;
|
|
3524
3753
|
return {
|
|
3525
3754
|
event_id: raw.event_id,
|
|
3526
3755
|
message_id: id,
|
|
@@ -3529,7 +3758,8 @@ function normalizeEvent(line) {
|
|
|
3529
3758
|
chatType,
|
|
3530
3759
|
mentions: mentions?.length ? mentions : void 0,
|
|
3531
3760
|
text,
|
|
3532
|
-
images: extractImageKeys(raw.content)
|
|
3761
|
+
images: extractImageKeys(raw.content),
|
|
3762
|
+
isBotMentioned
|
|
3533
3763
|
};
|
|
3534
3764
|
}
|
|
3535
3765
|
function normalizeCardAction(line) {
|
|
@@ -3808,7 +4038,23 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
|
|
|
3808
4038
|
return void 0;
|
|
3809
4039
|
}
|
|
3810
4040
|
};
|
|
3811
|
-
const
|
|
4041
|
+
const botIdentity = { openId: void 0, attempts: 0, pending: false };
|
|
4042
|
+
const resolveBotIdentity = () => {
|
|
4043
|
+
if (botIdentity.openId || botIdentity.pending || botIdentity.attempts >= 3) return;
|
|
4044
|
+
botIdentity.pending = true;
|
|
4045
|
+
botIdentity.attempts += 1;
|
|
4046
|
+
void call(["api", "GET", "/open-apis/bot/v3/info", "--as", "bot"]).then((info) => {
|
|
4047
|
+
if (typeof info?.open_id === "string") botIdentity.openId = info.open_id;
|
|
4048
|
+
else console.warn(`[im-forward] bot identity lookup returned no open_id (attempt ${botIdentity.attempts}); gating stays on any-mention semantics`);
|
|
4049
|
+
}).catch(() => console.warn(`[im-forward] bot identity lookup failed (attempt ${botIdentity.attempts}); gating stays on any-mention semantics`)).finally(() => {
|
|
4050
|
+
botIdentity.pending = false;
|
|
4051
|
+
});
|
|
4052
|
+
};
|
|
4053
|
+
const child = spawnConsume("im.message.receive_v1", (line) => {
|
|
4054
|
+
const event = normalizeEvent(line, botIdentity.openId);
|
|
4055
|
+
if (event?.chatType === "group" || event?.chatType === "p2p") resolveBotIdentity();
|
|
4056
|
+
return event;
|
|
4057
|
+
}, true);
|
|
3812
4058
|
{
|
|
3813
4059
|
const errors = lineReader((line) => {
|
|
3814
4060
|
const text = line.trim();
|