@cydm/pie 4.0.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.
@@ -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 path7 = candidate.trim();
345
- if (!path7 || path7.startsWith("/") || path7.startsWith("~") || /^[a-z]+:/i.test(path7) || path7.includes("://")) continue;
346
- const clean = path7.replace(/^\.\//, "").split("#")[0].split("?")[0];
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
- 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: [] };
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,17 +561,399 @@ 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 fs2 from "node:fs";
564
+ import * as fs4 from "node:fs";
559
565
  import { basename } from "node:path";
566
+
567
+ // builtin/extensions/im-forward/address-book.ts
568
+ import * as fs2 from "node:fs";
569
+ import * as os2 from "node:os";
570
+ import * as path2 from "node:path";
571
+ var MAX_ADDRESS_HEAD = 64;
572
+ function addressBookRoot() {
573
+ const raw = process.env.PIE_IPC_CONFIG_DIR;
574
+ if (raw && raw.trim()) {
575
+ const value = raw.trim();
576
+ const expanded = value === "~" ? os2.homedir() : value.startsWith("~/") ? path2.join(os2.homedir(), value.slice(2)) : value;
577
+ return path2.resolve(expanded);
578
+ }
579
+ return path2.resolve(resolveConfigDir());
580
+ }
581
+ function pidAlive(pid) {
582
+ if (!Number.isInteger(pid) || pid <= 0) return true;
583
+ try {
584
+ process.kill(pid, 0);
585
+ return true;
586
+ } catch (error) {
587
+ return error.code === "EPERM";
588
+ }
589
+ }
590
+ function scanAddressBook() {
591
+ const names = /* @__PURE__ */ new Map();
592
+ let complete = true;
593
+ let selfPublished;
594
+ let dirExists = false;
595
+ const dir = path2.join(addressBookRoot(), "run", "ipc");
596
+ let entries;
597
+ try {
598
+ entries = fs2.readdirSync(dir);
599
+ dirExists = true;
600
+ } catch (error) {
601
+ if (error.code === "ENOENT") return { names, complete: true, dirExists: false };
602
+ return { names, complete: false, dirExists: true };
603
+ }
604
+ for (const [index, file] of entries.entries()) {
605
+ if (!file.endsWith(".json")) continue;
606
+ try {
607
+ const status = JSON.parse(fs2.readFileSync(path2.join(dir, file), "utf8"));
608
+ dirExists = true;
609
+ const name = typeof status.sessionName === "string" ? status.sessionName.trim() : "";
610
+ const pid = typeof status.pid === "number" ? status.pid : void 0;
611
+ if (!name) continue;
612
+ if (pid === process.pid) {
613
+ selfPublished = name;
614
+ continue;
615
+ }
616
+ if (pid !== void 0 && !pidAlive(pid)) continue;
617
+ const owners = names.get(name) ?? /* @__PURE__ */ new Set();
618
+ owners.add(pid ?? -(index + 1));
619
+ names.set(name, owners);
620
+ } catch {
621
+ complete = false;
622
+ }
623
+ }
624
+ return { names, selfPublished, complete, dirExists };
625
+ }
626
+ var SEPARATORS = [":", "\uFF1A"];
627
+ function matchAddressName(text, candidates) {
628
+ const trimmed = text.trimStart();
629
+ let best;
630
+ for (const name of candidates) {
631
+ const value = name?.trim();
632
+ if (!value) continue;
633
+ if (!SEPARATORS.some((sep) => trimmed.startsWith(`${value}${sep}`))) continue;
634
+ if (!best || value.length > best.length) best = value;
635
+ }
636
+ return best;
637
+ }
638
+ function resolveAddress(text, ownLiveName, book) {
639
+ if (!/[::]/.test(text)) return { kind: "none" };
640
+ const resolvedBook = book ?? scanAddressBook();
641
+ const candidates = new Set(resolvedBook.names.keys());
642
+ if (resolvedBook.selfPublished) candidates.add(resolvedBook.selfPublished);
643
+ const live = ownLiveName?.trim();
644
+ if (live) candidates.add(live);
645
+ const name = matchAddressName(text, candidates);
646
+ if (!name) {
647
+ if (!resolvedBook.complete) {
648
+ return { kind: "ambiguous", name: text.trim().slice(0, MAX_ADDRESS_HEAD), reason: "address book unreadable" };
649
+ }
650
+ return { kind: "none" };
651
+ }
652
+ const body = text.trimStart().slice(name.length + 1).trim();
653
+ const foreignOwners = resolvedBook.names.get(name);
654
+ if (foreignOwners && foreignOwners.size > 0) {
655
+ if (resolvedBook.selfPublished === name || live === name) return { kind: "ambiguous", name, reason: "duplicate live session name" };
656
+ return { kind: "other", name };
657
+ }
658
+ if (!resolvedBook.complete) return { kind: "ambiguous", name, reason: "address book unreadable" };
659
+ const acceptName = resolvedBook.selfPublished ?? (resolvedBook.dirExists ? void 0 : live);
660
+ if (!acceptName) return { kind: "ambiguous", name, reason: "own advertisement not published" };
661
+ if (name === acceptName) return { kind: "self", body };
662
+ return { kind: "ambiguous", name, reason: "unpublished address" };
663
+ }
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
+
948
+ // builtin/extensions/im-forward/runtime.ts
560
949
  var ROUTE_TTL_MS = 24 * 60 * 60 * 1e3;
561
950
  var MAX_ROUTES = 500;
