aai-lark-bridge 0.2.30 → 0.2.31

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.30",
7
+ version: "0.2.31",
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 join26 } from "path";
7620
+ import { dirname as dirname19, join as join27 } from "path";
7621
7621
 
7622
7622
  // src/bridge/agent/capability.ts
7623
7623
  function claudeCapability(profile2) {
@@ -14736,9 +14736,12 @@ var PendingQueue = class {
14736
14736
  existing.timer = this.blocked.has(scope) ? void 0 : this.armTimer(scope);
14737
14737
  return existing.messages.length;
14738
14738
  }
14739
+ const behindRun = this.blocked.has(scope);
14739
14740
  this.map.set(scope, {
14740
14741
  messages: [msg],
14741
- timer: this.blocked.has(scope) ? void 0 : this.armTimer(scope)
14742
+ timer: behindRun ? void 0 : this.armTimer(scope),
14743
+ firstArrivedAt: Date.now(),
14744
+ behindRun
14742
14745
  });
14743
14746
  return 1;
14744
14747
  }
@@ -14785,13 +14788,128 @@ var PendingQueue = class {
14785
14788
  if (!entry) return;
14786
14789
  this.map.delete(scope);
14787
14790
  try {
14788
- this.onFlush(scope, entry.messages);
14791
+ this.onFlush(scope, entry.messages, {
14792
+ firstArrivedAt: entry.firstArrivedAt,
14793
+ behindRun: entry.behindRun
14794
+ });
14789
14795
  } catch (err) {
14790
14796
  log.fail("queue", err, { scope, batchSize: entry.messages.length });
14791
14797
  }
14792
14798
  }
14793
14799
  };
14794
14800
 
