aai-lark-bridge 0.2.31 → 0.2.34

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/cli.js CHANGED
@@ -4,7 +4,7 @@ import { Command } from "commander";
4
4
  // package.json
5
5
  var package_default = {
6
6
  name: "aai-lark-bridge",
7
- version: "0.2.31",
7
+ version: "0.2.34",
8
8
  description: "Lark AI Native Bridge - Lark\u57FA\u7840\u8BBE\u65BD\u5C42\u548CCLI\u96C6\u6210",
9
9
  type: "module",
10
10
  main: "./dist/index.js",
@@ -7617,7 +7617,7 @@ async function submitClaudeLogin(cfg, sub, deps = {}) {
7617
7617
  }
7618
7618
 
7619
7619
  // src/bridge/bot/channel.ts
7620
- import { dirname as dirname19, join as join27 } from "path";
7620
+ import { dirname as dirname19, join as join28 } from "path";
7621
7621
 
7622
7622
  // src/bridge/agent/capability.ts
7623
7623
  function claudeCapability(profile2) {
@@ -7874,7 +7874,7 @@ function isDispatchRoot(dir, rootMessageId) {
7874
7874
  }
7875
7875
  function dispatchRoute(dir, m) {
7876
7876
  if (m.threadId) return isDispatchRoot(dir, m.rootId) ? "thread" : void 0;
7877
- return isDispatchMarker(m.content) ? "start" : void 0;
7877
+ return isDispatchMarker(m.content) || isDispatchRoot(dir, m.messageId) ? "start" : void 0;
7878
7878
  }
7879
7879
  var LOCK_WAIT_MS = 2e3;
7880
7880
  var LOCK_STEP_MS = 50;
@@ -12667,6 +12667,19 @@ async function lookupMessageThreadId(channel, messageId) {
12667
12667
  return void 0;
12668
12668
  }
12669
12669
  }
12670
+ async function lookupMessageRoot(channel, messageId) {
12671
+ try {
12672
+ const [item] = await channel.fetchRawMessage(messageId);
12673
+ const raw = item;
12674
+ return { threadId: raw?.thread_id, rootId: raw?.root_id };
12675
+ } catch (err) {
12676
+ log.warn("thread", "root-lookup-failed", {
12677
+ messageId,
12678
+ err: err instanceof Error ? err.message : String(err)
12679
+ });
12680
+ return {};
12681
+ }
12682
+ }
12670
12683
 
12671
12684
  // src/bridge/card/handoff.ts
12672
12685
  import { createHash as createHash4 } from "crypto";
@@ -12734,7 +12747,7 @@ async function handleCardAction(deps) {
12734
12747
  const chatId = deps.evt.chatId;
12735
12748
  const raw = deps.evt.raw;
12736
12749
  const formValue = raw?.action?.form_value;
12737
- const { scope, threadId, mode } = await resolveScope(deps);
12750
+ const { scope, threadId, rootId, mode } = await resolveScope(deps);
12738
12751
  const accessDecision = mode === "p2p" ? canUseDm(deps.controls.profileConfig, deps.controls, operatorId) : canUseGroup(deps.controls.profileConfig, deps.controls, chatId, operatorId);
12739
12752
  if (!accessDecision.ok) {
12740
12753
  log.info("cardAction", "skip-not-allowed-user", {
@@ -12753,7 +12766,7 @@ async function handleCardAction(deps) {
12753
12766
  return;
12754
12767
  }
12755
12768
  log.info("cardAction", "cmd", { cmd, scope });
12756
- const msg = makeFakeMsg(deps.evt, threadId);
12769
+ const msg = makeFakeMsg(deps.evt, threadId, rootId);
12757
12770
  const ctx = {
12758
12771
  channel: deps.channel,
12759
12772
  msg,
@@ -12791,7 +12804,7 @@ async function handleCardAction(deps) {
12791
12804
  }
12792
12805
  if (BRIDGE_CALLBACK_MARKER in payload) {
12793
12806
  if (!verifyBridgeToken(deps, payload, scope, "agent_callback")) return;
12794
- forwardToAgent(deps, payload, formValue, scope, threadId, mode);
12807
+ forwardToAgent(deps, payload, formValue, scope, threadId, mode, rootId);
12795
12808
  return;
12796
12809
  }
12797
12810
  return;
@@ -12821,6 +12834,13 @@ async function resolveScope(deps) {
12821
12834
  const chatId = deps.evt.chatId;
12822
12835
  const mode = await deps.chatModeCache.resolve(deps.channel, chatId);
12823
12836
  if (mode !== "topic") {
12837
+ const bindingsDir = deps.controls.profileConfig.preferences.taskBindings?.dir;
12838
+ if (mode === "p2p" && bindingsDir) {
12839
+ const { threadId: threadId2, rootId } = await lookupMessageRoot(deps.channel, deps.evt.messageId);
12840
+ if (rootId && isDispatchRoot(bindingsDir, rootId)) {
12841
+ return { scope: `${chatId}:${rootId}`, threadId: threadId2, rootId, mode };
12842
+ }
12843
+ }
12824
12844
  return { scope: chatId, threadId: void 0, mode };
12825
12845
  }
12826
12846
  const threadId = await lookupMessageThreadId(deps.channel, deps.evt.messageId);
@@ -12829,7 +12849,7 @@ async function resolveScope(deps) {
12829
12849
  }
12830
12850
  return { scope: `${chatId}:${threadId}`, threadId, mode };
12831
12851
  }
12832
- function forwardToAgent(deps, payload, formValue, scope, threadId, mode) {
12852
+ function forwardToAgent(deps, payload, formValue, scope, threadId, mode, rootId) {
12833
12853
  const {
12834
12854
  [BRIDGE_CALLBACK_MARKER]: _marker,
12835
12855
  bridge_token: _token,
@@ -12845,6 +12865,7 @@ function forwardToAgent(deps, payload, formValue, scope, threadId, mode) {
12845
12865
  chatId: deps.evt.chatId,
12846
12866
  chatType: mode === "p2p" ? "p2p" : "group",
12847
12867
  threadId,
12868
+ ...rootId ? { rootId } : {},
12848
12869
  senderId: deps.evt.operator.openId,
12849
12870
  senderName: deps.evt.operator.name,
12850
12871
  content: `[card-click] ${JSON.stringify(merged)}`,
@@ -12892,12 +12913,13 @@ function composeArgs(sub, payload) {
12892
12913
  const arg = typeof payload.arg === "string" && payload.arg || typeof payload.name === "string" && payload.name || "";
12893
12914
  return arg ? `${sub} ${arg}` : sub;
12894
12915
  }
12895
- function makeFakeMsg(evt, threadId) {
12916
+ function makeFakeMsg(evt, threadId, rootId) {
12896
12917
  return {
12897
12918
  messageId: evt.messageId,
12898
12919
  chatId: evt.chatId,
12899
12920
  chatType: "p2p",
12900
12921
  threadId,
12922
+ ...rootId ? { rootId } : {},
12901
12923
  senderId: evt.operator.openId,
12902
12924
  senderName: evt.operator.name,
12903
12925
  content: "",
@@ -14745,6 +14767,10 @@ var PendingQueue = class {
14745
14767
  });
14746
14768
  return 1;
14747
14769
  }
14770
+ /** 有消息在排队、或正在 flush / 运行(被 block)的 scope:还没占上 ActiveRuns 的也算。 */
14771
+ scopes() {
14772
+ return [.../* @__PURE__ */ new Set([...this.map.keys(), ...this.blocked])];
14773
+ }
14748
14774
  cancel(scope) {
14749
14775
  const entry = this.map.get(scope);
14750
14776
  if (!entry) return [];
@@ -14812,9 +14838,100 @@ function runningWorkers(scopes, chatId) {
14812
14838
  return scopes.filter((s) => s.startsWith(prefix)).length;
14813
14839
  }
14814
14840
 
14815
- // src/bridge/bot/worker-report.ts
14816
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync6 } from "fs";
14841
+ // src/bridge/bot/spawn-inbox.ts
14842
+ import { existsSync as existsSync9, mkdirSync as mkdirSync6, readFileSync as readFileSync5, readdirSync as readdirSync2, rmSync as rmSync3 } from "fs";
14817
14843
  import { join as join26 } from "path";
14844
+ var SPAWN_DIR = "spawn";
14845
+ var SPAWN_POLL_MS = 1500;
14846
+ var RECENT_TTL_MS = 15 * 6e4;
14847
+ var RECENT_MAX = 200;
14848
+ var STALE_FILE_MS = 10 * 6e4;
14849
+ var RecentMessages = class {
14850
+ constructor(now = Date.now) {
14851
+ this.now = now;
14852
+ }
14853
+ now;
14854
+ map = /* @__PURE__ */ new Map();
14855
+ set(msg) {
14856
+ this.map.delete(msg.messageId);
14857
+ this.map.set(msg.messageId, { msg, at: this.now() });
14858
+ while (this.map.size > RECENT_MAX) this.map.delete(this.map.keys().next().value);
14859
+ }
14860
+ get(chatId, messageId) {
14861
+ const hit = this.map.get(messageId);
14862
+ if (!hit || this.now() - hit.at > RECENT_TTL_MS || hit.msg.chatId !== chatId) return void 0;
14863
+ return hit.msg;
14864
+ }
14865
+ };
14866
+ function processSpawnFiles(o) {
14867
+ const folder = join26(o.dir, SPAWN_DIR);
14868
+ if (!existsSync9(folder)) return [];
14869
+ const now = (o.now ?? Date.now)();
14870
+ const out = [];
14871
+ for (const name of readdirSync2(folder)) {
14872
+ if (!name.endsWith(".json")) continue;
14873
+ const file = join26(folder, name);
14874
+ let req;
14875
+ try {
14876
+ req = JSON.parse(readFileSync5(file, "utf8"));
14877
+ } catch {
14878
+ rmSync3(file, { force: true });
14879
+ out.push("bad-file");
14880
+ continue;
14881
+ }
14882
+ rmSync3(file, { force: true });
14883
+ const chatId = req.chat_id;
14884
+ const messageId = req.message_id;
14885
+ if (!chatId || !messageId || req.at && now - Date.parse(req.at) > STALE_FILE_MS) {
14886
+ out.push("bad-file");
14887
+ continue;
14888
+ }
14889
+ const msg = o.recent.get(chatId, messageId);
14890
+ if (!msg) {
14891
+ log.warn("spawn", "unknown-message", { chatId, messageId });
14892
+ out.push("unknown-message");
14893
+ continue;
14894
+ }
14895
+ const scope = `${chatId}:${messageId}`;
14896
+ if (o.isRoot(messageId) || o.activeScopes().includes(scope)) {
14897
+ out.push("already");
14898
+ continue;
14899
+ }
14900
+ const running = o.activeScopes().filter((s) => s.startsWith(`${chatId}:`)).length;
14901
+ if (running >= o.limit) {
14902
+ log.info("spawn", "worker-limit", { scope, limit: o.limit });
14903
+ o.reject(msg, "limit");
14904
+ out.push("limit");
14905
+ continue;
14906
+ }
14907
+ try {
14908
+ o.register(messageId, chatId);
14909
+ o.push(scope, msg);
14910
+ log.info("spawn", "spawned", { scope });
14911
+ out.push("spawned");
14912
+ } catch (err) {
14913
+ log.fail("spawn", err, { scope });
14914
+ out.push("bad-file");
14915
+ }
14916
+ }
14917
+ return out;
14918
+ }
14919
+ function startSpawnInbox(o, intervalMs = SPAWN_POLL_MS) {
14920
+ mkdirSync6(join26(o.dir, SPAWN_DIR), { recursive: true });
14921
+ const timer = setInterval(() => {
14922
+ try {
14923
+ processSpawnFiles(o);
14924
+ } catch (err) {
14925
+ log.fail("spawn", err);
14926
+ }
14927
+ }, intervalMs);
14928
+ timer.unref?.();
14929
+ return { stop: () => clearInterval(timer) };
14930
+ }
14931
+
14932
+ // src/bridge/bot/worker-report.ts
14933
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync7 } from "fs";
14934
+ import { join as join27 } from "path";
14818
14935
  var REPORT_MARKER = "[worker-report]";
14819
14936
  var SUMMARY_LINES = 4;
14820
14937
  var clip = (s, n) => s.length > n ? `${s.slice(0, n)}\u2026` : s;
@@ -14860,9 +14977,9 @@ function reportMessage(r, senderId, senderName) {
14860
14977
  }
14861
14978
  function appendWorkerLog(dir, r) {
14862
14979
  if (!/^[A-Za-z0-9_-]+$/.test(r.chatId)) return;
14863
- const folder = join26(dir, "workers");
14864
- mkdirSync6(folder, { recursive: true });
14865
- appendFileSync2(join26(folder, `${r.chatId}.jsonl`), `${JSON.stringify(r)}
14980
+ const folder = join27(dir, "workers");
14981
+ mkdirSync7(folder, { recursive: true });
14982
+ appendFileSync2(join27(folder, `${r.chatId}.jsonl`), `${JSON.stringify(r)}
14866
14983
  `);
14867
14984
  }
14868
14985
  async function observeWorkerRun(i) {
@@ -14909,6 +15026,33 @@ async function observeWorkerRun(i) {
14909
15026
  }
14910
15027
  return report;
14911
15028
  }
15029
+ var ReportInbox = class {
15030
+ constructor(max = 10, ttlMs = 24 * 60 * 60 * 1e3, now = Date.now) {
15031
+ this.max = max;
15032
+ this.ttlMs = ttlMs;
15033
+ this.now = now;
15034
+ }
15035
+ max;
15036
+ ttlMs;
15037
+ now;
15038
+ byChat = /* @__PURE__ */ new Map();
15039
+ add(chatId, text) {
15040
+ const list = this.byChat.get(chatId) ?? [];
15041
+ list.push({ text, at: this.now() });
15042
+ while (list.length > this.max) list.shift();
15043
+ this.byChat.set(chatId, list);
15044
+ }
15045
+ /** 取走这个私聊攒下的回流(过了 TTL 的丢掉)。 */
15046
+ take(chatId) {
15047
+ const list = this.byChat.get(chatId) ?? [];
15048
+ this.byChat.delete(chatId);
15049
+ const cutoff = this.now() - this.ttlMs;
15050
+ return list.filter((r) => r.at >= cutoff).map((r) => r.text);
15051
+ }
15052
+ };
15053
+ function reportsInstruction(reports) {
15054
+ return "\u4F60\u4E4B\u524D\u6D3E\u5230\u8BDD\u9898\u91CC\u7684\u4EFB\u52A1\u6709\u65B0\u7684\u7EC8\u6001\uFF0C\u4E0B\u9762\u662F\u7CFB\u7EDF\u56DE\u6D41\uFF0C\u53EA\u7528\u6765\u56DE\u6EAF\uFF0C\u4E0D\u662F\u7528\u6237\u8BF4\u7684\u8BDD\uFF0C\u4E0D\u8981\u4E3A\u5B83\u4EEC\u5355\u72EC\u56DE\u590D\u7528\u6237\uFF1B\u7528\u6237\u540E\u9762\u95EE\u8D77\u65F6\u51ED trace \u8BA4\u662F\u54EA\u4E2A\u8BDD\u9898\u3002\n\n" + reports.join("\n\n");
15055
+ }
14912
15056
 
14913
15057
  // src/bridge/bot/quote.ts
14914
15058
  import { normalize } from "@larksuite/channel";
@@ -15656,7 +15800,7 @@ async function startChannel(deps) {
15656
15800
  const pool = new ProcessPool(() => getMaxConcurrentRuns(controls.cfg));
15657
15801
  const executor = new RunExecutor({ agent, pool, activeRuns });
15658
15802
  const appSecret = await resolveAppSecret(cfg, deps.appPaths);
15659
- const callbackNonceStore = deps.appPaths?.mediaDir ? new CallbackNonceStore(join27(dirname19(deps.appPaths.mediaDir), "callback-nonces.json")) : void 0;
15803
+ const callbackNonceStore = deps.appPaths?.mediaDir ? new CallbackNonceStore(join28(dirname19(deps.appPaths.mediaDir), "callback-nonces.json")) : void 0;
15660
15804
  await callbackNonceStore?.load();
15661
15805
  const callbackAuth = callbackNonceStore ? new CallbackAuth({
15662
15806
  keys: [{ version: 1, secret: appSecret }],
@@ -15670,6 +15814,7 @@ async function startChannel(deps) {
15670
15814
  appSecret
15671
15815
  });
15672
15816
  const threadModeOverrideWarnedChats = /* @__PURE__ */ new Set();
15817
+ const recentDm = new RecentMessages();
15673
15818
  const logThreadModeOverride = ({ chatId, resolvedMode, threadId }) => {
15674
15819
  const fields = { chatId, cachedMode: resolvedMode, threadId };
15675
15820
  if (threadModeOverrideWarnedChats.has(chatId)) {
@@ -15719,6 +15864,7 @@ async function startChannel(deps) {
15719
15864
  const channel = createLarkChannel(opts);
15720
15865
  installStreamResilience(channel);
15721
15866
  const media = new MediaCache(channel, deps.appPaths?.mediaDir);
15867
+ const reportInbox = new ReportInbox();
15722
15868
  const pending = new PendingQueue(DEBOUNCE_MS, (scope, batch, arrival) => {
15723
15869
  const firstMsg = batch[0];
15724
15870
  if (!firstMsg) return;
@@ -15752,8 +15898,9 @@ async function startChannel(deps) {
15752
15898
  batch,
15753
15899
  arrival,
15754
15900
  pushToRouter: (m) => {
15755
- pending.push(m.chatId, m);
15901
+ reportInbox.add(m.chatId, m.content);
15756
15902
  },
15903
+ reportInbox,
15757
15904
  controls,
15758
15905
  cotClient,
15759
15906
  callbackAuth,
@@ -15793,6 +15940,7 @@ async function startChannel(deps) {
15793
15940
  workspaces,
15794
15941
  activeRuns,
15795
15942
  pending,
15943
+ recent: recentDm,
15796
15944
  msg,
15797
15945
  controls,
15798
15946
  chatModeCache,
@@ -15928,6 +16076,22 @@ async function startChannel(deps) {
15928
16076
  await ownerRefresh.start();
15929
16077
  const knownChatsRefresh = startKnownChatsRefreshTimer(channel, controls);
15930
16078
  armed.push(() => knownChatsRefresh.stop());
16079
+ const spawnDir = controls.profileConfig.preferences.taskBindings?.dir;
16080
+ const spawnInbox = spawnDir ? startSpawnInbox({
16081
+ dir: spawnDir,
16082
+ recent: recentDm,
16083
+ activeScopes: () => [.../* @__PURE__ */ new Set([...activeRuns.scopes(), ...pending.scopes()])],
16084
+ limit: MAX_DM_WORKERS,
16085
+ isRoot: (id) => isDispatchRoot(spawnDir, id),
16086
+ register: (id, chatId) => registerDispatchRoot(spawnDir, id, chatId),
16087
+ push: (scope, m) => {
16088
+ pending.push(scope, m);
16089
+ },
16090
+ reject: (m) => {
16091
+ void channel.send(m.chatId, { markdown: `\u4F60\u540C\u65F6\u5728\u8DD1\u7684\u4EFB\u52A1\u5DF2\u7ECF\u6709 ${MAX_DM_WORKERS} \u4E2A\uFF0C\u7B49\u5176\u4E2D\u4E00\u4E2A\u7ED3\u675F\u540E\u518D\u53D1\u8FD9\u6761\u3002` }, { replyTo: m.messageId }).catch((err) => log.warn("spawn", "limit-reply-failed", { err: String(err) }));
16092
+ }
16093
+ }) : void 0;
16094
+ if (spawnInbox) armed.push(() => spawnInbox.stop());
15931
16095
  const identity = channel.botIdentity;
15932
16096
  if (identity?.openId) {
15933
16097
  agent.setBotIdentity?.({
@@ -15958,6 +16122,7 @@ async function startChannel(deps) {
15958
16122
  unregisterChannel(controls.profile, channelToken);
15959
16123
  ownerRefresh.stop();
15960
16124
  knownChatsRefresh.stop();
16125
+ spawnInbox?.stop();
15961
16126
  keepalive.stop();
15962
16127
  meetingManager?.dispose();
15963
16128
  controls.meeting = void 0;
@@ -16081,6 +16246,7 @@ async function intakeMessage(deps) {
16081
16246
  }
16082
16247
  }
16083
16248
  const emsg = threadId === msg.threadId ? msg : { ...msg, threadId };
16249
+ if (msg.chatType === "p2p") deps.recent.set(emsg);
16084
16250
  const chatMode = threadId ? "topic" : resolvedMode;
16085
16251
  if (threadId && resolvedMode !== "topic") {
16086
16252
  chatModeCache.invalidate(msg.chatId);
@@ -16174,7 +16340,8 @@ async function intakeMessage(deps) {
16174
16340
  log.info("intake", "command", { scope, droppedPending: dropped.length });
16175
16341
  return;
16176
16342
  }
16177
- if (workerScope && !activeRuns.get(scope) && runningWorkers(activeRuns.scopes(), emsg.chatId) >= MAX_DM_WORKERS) {
16343
+ const inFlightScopes = [.../* @__PURE__ */ new Set([...activeRuns.scopes(), ...pending.scopes()])];
16344
+ if (workerScope && !inFlightScopes.includes(scope) && runningWorkers(inFlightScopes, emsg.chatId) >= MAX_DM_WORKERS) {
16178
16345
  log.info("intake", "worker-limit", { scope, limit: MAX_DM_WORKERS });
16179
16346
  await channel.send(emsg.chatId, { markdown: `\u4F60\u540C\u65F6\u5728\u8DD1\u7684\u4EFB\u52A1\u5DF2\u7ECF\u6709 ${MAX_DM_WORKERS} \u4E2A\uFF0C\u7B49\u5176\u4E2D\u4E00\u4E2A\u7ED3\u675F\u540E\u518D\u53D1\u8FD9\u6761\u3002` }, { replyTo: emsg.messageId }).catch((err) => log.warn("intake", "worker-limit-reply-failed", { err: String(err) }));
16180
16347
  return;
@@ -16282,6 +16449,7 @@ async function runAgentBatchInner(deps) {
16282
16449
  batch,
16283
16450
  arrival,
16284
16451
  pushToRouter,
16452
+ reportInbox,
16285
16453
  controls,
16286
16454
  cotClient,
16287
16455
  callbackAuth,
@@ -16355,11 +16523,13 @@ async function runAgentBatchInner(deps) {
16355
16523
  const prevModel = lastRunModelByScope.get(scope);
16356
16524
  const modelSwitched = prevModel !== void 0 && prevModel !== modelSelection;
16357
16525
  lastRunModelByScope.set(scope, modelSelection);
16526
+ const reportsForRouter = firstMsg.chatType === "p2p" && scope === chatId && !binding ? reportInbox?.take(chatId) ?? [] : [];
16358
16527
  const extraInstructions = [
16359
16528
  ...modelSwitched ? [
16360
16529
  `\u7528\u6237\u521A\u628A\u672C\u4F1A\u8BDD\u4F7F\u7528\u7684\u6A21\u578B\u5207\u6362\u4E3A\u300C${modelLabel(agentKind, modelPref)}\u300D\u3002\u4E4B\u524D\u7684\u5BF9\u8BDD\u91CC\u53EF\u80FD\u63D0\u5230\u522B\u7684\u6A21\u578B,\u8BF7\u4EE5\u5F53\u524D\u6A21\u578B\u4E3A\u51C6;\u82E5\u88AB\u95EE\u5230\u4F60\u7528\u7684\u662F\u4EC0\u4E48\u6A21\u578B,\u636E\u6B64\u56DE\u7B54\u3002`
16361
16530
  ] : [],
16362
- ...deps.userRead ? [deps.userRead.instruction] : []
16531
+ ...deps.userRead ? [deps.userRead.instruction] : [],
16532
+ ...reportsForRouter.length > 0 ? [reportsInstruction(reportsForRouter)] : []
16363
16533
  ];
16364
16534
  const prompt = buildPrompt(
16365
16535
  batch,
@@ -16369,7 +16539,7 @@ async function runAgentBatchInner(deps) {
16369
16539
  channel.botIdentity,
16370
16540
  extraInstructions
16371
16541
  );
16372
- const dispatchStart = firstMsg.chatType === "p2p" && !threadId && Boolean(controls.profileConfig.preferences.taskBindings) && isDispatchMarker(firstMsg.content);
16542
+ const dispatchStart = firstMsg.chatType === "p2p" && !threadId && Boolean(controls.profileConfig.preferences.taskBindings) && (isDispatchMarker(firstMsg.content) || isDispatchRoot(controls.profileConfig.preferences.taskBindings.dir, firstMsg.messageId));
16373
16543
  const sendOpts = {
16374
16544
  replyTo: dispatchStart ? firstMsg.messageId : lastMsg.messageId,
16375
16545
  ...mode === "topic" && threadId || dispatchStart ? { replyInThread: true } : {}
@@ -16383,11 +16553,12 @@ async function runAgentBatchInner(deps) {
16383
16553
  replyInThread: sendOpts.replyInThread === true
16384
16554
  });
16385
16555
  const accessDecision = firstMsg.chatType === "p2p" ? canUseDm(controls.profileConfig, controls, firstMsg.senderId) : canUseGroup(controls.profileConfig, controls, firstMsg.chatId, firstMsg.senderId);
16556
+ const workerScope = firstMsg.chatType === "p2p" && scope.startsWith(`${chatId}:`);
16386
16557
  const scopeContext = {
16387
16558
  source: "im",
16388
16559
  chatId,
16389
16560
  actorId: firstMsg.senderId,
16390
- ...threadId ? { threadId } : {}
16561
+ ...threadId && !workerScope ? { threadId } : {}
16391
16562
  };
16392
16563
  const capability = controls.profileConfig.agentKind === "codex" ? codexCapability(controls.profileConfig) : claudeCapability(controls.profileConfig);
16393
16564
  const flow = await startRunFlow({
@@ -16416,7 +16587,7 @@ async function runAgentBatchInner(deps) {
16416
16587
  now: Date.now(),
16417
16588
  stopGraceMs: getAgentStopGraceMs(controls.cfg),
16418
16589
  ...binding && taskPlan?.ok ? { task: { binding, maxBudgetUsd: taskPlan.maxBudgetUsd } } : {},
16419
- ...deps.userRead?.extraEnv || deps.claudeEnv || firstMsg.chatType === "p2p" ? { extraEnv: { ...deps.claudeEnv, ...deps.userRead?.extraEnv, ...firstMsg.chatType === "p2p" ? { SDLC_DM_CHAT: chatId } : {} } } : {},
16590
+ ...deps.userRead?.extraEnv || deps.claudeEnv || firstMsg.chatType === "p2p" ? { extraEnv: { ...deps.claudeEnv, ...deps.userRead?.extraEnv, ...firstMsg.chatType === "p2p" ? { SDLC_DM_CHAT: chatId } : {}, ...firstMsg.chatType === "p2p" && scope === chatId ? { SDLC_DM_MSG: lastMsg.messageId } : {} } } : {},
16420
16591
  observability: {
16421
16592
  profile: controls.profile,
16422
16593
  agent: capability.agentId,
@@ -19575,8 +19746,8 @@ function openBrowser(url) {
19575
19746
 
19576
19747
  // src/bridge/cli/commands/user-gateway.ts
19577
19748
  import { spawnSync as spawnSync5 } from "child_process";
19578
- import { existsSync as existsSync10 } from "fs";
19579
- import { join as join29 } from "path";
19749
+ import { existsSync as existsSync11 } from "fs";
19750
+ import { join as join30 } from "path";
19580
19751
 
19581
19752
  // src/bridge/user-gateway/db-query.ts
19582
19753
  import { spawn as spawn3 } from "child_process";
@@ -19634,13 +19805,13 @@ function toResult(r) {
19634
19805
 
19635
19806
  // src/bridge/user-gateway/gateway.ts
19636
19807
  import { randomBytes as randomBytes10 } from "crypto";
19637
- import { existsSync as existsSync9 } from "fs";
19808
+ import { existsSync as existsSync10 } from "fs";
19638
19809
  import { mkdir as mkdir19, rm as rm14, writeFile as writeFile9 } from "fs/promises";
19639
- import { join as join28 } from "path";
19810
+ import { join as join29 } from "path";
19640
19811
 
19641
19812
  // src/bridge/user-gateway/app-token.ts
19642
19813
  import { spawn as spawn4 } from "child_process";
19643
- import { readFileSync as readFileSync5 } from "fs";
19814
+ import { readFileSync as readFileSync6 } from "fs";
19644
19815
  var APP_TOKEN_REFRESH_BEFORE_MS = 5 * 6e4;
19645
19816
  var APP_TOKEN_FAIL_BACKOFF_MS = 6e4;
19646
19817
  function createAppTokenCache(fetcher, now = Date.now) {
@@ -19685,7 +19856,7 @@ function brandOfTenant(tenant) {
19685
19856
  }
19686
19857
  function sourceBrand(sourceConfigFile) {
19687
19858
  try {
19688
- return brandOfTenant(JSON.parse(readFileSync5(sourceConfigFile, "utf8")).accounts?.app?.tenant);
19859
+ return brandOfTenant(JSON.parse(readFileSync6(sourceConfigFile, "utf8")).accounts?.app?.tenant);
19689
19860
  } catch {
19690
19861
  return "lark";
19691
19862
  }
@@ -19722,7 +19893,7 @@ function run(command, args, input, env, timeoutMs) {
19722
19893
  }
19723
19894
  function realAppTokenFetcher(sourceConfigFile) {
19724
19895
  return async () => {
19725
- const cfg = JSON.parse(readFileSync5(sourceConfigFile, "utf8"));
19896
+ const cfg = JSON.parse(readFileSync6(sourceConfigFile, "utf8"));
19726
19897
  const app = cfg.accounts?.app;
19727
19898
  if (!app?.id) throw new Error("source \u914D\u7F6E\u91CC\u6CA1\u6709\u5E94\u7528 id");
19728
19899
  let cred;
@@ -19878,10 +20049,10 @@ function createGateway(opts) {
19878
20049
  const used = /* @__PURE__ */ new Map();
19879
20050
  const inFlight = /* @__PURE__ */ new Set();
19880
20051
  const pendingAuth = /* @__PURE__ */ new Map();
19881
- const tokenRoot = join28(opts.stateDir, "user-tokens", opts.appId);
19882
- const userDir = (openId) => join28(tokenRoot, openId);
19883
- const authorizedMark = (openId) => join28(userDir(openId), ".authorized");
19884
- const isAuthorized = (openId) => existsSync9(authorizedMark(openId));
20052
+ const tokenRoot = join29(opts.stateDir, "user-tokens", opts.appId);
20053
+ const userDir = (openId) => join29(tokenRoot, openId);
20054
+ const authorizedMark = (openId) => join29(userDir(openId), ".authorized");
20055
+ const isAuthorized = (openId) => existsSync10(authorizedMark(openId));
19885
20056
  const brand = sourceBrand(opts.larkSourceConfig);
19886
20057
  function env(dir) {
19887
20058
  return {
@@ -19892,11 +20063,11 @@ function createGateway(opts) {
19892
20063
  LARKSUITE_CLI_NO_SKILLS_NOTIFIER: "1"
19893
20064
  };
19894
20065
  }
19895
- const appDir = join28(opts.stateDir, "app");
20066
+ const appDir = join29(opts.stateDir, "app");
19896
20067
  const bound2 = /* @__PURE__ */ new Set();
19897
20068
  async function ensureBound(dir, identity) {
19898
20069
  if (bound2.has(dir)) return;
19899
- if (!existsSync9(join28(dir, "lark-channel", "config.json"))) {
20070
+ if (!existsSync10(join29(dir, "lark-channel", "config.json"))) {
19900
20071
  await mkdir19(dir, { recursive: true, mode: 448 });
19901
20072
  const r = await opts.exec(["config", "bind", "--source", "lark-channel", "--identity", identity], env(dir), 3e4);
19902
20073
  if (r.code !== 0) throw new Error(`lark-cli \u7ED1\u5B9A\u5931\u8D25\uFF1A${larkError(r).detail}`);
@@ -20195,7 +20366,7 @@ function createGateway(opts) {
20195
20366
  if (typeof v === "string") return { status: v };
20196
20367
  if (v.text?.trim() !== REVOKE_TEXT2) return { status: "not_revoke" };
20197
20368
  for (const [h, x] of handles) if (x.openId === v.openId) handles.delete(h);
20198
- const had = existsSync9(userDir(v.openId));
20369
+ const had = existsSync10(userDir(v.openId));
20199
20370
  await rm14(userDir(v.openId), { recursive: true, force: true });
20200
20371
  bound2.delete(userDir(v.openId));
20201
20372
  log.info("user-gateway", "auth.revoked", { sender: tail6(v.openId), messageId, had });
@@ -20442,10 +20613,10 @@ function fetchToken(cmd) {
20442
20613
  }
20443
20614
  async function runUserGateway(opts) {
20444
20615
  if (!/^cli_[A-Za-z0-9]+$/.test(opts.appId)) throw new Error("--app-id \u683C\u5F0F\u4E0D\u5BF9");
20445
- if (!existsSync10(opts.larkSourceConfig)) throw new Error(`\u627E\u4E0D\u5230 lark-cli source \u914D\u7F6E\uFF1A${opts.larkSourceConfig}`);
20616
+ if (!existsSync11(opts.larkSourceConfig)) throw new Error(`\u627E\u4E0D\u5230 lark-cli source \u914D\u7F6E\uFF1A${opts.larkSourceConfig}`);
20446
20617
  const port = Number(opts.port ?? 8788);
20447
20618
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("--port \u4E0D\u5BF9");
20448
- configureLogger({ logsDir: join29(opts.stateDir, "logs") });
20619
+ configureLogger({ logsDir: join30(opts.stateDir, "logs") });
20449
20620
  const gateway = createGateway({
20450
20621
  appId: opts.appId,
20451
20622
  stateDir: opts.stateDir,