@cydm/pie 4.2.0 → 4.3.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/dist/builtin/extensions/im-forward/index.js +717 -176
- package/dist/builtin/extensions/pie-ipc/index.js +126 -348
- package/dist/builtin/extensions/pie-proc/index.js +1 -27
- package/dist/chunks/chunk-GJLSYBFN.js +359 -0
- package/dist/chunks/{concierge-cli-R3RIBGJL.js → concierge-cli-CQMIAGWJ.js} +20 -23
- package/dist/cli.js +46 -20
- package/package.json +3 -3
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
IPC_PROTOCOL_VERSION
|
|
4
|
+
} from "../../../chunks/chunk-GJLSYBFN.js";
|
|
2
5
|
import {
|
|
3
6
|
detectImageMime,
|
|
4
7
|
readImageFormat
|
|
@@ -344,9 +347,9 @@ function collectFileReferences(text, cwd, fsStat, options) {
|
|
|
344
347
|
}
|
|
345
348
|
for (const candidate of candidates) {
|
|
346
349
|
if (results.length >= maxFiles) break;
|
|
347
|
-
let
|
|
348
|
-
if (!
|
|
349
|
-
const clean =
|
|
350
|
+
let path13 = candidate.trim();
|
|
351
|
+
if (!path13 || path13.startsWith("/") || path13.startsWith("~") || /^[a-z]+:/i.test(path13) || path13.includes("://")) continue;
|
|
352
|
+
const clean = path13.replace(/^\.\//, "").split("#")[0].split("?")[0];
|
|
350
353
|
if (clean.includes("..")) continue;
|
|
351
354
|
const extension = clean.split(".").pop().toLowerCase();
|
|
352
355
|
if (!extension || !ATTACHABLE_EXTENSIONS.has(extension)) continue;
|
|
@@ -444,10 +447,10 @@ function resolveConfig(cwd, dir) {
|
|
|
444
447
|
for (const file of configPaths(cwd, dir)) {
|
|
445
448
|
const layer = readLayer(file);
|
|
446
449
|
if (Object.keys(layer).length) present = true;
|
|
447
|
-
const legacy = ["chatId", "receiveId", "openId", "larkCli", "allowUsers"].some((key) => key in layer);
|
|
450
|
+
const legacy = ["chatId", "receiveId", "openId", "larkCli", "allowUsers", "groupAccess"].some((key) => key in layer);
|
|
448
451
|
if (legacy && !layer.provider) {
|
|
449
452
|
const previous = providers.feishu ?? {};
|
|
450
|
-
providers.feishu = { ...previous, ...Object.fromEntries(["chatId", "openId", "larkCli", "allowUsers"].filter((key) => key in layer).map((key) => [key, layer[key]])), ...layer.receiveId && !layer.chatId ? { chatId: layer.receiveId } : {} };
|
|
453
|
+
providers.feishu = { ...previous, ...Object.fromEntries(["chatId", "openId", "larkCli", "allowUsers", "groupAccess"].filter((key) => key in layer).map((key) => [key, layer[key]])), ...layer.receiveId && !layer.chatId ? { chatId: layer.receiveId } : {} };
|
|
451
454
|
merged.provider = "feishu";
|
|
452
455
|
}
|
|
453
456
|
if (isRecord(layer.providers)) {
|
|
@@ -459,9 +462,7 @@ function resolveConfig(cwd, dir) {
|
|
|
459
462
|
if ("provider" in merged && (typeof merged.provider !== "string" || !merged.provider.trim())) throw new Error("Invalid IM provider field. Run setup or repair the configuration; no provider fallback was used.");
|
|
460
463
|
const provider = typeof merged.provider === "string" ? merged.provider : "feishu";
|
|
461
464
|
const retry = merged.retryBackoffMs;
|
|
462
|
-
|
|
463
|
-
const outboundMode = rawMode === "gateway" || rawMode === "mirror" || rawMode === "silent" ? rawMode : void 0;
|
|
464
|
-
return { config: { enabled: merged.enabled === true, provider, settings: providers[provider] ?? {}, retryBackoffMs: typeof retry === "number" && Number.isFinite(retry) ? Math.min(6e4, Math.max(20, Math.round(retry))) : void 0, ...outboundMode ? { outboundMode } : {} }, problems: [] };
|
|
465
|
+
return { config: { enabled: merged.enabled === true, provider, settings: providers[provider] ?? {}, retryBackoffMs: typeof retry === "number" && Number.isFinite(retry) ? Math.min(6e4, Math.max(20, Math.round(retry))) : void 0 }, problems: [] };
|
|
465
466
|
} catch (error) {
|
|
466
467
|
return { config: null, problems: [error.message] };
|
|
467
468
|
}
|
|
@@ -489,7 +490,6 @@ function writeConfig(cwd, dir, update, expected) {
|
|
|
489
490
|
const target = saveLocation(cwd, dir);
|
|
490
491
|
const value = readLayer(target);
|
|
491
492
|
value.enabled = update.enabled;
|
|
492
|
-
if (update.outboundMode) value.outboundMode = update.outboundMode;
|
|
493
493
|
if (update.provider) {
|
|
494
494
|
value.provider = update.provider;
|
|
495
495
|
value.providers = { ...isRecord(value.providers) ? value.providers : {}, [update.provider]: update.settings ?? {} };
|
|
@@ -561,7 +561,7 @@ function resolveImForwardConfig(cwd, dir) {
|
|
|
561
561
|
|
|
562
562
|
// builtin/extensions/im-forward/runtime.ts
|
|
563
563
|
import * as crypto from "node:crypto";
|
|
564
|
-
import * as
|
|
564
|
+
import * as fs8 from "node:fs";
|
|
565
565
|
import { basename } from "node:path";
|
|
566
566
|
|
|
567
567
|
// builtin/extensions/im-forward/address-book.ts
|
|
@@ -945,6 +945,293 @@ function threadOwner(input) {
|
|
|
945
945
|
return { sessionId: read.owner.sessionId };
|
|
946
946
|
}
|
|
947
947
|
|
|
948
|
+
// builtin/extensions/im-forward/event-hub.ts
|
|
949
|
+
import * as fs4 from "node:fs";
|
|
950
|
+
import * as path4 from "node:path";
|
|
951
|
+
var DISPATCH_PREFIX = "[im-forward-dispatch]";
|
|
952
|
+
var LOCK_STALE_MS = 2e4;
|
|
953
|
+
function hubDir() {
|
|
954
|
+
return path4.join(resolveConfigDir(), "im-forward");
|
|
955
|
+
}
|
|
956
|
+
function lockPath(binding) {
|
|
957
|
+
const safe = binding.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
958
|
+
return path4.join(hubDir(), `consumer-${safe}.lock`);
|
|
959
|
+
}
|
|
960
|
+
function pidAlive3(pid) {
|
|
961
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
962
|
+
try {
|
|
963
|
+
process.kill(pid, 0);
|
|
964
|
+
return true;
|
|
965
|
+
} catch (error) {
|
|
966
|
+
return error.code === "EPERM";
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
function readLock(binding) {
|
|
970
|
+
try {
|
|
971
|
+
const parsed = JSON.parse(fs4.readFileSync(lockPath(binding), "utf8"));
|
|
972
|
+
if (typeof parsed.pid === "number" && typeof parsed.holder === "string" && typeof parsed.heartbeatAt === "number" && typeof parsed.binding === "string") {
|
|
973
|
+
return {
|
|
974
|
+
pid: parsed.pid,
|
|
975
|
+
holder: parsed.holder,
|
|
976
|
+
heartbeatAt: parsed.heartbeatAt,
|
|
977
|
+
binding: parsed.binding
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
return void 0;
|
|
981
|
+
} catch {
|
|
982
|
+
return void 0;
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
function lockAlive(info, now = Date.now()) {
|
|
986
|
+
if (!info) return false;
|
|
987
|
+
return pidAlive3(info.pid) && now - info.heartbeatAt < LOCK_STALE_MS;
|
|
988
|
+
}
|
|
989
|
+
function tryClaimConsumer(binding, holder, onLost) {
|
|
990
|
+
const target = lockPath(binding);
|
|
991
|
+
const mine = JSON.stringify({ pid: process.pid, holder, heartbeatAt: Date.now(), binding });
|
|
992
|
+
const takeOver2 = () => {
|
|
993
|
+
const tmp = `${target}.${process.pid}.${Date.now()}.tmp`;
|
|
994
|
+
try {
|
|
995
|
+
fs4.mkdirSync(hubDir(), { recursive: true, mode: 448 });
|
|
996
|
+
fs4.writeFileSync(tmp, `${mine}
|
|
997
|
+
`);
|
|
998
|
+
try {
|
|
999
|
+
fs4.linkSync(tmp, target);
|
|
1000
|
+
fs4.rmSync(tmp, { force: true });
|
|
1001
|
+
return true;
|
|
1002
|
+
} catch (error) {
|
|
1003
|
+
fs4.rmSync(tmp, { force: true });
|
|
1004
|
+
if (error.code !== "EEXIST") throw error;
|
|
1005
|
+
return false;
|
|
1006
|
+
}
|
|
1007
|
+
} catch {
|
|
1008
|
+
return false;
|
|
1009
|
+
}
|
|
1010
|
+
};
|
|
1011
|
+
const existing = readLock(binding);
|
|
1012
|
+
if (existing && lockAlive(existing)) return void 0;
|
|
1013
|
+
if (existing) {
|
|
1014
|
+
try {
|
|
1015
|
+
fs4.rmSync(target, { force: true });
|
|
1016
|
+
} catch {
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
if (!takeOver2()) return void 0;
|
|
1020
|
+
let released = false;
|
|
1021
|
+
const heartbeatTimer = setInterval(() => {
|
|
1022
|
+
if (released) return;
|
|
1023
|
+
try {
|
|
1024
|
+
const current = readLock(binding);
|
|
1025
|
+
if (current && current.pid !== process.pid) {
|
|
1026
|
+
released = true;
|
|
1027
|
+
clearInterval(heartbeatTimer);
|
|
1028
|
+
onLost?.();
|
|
1029
|
+
return;
|
|
1030
|
+
}
|
|
1031
|
+
fs4.writeFileSync(target, `${JSON.stringify({ pid: process.pid, holder, heartbeatAt: Date.now(), binding })}
|
|
1032
|
+
`);
|
|
1033
|
+
} catch {
|
|
1034
|
+
}
|
|
1035
|
+
}, 5e3);
|
|
1036
|
+
heartbeatTimer.unref();
|
|
1037
|
+
return {
|
|
1038
|
+
heartbeat: () => {
|
|
1039
|
+
try {
|
|
1040
|
+
fs4.writeFileSync(target, `${JSON.stringify({ pid: process.pid, holder, heartbeatAt: Date.now(), binding })}
|
|
1041
|
+
`);
|
|
1042
|
+
} catch {
|
|
1043
|
+
}
|
|
1044
|
+
},
|
|
1045
|
+
release: () => {
|
|
1046
|
+
if (released) return;
|
|
1047
|
+
released = true;
|
|
1048
|
+
clearInterval(heartbeatTimer);
|
|
1049
|
+
try {
|
|
1050
|
+
const current = readLock(binding);
|
|
1051
|
+
if (current && current.pid === process.pid) fs4.rmSync(target, { force: true });
|
|
1052
|
+
} catch {
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
// builtin/extensions/im-forward/event-dispatch.ts
|
|
1059
|
+
import * as net from "node:net";
|
|
1060
|
+
import * as fs5 from "node:fs";
|
|
1061
|
+
import * as path5 from "node:path";
|
|
1062
|
+
import { createHmac, randomUUID as randomUUID3 } from "node:crypto";
|
|
1063
|
+
function discoveryDir() {
|
|
1064
|
+
return path5.join(addressBookRoot(), "run", "ipc");
|
|
1065
|
+
}
|
|
1066
|
+
function pidAlive4(pid) {
|
|
1067
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
1068
|
+
try {
|
|
1069
|
+
process.kill(pid, 0);
|
|
1070
|
+
return true;
|
|
1071
|
+
} catch (error) {
|
|
1072
|
+
return error.code === "EPERM";
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
function findOwnerInstance(sessionId) {
|
|
1076
|
+
let entries;
|
|
1077
|
+
try {
|
|
1078
|
+
entries = fs5.readdirSync(discoveryDir());
|
|
1079
|
+
} catch {
|
|
1080
|
+
return void 0;
|
|
1081
|
+
}
|
|
1082
|
+
for (const name of entries.slice(0, 256)) {
|
|
1083
|
+
if (!name.endsWith(".json")) continue;
|
|
1084
|
+
try {
|
|
1085
|
+
const parsed = JSON.parse(fs5.readFileSync(path5.join(discoveryDir(), name), "utf8"));
|
|
1086
|
+
if (parsed.instanceId === name.slice(0, -".json".length) && parsed.sessionId === sessionId && parsed.port && typeof parsed.secret === "string" && parsed.protocol === IPC_PROTOCOL_VERSION && pidAlive4(parsed.pid ?? 0)) {
|
|
1087
|
+
return parsed;
|
|
1088
|
+
}
|
|
1089
|
+
} catch {
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
return void 0;
|
|
1093
|
+
}
|
|
1094
|
+
function sign(payload) {
|
|
1095
|
+
return createHmac("sha256", "").update(JSON.stringify(payload)).digest("hex");
|
|
1096
|
+
}
|
|
1097
|
+
function deliverOnce(port, secret, text) {
|
|
1098
|
+
return new Promise((resolve4) => {
|
|
1099
|
+
const id = randomUUID3();
|
|
1100
|
+
const envelope = {
|
|
1101
|
+
v: IPC_PROTOCOL_VERSION,
|
|
1102
|
+
id,
|
|
1103
|
+
from: `pie-${randomUUID3().slice(0, 12)}`,
|
|
1104
|
+
to: "unknown",
|
|
1105
|
+
kind: "message",
|
|
1106
|
+
createdAt: Date.now(),
|
|
1107
|
+
text,
|
|
1108
|
+
sessionId: "",
|
|
1109
|
+
waitMs: 0
|
|
1110
|
+
};
|
|
1111
|
+
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];
|
|
1112
|
+
const frame = JSON.stringify({ ...envelope, auth: createHmac("sha256", secret).update(JSON.stringify(payload)).digest("hex") });
|
|
1113
|
+
void sign;
|
|
1114
|
+
const socket = new net.Socket();
|
|
1115
|
+
let settled = false;
|
|
1116
|
+
const finish = (ok) => {
|
|
1117
|
+
if (settled) return;
|
|
1118
|
+
settled = true;
|
|
1119
|
+
clearTimeout(timer);
|
|
1120
|
+
socket.destroy();
|
|
1121
|
+
resolve4(ok);
|
|
1122
|
+
};
|
|
1123
|
+
const timer = setTimeout(() => finish(false), 5e3);
|
|
1124
|
+
socket.once("error", () => finish(false));
|
|
1125
|
+
socket.once("connect", () => {
|
|
1126
|
+
socket.write(`${frame}
|
|
1127
|
+
`);
|
|
1128
|
+
socket.setTimeout(250, () => finish(true));
|
|
1129
|
+
});
|
|
1130
|
+
try {
|
|
1131
|
+
socket.connect(port, "127.0.0.1");
|
|
1132
|
+
} catch {
|
|
1133
|
+
finish(false);
|
|
1134
|
+
}
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
async function dispatchEventToSession(sessionId, eventText) {
|
|
1138
|
+
const owner = findOwnerInstance(sessionId);
|
|
1139
|
+
if (!owner?.port || !owner.secret) return void 0;
|
|
1140
|
+
const ok = await deliverOnce(owner.port, owner.secret, eventText);
|
|
1141
|
+
return ok ? owner.instanceId : void 0;
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
// builtin/extensions/im-forward/session-roots.ts
|
|
1145
|
+
import * as fs6 from "node:fs";
|
|
1146
|
+
import * as path6 from "node:path";
|
|
1147
|
+
function rootsDir() {
|
|
1148
|
+
return path6.join(resolveConfigDir(), "im-forward", "roots");
|
|
1149
|
+
}
|
|
1150
|
+
function rootPath(provider, messageId) {
|
|
1151
|
+
const safe = `${provider}:${messageId}`.replace(/[^a-zA-Z0-9._:-]/g, "_");
|
|
1152
|
+
return path6.join(rootsDir(), `${safe}.json`);
|
|
1153
|
+
}
|
|
1154
|
+
function pidAlive5(pid) {
|
|
1155
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
1156
|
+
try {
|
|
1157
|
+
process.kill(pid, 0);
|
|
1158
|
+
return true;
|
|
1159
|
+
} catch (error) {
|
|
1160
|
+
return error.code === "EPERM";
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
function claimSessionRoot(provider, messageId, sessionId) {
|
|
1164
|
+
if (!messageId || !sessionId) return;
|
|
1165
|
+
try {
|
|
1166
|
+
const record = { sessionId, pid: process.pid, claimedAt: Date.now() };
|
|
1167
|
+
const target = rootPath(provider, messageId);
|
|
1168
|
+
fs6.mkdirSync(rootsDir(), { recursive: true, mode: 448 });
|
|
1169
|
+
fs6.writeFileSync(target, `${JSON.stringify(record)}
|
|
1170
|
+
`);
|
|
1171
|
+
} catch {
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
function sessionRootOwner(provider, messageId) {
|
|
1175
|
+
try {
|
|
1176
|
+
const parsed = JSON.parse(fs6.readFileSync(rootPath(provider, messageId), "utf8"));
|
|
1177
|
+
if (typeof parsed.sessionId === "string" && parsed.sessionId && typeof parsed.pid === "number") {
|
|
1178
|
+
if (!pidAlive5(parsed.pid)) return void 0;
|
|
1179
|
+
return { sessionId: parsed.sessionId, pid: parsed.pid, claimedAt: parsed.claimedAt ?? 0 };
|
|
1180
|
+
}
|
|
1181
|
+
return void 0;
|
|
1182
|
+
} catch {
|
|
1183
|
+
return void 0;
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
// builtin/extensions/im-forward/session-anchors.ts
|
|
1188
|
+
import * as fs7 from "node:fs";
|
|
1189
|
+
import * as path7 from "node:path";
|
|
1190
|
+
function anchorsDir() {
|
|
1191
|
+
return path7.join(addressBookRoot(), "im-forward", "anchors");
|
|
1192
|
+
}
|
|
1193
|
+
function anchorPath(sessionId) {
|
|
1194
|
+
const safe = sessionId.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
1195
|
+
return path7.join(anchorsDir(), `${safe}.json`);
|
|
1196
|
+
}
|
|
1197
|
+
function loadPersistedAnchor(sessionId, identity) {
|
|
1198
|
+
try {
|
|
1199
|
+
const raw = fs7.readFileSync(anchorPath(sessionId), "utf8");
|
|
1200
|
+
const parsed = JSON.parse(raw);
|
|
1201
|
+
if (typeof parsed.anchor?.messageId === "string" && parsed.anchor.messageId && typeof parsed.anchor.at === "number" && parsed.provider === identity.provider && // v2 group-home (11-12): the home is the APP'S WHOLE PRESENCE, so an
|
|
1202
|
+
// anchor may live in ANY room — a group chat id differs from the
|
|
1203
|
+
// configured DM target and must NOT invalidate the anchor (the old
|
|
1204
|
+
// equality here silently forked a group-anchored session back to the
|
|
1205
|
+
// DM root on restart). The provider check stays: a re-bound app is a
|
|
1206
|
+
// different home entirely.
|
|
1207
|
+
(parsed.targetId === identity.targetId || typeof parsed.anchor.home === "string")) {
|
|
1208
|
+
return {
|
|
1209
|
+
messageId: parsed.anchor.messageId,
|
|
1210
|
+
...typeof parsed.anchor.threadId === "string" && parsed.anchor.threadId ? { threadId: parsed.anchor.threadId } : {},
|
|
1211
|
+
...typeof parsed.anchor.home === "string" && parsed.anchor.home ? { home: parsed.anchor.home } : {},
|
|
1212
|
+
at: parsed.anchor.at
|
|
1213
|
+
};
|
|
1214
|
+
}
|
|
1215
|
+
return void 0;
|
|
1216
|
+
} catch {
|
|
1217
|
+
return void 0;
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
function savePersistedAnchor(sessionId, identity, anchor) {
|
|
1221
|
+
try {
|
|
1222
|
+
const file = {
|
|
1223
|
+
provider: identity.provider,
|
|
1224
|
+
targetId: identity.targetId,
|
|
1225
|
+
anchor
|
|
1226
|
+
};
|
|
1227
|
+
const target = anchorPath(sessionId);
|
|
1228
|
+
fs7.mkdirSync(path7.dirname(target), { recursive: true });
|
|
1229
|
+
fs7.writeFileSync(target, `${JSON.stringify(file)}
|
|
1230
|
+
`, "utf8");
|
|
1231
|
+
} catch {
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
|
|
948
1235
|
// builtin/extensions/im-forward/runtime.ts
|
|
949
1236
|
var ROUTE_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
950
1237
|
var MAX_ROUTES = 500;
|
|
@@ -984,20 +1271,10 @@ function hashText(input) {
|
|
|
984
1271
|
}
|
|
985
1272
|
return Math.abs(hash).toString(36);
|
|
986
1273
|
}
|
|
987
|
-
function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled
|
|
1274
|
+
function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
988
1275
|
const IM_INPUT_PREFIX = connection.sourcePrefix;
|
|
989
1276
|
const key = (id) => JSON.stringify([cfg.provider, id]);
|
|
990
|
-
const
|
|
991
|
-
const defaultOutboundMode = cfg.outboundMode ?? (isUnattended ? "gateway" : "mirror");
|
|
992
|
-
let outboundMode = defaultOutboundMode;
|
|
993
|
-
const setOutboundMode = (mode) => {
|
|
994
|
-
outboundMode = mode;
|
|
995
|
-
};
|
|
996
|
-
const maySpeak = (fromImInput) => {
|
|
997
|
-
if (outboundMode === "silent") return false;
|
|
998
|
-
if (outboundMode === "gateway") return true;
|
|
999
|
-
return fromImInput;
|
|
1000
|
-
};
|
|
1277
|
+
const isConcierge = cfg.unattended === true;
|
|
1001
1278
|
const scopes = /* @__PURE__ */ new Set();
|
|
1002
1279
|
let forwardingEnabled = cfg.enabled === true;
|
|
1003
1280
|
let configurationFailed = false;
|
|
@@ -1010,21 +1287,13 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled, liveOu
|
|
|
1010
1287
|
forwardingEnabled = live;
|
|
1011
1288
|
updateFooterTag();
|
|
1012
1289
|
}
|
|
1013
|
-
const nextMode = liveOutboundMode();
|
|
1014
|
-
if (nextMode !== outboundMode) {
|
|
1015
|
-
setOutboundMode(nextMode);
|
|
1016
|
-
updateFooterTag();
|
|
1017
|
-
} else {
|
|
1018
|
-
setOutboundMode(nextMode);
|
|
1019
|
-
}
|
|
1020
1290
|
return forwardingEnabled;
|
|
1021
1291
|
}
|
|
1022
1292
|
const STATUS_KEY = "im-forward";
|
|
1023
1293
|
function updateFooterTag() {
|
|
1024
|
-
const modeTag = outboundMode === "gateway" ? "" : outboundMode === "mirror" ? "\xB7m" : "\xB7s";
|
|
1025
1294
|
ctx.ui.setStatus?.(
|
|
1026
1295
|
STATUS_KEY,
|
|
1027
|
-
configurationFailed ? "[IM!]" : forwardingEnabled ? consumerLastExit ? "[IM!]" : consumerReady ?
|
|
1296
|
+
configurationFailed ? "[IM!]" : forwardingEnabled ? consumerLastExit ? "[IM!]" : consumerReady ? "[IM]" : "[IM\u2026]" : void 0
|
|
1028
1297
|
);
|
|
1029
1298
|
}
|
|
1030
1299
|
function writeEnabledToConfig(next) {
|
|
@@ -1064,7 +1333,46 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled, liveOu
|
|
|
1064
1333
|
let currentSessionId = null;
|
|
1065
1334
|
const pendingInputs = [];
|
|
1066
1335
|
const replyAnchor = /* @__PURE__ */ new Map();
|
|
1067
|
-
const
|
|
1336
|
+
const anchorIdentity = { provider: cfg.provider, targetId: cfg.targetId };
|
|
1337
|
+
const persistedAnchorsLoaded = /* @__PURE__ */ new Set();
|
|
1338
|
+
const anchorStakeFlights = /* @__PURE__ */ new Map();
|
|
1339
|
+
function resolveSessionAnchor(sessionId) {
|
|
1340
|
+
if (!persistedAnchorsLoaded.has(sessionId)) {
|
|
1341
|
+
persistedAnchorsLoaded.add(sessionId);
|
|
1342
|
+
if (!replyAnchor.has(sessionId)) {
|
|
1343
|
+
const persisted = loadPersistedAnchor(sessionId, anchorIdentity);
|
|
1344
|
+
if (persisted) {
|
|
1345
|
+
replyAnchor.set(sessionId, persisted);
|
|
1346
|
+
if (persisted.threadId) {
|
|
1347
|
+
const restoredAt = Date.now();
|
|
1348
|
+
routes.set(key(persisted.messageId), {
|
|
1349
|
+
messageId: persisted.messageId,
|
|
1350
|
+
threadId: persisted.threadId,
|
|
1351
|
+
sessionId,
|
|
1352
|
+
sentAt: restoredAt
|
|
1353
|
+
});
|
|
1354
|
+
threadRoutes.set(key(persisted.threadId), {
|
|
1355
|
+
messageId: persisted.messageId,
|
|
1356
|
+
threadId: persisted.threadId,
|
|
1357
|
+
sessionId,
|
|
1358
|
+
sentAt: restoredAt
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
const anchor = replyAnchor.get(sessionId);
|
|
1365
|
+
return anchor ? { messageId: anchor.messageId, threadId: anchor.threadId } : { threadId: null };
|
|
1366
|
+
}
|
|
1367
|
+
function persistSessionAnchor(sessionId, messageId, threadId, home) {
|
|
1368
|
+
replyAnchor.set(sessionId, { messageId, threadId, at: Date.now() });
|
|
1369
|
+
savePersistedAnchor(sessionId, anchorIdentity, {
|
|
1370
|
+
messageId,
|
|
1371
|
+
...threadId ? { threadId } : {},
|
|
1372
|
+
...home ? { home } : {},
|
|
1373
|
+
at: Date.now()
|
|
1374
|
+
});
|
|
1375
|
+
}
|
|
1068
1376
|
const routes = /* @__PURE__ */ new Map();
|
|
1069
1377
|
const threadRoutes = /* @__PURE__ */ new Map();
|
|
1070
1378
|
const seenEventIds = /* @__PURE__ */ new Map();
|
|
@@ -1096,7 +1404,7 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled, liveOu
|
|
|
1096
1404
|
if (route.threadId) threadRoutes.delete(key(route.threadId));
|
|
1097
1405
|
removeThreadAliasesOf(route);
|
|
1098
1406
|
const anchor = replyAnchor.get(route.sessionId);
|
|
1099
|
-
if (anchor && key(anchor.messageId) === id)
|
|
1407
|
+
if (anchor && key(anchor.messageId) === id && !anchor.threadId)
|
|
1100
1408
|
replyAnchor.delete(route.sessionId);
|
|
1101
1409
|
}
|
|
1102
1410
|
}
|
|
@@ -1151,8 +1459,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1151
1459
|
return {
|
|
1152
1460
|
caption: pending.caption || `${IM_INPUT_PREFIX} images`,
|
|
1153
1461
|
replyTo: pending.messageId || void 0,
|
|
1154
|
-
threadId: pending.threadId
|
|
1155
|
-
origin: pending.origin
|
|
1462
|
+
threadId: pending.threadId
|
|
1156
1463
|
};
|
|
1157
1464
|
}
|
|
1158
1465
|
}
|
|
@@ -1171,20 +1478,73 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1171
1478
|
}
|
|
1172
1479
|
ctx.on("terminal:input", (event) => {
|
|
1173
1480
|
const text = event.text?.trim() ?? "";
|
|
1481
|
+
if (isConcierge && /^\[pie-ipc\][^\n]*says:\s*\n?\[ipc-done\] requestId=[a-zA-Z0-9:-]+ (?:outcome=\S+ )?user_assigned=true(?:\s|$)/.test(text) && currentSessionId) {
|
|
1482
|
+
const requestTag = /requestId=([a-zA-Z0-9:-]+)/.exec(text)?.[1] ?? "ipc-delivery";
|
|
1483
|
+
stampDeliveryDestination(`ipc-done:${requestTag}`);
|
|
1484
|
+
}
|
|
1174
1485
|
if (text && !text.startsWith(IM_INPUT_PREFIX) && !text.startsWith("/") && !text.startsWith("!!") && !/@\[[^\]]+\]\(file:/.test(text) && currentSessionId) {
|
|
1175
1486
|
pendingInputs.push({
|
|
1176
1487
|
sessionId: currentSessionId,
|
|
1177
1488
|
caption: text,
|
|
1178
1489
|
messageId: "",
|
|
1179
1490
|
threadId: null,
|
|
1180
|
-
at: Date.now()
|
|
1181
|
-
origin: "terminal"
|
|
1491
|
+
at: Date.now()
|
|
1182
1492
|
});
|
|
1183
1493
|
pruneState();
|
|
1184
1494
|
}
|
|
1185
1495
|
return { action: "continue" };
|
|
1186
1496
|
});
|
|
1497
|
+
function outboundRoleAllows(attribution) {
|
|
1498
|
+
if (!isConcierge) return true;
|
|
1499
|
+
if (attribution !== void 0) return true;
|
|
1500
|
+
pruneDeliveryDestinations();
|
|
1501
|
+
const scope = `s:${currentSessionId}:`;
|
|
1502
|
+
const mine = [...deliveryDestinations.keys()].filter((tag) => tag.startsWith(scope));
|
|
1503
|
+
if (mine.length > 0) {
|
|
1504
|
+
for (const tag of mine) deliveryDestinations.delete(tag);
|
|
1505
|
+
return true;
|
|
1506
|
+
}
|
|
1507
|
+
return false;
|
|
1508
|
+
}
|
|
1509
|
+
const deliveryDestinations = /* @__PURE__ */ new Map();
|
|
1510
|
+
const DELIVERY_TAG_TTL_MS = 60 * 60 * 1e3;
|
|
1511
|
+
function stampDeliveryDestination(tag, replyTo) {
|
|
1512
|
+
pruneDeliveryDestinations();
|
|
1513
|
+
const scoped = `s:${currentSessionId}:${tag}`;
|
|
1514
|
+
deliveryDestinations.set(scoped, { at: Date.now(), ...replyTo ? { replyTo } : {} });
|
|
1515
|
+
}
|
|
1516
|
+
function pruneDeliveryDestinations() {
|
|
1517
|
+
const now = Date.now();
|
|
1518
|
+
for (const [tag, entry] of deliveryDestinations) {
|
|
1519
|
+
if (now - entry.at > DELIVERY_TAG_TTL_MS) deliveryDestinations.delete(tag);
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1187
1522
|
ctx.on("message:end", (event) => {
|
|
1523
|
+
const inbound = event.message;
|
|
1524
|
+
if (inbound?.role === "user") {
|
|
1525
|
+
const raw = typeof inbound.content === "string" ? inbound.content : Array.isArray(inbound.content) ? inbound.content.map((block) => block && typeof block === "object" && typeof block.text === "string" ? block.text : "").join("") : "";
|
|
1526
|
+
if (raw.trimStart().startsWith(DISPATCH_PREFIX)) {
|
|
1527
|
+
try {
|
|
1528
|
+
const parsed = JSON.parse(raw.trimStart().slice(DISPATCH_PREFIX.length).trim());
|
|
1529
|
+
if (parsed.event) {
|
|
1530
|
+
void handleInboundEvent(parsed.event);
|
|
1531
|
+
return;
|
|
1532
|
+
}
|
|
1533
|
+
} catch {
|
|
1534
|
+
ctx.log("im-forward: malformed dispatch payload dropped");
|
|
1535
|
+
}
|
|
1536
|
+
return;
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
if (inbound?.role === "user" && isConcierge && currentSessionId) {
|
|
1540
|
+
const userText = typeof inbound.content === "string" ? inbound.content : Array.isArray(inbound.content) ? inbound.content.map((block) => block && typeof block === "object" && typeof block.text === "string" ? block.text : "").join("") : "";
|
|
1541
|
+
const wrappedNotify = /^\[pie-ipc\][^\n]*says:\s*\n?\[ipc-done\] requestId=[a-zA-Z0-9:-]+ (?:outcome=\S+ )?user_assigned=true(?:\s|$)/.exec(userText);
|
|
1542
|
+
if (wrappedNotify) {
|
|
1543
|
+
const requestTag = /requestId=([a-zA-Z0-9:-]+)/.exec(userText)?.[1] ?? "ipc-delivery";
|
|
1544
|
+
stampDeliveryDestination(`ipc-done:${requestTag}`);
|
|
1545
|
+
ctx.log(`im-forward: delivery tag stamped (ipc-done:${requestTag}) \u2014 the woken turn may deliver`);
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1188
1548
|
if (!isForwardingEnabled()) return;
|
|
1189
1549
|
const message = event.message;
|
|
1190
1550
|
const stop = message.role === "assistant" ? message.stopReason : void 0;
|
|
@@ -1195,13 +1555,14 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1195
1555
|
if (!sessionId) return;
|
|
1196
1556
|
const sequence = ++forwardCounter;
|
|
1197
1557
|
const attribution = resolveOutboundAttribution(sessionId);
|
|
1198
|
-
if (!
|
|
1558
|
+
if (!outboundRoleAllows(attribution)) return;
|
|
1199
1559
|
void forwardMessage(
|
|
1200
1560
|
text,
|
|
1201
1561
|
sessionId,
|
|
1202
1562
|
sequence,
|
|
1203
1563
|
attribution?.caption,
|
|
1204
|
-
attribution?.replyTo
|
|
1564
|
+
attribution?.replyTo,
|
|
1565
|
+
attribution
|
|
1205
1566
|
);
|
|
1206
1567
|
});
|
|
1207
1568
|
ctx.on("turn:failed", (event) => {
|
|
@@ -1211,13 +1572,14 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1211
1572
|
const reason = failureReason(event.message ?? {});
|
|
1212
1573
|
const sequence = ++forwardCounter;
|
|
1213
1574
|
const attribution = resolveOutboundAttribution(sessionId);
|
|
1214
|
-
if (!
|
|
1575
|
+
if (!outboundRoleAllows(attribution)) return;
|
|
1215
1576
|
void forwardMessage(
|
|
1216
1577
|
`\u26A0\uFE0F \u4EFB\u52A1\u5931\u8D25\uFF1A${reason}`,
|
|
1217
1578
|
sessionId,
|
|
1218
1579
|
sequence,
|
|
1219
1580
|
attribution?.caption,
|
|
1220
|
-
attribution?.replyTo
|
|
1581
|
+
attribution?.replyTo,
|
|
1582
|
+
attribution
|
|
1221
1583
|
);
|
|
1222
1584
|
});
|
|
1223
1585
|
ctx.on("turn:cancelled", (event) => {
|
|
@@ -1226,16 +1588,17 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1226
1588
|
if (!sessionId) return;
|
|
1227
1589
|
const sequence = ++forwardCounter;
|
|
1228
1590
|
const attribution = resolveOutboundAttribution(sessionId);
|
|
1229
|
-
if (!
|
|
1591
|
+
if (!outboundRoleAllows(attribution)) return;
|
|
1230
1592
|
void forwardMessage(
|
|
1231
1593
|
`\u26D4\uFE0F \u4EFB\u52A1\u5DF2\u53D6\u6D88\uFF1A${event.reason}`,
|
|
1232
1594
|
sessionId,
|
|
1233
1595
|
sequence,
|
|
1234
1596
|
attribution?.caption,
|
|
1235
|
-
attribution?.replyTo
|
|
1597
|
+
attribution?.replyTo,
|
|
1598
|
+
attribution
|
|
1236
1599
|
);
|
|
1237
1600
|
});
|
|
1238
|
-
async function forwardMessage(text, sessionId, sequence, userInput, replyTo) {
|
|
1601
|
+
async function forwardMessage(text, sessionId, sequence, userInput, replyTo, attribution) {
|
|
1239
1602
|
pruneState();
|
|
1240
1603
|
const sessionName = ctx.getSessionDisplayName?.() ?? ctx.getSessionName?.();
|
|
1241
1604
|
const composed = composeForwardBody(
|
|
@@ -1247,31 +1610,157 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1247
1610
|
if (terminated || !isForwardingEnabled()) return;
|
|
1248
1611
|
const [chunks] = chunkMarkdown(composed);
|
|
1249
1612
|
const baseKey = `pie-im-forward-${cfg.provider}-${incarnation}-${sessionId}-${sequence}-${hashText(composed)}`;
|
|
1250
|
-
|
|
1251
|
-
const
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1613
|
+
const sessionAnchor = resolveSessionAnchor(sessionId);
|
|
1614
|
+
const attributionAnchor = attribution?.replyTo;
|
|
1615
|
+
let anchor = replyTo ?? attributionAnchor ?? sessionAnchor.messageId;
|
|
1616
|
+
let sessionAnchorThreadId = sessionAnchor.threadId;
|
|
1617
|
+
let stakeFlightToken;
|
|
1618
|
+
const stakeWanted = () => {
|
|
1619
|
+
if (isConcierge) return false;
|
|
1620
|
+
const current = resolveSessionAnchor(sessionId);
|
|
1621
|
+
sessionAnchorThreadId = current.threadId;
|
|
1622
|
+
return !current.messageId || !current.threadId;
|
|
1623
|
+
};
|
|
1624
|
+
const claimStake = () => {
|
|
1625
|
+
let release;
|
|
1626
|
+
const token = new Promise((resolve4) => {
|
|
1627
|
+
release = resolve4;
|
|
1628
|
+
});
|
|
1629
|
+
token.release = release;
|
|
1630
|
+
anchorStakeFlights.set(sessionId, token);
|
|
1631
|
+
stakeFlightToken = token;
|
|
1632
|
+
return token;
|
|
1633
|
+
};
|
|
1634
|
+
const pinnedAnchor = replyTo ?? attributionAnchor;
|
|
1635
|
+
let stakeGuard = 8;
|
|
1636
|
+
while (stakeGuard-- > 0 && !isConcierge) {
|
|
1637
|
+
if (stakeFlightToken) break;
|
|
1638
|
+
const refreshed0 = resolveSessionAnchor(sessionId);
|
|
1639
|
+
if (refreshed0.threadId) {
|
|
1640
|
+
sessionAnchorThreadId = refreshed0.threadId;
|
|
1641
|
+
break;
|
|
1642
|
+
}
|
|
1643
|
+
const existing = anchorStakeFlights.get(sessionId);
|
|
1644
|
+
if (!existing) {
|
|
1645
|
+
claimStake();
|
|
1646
|
+
break;
|
|
1647
|
+
}
|
|
1648
|
+
if (pinnedAnchor) break;
|
|
1649
|
+
try {
|
|
1650
|
+
await existing;
|
|
1651
|
+
} catch {
|
|
1652
|
+
}
|
|
1653
|
+
const refreshed = resolveSessionAnchor(sessionId);
|
|
1654
|
+
sessionAnchorThreadId = refreshed.threadId;
|
|
1655
|
+
if (!pinnedAnchor && refreshed.messageId && !refreshed.threadId) anchor = refreshed.messageId;
|
|
1656
|
+
}
|
|
1657
|
+
if (!isConcierge && !stakeFlightToken && !pinnedAnchor) {
|
|
1658
|
+
const last = resolveSessionAnchor(sessionId);
|
|
1659
|
+
if (!last.threadId) {
|
|
1660
|
+
ctx.log(`im-forward: topic stake unavailable for ${sessionId}; dropping forward (seq=${sequence})`);
|
|
1661
|
+
notifySendFailure(`${cfg.provider} topic stake contention`);
|
|
1662
|
+
return;
|
|
1255
1663
|
}
|
|
1664
|
+
sessionAnchorThreadId = last.threadId;
|
|
1665
|
+
}
|
|
1666
|
+
const releaseStakeFlight = () => {
|
|
1667
|
+
const token = stakeFlightToken;
|
|
1668
|
+
if (!token) return;
|
|
1669
|
+
token.release?.();
|
|
1670
|
+
anchorStakeFlights.delete(sessionId);
|
|
1671
|
+
};
|
|
1672
|
+
let threadPlacement = attribution?.threadId ? { replyInThread: true } : !anchor && !isConcierge ? { replyInThread: true } : sessionAnchorThreadId ? { replyInThread: true, topicId: sessionAnchorThreadId } : { replyInThread: false };
|
|
1673
|
+
const sendChunk = async (index) => {
|
|
1256
1674
|
const key2 = chunkKey(baseKey, index);
|
|
1257
1675
|
return providerCall(
|
|
1258
1676
|
"send",
|
|
1259
|
-
() => connection.send(cfg.targetId, chunks[index], key2, anchor
|
|
1677
|
+
() => connection.send(cfg.targetId, chunks[index], key2, anchor, {
|
|
1678
|
+
replyInThread: threadPlacement.replyInThread
|
|
1679
|
+
})
|
|
1260
1680
|
);
|
|
1261
1681
|
};
|
|
1262
|
-
let sent =
|
|
1263
|
-
|
|
1264
|
-
if (replyAnchor.get(sessionId)?.messageId === anchor)
|
|
1265
|
-
replyAnchor.delete(sessionId);
|
|
1266
|
-
anchorFallbacks++;
|
|
1267
|
-
anchor = void 0;
|
|
1682
|
+
let sent = null;
|
|
1683
|
+
try {
|
|
1268
1684
|
sent = await sendChunk(0);
|
|
1685
|
+
if (!sent && anchor && !terminated && isForwardingEnabled()) {
|
|
1686
|
+
if (replyAnchor.get(sessionId)?.messageId === anchor)
|
|
1687
|
+
replyAnchor.delete(sessionId);
|
|
1688
|
+
anchorFallbacks++;
|
|
1689
|
+
anchor = void 0;
|
|
1690
|
+
stakeGuard = 8;
|
|
1691
|
+
while (stakeGuard-- > 0) {
|
|
1692
|
+
if (stakeFlightToken) break;
|
|
1693
|
+
const current = resolveSessionAnchor(sessionId);
|
|
1694
|
+
if (current.threadId) {
|
|
1695
|
+
anchor = current.messageId;
|
|
1696
|
+
sessionAnchorThreadId = current.threadId;
|
|
1697
|
+
break;
|
|
1698
|
+
}
|
|
1699
|
+
const existing = anchorStakeFlights.get(sessionId);
|
|
1700
|
+
if (!existing) {
|
|
1701
|
+
claimStake();
|
|
1702
|
+
break;
|
|
1703
|
+
}
|
|
1704
|
+
try {
|
|
1705
|
+
await existing;
|
|
1706
|
+
} catch {
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
if (!stakeFlightToken && !anchor) {
|
|
1710
|
+
ctx.log(`im-forward: fallback stake unavailable for ${sessionId}; dropping re-send`);
|
|
1711
|
+
return;
|
|
1712
|
+
}
|
|
1713
|
+
sent = await sendChunk(0);
|
|
1714
|
+
}
|
|
1715
|
+
} finally {
|
|
1716
|
+
if (!sent) releaseStakeFlight();
|
|
1269
1717
|
}
|
|
1270
1718
|
if (!sent) {
|
|
1271
1719
|
notifySendFailure(`${cfg.provider} send failed`);
|
|
1272
1720
|
return;
|
|
1273
1721
|
}
|
|
1274
1722
|
registerRoute(sent, sessionId);
|
|
1723
|
+
const legacyUpgrade = !isConcierge && anchor !== void 0 && !sessionAnchor.threadId && sent.messageId !== anchor;
|
|
1724
|
+
const stakeNeeded = stakeFlightToken !== void 0;
|
|
1725
|
+
if (stakeNeeded) {
|
|
1726
|
+
try {
|
|
1727
|
+
let threadId = sent.threadId;
|
|
1728
|
+
if (!threadId) {
|
|
1729
|
+
const opener = await providerCall(
|
|
1730
|
+
"thread opener",
|
|
1731
|
+
() => connection.send(cfg.targetId, "\xB7", chunkKey(baseKey, 0, "opener"), sent.messageId, { replyInThread: true })
|
|
1732
|
+
);
|
|
1733
|
+
threadId = opener?.threadId ?? null;
|
|
1734
|
+
if (!threadId) {
|
|
1735
|
+
const meta = await providerCall(
|
|
1736
|
+
"metadata",
|
|
1737
|
+
() => connection.metadata(sent.messageId)
|
|
1738
|
+
);
|
|
1739
|
+
threadId = meta?.threadId ?? null;
|
|
1740
|
+
}
|
|
1741
|
+
if (opener) registerRoute(opener, sessionId);
|
|
1742
|
+
}
|
|
1743
|
+
persistSessionAnchor(sessionId, sent.messageId, threadId, cfg.targetId);
|
|
1744
|
+
if (threadId) {
|
|
1745
|
+
claimThreadOwnership({ provider: cfg.provider, threadId }, sessionId);
|
|
1746
|
+
}
|
|
1747
|
+
claimSessionRoot(cfg.provider, sent.messageId, sessionId);
|
|
1748
|
+
if (threadId) {
|
|
1749
|
+
threadRoutes.set(key(threadId), {
|
|
1750
|
+
messageId: sent.messageId,
|
|
1751
|
+
threadId,
|
|
1752
|
+
sessionId,
|
|
1753
|
+
sentAt: Date.now()
|
|
1754
|
+
});
|
|
1755
|
+
}
|
|
1756
|
+
if (threadId) {
|
|
1757
|
+
anchor = sent.messageId;
|
|
1758
|
+
threadPlacement = { replyInThread: true, topicId: threadId };
|
|
1759
|
+
}
|
|
1760
|
+
} finally {
|
|
1761
|
+
releaseStakeFlight();
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1275
1764
|
for (let index = 1; index < chunks.length; index++) {
|
|
1276
1765
|
if (terminated || !isForwardingEnabled()) return;
|
|
1277
1766
|
let next = await sendChunk(index);
|
|
@@ -1286,39 +1775,35 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1286
1775
|
notifySendFailure(
|
|
1287
1776
|
`${cfg.provider} send failed (part ${index + 1}/${chunks.length})`
|
|
1288
1777
|
);
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
);
|
|
1299
|
-
} else {
|
|
1300
|
-
ctx.log("im-forward: silent suppressed a part-failure notice");
|
|
1301
|
-
}
|
|
1778
|
+
void providerCall(
|
|
1779
|
+
"send notice",
|
|
1780
|
+
() => connection.send(
|
|
1781
|
+
cfg.targetId,
|
|
1782
|
+
`\u2026(\u7B2C ${index}/${chunks.length} \u6BB5\u4E4B\u540E\u7684\u5206\u6BB5\u53D1\u9001\u5931\u8D25\uFF0C\u5B8C\u6574\u5185\u5BB9\u89C1\u7EC8\u7AEF)`,
|
|
1783
|
+
chunkKey(baseKey, index, "fail"),
|
|
1784
|
+
anchor
|
|
1785
|
+
)
|
|
1786
|
+
);
|
|
1302
1787
|
return;
|
|
1303
1788
|
}
|
|
1304
1789
|
registerRoute(next, sessionId);
|
|
1305
1790
|
}
|
|
1306
|
-
if (connection.sendFile && !terminated && isForwardingEnabled()
|
|
1791
|
+
if (connection.sendFile && !terminated && isForwardingEnabled()) {
|
|
1307
1792
|
const files = collectFileReferences(
|
|
1308
1793
|
text,
|
|
1309
1794
|
ctx.cwd,
|
|
1310
|
-
(
|
|
1795
|
+
(path13) => {
|
|
1311
1796
|
try {
|
|
1312
|
-
const stat =
|
|
1797
|
+
const stat = fs8.statSync(path13);
|
|
1313
1798
|
return { isFile: stat.isFile(), size: stat.size };
|
|
1314
1799
|
} catch {
|
|
1315
1800
|
return null;
|
|
1316
1801
|
}
|
|
1317
1802
|
},
|
|
1318
1803
|
{
|
|
1319
|
-
canonicalize: (
|
|
1804
|
+
canonicalize: (path13) => {
|
|
1320
1805
|
try {
|
|
1321
|
-
return
|
|
1806
|
+
return fs8.realpathSync(path13);
|
|
1322
1807
|
} catch {
|
|
1323
1808
|
return null;
|
|
1324
1809
|
}
|
|
@@ -1327,7 +1812,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1327
1812
|
);
|
|
1328
1813
|
const failedFiles = [];
|
|
1329
1814
|
for (const [index, file] of files.entries()) {
|
|
1330
|
-
if (terminated || !isForwardingEnabled()
|
|
1815
|
+
if (terminated || !isForwardingEnabled()) return;
|
|
1331
1816
|
const attachment = await providerCall(
|
|
1332
1817
|
"send file",
|
|
1333
1818
|
() => connection.sendFile(
|
|
@@ -1345,7 +1830,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1345
1830
|
failedFiles.push(basename(file));
|
|
1346
1831
|
}
|
|
1347
1832
|
}
|
|
1348
|
-
if (failedFiles.length > 0 && !terminated && isForwardingEnabled()
|
|
1833
|
+
if (failedFiles.length > 0 && !terminated && isForwardingEnabled()) {
|
|
1349
1834
|
const names = failedFiles.slice(0, 5).map((name) => name.replace(/[\r\n]/g, " ").slice(0, 80)).join("\u3001");
|
|
1350
1835
|
const extra = failedFiles.length > 5 ? `\uFF08\u53E6 ${failedFiles.length - 5} \u4E2A\uFF09` : "";
|
|
1351
1836
|
await providerCall(
|
|
@@ -1360,9 +1845,20 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1360
1845
|
}
|
|
1361
1846
|
}
|
|
1362
1847
|
}
|
|
1363
|
-
const
|
|
1848
|
+
const sentAnchors = /* @__PURE__ */ new Set();
|
|
1849
|
+
function registerRoute(sent, sessionId) {
|
|
1850
|
+
sentAnchors.add(sent.messageId);
|
|
1851
|
+
const route = {
|
|
1852
|
+
messageId: sent.messageId,
|
|
1853
|
+
threadId: sent.threadId,
|
|
1854
|
+
sessionId,
|
|
1855
|
+
sentAt: Date.now()
|
|
1856
|
+
};
|
|
1857
|
+
routes.set(key(sent.messageId), route);
|
|
1858
|
+
ctx.log(`im-forward: forwarded session=${sessionId} as ${sent.messageId}`);
|
|
1859
|
+
}
|
|
1364
1860
|
const seamRegisterRoute = (sent, sessionId) => {
|
|
1365
|
-
|
|
1861
|
+
registerRoute(sent, sessionId ?? currentSessionId ?? "");
|
|
1366
1862
|
};
|
|
1367
1863
|
const seamClaimThread = (sent, sessionId) => {
|
|
1368
1864
|
if (!sent.threadId) return { claimed: false, reason: "no thread" };
|
|
@@ -1386,20 +1882,10 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1386
1882
|
claimThread: seamClaimThread,
|
|
1387
1883
|
anchors: sentAnchors
|
|
1388
1884
|
};
|
|
1389
|
-
function registerRoute(sent, sessionId) {
|
|
1390
|
-
sentAnchors.add(sent.messageId);
|
|
1391
|
-
const route = {
|
|
1392
|
-
messageId: sent.messageId,
|
|
1393
|
-
threadId: sent.threadId,
|
|
1394
|
-
sessionId,
|
|
1395
|
-
sentAt: Date.now()
|
|
1396
|
-
};
|
|
1397
|
-
routes.set(key(sent.messageId), route);
|
|
1398
|
-
ctx.log(`im-forward: forwarded session=${sessionId} as ${sent.messageId}`);
|
|
1399
|
-
}
|
|
1400
1885
|
ctx.on("session:changed", (event) => {
|
|
1401
1886
|
inputEpoch++;
|
|
1402
1887
|
currentSessionId = event.sessionId;
|
|
1888
|
+
if (event.sessionId) resolveSessionAnchor(event.sessionId);
|
|
1403
1889
|
if (event.sessionId && !consumer && !consumerRecovering && !restartTimer && !terminated && !suspended) {
|
|
1404
1890
|
ctx.log("im-forward: session bound, starting event consumer");
|
|
1405
1891
|
spawnConsumer();
|
|
@@ -1447,10 +1933,33 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1447
1933
|
function resolveInboundAddress(text) {
|
|
1448
1934
|
return resolveAddress(text, ctx.getSessionName?.());
|
|
1449
1935
|
}
|
|
1936
|
+
async function dispatchToOwner(event, meta) {
|
|
1937
|
+
let ownerSession;
|
|
1938
|
+
if (meta.threadId) {
|
|
1939
|
+
ownerSession = threadOwner({ provider: cfg.provider, threadId: meta.threadId }).sessionId;
|
|
1940
|
+
}
|
|
1941
|
+
if (!ownerSession && meta.replyTo) {
|
|
1942
|
+
ownerSession = sessionRootOwner(cfg.provider, meta.replyTo)?.sessionId;
|
|
1943
|
+
}
|
|
1944
|
+
if (!ownerSession || ownerSession === currentSessionId) return void 0;
|
|
1945
|
+
const payload = `${DISPATCH_PREFIX} ${JSON.stringify({ v: 1, binding: bindingKey(), event })}`;
|
|
1946
|
+
try {
|
|
1947
|
+
return await dispatchEventToSession(ownerSession, payload);
|
|
1948
|
+
} catch {
|
|
1949
|
+
return void 0;
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1450
1952
|
async function handleInboundEventInner(event, retry) {
|
|
1451
|
-
const
|
|
1452
|
-
if (
|
|
1453
|
-
|
|
1953
|
+
const isGroup = event.chatType === "group";
|
|
1954
|
+
if (isGroup) {
|
|
1955
|
+
if (cfg.groupAccess === "off") return;
|
|
1956
|
+
if (cfg.groupAccess === "allowUsers" && (!event.sender_id || !cfg.allowUsers?.includes(event.sender_id)))
|
|
1957
|
+
return;
|
|
1958
|
+
} else {
|
|
1959
|
+
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";
|
|
1960
|
+
if (!matchesTarget) return;
|
|
1961
|
+
}
|
|
1962
|
+
if (!isGroup && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id)))
|
|
1454
1963
|
return;
|
|
1455
1964
|
const messageId = event.message_id;
|
|
1456
1965
|
if (!messageId) return;
|
|
@@ -1509,8 +2018,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1509
2018
|
return;
|
|
1510
2019
|
}
|
|
1511
2020
|
const unanchored = !meta.replyTo && !meta.threadId;
|
|
1512
|
-
|
|
1513
|
-
if (claimsUnanchored && unanchored) {
|
|
2021
|
+
if (isConcierge && unanchored) {
|
|
1514
2022
|
const residentRoute = {
|
|
1515
2023
|
messageId: "",
|
|
1516
2024
|
threadId: meta.threadId ?? null,
|
|
@@ -1530,6 +2038,13 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1530
2038
|
);
|
|
1531
2039
|
return;
|
|
1532
2040
|
}
|
|
2041
|
+
if (consumerLock) {
|
|
2042
|
+
const dispatched = await dispatchToOwner(event, meta);
|
|
2043
|
+
if (dispatched) {
|
|
2044
|
+
ctx.log(`im-forward: event ${messageId} dispatched to owner ${dispatched}`);
|
|
2045
|
+
return;
|
|
2046
|
+
}
|
|
2047
|
+
}
|
|
1533
2048
|
ctx.log(`im-forward: no route for ${messageId}; ignoring`);
|
|
1534
2049
|
return;
|
|
1535
2050
|
}
|
|
@@ -1580,14 +2095,24 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1580
2095
|
}
|
|
1581
2096
|
return;
|
|
1582
2097
|
}
|
|
1583
|
-
|
|
2098
|
+
persistSessionAnchor(
|
|
2099
|
+
route.sessionId,
|
|
2100
|
+
messageId,
|
|
2101
|
+
route.threadId ?? meta.threadId ?? null,
|
|
2102
|
+
// v2 group-home: the room the user spoke in IS the anchor's home —
|
|
2103
|
+
// a group topic keeps living in the group across restarts.
|
|
2104
|
+
event.chat_id
|
|
2105
|
+
);
|
|
2106
|
+
claimSessionRoot(cfg.provider, messageId, route.sessionId);
|
|
2107
|
+
if (route.threadId ?? meta.threadId) {
|
|
2108
|
+
claimThreadOwnership({ provider: cfg.provider, threadId: route.threadId ?? meta.threadId }, route.sessionId);
|
|
2109
|
+
}
|
|
1584
2110
|
pendingInputs.push({
|
|
1585
2111
|
sessionId: route.sessionId,
|
|
1586
2112
|
caption,
|
|
1587
2113
|
messageId,
|
|
1588
2114
|
threadId: route.threadId,
|
|
1589
|
-
at: Date.now()
|
|
1590
|
-
origin: "im"
|
|
2115
|
+
at: Date.now()
|
|
1591
2116
|
});
|
|
1592
2117
|
pruneState();
|
|
1593
2118
|
ctx.log(
|
|
@@ -1695,36 +2220,17 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1695
2220
|
return { notOurs: true };
|
|
1696
2221
|
}
|
|
1697
2222
|
if (!meta.threadId) return { notOurs: true };
|
|
1698
|
-
const sharedOwner = threadOwner({ provider: cfg.provider, threadId: meta.threadId });
|
|
1699
2223
|
const byThread = threadRoutes.get(key(meta.threadId));
|
|
1700
|
-
if (sharedOwner.corrupt || sharedOwner.unavailable) return { transient: true };
|
|
1701
|
-
if (sharedOwner.sessionId && sharedOwner.sessionId !== currentSessionId) {
|
|
1702
|
-
return { notOurs: true };
|
|
1703
|
-
}
|
|
1704
|
-
if (sharedOwner.sessionId && sharedOwner.sessionId !== byThread?.sessionId) {
|
|
1705
|
-
return { notOurs: true };
|
|
1706
|
-
}
|
|
1707
2224
|
if (byThread) return { found: byThread };
|
|
1708
|
-
return await resolveRouteByThreadRoot(meta.threadId
|
|
2225
|
+
return await resolveRouteByThreadRoot(meta.threadId);
|
|
1709
2226
|
}
|
|
1710
|
-
async function resolveRouteByThreadRoot(threadId
|
|
2227
|
+
async function resolveRouteByThreadRoot(threadId) {
|
|
1711
2228
|
const messages = await fetchThreadMessages(threadId);
|
|
1712
2229
|
if (!messages) return { transient: true };
|
|
1713
2230
|
const rootId = messages[0];
|
|
1714
2231
|
if (!rootId) return { notOurs: true };
|
|
1715
2232
|
const route = routes.get(key(rootId));
|
|
1716
2233
|
if (!route) return { notOurs: true };
|
|
1717
|
-
if (knownSharedOwner === void 0) {
|
|
1718
|
-
const claim = claimThreadOwnership({ provider: cfg.provider, threadId }, route.sessionId);
|
|
1719
|
-
if (!claim.claimed) {
|
|
1720
|
-
if (claim.transient) {
|
|
1721
|
-
ctx.log(`im-forward: implicit thread claim for ${threadId} hit a transient registry error; retrying later`);
|
|
1722
|
-
return { transient: true };
|
|
1723
|
-
}
|
|
1724
|
-
ctx.log(`im-forward: implicit thread root ${threadId} NOT claimed: ${claim.reason}; treating as not ours`);
|
|
1725
|
-
return { notOurs: true };
|
|
1726
|
-
}
|
|
1727
|
-
}
|
|
1728
2234
|
threadRoutes.set(key(threadId), route);
|
|
1729
2235
|
return { found: route };
|
|
1730
2236
|
}
|
|
@@ -1745,10 +2251,36 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1745
2251
|
gen.retired = true;
|
|
1746
2252
|
});
|
|
1747
2253
|
}
|
|
2254
|
+
let consumerLock;
|
|
2255
|
+
function bindingKey() {
|
|
2256
|
+
return `${cfg.provider}:${cfg.appId ?? cfg.targetId}`;
|
|
2257
|
+
}
|
|
2258
|
+
function acquireConsumerSlot() {
|
|
2259
|
+
if (consumerLock) return true;
|
|
2260
|
+
const claim = tryClaimConsumer(bindingKey(), `pie-${currentSessionId ?? "unknown"}`, () => {
|
|
2261
|
+
ctx.log("im-forward: event-hub slot lost to another consumer; retiring ours");
|
|
2262
|
+
consumerLock = void 0;
|
|
2263
|
+
if (consumer || consumerRecovering) {
|
|
2264
|
+
void stopGeneration(generation ?? { handle: null, installed: false, failed: false, retired: true }).catch(() => void 0);
|
|
2265
|
+
consumer = null;
|
|
2266
|
+
consumerRecovering = false;
|
|
2267
|
+
consumerReady = false;
|
|
2268
|
+
}
|
|
2269
|
+
restartTimer = setTimeout(spawnConsumer, 15e3);
|
|
2270
|
+
restartTimer.unref?.();
|
|
2271
|
+
});
|
|
2272
|
+
if (!claim) {
|
|
2273
|
+
ctx.log("im-forward: another consumer owns the event-hub slot; dispatch mode");
|
|
2274
|
+
return false;
|
|
2275
|
+
}
|
|
2276
|
+
consumerLock = claim;
|
|
2277
|
+
return true;
|
|
2278
|
+
}
|
|
1748
2279
|
function spawnConsumer() {
|
|
1749
2280
|
restartTimer = void 0;
|
|
1750
2281
|
restartDueAt = void 0;
|
|
1751
2282
|
if (terminated || suspended || consumer || consumerRecovering) return;
|
|
2283
|
+
if (!acquireConsumerSlot()) return;
|
|
1752
2284
|
const gen = {
|
|
1753
2285
|
handle: null,
|
|
1754
2286
|
installed: false,
|
|
@@ -1871,6 +2403,8 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1871
2403
|
ctx.registerCleanup?.(async () => {
|
|
1872
2404
|
inputEpoch++;
|
|
1873
2405
|
terminated = true;
|
|
2406
|
+
consumerLock?.release();
|
|
2407
|
+
consumerLock = void 0;
|
|
1874
2408
|
const resources = [...scopes];
|
|
1875
2409
|
scopes.clear();
|
|
1876
2410
|
for (const { timer } of retryTimers.values()) clearTimeout(timer);
|
|
@@ -1976,9 +2510,9 @@ Enable forwarding and start the connection? No test message will be sent. Saving
|
|
|
1976
2510
|
|
|
1977
2511
|
// builtin/extensions/im-forward/providers/feishu/index.ts
|
|
1978
2512
|
import { spawn as spawn4 } from "node:child_process";
|
|
1979
|
-
import * as
|
|
2513
|
+
import * as fs11 from "node:fs";
|
|
1980
2514
|
import * as os3 from "node:os";
|
|
1981
|
-
import * as
|
|
2515
|
+
import * as path12 from "node:path";
|
|
1982
2516
|
|
|
1983
2517
|
// builtin/extensions/im-forward/lark-cli.ts
|
|
1984
2518
|
import { spawn as spawn2 } from "node:child_process";
|
|
@@ -1986,33 +2520,33 @@ import { StringDecoder as StringDecoder2 } from "node:string_decoder";
|
|
|
1986
2520
|
|
|
1987
2521
|
// builtin/extensions/im-forward/launch.ts
|
|
1988
2522
|
import { spawn } from "node:child_process";
|
|
1989
|
-
import * as
|
|
1990
|
-
import * as
|
|
2523
|
+
import * as fs9 from "node:fs";
|
|
2524
|
+
import * as path8 from "node:path";
|
|
1991
2525
|
import { StringDecoder } from "node:string_decoder";
|
|
1992
2526
|
function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.platform, env = process.env) {
|
|
1993
2527
|
const windows = platform === "win32";
|
|
1994
|
-
const candidates = explicit ? [
|
|
2528
|
+
const candidates = explicit ? [path8.resolve(cwd, explicit)] : (env.PATH ?? "").split(windows ? ";" : ":").filter(Boolean).flatMap((dir) => (windows ? ["lark-cli.exe", "lark-cli.cmd"] : ["lark-cli"]).map((name) => path8.resolve(cwd, dir, name)));
|
|
1995
2529
|
for (const candidate of candidates) {
|
|
1996
2530
|
try {
|
|
1997
|
-
if (!
|
|
1998
|
-
const ext =
|
|
2531
|
+
if (!fs9.statSync(candidate).isFile()) continue;
|
|
2532
|
+
const ext = path8.extname(candidate).toLowerCase();
|
|
1999
2533
|
if (ext === ".js" || ext === ".mjs") return { command: process.execPath, prefix: [candidate] };
|
|
2000
2534
|
if (windows && ext === ".cmd") {
|
|
2001
|
-
const dir =
|
|
2002
|
-
for (const root of [
|
|
2535
|
+
const dir = path8.dirname(candidate);
|
|
2536
|
+
for (const root of [path8.join(dir, "node_modules", "@larksuite", "cli"), path8.resolve(dir, "..", "@larksuite", "cli")]) {
|
|
2003
2537
|
try {
|
|
2004
|
-
const pkg = JSON.parse(
|
|
2538
|
+
const pkg = JSON.parse(fs9.readFileSync(path8.join(root, "package.json"), "utf8"));
|
|
2005
2539
|
const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["lark-cli"];
|
|
2006
2540
|
if (pkg.name !== "@larksuite/cli" || typeof bin !== "string" || bin.replace(/^\.\//, "") !== "scripts/run.js") continue;
|
|
2007
|
-
const entry =
|
|
2008
|
-
if (
|
|
2541
|
+
const entry = path8.join(root, "scripts", "run.js");
|
|
2542
|
+
if (fs9.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
|
|
2009
2543
|
} catch {
|
|
2010
2544
|
}
|
|
2011
2545
|
}
|
|
2012
2546
|
continue;
|
|
2013
2547
|
}
|
|
2014
2548
|
if (windows && ext !== ".exe") continue;
|
|
2015
|
-
|
|
2549
|
+
fs9.accessSync(candidate, fs9.constants.X_OK);
|
|
2016
2550
|
return { command: candidate, prefix: [] };
|
|
2017
2551
|
} catch {
|
|
2018
2552
|
}
|
|
@@ -2068,7 +2602,7 @@ function stopOwnedTreeInner(child, signal) {
|
|
|
2068
2602
|
}, 1500);
|
|
2069
2603
|
try {
|
|
2070
2604
|
const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
|
|
2071
|
-
killer = spawn(
|
|
2605
|
+
killer = spawn(path8.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { shell: false, windowsHide: true, stdio: "ignore" });
|
|
2072
2606
|
killer.on("error", () => finish(false));
|
|
2073
2607
|
killer.on("exit", (code) => finish(code === 0));
|
|
2074
2608
|
} catch {
|
|
@@ -2313,17 +2847,17 @@ function extractImageKey(content) {
|
|
|
2313
2847
|
}
|
|
2314
2848
|
|
|
2315
2849
|
// builtin/extensions/im-forward/providers/feishu/setup.ts
|
|
2316
|
-
import * as
|
|
2317
|
-
import * as
|
|
2850
|
+
import * as fs10 from "node:fs";
|
|
2851
|
+
import * as path11 from "node:path";
|
|
2318
2852
|
|
|
2319
2853
|
// builtin/extensions/im-forward/browser.ts
|
|
2320
2854
|
import { spawn as spawn3 } from "node:child_process";
|
|
2321
|
-
import
|
|
2855
|
+
import path9 from "node:path";
|
|
2322
2856
|
var browserScript = "$ErrorActionPreference = 'Stop'; try { $reader = [System.IO.StreamReader]::new([Console]::OpenStandardInput(), [System.Text.Encoding]::UTF8); $url = $reader.ReadToEnd(); Start-Process -FilePath $url; exit 0 } catch { exit 1 }";
|
|
2323
2857
|
function browserLaunch(platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
|
|
2324
2858
|
if (platform === "win32") {
|
|
2325
2859
|
if (!/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return;
|
|
2326
|
-
return { command:
|
|
2860
|
+
return { command: path9.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(browserScript, "utf16le").toString("base64")], stdin: true };
|
|
2327
2861
|
}
|
|
2328
2862
|
if (platform === "darwin") return { command: "/usr/bin/open", args: ["--"], stdin: false };
|
|
2329
2863
|
if (platform === "linux") return { command: "/usr/bin/xdg-open", args: [], stdin: false };
|
|
@@ -2382,24 +2916,24 @@ async function openBrowser(url, signal, seam = {}) {
|
|
|
2382
2916
|
}
|
|
2383
2917
|
|
|
2384
2918
|
// builtin/extensions/im-forward/existing-app-terminal.ts
|
|
2385
|
-
import
|
|
2919
|
+
import path10 from "node:path";
|
|
2386
2920
|
var existingAppInnerScript = "$ErrorActionPreference = 'Stop'; try { $payload = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PAYLOAD__')) | ConvertFrom-Json; Set-Location -LiteralPath $payload.cwd; & $payload.command @($payload.args); $code = $LASTEXITCODE; if ($null -eq $code) { exit 1 }; exit $code } catch { Write-Host 'Official setup failed. Close this window and retry from Pie.'; exit 1 }";
|
|
2387
2921
|
var existingAppOuterTemplate = "$ErrorActionPreference = 'Stop'; try { $inner = '" + existingAppInnerScript.replaceAll("'", "''") + "'; $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($inner)); $child = Start-Process -FilePath (Join-Path $PSHOME 'powershell.exe') -WindowStyle Normal -Wait -PassThru -ArgumentList @('-NoLogo', '-NoProfile', '-EncodedCommand', $encoded); exit $child.ExitCode } catch { exit 1 }";
|
|
2388
2922
|
function existingAppTerminal(binary, cwd, platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
|
|
2389
2923
|
if (platform !== "win32" || !/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return null;
|
|
2390
2924
|
const payload = Buffer.from(JSON.stringify({ command: binary.command, args: [...binary.prefix, "config", "init", "--brand", "feishu"], cwd }), "utf8").toString("base64");
|
|
2391
2925
|
const script = existingAppOuterTemplate.replace("__PAYLOAD__", payload);
|
|
2392
|
-
return { command:
|
|
2926
|
+
return { command: path10.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), prefix: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")] };
|
|
2393
2927
|
}
|
|
2394
2928
|
|
|
2395
2929
|
// builtin/extensions/im-forward/providers/feishu/setup.ts
|
|
2396
2930
|
function findNpmCli() {
|
|
2397
|
-
const dirs = [
|
|
2398
|
-
for (const dir of dirs) for (const root of [
|
|
2931
|
+
const dirs = [path11.dirname(process.execPath), ...(process.env.PATH ?? "").split(path11.delimiter)];
|
|
2932
|
+
for (const dir of dirs) for (const root of [path11.join(dir, "node_modules", "npm"), path11.resolve(dir, "..", "lib", "node_modules", "npm")]) {
|
|
2399
2933
|
try {
|
|
2400
|
-
const pkg = JSON.parse(
|
|
2401
|
-
const entry =
|
|
2402
|
-
if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" &&
|
|
2934
|
+
const pkg = JSON.parse(fs10.readFileSync(path11.join(root, "package.json"), "utf8"));
|
|
2935
|
+
const entry = path11.join(root, "bin", "npm-cli.js");
|
|
2936
|
+
if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" && fs10.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
|
|
2403
2937
|
} catch {
|
|
2404
2938
|
}
|
|
2405
2939
|
}
|
|
@@ -2892,13 +3426,24 @@ function normalizeEvent(line) {
|
|
|
2892
3426
|
if (!isRecord(raw) || raw.type !== "im.message.receive_v1" || typeof raw.event_id !== "string" || typeof raw.chat_id !== "string") return null;
|
|
2893
3427
|
const id = raw.message_id ?? raw.id;
|
|
2894
3428
|
if (typeof id !== "string") return null;
|
|
3429
|
+
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;
|
|
3430
|
+
let text = extractInboundText(raw.content).replace(/\[Image:\s*img_[A-Za-z0-9_-]+\]/g, "").trim();
|
|
3431
|
+
const chatType = raw.chat_type === void 0 ? void 0 : typeof raw.chat_type === "string" ? raw.chat_type : "invalid";
|
|
3432
|
+
if (chatType === "group" && mentions?.length) {
|
|
3433
|
+
const first = mentions[0];
|
|
3434
|
+
if (first?.name) {
|
|
3435
|
+
const esc = first.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
3436
|
+
text = text.replace(new RegExp(`^(?:[^\\n]*\\n)?@${esc}\\s*`), "").trim();
|
|
3437
|
+
}
|
|
3438
|
+
}
|
|
2895
3439
|
return {
|
|
2896
3440
|
event_id: raw.event_id,
|
|
2897
3441
|
message_id: id,
|
|
2898
3442
|
chat_id: raw.chat_id,
|
|
2899
3443
|
sender_id: typeof raw.sender_id === "string" ? raw.sender_id : void 0,
|
|
2900
|
-
chatType
|
|
2901
|
-
|
|
3444
|
+
chatType,
|
|
3445
|
+
mentions: mentions?.length ? mentions : void 0,
|
|
3446
|
+
text,
|
|
2902
3447
|
images: extractImageKeys(raw.content)
|
|
2903
3448
|
};
|
|
2904
3449
|
}
|
|
@@ -2921,14 +3466,16 @@ function connect(binary, profile, targetKind = "chat") {
|
|
|
2921
3466
|
lifetime.abort();
|
|
2922
3467
|
await Promise.allSettled([...active]);
|
|
2923
3468
|
},
|
|
2924
|
-
async send(target, text, key, replyTo) {
|
|
3469
|
+
async send(target, text, key, replyTo, options) {
|
|
2925
3470
|
const recipient = targetKind === "user" ? ["--user-id", target] : ["--chat-id", target];
|
|
2926
|
-
const
|
|
3471
|
+
const threadFlag = options?.replyInThread ? ["--reply-in-thread"] : [];
|
|
3472
|
+
const data = await call(replyTo ? ["im", "+messages-reply", "--as", "bot", "--message-id", replyTo, "--markdown", text, ...threadFlag, "--idempotency-key", key] : ["im", "+messages-send", "--as", "bot", ...recipient, "--markdown", text, "--idempotency-key", key]);
|
|
2927
3473
|
return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null } : null;
|
|
2928
3474
|
},
|
|
2929
|
-
async sendFile(target, file, key, replyTo) {
|
|
3475
|
+
async sendFile(target, file, key, replyTo, options) {
|
|
2930
3476
|
const recipient = targetKind === "user" ? ["--user-id", target] : ["--chat-id", target];
|
|
2931
|
-
const
|
|
3477
|
+
const threadFlag = options?.replyInThread ? ["--reply-in-thread"] : [];
|
|
3478
|
+
const data = await call(replyTo ? ["im", "+messages-reply", "--as", "bot", "--message-id", replyTo, ...threadFlag, "--file", file, "--idempotency-key", key] : ["im", "+messages-send", "--as", "bot", ...recipient, "--file", file, "--idempotency-key", key]);
|
|
2932
3479
|
return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null } : null;
|
|
2933
3480
|
},
|
|
2934
3481
|
async acknowledge(id) {
|
|
@@ -2947,19 +3494,19 @@ function connect(binary, profile, targetKind = "chat") {
|
|
|
2947
3494
|
return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
|
|
2948
3495
|
},
|
|
2949
3496
|
async downloadImage(messageId, image, index) {
|
|
2950
|
-
const directory =
|
|
2951
|
-
const cleanup = () =>
|
|
3497
|
+
const directory = fs11.mkdtempSync(path12.join(os3.tmpdir(), "pie-im-forward-"));
|
|
3498
|
+
const cleanup = () => fs11.rmSync(directory, { recursive: true, force: true });
|
|
2952
3499
|
try {
|
|
2953
3500
|
const name = `image-${index + 1}.png`;
|
|
2954
3501
|
const result = await native(binary, profile ? ["im", "+messages-resources-download", "--as", "bot", "--message-id", messageId, "--file-key", image, "--type", "image", "--output", name, "--profile", profile] : ["im", "+messages-resources-download", "--as", "bot", "--message-id", messageId, "--file-key", image, "--type", "image", "--output", name], 3e4, directory, { signal: lifetime.signal });
|
|
2955
3502
|
if (result.error || !parseLarkCliEnvelope(result.stdout).ok) throw new Error("Image download failed");
|
|
2956
|
-
let target =
|
|
2957
|
-
if (
|
|
3503
|
+
let target = path12.join(directory, name);
|
|
3504
|
+
if (fs11.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
|
|
2958
3505
|
const detected = readImageFormat(target);
|
|
2959
3506
|
if (detected.ext === ".bin") throw new Error("Unsupported image format");
|
|
2960
3507
|
if (detected.ext !== ".png") {
|
|
2961
|
-
const corrected =
|
|
2962
|
-
|
|
3508
|
+
const corrected = path12.join(directory, `image-${index + 1}${detected.ext}`);
|
|
3509
|
+
fs11.renameSync(target, corrected);
|
|
2963
3510
|
target = corrected;
|
|
2964
3511
|
}
|
|
2965
3512
|
return { file: { path: target, displayName: `feishu-image-${index + 1}${detected.ext}` }, cleanup };
|
|
@@ -3030,7 +3577,8 @@ var feishuProvider = {
|
|
|
3030
3577
|
if (!targetKind) return null;
|
|
3031
3578
|
const allowed = Array.isArray(raw.allowUsers) ? raw.allowUsers.filter((id) => typeof id === "string" && !!id.trim()) : void 0;
|
|
3032
3579
|
const appId = typeof raw.larkCliAppId === "string" && raw.larkCliAppId.trim() ? raw.larkCliAppId.trim() : void 0;
|
|
3033
|
-
|
|
3580
|
+
const groupAccess = raw.groupAccess === "allowUsers" || raw.groupAccess === "members" || raw.groupAccess === "off" ? raw.groupAccess : void 0;
|
|
3581
|
+
return { ...raw, targetId: targetKind === "user" ? openId : chatId, targetKind, allowUsers: allowed?.length ? allowed : void 0, ...appId ? { appId } : {}, ...groupAccess ? { groupAccess } : {} };
|
|
3034
3582
|
},
|
|
3035
3583
|
connect(settings, cwd) {
|
|
3036
3584
|
const binary = resolveLaunchSpec(typeof settings.larkCli === "string" ? settings.larkCli : void 0, cwd);
|
|
@@ -3051,13 +3599,6 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
3051
3599
|
const interactive = caps.interactiveUI;
|
|
3052
3600
|
const dir = resolveConfigDir();
|
|
3053
3601
|
let disposed = false;
|
|
3054
|
-
let relayConnection;
|
|
3055
|
-
let activeConfigTargetId;
|
|
3056
|
-
let relayRegisterRoute;
|
|
3057
|
-
let relayClaimThread;
|
|
3058
|
-
let relayAnchors;
|
|
3059
|
-
let relayCurrentSession;
|
|
3060
|
-
const relayAnchorOwned = (id) => relayAnchors?.has(id) === true;
|
|
3061
3602
|
let session = null;
|
|
3062
3603
|
let setupAbort;
|
|
3063
3604
|
let setupFlight;
|
|
@@ -3077,6 +3618,13 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
3077
3618
|
return handlers.get(name)?.(event);
|
|
3078
3619
|
});
|
|
3079
3620
|
let warnedMismatch = false;
|
|
3621
|
+
let relayConnection;
|
|
3622
|
+
let relayTargetId;
|
|
3623
|
+
let relayRegisterRoute;
|
|
3624
|
+
let relayClaimThread;
|
|
3625
|
+
let relayAnchors;
|
|
3626
|
+
let relayCurrentSession;
|
|
3627
|
+
const relayAnchorOwned = (id) => relayAnchors?.has(id) === true;
|
|
3080
3628
|
function liveEnabled(config) {
|
|
3081
3629
|
if (disposed) return false;
|
|
3082
3630
|
const live = readLiveConfig(ctx.cwd, dir);
|
|
@@ -3090,11 +3638,6 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
3090
3638
|
}
|
|
3091
3639
|
return live.config.enabled;
|
|
3092
3640
|
}
|
|
3093
|
-
const liveOutboundMode = () => {
|
|
3094
|
-
const live = readLiveConfig(ctx.cwd, dir);
|
|
3095
|
-
if (live.config?.outboundMode) return live.config.outboundMode;
|
|
3096
|
-
return caps.unattended ? "gateway" : "mirror";
|
|
3097
|
-
};
|
|
3098
3641
|
function activate(config) {
|
|
3099
3642
|
if (disposed) return;
|
|
3100
3643
|
const provider = providers.find((item) => item.id === config.provider);
|
|
@@ -3119,7 +3662,7 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
3119
3662
|
activeConfig = config;
|
|
3120
3663
|
warnedMismatch = false;
|
|
3121
3664
|
relayConnection = connection;
|
|
3122
|
-
|
|
3665
|
+
relayTargetId = settings.targetId;
|
|
3123
3666
|
const bridge = Object.create(ctx);
|
|
3124
3667
|
bridge.on = (name, handler) => {
|
|
3125
3668
|
handlers.set(name, handler);
|
|
@@ -3137,11 +3680,11 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
3137
3680
|
return () => {
|
|
3138
3681
|
};
|
|
3139
3682
|
};
|
|
3140
|
-
createRuntime(bridge, { enabled: config.enabled, provider: config.provider, label: provider.label, targetId: settings.targetId, targetKind: settings.targetKind, allowUsers: settings.allowUsers, retryBackoffMs: config.retryBackoffMs, ...settings.appId ? { appId: settings.appId } : {}, ...
|
|
3683
|
+
createRuntime(bridge, { enabled: config.enabled, provider: config.provider, label: provider.label, targetId: settings.targetId, targetKind: settings.targetKind, allowUsers: settings.allowUsers, retryBackoffMs: config.retryBackoffMs, ...settings.appId ? { appId: settings.appId } : {}, ...settings.groupAccess ? { groupAccess: settings.groupAccess } : {}, ...caps.unattended ? { unattended: true } : {} }, connection, () => liveEnabled(config), (next) => {
|
|
3141
3684
|
const latest = readLiveConfig(ctx.cwd, dir);
|
|
3142
3685
|
if (latest.problems.length || !latest.config || configurationIdentity(latest.config) !== configurationIdentity(config)) throw new Error("Configuration changed; setup required");
|
|
3143
3686
|
writeConfig(ctx.cwd, dir, { enabled: next });
|
|
3144
|
-
}
|
|
3687
|
+
});
|
|
3145
3688
|
relayCurrentSession = () => session;
|
|
3146
3689
|
const seam = bridge.__imRelaySeam;
|
|
3147
3690
|
relayRegisterRoute = seam?.registerRoute;
|
|
@@ -3162,7 +3705,7 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
3162
3705
|
activeConfig = void 0;
|
|
3163
3706
|
suspendEventConsumer = void 0;
|
|
3164
3707
|
relayConnection = void 0;
|
|
3165
|
-
|
|
3708
|
+
relayTargetId = void 0;
|
|
3166
3709
|
relayRegisterRoute = void 0;
|
|
3167
3710
|
relayClaimThread = void 0;
|
|
3168
3711
|
relayAnchors = void 0;
|
|
@@ -3304,7 +3847,7 @@ This does not remove the app credentials lark-cli itself stores; re-running setu
|
|
|
3304
3847
|
ctx.registerTool?.({
|
|
3305
3848
|
name: "im_relay",
|
|
3306
3849
|
label: "IM relay",
|
|
3307
|
-
description: "Send ONE explicit message to the user's IM chat on behalf of this session (multi-agent IM
|
|
3850
|
+
description: "Send ONE explicit message to the user's IM chat on behalf of this session (multi-agent IM v2 escape hatch). Use ONLY when instructed to open a direct channel (takeover: send your previous turn's body) or to post an agreed milestone into a task thread. This is not for ordinary replies \u2014 those forward automatically. Returns the sent message id; the user replying to it opens a thread routed to THIS session.",
|
|
3308
3851
|
parameters: Type.Object({
|
|
3309
3852
|
text: Type.String({ description: "Message body (markdown)", maxLength: 24e3 }),
|
|
3310
3853
|
replyTo: Type.Optional(Type.String({ description: "Optional message id to reply to (stay inside a task thread). Omit to post a new root message (takeover opener)." }))
|
|
@@ -3315,8 +3858,6 @@ This does not remove the app credentials lark-cli itself stores; re-running setu
|
|
|
3315
3858
|
const liveConfig = readLiveConfig(ctx.cwd, dir);
|
|
3316
3859
|
if (liveConfig.problems.length || !liveConfig.config) return { content: [{ type: "text", text: "im_relay unavailable: IM configuration is missing or unreadable." }], isError: true };
|
|
3317
3860
|
if (liveConfig.config.enabled !== true) return { content: [{ type: "text", text: "im_relay refused: IM forwarding is currently disabled (enabled:false)." }], isError: true };
|
|
3318
|
-
const liveMode = liveConfig.config.outboundMode ?? (caps.unattended ? "gateway" : "mirror");
|
|
3319
|
-
if (liveMode === "silent") return { content: [{ type: "text", text: "im_relay refused: this host is in silent mode (it never messages the user). If you need a takeover channel, the operator must lift the mode." }], isError: true };
|
|
3320
3861
|
if (configurationIdentity(liveConfig.config) !== configurationIdentity(activeConfig)) return { content: [{ type: "text", text: "im_relay refused: the IM configuration changed; run setup first." }], isError: true };
|
|
3321
3862
|
const connection = relayConnection;
|
|
3322
3863
|
if (!connection) return { content: [{ type: "text", text: "im_relay unavailable: no active provider connection." }], isError: true };
|
|
@@ -3326,7 +3867,7 @@ This does not remove the app credentials lark-cli itself stores; re-running setu
|
|
|
3326
3867
|
try {
|
|
3327
3868
|
const key = `pie-im-relay-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
3328
3869
|
const sendSessionId = relayCurrentSession?.() ?? void 0;
|
|
3329
|
-
const sent = await connection.send(
|
|
3870
|
+
const sent = await connection.send(relayTargetId, args.text, key, args.replyTo);
|
|
3330
3871
|
if (!sent) return { content: [{ type: "text", text: "im_relay: the provider send failed." }], isError: true };
|
|
3331
3872
|
const claim = relayClaimThread?.(sent, sendSessionId);
|
|
3332
3873
|
if (claim && !claim.claimed && claim.reason === "no thread") {
|