@keyou007/agent-bot 0.1.25-alpha.1 → 0.1.25

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.
Files changed (81) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +34 -6
  3. package/README.zh.md +34 -6
  4. package/config.example.yaml +1 -3
  5. package/dist/cli/help.js +2 -0
  6. package/dist/cli/help.js.map +1 -1
  7. package/dist/codex/CodexRuntime.js +15 -5
  8. package/dist/codex/CodexRuntime.js.map +1 -1
  9. package/dist/commands/CommandRouter.js +3 -0
  10. package/dist/commands/CommandRouter.js.map +1 -1
  11. package/dist/config/SettingsStore.js +341 -0
  12. package/dist/config/SettingsStore.js.map +1 -0
  13. package/dist/config/loadConfig.js +1 -2
  14. package/dist/config/loadConfig.js.map +1 -1
  15. package/dist/config/schema.js +0 -1
  16. package/dist/config/schema.js.map +1 -1
  17. package/dist/console/ConsoleTurnPresenter.js +3 -0
  18. package/dist/console/ConsoleTurnPresenter.js.map +1 -1
  19. package/dist/feishu/CardRenderer.js +34 -99
  20. package/dist/feishu/CardRenderer.js.map +1 -1
  21. package/dist/feishu/FeishuConnector.js +9 -0
  22. package/dist/feishu/FeishuConnector.js.map +1 -1
  23. package/dist/feishu/FeishuMessageClient.js +23 -18
  24. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  25. package/dist/feishu/FeishuTurnPresenter.js +36 -23
  26. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  27. package/dist/feishu/LocalCardImage.js +0 -4
  28. package/dist/feishu/LocalCardImage.js.map +1 -1
  29. package/dist/feishu/LocalImageMarkdown.js +59 -3
  30. package/dist/feishu/LocalImageMarkdown.js.map +1 -1
  31. package/dist/feishu/SettingsCard.js +199 -0
  32. package/dist/feishu/SettingsCard.js.map +1 -0
  33. package/dist/index.js +3 -6
  34. package/dist/index.js.map +1 -1
  35. package/dist/local-files/TurnPreviewPage.js +8 -4
  36. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  37. package/dist/presentation/TurnStateReducer.js +21 -2
  38. package/dist/presentation/TurnStateReducer.js.map +1 -1
  39. package/dist/presentation/turnStatus.js +34 -0
  40. package/dist/presentation/turnStatus.js.map +1 -0
  41. package/dist/proxy/ProxySessionController.js +409 -163
  42. package/dist/proxy/ProxySessionController.js.map +1 -1
  43. package/dist/runtime/submissionErrors.js +15 -0
  44. package/dist/runtime/submissionErrors.js.map +1 -0
  45. package/dist/state/ExecutionProvenanceStore.js +58 -0
  46. package/dist/state/ExecutionProvenanceStore.js.map +1 -0
  47. package/dist/state/StateStore.js +96 -33
  48. package/dist/state/StateStore.js.map +1 -1
  49. package/dist/state/migrations.js +12 -0
  50. package/dist/state/migrations.js.map +1 -1
  51. package/docs/technical-reference.md +11 -8
  52. package/docs/technical-reference.zh.md +11 -8
  53. package/npm-shrinkwrap.json +2 -2
  54. package/package.json +1 -1
  55. package/skills/agent-bot/SKILL.md +9 -3
  56. package/src/cli/help.ts +2 -0
  57. package/src/codex/CodexRuntime.ts +14 -5
  58. package/src/commands/CommandRouter.ts +3 -0
  59. package/src/commands/commandTypes.ts +1 -0
  60. package/src/config/SettingsStore.ts +588 -0
  61. package/src/config/loadConfig.ts +1 -2
  62. package/src/config/schema.ts +0 -1
  63. package/src/console/ConsoleTurnPresenter.ts +2 -0
  64. package/src/feishu/CardRenderer.ts +35 -114
  65. package/src/feishu/FeishuConnector.ts +9 -0
  66. package/src/feishu/FeishuMessageClient.ts +23 -22
  67. package/src/feishu/FeishuTurnPresenter.ts +33 -22
  68. package/src/feishu/LocalCardImage.ts +0 -6
  69. package/src/feishu/LocalImageMarkdown.ts +54 -3
  70. package/src/feishu/SettingsCard.ts +231 -0
  71. package/src/index.ts +3 -6
  72. package/src/local-files/TurnPreviewPage.ts +8 -4
  73. package/src/presentation/TurnStateReducer.ts +21 -2
  74. package/src/presentation/turnStatus.ts +38 -0
  75. package/src/presentation/turnViewTypes.ts +3 -0
  76. package/src/proxy/ProxySessionController.ts +382 -162
  77. package/src/runtime/submissionErrors.ts +15 -0
  78. package/src/runtime/types.ts +1 -0
  79. package/src/state/ExecutionProvenanceStore.ts +100 -0
  80. package/src/state/StateStore.ts +118 -33
  81. package/src/state/migrations.ts +12 -0
@@ -13,12 +13,13 @@ import type {
13
13
  ToolState,
14
14
  } from "../runtime/types.js";
15
15
  import type { TurnActivity, TurnViewState, TurnViewStatus } from "../presentation/turnViewTypes.js";
16
+ import type { ExecutionProvenance } from "../state/ExecutionProvenanceStore.js";
16
17
  import { visibleTurnActivities } from "../presentation/visibleTurnActivities.js";
17
18
  import { displayRuntimeError } from "../runtime/responseErrors.js";
18
19
  import { truncateMiddle, truncateText } from "../utils/markdown.js";
19
20
  import type { UpdateNotice } from "../updates/types.js";
20
21
  import type { ActiveTerminal, TerminalCardView } from "../terminal/TerminalServer.js";
