@cydm/pie 4.3.11 → 4.3.12
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 +1 -1
- package/dist/builtin/extensions/cron/index.js +76 -9
- package/dist/builtin/extensions/im-forward/README.md +17 -1
- package/dist/builtin/extensions/im-forward/index.js +478 -95
- package/dist/builtin/extensions/mcp-adapter/index.js +2 -2
- package/dist/builtin/extensions/memory/index.js +10 -3
- package/dist/builtin/extensions/pie-ipc/index.js +49 -268
- package/dist/builtin/extensions/pie-proc/index.js +1 -1
- package/dist/builtin/extensions/plan-mode/index.js +6 -5
- package/dist/builtin/extensions/subagent/index.js +15 -5
- package/dist/builtin/extensions/todo/index.js +6 -2
- package/dist/chunks/{chunk-DGXIR6CV.js → chunk-EGNGHINP.js} +516 -266
- package/dist/chunks/{chunk-ZAJEKDPV.js → chunk-GY47MKCJ.js} +2 -2
- package/dist/chunks/{chunk-KCZGLNRM.js → chunk-I7PBXG5Q.js} +1 -1
- package/dist/chunks/{chunk-LLCEO7ET.js → chunk-N5B5IGJ6.js} +350 -231
- package/dist/chunks/{src-5EZU72ZA.js → src-V2M7FLWY.js} +5 -1
- package/dist/cli.js +39 -6
- package/package.json +2 -2
|
@@ -26,10 +26,11 @@ import {
|
|
|
26
26
|
resolveImForwardConfig,
|
|
27
27
|
saveLocation,
|
|
28
28
|
sessionLabel,
|
|
29
|
+
signEnvelope,
|
|
29
30
|
truncateMarkdown,
|
|
30
31
|
tryClaimConsumer,
|
|
31
32
|
writeConfig
|
|
32
|
-
} from "../../../chunks/chunk-
|
|
33
|
+
} from "../../../chunks/chunk-EGNGHINP.js";
|
|
33
34
|
import {
|
|
34
35
|
detectImageMime,
|
|
35
36
|
readImageFormat
|
|
@@ -39,7 +40,7 @@ import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
|
39
40
|
// builtin/extensions/im-forward/runtime.ts
|
|
40
41
|
import * as crypto from "node:crypto";
|
|
41
42
|
import * as fs6 from "node:fs";
|
|
42
|
-
import { basename, join as pathJoin, resolve as pathResolve } from "node:path";
|
|
43
|
+
import { basename, join as pathJoin, resolve as pathResolve, join as join7 } from "node:path";
|
|
43
44
|
import * as os3 from "node:os";
|
|
44
45
|
|
|
45
46
|
// builtin/extensions/im-forward/thread-registry.ts
|
|
@@ -357,7 +358,9 @@ function parsePanelCommand(text) {
|
|
|
357
358
|
cmd = next?.[1] ?? "";
|
|
358
359
|
rest = next?.[2] ?? "";
|
|
359
360
|
}
|
|
360
|
-
if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.help" && cmd !== "\u9762\u677F")
|
|
361
|
+
if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.models" && cmd !== "panel.help" && cmd !== "\u9762\u677F") {
|
|
362
|
+
if (!/^panel\.model\.[A-Za-z0-9-]+\..+$/.test(cmd)) return void 0;
|
|
363
|
+
}
|
|
361
364
|
const leadingFlag = /^--restricted(?:\s+|$)/.exec(rest);
|
|
362
365
|
const restricted = leadingFlag !== null;
|
|
363
366
|
const payloadText = rest.slice(leadingFlag ? leadingFlag[0].length : 0).trim();
|
|
@@ -379,6 +382,7 @@ function scanPeers() {
|
|
|
379
382
|
try {
|
|
380
383
|
const parsed = JSON.parse(fs2.readFileSync(path3.join(dir, file), "utf8"));
|
|
381
384
|
if (typeof parsed.sessionId !== "string" || typeof parsed.pid !== "number") continue;
|
|
385
|
+
if (typeof parsed.instanceId !== "string" || !parsed.instanceId) continue;
|
|
382
386
|
try {
|
|
383
387
|
process.kill(parsed.pid, 0);
|
|
384
388
|
} catch {
|
|
@@ -386,9 +390,14 @@ function scanPeers() {
|
|
|
386
390
|
}
|
|
387
391
|
out.push({
|
|
388
392
|
name: parsed.displayName ?? parsed.sessionId.slice(0, 12),
|
|
393
|
+
instanceId: parsed.instanceId,
|
|
389
394
|
sessionId: parsed.sessionId,
|
|
390
395
|
state: typeof parsed.state === "string" ? parsed.state : "?",
|
|
391
|
-
unattended: parsed.unattended === true
|
|
396
|
+
unattended: parsed.unattended === true,
|
|
397
|
+
sessionTitle: typeof parsed.displaySessionName === "string" && parsed.displaySessionName.trim() ? parsed.displaySessionName.trim() : void 0,
|
|
398
|
+
project: typeof parsed.cwd === "string" && parsed.cwd ? parsed.cwd.split("/").filter(Boolean).at(-1) : void 0,
|
|
399
|
+
currentTool: typeof parsed.currentTool === "string" && parsed.currentTool ? parsed.currentTool : void 0,
|
|
400
|
+
model: typeof parsed.model === "string" && parsed.model ? parsed.model : void 0
|
|
392
401
|
});
|
|
393
402
|
} catch {
|
|
394
403
|
}
|
|
@@ -399,10 +408,16 @@ function scanPeers() {
|
|
|
399
408
|
}
|
|
400
409
|
function composePanel() {
|
|
401
410
|
const peers = scanPeers();
|
|
402
|
-
const rows = peers.map((p) =>
|
|
411
|
+
const rows = peers.map((p) => {
|
|
412
|
+
const title = p.sessionTitle ?? p.name;
|
|
413
|
+
const state = p.state === "working" && p.currentTool ? `working\xB7${p.currentTool}` : p.state;
|
|
414
|
+
const project = p.project && p.project !== title ? `\uFF08${p.project}\uFF09` : "";
|
|
415
|
+
return `| ${title}${project} | ${p.model ?? "\u2014"} | ${state} |
|
|
416
|
+
| \u21B3 ${p.name} | | |`;
|
|
417
|
+
});
|
|
403
418
|
const body = [
|
|
404
|
-
peers.length > 0 ? `| \u4F1A\u8BDD | \u72B6\u6001 |
|
|
405
|
-
|
|
419
|
+
peers.length > 0 ? `| \u4F1A\u8BDD | \u6A21\u578B | \u72B6\u6001 |
|
|
420
|
+
|---|---|---|
|
|
406
421
|
${rows.join("\n")}` : "_\u6CA1\u6709\u5B58\u6D3B\u7684 pie \u4F1A\u8BDD_",
|
|
407
422
|
``,
|
|
408
423
|
`\u5171 ${peers.length} \u4E2A\u4F1A\u8BDD \xB7 ${(/* @__PURE__ */ new Date()).toLocaleTimeString("zh-CN", { hour12: false })}`
|
|
@@ -417,15 +432,53 @@ ${rows.join("\n")}` : "_\u6CA1\u6709\u5B58\u6D3B\u7684 pie \u4F1A\u8BDD_",
|
|
|
417
432
|
actions: [
|
|
418
433
|
{ id: "panel.refresh", label: "\u{1F504} \u5237\u65B0" },
|
|
419
434
|
{ id: "panel.summon", label: "\u{1F4CB} \u91CD\u65B0\u53EC\u5524" },
|
|
435
|
+
{ id: "panel.models", label: "\u{1F39A} \u5207\u6A21\u578B" },
|
|
420
436
|
{ id: "panel.help", label: "\u2753 \u547D\u4EE4" }
|
|
421
437
|
]
|
|
422
438
|
};
|
|
423
439
|
}
|
|
440
|
+
function candidateModels() {
|
|
441
|
+
const out = /* @__PURE__ */ new Set();
|
|
442
|
+
try {
|
|
443
|
+
const configRoot = path3.dirname(path3.dirname(ipcDiscoveryRoot()));
|
|
444
|
+
const config = JSON.parse(fs2.readFileSync(path3.join(configRoot, "models.json"), "utf8"));
|
|
445
|
+
const d = config.defaults ?? {};
|
|
446
|
+
if (d.provider && d.modelId) out.add(`${d.provider}/${d.modelId}`);
|
|
447
|
+
for (const cls of Object.values(d.modelClasses ?? {})) {
|
|
448
|
+
if (cls?.provider && cls?.modelId) out.add(`${cls.provider}/${cls.modelId}`);
|
|
449
|
+
}
|
|
450
|
+
} catch {
|
|
451
|
+
}
|
|
452
|
+
return [...out];
|
|
453
|
+
}
|
|
424
454
|
function executePanelCommand(input) {
|
|
455
|
+
if (input.cmd === "panel.models") {
|
|
456
|
+
const peers = scanPeers();
|
|
457
|
+
const models = candidateModels();
|
|
458
|
+
const rows = peers.map((p) => `| ${p.sessionTitle ?? p.name} | ${p.model ?? "\u2014"} |`);
|
|
459
|
+
const actions = peers.flatMap(
|
|
460
|
+
(p) => models.map((m) => ({ id: `panel.model.${p.instanceId}.${m}`, label: `${p.name.slice(0, 10)}\u2192${m.split("/")[1]?.slice(0, 14) ?? m}` }))
|
|
461
|
+
).slice(0, 18);
|
|
462
|
+
return { spec: {
|
|
463
|
+
title: "\u5207\u6362\u6A21\u578B",
|
|
464
|
+
subtitle: `${peers.length} \u4F1A\u8BDD \xD7 ${models.length} \u5019\u9009`,
|
|
465
|
+
color: "violet",
|
|
466
|
+
body: [
|
|
467
|
+
peers.length > 0 ? `| \u4F1A\u8BDD | \u5F53\u524D\u6A21\u578B |
|
|
468
|
+
|---|---|
|
|
469
|
+
${rows.join("\n")}` : "_\u6CA1\u6709\u5B58\u6D3B\u7684 pie \u4F1A\u8BDD_",
|
|
470
|
+
``,
|
|
471
|
+
`\u5019\u9009\uFF1A${models.join(" \xB7 ") || "\uFF08models.json \u4E0D\u53EF\u8BFB\uFF09"}`,
|
|
472
|
+
``,
|
|
473
|
+
"\u6309\u94AE\u683C\u5F0F\uFF1A\u4F1A\u8BDD\u2192\u6A21\u578B\u3002\u70B9\u6309\u5373\u53D1 model.set \u63A7\u5236\u5E27\uFF08\u96F6 LLM\u3001\u4E0D\u8FDB\u5BF9\u65B9\u5386\u53F2\uFF09\u3002"
|
|
474
|
+
].join("\n"),
|
|
475
|
+
actions: actions.length > 0 ? actions : [{ id: "panel.summon", label: "\u21A9\uFE0F \u8FD4\u56DE\u9762\u677F" }]
|
|
476
|
+
}, patchOrigin: false };
|
|
477
|
+
}
|
|
425
478
|
if (input.cmd === "panel.help") {
|
|
426
479
|
return { spec: {
|
|
427
480
|
title: "\u9762\u677F\u547D\u4EE4",
|
|
428
|
-
body: "`/panel` \u6216 `/\u9762\u677F` \u53EC\u5524\u72B6\u6001\u9762\u677F\u3002\u5361\u7247\u6309\u94AE\uFF1A\u{1F504} \u5237\u65B0\uFF08\u539F\u5730\u66F4\u65B0\uFF09\u3001\u{1F4CB} \u91CD\u65B0\u53EC\u5524\u3001\u2753 \u672C\u8BF4\u660E\u3002\u7FA4\u5185\u4EFB\u4F55\u6210\u5458\u53EF\u70B9\uFF0C`--restricted` \u52A8\u4F5C\u9700 allowUsers \u767D\u540D\u5355\u3002",
|
|
481
|
+
body: "`/panel` \u6216 `/\u9762\u677F` \u53EC\u5524\u72B6\u6001\u9762\u677F\u3002\u5361\u7247\u6309\u94AE\uFF1A\u{1F504} \u5237\u65B0\uFF08\u539F\u5730\u66F4\u65B0\uFF09\u3001\u{1F4CB} \u91CD\u65B0\u53EC\u5524\u3001\u{1F39A} \u5207\u6A21\u578B\u3001\u2753 \u672C\u8BF4\u660E\u3002\u7FA4\u5185\u4EFB\u4F55\u6210\u5458\u53EF\u70B9\uFF0C`--restricted` \u52A8\u4F5C\u9700 allowUsers \u767D\u540D\u5355\u3002",
|
|
429
482
|
actions: [{ id: "panel.summon", label: "\u56DE\u5230\u9762\u677F" }]
|
|
430
483
|
}, patchOrigin: false };
|
|
431
484
|
}
|
|
@@ -487,7 +540,12 @@ function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
|
|
|
487
540
|
createdAt: Date.now(),
|
|
488
541
|
text,
|
|
489
542
|
sessionId: targetSessionId,
|
|
490
|
-
waitMs: 0
|
|
543
|
+
waitMs: 0,
|
|
544
|
+
replyTo: void 0,
|
|
545
|
+
notifyCompletion: void 0,
|
|
546
|
+
control: void 0,
|
|
547
|
+
userAssigned: void 0,
|
|
548
|
+
subscriberSession: void 0
|
|
491
549
|
};
|
|
492
550
|
const payload = [envelope.v, envelope.id, envelope.from, envelope.to, envelope.kind, envelope.createdAt, envelope.sessionId ?? null, envelope.text ?? null, envelope.replyTo ?? null, envelope.waitMs ?? null, envelope.notifyCompletion ?? null, envelope.control ?? null, envelope.userAssigned ?? null, envelope.subscriberSession ?? null];
|
|
493
551
|
const frame = JSON.stringify({ ...envelope, auth: createHmac("sha256", secret).update(JSON.stringify(payload)).digest("hex") });
|
|
@@ -683,6 +741,71 @@ function ipcDiscoveryRoot2() {
|
|
|
683
741
|
const configDir = process.platform === "win32" ? raw : pathResolve(raw === "~" ? home : raw.startsWith("~/") ? pathJoin(home, raw.slice(2)) : raw);
|
|
684
742
|
return pathJoin(configDir, "run", "ipc");
|
|
685
743
|
}
|
|
744
|
+
async function applyModelControl(peerRef, model) {
|
|
745
|
+
const net2 = await import("node:net");
|
|
746
|
+
let target;
|
|
747
|
+
try {
|
|
748
|
+
const dir = ipcDiscoveryRoot2();
|
|
749
|
+
for (const file of fs6.readdirSync(dir).filter((f) => f.endsWith(".json"))) {
|
|
750
|
+
const parsed = JSON.parse(fs6.readFileSync(join7(dir, file), "utf8"));
|
|
751
|
+
if (!parsed.port || !parsed.secret || typeof parsed.pid !== "number" || !parsed.instanceId) continue;
|
|
752
|
+
const match = parsed.instanceId === peerRef || parsed.instanceId.startsWith(peerRef) || parsed.displayName === peerRef;
|
|
753
|
+
if (!match) continue;
|
|
754
|
+
try {
|
|
755
|
+
process.kill(parsed.pid, 0);
|
|
756
|
+
} catch {
|
|
757
|
+
continue;
|
|
758
|
+
}
|
|
759
|
+
target = { port: parsed.port, secret: parsed.secret, instanceId: parsed.instanceId };
|
|
760
|
+
break;
|
|
761
|
+
}
|
|
762
|
+
} catch {
|
|
763
|
+
}
|
|
764
|
+
if (!target) return { ok: false, detail: `\u672A\u627E\u5230\u4F1A\u8BDD\uFF1A${peerRef}` };
|
|
765
|
+
const envelope = signEnvelope({
|
|
766
|
+
v: IPC_PROTOCOL_VERSION,
|
|
767
|
+
id: `panel-model-${Date.now()}`,
|
|
768
|
+
from: "pie-panel0000000",
|
|
769
|
+
to: target.instanceId,
|
|
770
|
+
kind: "control",
|
|
771
|
+
createdAt: Date.now(),
|
|
772
|
+
text: JSON.stringify({ control: "model.set", payload: { model } })
|
|
773
|
+
}, target.secret);
|
|
774
|
+
return await new Promise((resolve4) => {
|
|
775
|
+
let settled = false;
|
|
776
|
+
const finish = (ok, detail) => {
|
|
777
|
+
if (settled) return;
|
|
778
|
+
settled = true;
|
|
779
|
+
try {
|
|
780
|
+
sock.destroy();
|
|
781
|
+
} catch {
|
|
782
|
+
}
|
|
783
|
+
resolve4({ ok, detail });
|
|
784
|
+
};
|
|
785
|
+
const sock = net2.connect({ host: "127.0.0.1", port: target.port }, () => {
|
|
786
|
+
sock.write(JSON.stringify(envelope) + "\n");
|
|
787
|
+
});
|
|
788
|
+
sock.setTimeout(6e3, () => finish(false, "\u5BF9\u7AEF 6 \u79D2\u65E0\u56DE\u6267\uFF08\u53EF\u80FD\u6B63\u91CD\u542F\uFF1B\u63A7\u5236\u5E27\u5E42\u7B49\uFF0C\u91CD\u70B9\u5B89\u5168\uFF09"));
|
|
789
|
+
sock.on("error", (error) => finish(false, `\u8FDE\u63A5\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`));
|
|
790
|
+
sock.on("close", () => {
|
|
791
|
+
if (!settled) finish(false, "\u5BF9\u7AEF\u5173\u95ED\u4E86\u8FDE\u63A5\uFF08\u7B56\u7565\u62D2\u7EDD\u6216\u5E27\u88AB\u62D2\uFF1B\u91CD\u53D1\u5B89\u5168\uFF09");
|
|
792
|
+
});
|
|
793
|
+
sock.on("data", (buffer) => {
|
|
794
|
+
for (const line of buffer.toString("utf8").split("\n")) {
|
|
795
|
+
if (!line.trim()) continue;
|
|
796
|
+
try {
|
|
797
|
+
const parsed = JSON.parse(line);
|
|
798
|
+
if (parsed.kind === "ack" || parsed.kind === "result") {
|
|
799
|
+
const refused = /"ok"\s*:\s*false|error|拒绝|invalid|unknown|refus|denied/i.test(parsed.text ?? "");
|
|
800
|
+
finish(!refused, `\u5BF9\u7AEF\u56DE\u6267\uFF1A${parsed.text ?? "(\u7A7A)"}`);
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
} catch {
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
});
|
|
807
|
+
});
|
|
808
|
+
}
|
|
686
809
|
function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
687
810
|
const IM_INPUT_PREFIX = connection.sourcePrefix;
|
|
688
811
|
const key = (id) => JSON.stringify([cfg.provider, id]);
|
|
@@ -705,9 +828,27 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
|
705
828
|
function updateFooterTag() {
|
|
706
829
|
ctx.ui.setStatus?.(
|
|
707
830
|
STATUS_KEY,
|
|
708
|
-
configurationFailed ? "[IM!]" : forwardingEnabled ? consumerLastExit ? "[IM!]" : consumerReady ? "[IM]" : "[IM\u2026]" : void 0
|
|
831
|
+
configurationFailed ? "[IM!]" : forwardingEnabled ? consumerLastExit ? "[IM!]" : busStale ? "[IM-DEGRADED:bus]" : consumerReady ? "[IM]" : "[IM\u2026]" : void 0
|
|
709
832
|
);
|
|
710
833
|
}
|
|
834
|
+
let busStale = false;
|
|
835
|
+
const probeBusHealth = async () => {
|
|
836
|
+
if (terminated || !connection.consumeBusHealth) return;
|
|
837
|
+
try {
|
|
838
|
+
const health = await connection.consumeBusHealth();
|
|
839
|
+
if (terminated || health === void 0) return;
|
|
840
|
+
const next = health === "stale";
|
|
841
|
+
if (next !== busStale) {
|
|
842
|
+
busStale = next;
|
|
843
|
+
if (next) {
|
|
844
|
+
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");
|
|
845
|
+
ctx.ui.notify("IM \u8F6C\u53D1\uFF1A\u4E8B\u4EF6\u603B\u7EBF\u4E91\u7AEF\u8FDE\u63A5\u7591\u4F3C\u8001\u5316\uFF08\u9762\u677F\u6309\u94AE\u53EF\u80FD\u65E0\u54CD\u5E94\uFF09\u3002\u4FEE\u590D\uFF1Alark-cli event stop --force \u540E\u91CD\u542F\u3002", "warning");
|
|
846
|
+
}
|
|
847
|
+
updateFooterTag();
|
|
848
|
+
}
|
|
849
|
+
} catch {
|
|
850
|
+
}
|
|
851
|
+
};
|
|
711
852
|
function writeEnabledToConfig(next) {
|
|
712
853
|
persistEnabled(next);
|
|
713
854
|
}
|
|
@@ -754,7 +895,7 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
|
754
895
|
if (!replyAnchor.has(sessionId)) {
|
|
755
896
|
const persisted = loadPersistedAnchor(sessionId, anchorIdentity);
|
|
756
897
|
if (persisted) {
|
|
757
|
-
replyAnchor.set(sessionId, persisted);
|
|
898
|
+
replyAnchor.set(sessionId, { messageId: persisted.messageId, threadId: persisted.threadId ?? null, at: persisted.at });
|
|
758
899
|
if (persisted.threadId) {
|
|
759
900
|
const restoredAt = Date.now();
|
|
760
901
|
routes.set(key(persisted.messageId), {
|
|
@@ -796,6 +937,27 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
|
796
937
|
let lastSendError;
|
|
797
938
|
let lastSendErrorAt = 0;
|
|
798
939
|
let lastSendFailureNotifyAt = 0;
|
|
940
|
+
function settleDelivery(requests, delivered) {
|
|
941
|
+
if (!requests || requests.size === 0) return;
|
|
942
|
+
for (const [id, meta] of requests) {
|
|
943
|
+
if (inFlightDeliveries.get(id) === meta.gen) inFlightDeliveries.delete(id);
|
|
944
|
+
if (delivered) {
|
|
945
|
+
if (meta.final) {
|
|
946
|
+
deliveredPrune();
|
|
947
|
+
deliveredRequests.set(id, Date.now());
|
|
948
|
+
sealedByGeneration.set(id, meta.gen);
|
|
949
|
+
}
|
|
950
|
+
} else {
|
|
951
|
+
if (sealedByGeneration.get(id) === meta.gen) {
|
|
952
|
+
unsealDeliveredRequest(id);
|
|
953
|
+
sealedByGeneration.delete(id);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
const sealedByGeneration = /* @__PURE__ */ new Map();
|
|
959
|
+
const sealGenerations = /* @__PURE__ */ new Map();
|
|
960
|
+
const inFlightDeliveries = /* @__PURE__ */ new Map();
|
|
799
961
|
function notifySendFailure(error) {
|
|
800
962
|
lastSendError = error;
|
|
801
963
|
lastSendErrorAt = Date.now();
|
|
@@ -893,7 +1055,9 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
893
1055
|
const text = event.text?.trim() ?? "";
|
|
894
1056
|
if (isManager && /^\[pie-ipc\][^\n]*says:\s*\n?\[ipc-done\] requestId=[a-zA-Z0-9:-]+ (?:outcome=\S+ )?user_assigned=true(?:\s|$)/.test(text) && currentSessionId) {
|
|
895
1057
|
const requestTag = /requestId=([a-zA-Z0-9:-]+)/.exec(text)?.[1] ?? "ipc-delivery";
|
|
896
|
-
|
|
1058
|
+
if (!stampDeliveryDestinationDeduped(`ipc-done:${requestTag}`, void 0, true)) {
|
|
1059
|
+
ctx.log(`im-forward: late/duplicate wake for ${requestTag} \u2014 result already delivered; turn output stays gated`);
|
|
1060
|
+
}
|
|
897
1061
|
}
|
|
898
1062
|
if (text && !text.startsWith(IM_INPUT_PREFIX) && !text.startsWith("/") && !text.startsWith("!!") && !/@\[[^\]]+\]\(file:/.test(text) && currentSessionId) {
|
|
899
1063
|
pendingInputs.push({
|
|
@@ -907,24 +1071,60 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
907
1071
|
}
|
|
908
1072
|
return { action: "continue" };
|
|
909
1073
|
});
|
|
910
|
-
function outboundRoleAllows(attribution) {
|
|
1074
|
+
function outboundRoleAllows(attribution, consumed) {
|
|
911
1075
|
if (!isManager) return true;
|
|
912
1076
|
if (attribution !== void 0) return true;
|
|
913
1077
|
pruneDeliveryDestinations();
|
|
914
1078
|
const scope = `s:${currentSessionId}:`;
|
|
915
1079
|
const mine = [...deliveryDestinations.keys()].filter((tag) => tag.startsWith(scope));
|
|
916
1080
|
if (mine.length > 0) {
|
|
1081
|
+
let allowed = false;
|
|
1082
|
+
for (const tag of mine) {
|
|
1083
|
+
if (tag.startsWith(`${scope}ipc-done:`)) {
|
|
1084
|
+
const id = tag.slice(`${scope}ipc-done:`.length);
|
|
1085
|
+
if (inFlightDeliveries.has(id)) continue;
|
|
1086
|
+
const final = deliveryDestinations.get(tag)?.final === true;
|
|
1087
|
+
const gen = (sealGenerations.get(id) ?? 0) + 1;
|
|
1088
|
+
sealGenerations.set(id, gen);
|
|
1089
|
+
inFlightDeliveries.set(id, gen);
|
|
1090
|
+
consumed?.set(id, { gen, final });
|
|
1091
|
+
allowed = true;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
917
1094
|
for (const tag of mine) deliveryDestinations.delete(tag);
|
|
918
|
-
return
|
|
1095
|
+
return allowed;
|
|
919
1096
|
}
|
|
920
1097
|
return false;
|
|
921
1098
|
}
|
|
922
1099
|
const deliveryDestinations = /* @__PURE__ */ new Map();
|
|
923
1100
|
const DELIVERY_TAG_TTL_MS = 60 * 60 * 1e3;
|
|
924
|
-
|
|
1101
|
+
const deliveredRequests = /* @__PURE__ */ new Map();
|
|
1102
|
+
const DELIVERED_REQUEST_TTL_MS = 6 * 60 * 60 * 1e3;
|
|
1103
|
+
function deliveredPrune(now = Date.now()) {
|
|
1104
|
+
for (const [key2, at] of deliveredRequests) {
|
|
1105
|
+
if (now - at > DELIVERED_REQUEST_TTL_MS) deliveredRequests.delete(key2);
|
|
1106
|
+
}
|
|
1107
|
+
while (deliveredRequests.size > 200) {
|
|
1108
|
+
const oldest = [...deliveredRequests.entries()].sort((a, b) => a[1] - b[1])[0];
|
|
1109
|
+
deliveredRequests.delete(oldest[0]);
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
function stampDeliveryDestinationDeduped(tag, replyTo, final) {
|
|
1113
|
+
if (tag.startsWith("ipc-done:")) {
|
|
1114
|
+
const bare = tag.slice("ipc-done:".length);
|
|
1115
|
+
deliveredPrune();
|
|
1116
|
+
if (deliveredRequests.has(bare)) return false;
|
|
1117
|
+
}
|
|
1118
|
+
stampDeliveryDestination(tag, replyTo, final);
|
|
1119
|
+
return true;
|
|
1120
|
+
}
|
|
1121
|
+
function unsealDeliveredRequest(requestId) {
|
|
1122
|
+
deliveredRequests.delete(requestId);
|
|
1123
|
+
}
|
|
1124
|
+
function stampDeliveryDestination(tag, replyTo, final) {
|
|
925
1125
|
pruneDeliveryDestinations();
|
|
926
1126
|
const scoped = `s:${currentSessionId}:${tag}`;
|
|
927
|
-
deliveryDestinations.set(scoped, { at: Date.now(), ...replyTo ? { replyTo } : {} });
|
|
1127
|
+
deliveryDestinations.set(scoped, { at: Date.now(), ...replyTo ? { replyTo } : {}, ...final !== void 0 ? { final } : {} });
|
|
928
1128
|
}
|
|
929
1129
|
function pruneDeliveryDestinations() {
|
|
930
1130
|
const now = Date.now();
|
|
@@ -955,8 +1155,12 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
955
1155
|
const wrappedNotify = stampedWake.exec(userText);
|
|
956
1156
|
if (wrappedNotify) {
|
|
957
1157
|
const requestTag = /requestId=([a-zA-Z0-9:-]+)/.exec(userText)?.[1] ?? "ipc-delivery";
|
|
958
|
-
|
|
959
|
-
|
|
1158
|
+
const isFinal = /^\[pie-ipc\][^\n]*says:\s*\n?\[ipc-(?:done|done-check)\] /.test(userText);
|
|
1159
|
+
if (!stampDeliveryDestinationDeduped(`ipc-done:${requestTag}`, void 0, isFinal)) {
|
|
1160
|
+
ctx.log(`im-forward: late/duplicate wake for ${requestTag} \u2014 result already delivered; turn output stays gated`);
|
|
1161
|
+
} else {
|
|
1162
|
+
ctx.log(`im-forward: delivery tag stamped (ipc-done:${requestTag}${isFinal ? "" : ", progress"}) \u2014 the woken turn may deliver`);
|
|
1163
|
+
}
|
|
960
1164
|
}
|
|
961
1165
|
}
|
|
962
1166
|
if (!isForwardingEnabled()) return;
|
|
@@ -969,15 +1173,17 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
969
1173
|
if (!sessionId) return;
|
|
970
1174
|
const sequence = ++forwardCounter;
|
|
971
1175
|
const attribution = resolveOutboundAttribution(sessionId);
|
|
972
|
-
|
|
973
|
-
|
|
1176
|
+
const deliver = /* @__PURE__ */ new Map();
|
|
1177
|
+
if (!outboundRoleAllows(attribution, deliver)) return;
|
|
1178
|
+
void forwardMessage(
|
|
974
1179
|
text,
|
|
975
1180
|
sessionId,
|
|
976
1181
|
sequence,
|
|
977
1182
|
attribution?.caption,
|
|
978
1183
|
attribution?.replyTo,
|
|
979
|
-
attribution
|
|
980
|
-
|
|
1184
|
+
attribution,
|
|
1185
|
+
deliver
|
|
1186
|
+
).catch(() => void 0);
|
|
981
1187
|
});
|
|
982
1188
|
ctx.on("turn:failed", (event) => {
|
|
983
1189
|
if (!isForwardingEnabled()) return;
|
|
@@ -986,15 +1192,18 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
986
1192
|
const reason = failureReason(event.message ?? {});
|
|
987
1193
|
const sequence = ++forwardCounter;
|
|
988
1194
|
const attribution = resolveOutboundAttribution(sessionId);
|
|
989
|
-
|
|
1195
|
+
const deliverTf = /* @__PURE__ */ new Map();
|
|
1196
|
+
if (!outboundRoleAllows(attribution, deliverTf)) return;
|
|
990
1197
|
void forwardMessage(
|
|
991
1198
|
`\u26A0\uFE0F \u4EFB\u52A1\u5931\u8D25\uFF1A${reason}`,
|
|
992
1199
|
sessionId,
|
|
993
1200
|
sequence,
|
|
994
1201
|
attribution?.caption,
|
|
995
1202
|
attribution?.replyTo,
|
|
996
|
-
attribution
|
|
997
|
-
|
|
1203
|
+
attribution,
|
|
1204
|
+
deliverTf,
|
|
1205
|
+
true
|
|
1206
|
+
).catch(() => void 0);
|
|
998
1207
|
});
|
|
999
1208
|
ctx.on("turn:cancelled", (event) => {
|
|
1000
1209
|
if (!isForwardingEnabled()) return;
|
|
@@ -1002,17 +1211,30 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1002
1211
|
if (!sessionId) return;
|
|
1003
1212
|
const sequence = ++forwardCounter;
|
|
1004
1213
|
const attribution = resolveOutboundAttribution(sessionId);
|
|
1005
|
-
|
|
1214
|
+
const deliverTc = /* @__PURE__ */ new Map();
|
|
1215
|
+
if (!outboundRoleAllows(attribution, deliverTc)) return;
|
|
1006
1216
|
void forwardMessage(
|
|
1007
1217
|
`\u26D4\uFE0F \u4EFB\u52A1\u5DF2\u53D6\u6D88\uFF1A${event.reason}`,
|
|
1008
1218
|
sessionId,
|
|
1009
1219
|
sequence,
|
|
1010
1220
|
attribution?.caption,
|
|
1011
1221
|
attribution?.replyTo,
|
|
1012
|
-
attribution
|
|
1013
|
-
|
|
1222
|
+
attribution,
|
|
1223
|
+
deliverTc,
|
|
1224
|
+
true
|
|
1225
|
+
).catch(() => void 0);
|
|
1014
1226
|
});
|
|
1015
|
-
async function forwardMessage(text, sessionId, sequence, userInput, replyTo, attribution) {
|
|
1227
|
+
async function forwardMessage(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice) {
|
|
1228
|
+
let settled = false;
|
|
1229
|
+
try {
|
|
1230
|
+
return await forwardMessageInner(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice, () => {
|
|
1231
|
+
settled = true;
|
|
1232
|
+
});
|
|
1233
|
+
} finally {
|
|
1234
|
+
if (!settled) settleDelivery(deliverRequests, false);
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
async function forwardMessageInner(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice, markSettled) {
|
|
1016
1238
|
pruneState();
|
|
1017
1239
|
const sessionName = ctx.getSessionDisplayName?.() ?? ctx.getSessionName?.();
|
|
1018
1240
|
const composeMode = resolveSessionAnchor(sessionId).threadId ? "topic-reply" : "topic-root";
|
|
@@ -1023,7 +1245,10 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1023
1245
|
text,
|
|
1024
1246
|
composeMode
|
|
1025
1247
|
);
|
|
1026
|
-
if (terminated || !isForwardingEnabled())
|
|
1248
|
+
if (terminated || !isForwardingEnabled()) {
|
|
1249
|
+
settleDelivery(deliverRequests, false);
|
|
1250
|
+
return false;
|
|
1251
|
+
}
|
|
1027
1252
|
const [chunks] = chunkMarkdown(composed);
|
|
1028
1253
|
const baseKey = `pie-im-forward-${cfg.provider}-${incarnation}-${sessionId}-${sequence}-${hashText(composed)}`;
|
|
1029
1254
|
const sessionAnchor = resolveSessionAnchor(sessionId);
|
|
@@ -1124,7 +1349,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1124
1349
|
}
|
|
1125
1350
|
if (!stakeFlightToken && !anchor) {
|
|
1126
1351
|
ctx.log(`im-forward: fallback stake unavailable for ${sessionId}; dropping re-send`);
|
|
1127
|
-
|
|
1352
|
+
settleDelivery(deliverRequests, false);
|
|
1353
|
+
return false;
|
|
1128
1354
|
}
|
|
1129
1355
|
sent = await sendChunk(0);
|
|
1130
1356
|
}
|
|
@@ -1133,8 +1359,12 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1133
1359
|
}
|
|
1134
1360
|
if (!sent) {
|
|
1135
1361
|
notifySendFailure(`${cfg.provider} send failed`);
|
|
1136
|
-
|
|
1362
|
+
settleDelivery(deliverRequests, false);
|
|
1363
|
+
markSettled?.();
|
|
1364
|
+
return false;
|
|
1137
1365
|
}
|
|
1366
|
+
settleDelivery(deliverRequests, true);
|
|
1367
|
+
markSettled?.();
|
|
1138
1368
|
registerRoute(sent, sessionId);
|
|
1139
1369
|
const legacyUpgrade = !isManager && anchor !== void 0 && !sessionAnchor.threadId && sent.messageId !== anchor;
|
|
1140
1370
|
const stakeNeeded = stakeFlightToken !== void 0;
|
|
@@ -1204,7 +1434,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1204
1434
|
}
|
|
1205
1435
|
registerRoute(next, sessionId);
|
|
1206
1436
|
}
|
|
1207
|
-
if (connection.sendFile && !terminated && isForwardingEnabled()) {
|
|
1437
|
+
if (connection.sendFile && !terminated && isForwardingEnabled() && !systemNotice) {
|
|
1208
1438
|
const files = collectFileReferences(
|
|
1209
1439
|
text,
|
|
1210
1440
|
ctx.cwd,
|
|
@@ -1383,20 +1613,103 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1383
1613
|
return { kind: "delivery-failed", owner: ownerSession };
|
|
1384
1614
|
}
|
|
1385
1615
|
}
|
|
1616
|
+
const panelCardOwners = /* @__PURE__ */ new Map();
|
|
1617
|
+
const rememberPanelCard = (messageId, sessionId, chatId) => {
|
|
1618
|
+
if (!messageId) return;
|
|
1619
|
+
panelCardOwners.set(messageId, { sessionId, epoch: inputEpoch, chatId });
|
|
1620
|
+
if (panelCardOwners.size > 100) {
|
|
1621
|
+
const oldest = [...panelCardOwners.keys()].slice(0, Math.ceil(panelCardOwners.size / 4));
|
|
1622
|
+
for (const k of oldest) panelCardOwners.delete(k);
|
|
1623
|
+
}
|
|
1624
|
+
};
|
|
1625
|
+
const runPanelCommand = async (panelCmd, event, sessionId, isCurrent) => {
|
|
1626
|
+
if (!isCurrent()) return;
|
|
1627
|
+
const started = Date.now();
|
|
1628
|
+
if (panelCmd.restricted && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id))) {
|
|
1629
|
+
ctx.log(`im-forward: restricted panel action ${panelCmd.cmd} refused for ${event.sender_id ?? "unknown"} (not in allowUsers)`);
|
|
1630
|
+
try {
|
|
1631
|
+
await connection.send(event.chat_id, "\u26D4\uFE0F \u6B64\u64CD\u4F5C\u9700\u8981\u7BA1\u7406\u5458\u6743\u9650\uFF08allowUsers\uFF09\u3002", `panel-refused-${event.event_id}`);
|
|
1632
|
+
} catch {
|
|
1633
|
+
}
|
|
1634
|
+
return;
|
|
1635
|
+
}
|
|
1636
|
+
const modelAction = /^panel\.model\.([A-Za-z0-9-]+)\.(.+)$/.exec(panelCmd.cmd);
|
|
1637
|
+
if (modelAction) {
|
|
1638
|
+
const [, peerRef, model] = modelAction;
|
|
1639
|
+
const receipt = await applyModelControl(peerRef, model);
|
|
1640
|
+
if (!isCurrent()) return;
|
|
1641
|
+
const spec = {
|
|
1642
|
+
title: "\u5207\u6362\u7ED3\u679C",
|
|
1643
|
+
body: `${receipt.ok ? "\u2705" : "\u26A0\uFE0F"} ${model} \u2192 ${peerRef}
|
|
1644
|
+
|
|
1645
|
+
${receipt.detail}`,
|
|
1646
|
+
actions: [{ id: "panel.models", label: "\u21A9\uFE0F \u8FD4\u56DE\u6A21\u578B\u9762\u677F" }]
|
|
1647
|
+
};
|
|
1648
|
+
try {
|
|
1649
|
+
if (connection.sendCard) {
|
|
1650
|
+
const sent = await connection.sendCard(event.chat_id, spec, `panel-model-${event.event_id}`);
|
|
1651
|
+
if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
|
|
1652
|
+
} else await connection.send(event.chat_id, `**${spec.title}**
|
|
1653
|
+
${spec.body}`, `panel-model-${event.event_id}`);
|
|
1654
|
+
} catch {
|
|
1655
|
+
}
|
|
1656
|
+
return;
|
|
1657
|
+
}
|
|
1658
|
+
const result = executePanelCommand({ ...panelCmd, senderId: event.sender_id, originCardId: event.message_id });
|
|
1659
|
+
try {
|
|
1660
|
+
if (result.patchOrigin && connection.patch && event.message_id) {
|
|
1661
|
+
const ok = await connection.patch(event.message_id, result.spec);
|
|
1662
|
+
if (ok) {
|
|
1663
|
+
if (isCurrent()) rememberPanelCard(event.message_id, sessionId, event.chat_id);
|
|
1664
|
+
ctx.log(`im-forward: panel card patched (${panelCmd.cmd}, runtimeMs=${Date.now() - started})`);
|
|
1665
|
+
return;
|
|
1666
|
+
}
|
|
1667
|
+
ctx.log("im-forward: panel patch failed; falling back to a fresh card");
|
|
1668
|
+
}
|
|
1669
|
+
if (!isCurrent()) return;
|
|
1670
|
+
if (connection.sendCard) {
|
|
1671
|
+
const sent = await connection.sendCard(event.chat_id, result.spec, `panel-${event.event_id}`);
|
|
1672
|
+
if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
|
|
1673
|
+
ctx.log(`im-forward: panel card sent (${panelCmd.cmd})`);
|
|
1674
|
+
} else {
|
|
1675
|
+
await connection.send(event.chat_id, `**${result.spec.title ?? "\u9762\u677F"}**
|
|
1676
|
+
${result.spec.body}`, `panel-${event.event_id}`);
|
|
1677
|
+
}
|
|
1678
|
+
} catch (error) {
|
|
1679
|
+
ctx.log(`im-forward: panel command failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1680
|
+
}
|
|
1681
|
+
};
|
|
1386
1682
|
async function handleInboundEventInner(event, retry) {
|
|
1387
1683
|
const isGroup = event.chatType === "group";
|
|
1388
1684
|
if (isGroup) {
|
|
1389
|
-
if (cfg.groupAccess === "off")
|
|
1390
|
-
|
|
1685
|
+
if (cfg.groupAccess === "off") {
|
|
1686
|
+
ctx.log("im-forward: group event refused (off)");
|
|
1687
|
+
return;
|
|
1688
|
+
}
|
|
1689
|
+
if (cfg.groupAccess === "allowUsers" && (!event.sender_id || !cfg.allowUsers?.includes(event.sender_id))) {
|
|
1690
|
+
ctx.log("im-forward: group event refused (allowUsers)");
|
|
1391
1691
|
return;
|
|
1692
|
+
}
|
|
1392
1693
|
} else {
|
|
1393
1694
|
const matchesTarget = cfg.targetKind === "user" ? event.sender_id === cfg.targetId && (event.chatType === void 0 || event.chatType === "p2p") : event.chat_id === cfg.targetId || event.chatType === "p2p";
|
|
1394
1695
|
if (!matchesTarget) return;
|
|
1395
1696
|
}
|
|
1396
|
-
if (!isGroup && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id)))
|
|
1697
|
+
if (!isGroup && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id))) {
|
|
1698
|
+
ctx.log("im-forward: direct event refused (allowUsers)");
|
|
1397
1699
|
return;
|
|
1700
|
+
}
|
|
1398
1701
|
const messageId = event.message_id;
|
|
1399
1702
|
if (!messageId) return;
|
|
1703
|
+
const owner = panelCardOwners.get(messageId);
|
|
1704
|
+
const fastEpoch = inputEpoch;
|
|
1705
|
+
if (owner && owner.sessionId === currentSessionId && owner.epoch === fastEpoch && owner.chatId === event.chat_id && event.text?.startsWith("/card ")) {
|
|
1706
|
+
const command = parsePanelCommand(event.text);
|
|
1707
|
+
if (command) {
|
|
1708
|
+
ctx.log(`im-forward: panel fast path (${command.cmd})`);
|
|
1709
|
+
await runPanelCommand(command, event, owner.sessionId, () => !terminated && inputEpoch === fastEpoch && currentSessionId === owner.sessionId && isForwardingEnabled());
|
|
1710
|
+
return;
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1400
1713
|
const address = resolveInboundAddress(event.text);
|
|
1401
1714
|
if (address.kind === "other") {
|
|
1402
1715
|
ctx.log(`im-forward: message addressed to "${address.name}" (another live session); ignoring here`);
|
|
@@ -1406,6 +1719,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1406
1719
|
ctx.log(`im-forward: address "${address.name}" is unresolved (${address.reason}); dropping`);
|
|
1407
1720
|
return;
|
|
1408
1721
|
}
|
|
1722
|
+
if (!currentSessionId) return;
|
|
1409
1723
|
const releaseInvalidatedEvent = () => {
|
|
1410
1724
|
if (event.event_id) seenEventIds.delete(key(event.event_id));
|
|
1411
1725
|
};
|
|
@@ -1533,34 +1847,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1533
1847
|
{
|
|
1534
1848
|
const panelCmd = parsePanelCommand(caption);
|
|
1535
1849
|
if (panelCmd) {
|
|
1536
|
-
|
|
1537
|
-
ctx.log(`im-forward: restricted panel action ${panelCmd.cmd} refused for ${event.sender_id ?? "unknown"} (not in allowUsers)`);
|
|
1538
|
-
try {
|
|
1539
|
-
await connection.send(event.chat_id, "\u26D4\uFE0F \u6B64\u64CD\u4F5C\u9700\u8981\u7BA1\u7406\u5458\u6743\u9650\uFF08allowUsers\uFF09\u3002", `panel-refused-${event.event_id}`);
|
|
1540
|
-
} catch {
|
|
1541
|
-
}
|
|
1542
|
-
return;
|
|
1543
|
-
}
|
|
1544
|
-
const result = executePanelCommand({ ...panelCmd, originCardId: event.message_id });
|
|
1545
|
-
try {
|
|
1546
|
-
if (result.patchOrigin && connection.patch && event.message_id) {
|
|
1547
|
-
const ok = await connection.patch(event.message_id, result.spec);
|
|
1548
|
-
if (ok) {
|
|
1549
|
-
ctx.log(`im-forward: panel card patched (${panelCmd.cmd})`);
|
|
1550
|
-
return;
|
|
1551
|
-
}
|
|
1552
|
-
ctx.log("im-forward: panel patch failed; falling back to a fresh card");
|
|
1553
|
-
}
|
|
1554
|
-
if (connection.sendCard) {
|
|
1555
|
-
await connection.sendCard(event.chat_id, result.spec, `panel-${event.event_id}`);
|
|
1556
|
-
ctx.log(`im-forward: panel card sent (${panelCmd.cmd})`);
|
|
1557
|
-
} else {
|
|
1558
|
-
await connection.send(event.chat_id, `**${result.spec.title ?? "\u9762\u677F"}**
|
|
1559
|
-
${result.spec.body}`, `panel-${event.event_id}`);
|
|
1560
|
-
}
|
|
1561
|
-
} catch (error) {
|
|
1562
|
-
ctx.log(`im-forward: panel command failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1563
|
-
}
|
|
1850
|
+
await runPanelCommand(panelCmd, event, sessionId, () => scope.isCurrent());
|
|
1564
1851
|
return;
|
|
1565
1852
|
}
|
|
1566
1853
|
}
|
|
@@ -1578,16 +1865,21 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1578
1865
|
}
|
|
1579
1866
|
}
|
|
1580
1867
|
if (currentAfterSubmit) {
|
|
1868
|
+
const rejectReason = scope.lastRejectReason;
|
|
1869
|
+
const notice = rejectReason ? `\u26A0\uFE0F \u6D88\u606F\u672A\u80FD\u63D0\u4EA4\uFF1A${rejectReason}` : `\u26A0\uFE0F \u6D88\u606F\u63A5\u6536\u5931\u8D25\uFF0C\u672A\u63D0\u4EA4\u4EFB\u52A1\u3002${imageKeys.length ? "\u8BF7\u68C0\u67E5\u9644\u4EF6\u540E\u91CD\u8BD5\u3002" : "\u8BF7\u91CD\u8BD5\u3002"}`;
|
|
1581
1870
|
ctx.ui.notify(
|
|
1582
1871
|
"im-forward: message was not accepted; no input submitted.",
|
|
1583
1872
|
"warning"
|
|
1584
1873
|
);
|
|
1585
1874
|
await forwardMessage(
|
|
1586
|
-
|
|
1875
|
+
notice,
|
|
1587
1876
|
route.sessionId,
|
|
1588
1877
|
++forwardCounter,
|
|
1589
1878
|
caption,
|
|
1590
|
-
messageId
|
|
1879
|
+
messageId,
|
|
1880
|
+
void 0,
|
|
1881
|
+
void 0,
|
|
1882
|
+
true
|
|
1591
1883
|
);
|
|
1592
1884
|
}
|
|
1593
1885
|
return;
|
|
@@ -1639,7 +1931,10 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1639
1931
|
boundSession ?? currentSessionId ?? "",
|
|
1640
1932
|
++forwardCounter,
|
|
1641
1933
|
void 0,
|
|
1642
|
-
event.message_id
|
|
1934
|
+
event.message_id,
|
|
1935
|
+
void 0,
|
|
1936
|
+
void 0,
|
|
1937
|
+
true
|
|
1643
1938
|
);
|
|
1644
1939
|
}
|
|
1645
1940
|
return;
|
|
@@ -1806,7 +2101,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1806
2101
|
if (consumerLock) return true;
|
|
1807
2102
|
if (!needsCanonicalResolution()) return acquireClaimedSlot(resolveBindingKeySync());
|
|
1808
2103
|
const resolved = await resolveBindingKey();
|
|
1809
|
-
return acquireClaimedSlot(resolved);
|
|
2104
|
+
return resolved ? acquireClaimedSlot(resolved) : false;
|
|
1810
2105
|
}
|
|
1811
2106
|
function acquireClaimedSlot(binding) {
|
|
1812
2107
|
if (consumerLock) return true;
|
|
@@ -1994,9 +2289,15 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1994
2289
|
};
|
|
1995
2290
|
};
|
|
1996
2291
|
updateFooterTag();
|
|
2292
|
+
const busHealthTimer = setInterval(() => {
|
|
2293
|
+
void probeBusHealth();
|
|
2294
|
+
}, 5 * 60 * 1e3);
|
|
2295
|
+
busHealthTimer.unref?.();
|
|
2296
|
+
void probeBusHealth();
|
|
1997
2297
|
ctx.registerCleanup?.(async () => {
|
|
1998
2298
|
inputEpoch++;
|
|
1999
2299
|
terminated = true;
|
|
2300
|
+
clearInterval(busHealthTimer);
|
|
2000
2301
|
registerDispatchReceiver(void 0);
|
|
2001
2302
|
registerTurnImDriver(void 0);
|
|
2002
2303
|
consumerLock?.release();
|
|
@@ -2089,7 +2390,7 @@ async function runSetup(ctx, dir, providers, signal, isCurrent = () => !signal.a
|
|
|
2089
2390
|
ctx.ui.notify("IM forwarding setup: invalid provider settings; nothing was saved.", "error");
|
|
2090
2391
|
return;
|
|
2091
2392
|
}
|
|
2092
|
-
const profile = typeof settings.larkCliProfile === "string" ? settings.larkCliProfile : void 0;
|
|
2393
|
+
const profile = typeof settings.larkCliProfile === "string" ? String(settings.larkCliProfile) : void 0;
|
|
2093
2394
|
const profileLine = profile ? `
|
|
2094
2395
|
lark-cli profile: ${String(profile)}` : "";
|
|
2095
2396
|
const appLine = resolved.appId ? `
|
|
@@ -2455,7 +2756,8 @@ var COLOR_TEMPLATE = {
|
|
|
2455
2756
|
blue: "blue",
|
|
2456
2757
|
green: "green",
|
|
2457
2758
|
grey: "grey",
|
|
2458
|
-
red: "red"
|
|
2759
|
+
red: "red",
|
|
2760
|
+
violet: "violet"
|
|
2459
2761
|
};
|
|
2460
2762
|
function compileCard(spec) {
|
|
2461
2763
|
const elements = [];
|
|
@@ -2499,7 +2801,7 @@ function compileCard(spec) {
|
|
|
2499
2801
|
doc.header = {
|
|
2500
2802
|
...spec.title === void 0 ? {} : { title: { tag: "plain_text", content: spec.title } },
|
|
2501
2803
|
...spec.subtitle === void 0 ? {} : { subtitle: { tag: "plain_text", content: spec.subtitle } },
|
|
2502
|
-
template: COLOR_TEMPLATE[spec.color ?? "blue"]
|
|
2804
|
+
template: COLOR_TEMPLATE[spec.color ?? "blue"] ?? "blue"
|
|
2503
2805
|
};
|
|
2504
2806
|
}
|
|
2505
2807
|
return doc;
|
|
@@ -3220,26 +3522,30 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
|
|
|
3220
3522
|
};
|
|
3221
3523
|
let canonicalAppIdCache = null;
|
|
3222
3524
|
let canonicalResolved = false;
|
|
3525
|
+
const BUS_RECONNECT_GRACE_MS = 10 * 60 * 1e3;
|
|
3526
|
+
async function canonicalAppIdNow() {
|
|
3527
|
+
if (canonicalResolved) return canonicalAppIdCache || void 0;
|
|
3528
|
+
if (!profile) {
|
|
3529
|
+
canonicalResolved = true;
|
|
3530
|
+
return void 0;
|
|
3531
|
+
}
|
|
3532
|
+
try {
|
|
3533
|
+
const result = await native(binary, ["profile", "list"], 1e4, void 0, { signal: lifetime.signal });
|
|
3534
|
+
const profiles = result.error ? null : parseProfiles(result.stdout);
|
|
3535
|
+
if (!profiles) return void 0;
|
|
3536
|
+
const appId = profiles.find((item) => item.name === profile)?.appId;
|
|
3537
|
+
if (!appId) return void 0;
|
|
3538
|
+
canonicalAppIdCache = appId;
|
|
3539
|
+
canonicalResolved = true;
|
|
3540
|
+
return appId;
|
|
3541
|
+
} catch {
|
|
3542
|
+
return void 0;
|
|
3543
|
+
}
|
|
3544
|
+
}
|
|
3223
3545
|
return {
|
|
3224
3546
|
sourcePrefix: "[Feishu]",
|
|
3225
3547
|
async canonicalAppId() {
|
|
3226
|
-
|
|
3227
|
-
if (!profile) {
|
|
3228
|
-
canonicalResolved = true;
|
|
3229
|
-
return void 0;
|
|
3230
|
-
}
|
|
3231
|
-
try {
|
|
3232
|
-
const result = await native(binary, ["profile", "list"], 1e4, void 0, { signal: lifetime.signal });
|
|
3233
|
-
const profiles = result.error ? null : parseProfiles(result.stdout);
|
|
3234
|
-
if (!profiles) return void 0;
|
|
3235
|
-
const appId = profiles.find((item) => item.name === profile)?.appId;
|
|
3236
|
-
if (!appId) return void 0;
|
|
3237
|
-
canonicalAppIdCache = appId;
|
|
3238
|
-
canonicalResolved = true;
|
|
3239
|
-
return canonicalAppIdCache;
|
|
3240
|
-
} catch {
|
|
3241
|
-
return void 0;
|
|
3242
|
-
}
|
|
3548
|
+
return canonicalAppIdNow();
|
|
3243
3549
|
},
|
|
3244
3550
|
async dispose() {
|
|
3245
3551
|
lifetime.abort();
|
|
@@ -3320,7 +3626,30 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
|
|
|
3320
3626
|
let closed = false;
|
|
3321
3627
|
let failed = false;
|
|
3322
3628
|
let lastErrorLine = "";
|
|
3323
|
-
const children =
|
|
3629
|
+
const children = /* @__PURE__ */ new Set();
|
|
3630
|
+
const optionalRespawnAttempts = /* @__PURE__ */ new Map();
|
|
3631
|
+
const optionalRespawnTimers = /* @__PURE__ */ new Map();
|
|
3632
|
+
const optionalMaps = /* @__PURE__ */ new Map();
|
|
3633
|
+
const scheduleOptionalRespawn = (eventKey, map) => {
|
|
3634
|
+
optionalMaps.set(eventKey, map);
|
|
3635
|
+
if (stopped) return;
|
|
3636
|
+
if (optionalRespawnTimers.has(eventKey)) return;
|
|
3637
|
+
const attempt = optionalRespawnAttempts.get(eventKey) ?? 0;
|
|
3638
|
+
const delay2 = Math.min(5e3 * 2 ** attempt, 12e4);
|
|
3639
|
+
optionalRespawnAttempts.set(eventKey, attempt + 1);
|
|
3640
|
+
const timer = setTimeout(() => {
|
|
3641
|
+
optionalRespawnTimers.delete(eventKey);
|
|
3642
|
+
if (stopped) return;
|
|
3643
|
+
try {
|
|
3644
|
+
const map2 = optionalMaps.get(eventKey) ?? map;
|
|
3645
|
+
spawnConsume(eventKey, map2, false);
|
|
3646
|
+
} catch {
|
|
3647
|
+
scheduleOptionalRespawn(eventKey, map);
|
|
3648
|
+
}
|
|
3649
|
+
}, delay2);
|
|
3650
|
+
timer.unref?.();
|
|
3651
|
+
optionalRespawnTimers.set(eventKey, timer);
|
|
3652
|
+
};
|
|
3324
3653
|
const spawnConsume = (eventKey, map, required) => {
|
|
3325
3654
|
const child2 = spawn4(binary.command, [...binary.prefix, "event", "consume", eventKey, "--as", "bot", ...profile ? ["--profile", profile] : []], { stdio: ["pipe", "pipe", "pipe"], shell: false, windowsHide: true, detached: process.platform !== "win32" });
|
|
3326
3655
|
child2.stdin?.on("error", () => void 0);
|
|
@@ -3333,7 +3662,10 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
|
|
|
3333
3662
|
const errors = lineReader((line) => {
|
|
3334
3663
|
const text = line.trim();
|
|
3335
3664
|
if (!text) return;
|
|
3336
|
-
if (text.startsWith("[event] ready"))
|
|
3665
|
+
if (text.startsWith("[event] ready")) {
|
|
3666
|
+
if (!required) optionalRespawnAttempts.set(eventKey, 0);
|
|
3667
|
+
return;
|
|
3668
|
+
}
|
|
3337
3669
|
if (safeErrorPatterns.some((pattern) => pattern.test(text)) && text.length <= 200) lastErrorLine = text;
|
|
3338
3670
|
}, 4096);
|
|
3339
3671
|
child2.stdout?.on("data", output.write);
|
|
@@ -3348,11 +3680,17 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
|
|
|
3348
3680
|
fail(`Feishu consumer code=${code} signal=${signal} (${eventKey})`);
|
|
3349
3681
|
});
|
|
3350
3682
|
} else {
|
|
3351
|
-
|
|
3352
|
-
|
|
3353
|
-
|
|
3683
|
+
let ended = false;
|
|
3684
|
+
const endedOnce = () => {
|
|
3685
|
+
if (ended) return;
|
|
3686
|
+
ended = true;
|
|
3687
|
+
if (!stopped && !closed && !failed) scheduleOptionalRespawn(eventKey, map);
|
|
3688
|
+
};
|
|
3689
|
+
child2.on("error", endedOnce);
|
|
3690
|
+
child2.on("close", endedOnce);
|
|
3354
3691
|
}
|
|
3355
|
-
children.
|
|
3692
|
+
children.add(child2);
|
|
3693
|
+
child2.once("close", () => children.delete(child2));
|
|
3356
3694
|
return child2;
|
|
3357
3695
|
};
|
|
3358
3696
|
const safeErrorPatterns = [
|
|
@@ -3400,6 +3738,7 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
|
|
|
3400
3738
|
const ev = normalizeCardAction(line);
|
|
3401
3739
|
if (!ev) return null;
|
|
3402
3740
|
void resolveChatType(ev.chat_id).then((t) => {
|
|
3741
|
+
if (stopped || closed || failed) return;
|
|
3403
3742
|
if (t) ev.chatType = t;
|
|
3404
3743
|
callbacks.event(ev);
|
|
3405
3744
|
});
|
|
@@ -3413,11 +3752,55 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
|
|
|
3413
3752
|
}
|
|
3414
3753
|
return { async stop() {
|
|
3415
3754
|
stopped = true;
|
|
3416
|
-
|
|
3755
|
+
for (const timer of optionalRespawnTimers.values()) clearTimeout(timer);
|
|
3756
|
+
optionalRespawnTimers.clear();
|
|
3757
|
+
await Promise.allSettled([...children].map((child2) => shutdownConsumer(child2)));
|
|
3417
3758
|
} };
|
|
3759
|
+
},
|
|
3760
|
+
// 4.3.14 bus health: read the shared daemon's log tail and decide whether
|
|
3761
|
+
// the CLOUD websocket looks dead. Signal: the LAST `[SDK] disconnected`
|
|
3762
|
+
// line older than the reconnect grace with no newer connect (measured:
|
|
3763
|
+
// healthy reconnects land within ~2min; the aged 11h case stayed
|
|
3764
|
+
// disconnected until a manual `event stop --force`). Missing/unparsed log
|
|
3765
|
+
// = undefined (no signal, not an alarm) — escalate only on a POSITIVE
|
|
3766
|
+
// stale reading.
|
|
3767
|
+
async consumeBusHealth() {
|
|
3768
|
+
const appId = await canonicalAppIdNow();
|
|
3769
|
+
if (!appId) return void 0;
|
|
3770
|
+
const larkHome = process.env.PIE_LARK_CLI_HOME && process.env.PIE_LARK_CLI_HOME.trim() ? process.env.PIE_LARK_CLI_HOME : os4.homedir();
|
|
3771
|
+
const logPath = path11.join(larkHome, ".lark-cli", "events", appId, "bus.log");
|
|
3772
|
+
let tail;
|
|
3773
|
+
try {
|
|
3774
|
+
const fd = fs9.openSync(logPath, "r");
|
|
3775
|
+
try {
|
|
3776
|
+
const size = fs9.fstatSync(fd).size;
|
|
3777
|
+
const start = Math.max(0, size - 64 * 1024);
|
|
3778
|
+
const buf = Buffer.alloc(size - start);
|
|
3779
|
+
fs9.readSync(fd, buf, 0, buf.length, start);
|
|
3780
|
+
tail = buf.toString("utf8");
|
|
3781
|
+
} finally {
|
|
3782
|
+
fs9.closeSync(fd);
|
|
3783
|
+
}
|
|
3784
|
+
} catch {
|
|
3785
|
+
return void 0;
|
|
3786
|
+
}
|
|
3787
|
+
return parseBusHealth(tail, Date.now(), BUS_RECONNECT_GRACE_MS);
|
|
3418
3788
|
}
|
|
3419
3789
|
};
|
|
3420
3790
|
}
|
|
3791
|
+
function parseBusHealth(tail, now, graceMs = 10 * 6e4) {
|
|
3792
|
+
const lines = tail.split("\n");
|
|
3793
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
3794
|
+
const line = lines[i];
|
|
3795
|
+
const m = /^(\d{4})\/(\d{2})\/(\d{2}) (\d{2}):(\d{2}):(\d{2}) \[SDK\] (connected|disconnected) to /.exec(line);
|
|
3796
|
+
if (!m) continue;
|
|
3797
|
+
const when = new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]).getTime();
|
|
3798
|
+
if (!Number.isFinite(when)) return void 0;
|
|
3799
|
+
if (m[7] === "connected") return "ok";
|
|
3800
|
+
return now - when > graceMs ? "stale" : void 0;
|
|
3801
|
+
}
|
|
3802
|
+
return void 0;
|
|
3803
|
+
}
|
|
3421
3804
|
var feishuProvider = {
|
|
3422
3805
|
id: "feishu",
|
|
3423
3806
|
label: "Feishu (Lark)",
|