@keyou007/agent-bot 0.1.25-alpha.0 → 0.1.25-alpha.2

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 (103) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +60 -5
  3. package/README.zh.md +60 -5
  4. package/config.example.yaml +1 -3
  5. package/dist/cli/controlProtocol.js.map +1 -1
  6. package/dist/cli/help.js +14 -0
  7. package/dist/cli/help.js.map +1 -1
  8. package/dist/cli.js +32 -0
  9. package/dist/cli.js.map +1 -1
  10. package/dist/codex/CodexRuntime.js +15 -5
  11. package/dist/codex/CodexRuntime.js.map +1 -1
  12. package/dist/commands/CommandRouter.js +7 -0
  13. package/dist/commands/CommandRouter.js.map +1 -1
  14. package/dist/config/SettingsStore.js +341 -0
  15. package/dist/config/SettingsStore.js.map +1 -0
  16. package/dist/config/loadConfig.js +1 -2
  17. package/dist/config/loadConfig.js.map +1 -1
  18. package/dist/config/schema.js +0 -1
  19. package/dist/config/schema.js.map +1 -1
  20. package/dist/console/ConsoleTurnPresenter.js +3 -0
  21. package/dist/console/ConsoleTurnPresenter.js.map +1 -1
  22. package/dist/feishu/CardRenderer.js +32 -96
  23. package/dist/feishu/CardRenderer.js.map +1 -1
  24. package/dist/feishu/FeishuConnector.js +9 -0
  25. package/dist/feishu/FeishuConnector.js.map +1 -1
  26. package/dist/feishu/FeishuMessageClient.js +35 -14
  27. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  28. package/dist/feishu/FeishuTurnPresenter.js +36 -23
  29. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  30. package/dist/feishu/LocalCardImage.js.map +1 -1
  31. package/dist/feishu/LocalImageMarkdown.js +59 -3
  32. package/dist/feishu/LocalImageMarkdown.js.map +1 -1
  33. package/dist/feishu/SettingsCard.js +199 -0
  34. package/dist/feishu/SettingsCard.js.map +1 -0
  35. package/dist/index.js +17 -6
  36. package/dist/index.js.map +1 -1
  37. package/dist/local-files/TurnPreviewPage.js +8 -4
  38. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  39. package/dist/presentation/TurnStateReducer.js +21 -2
  40. package/dist/presentation/TurnStateReducer.js.map +1 -1
  41. package/dist/presentation/turnStatus.js +34 -0
  42. package/dist/presentation/turnStatus.js.map +1 -0
  43. package/dist/proxy/ProxySessionController.js +688 -153
  44. package/dist/proxy/ProxySessionController.js.map +1 -1
  45. package/dist/runtime/submissionErrors.js +15 -0
  46. package/dist/runtime/submissionErrors.js.map +1 -0
  47. package/dist/scheduling/ScheduleCards.js +240 -0
  48. package/dist/scheduling/ScheduleCards.js.map +1 -0
  49. package/dist/scheduling/ScheduleCommand.js +67 -0
  50. package/dist/scheduling/ScheduleCommand.js.map +1 -0
  51. package/dist/scheduling/ScheduledTaskStore.js +226 -0
  52. package/dist/scheduling/ScheduledTaskStore.js.map +1 -0
  53. package/dist/scheduling/TaskScheduler.js +132 -0
  54. package/dist/scheduling/TaskScheduler.js.map +1 -0
  55. package/dist/scheduling/types.js +89 -0
  56. package/dist/scheduling/types.js.map +1 -0
  57. package/dist/state/ExecutionProvenanceStore.js +58 -0
  58. package/dist/state/ExecutionProvenanceStore.js.map +1 -0
  59. package/dist/state/StateStore.js +145 -45
  60. package/dist/state/StateStore.js.map +1 -1
  61. package/dist/state/migrations.js +37 -0
  62. package/dist/state/migrations.js.map +1 -1
  63. package/dist/supervision/SafeRestartNotifier.js +1 -1
  64. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  65. package/docs/technical-reference.md +11 -8
  66. package/docs/technical-reference.zh.md +11 -8
  67. package/npm-shrinkwrap.json +24 -2
  68. package/package.json +2 -1
  69. package/skills/agent-bot/SKILL.md +33 -3
  70. package/src/cli/controlProtocol.ts +1 -0
  71. package/src/cli/help.ts +14 -0
  72. package/src/cli.ts +25 -0
  73. package/src/codex/CodexRuntime.ts +14 -5
  74. package/src/commands/CommandRouter.ts +7 -0
  75. package/src/commands/commandTypes.ts +2 -0
  76. package/src/config/SettingsStore.ts +588 -0
  77. package/src/config/loadConfig.ts +1 -2
  78. package/src/config/schema.ts +0 -1
  79. package/src/console/ConsoleTurnPresenter.ts +2 -0
  80. package/src/feishu/CardRenderer.ts +33 -110
  81. package/src/feishu/FeishuConnector.ts +9 -0
  82. package/src/feishu/FeishuMessageClient.ts +39 -17
  83. package/src/feishu/FeishuTurnPresenter.ts +33 -22
  84. package/src/feishu/LocalCardImage.ts +0 -1
  85. package/src/feishu/LocalImageMarkdown.ts +54 -3
  86. package/src/feishu/SettingsCard.ts +231 -0
  87. package/src/index.ts +17 -6
  88. package/src/local-files/TurnPreviewPage.ts +8 -4
  89. package/src/presentation/TurnStateReducer.ts +21 -2
  90. package/src/presentation/turnStatus.ts +38 -0
  91. package/src/presentation/turnViewTypes.ts +3 -0
  92. package/src/proxy/ProxySessionController.ts +628 -152
  93. package/src/runtime/submissionErrors.ts +15 -0
  94. package/src/runtime/types.ts +1 -0
  95. package/src/scheduling/ScheduleCards.ts +317 -0
  96. package/src/scheduling/ScheduleCommand.ts +76 -0
  97. package/src/scheduling/ScheduledTaskStore.ts +332 -0
  98. package/src/scheduling/TaskScheduler.ts +171 -0
  99. package/src/scheduling/types.ts +151 -0
  100. package/src/state/ExecutionProvenanceStore.ts +100 -0
  101. package/src/state/StateStore.ts +167 -44
  102. package/src/state/migrations.ts +37 -0
  103. package/src/supervision/SafeRestartNotifier.ts +1 -1
