aai-lark-bridge 0.2.9 → 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.9",
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",
@@ -14345,6 +14345,108 @@ function activeChannelCount(profile2) {
14345
14345
  return active2.get(profile2)?.size ?? 0;
14346
14346
  }
14347
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
+
14348
14450
  // src/bridge/bot/cot.ts
14349
14451
  var ENDPOINTS2 = {
14350
14452
  feishu: "https://open.feishu.cn",
@@ -14836,6 +14938,7 @@ async function startChannel(deps) {
14836
14938
  respectProxyEnv: true
14837
14939
  };
14838
14940
  const channel = createLarkChannel(opts);
14941
+ installStreamResilience(channel);
14839
14942
  const media = new MediaCache(channel, deps.appPaths?.mediaDir);
14840
14943
  const pending = new PendingQueue(DEBOUNCE_MS, (scope, batch) => {
14841
14944
  const firstMsg = batch[0];
@@ -15703,6 +15806,7 @@ async function runAgentBatch(deps) {
15703
15806
  let latestState = startState;
15704
15807
  let producerStarted = false;
15705
15808
  let markdownCtrl;
15809
+ const streamOpts = { ...sendOpts };
15706
15810
  const progress = createLazyProgressStream(
15707
15811
  scope,
15708
15812
  replyMode,
@@ -15717,7 +15821,7 @@ async function runAgentBatch(deps) {
15717
15821
  await renderDone;
15718
15822
  }
15719
15823
  },
15720
- sendOpts
15824
+ streamOpts
15721
15825
  )
15722
15826
  );
15723
15827
  const renderDone = processAgentStream(
@@ -15750,7 +15854,20 @@ async function runAgentBatch(deps) {
15750
15854
  }
15751
15855
  });
15752
15856
  } catch (err) {
15753
- 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
+ }
15754
15871
  log.fail("stream", err, { mode: replyMode, step: "progress-stream" });
15755
15872
  }
15756
15873
  await recallIfEmptyStreamedReply(channel, progress, forView(latestState), scope);
@@ -15780,6 +15897,18 @@ async function runAgentBatch(deps) {
15780
15897
  sendOpts,
15781
15898
  cardRenderOptions
15782
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
+ });
15783
15912
  }
15784
15913
  } else {
15785
15914
  const finalState = await processAgentStream(
@@ -15813,14 +15942,24 @@ function createLazyProgressStream(scope, mode, open4) {
15813
15942
  let stream2;
15814
15943
  let openedAt;
15815
15944
  let givenUp = false;
15945
+ let isSettled = false;
15816
15946
  let settle;
15817
15947
  const settled = new Promise((resolve3, reject4) => {
15818
15948
  settle = (result) => {
15819
15949
  result.then(resolve3, reject4);
15820
15950
  };
15821
15951
  });
15952
+ settled.then(
15953
+ () => {
15954
+ isSettled = true;
15955
+ },
15956
+ () => {
15957
+ isSettled = true;
15958
+ }
15959
+ );
15822
15960
  return {
15823
15961
  settled,
15962
+ isSettled: () => isSettled,
15824
15963
  opened: () => stream2 !== void 0,
15825
15964
  openedAt: () => openedAt,
15826
15965
  ensureOpen: () => {
@@ -15872,25 +16011,54 @@ function scheduleProgressTerminalUpdate(channel, progress, state, scope, mode) {
15872
16011
  void progress.settled.then(async (result) => {
15873
16012
  const messageId = result?.messageId;
15874
16013
  if (!messageId) return;
15875
- try {
15876
- const terminalState = {
15877
- ...state,
15878
- // Markdown never shows reasoning; a repair must preserve that boundary.
15879
- reasoning: mode === "markdown" ? { content: "", active: false } : state.reasoning,
15880
- blocks: state.terminal === "done" ? [...state.blocks, { kind: "text", content: "\u672C\u8F6E\u6267\u884C\u5DF2\u7ED3\u675F\u3002", streaming: false }] : state.blocks
15881
- };
15882
- await channel.updateCard(messageId, renderCard(terminalState));
15883
- log.info("outbound", "progress-terminal-updated", { scope, messageId, terminal: state.terminal });
15884
- } catch (err) {
15885
- log.warn("outbound", "progress-terminal-update-failed", {
15886
- scope,
15887
- messageId,
15888
- err: err instanceof Error ? err.message : String(err)
15889
- });
15890
- }
16014
+ await repairProgressMessage(channel, messageId, state, scope, mode);
15891
16015
  }, () => {
15892
16016
  });
15893
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
+ }
15894
16062
  async function recallIfEmptyStreamedReply(channel, progress, finalState, scope) {
15895
16063
  if (!progress.opened()) return;
15896
16064
  if (progress.abandoned()) {