562
951
  var MAX_SEEN_EVENTS = 1e3;
563
- var REPLY_CHAIN_MAX_DEPTH = 5;
564
952
  var RESTART_BACKOFF_MIN_MS = 5e3;
565
953
  var RESTART_BACKOFF_MAX_MS = 6e4;
566
954
  var SEND_FAILURE_NOTIFY_THROTTLE_MS = 5 * 60 * 1e3;
567
955
  var CHUNK_RETRY_DELAY_MS = 2e3;
568
- var delay = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
956
+ var delay = (ms) => new Promise((resolve4) => setTimeout(resolve4, ms));
569
957
  var MAX_INBOUND_RETRIES = 3;
570
958
  var DEFAULT_INBOUND_RETRY_BACKOFF_MS = 5e3;
571
959
  var MAX_PENDING_IM_INPUTS = 50;
@@ -596,9 +984,20 @@ function hashText(input) {
596
984
  }
597
985
  return Math.abs(hash).toString(36);
598
986
  }
599
- function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
987
+ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled, liveOutboundMode = () => cfg.outboundMode ?? (cfg.unattended === true ? "gateway" : "mirror")) {
600
988
  const IM_INPUT_PREFIX = connection.sourcePrefix;
601
989
  const key = (id) => JSON.stringify([cfg.provider, id]);
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
+ };
602
1001
  const scopes = /* @__PURE__ */ new Set();
603
1002
  let forwardingEnabled = cfg.enabled === true;
604
1003
  let configurationFailed = false;
@@ -611,13 +1010,21 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
611
1010
  forwardingEnabled = live;
612
1011
  updateFooterTag();
613
1012
  }
1013
+ const nextMode = liveOutboundMode();
1014
+ if (nextMode !== outboundMode) {
1015
+ setOutboundMode(nextMode);
1016
+ updateFooterTag();
1017
+ } else {
1018
+ setOutboundMode(nextMode);
1019
+ }
614
1020
  return forwardingEnabled;
615
1021
  }
616
1022
  const STATUS_KEY = "im-forward";
617
1023
  function updateFooterTag() {
1024
+ const modeTag = outboundMode === "gateway" ? "" : outboundMode === "mirror" ? "\xB7m" : "\xB7s";
618
1025
  ctx.ui.setStatus?.(
619
1026
  STATUS_KEY,
620
- configurationFailed ? "[IM!]" : forwardingEnabled ? consumerLastExit ? "[IM!]" : consumerReady ? "[IM]" : "[IM\u2026]" : void 0
1027
+ configurationFailed ? "[IM!]" : forwardingEnabled ? consumerLastExit ? "[IM!]" : consumerReady ? `[IM${modeTag}]` : "[IM\u2026]" : void 0
621
1028
  );
622
1029
  }
623
1030
  function writeEnabledToConfig(next) {
@@ -657,9 +1064,9 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
657
1064
  let currentSessionId = null;
658
1065
  const pendingInputs = [];
659
1066
  const replyAnchor = /* @__PURE__ */ new Map();
1067
+ const sentAnchors = /* @__PURE__ */ new Set();
660
1068
  const routes = /* @__PURE__ */ new Map();
661
1069
  const threadRoutes = /* @__PURE__ */ new Map();
662
- let hasForwarded = false;
663
1070
  const seenEventIds = /* @__PURE__ */ new Map();
664
1071
  const retryTimers = /* @__PURE__ */ new Map();
665
1072
  let forwardCounter = 0;
@@ -744,7 +1151,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
744
1151
  return {
745
1152
  caption: pending.caption || `${IM_INPUT_PREFIX} images`,
746
1153
  replyTo: pending.messageId || void 0,
747
- threadId: pending.threadId
1154
+ threadId: pending.threadId,
1155
+ origin: pending.origin
748
1156
  };
749
1157
  }
750
1158
  }
@@ -769,7 +1177,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
769
1177
  caption: text,
770
1178
  messageId: "",
771
1179
  threadId: null,
772
- at: Date.now()
1180
+ at: Date.now(),
1181
+ origin: "terminal"
773
1182
  });
774
1183
  pruneState();
775
1184
  }
@@ -786,6 +1195,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
786
1195
  if (!sessionId) return;
787
1196
  const sequence = ++forwardCounter;
788
1197
  const attribution = resolveOutboundAttribution(sessionId);