@@ -13,6 +13,7 @@ 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";
@@ -243,12 +244,6 @@ export interface DirectoryNewFolderCardView {
243
244
 
244
245
  const DIRECTORY_BROWSER_ROW_COUNT = 16;
245
246
 
246
- export type ThinkingCardLayout = "grouped" | "timeline";
247
-
248
- export interface CardRendererOptions {
249
- thinkingCardLayout?: ThinkingCardLayout;
250
- }
251
-
252
247
  export interface ResetHistoryCardEntry extends TaskListCardEntry {
253
248
  sequence: number;
254
249
  graphNodeLine: string;
@@ -318,12 +313,6 @@ export interface AppServerReleaseCardView {
318
313
  }
319
314
 
320
315
  export class CardRenderer {
321
- private readonly thinkingCardLayout: ThinkingCardLayout;
322
-
323
- constructor(options: CardRendererOptions = {}) {
324
- this.thinkingCardLayout = options.thinkingCardLayout ?? "grouped";
325
- }
326
-
327
316
  renderThreadWriterConflict(view: ThreadWriterConflictCardView): Record<string, unknown> {
328
317
  if (view.status === "released") {
329
318
  return sectionCard("任务占用已解除", [markdown([
@@ -1291,9 +1280,7 @@ export class CardRenderer {
1291
1280
  }
1292
1281
 
1293
1282
  renderTurn(state: TurnViewState, previewUrl?: string): Record<string, unknown> {
1294
- const elements = this.thinkingCardLayout === "timeline"
1295
- ? renderTurnElements(state, "hidden")
1296
- : renderGroupedTurnElements(state, "hidden");
1283
+ const elements = renderGroupedTurnElements(state, "hidden");
1297
1284
  const footerActions: TaskListCardAction[] = [];
1298
1285
  if (isTurnStoppable(state.status)) {
1299
1286
  footerActions.push({
@@ -1344,39 +1331,46 @@ export class CardRenderer {
1344
1331
  );
1345
1332
  }
1346
1333
 
1347
- renderTurnDetails(state: TurnViewState, previewUrl?: string): Record<string, unknown> {
1334
+ renderTurnDetails(state: TurnViewState, previewUrl?: string, provenance?: ExecutionProvenance): Record<string, unknown> {
1348
1335
  const title = state.taskTitle
1349
1336
  ? `任务执行详情:${truncateText(state.taskTitle.replace(/\s+/g, " ").trim(), 60)}`
1350
1337
  : "任务执行详情";
1351
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
+ }
1352
1353
  if (state.prompt) elements.push(markdown(`**Prompt**\n${truncateText(state.prompt, 1_000)}`));
1353
1354
  if (state.historyDetailError) {
1354
1355
  elements.push(markdown(`**历史执行详情读取失败**\n${truncateText(state.historyDetailError, 1_000)}\n请重新打开详情或 Preview 重试;本轮执行状态未改变。`));
1355
1356
  } else if (state.historyDetail === "summary") {
1356
1357
  elements.push(markdown("当前仅保存轮次摘要,尚未加载历史执行详情。"));
1357
1358
  }
1358
- elements.push(...renderTurnElements(state, "always"));
1359
+ elements.push(...renderGroupedTurnElements(state, "always"));
1359
1360
  if (previewUrl) elements.push(taskActionRow([turnPreviewAction(previewUrl)]));
1360
1361
  return turnCard(title, "blue", elements, renderTurnSubtitle(state));
1361
1362
  }
1362
1363
 
1363
1364
  renderActivityHistory(state: TurnViewState, requestedPage: number): Record<string, unknown> {
1364
- const grouped = this.thinkingCardLayout === "grouped";
1365
1365
  const activities = turnActivities(state);
1366
- const allGroups = grouped ? groupTurnActivities(activities).flatMap(splitGroupedExecutionActivity) : [];
1367
- const historyGroups = grouped
1368
- ? groupedLiveActivityPage(groupedActivityPagesFromGroups(allGroups, state.projectCwd), state.projectCwd).historyGroups
1369
- : [];
1366
+ const allGroups = groupTurnActivities(activities).flatMap(splitGroupedExecutionActivity);
1367
+ const historyGroups = groupedLiveActivityPage(groupedActivityPagesFromGroups(allGroups, state.projectCwd), state.projectCwd).historyGroups;
1370
1368
  const usesHistoricalPrefixPages = historyGroups.length > 0;
1371
- const pages = grouped
1372
- ? groupedActivityPagesFromGroups(
1373
- usesHistoricalPrefixPages ? historyGroups : allGroups,
1374
- state.projectCwd,
1375
- {
1376
- fullActivityText: true,
1377
- },
1378
- )
1379
- : activityPages(activities);
1369
+ const pages = groupedActivityPagesFromGroups(
1370
+ usesHistoricalPrefixPages ? historyGroups : allGroups,
1371
+ state.projectCwd,
1372
+ { fullActivityText: true },
1373
+ );
1380
1374
  if (pages.length === 0) {
1381
1375
  return this.renderSectionsCard("思考活动历史", [{ lines: ["没有保存到活动记录。"] }]);
1382
1376
  }
@@ -1398,11 +1392,9 @@ export class CardRenderer {
1398
1392
  ];
1399
1393
  const elements: Record<string, unknown>[] = [];
1400
1394
  if (actions.length > 0) elements.push(taskActionRow(actions), { tag: "hr" });
1401
- elements.push(...(grouped
1402
- ? renderGroupedActivityGroups(pages[page] as GroupedTurnActivity[] | undefined ?? [], state.projectCwd, {
1403
- fullActivityText: true,
1404
- })
1405
- : renderActivities(pages[page] as TurnActivity[] | undefined ?? [], state.projectCwd, true)));
1395
+ elements.push(...renderGroupedActivityGroups(pages[page] ?? [], state.projectCwd, {
1396
+ fullActivityText: true,
1397
+ }));
1406
1398
  return sectionCard(`思考活动历史 · ${page + 1}/${totalPages}`, elements.length > 0 ? elements : [markdown("无")]);
1407
1399
  }
1408
1400
 
@@ -1512,7 +1504,7 @@ export class CardRenderer {
1512
1504
  if (index > 0) elements.push({ tag: "hr" });
1513
1505
  const content = section.lines.join("\n");
1514
1506
  if (section.collapsible && section.title) {
1515
- elements.push(collapsiblePanel(section.title, content, { elementId: section.elementId }));
1507
+ elements.push(collapsiblePanel(section.title, [markdown(content)], { elementId: section.elementId }));
1516
1508
  } else {
1517
1509
  const heading = section.title ? `**${section.title}**\n` : "";
1518
1510
  elements.push(markdown(`${heading}${content}`));
@@ -1756,41 +1748,6 @@ function isTurnStoppable(status: TurnViewStatus): boolean {
1756
1748
  return status === "running" || status === "tool_running" || status === "waiting_for_approval";
1757
1749
  }
1758
1750
 
1759
- function renderTurnElements(
1760
- state: TurnViewState,
1761
- assistantTextMode: "hidden" | "always",
1762
- ): Record<string, unknown>[] {
1763
- const elements: Record<string, unknown>[] = [];
1764
- const allActivities = turnActivities(state);
1765
- const pages = activityPages(allActivities);
1766
- const visibleActivities = pages.at(-1) ?? [];
1767
- if (state.plan.length > 0) elements.push(planPanel(state.plan));
1768
- if (pages.length > 1 || (state.previewJournal && state.activitiesTruncated)) {
1769
- elements.push(taskActionRow([{
1770
- text: state.activitiesTruncated ? "查看历史思考" : `查看历史思考(共 ${pages.length} 页)`,
1771
- value: {
1772
- action: "activity_history",
1773
- turnId: state.turnId,
1774
- page: String(state.activitiesTruncated ? Number.MAX_SAFE_INTEGER : pages.length - 2),
1775
- },
1776
- }]));
1777
- }
1778
- if (state.activitiesTruncated || pages.length > 1) elements.push(markdown("…"));
1779
- elements.push(...renderActivities(visibleActivities, state.projectCwd));
1780
- if (state.fileSummary.length > 0) elements.push(fileSummaryPanel(state));
1781
-
1782
- if (state.approval) elements.push(...renderApprovalElements(state, state.approval));
1783
- if (state.error) elements.push(markdown(codeBlock(displayRuntimeError(state.error), 2_000)));
1784
- const showAssistantText = state.assistantText && assistantTextMode === "always";
1785
- if (showAssistantText) {
1786
- if (elements.length > 0) elements.push({ tag: "hr" });
1787
- const heading = state.status === "completed" ? "回答" : "回答生成中";
1788
- elements.push(markdown(`**${heading}**\n${truncateText(state.assistantText, 3_000)}`));
1789
- }
1790
- if (elements.length === 0) elements.push(markdown(emptyTurnText(state.status, state.agentLabel)));
1791
- return elements;
1792
- }
1793
-
1794
1751
  function renderGroupedTurnElements(
1795
1752
  state: TurnViewState,
1796
1753
  assistantTextMode: "hidden" | "always",
@@ -1820,6 +1777,7 @@ function renderGroupedTurnElements(
1820
1777
  if (state.fileSummary.length > 0) elements.push(fileSummaryPanel(state));
1821
1778
 
1822
1779
  if (state.approval) elements.push(...renderApprovalElements(state, state.approval));
1780
+ if (state.statusMessage) elements.push(markdown(codeBlock(state.statusMessage, 2_000)));
1823
1781
  if (state.error) elements.push(markdown(codeBlock(displayRuntimeError(state.error), 2_000)));
1824
1782
  const showAssistantText = state.assistantText && assistantTextMode === "always";
1825
1783
  if (showAssistantText) {
@@ -1909,6 +1867,7 @@ function escapeApprovalText(value: string): string {
1909
1867
  }
1910
1868
 
1911
1869
  function emptyTurnText(status: TurnViewStatus, agentLabel?: string): string {
1870
+ if (status === "unknown") return "执行状态待核实,未自动重发。";
1912
1871
  const label = agentLabel?.trim().replace(/[\r\n]+/g, " ") || "Agent";
1913
1872
  if (status === "starting") return `正在连接 ${label}…`;
1914
1873
  if (status === "completed") return "本轮已完成。";
@@ -1980,31 +1939,6 @@ function boldUserActivity(text: string, showIcon: boolean): string {
1980
1939
  .join("\n");
1981
1940
  }
1982
1941
 
1983
- function renderActivities(
1984
- activities: TurnActivity[],
1985
- projectCwd?: string,
1986
- fullAssistantText = false,
1987
- ): Record<string, unknown>[] {
1988
- const elements: Record<string, unknown>[] = [];
1989
- let reasoningGroup: Array<Extract<TurnActivity, { kind: "reasoning" }>> = [];
1990
- const flushReasoning = (): void => {
1991
- if (reasoningGroup.length === 0) return;
1992
- elements.push(...renderReasoningGroup(reasoningGroup));
1993
- reasoningGroup = [];
1994
- };
1995
-
1996
- for (const activity of activities) {
1997
- if (isRawReasoning(activity)) {
1998
- reasoningGroup.push(activity);
1999
- continue;
2000
- }
2001
- flushReasoning();
2002
- elements.push(...renderActivity(activity, projectCwd, fullAssistantText));
2003
- }
2004
- flushReasoning();
2005
- return elements;
2006
- }
2007
-
2008
1942
  type GroupedTurnActivity =
2009
1943
  | { kind: "activity"; activity: TurnActivity }
2010
1944
  | { kind: "gap"; id: string }
@@ -2152,7 +2086,6 @@ function isRawReasoning(
2152
2086
  return activity.kind === "reasoning" && !activity.id.startsWith("commentary:");
2153
2087
  }
2154
2088
 
2155
- const ACTIVITIES_PER_PAGE = 40;
2156
2089
  const GROUPED_TOOLS_PER_PANEL = 8;
2157
2090
  const GROUPED_PAGE_ACTIVITY_BYTES = 24 * 1024;
2158
2091
  const GROUPED_PAGE_ACTIVITY_COMPONENTS = 160;
@@ -2160,18 +2093,6 @@ const PINNED_LIVE_COMMENTARIES = 3;
2160
2093
  const MAX_LIVE_ASSISTANT_TEXT = 2_000;
2161
2094
  const ACTIVITY_TEXT_CHUNK = 2_500;
2162
2095
 
2163
- function activityPages(activities: TurnActivity[]): TurnActivity[][] {
2164
- if (activities.length === 0) return [];
2165
- if (activities.length <= ACTIVITIES_PER_PAGE) return [activities];
2166
- const pages: TurnActivity[][] = [];
2167
- const firstPageSize = activities.length % ACTIVITIES_PER_PAGE || ACTIVITIES_PER_PAGE;
2168
- pages.push(activities.slice(0, firstPageSize));
2169
- for (let index = firstPageSize; index < activities.length; index += ACTIVITIES_PER_PAGE) {
2170
- pages.push(activities.slice(index, index + ACTIVITIES_PER_PAGE));
2171
- }
2172
- return pages;
2173
- }
2174
-
2175
2096
  function groupedActivityPages(
2176
2097
  activities: TurnActivity[],
2177
2098
  projectCwd?: string,
@@ -2847,6 +2768,7 @@ function persistedTaskStatus(sessionStatus: string, lastTurnStatus?: string): st
2847
2768
  }
2848
2769
 
2849
2770
  function turnTitle(status: TurnViewStatus, prompt?: string): string {
2771
+ if (status === "unknown") return `待核实${prompt ? `:${truncateTurnPrompt(prompt)}` : ""}`;
2850
2772
  const reactionEmoji = status === "completed"
2851
2773
  ? "✅"
2852
2774
  : status === "failed"
@@ -2877,6 +2799,7 @@ function truncateTurnPrompt(prompt?: string): string {
2877
2799
  }
2878
2800
 
2879
2801
  function turnTemplate(status: TurnViewStatus): string {
2802
+ if (status === "unknown") return "orange";
2880
2803
  if (status === "completed") return "green";
2881
2804
  if (status === "failed") return "red";
2882
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;
@@ -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,9 +899,35 @@ 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> {
907
- if (Array.isArray(value)) return Promise.all(value.map((item) => this.prepareCardValue(item)));
902
+ private async prepareCardValue(value: unknown, expandMarkdown = false): Promise<unknown> {
903
+ if (Array.isArray(value)) {
904
+ // Card Markdown expands to sibling text/image elements; other arrays keep their shape.
905
+ const prepared = await Promise.all(value.map(async (item) => {
906
+ const result = await this.prepareCardValue(item, true);
907
+ return isRecord(item) && item.tag === "markdown" && Array.isArray(result)
908
+ ? result : [result];
909
+ }));
910
+ return prepared.flat();
911
+ }
908
912
  if (!isRecord(value)) return value;
913
+ if ((value.tag === "markdown" || value.tag === "lark_md") && typeof value.content === "string") {
914
+ const { content, element_id: elementId, ...format } = value;
915
+ const elements = await renderMarkdownWithLocalImages(
916
+ content,
917
+ (filePath) => this.uploadImageCached(filePath),
918
+ (error, filePath) => this.logger.warn({ error, filePath }, "Failed to upload local card image to Feishu."),
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
+ }
925
+ return (elements.length ? elements : [{ tag: "markdown", content }]).map((element, index) => ({
926
+ ...(element.tag === "markdown" ? format : {}),
927
+ ...element,
928
+ ...(index === 0 && typeof elementId === "string" ? { element_id: elementId } : {}),
929
+ }));
930
+ }
909
931
  const localImagePath = value[LOCAL_CARD_IMAGE_PATH];
910
932
  if (value.tag === "img" && typeof localImagePath === "string") {
911
933
  const image = { ...value };
@@ -920,7 +942,7 @@ export class FeishuMessageClient implements FeishuOutbound {
920
942
  }
921
943
  const prepared: Record<string, unknown> = {};
922
944
  await Promise.all(Object.entries(value).map(async ([key, child]) => {
923
- prepared[key] = await this.prepareCardValue(child);
945
+ prepared[key] = key === "value" ? child : await this.prepareCardValue(child);
924
946
  }));
925
947
  return prepared;
926
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,5 +1,4 @@
1
1
  export const LOCAL_CARD_IMAGE_PATH = "__acp_local_image_path";
2
-
3
2
  export function localCardImage(filePath: string, label: string): Record<string, unknown> {
4
3
  return {
5
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;