aai-lark-bridge 0.2.29 → 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.29",
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",
@@ -7269,14 +7269,19 @@ function createClaudeSeat(opts) {
7269
7269
  return "stale_card";
7270
7270
  }
7271
7271
  logins.delete(openId);
7272
- const ok = await withLock(openId, () => l.proc.submit(code.trim())).catch(() => false);
7273
- if (ok && readCredentials(dirOf(openId))) {
7272
+ const r = await withLock(openId, () => l.proc.submit(code.trim())).catch(() => "failed");
7273
+ if (r === "retry") {
7274
+ logins.set(openId, l);
7275
+ log.info("user-gateway", "claude.login-code-retry", { sender: tail62(openId) });
7276
+ return "retry_code";
7277
+ }
7278
+ if (r === "ok" && readCredentials(dirOf(openId))) {
7274
7279
  log.info("user-gateway", "claude.login-completed", { sender: tail62(openId) });
7275
7280
  closeCard(l.card, "\u5DF2\u767B\u5F55\u3002\u4E4B\u540E\u63D0\u95EE\u4F1A\u7528\u4F60\u81EA\u5DF1\u7684 Claude \u5E2D\u4F4D\u3002");
7276
7281
  return "logged_in";
7277
7282
  }
7278
7283
  log.warn("user-gateway", "claude.login-failed", { sender: tail62(openId) });
7279
- closeCard(l.card, "\u6388\u6743\u7801\u4E0D\u5BF9\uFF0C\u8FD9\u5F20\u5361\u7247\u5DF2\u4F5C\u5E9F\uFF0C\u5DF2\u7ED9\u4F60\u53D1\u4E86\u65B0\u5361\u7247\u3002");
7284
+ closeCard(l.card, "\u6388\u6743\u7801\u88AB\u62D2\u7EDD\uFF08\u8FC7\u671F\u6216\u5DF2\u7528\u8FC7\uFF09\uFF0C\u8FD9\u5F20\u5361\u7247\u5DF2\u4F5C\u5E9F\uFF0C\u5DF2\u7ED9\u4F60\u53D1\u4E86\u65B0\u5361\u7247\uFF1A\u8BF7\u70B9\u65B0\u5361\u7247\u7684\u300C\u53BB\u6388\u6743\u300D\u91CD\u65B0\u83B7\u53D6\u6388\u6743\u7801\uFF0C\u65E7\u7801\u4E0D\u80FD\u518D\u7528\u3002");
7280
7285
  await startLogin(openId);
7281
7286
  return "wrong_code";
7282
7287
  }
@@ -7305,6 +7310,17 @@ function seatFromEnv(env) {
7305
7310
  const list = (env.SDLC_CLAUDE_SEAT_LIST ?? "").split(",").map((s) => s.trim()).filter((s) => /^ou_[A-Za-z0-9_-]{1,100}$/.test(s));
7306
7311
  return { mode, list };
7307
7312
  }
