@cydm/pie 4.1.0 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builtin/extensions/ask-user/index.js +2 -2
- package/dist/builtin/extensions/cron/index.js +177 -24
- package/dist/builtin/extensions/im-forward/index.js +500 -64
- package/dist/builtin/extensions/memory/index.js +3 -3
- package/dist/builtin/extensions/pie-ipc/index.js +10 -3
- package/dist/builtin/extensions/pie-proc/README.md +13 -0
- package/dist/builtin/extensions/pie-proc/index.js +41 -9
- package/dist/builtin/extensions/plan-mode/index.js +2 -2
- package/dist/builtin/extensions/subagent/index.js +3 -3
- package/dist/builtin/extensions/todo/index.js +2 -2
- package/dist/chunks/{chunk-WK4N5HT5.js → chunk-BK36Y35W.js} +31 -0
- package/dist/chunks/{chunk-UOZHQ73X.js → chunk-J2LGVYH2.js} +2 -2
- package/dist/chunks/{chunk-FDLLNPIE.js → chunk-PC6HUZAD.js} +1 -1
- package/dist/chunks/{chunk-TDKNKNPL.js → chunk-PFXSA2LK.js} +3 -3
- package/dist/chunks/{concierge-cli-VWNRJG5A.js → concierge-cli-R3RIBGJL.js} +142 -53
- package/dist/chunks/{src-AB7PLORG.js → src-AQ4H43UM.js} +2 -2
- package/dist/chunks/{src-ZZZO4HSR.js → src-VPMIQGEW.js} +1 -1
- package/dist/cli.js +85 -15
- package/package.json +2 -2
|
@@ -3,6 +3,9 @@ import {
|
|
|
3
3
|
detectImageMime,
|
|
4
4
|
readImageFormat
|
|
5
5
|
} from "../../../chunks/chunk-F7EBZTZO.js";
|
|
6
|
+
import {
|
|
7
|
+
Type
|
|
8
|
+
} from "../../../chunks/chunk-XXGYUYXI.js";
|
|
6
9
|
import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
7
10
|
|
|
8
11
|
// builtin/extensions/im-forward/config.ts
|
|
@@ -341,9 +344,9 @@ function collectFileReferences(text, cwd, fsStat, options) {
|
|
|
341
344
|
}
|
|
342
345
|
for (const candidate of candidates) {
|
|
343
346
|
if (results.length >= maxFiles) break;
|
|
344
|
-
let
|
|
345
|
-
if (!
|
|
346
|
-
const clean =
|
|
347
|
+
let path9 = candidate.trim();
|
|
348
|
+
if (!path9 || path9.startsWith("/") || path9.startsWith("~") || /^[a-z]+:/i.test(path9) || path9.includes("://")) continue;
|
|
349
|
+
const clean = path9.replace(/^\.\//, "").split("#")[0].split("?")[0];
|
|
347
350
|
if (clean.includes("..")) continue;
|
|
348
351
|
const extension = clean.split(".").pop().toLowerCase();
|
|
349
352
|
if (!extension || !ATTACHABLE_EXTENSIONS.has(extension)) continue;
|
|
@@ -456,7 +459,9 @@ function resolveConfig(cwd, dir) {
|
|
|
456
459
|
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.");
|
|
457
460
|
const provider = typeof merged.provider === "string" ? merged.provider : "feishu";
|
|
458
461
|
const retry = merged.retryBackoffMs;
|
|
459
|
-
|
|
462
|
+
const rawMode = merged.outboundMode;
|
|
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: [] };
|
|
460
465
|
} catch (error) {
|
|
461
466
|
return { config: null, problems: [error.message] };
|
|
462
467
|
}
|
|
@@ -484,6 +489,7 @@ function writeConfig(cwd, dir, update, expected) {
|
|
|
484
489
|
const target = saveLocation(cwd, dir);
|
|
485
490
|
const value = readLayer(target);
|
|
486
491
|
value.enabled = update.enabled;
|
|
492
|
+
if (update.outboundMode) value.outboundMode = update.outboundMode;
|
|
487
493
|
if (update.provider) {
|
|
488
494
|
value.provider = update.provider;
|
|
489
495
|
value.providers = { ...isRecord(value.providers) ? value.providers : {}, [update.provider]: update.settings ?? {} };
|
|
@@ -555,7 +561,7 @@ function resolveImForwardConfig(cwd, dir) {
|
|
|
555
561
|
|
|
556
562
|
// builtin/extensions/im-forward/runtime.ts
|
|
557
563
|
import * as crypto from "node:crypto";
|
|
558
|
-
import * as
|
|
564
|
+
import * as fs4 from "node:fs";
|
|
559
565
|
import { basename } from "node:path";
|
|
560
566
|
|
|
561
567
|
// builtin/extensions/im-forward/address-book.ts
|
|
@@ -656,6 +662,289 @@ function resolveAddress(text, ownLiveName, book) {
|
|
|
656
662
|
return { kind: "ambiguous", name, reason: "unpublished address" };
|
|
657
663
|
}
|
|
658
664
|
|
|
665
|
+
// builtin/extensions/im-forward/thread-registry.ts
|
|
666
|
+
import * as fs3 from "node:fs";
|
|
667
|
+
import * as path3 from "node:path";
|
|
668
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
669
|
+
var SCHEMA = 1;
|
|
670
|
+
var RUNTIME_ID = randomUUID2();
|
|
671
|
+
function encodeThreadKey(input) {
|
|
672
|
+
const raw = `${input.provider}\0${input.threadId}`;
|
|
673
|
+
return Buffer.from(raw, "utf8").toString("base64url");
|
|
674
|
+
}
|
|
675
|
+
function threadsDir() {
|
|
676
|
+
return path3.join(addressBookRoot(), "threads");
|
|
677
|
+
}
|
|
678
|
+
function pidAlive2(pid) {
|
|
679
|
+
if (!Number.isInteger(pid) || pid <= 0) return true;
|
|
680
|
+
try {
|
|
681
|
+
process.kill(pid, 0);
|
|
682
|
+
return true;
|
|
683
|
+
} catch (error) {
|
|
684
|
+
return error.code === "EPERM";
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
function ownerPath(threadKey) {
|
|
688
|
+
return path3.join(threadsDir(), `${threadKey}.json`);
|
|
689
|
+
}
|
|
690
|
+
function readOwner(threadKey) {
|
|
691
|
+
const file = ownerPath(threadKey);
|
|
692
|
+
let raw;
|
|
693
|
+
try {
|
|
694
|
+
raw = JSON.parse(fs3.readFileSync(file, "utf8"));
|
|
695
|
+
} catch (error) {
|
|
696
|
+
const code = error.code;
|
|
697
|
+
if (code === "ENOENT") return {};
|
|
698
|
+
return { corrupt: true };
|
|
699
|
+
}
|
|
700
|
+
if (typeof raw !== "object" || raw === null) return { corrupt: true };
|
|
701
|
+
const record = raw;
|
|
702
|
+
if (record.schema !== SCHEMA || typeof record.threadKey !== "string" || record.threadKey !== threadKey || // foreign key inside our file: corrupt
|
|
703
|
+
typeof record.sessionId !== "string" || typeof record.pid !== "number" || typeof record.runtimeId !== "string" || typeof record.claimedAt !== "number") {
|
|
704
|
+
return { corrupt: true };
|
|
705
|
+
}
|
|
706
|
+
return { owner: record };
|
|
707
|
+
}
|
|
708
|
+
function recordFor(threadKey, sessionId) {
|
|
709
|
+
return {
|
|
710
|
+
schema: SCHEMA,
|
|
711
|
+
threadKey,
|
|
712
|
+
sessionId,
|
|
713
|
+
pid: process.pid,
|
|
714
|
+
runtimeId: RUNTIME_ID,
|
|
715
|
+
claimedAt: Date.now()
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
function takeOver(threadKey, _dead, sessionId) {
|
|
719
|
+
const file = ownerPath(threadKey);
|
|
720
|
+
try {
|
|
721
|
+
fs3.rmSync(file, { force: true });
|
|
722
|
+
} catch {
|
|
723
|
+
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
724
|
+
}
|
|
725
|
+
return writeNew(threadKey, sessionId);
|
|
726
|
+
}
|
|
727
|
+
function decide(owner, threadKey, sessionId) {
|
|
728
|
+
if (owner.sessionId === sessionId && owner.runtimeId === RUNTIME_ID) {
|
|
729
|
+
return { claimed: true, ownerSessionId: sessionId };
|
|
730
|
+
}
|
|
731
|
+
if (owner.pid > 0 && !pidAlive2(owner.pid)) {
|
|
732
|
+
return takeOver(threadKey, owner, sessionId);
|
|
733
|
+
}
|
|
734
|
+
return {
|
|
735
|
+
claimed: false,
|
|
736
|
+
reason: `thread owned by session ${owner.sessionId}`,
|
|
737
|
+
ownerSessionId: owner.sessionId
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
function writeNew(threadKey, sessionId) {
|
|
741
|
+
const file = ownerPath(threadKey);
|
|
742
|
+
const record = recordFor(threadKey, sessionId);
|
|
743
|
+
const tmp = path3.join(threadsDir(), `.new-${randomUUID2()}.json`);
|
|
744
|
+
try {
|
|
745
|
+
const fd = fs3.openSync(tmp, "wx", 384);
|
|
746
|
+
try {
|
|
747
|
+
fs3.writeFileSync(fd, JSON.stringify(record));
|
|
748
|
+
try {
|
|
749
|
+
fs3.fsyncSync(fd);
|
|
750
|
+
} catch (error) {
|
|
751
|
+
try {
|
|
752
|
+
fs3.closeSync(fd);
|
|
753
|
+
} catch {
|
|
754
|
+
}
|
|
755
|
+
try {
|
|
756
|
+
fs3.rmSync(tmp, { force: true });
|
|
757
|
+
} catch {
|
|
758
|
+
}
|
|
759
|
+
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
760
|
+
}
|
|
761
|
+
} finally {
|
|
762
|
+
fs3.closeSync(fd);
|
|
763
|
+
}
|
|
764
|
+
} catch {
|
|
765
|
+
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
766
|
+
}
|
|
767
|
+
try {
|
|
768
|
+
fs3.linkSync(tmp, file);
|
|
769
|
+
return { claimed: true, ownerSessionId: sessionId };
|
|
770
|
+
} catch (error) {
|
|
771
|
+
const code = error.code;
|
|
772
|
+
if (code === "EEXIST") {
|
|
773
|
+
const winner = readOwner(threadKey);
|
|
774
|
+
if (winner.corrupt) return { claimed: false, reason: "thread record unreadable", transient: true };
|
|
775
|
+
if (winner.owner) return decide(winner.owner, threadKey, sessionId);
|
|
776
|
+
return writeNew(threadKey, sessionId);
|
|
777
|
+
}
|
|
778
|
+
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
779
|
+
} finally {
|
|
780
|
+
try {
|
|
781
|
+
fs3.rmSync(tmp, { force: true });
|
|
782
|
+
} catch {
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
function claimThreadOwnership(input, sessionId) {
|
|
787
|
+
if (!input.threadId || !sessionId) return { claimed: false, reason: "no thread or session" };
|
|
788
|
+
const threadKey = encodeThreadKey(input);
|
|
789
|
+
let stat;
|
|
790
|
+
try {
|
|
791
|
+
stat = fs3.statSync(threadsDir());
|
|
792
|
+
} catch (error) {
|
|
793
|
+
if (error.code !== "ENOENT") {
|
|
794
|
+
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
795
|
+
}
|
|
796
|
+
stat = void 0;
|
|
797
|
+
}
|
|
798
|
+
if (stat && !stat.isDirectory()) return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
799
|
+
try {
|
|
800
|
+
fs3.mkdirSync(threadsDir(), { recursive: true, mode: 448 });
|
|
801
|
+
} catch {
|
|
802
|
+
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
803
|
+
}
|
|
804
|
+
const lock = acquireThreadLock(threadKey);
|
|
805
|
+
if (!lock.acquired) return { claimed: false, reason: lock.reason, transient: lock.transient };
|
|
806
|
+
try {
|
|
807
|
+
const existing = readOwner(threadKey);
|
|
808
|
+
if (existing.corrupt) {
|
|
809
|
+
return { claimed: false, reason: "thread record unreadable", transient: true };
|
|
810
|
+
}
|
|
811
|
+
if (existing.owner) return decide(existing.owner, threadKey, sessionId);
|
|
812
|
+
return writeNew(threadKey, sessionId);
|
|
813
|
+
} finally {
|
|
814
|
+
releaseThreadLock(threadKey);
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
function lockDirPath(threadKey) {
|
|
818
|
+
return path3.join(threadsDir(), `${threadKey}.lock`);
|
|
819
|
+
}
|
|
820
|
+
function writeHolderEntry(dir, token) {
|
|
821
|
+
fs3.writeFileSync(path3.join(dir, `held.${token}`), JSON.stringify({ version: 1, pid: process.pid, createdAt: Date.now() }), { mode: 384, flag: "wx" });
|
|
822
|
+
}
|
|
823
|
+
function retireStaleLock(lock) {
|
|
824
|
+
let entries;
|
|
825
|
+
try {
|
|
826
|
+
entries = fs3.readdirSync(lock);
|
|
827
|
+
} catch {
|
|
828
|
+
return false;
|
|
829
|
+
}
|
|
830
|
+
const holders = entries.filter((name) => name.startsWith("held."));
|
|
831
|
+
if (holders.length === 0) {
|
|
832
|
+
if (entries.length !== 0) return false;
|
|
833
|
+
try {
|
|
834
|
+
fs3.rmdirSync(lock);
|
|
835
|
+
return true;
|
|
836
|
+
} catch {
|
|
837
|
+
return false;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
for (const name of holders) {
|
|
841
|
+
let pid;
|
|
842
|
+
try {
|
|
843
|
+
const parsed = JSON.parse(fs3.readFileSync(path3.join(lock, name), "utf8"));
|
|
844
|
+
if (parsed?.version !== 1 || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return false;
|
|
845
|
+
pid = parsed.pid;
|
|
846
|
+
} catch {
|
|
847
|
+
return false;
|
|
848
|
+
}
|
|
849
|
+
try {
|
|
850
|
+
process.kill(pid, 0);
|
|
851
|
+
return false;
|
|
852
|
+
} catch (error) {
|
|
853
|
+
if (error?.code !== "ESRCH") return false;
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
for (const name of holders) {
|
|
857
|
+
try {
|
|
858
|
+
fs3.unlinkSync(path3.join(lock, name));
|
|
859
|
+
} catch (error) {
|
|
860
|
+
if (error.code !== "ENOENT") return false;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
try {
|
|
864
|
+
fs3.rmdirSync(lock);
|
|
865
|
+
return true;
|
|
866
|
+
} catch {
|
|
867
|
+
return false;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
var acquiredLocks = /* @__PURE__ */ new Map();
|
|
871
|
+
function acquireThreadLock(threadKey) {
|
|
872
|
+
if (acquiredLocks.has(threadKey)) return { acquired: true };
|
|
873
|
+
const lock = lockDirPath(threadKey);
|
|
874
|
+
const token = randomUUID2();
|
|
875
|
+
const candidate = path3.join(threadsDir(), `lock.acquire.${token}`);
|
|
876
|
+
try {
|
|
877
|
+
try {
|
|
878
|
+
fs3.mkdirSync(candidate, { mode: 448 });
|
|
879
|
+
} catch {
|
|
880
|
+
return { acquired: false, reason: "thread registry unavailable", transient: true };
|
|
881
|
+
}
|
|
882
|
+
try {
|
|
883
|
+
writeHolderEntry(candidate, token);
|
|
884
|
+
} catch {
|
|
885
|
+
try {
|
|
886
|
+
fs3.rmSync(candidate, { recursive: true, force: true });
|
|
887
|
+
} catch {
|
|
888
|
+
}
|
|
889
|
+
return { acquired: false, reason: "thread registry unavailable", transient: true };
|
|
890
|
+
}
|
|
891
|
+
const deadline = Date.now() + 5e3;
|
|
892
|
+
for (; ; ) {
|
|
893
|
+
try {
|
|
894
|
+
fs3.renameSync(candidate, lock);
|
|
895
|
+
acquiredLocks.set(threadKey, token);
|
|
896
|
+
return { acquired: true };
|
|
897
|
+
} catch (error) {
|
|
898
|
+
const code = error?.code;
|
|
899
|
+
if (code !== "EEXIST" && code !== "ENOTEMPTY" && code !== "EPERM" && code !== "ENOTDIR") {
|
|
900
|
+
return { acquired: false, reason: "thread registry unavailable", transient: true };
|
|
901
|
+
}
|
|
902
|
+
if (Date.now() > deadline) return { acquired: false, reason: "thread lock busy", transient: true };
|
|
903
|
+
try {
|
|
904
|
+
retireStaleLock(lock);
|
|
905
|
+
} catch {
|
|
906
|
+
}
|
|
907
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1 + Math.floor(Math.random() * 3));
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
} finally {
|
|
911
|
+
try {
|
|
912
|
+
fs3.rmSync(candidate, { recursive: true, force: true });
|
|
913
|
+
} catch {
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
function releaseThreadLock(threadKey) {
|
|
918
|
+
const token = acquiredLocks.get(threadKey);
|
|
919
|
+
if (token === void 0) return;
|
|
920
|
+
acquiredLocks.delete(threadKey);
|
|
921
|
+
const lock = lockDirPath(threadKey);
|
|
922
|
+
try {
|
|
923
|
+
fs3.unlinkSync(path3.join(lock, `held.${token}`));
|
|
924
|
+
} catch {
|
|
925
|
+
}
|
|
926
|
+
try {
|
|
927
|
+
const remaining = fs3.readdirSync(lock);
|
|
928
|
+
if (remaining.length === 0) fs3.rmdirSync(lock);
|
|
929
|
+
} catch {
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
function threadOwner(input) {
|
|
933
|
+
const threadKey = encodeThreadKey(input);
|
|
934
|
+
let read;
|
|
935
|
+
try {
|
|
936
|
+
read = readOwner(threadKey);
|
|
937
|
+
} catch {
|
|
938
|
+
return { unavailable: true };
|
|
939
|
+
}
|
|
940
|
+
if (read.corrupt) return { corrupt: true };
|
|
941
|
+
if (!read.owner) return {};
|
|
942
|
+
if (read.owner.pid > 0 && !pidAlive2(read.owner.pid)) {
|
|
943
|
+
return {};
|
|
944
|
+
}
|
|
945
|
+
return { sessionId: read.owner.sessionId };
|
|
946
|
+
}
|
|
947
|
+
|
|
659
948
|
// builtin/extensions/im-forward/runtime.ts
|
|
660
949
|
var ROUTE_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
661
950
|
var MAX_ROUTES = 500;
|
|
@@ -695,10 +984,20 @@ function hashText(input) {
|
|
|
695
984
|
}
|
|
696
985
|
return Math.abs(hash).toString(36);
|
|
697
986
|
}
|
|
698
|
-
function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
987
|
+
function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled, liveOutboundMode = () => cfg.outboundMode ?? (cfg.unattended === true ? "gateway" : "mirror")) {
|
|
699
988
|
const IM_INPUT_PREFIX = connection.sourcePrefix;
|
|
700
989
|
const key = (id) => JSON.stringify([cfg.provider, id]);
|
|
701
990
|
const isUnattended = cfg.unattended === true;
|
|
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
|
+
};
|
|
702
1001
|
const scopes = /* @__PURE__ */ new Set();
|
|
703
1002
|
let forwardingEnabled = cfg.enabled === true;
|
|
704
1003
|
let configurationFailed = false;
|
|
@@ -711,13 +1010,21 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
|
711
1010
|
forwardingEnabled = live;
|
|
712
1011
|
updateFooterTag();
|
|
713
1012
|
}
|
|
1013
|
+
const nextMode = liveOutboundMode();
|
|
1014
|
+
if (nextMode !== outboundMode) {
|
|
1015
|
+
setOutboundMode(nextMode);
|
|
1016
|
+
updateFooterTag();
|
|
1017
|
+
} else {
|
|
1018
|
+
setOutboundMode(nextMode);
|
|
1019
|
+
}
|
|
714
1020
|
return forwardingEnabled;
|
|
715
1021
|
}
|
|
716
1022
|
const STATUS_KEY = "im-forward";
|
|
717
1023
|
function updateFooterTag() {
|
|
1024
|
+
const modeTag = outboundMode === "gateway" ? "" : outboundMode === "mirror" ? "\xB7m" : "\xB7s";
|
|
718
1025
|
ctx.ui.setStatus?.(
|
|
719
1026
|
STATUS_KEY,
|
|
720
|
-
configurationFailed ? "[IM!]" : forwardingEnabled ? consumerLastExit ? "[IM!]" : consumerReady ?
|
|
1027
|
+
configurationFailed ? "[IM!]" : forwardingEnabled ? consumerLastExit ? "[IM!]" : consumerReady ? `[IM${modeTag}]` : "[IM\u2026]" : void 0
|
|
721
1028
|
);
|
|
722
1029
|
}
|
|
723
1030
|
function writeEnabledToConfig(next) {
|
|
@@ -757,6 +1064,7 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
|
757
1064
|
let currentSessionId = null;
|
|
758
1065
|
const pendingInputs = [];
|
|
759
1066
|
const replyAnchor = /* @__PURE__ */ new Map();
|
|
1067
|
+
const sentAnchors = /* @__PURE__ */ new Set();
|
|
760
1068
|
const routes = /* @__PURE__ */ new Map();
|
|
761
1069
|
const threadRoutes = /* @__PURE__ */ new Map();
|
|
762
1070
|
const seenEventIds = /* @__PURE__ */ new Map();
|
|
@@ -843,7 +1151,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
843
1151
|
return {
|
|
844
1152
|
caption: pending.caption || `${IM_INPUT_PREFIX} images`,
|
|
845
1153
|
replyTo: pending.messageId || void 0,
|
|
846
|
-
threadId: pending.threadId
|
|
1154
|
+
threadId: pending.threadId,
|
|
1155
|
+
origin: pending.origin
|
|
847
1156
|
};
|
|
848
1157
|
}
|
|
849
1158
|
}
|
|
@@ -868,7 +1177,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
868
1177
|
caption: text,
|
|
869
1178
|
messageId: "",
|
|
870
1179
|
threadId: null,
|
|
871
|
-
at: Date.now()
|
|
1180
|
+
at: Date.now(),
|
|
1181
|
+
origin: "terminal"
|
|
872
1182
|
});
|
|
873
1183
|
pruneState();
|
|
874
1184
|
}
|
|
@@ -885,6 +1195,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
885
1195
|
if (!sessionId) return;
|
|
886
1196
|
const sequence = ++forwardCounter;
|
|
887
1197
|
const attribution = resolveOutboundAttribution(sessionId);
|
|
1198
|
+
if (!maySpeak(attribution?.origin === "im")) return;
|
|
888
1199
|
void forwardMessage(
|
|
889
1200
|
text,
|
|
890
1201
|
sessionId,
|
|
@@ -900,6 +1211,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
900
1211
|
const reason = failureReason(event.message ?? {});
|
|
901
1212
|
const sequence = ++forwardCounter;
|
|
902
1213
|
const attribution = resolveOutboundAttribution(sessionId);
|
|
1214
|
+
if (!maySpeak(attribution?.origin === "im")) return;
|
|
903
1215
|
void forwardMessage(
|
|
904
1216
|
`\u26A0\uFE0F \u4EFB\u52A1\u5931\u8D25\uFF1A${reason}`,
|
|
905
1217
|
sessionId,
|
|
@@ -914,6 +1226,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
914
1226
|
if (!sessionId) return;
|
|
915
1227
|
const sequence = ++forwardCounter;
|
|
916
1228
|
const attribution = resolveOutboundAttribution(sessionId);
|
|
1229
|
+
if (!maySpeak(attribution?.origin === "im")) return;
|
|
917
1230
|
void forwardMessage(
|
|
918
1231
|
`\u26D4\uFE0F \u4EFB\u52A1\u5DF2\u53D6\u6D88\uFF1A${event.reason}`,
|
|
919
1232
|
sessionId,
|
|
@@ -924,7 +1237,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
924
1237
|
});
|
|
925
1238
|
async function forwardMessage(text, sessionId, sequence, userInput, replyTo) {
|
|
926
1239
|
pruneState();
|
|
927
|
-
const sessionName = ctx.getSessionName?.();
|
|
1240
|
+
const sessionName = ctx.getSessionDisplayName?.() ?? ctx.getSessionName?.();
|
|
928
1241
|
const composed = composeForwardBody(
|
|
929
1242
|
sessionId,
|
|
930
1243
|
sessionName,
|
|
@@ -936,6 +1249,10 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
936
1249
|
const baseKey = `pie-im-forward-${cfg.provider}-${incarnation}-${sessionId}-${sequence}-${hashText(composed)}`;
|
|
937
1250
|
let anchor = replyTo ?? replyAnchor.get(sessionId)?.messageId;
|
|
938
1251
|
const sendChunk = async (index) => {
|
|
1252
|
+
if (outboundMode === "silent") {
|
|
1253
|
+
ctx.log("im-forward: silent mode stopped an in-flight send");
|
|
1254
|
+
return null;
|
|
1255
|
+
}
|
|
939
1256
|
const key2 = chunkKey(baseKey, index);
|
|
940
1257
|
return providerCall(
|
|
941
1258
|
"send",
|
|
@@ -969,35 +1286,39 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
969
1286
|
notifySendFailure(
|
|
970
1287
|
`${cfg.provider} send failed (part ${index + 1}/${chunks.length})`
|
|
971
1288
|
);
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
1289
|
+
if (outboundMode !== "silent") {
|
|
1290
|
+
void providerCall(
|
|
1291
|
+
"send notice",
|
|
1292
|
+
() => connection.send(
|
|
1293
|
+
cfg.targetId,
|
|
1294
|
+
`\u2026(\u7B2C ${index}/${chunks.length} \u6BB5\u4E4B\u540E\u7684\u5206\u6BB5\u53D1\u9001\u5931\u8D25\uFF0C\u5B8C\u6574\u5185\u5BB9\u89C1\u7EC8\u7AEF)`,
|
|
1295
|
+
chunkKey(baseKey, index, "fail"),
|
|
1296
|
+
anchor
|
|
1297
|
+
)
|
|
1298
|
+
);
|
|
1299
|
+
} else {
|
|
1300
|
+
ctx.log("im-forward: silent suppressed a part-failure notice");
|
|
1301
|
+
}
|
|
981
1302
|
return;
|
|
982
1303
|
}
|
|
983
1304
|
registerRoute(next, sessionId);
|
|
984
1305
|
}
|
|
985
|
-
if (connection.sendFile && !terminated && isForwardingEnabled()) {
|
|
1306
|
+
if (connection.sendFile && !terminated && isForwardingEnabled() && outboundMode !== "silent") {
|
|
986
1307
|
const files = collectFileReferences(
|
|
987
1308
|
text,
|
|
988
1309
|
ctx.cwd,
|
|
989
|
-
(
|
|
1310
|
+
(path9) => {
|
|
990
1311
|
try {
|
|
991
|
-
const stat =
|
|
1312
|
+
const stat = fs4.statSync(path9);
|
|
992
1313
|
return { isFile: stat.isFile(), size: stat.size };
|
|
993
1314
|
} catch {
|
|
994
1315
|
return null;
|
|
995
1316
|
}
|
|
996
1317
|
},
|
|
997
1318
|
{
|
|
998
|
-
canonicalize: (
|
|
1319
|
+
canonicalize: (path9) => {
|
|
999
1320
|
try {
|
|
1000
|
-
return
|
|
1321
|
+
return fs4.realpathSync(path9);
|
|
1001
1322
|
} catch {
|
|
1002
1323
|
return null;
|
|
1003
1324
|
}
|
|
@@ -1006,7 +1327,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1006
1327
|
);
|
|
1007
1328
|
const failedFiles = [];
|
|
1008
1329
|
for (const [index, file] of files.entries()) {
|
|
1009
|
-
if (terminated || !isForwardingEnabled()) return;
|
|
1330
|
+
if (terminated || !isForwardingEnabled() || outboundMode === "silent") return;
|
|
1010
1331
|
const attachment = await providerCall(
|
|
1011
1332
|
"send file",
|
|
1012
1333
|
() => connection.sendFile(
|
|
@@ -1024,7 +1345,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1024
1345
|
failedFiles.push(basename(file));
|
|
1025
1346
|
}
|
|
1026
1347
|
}
|
|
1027
|
-
if (failedFiles.length > 0 && !terminated && isForwardingEnabled()) {
|
|
1348
|
+
if (failedFiles.length > 0 && !terminated && isForwardingEnabled() && outboundMode !== "silent") {
|
|
1028
1349
|
const names = failedFiles.slice(0, 5).map((name) => name.replace(/[\r\n]/g, " ").slice(0, 80)).join("\u3001");
|
|
1029
1350
|
const extra = failedFiles.length > 5 ? `\uFF08\u53E6 ${failedFiles.length - 5} \u4E2A\uFF09` : "";
|
|
1030
1351
|
await providerCall(
|
|
@@ -1039,7 +1360,34 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1039
1360
|
}
|
|
1040
1361
|
}
|
|
1041
1362
|
}
|
|
1363
|
+
const originalRegisterRoute = registerRoute;
|
|
1364
|
+
const seamRegisterRoute = (sent, sessionId) => {
|
|
1365
|
+
originalRegisterRoute(sent, sessionId ?? currentSessionId ?? "");
|
|
1366
|
+
};
|
|
1367
|
+
const seamClaimThread = (sent, sessionId) => {
|
|
1368
|
+
if (!sent.threadId) return { claimed: false, reason: "no thread" };
|
|
1369
|
+
const owner = sessionId ?? currentSessionId;
|
|
1370
|
+
if (!owner) return { claimed: false, reason: "no session" };
|
|
1371
|
+
const threadKey = key(sent.threadId);
|
|
1372
|
+
const shared = claimThreadOwnership({ provider: cfg.provider, threadId: sent.threadId }, owner);
|
|
1373
|
+
if (!shared.claimed) {
|
|
1374
|
+
ctx.log(`im-forward: relay REFUSED thread ${sent.threadId}: ${shared.reason}`);
|
|
1375
|
+
return { claimed: false, reason: shared.reason };
|
|
1376
|
+
}
|
|
1377
|
+
const route = { messageId: sent.messageId, threadId: sent.threadId, sessionId: owner, sentAt: Date.now() };
|
|
1378
|
+
threadRoutes.set(threadKey, route);
|
|
1379
|
+
routes.set(key(sent.messageId), route);
|
|
1380
|
+
sentAnchors.add(sent.messageId);
|
|
1381
|
+
ctx.log(`im-forward: relay claimed thread ${sent.threadId} for session ${owner}`);
|
|
1382
|
+
return { claimed: true };
|
|
1383
|
+
};
|
|
1384
|
+
ctx.__imRelaySeam = {
|
|
1385
|
+
registerRoute: seamRegisterRoute,
|
|
1386
|
+
claimThread: seamClaimThread,
|
|
1387
|
+
anchors: sentAnchors
|
|
1388
|
+
};
|
|
1042
1389
|
function registerRoute(sent, sessionId) {
|
|
1390
|
+
sentAnchors.add(sent.messageId);
|
|
1043
1391
|
const route = {
|
|
1044
1392
|
messageId: sent.messageId,
|
|
1045
1393
|
threadId: sent.threadId,
|
|
@@ -1161,7 +1509,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1161
1509
|
return;
|
|
1162
1510
|
}
|
|
1163
1511
|
const unanchored = !meta.replyTo && !meta.threadId;
|
|
1164
|
-
|
|
1512
|
+
const claimsUnanchored = isUnattended && outboundMode === "gateway";
|
|
1513
|
+
if (claimsUnanchored && unanchored) {
|
|
1165
1514
|
const residentRoute = {
|
|
1166
1515
|
messageId: "",
|
|
1167
1516
|
threadId: meta.threadId ?? null,
|
|
@@ -1237,7 +1586,8 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1237
1586
|
caption,
|
|
1238
1587
|
messageId,
|
|
1239
1588
|
threadId: route.threadId,
|
|
1240
|
-
at: Date.now()
|
|
1589
|
+
at: Date.now(),
|
|
1590
|
+
origin: "im"
|
|
1241
1591
|
});
|
|
1242
1592
|
pruneState();
|
|
1243
1593
|
ctx.log(
|
|
@@ -1345,17 +1695,36 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1345
1695
|
return { notOurs: true };
|
|
1346
1696
|
}
|
|
1347
1697
|
if (!meta.threadId) return { notOurs: true };
|
|
1698
|
+
const sharedOwner = threadOwner({ provider: cfg.provider, threadId: meta.threadId });
|
|
1348
1699
|
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
|
+
}
|
|
1349
1707
|
if (byThread) return { found: byThread };
|
|
1350
|
-
return await resolveRouteByThreadRoot(meta.threadId);
|
|
1708
|
+
return await resolveRouteByThreadRoot(meta.threadId, sharedOwner.sessionId);
|
|
1351
1709
|
}
|
|
1352
|
-
async function resolveRouteByThreadRoot(threadId) {
|
|
1710
|
+
async function resolveRouteByThreadRoot(threadId, knownSharedOwner) {
|
|
1353
1711
|
const messages = await fetchThreadMessages(threadId);
|
|
1354
1712
|
if (!messages) return { transient: true };
|
|
1355
1713
|
const rootId = messages[0];
|
|
1356
1714
|
if (!rootId) return { notOurs: true };
|
|
1357
1715
|
const route = routes.get(key(rootId));
|
|
1358
1716
|
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
|
+
}
|
|
1359
1728
|
threadRoutes.set(key(threadId), route);
|
|
1360
1729
|
return { found: route };
|
|
1361
1730
|
}
|
|
@@ -1607,9 +1976,9 @@ Enable forwarding and start the connection? No test message will be sent. Saving
|
|
|
1607
1976
|
|
|
1608
1977
|
// builtin/extensions/im-forward/providers/feishu/index.ts
|
|
1609
1978
|
import { spawn as spawn4 } from "node:child_process";
|
|
1610
|
-
import * as
|
|
1979
|
+
import * as fs7 from "node:fs";
|
|
1611
1980
|
import * as os3 from "node:os";
|
|
1612
|
-
import * as
|
|
1981
|
+
import * as path8 from "node:path";
|
|
1613
1982
|
|
|
1614
1983
|
// builtin/extensions/im-forward/lark-cli.ts
|
|
1615
1984
|
import { spawn as spawn2 } from "node:child_process";
|
|
@@ -1617,33 +1986,33 @@ import { StringDecoder as StringDecoder2 } from "node:string_decoder";
|
|
|
1617
1986
|
|
|
1618
1987
|
// builtin/extensions/im-forward/launch.ts
|
|
1619
1988
|
import { spawn } from "node:child_process";
|
|
1620
|
-
import * as
|
|
1621
|
-
import * as
|
|
1989
|
+
import * as fs5 from "node:fs";
|
|
1990
|
+
import * as path4 from "node:path";
|
|
1622
1991
|
import { StringDecoder } from "node:string_decoder";
|
|
1623
1992
|
function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.platform, env = process.env) {
|
|
1624
1993
|
const windows = platform === "win32";
|
|
1625
|
-
const candidates = explicit ? [
|
|
1994
|
+
const candidates = explicit ? [path4.resolve(cwd, explicit)] : (env.PATH ?? "").split(windows ? ";" : ":").filter(Boolean).flatMap((dir) => (windows ? ["lark-cli.exe", "lark-cli.cmd"] : ["lark-cli"]).map((name) => path4.resolve(cwd, dir, name)));
|
|
1626
1995
|
for (const candidate of candidates) {
|
|
1627
1996
|
try {
|
|
1628
|
-
if (!
|
|
1629
|
-
const ext =
|
|
1997
|
+
if (!fs5.statSync(candidate).isFile()) continue;
|
|
1998
|
+
const ext = path4.extname(candidate).toLowerCase();
|
|
1630
1999
|
if (ext === ".js" || ext === ".mjs") return { command: process.execPath, prefix: [candidate] };
|
|
1631
2000
|
if (windows && ext === ".cmd") {
|
|
1632
|
-
const dir =
|
|
1633
|
-
for (const root of [
|
|
2001
|
+
const dir = path4.dirname(candidate);
|
|
2002
|
+
for (const root of [path4.join(dir, "node_modules", "@larksuite", "cli"), path4.resolve(dir, "..", "@larksuite", "cli")]) {
|
|
1634
2003
|
try {
|
|
1635
|
-
const pkg = JSON.parse(
|
|
2004
|
+
const pkg = JSON.parse(fs5.readFileSync(path4.join(root, "package.json"), "utf8"));
|
|
1636
2005
|
const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["lark-cli"];
|
|
1637
2006
|
if (pkg.name !== "@larksuite/cli" || typeof bin !== "string" || bin.replace(/^\.\//, "") !== "scripts/run.js") continue;
|
|
1638
|
-
const entry =
|
|
1639
|
-
if (
|
|
2007
|
+
const entry = path4.join(root, "scripts", "run.js");
|
|
2008
|
+
if (fs5.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
|
|
1640
2009
|
} catch {
|
|
1641
2010
|
}
|
|
1642
2011
|
}
|
|
1643
2012
|
continue;
|
|
1644
2013
|
}
|
|
1645
2014
|
if (windows && ext !== ".exe") continue;
|
|
1646
|
-
|
|
2015
|
+
fs5.accessSync(candidate, fs5.constants.X_OK);
|
|
1647
2016
|
return { command: candidate, prefix: [] };
|
|
1648
2017
|
} catch {
|
|
1649
2018
|
}
|
|
@@ -1699,7 +2068,7 @@ function stopOwnedTreeInner(child, signal) {
|
|
|
1699
2068
|
}, 1500);
|
|
1700
2069
|
try {
|
|
1701
2070
|
const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
|
|
1702
|
-
killer = spawn(
|
|
2071
|
+
killer = spawn(path4.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { shell: false, windowsHide: true, stdio: "ignore" });
|
|
1703
2072
|
killer.on("error", () => finish(false));
|
|
1704
2073
|
killer.on("exit", (code) => finish(code === 0));
|
|
1705
2074
|
} catch {
|
|
@@ -1944,17 +2313,17 @@ function extractImageKey(content) {
|
|
|
1944
2313
|
}
|
|
1945
2314
|
|
|
1946
2315
|
// builtin/extensions/im-forward/providers/feishu/setup.ts
|
|
1947
|
-
import * as
|
|
1948
|
-
import * as
|
|
2316
|
+
import * as fs6 from "node:fs";
|
|
2317
|
+
import * as path7 from "node:path";
|
|
1949
2318
|
|
|
1950
2319
|
// builtin/extensions/im-forward/browser.ts
|
|
1951
2320
|
import { spawn as spawn3 } from "node:child_process";
|
|
1952
|
-
import
|
|
2321
|
+
import path5 from "node:path";
|
|
1953
2322
|
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 }";
|
|
1954
2323
|
function browserLaunch(platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
|
|
1955
2324
|
if (platform === "win32") {
|
|
1956
2325
|
if (!/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return;
|
|
1957
|
-
return { command:
|
|
2326
|
+
return { command: path5.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(browserScript, "utf16le").toString("base64")], stdin: true };
|
|
1958
2327
|
}
|
|
1959
2328
|
if (platform === "darwin") return { command: "/usr/bin/open", args: ["--"], stdin: false };
|
|
1960
2329
|
if (platform === "linux") return { command: "/usr/bin/xdg-open", args: [], stdin: false };
|
|
@@ -2013,24 +2382,24 @@ async function openBrowser(url, signal, seam = {}) {
|
|
|
2013
2382
|
}
|
|
2014
2383
|
|
|
2015
2384
|
// builtin/extensions/im-forward/existing-app-terminal.ts
|
|
2016
|
-
import
|
|
2385
|
+
import path6 from "node:path";
|
|
2017
2386
|
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 }";
|
|
2018
2387
|
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 }";
|
|
2019
2388
|
function existingAppTerminal(binary, cwd, platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
|
|
2020
2389
|
if (platform !== "win32" || !/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return null;
|
|
2021
2390
|
const payload = Buffer.from(JSON.stringify({ command: binary.command, args: [...binary.prefix, "config", "init", "--brand", "feishu"], cwd }), "utf8").toString("base64");
|
|
2022
2391
|
const script = existingAppOuterTemplate.replace("__PAYLOAD__", payload);
|
|
2023
|
-
return { command:
|
|
2392
|
+
return { command: path6.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), prefix: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")] };
|
|
2024
2393
|
}
|
|
2025
2394
|
|
|
2026
2395
|
// builtin/extensions/im-forward/providers/feishu/setup.ts
|
|
2027
2396
|
function findNpmCli() {
|
|
2028
|
-
const dirs = [
|
|
2029
|
-
for (const dir of dirs) for (const root of [
|
|
2397
|
+
const dirs = [path7.dirname(process.execPath), ...(process.env.PATH ?? "").split(path7.delimiter)];
|
|
2398
|
+
for (const dir of dirs) for (const root of [path7.join(dir, "node_modules", "npm"), path7.resolve(dir, "..", "lib", "node_modules", "npm")]) {
|
|
2030
2399
|
try {
|
|
2031
|
-
const pkg = JSON.parse(
|
|
2032
|
-
const entry =
|
|
2033
|
-
if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" &&
|
|
2400
|
+
const pkg = JSON.parse(fs6.readFileSync(path7.join(root, "package.json"), "utf8"));
|
|
2401
|
+
const entry = path7.join(root, "bin", "npm-cli.js");
|
|
2402
|
+
if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" && fs6.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
|
|
2034
2403
|
} catch {
|
|
2035
2404
|
}
|
|
2036
2405
|
}
|
|
@@ -2568,26 +2937,29 @@ function connect(binary, profile, targetKind = "chat") {
|
|
|
2568
2937
|
async metadata(id) {
|
|
2569
2938
|
const data = await call(["im", "+messages-mget", "--as", "bot", "--message-ids", id]);
|
|
2570
2939
|
const message = Array.isArray(data?.messages) ? data.messages[0] : void 0;
|
|
2571
|
-
return isRecord(message) ? {
|
|
2940
|
+
return isRecord(message) ? {
|
|
2941
|
+
threadId: typeof message.thread_id === "string" && message.thread_id || null,
|
|
2942
|
+
replyTo: typeof message.reply_to === "string" && message.reply_to || typeof message.root_id === "string" && message.root_id || null
|
|
2943
|
+
} : null;
|
|
2572
2944
|
},
|
|
2573
2945
|
async threadMessages(id) {
|
|
2574
2946
|
const data = await call(["im", "+threads-messages-list", "--as", "bot", "--thread", id]);
|
|
2575
2947
|
return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
|
|
2576
2948
|
},
|
|
2577
2949
|
async downloadImage(messageId, image, index) {
|
|
2578
|
-
const directory =
|
|
2579
|
-
const cleanup = () =>
|
|
2950
|
+
const directory = fs7.mkdtempSync(path8.join(os3.tmpdir(), "pie-im-forward-"));
|
|
2951
|
+
const cleanup = () => fs7.rmSync(directory, { recursive: true, force: true });
|
|
2580
2952
|
try {
|
|
2581
2953
|
const name = `image-${index + 1}.png`;
|
|
2582
2954
|
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 });
|
|
2583
2955
|
if (result.error || !parseLarkCliEnvelope(result.stdout).ok) throw new Error("Image download failed");
|
|
2584
|
-
let target =
|
|
2585
|
-
if (
|
|
2956
|
+
let target = path8.join(directory, name);
|
|
2957
|
+
if (fs7.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
|
|
2586
2958
|
const detected = readImageFormat(target);
|
|
2587
2959
|
if (detected.ext === ".bin") throw new Error("Unsupported image format");
|
|
2588
2960
|
if (detected.ext !== ".png") {
|
|
2589
|
-
const corrected =
|
|
2590
|
-
|
|
2961
|
+
const corrected = path8.join(directory, `image-${index + 1}${detected.ext}`);
|
|
2962
|
+
fs7.renameSync(target, corrected);
|
|
2591
2963
|
target = corrected;
|
|
2592
2964
|
}
|
|
2593
2965
|
return { file: { path: target, displayName: `feishu-image-${index + 1}${detected.ext}` }, cleanup };
|
|
@@ -2679,6 +3051,13 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
2679
3051
|
const interactive = caps.interactiveUI;
|
|
2680
3052
|
const dir = resolveConfigDir();
|
|
2681
3053
|
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;
|
|
2682
3061
|
let session = null;
|
|
2683
3062
|
let setupAbort;
|
|
2684
3063
|
let setupFlight;
|
|
@@ -2711,6 +3090,11 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
2711
3090
|
}
|
|
2712
3091
|
return live.config.enabled;
|
|
2713
3092
|
}
|
|
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
|
+
};
|
|
2714
3098
|
function activate(config) {
|
|
2715
3099
|
if (disposed) return;
|
|
2716
3100
|
const provider = providers.find((item) => item.id === config.provider);
|
|
@@ -2734,6 +3118,8 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
2734
3118
|
}
|
|
2735
3119
|
activeConfig = config;
|
|
2736
3120
|
warnedMismatch = false;
|
|
3121
|
+
relayConnection = connection;
|
|
3122
|
+
activeConfigTargetId = settings.targetId;
|
|
2737
3123
|
const bridge = Object.create(ctx);
|
|
2738
3124
|
bridge.on = (name, handler) => {
|
|
2739
3125
|
handlers.set(name, handler);
|
|
@@ -2751,11 +3137,16 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
2751
3137
|
return () => {
|
|
2752
3138
|
};
|
|
2753
3139
|
};
|
|
2754
|
-
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 } : {}, ...caps.unattended ? { unattended: true } : {} }, connection, () => liveEnabled(config), (next) => {
|
|
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 } : {}, ...caps.unattended ? { unattended: true } : {}, ...config.outboundMode ? { outboundMode: config.outboundMode } : {} }, connection, () => liveEnabled(config), (next) => {
|
|
2755
3141
|
const latest = readLiveConfig(ctx.cwd, dir);
|
|
2756
3142
|
if (latest.problems.length || !latest.config || configurationIdentity(latest.config) !== configurationIdentity(config)) throw new Error("Configuration changed; setup required");
|
|
2757
3143
|
writeConfig(ctx.cwd, dir, { enabled: next });
|
|
2758
|
-
});
|
|
3144
|
+
}, liveOutboundMode);
|
|
3145
|
+
relayCurrentSession = () => session;
|
|
3146
|
+
const seam = bridge.__imRelaySeam;
|
|
3147
|
+
relayRegisterRoute = seam?.registerRoute;
|
|
3148
|
+
relayClaimThread = seam?.claimThread;
|
|
3149
|
+
relayAnchors = seam?.anchors;
|
|
2759
3150
|
if (session) handlers.get("session:changed")?.({ type: "session:changed", sessionId: session });
|
|
2760
3151
|
ctx.__forceInboundRetriesForTest = bridge.__forceInboundRetriesForTest;
|
|
2761
3152
|
suspendEventConsumer = bridge.suspendEventConsumer?.bind(bridge);
|
|
@@ -2770,6 +3161,12 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
2770
3161
|
status = void 0;
|
|
2771
3162
|
activeConfig = void 0;
|
|
2772
3163
|
suspendEventConsumer = void 0;
|
|
3164
|
+
relayConnection = void 0;
|
|
3165
|
+
activeConfigTargetId = void 0;
|
|
3166
|
+
relayRegisterRoute = void 0;
|
|
3167
|
+
relayClaimThread = void 0;
|
|
3168
|
+
relayAnchors = void 0;
|
|
3169
|
+
relayCurrentSession = void 0;
|
|
2773
3170
|
const cleanup = runtimeCleanup;
|
|
2774
3171
|
runtimeCleanup = void 0;
|
|
2775
3172
|
ctx.ui.setStatus?.("im-forward", void 0);
|
|
@@ -2904,6 +3301,45 @@ This does not remove the app credentials lark-cli itself stores; re-running setu
|
|
|
2904
3301
|
else if (choice === "Clear configuration\u2026") await clearConfiguration(commandCtx);
|
|
2905
3302
|
} });
|
|
2906
3303
|
}
|
|
3304
|
+
ctx.registerTool?.({
|
|
3305
|
+
name: "im_relay",
|
|
3306
|
+
label: "IM relay",
|
|
3307
|
+
description: "Send ONE explicit message to the user's IM chat on behalf of this session (multi-agent IM design). 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 follow the host's outbound mode automatically. Returns the sent message id; the user replying to it opens a thread routed to THIS session.",
|
|
3308
|
+
parameters: Type.Object({
|
|
3309
|
+
text: Type.String({ description: "Message body (markdown)", maxLength: 24e3 }),
|
|
3310
|
+
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)." }))
|
|
3311
|
+
}),
|
|
3312
|
+
risk: { riskClass: "external_side_effect", permissionScope: "host", availableInPlanMode: false, requiresPermission: true, externalSideEffect: true, allowedForSubagentByDefault: false, concurrencySafe: false },
|
|
3313
|
+
execute: async (args) => {
|
|
3314
|
+
if (disposed || !activeConfig) return { content: [{ type: "text", text: "im_relay unavailable: IM forwarding is not configured/active here." }], isError: true };
|
|
3315
|
+
const liveConfig = readLiveConfig(ctx.cwd, dir);
|
|
3316
|
+
if (liveConfig.problems.length || !liveConfig.config) return { content: [{ type: "text", text: "im_relay unavailable: IM configuration is missing or unreadable." }], isError: true };
|
|
3317
|
+
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
|
+
if (configurationIdentity(liveConfig.config) !== configurationIdentity(activeConfig)) return { content: [{ type: "text", text: "im_relay refused: the IM configuration changed; run setup first." }], isError: true };
|
|
3321
|
+
const connection = relayConnection;
|
|
3322
|
+
if (!connection) return { content: [{ type: "text", text: "im_relay unavailable: no active provider connection." }], isError: true };
|
|
3323
|
+
if (args.replyTo !== void 0 && !relayAnchorOwned(args.replyTo)) {
|
|
3324
|
+
return { content: [{ type: "text", text: "im_relay refused: replyTo is not a message this host produced in the bound chat (unknown or foreign anchor)." }], isError: true };
|
|
3325
|
+
}
|
|
3326
|
+
try {
|
|
3327
|
+
const key = `pie-im-relay-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
3328
|
+
const sendSessionId = relayCurrentSession?.() ?? void 0;
|
|
3329
|
+
const sent = await connection.send(activeConfigTargetId, args.text, key, args.replyTo);
|
|
3330
|
+
if (!sent) return { content: [{ type: "text", text: "im_relay: the provider send failed." }], isError: true };
|
|
3331
|
+
const claim = relayClaimThread?.(sent, sendSessionId);
|
|
3332
|
+
if (claim && !claim.claimed && claim.reason === "no thread") {
|
|
3333
|
+
relayRegisterRoute?.(sent, sendSessionId);
|
|
3334
|
+
} else if (claim && !claim.claimed) {
|
|
3335
|
+
return { content: [{ type: "text", text: `Relayed as ${sent.messageId}, but the thread was NOT claimed: ${claim.reason}. Bare speech in that thread still routes to its existing owner \u2014 do not treat this thread as yours.` }], isError: true };
|
|
3336
|
+
}
|
|
3337
|
+
return { content: [{ type: "text", text: `Relayed as ${sent.messageId}${sent.threadId ? ` (thread ${sent.threadId})` : ""}. The user's reply there routes back to this session.` }] };
|
|
3338
|
+
} catch (error) {
|
|
3339
|
+
return { content: [{ type: "text", text: `im_relay failed: ${error instanceof Error ? error.message : String(error)}` }], isError: true };
|
|
3340
|
+
}
|
|
3341
|
+
}
|
|
3342
|
+
});
|
|
2907
3343
|
ctx.registerCleanup?.(async () => {
|
|
2908
3344
|
disposed = true;
|
|
2909
3345
|
setupAbort?.abort();
|