aai-lark-bridge 0.2.17 → 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.17",
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",
@@ -7105,6 +7105,7 @@ import { join as join19 } from "path";
7105
7105
  var LOGOUT_TEXT = "\u9000\u51FA Claude \u767B\u5F55";
7106
7106
  var MIN_TOKEN_LEFT_MS = 2 * 60 * 6e4;
7107
7107
  var LOGIN_MAX_MS = 10 * 6e4;
7108
+ var SUBMIT_MAX_MS = 3e4;
7108
7109
  function readCredentials(dir) {
7109
7110
  const f = join19(dir, ".credentials.json");
7110
7111
  if (!existsSync6(f)) return void 0;
@@ -7291,7 +7292,7 @@ function realClaudeCli(binary = process.env.SDLC_REAL_CLAUDE || "claude") {
7291
7292
  const keep = Object.fromEntries(Object.entries(process.env).filter(([k]) => /^(PATH|LANG|https?_proxy|no_proxy|HTTPS?_PROXY|NO_PROXY)$/.test(k)));
7292
7293
  return { ...keep, HOME: dir, CLAUDE_CONFIG_DIR: dir };
7293
7294
  };
7294
- const run = (args, dir, timeoutMs) => new Promise((resolve3) => {
7295
+ const run2 = (args, dir, timeoutMs) => new Promise((resolve3) => {
7295
7296
  void mkdtemp(join19(tmpdir4(), "claude-seat-")).then((cwd) => {
7296
7297
  const p3 = spawn(binary, args, { cwd, env: baseEnv(dir), stdio: ["ignore", "ignore", "ignore"] });
7297
7298
  const t = setTimeout(() => p3.kill("SIGTERM"), timeoutMs).unref();
@@ -7330,11 +7331,25 @@ function realClaudeCli(binary = process.env.SDLC_REAL_CLAUDE || "claude") {
7330
7331
  return {
7331
7332
  url,
7332
7333
  async submit(code) {
7334
+ const before = out.length;
7333
7335
  p3.stdin.end(`${code}
7334
7336
  `);
7335
- const rc = await exited;
7337
+ const verdict = await new Promise((resolve3) => {
7338
+ const check2 = () => {
7339
+ if (/Invalid code/i.test(out.slice(before))) resolve3("invalid");
7340
+ };
7341
+ p3.stdout.on("data", check2);
7342
+ p3.stderr.on("data", check2);
7343
+ check2();
7344
+ void exited.then(resolve3);
7345
+ setTimeout(() => resolve3("invalid"), SUBMIT_MAX_MS).unref();
7346
+ });
7336
7347
  clearTimeout(timer);
7337
- return rc === 0 && /Login successful/i.test(out);
7348
+ if (verdict === "invalid") {
7349
+ p3.kill("SIGTERM");
7350
+ return false;
7351
+ }
7352
+ return verdict === 0 && /Login successful/i.test(out);
7338
7353
  },
7339
7354
  cancel() {
7340
7355
  clearTimeout(timer);
@@ -7343,10 +7358,10 @@ function realClaudeCli(binary = process.env.SDLC_REAL_CLAUDE || "claude") {
7343
7358
  };
7344
7359
  },
7345
7360
  async refresh(dir) {
7346
- 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;
7347
7362
  },
7348
7363
  async logout(dir) {
7349
- await run(["auth", "logout"], dir, 3e4);
7364
+ await run2(["auth", "logout"], dir, 3e4);
7350
7365
  }
7351
7366
  };
7352
7367
  }
@@ -13355,12 +13370,12 @@ var ActiveRuns = class {
13355
13370
  this.reservations.delete(chatId);
13356
13371
  };
13357
13372
  }
13358
- register(chatId, run) {
13373
+ register(chatId, run2) {
13359
13374
  if (this.handles.has(chatId)) {
13360
13375
  throw new Error(`run already active for scope: ${chatId}`);
13361
13376
  }
13362
13377
  this.reservations.delete(chatId);
13363
- const handle2 = { run, interrupted: false };
13378
+ const handle2 = { run: run2, interrupted: false };
13364
13379
  this.handles.set(chatId, handle2);
13365
13380
  return handle2;
13366
13381
  }
@@ -13384,9 +13399,9 @@ var ActiveRuns = class {
13384
13399
  get(chatId) {
13385
13400
  return this.handles.get(chatId);
13386
13401
  }
13387
- unregister(chatId, run) {
13402
+ unregister(chatId, run2) {
13388
13403
  const existing = this.handles.get(chatId);
13389
- if (existing?.run === run) this.handles.delete(chatId);
13404
+ if (existing?.run === run2) this.handles.delete(chatId);
13390
13405
  }
13391
13406
  snapshot() {
13392
13407
  return [...this.handles.values()];
@@ -13538,7 +13553,7 @@ var RunExecutor = class {
13538
13553
  ...input.strictMcp ? { strictMcp: true } : {},
13539
13554
  ...input.extraEnv ? { extraEnv: input.extraEnv } : {}
13540
13555
  };
13541
- let run;
13556
+ let run2;
13542
13557
  try {
13543
13558
  await this.agent.prepareRun?.(runOptions);
13544
13559
  } catch (err) {
@@ -13556,7 +13571,7 @@ var RunExecutor = class {
13556
13571
  );
13557
13572
  }
13558
13573
  try {
13559
- run = this.agent.run(runOptions);
13574
+ run2 = this.agent.run(runOptions);
13560
13575
  } catch (err) {
13561
13576
  release();
13562
13577
  releaseScope();
@@ -13579,11 +13594,11 @@ var RunExecutor = class {
13579
13594
  });
13580
13595
  let handle2;
13581
13596
  try {
13582
- handle2 = this.activeRuns.register(input.scopeId, run);
13597
+ handle2 = this.activeRuns.register(input.scopeId, run2);
13583
13598
  } catch (err) {
13584
13599
  releaseScope();
13585
13600
  release();
13586
- await run.stop().catch(() => {
13601
+ await run2.stop().catch(() => {
13587
13602
  });
13588
13603
  throw new RunRejected(
13589
13604
  "run-already-active",
@@ -13594,16 +13609,16 @@ var RunExecutor = class {
13594
13609
  const cleanup = async (waitForExit) => {
13595
13610
  if (cleaned) return;
13596
13611
  cleaned = true;
13597
- this.activeRuns.unregister(input.scopeId, run);
13612
+ this.activeRuns.unregister(input.scopeId, run2);
13598
13613
  release();
13599
13614
  if (waitForExit) {
13600
- const exited = await run.waitForExit(this.postDoneExitGraceMs);
13615
+ const exited = await run2.waitForExit(this.postDoneExitGraceMs);
13601
13616
  if (!exited) {
13602
13617
  log.warn("run", "post-done-exit-timeout", {
13603
13618
  ...dimensions,
13604
13619
  graceMs: this.postDoneExitGraceMs
13605
13620
  });
13606
- await run.stop().catch((err) => {
13621
+ await run2.stop().catch((err) => {
13607
13622
  log.warn("run", "post-done-stop-failed", {
13608
13623
  ...dimensions,
13609
13624
  err: err instanceof Error ? err.message : String(err)
@@ -13612,7 +13627,7 @@ var RunExecutor = class {
13612
13627
  }
13613
13628
  }
13614
13629
  };
13615
- const fanout = new EventFanout(observeRunEvents(run.events, {
13630
+ const fanout = new EventFanout(observeRunEvents(run2.events, {
13616
13631
  dimensions,
13617
13632
  startedAt,
13618
13633
  now: this.now
@@ -13622,13 +13637,13 @@ var RunExecutor = class {
13622
13637
  return {
13623
13638
  runId,
13624
13639
  scopeId: input.scopeId,
13625
- run,
13640
+ run: run2,
13626
13641
  handle: handle2,
13627
13642
  subscribe: () => fanout.subscribe(),
13628
13643
  stop: async () => {
13629
13644
  handle2.interrupted = true;
13630
- await run.stop();
13631
- await run.waitForExit(this.postDoneExitGraceMs);
13645
+ await run2.stop();
13646
+ await run2.waitForExit(this.postDoneExitGraceMs);
13632
13647
  await cleanup(false);
13633
13648
  }
13634
13649
  };
@@ -14415,12 +14430,12 @@ var InboundMarkStore = class {
14415
14430
  }
14416
14431
  kick() {
14417
14432
  if (this.inFlight) return;
14418
- const run = this.drain().finally(() => {
14419
- if (this.inFlight !== run) return;
14433
+ const run2 = this.drain().finally(() => {
14434
+ if (this.inFlight !== run2) return;
14420
14435
  this.inFlight = void 0;
14421
14436
  if (this.pending) this.kick();
14422
14437
  });
14423
- this.inFlight = run;
14438
+ this.inFlight = run2;
14424
14439
  }
14425
14440
  /** Wait for in-flight and queued writes (disconnect and tests). */
14426
14441
  async flush() {
@@ -14878,10 +14893,10 @@ function installStreamResilience(channel, opts = {}) {
14878
14893
  messageIdByStream: /* @__PURE__ */ new WeakMap()
14879
14894
  };
14880
14895
  trackers.set(channel, tracker);
14881
- async function withRetry(op, target, run) {
14896
+ async function withRetry(op, target, run2) {
14882
14897
  for (let attempt = 1; ; attempt++) {
14883
14898
  try {
14884
- return await run();
14899
+ return await run2();
14885
14900
  } catch (err) {
14886
14901
  if (attempt >= maxAttempts || !isTransientWriteError(err)) throw err;
14887
14902
  const raw = err;
@@ -19239,6 +19254,105 @@ import { randomBytes as randomBytes10 } from "crypto";
19239
19254
  import { existsSync as existsSync9 } from "fs";
19240
19255
  import { mkdir as mkdir19, rm as rm14, writeFile as writeFile9 } from "fs/promises";
19241
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
19242
19356
  var USER_READ_SCOPES = [
19243
19357
  "search:message",
19244
19358
  "im:message.p2p_msg:get_as_user",
@@ -19390,18 +19504,28 @@ function createGateway(opts) {
19390
19504
  if (!existsSync9(join27(dir, "lark-channel", "config.json"))) {
19391
19505
  await mkdir19(dir, { recursive: true, mode: 448 });
19392
19506
  const r = await opts.exec(["config", "bind", "--source", "lark-channel", "--identity", identity], env(dir), 3e4);
19393
- 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}`);
19394
19508
  }
19395
19509
  bound2.add(dir);
19396
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
+ }
19397
19516
  const asApp = async (args, timeoutMs = 3e4) => {
19398
19517
  await ensureBound(appDir, "bot-only");
19399
- 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
+ }
19400
19524
  for (const wait of RATE_LIMIT_BACKOFF_MS) {
19401
19525
  if (r.code === 0 || !isRateLimited(r)) break;
19402
19526
  log.warn("user-gateway", "lark.rate-limited", { api: args.slice(0, 3).join(" "), retryInMs: wait });
19403
19527
  await sleep2(wait);
19404
- r = await opts.exec(args, env(appDir), timeoutMs);
19528
+ r = await opts.exec(args, await appEnv(), timeoutMs);
19405
19529
  }
19406
19530
  return r;
19407
19531
  };