21
- import { localCardImage, localCardMarkdown } from "./LocalCardImage.js";
22
+ import { localCardImage } from "./LocalCardImage.js";
22
23
 
23
24
  export interface StartupStatusView {
24
25
  startedAt: Date;
@@ -176,7 +177,6 @@ export interface ExecutionSettingsCardView {
176
177
  export interface CardSection {
177
178
  title?: string;
178
179
  lines: string[];
179
- localImages?: boolean;
180
180
  collapsible?: boolean;
181
181
  elementId?: string;
182
182
  }
@@ -244,12 +244,6 @@ export interface DirectoryNewFolderCardView {
244
244
 
245
245
  const DIRECTORY_BROWSER_ROW_COUNT = 16;
246
246
 
247
- export type ThinkingCardLayout = "grouped" | "timeline";
248
-
249
- export interface CardRendererOptions {
250
- thinkingCardLayout?: ThinkingCardLayout;
251
- }
252
-
253
247
  export interface ResetHistoryCardEntry extends TaskListCardEntry {
254
248
  sequence: number;
255
249
  graphNodeLine: string;
@@ -319,12 +313,6 @@ export interface AppServerReleaseCardView {
319
313
  }
320
314
 
321
315
  export class CardRenderer {
322
- private readonly thinkingCardLayout: ThinkingCardLayout;
323
-
324
- constructor(options: CardRendererOptions = {}) {
325
- this.thinkingCardLayout = options.thinkingCardLayout ?? "grouped";
326
- }
327
-
328
316
  renderThreadWriterConflict(view: ThreadWriterConflictCardView): Record<string, unknown> {
329
317
  if (view.status === "released") {
330
318
  return sectionCard("任务占用已解除", [markdown([
@@ -1292,9 +1280,7 @@ export class CardRenderer {
1292
1280
  }
1293
1281
 
1294
1282
  renderTurn(state: TurnViewState, previewUrl?: string): Record<string, unknown> {
1295
- const elements = this.thinkingCardLayout === "timeline"
1296
- ? renderTurnElements(state, "hidden")
1297
- : renderGroupedTurnElements(state, "hidden");
1283
+ const elements = renderGroupedTurnElements(state, "hidden");
1298
1284
  const footerActions: TaskListCardAction[] = [];
1299
1285
  if (isTurnStoppable(state.status)) {
1300
1286
  footerActions.push({
@@ -1345,39 +1331,46 @@ export class CardRenderer {
1345
1331
  );
1346
1332
  }
1347
1333
 
1348
- renderTurnDetails(state: TurnViewState, previewUrl?: string): Record<string, unknown> {
1334
+ renderTurnDetails(state: TurnViewState, previewUrl?: string, provenance?: ExecutionProvenance): Record<string, unknown> {
1349
1335
  const title = state.taskTitle
1350
1336
  ? `任务执行详情:${truncateText(state.taskTitle.replace(/\s+/g, " ").trim(), 60)}`
1351
1337
  : "任务执行详情";
1352
1338
  const elements = [markdown(`Turn: \`${state.turnId}\``)];
1339
+ if (provenance) {
1340
+ const labels: Record<ExecutionProvenance["trigger"], string> = {
1341
+ user: "用户消息", queue: "排队消息", schedule: "定时任务", recovery: "未提交请求恢复",
1342
+ retry: "提交前重试", plan_handoff: "已批准方案续接", response_continuation: "模型空输入续接",
1343
+ };
1344
+ const settings = provenance.settings;
1345
+ elements.push(markdown([
1346
+ `**执行来源**:${labels[provenance.trigger]} · ${new Date(provenance.submittedAt).toLocaleString("zh-CN")}`,
1347
+ `**原始指令**:${inlineCode(provenance.instructionId)}`,
1348
+ provenance.parentSourceTurnId ? `**来源轮次**:${inlineCode(provenance.parentSourceTurnId)}` : undefined,
1349
+ provenance.scheduledFor === undefined ? undefined : `**计划时间**:${new Date(provenance.scheduledFor).toLocaleString("zh-CN")}`,
1350
+ `**提交设置**:${[settings.agentName, settings.modelProvider ?? "默认", settings.model ?? "默认", settings.reasoningEffort ?? "自动", permissionModeLabel(settings.permissionMode)].map(inlineCode).join(" / ")}`,
1351
+ ].filter(Boolean).join("\n")));
1352
+ }
1353
1353
  if (state.prompt) elements.push(markdown(`**Prompt**\n${truncateText(state.prompt, 1_000)}`));
1354
1354
  if (state.historyDetailError) {
1355
1355
  elements.push(markdown(`**历史执行详情读取失败**\n${truncateText(state.historyDetailError, 1_000)}\n请重新打开详情或 Preview 重试;本轮执行状态未改变。`));
1356
1356
  } else if (state.historyDetail === "summary") {
1357
1357
  elements.push(markdown("当前仅保存轮次摘要,尚未加载历史执行详情。"));
1358
1358
  }
1359
- elements.push(...renderTurnElements(state, "always"));
1359
+ elements.push(...renderGroupedTurnElements(state, "always"));
1360
1360
  if (previewUrl) elements.push(taskActionRow([turnPreviewAction(previewUrl)]));
1361
1361
  return turnCard(title, "blue", elements, renderTurnSubtitle(state));
1362
1362
  }
1363
1363
 
1364
1364
  renderActivityHistory(state: TurnViewState, requestedPage: number): Record<string, unknown> {
1365
- const grouped = this.thinkingCardLayout === "grouped";
1366
1365
  const activities = turnActivities(state);
1367
- const allGroups = grouped ? groupTurnActivities(activities).flatMap(splitGroupedExecutionActivity) : [];
1368
- const historyGroups = grouped
1369
- ? groupedLiveActivityPage(groupedActivityPagesFromGroups(allGroups, state.projectCwd), state.projectCwd).historyGroups
1370
- : [];
1366
+ const allGroups = groupTurnActivities(activities).flatMap(splitGroupedExecutionActivity);
1367
+ const historyGroups = groupedLiveActivityPage(groupedActivityPagesFromGroups(allGroups, state.projectCwd), state.projectCwd).historyGroups;
1371
1368
  const usesHistoricalPrefixPages = historyGroups.length > 0;
1372
- const pages = grouped
1373
- ? groupedActivityPagesFromGroups(
1374
- usesHistoricalPrefixPages ? historyGroups : allGroups,
1375
- state.projectCwd,
1376
- {
1377
- fullActivityText: true,
1378
- },
1379
- )
1380
- : activityPages(activities);
1369
+ const pages = groupedActivityPagesFromGroups(
1370
+ usesHistoricalPrefixPages ? historyGroups : allGroups,
1371
+ state.projectCwd,
1372
+ { fullActivityText: true },
1373
+ );
1381
1374
  if (pages.length === 0) {
1382
1375
  return this.renderSectionsCard("思考活动历史", [{ lines: ["没有保存到活动记录。"] }]);
1383
1376
  }
@@ -1399,11 +1392,9 @@ export class CardRenderer {
1399
1392
  ];
1400
1393
  const elements: Record<string, unknown>[] = [];
1401
1394
  if (actions.length > 0) elements.push(taskActionRow(actions), { tag: "hr" });
1402
- elements.push(...(grouped
1403
- ? renderGroupedActivityGroups(pages[page] as GroupedTurnActivity[] | undefined ?? [], state.projectCwd, {
1404
- fullActivityText: true,
1405
- })
1406
- : renderActivities(pages[page] as TurnActivity[] | undefined ?? [], state.projectCwd, true)));
1395
+ elements.push(...renderGroupedActivityGroups(pages[page] ?? [], state.projectCwd, {
1396
+ fullActivityText: true,
1397
+ }));
1407
1398
  return sectionCard(`思考活动历史 · ${page + 1}/${totalPages}`, elements.length > 0 ? elements : [markdown("无")]);
1408
1399
  }
1409
1400
 
@@ -1512,12 +1503,11 @@ export class CardRenderer {
1512
1503
  sections.forEach((section, index) => {
1513
1504
  if (index > 0) elements.push({ tag: "hr" });
1514
1505
  const content = section.lines.join("\n");
1515
- const renderMarkdown = section.localImages ? localCardMarkdown : markdown;
1516
1506
  if (section.collapsible && section.title) {
1517
- elements.push(collapsiblePanel(section.title, [renderMarkdown(content)], { elementId: section.elementId }));
1507
+ elements.push(collapsiblePanel(section.title, [markdown(content)], { elementId: section.elementId }));
1518
1508
  } else {
1519
1509
  const heading = section.title ? `**${section.title}**\n` : "";
1520
- elements.push(renderMarkdown(`${heading}${content}`));
1510
+ elements.push(markdown(`${heading}${content}`));
1521
1511
  }
1522
1512
  });
1523
1513
  if (actions.length > 0) elements.push({ tag: "hr" }, taskActionRow(actions));
@@ -1758,41 +1748,6 @@ function isTurnStoppable(status: TurnViewStatus): boolean {
1758
1748
  return status === "running" || status === "tool_running" || status === "waiting_for_approval";
1759
1749
  }
1760
1750
 
1761
- function renderTurnElements(
1762
- state: TurnViewState,
1763
- assistantTextMode: "hidden" | "always",
1764
- ): Record<string, unknown>[] {
1765
- const elements: Record<string, unknown>[] = [];
1766
- const allActivities = turnActivities(state);
1767
- const pages = activityPages(allActivities);
1768
- const visibleActivities = pages.at(-1) ?? [];
1769
- if (state.plan.length > 0) elements.push(planPanel(state.plan));
1770
- if (pages.length > 1 || (state.previewJournal && state.activitiesTruncated)) {
1771
- elements.push(taskActionRow([{
1772
- text: state.activitiesTruncated ? "查看历史思考" : `查看历史思考(共 ${pages.length} 页)`,
1773
- value: {
1774
- action: "activity_history",
1775
- turnId: state.turnId,
1776
- page: String(state.activitiesTruncated ? Number.MAX_SAFE_INTEGER : pages.length - 2),
1777
- },
1778
- }]));
1779
- }
1780
- if (state.activitiesTruncated || pages.length > 1) elements.push(markdown("…"));
1781
- elements.push(...renderActivities(visibleActivities, state.projectCwd));
1782
- if (state.fileSummary.length > 0) elements.push(fileSummaryPanel(state));
1783
-
1784
- if (state.approval) elements.push(...renderApprovalElements(state, state.approval));
1785
- if (state.error) elements.push(markdown(codeBlock(displayRuntimeError(state.error), 2_000)));
1786
- const showAssistantText = state.assistantText && assistantTextMode === "always";
1787
- if (showAssistantText) {
1788
- if (elements.length > 0) elements.push({ tag: "hr" });
1789
- const heading = state.status === "completed" ? "回答" : "回答生成中";
1790
- elements.push(markdown(`**${heading}**\n${truncateText(state.assistantText, 3_000)}`));
1791
- }
1792
- if (elements.length === 0) elements.push(markdown(emptyTurnText(state.status, state.agentLabel)));
1793
- return elements;
1794
- }
1795
-
1796
1751
  function renderGroupedTurnElements(
1797
1752
  state: TurnViewState,
1798
1753
  assistantTextMode: "hidden" | "always",
@@ -1822,6 +1777,7 @@ function renderGroupedTurnElements(
1822
1777
  if (state.fileSummary.length > 0) elements.push(fileSummaryPanel(state));
1823
1778
 
1824
1779
  if (state.approval) elements.push(...renderApprovalElements(state, state.approval));
1780
+ if (state.statusMessage) elements.push(markdown(codeBlock(state.statusMessage, 2_000)));
1825
1781
  if (state.error) elements.push(markdown(codeBlock(displayRuntimeError(state.error), 2_000)));
1826
1782
  const showAssistantText = state.assistantText && assistantTextMode === "always";
1827
1783
  if (showAssistantText) {
@@ -1911,6 +1867,7 @@ function escapeApprovalText(value: string): string {
1911
1867
  }
1912
1868
 
1913
1869
  function emptyTurnText(status: TurnViewStatus, agentLabel?: string): string {
1870
+ if (status === "unknown") return "执行状态待核实,未自动重发。";
1914
1871
  const label = agentLabel?.trim().replace(/[\r\n]+/g, " ") || "Agent";
1915
1872
  if (status === "starting") return `正在连接 ${label}…`;
1916
1873
  if (status === "completed") return "本轮已完成。";
@@ -1982,31 +1939,6 @@ function boldUserActivity(text: string, showIcon: boolean): string {
1982
1939
  .join("\n");
1983
1940
  }
1984
1941
 
1985
- function renderActivities(
1986
- activities: TurnActivity[],
1987
- projectCwd?: string,
1988
- fullAssistantText = false,
1989
- ): Record<string, unknown>[] {
1990
- const elements: Record<string, unknown>[] = [];
1991
- let reasoningGroup: Array<Extract<TurnActivity, { kind: "reasoning" }>> = [];
1992
- const flushReasoning = (): void => {
1993
- if (reasoningGroup.length === 0) return;
1994
- elements.push(...renderReasoningGroup(reasoningGroup));
1995
- reasoningGroup = [];
1996
- };
1997
-
1998
- for (const activity of activities) {
1999
- if (isRawReasoning(activity)) {
2000
- reasoningGroup.push(activity);
2001
- continue;
2002
- }
2003
- flushReasoning();
2004
- elements.push(...renderActivity(activity, projectCwd, fullAssistantText));
2005
- }
2006
- flushReasoning();
2007
- return elements;
2008
- }
2009
-
2010
1942
  type GroupedTurnActivity =
2011
1943
  | { kind: "activity"; activity: TurnActivity }
2012
1944
  | { kind: "gap"; id: string }
@@ -2154,7 +2086,6 @@ function isRawReasoning(
2154
2086
  return activity.kind === "reasoning" && !activity.id.startsWith("commentary:");
2155
2087
  }
2156
2088
 
2157
- const ACTIVITIES_PER_PAGE = 40;
2158
2089
  const GROUPED_TOOLS_PER_PANEL = 8;
2159
2090
  const GROUPED_PAGE_ACTIVITY_BYTES = 24 * 1024;
2160
2091
  const GROUPED_PAGE_ACTIVITY_COMPONENTS = 160;
@@ -2162,18 +2093,6 @@ const PINNED_LIVE_COMMENTARIES = 3;
2162
2093
  const MAX_LIVE_ASSISTANT_TEXT = 2_000;
2163
2094
  const ACTIVITY_TEXT_CHUNK = 2_500;
2164
2095
 
2165
- function activityPages(activities: TurnActivity[]): TurnActivity[][] {
2166
- if (activities.length === 0) return [];
2167
- if (activities.length <= ACTIVITIES_PER_PAGE) return [activities];
2168
- const pages: TurnActivity[][] = [];
2169
- const firstPageSize = activities.length % ACTIVITIES_PER_PAGE || ACTIVITIES_PER_PAGE;
2170
- pages.push(activities.slice(0, firstPageSize));
2171
- for (let index = firstPageSize; index < activities.length; index += ACTIVITIES_PER_PAGE) {
2172
- pages.push(activities.slice(index, index + ACTIVITIES_PER_PAGE));
2173
- }
2174
- return pages;
2175
- }
2176
-
2177
2096
  function groupedActivityPages(
2178
2097
  activities: TurnActivity[],
2179
2098
  projectCwd?: string,
@@ -2849,6 +2768,7 @@ function persistedTaskStatus(sessionStatus: string, lastTurnStatus?: string): st
2849
2768
  }
2850
2769
 
2851
2770
  function turnTitle(status: TurnViewStatus, prompt?: string): string {
2771
+ if (status === "unknown") return `待核实${prompt ? `:${truncateTurnPrompt(prompt)}` : ""}`;
2852
2772
  const reactionEmoji = status === "completed"
2853
2773
  ? "✅"
2854
2774
  : status === "failed"
@@ -2879,6 +2799,7 @@ function truncateTurnPrompt(prompt?: string): string {
2879
2799
  }
2880
2800
 
2881
2801
  function turnTemplate(status: TurnViewStatus): string {
2802
+ if (status === "unknown") return "orange";
2882
2803
  if (status === "completed") return "green";
2883
2804
  if (status === "failed") return "red";
2884
2805
  if (status === "cancelled") return "grey";
@@ -413,6 +413,15 @@ function getCardActionValue(action: Record<string, unknown>): Record<string, unk
413
413
  if (Object.keys(option).length > 0) return option;
414
414
  }
415
415
  const value = isRecord(action.value) ? action.value : {};
416
+ if (action.tag === "select_static" && typeof action.option === "string") {
417
+ return { ...value, option: action.option };
418
+ }
419
+ if (action.tag === "checker" && typeof action.checked === "boolean") {
420
+ return { ...value, checked: action.checked };
421
+ }
422
+ if (action.tag === "input" && typeof action.input_value === "string") {
423
+ return { ...value, inputValue: action.input_value };
424
+ }
416
425
  return isRecord(action.form_value)
417
426
  ? { ...value, formValue: action.form_value }
418
427
  : value;
@@ -5,7 +5,7 @@ import type { Logger } from "pino";
5
5
  import { defaultSqlitePath } from "../config/paths.js";
6
6
  import type { AppConfig } from "../config/schema.js";
7
7
  import { normalizeFeishuMarkdown } from "./FeishuMarkdown.js";
8
- import { LOCAL_CARD_IMAGE_PATH, LOCAL_CARD_MARKDOWN_IMAGES } from "./LocalCardImage.js";
8
+ import { LOCAL_CARD_IMAGE_PATH } from "./LocalCardImage.js";
9
9
  import { renderMarkdownWithLocalImages } from "./LocalImageMarkdown.js";
10
10
  import { splitFinalResponseBranding } from "./FinalResponseBranding.js";
11
11
  import {
@@ -337,7 +337,7 @@ export class FeishuMessageClient implements FeishuOutbound {
337
337
 
338
338
  async sendMarkdown(contextKey: string, markdown: string, idempotencyKey?: string): Promise<string | undefined> {
339
339
  const normalizedMarkdown = normalizeFeishuMarkdown(markdown);
340
- const elements = await this.renderFinalAnswerElements(normalizedMarkdown);
340
+ const elements = this.renderFinalAnswerElements(normalizedMarkdown);
341
341
  return this.sendMessage(
342
342
  contextKey,
343
343
  "interactive",
@@ -352,7 +352,7 @@ export class FeishuMessageClient implements FeishuOutbound {
352
352
  card: Record<string, unknown>,
353
353
  idempotencyKey?: string,
354
354
  ): Promise<string | undefined> {
355
- return this.sendMessage(contextKey, "interactive", await this.prepareInteractiveCard(card), idempotencyKey);
355
+ return this.sendMessage(contextKey, "interactive", card, idempotencyKey);
356
356
  }
357
357
 
358
358
  async replyText(
@@ -380,7 +380,7 @@ export class FeishuMessageClient implements FeishuOutbound {
380
380
  idempotencyKey?: string,
381
381
  ): Promise<string | undefined> {
382
382
  const normalizedMarkdown = normalizeFeishuMarkdown(markdown);
383
- const elements = await this.renderFinalAnswerElements(normalizedMarkdown);
383
+ const elements = this.renderFinalAnswerElements(normalizedMarkdown);
384
384
  return this.replyMessage(
385
385
  contextKey,
386
386
  target,
@@ -401,20 +401,14 @@ export class FeishuMessageClient implements FeishuOutbound {
401
401
  contextKey,
402
402
  target,
403
403
  "interactive",
404
- await this.prepareInteractiveCard(card),
404
+ card,
405
405
  idempotencyKey,
406
406
  );
407
407
  }
408
408
 
409
- private async renderFinalAnswerElements(markdown: string): Promise<Array<Record<string, unknown>>> {
409
+ private renderFinalAnswerElements(markdown: string): Array<Record<string, unknown>> {
410
410
  const { content, branding } = splitFinalResponseBranding(markdown);
411
- const elements = content
412
- ? await renderMarkdownWithLocalImages(
413
- content,
414
- (filePath) => this.uploadImageCached(filePath),
415
- (error, filePath) => this.logger.warn({ error, filePath }, "Failed to upload local image to Feishu."),
416
- )
417
- : [];
411
+ const elements = content ? [{ tag: "markdown", content }] : [];
418
412
  if (!branding) return elements;
419
413
  return [
420
414
  ...elements,
@@ -473,9 +467,10 @@ export class FeishuMessageClient implements FeishuOutbound {
473
467
  idempotencyKey?: string,
474
468
  cardTableLimitFallbackText?: string,
475
469
  ): Promise<string | undefined> {
470
+ const prepared = msgType === "interactive" ? await this.prepareInteractiveCard(content) : content;
476
471
  return this.enqueueSend(contextKey, async () => {
477
472
  try {
478
- return await this.sendMessageNow(contextKey, msgType, content, idempotencyKey);
473
+ return await this.sendMessageNow(contextKey, msgType, prepared, idempotencyKey);
479
474
  } catch (error) {
480
475
  const normalized = normalizeTransportError(error, "send");
481
476
  if (!cardTableLimitFallbackText || !normalized.isCardTableLimitFailure) throw error;
@@ -501,9 +496,10 @@ export class FeishuMessageClient implements FeishuOutbound {
501
496
  idempotencyKey?: string,
502
497
  cardTableLimitFallbackText?: string,
503
498
  ): Promise<string | undefined> {
499
+ const prepared = msgType === "interactive" ? await this.prepareInteractiveCard(content) : content;
504
500
  return this.enqueueSend(contextKey, async () => {
505
501
  try {
506
- return await this.replyMessageNow(target, msgType, content, idempotencyKey);
502
+ return await this.replyMessageNow(target, msgType, prepared, idempotencyKey);
507
503
  } catch (error) {
508
504
  const normalized = normalizeTransportError(error, "reply");
509
505
  if (!cardTableLimitFallbackText || !normalized.isCardTableLimitFailure) throw error;
@@ -903,24 +899,29 @@ export class FeishuMessageClient implements FeishuOutbound {
903
899
  return await this.prepareCardValue(card) as Record<string, unknown>;
904
900
  }
905
901
 
906
- private async prepareCardValue(value: unknown): Promise<unknown> {
902
+ private async prepareCardValue(value: unknown, expandMarkdown = false): Promise<unknown> {
907
903
  if (Array.isArray(value)) {
908
- // Marked Markdown expands to sibling text/image elements; other arrays keep their shape.
904
+ // Card Markdown expands to sibling text/image elements; other arrays keep their shape.
909
905
  const prepared = await Promise.all(value.map(async (item) => {
910
- const result = await this.prepareCardValue(item);
911
- return isRecord(item) && item.tag === "markdown" && item[LOCAL_CARD_MARKDOWN_IMAGES] === true && Array.isArray(result)
906
+ const result = await this.prepareCardValue(item, true);
907
+ return isRecord(item) && item.tag === "markdown" && Array.isArray(result)
912
908
  ? result : [result];
913
909
  }));
914
910
  return prepared.flat();
915
911
  }
916
912
  if (!isRecord(value)) return value;
917
- if (value.tag === "markdown" && value[LOCAL_CARD_MARKDOWN_IMAGES] === true && typeof value.content === "string") {
918
- const { content, element_id: elementId, [LOCAL_CARD_MARKDOWN_IMAGES]: _marker, ...format } = value;
913
+ if ((value.tag === "markdown" || value.tag === "lark_md") && typeof value.content === "string") {
914
+ const { content, element_id: elementId, ...format } = value;
919
915
  const elements = await renderMarkdownWithLocalImages(
920
916
  content,
921
917
  (filePath) => this.uploadImageCached(filePath),
922
918
  (error, filePath) => this.logger.warn({ error, filePath }, "Failed to upload local card image to Feishu."),
923
919
  );
920
+ if (value.tag === "lark_md" || !expandMarkdown) {
921
+ return { ...value, content: elements.length ? elements.map((element) => element.tag === "img"
922
+ ? `![${cardImageLabel(element).replace(/[\\\[\]]/gu, "\\$&")}](${String(element.img_key)})`
923
+ : String(element.content)).join("") : content };
924
+ }
924
925
  return (elements.length ? elements : [{ tag: "markdown", content }]).map((element, index) => ({
925
926
  ...(element.tag === "markdown" ? format : {}),
926
927
  ...element,
@@ -941,7 +942,7 @@ export class FeishuMessageClient implements FeishuOutbound {
941
942
  }
942
943
  const prepared: Record<string, unknown> = {};
943
944
  await Promise.all(Object.entries(value).map(async ([key, child]) => {
944
- prepared[key] = await this.prepareCardValue(child);
945
+ prepared[key] = key === "value" ? child : await this.prepareCardValue(child);
945
946
  }));
946
947
  return prepared;
947
948
  }
@@ -9,6 +9,7 @@ import {
9
9
  } from "../presentation/TurnStateReducer.js";
10
10
  import { splitMarkdown } from "../presentation/splitMarkdown.js";
11
11
  import type { TurnViewState } from "../presentation/turnViewTypes.js";
12
+ import { canApplyTurnEvent, isSettledTurnStatus, isTerminalTurnStatus } from "../presentation/turnStatus.js";
12
13
  import { CardRenderer } from "./CardRenderer.js";
13
14
  import { CardUpdateScheduler } from "./CardUpdateScheduler.js";
14
15
  import { normalizeFeishuMarkdown, type LocalFileUrlResolver } from "./FeishuMarkdown.js";
@@ -30,6 +31,7 @@ interface TurnDeliveryRecord {
30
31
  }
31
32
 
32
33
  export interface TurnPresentationStore {
34
+ provenance?: Pick<import("../state/ExecutionProvenanceStore.js").ExecutionProvenanceStore, "forTurn">;
33
35
  previews?: TurnPreviewJournal;
34
36
  saveTurnSnapshot(turnId: string, localSessionId: string, snapshot: unknown, contextKey?: string): void;
35
37
  promotePendingTurn(
@@ -250,7 +252,7 @@ export class FeishuTurnPresenter {
250
252
  message: string,
251
253
  ): Promise<void> {
252
254
  const snapshot = this.store.getTurnSnapshot(turnId);
253
- if (!isTurnViewState(snapshot) || snapshot.sessionId !== sessionId || isTerminalViewStatus(snapshot.status)) return;
255
+ if (!isTurnViewState(snapshot) || snapshot.sessionId !== sessionId || isTerminalTurnStatus(snapshot.status)) return;
254
256
  const completedAt = Date.now();
255
257
  const state: TurnViewState = {
256
258
  ...snapshot,
@@ -326,12 +328,15 @@ export class FeishuTurnPresenter {
326
328
 
327
329
  async onEvent(event: AgentEvent): Promise<void> {
328
330
  let existing = this.entries.get(event.turnId);
329
- if (!existing) {
330
- const saved = this.store.getTurnSnapshot(event.turnId);
331
- if (isTurnViewState(saved) && saved.continuedToTurnId) return;
331
+ const saved = existing?.state ?? this.store.getTurnSnapshot(event.turnId);
332
+ if (isTurnViewState(saved)) {
333
+ if (saved.sessionId !== event.sessionId || saved.continuedToTurnId) return;
334
+ // Repeated terminal events may retry delivery, but must not rewrite the result.
335
+ if (!canApplyTurnEvent(saved, event) && !(isTerminalEvent(event) && isTerminalTurnStatus(saved.status))) return;
332
336
  }
333
337
  let eventApplied = false;
334
338
  if (event.type === "turn_completed" && event.approvedPlan) {
339
+ if (isTurnViewState(saved) && isSettledTurnStatus(saved.status)) return;
335
340
  const entry = existing ?? this.createEntry({ type: "progress", sessionId: event.sessionId,
336
341
  turnId: event.turnId, activityId: "plan-handoff", text: "方案已确认,继续执行" });
337
342
  if (!entry || entry.continuing) return;
@@ -345,7 +350,7 @@ export class FeishuTurnPresenter {
345
350
  await entry.scheduler?.flush(entry.state);
346
351
  return;
347
352
  }
348
- if (!existing && event.type === "turn_started") {
353
+ if (!existing && !isTurnViewState(saved) && event.type === "turn_started") {
349
354
  const pending = this.pendingEntries.get(event.sessionId);
350
355
  if (pending?.continuing) {
351
356
  const previous = pending.state;
@@ -412,17 +417,26 @@ export class FeishuTurnPresenter {
412
417
 
413
418
  if (existing && !eventApplied) {
414
419
  event = presentationEvent(event, entry.state);
415
- this.store.previews?.seed(entry.state);
416
- this.store.previews?.event(event, entry.state.previewTurnId);
417
- const previousStatus = entry.state.status;
418
- entry.state = this.cardState(reduceTurnEvent(entry.state, event));
419
- if (isTerminalViewStatus(previousStatus) && !event.type.startsWith("turn_")) entry.state.status = previousStatus;
420
- this.persist(event.turnId, event.sessionId, entry.state, entry.contextKey, true);
420
+ if (canApplyTurnEvent(entry.state, event)) {
421
+ this.store.previews?.seed(entry.state);
422
+ this.store.previews?.event(event, entry.state.previewTurnId);
423
+ entry.state = this.cardState(reduceTurnEvent(entry.state, event));
424
+ this.persist(event.turnId, event.sessionId, entry.state, entry.contextKey, true);
425
+ }
421
426
  }
422
427
 
423
428
  await entry.initializing;
424
429
  if (!entry.scheduler) return;
425
430
 
431
+ if (event.type === "turn_status_unknown" && entry.state.status === "unknown") {
432
+ if (this.pendingEntries.get(event.sessionId) === entry) this.pendingEntries.delete(event.sessionId);
433
+ entry.continuing = false;
434
+ this.stopElapsedUpdates(entry);
435
+ if (!entry.historySnapshot) await entry.scheduler.flush(entry.state);
436
+ await this.syncThinkingCardReaction(entry);
437
+ return;
438
+ }
439
+
426
440
  if (isTerminalEvent(event)) {
427
441
  if (this.pendingEntries.get(event.sessionId) === entry) this.pendingEntries.delete(event.sessionId);
428
442
  entry.continuing = false;
@@ -528,13 +542,13 @@ export class FeishuTurnPresenter {
528
542
 
529
543
  private persist(turnId: string, sessionId: string, state: TurnViewState, contextKey?: string, event = false): void {
530
544
  if (!this.store.previews) { this.store.saveTurnSnapshot(turnId, sessionId, state, contextKey); return; }
531
- if (!event || isTerminalViewStatus(state.status)) this.store.previews.state(state);
545
+ if (!event || isSettledTurnStatus(state.status)) this.store.previews.state(state);
532
546
  const compact = compactTurnView(state);
533
547
  this.dirty.set(turnId, { state: compact, contextKey });
534
- if (!event || isTerminalViewStatus(state.status) || state.status === "waiting_for_approval") {
548
+ if (!event || isSettledTurnStatus(state.status) || state.status === "waiting_for_approval") {
535
549
  this.store.previews.flush(state.previewTurnId ?? turnId, true);
536
550
  this.flushPersistence();
537
- if (isTerminalViewStatus(state.status)) this.store.previews.release(state.previewTurnId ?? turnId);
551
+ if (isSettledTurnStatus(state.status)) this.store.previews.release(state.previewTurnId ?? turnId);
538
552
  } else if (!this.persistTimer) {
539
553
  this.persistTimer = setTimeout(() => {
540
554
  try { this.flushPersistence(); } catch (error) { this.options.onError?.(error); }
@@ -575,7 +589,7 @@ export class FeishuTurnPresenter {
575
589
  );
576
590
  this.store.previews?.seed(initial);
577
591
  event = presentationEvent(event, initial);
578
- this.store.previews?.event(event, initial.previewTurnId);
592
+ if (canApplyTurnEvent(initial, event)) this.store.previews?.event(event, initial.previewTurnId);
579
593
  const state = this.cardState(reduceTurnEvent(initial, event));
580
594
  const entry = { contextKey, state, initializing: Promise.resolve() } as TurnEntry;
581
595
  this.entries.set(event.turnId, entry);
@@ -631,6 +645,7 @@ export class FeishuTurnPresenter {
631
645
  return this.renderer.renderTurnDetails(
632
646
  normalizeTurnCardMarkdown(state, this.options.localFileUrl),
633
647
  this.turnPreviewUrl(state),
648
+ this.store.provenance?.forTurn(state.turnId, state.sessionId),
634
649
  );
635
650
  }
636
651
 
@@ -670,10 +685,10 @@ export class FeishuTurnPresenter {
670
685
  }
671
686
 
672
687
  private startElapsedUpdates(entry: TurnEntry): void {
673
- if (entry.elapsedTimer || isTerminalViewStatus(entry.state.status)) return;
688
+ if (entry.elapsedTimer || isSettledTurnStatus(entry.state.status)) return;
674
689
  const intervalMs = Math.max(1, this.options.elapsedUpdateIntervalMs ?? DEFAULT_ELAPSED_UPDATE_INTERVAL_MS);
675
690
  entry.elapsedTimer = setInterval(() => {
676
- if (isTerminalViewStatus(entry.state.status)) {
691
+ if (isSettledTurnStatus(entry.state.status)) {
677
692
  this.stopElapsedUpdates(entry);
678
693
  return;
679
694
  }
@@ -863,12 +878,8 @@ function isTerminalEvent(event: AgentEvent): boolean {
863
878
  return event.type === "turn_completed" || event.type === "turn_cancelled" || event.type === "turn_failed";
864
879
  }
865
880
 
866
- function isTerminalViewStatus(status: TurnViewState["status"]): boolean {
867
- return status === "completed" || status === "cancelled" || status === "failed";
868
- }
869
-
870
881
  function thinkingCardReactionForStatus(status: TurnViewState["status"]): string | undefined {
871
- if (status === "completed") return undefined;
882
+ if (status === "completed" || status === "unknown") return undefined;
872
883
  if (status === "failed") return THINKING_CARD_FAILED_REACTION;
873
884
  if (status === "cancelled") return THINKING_CARD_CANCELLED_REACTION;
874
885
  return THINKING_CARD_RUNNING_REACTION;
@@ -1,10 +1,4 @@
1
1
  export const LOCAL_CARD_IMAGE_PATH = "__acp_local_image_path";
2
- export const LOCAL_CARD_MARKDOWN_IMAGES = "__acp_local_markdown_images";
3
-
4
- export function localCardMarkdown(content: string): Record<string, unknown> {
5
- return { tag: "markdown", content, [LOCAL_CARD_MARKDOWN_IMAGES]: true };
6
- }
7
-
8
2
  export function localCardImage(filePath: string, label: string): Record<string, unknown> {
9
3
  return {
10
4
  tag: "img",
@@ -1,9 +1,11 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
+ import MarkdownIt from "markdown-it";
4
5
 
5
- const MARKDOWN_LINK = /(!?)\[([^\]]*)\]\(([^)\r\n]+)\)/g;
6
+ const MARKDOWN_LINK = /(!?)\[([^\]\r\n]*)\]\((<[^>\r\n]+>|[^)\r\n]+)(?:[ \t]+(?:"[^"\r\n]*"|'[^'\r\n]*'))?\)/g;
6
7
  const IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".tiff", ".bmp", ".ico"]);
8
+ const markdownParser = new MarkdownIt();
7
9
 
8
10
  export async function renderMarkdownWithLocalImages(
9
11
  markdown: string,
@@ -12,14 +14,19 @@ export async function renderMarkdownWithLocalImages(
12
14
  ): Promise<Array<Record<string, unknown>>> {
13
15
  const elements: Array<Record<string, unknown>> = [];
14
16
  const uploads = new Map<string, Promise<string>>();
17
+ const protectedRanges = markdown.includes("[") ? markdownCodeRanges(markdown) : [];
15
18
  let cursor = 0;
16
19
 
17
20
  for (const match of markdown.matchAll(MARKDOWN_LINK)) {
18
21
  const matchIndex = match.index;
19
- const target = match[3];
20
- if (matchIndex === undefined || target === undefined) continue;
22
+ const rawTarget = match[3];
23
+ if (matchIndex === undefined || rawTarget === undefined
24
+ || escapedAt(markdown, matchIndex)
25
+ || protectedRanges.some(([start, end]) => matchIndex >= start && matchIndex < end)) continue;
26
+ const target = markdownTarget(rawTarget);
21
27
  const filePath = localImagePath(target);
22
28
  const imageSyntax = match[1] === "!";
29
+ if (imageSyntax && /^img_[a-z\d_-]+$/iu.test(target)) continue;
23
30
  const label = match[2]?.trim() || path.basename(unwrapTarget(target.trim()));
24
31
  if (!filePath) {
25
32
  if (!imageSyntax) continue;
@@ -56,6 +63,50 @@ export async function renderMarkdownWithLocalImages(
56
63
  return elements;
57
64
  }
58
65
 
66
+ function markdownCodeRanges(markdown: string): Array<[number, number]> {
67
+ const lineOffsets = [0, ...[...markdown.matchAll(/\r?\n/gu)].map(match => match.index + match[0].length)];
68
+ const ranges: Array<[number, number]> = [];
69
+ for (const token of markdownParser.parse(markdown, {})) {
70
+ if (!token.map) continue;
71
+ const start = lineOffsets[token.map[0]] ?? markdown.length;
72
+ const end = lineOffsets[token.map[1]] ?? markdown.length;
73
+ if (token.type === "fence" || token.type === "code_block") {
74
+ ranges.push([start, end]);
75
+ } else if (token.type === "inline") {
76
+ const text = markdown.slice(start, end);
77
+ const runs = [...text.matchAll(/`+/gu)];
78
+ for (let index = 0; index < runs.length; index += 1) {
79
+ const opener = runs[index]!;
80
+ if (escapedAt(text, opener.index)) continue;
81
+ const closing = runs.findIndex((run, candidate) => candidate > index && run[0].length === opener[0].length);
82
+ if (closing < 0) continue;
83
+ const closer = runs[closing]!;
84
+ ranges.push([start + opener.index, start + closer.index + closer[0].length]);
85
+ index = closing;
86
+ }
87
+ }
88
+ }
89
+ return ranges;
90
+ }
91
+
92
+ function escapedAt(text: string, offset: number): boolean {
93
+ let slashes = 0;
94
+ while (offset > 0 && text[--offset] === "\\") slashes += 1;
95
+ return slashes % 2 !== 0;
96
+ }
97
+
98
+ function markdownTarget(rawTarget: string): string {
99
+ const target = rawTarget.trim();
100
+ const parsed = markdownParser.helpers.parseLinkDestination(target, 0, target.length);
101
+ if (parsed.ok) {
102
+ const suffix = target.slice(parsed.pos).trim();
103
+ if (!suffix) return parsed.str;
104
+ const title = markdownParser.helpers.parseLinkTitle(suffix, 0, suffix.length);
105
+ if (title.ok && title.pos === suffix.length) return parsed.str;
106
+ }
107
+ return unwrapTarget(target);
108
+ }
109
+
59
110
  function localImagePath(rawTarget: string): string | undefined {
60
111
  const target = unwrapTarget(rawTarget.trim());
61
112
  let candidate: string;