aai-lark-bridge 0.2.18 → 0.2.20

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.18",
7
+ version: "0.2.20",
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",
@@ -7292,7 +7292,7 @@ function realClaudeCli(binary = process.env.SDLC_REAL_CLAUDE || "claude") {
7292
7292
  const keep = Object.fromEntries(Object.entries(process.env).filter(([k]) => /^(PATH|LANG|https?_proxy|no_proxy|HTTPS?_PROXY|NO_PROXY)$/.test(k)));
7293
7293
  return { ...keep, HOME: dir, CLAUDE_CONFIG_DIR: dir };
7294
7294
  };
7295
- const run = (args, dir, timeoutMs) => new Promise((resolve3) => {
7295
+ const run2 = (args, dir, timeoutMs) => new Promise((resolve3) => {
7296
7296
  void mkdtemp(join19(tmpdir4(), "claude-seat-")).then((cwd) => {
7297
7297
  const p3 = spawn(binary, args, { cwd, env: baseEnv(dir), stdio: ["ignore", "ignore", "ignore"] });
7298
7298
  const t = setTimeout(() => p3.kill("SIGTERM"), timeoutMs).unref();
@@ -7358,10 +7358,10 @@ function realClaudeCli(binary = process.env.SDLC_REAL_CLAUDE || "claude") {
7358
7358
  };
7359
7359
  },
7360
7360
  async refresh(dir) {
7361
- return await run(["-p", "\u53EA\u56DE\u590D\u6570\u5B571", "--model", "haiku", "--output-format", "json"], dir, 12e4) === 0;
7361
+ return await run2(["-p", "\u53EA\u56DE\u590D\u6570\u5B571", "--model", "haiku", "--output-format", "json"], dir, 12e4) === 0;
7362
7362
  },
7363
7363
  async logout(dir) {
7364
- await run(["auth", "logout"], dir, 3e4);
7364
+ await run2(["auth", "logout"], dir, 3e4);
7365
7365
  }
7366
7366
  };
7367
7367
  }
@@ -7426,7 +7426,10 @@ async function requestUserRead(cfg, messageId, deps = {}) {
7426
7426
  kind: "handle",
7427
7427
  gatewayRunId,
7428
7428
  env: { [HANDLE_ENV]: r.handle, [GATEWAY_ENV]: cfg.gatewayUrl },
7429
- prompt: PROMPT_TOOL
7429
+ // 网关按查库名单决定这个句柄能不能查库(intent 0049);能查才把部署方写的说明给 agent
7430
+ prompt: r.db === true && cfg.dbPrompt ? `${PROMPT_TOOL}
7431
+
7432
+ ${cfg.dbPrompt}` : PROMPT_TOOL
7430
7433
  };
7431
7434
  }
7432
7435
  log.info("user-read", "no-handle", { messageId, status: String(r.status) });
@@ -13370,12 +13373,12 @@ var ActiveRuns = class {
13370
13373
  this.reservations.delete(chatId);
13371
13374
  };
13372
13375
  }
13373
- register(chatId, run) {
13376
+ register(chatId, run2) {
13374
13377
  if (this.handles.has(chatId)) {
13375
13378
  throw new Error(`run already active for scope: ${chatId}`);
13376
13379
  }
13377
13380
  this.reservations.delete(chatId);
13378
- const handle2 = { run, interrupted: false };
13381
+ const handle2 = { run: run2, interrupted: false };
13379
13382
  this.handles.set(chatId, handle2);
13380
13383
  return handle2;
13381
13384
  }
@@ -13399,9 +13402,9 @@ var ActiveRuns = class {
13399
13402
  get(chatId) {
13400
13403
  return this.handles.get(chatId);
13401
13404
  }
13402
- unregister(chatId, run) {
13405
+ unregister(chatId, run2) {
13403
13406
  const existing = this.handles.get(chatId);
13404
- if (existing?.run === run) this.handles.delete(chatId);
13407
+ if (existing?.run === run2) this.handles.delete(chatId);
13405
13408
  }
13406
13409
  snapshot() {
13407
13410
  return [...this.handles.values()];
@@ -13553,7 +13556,7 @@ var RunExecutor = class {
13553
13556
  ...input.strictMcp ? { strictMcp: true } : {},
13554
13557
  ...input.extraEnv ? { extraEnv: input.extraEnv } : {}
13555
13558
  };
13556
- let run;
13559
+ let run2;
13557
13560
  try {
13558
13561
  await this.agent.prepareRun?.(runOptions);
13559
13562
  } catch (err) {
@@ -13571,7 +13574,7 @@ var RunExecutor = class {
13571
13574
  );
13572
13575
  }
13573
13576
  try {
13574
- run = this.agent.run(runOptions);
13577
+ run2 = this.agent.run(runOptions);
13575
13578
  } catch (err) {
13576
13579
  release();
13577
13580
  releaseScope();
@@ -13594,11 +13597,11 @@ var RunExecutor = class {
13594
13597
  });
13595
13598
  let handle2;
13596
13599
  try {
13597
- handle2 = this.activeRuns.register(input.scopeId, run);
13600
+ handle2 = this.activeRuns.register(input.scopeId, run2);
13598
13601
  } catch (err) {
13599
13602
  releaseScope();
13600
13603
  release();
13601
- await run.stop().catch(() => {
13604
+ await run2.stop().catch(() => {
13602
13605
  });
13603
13606
  throw new RunRejected(
13604
13607
  "run-already-active",
@@ -13609,16 +13612,16 @@ var RunExecutor = class {
13609
13612
  const cleanup = async (waitForExit) => {
13610
13613
  if (cleaned) return;
13611
13614
  cleaned = true;
13612
- this.activeRuns.unregister(input.scopeId, run);
13615
+ this.activeRuns.unregister(input.scopeId, run2);
13613
13616
  release();
13614
13617
  if (waitForExit) {
13615
- const exited = await run.waitForExit(this.postDoneExitGraceMs);
13618
+ const exited = await run2.waitForExit(this.postDoneExitGraceMs);
13616
13619
  if (!exited) {
13617
13620
  log.warn("run", "post-done-exit-timeout", {
13618
13621
  ...dimensions,
13619
13622
  graceMs: this.postDoneExitGraceMs
13620
13623
  });
13621
- await run.stop().catch((err) => {
13624
+ await run2.stop().catch((err) => {
13622
13625
  log.warn("run", "post-done-stop-failed", {
13623
13626
  ...dimensions,
13624
13627
  err: err instanceof Error ? err.message : String(err)
@@ -13627,7 +13630,7 @@ var RunExecutor = class {
13627
13630
  }
13628
13631
  }
13629
13632
  };
13630
- const fanout = new EventFanout(observeRunEvents(run.events, {
13633
+ const fanout = new EventFanout(observeRunEvents(run2.events, {
13631
13634
  dimensions,
13632
13635
  startedAt,
13633
13636
  now: this.now
@@ -13637,13 +13640,13 @@ var RunExecutor = class {
13637
13640
  return {
13638
13641
  runId,
13639
13642
  scopeId: input.scopeId,
13640
- run,
13643
+ run: run2,
13641
13644
  handle: handle2,
13642
13645
  subscribe: () => fanout.subscribe(),
13643
13646
  stop: async () => {
13644
13647
  handle2.interrupted = true;
13645
- await run.stop();
13646
- await run.waitForExit(this.postDoneExitGraceMs);
13648
+ await run2.stop();
13649
+ await run2.waitForExit(this.postDoneExitGraceMs);
13647
13650
  await cleanup(false);
13648
13651
  }
13649
13652
  };
@@ -14430,12 +14433,12 @@ var InboundMarkStore = class {
14430
14433
  }
14431
14434
  kick() {
14432
14435
  if (this.inFlight) return;
14433
- const run = this.drain().finally(() => {
14434
- if (this.inFlight !== run) return;
14436
+ const run2 = this.drain().finally(() => {
14437
+ if (this.inFlight !== run2) return;
14435
14438
  this.inFlight = void 0;
14436
14439
  if (this.pending) this.kick();
14437
14440
  });
14438
- this.inFlight = run;
14441
+ this.inFlight = run2;
14439
14442
  }
14440
14443
  /** Wait for in-flight and queued writes (disconnect and tests). */
14441
14444
  async flush() {
@@ -14893,10 +14896,10 @@ function installStreamResilience(channel, opts = {}) {
14893
14896
  messageIdByStream: /* @__PURE__ */ new WeakMap()
14894
14897
  };
14895
14898
  trackers.set(channel, tracker);
14896
- async function withRetry(op, target, run) {
14899
+ async function withRetry(op, target, run2) {
14897
14900
  for (let attempt = 1; ; attempt++) {
14898
14901
  try {
14899
- return await run();
14902
+ return await run2();
14900
14903
  } catch (err) {
14901
14904
  if (attempt >= maxAttempts || !isTransientWriteError(err)) throw err;
14902
14905
  const raw = err;
@@ -19249,11 +19252,162 @@ import { spawnSync as spawnSync5 } from "child_process";
19249
19252
  import { existsSync as existsSync10 } from "fs";
19250
19253
  import { join as join28 } from "path";
19251
19254
 
19255
+ // src/bridge/user-gateway/db-query.ts
19256
+ import { spawn as spawn3 } from "child_process";
19257
+ var DB_QUERY_TIMEOUT_MS = 16e4;
19258
+ var TASK_HANDLE_TTL_MS = 150 * 6e4;
19259
+ var SQL_LOG_MAX = 2e3;
19260
+ var LOCK_WAIT_SEC = 60;
19261
+ var DB_NAME = /^[a-z0-9_-]{1,40}$/;
19262
+ var OPEN_ID = /^ou_[A-Za-z0-9_-]{1,100}$/;
19263
+ function dbFromEnv(env, cmd = "") {
19264
+ const argv = cmd.trim() ? cmd.trim().split(/\s+/) : [];
19265
+ const readers = (env.SDLC_DB_READERS ?? "").split(",").map((s) => s.trim()).filter((s) => OPEN_ID.test(s));
19266
+ return { enabled: (env.SDLC_DB_GATEWAY ?? "").trim() === "on" && argv.length > 0, readers, cmd: argv };
19267
+ }
19268
+ function realDbRunner(cmd) {
19269
+ return (args, timeoutMs) => new Promise((resolve3) => {
19270
+ const [bin, ...pre] = cmd;
19271
+ const p3 = spawn3(bin, [...pre, ...args], {
19272
+ env: { ...process.env, SDLC_Q_MODE: "direct", SDLC_Q_LOCK_WAIT: String(LOCK_WAIT_SEC) },
19273
+ stdio: ["ignore", "pipe", "pipe"]
19274
+ });
19275
+ let stdout = "";
19276
+ let stderr = "";
19277
+ let timedOut = false;
19278
+ const t = setTimeout(() => {
19279
+ timedOut = true;
19280
+ p3.kill("SIGTERM");
19281
+ }, timeoutMs);
19282
+ p3.stdout.on("data", (d) => stdout += d.toString("utf8"));
19283
+ p3.stderr.on("data", (d) => stderr += d.toString("utf8"));
19284
+ p3.on("error", (err) => {
19285
+ clearTimeout(t);
19286
+ resolve3({ code: null, stdout, stderr: String(err), timedOut });
19287
+ });
19288
+ p3.on("close", (code) => {
19289
+ clearTimeout(t);
19290
+ resolve3({ code, stdout, stderr, timedOut });
19291
+ });
19292
+ });
19293
+ }
19294
+ function csvRows(csv) {
19295
+ const lines = csv.split("\n").filter((l) => l && !l.startsWith("\uFF08\u7ED3\u679C\u8D85\u8FC7"));
19296
+ return Math.max(0, lines.length - 1);
19297
+ }
19298
+ function toResult(r) {
19299
+ const detail = r.stderr.trim().slice(0, 500);
19300
+ if (r.timedOut) return { status: "failed", detail: "\u67E5\u8BE2\u8D85\u65F6" };
19301
+ if (r.code === 0) return { status: "ok", csv: r.stdout };
19302
+ if (r.code === 2) return { status: "rejected", detail };
19303
+ if (r.code === 3) return { status: "busy" };
19304
+ return { status: "failed", detail };
19305
+ }
19306
+
19252
19307
  // src/bridge/user-gateway/gateway.ts
19253
19308
  import { randomBytes as randomBytes10 } from "crypto";
19254
19309
  import { existsSync as existsSync9 } from "fs";
19255
19310
  import { mkdir as mkdir19, rm as rm14, writeFile as writeFile9 } from "fs/promises";
19256
19311
  import { join as join27 } from "path";
19312
+
19313
+ // src/bridge/user-gateway/app-token.ts
19314
+ import { spawn as spawn4 } from "child_process";
19315
+ import { readFileSync as readFileSync5 } from "fs";
19316
+ var APP_TOKEN_REFRESH_BEFORE_MS = 5 * 6e4;
19317
+ var APP_TOKEN_FAIL_BACKOFF_MS = 6e4;
19318
+ function createAppTokenCache(fetcher, now = Date.now) {
19319
+ let cached;
19320
+ let inFlight;
19321
+ let failedAt = -Infinity;
19322
+ async function refresh() {
19323
+ if (!fetcher) return void 0;
19324
+ try {
19325
+ const r = await fetcher();
19326
+ cached = { token: r.token, expiresAt: now() + r.expiresInSec * 1e3 };
19327
+ log.info("user-gateway", "lark.tat-fetched", { expiresInSec: r.expiresInSec });
19328
+ return cached;
19329
+ } catch (err) {
19330
+ failedAt = now();
19331
+ log.warn("user-gateway", "lark.tat-fetch-failed", { detail: String(err).slice(0, 200) });
19332
+ return void 0;
19333
+ }
19334
+ }
19335
+ return {
19336
+ /** 有效的令牌;取不到返回 undefined(调用方退回让 lark-cli 自己取)。同时只取一次。 */
19337
+ async get() {
19338
+ if (cached && cached.expiresAt - now() > APP_TOKEN_REFRESH_BEFORE_MS) return cached;
19339
+ if (now() - failedAt < APP_TOKEN_FAIL_BACKOFF_MS) return void 0;
19340
+ inFlight ??= refresh().finally(() => {
19341
+ inFlight = void 0;
19342
+ });
19343
+ return inFlight;
19344
+ },
19345
+ /** 接口说令牌失效(比如 App Secret 轮换了):丢掉缓存,下次重取。 */
19346
+ invalidate() {
19347
+ cached = void 0;
19348
+ }
19349
+ };
19350
+ }
19351
+ function isAppTokenInvalid(r) {
19352
+ return /\b9999166[1-8]\b|token_invalid/.test(`${r.stdout}
19353
+ ${r.stderr}`);
19354
+ }
19355
+ var FETCH_SCRIPT = `
19356
+ const chunks = [];
19357
+ process.stdin.on('data', (c) => chunks.push(c)).on('end', async () => {
19358
+ const { url, appId, secret } = JSON.parse(Buffer.concat(chunks).toString('utf8'));
19359
+ try {
19360
+ const r = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ app_id: appId, app_secret: secret }), signal: AbortSignal.timeout(15000) });
19361
+ const j = await r.json();
19362
+ process.stdout.write(JSON.stringify({ status: r.status, code: j.code, msg: j.msg, tat: j.tenant_access_token, expire: j.expire }));
19363
+ } catch (e) {
19364
+ process.stdout.write(JSON.stringify({ status: 0, code: -1, msg: String(e && e.message) }));
19365
+ }
19366
+ });`;
19367
+ function run(command, args, input, env, timeoutMs) {
19368
+ return new Promise((resolve3, reject4) => {
19369
+ const p3 = spawn4(command, args, { env, stdio: ["pipe", "pipe", "ignore"] });
19370
+ let out = "";
19371
+ const t = setTimeout(() => p3.kill("SIGTERM"), timeoutMs).unref();
19372
+ p3.stdout.on("data", (d) => out += d.toString("utf8"));
19373
+ p3.on("error", (err) => {
19374
+ clearTimeout(t);
19375
+ reject4(err);
19376
+ });
19377
+ p3.on("close", (code) => {
19378
+ clearTimeout(t);
19379
+ if (code === 0) resolve3(out);
19380
+ else reject4(new Error(`${command} \u9000\u51FA\u7801 ${code}`));
19381
+ });
19382
+ p3.stdin.end(input);
19383
+ });
19384
+ }
19385
+ function realAppTokenFetcher(sourceConfigFile) {
19386
+ return async () => {
19387
+ const cfg = JSON.parse(readFileSync5(sourceConfigFile, "utf8"));
19388
+ const app = cfg.accounts?.app;
19389
+ if (!app?.id) throw new Error("source \u914D\u7F6E\u91CC\u6CA1\u6709\u5E94\u7528 id");
19390
+ let cred;
19391
+ if (typeof app.secret === "string") cred = app.secret;
19392
+ else {
19393
+ const ref = app.secret;
19394
+ const prov = ref?.provider ? cfg.secrets?.providers?.[ref.provider] : void 0;
19395
+ if (ref?.source !== "exec" || !prov?.command || !ref.id) throw new Error("\u53EA\u652F\u6301 exec \u65B9\u5F0F\u53D6\u5BC6\u94A5");
19396
+ const res = JSON.parse(await run(prov.command, prov.args ?? [], JSON.stringify({ protocolVersion: 1, ids: [ref.id] }), { ...prov.env }, 3e4));
19397
+ cred = res.values?.[ref.id];
19398
+ }
19399
+ if (!cred) throw new Error("\u53D6\u4E0D\u5230 App Secret");
19400
+ const host = app.tenant === "feishu" ? "https://open.feishu.cn" : "https://open.larksuite.com";
19401
+ const out = JSON.parse(
19402
+ await run(process.execPath, ["--no-warnings", "-e", FETCH_SCRIPT], JSON.stringify({ url: `${host}/open-apis/auth/v3/tenant_access_token/internal`, appId: app.id, secret: cred }), { ...process.env, NODE_USE_ENV_PROXY: "1" }, 2e4)
19403
+ );
19404
+ if (out.code !== 0 || !out.tat || !out.expire) throw new Error(`\u6362\u5E94\u7528\u4EE4\u724C\u5931\u8D25\uFF1AHTTP ${out.status} code ${out.code} ${out.msg ?? ""}`.trim());
19405
+ const issued = out.tat;
19406
+ return { token: issued, expiresInSec: out.expire };
19407
+ };
19408
+ }
19409
+
19410
+ // src/bridge/user-gateway/gateway.ts
19257
19411
  var USER_READ_SCOPES = [
19258
19412
  "search:message",
19259
19413
  "im:message.p2p_msg:get_as_user",
@@ -19276,7 +19430,7 @@ var RATE_LIMIT_BACKOFF_MS = [2e3, 5e3, 1e4];
19276
19430
  var REVOKE_TEXT2 = "\u64A4\u9500\u6388\u6743";
19277
19431
  var MESSAGE_ID = /^om_[A-Za-z0-9_-]{1,100}$/;
19278
19432
  var CHAT_ID = /^oc_[A-Za-z0-9_-]{1,100}$/;
19279
- var OPEN_ID = /^ou_[A-Za-z0-9_-]{1,100}$/;
19433
+ var OPEN_ID2 = /^ou_[A-Za-z0-9_-]{1,100}$/;
19280
19434
  var RUN_ID = /^[A-Za-z0-9._:-]{1,200}$/;
19281
19435
  var NONCE = /^[0-9a-f]{32}$/;
19282
19436
  var TASK_GUID = /^[A-Za-z0-9-]{8,100}$/;
@@ -19405,18 +19559,28 @@ function createGateway(opts) {
19405
19559
  if (!existsSync9(join27(dir, "lark-channel", "config.json"))) {
19406
19560
  await mkdir19(dir, { recursive: true, mode: 448 });
19407
19561
  const r = await opts.exec(["config", "bind", "--source", "lark-channel", "--identity", identity], env(dir), 3e4);
19408
- if (r.code !== 0) throw new Error(`lark-cli \u7ED1\u5B9A\u5931\u8D25\uFF1A${firstLine(r.stderr || r.stdout)}`);
19562
+ if (r.code !== 0) throw new Error(`lark-cli \u7ED1\u5B9A\u5931\u8D25\uFF1A${larkError(r).detail}`);
19409
19563
  }
19410
19564
  bound2.add(dir);
19411
19565
  }
19566
+ const tatCache = createAppTokenCache(opts.appTokenFetcher === void 0 ? realAppTokenFetcher(opts.larkSourceConfig) : opts.appTokenFetcher, now);
19567
+ async function appEnv() {
19568
+ const t = await tatCache.get();
19569
+ return t ? { ...env(appDir), LARKSUITE_CLI_APP_ID: opts.appId, LARKSUITE_CLI_TENANT_ACCESS_TOKEN: t.token } : env(appDir);
19570
+ }
19412
19571
  const asApp = async (args, timeoutMs = 3e4) => {
19413
19572
  await ensureBound(appDir, "bot-only");
19414
- let r = await opts.exec(args, env(appDir), timeoutMs);
19573
+ let r = await opts.exec(args, await appEnv(), timeoutMs);
19574
+ if (r.code !== 0 && isAppTokenInvalid(r)) {
19575
+ log.warn("user-gateway", "lark.tat-invalid", { api: args.slice(0, 3).join(" ") });
19576
+ tatCache.invalidate();
19577
+ r = await opts.exec(args, await appEnv(), timeoutMs);
19578
+ }
19415
19579
  for (const wait of RATE_LIMIT_BACKOFF_MS) {
19416
19580
  if (r.code === 0 || !isRateLimited(r)) break;
19417
19581
  log.warn("user-gateway", "lark.rate-limited", { api: args.slice(0, 3).join(" "), retryInMs: wait });
19418
19582
  await sleep2(wait);
19419
- r = await opts.exec(args, env(appDir), timeoutMs);
19583
+ r = await opts.exec(args, await appEnv(), timeoutMs);
19420
19584
  }
19421
19585
  return r;
19422
19586
  };
@@ -19455,7 +19619,7 @@ function createGateway(opts) {
19455
19619
  return msg.code === 0 ? "not_found" : "lark_error";
19456
19620
  }
19457
19621
  const sender = isRecord6(item.sender) ? item.sender : {};
19458
- if (sender.sender_type !== "user" || sender.id_type !== "open_id" || typeof sender.id !== "string" || !OPEN_ID.test(sender.id)) {
19622
+ if (sender.sender_type !== "user" || sender.id_type !== "open_id" || typeof sender.id !== "string" || !OPEN_ID2.test(sender.id)) {
19459
19623
  return "not_user";
19460
19624
  }
19461
19625
  const created = Number(item.create_time);
@@ -19533,6 +19697,8 @@ function createGateway(opts) {
19533
19697
  const members = Array.isArray(task.members) ? task.members : [];
19534
19698
  return members.filter((m) => isRecord6(m) && m.role === "assignee" && typeof m.id === "string").map((m) => m.id);
19535
19699
  }
19700
+ const db = opts.db ?? { enabled: false, readers: [], cmd: [] };
19701
+ const runDb = opts.dbRunner ?? realDbRunner(db.cmd);
19536
19702
  const seat = createClaudeSeat({
19537
19703
  stateDir: opts.stateDir,
19538
19704
  appId: opts.appId,
@@ -19621,9 +19787,10 @@ function createGateway(opts) {
19621
19787
  }
19622
19788
  const handle2 = randomBytes10(32).toString("base64url");
19623
19789
  const expiresAt = now() + HANDLE_TTL_MS;
19624
- handles.set(handle2, { openId: v.openId, messageId, runId, expiresAt });
19625
- log.info("user-gateway", "handle.issued", { identity: "user", sender: tail6(v.openId), messageId, runId });
19626
- return { status: "ok", handle: handle2, expiresAt };
19790
+ const canDb = db.enabled && db.readers.includes(v.openId);
19791
+ handles.set(handle2, { openId: v.openId, messageId, runId, expiresAt, kind: "dm", db: canDb });
19792
+ log.info("user-gateway", "handle.issued", { identity: "user", sender: tail6(v.openId), messageId, runId, db: canDb });
19793
+ return { status: "ok", handle: handle2, expiresAt, db: canDb };
19627
19794
  },
19628
19795
  /** DELETE /handles/{runId}:运行结束,作废这次运行的句柄。 */
19629
19796
  dropHandles(runId) {
@@ -19641,7 +19808,7 @@ function createGateway(opts) {
19641
19808
  async read(handle2, api, input) {
19642
19809
  sweep();
19643
19810
  const h = handles.get(handle2);
19644
- if (!h) return { status: "expired" };
19811
+ if (!h || h.kind !== "dm") return { status: "expired" };
19645
19812
  let args;
19646
19813
  try {
19647
19814
  args = readArgs(api, input);
@@ -19715,7 +19882,7 @@ function createGateway(opts) {
19715
19882
  let taskGuid, openId, runId;
19716
19883
  try {
19717
19884
  taskGuid = str2(input, "taskGuid", TASK_GUID);
19718
- openId = str2(input, "openId", OPEN_ID);
19885
+ openId = str2(input, "openId", OPEN_ID2);
19719
19886
  runId = str2(input, "runId", RUN_ID);
19720
19887
  } catch {
19721
19888
  return { status: "bad_request" };
@@ -19737,7 +19904,7 @@ function createGateway(opts) {
19737
19904
  let openId, card, nonce;
19738
19905
  const code = typeof input.code === "string" ? input.code.trim() : "";
19739
19906
  try {
19740
- openId = str2(input, "openId", OPEN_ID);
19907
+ openId = str2(input, "openId", OPEN_ID2);
19741
19908
  card = str2(input, "cardMessageId", MESSAGE_ID);
19742
19909
  nonce = str2(input, "nonce", NONCE);
19743
19910
  } catch {
@@ -19760,6 +19927,53 @@ function createGateway(opts) {
19760
19927
  if (v.text?.trim() !== LOGOUT_TEXT) return { status: "not_logout" };
19761
19928
  return { status: await seat.logout(v.openId) };
19762
19929
  },
19930
+ /**
19931
+ * POST /db/task-handle:调度的只读运行(只读分析、出文档、补报告)起 claude 前凭任务申请查库句柄(intent 0049 R-04)。
19932
+ * 负责人得是这个任务的 assignee(网关向飞书核对,同 0048 的 /claude/task-token);不看私聊查库名单(spec D-3)。
19933
+ */
19934
+ async dbTaskHandle(input) {
19935
+ let taskGuid, openId, runId;
19936
+ try {
19937
+ taskGuid = str2(input, "taskGuid", TASK_GUID);
19938
+ openId = str2(input, "openId", OPEN_ID2);
19939
+ runId = str2(input, "runId", RUN_ID);
19940
+ } catch {
19941
+ return { status: "bad_request" };
19942
+ }
19943
+ if (!db.enabled) return { status: "off" };
19944
+ const assignees = await taskAssignees(taskGuid);
19945
+ if (assignees === "lark_error") return { status: "lark_error" };
19946
+ if (!assignees.includes(openId)) {
19947
+ log.warn("user-gateway", "db.handle-refused", { sender: tail6(openId), runId, result: "not_assignee" });
19948
+ return { status: "not_assignee" };
19949
+ }
19950
+ const handle2 = randomBytes10(32).toString("base64url");
19951
+ const expiresAt = now() + TASK_HANDLE_TTL_MS;
19952
+ handles.set(handle2, { openId, messageId: "", runId, expiresAt, kind: "task", db: true });
19953
+ log.info("user-gateway", "db.handle-issued", { sender: tail6(openId), runId, task: taskGuid });
19954
+ return { status: "ok", handle: handle2, expiresAt };
19955
+ },
19956
+ /** POST /db/query:凭句柄替 agent 查一条,每次记一条 db.query(intent 0049 R-01、R-03、R-05)。 */
19957
+ async dbQuery(handle2, input) {
19958
+ if (!db.enabled) return { status: "off" };
19959
+ sweep();
19960
+ const h = handles.get(handle2);
19961
+ if (!h) return { status: "expired" };
19962
+ const name = typeof input.db === "string" && input.db ? input.db : "lotus";
19963
+ const sql = typeof input.sql === "string" ? input.sql : "";
19964
+ const fields = { sender: tail6(h.openId), runId: h.runId, kind: h.kind, db: name, sql: sql.slice(0, SQL_LOG_MAX) };
19965
+ if (!h.db) {
19966
+ log.warn("user-gateway", "db.query", { ...fields, rows: 0, ms: 0, result: "not_allowed" });
19967
+ return { status: "not_allowed" };
19968
+ }
19969
+ if (!DB_NAME.test(name) || !sql.trim()) return { status: "bad_request", detail: !sql.trim() ? "\u7A7A\u67E5\u8BE2" : `\u5E93\u540D\u4E0D\u5BF9\uFF1A${name}` };
19970
+ const t0 = now();
19971
+ const r = toResult(await runDb(["--db", name, sql], DB_QUERY_TIMEOUT_MS));
19972
+ const rows = r.status === "ok" ? csvRows(r.csv) : 0;
19973
+ const detail = "detail" in r ? { detail: r.detail.slice(0, 200) } : {};
19974
+ (r.status === "ok" ? log.info : log.warn)("user-gateway", "db.query", { ...fields, rows, ms: now() - t0, result: r.status, ...detail });
19975
+ return r;
19976
+ },
19763
19977
  /** 测试用:等正在进行的授权轮询结束。 */
19764
19978
  async settle() {
19765
19979
  await Promise.all([...pendingAuth.values()]);
@@ -19772,6 +19986,8 @@ import { createHash as createHash8, timingSafeEqual as timingSafeEqual3 } from "
19772
19986
  import { createServer as createServer2 } from "http";
19773
19987
  var MAX_BODY = 16 * 1024;
19774
19988
  var CLAUDE_ROUTES = /* @__PURE__ */ new Set(["/claude/token", "/claude/task-token", "/claude/login-submit", "/claude/logout"]);
19989
+ var DB_TASK_HANDLE = "/db/task-handle";
19990
+ var DB_QUERY = "/db/query";
19775
19991
  var digest = (s) => createHash8("sha256").update(s).digest();
19776
19992
  function tokenOk(given, expected) {
19777
19993
  if (typeof given !== "string" || !given) return false;
@@ -19814,7 +20030,7 @@ function createGatewayServer(opts) {
19814
20030
  const path = url.pathname;
19815
20031
  const method = req.method ?? "GET";
19816
20032
  if (method === "GET" && path === "/healthz") return send2(res, 200, { status: "ok" });
19817
- const claude = method === "POST" && CLAUDE_ROUTES.has(path);
20033
+ const claude = method === "POST" && (CLAUDE_ROUTES.has(path) || path === DB_TASK_HANDLE);
19818
20034
  const admin = claude || method === "POST" && (path === "/handles" || path === "/revoke") || method === "DELETE" && path.startsWith("/handles/");
19819
20035
  if (admin) {
19820
20036
  if (!tokenOk(req.headers["x-gateway-token"], expected)) {
@@ -19826,6 +20042,7 @@ function createGatewayServer(opts) {
19826
20042
  return send2(res, 200, { status: "ok", dropped: gateway.dropHandles(runId) });
19827
20043
  }
19828
20044
  const body = await readBody(req);
20045
+ if (path === DB_TASK_HANDLE) return send2(res, 200, await gateway.dbTaskHandle(body));
19829
20046
  if (path === "/claude/token") return send2(res, 200, await gateway.claudeToken(body));
19830
20047
  if (path === "/claude/task-token") return send2(res, 200, await gateway.claudeTaskToken(body));
19831
20048
  if (path === "/claude/login-submit") return send2(res, 200, await gateway.claudeLoginSubmit(body));
@@ -19833,12 +20050,20 @@ function createGatewayServer(opts) {
19833
20050
  if (path === "/handles") return send2(res, 200, await gateway.requestHandle(body));
19834
20051
  return send2(res, 200, await gateway.revoke(body));
19835
20052
  }
20053
+ const bearer = () => {
20054
+ const auth = req.headers.authorization;
20055
+ return typeof auth === "string" && auth.startsWith("Bearer ") ? auth.slice(7).trim() : "";
20056
+ };
20057
+ if (method === "POST" && path === DB_QUERY) {
20058
+ const handle2 = bearer();
20059
+ if (!handle2) return send2(res, 200, { status: "expired" });
20060
+ return send2(res, 200, await gateway.dbQuery(handle2, await readBody(req)));
20061
+ }
19836
20062
  const read = method === "POST" ? /^\/read\/([a-z-]+)$/.exec(path) : null;
19837
20063
  if (read) {
19838
20064
  const api = read[1] ?? "";
19839
20065
  if (!isReadApi(api)) return send2(res, 404, { status: "unknown_api" });
19840
- const auth = req.headers.authorization;
19841
- const handle2 = typeof auth === "string" && auth.startsWith("Bearer ") ? auth.slice(7).trim() : "";
20066
+ const handle2 = bearer();
19842
20067
  if (!handle2) return send2(res, 200, { status: "expired" });
19843
20068
  return send2(res, 200, await gateway.read(handle2, api, await readBody(req)));
19844
20069
  }
@@ -19874,12 +20099,14 @@ async function runUserGateway(opts) {
19874
20099
  larkSourceConfig: opts.larkSourceConfig,
19875
20100
  exec: defaultExec,
19876
20101
  // Claude 席位开关(intent 0048):容器的 SDLC_CLAUDE_SEAT、SDLC_CLAUDE_SEAT_LIST,缺省关
19877
- seat: seatFromEnv(process.env)
20102
+ seat: seatFromEnv(process.env),
20103
+ // 查库开关(intent 0049):容器的 SDLC_DB_GATEWAY、SDLC_DB_READERS,缺省关
20104
+ db: dbFromEnv(process.env, opts.dbCmd)
19878
20105
  });
19879
20106
  const pass = fetchToken(opts.tokenCmd);
19880
20107
  const server = createGatewayServer({ gateway, gatewayToken: pass });
19881
20108
  await new Promise((resolve3) => server.listen(port, opts.host ?? "0.0.0.0", resolve3));
19882
- log.info("user-gateway", "started", { port, claudeSeat: seatFromEnv(process.env).mode });
20109
+ log.info("user-gateway", "started", { port, claudeSeat: seatFromEnv(process.env).mode, db: dbFromEnv(process.env, opts.dbCmd).enabled });
19883
20110
  console.log(`user-gateway listening on ${opts.host ?? "0.0.0.0"}:${port}`);
19884
20111
  await new Promise((resolve3) => {
19885
20112
  const stop2 = () => server.close(() => resolve3());
@@ -19897,7 +20124,7 @@ program.command("run").description("Run the bridge in the foreground (was `start
19897
20124
  program.command("migrate").description("Migrate legacy bridge config/state into the current profile layout").option("-c, --config <path>", "path to config file").option("--profile <name>", "target profile name for legacy v1 config migration").option("--agent <kind>", "agent kind for legacy v1 profile migration (claude or codex)").action(async (opts) => {
19898
20125
  await runMigrate(opts);
19899
20126
  });
19900
- program.command("user-gateway").description("Run the per-sender user-token gateway (intent 0046); keeps user tokens out of the agent container").requiredOption("--app-id <id>", "App ID whose users authorize").requiredOption("--state-dir <path>", "gateway volume; user tokens live under user-tokens/<appId>/<open_id>/").requiredOption("--lark-source-config <path>", "lark-cli source config with the app id and secret provider").requiredOption("--token-cmd <cmd>", 'command printing the gateway token, e.g. "sdlc-secret gateway-token" (no shell)').option("--host <host>", "listen address", "0.0.0.0").option("--port <port>", "listen port", "8788").action(async (opts) => {
20127
+ program.command("user-gateway").description("Run the per-sender user-token gateway (intent 0046); keeps user tokens out of the agent container").requiredOption("--app-id <id>", "App ID whose users authorize").requiredOption("--state-dir <path>", "gateway volume; user tokens live under user-tokens/<appId>/<open_id>/").requiredOption("--lark-source-config <path>", "lark-cli source config with the app id and secret provider").requiredOption("--token-cmd <cmd>", 'command printing the gateway token, e.g. "sdlc-secret gateway-token" (no shell)').option("--host <host>", "listen address", "0.0.0.0").option("--port <port>", "listen port", "8788").option("--db-cmd <cmd>", "query command for /db/query (intent 0049), e.g. the q proxy; used only when SDLC_DB_GATEWAY=on").action(async (opts) => {
19901
20128
  await runUserGateway(opts);
19902
20129
  });
19903
20130
  var profile = program.command("profile").description("Manage local bridge profiles");