aai-lark-bridge 0.2.5 → 0.2.7

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.5",
7
+ version: "0.2.7",
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",
@@ -6235,6 +6235,9 @@ function* translateEvent(raw) {
6235
6235
  };
6236
6236
  return;
6237
6237
  }
6238
+ if (typeof evt.result === "string" && evt.result.trim()) {
6239
+ yield { type: "final_text", content: evt.result };
6240
+ }
6238
6241
  yield { type: "done", sessionId: evt.session_id, terminationReason: "normal" };
6239
6242
  }
6240
6243
  }
@@ -7147,6 +7150,8 @@ import {
7147
7150
  mkdirSync as mkdirSync3,
7148
7151
  readFileSync as readFileSync3,
7149
7152
  realpathSync,
7153
+ renameSync as renameSync2,
7154
+ rmSync as rmSync2,
7150
7155
  statSync,
7151
7156
  unlinkSync as unlinkSync2,
7152
7157
  writeFileSync as writeFileSync3
@@ -7241,6 +7246,85 @@ function resolveBinding(rawConfig, chatId, senderOpenId) {
7241
7246
  }
7242
7247
  };
7243
7248
  }
7249
+ function taskOfMessage(dir, messageId) {
7250
+ if (!messageId || !safeName(messageId)) return void 0;
7251
+ try {
7252
+ const v = JSON.parse(readFileSync3(join19(dir, "messages", `${messageId}.json`), "utf8"));
7253
+ return typeof v.task_id === "string" && v.task_id !== "" ? v.task_id : void 0;
7254
+ } catch {
7255
+ return void 0;
7256
+ }
7257
+ }
7258
+ var LOCK_WAIT_MS = 2e3;
7259
+ var LOCK_STEP_MS = 50;
7260
+ var LOCK_STALE_MS = 1e4;
7261
+ var sleepSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
7262
+ function withChatLock(dir, chatId, fn) {
7263
+ const lock5 = join19(dir, "chats", `${chatId}.lock`);
7264
+ const until = Date.now() + LOCK_WAIT_MS;
7265
+ for (; ; ) {
7266
+ try {
7267
+ mkdirSync3(lock5);
7268
+ break;
7269
+ } catch (err) {
7270
+ if (err.code !== "EEXIST") throw err;
7271
+ try {
7272
+ if (Date.now() - statSync(lock5).mtimeMs > LOCK_STALE_MS) {
7273
+ rmSync2(lock5, { recursive: true, force: true });
7274
+ continue;
7275
+ }
7276
+ } catch {
7277
+ continue;
7278
+ }
7279
+ if (Date.now() >= until) throw new Error(`binding locked for over ${LOCK_WAIT_MS} ms`);
7280
+ sleepSync(LOCK_STEP_MS);
7281
+ }
7282
+ }
7283
+ try {
7284
+ return fn();
7285
+ } finally {
7286
+ rmSync2(lock5, { recursive: true, force: true });
7287
+ }
7288
+ }
7289
+ function switchByReply(rawConfig, chatId, senderOpenId, messageIds, now = /* @__PURE__ */ new Date()) {
7290
+ const cfg = taskBindingsConfig(rawConfig);
7291
+ if (!cfg || !safeName(chatId)) return void 0;
7292
+ const replied = messageIds.find((id) => taskOfMessage(cfg.dir, id));
7293
+ const taskId = taskOfMessage(cfg.dir, replied);
7294
+ if (!replied || !taskId) return void 0;
7295
+ const file = join19(cfg.dir, "chats", `${chatId}.json`);
7296
+ if (!existsSync6(file)) return void 0;
7297
+ const moved = withChatLock(cfg.dir, chatId, () => {
7298
+ const doc = JSON.parse(readFileSync3(file, "utf8"));
7299
+ if (doc.version !== BINDING_VERSION || doc.chat_id !== chatId || doc.user_open_id !== senderOpenId) return void 0;
7300
+ if (doc.active?.task_id === taskId) return void 0;
7301
+ const queue = Array.isArray(doc.queue) ? doc.queue : [];
7302
+ const i = queue.findIndex((x) => x?.task_id === taskId);
7303
+ if (i < 0) return void 0;
7304
+ const item = queue.splice(i, 1)[0];
7305
+ const from = doc.active ?? null;
7306
+ if (from) queue.unshift(from);
7307
+ const next = { ...doc, active: item, queue, updated_at: now.toISOString() };
7308
+ const tmp = `${file}.new-${process.pid}`;
7309
+ writeFileSync3(tmp, JSON.stringify(next, null, 2), { mode: 384 });
7310
+ renameSync2(tmp, file);
7311
+ return { from: from?.task_id ?? null, to: taskId };
7312
+ });
7313
+ if (!moved) return void 0;
7314
+ const event = { type: "switched", chat_id: chatId, task_id: moved.to, from_task_id: moved.from, message_id: replied, at: now.toISOString() };
7315
+ let eventWritten = false;
7316
+ try {
7317
+ const eventsDir = join19(cfg.dir, "events");
7318
+ mkdirSync3(eventsDir, { recursive: true });
7319
+ const tmp = join19(eventsDir, `.${randomBytes4(6).toString("hex")}.tmp`);
7320
+ writeFileSync3(tmp, JSON.stringify(event));
7321
+ renameSync2(tmp, join19(eventsDir, `switch-${now.getTime()}-${randomBytes4(4).toString("hex")}.json`));
7322
+ eventWritten = true;
7323
+ } catch {
7324
+ eventWritten = false;
7325
+ }
7326
+ return { ...moved, eventWritten };
7327
+ }
7244
7328
  function ledgerFile(dir, ledgerKey) {
7245
7329
  return join19(dir, "spend", `${ledgerKey}.jsonl`);
7246
7330
  }
