@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
@@ -52,6 +52,11 @@ import {
52
52
  import { normalizeFeishuPostText } from "../feishu/InboundText.js";
53
53
  import { RECENT_CONTEXT_LIMIT, RECENT_CONTEXT_IMAGE_LIMIT, RECENT_CONTEXT_TEXT_LIMIT, recentContextPrompt } from "../feishu/RecentMessageContext.js";
54
54
  import { allowsFeishuUser } from "../feishu/ownerAccess.js";
55
+ import type { ScheduleCommand, ScheduledJob, ScheduleInput } from "../scheduling/types.js";
56
+ import { scheduleCommandSchema } from "../scheduling/types.js";
57
+ import type { SettingsCatalog, SettingsSnapshot, SettingsStore } from "../config/SettingsStore.js";
58
+ import { renderSettingsCard } from "../feishu/SettingsCard.js";
59
+ import { renderSchedule, renderScheduleList, renderScheduleForm } from "../scheduling/ScheduleCards.js";
55
60
  import { classifyFileContent } from "../local-files/LocalFileViewerServer.js";
56
61
  import { errorLogValue } from "../logging/errorLogValue.js";
57
62
  import type { OutboundRouter } from "../presentation/OutboundRouter.js";
@@ -60,6 +65,7 @@ import { createTurnViewState, hydrateTurnViewState } from "../presentation/TurnS
60
65
  import { buildTurnGraphRows } from "../presentation/turnGraph.js";
61
66
  import type { AgentRuntimeRegistry } from "../runtime/AgentRuntimeRegistry.js";
62
67
  import { displayRuntimeError, isResponseContinuationError } from "../runtime/responseErrors.js";
68
+ import { TurnNotSubmittedError, TurnStoppedBeforeSubmissionError } from "../runtime/submissionErrors.js";
63
69
  import type {
64
70
  AgentRuntime,
65
71
  ApprovalDecision,
@@ -99,6 +105,7 @@ import {
99
105
  type TurnRuntimeOriginRecord,
100
106
  } from "../state/StateStore.js";
101
107
  import { SessionOperationQueue } from "./SessionOperationQueue.js";
108
+ import type { ExecutionTrigger } from "../state/ExecutionProvenanceStore.js";
102
109
  import { createId } from "../utils/id.js";
103
110
  import { formatStorageSize } from "../utils/formatStorageSize.js";
104
111
  import { truncateMiddle, truncateText } from "../utils/markdown.js";
@@ -117,6 +124,11 @@ interface LoadedSession {
117
124
  }
118
125
 
119
126
  interface StartTurnOptions {
127
+ trigger?: ExecutionTrigger;
128
+ instructionId?: string;
129
+ parentSourceTurnId?: string;
130
+ executionGeneration?: number;
131
+ scheduleRunId?: string;
120
132
  attemptId?: string;
121
133
  messageId?: string;
122
134
  displayPrompt?: string;
@@ -286,6 +298,8 @@ const HELP_COMMAND_SECTIONS: Array<{
286
298
  requiresArgument: true,
287
299
  },
288
300
  { command: "/sessions", usage: "[关键词]", description: "查找本机任务" },
301
+ { command: "/schedule", description: "创建和管理绑定现有任务的定时计划" },
302
+ { command: "/settings", description: "配置 Agent Bot 和各 Agent 默认值(仅所有者)" },
289
303
  {
290
304
  command: "/archive",
291
305
  usage: "[序号或任务 ID]",
@@ -515,6 +529,8 @@ export interface ControlTaskReleaseResult {
515
529
  }
516
530
 
517
531
  export interface ProxyLifecycle {
532
+ settings?: SettingsStore;
533
+ canStartScheduledTasks?(): boolean;
518
534
  terminalUrl?(jobId: string): string | undefined;
519
535
  authorizeTerminal?(action: CardAction): Promise<string>;
520
536
  stopSafeRestartTerminal?(action: CardAction): Promise<string>;
@@ -526,10 +542,6 @@ export interface ProxyLifecycle {
526
542
  showUpdates?(contextKey: string, userId?: string): Promise<void>;
527
543
  selectUpdate?(action: CardAction, replyTarget?: MessageReplyTarget): Promise<void>;
528
544
  rememberFeishuUserOpenId?(userOpenId: string): Promise<void> | void;
529
- persistAgentExecutionDefaults?(
530
- agentName: string,
531
- defaults: AgentExecutionDefaults,
532
- ): Promise<void> | void;
533
545
  }
534
546
 
535
547
  export type ShellCommandExecutor = (
@@ -556,9 +568,9 @@ export class ProxySessionController {
556
568
  private readonly queuedPromptCards = new Map<string, Map<string, string>>();
557
569
  private readonly queuedPromptCardWrites = new Map<string, Promise<void>>();
558
570
  private readonly settingsOperations = new SessionOperationQueue();
571
+ private readonly globalSettingsOperations = new SessionOperationQueue();
559
572
  // Loads may run inside settingsOperations; never acquire that queue while hydrating.
560
573
  private readonly sessionHydrationOperations = new SessionOperationQueue();
561
- private readonly agentDefaultsOperations = new SessionOperationQueue();
562
574
  private readonly sessionResets = new Map<string, Promise<void>>();
563
575
  private readonly resetHistoryOperations = new Map<string, string>();
564
576
  private readonly remoteTurnHistoryRefreshes = new Map<string, number>();
@@ -992,8 +1004,15 @@ export class ProxySessionController {
992
1004
  if (command.type === "prompt" && message.chatType === "group" && message.mentionedBot
993
1005
  && this.store.chatRequiresMention(baseChatContextKey(message.contextKey))) {
994
1006
  const current = this.currentSession(message.contextKey);
995
- if (current) this.store.rememberRecentContextMessages(current.localSessionId, current.remoteSessionId ?? "", message.contextKey, message.messageId,
996
- [...recentContextIds, message.messageId, ...[referencedMessageId, injectedRootMessageId].filter((id): id is string => Boolean(id))]);
1007
+ if (current) {
1008
+ try {
1009
+ this.store.rememberRecentContextMessages(current.localSessionId, current.remoteSessionId ?? "", message.contextKey, message.messageId,
1010
+ [...recentContextIds, message.messageId, ...[referencedMessageId, injectedRootMessageId].filter((id): id is string => Boolean(id))]);
1011
+ } catch (error) {
1012
+ this.logger.warn({ error, localSessionId: current.localSessionId, messageId: message.messageId },
1013
+ "Failed to save recent context receipts after accepting the prompt.");
1014
+ }
1015
+ }
997
1016
  }
998
1017
  if (injectedRootMessageId) {
999
1018
  const current = this.currentSession(message.contextKey);
@@ -1055,7 +1074,11 @@ export class ProxySessionController {
1055
1074
  await this.outbound.withReplyTarget(contextKey, replyTarget, async () => {
1056
1075
  try {
1057
1076
  const kind = String(scopedAction.value.action ?? "");
1058
- if (kind === "terminal_authorize") {
1077
+ if (kind.startsWith("bot_settings_")) {
1078
+ await this.handleSettingsAction(scopedAction, replyTarget);
1079
+ } else if (kind.startsWith("schedule_")) {
1080
+ await this.handleScheduleAction(scopedAction, replyTarget);
1081
+ } else if (kind === "terminal_authorize") {
1059
1082
  if (!this.lifecycle?.authorizeTerminal) throw new Error("网页终端未启用。");
1060
1083
  await this.outbound.sendText(contextKey, await this.lifecycle.authorizeTerminal(scopedAction));
1061
1084
  } else if (kind === "safe_restart_terminal_stop") {
@@ -1253,7 +1276,6 @@ export class ProxySessionController {
1253
1276
  );
1254
1277
  } else if (kind === "session_stop") {
1255
1278
  const sessionId = String(scopedAction.value.sessionId ?? "");
1256
- await this.outbound.sendText(contextKey, STOP_TASK_STARTED_MESSAGE);
1257
1279
  await this.stopSessionReference(contextKey, sessionId);
1258
1280
  if (scopedAction.value.cardView === "status") await this.refreshStatusCardFromAction(scopedAction, sessionId);
1259
1281
  else if (scopedAction.value.cardView !== "safe_restart") {
@@ -1775,6 +1797,199 @@ export class ProxySessionController {
1775
1797
  return this.requireCurrentSession(contextKey);
1776
1798
  }
1777
1799
 
1800
+ async drainScheduledPrompts(localSessionId: string): Promise<void> {
1801
+ if (this.lifecycle?.canStartScheduledTasks?.() === false) return;
1802
+ await this.scheduleNextQueuedPrompt(localSessionId);
1803
+ }
1804
+
1805
+ async notifySchedule(job: ScheduledJob, text: string): Promise<void> {
1806
+ const target = job.replyMessageId ? { messageId: job.replyMessageId, replyInThread: true as const } : undefined;
1807
+ await this.outbound.withReplyTarget(job.contextKey, target, () => this.outbound.sendText(job.contextKey, text));
1808
+ }
1809
+
1810
+ async controlSchedule(command: ScheduleCommand, localSessionId?: string): Promise<unknown> {
1811
+ command = scheduleCommandSchema.parse(command);
1812
+ if (command.operation === "list") return this.store.schedules.list(undefined, 100);
1813
+ if (command.operation === "add") {
1814
+ if (!localSessionId || !command.input) throw new Error("需要目标任务和计划参数。");
1815
+ const session = this.requireControlSession(localSessionId);
1816
+ const contextKey = this.controlSessionContextKey(session);
1817
+ const target = this.controlSessionReplyTarget(session);
1818
+ const job = this.createSchedule(command.input, session.localSessionId, contextKey, target?.messageId);
1819
+ await this.outbound.withReplyTarget(contextKey, target, () => this.showSchedule(job));
1820
+ return job;
1821
+ }
1822
+ const saved = this.store.schedules.get(command.id ?? "");
1823
+ if (saved && command.operation === "show") return saved;
1824
+ if (saved && command.operation === "history") return this.store.schedules.runs(saved.id);
1825
+ const job = this.store.schedules.require(command.id ?? "");
1826
+ if (command.operation === "show") return job;
1827
+ if (command.operation === "history") return this.store.schedules.runs(job.id);
1828
+ if (command.operation === "edit") {
1829
+ if (!command.input) throw new Error("需要计划参数。");
1830
+ const updated = this.store.schedules.edit(job.id, job.revision, command.input);
1831
+ const target = job.replyMessageId ? { messageId: job.replyMessageId, replyInThread: true as const } : undefined;
1832
+ await this.outbound.withReplyTarget(job.contextKey, target, () => this.showSchedule(updated));
1833
+ return updated;
1834
+ }
1835
+ if (command.operation === "run") {
1836
+ this.assertScheduleTarget(job);
1837
+ const run = this.store.schedules.dispatch(job, Date.now(), Date.now(), { manual: true });
1838
+ await this.drainScheduledPrompts(job.localSessionId);
1839
+ return run;
1840
+ }
1841
+ if (!["pause", "resume", "delete"].includes(command.operation)) throw new Error("无效的定时任务操作。");
1842
+ if (command.operation === "resume") this.assertScheduleTarget(job);
1843
+ return this.store.schedules.change(job.id, job.revision, command.operation as "pause" | "resume" | "delete");
1844
+ }
1845
+
1846
+ private requireSettingsOwner(userId?: string): SettingsStore {
1847
+ if (!this.config.feishu.userOpenId || userId !== this.config.feishu.userOpenId) {
1848
+ throw new Error("只有 Agent Bot 所有者可以管理全局配置。");
1849
+ }
1850
+ if (!this.lifecycle?.settings) throw new Error("当前运行方式不支持配置面板。");
1851
+ return this.lifecycle.settings;
1852
+ }
1853
+
1854
+ private async handleSettingsAction(action: CardAction, replyTarget?: MessageReplyTarget): Promise<void> {
1855
+ const settings = this.requireSettingsOwner(action.userId);
1856
+ return this.globalSettingsOperations.run("profile", () => this.handleSettingsActionNow(settings, action, replyTarget));
1857
+ }
1858
+
1859
+ private async settingsCatalog(snapshot: SettingsSnapshot, selectedProvider?: string): Promise<SettingsCatalog | undefined> {
1860
+ if (!snapshot.agentName) return undefined;
1861
+ let providers: SettingsCatalog["providers"];
1862
+ try {
1863
+ const runtime = this.runtimes.forAgent(snapshot.agentName);
1864
+ providers = await runtime.listModelProviders?.() ?? [];
1865
+ const requested = selectedProvider ?? snapshot.modelProvider;
1866
+ const provider = requested || providers.find((entry) => entry.isDefault)?.id;
1867
+ const result = await this.modelOptions(runtime, provider,
1868
+ selectedProvider === undefined || selectedProvider === (snapshot.modelProvider ?? "") ? snapshot.model : undefined);
1869
+ return { models: result.models, providers,
1870
+ ...(result.warning || result.models.length === 0
1871
+ ? { warning: "模型列表暂不可完整获取;保留当前配置,也可选择使用 Agent 默认。" } : {}) };
1872
+ } catch {
1873
+ return { models: [], providers, warning: "无法获取模型列表;保留当前配置,也可选择使用 Agent 默认。" };
1874
+ }
1875
+ }
1876
+
1877
+ private async handleSettingsActionNow(settings: SettingsStore, action: CardAction, replyTarget?: MessageReplyTarget): Promise<void> {
1878
+ const kind = action.value.action;
1879
+ if (kind === "bot_settings_restart") {
1880
+ await this.lifecycle!.restart(action.contextKey, false, replyTarget);
1881
+ return;
1882
+ }
1883
+ if (!["bot_settings_show", "bot_settings_agent", "bot_settings_change"].includes(String(kind))) throw new Error("无效的配置操作。");
1884
+ const messageId = requiredCardMessageId(action.messageId);
1885
+ const agentValue = kind === "bot_settings_agent" ? action.value.option : action.value.agentName;
1886
+ const agentName = typeof agentValue === "string" ? agentValue : undefined;
1887
+ const current = settings.read(action.value.section, agentName);
1888
+ const selectedProvider = kind === "bot_settings_change" && action.value.field === "modelProvider" && typeof action.value.option === "string"
1889
+ ? (action.value.option === "__agent_default__" ? "" : action.value.option) : undefined;
1890
+ const catalog = await this.settingsCatalog(current, selectedProvider);
1891
+ if (settings.read(current.section, current.agentName).revision !== current.revision)
1892
+ throw new Error("配置已变化,请刷新面板后重新编辑。");
1893
+ let snapshot = settings.read(current.section, current.agentName, catalog);
1894
+ let notice: string | undefined;
1895
+ if (kind === "bot_settings_change") {
1896
+ const field = snapshot.fields.find((entry) => entry.name === action.value.field);
1897
+ const value = field?.kind === "boolean" ? action.value.checked
1898
+ : field?.kind === "select" ? action.value.option : action.value.inputValue;
1899
+ try {
1900
+ snapshot = settings.saveField(snapshot.section, snapshot.agentName, action.value.field, action.value.revision, value, catalog);
1901
+ if (["modelProvider", "model"].includes(String(action.value.field))
1902
+ && current.agentName && settings.read("agents", current.agentName).values.reasoningEffort === ""
1903
+ && current.reasoningEffort) notice = "已自动保存,思考强度已恢复 Agent 默认;安全重启后生效。";
1904
+ } catch (error) {
1905
+ snapshot = settings.read(current.section, current.agentName, await this.settingsCatalog(current));
1906
+ notice = `未保存:${error instanceof Error ? error.message : "配置保存失败,请重试。"}`;
1907
+ }
1908
+ }
1909
+ await this.outbound.updateInteractiveCard(action.contextKey, messageId, renderSettingsCard(snapshot, action.contextKey, notice));
1910
+ }
1911
+
1912
+ private createSchedule(input: ScheduleInput, localSessionId: string, contextKey: string, replyMessageId?: string): ScheduledJob {
1913
+ if (!this.config.feishu.userOpenId) throw new Error("请先配置 Agent Bot 所有者,才能创建定时任务。");
1914
+ this.requireSession(contextKey, localSessionId);
1915
+ if (isThreadContextKey(contextKey) && !replyMessageId) throw new Error("缺少话题回复位置,请在原话题中创建计划。");
1916
+ return this.store.schedules.create(input, { localSessionId, contextKey, replyMessageId, ownerId: this.config.feishu.userOpenId });
1917
+ }
1918
+
1919
+ private assertScheduleTarget(job: ScheduledJob): void {
1920
+ if (job.ownerId !== this.config.feishu.userOpenId) throw new Error("计划所有者已变化,请重新创建计划。");
1921
+ const session = this.store.getSession(job.localSessionId);
1922
+ if (!session || session.status === "closed") throw new Error("目标任务已关闭,不能执行该计划。");
1923
+ if (!this.outbound.canRoute(job.contextKey)) throw new Error("计划的原始会话不可用。");
1924
+ }
1925
+
1926
+ private async showSchedule(job: ScheduledJob, messageId?: string, history = false): Promise<void> {
1927
+ const title = this.store.getSession(job.localSessionId)?.title ?? job.localSessionId;
1928
+ const card = renderSchedule(job, title, this.store.schedules.runs(job.id, history ? 10 : 1), history);
1929
+ if (messageId) await this.outbound.updateInteractiveCard(job.contextKey, messageId, card);
1930
+ else await this.outbound.sendInteractiveCard(job.contextKey, card);
1931
+ }
1932
+
1933
+ private async showScheduleList(contextKey: string, page = 0, messageId?: string): Promise<void> {
1934
+ if (!Number.isSafeInteger(page) || page < 0 || page > 10_000) throw new Error("无效的计划页码。");
1935
+ const card = renderScheduleList(this.store.schedules.list(contextKey, 11, page * 10), contextKey, page);
1936
+ if (messageId) await this.outbound.updateInteractiveCard(contextKey, messageId, card);
1937
+ else await this.outbound.sendInteractiveCard(contextKey, card);
1938
+ }
1939
+
1940
+ private async handleScheduleAction(action: CardAction, replyTarget?: MessageReplyTarget): Promise<void> {
1941
+ if (!this.config.feishu.userOpenId || action.userId !== this.config.feishu.userOpenId) throw new Error("只有 Agent Bot 所有者可以管理定时任务。");
1942
+ const operation = String(action.value.action).slice("schedule_".length);
1943
+ const messageId = requiredCardMessageId(action.messageId);
1944
+ if (operation === "list") return this.showScheduleList(action.contextKey, Number(action.value.page ?? 0), messageId);
1945
+ if (operation === "new") {
1946
+ const session = this.requireCurrentSession(action.contextKey);
1947
+ return this.outbound.updateInteractiveCard(action.contextKey, messageId, renderScheduleForm(action.contextKey, undefined, session.localSessionId));
1948
+ }
1949
+ const id = String(action.value.scheduleId ?? "");
1950
+ const job = id ? (["show", "history"].includes(operation) ? this.store.schedules.get(id) : this.store.schedules.require(id)) : undefined;
1951
+ if (job && (job.contextKey !== action.contextKey || job.ownerId !== action.userId)) throw new Error("此会话无权操作该计划。");
1952
+ if (operation === "show" || operation === "history") {
1953
+ if (!job) throw new Error("计划不存在。");
1954
+ return this.showSchedule(job, messageId, operation === "history");
1955
+ }
1956
+ if (job && job.revision !== Number(action.value.revision)) throw new Error("计划卡片已过期,请刷新。");
1957
+ if (operation === "resolve" && job) {
1958
+ const run = this.store.schedules.getRun(String(action.value.runId ?? ""));
1959
+ if (!run || run.jobId !== job.id || run.status !== "unknown") throw new Error("本次运行状态已变化,请刷新。");
1960
+ const session = this.store.getSession(job.localSessionId);
1961
+ if (session && run.turnId && this.runtimes.forAgent(session.agentName).getSession(session.localSessionId)?.activeTurnId === run.turnId) {
1962
+ throw new Error("本次运行仍活跃,请先停止或等待完成。");
1963
+ }
1964
+ this.store.schedules.finish(run.id, "cancelled", "用户已核实本次运行结束,解除调度阻塞。");
1965
+ return this.showSchedule(job, messageId, true);
1966
+ }
1967
+ if (operation === "edit") {
1968
+ if (!job) throw new Error("计划不存在。");
1969
+ return this.outbound.updateInteractiveCard(action.contextKey, messageId, renderScheduleForm(action.contextKey, job));
1970
+ }
1971
+ if (operation === "submit") {
1972
+ const form = action.value.formValue as Record<string, unknown> | undefined;
1973
+ if (!form || typeof form !== "object") throw new Error("缺少计划表单。");
1974
+ const string = (key: string) => typeof form[key] === "string" ? form[key] as string : "";
1975
+ const input: ScheduleInput = { name: string("name"), prompt: string("prompt"), timeZone: string("timeZone"),
1976
+ maxDelayMinutes: Number(string("maxDelayMinutes")), catchUpMinutes: Number(string("catchUpMinutes")),
1977
+ ...(string("cron").trim() ? { cron: string("cron") } : {}), ...(string("at").trim() ? { at: string("at") } : {}) };
1978
+ const updated = job ? this.store.schedules.edit(job.id, job.revision, input)
1979
+ : this.createSchedule(input, String(action.value.sessionId ?? ""), action.contextKey, replyTarget?.messageId);
1980
+ return this.showSchedule(updated, messageId);
1981
+ }
1982
+ if (!job) throw new Error("计划不存在。");
1983
+ if (operation === "run") {
1984
+ await this.controlSchedule({ operation: "run", id: job.id });
1985
+ return this.showSchedule(this.store.schedules.require(job.id), messageId, true);
1986
+ }
1987
+ if (!["confirm", "pause", "resume", "delete"].includes(operation)) throw new Error("无效的定时任务操作。");
1988
+ if (operation === "confirm" || operation === "resume") this.assertScheduleTarget(job);
1989
+ const updated = this.store.schedules.change(job.id, job.revision, operation as "confirm" | "pause" | "resume" | "delete");
1990
+ await this.showSchedule(updated, messageId);
1991
+ }
1992
+
1778
1993
  async controlQueueTaskPrompt(localSessionId: string, text: string): Promise<{ promptId: string; queued: number }> {
1779
1994
  const promptText = text.trim();
1780
1995
  if (!promptText) throw new Error("The queued Prompt cannot be empty.");
@@ -2079,6 +2294,37 @@ export class ProxySessionController {
2079
2294
  throw new Error(unboundThreadTaskMessage());
2080
2295
  }
2081
2296
  switch (command.type) {
2297
+ case "settings": {
2298
+ const settings = this.requireSettingsOwner(userId);
2299
+ await this.globalSettingsOperations.run("profile", async () => {
2300
+ const current = settings.read();
2301
+ const catalog = await this.settingsCatalog(current);
2302
+ if (settings.read().revision !== current.revision) throw new Error("配置已变化,请重新打开设置。");
2303
+ await this.outbound.sendInteractiveCard(contextKey, renderSettingsCard(settings.read("general", undefined, catalog), contextKey));
2304
+ });
2305
+ return;
2306
+ }
2307
+ case "schedule": {
2308
+ if (!this.config.feishu.userOpenId || userId !== this.config.feishu.userOpenId) throw new Error("只有 Agent Bot 所有者可以管理定时任务。");
2309
+ if (command.command.operation === "list") {
2310
+ await this.showScheduleList(contextKey);
2311
+ return;
2312
+ }
2313
+ if (command.command.operation === "add") {
2314
+ const session = this.requireCurrentSession(contextKey);
2315
+ const job = this.createSchedule(command.command.input!, session.localSessionId, contextKey, replyTarget?.messageId);
2316
+ await this.showSchedule(job);
2317
+ return;
2318
+ }
2319
+ const job = ["show", "history"].includes(command.command.operation)
2320
+ ? this.store.schedules.get(command.command.id ?? "") : this.store.schedules.require(command.command.id ?? "");
2321
+ if (!job) throw new Error("计划不存在。");
2322
+ if (job.contextKey !== contextKey || job.ownerId !== userId) throw new Error("此会话无权操作该计划。");
2323
+ await this.controlSchedule(command.command);
2324
+ if (command.command.operation === "edit") return;
2325
+ await this.showSchedule(this.store.schedules.get(job.id)!, undefined, command.command.operation === "history");
2326
+ return;
2327
+ }
2082
2328
  case "shell":
2083
2329
  await this.runShellCommand(contextKey, command.command, messageId, incomingMessage);
2084
2330
  return;
@@ -2337,6 +2583,10 @@ export class ProxySessionController {
2337
2583
  for (const attempt of this.store.listCancellationRequestedTurnAttempts()) {
2338
2584
  const session = this.store.getSession(attempt.localSessionId);
2339
2585
  if (!attempt.turnId) {
2586
+ if (attempt.submissionState !== "not_submitted") {
2587
+ await this.markAttemptUnknown(attempt, "停止意图已保存,但提交结果未知;未自动重发。请核实远端执行状态。");
2588
+ continue;
2589
+ }
2340
2590
  this.store.updateTurnAttempt(attempt.attemptId, { status: "cancelled" });
2341
2591
  if (session?.status === "starting" || session?.status === "running") {
2342
2592
  this.store.updateSession(session.localSessionId, { status: "ready" });
@@ -2355,12 +2605,20 @@ export class ProxySessionController {
2355
2605
  );
2356
2606
  }
2357
2607
  try {
2358
- await this.handleRuntimeEvent({
2359
- type: "turn_cancelled",
2360
- sessionId: attempt.localSessionId,
2361
- turnId: attempt.turnId,
2362
- });
2608
+ if (!session?.remoteSessionId) throw new Error("Missing remote session for cancellation verification.");
2609
+ const runtime = this.runtimes.forAgent(session.agentName);
2610
+ const remote = await runtime.readRemoteSession?.(session.remoteSessionId);
2611
+ if (!remote || remote.lastTurnId !== attempt.turnId) throw new Error("Original turn status is unverified.");
2612
+ if (isRemoteSessionActive(remote)) {
2613
+ if (!runtime.interruptRemoteTurn) throw new Error("Remote interruption is unavailable.");
2614
+ await runtime.interruptRemoteTurn(session.remoteSessionId, attempt.turnId);
2615
+ await this.loadSession(session);
2616
+ } else if (["completed", "failed", "interrupted"].includes(remote.lastTurnStatus ?? "")) {
2617
+ await this.loadSession(session);
2618
+ await runtime.synchronizeSession(session.localSessionId);
2619
+ } else throw new Error("Original turn termination is unverified.");
2363
2620
  } catch (error) {
2621
+ await this.markAttemptUnknown(attempt, "停止意图已保存,但尚不能确认原轮次已结束。未自动续跑,请核实执行记录。");
2364
2622
  this.logger.warn(
2365
2623
  { error, attemptId: attempt.attemptId, turnId: attempt.turnId },
2366
2624
  "Failed to finish a persisted user-requested turn cancellation.",
@@ -2373,6 +2631,8 @@ export class ProxySessionController {
2373
2631
  for (const session of this.store.listAllSessions()) {
2374
2632
  if (session.status !== "starting" && session.status !== "running" && session.status !== "ready") continue;
2375
2633
  if (this.store.findIncompleteTurnAttemptForSession(session.localSessionId)) continue;
2634
+ if (this.store.hasUnknownTurnAttemptForSession(session.localSessionId)) continue;
2635
+ if (this.store.hasCancellationRequestedForSession(session.localSessionId)) continue;
2376
2636
  const lastTurn = session.lastTurnId
2377
2637
  ? {
2378
2638
  turnId: session.lastTurnId,
@@ -2394,6 +2654,7 @@ export class ProxySessionController {
2394
2654
  : lastTurn;
2395
2655
  if (!latest && session.status === "ready") continue;
2396
2656
  const snapshot = turnViewSnapshot(latest?.snapshot);
2657
+ if (snapshot?.status === "unknown") continue;
2397
2658
  if (snapshot && isTerminalTurnViewStatus(snapshot.status)) {
2398
2659
  this.store.updateSession(session.localSessionId, {
2399
2660
  status: snapshot.status === "failed" ? "failed" : "ready",
@@ -2403,6 +2664,8 @@ export class ProxySessionController {
2403
2664
  const persistedTurnId = latest?.turnId;
2404
2665
  const pendingTurnId = persistedTurnId?.startsWith("pending_") ? persistedTurnId : undefined;
2405
2666
  const turnId = pendingTurnId ? undefined : persistedTurnId ?? session.lastTurnId;
2667
+ if (persistedTurnId && this.store.schedules.ownsTurn(persistedTurnId)) continue;
2668
+ if (turnId && this.store.schedules.ownsTurn(turnId)) continue;
2406
2669
  const replyTarget = snapshot?.replyTarget?.replyInThread ? snapshot.replyTarget : undefined;
2407
2670
  this.store.createTurnAttempt({
2408
2671
  attemptId: createId("attempt"),
@@ -2414,6 +2677,7 @@ export class ProxySessionController {
2414
2677
  pendingTurnId,
2415
2678
  turnId,
2416
2679
  status: turnId ? "running" : "accepted",
2680
+ submissionState: turnId ? "submitted" : "submission_unknown",
2417
2681
  createdAt: latest?.updatedAt ?? session.updatedAt,
2418
2682
  updatedAt: latest?.updatedAt ?? session.updatedAt,
2419
2683
  });
@@ -2424,6 +2688,10 @@ export class ProxySessionController {
2424
2688
  attempt: TurnAttemptRecord,
2425
2689
  message = "执行中断已超过 10 分钟,未自动恢复。",
2426
2690
  ): Promise<void> {
2691
+ if (attempt.submissionState !== "not_submitted") {
2692
+ await this.markAttemptUnknown(attempt, `${message} 原执行结果待核实,未自动重发。`);
2693
+ return;
2694
+ }
2427
2695
  clearTimeout(this.recoveryRetryTimers.get(attempt.attemptId));
2428
2696
  this.recoveryRetryTimers.delete(attempt.attemptId);
2429
2697
  this.recoveryRetryStartedAt.delete(attempt.attemptId);
@@ -2520,11 +2788,22 @@ export class ProxySessionController {
2520
2788
 
2521
2789
  private async recoverTurnAttempt(attempt: TurnAttemptRecord, announce = true): Promise<void> {
2522
2790
  if (this.recoveryClosed) return;
2791
+ if (attempt.executionGeneration !== this.store.executionGeneration(attempt.localSessionId)) {
2792
+ if (attempt.submissionState === "not_submitted") this.store.updateTurnAttempt(attempt.attemptId, { status: "cancelled" });
2793
+ else await this.markAttemptUnknown(attempt, "停止意图已保存,原执行结果待核实,未自动续跑。");
2794
+ return;
2795
+ }
2523
2796
  const session = this.store.getSession(attempt.localSessionId);
2524
2797
  if (!session || session.status === "closed") {
2525
2798
  this.store.updateTurnAttempt(attempt.attemptId, { status: "interrupted" });
2526
2799
  return;
2527
2800
  }
2801
+ const scheduledRun = this.store.schedules.getRun(attempt.attemptId);
2802
+ if (scheduledRun?.status === "unknown"
2803
+ || (scheduledRun && !attempt.turnId && ["cancelled", "expired", "failed", "skipped", "completed"].includes(scheduledRun.status))) {
2804
+ this.store.updateTurnAttempt(attempt.attemptId, { status: scheduledRun.status === "cancelled" ? "cancelled" : "interrupted" });
2805
+ return;
2806
+ }
2528
2807
  const contextKey = attempt.contextKey || session.contextKey;
2529
2808
  const replyTarget = attempt.replyMessageId
2530
2809
  ? { messageId: attempt.replyMessageId, replyInThread: true as const }
@@ -2552,6 +2831,10 @@ export class ProxySessionController {
2552
2831
 
2553
2832
  const runtime = this.runtimes.forAgent(session.agentName);
2554
2833
  const sourceTurnId = attempt.turnId;
2834
+ if (this.store.schedules.getRun(attempt.attemptId) && (!sourceTurnId || runtime.kind === "acp")) {
2835
+ await this.markScheduledAttemptUnknown(attempt, "重启后无法确认本次运行状态,未自动重发。请核实执行记录。");
2836
+ return;
2837
+ }
2555
2838
  if (runtime.kind === "acp") {
2556
2839
  await this.continueInterruptedAttempt(attempt, session, sourceTurnId, replyTarget);
2557
2840
  return;
@@ -2571,7 +2854,7 @@ export class ProxySessionController {
2571
2854
  await this.reconcileRecoveredRemoteTurn(attempt, session, remote.lastTurnId);
2572
2855
  return;
2573
2856
  }
2574
- if (remote && remoteTurnBelongsToAttempt && remote.lastTurnStatus === "failed") {
2857
+ if (remote && remoteTurnBelongsToAttempt && (remote.lastTurnStatus === "failed" || remote.lastTurnStatus === "interrupted")) {
2575
2858
  await this.reconcileRecoveredRemoteTurn(attempt, session, remote.lastTurnId);
2576
2859
  return;
2577
2860
  }
@@ -2589,9 +2872,43 @@ export class ProxySessionController {
2589
2872
  this.scheduleRecoveryRetry(attempt.attemptId);
2590
2873
  return;
2591
2874
  }
2875
+ if (this.store.schedules.getRun(attempt.attemptId)) {
2876
+ await this.markScheduledAttemptUnknown(attempt, "原轮次状态待核实,未自动重发。请核实执行记录。");
2877
+ return;
2878
+ }
2592
2879
  await this.continueInterruptedAttempt(attempt, session, sourceTurnId, replyTarget);
2593
2880
  }
2594
2881
 
2882
+ private async markScheduledAttemptUnknown(attempt: TurnAttemptRecord, detail: string): Promise<void> {
2883
+ await this.markAttemptUnknown(attempt, detail);
2884
+ this.store.schedules.finish(attempt.attemptId, "unknown", detail);
2885
+ const run = this.store.schedules.getRun(attempt.attemptId)!;
2886
+ const job = this.store.schedules.get(run.jobId);
2887
+ if (job) await this.notifySchedule(job, `定时任务「${job.spec.name}」:${detail}`);
2888
+ }
2889
+
2890
+ private async markAttemptUnknown(attempt: TurnAttemptRecord, message: string): Promise<void> {
2891
+ clearTimeout(this.recoveryRetryTimers.get(attempt.attemptId));
2892
+ this.recoveryRetryTimers.delete(attempt.attemptId);
2893
+ this.recoveryRetryStartedAt.delete(attempt.attemptId);
2894
+ this.recoveredLiveAttempts.delete(attempt.attemptId);
2895
+ const session = this.store.getSession(attempt.localSessionId);
2896
+ const turnId = attempt.turnId ?? attempt.pendingTurnId;
2897
+ this.store.updateTurnAttempt(attempt.attemptId, { status: "unknown" });
2898
+ if (this.store.schedules.getRun(attempt.attemptId)) this.store.schedules.finish(attempt.attemptId, "unknown", message);
2899
+ if (!session || session.status === "closed") return;
2900
+ this.outbound.registerSession(session.localSessionId, attempt.contextKey, session.title, session.cwd,
2901
+ this.agentLabel(session.agentName), session.model, session.modelProvider);
2902
+ const active = this.runtimes.forAgent(session.agentName).getSession(session.localSessionId)?.activeTurnId;
2903
+ if (!session.lastTurnId || session.lastTurnId === turnId || session.lastTurnId === attempt.recoveredFromTurnId
2904
+ || (!attempt.turnId && !active)) {
2905
+ this.store.updateRuntimeSession(session.localSessionId, { lastTurnId: turnId, lastTurnStatus: "unknown" });
2906
+ if (!active) this.store.updateSession(session.localSessionId, { status: "ready" });
2907
+ }
2908
+ if (turnId) await this.outbound.onEvent({ type: "turn_status_unknown", sessionId: session.localSessionId, turnId, message });
2909
+ else await this.outbound.sendText(attempt.contextKey, message);
2910
+ }
2911
+
2595
2912
  private async reconcileRecoveredRemoteTurn(
2596
2913
  attempt: TurnAttemptRecord,
2597
2914
  session: SessionRecord,
@@ -2725,6 +3042,10 @@ export class ProxySessionController {
2725
3042
  sourceTurnId: string | undefined,
2726
3043
  replyTarget?: MessageReplyTarget,
2727
3044
  ): Promise<void> {
3045
+ if (attempt.submissionState !== "not_submitted" || sourceTurnId) {
3046
+ await this.markAttemptUnknown(attempt, "原执行结果待核实,未自动重发。请检查执行记录后发送消息继续。");
3047
+ return;
3048
+ }
2728
3049
  const oldCardTurnId = attempt.pendingTurnId ?? sourceTurnId;
2729
3050
  if (oldCardTurnId) {
2730
3051
  await this.outbound.interruptTurnForRecovery(
@@ -2739,7 +3060,7 @@ export class ProxySessionController {
2739
3060
  );
2740
3061
  });
2741
3062
  }
2742
- this.store.prepareTurnAttemptRecovery(attempt.attemptId, oldCardTurnId);
3063
+ if (!this.store.prepareTurnAttemptRecovery(attempt.attemptId, oldCardTurnId)) return;
2743
3064
  this.store.updateSession(session.localSessionId, { status: "ready" });
2744
3065
  if (sourceTurnId) {
2745
3066
  this.store.updateRuntimeSession(session.localSessionId, {
@@ -2750,7 +3071,7 @@ export class ProxySessionController {
2750
3071
  const current = this.store.getSession(session.localSessionId) ?? session;
2751
3072
  const loaded = await this.loadSession({ ...current, contextKey: attempt.contextKey },
2752
3073
  Boolean(this.store.getPendingProviderSettings(current.localSessionId)));
2753
- const recoveryText = recoveryRuntimePrompt(attempt.promptText);
3074
+ const recoveryText = attempt.promptText;
2754
3075
  const turnId = await this.startTurn(
2755
3076
  loaded,
2756
3077
  recoveryText,
@@ -2758,6 +3079,8 @@ export class ProxySessionController {
2758
3079
  attempt.localImagePaths,
2759
3080
  {
2760
3081
  attemptId: attempt.attemptId,
3082
+ executionGeneration: attempt.executionGeneration,
3083
+ trigger: "recovery",
2761
3084
  messageId: attempt.messageId,
2762
3085
  displayPrompt: recoveryCardPrompt(attempt.promptText),
2763
3086
  preserveAttemptOnFailure: true,
@@ -2816,6 +3139,7 @@ export class ProxySessionController {
2816
3139
  localImagePaths?: string[],
2817
3140
  displayPrompt?: string,
2818
3141
  ): Promise<void> {
3142
+ const executionGeneration = this.store.executionGeneration(record.localSessionId);
2819
3143
  if (this.llmRetryingSessions.has(record.localSessionId) || this.planHandoffs.has(record.localSessionId)) {
2820
3144
  const queued = this.persistQueuedPrompt(record.localSessionId, contextKey, text, {
2821
3145
  localImagePaths,
@@ -2874,6 +3198,8 @@ export class ProxySessionController {
2874
3198
  this.logger.warn({ error, sessionId: record.localSessionId }, "Failed to synchronize session before prompt.");
2875
3199
  }
2876
3200
  }
3201
+ this.assertExecutionGeneration(record.localSessionId, executionGeneration);
3202
+ this.store.acknowledgeUnknownTurnAttempts(record.localSessionId);
2877
3203
  const activeTurnId = loaded.session.activeTurnId;
2878
3204
  if (activeTurnId) {
2879
3205
  const activeContextKey = this.store.getTurnContextKey(activeTurnId);
@@ -2892,6 +3218,9 @@ export class ProxySessionController {
2892
3218
  if (messageId) await this.bindMessageReactionToTurn(messageId, record.localSessionId, activeTurnId);
2893
3219
  return;
2894
3220
  } catch (error) {
3221
+ if (!(error instanceof TurnNotSubmittedError)) {
3222
+ throw new Error("追加消息的提交结果待核实,未自动重发或入队。请检查执行记录后继续。", { cause: error });
3223
+ }
2895
3224
  this.logger.debug({ error, sessionId: record.localSessionId, activeTurnId }, "Steering failed; reconciling the App Server thread.");
2896
3225
  let current = loaded.runtime.getSession(record.localSessionId);
2897
3226
  try {
@@ -2900,12 +3229,13 @@ export class ProxySessionController {
2900
3229
  this.logger.warn({ error: syncError, sessionId: record.localSessionId }, "Failed to synchronize after steering failure.");
2901
3230
  }
2902
3231
  if (!current?.activeTurnId) {
2903
- const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt });
3232
+ const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt, executionGeneration });
2904
3233
  if (messageId) await this.bindMessageReactionToTurn(messageId, record.localSessionId, turnId);
2905
3234
  return;
2906
3235
  }
2907
3236
  if (current.activeTurnId !== activeTurnId) {
2908
3237
  try {
3238
+ this.assertExecutionGeneration(record.localSessionId, executionGeneration);
2909
3239
  await loaded.runtime.steerTurn(
2910
3240
  record.localSessionId,
2911
3241
  current.activeTurnId,
@@ -2921,6 +3251,9 @@ export class ProxySessionController {
2921
3251
  if (messageId) await this.bindMessageReactionToTurn(messageId, record.localSessionId, current.activeTurnId);
2922
3252
  return;
2923
3253
  } catch (retryError) {
3254
+ if (!(retryError instanceof TurnNotSubmittedError)) {
3255
+ throw new Error("追加消息的提交结果待核实,未自动重发或入队。", { cause: retryError });
3256
+ }
2924
3257
  this.logger.warn(
2925
3258
  { error: retryError, sessionId: record.localSessionId, activeTurnId: current.activeTurnId },
2926
3259
  "Failed to steer the reconciled App Server turn; queueing prompt.",
@@ -2936,7 +3269,7 @@ export class ProxySessionController {
2936
3269
  return;
2937
3270
  }
2938
3271
  }
2939
- const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt });
3272
+ const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt, executionGeneration });
2940
3273
  if (messageId) await this.bindMessageReactionToTurn(messageId, record.localSessionId, turnId);
2941
3274
  }
2942
3275
 
@@ -3122,12 +3455,13 @@ export class ProxySessionController {
3122
3455
  return { text, localImagePaths, messageIds: [] };
3123
3456
  }
3124
3457
  if (message.threadContext && !message.threadId) throw new Error("无法识别当前话题,已停止补充上下文以避免读取其他话题。");
3458
+ const current = this.currentSession(message.contextKey);
3459
+ const stopIds = current ? new Set([
3460
+ ...this.store.recentContextMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey, false),
3461
+ ...this.store.recentSubmittedMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey),
3462
+ ]) : new Set<string>();
3463
+ const seen = current ? this.store.recentContextMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey) : new Set<string>();
3125
3464
  try {
3126
- const current = this.currentSession(message.contextKey);
3127
- const stopIds = current ? new Set([
3128
- ...this.store.recentContextMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey, false),
3129
- ...this.store.recentSubmittedMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey),
3130
- ]) : new Set<string>();
3131
3465
  const messages = await this.outbound.readRecentMessages(message.contextKey, {
3132
3466
  chatId: message.chatId,
3133
3467
  ...(message.threadId ? { threadId: message.threadId } : {}),
@@ -3135,7 +3469,6 @@ export class ProxySessionController {
3135
3469
  beforeTimestamp: message.createdAt,
3136
3470
  ...(stopIds.size ? { stopBeforeMessageIds: [...stopIds] } : {}),
3137
3471
  });
3138
- const seen = current ? this.store.recentContextMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey) : new Set<string>();
3139
3472
  seen.add(message.messageId);
3140
3473
  if (message.parentMessageId) seen.add(message.parentMessageId);
3141
3474
  if (message.threadContext && message.rootMessageId) seen.add(message.rootMessageId);
@@ -3995,6 +4328,9 @@ export class ProxySessionController {
3995
4328
  loaded: LoadedSession, text: string, replyTarget?: MessageReplyTarget,
3996
4329
  localImagePaths?: string[], options: StartTurnOptions = {},
3997
4330
  ): Promise<string> {
4331
+ options = { ...options, executionGeneration: options.executionGeneration
4332
+ ?? (options.attemptId ? this.store.getTurnAttempt(options.attemptId)?.executionGeneration : undefined)
4333
+ ?? this.store.executionGeneration(loaded.record.localSessionId) };
3998
4334
  return this.settingsOperations.run(loaded.record.localSessionId, async () => {
3999
4335
  if (options.responseContinuationTurnId) {
4000
4336
  const current = this.store.getSession(loaded.record.localSessionId);
@@ -4027,6 +4363,10 @@ export class ProxySessionController {
4027
4363
  localImagePaths?: string[],
4028
4364
  options: StartTurnOptions = {},
4029
4365
  ): Promise<string> {
4366
+ const executionGeneration = options.executionGeneration
4367
+ ?? (options.attemptId ? this.store.getTurnAttempt(options.attemptId)?.executionGeneration : undefined)
4368
+ ?? this.store.executionGeneration(loaded.record.localSessionId);
4369
+ this.assertExecutionGeneration(loaded.record.localSessionId, executionGeneration);
4030
4370
  const currentRecord = this.store.getSession(loaded.record.localSessionId);
4031
4371
  const title = currentRecord?.title ?? normalizeTaskTitle(options.displayPrompt ?? text);
4032
4372
  if (!currentRecord?.title && title) this.store.updateRuntimeSession(loaded.record.localSessionId, { title });
@@ -4034,6 +4374,7 @@ export class ProxySessionController {
4034
4374
  const attemptId = options.attemptId ?? createId("attempt");
4035
4375
  if (options.attemptId) {
4036
4376
  this.store.updateTurnAttempt(attemptId, {
4377
+ executionGeneration,
4037
4378
  messageId: options.messageId ?? undefined,
4038
4379
  replyMessageId: replyTarget?.messageId ?? undefined,
4039
4380
  status: "recovering",
@@ -4047,12 +4388,25 @@ export class ProxySessionController {
4047
4388
  localImagePaths,
4048
4389
  messageId: options.messageId,
4049
4390
  replyMessageId: replyTarget?.messageId,
4391
+ executionGeneration,
4050
4392
  });
4051
4393
  }
4052
4394
  let turnId: string;
4053
4395
  let runtimeText = text;
4054
4396
  let cardPrompt = options.displayPrompt ?? text;
4055
4397
  let retriedStart = false;
4398
+ const recordSubmission = (): void => {
4399
+ const runtimeSession = loaded.runtime.getSession(loaded.record.localSessionId) ?? loaded.session;
4400
+ const run = options.scheduleRunId ? this.store.schedules.getRun(options.scheduleRunId) : undefined;
4401
+ this.store.provenance.recordSubmission({
4402
+ attemptId, localSessionId: loaded.record.localSessionId,
4403
+ instructionId: options.instructionId ?? options.messageId,
4404
+ trigger: retriedStart ? "retry" : options.trigger ?? (options.scheduleRunId ? "schedule" : "user"),
4405
+ parentSourceTurnId: options.parentSourceTurnId,
4406
+ scheduledFor: run?.scheduledFor,
4407
+ settings: runtimeSession,
4408
+ });
4409
+ };
4056
4410
  try {
4057
4411
  while (true) {
4058
4412
  let pendingTurnId: string | undefined;
@@ -4068,6 +4422,15 @@ export class ProxySessionController {
4068
4422
  localImagePaths,
4069
4423
  );
4070
4424
  } catch (error) {
4425
+ if (options.scheduleRunId) {
4426
+ const run = this.store.schedules.getRun(options.scheduleRunId)!;
4427
+ const job = this.store.schedules.get(run.jobId);
4428
+ if (job?.status === "enabled") {
4429
+ const paused = this.store.schedules.change(job.id, job.revision, "pause");
4430
+ this.store.schedules.update({ ...paused, notice: "原会话的思考卡片创建失败,计划已暂停。请修复后恢复。" });
4431
+ }
4432
+ this.store.schedules.finish(run.id, "failed", "无法创建原会话的思考卡片,未提交模型。");
4433
+ }
4071
4434
  this.store.updateTurnAttempt(attemptId, {
4072
4435
  status: options.preserveAttemptOnFailure ? "recovering" : "failed",
4073
4436
  });
@@ -4076,6 +4439,7 @@ export class ProxySessionController {
4076
4439
  this.store.updateTurnAttempt(attemptId, { pendingTurnId: pendingTurnId ?? null });
4077
4440
 
4078
4441
  try {
4442
+ this.assertExecutionGeneration(loaded.record.localSessionId, executionGeneration);
4079
4443
  if (options.approvedPlanTurnId && (this.planHandoffs.get(loaded.record.localSessionId) !== options.approvedPlanTurnId
4080
4444
  || this.sessionResets.has(loaded.record.localSessionId))) {
4081
4445
  throw new Error("方案执行已取消。");
@@ -4086,8 +4450,17 @@ export class ProxySessionController {
4086
4450
  || this.sessionResets.has(loaded.record.localSessionId) || !loaded.runtime.recoverResponseContinuation) {
4087
4451
  throw new Error("模型续接恢复已取消。");
4088
4452
  }
4453
+ this.store.beginTurnAttemptSubmission(attemptId, recordSubmission);
4089
4454
  turnId = await loaded.runtime.recoverResponseContinuation(loaded.record.localSessionId, options.responseContinuationTurnId, recovery.abort.signal);
4090
4455
  } else {
4456
+ if (options.scheduleRunId) {
4457
+ const run = this.store.schedules.getRun(options.scheduleRunId);
4458
+ if ((!options.approvedPlanTurnId && !this.store.schedules.canSubmit(options.scheduleRunId))
4459
+ || this.lifecycle?.canStartScheduledTasks?.() === false) throw new Error("定时任务已取消、过期或正在安全重启。");
4460
+ this.assertScheduleTarget(this.store.schedules.require(run!.jobId));
4461
+ this.store.schedules.saveRun({ ...run!, status: "submitting" });
4462
+ }
4463
+ this.store.beginTurnAttemptSubmission(attemptId, recordSubmission);
4091
4464
  turnId = await loaded.runtime.startTurn(
4092
4465
  loaded.record.localSessionId,
4093
4466
  options.approvedPlanTurnId
@@ -4098,8 +4471,34 @@ export class ProxySessionController {
4098
4471
  break;
4099
4472
  } catch (error) {
4100
4473
  const message = error instanceof Error ? error.message : String(error);
4101
- const attempt = this.store.getTurnAttempt(attemptId);
4474
+ let attempt = this.store.getTurnAttempt(attemptId);
4475
+ if (error instanceof TurnStoppedBeforeSubmissionError) {
4476
+ this.store.updateTurnAttempt(attemptId, { status: "cancelled" });
4477
+ if (pendingTurnId) await this.outbound.onEvent({ type: "turn_cancelled", sessionId: loaded.record.localSessionId, turnId: pendingTurnId });
4478
+ throw error;
4479
+ }
4480
+ if (attempt?.status === "unknown") throw error;
4481
+ if (attempt?.turnId && attempt.turnId !== options.approvedPlanTurnId) {
4482
+ turnId = attempt.turnId;
4483
+ if (isIncompleteTurnAttemptStatus(attempt.status)) this.store.updateTurnAttempt(attemptId, { status: "running" });
4484
+ break;
4485
+ }
4486
+ if (error instanceof TurnNotSubmittedError && attempt && !attempt.turnId) {
4487
+ this.store.updateTurnAttempt(attemptId, { submissionState: "not_submitted" });
4488
+ attempt = this.store.getTurnAttempt(attemptId);
4489
+ }
4490
+ if (attempt?.status === "cancelling") {
4491
+ if (attempt.submissionState === "not_submitted") this.store.updateTurnAttempt(attemptId, { status: "cancelled" });
4492
+ else await this.markAttemptUnknown(attempt, "停止意图已保存,但请求结果未知。未自动重发,请核实执行记录。");
4493
+ throw error;
4494
+ }
4495
+ if (attempt?.submissionState === "submission_unknown") {
4496
+ await this.markAttemptUnknown(attempt, "请求已发出,但无法确认执行结果;未自动重发。请核实后发送消息继续。");
4497
+ throw error;
4498
+ }
4102
4499
  const retryAttempt = attempt
4500
+ && error instanceof TurnNotSubmittedError
4501
+ && !options.scheduleRunId
4103
4502
  && !options.responseContinuationTurnId
4104
4503
  && isRetryableLlmTurnFailure(message)
4105
4504
  && attempt.retryCount < MAX_LLM_TURN_RETRIES
@@ -4137,7 +4536,7 @@ export class ProxySessionController {
4137
4536
  "Failed to finalize the pending thinking card before an LLM start retry.",
4138
4537
  );
4139
4538
  });
4140
- runtimeText = llmRetryRuntimePrompt(retryAttempt.promptText, retryAttempt.retryCount);
4539
+ runtimeText = retryAttempt.promptText;
4141
4540
  cardPrompt = llmRetryCardPrompt(options.displayPrompt ?? retryAttempt.promptText, retryAttempt.retryCount);
4142
4541
  }
4143
4542
  }
@@ -4145,21 +4544,44 @@ export class ProxySessionController {
4145
4544
  if (retriedStart) this.llmRetryingSessions.delete(loaded.record.localSessionId);
4146
4545
  }
4147
4546
  const attempt = this.store.getTurnAttempt(attemptId);
4547
+ this.store.provenance.bindLatestTurn(attemptId, turnId);
4548
+ if (this.store.executionGeneration(loaded.record.localSessionId) !== executionGeneration) {
4549
+ this.store.updateTurnAttempt(attemptId, { turnId, submissionState: "submitted", status: "cancelling" });
4550
+ try {
4551
+ await loaded.runtime.cancelTurn(loaded.record.localSessionId, turnId);
4552
+ } catch (error) {
4553
+ await this.markAttemptUnknown(this.store.getTurnAttempt(attemptId)!, "停止请求已保存,但无法确认刚启动轮次已停止。请核实执行记录。");
4554
+ throw error;
4555
+ }
4556
+ return turnId;
4557
+ }
4148
4558
  this.store.updateTurnAttempt(attemptId, {
4149
4559
  pendingTurnId: null,
4150
4560
  turnId,
4561
+ submissionState: "submitted",
4151
4562
  ...(attempt && isIncompleteTurnAttemptStatus(attempt.status) ? { status: "running" as const } : {}),
4152
4563
  });
4153
4564
  const latest = this.store.getSession(loaded.record.localSessionId);
4154
4565
  const alreadyTerminal = latest?.lastTurnId === turnId
4155
- && ["completed", "cancelled", "failed"].includes(latest.lastTurnStatus ?? "");
4566
+ && ["completed", "cancelled", "failed", "unknown"].includes(latest.lastTurnStatus ?? "");
4156
4567
  if (!alreadyTerminal) {
4157
4568
  this.store.updateSession(loaded.record.localSessionId, { status: "running" });
4158
4569
  this.store.updateRuntimeSession(loaded.record.localSessionId, { lastTurnId: turnId, lastTurnStatus: "running" });
4159
4570
  }
4571
+ if (options.scheduleRunId) {
4572
+ const run = this.store.schedules.getRun(options.scheduleRunId)!;
4573
+ const completedAttempt = this.store.getTurnAttempt(attemptId);
4574
+ const status = completedAttempt?.status;
4575
+ this.store.schedules.saveRun({ ...run, turnId,
4576
+ status: status === "completed" || status === "failed" || status === "cancelled" ? status : "running" });
4577
+ }
4160
4578
  return turnId;
4161
4579
  }
4162
4580
 
4581
+ private assertExecutionGeneration(sessionId: string, generation: number): void {
4582
+ if (this.store.executionGeneration(sessionId) !== generation) throw new TurnStoppedBeforeSubmissionError();
4583
+ }
4584
+
4163
4585
  private async createSession(
4164
4586
  contextKey: string,
4165
4587
  agentName: string,
@@ -4180,6 +4602,7 @@ export class ProxySessionController {
4180
4602
  ? createProjectlessWorkspace({ prompt: initialTitle }).cwd
4181
4603
  : path.resolve(cwd ?? this.config.defaults.cwd);
4182
4604
  const record = this.store.createSession({ localSessionId, contextKey, agentName, cwd: sessionCwd, status: "starting" });
4605
+ const executionGeneration = this.store.executionGeneration(localSessionId);
4183
4606
  if (initialTitle || resolvedExecutionSettings.modelProvider || resolvedExecutionSettings.model
4184
4607
  || resolvedExecutionSettings.reasoningEffort || resolvedExecutionSettings.permissionMode) {
4185
4608
  this.store.updateRuntimeSession(localSessionId, {
@@ -4218,6 +4641,7 @@ export class ProxySessionController {
4218
4641
  this.persistRuntimeSession(record, session, session.activeTurnId ? "running" : "ready");
4219
4642
  this.outbound.updateSessionModel(localSessionId, session.model, session.modelProvider);
4220
4643
  const saved = this.store.getSession(localSessionId) ?? record;
4644
+ if (prepareTurn) this.assertExecutionGeneration(localSessionId, executionGeneration);
4221
4645
  if (announce) {
4222
4646
  const task = initialTitle ? `${initialTitle}(${session.remoteSessionId})` : session.remoteSessionId;
4223
4647
  await this.outbound.sendText(contextKey, `已创建 ${agent.title} 任务:${task}`);
@@ -4793,6 +5217,21 @@ export class ProxySessionController {
4793
5217
  }
4794
5218
 
4795
5219
  private async handleRuntimeEvent(event: RuntimeEvent): Promise<void> {
5220
+ if (event.type === "turn_started" || event.type === "turn_completed" || event.type === "turn_cancelled"
5221
+ || event.type === "turn_failed" || event.type === "turn_status_unknown") {
5222
+ const current = this.store.getSession(event.sessionId);
5223
+ if (event.type === "turn_started" && current?.status === "closed") return;
5224
+ const saved = turnViewSnapshot(this.store.getTurnSnapshot(event.turnId));
5225
+ const knownStatus = saved?.status ?? (current?.lastTurnId === event.turnId ? current.lastTurnStatus : undefined);
5226
+ if (knownStatus === "unknown" && event.type === "turn_started") return;
5227
+ const terminalStatus = event.type === "turn_completed" ? "completed"
5228
+ : event.type === "turn_cancelled" ? "cancelled" : event.type === "turn_failed" ? "failed" : undefined;
5229
+ if (knownStatus && ["completed", "cancelled", "failed"].includes(knownStatus)
5230
+ && (event.type === "turn_started" || event.type === "turn_status_unknown"
5231
+ || (terminalStatus && terminalStatus !== knownStatus && terminalStatus !== "completed"))) return;
5232
+ if (event.type === "turn_started" && current?.lastTurnId && current.lastTurnId !== event.turnId
5233
+ && (saved || this.store.getTurnRuntimeOrigin(event.turnId))) return;
5234
+ }
4796
5235
  if ("turnId" in event) {
4797
5236
  const recoveryAttempt = this.recoveryRetryStartedAt.size > 0
4798
5237
  ? this.store.findIncompleteTurnAttemptByTurnId(event.turnId) : undefined;
@@ -4811,6 +5250,9 @@ export class ProxySessionController {
4811
5250
  }
4812
5251
  if (event.type === "turn_started") {
4813
5252
  const attempt = this.store.bindTurnAttempt(event.sessionId, event.turnId);
5253
+ if (attempt) this.store.provenance.bindLatestTurn(attempt.attemptId, event.turnId);
5254
+ const scheduledRun = attempt ? this.store.schedules.getRun(attempt.attemptId) : undefined;
5255
+ if (scheduledRun) this.store.schedules.saveRun({ ...scheduledRun, status: "running", turnId: event.turnId });
4814
5256
  if (attempt?.recoveredFromTurnId && attempt.recoveredFromTurnId !== event.turnId) {
4815
5257
  this.store.rebindPendingTurnMessages(event.sessionId, attempt.recoveredFromTurnId, event.turnId);
4816
5258
  }
@@ -4841,20 +5283,11 @@ export class ProxySessionController {
4841
5283
  && Boolean(this.runtimes.forAgent(source.agentName).recoverResponseContinuation)
4842
5284
  && isResponseContinuationError(event.message);
4843
5285
  if (failedAttempt && responseContinuation) {
4844
- const retryAttempt = this.store.prepareTurnAttemptRetry(failedAttempt.attemptId, event.turnId);
5286
+ const retryAttempt = this.store.prepareTurnAttemptRetry(failedAttempt.attemptId, event.turnId, true);
4845
5287
  if (retryAttempt) {
4846
5288
  this.retriedFailureTurnIds.add(event.turnId);
4847
5289
  this.responseContinuations.set(event.sessionId, { turnId: event.turnId, abort: new AbortController() });
4848
- await this.retryFailedLlmTurn(event, retryAttempt, true);
4849
- return;
4850
- }
4851
- }
4852
- if (failedAttempt && !this.responseContinuations.has(event.sessionId)
4853
- && isRetryableLlmTurnFailure(event.message) && failedAttempt.retryCount < MAX_LLM_TURN_RETRIES) {
4854
- const retryAttempt = this.store.prepareTurnAttemptRetry(failedAttempt.attemptId, event.turnId);
4855
- if (retryAttempt) {
4856
- this.retriedFailureTurnIds.add(event.turnId);
4857
- await this.retryFailedLlmTurn(event, retryAttempt);
5290
+ await this.recoverFailedResponse(event, retryAttempt);
4858
5291
  return;
4859
5292
  }
4860
5293
  }
@@ -4879,10 +5312,23 @@ export class ProxySessionController {
4879
5312
  event.turnId,
4880
5313
  event.type === "turn_completed" ? "completed" : event.type === "turn_cancelled" ? "cancelled" : "failed",
4881
5314
  );
4882
- this.store.updateRuntimeSession(event.sessionId, {
4883
- lastTurnId: event.turnId,
4884
- lastTurnStatus: event.type === "turn_completed" ? "completed" : event.type === "turn_cancelled" ? "cancelled" : "failed",
4885
- });
5315
+ const current = this.store.getSession(event.sessionId);
5316
+ if (!current?.lastTurnId || current.lastTurnId === event.turnId) {
5317
+ this.store.updateRuntimeSession(event.sessionId, {
5318
+ lastTurnId: event.turnId,
5319
+ lastTurnStatus: event.type === "turn_completed" ? "completed" : event.type === "turn_cancelled" ? "cancelled" : "failed",
5320
+ });
5321
+ }
5322
+ } else if (event.type === "turn_status_unknown") {
5323
+ const pending = this.store.findIncompleteTurnAttemptForSession(event.sessionId);
5324
+ const attempt = this.store.findIncompleteTurnAttemptByTurnId(event.turnId);
5325
+ if (attempt) this.store.updateTurnAttempt(attempt.attemptId, { status: "unknown" });
5326
+ const current = this.store.getSession(event.sessionId);
5327
+ if (!current?.lastTurnId || current.lastTurnId === event.turnId || pending?.pendingTurnId === event.turnId) {
5328
+ this.store.updateRuntimeSession(event.sessionId, { lastTurnId: event.turnId, lastTurnStatus: "unknown" });
5329
+ const active = current && this.runtimes.forAgent(current.agentName).getSession(event.sessionId)?.activeTurnId;
5330
+ if (current?.status !== "closed" && !active) this.store.updateSession(event.sessionId, { status: "ready" });
5331
+ }
4886
5332
  }
4887
5333
 
4888
5334
  const enrichedEvent: RuntimeEvent = event.type === "context_compaction"
@@ -4926,7 +5372,7 @@ export class ProxySessionController {
4926
5372
  const activeTurnId = latest
4927
5373
  ? this.runtimes.forAgent(latest.agentName).getSession(event.sessionId)?.activeTurnId
4928
5374
  : undefined;
4929
- if (latest?.lastTurnId === event.turnId && !activeTurnId) {
5375
+ if (latest?.lastTurnId === event.turnId && latest.status !== "closed" && !activeTurnId) {
4930
5376
  this.store.updateSession(event.sessionId, { status: event.type === "turn_failed" ? "failed" : "ready" });
4931
5377
  await this.applyPendingProviderWhenIdle(event.sessionId);
4932
5378
  await this.scheduleNextQueuedPrompt(event.sessionId);
@@ -4944,7 +5390,14 @@ export class ProxySessionController {
4944
5390
  const source = this.store.getSession(sessionId);
4945
5391
  if (!source || source.status === "closed" || source.lastTurnId !== turnId) return;
4946
5392
  this.planHandoffs.set(sessionId, turnId);
5393
+ const scheduledRun = this.store.schedules.getRun(attempt.attemptId);
4947
5394
  this.store.markTurnAttemptTerminal(turnId, "completed");
5395
+ if (scheduledRun) {
5396
+ this.store.schedules.saveRun({ ...scheduledRun, status: "running" });
5397
+ this.store.updateTurnAttempt(attempt.attemptId, {
5398
+ status: "recovering", turnId: null, submissionState: "not_submitted", recoveredFromTurnId: turnId,
5399
+ });
5400
+ }
4948
5401
  this.store.updateRuntimeSession(sessionId, { lastTurnId: turnId, lastTurnStatus: "completed" });
4949
5402
  let continued = false;
4950
5403
  let failed = false;
@@ -4973,7 +5426,10 @@ export class ProxySessionController {
4973
5426
  "The proposed plan has been approved. Continue in the current task and workspace without asking for plan approval again; preserve the existing conversation and completed work. Implement the plan unless the user explicitly requested discussion or planning only, or prohibited implementation; those constraints still apply.",
4974
5427
  attempt.replyMessageId ? { messageId: attempt.replyMessageId, replyInThread: true } : undefined,
4975
5428
  undefined,
4976
- { messageId: attempt.messageId, displayPrompt: "方案已确认,继续执行", approvedPlanTurnId: turnId },
5429
+ { messageId: attempt.messageId, displayPrompt: "方案已确认,继续执行", approvedPlanTurnId: turnId,
5430
+ executionGeneration: attempt.executionGeneration,
5431
+ trigger: "plan_handoff", parentSourceTurnId: turnId,
5432
+ ...(scheduledRun ? { attemptId: attempt.attemptId, scheduleRunId: attempt.attemptId } : {}) },
4977
5433
  );
4978
5434
  }
4979
5435
  continued = true;
@@ -4986,13 +5442,19 @@ export class ProxySessionController {
4986
5442
  this.store.audit(attempt.contextKey, "approved_plan_continued", { sessionId, turnId, nextTurnId });
4987
5443
  });
4988
5444
  } catch (error) {
4989
- failed = true;
4990
- this.logger.error({ error, sessionId, turnId }, "Failed to continue an approved plan.");
4991
- await this.outbound.sendText(attempt.contextKey,
4992
- "方案已确认,但后续执行启动失败:" + runtimeErrorMessage(error) + "。请发送消息继续。");
5445
+ failed = !(error instanceof TurnStoppedBeforeSubmissionError);
5446
+ if (failed) {
5447
+ this.logger.error({ error, sessionId, turnId }, "Failed to continue an approved plan.");
5448
+ await this.outbound.sendText(attempt.contextKey,
5449
+ "方案已确认,但后续执行启动失败:" + runtimeErrorMessage(error) + "。请发送消息继续。");
5450
+ }
4993
5451
  } finally {
4994
5452
  if (this.planHandoffs.get(sessionId) === turnId) this.planHandoffs.delete(sessionId);
4995
5453
  if (!continued) {
5454
+ if (scheduledRun && this.store.getTurnAttempt(attempt.attemptId)?.status !== "unknown") {
5455
+ this.store.updateTurnAttempt(attempt.attemptId, { status: failed ? "failed" : "cancelled" });
5456
+ this.store.schedules.finish(attempt.attemptId, failed ? "failed" : "cancelled");
5457
+ }
4996
5458
  try {
4997
5459
  await this.outbound.onEvent(failed
4998
5460
  ? { type: "turn_failed", sessionId, turnId, message: "方案已确认,但后续执行未能启动。" }
@@ -5010,10 +5472,9 @@ export class ProxySessionController {
5010
5472
  }
5011
5473
  }
5012
5474
 
5013
- private async retryFailedLlmTurn(
5475
+ private async recoverFailedResponse(
5014
5476
  event: Extract<RuntimeEvent, { type: "turn_failed" }>,
5015
5477
  attempt: TurnAttemptRecord,
5016
- responseContinuation = false,
5017
5478
  ): Promise<void> {
5018
5479
  const retryNumber = attempt.retryCount;
5019
5480
  const session = this.store.getSession(event.sessionId);
@@ -5031,17 +5492,15 @@ export class ProxySessionController {
5031
5492
  attemptId: attempt.attemptId,
5032
5493
  failedTurnId: event.turnId,
5033
5494
  retryNumber,
5034
- maxRetries: responseContinuation ? 1 : MAX_LLM_TURN_RETRIES,
5035
- responseContinuation,
5495
+ maxRetries: 1,
5496
+ responseContinuation: true,
5036
5497
  error: event.message,
5037
5498
  });
5038
5499
 
5039
5500
  try {
5040
5501
  await this.outbound.onEvent({
5041
5502
  ...event,
5042
- message: responseContinuation
5043
- ? `${event.message}\n\n模型续接状态失效,正在恢复连接并继续(1/1)。`
5044
- : `${event.message}\n\n检测到临时模型服务错误,正在自动重试(${retryNumber}/${MAX_LLM_TURN_RETRIES})。`,
5503
+ message: `${event.message}\n\n模型续接状态失效,正在恢复连接并继续(1/1)。`,
5045
5504
  });
5046
5505
  } catch (error) {
5047
5506
  this.logger.warn(
@@ -5058,23 +5517,26 @@ export class ProxySessionController {
5058
5517
  const loaded = await this.loadSession(current, Boolean(this.store.getPendingProviderSettings(current.localSessionId)));
5059
5518
  const retryTurnId = await this.startTurn(
5060
5519
  loaded,
5061
- responseContinuation ? "" : llmRetryRuntimePrompt(attempt.promptText, retryNumber),
5520
+ "",
5062
5521
  replyTarget,
5063
- responseContinuation ? undefined : attempt.localImagePaths,
5522
+ undefined,
5064
5523
  {
5065
5524
  attemptId: attempt.attemptId,
5525
+ executionGeneration: attempt.executionGeneration,
5526
+ trigger: "response_continuation", parentSourceTurnId: event.turnId,
5066
5527
  messageId: attempt.messageId,
5067
- displayPrompt: responseContinuation ? `恢复模型续接:${attempt.promptText}` : llmRetryCardPrompt(attempt.promptText, retryNumber),
5528
+ displayPrompt: `恢复模型续接:${attempt.promptText}`,
5068
5529
  preserveAttemptOnFailure: true,
5069
- ...(responseContinuation ? { responseContinuationTurnId: event.turnId } : {}),
5530
+ responseContinuationTurnId: event.turnId,
5070
5531
  },
5071
5532
  );
5072
5533
  this.store.rebindPendingTurnMessages(session.localSessionId, event.turnId, retryTurnId);
5073
5534
  } catch (error) {
5074
- const aborted = responseContinuation && !this.responseContinuations.has(session.localSessionId);
5535
+ const aborted = !this.responseContinuations.has(session.localSessionId);
5536
+ if (this.store.getTurnAttempt(attempt.attemptId)?.status === "unknown") return;
5075
5537
  this.store.updateTurnAttempt(attempt.attemptId, { status: aborted ? "cancelled" : "failed" });
5076
5538
  const latest = this.store.getSession(session.localSessionId);
5077
- if (!responseContinuation || (latest?.lastTurnId === event.turnId && latest.status !== "closed")) {
5539
+ if (latest?.lastTurnId === event.turnId && latest.status !== "closed") {
5078
5540
  this.store.updateSession(session.localSessionId, { status: aborted ? "ready" : "failed" });
5079
5541
  }
5080
5542
  await this.finalizeTurnMessageReactions(event.turnId, aborted ? "cancelled" : "failed").catch((reactionError: unknown) => {
@@ -5087,7 +5549,7 @@ export class ProxySessionController {
5087
5549
  { error, sessionId: session.localSessionId, retryNumber },
5088
5550
  "Failed to start an automatic LLM turn retry.",
5089
5551
  );
5090
- if (responseContinuation && !aborted) {
5552
+ if (!aborted) {
5091
5553
  await this.outbound.sendText(attempt.contextKey,
5092
5554
  `模型续接恢复未能启动:${displayRuntimeError(runtimeErrorMessage(error))}。请发送消息继续。`);
5093
5555
  }
@@ -5137,8 +5599,14 @@ export class ProxySessionController {
5137
5599
  }
5138
5600
 
5139
5601
  private async startNextQueuedPromptIfIdleNow(sessionId: string): Promise<void> {
5602
+ const executionGeneration = this.store.executionGeneration(sessionId);
5140
5603
  if (this.planHandoffs.has(sessionId) || this.sessionResets.has(sessionId)) return;
5604
+ if (this.store.hasUnknownTurnAttemptForSession(sessionId)) return;
5605
+ if (this.store.hasCancellationRequestedForSession(sessionId)) return;
5141
5606
  if (this.store.countQueuedPrompts(sessionId) === 0) return;
5607
+ const queuedHead = this.store.peekQueuedPrompt(sessionId);
5608
+ if (queuedHead && this.store.schedules.getRun(queuedHead.promptId)
5609
+ && this.lifecycle?.canStartScheduledTasks?.() === false) return;
5142
5610
  const baseRecord = this.store.getSession(sessionId);
5143
5611
  if (!baseRecord || baseRecord.status === "closed") return;
5144
5612
  let prompt: QueuedPromptRecord | undefined;
@@ -5152,20 +5620,60 @@ export class ProxySessionController {
5152
5620
 
5153
5621
  await this.applyPendingProviderSettings(loaded);
5154
5622
  if (this.store.getPendingProviderSettings(sessionId)) return;
5623
+ this.assertExecutionGeneration(sessionId, executionGeneration);
5155
5624
  prompt = this.store.takeNextQueuedPrompt(sessionId);
5156
5625
  if (!prompt) return;
5626
+ const scheduledRun = this.store.schedules.getRun(prompt.promptId);
5157
5627
  const record = this.store.getSessionForContext(sessionId, prompt.contextKey) ?? baseRecord;
5158
5628
  loaded = { ...loaded, record };
5159
5629
  await this.refreshPromptQueueCards(sessionId);
5630
+ if (scheduledRun) {
5631
+ if (!this.store.schedules.canSubmit(scheduledRun.id)
5632
+ || this.lifecycle?.canStartScheduledTasks?.() === false) throw new Error("定时任务已取消、过期或正在安全重启。");
5633
+ const job = this.store.schedules.require(scheduledRun.jobId);
5634
+ this.assertScheduleTarget(job);
5635
+ try {
5636
+ await this.notifySchedule(job, prompt.text);
5637
+ } catch (error) {
5638
+ const currentJob = this.store.schedules.get(job.id);
5639
+ if (currentJob?.status === "enabled") {
5640
+ const paused = this.store.schedules.change(job.id, currentJob.revision, "pause");
5641
+ this.store.schedules.update({ ...paused, notice: "原会话的 Prompt 发送失败,计划已暂停。请修复后恢复。" });
5642
+ }
5643
+ this.store.schedules.finish(scheduledRun.id, "failed", "无法向原会话发送 Prompt,未提交模型。");
5644
+ this.store.updateTurnAttempt(scheduledRun.id, { status: "failed" });
5645
+ throw error;
5646
+ }
5647
+ }
5160
5648
  const turnId = await this.startTurnNow(
5161
5649
  loaded,
5162
5650
  prompt.text,
5163
5651
  prompt.replyMessageId ? { messageId: prompt.replyMessageId, replyInThread: true } : undefined,
5164
5652
  prompt.localImagePaths,
5165
- { messageId: prompt.messageId, displayPrompt: prompt.displayPrompt },
5653
+ { messageId: prompt.messageId, displayPrompt: prompt.displayPrompt, executionGeneration,
5654
+ trigger: scheduledRun ? "schedule" : "queue", instructionId: prompt.promptId,
5655
+ ...(scheduledRun ? { attemptId: prompt.promptId, scheduleRunId: prompt.promptId } : {}) },
5166
5656
  );
5167
5657
  if (prompt.messageId) await this.bindMessageReactionToTurn(prompt.messageId, sessionId, turnId);
5168
5658
  } catch (error) {
5659
+ if (error instanceof TurnStoppedBeforeSubmissionError) {
5660
+ if (prompt) {
5661
+ this.store.enqueuePrompt(prompt);
5662
+ const run = this.store.schedules.getRun(prompt.promptId);
5663
+ if (run) {
5664
+ this.store.schedules.saveRun({ ...run, status: "queued" });
5665
+ this.store.updateTurnAttempt(run.id, { status: "accepted", executionGeneration: this.store.executionGeneration(sessionId) });
5666
+ }
5667
+ await this.refreshPromptQueueCards(sessionId);
5668
+ }
5669
+ return;
5670
+ }
5671
+ if (prompt) {
5672
+ const run = this.store.schedules.getRun(prompt.promptId);
5673
+ if (run && ["dispatching", "submitting"].includes(run.status)) {
5674
+ this.store.schedules.finish(run.id, run.status === "submitting" ? "unknown" : "failed", runtimeErrorMessage(error));
5675
+ }
5676
+ }
5169
5677
  this.logger.warn(
5170
5678
  {
5171
5679
  error,
@@ -5345,14 +5853,18 @@ export class ProxySessionController {
5345
5853
 
5346
5854
  private async cancel(contextKey: string): Promise<void> {
5347
5855
  const record = this.requireCurrentSession(contextKey);
5348
- await this.outbound.sendText(contextKey, STOP_TASK_STARTED_MESSAGE);
5349
5856
  await this.cancelSession(record);
5350
5857
  }
5351
5858
 
5352
5859
  private async cancelSession(record: SessionRecord): Promise<void> {
5860
+ this.store.requestSessionExecutionStop(record.localSessionId);
5861
+ const stopGeneration = this.store.executionGeneration(record.localSessionId);
5353
5862
  this.responseContinuations.get(record.localSessionId)?.abort.abort();
5354
5863
  this.responseContinuations.delete(record.localSessionId);
5355
5864
  this.planHandoffs.delete(record.localSessionId);
5865
+ await this.outbound.sendText(record.contextKey, STOP_TASK_STARTED_MESSAGE).catch((error: unknown) => {
5866
+ this.logger.warn({ error, sessionId: record.localSessionId }, "Failed to deliver the stop acknowledgement; still sending interrupt.");
5867
+ });
5356
5868
  const runtime = this.runtimes.forAgent(record.agentName);
5357
5869
  if (runtime.kind === "codex" && record.remoteSessionId && runtime.interruptRemoteTurn) {
5358
5870
  if (runtime.getGoal && runtime.setGoal) {
@@ -5384,14 +5896,17 @@ export class ProxySessionController {
5384
5896
  }
5385
5897
  }
5386
5898
  if (!turnId) {
5899
+ this.finishUnsubmittedStops(record.localSessionId);
5387
5900
  await this.outbound.sendText(record.contextKey, "当前没有正在执行的任务。");
5388
5901
  return;
5389
5902
  }
5390
- const cancellationAttempt = this.store.requestTurnAttemptCancellation(turnId);
5903
+ const latestAttempt = this.store.findIncompleteTurnAttemptByTurnId(turnId);
5904
+ if (latestAttempt && latestAttempt.executionGeneration >= stopGeneration) return;
5905
+ this.store.requestTurnAttemptCancellation(turnId);
5391
5906
  try {
5392
5907
  await runtime.interruptRemoteTurn(record.remoteSessionId, turnId);
5393
5908
  } catch (error) {
5394
- if (cancellationAttempt) this.store.restoreTurnAttemptAfterCancellationFailure(cancellationAttempt);
5909
+ // Keep the durable stop intent even when the interrupt response is lost.
5395
5910
  throw error;
5396
5911
  }
5397
5912
  this.store.audit(record.contextKey, "turn_interrupt_sent", {
@@ -5406,18 +5921,29 @@ export class ProxySessionController {
5406
5921
  const loaded = await this.loadSession(record);
5407
5922
  const turnId = loaded.session.activeTurnId;
5408
5923
  if (!turnId) {
5924
+ this.finishUnsubmittedStops(record.localSessionId);
5409
5925
  await this.outbound.sendText(record.contextKey, "当前没有正在执行的任务。");
5410
5926
  return;
5411
5927
  }
5412
- const cancellationAttempt = this.store.requestTurnAttemptCancellation(turnId);
5928
+ const latestAttempt = this.store.findIncompleteTurnAttemptByTurnId(turnId);
5929
+ if (latestAttempt && latestAttempt.executionGeneration >= stopGeneration) return;
5930
+ this.store.requestTurnAttemptCancellation(turnId);
5413
5931
  try {
5414
5932
  await loaded.runtime.cancelTurn(record.localSessionId, turnId);
5415
5933
  } catch (error) {
5416
- if (cancellationAttempt) this.store.restoreTurnAttemptAfterCancellationFailure(cancellationAttempt);
5934
+ // Keep the durable stop intent even when the interrupt response is lost.
5417
5935
  throw error;
5418
5936
  }
5419
5937
  }
5420
5938
 
5939
+ private finishUnsubmittedStops(sessionId: string): void {
5940
+ for (const attempt of this.store.listCancellationRequestedTurnAttempts()) {
5941
+ if (attempt.localSessionId === sessionId && attempt.submissionState === "not_submitted") {
5942
+ this.store.updateTurnAttempt(attempt.attemptId, { status: "cancelled" });
5943
+ }
5944
+ }
5945
+ }
5946
+
5421
5947
  private async resetCurrentSessionToTurn(
5422
5948
  contextKey: string,
5423
5949
  sessionId: string,
@@ -5886,7 +6412,7 @@ export class ProxySessionController {
5886
6412
  `模型 ${cardCode(session.model ?? settings.model)}`,
5887
6413
  `思考强度 ${cardCode(session.reasoningEffort ?? settings.effort)}`,
5888
6414
  `权限 ${cardCode(session.permissionMode)}`,
5889
- `并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
6415
+ "只影响当前任务,从下一次请求生效。",
5890
6416
  ].join(",");
5891
6417
  if (options.updateMessageId) {
5892
6418
  await this.openExecutionSettingsNow(contextKey, "provider", {
@@ -5907,7 +6433,7 @@ export class ProxySessionController {
5907
6433
  if (!loaded.runtime.setExecutionSettings) throw new Error("当前运行时不支持 Provider 设置。");
5908
6434
  loaded.session = loaded.runtime.getSession(loaded.record.localSessionId) ?? loaded.session;
5909
6435
  const remoteSessionId = loaded.session.remoteSessionId;
5910
- const persist = (candidate: RuntimeSession, replacement?: RuntimeSettingsReplacement): Promise<void> => this.agentDefaultsOperations.run(loaded.record.agentName, async () => {
6436
+ const persist = async (candidate: RuntimeSession, replacement?: RuntimeSettingsReplacement): Promise<void> => {
5911
6437
  if (candidate.remoteSessionId !== remoteSessionId) {
5912
6438
  const saved = this.store.getSession(loaded.record.localSessionId);
5913
6439
  if (replacement?.emptyRemoteSessionId !== remoteSessionId || !saved || saved.remoteSessionId !== remoteSessionId
@@ -5919,23 +6445,14 @@ export class ProxySessionController {
5919
6445
  }
5920
6446
  }
5921
6447
  assertProviderSettingsApplied(candidate, settings);
5922
- const agent = this.ensureAgent(loaded.record.agentName);
5923
- const previousDefaults = agent.defaults;
5924
- await this.persistAgentExecutionDefaultsNow(loaded.record.localSessionId, candidate);
5925
- try {
5926
- this.store.updateRuntimeSession(loaded.record.localSessionId, {
5927
- remoteSessionId: candidate.remoteSessionId,
5928
- modelProvider: candidate.modelProvider,
5929
- model: candidate.model,
5930
- reasoningEffort: candidate.reasoningEffort,
5931
- permissionMode: candidate.permissionMode,
5932
- });
5933
- } catch (error) {
5934
- await this.lifecycle?.persistAgentExecutionDefaults?.(loaded.record.agentName, previousDefaults ?? {});
5935
- agent.defaults = previousDefaults;
5936
- throw error;
5937
- }
5938
- });
6448
+ this.store.updateRuntimeSession(loaded.record.localSessionId, {
6449
+ remoteSessionId: candidate.remoteSessionId,
6450
+ modelProvider: candidate.modelProvider,
6451
+ model: candidate.model,
6452
+ reasoningEffort: candidate.reasoningEffort,
6453
+ permissionMode: candidate.permissionMode,
6454
+ });
6455
+ };
5939
6456
  const session = await loaded.runtime.setExecutionSettings(loaded.record.localSessionId, settings, persist);
5940
6457
  loaded.record = this.store.getSession(loaded.record.localSessionId) ?? loaded.record;
5941
6458
  this.settingsOnlySessions.delete(loaded.record.localSessionId);
@@ -6158,7 +6675,6 @@ export class ProxySessionController {
6158
6675
  }
6159
6676
  this.store.updateRuntimeSession(loaded.record.localSessionId, { model, reasoningEffort: nextEffort });
6160
6677
  this.outbound.updateSessionModel(loaded.record.localSessionId, model, loaded.session.modelProvider);
6161
- await this.persistAgentExecutionDefaults(loaded.record.localSessionId);
6162
6678
  });
6163
6679
  const effortMessage = nextEffort && nextEffort !== currentEffort
6164
6680
  ? `,思考强度已自动调整为 ${nextEffort}`
@@ -6167,13 +6683,13 @@ export class ProxySessionController {
6167
6683
  await this.openExecutionSettingsNow(contextKey, "model", {
6168
6684
  sessionId: loaded.record.localSessionId,
6169
6685
  updateMessageId: options.updateMessageId,
6170
- notice: `模型已切换为 ${cardCode(model)}${effortMessage},并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
6686
+ notice: `模型已切换为 ${cardCode(model)}${effortMessage},只影响当前任务,从下一次请求生效。`,
6171
6687
  });
6172
6688
  return;
6173
6689
  }
6174
6690
  await this.outbound.sendText(
6175
6691
  contextKey,
6176
- `模型已切换为 ${model}${effortMessage},并已保存为 ${loaded.record.agentName} Agent 的默认设置,从下一次请求生效。`,
6692
+ `模型已切换为 ${model}${effortMessage},只影响当前任务,从下一次请求生效。`,
6177
6693
  );
6178
6694
  }
6179
6695
 
@@ -6614,19 +7130,18 @@ export class ProxySessionController {
6614
7130
  await this.sessionHydrationOperations.run(loaded.record.localSessionId, async () => {
6615
7131
  await loaded.runtime.setReasoningEffort(loaded.record.localSessionId, effort);
6616
7132
  this.store.updateRuntimeSession(loaded.record.localSessionId, { reasoningEffort: effort });
6617
- await this.persistAgentExecutionDefaults(loaded.record.localSessionId);
6618
7133
  });
6619
7134
  if (options.updateMessageId) {
6620
7135
  await this.openExecutionSettingsNow(contextKey, "thinking", {
6621
7136
  sessionId: loaded.record.localSessionId,
6622
7137
  updateMessageId: options.updateMessageId,
6623
- notice: `思考强度已切换为 ${cardCode(effort)},并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
7138
+ notice: `思考强度已切换为 ${cardCode(effort)},只影响当前任务,从下一次请求生效。`,
6624
7139
  });
6625
7140
  return;
6626
7141
  }
6627
7142
  await this.outbound.sendText(
6628
7143
  contextKey,
6629
- `思考强度已切换为 ${effort},并已保存为 ${loaded.record.agentName} Agent 的默认设置,从下一次请求生效。`,
7144
+ `思考强度已切换为 ${effort},只影响当前任务,从下一次请求生效。`,
6630
7145
  );
6631
7146
  }
6632
7147
 
@@ -6658,23 +7173,22 @@ export class ProxySessionController {
6658
7173
  loaded.session = loaded.runtime.getSession(record.localSessionId) ?? loaded.session;
6659
7174
  loaded.session.permissionMode = mode;
6660
7175
  this.store.updateRuntimeSession(record.localSessionId, { permissionMode: mode });
6661
- await this.persistAgentExecutionDefaults(record.localSessionId);
6662
7176
  });
6663
7177
  if (options.updateMessageId) {
6664
7178
  await this.openExecutionSettingsNow(contextKey, "permission", {
6665
7179
  sessionId: loaded.record.localSessionId,
6666
7180
  updateMessageId: options.updateMessageId,
6667
7181
  notice: mode === "auto"
6668
- ? `已切换为自动执行模式,并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`
6669
- : `已切换为执行前确认模式,并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
7182
+ ? "已切换为自动执行模式,只影响当前任务,从下一次请求生效。"
7183
+ : "已切换为执行前确认模式,只影响当前任务,从下一次请求生效。",
6670
7184
  });
6671
7185
  return;
6672
7186
  }
6673
7187
  await this.outbound.sendText(
6674
7188
  contextKey,
6675
7189
  mode === "auto"
6676
- ? `已切换为自动执行模式,并已保存为 ${loaded.record.agentName} Agent 的默认设置。`
6677
- : `已切换为执行前确认模式,并已保存为 ${loaded.record.agentName} Agent 的默认设置。`,
7190
+ ? "已切换为自动执行模式,只影响当前任务,从下一次请求生效。"
7191
+ : "已切换为执行前确认模式,只影响当前任务,从下一次请求生效。",
6678
7192
  );
6679
7193
  }
6680
7194
 
@@ -6810,6 +7324,7 @@ export class ProxySessionController {
6810
7324
  && !this.store.getTurnPromptSummary(turnId)) {
6811
7325
  await this.outbound.sendInteractiveCard(contextKey, this.cardRenderer.renderTurnDetails(
6812
7326
  this.runningTurnSnapshot(current, turnId),
7327
+ undefined, this.store.provenance.forTurn(turnId, current.localSessionId),
6813
7328
  ));
6814
7329
  return;
6815
7330
  }
@@ -7403,7 +7918,7 @@ export class ProxySessionController {
7403
7918
  projectActions,
7404
7919
  cardEntry: {
7405
7920
  reference: entry.reference,
7406
- summary: `${offset + index + 1}. ${marker}${title} · ${entry.agentName}`,
7921
+ summary: `${offset + index + 1}. ${marker}${title} · ${entry.agentName}${entry.status === "待核实" ? " · 待核实" : ""}`,
7407
7922
  detailLines: [
7408
7923
  `**最新 Prompt**:${cardText(lastUserPrompt)}`,
7409
7924
  `<font color='grey'>最近更新:${cardText(entry.updatedLabel)}</font>`,
@@ -8004,11 +8519,11 @@ export class ProxySessionController {
8004
8519
  queued = this.store.countQueuedPrompts(current.localSessionId);
8005
8520
  snapshot = turnViewSnapshot(current.lastTurnId ? this.store.getTurnSnapshot(current.lastTurnId) : undefined);
8006
8521
  const waitingForApproval = snapshot?.turnId === current.lastTurnId && snapshot?.status === "waiting_for_approval";
8007
- const statusLabel = waitingForApproval ? "等待确认"
8522
+ const statusLabel = current.lastTurnStatus === "unknown" ? "待核实" : waitingForApproval ? "等待确认"
8008
8523
  : remoteActive && remote && localCurrent && !isBotOwnedActiveTurn(localCurrent, remote)
8009
8524
  ? "外部执行中"
8010
8525
  : sessionStatusLabel(current.status, activeTurnId);
8011
- const resultLabel = waitingForApproval ? "等待确认" : remoteActive
8526
+ const resultLabel = current.lastTurnStatus === "unknown" ? "待核实" : waitingForApproval ? "等待确认" : remoteActive
8012
8527
  ? "执行中"
8013
8528
  : remoteTurnStatusLabel(remote?.lastTurnStatus ?? current.lastTurnStatus);
8014
8529
  taskLines.push(
@@ -8276,28 +8791,6 @@ export class ProxySessionController {
8276
8791
  return agent;
8277
8792
  }
8278
8793
 
8279
- private async persistAgentExecutionDefaults(localSessionId: string, candidate?: RuntimeSession): Promise<void> {
8280
- const record = this.store.getSession(localSessionId);
8281
- if (!record) throw new Error(`找不到任务:${localSessionId}`);
8282
- return this.agentDefaultsOperations.run(record.agentName, () => this.persistAgentExecutionDefaultsNow(localSessionId, candidate));
8283
- }
8284
-
8285
- private async persistAgentExecutionDefaultsNow(localSessionId: string, candidate?: RuntimeSession): Promise<void> {
8286
- const record = this.store.getSession(localSessionId);
8287
- if (!record) throw new Error(`找不到任务:${localSessionId}`);
8288
- const session = candidate ?? record;
8289
- const agent = this.ensureAgent(session.agentName);
8290
- const observed: AgentExecutionDefaults = {
8291
- ...(session.modelProvider?.trim() ? { modelProvider: session.modelProvider } : {}),
8292
- ...(session.model?.trim() ? { model: session.model } : {}),
8293
- ...(session.reasoningEffort?.trim() ? { reasoningEffort: session.reasoningEffort } : {}),
8294
- ...(session.permissionMode ? { permissionMode: session.permissionMode } : {}),
8295
- };
8296
- const defaults = { ...(agent.defaults ?? {}), ...observed };
8297
- await this.lifecycle?.persistAgentExecutionDefaults?.(session.agentName, defaults);
8298
- agent.defaults = defaults;
8299
- }
8300
-
8301
8794
  private agentLabel(agentName: string): string {
8302
8795
  return this.ensureAgent(agentName).title;
8303
8796
  }
@@ -9097,7 +9590,9 @@ function mergeTaskList(
9097
9590
  const local = localByRemoteId.get(agentRemoteKey(agentName, remote.id));
9098
9591
  if (local) representedLocalIds.add(local.localSessionId);
9099
9592
  const active = remote.status === "active" || remote.lastTurnStatus === "inProgress";
9100
- const status = remote.status === "active" || remote.lastTurnStatus === "inProgress"
9593
+ const status = local?.lastTurnStatus === "unknown"
9594
+ && (!remote.lastTurnStatus || remote.lastTurnId !== local.lastTurnId) ? "待核实"
9595
+ : remote.status === "active" || remote.lastTurnStatus === "inProgress"
9101
9596
  ? local && isBotOwnedActiveTurn(local, remote) ? "执行中" : "外部执行中"
9102
9597
  : remoteSessionStatusLabel(remote.status);
9103
9598
  const recencyAt = remote.recencyAt ?? remote.updatedAt;
@@ -9129,7 +9624,7 @@ function mergeTaskList(
9129
9624
  agentName: local.agentName,
9130
9625
  title: local.title ?? "未命名任务",
9131
9626
  cwd: local.cwd,
9132
- status: sessionStatusLabel(local.status),
9627
+ status: local.lastTurnStatus === "unknown" ? "待核实" : sessionStatusLabel(local.status),
9133
9628
  active: local.status === "running",
9134
9629
  current: local.localSessionId === currentLocalSessionId,
9135
9630
  lastUserPrompt: latestLocalUserPrompts.get(local.localSessionId),
@@ -9334,6 +9829,7 @@ function remoteTurnStatusLabel(status?: string): string {
9334
9829
  failed: "失败",
9335
9830
  running: "执行中",
9336
9831
  cancelled: "已停止",
9832
+ unknown: "待核实",
9337
9833
  };
9338
9834
  return status ? labels[status] ?? status : "尚无执行记录";
9339
9835
  }
@@ -9350,6 +9846,7 @@ function turnViewStatusLabel(status: TurnViewState["status"]): string {
9350
9846
  running: "执行中",
9351
9847
  tool_running: "工具执行中",
9352
9848
  waiting_for_approval: "等待确认",
9849
+ unknown: "待核实",
9353
9850
  completed: "已完成",
9354
9851
  cancelled: "已停止",
9355
9852
  failed: "失败",
@@ -9453,6 +9950,8 @@ function mapRemoteTurnStatus(status?: RemoteSessionSummary["lastTurnStatus"]): s
9453
9950
 
9454
9951
  function mergeRemoteTaskStatus(record: SessionRecord, remote?: RemoteSessionSummary): SessionRecord {
9455
9952
  if (!remote) return record;
9953
+ if (record.lastTurnStatus === "unknown"
9954
+ && (!remote.lastTurnStatus || remote.lastTurnId !== record.lastTurnId)) return record;
9456
9955
  const remoteTurnStatus = mapRemoteTurnStatus(remote.lastTurnStatus);
9457
9956
  const createdAt = remote.createdAt === undefined
9458
9957
  ? record.createdAt
@@ -9882,30 +10381,13 @@ function recoveryCardPrompt(prompt: string): string {
9882
10381
  return `恢复重启前的任务:${prompt}`;
9883
10382
  }
9884
10383
 
9885
- function recoveryRuntimePrompt(prompt: string): string {
9886
- return [
9887
- "Agent Bot restarted while the previous turn was still running.",
9888
- "Continue the unfinished task in the current task and workspace.",
9889
- "Inspect the existing conversation, files, and completed tool effects first. Do not repeat completed or irreversible actions.",
9890
- "Finish the original request:",
9891
- "",
9892
- prompt,
9893
- ].join("\n");
9894
- }
10384
+
9895
10385
 
9896
10386
  function llmRetryCardPrompt(prompt: string, retryNumber: number): string {
9897
10387
  return `自动重试 ${retryNumber}/${MAX_LLM_TURN_RETRIES}:${prompt}`;
9898
10388
  }
9899
10389
 
9900
- function llmRetryRuntimePrompt(prompt: string, retryNumber: number): string {
9901
- return [
9902
- `Agent Bot is automatically retrying this request after a transient LLM service failure (${retryNumber}/${MAX_LLM_TURN_RETRIES}).`,
9903
- "Continue in the current task and workspace. Inspect the conversation, files, and completed tool effects before acting.",
9904
- "Do not repeat completed or irreversible actions. Finish the original request:",
9905
- "",
9906
- prompt,
9907
- ].join("\n");
9908
- }
10390
+
9909
10391
 
9910
10392
  function isRetryableLlmTurnFailure(message: string): boolean {
9911
10393
  const normalized = message.trim().toLowerCase();
@@ -9935,13 +10417,7 @@ function isRetryableLlmTurnFailure(message: string): boolean {
9935
10417
  }
9936
10418
 
9937
10419
  function remoteTurnMatchesAttempt(remote: RemoteSessionSummary | undefined, attempt: TurnAttemptRecord): boolean {
9938
- if (!remote?.lastTurnId) return false;
9939
- if (attempt.turnId) return remote.lastTurnId === attempt.turnId;
9940
- const remoteUpdatedAt = remote.updatedAt === undefined ? undefined : normalizeRemoteTimestamp(remote.updatedAt);
9941
- const acceptedAt = Date.parse(attempt.createdAt);
9942
- return remoteUpdatedAt !== undefined
9943
- && Number.isFinite(acceptedAt)
9944
- && remoteUpdatedAt >= acceptedAt - 1_000;
10420
+ return Boolean(attempt.turnId && remote?.lastTurnId === attempt.turnId);
9945
10421
  }
9946
10422
 
9947
10423
  function isRecoveryAttemptRecent(attempt: TurnAttemptRecord, cutoff: number): boolean {