7313
+ function normalizeCode(raw, state) {
7314
+ const c = raw.replace(/[\s\u200b-\u200d\u2060\ufeff]/g, "").replace(/^["'`“”‘’]+|["'`“”‘’]+$/g, "");
7315
+ return state && c && !c.includes("#") ? `${c}#${state}` : c;
7316
+ }
7317
+ function stateOfUrl(url) {
7318
+ try {
7319
+ return new URL(url).searchParams.get("state") || void 0;
7320
+ } catch {
7321
+ return void 0;
7322
+ }
7323
+ }
7308
7324
  function codeShape(code) {
7309
7325
  const c = code.trim();
7310
7326
  const i = c.indexOf("#");
@@ -7335,6 +7351,8 @@ function realClaudeCli(binary = process.env.SDLC_REAL_CLAUDE || "claude") {
7335
7351
  return {
7336
7352
  async startLogin(dir) {
7337
7353
  const p3 = spawn(binary, ["auth", "login", "--claudeai"], { cwd: dir, env: baseEnv(dir), stdio: ["pipe", "pipe", "pipe"] });
7354
+ p3.stdin.on("error", () => {
7355
+ });
7338
7356
  const timer = setTimeout(() => p3.kill("SIGTERM"), LOGIN_MAX_MS + 6e4).unref();
7339
7357
  let out = "";
7340
7358
  const exited = new Promise((resolve3) => {
@@ -7356,33 +7374,41 @@ function realClaudeCli(binary = process.env.SDLC_REAL_CLAUDE || "claude") {
7356
7374
  p3.kill("SIGTERM");
7357
7375
  throw err;
7358
7376
  });
7377
+ const state = stateOfUrl(url);
7359
7378
  return {
7360
7379
  url,
7361
- async submit(code) {
7380
+ async submit(raw) {
7381
+ const code = normalizeCode(raw, state);
7382
+ if (code !== raw.trim()) log.info("user-gateway", "claude.login-code-normalized", { before: codeShape(raw), after: codeShape(code) });
7362
7383
  const before = out.length;
7363
- p3.stdin.end(`${code}
7384
+ p3.stdin.write(`${code}
7364
7385
  `);
7365
7386
  const verdict = await new Promise((resolve3) => {
7366
7387
  const check2 = () => {
7367
- if (/Invalid code/i.test(out.slice(before))) resolve3("invalid");
7388
+ if (/Invalid code/i.test(out.slice(before))) done("invalid");
7389
+ };
7390
+ const to = setTimeout(() => done("timeout"), SUBMIT_MAX_MS);
7391
+ const done = (v) => {
7392
+ clearTimeout(to);
7393
+ p3.stdout.off("data", check2);
7394
+ p3.stderr.off("data", check2);
7395
+ resolve3(v);
7368
7396
  };
7369
7397
  p3.stdout.on("data", check2);
7370
7398
  p3.stderr.on("data", check2);
7371
7399
  check2();
7372
- void exited.then(resolve3);
7373
- setTimeout(() => resolve3("invalid"), SUBMIT_MAX_MS).unref();
7400
+ void exited.then(done);
7374
7401
  });
7402
+ if (verdict === "invalid") return "retry";
7375
7403
  clearTimeout(timer);
7376
- const ok = verdict !== "invalid" && verdict === 0 && /Login successful/i.test(out);
7377
- if (!ok) {
7378
- log.warn("user-gateway", "claude.login-submit-failed", {
7379
- verdict: verdict === "invalid" ? "invalid-or-timeout" : `exit-${verdict}`,
7380
- codeShape: codeShape(code),
7381
- cliOutput: scrub(out.slice(before), code)
7382
- });
7383
- }
7384
- if (verdict === "invalid") p3.kill("SIGTERM");
7385
- return ok;
7404
+ if (verdict === 0 && /Login successful/i.test(out)) return "ok";
7405
+ log.warn("user-gateway", "claude.login-submit-failed", {
7406
+ verdict: verdict === "timeout" ? "timeout" : `exit-${verdict}`,
7407
+ codeShape: codeShape(code),
7408
+ cliOutput: scrub(out.slice(before), code)
7409
+ });
7410
+ if (verdict === "timeout") p3.kill("SIGTERM");
7411
+ return "failed";
7386
7412
  },
7387
7413
  cancel() {
7388
7414
  clearTimeout(timer);
@@ -7503,7 +7529,9 @@ var SEAT_TEXT = {
7503
7529
  needLogin: "\u4F60\u8FD8\u6CA1\u767B\u5F55 Claude \u8D26\u53F7\u3002\u6211\u5DF2\u79C1\u804A\u53D1\u4F60\u4E00\u5F20\u767B\u5F55\u5361\u7247\uFF1A\u70B9\u5361\u7247\u6388\u6743\uFF0C\u628A\u6388\u6743\u7801\u586B\u8FDB\u5361\u7247\u91CC\u7684\u8F93\u5165\u6846\u63D0\u4EA4\uFF0C\u518D\u91CD\u65B0\u63D0\u95EE\u3002\u6388\u6743\u7801\u4E0D\u8981\u53D1\u5728\u804A\u5929\u91CC\u3002",
7504
7530
  pending: "\u4F60\u7684 Claude \u767B\u5F55\u8FD8\u6CA1\u5B8C\u6210\uFF1A\u8BF7\u628A\u6388\u6743\u7801\u586B\u8FDB\u79C1\u804A\u91CC\u90A3\u5F20\u767B\u5F55\u5361\u7247\u7684\u8F93\u5165\u6846\u63D0\u4EA4\uFF0C\u518D\u91CD\u65B0\u63D0\u95EE\u3002\u6388\u6743\u7801\u4E0D\u8981\u53D1\u5728\u804A\u5929\u91CC\u3002",
7505
7531
  loggedIn: "Claude \u767B\u5F55\u6210\u529F\uFF0C\u8BF7\u91CD\u65B0\u63D0\u95EE\u3002",
7506
- wrongCode: "\u6388\u6743\u7801\u4E0D\u5BF9\u3002\u6211\u79C1\u804A\u53D1\u4E86\u4E00\u5F20\u65B0\u5361\u7247\uFF0C\u8BF7\u91CD\u65B0\u70B9\u5361\u7247\u767B\u5F55\u3002",
7532
+ badCode: "\u6CA1\u6536\u5230\u6709\u6548\u7684\u6388\u6743\u7801\uFF08\u7A7A\u7684\uFF0C\u6216\u5E26\u4E86\u7A7A\u683C\u3001\u6362\u884C\uFF09\u3002\u8FD9\u5F20\u5361\u7247\u8FD8\u80FD\u7528\uFF1A\u8BF7\u91CD\u65B0\u590D\u5236\u6388\u6743\u9875\u4E0A\u7684\u5B8C\u6574\u6388\u6743\u7801\uFF0C\u7C98\u8D34\u8FDB\u8F93\u5165\u6846\u518D\u63D0\u4EA4\u3002",
7533
+ retryCode: "\u6388\u6743\u7801\u683C\u5F0F\u4E0D\u5BF9\u3002\u8FD9\u5F20\u5361\u7247\u8FD8\u80FD\u7528\uFF1A\u8BF7\u56DE\u6388\u6743\u9875\u70B9\u300C\u590D\u5236\u300D\u6309\u94AE\u590D\u5236\u5B8C\u6574\u6388\u6743\u7801\uFF08\u542B # \u540E\u9762\u7684\u90E8\u5206\uFF09\uFF0C\u7C98\u8D34\u8FDB\u8F93\u5165\u6846\u518D\u63D0\u4EA4\u3002",
7534
+ wrongCode: "\u6388\u6743\u7801\u88AB\u62D2\u7EDD\uFF08\u8FC7\u671F\u6216\u5DF2\u7528\u8FC7\uFF09\u3002\u6211\u79C1\u804A\u53D1\u4E86\u4E00\u5F20\u65B0\u5361\u7247\uFF1A\u8BF7\u70B9\u65B0\u5361\u7247\u7684\u300C\u53BB\u6388\u6743\u300D\u91CD\u65B0\u83B7\u53D6\u6388\u6743\u7801\uFF0C\u65E7\u7801\u4E0D\u80FD\u518D\u7528\u3002",
7507
7535
  staleCard: "\u8FD9\u5F20\u767B\u5F55\u5361\u7247\u5DF2\u7ECF\u8FC7\u671F\u6216\u4F5C\u5E9F\u4E86\uFF0C\u8BF7\u7528\u6700\u65B0\u7684\u90A3\u5F20\uFF1B\u6CA1\u6709\u7684\u8BDD\u518D\u63D0\u95EE\u4E00\u6B21\u4F1A\u6536\u5230\u65B0\u5361\u7247\u3002",
7508
7536
  loginFailed: "Claude \u767B\u5F55\u5361\u7247\u6682\u65F6\u53D1\u4E0D\u51FA\uFF0C\u8BF7\u7A0D\u540E\u518D\u95EE\u3002",
7509
7537
  refreshFailed: `Claude \u767B\u5F55\u7EED\u671F\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u518D\u95EE\uFF1B\u4E00\u76F4\u4E0D\u884C\u5C31\u79C1\u804A\u6211\u53D1\u300C${LOGOUT_TEXT}\u300D\uFF0C\u518D\u91CD\u65B0\u767B\u5F55\u3002`,
@@ -7570,6 +7598,10 @@ async function submitClaudeLogin(cfg, sub, deps = {}) {
7570
7598
  switch (r.status) {
7571
7599
  case "logged_in":
7572
7600
  return SEAT_TEXT.loggedIn;
7601
+ case "bad_code":
7602
+ return SEAT_TEXT.badCode;
7603
+ case "retry_code":
7604
+ return SEAT_TEXT.retryCode;
7573
7605
  case "wrong_code":
7574
7606
  return SEAT_TEXT.wrongCode;
7575
7607
  case "not_pending":
@@ -7585,7 +7617,7 @@ async function submitClaudeLogin(cfg, sub, deps = {}) {
7585
7617
  }
7586
7618
 
7587
7619
  // src/bridge/bot/channel.ts
7588
- import { dirname as dirname19, join as join26 } from "path";
7620
+ import { dirname as dirname19, join as join27 } from "path";
7589
7621
 
7590
7622
  // src/bridge/agent/capability.ts
7591
7623
  function claudeCapability(profile2) {
@@ -12766,16 +12798,24 @@ async function handleCardAction(deps) {
12766
12798
  }
12767
12799
  function handleClaudeLogin(deps, value) {
12768
12800
  const cfg = deps.controls.profileConfig.larkCli.claudeSeat;
12769
- if (!cfg) return;
12801
+ if (!cfg) {
12802
+ log.warn("cardAction", "claude-login-no-seat-config", { messageId: deps.evt.messageId });
12803
+ return;
12804
+ }
12770
12805
  const raw = deps.evt.raw;
12771
12806
  const code = raw?.action?.form_value?.code;
12772
12807
  const chatId = deps.evt.chatId;
12808
+ log.info("cardAction", "claude-login-received", {
12809
+ messageId: deps.evt.messageId,
12810
+ codeShape: typeof code === "string" ? codeShape(code) : `type=${typeof code}`
12811
+ });
12773
12812
  void submitClaudeLogin(cfg, {
12774
12813
  operatorId: deps.evt.operator.openId,
12775
12814
  cardMessageId: deps.evt.messageId,
12776
12815
  nonce: value[LOGIN_CARD_KEY],
12777
12816
  code
12778
12817
  }).then((text) => deps.channel.send(chatId, { markdown: text })).catch((err) => log.fail("cardAction", err, { step: "claude-login" }));
12818
+ return { toast: { type: "info", content: "\u5DF2\u6536\u5230\u6388\u6743\u7801\uFF0C\u6B63\u5728\u9A8C\u8BC1\uFF0C\u7ED3\u679C\u4F1A\u79C1\u804A\u53D1\u4F60\u3002" } };
12779
12819
  }
12780
12820
  async function resolveScope(deps) {
12781
12821
  const chatId = deps.evt.chatId;
@@ -14696,9 +14736,12 @@ var PendingQueue = class {
14696
14736
  existing.timer = this.blocked.has(scope) ? void 0 : this.armTimer(scope);
14697
14737
  return existing.messages.length;
14698
14738
  }
14739
+ const behindRun = this.blocked.has(scope);
14699
14740
  this.map.set(scope, {
14700
14741
  messages: [msg],
14701
- timer: this.blocked.has(scope) ? void 0 : this.armTimer(scope)
14742
+ timer: behindRun ? void 0 : this.armTimer(scope),
14743
+ firstArrivedAt: Date.now(),
14744
+ behindRun
14702
14745
  });
14703
14746
  return 1;
14704
14747
  }
@@ -14745,13 +14788,128 @@ var PendingQueue = class {
14745
14788
  if (!entry) return;
14746
14789
  this.map.delete(scope);
14747
14790
  try {
14748
- this.onFlush(scope, entry.messages);
14791
+ this.onFlush(scope, entry.messages, {
14792
+ firstArrivedAt: entry.firstArrivedAt,
14793
+ behindRun: entry.behindRun
14794
+ });
14749
14795
  } catch (err) {
14750
14796
  log.fail("queue", err, { scope, batchSize: entry.messages.length });
14751
14797
  }
14752
14798
  }
14753
14799
  };
14754
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
+
14755
14913
  // src/bridge/bot/quote.ts
14756
14914
  import { normalize } from "@larksuite/channel";
14757
14915
 
@@ -15498,7 +15656,7 @@ async function startChannel(deps) {
15498
15656
  const pool = new ProcessPool(() => getMaxConcurrentRuns(controls.cfg));
15499
15657
  const executor = new RunExecutor({ agent, pool, activeRuns });
15500
15658
  const appSecret = await resolveAppSecret(cfg, deps.appPaths);
15501
- 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;
15502
15660
  await callbackNonceStore?.load();
15503
15661
  const callbackAuth = callbackNonceStore ? new CallbackAuth({
15504
15662
  keys: [{ version: 1, secret: appSecret }],
@@ -15561,7 +15719,7 @@ async function startChannel(deps) {
15561
15719
  const channel = createLarkChannel(opts);
15562
15720
  installStreamResilience(channel);
15563
15721
  const media = new MediaCache(channel, deps.appPaths?.mediaDir);
15564
- const pending = new PendingQueue(DEBOUNCE_MS, (scope, batch) => {
15722
+ const pending = new PendingQueue(DEBOUNCE_MS, (scope, batch, arrival) => {
15565
15723
  const firstMsg = batch[0];
15566
15724
  if (!firstMsg) return;
15567
15725
  pending.block(scope);
@@ -15592,6 +15750,10 @@ async function startChannel(deps) {
15592
15750
  workspaces,
15593
15751
  media,
15594
15752
  batch,
15753
+ arrival,
15754
+ pushToRouter: (m) => {
15755
+ pending.push(m.chatId, m);
15756
+ },
15595
15757
  controls,
15596
15758
  cotClient,
15597
15759
  callbackAuth,
@@ -15646,8 +15808,8 @@ async function startChannel(deps) {
15646
15808
  },
15647
15809
  cardAction: async (evt) => {
15648
15810
  markInbound("card-action");
15649
- await withTrace({ chatId: evt.chatId, msgId: evt.messageId }, async () => {
15650
- await handleCardAction({
15811
+ return await withTrace({ chatId: evt.chatId, msgId: evt.messageId }, async () => {
15812
+ return await handleCardAction({
15651
15813
  channel,
15652
15814
  evt,
15653
15815
  sessions: sessions2,
@@ -15928,7 +16090,8 @@ async function intakeMessage(deps) {
15928
16090
  threadId
15929
16091
  });
15930
16092
  }
15931
- 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);
15932
16095
  log.info("intake", "enter", {
15933
16096
  scope,
15934
16097
  chatType: msg.chatType,
@@ -16011,6 +16174,11 @@ async function intakeMessage(deps) {
16011
16174
  log.info("intake", "command", { scope, droppedPending: dropped.length });
16012
16175
  return;
16013
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
+ }
16014
16182
  const size = pending.push(scope, emsg);
16015
16183
  log.info("intake", "queued", { scope, queueSize: size, debounceMs: DEBOUNCE_MS });
16016
16184
  }
@@ -16112,6 +16280,8 @@ async function runAgentBatchInner(deps) {
16112
16280
  workspaces,
16113
16281
  media,
16114
16282
  batch,
16283
+ arrival,
16284
+ pushToRouter,
16115
16285
  controls,
16116
16286
  cotClient,
16117
16287
  callbackAuth,
@@ -16246,7 +16416,7 @@ async function runAgentBatchInner(deps) {
16246
16416
  now: Date.now(),
16247
16417
  stopGraceMs: getAgentStopGraceMs(controls.cfg),
16248
16418
  ...binding && taskPlan?.ok ? { task: { binding, maxBudgetUsd: taskPlan.maxBudgetUsd } } : {},
16249
- ...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 } : {} } } : {},
16250
16420
  observability: {
16251
16421
  profile: controls.profile,
16252
16422
  agent: capability.agentId,
@@ -16272,6 +16442,31 @@ async function runAgentBatchInner(deps) {
16272
16442
  return;
16273
16443
  }
16274
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
+ }
16275
16470
  log.info("prompt", "built", {
16276
16471
  promptChars: flow.policy.prompt.length,
16277
16472
  quotes: quotes.length,
@@ -19381,7 +19576,7 @@ function openBrowser(url) {
19381
19576
  // src/bridge/cli/commands/user-gateway.ts
19382
19577
  import { spawnSync as spawnSync5 } from "child_process";
19383
19578
  import { existsSync as existsSync10 } from "fs";
19384
- import { join as join28 } from "path";
19579
+ import { join as join29 } from "path";
19385
19580
 
19386
19581
  // src/bridge/user-gateway/db-query.ts
19387
19582
  import { spawn as spawn3 } from "child_process";
@@ -19441,7 +19636,7 @@ function toResult(r) {
19441
19636
  import { randomBytes as randomBytes10 } from "crypto";
19442
19637
  import { existsSync as existsSync9 } from "fs";
19443
19638
  import { mkdir as mkdir19, rm as rm14, writeFile as writeFile9 } from "fs/promises";
19444
- import { join as join27 } from "path";
19639
+ import { join as join28 } from "path";
19445
19640
 
19446
19641
  // src/bridge/user-gateway/app-token.ts
19447
19642
  import { spawn as spawn4 } from "child_process";
@@ -19683,9 +19878,9 @@ function createGateway(opts) {
19683
19878
  const used = /* @__PURE__ */ new Map();
19684
19879
  const inFlight = /* @__PURE__ */ new Set();
19685
19880
  const pendingAuth = /* @__PURE__ */ new Map();
19686
- const tokenRoot = join27(opts.stateDir, "user-tokens", opts.appId);
19687
- const userDir = (openId) => join27(tokenRoot, openId);
19688
- 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");
19689
19884
  const isAuthorized = (openId) => existsSync9(authorizedMark(openId));
19690
19885
  const brand = sourceBrand(opts.larkSourceConfig);
19691
19886
  function env(dir) {
@@ -19697,11 +19892,11 @@ function createGateway(opts) {
19697
19892
  LARKSUITE_CLI_NO_SKILLS_NOTIFIER: "1"
19698
19893
  };
19699
19894
  }
19700
- const appDir = join27(opts.stateDir, "app");
19895
+ const appDir = join28(opts.stateDir, "app");
19701
19896
  const bound2 = /* @__PURE__ */ new Set();
19702
19897
  async function ensureBound(dir, identity) {
19703
19898
  if (bound2.has(dir)) return;
19704
- if (!existsSync9(join27(dir, "lark-channel", "config.json"))) {
19899
+ if (!existsSync9(join28(dir, "lark-channel", "config.json"))) {
19705
19900
  await mkdir19(dir, { recursive: true, mode: 448 });
19706
19901
  const r = await opts.exec(["config", "bind", "--source", "lark-channel", "--identity", identity], env(dir), 3e4);
19707
19902
  if (r.code !== 0) throw new Error(`lark-cli \u7ED1\u5B9A\u5931\u8D25\uFF1A${larkError(r).detail}`);
@@ -20047,7 +20242,7 @@ function createGateway(opts) {
20047
20242
  */
20048
20243
  async claudeLoginSubmit(input) {
20049
20244
  let openId, card, nonce;
20050
- const code = typeof input.code === "string" ? input.code.trim() : "";
20245
+ const code = typeof input.code === "string" ? normalizeCode(input.code) : "";
20051
20246
  try {
20052
20247
  openId = str2(input, "openId", OPEN_ID2);
20053
20248
  card = str2(input, "cardMessageId", MESSAGE_ID);
@@ -20055,7 +20250,11 @@ function createGateway(opts) {
20055
20250
  } catch {
20056
20251
  return { status: "bad_request" };
20057
20252
  }
20058
- if (!code || code.length > 500 || /\s/.test(code)) return { status: "wrong_code" };
20253
+ if (!code || code.length > 500) {
20254
+ const why = !code ? "empty" : "too-long";
20255
+ log.warn("user-gateway", "claude.login-submit-rejected", { sender: openId.slice(-6), why, codeShape: codeShape(code) });
20256
+ return { status: "bad_code" };
20257
+ }
20059
20258
  if (!seat.covers(openId)) return { status: "off" };
20060
20259
  return { status: await seat.submitCode(openId, code, { card, nonce }) };
20061
20260
  },
@@ -20246,7 +20445,7 @@ async function runUserGateway(opts) {
20246
20445
  if (!existsSync10(opts.larkSourceConfig)) throw new Error(`\u627E\u4E0D\u5230 lark-cli source \u914D\u7F6E\uFF1A${opts.larkSourceConfig}`);
20247
20446
  const port = Number(opts.port ?? 8788);
20248
20447
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("--port \u4E0D\u5BF9");
20249
- configureLogger({ logsDir: join28(opts.stateDir, "logs") });
20448
+ configureLogger({ logsDir: join29(opts.stateDir, "logs") });
20250
20449
  const gateway = createGateway({
20251
20450
  appId: opts.appId,
20252
20451
  stateDir: opts.stateDir,