14801
+ // src/bridge/bot/scope.ts
14802
+ function dispatchScope(dir, m) {
14803
+ if (!dir) return void 0;
14804
+ const route2 = dispatchRoute(dir, m);
14805
+ if (route2 === "start") return `${m.chatId}:${m.messageId}`;
14806
+ if (route2 === "thread" && m.rootId) return `${m.chatId}:${m.rootId}`;
14807
+ return void 0;
14808
+ }
14809
+ var MAX_DM_WORKERS = 3;
14810
+ function runningWorkers(scopes, chatId) {
14811
+ const prefix = `${chatId}:`;
14812
+ return scopes.filter((s) => s.startsWith(prefix)).length;
14813
+ }
14814
+
14815
+ // src/bridge/bot/worker-report.ts
14816
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync6 } from "fs";
14817
+ import { join as join26 } from "path";
14818
+ var REPORT_MARKER = "[worker-report]";
14819
+ var SUMMARY_LINES = 4;
14820
+ var clip = (s, n) => s.length > n ? `${s.slice(0, n)}\u2026` : s;
14821
+ var oneLine = (s) => s.replace(/\s+/g, " ").trim();
14822
+ function terminalOf(evt) {
14823
+ if (evt.type === "done") {
14824
+ if (evt.terminationReason === "interrupted") return { state: "stopped" };
14825
+ if (evt.terminationReason === "timeout") return { state: "blocked", reason: "\u957F\u65F6\u95F4\u6CA1\u6709\u8FDB\u5C55\uFF0C\u5DF2\u505C\u6B62" };
14826
+ return { state: "ready" };
14827
+ }
14828
+ if (evt.type === "error") {
14829
+ if (evt.terminationReason === "interrupted") return { state: "stopped" };
14830
+ if (evt.terminationReason === "timeout") return { state: "blocked", reason: "\u957F\u65F6\u95F4\u6CA1\u6709\u8FDB\u5C55\uFF0C\u5DF2\u505C\u6B62" };
14831
+ if (evt.budgetHit) return { state: "blocked", reason: "\u649E\u5230\u82B1\u8D39\u4E0A\u9650" };
14832
+ return { state: "failed", reason: evt.message };
14833
+ }
14834
+ return void 0;
14835
+ }
14836
+ function formatReport(r) {
14837
+ const body = (r.summary ? r.summary.split("\n").map((l) => l.trim()).filter(Boolean) : ["\uFF08\u6CA1\u6709\u5185\u5BB9\uFF09"]).slice(0, SUMMARY_LINES - 1);
14838
+ const lines = [
14839
+ `${REPORT_MARKER} ${r.state}\uFF5C\u7528\u6237\u95EE\u7684\uFF1A${clip(oneLine(r.ask), 40)}`,
14840
+ ...body.map((l) => clip(l, 120))
14841
+ ].slice(0, SUMMARY_LINES);
14842
+ lines.push(`trace: scope=${r.scope} root=${r.rootId} session=${r.sessionId ?? "-"} run=${r.runId} at=${r.at}`);
14843
+ return lines.join("\n");
14844
+ }
14845
+ function reportMessage(r, senderId, senderName) {
14846
+ return {
14847
+ messageId: `worker-report-${r.runId}`,
14848
+ chatId: r.chatId,
14849
+ chatType: "p2p",
14850
+ senderId,
14851
+ ...senderName ? { senderName } : {},
14852
+ content: formatReport(r),
14853
+ rawContentType: "worker_report",
14854
+ resources: [],
14855
+ mentions: [],
14856
+ mentionAll: false,
14857
+ mentionedBot: false,
14858
+ createTime: Date.now()
14859
+ };
14860
+ }
14861
+ function appendWorkerLog(dir, r) {
14862
+ 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)}
14866
+ `);
14867
+ }
14868
+ async function observeWorkerRun(i) {
14869
+ const rootId = i.scope.slice(i.chatId.length + 1);
14870
+ let sessionId;
14871
+ let finalText = "";
14872
+ let streamed = "";
14873
+ let terminal;
14874
+ try {
14875
+ for await (const evt of i.events) {
14876
+ if ((evt.type === "system" || evt.type === "done") && evt.sessionId) sessionId = evt.sessionId;
14877
+ if (evt.type === "final_text") finalText = evt.content;
14878
+ if (evt.type === "text") streamed += evt.delta;
14879
+ const t = terminalOf(evt);
14880
+ if (t) terminal = t;
14881
+ }
14882
+ } catch (err) {
14883
+ i.onError?.("observe", err);
14884
+ terminal ??= { state: "failed", reason: err instanceof Error ? err.message : String(err) };
14885
+ }
14886
+ if (!terminal) return void 0;
14887
+ const report = {
14888
+ state: terminal.state,
14889
+ chatId: i.chatId,
14890
+ scope: i.scope,
14891
+ rootId,
14892
+ runId: i.runId,
14893
+ ...sessionId ? { sessionId } : {},
14894
+ ask: i.ask,
14895
+ summary: terminal.reason ?? (finalText || streamed).trim(),
14896
+ at: (i.now?.() ?? /* @__PURE__ */ new Date()).toISOString()
14897
+ };
14898
+ if (i.dir) {
14899
+ try {
14900
+ appendWorkerLog(i.dir, report);
14901
+ } catch (err) {
14902
+ i.onError?.("log", err);
14903
+ }
14904
+ }
14905
+ try {
14906
+ i.push(reportMessage(report, i.senderId, i.senderName));
14907
+ } catch (err) {
14908
+ i.onError?.("push", err);
14909
+ }
14910
+ return report;
14911
+ }
14912
+
14795
14913
  // src/bridge/bot/quote.ts
14796
14914
  import { normalize } from "@larksuite/channel";
14797
14915
 
@@ -15538,7 +15656,7 @@ async function startChannel(deps) {
15538
15656
  const pool = new ProcessPool(() => getMaxConcurrentRuns(controls.cfg));
15539
15657
  const executor = new RunExecutor({ agent, pool, activeRuns });
15540
15658
  const appSecret = await resolveAppSecret(cfg, deps.appPaths);
15541
- const callbackNonceStore = deps.appPaths?.mediaDir ? new CallbackNonceStore(join26(dirname19(deps.appPaths.mediaDir), "callback-nonces.json")) : void 0;
15659
+ const callbackNonceStore = deps.appPaths?.mediaDir ? new CallbackNonceStore(join27(dirname19(deps.appPaths.mediaDir), "callback-nonces.json")) : void 0;
15542
15660
  await callbackNonceStore?.load();
15543
15661
  const callbackAuth = callbackNonceStore ? new CallbackAuth({
15544
15662
  keys: [{ version: 1, secret: appSecret }],
@@ -15601,7 +15719,7 @@ async function startChannel(deps) {
15601
15719
  const channel = createLarkChannel(opts);
15602
15720
  installStreamResilience(channel);
15603
15721
  const media = new MediaCache(channel, deps.appPaths?.mediaDir);
15604
- const pending = new PendingQueue(DEBOUNCE_MS, (scope, batch) => {
15722
+ const pending = new PendingQueue(DEBOUNCE_MS, (scope, batch, arrival) => {
15605
15723
  const firstMsg = batch[0];
15606
15724
  if (!firstMsg) return;
15607
15725
  pending.block(scope);
@@ -15632,6 +15750,10 @@ async function startChannel(deps) {
15632
15750
  workspaces,
15633
15751
  media,
15634
15752
  batch,
15753
+ arrival,
15754
+ pushToRouter: (m) => {
15755
+ pending.push(m.chatId, m);
15756
+ },
15635
15757
  controls,
15636
15758
  cotClient,
15637
15759
  callbackAuth,
@@ -15968,7 +16090,8 @@ async function intakeMessage(deps) {
15968
16090
  threadId
15969
16091
  });
15970
16092
  }
15971
- const scope = chatMode === "topic" && threadId ? `${msg.chatId}:${threadId}` : msg.chatId;
16093
+ const workerScope = msg.chatType === "p2p" ? dispatchScope(controls.profileConfig.preferences.taskBindings?.dir, emsg) : void 0;
16094
+ const scope = workerScope ?? (chatMode === "topic" && threadId ? `${msg.chatId}:${threadId}` : msg.chatId);
15972
16095
  log.info("intake", "enter", {
15973
16096
  scope,
15974
16097
  chatType: msg.chatType,
@@ -16051,6 +16174,11 @@ async function intakeMessage(deps) {
16051
16174
  log.info("intake", "command", { scope, droppedPending: dropped.length });
16052
16175
  return;
16053
16176
  }
16177
+ if (workerScope && !activeRuns.get(scope) && runningWorkers(activeRuns.scopes(), emsg.chatId) >= MAX_DM_WORKERS) {
16178
+ log.info("intake", "worker-limit", { scope, limit: MAX_DM_WORKERS });
16179
+ 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
+ return;
16181
+ }
16054
16182
  const size = pending.push(scope, emsg);
16055
16183
  log.info("intake", "queued", { scope, queueSize: size, debounceMs: DEBOUNCE_MS });
16056
16184
  }
@@ -16152,6 +16280,8 @@ async function runAgentBatchInner(deps) {
16152
16280
  workspaces,
16153
16281
  media,
16154
16282
  batch,
16283
+ arrival,
16284
+ pushToRouter,
16155
16285
  controls,
16156
16286
  cotClient,
16157
16287
  callbackAuth,
@@ -16286,7 +16416,7 @@ async function runAgentBatchInner(deps) {
16286
16416
  now: Date.now(),
16287
16417
  stopGraceMs: getAgentStopGraceMs(controls.cfg),
16288
16418
  ...binding && taskPlan?.ok ? { task: { binding, maxBudgetUsd: taskPlan.maxBudgetUsd } } : {},
16289
- ...deps.userRead?.extraEnv || deps.claudeEnv ? { extraEnv: { ...deps.claudeEnv, ...deps.userRead?.extraEnv } } : {},
16419
+ ...deps.userRead?.extraEnv || deps.claudeEnv || firstMsg.chatType === "p2p" ? { extraEnv: { ...deps.claudeEnv, ...deps.userRead?.extraEnv, ...firstMsg.chatType === "p2p" ? { SDLC_DM_CHAT: chatId } : {} } } : {},
16290
16420
  observability: {
16291
16421
  profile: controls.profile,
16292
16422
  agent: capability.agentId,
@@ -16312,6 +16442,31 @@ async function runAgentBatchInner(deps) {
16312
16442
  return;
16313
16443
  }
16314
16444
  const { execution, cwdRealpath: cwd } = flow;
16445
+ if (firstMsg.chatType === "p2p" && scope.startsWith(`${chatId}:`)) {
16446
+ void observeWorkerRun({
16447
+ events: execution.subscribe(),
16448
+ chatId,
16449
+ scope,
16450
+ runId: execution.runId,
16451
+ ask: lastMsg.content,
16452
+ senderId: firstMsg.senderId,
16453
+ ...firstMsg.senderName ? { senderName: firstMsg.senderName } : {},
16454
+ dir: controls.profileConfig.preferences.taskBindings?.dir,
16455
+ push: (m) => {
16456
+ pushToRouter?.(m);
16457
+ },
16458
+ onError: (step, err) => log.fail("worker-report", err, { step, scope })
16459
+ });
16460
+ }
16461
+ if (arrival) {
16462
+ log.info("intake", "arrival-to-start", {
16463
+ scope,
16464
+ mode,
16465
+ batchSize: batch.length,
16466
+ behindRun: arrival.behindRun,
16467
+ arrivalToStartMs: Date.now() - arrival.firstArrivedAt
16468
+ });
16469
+ }
16315
16470
  log.info("prompt", "built", {
16316
16471
  promptChars: flow.policy.prompt.length,
16317
16472
  quotes: quotes.length,
@@ -19421,7 +19576,7 @@ function openBrowser(url) {
19421
19576
  // src/bridge/cli/commands/user-gateway.ts
19422
19577
  import { spawnSync as spawnSync5 } from "child_process";
19423
19578
  import { existsSync as existsSync10 } from "fs";
19424
- import { join as join28 } from "path";
19579
+ import { join as join29 } from "path";
19425
19580
 
19426
19581
  // src/bridge/user-gateway/db-query.ts
19427
19582
  import { spawn as spawn3 } from "child_process";
@@ -19481,7 +19636,7 @@ function toResult(r) {
19481
19636
  import { randomBytes as randomBytes10 } from "crypto";
19482
19637
  import { existsSync as existsSync9 } from "fs";
19483
19638
  import { mkdir as mkdir19, rm as rm14, writeFile as writeFile9 } from "fs/promises";
19484
- import { join as join27 } from "path";
19639
+ import { join as join28 } from "path";
19485
19640
 
19486
19641
  // src/bridge/user-gateway/app-token.ts
19487
19642
  import { spawn as spawn4 } from "child_process";
@@ -19723,9 +19878,9 @@ function createGateway(opts) {
19723
19878
  const used = /* @__PURE__ */ new Map();
19724
19879
  const inFlight = /* @__PURE__ */ new Set();
19725
19880
  const pendingAuth = /* @__PURE__ */ new Map();
19726
- const tokenRoot = join27(opts.stateDir, "user-tokens", opts.appId);
19727
- const userDir = (openId) => join27(tokenRoot, openId);
19728
- const authorizedMark = (openId) => join27(userDir(openId), ".authorized");
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");
19729
19884
  const isAuthorized = (openId) => existsSync9(authorizedMark(openId));
19730
19885
  const brand = sourceBrand(opts.larkSourceConfig);
19731
19886
  function env(dir) {
@@ -19737,11 +19892,11 @@ function createGateway(opts) {
19737
19892
  LARKSUITE_CLI_NO_SKILLS_NOTIFIER: "1"
19738
19893
  };
19739
19894
  }
19740
- const appDir = join27(opts.stateDir, "app");
19895
+ const appDir = join28(opts.stateDir, "app");
19741
19896
  const bound2 = /* @__PURE__ */ new Set();
19742
19897
  async function ensureBound(dir, identity) {
19743
19898
  if (bound2.has(dir)) return;
19744
- if (!existsSync9(join27(dir, "lark-channel", "config.json"))) {
19899
+ if (!existsSync9(join28(dir, "lark-channel", "config.json"))) {
19745
19900
  await mkdir19(dir, { recursive: true, mode: 448 });
19746
19901
  const r = await opts.exec(["config", "bind", "--source", "lark-channel", "--identity", identity], env(dir), 3e4);
19747
19902
  if (r.code !== 0) throw new Error(`lark-cli \u7ED1\u5B9A\u5931\u8D25\uFF1A${larkError(r).detail}`);
@@ -20290,7 +20445,7 @@ async function runUserGateway(opts) {
20290
20445
  if (!existsSync10(opts.larkSourceConfig)) throw new Error(`\u627E\u4E0D\u5230 lark-cli source \u914D\u7F6E\uFF1A${opts.larkSourceConfig}`);
20291
20446
  const port = Number(opts.port ?? 8788);
20292
20447
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("--port \u4E0D\u5BF9");
20293
- configureLogger({ logsDir: join28(opts.stateDir, "logs") });
20448
+ configureLogger({ logsDir: join29(opts.stateDir, "logs") });
20294
20449
  const gateway = createGateway({
20295
20450
  appId: opts.appId,
20296
20451
  stateDir: opts.stateDir,