1198
+ if (!maySpeak(attribution?.origin === "im")) return;
789
1199
  void forwardMessage(
790
1200
  text,
791
1201
  sessionId,
@@ -801,6 +1211,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
801
1211
  const reason = failureReason(event.message ?? {});
802
1212
  const sequence = ++forwardCounter;
803
1213
  const attribution = resolveOutboundAttribution(sessionId);
1214
+ if (!maySpeak(attribution?.origin === "im")) return;
804
1215
  void forwardMessage(
805
1216
  `\u26A0\uFE0F \u4EFB\u52A1\u5931\u8D25\uFF1A${reason}`,
806
1217
  sessionId,
@@ -815,6 +1226,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
815
1226
  if (!sessionId) return;
816
1227
  const sequence = ++forwardCounter;
817
1228
  const attribution = resolveOutboundAttribution(sessionId);
1229
+ if (!maySpeak(attribution?.origin === "im")) return;
818
1230
  void forwardMessage(
819
1231
  `\u26D4\uFE0F \u4EFB\u52A1\u5DF2\u53D6\u6D88\uFF1A${event.reason}`,
820
1232
  sessionId,
@@ -825,7 +1237,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
825
1237
  });
826
1238
  async function forwardMessage(text, sessionId, sequence, userInput, replyTo) {
827
1239
  pruneState();
828
- const sessionName = ctx.getSessionName?.();
1240
+ const sessionName = ctx.getSessionDisplayName?.() ?? ctx.getSessionName?.();
829
1241
  const composed = composeForwardBody(
830
1242
  sessionId,
831
1243
  sessionName,
@@ -837,6 +1249,10 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
837
1249
  const baseKey = `pie-im-forward-${cfg.provider}-${incarnation}-${sessionId}-${sequence}-${hashText(composed)}`;
838
1250
  let anchor = replyTo ?? replyAnchor.get(sessionId)?.messageId;
839
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
+ }
840
1256
  const key2 = chunkKey(baseKey, index);
841
1257
  return providerCall(
842
1258
  "send",
@@ -870,35 +1286,39 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
870
1286
  notifySendFailure(
871
1287
  `${cfg.provider} send failed (part ${index + 1}/${chunks.length})`
872
1288
  );
873
- void providerCall(
874
- "send notice",
875
- () => connection.send(
876
- cfg.targetId,
877
- `\u2026(\u7B2C ${index}/${chunks.length} \u6BB5\u4E4B\u540E\u7684\u5206\u6BB5\u53D1\u9001\u5931\u8D25\uFF0C\u5B8C\u6574\u5185\u5BB9\u89C1\u7EC8\u7AEF)`,
878
- chunkKey(baseKey, index, "fail"),
879
- anchor
880
- )
881
- );
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
+ }
882
1302
  return;
883
1303
  }
884
1304
  registerRoute(next, sessionId);
885
1305
  }
