aai-lark-bridge 0.2.50 → 0.2.53

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.50",
7
+ version: "0.2.53",
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",
@@ -7495,23 +7495,46 @@ function realClaudeCli(binary = process.env.SDLC_REAL_CLAUDE || "claude") {
7495
7495
  }
7496
7496
 
7497
7497
  // src/bridge/bot/user-read.ts
7498
- import { spawnSync as spawnSync4 } from "child_process";
7498
+ import { execFile } from "child_process";
7499
7499
  import { randomUUID } from "crypto";
7500
7500
  var HANDLE_ENV = "AAI_USER_READ_HANDLE";
7501
7501
  var GATEWAY_ENV = "AAI_USER_READ_GATEWAY";
7502
7502
  var REVOKE_TEXT = "\u64A4\u9500\u6388\u6743";
7503
7503
  var TIMEOUT_MS = 6e4;
7504
- function readTokenByCommand(command) {
7504
+ var TOKEN_CACHE_MS = 10 * 6e4;
7505
+ var tokenCache = /* @__PURE__ */ new Map();
7506
+ var tokenInFlight = /* @__PURE__ */ new Map();
7507
+ function runTokenCommand(command) {
7505
7508
  const [bin, ...args] = command.trim().split(/\s+/);
7506
- if (!bin) throw new Error("tokenCommand \u4E3A\u7A7A");
7507
- const r = spawnSync4(bin, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 15e3 });
7508
- const value = r.status === 0 ? r.stdout.trim() : "";
7509
- if (!value) throw new Error(`\u53D6\u7F51\u5173\u53E3\u4EE4\u5931\u8D25\uFF08${bin} \u9000\u51FA\u7801 ${r.status}\uFF09`);
7510
- return value;
7509
+ if (!bin) return Promise.reject(new Error("tokenCommand \u4E3A\u7A7A"));
7510
+ return new Promise((resolve3, reject4) => {
7511
+ execFile(bin, args, { encoding: "utf8", timeout: 15e3, maxBuffer: 64 * 1024 }, (err, stdout) => {
7512
+ const value = err ? "" : String(stdout).trim();
7513
+ if (!value) {
7514
+ const code = err && typeof err.code !== "undefined" ? String(err.code) : "0";
7515
+ reject4(new Error(`\u53D6\u7F51\u5173\u53E3\u4EE4\u5931\u8D25\uFF08${bin} \u9000\u51FA\u7801 ${code}\uFF09`));
7516
+ return;
7517
+ }
7518
+ resolve3(value);
7519
+ });
7520
+ });
7521
+ }
7522
+ async function readTokenByCommand(command, now = Date.now) {
7523
+ const hit = tokenCache.get(command);
7524
+ if (hit && hit.until > now()) return hit.value;
7525
+ let p3 = tokenInFlight.get(command);
7526
+ if (!p3) {
7527
+ p3 = runTokenCommand(command).then((value) => {
7528
+ tokenCache.set(command, { value, until: now() + TOKEN_CACHE_MS });
7529
+ return value;
7530
+ }).finally(() => tokenInFlight.delete(command));
7531
+ tokenInFlight.set(command, p3);
7532
+ }
7533
+ return p3;
7511
7534
  }
