@cydm/pie 4.4.3 → 4.5.1
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/README.md +24 -0
- package/dist/builtin/extensions/cron/index.js +1 -1
- package/dist/builtin/extensions/im-forward/index.js +272 -83
- package/dist/builtin/extensions/memory/index.js +2 -2
- package/dist/builtin/extensions/pie-ipc/README.md +1 -1
- package/dist/builtin/extensions/pie-ipc/index.js +30 -6
- package/dist/builtin/extensions/pie-proc/index.js +10 -2
- package/dist/builtin/extensions/plan-mode/index.js +4 -4
- package/dist/chunks/{chunk-JMKLTTZQ.js → chunk-2CJIENLY.js} +1 -0
- package/dist/chunks/{chunk-X6LBWHK3.js → chunk-7RJXKN7N.js} +1 -1
- package/dist/chunks/{manager-cli-WEHNUV5T.js → manager-cli-T26F3FUW.js} +299 -141
- package/dist/chunks/manager-upgrade-YVHK3XZE.js +582 -0
- package/dist/cli.js +62 -10
- package/package.json +2 -2
|
@@ -32,7 +32,7 @@ import {
|
|
|
32
32
|
truncateMarkdown,
|
|
33
33
|
tryClaimConsumer,
|
|
34
34
|
writeConfig
|
|
35
|
-
} from "../../../chunks/chunk-
|
|
35
|
+
} from "../../../chunks/chunk-2CJIENLY.js";
|
|
36
36
|
import {
|
|
37
37
|
detectImageMime,
|
|
38
38
|
readImageFormat
|
|
@@ -43,7 +43,7 @@ import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
|
43
43
|
// builtin/extensions/im-forward/runtime.ts
|
|
44
44
|
import * as crypto from "node:crypto";
|
|
45
45
|
import * as fs6 from "node:fs";
|
|
46
|
-
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";
|
|
47
47
|
import * as os3 from "node:os";
|
|
48
48
|
|
|
49
49
|
// builtin/extensions/im-forward/thread-registry.ts
|
|
@@ -333,6 +333,7 @@ function threadOwner(input) {
|
|
|
333
333
|
import * as fs2 from "node:fs";
|
|
334
334
|
import * as os2 from "node:os";
|
|
335
335
|
import * as path3 from "node:path";
|
|
336
|
+
import { fileURLToPath } from "node:url";
|
|
336
337
|
|
|
337
338
|
// builtin/extensions/im-forward/discovery.ts
|
|
338
339
|
import * as os from "node:os";
|
|
@@ -361,7 +362,7 @@ function parsePanelCommand(text) {
|
|
|
361
362
|
cmd = next?.[1] ?? "";
|
|
362
363
|
rest = next?.[2] ?? "";
|
|
363
364
|
}
|
|
364
|
-
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") {
|
|
365
366
|
if (!/^panel\.model\.[A-Za-z0-9-]+\..+$/.test(cmd)) return void 0;
|
|
366
367
|
}
|
|
367
368
|
const leadingFlag = /^--restricted(?:\s+|$)/.exec(rest);
|
|
@@ -400,7 +401,8 @@ function scanPeers() {
|
|
|
400
401
|
sessionTitle: typeof parsed.displaySessionName === "string" && parsed.displaySessionName.trim() ? parsed.displaySessionName.trim() : void 0,
|
|
401
402
|
project: typeof parsed.cwd === "string" && parsed.cwd ? parsed.cwd.split("/").filter(Boolean).at(-1) : void 0,
|
|
402
403
|
currentTool: typeof parsed.currentTool === "string" && parsed.currentTool ? parsed.currentTool : void 0,
|
|
403
|
-
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
|
|
404
406
|
});
|
|
405
407
|
} catch {
|
|
406
408
|
}
|
|
@@ -414,32 +416,67 @@ function composePanel() {
|
|
|
414
416
|
const rows = peers.map((p) => {
|
|
415
417
|
const title = p.sessionTitle ?? p.name;
|
|
416
418
|
const state = p.state === "working" && p.currentTool ? `working\xB7${p.currentTool}` : p.state;
|
|
417
|
-
const project = p.project && p.project !== title ?
|
|
418
|
-
return `| ${title}${project} | ${p.model ?? "\u2014"} | ${state} |
|
|
419
|
-
| \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} | | | |`;
|
|
420
422
|
});
|
|
423
|
+
const upgradeLine = upgradeSummaryLine();
|
|
421
424
|
const body = [
|
|
422
|
-
peers.length > 0 ? `|
|
|
423
|
-
|
|
424
|
-
${rows.join("\n")}` : "
|
|
425
|
+
peers.length > 0 ? `| Session | Model | State | Ver |
|
|
426
|
+
|---|---|---|---|
|
|
427
|
+
${rows.join("\n")}` : "_No live pie sessions_",
|
|
425
428
|
``,
|
|
426
|
-
|
|
427
|
-
|
|
429
|
+
upgradeLine,
|
|
430
|
+
`${peers.length} session(s) \xB7 ${(/* @__PURE__ */ new Date()).toLocaleTimeString("en-GB", { hour12: false })}`
|
|
431
|
+
].filter((line) => line !== void 0).join("\n");
|
|
428
432
|
return {
|
|
429
|
-
title: "Pie
|
|
430
|
-
subtitle: `${os2.hostname()} \xB7 ${peers.length} \
|
|
433
|
+
title: "Pie Panel",
|
|
434
|
+
subtitle: `${os2.hostname()} \xB7 ${peers.length} session(s) \xB7 pie ${pieVersion()}`,
|
|
431
435
|
color: "blue",
|
|
432
436
|
body,
|
|
433
437
|
// r1-P2: only REGISTERED commands get buttons — unmapped ids would fall
|
|
434
438
|
// through to an LLM turn (a button press must never spend a model turn).
|
|
435
439
|
actions: [
|
|
436
|
-
{ id: "panel.refresh", label: "\u{1F504}
|
|
437
|
-
{ id: "panel.summon", label: "\u{1F4CB}
|
|
438
|
-
{ id: "panel.models", label: "\u{1F39A}
|
|
439
|
-
{ 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" }
|
|
440
445
|
]
|
|
441
446
|
};
|
|
442
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
|
+
}
|
|
443
480
|
function candidateModels() {
|
|
444
481
|
const out = /* @__PURE__ */ new Set();
|
|
445
482
|
try {
|
|
@@ -463,26 +500,51 @@ function executePanelCommand(input) {
|
|
|
463
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}` }))
|
|
464
501
|
).slice(0, 18);
|
|
465
502
|
return { spec: {
|
|
466
|
-
title: "
|
|
467
|
-
subtitle: `${peers.length}
|
|
503
|
+
title: "Switch Model",
|
|
504
|
+
subtitle: `${peers.length} session(s) \xD7 ${models.length} candidates`,
|
|
468
505
|
color: "violet",
|
|
469
506
|
body: [
|
|
470
|
-
peers.length > 0 ? `|
|
|
507
|
+
peers.length > 0 ? `| Session | Model |
|
|
471
508
|
|---|---|
|
|
472
|
-
${rows.join("\n")}` : "
|
|
509
|
+
${rows.join("\n")}` : "_No live pie sessions_",
|
|
473
510
|
``,
|
|
474
|
-
|
|
511
|
+
`Candidates: ${models.join(" \xB7 ") || "(models.json unreadable)"}`,
|
|
475
512
|
``,
|
|
476
|
-
"
|
|
513
|
+
"Each button maps a session to a model. Tapping sends a model.set control frame (zero LLM, nothing enters the peer history)."
|
|
477
514
|
].join("\n"),
|
|
478
|
-
actions: actions.length > 0 ? actions : [{ id: "panel.summon", label: "\u21A9\uFE0F
|
|
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)`,
|
|
529
|
+
``,
|
|
530
|
+
last,
|
|
531
|
+
``,
|
|
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."
|
|
534
|
+
].join("\n"),
|
|
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
|
+
]
|
|
479
541
|
}, patchOrigin: false };
|
|
480
542
|
}
|
|
481
543
|
if (input.cmd === "panel.help") {
|
|
482
544
|
return { spec: {
|
|
483
|
-
title: "
|
|
484
|
-
body: "`/panel`
|
|
485
|
-
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" }]
|
|
486
548
|
}, patchOrigin: false };
|
|
487
549
|
}
|
|
488
550
|
return { spec: composePanel(), patchOrigin: input.cmd === "panel.refresh" && input.originCardId !== void 0 };
|
|
@@ -560,7 +622,7 @@ var SYNTHETIC_SENDER = (() => {
|
|
|
560
622
|
return `pie-${hex.slice(0, 12)}`;
|
|
561
623
|
})();
|
|
562
624
|
function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
|
|
563
|
-
return new Promise((
|
|
625
|
+
return new Promise((resolve5) => {
|
|
564
626
|
const id = randomUUID2();
|
|
565
627
|
const envelope = {
|
|
566
628
|
v: IPC_PROTOCOL_VERSION,
|
|
@@ -588,7 +650,7 @@ function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
|
|
|
588
650
|
settled = true;
|
|
589
651
|
clearTimeout(timer);
|
|
590
652
|
socket.destroy();
|
|
591
|
-
|
|
653
|
+
resolve5(ok);
|
|
592
654
|
};
|
|
593
655
|
const timer = setTimeout(() => finish(false), 5e3);
|
|
594
656
|
socket.once("error", () => finish(false));
|
|
@@ -734,7 +796,7 @@ var RESTART_BACKOFF_MIN_MS = 5e3;
|
|
|
734
796
|
var RESTART_BACKOFF_MAX_MS = 6e4;
|
|
735
797
|
var SEND_FAILURE_NOTIFY_THROTTLE_MS = 5 * 60 * 1e3;
|
|
736
798
|
var CHUNK_RETRY_DELAY_MS = 2e3;
|
|
737
|
-
var delay = (ms) => new Promise((
|
|
799
|
+
var delay = (ms) => new Promise((resolve5) => setTimeout(resolve5, ms));
|
|
738
800
|
var MAX_INBOUND_RETRIES = 3;
|
|
739
801
|
var DEFAULT_INBOUND_RETRY_BACKOFF_MS = 5e3;
|
|
740
802
|
var MAX_PENDING_IM_INPUTS = 50;
|
|
@@ -757,7 +819,7 @@ function summarizeFailureReason(reason) {
|
|
|
757
819
|
return { summary: "network problem", persistent: false };
|
|
758
820
|
return { summary: "provider exited", persistent: false };
|
|
759
821
|
}
|
|
760
|
-
var IM_INPUT_FALLBACK_CAPTION = "
|
|
822
|
+
var IM_INPUT_FALLBACK_CAPTION = "Please review these images and respond.";
|
|
761
823
|
function hashText(input) {
|
|
762
824
|
let hash = 0;
|
|
763
825
|
for (let i = 0; i < input.length; i++) {
|
|
@@ -812,7 +874,7 @@ async function applyModelControl(peerRef, model) {
|
|
|
812
874
|
}
|
|
813
875
|
} catch {
|
|
814
876
|
}
|
|
815
|
-
if (!target) return { ok: false, detail:
|
|
877
|
+
if (!target) return { ok: false, detail: `Session not found: ${peerRef}` };
|
|
816
878
|
const envelope = signEnvelope({
|
|
817
879
|
v: IPC_PROTOCOL_VERSION,
|
|
818
880
|
id: `panel-model-${Date.now()}`,
|
|
@@ -823,7 +885,7 @@ async function applyModelControl(peerRef, model) {
|
|
|
823
885
|
createdAt: Date.now(),
|
|
824
886
|
text: JSON.stringify({ control: "model.set", payload: { model } })
|
|
825
887
|
}, target.secret);
|
|
826
|
-
return await new Promise((
|
|
888
|
+
return await new Promise((resolve5) => {
|
|
827
889
|
let settled = false;
|
|
828
890
|
const finish = (ok, detail) => {
|
|
829
891
|
if (settled) return;
|
|
@@ -832,15 +894,15 @@ async function applyModelControl(peerRef, model) {
|
|
|
832
894
|
sock.destroy();
|
|
833
895
|
} catch {
|
|
834
896
|
}
|
|
835
|
-
|
|
897
|
+
resolve5({ ok, detail });
|
|
836
898
|
};
|
|
837
899
|
const sock = net2.connect({ host: "127.0.0.1", port: target.port }, () => {
|
|
838
900
|
sock.write(JSON.stringify(envelope) + "\n");
|
|
839
901
|
});
|
|
840
|
-
sock.setTimeout(6e3, () => finish(false, "\
|
|
841
|
-
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)}`));
|
|
842
904
|
sock.on("close", () => {
|
|
843
|
-
if (!settled) finish(false, "
|
|
905
|
+
if (!settled) finish(false, "Peer closed the connection (policy refusal or rejected frame; resending is safe)");
|
|
844
906
|
});
|
|
845
907
|
sock.on("data", (buffer) => {
|
|
846
908
|
for (const line of buffer.toString("utf8").split("\n")) {
|
|
@@ -849,7 +911,7 @@ async function applyModelControl(peerRef, model) {
|
|
|
849
911
|
const parsed = JSON.parse(line);
|
|
850
912
|
if (parsed.kind === "ack" || parsed.kind === "result") {
|
|
851
913
|
const refused = /"ok"\s*:\s*false|error|拒绝|invalid|unknown|refus|denied/i.test(parsed.text ?? "");
|
|
852
|
-
finish(!refused,
|
|
914
|
+
finish(!refused, `Peer receipt: ${parsed.text ?? "(empty)"}`);
|
|
853
915
|
return;
|
|
854
916
|
}
|
|
855
917
|
} catch {
|
|
@@ -925,7 +987,7 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
|
925
987
|
busStale = next;
|
|
926
988
|
if (next) {
|
|
927
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");
|
|
928
|
-
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");
|
|
929
991
|
}
|
|
930
992
|
updateFooterTag();
|
|
931
993
|
}
|
|
@@ -1289,9 +1351,9 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1289
1351
|
const attribution = resolveOutboundAttribution(sessionId);
|
|
1290
1352
|
const deliverTf = /* @__PURE__ */ new Map();
|
|
1291
1353
|
if (!outboundRoleAllows(attribution, deliverTf)) return;
|
|
1292
|
-
const recoveryHint =
|
|
1354
|
+
const recoveryHint = `Your input is still in the session \u2014 reply "redo the last one" to answer from it again without resending the original request.`;
|
|
1293
1355
|
void forwardMessage(
|
|
1294
|
-
`\u26A0\uFE0F
|
|
1356
|
+
`\u26A0\uFE0F Task failed: ${reason} (retries exhausted)
|
|
1295
1357
|
${recoveryHint}`,
|
|
1296
1358
|
sessionId,
|
|
1297
1359
|
sequence,
|
|
@@ -1311,7 +1373,7 @@ ${recoveryHint}`,
|
|
|
1311
1373
|
const deliverTc = /* @__PURE__ */ new Map();
|
|
1312
1374
|
if (!outboundRoleAllows(attribution, deliverTc)) return;
|
|
1313
1375
|
void forwardMessage(
|
|
1314
|
-
`\u26D4\uFE0F
|
|
1376
|
+
`\u26D4\uFE0F Task cancelled: ${event.reason}`,
|
|
1315
1377
|
sessionId,
|
|
1316
1378
|
sequence,
|
|
1317
1379
|
attribution?.caption,
|
|
@@ -1361,8 +1423,8 @@ ${recoveryHint}`,
|
|
|
1361
1423
|
};
|
|
1362
1424
|
const claimStake = () => {
|
|
1363
1425
|
let release;
|
|
1364
|
-
const token = new Promise((
|
|
1365
|
-
release =
|
|
1426
|
+
const token = new Promise((resolve5) => {
|
|
1427
|
+
release = resolve5;
|
|
1366
1428
|
});
|
|
1367
1429
|
token.release = release;
|
|
1368
1430
|
anchorStakeFlights.set(sessionId, token);
|
|
@@ -1522,7 +1584,7 @@ ${recoveryHint}`,
|
|
|
1522
1584
|
"send notice",
|
|
1523
1585
|
() => connection.send(
|
|
1524
1586
|
cfg.targetId,
|
|
1525
|
-
`\u2026(
|
|
1587
|
+
`\u2026(chunked delivery failed after part ${index}/${chunks.length}; full content is in the terminal)`,
|
|
1526
1588
|
chunkKey(baseKey, index, "fail"),
|
|
1527
1589
|
anchor
|
|
1528
1590
|
)
|
|
@@ -1575,12 +1637,12 @@ ${recoveryHint}`,
|
|
|
1575
1637
|
}
|
|
1576
1638
|
if (failedFiles.length > 0 && !terminated && isForwardingEnabled()) {
|
|
1577
1639
|
const names = failedFiles.slice(0, 5).map((name) => name.replace(/[\r\n]/g, " ").slice(0, 80)).join("\u3001");
|
|
1578
|
-
const extra = failedFiles.length > 5 ?
|
|
1640
|
+
const extra = failedFiles.length > 5 ? ` (+${failedFiles.length - 5} more)` : "";
|
|
1579
1641
|
await providerCall(
|
|
1580
1642
|
"send attachment notice",
|
|
1581
1643
|
() => connection.send(
|
|
1582
1644
|
cfg.targetId,
|
|
1583
|
-
|
|
1645
|
+
`Attachment upload failed: ${names}${extra}. Check the files in the terminal.`,
|
|
1584
1646
|
chunkKey(baseKey, files.length, "fail"),
|
|
1585
1647
|
anchor
|
|
1586
1648
|
)
|
|
@@ -1728,7 +1790,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1728
1790
|
if (panelCmd.restricted && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id))) {
|
|
1729
1791
|
ctx.log(`im-forward: restricted panel action ${panelCmd.cmd} refused for ${event.sender_id ?? "unknown"} (not in allowUsers)`);
|
|
1730
1792
|
try {
|
|
1731
|
-
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}`);
|
|
1732
1794
|
} catch {
|
|
1733
1795
|
}
|
|
1734
1796
|
return;
|
|
@@ -1739,11 +1801,11 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1739
1801
|
const receipt = await applyModelControl(peerRef, model);
|
|
1740
1802
|
if (!isCurrent()) return;
|
|
1741
1803
|
const spec = {
|
|
1742
|
-
title: "
|
|
1804
|
+
title: "Model Switch Result",
|
|
1743
1805
|
body: `${receipt.ok ? "\u2705" : "\u26A0\uFE0F"} ${model} \u2192 ${peerRef}
|
|
1744
1806
|
|
|
1745
1807
|
${receipt.detail}`,
|
|
1746
|
-
actions: [{ id: "panel.models", label: "\u21A9\uFE0F
|
|
1808
|
+
actions: [{ id: "panel.models", label: "\u21A9\uFE0F Back to model panel" }]
|
|
1747
1809
|
};
|
|
1748
1810
|
try {
|
|
1749
1811
|
if (connection.sendCard) {
|
|
@@ -1755,6 +1817,89 @@ ${spec.body}`, `panel-model-${event.event_id}`);
|
|
|
1755
1817
|
}
|
|
1756
1818
|
return;
|
|
1757
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
|
+
}
|
|
1758
1903
|
const result = executePanelCommand({ ...panelCmd, senderId: event.sender_id, originCardId: event.message_id });
|
|
1759
1904
|
try {
|
|
1760
1905
|
if (result.patchOrigin && connection.patch && event.message_id) {
|
|
@@ -1772,7 +1917,7 @@ ${spec.body}`, `panel-model-${event.event_id}`);
|
|
|
1772
1917
|
if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
|
|
1773
1918
|
ctx.log(`im-forward: panel card sent (${panelCmd.cmd})`);
|
|
1774
1919
|
} else {
|
|
1775
|
-
await connection.send(event.chat_id, `**${result.spec.title ?? "
|
|
1920
|
+
await connection.send(event.chat_id, `**${result.spec.title ?? "Panel"}**
|
|
1776
1921
|
${result.spec.body}`, `panel-${event.event_id}`);
|
|
1777
1922
|
}
|
|
1778
1923
|
} catch (error) {
|
|
@@ -1780,8 +1925,13 @@ ${result.spec.body}`, `panel-${event.event_id}`);
|
|
|
1780
1925
|
}
|
|
1781
1926
|
};
|
|
1782
1927
|
async function handleInboundEventInner(event, retry) {
|
|
1928
|
+
let nonBoundGroup = false;
|
|
1783
1929
|
const isGroup = event.chatType === "group";
|
|
1784
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
|
+
}
|
|
1785
1935
|
if (cfg.groupAccess === "off") {
|
|
1786
1936
|
ctx.log("im-forward: group event refused (off)");
|
|
1787
1937
|
return;
|
|
@@ -1812,6 +1962,13 @@ ${result.spec.body}`, `panel-${event.event_id}`);
|
|
|
1812
1962
|
}
|
|
1813
1963
|
const address = resolveInboundAddress(event.text);
|
|
1814
1964
|
if (address.kind === "other") {
|
|
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
|
+
}
|
|
1815
1972
|
if (consumerLock) {
|
|
1816
1973
|
const epoch2 = inputEpoch;
|
|
1817
1974
|
const session = currentSessionId;
|
|
@@ -1853,6 +2010,11 @@ ${result.spec.body}`, `panel-${event.event_id}`);
|
|
|
1853
2010
|
releaseInvalidatedEvent();
|
|
1854
2011
|
return;
|
|
1855
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
|
+
}
|
|
1856
2018
|
const pinnedSession = event.event_id ? retrySessionIds.get(key(event.event_id)) : void 0;
|
|
1857
2019
|
if (pinnedSession !== void 0 && pinnedSession !== sessionId) {
|
|
1858
2020
|
ctx.log(`im-forward: retry crossed a session switch (${pinnedSession} -> ${sessionId}); releasing for redelivery`);
|
|
@@ -1873,7 +2035,7 @@ ${result.spec.body}`, `panel-${event.event_id}`);
|
|
|
1873
2035
|
return;
|
|
1874
2036
|
}
|
|
1875
2037
|
const unanchored = !meta.replyTo && !meta.threadId;
|
|
1876
|
-
if (isManager && unanchored) {
|
|
2038
|
+
if (isManager && unanchored && !nonBoundGroup) {
|
|
1877
2039
|
const residentRoute = {
|
|
1878
2040
|
messageId: "",
|
|
1879
2041
|
threadId: meta.threadId ?? null,
|
|
@@ -1907,7 +2069,7 @@ ${result.spec.body}`, `panel-${event.event_id}`);
|
|
|
1907
2069
|
ctx.log(`im-forward: thread ownership unreadable for ${messageId}; dropping (fail closed)`);
|
|
1908
2070
|
return;
|
|
1909
2071
|
}
|
|
1910
|
-
if (isManager && meta.threadId && (event.chatType === "group" || event.chatType === "p2p")) {
|
|
2072
|
+
if (isManager && meta.threadId && !nonBoundGroup && (event.chatType === "group" || event.chatType === "p2p")) {
|
|
1911
2073
|
if (!scope.isCurrent()) {
|
|
1912
2074
|
releaseInvalidatedEvent();
|
|
1913
2075
|
return;
|
|
@@ -1937,6 +2099,11 @@ ${result.spec.body}`, `panel-${event.event_id}`);
|
|
|
1937
2099
|
releaseInvalidatedEvent();
|
|
1938
2100
|
return;
|
|
1939
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
|
+
}
|
|
1940
2107
|
await acceptRoutedMessage(route, event, meta, scope, address, sessionId);
|
|
1941
2108
|
} finally {
|
|
1942
2109
|
scopes.delete(scope);
|
|
@@ -1973,7 +2140,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1973
2140
|
}
|
|
1974
2141
|
if (currentAfterSubmit) {
|
|
1975
2142
|
const rejectReason = scope.lastRejectReason;
|
|
1976
|
-
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."}`;
|
|
1977
2144
|
ctx.ui.notify(
|
|
1978
2145
|
"im-forward: message was not accepted; no input submitted.",
|
|
1979
2146
|
"warning"
|
|
@@ -2034,7 +2201,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
2034
2201
|
const boundSession = retrySessionIds.get(eventId);
|
|
2035
2202
|
retrySessionIds.delete(eventId);
|
|
2036
2203
|
void forwardMessage(
|
|
2037
|
-
`\u26A0\uFE0F
|
|
2204
|
+
`\u26A0\uFE0F Message intake failed (retries exhausted). Check the Pie terminal logs.`,
|
|
2038
2205
|
boundSession ?? currentSessionId ?? "",
|
|
2039
2206
|
++forwardCounter,
|
|
2040
2207
|
void 0,
|
|
@@ -2550,12 +2717,12 @@ async function probeCardActionSubscription(ctx, cwd, binaryOverride, profile) {
|
|
|
2550
2717
|
const { spawn: spawn5 } = await import("node:child_process");
|
|
2551
2718
|
const binary = binaryOverride ?? await settingsProbeBinary();
|
|
2552
2719
|
if (!binary) return;
|
|
2553
|
-
await new Promise((
|
|
2720
|
+
await new Promise((resolve5) => {
|
|
2554
2721
|
let settled = false;
|
|
2555
2722
|
const done = () => {
|
|
2556
2723
|
if (!settled) {
|
|
2557
2724
|
settled = true;
|
|
2558
|
-
|
|
2725
|
+
resolve5();
|
|
2559
2726
|
}
|
|
2560
2727
|
};
|
|
2561
2728
|
const timer = setTimeout(() => {
|
|
@@ -2566,7 +2733,7 @@ async function probeCardActionSubscription(ctx, cwd, binaryOverride, profile) {
|
|
|
2566
2733
|
done();
|
|
2567
2734
|
}, 3500);
|
|
2568
2735
|
timer.unref?.();
|
|
2569
|
-
const child = spawn5(binary, ["event", "consume", "card.action.trigger", "--as", "bot", ...profile ? ["--profile", profile] : []], { cwd, stdio: ["ignore", "pipe", "pipe"] });
|
|
2736
|
+
const child = spawn5(binary, ["event", "consume", "card.action.trigger", "--as", "bot", ...profile ? ["--profile", profile] : []], { cwd, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
|
2570
2737
|
child.on("error", () => done());
|
|
2571
2738
|
child.on("close", () => done());
|
|
2572
2739
|
let out = "";
|
|
@@ -2577,8 +2744,8 @@ async function probeCardActionSubscription(ctx, cwd, binaryOverride, profile) {
|
|
|
2577
2744
|
const unsubscribed = /requires callbacks not subscribed/i.test(out);
|
|
2578
2745
|
if (unsubscribed) {
|
|
2579
2746
|
const launcher = /https:\/\/open\.feishu\.cn\/page\/launcher\?[^\s"]+/.exec(out)?.[0];
|
|
2580
|
-
ctx.ui.notify(
|
|
2581
|
-
|
|
2747
|
+
ctx.ui.notify(`Panel buttons require a one-time subscription to card.action.trigger. Without it, the panel still works through text commands.${launcher ? `
|
|
2748
|
+
Open this link and scan the QR code to subscribe: ${launcher}` : "\nIn the developer console, open Events & Callbacks and subscribe to card.action.trigger."}`, "info");
|
|
2582
2749
|
}
|
|
2583
2750
|
});
|
|
2584
2751
|
});
|
|
@@ -2586,7 +2753,7 @@ async function probeCardActionSubscription(ctx, cwd, binaryOverride, profile) {
|
|
|
2586
2753
|
async function settingsProbeBinary() {
|
|
2587
2754
|
try {
|
|
2588
2755
|
const { spawnSync } = await import("node:child_process");
|
|
2589
|
-
const which = spawnSync(process.platform === "win32" ? "where" : "which", ["lark-cli"], { encoding: "utf8", timeout: 3e3 });
|
|
2756
|
+
const which = spawnSync(process.platform === "win32" ? "where" : "which", ["lark-cli"], { encoding: "utf8", timeout: 3e3, windowsHide: true });
|
|
2590
2757
|
const path12 = which.stdout?.split(/\r?\n/)[0]?.trim();
|
|
2591
2758
|
return path12 || void 0;
|
|
2592
2759
|
} catch {
|
|
@@ -2664,7 +2831,7 @@ function stopOwnedTreeInner(child, signal) {
|
|
|
2664
2831
|
}
|
|
2665
2832
|
}
|
|
2666
2833
|
}
|
|
2667
|
-
return new Promise((
|
|
2834
|
+
return new Promise((resolve5) => {
|
|
2668
2835
|
let done = false;
|
|
2669
2836
|
let killer;
|
|
2670
2837
|
const finish = (ok) => {
|
|
@@ -2677,7 +2844,7 @@ function stopOwnedTreeInner(child, signal) {
|
|
|
2677
2844
|
} catch {
|
|
2678
2845
|
}
|
|
2679
2846
|
}
|
|
2680
|
-
|
|
2847
|
+
resolve5(ok);
|
|
2681
2848
|
};
|
|
2682
2849
|
const timer = setTimeout(() => {
|
|
2683
2850
|
try {
|
|
@@ -2732,14 +2899,14 @@ function shutdownConsumer(child) {
|
|
|
2732
2899
|
}
|
|
2733
2900
|
async function shutdownConsumerInner(child) {
|
|
2734
2901
|
let closed = false;
|
|
2735
|
-
const close = new Promise((
|
|
2902
|
+
const close = new Promise((resolve5) => child.once("close", () => {
|
|
2736
2903
|
closed = true;
|
|
2737
|
-
|
|
2904
|
+
resolve5();
|
|
2738
2905
|
}));
|
|
2739
2906
|
const wait = async (ms) => {
|
|
2740
2907
|
let timer;
|
|
2741
|
-
await Promise.race([close, new Promise((
|
|
2742
|
-
timer = setTimeout(
|
|
2908
|
+
await Promise.race([close, new Promise((resolve5) => {
|
|
2909
|
+
timer = setTimeout(resolve5, ms);
|
|
2743
2910
|
})]);
|
|
2744
2911
|
clearTimeout(timer);
|
|
2745
2912
|
};
|
|
@@ -2763,9 +2930,9 @@ async function shutdownConsumerInner(child) {
|
|
|
2763
2930
|
|
|
2764
2931
|
// builtin/extensions/im-forward/lark-cli.ts
|
|
2765
2932
|
async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
|
|
2766
|
-
return new Promise((
|
|
2933
|
+
return new Promise((resolve5) => {
|
|
2767
2934
|
if (options.signal?.aborted) {
|
|
2768
|
-
|
|
2935
|
+
resolve5({ stdout: "", error: "cancelled" });
|
|
2769
2936
|
return;
|
|
2770
2937
|
}
|
|
2771
2938
|
let child;
|
|
@@ -2780,7 +2947,7 @@ async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
|
|
|
2780
2947
|
...cwd ? { cwd } : {}
|
|
2781
2948
|
});
|
|
2782
2949
|
} catch {
|
|
2783
|
-
|
|
2950
|
+
resolve5({ stdout: "", error: "spawn failed" });
|
|
2784
2951
|
return;
|
|
2785
2952
|
}
|
|
2786
2953
|
let stdout = "";
|
|
@@ -2798,7 +2965,7 @@ async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
|
|
|
2798
2965
|
clearTimeout(killTimer);
|
|
2799
2966
|
clearTimeout(closeTimer);
|
|
2800
2967
|
options.signal?.removeEventListener("abort", abort);
|
|
2801
|
-
|
|
2968
|
+
resolve5(result);
|
|
2802
2969
|
};
|
|
2803
2970
|
const terminatedResult = () => ({ stdout: termination?.startsWith("timeout") ? stdout : "", error: termination });
|
|
2804
2971
|
const stop = (signal) => {
|
|
@@ -3008,7 +3175,7 @@ async function openBrowser(url, signal, seam = {}) {
|
|
|
3008
3175
|
if (signal.aborted || !/^https:\/\/[^\s\x00-\x1f\x7f]+$/.test(url)) return "failed";
|
|
3009
3176
|
const spec = browserLaunch(seam.platform);
|
|
3010
3177
|
if (!spec) return "failed";
|
|
3011
|
-
return new Promise((
|
|
3178
|
+
return new Promise((resolve5) => {
|
|
3012
3179
|
let child;
|
|
3013
3180
|
let settled = false;
|
|
3014
3181
|
let stopping = false;
|
|
@@ -3023,7 +3190,7 @@ async function openBrowser(url, signal, seam = {}) {
|
|
|
3023
3190
|
child?.stdin?.destroy();
|
|
3024
3191
|
child?.stdout?.destroy();
|
|
3025
3192
|
child?.stderr?.destroy();
|
|
3026
|
-
|
|
3193
|
+
resolve5(result);
|
|
3027
3194
|
};
|
|
3028
3195
|
const stop = () => {
|
|
3029
3196
|
if (settled || stopping) return;
|
|
@@ -3558,7 +3725,8 @@ ${detect.error ?? ""}`);
|
|
|
3558
3725
|
}
|
|
3559
3726
|
|
|
3560
3727
|
// builtin/extensions/im-forward/providers/feishu/index.ts
|
|
3561
|
-
|
|
3728
|
+
var selfEchoDrops = { count: 0 };
|
|
3729
|
+
function normalizeEvent(line, botOpenId) {
|
|
3562
3730
|
let raw;
|
|
3563
3731
|
try {
|
|
3564
3732
|
raw = JSON.parse(line);
|
|
@@ -3571,13 +3739,17 @@ function normalizeEvent(line) {
|
|
|
3571
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;
|
|
3572
3740
|
let text = extractInboundText(raw.content).replace(/\[Image:\s*img_[A-Za-z0-9_-]+\]/g, "").trim();
|
|
3573
3741
|
const chatType = raw.chat_type === void 0 ? void 0 : typeof raw.chat_type === "string" ? raw.chat_type : "invalid";
|
|
3574
|
-
if (
|
|
3575
|
-
|
|
3576
|
-
if (
|
|
3577
|
-
|
|
3578
|
-
|
|
3579
|
-
|
|
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;
|
|
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();
|
|
3580
3751
|
}
|
|
3752
|
+
const isBotMentioned = chatType === "group" ? botOpenId ? mentions?.some((m) => m.id === botOpenId) === true : Boolean(mentions?.length) : void 0;
|
|
3581
3753
|
return {
|
|
3582
3754
|
event_id: raw.event_id,
|
|
3583
3755
|
message_id: id,
|
|
@@ -3586,7 +3758,8 @@ function normalizeEvent(line) {
|
|
|
3586
3758
|
chatType,
|
|
3587
3759
|
mentions: mentions?.length ? mentions : void 0,
|
|
3588
3760
|
text,
|
|
3589
|
-
images: extractImageKeys(raw.content)
|
|
3761
|
+
images: extractImageKeys(raw.content),
|
|
3762
|
+
isBotMentioned
|
|
3590
3763
|
};
|
|
3591
3764
|
}
|
|
3592
3765
|
function normalizeCardAction(line) {
|
|
@@ -3865,7 +4038,23 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
|
|
|
3865
4038
|
return void 0;
|
|
3866
4039
|
}
|
|
3867
4040
|
};
|
|
3868
|
-
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);
|
|
3869
4058
|
{
|
|
3870
4059
|
const errors = lineReader((line) => {
|
|
3871
4060
|
const text = line.trim();
|