aai-lark-bridge 0.2.51 → 0.2.54

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.51",
7
+ version: "0.2.54",
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",
@@ -7108,7 +7108,7 @@ import { randomBytes as randomBytes5 } from "crypto";
7108
7108
  // src/bridge/user-gateway/claude-seat.ts
7109
7109
  import { spawn } from "child_process";
7110
7110
  import { randomBytes as randomBytes4 } from "crypto";
7111
- import { existsSync as existsSync6, readFileSync as readFileSync3 } from "fs";
7111
+ import { existsSync as existsSync6, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
7112
7112
  import { mkdir as mkdir13, mkdtemp, rm as rm11 } from "fs/promises";
7113
7113
  import { tmpdir as tmpdir4 } from "os";
7114
7114
  import { join as join19 } from "path";
@@ -7133,6 +7133,40 @@ function readCredentials(dir) {
7133
7133
  return void 0;
7134
7134
  }
7135
7135
  }
7136
+ function forceExpire(dir, nowMs) {
7137
+ const f = join19(dir, ".credentials.json");
7138
+ const noop2 = () => {
7139
+ };
7140
+ let raw;
7141
+ let j;
7142
+ try {
7143
+ raw = readFileSync3(f, "utf8");
7144
+ j = JSON.parse(raw);
7145
+ } catch {
7146
+ return noop2;
7147
+ }
7148
+ const o = j.claudeAiOauth;
7149
+ if (!o || typeof o.expiresAt !== "number" || o.expiresAt <= nowMs) return noop2;
7150
+ const original = o.expiresAt;
7151
+ const forced = nowMs - 1e3;
7152
+ try {
7153
+ o.expiresAt = forced;
7154
+ writeFileSync3(f, JSON.stringify(j), { mode: 384 });
7155
+ } catch {
7156
+ return noop2;
7157
+ }
7158
+ return () => {
7159
+ try {
7160
+ const cur = JSON.parse(readFileSync3(f, "utf8"));
7161
+ const c = cur.claudeAiOauth;
7162
+ if (c && c.expiresAt === forced) {
7163
+ c.expiresAt = original;
7164
+ writeFileSync3(f, JSON.stringify(cur), { mode: 384 });
7165
+ }
7166
+ } catch {
7167
+ }
7168
+ };
7169
+ }
7136
7170
  function covers(sw, openId) {
7137
7171
  return sw.mode === "all" || sw.mode === "list" && sw.list.includes(openId);
7138
7172
  }