7512
7535
  async function callGateway(cfg, method, path, body, deps) {
7513
7536
  const doFetch = deps.fetch ?? fetch;
7514
- const pass = (deps.readToken ?? readTokenByCommand)(cfg.tokenCommand);
7537
+ const pass = await (deps.readToken ?? readTokenByCommand)(cfg.tokenCommand);
7515
7538
  const res = await doFetch(`${cfg.gatewayUrl}${path}`, {
7516
7539
  method,
7517
7540
  headers: { "content-type": "application/json", "x-gateway-token": pass },
@@ -7519,9 +7542,22 @@ async function callGateway(cfg, method, path, body, deps) {
7519
7542
  signal: AbortSignal.timeout(TIMEOUT_MS)
7520
7543
  });
7521
7544
  const json = await res.json().catch(() => ({}));
7545
+ if (res.status === 401) tokenCache.delete(cfg.tokenCommand);
7522
7546
  if (!res.ok) throw new Error(`\u7F51\u5173\u8FD4\u56DE ${res.status} ${String(json.status ?? "")}`);
7523
7547
  return json;
7524
7548
  }
7549
+ async function holdProof(cfg, messageId, deps = {}) {
7550
+ try {
7551
+ const r = await callGateway(cfg, "POST", "/proof/hold", { messageId }, deps);
7552
+ const status = String(r.status ?? "");
7553
+ if (status === "held") log.info("user-read", "proof-held", { messageId });
7554
+ else log.warn("user-read", "proof-hold-refused", { messageId, status });
7555
+ return status;
7556
+ } catch (err) {
7557
+ log.warn("user-read", "gateway-failed", { messageId, step: "proof-hold", detail: String(err) });
7558
+ return "error";
7559
+ }
7560
+ }
7525
7561
  var PROMPT_TOOL = `## \u7528\u63D0\u95EE\u4EBA\u7684\u8EAB\u4EFD\u53EA\u8BFB\uFF08aai-user-read\uFF09
7526
7562
 
7527
7563
  \u8FD9\u4E00\u8F6E\u63D0\u95EE\u4EBA\u5DF2\u6388\u6743\uFF0C\u4F60\u53EF\u4EE5\u7528 \`aai-user-read\` \u4EE5\u4ED6\u7684\u8EAB\u4EFD**\u53EA\u8BFB**\u4ED6\u80FD\u770B\u5230\u7684\u6D88\u606F\u548C\u6587\u6863\u3002\u8FD9\u662F\u8BFB\u4ED6\u4E2A\u4EBA\u6570\u636E\u7684\u552F\u4E00\u9014\u5F84\uFF0C\u522B\u7528 \`lark-cli --as user\`\uFF0C\u4E5F\u522B\u8DD1 \`lark-cli auth login\`\u3002
@@ -13766,10 +13802,10 @@ async function removeRejectedResolvedFiles(attachments) {
13766
13802
  }
13767
13803
 
13768
13804
  // src/bridge/bot/group-intake.ts
13769
- import { execFile } from "child_process";
13805
+ import { execFile as execFile2 } from "child_process";
13770
13806
  var GROUP_INTAKE_TIMEOUT_MS = 3e4;
13771
13807
  var defaultRunner = (bin, args, timeoutMs) => new Promise((resolve3) => {
13772
- execFile(bin, args, { encoding: "utf8", timeout: timeoutMs, maxBuffer: 1 << 20 }, (err, stdout) => {
13808
+ execFile2(bin, args, { encoding: "utf8", timeout: timeoutMs, maxBuffer: 1 << 20 }, (err, stdout) => {
13773
13809
  resolve3({ stdout: String(stdout ?? ""), ...err ? { error: err.killed ? "\u8D85\u65F6" : String(err.message ?? err) } : {} });
13774
13810
  });
13775
13811
  });
@@ -13789,7 +13825,7 @@ async function runGroupIntake(cfg, msg, run2 = defaultRunner) {
13789
13825
  if (out?.status === "created" || out?.status === "existing") {
13790
13826
  log.info("group-intake", out.status, base);
13791
13827
  const head = out.status === "created" ? "\u5DF2\u5EFA\u4EFB\u52A1" : "\u8FD9\u6761\u6D88\u606F\u5DF2\u7ECF\u5EFA\u8FC7\u4EFB\u52A1";
13792
- const next = out.note?.trim() ? `\u8D1F\u8D23\u4EBA\u662F\u4F60\u3002${out.note.trim()}` : "\u8D1F\u8D23\u4EBA\u662F\u4F60\uFF0C\u8C03\u5EA6 5 \u5206\u949F\u5185\u63A5\u8D70\uFF0C\u7ED3\u679C\u79C1\u804A\u4F60\u3002";
13828
+ const next = out.note?.trim() ? `\u8D1F\u8D23\u4EBA\u662F\u4F60\u3002${out.note.trim()}` : "\u8D1F\u8D23\u4EBA\u662F\u4F60\uFF0C\u8C03\u5EA6\u63A5\u624B\u540E\u5728\u4EFB\u52A1\u8BDD\u9898\u91CC\u901A\u77E5\u4F60\uFF0C\u7ED3\u679C\u79C1\u804A\u4F60\u3002";
13793
13829
  return `${head}\uFF1A${out.url ?? ""}
13794
13830
  ${next}`;
13795
13831
  }
@@ -15068,11 +15104,15 @@ async function httpProbe(domain) {
15068
15104
  var PendingQueue = class {
15069
15105
  map = /* @__PURE__ */ new Map();
15070
15106
  blocked = /* @__PURE__ */ new Set();
15107
+ /** scope 被挡住的起始时间:排队提示里的「已跑 N 分钟」从这里算。 */
15108
+ blockedAt = /* @__PURE__ */ new Map();
15071
15109
  delayMs;
15072
15110
  onFlush;
15073
- constructor(delayMs, onFlush) {
15111
+ notice;
15112
+ constructor(delayMs, onFlush, notice) {
15074
15113
  this.delayMs = delayMs;
15075
15114
  this.onFlush = onFlush;
15115
+ this.notice = notice;
15076
15116
  }
15077
15117
  push(scope, msg) {
15078
15118
  const existing = this.map.get(scope);
@@ -15080,51 +15120,101 @@ var PendingQueue = class {
15080
15120
  if (existing.timer) clearTimeout(existing.timer);
15081
15121
  existing.messages.push(msg);
15082
15122
  existing.timer = this.blocked.has(scope) ? void 0 : this.armTimer(scope);
15123
+ if (this.blocked.has(scope)) this.armNotice(scope, existing);
15083
15124
  return existing.messages.length;
15084
15125
  }
15085
15126
  const behindRun = this.blocked.has(scope);
15086
- this.map.set(scope, {
15127
+ const entry = {
15087
15128
  messages: [msg],
15088
15129
  timer: behindRun ? void 0 : this.armTimer(scope),
15089
15130
  firstArrivedAt: Date.now(),
15090
15131
  behindRun
15091
- });
15132
+ };
15133
+ this.map.set(scope, entry);
15134
+ if (behindRun) this.armNotice(scope, entry);
15092
15135
  return 1;
15093
15136
  }
15094
15137
  /** 有消息在排队、或正在 flush / 运行(被 block)的 scope:还没占上 ActiveRuns 的也算。 */
15095
15138
  scopes() {
15096
15139
  return [.../* @__PURE__ */ new Set([...this.map.keys(), ...this.blocked])];
15097
15140
  }
15141
+ /** 被挡住(有一轮在 flush 或在跑)的 scope。 */
15142
+ blockedScopes() {
15143
+ return [...this.blocked];
15144
+ }
15098
15145
  cancel(scope) {
15099
15146
  const entry = this.map.get(scope);
15100
15147
  if (!entry) return [];
15101
- if (entry.timer) clearTimeout(entry.timer);
15148
+ clearTimers(entry);
15102
15149
  this.map.delete(scope);
15103
15150
  return entry.messages;
15104
15151
  }
15105
15152
  cancelAll() {
15106
- for (const entry of this.map.values()) {
15107
- if (entry.timer) clearTimeout(entry.timer);
15153
+ for (const entry of this.map.values()) clearTimers(entry);
15154
+ this.map.clear();
15155
+ this.blocked.clear();
15156
+ this.blockedAt.clear();
15157
+ }
15158
+ /**
15159
+ * 拿走全部排队消息、清掉定时器和阻塞(intent 0115 D-7):频道断开或启动失败时交给 supervisor,
15160
+ * 新频道用 {@link adopt} 接着处理,不再像 cancelAll 那样丢掉。
15161
+ */
15162
+ drain() {
15163
+ const out = [];
15164
+ for (const [scope, entry] of this.map) {
15165
+ clearTimers(entry);
15166
+ out.push({ scope, messages: entry.messages, firstArrivedAt: entry.firstArrivedAt, behindRun: entry.behindRun });
15108
15167
  }
15109
15168
  this.map.clear();
15110
15169
  this.blocked.clear();
15170
+ this.blockedAt.clear();
15171
+ return out;
15172
+ }
15173
+ /** 接住上一个频道交来的排队消息:排在这个 scope 已有消息的前面,没被挡住的照常起去抖定时器。 */
15174
+ adopt(snapshots) {
15175
+ for (const snap of snapshots) {
15176
+ if (!snap.messages.length) continue;
15177
+ const existing = this.map.get(snap.scope);
15178
+ if (existing) {
15179
+ existing.messages.unshift(...snap.messages);
15180
+ existing.firstArrivedAt = Math.min(existing.firstArrivedAt, snap.firstArrivedAt);
15181
+ existing.behindRun ||= snap.behindRun;
15182
+ continue;
15183
+ }
15184
+ const blocked = this.blocked.has(snap.scope);
15185
+ const entry = {
15186
+ messages: [...snap.messages],
15187
+ timer: blocked ? void 0 : this.armTimer(snap.scope),
15188
+ firstArrivedAt: snap.firstArrivedAt,
15189
+ behindRun: snap.behindRun
15190
+ };
15191
+ this.map.set(snap.scope, entry);
15192
+ if (blocked) this.armNotice(snap.scope, entry);
15193
+ }
15111
15194
  }
15112
15195
  /** Pause the debounce timer; pushed messages keep accumulating. */
15113
15196
  block(scope) {
15114
15197
  if (this.blocked.has(scope)) return;
15115
15198
  this.blocked.add(scope);
15199
+ this.blockedAt.set(scope, Date.now());
15116
15200
  const entry = this.map.get(scope);
15117
15201
  if (entry?.timer) {
15118
15202
  clearTimeout(entry.timer);
15119
15203
  entry.timer = void 0;
15120
15204
  }
15205
+ if (entry) this.armNotice(scope, entry);
15121
15206
  log.info("queue", "blocked", { scope, queued: entry?.messages.length ?? 0 });
15122
15207
  }
15123
15208
  /** Resume the debounce timer; arms a fresh quiet window if anything queued. */
15124
15209
  unblock(scope) {
15125
15210
  if (!this.blocked.has(scope)) return;
15126
15211
  this.blocked.delete(scope);
15212
+ this.blockedAt.delete(scope);
15127
15213
  const entry = this.map.get(scope);
15214
+ if (entry?.noticeTimer) {
15215
+ clearTimeout(entry.noticeTimer);
15216
+ entry.noticeTimer = void 0;
15217
+ }
15128
15218
  log.info("queue", "unblocked", { scope, queued: entry?.messages.length ?? 0 });
15129
15219
  if (!entry || entry.messages.length === 0) return;
15130
15220
  if (entry.timer) clearTimeout(entry.timer);
@@ -15133,9 +15223,28 @@ var PendingQueue = class {
15133
15223
  armTimer(scope) {
15134
15224
  return setTimeout(() => this.flush(scope), this.delayMs);
15135
15225
  }
15226
+ /** 被挡住的这一批起一个排队提示定时器;已经提示过或已有定时器就不重复起。 */
15227
+ armNotice(scope, entry) {
15228
+ const notice = this.notice;
15229
+ if (!notice || entry.noticed || entry.noticeTimer) return;
15230
+ entry.noticeTimer = setTimeout(() => {
15231
+ entry.noticeTimer = void 0;
15232
+ if (this.map.get(scope) !== entry || !this.blocked.has(scope) || entry.noticed) return;
15233
+ if (!notice.enabled()) return;
15234
+ entry.noticed = true;
15235
+ const since = this.blockedAt.get(scope) ?? entry.firstArrivedAt;
15236
+ try {
15237
+ notice.send(scope, [...entry.messages], Math.max(0, Date.now() - since));
15238
+ } catch (err) {
15239
+ log.warn("queue", "notice-failed", { scope, err: String(err) });
15240
+ }
15241
+ }, notice.afterMs);
15242
+ entry.noticeTimer.unref?.();
15243
+ }
15136
15244
  flush(scope) {
15137
15245
  const entry = this.map.get(scope);
15138
15246
  if (!entry) return;
15247
+ clearTimers(entry);
15139
15248
  this.map.delete(scope);
15140
15249
  try {
15141
15250
  this.onFlush(scope, entry.messages, {
@@ -15147,6 +15256,36 @@ var PendingQueue = class {
15147
15256
  }
15148
15257
  }
15149
15258
  };
15259
+ function clearTimers(entry) {
15260
+ if (entry.timer) clearTimeout(entry.timer);
15261
+ if (entry.noticeTimer) clearTimeout(entry.noticeTimer);
15262
+ entry.timer = void 0;
15263
+ entry.noticeTimer = void 0;
15264
+ }
15265
+ function queueNoticeText(runningMs) {
15266
+ const min = Math.max(1, Math.round(runningMs / 6e4));
15267
+ return `\u524D\u9762\u8FD8\u6709\u5BF9\u8BDD\u5728\u8DD1\uFF08\u5DF2\u8DD1 ${min} \u5206\u949F\uFF09\uFF0C\u8FD9\u6761\u4F1A\u63A5\u7740\u5904\u7406`;
15268
+ }
15269
+ var INTERRUPTED_TEXT = "\u521A\u624D\u7684\u5BF9\u8BDD\u88AB\u4E2D\u65AD\u4E86\uFF0C\u8BF7\u91CD\u53D1";
15270
+ var PendingCarry = class {
15271
+ entries = [];
15272
+ interrupted = [];
15273
+ deposit(h) {
15274
+ this.entries.push(...h.entries);
15275
+ for (const r of h.interrupted) {
15276
+ if (!this.interrupted.some((x) => x.scope === r.scope)) this.interrupted.push(r);
15277
+ }
15278
+ }
15279
+ take() {
15280
+ const h = { entries: this.entries, interrupted: this.interrupted };
15281
+ this.entries = [];
15282
+ this.interrupted = [];
15283
+ return h;
15284
+ }
15285
+ get size() {
15286
+ return this.entries.length + this.interrupted.length;
15287
+ }
15288
+ };
15150
15289
 
15151
15290
  // src/bridge/bot/scope.ts
15152
15291
  function dispatchScope(dir, m) {
@@ -16179,6 +16318,7 @@ function stringifyArgs(args) {
16179
16318
  }
16180
16319
  }).join(" ");
16181
16320
  }
16321
+ var QUEUE_NOTICE_AFTER_MS = 3e4;
16182
16322
  async function startChannel(deps) {
16183
16323
  const { cfg, agent, sessions: sessions2, sessionCatalog, workspaces, controls } = deps;
16184
16324
  const activeRuns = new ActiveRuns();
@@ -16252,10 +16392,12 @@ async function startChannel(deps) {
16252
16392
  installStreamResilience(channel);
16253
16393
  const media = new MediaCache(channel, deps.appPaths?.mediaDir);
16254
16394
  const reportInbox = new ReportInbox();
16395
+ const inFlightBatch = /* @__PURE__ */ new Map();
16255
16396
  const pending = new PendingQueue(DEBOUNCE_MS, (scope, batch, arrival) => {
16256
16397
  const firstMsg = batch[0];
16257
16398
  if (!firstMsg) return;
16258
16399
  pending.block(scope);
16400
+ inFlightBatch.set(scope, batch[batch.length - 1] ?? firstMsg);
16259
16401
  void withTrace({ chatId: firstMsg.chatId }, async () => {
16260
16402
  log.info("flush", "start", {
16261
16403
  scope,
@@ -16300,11 +16442,48 @@ async function startChannel(deps) {
16300
16442
  } catch (err) {
16301
16443
  log.fail("flush", err);
16302
16444
  } finally {
16445
+ inFlightBatch.delete(scope);
16303
16446
  pending.unblock(scope);
16304
16447
  log.info("flush", "end");
16305
16448
  }
16306
16449
  });
16450
+ }, {
16451
+ // 排队提示(intent 0115 R-13):开关每次到点时读,/config 改了立即生效
16452
+ afterMs: QUEUE_NOTICE_AFTER_MS,
16453
+ enabled: () => controls.profileConfig.preferences.queueNotice === true,
16454
+ send: (scope, messages, runningMs) => {
16455
+ const first = messages[0];
16456
+ if (!first) return;
16457
+ log.info("queue", "notice", { scope, queued: messages.length, runningSec: Math.round(runningMs / 1e3) });
16458
+ void channel.send(first.chatId, { markdown: queueNoticeText(runningMs) }, { replyTo: first.messageId, ...first.threadId ? { replyInThread: true } : {} }).catch((err) => log.warn("queue", "notice-send-failed", { scope, err: String(err) }));
16459
+ }
16307
16460
  });
16461
+ const handOffPending = (step) => {
16462
+ const carry = deps.pendingCarry;
16463
+ if (!carry) {
16464
+ pending.cancelAll();
16465
+ return;
16466
+ }
16467
+ const interrupted = [...inFlightBatch].map(([scope, m]) => ({
16468
+ scope,
16469
+ chatId: m.chatId,
16470
+ ...m.threadId ? { threadId: m.threadId } : {},
16471
+ messageId: m.messageId
16472
+ }));
16473
+ const entries = pending.drain();
16474
+ carry.deposit({ entries, interrupted });
16475
+ log.info("queue", "handoff", { step, scopes: entries.length, queued: entries.reduce((n, e) => n + e.messages.length, 0), interrupted: interrupted.length });
16476
+ };
16477
+ const adoptPending = (handoff) => {
16478
+ if (handoff.entries.length) {
16479
+ pending.adopt(handoff.entries);
16480
+ log.info("queue", "adopted", { scopes: handoff.entries.length, queued: handoff.entries.reduce((n, e) => n + e.messages.length, 0) });
16481
+ }
16482
+ for (const r of handoff.interrupted) {
16483
+ log.info("queue", "interrupted-notice", { scope: r.scope, msgId: r.messageId });
16484
+ void channel.send(r.chatId, { markdown: INTERRUPTED_TEXT }, { replyTo: r.messageId, ...r.threadId ? { replyInThread: true } : {} }).catch((err) => log.warn("queue", "interrupted-notice-failed", { scope: r.scope, err: String(err) }));
16485
+ }
16486
+ };
16308
16487
  let consecutiveReconnects = 0;
16309
16488
  const inboundMarks = deps.appPaths?.inboundStateFile ? new InboundMarkStore(deps.appPaths.inboundStateFile, cfg.accounts.app.id) : void 0;
16310
16489
  const persistedInboundAt = await inboundMarks?.load();
@@ -16542,7 +16721,7 @@ async function startChannel(deps) {
16542
16721
  keepalive.stop();
16543
16722
  meetingManager?.dispose();
16544
16723
  controls.meeting = void 0;
16545
- pending.cancelAll();
16724
+ handOffPending("disconnect");
16546
16725
  const [disconnectResult, stopAllResult, ...flushResults] = await Promise.allSettled([
16547
16726
  channel.disconnect(),
16548
16727
  activeRuns.stopAll(),
@@ -16563,7 +16742,8 @@ async function startChannel(deps) {
16563
16742
  if (disconnectResult.status === "rejected") {
16564
16743
  throw disconnectResult.reason;
16565
16744
  }
16566
- }
16745
+ },
16746
+ adoptPending
16567
16747
  };
16568
16748
  } catch (err) {
16569
16749
  for (const stop2 of armed.reverse()) {
@@ -16574,7 +16754,7 @@ async function startChannel(deps) {
16574
16754
  }
16575
16755
  meetingManager?.dispose();
16576
16756
  controls.meeting = void 0;
16577
- pending.cancelAll();
16757
+ handOffPending("startup-failed");
16578
16758
  await teardownChannel(channel);
16579
16759
  throw err;
16580
16760
  }
@@ -16753,8 +16933,9 @@ async function intakeMessage(deps) {
16753
16933
  controls
16754
16934
  });
16755
16935
  if (handled) {
16756
- const dropped = pending.cancel(scope);
16757
- log.info("intake", "command", { scope, droppedPending: dropped.length });
16936
+ const cmd = emsg.content.trim().split(/\s+/)[0] ?? "";
16937
+ const dropped = cmd === "/stop" ? pending.cancel(scope) : [];
16938
+ log.info("intake", "command", { scope, cmd, droppedPending: dropped.length });
16758
16939
  return;
16759
16940
  }
16760
16941
  const inFlightScopes = [.../* @__PURE__ */ new Set([...activeRuns.scopes(), ...pending.scopes()])];
@@ -16763,6 +16944,11 @@ async function intakeMessage(deps) {
16763
16944
  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) }));
16764
16945
  return;
16765
16946
  }
16947
+ if (emsg.chatType === "p2p" && controls.profileConfig.preferences.proofHold === true) {
16948
+ const larkCli = controls.profileConfig.larkCli;
16949
+ const gw = larkCli.perSenderUser?.enabled ? larkCli.perSenderUser : larkCli.claudeSeat && larkCli.claudeSeat.mode !== "off" ? larkCli.claudeSeat : void 0;
16950
+ if (gw) void holdProof(gw, emsg.messageId);
16951
+ }
16766
16952
  const size = pending.push(scope, emsg);
16767
16953
  log.info("intake", "queued", { scope, queueSize: size, debounceMs: DEBOUNCE_MS });
16768
16954
  }
@@ -19756,6 +19942,11 @@ var ManagedProfile = class {
19756
19942
  entry;
19757
19943
  startedAt = "";
19758
19944
  restarting = false;
19945
+ /**
19946
+ * 排队队列由 supervisor 持有(intent 0115 D-7):频道断开、启动失败时排队消息和被停掉的会话存在这里,
19947
+ * 下一个就绪的频道接着处理,不再随旧频道一起丢掉。
19948
+ */
19949
+ carry = new PendingCarry();
19759
19950
  get appId() {
19760
19951
  return this.cfg.accounts.app.id;
19761
19952
  }
@@ -19787,8 +19978,10 @@ var ManagedProfile = class {
19787
19978
  sessionCatalog: this.sessionCatalog,
19788
19979
  workspaces: this.workspaces,
19789
19980
  controls: this.controls,
19790
- appPaths: this.appPaths
19981
+ appPaths: this.appPaths,
19982
+ pendingCarry: this.carry
19791
19983
  });
19984
+ this.handOverPending(this.bridge);
19792
19985
  const botName = this.bridge.channel.botIdentity?.name;
19793
19986
  if (botName) {
19794
19987
  await updateEntry(this.entry.id, { botName }, this.appPaths.userRegistryFile).catch(
@@ -19814,6 +20007,11 @@ var ManagedProfile = class {
19814
20007
  await releaseRuntimeLocks(this.locks);
19815
20008
  this.locks = [];
19816
20009
  }
20010
+ /** 把交接处里的排队消息和被停掉的会话交给就绪的频道;频道不支持交接(测试替身)就留着。 */
20011
+ handOverPending(bridge) {
20012
+ if (!this.carry.size || !bridge.adoptPending) return;
20013
+ bridge.adoptPending(this.carry.take());
20014
+ }
19817
20015
  /** Best-effort sync unregister for the process 'exit' hook. */
19818
20016
  unregisterSelfSync() {
19819
20017
  if (this.entry) unregisterSync(this.entry.id, this.appPaths.userRegistryFile);
@@ -19889,7 +20087,8 @@ var ManagedProfile = class {
19889
20087
  sessionCatalog: this.sessionCatalog,
19890
20088
  workspaces: this.workspaces,
19891
20089
  controls: nextControls,
19892
- appPaths: nextRuntime.appPaths
20090
+ appPaths: nextRuntime.appPaths,
20091
+ pendingCarry: this.carry
19893
20092
  });
19894
20093
  try {
19895
20094
  await this.bridge.disconnect();
@@ -19897,6 +20096,7 @@ var ManagedProfile = class {
19897
20096
  log.warn("supervisor", "old-disconnect-failed", { profile: this.profile, err: String(err) });
19898
20097
  }
19899
20098
  this.bridge = nextBridge;
20099
+ this.handOverPending(nextBridge);
19900
20100
  await updateEntry(
19901
20101
  this.entry.id,
19902
20102
  {
@@ -19919,6 +20119,7 @@ var ManagedProfile = class {
19919
20119
  this.controls = nextControls;
19920
20120
  } catch (err) {
19921
20121
  log.warn("supervisor", "restart-failed", { profile: this.profile, err: String(err) });
20122
+ if (this.bridge) this.handOverPending(this.bridge);
19922
20123
  throw err;
19923
20124
  } finally {
19924
20125
  if (nextAppLock) await nextAppLock.release().catch(() => void 0);
@@ -20275,7 +20476,7 @@ function openBrowser(url) {
20275
20476
  }
20276
20477
 
20277
20478
  // src/bridge/cli/commands/user-gateway.ts
20278
- import { spawnSync as spawnSync5 } from "child_process";
20479
+ import { spawnSync as spawnSync4 } from "child_process";
20279
20480
  import { existsSync as existsSync13 } from "fs";
20280
20481
  import { join as join32 } from "path";
20281
20482
 
@@ -20284,6 +20485,8 @@ import { spawn as spawn4 } from "child_process";
20284
20485
  var DB_QUERY_TIMEOUT_MS = 16e4;
20285
20486
  var TASK_HANDLE_TTL_MS = 150 * 6e4;
20286
20487
  var SQL_LOG_MAX = 2e3;
20488
+ var KILL_GRACE_MS = 5e3;
20489
+ var QUEUE_NOTE = /^(排队 \d+ 秒,前面 \d+ 条)$/;
20287
20490
  var LOCK_WAIT_SEC = 60;
20288
20491
  var DB_NAME = /^[a-z0-9_-]{1,40}$/;
20289
20492
  function dbFromEnv(env, cmd = "") {
@@ -20300,18 +20503,25 @@ function realDbRunner(cmd) {
20300
20503
  let stdout = "";
20301
20504
  let stderr = "";
20302
20505
  let timedOut = false;
20506
+ let killTimer;
20303
20507
  const t = setTimeout(() => {
20304
20508
  timedOut = true;
20305
20509
  p3.kill("SIGTERM");
20510
+ killTimer = setTimeout(() => {
20511
+ if (p3.exitCode === null && p3.signalCode === null) p3.kill("SIGKILL");
20512
+ }, KILL_GRACE_MS);
20513
+ killTimer.unref();
20306
20514
  }, timeoutMs);
20307
20515
  p3.stdout.on("data", (d) => stdout += d.toString("utf8"));
20308
20516
  p3.stderr.on("data", (d) => stderr += d.toString("utf8"));
20309
20517
  p3.on("error", (err) => {
20310
20518
  clearTimeout(t);
20519
+ if (killTimer) clearTimeout(killTimer);
20311
20520
  resolve3({ code: null, stdout, stderr: String(err), timedOut });
20312
20521
  });
20313
20522
  p3.on("close", (code) => {
20314
20523
  clearTimeout(t);
20524
+ if (killTimer) clearTimeout(killTimer);
20315
20525
  resolve3({ code, stdout, stderr, timedOut });
20316
20526
  });
20317
20527
  });
@@ -20323,7 +20533,10 @@ function csvRows(csv) {
20323
20533
  function toResult(r) {
20324
20534
  const detail = r.stderr.trim().slice(0, 500);
20325
20535
  if (r.timedOut) return { status: "failed", detail: "\u67E5\u8BE2\u8D85\u65F6" };
20326
- if (r.code === 0) return { status: "ok", csv: r.stdout };
20536
+ if (r.code === 0) {
20537
+ const note = r.stderr.split("\n").map((l) => l.trim()).find((l) => QUEUE_NOTE.test(l));
20538
+ return note ? { status: "ok", csv: r.stdout, note } : { status: "ok", csv: r.stdout };
20539
+ }
20327
20540
  if (r.code === 2) return { status: "rejected", detail };
20328
20541
  if (r.code === 3) return { status: "busy" };
20329
20542
  return { status: "failed", detail };
@@ -20331,7 +20544,7 @@ function toResult(r) {
20331
20544
 
20332
20545
  // src/bridge/user-gateway/gateway.ts
20333
20546
  import { createHash as createHash9, randomBytes as randomBytes11 } from "crypto";
20334
- import { existsSync as existsSync12, rmSync as rmSync5 } from "fs";
20547
+ import { existsSync as existsSync12, readFileSync as readFileSync9, renameSync as renameSync7, rmSync as rmSync5, writeFileSync as writeFileSync8 } from "fs";
20335
20548
  import { mkdir as mkdir19, readdir as readdir6, readFile as readFileFs, rm as rm14, stat as stat8, writeFile as writeFile9 } from "fs/promises";
20336
20549
  import { join as join31 } from "path";
20337
20550
 
@@ -20830,7 +21043,9 @@ var MAX_TMP_BYTES = 500 * 1024 * 1024;
20830
21043
  var DOWNLOAD_TIMEOUT_MS = 6e4;
20831
21044
  var BASE_MAX_CHARS = 1e5;
20832
21045
  var MAINTENANCE_MS = 6e4;
20833
- var USED_TTL_MS = MESSAGE_MAX_AGE_MS + CLOCK_SKEW_MS + 6e4;
21046
+ var PROOF_HOLD_MS = 60 * 6e4;
21047
+ var USED_TTL_MS = PROOF_HOLD_MS + 6e4 + CLOCK_SKEW_MS;
21048
+ var PROOF_HOLDS_FILE = "proof-holds.json";
20834
21049
  var AUTH_POLL_MS = 5e3;
20835
21050
  var AUTH_MAX_MS = 10 * 6e4;
20836
21051
  var RATE_LIMIT_BACKOFF_MS = [2e3, 5e3, 1e4];
@@ -21006,6 +21221,9 @@ function createGateway(opts) {
21006
21221
  log.warn("user-gateway", event, { api, reason, runId: g?.runId, agoSec: g ? Math.round((now() - g.at) / 1e3) : void 0 });
21007
21222
  }
21008
21223
  const used = /* @__PURE__ */ new Map();
21224
+ const holds = /* @__PURE__ */ new Map();
21225
+ const holdsFile = join31(opts.stateDir, PROOF_HOLDS_FILE);
21226
+ loadProofState();
21009
21227
  const issuedFor = /* @__PURE__ */ new Map();
21010
21228
  const inFlight = /* @__PURE__ */ new Set();
21011
21229
  const pendingAuth = /* @__PURE__ */ new Map();
@@ -21105,9 +21323,55 @@ function createGateway(opts) {
21105
21323
  expired = true;
21106
21324
  }
21107
21325
  if (expired) void cleanupTmp();
21108
- for (const [m, until] of used) if (until <= t) used.delete(m);
21326
+ let changed = false;
21327
+ for (const [m, until] of used)
21328
+ if (until <= t) {
21329
+ used.delete(m);
21330
+ changed = true;
21331
+ }
21332
+ for (const [m, h] of holds)
21333
+ if (h.at + PROOF_HOLD_MS <= t) {
21334
+ holds.delete(m);
21335
+ changed = true;
21336
+ }
21337
+ if (changed) saveProofState();
21109
21338
  for (const [m, v] of issuedFor) if (v.until <= t) issuedFor.delete(m);
21110
21339
  }
21340
+ function loadProofState() {
21341
+ let raw;
21342
+ try {
21343
+ raw = JSON.parse(readFileSync9(holdsFile, "utf8"));
21344
+ } catch (err) {
21345
+ if (err.code !== "ENOENT") log.warn("user-gateway", "proof-state.unreadable", { detail: String(err) });
21346
+ return;
21347
+ }
21348
+ const t = now();
21349
+ if (!isRecord6(raw)) return;
21350
+ if (isRecord6(raw.used)) {
21351
+ for (const [k, v] of Object.entries(raw.used)) if (typeof v === "number" && v > t) used.set(k, v);
21352
+ }
21353
+ if (isRecord6(raw.holds)) {
21354
+ for (const [k, v] of Object.entries(raw.holds)) {
21355
+ if (!MESSAGE_ID.test(k) || !isRecord6(v)) continue;
21356
+ const { sender, chat, at } = v;
21357
+ if (typeof sender === "string" && typeof chat === "string" && typeof at === "number" && at + PROOF_HOLD_MS > t) holds.set(k, { sender, chat, at });
21358
+ }
21359
+ }
21360
+ log.info("user-gateway", "proof-state.loaded", { holds: holds.size, used: used.size });
21361
+ }
21362
+ function saveProofState() {
21363
+ const tmp = `${holdsFile}.${process.pid}.tmp`;
21364
+ try {
21365
+ writeFileSync8(tmp, JSON.stringify({ holds: Object.fromEntries(holds), used: Object.fromEntries(used) }), { mode: 384 });
21366
+ renameSync7(tmp, holdsFile);
21367
+ } catch (err) {
21368
+ log.warn("user-gateway", "proof-state.write-failed", { detail: String(err) });
21369
+ try {
21370
+ rmSync5(tmp, { force: true });
21371
+ } catch {
21372
+ }
21373
+ }
21374
+ }
21111
21375
  async function verify(messageId, purpose, requireP2p = true) {
21112
21376
  sweep();
21113
21377
  const key = `${purpose}:${messageId}`;
@@ -21121,6 +21385,7 @@ function createGateway(opts) {
21121
21385
  if (typeof v === "string") return v;
21122
21386
  if (requireP2p && !v.p2p) return "not_p2p";
21123
21387
  used.set(key, now() + USED_TTL_MS);
21388
+ saveProofState();
21124
21389
  return v;
21125
21390
  } catch (err) {
21126
21391
  log.warn("user-gateway", "verify.failed", { messageId, detail: String(err) });
@@ -21154,7 +21419,7 @@ function createGateway(opts) {
21154
21419
  inFlight.delete(key);
21155
21420
  }
21156
21421
  }
21157
- async function check2(messageId) {
21422
+ async function check2(messageId, hold = false) {
21158
21423
  const msg = await asApp(["api", "GET", `/open-apis/im/v1/messages/${messageId}`, "--as", "bot"]);
21159
21424
  const mjson = parseJson4(msg.stdout);
21160
21425
  const item = isRecord6(mjson) && isRecord6(mjson.data) && Array.isArray(mjson.data.items) ? mjson.data.items[0] : void 0;
@@ -21168,8 +21433,17 @@ function createGateway(opts) {
21168
21433
  }
21169
21434
  const created = Number(item.create_time);
21170
21435
  const t = now();
21171
- if (!Number.isFinite(created) || t - created > MESSAGE_MAX_AGE_MS || created - t > CLOCK_SKEW_MS) return "stale";
21172
21436
  const chatId = typeof item.chat_id === "string" ? item.chat_id : "";
21437
+ if (!Number.isFinite(created) || created - t > CLOCK_SKEW_MS) return "stale";
21438
+ if (t - created > MESSAGE_MAX_AGE_MS) {
21439
+ const h = hold ? void 0 : holds.get(messageId);
21440
+ if (!h || h.at + PROOF_HOLD_MS <= t) return "stale";
21441
+ if (h.sender !== sender.id || h.chat !== chatId) {
21442
+ log.warn("user-gateway", "proof-hold.mismatch", { messageId });
21443
+ return "stale";
21444
+ }
21445
+ log.info("user-gateway", "proof-hold.used", { messageId, heldMin: Math.round((t - h.at) / 6e4) });
21446
+ }
21173
21447
  if (!CHAT_ID.test(chatId)) return "not_found";
21174
21448
  const chat = await asApp(["api", "GET", `/open-apis/im/v1/chats/${chatId}`, "--as", "bot"]);
21175
21449
  const cjson = parseJson4(chat.stdout);
@@ -21183,7 +21457,7 @@ function createGateway(opts) {
21183
21457
  const body = parseJson4(item.body.content);
21184
21458
  if (isRecord6(body) && typeof body.text === "string") text = body.text;
21185
21459
  }
21186
- return { openId: sender.id, p2p: mode === "p2p", ...text !== void 0 ? { text } : {} };
21460
+ return { openId: sender.id, p2p: mode === "p2p", chatId, ...text !== void 0 ? { text } : {} };
21187
21461
  }
21188
21462
  async function sendAuthCard(openId, url) {
21189
21463
  const card = {
@@ -21425,6 +21699,37 @@ function createGateway(opts) {
21425
21699
  }
21426
21700
  }
21427
21701
  return {
21702
+ /**
21703
+ * POST /proof/hold(intent 0115 D-6):消息一到 bridge 就来登记。按现有规则(发送人是用户、2 分钟内、会话可读)核对,
21704
+ * 通过就记下 messageId → 发送人、会话、登记时间并存盘。已登记的不刷新时间。登记本身不算「用过」任何用途。
21705
+ */
21706
+ async proofHold(input) {
21707
+ let messageId;
21708
+ try {
21709
+ messageId = str2(input, "messageId", MESSAGE_ID);
21710
+ } catch {
21711
+ return { status: "bad_request" };
21712
+ }
21713
+ sweep();
21714
+ const prev = holds.get(messageId);
21715
+ if (prev) return { status: "held", heldAt: prev.at, expiresAt: prev.at + PROOF_HOLD_MS };
21716
+ let v;
21717
+ try {
21718
+ v = await check2(messageId, true);
21719
+ } catch (err) {
21720
+ log.warn("user-gateway", "verify.failed", { messageId, detail: String(err) });
21721
+ return { status: "lark_error" };
21722
+ }
21723
+ if (typeof v === "string") {
21724
+ log.info("user-gateway", "proof-hold.refused", { messageId, result: v });
21725
+ return { status: v };
21726
+ }
21727
+ const at = now();
21728
+ holds.set(messageId, { sender: v.openId, chat: v.chatId, at });
21729
+ saveProofState();
21730
+ log.info("user-gateway", "proof-hold.held", { messageId, sender: tail6(v.openId) });
21731
+ return { status: "held", heldAt: at, expiresAt: at + PROOF_HOLD_MS };
21732
+ },
21428
21733
  /** POST /handles:核实提问人(私聊或群里的消息),发句柄;没授权就发卡片并返回 need_auth,查库开着时同一轮仍带只能查库的句柄(intent 0068)。 */
21429
21734
  async requestHandle(input) {
21430
21735
  let messageId, runId;
@@ -21489,7 +21794,7 @@ function createGateway(opts) {
21489
21794
  sweep();
21490
21795
  const h = handles.get(handle2);
21491
21796
  if (!h) noteExpired("read.expired", api, handle2);
21492
- if (!h || h.kind !== "dm") return { status: "expired" };
21797
+ if (!h || h.kind !== "dm" && !(h.kind === "task" && h.read)) return { status: "expired" };
21493
21798
  if (!h.read) {
21494
21799
  log.info("user-gateway", "read.need-auth", { identity: "user", sender: tail6(h.openId), messageId: h.messageId, runId: h.runId, api, detail: "handle-without-read" });
21495
21800
  return { status: "need_auth" };
@@ -21633,6 +21938,7 @@ function createGateway(opts) {
21633
21938
  /**
21634
21939
  * POST /db/task-handle:调度的只读运行(只读分析、出文档、补报告)起 claude 前凭任务申请查库句柄(intent 0049 R-04)。
21635
21940
  * 负责人得是这个任务的 assignee(网关向飞书核对,同 0048 的 /claude/task-token);不看私聊查库名单(spec D-3)。
21941
+ * 带 userRead: true(intent 0113 R-09,只给查证运行):负责人已授权就签 read: true 的读句柄,查库关着也能签;没授权回 need_auth,不发授权卡片、不签句柄。
21636
21942
  * 评测(intent 0050,带 eval: true):评测的任务号不是真飞书任务,不带 taskGuid,只看查库总开关(intent 0068 起没有名单),日志记 task=eval。
21637
21943
  */
21638
21944
  async dbTaskHandle(input) {
@@ -21645,7 +21951,9 @@ function createGateway(opts) {
21645
21951
  } catch {
21646
21952
  return { status: "bad_request" };
21647
21953
  }
21648
- if (!db.enabled) return { status: "off" };
21954
+ const userRead = input.userRead === true;
21955
+ if (isEval && userRead) return { status: "bad_request" };
21956
+ if (!db.enabled && !userRead) return { status: "off" };
21649
21957
  if (taskGuid !== null) {
21650
21958
  const assignees = await taskAssignees(taskGuid);
21651
21959
  if (assignees === "lark_error") return { status: "lark_error" };
@@ -21654,10 +21962,14 @@ function createGateway(opts) {
21654
21962
  return { status: "not_assignee" };
21655
21963
  }
21656
21964
  }
21965
+ if (userRead && !isAuthorized(openId)) {
21966
+ log.info("user-gateway", "db.handle-refused", { sender: tail6(openId), runId, result: "need_auth" });
21967
+ return { status: "need_auth" };
21968
+ }
21657
21969
  const handle2 = randomBytes11(32).toString("base64url");
21658
21970
  const expiresAt = now() + TASK_HANDLE_TTL_MS;
21659
- handles.set(handle2, { openId, messageId: "", runId, expiresAt, kind: "task", db: true, read: false });
21660
- log.info("user-gateway", "db.handle-issued", { sender: tail6(openId), runId, task: taskGuid ?? "eval" });
21971
+ handles.set(handle2, { openId, messageId: "", runId, expiresAt, kind: "task", db: db.enabled, read: userRead });
21972
+ log.info("user-gateway", "db.handle-issued", { sender: tail6(openId), runId, task: taskGuid ?? "eval", read: userRead });
21661
21973
  return { status: "ok", handle: handle2, expiresAt };
21662
21974
  },
21663
21975
  /** POST /db/query:凭句柄替 agent 查一条,每次记一条 db.query(intent 0049 R-01、R-03、R-05)。 */
@@ -21698,6 +22010,7 @@ var MAX_BODY = 16 * 1024;
21698
22010
  var CLAUDE_ROUTES = /* @__PURE__ */ new Set(["/claude/token", "/claude/task-token", "/claude/ready", "/claude/login-submit", "/claude/logout"]);
21699
22011
  var DB_TASK_HANDLE = "/db/task-handle";
21700
22012
  var DB_QUERY = "/db/query";
22013
+ var PROOF_HOLD = "/proof/hold";
21701
22014
  var digest = (s) => createHash10("sha256").update(s).digest();
21702
22015
  function tokenOk(given, expected) {
21703
22016
  if (typeof given !== "string" || !given) return false;
@@ -21741,7 +22054,7 @@ function createGatewayServer(opts) {
21741
22054
  const method = req.method ?? "GET";
21742
22055
  if (method === "GET" && path === "/healthz") return send2(res, 200, { status: "ok" });
21743
22056
  const claude = method === "POST" && (CLAUDE_ROUTES.has(path) || path === DB_TASK_HANDLE);
21744
- const admin = claude || method === "POST" && (path === "/handles" || path === "/revoke") || method === "DELETE" && path.startsWith("/handles/");
22057
+ const admin = claude || method === "POST" && (path === "/handles" || path === "/revoke" || path === PROOF_HOLD) || method === "DELETE" && path.startsWith("/handles/");
21745
22058
  if (admin) {
21746
22059
  if (!tokenOk(req.headers["x-gateway-token"], expected)) {
21747
22060
  log.warn("user-gateway", "request.unauthorized", { method, route: path.startsWith("/handles/") ? "handles/:runId" : path.slice(1) });
@@ -21758,6 +22071,7 @@ function createGatewayServer(opts) {
21758
22071
  if (path === "/claude/ready") return send2(res, 200, await gateway.claudeReady(body));
21759
22072
  if (path === "/claude/login-submit") return send2(res, 200, await gateway.claudeLoginSubmit(body));
21760
22073
  if (path === "/claude/logout") return send2(res, 200, await gateway.claudeLogout(body));
22074
+ if (path === PROOF_HOLD) return send2(res, 200, await gateway.proofHold(body));
21761
22075
  if (path === "/handles") return send2(res, 200, await gateway.requestHandle(body));
21762
22076
  return send2(res, 200, await gateway.revoke(body));
21763
22077
  }
@@ -21799,7 +22113,7 @@ function createGatewayServer(opts) {
21799
22113
  function fetchToken(cmd) {
21800
22114
  const [bin, ...args] = cmd.trim().split(/\s+/);
21801
22115
  if (!bin) throw new Error("--token-cmd \u4E3A\u7A7A");
21802
- const r = spawnSync5(bin, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 3e4 });
22116
+ const r = spawnSync4(bin, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 3e4 });
21803
22117
  const value = r.status === 0 ? r.stdout.trim() : "";
21804
22118
  if (!value) throw new Error(`\u53D6\u7F51\u5173\u53E3\u4EE4\u5931\u8D25\uFF08${bin} \u9000\u51FA\u7801 ${r.status}\uFF09`);
21805
22119
  return value;