aai-lark-bridge 0.2.18 → 0.2.19

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.19",
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
  }
@@ -13370,12 +13370,12 @@ var ActiveRuns = class {
13370
13370
  this.reservations.delete(chatId);
13371
13371
  };
13372
13372
  }
13373
- register(chatId, run) {
13373
+ register(chatId, run2) {
13374
13374
  if (this.handles.has(chatId)) {
13375
13375
  throw new Error(`run already active for scope: ${chatId}`);
13376
13376
  }
13377
13377
  this.reservations.delete(chatId);
13378
- const handle2 = { run, interrupted: false };
13378
+ const handle2 = { run: run2, interrupted: false };
13379
13379
  this.handles.set(chatId, handle2);
13380
13380
  return handle2;
13381
13381
  }
@@ -13399,9 +13399,9 @@ var ActiveRuns = class {
13399
13399
  get(chatId) {
13400
13400
  return this.handles.get(chatId);
13401
13401
  }
13402
- unregister(chatId, run) {
13402
+ unregister(chatId, run2) {
13403
13403
  const existing = this.handles.get(chatId);
13404
- if (existing?.run === run) this.handles.delete(chatId);
13404
+ if (existing?.run === run2) this.handles.delete(chatId);
13405
13405
  }
13406
13406
  snapshot() {
13407
13407
  return [...this.handles.values()];
@@ -13553,7 +13553,7 @@ var RunExecutor = class {
13553
13553
  ...input.strictMcp ? { strictMcp: true } : {},
13554
13554
  ...input.extraEnv ? { extraEnv: input.extraEnv } : {}
13555
13555
  };
13556
- let run;
13556
+ let run2;
13557
13557
  try {
13558
13558
  await this.agent.prepareRun?.(runOptions);
13559
13559
  } catch (err) {
@@ -13571,7 +13571,7 @@ var RunExecutor = class {
13571
13571
  );
13572
13572
  }
13573
13573
  try {
13574
- run = this.agent.run(runOptions);
13574
+ run2 = this.agent.run(runOptions);
13575
13575
  } catch (err) {
13576
13576
  release();
13577
13577
  releaseScope();
@@ -13594,11 +13594,11 @@ var RunExecutor = class {
13594
13594
  });
13595
13595
  let handle2;
13596
13596
  try {
13597
- handle2 = this.activeRuns.register(input.scopeId, run);
13597
+ handle2 = this.activeRuns.register(input.scopeId, run2);
13598
13598
  } catch (err) {
13599
13599
  releaseScope();
13600
13600
  release();
13601
- await run.stop().catch(() => {
13601
+ await run2.stop().catch(() => {
13602
13602
  });
13603
13603
  throw new RunRejected(
13604
13604
  "run-already-active",
@@ -13609,16 +13609,16 @@ var RunExecutor = class {
13609
13609
  const cleanup = async (waitForExit) => {
13610
13610
  if (cleaned) return;
13611
13611
  cleaned = true;
13612
- this.activeRuns.unregister(input.scopeId, run);
13612
+ this.activeRuns.unregister(input.scopeId, run2);
13613
13613
  release();
13614
13614
  if (waitForExit) {
13615
- const exited = await run.waitForExit(this.postDoneExitGraceMs);
13615
+ const exited = await run2.waitForExit(this.postDoneExitGraceMs);
13616
13616
  if (!exited) {
13617
13617
  log.warn("run", "post-done-exit-timeout", {
13618
13618
  ...dimensions,
13619
13619
  graceMs: this.postDoneExitGraceMs
13620
13620
  });
13621
- await run.stop().catch((err) => {
13621
+ await run2.stop().catch((err) => {
13622
13622
  log.warn("run", "post-done-stop-failed", {
13623
13623
  ...dimensions,
13624
13624
  err: err instanceof Error ? err.message : String(err)
@@ -13627,7 +13627,7 @@ var RunExecutor = class {
13627
13627
  }
13628
13628
  }
13629
13629
  };
13630
- const fanout = new EventFanout(observeRunEvents(run.events, {
13630
+ const fanout = new EventFanout(observeRunEvents(run2.events, {
13631
13631
  dimensions,
13632
13632
  startedAt,
13633
13633
  now: this.now
@@ -13637,13 +13637,13 @@ var RunExecutor = class {
13637
13637
  return {
13638
13638
  runId,
13639
13639
  scopeId: input.scopeId,
13640
- run,
13640
+ run: run2,
13641
13641
  handle: handle2,
13642
13642
  subscribe: () => fanout.subscribe(),
13643
13643
  stop: async () => {
13644
13644
  handle2.interrupted = true;
13645
- await run.stop();
13646
- await run.waitForExit(this.postDoneExitGraceMs);
13645
+ await run2.stop();
13646
+ await run2.waitForExit(this.postDoneExitGraceMs);
13647
13647
  await cleanup(false);
13648
13648
  }
13649
13649
  };
@@ -14430,12 +14430,12 @@ var InboundMarkStore = class {
14430
14430
  }
14431
14431
  kick() {
14432
14432
  if (this.inFlight) return;
14433
- const run = this.drain().finally(() => {
14434
- if (this.inFlight !== run) return;
14433
+ const run2 = this.drain().finally(() => {
14434
+ if (this.inFlight !== run2) return;
14435
14435
  this.inFlight = void 0;
14436
14436
  if (this.pending) this.kick();
14437
14437
  });
14438
- this.inFlight = run;
14438
+ this.inFlight = run2;
14439
14439
  }
14440
14440
  /** Wait for in-flight and queued writes (disconnect and tests). */
14441
14441
  async flush() {
@@ -14893,10 +14893,10 @@ function installStreamResilience(channel, opts = {}) {
14893
14893
  messageIdByStream: /* @__PURE__ */ new WeakMap()
14894
14894
  };
14895
14895
  trackers.set(channel, tracker);
14896
- async function withRetry(op, target, run) {
14896
+ async function withRetry(op, target, run2) {
14897
14897
  for (let attempt = 1; ; attempt++) {
14898
14898
  try {
14899
- return await run();
14899
+ return await run2();
14900
14900
  } catch (err) {
14901
14901
  if (attempt >= maxAttempts || !isTransientWriteError(err)) throw err;
14902
14902
  const raw = err;
@@ -19254,6 +19254,105 @@ import { randomBytes as randomBytes10 } from "crypto";
19254
19254
  import { existsSync as existsSync9 } from "fs";
19255
19255
  import { mkdir as mkdir19, rm as rm14, writeFile as writeFile9 } from "fs/promises";
19256
19256
  import { join as join27 } from "path";
19257
+
19258
+ // src/bridge/user-gateway/app-token.ts
19259
+ import { spawn as spawn3 } from "child_process";
19260
+ import { readFileSync as readFileSync5 } from "fs";
19261
+ var APP_TOKEN_REFRESH_BEFORE_MS = 5 * 6e4;
19262
+ var APP_TOKEN_FAIL_BACKOFF_MS = 6e4;
19263
+ function createAppTokenCache(fetcher, now = Date.now) {
19264
+ let cached;
19265
+ let inFlight;
19266
+ let failedAt = -Infinity;
19267
+ async function refresh() {
19268
+ if (!fetcher) return void 0;
19269
+ try {
19270
+ const r = await fetcher();
19271
+ cached = { token: r.token, expiresAt: now() + r.expiresInSec * 1e3 };
19272
+ log.info("user-gateway", "lark.tat-fetched", { expiresInSec: r.expiresInSec });
19273
+ return cached;
19274
+ } catch (err) {
19275
+ failedAt = now();
19276
+ log.warn("user-gateway", "lark.tat-fetch-failed", { detail: String(err).slice(0, 200) });
19277
+ return void 0;
19278
+ }
19279
+ }
19280
+ return {
19281
+ /** 有效的令牌;取不到返回 undefined(调用方退回让 lark-cli 自己取)。同时只取一次。 */
19282
+ async get() {
19283
+ if (cached && cached.expiresAt - now() > APP_TOKEN_REFRESH_BEFORE_MS) return cached;
19284
+ if (now() - failedAt < APP_TOKEN_FAIL_BACKOFF_MS) return void 0;
19285
+ inFlight ??= refresh().finally(() => {
19286
+ inFlight = void 0;
19287
+ });
19288
+ return inFlight;
19289
+ },
19290
+ /** 接口说令牌失效(比如 App Secret 轮换了):丢掉缓存,下次重取。 */
19291
+ invalidate() {
19292
+ cached = void 0;
19293
+ }
19294
+ };
19295
+ }
19296
+ function isAppTokenInvalid(r) {
19297
+ return /\b9999166[1-8]\b|token_invalid/.test(`${r.stdout}
19298
+ ${r.stderr}`);
19299
+ }
19300
+ var FETCH_SCRIPT = `
19301
+ const chunks = [];
19302
+ process.stdin.on('data', (c) => chunks.push(c)).on('end', async () => {
19303
+ const { url, appId, secret } = JSON.parse(Buffer.concat(chunks).toString('utf8'));
19304
+ try {
19305
+ 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) });
19306
+ const j = await r.json();
19307
+ process.stdout.write(JSON.stringify({ status: r.status, code: j.code, msg: j.msg, tat: j.tenant_access_token, expire: j.expire }));
19308
+ } catch (e) {
19309
+ process.stdout.write(JSON.stringify({ status: 0, code: -1, msg: String(e && e.message) }));
19310
+ }
19311
+ });`;
19312
+ function run(command, args, input, env, timeoutMs) {
19313
+ return new Promise((resolve3, reject4) => {
19314
+ const p3 = spawn3(command, args, { env, stdio: ["pipe", "pipe", "ignore"] });
19315
+ let out = "";
19316
+ const t = setTimeout(() => p3.kill("SIGTERM"), timeoutMs).unref();
19317
+ p3.stdout.on("data", (d) => out += d.toString("utf8"));
19318
+ p3.on("error", (err) => {
19319
+ clearTimeout(t);
19320
+ reject4(err);
19321
+ });
19322
+ p3.on("close", (code) => {
19323
+ clearTimeout(t);
19324
+ if (code === 0) resolve3(out);
19325
+ else reject4(new Error(`${command} \u9000\u51FA\u7801 ${code}`));
19326
+ });
19327
+ p3.stdin.end(input);
19328
+ });
19329
+ }
19330
+ function realAppTokenFetcher(sourceConfigFile) {
19331
+ return async () => {
19332
+ const cfg = JSON.parse(readFileSync5(sourceConfigFile, "utf8"));
19333
+ const app = cfg.accounts?.app;
19334
+ if (!app?.id) throw new Error("source \u914D\u7F6E\u91CC\u6CA1\u6709\u5E94\u7528 id");
19335
+ let cred;
19336
+ if (typeof app.secret === "string") cred = app.secret;
19337
+ else {
19338
+ const ref = app.secret;
19339
+ const prov = ref?.provider ? cfg.secrets?.providers?.[ref.provider] : void 0;
19340
+ if (ref?.source !== "exec" || !prov?.command || !ref.id) throw new Error("\u53EA\u652F\u6301 exec \u65B9\u5F0F\u53D6\u5BC6\u94A5");
19341
+ const res = JSON.parse(await run(prov.command, prov.args ?? [], JSON.stringify({ protocolVersion: 1, ids: [ref.id] }), { ...prov.env }, 3e4));
19342
+ cred = res.values?.[ref.id];
19343
+ }
19344
+ if (!cred) throw new Error("\u53D6\u4E0D\u5230 App Secret");
19345
+ const host = app.tenant === "feishu" ? "https://open.feishu.cn" : "https://open.larksuite.com";
19346
+ const out = JSON.parse(
19347
+ 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)
19348
+ );
19349
+ 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());
19350
+ const issued = out.tat;
19351
+ return { token: issued, expiresInSec: out.expire };
19352
+ };
19353
+ }
19354
+
19355
+ // src/bridge/user-gateway/gateway.ts
19257
19356
  var USER_READ_SCOPES = [
19258
19357
  "search:message",
19259
19358
  "im:message.p2p_msg:get_as_user",
@@ -19405,18 +19504,28 @@ function createGateway(opts) {
19405
19504
  if (!existsSync9(join27(dir, "lark-channel", "config.json"))) {
19406
19505
  await mkdir19(dir, { recursive: true, mode: 448 });
19407
19506
  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)}`);
19507
+ if (r.code !== 0) throw new Error(`lark-cli \u7ED1\u5B9A\u5931\u8D25\uFF1A${larkError(r).detail}`);
19409
19508
  }
19410
19509
  bound2.add(dir);
19411
19510
  }
19511
+ const tatCache = createAppTokenCache(opts.appTokenFetcher === void 0 ? realAppTokenFetcher(opts.larkSourceConfig) : opts.appTokenFetcher, now);
19512
+ async function appEnv() {
19513
+ const t = await tatCache.get();
19514
+ return t ? { ...env(appDir), LARKSUITE_CLI_APP_ID: opts.appId, LARKSUITE_CLI_TENANT_ACCESS_TOKEN: t.token } : env(appDir);
19515
+ }
19412
19516
  const asApp = async (args, timeoutMs = 3e4) => {
19413
19517
  await ensureBound(appDir, "bot-only");
19414
- let r = await opts.exec(args, env(appDir), timeoutMs);
19518
+ let r = await opts.exec(args, await appEnv(), timeoutMs);
19519
+ if (r.code !== 0 && isAppTokenInvalid(r)) {
19520
+ log.warn("user-gateway", "lark.tat-invalid", { api: args.slice(0, 3).join(" ") });
19521
+ tatCache.invalidate();
19522
+ r = await opts.exec(args, await appEnv(), timeoutMs);
19523
+ }
19415
19524
  for (const wait of RATE_LIMIT_BACKOFF_MS) {
19416
19525
  if (r.code === 0 || !isRateLimited(r)) break;
19417
19526
  log.warn("user-gateway", "lark.rate-limited", { api: args.slice(0, 3).join(" "), retryInMs: wait });
19418
19527
  await sleep2(wait);
19419
- r = await opts.exec(args, env(appDir), timeoutMs);
19528
+ r = await opts.exec(args, await appEnv(), timeoutMs);
19420
19529
  }
19421
19530
  return r;
19422
19531
  };