@@ -11960,7 +12044,7 @@ async function lookupMessageThreadId(channel, messageId) {
11960
12044
 
11961
12045
  // src/bridge/card/handoff.ts
11962
12046
  import { createHash as createHash4 } from "crypto";
11963
- import { existsSync as existsSync7, mkdirSync as mkdirSync4, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
12047
+ import { existsSync as existsSync7, mkdirSync as mkdirSync4, renameSync as renameSync3, writeFileSync as writeFileSync4 } from "fs";
11964
12048
  import { isAbsolute as isAbsolute4, join as join22 } from "path";
11965
12049
  function handoffDirs(raw) {
11966
12050
  if (!raw || typeof raw !== "object") return {};
@@ -12003,7 +12087,7 @@ function tryHandoff(evt, dirs) {
12003
12087
  received_at: (/* @__PURE__ */ new Date()).toISOString()
12004
12088
  })
12005
12089
  );
12006
- renameSync2(tmp, file);
12090
+ renameSync3(tmp, file);
12007
12091
  log.info("cardAction", "handoff", { kind, file: name });
12008
12092
  } catch (err) {
12009
12093
  log.fail("cardAction", err, { kind, step: "handoff" });
@@ -13712,7 +13796,7 @@ function preview(text) {
13712
13796
 
13713
13797
  // src/bridge/bot/doc-confirmation.ts
13714
13798
  import { createHash as createHash7 } from "crypto";
13715
- import { mkdirSync as mkdirSync5, realpathSync as realpathSync2, renameSync as renameSync3, writeFileSync as writeFileSync5 } from "fs";
13799
+ import { mkdirSync as mkdirSync5, realpathSync as realpathSync2, renameSync as renameSync4, writeFileSync as writeFileSync5 } from "fs";
13716
13800
  import { isAbsolute as isAbsolute5, join as join24, sep as sep3 } from "path";
13717
13801
  import { spawn } from "child_process";
13718
13802
  var waking = /* @__PURE__ */ new Set();
@@ -13733,7 +13817,7 @@ function enqueueDocConfirmation(workspace, event, { selfReply = false } = {}) {
13733
13817
  const target = join24(inbox, key + ".json");
13734
13818
  const tmp = target + `.new-${process.pid}`;
13735
13819
  writeFileSync5(tmp, JSON.stringify(hint), { mode: 384 });
13736
- renameSync3(tmp, target);
13820
+ renameSync4(tmp, target);
13737
13821
  if (!waking.has(root)) {
13738
13822
  waking.add(root);
13739
13823
  try {
@@ -15130,7 +15214,7 @@ async function intakeMessage(deps) {
15130
15214
  );
15131
15215
  return;
15132
15216
  }
15133
- const binding = emsg.chatType === "p2p" ? dmBinding(controls, emsg, scope) : void 0;
15217
+ const binding = emsg.chatType === "p2p" ? dmBinding(controls, emsg, scope, { switchByReply: true }) : void 0;
15134
15218
  if (binding?.kind === "invalid") {
15135
15219
  await channel.send(emsg.chatId, { markdown: BINDING_INVALID_REPLY }, { replyTo: emsg.messageId }).catch(
15136
15220
  (err) => log.warn("binding", "invalid-reply-failed", { err: String(err) })
@@ -15169,9 +15253,17 @@ async function intakeMessage(deps) {
15169
15253
  const size = pending.push(scope, emsg);
15170
15254
  log.info("intake", "queued", { scope, queueSize: size, debounceMs: DEBOUNCE_MS });
15171
15255
  }
15172
- function dmBinding(controls, msg, scope) {
15256
+ function dmBinding(controls, msg, scope, opts = {}) {
15173
15257
  const cfg = controls.profileConfig.preferences.taskBindings;
15174
15258
  if (!cfg) return void 0;
15259
+ if (opts.switchByReply) {
15260
+ try {
15261
+ const moved = switchByReply(cfg, msg.chatId, msg.senderId, [msg.replyToMessageId, msg.rootId]);
15262
+ if (moved) log.info("binding", "switched-by-reply", { scope, from: moved.from, to: moved.to, eventWritten: moved.eventWritten });
15263
+ } catch (err) {
15264
+ log.warn("binding", "switch-by-reply-failed", { scope, reason: err instanceof Error ? err.message : String(err) });
15265
+ }
15266
+ }
15175
15267
  let result;
15176
15268
  try {
15177
15269
  result = resolveBinding(cfg, msg.chatId, msg.senderId);
@@ -15414,6 +15506,11 @@ async function runAgentBatch(deps) {
15414
15506
  if (getShowToolCalls(controls.cfg)) return state;
15415
15507
  return { ...state, blocks: state.blocks.filter((b) => b.kind !== "tool") };
15416
15508
  };
15509
+ const forView = (state) => {
15510
+ const s = filterForPrefs(state);
15511
+ if (controls.profileConfig.agentKind === "codex" || !s.finalText) return s;
15512
+ return { ...s, blocks: [{ kind: "text", content: s.finalText, streaming: false }] };
15513
+ };
15417
15514
  const cardRenderOptions = callbackAuth ? {
15418
15515
  signCallback: (action) => callbackAuth.sign({
15419
15516
  runId: execution.runId,
@@ -15494,7 +15591,7 @@ async function runAgentBatch(deps) {
15494
15591
  producerStarted = true;
15495
15592
  if (progress.abandoned()) return;
15496
15593
  cardCtrl = ctrl;
15497
- await ctrl.update(renderCard(filterForPrefs(latestState), cardRenderOptions));
15594
+ await ctrl.update(renderCard(forView(latestState), cardRenderOptions));
15498
15595
  await renderDone;
15499
15596
  }
15500
15597
  }
@@ -15512,7 +15609,7 @@ async function runAgentBatch(deps) {
15512
15609
  latestState = state;
15513
15610
  if (shouldOpenProgressStream(filterForPrefs(state))) progress.ensureOpen();
15514
15611
  if (cardCtrl) {
15515
- await cardCtrl.update(renderCard(filterForPrefs(state), cardRenderOptions));
15612
+ await cardCtrl.update(renderCard(forView(state), cardRenderOptions));
15516
15613
  }
15517
15614
  },
15518
15615
  startState
@@ -15525,10 +15622,10 @@ async function runAgentBatch(deps) {
15525
15622
  producerStarted: () => producerStarted,
15526
15623
  fallback: async (state) => {
15527
15624
  if (controls.profileConfig.agentKind === "codex") return;
15528
- if (renderText(filterForPrefs(state)).trim() === "") return;
15625
+ if (renderText(forView(state)).trim() === "") return;
15529
15626
  await channel.send(
15530
15627
  chatId,
15531
- { card: renderCard(filterForPrefs(state), cardRenderOptions) },
15628
+ { card: renderCard(forView(state), cardRenderOptions) },
15532
15629
  sendOpts
15533
15630
  );
15534
15631
  }
@@ -15537,8 +15634,8 @@ async function runAgentBatch(deps) {
15537
15634
  if (controls.profileConfig.agentKind !== "codex") throw err;
15538
15635
  log.fail("stream", err, { mode: replyMode, step: "progress-stream" });
15539
15636
  }
15540
- await recallIfEmptyStreamedReply(channel, progress, filterForPrefs(latestState), scope);
15541
- scheduleProgressTerminalUpdate(channel, progress, filterForPrefs(latestState), scope, replyMode);
15637
+ await recallIfEmptyStreamedReply(channel, progress, forView(latestState), scope);
15638
+ scheduleProgressTerminalUpdate(channel, progress, forView(latestState), scope, replyMode);
15542
15639
  if (controls.profileConfig.agentKind === "codex") {
15543
15640
  await sendFinalReply({
15544
15641
  channel,
@@ -15559,7 +15656,7 @@ async function runAgentBatch(deps) {
15559
15656
  channel,
15560
15657
  chatId,
15561
15658
  scope,
15562
- state: tailTextState(filterForPrefs(latestState)),
15659
+ state: tailTextState(forView(latestState)),
15563
15660
  replyMode,
15564
15661
  sendOpts,
15565
15662
  cardRenderOptions
@@ -15579,7 +15676,7 @@ async function runAgentBatch(deps) {
15579
15676
  producerStarted = true;
15580
15677
  if (progress.abandoned()) return;
15581
15678
  markdownCtrl = ctrl;
15582
- await ctrl.setContent(renderText(filterForPrefs(latestState)));
15679
+ await ctrl.setContent(renderText(forView(latestState)));
15583
15680
  await renderDone;
15584
15681
  }
15585
15682
  },
@@ -15596,7 +15693,7 @@ async function runAgentBatch(deps) {
15596
15693
  latestState = state;
15597
15694
  if (shouldOpenProgressStream(filterForPrefs(state))) progress.ensureOpen();
15598
15695
  if (markdownCtrl) {
15599
- await markdownCtrl.setContent(renderText(filterForPrefs(state)));
15696
+ await markdownCtrl.setContent(renderText(forView(state)));
15600
15697
  }
15601
15698
  },
15602
15699
  startState
@@ -15609,7 +15706,7 @@ async function runAgentBatch(deps) {
15609
15706
  producerStarted: () => producerStarted,
15610
15707
  fallback: async (state) => {
15611
15708
  if (controls.profileConfig.agentKind === "codex") return;
15612
- const body = renderText(filterForPrefs(state));
15709
+ const body = renderText(forView(state));
15613
15710
  if (body.trim()) {
15614
15711
  await channel.send(chatId, { markdown: body }, sendOpts);
15615
15712
  }
@@ -15619,8 +15716,8 @@ async function runAgentBatch(deps) {
15619
15716
  if (controls.profileConfig.agentKind !== "codex") throw err;
15620
15717
  log.fail("stream", err, { mode: replyMode, step: "progress-stream" });
15621
15718
  }
15622
- await recallIfEmptyStreamedReply(channel, progress, filterForPrefs(latestState), scope);
15623
- scheduleProgressTerminalUpdate(channel, progress, filterForPrefs(latestState), scope, replyMode);
15719
+ await recallIfEmptyStreamedReply(channel, progress, forView(latestState), scope);
15720
+ scheduleProgressTerminalUpdate(channel, progress, forView(latestState), scope, replyMode);
15624
15721
  if (controls.profileConfig.agentKind === "codex") {
15625
15722
  await sendFinalReply({
15626
15723
  channel,
@@ -15641,7 +15738,7 @@ async function runAgentBatch(deps) {
15641
15738
  channel,
15642
15739
  chatId,
15643
15740
  scope,
15644
- state: tailTextState(filterForPrefs(latestState)),
15741
+ state: tailTextState(forView(latestState)),
15645
15742
  replyMode,
15646
15743
  sendOpts,
15647
15744
  cardRenderOptions
@@ -15662,7 +15759,7 @@ async function runAgentBatch(deps) {
15662
15759
  channel,
15663
15760
  chatId,
15664
15761
  scope,
15665
- state: controls.profileConfig.agentKind === "codex" ? finalAnswerOnlyState(filterForPrefs(finalState)) : filterForPrefs(finalState),
15762
+ state: controls.profileConfig.agentKind === "codex" ? finalAnswerOnlyState(filterForPrefs(finalState)) : forView(finalState),
15666
15763
  replyMode,
15667
15764
  sendOpts,
15668
15765
  cardRenderOptions