@@ -7248,7 +7282,9 @@ function createClaudeSeat(opts) {
7248
7282
  const recent = now() - (refreshedAt.get(openId) ?? -Infinity) < REFRESH_COOLDOWN_MS && c.expiresAt - now() >= MIN_AFTER_REFRESH_MS;
7249
7283
  if (c.expiresAt - now() < MIN_TOKEN_LEFT_MS && !recent) {
7250
7284
  const attempt = async (n) => {
7285
+ const restore = forceExpire(dir, now());
7251
7286
  const r = normalizeRefresh(await opts.cli.refresh(dir).catch((err) => ({ ok: false, spawnError: scrubOutput(String(err)) })));
7287
+ restore();
7252
7288
  const cur = readCredentials(dir);
7253
7289
  const left = cur ? cur.expiresAt - now() : 0;
7254
7290
  const good = r.ok && !!cur && left >= MIN_AFTER_REFRESH_MS;
@@ -7495,23 +7531,46 @@ function realClaudeCli(binary = process.env.SDLC_REAL_CLAUDE || "claude") {
7495
7531
  }
7496
7532
 
7497
7533
  // src/bridge/bot/user-read.ts
7498
- import { spawnSync as spawnSync4 } from "child_process";
7534
+ import { execFile } from "child_process";
7499
7535
  import { randomUUID } from "crypto";
7500
7536
  var HANDLE_ENV = "AAI_USER_READ_HANDLE";
7501
7537
  var GATEWAY_ENV = "AAI_USER_READ_GATEWAY";
7502
7538
  var REVOKE_TEXT = "\u64A4\u9500\u6388\u6743";
7503
7539
  var TIMEOUT_MS = 6e4;
7504
- function readTokenByCommand(command) {
7540
+ var TOKEN_CACHE_MS = 10 * 6e4;
7541
+ var tokenCache = /* @__PURE__ */ new Map();
7542
+ var tokenInFlight = /* @__PURE__ */ new Map();
7543
+ function runTokenCommand(command) {
7505
7544
  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;
7545
+ if (!bin) return Promise.reject(new Error("tokenCommand \u4E3A\u7A7A"));
7546
+ return new Promise((resolve3, reject4) => {
7547
+ execFile(bin, args, { encoding: "utf8", timeout: 15e3, maxBuffer: 64 * 1024 }, (err, stdout) => {
7548
+ const value = err ? "" : String(stdout).trim();
7549
+ if (!value) {
7550
+ const code = err && typeof err.code !== "undefined" ? String(err.code) : "0";
7551
+ reject4(new Error(`\u53D6\u7F51\u5173\u53E3\u4EE4\u5931\u8D25\uFF08${bin} \u9000\u51FA\u7801 ${code}\uFF09`));
7552
+ return;
7553
+ }
7554
+ resolve3(value);
7555
+ });
7556
+ });
7557
+ }
7558
+ async function readTokenByCommand(command, now = Date.now) {
7559
+ const hit = tokenCache.get(command);
7560
+ if (hit && hit.until > now()) return hit.value;
7561
+ let p3 = tokenInFlight.get(command);
7562
+ if (!p3) {
7563
+ p3 = runTokenCommand(command).then((value) => {
7564
+ tokenCache.set(command, { value, until: now() + TOKEN_CACHE_MS });
7565
+ return value;
7566
+ }).finally(() => tokenInFlight.delete(command));
7567
+ tokenInFlight.set(command, p3);
7568
+ }
7569
+ return p3;
7511
7570
  }
7512
7571
  async function callGateway(cfg, method, path, body, deps) {
7513
7572
  const doFetch = deps.fetch ?? fetch;
7514
- const pass = (deps.readToken ?? readTokenByCommand)(cfg.tokenCommand);
7573
+ const pass = await (deps.readToken ?? readTokenByCommand)(cfg.tokenCommand);
7515
7574
  const res = await doFetch(`${cfg.gatewayUrl}${path}`, {
7516
7575
  method,
7517
7576
  headers: { "content-type": "application/json", "x-gateway-token": pass },
@@ -7519,9 +7578,22 @@ async function callGateway(cfg, method, path, body, deps) {
7519
7578
  signal: AbortSignal.timeout(TIMEOUT_MS)
7520
7579
  });
7521
7580
  const json = await res.json().catch(() => ({}));
7581
+ if (res.status === 401) tokenCache.delete(cfg.tokenCommand);
7522
7582
  if (!res.ok) throw new Error(`\u7F51\u5173\u8FD4\u56DE ${res.status} ${String(json.status ?? "")}`);
7523
7583
  return json;
7524
7584
  }
7585
+ async function holdProof(cfg, messageId, deps = {}) {
7586
+ try {
7587
+ const r = await callGateway(cfg, "POST", "/proof/hold", { messageId }, deps);
7588
+ const status = String(r.status ?? "");
7589
+ if (status === "held") log.info("user-read", "proof-held", { messageId });
7590
+ else log.warn("user-read", "proof-hold-refused", { messageId, status });
7591
+ return status;
7592
+ } catch (err) {
7593
+ log.warn("user-read", "gateway-failed", { messageId, step: "proof-hold", detail: String(err) });
7594
+ return "error";
7595
+ }
7596
+ }
7525
7597
  var PROMPT_TOOL = `## \u7528\u63D0\u95EE\u4EBA\u7684\u8EAB\u4EFD\u53EA\u8BFB\uFF08aai-user-read\uFF09
7526
7598
 
7527
7599
  \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
@@ -7783,7 +7855,7 @@ function modelLabel(agentKind, value) {
7783
7855
  // src/bridge/bot/router.ts
7784
7856
  import { spawn as spawn2 } from "child_process";
7785
7857
  import { randomBytes as randomBytes6 } from "crypto";
7786
- import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "fs";
7858
+ import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
7787
7859
  import { isAbsolute as isAbsolute2, join as join20 } from "path";
7788
7860
  var SAFE = /^[A-Za-z0-9_.:@+-]{1,200}$/;
7789
7861
  var ROUTER_TIMEOUT_MS = 6e4;
@@ -7898,7 +7970,7 @@ function writePending(workspace, pending) {
7898
7970
  const dir = join20(stateDir(workspace), "route-pending");
7899
7971
  mkdirSync3(dir, { recursive: true, mode: 448 });
7900
7972
  const f = join20(dir, `${pending.nonce}.json`);
7901
- writeFileSync3(`${f}.new`, JSON.stringify(pending), { mode: 384 });
7973
+ writeFileSync4(`${f}.new`, JSON.stringify(pending), { mode: 384 });
7902
7974
  renameSync2(`${f}.new`, f);
7903
7975
  return true;
7904
7976
  }
@@ -7977,7 +8049,7 @@ import {
7977
8049
  rmSync as rmSync2,
7978
8050
  statSync,
7979
8051
  unlinkSync as unlinkSync2,
7980
- writeFileSync as writeFileSync4
8052
+ writeFileSync as writeFileSync5
7981
8053
  } from "fs";
7982
8054
  import { basename as basename5, dirname as dirname14, isAbsolute as isAbsolute3, join as join21, sep as sep2 } from "path";
7983
8055
  var BINDING_VERSION = 1;
@@ -8096,7 +8168,7 @@ function registerDispatchRoot(dir, rootMessageId, chatId, now = /* @__PURE__ */
8096
8168
  const file = join21(folder, `${rootMessageId}.json`);
8097
8169
  if (existsSync8(file)) return;
8098
8170
  const tmp = `${file}.${randomBytes7(4).toString("hex")}.tmp`;
8099
- writeFileSync4(tmp, `${JSON.stringify({ chat_id: chatId, at: now.toISOString() })}
8171
+ writeFileSync5(tmp, `${JSON.stringify({ chat_id: chatId, at: now.toISOString() })}
8100
8172
  `);
8101
8173
  renameSync3(tmp, file);
8102
8174
  pruneDispatchRoots(folder, now);
@@ -8175,7 +8247,7 @@ function switchToTask(rawConfig, chatId, senderOpenId, taskId, { messageId = nul
8175
8247
  if (from) queue.unshift(from);
8176
8248
  const next = { ...doc, active: item, queue, updated_at: now.toISOString() };
8177
8249
  const tmp = `${file}.new-${process.pid}`;
8178
- writeFileSync4(tmp, JSON.stringify(next, null, 2), { mode: 384 });
8250
+ writeFileSync5(tmp, JSON.stringify(next, null, 2), { mode: 384 });
8179
8251
  renameSync3(tmp, file);
8180
8252
  return { from: from?.task_id ?? null, to: taskId };
8181
8253
  });
@@ -8186,7 +8258,7 @@ function switchToTask(rawConfig, chatId, senderOpenId, taskId, { messageId = nul
8186
8258
  const eventsDir = join21(cfg.dir, "events");
8187
8259
  mkdirSync4(eventsDir, { recursive: true });
8188
8260
  const tmp = join21(eventsDir, `.${randomBytes7(6).toString("hex")}.tmp`);
8189
- writeFileSync4(tmp, JSON.stringify(event));
8261
+ writeFileSync5(tmp, JSON.stringify(event));
8190
8262
  renameSync3(tmp, join21(eventsDir, `switch-${now.getTime()}-${randomBytes7(4).toString("hex")}.json`));
8191
8263
  eventWritten = true;
8192
8264
  } catch {
@@ -8229,7 +8301,7 @@ function writeBudgetHitEvent(dir, event) {
8229
8301
  return false;
8230
8302
  }
8231
8303
  const tmp = join21(eventsDir, `.${randomBytes7(6).toString("hex")}.tmp`);
8232
- writeFileSync4(tmp, JSON.stringify(event));
8304
+ writeFileSync5(tmp, JSON.stringify(event));
8233
8305
  try {
8234
8306
  linkSync(tmp, file);
8235
8307
  return true;
@@ -8284,7 +8356,7 @@ function dropTaskEvent(workspace, taskId, event, route3) {
8284
8356
  const key = createHash2("sha256").update(`${taskId}\0${event.id}`).digest("hex").slice(0, 32);
8285
8357
  const target = join21(inbox, `${key}.json`);
8286
8358
  const tmp = `${target}.new-${process.pid}`;
8287
- writeFileSync4(tmp, JSON.stringify({ task_id: taskId, event, ...route3 ? { route: route3 } : {} }), { mode: 384 });
8359
+ writeFileSync5(tmp, JSON.stringify({ task_id: taskId, event, ...route3 ? { route: route3 } : {} }), { mode: 384 });
8288
8360
  renameSync3(tmp, target);
8289
8361
  return true;
8290
8362
  }
@@ -8329,7 +8401,7 @@ function taskRunHooks(input) {
8329
8401
 
8330
8402
  // src/bridge/binding/awaiting.ts
8331
8403
  import { createHash as createHash3 } from "crypto";
8332
- import { existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync6, renameSync as renameSync4, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
8404
+ import { existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync6, renameSync as renameSync4, rmSync as rmSync3, writeFileSync as writeFileSync6 } from "fs";
8333
8405
  import { join as join22 } from "path";
8334
8406
  var AWAITING_TTL_MS = 24 * 36e5;
8335
8407
  var DECISION_SHOW_MAX = 200;
@@ -8364,7 +8436,7 @@ function submitDecision(dir, handoffDir, a, msg) {
8364
8436
  const file = join22(handoffDir, name);
8365
8437
  if (!existsSync9(file)) {
8366
8438
  const tmp = join22(handoffDir, `.${name}.${process.pid}.tmp`);
8367
- writeFileSync5(
8439
+ writeFileSync6(
8368
8440
  tmp,
8369
8441
  JSON.stringify({
8370
8442
  event_id: "",
@@ -13007,7 +13079,7 @@ async function lookupMessageRoot(channel, messageId) {
13007
13079
 
13008
13080
  // src/bridge/card/handoff.ts
13009
13081
  import { createHash as createHash5 } from "crypto";
13010
- import { existsSync as existsSync10, mkdirSync as mkdirSync6, renameSync as renameSync5, writeFileSync as writeFileSync6 } from "fs";
13082
+ import { existsSync as existsSync10, mkdirSync as mkdirSync6, renameSync as renameSync5, writeFileSync as writeFileSync7 } from "fs";
13011
13083
  import { isAbsolute as isAbsolute5, join as join25 } from "path";
13012
13084
  function handoffDirs(raw) {
13013
13085
  if (!raw || typeof raw !== "object") return {};
@@ -13036,7 +13108,7 @@ function tryHandoff(evt, dirs) {
13036
13108
  const file = join25(dir, name);
13037
13109
  if (existsSync10(file)) return true;
13038
13110
  const tmp = join25(dir, `.${name}.${process.pid}.tmp`);
13039
- writeFileSync6(
13111
+ writeFileSync7(
13040
13112
  tmp,
13041
13113
  JSON.stringify({
13042
13114
  event_id: eventId,
@@ -13766,10 +13838,10 @@ async function removeRejectedResolvedFiles(attachments) {
13766
13838
  }
13767
13839
 
13768
13840
  // src/bridge/bot/group-intake.ts
13769
- import { execFile } from "child_process";
13841
+ import { execFile as execFile2 } from "child_process";
13770
13842
  var GROUP_INTAKE_TIMEOUT_MS = 3e4;
13771
13843
  var defaultRunner = (bin, args, timeoutMs) => new Promise((resolve3) => {
13772
- execFile(bin, args, { encoding: "utf8", timeout: timeoutMs, maxBuffer: 1 << 20 }, (err, stdout) => {
13844
+ execFile2(bin, args, { encoding: "utf8", timeout: timeoutMs, maxBuffer: 1 << 20 }, (err, stdout) => {
13773
13845
  resolve3({ stdout: String(stdout ?? ""), ...err ? { error: err.killed ? "\u8D85\u65F6" : String(err.message ?? err) } : {} });
13774
13846
  });
13775
13847
  });
@@ -13789,7 +13861,7 @@ async function runGroupIntake(cfg, msg, run2 = defaultRunner) {
13789
13861
  if (out?.status === "created" || out?.status === "existing") {
13790
13862
  log.info("group-intake", out.status, base);
13791
13863
  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";
13864
+ 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
13865
  return `${head}\uFF1A${out.url ?? ""}
13794
13866
  ${next}`;
13795
13867
  }
@@ -14828,7 +14900,7 @@ function preview(text) {
14828
14900
 
14829
14901
  // src/bridge/bot/doc-confirmation.ts
14830
14902
  import { createHash as createHash8 } from "crypto";
14831
- import { mkdirSync as mkdirSync7, realpathSync as realpathSync2, renameSync as renameSync6, writeFileSync as writeFileSync7 } from "fs";
14903
+ import { mkdirSync as mkdirSync7, realpathSync as realpathSync2, renameSync as renameSync6, writeFileSync as writeFileSync8 } from "fs";
14832
14904
  import { isAbsolute as isAbsolute6, join as join27, sep as sep3 } from "path";
14833
14905
  import { spawn as spawn3 } from "child_process";
14834
14906
  var waking = /* @__PURE__ */ new Set();
@@ -14848,7 +14920,7 @@ function enqueueDocConfirmation(workspace, event, { selfReply = false } = {}) {
14848
14920
  const key = createHash8("sha256").update(JSON.stringify([hint.file_token, hint.comment_id, hint.reply_id])).digest("hex");
14849
14921
  const target = join27(inbox, key + ".json");
14850
14922
  const tmp = target + `.new-${process.pid}`;
14851
- writeFileSync7(tmp, JSON.stringify(hint), { mode: 384 });
14923
+ writeFileSync8(tmp, JSON.stringify(hint), { mode: 384 });
14852
14924
  renameSync6(tmp, target);
14853
14925
  if (!waking.has(root)) {
14854
14926
  waking.add(root);
@@ -15068,11 +15140,15 @@ async function httpProbe(domain) {
15068
15140
  var PendingQueue = class {
15069
15141
  map = /* @__PURE__ */ new Map();
15070
15142
  blocked = /* @__PURE__ */ new Set();
15143
+ /** scope 被挡住的起始时间:排队提示里的「已跑 N 分钟」从这里算。 */
15144
+ blockedAt = /* @__PURE__ */ new Map();
15071
15145
  delayMs;
15072
15146
  onFlush;
15073
- constructor(delayMs, onFlush) {
15147
+ notice;
15148
+ constructor(delayMs, onFlush, notice) {
15074
15149
  this.delayMs = delayMs;
15075
15150
  this.onFlush = onFlush;
15151
+ this.notice = notice;
15076
15152
  }
15077
15153
  push(scope, msg) {
15078
15154
  const existing = this.map.get(scope);
@@ -15080,51 +15156,101 @@ var PendingQueue = class {
15080
15156
  if (existing.timer) clearTimeout(existing.timer);
15081
15157
  existing.messages.push(msg);
15082
15158
  existing.timer = this.blocked.has(scope) ? void 0 : this.armTimer(scope);
15159
+ if (this.blocked.has(scope)) this.armNotice(scope, existing);
15083
15160
  return existing.messages.length;
15084
15161
  }
15085
15162
  const behindRun = this.blocked.has(scope);
15086
- this.map.set(scope, {
15163
+ const entry = {
15087
15164
  messages: [msg],
15088
15165
  timer: behindRun ? void 0 : this.armTimer(scope),
15089
15166
  firstArrivedAt: Date.now(),
15090
15167
  behindRun
15091
- });
15168
+ };
15169
+ this.map.set(scope, entry);
15170
+ if (behindRun) this.armNotice(scope, entry);
15092
15171
  return 1;
15093
15172
  }
15094
15173
  /** 有消息在排队、或正在 flush / 运行(被 block)的 scope:还没占上 ActiveRuns 的也算。 */
15095
15174
  scopes() {
15096
15175
  return [.../* @__PURE__ */ new Set([...this.map.keys(), ...this.blocked])];
15097
15176
  }
15177
+ /** 被挡住(有一轮在 flush 或在跑)的 scope。 */
15178
+ blockedScopes() {
15179
+ return [...this.blocked];
15180
+ }
15098
15181
  cancel(scope) {
15099
15182
  const entry = this.map.get(scope);
15100
15183
  if (!entry) return [];
15101
- if (entry.timer) clearTimeout(entry.timer);
15184
+ clearTimers(entry);
15102
15185
  this.map.delete(scope);
15103
15186
  return entry.messages;
15104
15187
  }
15105
15188
  cancelAll() {
15106
- for (const entry of this.map.values()) {
15107
- if (entry.timer) clearTimeout(entry.timer);
15189
+ for (const entry of this.map.values()) clearTimers(entry);
15190
+ this.map.clear();
15191
+ this.blocked.clear();
15192
+ this.blockedAt.clear();
15193
+ }
15194
+ /**
15195
+ * 拿走全部排队消息、清掉定时器和阻塞(intent 0115 D-7):频道断开或启动失败时交给 supervisor,
15196
+ * 新频道用 {@link adopt} 接着处理,不再像 cancelAll 那样丢掉。
15197
+ */
15198
+ drain() {
15199
+ const out = [];
15200
+ for (const [scope, entry] of this.map) {
15201
+ clearTimers(entry);
15202
+ out.push({ scope, messages: entry.messages, firstArrivedAt: entry.firstArrivedAt, behindRun: entry.behindRun });
15108
15203
  }
15109
15204
  this.map.clear();
15110
15205
  this.blocked.clear();
15206
+ this.blockedAt.clear();
15207
+ return out;
15208
+ }
15209
+ /** 接住上一个频道交来的排队消息:排在这个 scope 已有消息的前面,没被挡住的照常起去抖定时器。 */
15210
+ adopt(snapshots) {
15211
+ for (const snap of snapshots) {
15212
+ if (!snap.messages.length) continue;
15213
+ const existing = this.map.get(snap.scope);
15214
+ if (existing) {
15215
+ existing.messages.unshift(...snap.messages);
15216
+ existing.firstArrivedAt = Math.min(existing.firstArrivedAt, snap.firstArrivedAt);
15217
+ existing.behindRun ||= snap.behindRun;
15218
+ continue;
15219
+ }
15220
+ const blocked = this.blocked.has(snap.scope);
15221
+ const entry = {
15222
+ messages: [...snap.messages],
15223
+ timer: blocked ? void 0 : this.armTimer(snap.scope),
15224
+ firstArrivedAt: snap.firstArrivedAt,
15225
+ behindRun: snap.behindRun
15226
+ };
15227
+ this.map.set(snap.scope, entry);
15228
+ if (blocked) this.armNotice(snap.scope, entry);
15229
+ }
15111
15230
  }
15112
15231
  /** Pause the debounce timer; pushed messages keep accumulating. */
15113
15232
  block(scope) {
15114
15233
  if (this.blocked.has(scope)) return;
15115
15234
  this.blocked.add(scope);
15235
+ this.blockedAt.set(scope, Date.now());
15116
15236
  const entry = this.map.get(scope);
15117
15237
  if (entry?.timer) {
15118
15238
  clearTimeout(entry.timer);
15119
15239
  entry.timer = void 0;
15120
15240
  }
15241
+ if (entry) this.armNotice(scope, entry);
15121
15242
  log.info("queue", "blocked", { scope, queued: entry?.messages.length ?? 0 });
15122
15243
  }
15123
15244
  /** Resume the debounce timer; arms a fresh quiet window if anything queued. */
15124
15245
  unblock(scope) {
15125
15246
  if (!this.blocked.has(scope)) return;
15126
15247
  this.blocked.delete(scope);
15248
+ this.blockedAt.delete(scope);
15127
15249
  const entry = this.map.get(scope);
15250
+ if (entry?.noticeTimer) {
15251
+ clearTimeout(entry.noticeTimer);
15252
+ entry.noticeTimer = void 0;
15253
+ }
15128
15254
  log.info("queue", "unblocked", { scope, queued: entry?.messages.length ?? 0 });
15129
15255
  if (!entry || entry.messages.length === 0) return;
15130
15256
  if (entry.timer) clearTimeout(entry.timer);
@@ -15133,9 +15259,28 @@ var PendingQueue = class {
15133
15259
  armTimer(scope) {
15134
15260
  return setTimeout(() => this.flush(scope), this.delayMs);
15135
15261
  }
15262
+ /** 被挡住的这一批起一个排队提示定时器;已经提示过或已有定时器就不重复起。 */
15263
+ armNotice(scope, entry) {
15264
+ const notice = this.notice;
15265
+ if (!notice || entry.noticed || entry.noticeTimer) return;
15266
+ entry.noticeTimer = setTimeout(() => {
15267
+ entry.noticeTimer = void 0;
15268
+ if (this.map.get(scope) !== entry || !this.blocked.has(scope) || entry.noticed) return;
15269
+ if (!notice.enabled()) return;
15270
+ entry.noticed = true;
15271
+ const since = this.blockedAt.get(scope) ?? entry.firstArrivedAt;
15272
+ try {
15273
+ notice.send(scope, [...entry.messages], Math.max(0, Date.now() - since));
15274
+ } catch (err) {
15275
+ log.warn("queue", "notice-failed", { scope, err: String(err) });
15276
+ }
15277
+ }, notice.afterMs);
15278
+ entry.noticeTimer.unref?.();
15279
+ }
15136
15280
  flush(scope) {
15137
15281
  const entry = this.map.get(scope);
15138
15282
  if (!entry) return;
15283
+ clearTimers(entry);
15139
15284
  this.map.delete(scope);
15140
15285
  try {
15141
15286
  this.onFlush(scope, entry.messages, {
@@ -15147,6 +15292,36 @@ var PendingQueue = class {
15147
15292
  }
15148
15293
  }
15149
15294
  };
15295
+ function clearTimers(entry) {
15296
+ if (entry.timer) clearTimeout(entry.timer);
15297
+ if (entry.noticeTimer) clearTimeout(entry.noticeTimer);
15298
+ entry.timer = void 0;
15299
+ entry.noticeTimer = void 0;
15300
+ }
15301
+ function queueNoticeText(runningMs) {
15302
+ const min = Math.max(1, Math.round(runningMs / 6e4));
15303
+ return `\u524D\u9762\u8FD8\u6709\u5BF9\u8BDD\u5728\u8DD1\uFF08\u5DF2\u8DD1 ${min} \u5206\u949F\uFF09\uFF0C\u8FD9\u6761\u4F1A\u63A5\u7740\u5904\u7406`;
15304
+ }
15305
+ var INTERRUPTED_TEXT = "\u521A\u624D\u7684\u5BF9\u8BDD\u88AB\u4E2D\u65AD\u4E86\uFF0C\u8BF7\u91CD\u53D1";
15306
+ var PendingCarry = class {
15307
+ entries = [];
15308
+ interrupted = [];
15309
+ deposit(h) {
15310
+ this.entries.push(...h.entries);
15311
+ for (const r of h.interrupted) {
15312
+ if (!this.interrupted.some((x) => x.scope === r.scope)) this.interrupted.push(r);
15313
+ }
15314
+ }
15315
+ take() {
15316
+ const h = { entries: this.entries, interrupted: this.interrupted };
15317
+ this.entries = [];
15318
+ this.interrupted = [];
15319
+ return h;
15320
+ }
15321
+ get size() {
15322
+ return this.entries.length + this.interrupted.length;
15323
+ }
15324
+ };
15150
15325
 
15151
15326
  // src/bridge/bot/scope.ts
15152
15327
  function dispatchScope(dir, m) {
@@ -16179,6 +16354,7 @@ function stringifyArgs(args) {
16179
16354
  }
16180
16355
  }).join(" ");
16181
16356
  }
16357
+ var QUEUE_NOTICE_AFTER_MS = 3e4;
16182
16358
  async function startChannel(deps) {
16183
16359
  const { cfg, agent, sessions: sessions2, sessionCatalog, workspaces, controls } = deps;
16184
16360
  const activeRuns = new ActiveRuns();
@@ -16252,10 +16428,12 @@ async function startChannel(deps) {
16252
16428
  installStreamResilience(channel);
16253
16429
  const media = new MediaCache(channel, deps.appPaths?.mediaDir);
16254
16430
  const reportInbox = new ReportInbox();
16431
+ const inFlightBatch = /* @__PURE__ */ new Map();
16255
16432
  const pending = new PendingQueue(DEBOUNCE_MS, (scope, batch, arrival) => {
16256
16433
  const firstMsg = batch[0];
16257
16434
  if (!firstMsg) return;
16258
16435
  pending.block(scope);
16436
+ inFlightBatch.set(scope, batch[batch.length - 1] ?? firstMsg);
16259
16437
  void withTrace({ chatId: firstMsg.chatId }, async () => {
16260
16438
  log.info("flush", "start", {
16261
16439
  scope,
@@ -16300,11 +16478,48 @@ async function startChannel(deps) {
16300
16478
  } catch (err) {
16301
16479
  log.fail("flush", err);
16302
16480
  } finally {
16481
+ inFlightBatch.delete(scope);
16303
16482
  pending.unblock(scope);
16304
16483
  log.info("flush", "end");
16305
16484
  }
16306
16485
  });
16486
+ }, {
16487
+ // 排队提示(intent 0115 R-13):开关每次到点时读,/config 改了立即生效
16488
+ afterMs: QUEUE_NOTICE_AFTER_MS,
16489
+ enabled: () => controls.profileConfig.preferences.queueNotice === true,
16490
+ send: (scope, messages, runningMs) => {
16491
+ const first = messages[0];
16492
+ if (!first) return;
16493
+ log.info("queue", "notice", { scope, queued: messages.length, runningSec: Math.round(runningMs / 1e3) });
16494
+ 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) }));
16495
+ }
16307
16496
  });
16497
+ const handOffPending = (step) => {
16498
+ const carry = deps.pendingCarry;
16499
+ if (!carry) {
16500
+ pending.cancelAll();
16501
+ return;
16502
+ }
16503
+ const interrupted = [...inFlightBatch].map(([scope, m]) => ({
16504
+ scope,
16505
+ chatId: m.chatId,
16506
+ ...m.threadId ? { threadId: m.threadId } : {},
16507
+ messageId: m.messageId
16508
+ }));
16509
+ const entries = pending.drain();
16510
+ carry.deposit({ entries, interrupted });
16511
+ log.info("queue", "handoff", { step, scopes: entries.length, queued: entries.reduce((n, e) => n + e.messages.length, 0), interrupted: interrupted.length });
16512
+ };
16513
+ const adoptPending = (handoff) => {
16514
+ if (handoff.entries.length) {
16515
+ pending.adopt(handoff.entries);
16516
+ log.info("queue", "adopted", { scopes: handoff.entries.length, queued: handoff.entries.reduce((n, e) => n + e.messages.length, 0) });
16517
+ }
16518
+ for (const r of handoff.interrupted) {
16519
+ log.info("queue", "interrupted-notice", { scope: r.scope, msgId: r.messageId });
16520
+ 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) }));
16521
+ }
16522
+ };
16308
16523
  let consecutiveReconnects = 0;
16309
16524
  const inboundMarks = deps.appPaths?.inboundStateFile ? new InboundMarkStore(deps.appPaths.inboundStateFile, cfg.accounts.app.id) : void 0;
16310
16525
  const persistedInboundAt = await inboundMarks?.load();
@@ -16542,7 +16757,7 @@ async function startChannel(deps) {
16542
16757
  keepalive.stop();
16543
16758
  meetingManager?.dispose();
16544
16759
  controls.meeting = void 0;
16545
- pending.cancelAll();
16760
+ handOffPending("disconnect");
16546
16761
  const [disconnectResult, stopAllResult, ...flushResults] = await Promise.allSettled([
16547
16762
  channel.disconnect(),
16548
16763
  activeRuns.stopAll(),
@@ -16563,7 +16778,8 @@ async function startChannel(deps) {
16563
16778
  if (disconnectResult.status === "rejected") {
16564
16779
  throw disconnectResult.reason;
16565
16780
  }
16566
- }
16781
+ },
16782
+ adoptPending
16567
16783
  };
16568
16784
  } catch (err) {
16569
16785
  for (const stop2 of armed.reverse()) {
@@ -16574,7 +16790,7 @@ async function startChannel(deps) {
16574
16790
  }
16575
16791
  meetingManager?.dispose();
16576
16792
  controls.meeting = void 0;
16577
- pending.cancelAll();
16793
+ handOffPending("startup-failed");
16578
16794
  await teardownChannel(channel);
16579
16795
  throw err;
16580
16796
  }
@@ -16753,8 +16969,9 @@ async function intakeMessage(deps) {
16753
16969
  controls
16754
16970
  });
16755
16971
  if (handled) {
16756
- const dropped = pending.cancel(scope);
16757
- log.info("intake", "command", { scope, droppedPending: dropped.length });
16972
+ const cmd = emsg.content.trim().split(/\s+/)[0] ?? "";
16973
+ const dropped = cmd === "/stop" ? pending.cancel(scope) : [];
16974
+ log.info("intake", "command", { scope, cmd, droppedPending: dropped.length });
16758
16975
  return;
16759
16976
  }
16760
16977
  const inFlightScopes = [.../* @__PURE__ */ new Set([...activeRuns.scopes(), ...pending.scopes()])];
@@ -16763,6 +16980,11 @@ async function intakeMessage(deps) {
16763
16980
  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
16981
  return;
16765
16982
  }
16983
+ if (emsg.chatType === "p2p" && controls.profileConfig.preferences.proofHold === true) {
16984
+ const larkCli = controls.profileConfig.larkCli;
16985
+ const gw = larkCli.perSenderUser?.enabled ? larkCli.perSenderUser : larkCli.claudeSeat && larkCli.claudeSeat.mode !== "off" ? larkCli.claudeSeat : void 0;
16986
+ if (gw) void holdProof(gw, emsg.messageId);
16987
+ }
16766
16988
  const size = pending.push(scope, emsg);
16767
16989
  log.info("intake", "queued", { scope, queueSize: size, debounceMs: DEBOUNCE_MS });
16768
16990
  }
@@ -19756,6 +19978,11 @@ var ManagedProfile = class {
19756
19978
  entry;
19757
19979
  startedAt = "";
19758
19980
  restarting = false;
19981
+ /**
19982
+ * 排队队列由 supervisor 持有(intent 0115 D-7):频道断开、启动失败时排队消息和被停掉的会话存在这里,
19983
+ * 下一个就绪的频道接着处理,不再随旧频道一起丢掉。
19984
+ */
19985
+ carry = new PendingCarry();
19759
19986
  get appId() {
19760
19987
  return this.cfg.accounts.app.id;
19761
19988
  }
@@ -19787,8 +20014,10 @@ var ManagedProfile = class {
19787
20014
  sessionCatalog: this.sessionCatalog,
19788
20015
  workspaces: this.workspaces,
19789
20016
  controls: this.controls,
19790
- appPaths: this.appPaths
20017
+ appPaths: this.appPaths,
20018
+ pendingCarry: this.carry
19791
20019
  });
20020
+ this.handOverPending(this.bridge);
19792
20021
  const botName = this.bridge.channel.botIdentity?.name;
19793
20022
  if (botName) {
19794
20023
  await updateEntry(this.entry.id, { botName }, this.appPaths.userRegistryFile).catch(
@@ -19814,6 +20043,11 @@ var ManagedProfile = class {
19814
20043
  await releaseRuntimeLocks(this.locks);
19815
20044
  this.locks = [];
19816
20045
  }
20046
+ /** 把交接处里的排队消息和被停掉的会话交给就绪的频道;频道不支持交接(测试替身)就留着。 */
20047
+ handOverPending(bridge) {
20048
+ if (!this.carry.size || !bridge.adoptPending) return;
20049
+ bridge.adoptPending(this.carry.take());
20050
+ }
19817
20051
  /** Best-effort sync unregister for the process 'exit' hook. */
19818
20052
  unregisterSelfSync() {
19819
20053
  if (this.entry) unregisterSync(this.entry.id, this.appPaths.userRegistryFile);
@@ -19889,7 +20123,8 @@ var ManagedProfile = class {
19889
20123
  sessionCatalog: this.sessionCatalog,
19890
20124
  workspaces: this.workspaces,
19891
20125
  controls: nextControls,
19892
- appPaths: nextRuntime.appPaths
20126
+ appPaths: nextRuntime.appPaths,
20127
+ pendingCarry: this.carry
19893
20128
  });
19894
20129
  try {
19895
20130
  await this.bridge.disconnect();
@@ -19897,6 +20132,7 @@ var ManagedProfile = class {
19897
20132
  log.warn("supervisor", "old-disconnect-failed", { profile: this.profile, err: String(err) });
19898
20133
  }
19899
20134
  this.bridge = nextBridge;
20135
+ this.handOverPending(nextBridge);
19900
20136
  await updateEntry(
19901
20137
  this.entry.id,
19902
20138
  {
@@ -19919,6 +20155,7 @@ var ManagedProfile = class {
19919
20155
  this.controls = nextControls;
19920
20156
  } catch (err) {
19921
20157
  log.warn("supervisor", "restart-failed", { profile: this.profile, err: String(err) });
20158
+ if (this.bridge) this.handOverPending(this.bridge);
19922
20159
  throw err;
19923
20160
  } finally {
19924
20161
  if (nextAppLock) await nextAppLock.release().catch(() => void 0);
@@ -20275,7 +20512,7 @@ function openBrowser(url) {
20275
20512
  }
20276
20513
 
20277
20514
  // src/bridge/cli/commands/user-gateway.ts
20278
- import { spawnSync as spawnSync5 } from "child_process";
20515
+ import { spawnSync as spawnSync4 } from "child_process";
20279
20516
  import { existsSync as existsSync13 } from "fs";
20280
20517
  import { join as join32 } from "path";
20281
20518
 
@@ -20284,6 +20521,8 @@ import { spawn as spawn4 } from "child_process";
20284
20521
  var DB_QUERY_TIMEOUT_MS = 16e4;
20285
20522
  var TASK_HANDLE_TTL_MS = 150 * 6e4;
20286
20523
  var SQL_LOG_MAX = 2e3;
20524
+ var KILL_GRACE_MS = 5e3;
20525
+ var QUEUE_NOTE = /^(排队 \d+ 秒,前面 \d+ 条)$/;
20287
20526
  var LOCK_WAIT_SEC = 60;
20288
20527
  var DB_NAME = /^[a-z0-9_-]{1,40}$/;
20289
20528
  function dbFromEnv(env, cmd = "") {
@@ -20300,18 +20539,25 @@ function realDbRunner(cmd) {
20300
20539
  let stdout = "";
20301
20540
  let stderr = "";
20302
20541
  let timedOut = false;
20542
+ let killTimer;
20303
20543
  const t = setTimeout(() => {
20304
20544
  timedOut = true;
20305
20545
  p3.kill("SIGTERM");
20546
+ killTimer = setTimeout(() => {
20547
+ if (p3.exitCode === null && p3.signalCode === null) p3.kill("SIGKILL");
20548
+ }, KILL_GRACE_MS);
20549
+ killTimer.unref();
20306
20550
  }, timeoutMs);
20307
20551
  p3.stdout.on("data", (d) => stdout += d.toString("utf8"));
20308
20552
  p3.stderr.on("data", (d) => stderr += d.toString("utf8"));
20309
20553
  p3.on("error", (err) => {
20310
20554
  clearTimeout(t);
20555
+ if (killTimer) clearTimeout(killTimer);
20311
20556
  resolve3({ code: null, stdout, stderr: String(err), timedOut });
20312
20557
  });
20313
20558
  p3.on("close", (code) => {
20314
20559
  clearTimeout(t);
20560
+ if (killTimer) clearTimeout(killTimer);
20315
20561
  resolve3({ code, stdout, stderr, timedOut });
20316
20562
  });
20317
20563
  });
@@ -20323,7 +20569,10 @@ function csvRows(csv) {
20323
20569
  function toResult(r) {
20324
20570
  const detail = r.stderr.trim().slice(0, 500);
20325
20571
  if (r.timedOut) return { status: "failed", detail: "\u67E5\u8BE2\u8D85\u65F6" };
20326
- if (r.code === 0) return { status: "ok", csv: r.stdout };
20572
+ if (r.code === 0) {
20573
+ const note = r.stderr.split("\n").map((l) => l.trim()).find((l) => QUEUE_NOTE.test(l));
20574
+ return note ? { status: "ok", csv: r.stdout, note } : { status: "ok", csv: r.stdout };
20575
+ }
20327
20576
  if (r.code === 2) return { status: "rejected", detail };
20328
20577
  if (r.code === 3) return { status: "busy" };
20329
20578
  return { status: "failed", detail };
@@ -20331,7 +20580,7 @@ function toResult(r) {
20331
20580
 
20332
20581
  // src/bridge/user-gateway/gateway.ts
20333
20582
  import { createHash as createHash9, randomBytes as randomBytes11 } from "crypto";
20334
- import { existsSync as existsSync12, rmSync as rmSync5 } from "fs";
20583
+ import { existsSync as existsSync12, readFileSync as readFileSync9, renameSync as renameSync7, rmSync as rmSync5, writeFileSync as writeFileSync9 } from "fs";
20335
20584
  import { mkdir as mkdir19, readdir as readdir6, readFile as readFileFs, rm as rm14, stat as stat8, writeFile as writeFile9 } from "fs/promises";
20336
20585
  import { join as join31 } from "path";
20337
20586
 
@@ -20830,7 +21079,9 @@ var MAX_TMP_BYTES = 500 * 1024 * 1024;
20830
21079
  var DOWNLOAD_TIMEOUT_MS = 6e4;
20831
21080
  var BASE_MAX_CHARS = 1e5;
20832
21081
  var MAINTENANCE_MS = 6e4;
20833
- var USED_TTL_MS = MESSAGE_MAX_AGE_MS + CLOCK_SKEW_MS + 6e4;
21082
+ var PROOF_HOLD_MS = 60 * 6e4;
21083
+ var USED_TTL_MS = PROOF_HOLD_MS + 6e4 + CLOCK_SKEW_MS;
21084
+ var PROOF_HOLDS_FILE = "proof-holds.json";
20834
21085
  var AUTH_POLL_MS = 5e3;
20835
21086
  var AUTH_MAX_MS = 10 * 6e4;
20836
21087
  var RATE_LIMIT_BACKOFF_MS = [2e3, 5e3, 1e4];
@@ -21006,6 +21257,9 @@ function createGateway(opts) {
21006
21257
  log.warn("user-gateway", event, { api, reason, runId: g?.runId, agoSec: g ? Math.round((now() - g.at) / 1e3) : void 0 });
21007
21258
  }
21008
21259
  const used = /* @__PURE__ */ new Map();
21260
+ const holds = /* @__PURE__ */ new Map();
21261
+ const holdsFile = join31(opts.stateDir, PROOF_HOLDS_FILE);
21262
+ loadProofState();
21009
21263
  const issuedFor = /* @__PURE__ */ new Map();
21010
21264
  const inFlight = /* @__PURE__ */ new Set();
21011
21265
  const pendingAuth = /* @__PURE__ */ new Map();
@@ -21105,9 +21359,55 @@ function createGateway(opts) {
21105
21359
  expired = true;
21106
21360
  }
21107
21361
  if (expired) void cleanupTmp();
21108
- for (const [m, until] of used) if (until <= t) used.delete(m);
21362
+ let changed = false;
21363
+ for (const [m, until] of used)
21364
+ if (until <= t) {
21365
+ used.delete(m);
21366
+ changed = true;
21367
+ }
21368
+ for (const [m, h] of holds)
21369
+ if (h.at + PROOF_HOLD_MS <= t) {
21370
+ holds.delete(m);
21371
+ changed = true;
21372
+ }
21373
+ if (changed) saveProofState();
21109
21374
  for (const [m, v] of issuedFor) if (v.until <= t) issuedFor.delete(m);
21110
21375
  }
21376
+ function loadProofState() {
21377
+ let raw;
21378
+ try {
21379
+ raw = JSON.parse(readFileSync9(holdsFile, "utf8"));
21380
+ } catch (err) {
21381
+ if (err.code !== "ENOENT") log.warn("user-gateway", "proof-state.unreadable", { detail: String(err) });
21382
+ return;
21383
+ }
21384
+ const t = now();
21385
+ if (!isRecord6(raw)) return;
21386
+ if (isRecord6(raw.used)) {
21387
+ for (const [k, v] of Object.entries(raw.used)) if (typeof v === "number" && v > t) used.set(k, v);
21388
+ }
21389
+ if (isRecord6(raw.holds)) {
21390
+ for (const [k, v] of Object.entries(raw.holds)) {
21391
+ if (!MESSAGE_ID.test(k) || !isRecord6(v)) continue;
21392
+ const { sender, chat, at } = v;
21393
+ if (typeof sender === "string" && typeof chat === "string" && typeof at === "number" && at + PROOF_HOLD_MS > t) holds.set(k, { sender, chat, at });
21394
+ }
21395
+ }
21396
+ log.info("user-gateway", "proof-state.loaded", { holds: holds.size, used: used.size });
21397
+ }
21398
+ function saveProofState() {
21399
+ const tmp = `${holdsFile}.${process.pid}.tmp`;
21400
+ try {
21401
+ writeFileSync9(tmp, JSON.stringify({ holds: Object.fromEntries(holds), used: Object.fromEntries(used) }), { mode: 384 });
21402
+ renameSync7(tmp, holdsFile);
21403
+ } catch (err) {
21404
+ log.warn("user-gateway", "proof-state.write-failed", { detail: String(err) });
21405
+ try {
21406
+ rmSync5(tmp, { force: true });
21407
+ } catch {
21408
+ }
21409
+ }
21410
+ }
21111
21411
  async function verify(messageId, purpose, requireP2p = true) {
21112
21412
  sweep();
21113
21413
  const key = `${purpose}:${messageId}`;
@@ -21121,6 +21421,7 @@ function createGateway(opts) {
21121
21421
  if (typeof v === "string") return v;
21122
21422
  if (requireP2p && !v.p2p) return "not_p2p";
21123
21423
  used.set(key, now() + USED_TTL_MS);
21424
+ saveProofState();
21124
21425
  return v;
21125
21426
  } catch (err) {
21126
21427
  log.warn("user-gateway", "verify.failed", { messageId, detail: String(err) });
@@ -21154,7 +21455,7 @@ function createGateway(opts) {
21154
21455
  inFlight.delete(key);
21155
21456
  }
21156
21457
  }
21157
- async function check2(messageId) {
21458
+ async function check2(messageId, hold = false) {
21158
21459
  const msg = await asApp(["api", "GET", `/open-apis/im/v1/messages/${messageId}`, "--as", "bot"]);
21159
21460
  const mjson = parseJson4(msg.stdout);
21160
21461
  const item = isRecord6(mjson) && isRecord6(mjson.data) && Array.isArray(mjson.data.items) ? mjson.data.items[0] : void 0;
@@ -21168,8 +21469,17 @@ function createGateway(opts) {
21168
21469
  }
21169
21470
  const created = Number(item.create_time);
21170
21471
  const t = now();
21171
- if (!Number.isFinite(created) || t - created > MESSAGE_MAX_AGE_MS || created - t > CLOCK_SKEW_MS) return "stale";
21172
21472
  const chatId = typeof item.chat_id === "string" ? item.chat_id : "";
21473
+ if (!Number.isFinite(created) || created - t > CLOCK_SKEW_MS) return "stale";
21474
+ if (t - created > MESSAGE_MAX_AGE_MS) {
21475
+ const h = hold ? void 0 : holds.get(messageId);
21476
+ if (!h || h.at + PROOF_HOLD_MS <= t) return "stale";
21477
+ if (h.sender !== sender.id || h.chat !== chatId) {
21478
+ log.warn("user-gateway", "proof-hold.mismatch", { messageId });
21479
+ return "stale";
21480
+ }
21481
+ log.info("user-gateway", "proof-hold.used", { messageId, heldMin: Math.round((t - h.at) / 6e4) });
21482
+ }
21173
21483
  if (!CHAT_ID.test(chatId)) return "not_found";
21174
21484
  const chat = await asApp(["api", "GET", `/open-apis/im/v1/chats/${chatId}`, "--as", "bot"]);
21175
21485
  const cjson = parseJson4(chat.stdout);
@@ -21183,7 +21493,7 @@ function createGateway(opts) {
21183
21493
  const body = parseJson4(item.body.content);
21184
21494
  if (isRecord6(body) && typeof body.text === "string") text = body.text;
21185
21495
  }
21186
- return { openId: sender.id, p2p: mode === "p2p", ...text !== void 0 ? { text } : {} };
21496
+ return { openId: sender.id, p2p: mode === "p2p", chatId, ...text !== void 0 ? { text } : {} };
21187
21497
  }
21188
21498
  async function sendAuthCard(openId, url) {
21189
21499
  const card = {
@@ -21425,6 +21735,37 @@ function createGateway(opts) {
21425
21735
  }
21426
21736
  }
21427
21737
  return {
21738
+ /**
21739
+ * POST /proof/hold(intent 0115 D-6):消息一到 bridge 就来登记。按现有规则(发送人是用户、2 分钟内、会话可读)核对,
21740
+ * 通过就记下 messageId → 发送人、会话、登记时间并存盘。已登记的不刷新时间。登记本身不算「用过」任何用途。
21741
+ */
21742
+ async proofHold(input) {
21743
+ let messageId;
21744
+ try {
21745
+ messageId = str2(input, "messageId", MESSAGE_ID);
21746
+ } catch {
21747
+ return { status: "bad_request" };
21748
+ }
21749
+ sweep();
21750
+ const prev = holds.get(messageId);
21751
+ if (prev) return { status: "held", heldAt: prev.at, expiresAt: prev.at + PROOF_HOLD_MS };
21752
+ let v;
21753
+ try {
21754
+ v = await check2(messageId, true);
21755
+ } catch (err) {
21756
+ log.warn("user-gateway", "verify.failed", { messageId, detail: String(err) });
21757
+ return { status: "lark_error" };
21758
+ }
21759
+ if (typeof v === "string") {
21760
+ log.info("user-gateway", "proof-hold.refused", { messageId, result: v });
21761
+ return { status: v };
21762
+ }
21763
+ const at = now();
21764
+ holds.set(messageId, { sender: v.openId, chat: v.chatId, at });
21765
+ saveProofState();
21766
+ log.info("user-gateway", "proof-hold.held", { messageId, sender: tail6(v.openId) });
21767
+ return { status: "held", heldAt: at, expiresAt: at + PROOF_HOLD_MS };
21768
+ },
21428
21769
  /** POST /handles:核实提问人(私聊或群里的消息),发句柄;没授权就发卡片并返回 need_auth,查库开着时同一轮仍带只能查库的句柄(intent 0068)。 */
21429
21770
  async requestHandle(input) {
21430
21771
  let messageId, runId;
@@ -21705,6 +22046,7 @@ var MAX_BODY = 16 * 1024;
21705
22046
  var CLAUDE_ROUTES = /* @__PURE__ */ new Set(["/claude/token", "/claude/task-token", "/claude/ready", "/claude/login-submit", "/claude/logout"]);
21706
22047
  var DB_TASK_HANDLE = "/db/task-handle";
21707
22048
  var DB_QUERY = "/db/query";
22049
+ var PROOF_HOLD = "/proof/hold";
21708
22050
  var digest = (s) => createHash10("sha256").update(s).digest();
21709
22051
  function tokenOk(given, expected) {
21710
22052
  if (typeof given !== "string" || !given) return false;
@@ -21748,7 +22090,7 @@ function createGatewayServer(opts) {
21748
22090
  const method = req.method ?? "GET";
21749
22091
  if (method === "GET" && path === "/healthz") return send2(res, 200, { status: "ok" });
21750
22092
  const claude = method === "POST" && (CLAUDE_ROUTES.has(path) || path === DB_TASK_HANDLE);
21751
- const admin = claude || method === "POST" && (path === "/handles" || path === "/revoke") || method === "DELETE" && path.startsWith("/handles/");
22093
+ const admin = claude || method === "POST" && (path === "/handles" || path === "/revoke" || path === PROOF_HOLD) || method === "DELETE" && path.startsWith("/handles/");
21752
22094
  if (admin) {
21753
22095
  if (!tokenOk(req.headers["x-gateway-token"], expected)) {
21754
22096
  log.warn("user-gateway", "request.unauthorized", { method, route: path.startsWith("/handles/") ? "handles/:runId" : path.slice(1) });
@@ -21765,6 +22107,7 @@ function createGatewayServer(opts) {
21765
22107
  if (path === "/claude/ready") return send2(res, 200, await gateway.claudeReady(body));
21766
22108
  if (path === "/claude/login-submit") return send2(res, 200, await gateway.claudeLoginSubmit(body));
21767
22109
  if (path === "/claude/logout") return send2(res, 200, await gateway.claudeLogout(body));
22110
+ if (path === PROOF_HOLD) return send2(res, 200, await gateway.proofHold(body));
21768
22111
  if (path === "/handles") return send2(res, 200, await gateway.requestHandle(body));
21769
22112
  return send2(res, 200, await gateway.revoke(body));
21770
22113
  }
@@ -21806,7 +22149,7 @@ function createGatewayServer(opts) {
21806
22149
  function fetchToken(cmd) {
21807
22150
  const [bin, ...args] = cmd.trim().split(/\s+/);
21808
22151
  if (!bin) throw new Error("--token-cmd \u4E3A\u7A7A");
21809
- const r = spawnSync5(bin, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 3e4 });
22152
+ const r = spawnSync4(bin, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 3e4 });
21810
22153
  const value = r.status === 0 ? r.stdout.trim() : "";
21811
22154
  if (!value) throw new Error(`\u53D6\u7F51\u5173\u53E3\u4EE4\u5931\u8D25\uFF08${bin} \u9000\u51FA\u7801 ${r.status}\uFF09`);
21812
22155
  return value;