886
- if (connection.sendFile && !terminated && isForwardingEnabled()) {
1306
+ if (connection.sendFile && !terminated && isForwardingEnabled() && outboundMode !== "silent") {
887
1307
  const files = collectFileReferences(
888
1308
  text,
889
1309
  ctx.cwd,
890
- (path7) => {
1310
+ (path9) => {
891
1311
  try {
892
- const stat = fs2.statSync(path7);
1312
+ const stat = fs4.statSync(path9);
893
1313
  return { isFile: stat.isFile(), size: stat.size };
894
1314
  } catch {
895
1315
  return null;
896
1316
  }
897
1317
  },
898
1318
  {
899
- canonicalize: (path7) => {
1319
+ canonicalize: (path9) => {
900
1320
  try {
901
- return fs2.realpathSync(path7);
1321
+ return fs4.realpathSync(path9);
902
1322
  } catch {
903
1323
  return null;
904
1324
  }
@@ -907,7 +1327,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
907
1327
  );
908
1328
  const failedFiles = [];
909
1329
  for (const [index, file] of files.entries()) {
910
- if (terminated || !isForwardingEnabled()) return;
1330
+ if (terminated || !isForwardingEnabled() || outboundMode === "silent") return;
911
1331
  const attachment = await providerCall(
912
1332
  "send file",
913
1333
  () => connection.sendFile(
@@ -925,7 +1345,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
925
1345
  failedFiles.push(basename(file));
926
1346
  }
927
1347
  }
928
- if (failedFiles.length > 0 && !terminated && isForwardingEnabled()) {
1348
+ if (failedFiles.length > 0 && !terminated && isForwardingEnabled() && outboundMode !== "silent") {
929
1349
  const names = failedFiles.slice(0, 5).map((name) => name.replace(/[\r\n]/g, " ").slice(0, 80)).join("\u3001");
930
1350
  const extra = failedFiles.length > 5 ? `\uFF08\u53E6 ${failedFiles.length - 5} \u4E2A\uFF09` : "";
931
1351
  await providerCall(
@@ -940,7 +1360,34 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
940
1360
  }
941
1361
  }
942
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
+ };
943
1389
  function registerRoute(sent, sessionId) {
1390
+ sentAnchors.add(sent.messageId);
944
1391
  const route = {
945
1392
  messageId: sent.messageId,
946
1393
  threadId: sent.threadId,
@@ -948,8 +1395,6 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
948
1395
  sentAt: Date.now()
949
1396
  };
950
1397
  routes.set(key(sent.messageId), route);
951
- if (sent.threadId) threadRoutes.set(key(sent.threadId), route);
952
- hasForwarded = true;
953
1398
  ctx.log(`im-forward: forwarded session=${sessionId} as ${sent.messageId}`);
954
1399
  }
955
1400
  ctx.on("session:changed", (event) => {
@@ -992,24 +1437,15 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
992
1437
  }
993
1438
  try {
994
1439
  await handleInboundEventInner(event, retry);
995
- } catch {
996
- ctx.log(`im-forward: ${cfg.provider} inbound handling failed`);
1440
+ } catch (error) {
1441
+ ctx.log(`im-forward: ${cfg.provider} inbound handling failed: ${error instanceof Error ? error.message : String(error)}`);
997
1442
  retry();
998
1443
  } finally {
999
1444
  terminalCleanup();
1000
1445
  }
1001
1446
  }
1002
- function escapeRegExp(text) {
1003
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1004
- }
1005
- function parseSessionAddress(text) {
1006
- const name = ctx.getSessionName?.()?.trim();
1007
- if (!name) return { kind: "absent" };
1008
- const own = new RegExp(`^${escapeRegExp(name)}:[ \\t]+(.+)$`, "s").exec(
1009
- text.trim()
1010
- );
1011
- if (own) return { kind: "addressed", body: own[1] };
1012
- return { kind: "absent" };
1447
+ function resolveInboundAddress(text) {
1448
+ return resolveAddress(text, ctx.getSessionName?.());
1013
1449
  }
1014
1450
  async function handleInboundEventInner(event, retry) {
1015
1451
  const matchesTarget = cfg.targetKind === "user" ? event.sender_id === cfg.targetId && (event.chatType === void 0 || event.chatType === "p2p") : event.chat_id === cfg.targetId;
@@ -1018,13 +1454,25 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1018
1454
  return;
1019
1455
  const messageId = event.message_id;
1020
1456
  if (!messageId) return;
1457
+ const address = resolveInboundAddress(event.text);
1458
+ if (address.kind === "other") {
1459
+ ctx.log(`im-forward: message addressed to "${address.name}" (another live session); ignoring here`);
1460
+ return;
1461
+ }
1462
+ if (address.kind === "ambiguous") {
1463
+ ctx.log(`im-forward: address "${address.name}" is unresolved (${address.reason}); dropping`);
1464
+ return;
1465
+ }
1021
1466
  const releaseInvalidatedEvent = () => {
1022
1467
  if (event.event_id) seenEventIds.delete(key(event.event_id));
1023
1468
  };
1024
1469
  const sessionId = currentSessionId;
1025
1470
  const epoch = inputEpoch;
1471
+ const acceptedSignature = (resolved) => resolved.kind === "self" ? `self:${resolved.body}` : resolved.kind;
1472
+ let acceptedKey = acceptedSignature(address);
1473
+ const textStillOurs = () => acceptedSignature(resolveInboundAddress(event.text)) === acceptedKey;
1026
1474
  const scope = ctx.beginUserInput?.(
1027
- () => !terminated && inputEpoch === epoch && currentSessionId === sessionId && isForwardingEnabled()
1475
+ () => !terminated && inputEpoch === epoch && currentSessionId === sessionId && isForwardingEnabled() && textStillOurs()
1028
1476
  );
1029
1477
  if (!scope) {
1030
1478
  retry();
@@ -1041,8 +1489,13 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1041
1489
  releaseInvalidatedEvent();
1042
1490
  return;
1043
1491
  }
1044
- const address = parseSessionAddress(event.text);
1045
- const resolution = address.kind === "addressed" ? {
1492
+ const pinnedSession = event.event_id ? retrySessionIds.get(key(event.event_id)) : void 0;
1493
+ if (pinnedSession !== void 0 && pinnedSession !== sessionId) {
1494
+ ctx.log(`im-forward: retry crossed a session switch (${pinnedSession} -> ${sessionId}); releasing for redelivery`);
1495
+ releaseInvalidatedEvent();
1496
+ return;
1497
+ }
1498
+ const resolution = address.kind === "self" ? {
1046
1499
  found: {
1047
1500
  messageId: "",
1048
1501
  threadId: meta.threadId ?? null,
@@ -1055,24 +1508,20 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1055
1508
  retry();
1056
1509
  return;
1057
1510
  }
1058
- if (routes.size === 0 && threadRoutes.size === 0 && !hasForwarded) {
1059
- const firstSeenSession = event.event_id ? retrySessionIds.get(key(event.event_id)) : void 0;
1060
- if (firstSeenSession !== void 0 && firstSeenSession !== sessionId) {
1061
- ctx.log(`im-forward: cold-start retry crossed a session switch (${firstSeenSession} -> ${sessionId}); releasing for redelivery`);
1062
- releaseInvalidatedEvent();
1063
- return;
1064
- }
1065
- const bootstrapRoute = {
1511
+ const unanchored = !meta.replyTo && !meta.threadId;
1512
+ const claimsUnanchored = isUnattended && outboundMode === "gateway";
1513
+ if (claimsUnanchored && unanchored) {
1514
+ const residentRoute = {
1066
1515
  messageId: "",
1067
1516
  threadId: meta.threadId ?? null,
1068
1517
  sessionId,
1069
1518
  sentAt: Date.now()
1070
1519
  };
1071
1520
  ctx.log(
1072
- `im-forward: cold-start route bound to session ${sessionId} (first message in target conversation)`
1521
+ `im-forward: unanchored message bound to resident session ${sessionId}`
1073
1522
  );
1074
1523
  await acceptRoutedMessage(
1075
- bootstrapRoute,
1524
+ residentRoute,
1076
1525
  event,
1077
1526
  meta,
1078
1527
  scope,
@@ -1100,8 +1549,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1100
1549
  const releaseInvalidatedEvent = () => {
1101
1550
  if (event.event_id) seenEventIds.delete(key(event.event_id));
1102
1551
  };
1103
- const imageKeys = event.images;
1104
- const caption = address.kind === "addressed" ? address.body : event.text;
1552
+ const imageKeys = event.images ?? [];
1553
+ const caption = address.kind === "self" ? address.body : event.text;
1105
1554
  if (!caption && !imageKeys.length) return;
1106
1555
  const submitText = `${IM_INPUT_PREFIX}
1107
1556
  ${caption || IM_INPUT_FALLBACK_CAPTION}`;
@@ -1109,6 +1558,13 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1109
1558
  const currentAfterSubmit = scope.isCurrent();
1110
1559
  if (!accepted || !currentAfterSubmit) {
1111
1560
  if (!accepted && !currentAfterSubmit) releaseInvalidatedEvent();
1561
+ if (!accepted) {
1562
+ const late = resolveInboundAddress(event.text);
1563
+ if (late.kind === "other" || late.kind === "ambiguous") {
1564
+ ctx.log(`im-forward: cancelled at the submission boundary \u2014 address moved to ${late.kind}; no notice sent`);
1565
+ return;
1566
+ }
1567
+ }
1112
1568
  if (currentAfterSubmit) {
1113
1569
  ctx.ui.notify(
1114
1570
  "im-forward: message was not accepted; no input submitted.",
@@ -1130,7 +1586,8 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1130
1586
  caption,
1131
1587
  messageId,
1132
1588
  threadId: route.threadId,
1133
- at: Date.now()
1589
+ at: Date.now(),
1590
+ origin: "im"
1134
1591
  });
1135
1592
  pruneState();
1136
1593
  ctx.log(
@@ -1230,48 +1687,46 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1230
1687
  );
1231
1688
  }
1232
1689
  async function resolveRouteForInbound(messageId, meta) {
1233
- if (meta.threadId) {
1234
- const byThread = threadRoutes.get(key(meta.threadId));
1235
- if (byThread) return { found: byThread };
1236
- }
1237
1690
  const direct = routes.get(key(messageId));
1238
1691
  if (direct) return { found: direct };
1239
- let chain = { notOurs: true };
1240
1692
  if (meta.replyTo) {
1241
- chain = await resolveRouteForReply(meta.replyTo);
1242
- if ("found" in chain) return chain;
1693
+ const replied = routes.get(key(meta.replyTo));
1694
+ if (replied) return { found: replied };
1695
+ return { notOurs: true };
1696
+ }
1697
+ if (!meta.threadId) return { notOurs: true };
1698
+ const sharedOwner = threadOwner({ provider: cfg.provider, threadId: meta.threadId });
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 };
1243
1706
  }
1244
- if (!meta.threadId) return chain;
1245
- const byRoot = await resolveRouteByThreadRoot(meta.threadId);
1246
- if ("found" in byRoot) return byRoot;
1247
- return isTransient(chain) || isTransient(byRoot) ? { transient: true } : { notOurs: true };
1707
+ if (byThread) return { found: byThread };
1708
+ return await resolveRouteByThreadRoot(meta.threadId, sharedOwner.sessionId);
1248
1709
  }
1249
- async function resolveRouteByThreadRoot(threadId) {
1710
+ async function resolveRouteByThreadRoot(threadId, knownSharedOwner) {
1250
1711
  const messages = await fetchThreadMessages(threadId);
1251
1712
  if (!messages) return { transient: true };
1252
- for (const id of messages) {
1253
- const route = routes.get(key(id));
1254
- if (route) {
1255
- threadRoutes.set(key(threadId), route);
1256
- return { found: route };
1257
- }
1258
- }
1259
- return { notOurs: true };
1260
- }
1261
- async function resolveRouteForReply(startId) {
1262
- let current = startId;
1263
- const visited = /* @__PURE__ */ new Set();
1264
- for (let depth = 0; depth < REPLY_CHAIN_MAX_DEPTH; depth++) {
1265
- const direct = routes.get(key(current));
1266
- if (direct) return { found: direct };
1267
- if (visited.has(current)) return { notOurs: true };
1268
- visited.add(current);
1269
- const parent = await fetchMessageMeta(current);
1270
- if (!parent) return { transient: true };
1271
- if (!parent.replyTo) return { notOurs: true };
1272
- current = parent.replyTo;
1273
- }
1274
- return { notOurs: true };
1713
+ const rootId = messages[0];
1714
+ if (!rootId) return { notOurs: true };
1715
+ const route = routes.get(key(rootId));
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
+ }
1728
+ threadRoutes.set(key(threadId), route);
1729
+ return { found: route };
1275
1730
  }
1276
1731
  let consumer = null;
1277
1732
  let consumerReady = false;
@@ -1450,14 +1905,13 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
1450
1905
  `- routes: ${routes.size} forwarded message(s) routable (${threadRoutes.size} thread(s), ${replyAnchor.size} anchor(s))`,
1451
1906
  `- current session: ${currentSessionId ?? "(none)"}`
1452
1907
  ];
1453
- if (!routes.size && !terminated && consumerReady)
1908
+ if (!terminated && consumerReady)
1454
1909
  lines.push(
1455
- // r18 P2: match the actual behavior — a NEVER-forwarded runtime now
1456
- // bootstraps on the first authorized message in the target
1457
- // conversation (r17); an EVER-forwarded runtime whose routes all
1458
- // expired keeps classic routing (explicit '<session>: text'
1459
- // addressing still works).
1460
- hasForwarded ? "- note: all routes expired \u2014 replies to old forwards are dropped. Send a new local turn, or address explicitly with '<session name>: text'." : "- note: no forwarded message yet \u2014 the first authorized message in the bound conversation will open the session (cold-start)."
1910
+ // USER ROUTING DESIGN (11-08): unanchored messages go to the
1911
+ // resident (this runtime, if unattended); anchored routing is
1912
+ // table-based and explicit addressing always works. Unconditional:
1913
+ // ownership is a capability axis, not route-table state.
1914
+ cfg.unattended ? "- note: unanchored DM/@app messages bind to this resident session; reply/thread messages route to their referenced session." : "- note: interactive host \u2014 only reply/thread-attributed or explicitly addressed messages enter (unanchored messages belong to the resident concierge, if running)."
1461
1915
  );
1462
1916
  if (lastSendError)
1463
1917
  lines.push(
@@ -1522,9 +1976,9 @@ Enable forwarding and start the connection? No test message will be sent. Saving
1522
1976
 
1523
1977
  // builtin/extensions/im-forward/providers/feishu/index.ts
1524
1978
  import { spawn as spawn4 } from "node:child_process";
1525
- import * as fs5 from "node:fs";
1526
- import * as os2 from "node:os";
1527
- import * as path6 from "node:path";
1979
+ import * as fs7 from "node:fs";
1980
+ import * as os3 from "node:os";
1981
+ import * as path8 from "node:path";
1528
1982
 
1529
1983
  // builtin/extensions/im-forward/lark-cli.ts
1530
1984
  import { spawn as spawn2 } from "node:child_process";
@@ -1532,33 +1986,33 @@ import { StringDecoder as StringDecoder2 } from "node:string_decoder";
1532
1986
 
1533
1987
  // builtin/extensions/im-forward/launch.ts
1534
1988
  import { spawn } from "node:child_process";
1535
- import * as fs3 from "node:fs";
1536
- import * as path2 from "node:path";
1989
+ import * as fs5 from "node:fs";
1990
+ import * as path4 from "node:path";
1537
1991
  import { StringDecoder } from "node:string_decoder";
1538
1992
  function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.platform, env = process.env) {
1539
1993
  const windows = platform === "win32";
1540
- const candidates = explicit ? [path2.resolve(cwd, explicit)] : (env.PATH ?? "").split(windows ? ";" : ":").filter(Boolean).flatMap((dir) => (windows ? ["lark-cli.exe", "lark-cli.cmd"] : ["lark-cli"]).map((name) => path2.resolve(cwd, dir, name)));
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)));
1541
1995
  for (const candidate of candidates) {
1542
1996
  try {
1543
- if (!fs3.statSync(candidate).isFile()) continue;
1544
- const ext = path2.extname(candidate).toLowerCase();
1997
+ if (!fs5.statSync(candidate).isFile()) continue;
1998
+ const ext = path4.extname(candidate).toLowerCase();
1545
1999
  if (ext === ".js" || ext === ".mjs") return { command: process.execPath, prefix: [candidate] };
1546
2000
  if (windows && ext === ".cmd") {
1547
- const dir = path2.dirname(candidate);
1548
- for (const root of [path2.join(dir, "node_modules", "@larksuite", "cli"), path2.resolve(dir, "..", "@larksuite", "cli")]) {
2001
+ const dir = path4.dirname(candidate);
2002
+ for (const root of [path4.join(dir, "node_modules", "@larksuite", "cli"), path4.resolve(dir, "..", "@larksuite", "cli")]) {
1549
2003
  try {
1550
- const pkg = JSON.parse(fs3.readFileSync(path2.join(root, "package.json"), "utf8"));
2004
+ const pkg = JSON.parse(fs5.readFileSync(path4.join(root, "package.json"), "utf8"));
1551
2005
  const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["lark-cli"];
1552
2006
  if (pkg.name !== "@larksuite/cli" || typeof bin !== "string" || bin.replace(/^\.\//, "") !== "scripts/run.js") continue;
1553
- const entry = path2.join(root, "scripts", "run.js");
1554
- if (fs3.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
2007
+ const entry = path4.join(root, "scripts", "run.js");
2008
+ if (fs5.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
1555
2009
  } catch {
1556
2010
  }
1557
2011
  }
1558
2012
  continue;
1559
2013
  }
1560
2014
  if (windows && ext !== ".exe") continue;
1561
- fs3.accessSync(candidate, fs3.constants.X_OK);
2015
+ fs5.accessSync(candidate, fs5.constants.X_OK);
1562
2016
  return { command: candidate, prefix: [] };
1563
2017
  } catch {
1564
2018
  }
@@ -1590,7 +2044,7 @@ function stopOwnedTreeInner(child, signal) {
1590
2044
  }
1591
2045
  }
1592
2046
  }
1593
- return new Promise((resolve3) => {
2047
+ return new Promise((resolve4) => {
1594
2048
  let done = false;
1595
2049
  let killer;
1596
2050
  const finish = (ok) => {
@@ -1603,7 +2057,7 @@ function stopOwnedTreeInner(child, signal) {
1603
2057
  } catch {
1604
2058
  }
1605
2059
  }
1606
- resolve3(ok);
2060
+ resolve4(ok);
1607
2061
  };
1608
2062
  const timer = setTimeout(() => {
1609
2063
  try {
@@ -1614,7 +2068,7 @@ function stopOwnedTreeInner(child, signal) {
1614
2068
  }, 1500);
1615
2069
  try {
1616
2070
  const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
1617
- killer = spawn(path2.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { shell: false, windowsHide: true, stdio: "ignore" });
2071
+ killer = spawn(path4.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { shell: false, windowsHide: true, stdio: "ignore" });
1618
2072
  killer.on("error", () => finish(false));
1619
2073
  killer.on("exit", (code) => finish(code === 0));
1620
2074
  } catch {
@@ -1658,14 +2112,14 @@ function shutdownConsumer(child) {
1658
2112
  }
1659
2113
  async function shutdownConsumerInner(child) {
1660
2114
  let closed = false;
1661
- const close = new Promise((resolve3) => child.once("close", () => {
2115
+ const close = new Promise((resolve4) => child.once("close", () => {
1662
2116
  closed = true;
1663
- resolve3();
2117
+ resolve4();
1664
2118
  }));
1665
2119
  const wait = async (ms) => {
1666
2120
  let timer;
1667
- await Promise.race([close, new Promise((resolve3) => {
1668
- timer = setTimeout(resolve3, ms);
2121
+ await Promise.race([close, new Promise((resolve4) => {
2122
+ timer = setTimeout(resolve4, ms);
1669
2123
  })]);
1670
2124
  clearTimeout(timer);
1671
2125
  };
@@ -1689,9 +2143,9 @@ async function shutdownConsumerInner(child) {
1689
2143
 
1690
2144
  // builtin/extensions/im-forward/lark-cli.ts
1691
2145
  async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
1692
- return new Promise((resolve3) => {
2146
+ return new Promise((resolve4) => {
1693
2147
  if (options.signal?.aborted) {
1694
- resolve3({ stdout: "", error: "cancelled" });
2148
+ resolve4({ stdout: "", error: "cancelled" });
1695
2149
  return;
1696
2150
  }
1697
2151
  let child;
@@ -1706,7 +2160,7 @@ async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
1706
2160
  ...cwd ? { cwd } : {}
1707
2161
  });
1708
2162
  } catch {
1709
- resolve3({ stdout: "", error: "spawn failed" });
2163
+ resolve4({ stdout: "", error: "spawn failed" });
1710
2164
  return;
1711
2165
  }
1712
2166
  let stdout = "";
@@ -1724,7 +2178,7 @@ async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
1724
2178
  clearTimeout(killTimer);
1725
2179
  clearTimeout(closeTimer);
1726
2180
  options.signal?.removeEventListener("abort", abort);
1727
- resolve3(result);
2181
+ resolve4(result);
1728
2182
  };
1729
2183
  const terminatedResult = () => ({ stdout: termination?.startsWith("timeout") ? stdout : "", error: termination });
1730
2184
  const stop = (signal) => {
@@ -1859,17 +2313,17 @@ function extractImageKey(content) {
1859
2313
  }
1860
2314
 
1861
2315
  // builtin/extensions/im-forward/providers/feishu/setup.ts
1862
- import * as fs4 from "node:fs";
1863
- import * as path5 from "node:path";
2316
+ import * as fs6 from "node:fs";
2317
+ import * as path7 from "node:path";
1864
2318
 
1865
2319
  // builtin/extensions/im-forward/browser.ts
1866
2320
  import { spawn as spawn3 } from "node:child_process";
1867
- import path3 from "node:path";
2321
+ import path5 from "node:path";
1868
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 }";
1869
2323
  function browserLaunch(platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
1870
2324
  if (platform === "win32") {
1871
2325
  if (!/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return;
1872
- return { command: path3.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(browserScript, "utf16le").toString("base64")], stdin: true };
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 };
1873
2327
  }
1874
2328
  if (platform === "darwin") return { command: "/usr/bin/open", args: ["--"], stdin: false };
1875
2329
  if (platform === "linux") return { command: "/usr/bin/xdg-open", args: [], stdin: false };
@@ -1878,7 +2332,7 @@ async function openBrowser(url, signal, seam = {}) {
1878
2332
  if (signal.aborted || !/^https:\/\/[^\s\x00-\x1f\x7f]+$/.test(url)) return "failed";
1879
2333
  const spec = browserLaunch(seam.platform);
1880
2334
  if (!spec) return "failed";
1881
- return new Promise((resolve3) => {
2335
+ return new Promise((resolve4) => {
1882
2336
  let child;
1883
2337
  let settled = false;
1884
2338
  let stopping = false;
@@ -1893,7 +2347,7 @@ async function openBrowser(url, signal, seam = {}) {
1893
2347
  child?.stdin?.destroy();
1894
2348
  child?.stdout?.destroy();
1895
2349
  child?.stderr?.destroy();
1896
- resolve3(result);
2350
+ resolve4(result);
1897
2351
  };
1898
2352
  const stop = () => {
1899
2353
  if (settled || stopping) return;
@@ -1928,24 +2382,24 @@ async function openBrowser(url, signal, seam = {}) {
1928
2382
  }
1929
2383
 
1930
2384
  // builtin/extensions/im-forward/existing-app-terminal.ts
1931
- import path4 from "node:path";
2385
+ import path6 from "node:path";
1932
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 }";
1933
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 }";
1934
2388
  function existingAppTerminal(binary, cwd, platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
1935
2389
  if (platform !== "win32" || !/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return null;
1936
2390
  const payload = Buffer.from(JSON.stringify({ command: binary.command, args: [...binary.prefix, "config", "init", "--brand", "feishu"], cwd }), "utf8").toString("base64");
1937
2391
  const script = existingAppOuterTemplate.replace("__PAYLOAD__", payload);
1938
- return { command: path4.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), prefix: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")] };
2392
+ return { command: path6.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), prefix: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")] };
1939
2393
  }
1940
2394
 
1941
2395
  // builtin/extensions/im-forward/providers/feishu/setup.ts
1942
2396
  function findNpmCli() {
1943
- const dirs = [path5.dirname(process.execPath), ...(process.env.PATH ?? "").split(path5.delimiter)];
1944
- for (const dir of dirs) for (const root of [path5.join(dir, "node_modules", "npm"), path5.resolve(dir, "..", "lib", "node_modules", "npm")]) {
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")]) {
1945
2399
  try {
1946
- const pkg = JSON.parse(fs4.readFileSync(path5.join(root, "package.json"), "utf8"));
1947
- const entry = path5.join(root, "bin", "npm-cli.js");
1948
- if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" && fs4.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
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] };
1949
2403
  } catch {
1950
2404
  }
1951
2405
  }
@@ -2483,26 +2937,29 @@ function connect(binary, profile, targetKind = "chat") {
2483
2937
  async metadata(id) {
2484
2938
  const data = await call(["im", "+messages-mget", "--as", "bot", "--message-ids", id]);
2485
2939
  const message = Array.isArray(data?.messages) ? data.messages[0] : void 0;
2486
- return isRecord(message) ? { threadId: typeof message.thread_id === "string" && message.thread_id || null, replyTo: typeof message.reply_to === "string" && message.reply_to || null } : null;
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;
2487
2944
  },
2488
2945
  async threadMessages(id) {
2489
2946
  const data = await call(["im", "+threads-messages-list", "--as", "bot", "--thread", id]);
2490
2947
  return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
2491
2948
  },
2492
2949
  async downloadImage(messageId, image, index) {
2493
- const directory = fs5.mkdtempSync(path6.join(os2.tmpdir(), "pie-im-forward-"));
2494
- const cleanup = () => fs5.rmSync(directory, { recursive: true, force: true });
2950
+ const directory = fs7.mkdtempSync(path8.join(os3.tmpdir(), "pie-im-forward-"));
2951
+ const cleanup = () => fs7.rmSync(directory, { recursive: true, force: true });
2495
2952
  try {
2496
2953
  const name = `image-${index + 1}.png`;
2497
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 });
2498
2955
  if (result.error || !parseLarkCliEnvelope(result.stdout).ok) throw new Error("Image download failed");
2499
- let target = path6.join(directory, name);
2500
- if (fs5.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
2956
+ let target = path8.join(directory, name);
2957
+ if (fs7.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
2501
2958
  const detected = readImageFormat(target);
2502
2959
  if (detected.ext === ".bin") throw new Error("Unsupported image format");
2503
2960
  if (detected.ext !== ".png") {
2504
- const corrected = path6.join(directory, `image-${index + 1}${detected.ext}`);
2505
- fs5.renameSync(target, corrected);
2961
+ const corrected = path8.join(directory, `image-${index + 1}${detected.ext}`);
2962
+ fs7.renameSync(target, corrected);
2506
2963
  target = corrected;
2507
2964
  }
2508
2965
  return { file: { path: target, displayName: `feishu-image-${index + 1}${detected.ext}` }, cleanup };
@@ -2594,6 +3051,13 @@ function initializeImForward(ctx, providers = implementedProviders) {
2594
3051
  const interactive = caps.interactiveUI;
2595
3052
  const dir = resolveConfigDir();
2596
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;
2597
3061
  let session = null;
2598
3062
  let setupAbort;
2599
3063
  let setupFlight;
@@ -2626,6 +3090,11 @@ function initializeImForward(ctx, providers = implementedProviders) {
2626
3090
  }
2627
3091
  return live.config.enabled;
2628
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
+ };
2629
3098
  function activate(config) {
2630
3099
  if (disposed) return;
2631
3100
  const provider = providers.find((item) => item.id === config.provider);
@@ -2649,6 +3118,8 @@ function initializeImForward(ctx, providers = implementedProviders) {
2649
3118
  }
2650
3119
  activeConfig = config;
2651
3120
  warnedMismatch = false;
3121
+ relayConnection = connection;
3122
+ activeConfigTargetId = settings.targetId;
2652
3123
  const bridge = Object.create(ctx);
2653
3124
  bridge.on = (name, handler) => {
2654
3125
  handlers.set(name, handler);
@@ -2666,11 +3137,16 @@ function initializeImForward(ctx, providers = implementedProviders) {
2666
3137
  return () => {
2667
3138
  };
2668
3139
  };
2669
- 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 } : {} }, 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) => {
2670
3141
  const latest = readLiveConfig(ctx.cwd, dir);
2671
3142
  if (latest.problems.length || !latest.config || configurationIdentity(latest.config) !== configurationIdentity(config)) throw new Error("Configuration changed; setup required");
2672
3143
  writeConfig(ctx.cwd, dir, { enabled: next });
2673
- });
3144
+ }, liveOutboundMode);
3145
+ relayCurrentSession = () => session;
3146
+ const seam = bridge.__imRelaySeam;
3147
+ relayRegisterRoute = seam?.registerRoute;
3148
+ relayClaimThread = seam?.claimThread;
3149
+ relayAnchors = seam?.anchors;
2674
3150
  if (session) handlers.get("session:changed")?.({ type: "session:changed", sessionId: session });
2675
3151
  ctx.__forceInboundRetriesForTest = bridge.__forceInboundRetriesForTest;
2676
3152
  suspendEventConsumer = bridge.suspendEventConsumer?.bind(bridge);
@@ -2685,6 +3161,12 @@ function initializeImForward(ctx, providers = implementedProviders) {
2685
3161
  status = void 0;
2686
3162
  activeConfig = void 0;
2687
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;
2688
3170
  const cleanup = runtimeCleanup;
2689
3171
  runtimeCleanup = void 0;
2690
3172
  ctx.ui.setStatus?.("im-forward", void 0);
@@ -2819,6 +3301,45 @@ This does not remove the app credentials lark-cli itself stores; re-running setu
2819
3301
  else if (choice === "Clear configuration\u2026") await clearConfiguration(commandCtx);
2820
3302
  } });
2821
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
+ });
2822
3343
  ctx.registerCleanup?.(async () => {
2823
3344
  disposed = true;
2824
3345
  setupAbort?.abort();