aai-lark-bridge 0.2.8 → 0.2.10

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.8",
7
+ version: "0.2.10",
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",
@@ -1541,15 +1541,31 @@ var log = {
1541
1541
  const stack = err instanceof Error ? err.stack : void 0;
1542
1542
  const apiData = err?.response?.data;
1543
1543
  const apiStatus = err?.response?.status;
1544
+ const code = err?.code;
1545
+ const cause = err instanceof Error && "cause" in err && err.cause !== void 0 ? describeCause(err.cause) : void 0;
1544
1546
  emit("error", phase, "fail", {
1545
1547
  ...fields,
1546
1548
  err: message,
1549
+ ...typeof code === "string" ? { code } : {},
1547
1550
  apiStatus,
1548
1551
  apiData,
1549
- stack
1552
+ stack,
1553
+ ...cause !== void 0 ? { cause } : {}
1550
1554
  });
1551
1555
  }
1552
1556
  };
1557
+ function describeCause(cause) {
1558
+ if (!(cause instanceof Error)) return String(cause);
1559
+ const c = cause;
1560
+ return {
1561
+ name: c.name,
1562
+ message: c.message,
1563
+ ...c.code !== void 0 ? { code: c.code } : {},
1564
+ ...c.errno !== void 0 ? { errno: c.errno } : {},
1565
+ ...c.syscall !== void 0 ? { syscall: c.syscall } : {},
1566
+ ...c.stack ? { stack: c.stack } : {}
1567
+ };
1568
+ }
1553
1569
  function configureLogger(opts) {
1554
1570
  if (stream) {
1555
1571
  try {
@@ -1569,6 +1585,9 @@ function withTrace(ctx, fn) {
1569
1585
  const traceId = ctx.traceId ?? newTraceId();
1570
1586
  return als.run({ ...ctx, traceId }, fn);
1571
1587
  }
1588
+ function currentTraceId() {
1589
+ return als.getStore()?.traceId;
1590
+ }
1572
1591
  function newTraceId() {
1573
1592
  return Math.random().toString(36).slice(2, 10);
1574
1593
  }
@@ -14326,6 +14345,108 @@ function activeChannelCount(profile2) {
14326
14345
  return active2.get(profile2)?.size ?? 0;
14327
14346
  }
14328
14347
 
14348
+ // src/bridge/bot/stream-resilience.ts
14349
+ var DEFAULT_MAX_ATTEMPTS = 3;
14350
+ var DEFAULT_BASE_DELAY_MS = 500;
14351
+ var FEISHU_INTERNAL_ERROR_CODE = 2200;
14352
+ var trackers = /* @__PURE__ */ new WeakMap();
14353
+ function isTransientWriteError(err) {
14354
+ const raw = err;
14355
+ if (raw?.response?.data?.code === FEISHU_INTERNAL_ERROR_CODE) return true;
14356
+ const status = raw?.response?.status;
14357
+ if (typeof status === "number") return status === 429 || status >= 500;
14358
+ return typeof raw?.code === "string";
14359
+ }
14360
+ function installStreamResilience(channel, opts = {}) {
14361
+ const sender = channel.sender;
14362
+ const methods = [
14363
+ "updateCardElementContent",
14364
+ "sendCardByReference",
14365
+ "finishStreamingCard",
14366
+ "patchCard"
14367
+ ];
14368
+ if (!sender || methods.some((m) => typeof sender[m] !== "function")) {
14369
+ log.warn("stream", "resilience-unavailable", {
14370
+ reason: "channel \u672A\u66B4\u9732 outbound sender\uFF08SDK \u7248\u672C\u53D8\u52A8\uFF1F\uFF09\uFF0C\u6D41\u5F0F\u5199\u5165\u4E0D\u91CD\u8BD5"
14371
+ });
14372
+ return false;
14373
+ }
14374
+ const s = sender;
14375
+ const maxAttempts = opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
14376
+ const baseDelayMs = opts.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;
14377
+ const sleep2 = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
14378
+ const tracker = {
14379
+ streamOptsByCard: /* @__PURE__ */ new Map(),
14380
+ lostStreams: /* @__PURE__ */ new WeakSet(),
14381
+ messageIdByStream: /* @__PURE__ */ new WeakMap()
14382
+ };
14383
+ trackers.set(channel, tracker);
14384
+ async function withRetry(op, target, run) {
14385
+ for (let attempt = 1; ; attempt++) {
14386
+ try {
14387
+ return await run();
14388
+ } catch (err) {
14389
+ if (attempt >= maxAttempts || !isTransientWriteError(err)) throw err;
14390
+ const raw = err;
14391
+ log.warn("stream", "write-retry", {
14392
+ op,
14393
+ target,
14394
+ attempt,
14395
+ status: raw?.response?.status,
14396
+ code: raw?.response?.data?.code
14397
+ });
14398
+ await sleep2(baseDelayMs * 3 ** (attempt - 1));
14399
+ }
14400
+ }
14401
+ }
14402
+ const sendCardByReference = s.sendCardByReference.bind(s);
14403
+ s.sendCardByReference = async (to, idType, cardId, streamOpts) => {
14404
+ const messageId = await sendCardByReference(to, idType, cardId, streamOpts);
14405
+ if (streamOpts && typeof streamOpts === "object") {
14406
+ tracker.streamOptsByCard.set(cardId, streamOpts);
14407
+ if (typeof messageId === "string") tracker.messageIdByStream.set(streamOpts, messageId);
14408
+ }
14409
+ return messageId;
14410
+ };
14411
+ const updateCardElementContent = s.updateCardElementContent.bind(s);
14412
+ s.updateCardElementContent = async (cardId, elementId, content, sequence) => {
14413
+ try {
14414
+ await withRetry(
14415
+ "element-content",
14416
+ cardId,
14417
+ () => updateCardElementContent(cardId, elementId, content, sequence)
14418
+ );
14419
+ } catch (err) {
14420
+ const streamOpts = tracker.streamOptsByCard.get(cardId);
14421
+ if (streamOpts) tracker.lostStreams.add(streamOpts);
14422
+ log.warn("stream", "write-lost", {
14423
+ cardId,
14424
+ sequence,
14425
+ tracked: streamOpts !== void 0,
14426
+ err: err instanceof Error ? err.message : String(err)
14427
+ });
14428
+ throw err;
14429
+ }
14430
+ };
14431
+ const finishStreamingCard = s.finishStreamingCard.bind(s);
14432
+ s.finishStreamingCard = async (cardId, sequence, summary) => {
14433
+ try {
14434
+ await withRetry("finish", cardId, () => finishStreamingCard(cardId, sequence, summary));
14435
+ } finally {
14436
+ tracker.streamOptsByCard.delete(cardId);
14437
+ }
14438
+ };
14439
+ const patchCard = s.patchCard.bind(s);
14440
+ s.patchCard = (messageId, card) => withRetry("patch", messageId, () => patchCard(messageId, card));
14441
+ return true;
14442
+ }
14443
+ function streamWritesLost(channel, streamOpts) {
14444
+ return trackers.get(channel)?.lostStreams.has(streamOpts) ?? false;
14445
+ }
14446
+ function streamMessageId(channel, streamOpts) {
14447
+ return trackers.get(channel)?.messageIdByStream.get(streamOpts);
14448
+ }
14449
+
14329
14450
  // src/bridge/bot/cot.ts
14330
14451
  var ENDPOINTS2 = {
14331
14452
  feishu: "https://open.feishu.cn",
@@ -14817,6 +14938,7 @@ async function startChannel(deps) {
14817
14938
  respectProxyEnv: true
14818
14939
  };
14819
14940
  const channel = createLarkChannel(opts);
14941
+ installStreamResilience(channel);
14820
14942
  const media = new MediaCache(channel, deps.appPaths?.mediaDir);
14821
14943
  const pending = new PendingQueue(DEBOUNCE_MS, (scope, batch) => {
14822
14944
  const firstMsg = batch[0];
@@ -15283,6 +15405,10 @@ function dmBinding(controls, msg, scope, opts = {}) {
15283
15405
  }
15284
15406
  return result;
15285
15407
  }
15408
+ function spawnFailedReply() {
15409
+ const traceId = currentTraceId();
15410
+ return "\u26A0\uFE0F \u8FD9\u6761\u6D88\u606F\u6CA1\u6709\u4EA4\u7ED9 agent\uFF1Abridge \u6CA1\u80FD\u542F\u52A8 agent\u3002\u8BF7\u7A0D\u540E\u91CD\u53D1\uFF1B\u8FDE\u7EED\u5931\u8D25\u8BF7\u8054\u7CFB bridge \u7BA1\u7406\u5458\u91CD\u542F bridge" + (traceId ? `\uFF0C\u5E76\u9644\u4E0A\u6392\u67E5\u7F16\u53F7 ${traceId}\u3002` : "\u3002");
15411
+ }
15286
15412
  async function runAgentBatch(deps) {
15287
15413
  const {
15288
15414
  channel,
@@ -15428,6 +15554,13 @@ async function runAgentBatch(deps) {
15428
15554
  source: "im",
15429
15555
  stage: "submit"
15430
15556
  }
15557
+ }).catch(async (err) => {
15558
+ if (err instanceof SpawnFailed) {
15559
+ await channel.send(chatId, { markdown: spawnFailedReply() }, sendOpts).catch((replyErr) => {
15560
+ log.fail("flush", replyErr, { step: "postSpawnFailedReply" });
15561
+ });
15562
+ }
15563
+ throw err;
15431
15564
  });
15432
15565
  if (!flow.ok) {
15433
15566
  log.info("run-flow", "rejected", { scope, code: flow.rejectReason.code });
@@ -15673,6 +15806,7 @@ async function runAgentBatch(deps) {
15673
15806
  let latestState = startState;
15674
15807
  let producerStarted = false;
15675
15808
  let markdownCtrl;
15809
+ const streamOpts = { ...sendOpts };
15676
15810
  const progress = createLazyProgressStream(
15677
15811
  scope,
15678
15812
  replyMode,
@@ -15687,7 +15821,7 @@ async function runAgentBatch(deps) {
15687
15821
  await renderDone;
15688
15822
  }
15689
15823
  },
15690
- sendOpts
15824
+ streamOpts
15691
15825
  )
15692
15826
  );
15693
15827
  const renderDone = processAgentStream(
@@ -15720,7 +15854,20 @@ async function runAgentBatch(deps) {
15720
15854
  }
15721
15855
  });
15722
15856
  } catch (err) {
15723
- if (controls.profileConfig.agentKind !== "codex") throw err;
15857
+ if (controls.profileConfig.agentKind !== "codex") {
15858
+ await redeliverIfStreamWritesLost({
15859
+ channel,
15860
+ chatId,
15861
+ scope,
15862
+ progress,
15863
+ streamOpts,
15864
+ state: forView(latestState),
15865
+ replyMode,
15866
+ sendOpts,
15867
+ cardRenderOptions
15868
+ });
15869
+ throw err;
15870
+ }
15724
15871
  log.fail("stream", err, { mode: replyMode, step: "progress-stream" });
15725
15872
  }
15726
15873
  await recallIfEmptyStreamedReply(channel, progress, forView(latestState), scope);
@@ -15750,6 +15897,18 @@ async function runAgentBatch(deps) {
15750
15897
  sendOpts,
15751
15898
  cardRenderOptions
15752
15899
  });
15900
+ } else {
15901
+ await redeliverIfStreamWritesLost({
15902
+ channel,
15903
+ chatId,
15904
+ scope,
15905
+ progress,
15906
+ streamOpts,
15907
+ state: forView(latestState),
15908
+ replyMode,
15909
+ sendOpts,
15910
+ cardRenderOptions
15911
+ });
15753
15912
  }
15754
15913
  } else {
15755
15914
  const finalState = await processAgentStream(
@@ -15783,14 +15942,24 @@ function createLazyProgressStream(scope, mode, open4) {
15783
15942
  let stream2;
15784
15943
  let openedAt;
15785
15944
  let givenUp = false;
15945
+ let isSettled = false;
15786
15946
  let settle;
15787
15947
  const settled = new Promise((resolve3, reject4) => {
15788
15948
  settle = (result) => {
15789
15949
  result.then(resolve3, reject4);
15790
15950
  };
15791
15951
  });
15952
+ settled.then(
15953
+ () => {
15954
+ isSettled = true;
15955
+ },
15956
+ () => {
15957
+ isSettled = true;
15958
+ }
15959
+ );
15792
15960
  return {
15793
15961
  settled,
15962
+ isSettled: () => isSettled,
15794
15963
  opened: () => stream2 !== void 0,
15795
15964
  openedAt: () => openedAt,
15796
15965
  ensureOpen: () => {
@@ -15842,25 +16011,54 @@ function scheduleProgressTerminalUpdate(channel, progress, state, scope, mode) {
15842
16011
  void progress.settled.then(async (result) => {
15843
16012
  const messageId = result?.messageId;
15844
16013
  if (!messageId) return;
15845
- try {
15846
- const terminalState = {
15847
- ...state,
15848
- // Markdown never shows reasoning; a repair must preserve that boundary.
15849
- reasoning: mode === "markdown" ? { content: "", active: false } : state.reasoning,
15850
- blocks: state.terminal === "done" ? [...state.blocks, { kind: "text", content: "\u672C\u8F6E\u6267\u884C\u5DF2\u7ED3\u675F\u3002", streaming: false }] : state.blocks
15851
- };
15852
- await channel.updateCard(messageId, renderCard(terminalState));
15853
- log.info("outbound", "progress-terminal-updated", { scope, messageId, terminal: state.terminal });
15854
- } catch (err) {
15855
- log.warn("outbound", "progress-terminal-update-failed", {
15856
- scope,
15857
- messageId,
15858
- err: err instanceof Error ? err.message : String(err)
15859
- });
15860
- }
16014
+ await repairProgressMessage(channel, messageId, state, scope, mode);
15861
16015
  }, () => {
15862
16016
  });
15863
16017
  }
16018
+ async function repairProgressMessage(channel, messageId, state, scope, mode) {
16019
+ try {
16020
+ const terminalState = {
16021
+ ...state,
16022
+ // Markdown never shows reasoning; a repair must preserve that boundary.
16023
+ reasoning: mode === "markdown" ? { content: "", active: false } : state.reasoning,
16024
+ blocks: state.terminal === "done" ? [...state.blocks, { kind: "text", content: "\u672C\u8F6E\u6267\u884C\u5DF2\u7ED3\u675F\u3002", streaming: false }] : state.blocks
16025
+ };
16026
+ await channel.updateCard(messageId, renderCard(terminalState));
16027
+ log.info("outbound", "progress-terminal-updated", { scope, messageId, terminal: state.terminal });
16028
+ } catch (err) {
16029
+ log.warn("outbound", "progress-terminal-update-failed", {
16030
+ scope,
16031
+ messageId,
16032
+ err: err instanceof Error ? err.message : String(err)
16033
+ });
16034
+ }
16035
+ }
16036
+ async function redeliverIfStreamWritesLost(input) {
16037
+ const { channel, progress, scope } = input;
16038
+ if (!progress.opened() || progress.abandoned()) return;
16039
+ const check2 = async () => {
16040
+ const result = await progress.settled.catch(() => void 0);
16041
+ if (!streamWritesLost(channel, input.streamOpts)) return;
16042
+ const messageId = result?.messageId ?? streamMessageId(channel, input.streamOpts);
16043
+ log.warn("stream", "writes-lost-redeliver", { scope, mode: input.replyMode, messageId });
16044
+ await sendFinalReply({
16045
+ channel,
16046
+ chatId: input.chatId,
16047
+ scope,
16048
+ state: tailTextState(input.state),
16049
+ replyMode: input.replyMode,
16050
+ sendOpts: input.sendOpts,
16051
+ cardRenderOptions: input.cardRenderOptions
16052
+ });
16053
+ if (messageId && renderText(input.state).trim() !== "") {
16054
+ await repairProgressMessage(channel, messageId, input.state, scope, input.replyMode);
16055
+ }
16056
+ };
16057
+ const checked = check2().catch(
16058
+ (err) => log.fail("stream", err, { step: "writes-lost-redeliver" })
16059
+ );
16060
+ if (progress.isSettled()) await checked;
16061
+ }
15864
16062
  async function recallIfEmptyStreamedReply(channel, progress, finalState, scope) {
15865
16063
  if (!progress.opened()) return;
15866
16064
  if (progress.abandoned()) {