@keyou007/agent-bot 0.1.25-alpha.1 → 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 (81) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +34 -6
  3. package/README.zh.md +34 -6
  4. package/config.example.yaml +1 -3
  5. package/dist/cli/help.js +2 -0
  6. package/dist/cli/help.js.map +1 -1
  7. package/dist/codex/CodexRuntime.js +15 -5
  8. package/dist/codex/CodexRuntime.js.map +1 -1
  9. package/dist/commands/CommandRouter.js +3 -0
  10. package/dist/commands/CommandRouter.js.map +1 -1
  11. package/dist/config/SettingsStore.js +341 -0
  12. package/dist/config/SettingsStore.js.map +1 -0
  13. package/dist/config/loadConfig.js +1 -2
  14. package/dist/config/loadConfig.js.map +1 -1
  15. package/dist/config/schema.js +0 -1
  16. package/dist/config/schema.js.map +1 -1
  17. package/dist/console/ConsoleTurnPresenter.js +3 -0
  18. package/dist/console/ConsoleTurnPresenter.js.map +1 -1
  19. package/dist/feishu/CardRenderer.js +34 -99
  20. package/dist/feishu/CardRenderer.js.map +1 -1
  21. package/dist/feishu/FeishuConnector.js +9 -0
  22. package/dist/feishu/FeishuConnector.js.map +1 -1
  23. package/dist/feishu/FeishuMessageClient.js +23 -18
  24. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  25. package/dist/feishu/FeishuTurnPresenter.js +36 -23
  26. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  27. package/dist/feishu/LocalCardImage.js +0 -4
  28. package/dist/feishu/LocalCardImage.js.map +1 -1
  29. package/dist/feishu/LocalImageMarkdown.js +59 -3
  30. package/dist/feishu/LocalImageMarkdown.js.map +1 -1
  31. package/dist/feishu/SettingsCard.js +199 -0
  32. package/dist/feishu/SettingsCard.js.map +1 -0
  33. package/dist/index.js +3 -6
  34. package/dist/index.js.map +1 -1
  35. package/dist/local-files/TurnPreviewPage.js +8 -4
  36. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  37. package/dist/presentation/TurnStateReducer.js +21 -2
  38. package/dist/presentation/TurnStateReducer.js.map +1 -1
  39. package/dist/presentation/turnStatus.js +34 -0
  40. package/dist/presentation/turnStatus.js.map +1 -0
  41. package/dist/proxy/ProxySessionController.js +409 -163
  42. package/dist/proxy/ProxySessionController.js.map +1 -1
  43. package/dist/runtime/submissionErrors.js +15 -0
  44. package/dist/runtime/submissionErrors.js.map +1 -0
  45. package/dist/state/ExecutionProvenanceStore.js +58 -0
  46. package/dist/state/ExecutionProvenanceStore.js.map +1 -0
  47. package/dist/state/StateStore.js +96 -33
  48. package/dist/state/StateStore.js.map +1 -1
  49. package/dist/state/migrations.js +12 -0
  50. package/dist/state/migrations.js.map +1 -1
  51. package/docs/technical-reference.md +11 -8
  52. package/docs/technical-reference.zh.md +11 -8
  53. package/npm-shrinkwrap.json +2 -2
  54. package/package.json +1 -1
  55. package/skills/agent-bot/SKILL.md +9 -3
  56. package/src/cli/help.ts +2 -0
  57. package/src/codex/CodexRuntime.ts +14 -5
  58. package/src/commands/CommandRouter.ts +3 -0
  59. package/src/commands/commandTypes.ts +1 -0
  60. package/src/config/SettingsStore.ts +588 -0
  61. package/src/config/loadConfig.ts +1 -2
  62. package/src/config/schema.ts +0 -1
  63. package/src/console/ConsoleTurnPresenter.ts +2 -0
  64. package/src/feishu/CardRenderer.ts +35 -114
  65. package/src/feishu/FeishuConnector.ts +9 -0
  66. package/src/feishu/FeishuMessageClient.ts +23 -22
  67. package/src/feishu/FeishuTurnPresenter.ts +33 -22
  68. package/src/feishu/LocalCardImage.ts +0 -6
  69. package/src/feishu/LocalImageMarkdown.ts +54 -3
  70. package/src/feishu/SettingsCard.ts +231 -0
  71. package/src/index.ts +3 -6
  72. package/src/local-files/TurnPreviewPage.ts +8 -4
  73. package/src/presentation/TurnStateReducer.ts +21 -2
  74. package/src/presentation/turnStatus.ts +38 -0
  75. package/src/presentation/turnViewTypes.ts +3 -0
  76. package/src/proxy/ProxySessionController.ts +382 -162
  77. package/src/runtime/submissionErrors.ts +15 -0
  78. package/src/runtime/types.ts +1 -0
  79. package/src/state/ExecutionProvenanceStore.ts +100 -0
  80. package/src/state/StateStore.ts +118 -33
  81. package/src/state/migrations.ts +12 -0
@@ -54,6 +54,8 @@ import { RECENT_CONTEXT_LIMIT, RECENT_CONTEXT_IMAGE_LIMIT, RECENT_CONTEXT_TEXT_L
54
54
  import { allowsFeishuUser } from "../feishu/ownerAccess.js";
55
55
  import type { ScheduleCommand, ScheduledJob, ScheduleInput } from "../scheduling/types.js";
56
56
  import { scheduleCommandSchema } from "../scheduling/types.js";
57
+ import type { SettingsCatalog, SettingsSnapshot, SettingsStore } from "../config/SettingsStore.js";
58
+ import { renderSettingsCard } from "../feishu/SettingsCard.js";
57
59
  import { renderSchedule, renderScheduleList, renderScheduleForm } from "../scheduling/ScheduleCards.js";
58
60
  import { classifyFileContent } from "../local-files/LocalFileViewerServer.js";
59
61
  import { errorLogValue } from "../logging/errorLogValue.js";
@@ -63,6 +65,7 @@ import { createTurnViewState, hydrateTurnViewState } from "../presentation/TurnS
63
65
  import { buildTurnGraphRows } from "../presentation/turnGraph.js";
64
66
  import type { AgentRuntimeRegistry } from "../runtime/AgentRuntimeRegistry.js";
65
67
  import { displayRuntimeError, isResponseContinuationError } from "../runtime/responseErrors.js";
68
+ import { TurnNotSubmittedError, TurnStoppedBeforeSubmissionError } from "../runtime/submissionErrors.js";
66
69
  import type {
67
70
  AgentRuntime,
68
71
  ApprovalDecision,
@@ -102,6 +105,7 @@ import {
102
105
  type TurnRuntimeOriginRecord,
103
106
  } from "../state/StateStore.js";
104
107
  import { SessionOperationQueue } from "./SessionOperationQueue.js";
108
+ import type { ExecutionTrigger } from "../state/ExecutionProvenanceStore.js";
105
109
  import { createId } from "../utils/id.js";
106
110
  import { formatStorageSize } from "../utils/formatStorageSize.js";
107
111
  import { truncateMiddle, truncateText } from "../utils/markdown.js";
@@ -120,6 +124,10 @@ interface LoadedSession {
120
124
  }
121
125
 
122
126
  interface StartTurnOptions {
127
+ trigger?: ExecutionTrigger;
128
+ instructionId?: string;
129
+ parentSourceTurnId?: string;
130
+ executionGeneration?: number;
123
131
  scheduleRunId?: string;
124
132
  attemptId?: string;
125
133
  messageId?: string;
@@ -291,6 +299,7 @@ const HELP_COMMAND_SECTIONS: Array<{
291
299
  },
292
300
  { command: "/sessions", usage: "[关键词]", description: "查找本机任务" },
293
301
  { command: "/schedule", description: "创建和管理绑定现有任务的定时计划" },
302
+ { command: "/settings", description: "配置 Agent Bot 和各 Agent 默认值(仅所有者)" },
294
303
  {
295
304
  command: "/archive",
296
305
  usage: "[序号或任务 ID]",
@@ -520,6 +529,7 @@ export interface ControlTaskReleaseResult {
520
529
  }
521
530
 
522
531
  export interface ProxyLifecycle {
532
+ settings?: SettingsStore;
523
533
  canStartScheduledTasks?(): boolean;
524
534
  terminalUrl?(jobId: string): string | undefined;
525
535
  authorizeTerminal?(action: CardAction): Promise<string>;
@@ -532,10 +542,6 @@ export interface ProxyLifecycle {
532
542
  showUpdates?(contextKey: string, userId?: string): Promise<void>;
533
543
  selectUpdate?(action: CardAction, replyTarget?: MessageReplyTarget): Promise<void>;
534
544
  rememberFeishuUserOpenId?(userOpenId: string): Promise<void> | void;
535
- persistAgentExecutionDefaults?(
536
- agentName: string,
537
- defaults: AgentExecutionDefaults,
538
- ): Promise<void> | void;
539
545
  }
540
546
 
541
547
  export type ShellCommandExecutor = (
@@ -562,9 +568,9 @@ export class ProxySessionController {
562
568
  private readonly queuedPromptCards = new Map<string, Map<string, string>>();
563
569
  private readonly queuedPromptCardWrites = new Map<string, Promise<void>>();
564
570
  private readonly settingsOperations = new SessionOperationQueue();
571
+ private readonly globalSettingsOperations = new SessionOperationQueue();
565
572
  // Loads may run inside settingsOperations; never acquire that queue while hydrating.
566
573
  private readonly sessionHydrationOperations = new SessionOperationQueue();
567
- private readonly agentDefaultsOperations = new SessionOperationQueue();
568
574
  private readonly sessionResets = new Map<string, Promise<void>>();
569
575
  private readonly resetHistoryOperations = new Map<string, string>();
570
576
  private readonly remoteTurnHistoryRefreshes = new Map<string, number>();
@@ -998,8 +1004,15 @@ export class ProxySessionController {
998
1004
  if (command.type === "prompt" && message.chatType === "group" && message.mentionedBot
999
1005
  && this.store.chatRequiresMention(baseChatContextKey(message.contextKey))) {
1000
1006
  const current = this.currentSession(message.contextKey);
1001
- if (current) this.store.rememberRecentContextMessages(current.localSessionId, current.remoteSessionId ?? "", message.contextKey, message.messageId,
1002
- [...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
+ }
1003
1016
  }
1004
1017
  if (injectedRootMessageId) {
1005
1018
  const current = this.currentSession(message.contextKey);
@@ -1061,7 +1074,9 @@ export class ProxySessionController {
1061
1074
  await this.outbound.withReplyTarget(contextKey, replyTarget, async () => {
1062
1075
  try {
1063
1076
  const kind = String(scopedAction.value.action ?? "");
1064
- if (kind.startsWith("schedule_")) {
1077
+ if (kind.startsWith("bot_settings_")) {
1078
+ await this.handleSettingsAction(scopedAction, replyTarget);
1079
+ } else if (kind.startsWith("schedule_")) {
1065
1080
  await this.handleScheduleAction(scopedAction, replyTarget);
1066
1081
  } else if (kind === "terminal_authorize") {
1067
1082
  if (!this.lifecycle?.authorizeTerminal) throw new Error("网页终端未启用。");
@@ -1261,7 +1276,6 @@ export class ProxySessionController {
1261
1276
  );
1262
1277
  } else if (kind === "session_stop") {
1263
1278
  const sessionId = String(scopedAction.value.sessionId ?? "");
1264
- await this.outbound.sendText(contextKey, STOP_TASK_STARTED_MESSAGE);
1265
1279
  await this.stopSessionReference(contextKey, sessionId);
1266
1280
  if (scopedAction.value.cardView === "status") await this.refreshStatusCardFromAction(scopedAction, sessionId);
1267
1281
  else if (scopedAction.value.cardView !== "safe_restart") {
@@ -1829,6 +1843,72 @@ export class ProxySessionController {
1829
1843
  return this.store.schedules.change(job.id, job.revision, command.operation as "pause" | "resume" | "delete");
1830
1844
  }
1831
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
+
1832
1912
  private createSchedule(input: ScheduleInput, localSessionId: string, contextKey: string, replyMessageId?: string): ScheduledJob {
1833
1913
  if (!this.config.feishu.userOpenId) throw new Error("请先配置 Agent Bot 所有者,才能创建定时任务。");
1834
1914
  this.requireSession(contextKey, localSessionId);
@@ -2214,6 +2294,16 @@ export class ProxySessionController {
2214
2294
  throw new Error(unboundThreadTaskMessage());
2215
2295
  }
2216
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
+ }
2217
2307
  case "schedule": {
2218
2308
  if (!this.config.feishu.userOpenId || userId !== this.config.feishu.userOpenId) throw new Error("只有 Agent Bot 所有者可以管理定时任务。");
2219
2309
  if (command.command.operation === "list") {
@@ -2493,6 +2583,10 @@ export class ProxySessionController {
2493
2583
  for (const attempt of this.store.listCancellationRequestedTurnAttempts()) {
2494
2584
  const session = this.store.getSession(attempt.localSessionId);
2495
2585
  if (!attempt.turnId) {
2586
+ if (attempt.submissionState !== "not_submitted") {
2587
+ await this.markAttemptUnknown(attempt, "停止意图已保存,但提交结果未知;未自动重发。请核实远端执行状态。");
2588
+ continue;
2589
+ }
2496
2590
  this.store.updateTurnAttempt(attempt.attemptId, { status: "cancelled" });
2497
2591
  if (session?.status === "starting" || session?.status === "running") {
2498
2592
  this.store.updateSession(session.localSessionId, { status: "ready" });
@@ -2511,12 +2605,20 @@ export class ProxySessionController {
2511
2605
  );
2512
2606
  }
2513
2607
  try {
2514
- await this.handleRuntimeEvent({
2515
- type: "turn_cancelled",
2516
- sessionId: attempt.localSessionId,
2517
- turnId: attempt.turnId,
2518
- });
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.");
2519
2620
  } catch (error) {
2621
+ await this.markAttemptUnknown(attempt, "停止意图已保存,但尚不能确认原轮次已结束。未自动续跑,请核实执行记录。");
2520
2622
  this.logger.warn(
2521
2623
  { error, attemptId: attempt.attemptId, turnId: attempt.turnId },
2522
2624
  "Failed to finish a persisted user-requested turn cancellation.",
@@ -2529,6 +2631,8 @@ export class ProxySessionController {
2529
2631
  for (const session of this.store.listAllSessions()) {
2530
2632
  if (session.status !== "starting" && session.status !== "running" && session.status !== "ready") continue;
2531
2633
  if (this.store.findIncompleteTurnAttemptForSession(session.localSessionId)) continue;
2634
+ if (this.store.hasUnknownTurnAttemptForSession(session.localSessionId)) continue;
2635
+ if (this.store.hasCancellationRequestedForSession(session.localSessionId)) continue;
2532
2636
  const lastTurn = session.lastTurnId
2533
2637
  ? {
2534
2638
  turnId: session.lastTurnId,
@@ -2550,6 +2654,7 @@ export class ProxySessionController {
2550
2654
  : lastTurn;
2551
2655
  if (!latest && session.status === "ready") continue;
2552
2656
  const snapshot = turnViewSnapshot(latest?.snapshot);
2657
+ if (snapshot?.status === "unknown") continue;
2553
2658
  if (snapshot && isTerminalTurnViewStatus(snapshot.status)) {
2554
2659
  this.store.updateSession(session.localSessionId, {
2555
2660
  status: snapshot.status === "failed" ? "failed" : "ready",
@@ -2572,6 +2677,7 @@ export class ProxySessionController {
2572
2677
  pendingTurnId,
2573
2678
  turnId,
2574
2679
  status: turnId ? "running" : "accepted",
2680
+ submissionState: turnId ? "submitted" : "submission_unknown",
2575
2681
  createdAt: latest?.updatedAt ?? session.updatedAt,
2576
2682
  updatedAt: latest?.updatedAt ?? session.updatedAt,
2577
2683
  });
@@ -2582,6 +2688,10 @@ export class ProxySessionController {
2582
2688
  attempt: TurnAttemptRecord,
2583
2689
  message = "执行中断已超过 10 分钟,未自动恢复。",
2584
2690
  ): Promise<void> {
2691
+ if (attempt.submissionState !== "not_submitted") {
2692
+ await this.markAttemptUnknown(attempt, `${message} 原执行结果待核实,未自动重发。`);
2693
+ return;
2694
+ }
2585
2695
  clearTimeout(this.recoveryRetryTimers.get(attempt.attemptId));
2586
2696
  this.recoveryRetryTimers.delete(attempt.attemptId);
2587
2697
  this.recoveryRetryStartedAt.delete(attempt.attemptId);
@@ -2678,6 +2788,11 @@ export class ProxySessionController {
2678
2788
 
2679
2789
  private async recoverTurnAttempt(attempt: TurnAttemptRecord, announce = true): Promise<void> {
2680
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
+ }
2681
2796
  const session = this.store.getSession(attempt.localSessionId);
2682
2797
  if (!session || session.status === "closed") {
2683
2798
  this.store.updateTurnAttempt(attempt.attemptId, { status: "interrupted" });
@@ -2739,7 +2854,7 @@ export class ProxySessionController {
2739
2854
  await this.reconcileRecoveredRemoteTurn(attempt, session, remote.lastTurnId);
2740
2855
  return;
2741
2856
  }
2742
- if (remote && remoteTurnBelongsToAttempt && remote.lastTurnStatus === "failed") {
2857
+ if (remote && remoteTurnBelongsToAttempt && (remote.lastTurnStatus === "failed" || remote.lastTurnStatus === "interrupted")) {
2743
2858
  await this.reconcileRecoveredRemoteTurn(attempt, session, remote.lastTurnId);
2744
2859
  return;
2745
2860
  }
@@ -2765,16 +2880,35 @@ export class ProxySessionController {
2765
2880
  }
2766
2881
 
2767
2882
  private async markScheduledAttemptUnknown(attempt: TurnAttemptRecord, detail: string): Promise<void> {
2768
- this.store.updateTurnAttempt(attempt.attemptId, { status: "interrupted" });
2883
+ await this.markAttemptUnknown(attempt, detail);
2769
2884
  this.store.schedules.finish(attempt.attemptId, "unknown", detail);
2770
2885
  const run = this.store.schedules.getRun(attempt.attemptId)!;
2771
2886
  const job = this.store.schedules.get(run.jobId);
2772
- if (attempt.pendingTurnId) {
2773
- await this.outbound.interruptTurnForRecovery(attempt.localSessionId, attempt.contextKey, attempt.pendingTurnId, detail);
2774
- }
2775
2887
  if (job) await this.notifySchedule(job, `定时任务「${job.spec.name}」:${detail}`);
2776
2888
  }
2777
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
+
2778
2912
  private async reconcileRecoveredRemoteTurn(
2779
2913
  attempt: TurnAttemptRecord,
2780
2914
  session: SessionRecord,
@@ -2908,6 +3042,10 @@ export class ProxySessionController {
2908
3042
  sourceTurnId: string | undefined,
2909
3043
  replyTarget?: MessageReplyTarget,
2910
3044
  ): Promise<void> {
3045
+ if (attempt.submissionState !== "not_submitted" || sourceTurnId) {
3046
+ await this.markAttemptUnknown(attempt, "原执行结果待核实,未自动重发。请检查执行记录后发送消息继续。");
3047
+ return;
3048
+ }
2911
3049
  const oldCardTurnId = attempt.pendingTurnId ?? sourceTurnId;
2912
3050
  if (oldCardTurnId) {
2913
3051
  await this.outbound.interruptTurnForRecovery(
@@ -2922,7 +3060,7 @@ export class ProxySessionController {
2922
3060
  );
2923
3061
  });
2924
3062
  }
2925
- this.store.prepareTurnAttemptRecovery(attempt.attemptId, oldCardTurnId);
3063
+ if (!this.store.prepareTurnAttemptRecovery(attempt.attemptId, oldCardTurnId)) return;
2926
3064
  this.store.updateSession(session.localSessionId, { status: "ready" });
2927
3065
  if (sourceTurnId) {
2928
3066
  this.store.updateRuntimeSession(session.localSessionId, {
@@ -2933,7 +3071,7 @@ export class ProxySessionController {
2933
3071
  const current = this.store.getSession(session.localSessionId) ?? session;
2934
3072
  const loaded = await this.loadSession({ ...current, contextKey: attempt.contextKey },
2935
3073
  Boolean(this.store.getPendingProviderSettings(current.localSessionId)));
2936
- const recoveryText = recoveryRuntimePrompt(attempt.promptText);
3074
+ const recoveryText = attempt.promptText;
2937
3075
  const turnId = await this.startTurn(
2938
3076
  loaded,
2939
3077
  recoveryText,
@@ -2941,6 +3079,8 @@ export class ProxySessionController {
2941
3079
  attempt.localImagePaths,
2942
3080
  {
2943
3081
  attemptId: attempt.attemptId,
3082
+ executionGeneration: attempt.executionGeneration,
3083
+ trigger: "recovery",
2944
3084
  messageId: attempt.messageId,
2945
3085
  displayPrompt: recoveryCardPrompt(attempt.promptText),
2946
3086
  preserveAttemptOnFailure: true,
@@ -2999,6 +3139,7 @@ export class ProxySessionController {
2999
3139
  localImagePaths?: string[],
3000
3140
  displayPrompt?: string,
3001
3141
  ): Promise<void> {
3142
+ const executionGeneration = this.store.executionGeneration(record.localSessionId);
3002
3143
  if (this.llmRetryingSessions.has(record.localSessionId) || this.planHandoffs.has(record.localSessionId)) {
3003
3144
  const queued = this.persistQueuedPrompt(record.localSessionId, contextKey, text, {
3004
3145
  localImagePaths,
@@ -3057,6 +3198,8 @@ export class ProxySessionController {
3057
3198
  this.logger.warn({ error, sessionId: record.localSessionId }, "Failed to synchronize session before prompt.");
3058
3199
  }
3059
3200
  }
3201
+ this.assertExecutionGeneration(record.localSessionId, executionGeneration);
3202
+ this.store.acknowledgeUnknownTurnAttempts(record.localSessionId);
3060
3203
  const activeTurnId = loaded.session.activeTurnId;
3061
3204
  if (activeTurnId) {
3062
3205
  const activeContextKey = this.store.getTurnContextKey(activeTurnId);
@@ -3075,6 +3218,9 @@ export class ProxySessionController {
3075
3218
  if (messageId) await this.bindMessageReactionToTurn(messageId, record.localSessionId, activeTurnId);
3076
3219
  return;
3077
3220
  } catch (error) {
3221
+ if (!(error instanceof TurnNotSubmittedError)) {
3222
+ throw new Error("追加消息的提交结果待核实,未自动重发或入队。请检查执行记录后继续。", { cause: error });
3223
+ }
3078
3224
  this.logger.debug({ error, sessionId: record.localSessionId, activeTurnId }, "Steering failed; reconciling the App Server thread.");
3079
3225
  let current = loaded.runtime.getSession(record.localSessionId);
3080
3226
  try {
@@ -3083,12 +3229,13 @@ export class ProxySessionController {
3083
3229
  this.logger.warn({ error: syncError, sessionId: record.localSessionId }, "Failed to synchronize after steering failure.");
3084
3230
  }
3085
3231
  if (!current?.activeTurnId) {
3086
- const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt });
3232
+ const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt, executionGeneration });
3087
3233
  if (messageId) await this.bindMessageReactionToTurn(messageId, record.localSessionId, turnId);
3088
3234
  return;
3089
3235
  }
3090
3236
  if (current.activeTurnId !== activeTurnId) {
3091
3237
  try {
3238
+ this.assertExecutionGeneration(record.localSessionId, executionGeneration);
3092
3239
  await loaded.runtime.steerTurn(
3093
3240
  record.localSessionId,
3094
3241
  current.activeTurnId,
@@ -3104,6 +3251,9 @@ export class ProxySessionController {
3104
3251
  if (messageId) await this.bindMessageReactionToTurn(messageId, record.localSessionId, current.activeTurnId);
3105
3252
  return;
3106
3253
  } catch (retryError) {
3254
+ if (!(retryError instanceof TurnNotSubmittedError)) {
3255
+ throw new Error("追加消息的提交结果待核实,未自动重发或入队。", { cause: retryError });
3256
+ }
3107
3257
  this.logger.warn(
3108
3258
  { error: retryError, sessionId: record.localSessionId, activeTurnId: current.activeTurnId },
3109
3259
  "Failed to steer the reconciled App Server turn; queueing prompt.",
@@ -3119,7 +3269,7 @@ export class ProxySessionController {
3119
3269
  return;
3120
3270
  }
3121
3271
  }
3122
- const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt });
3272
+ const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt, executionGeneration });
3123
3273
  if (messageId) await this.bindMessageReactionToTurn(messageId, record.localSessionId, turnId);
3124
3274
  }
3125
3275
 
@@ -3305,12 +3455,13 @@ export class ProxySessionController {
3305
3455
  return { text, localImagePaths, messageIds: [] };
3306
3456
  }
3307
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>();
3308
3464
  try {
3309
- const current = this.currentSession(message.contextKey);
3310
- const stopIds = current ? new Set([
3311
- ...this.store.recentContextMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey, false),
3312
- ...this.store.recentSubmittedMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey),
3313
- ]) : new Set<string>();
3314
3465
  const messages = await this.outbound.readRecentMessages(message.contextKey, {
3315
3466
  chatId: message.chatId,
3316
3467
  ...(message.threadId ? { threadId: message.threadId } : {}),
@@ -3318,7 +3469,6 @@ export class ProxySessionController {
3318
3469
  beforeTimestamp: message.createdAt,
3319
3470
  ...(stopIds.size ? { stopBeforeMessageIds: [...stopIds] } : {}),
3320
3471
  });
3321
- const seen = current ? this.store.recentContextMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey) : new Set<string>();
3322
3472
  seen.add(message.messageId);
3323
3473
  if (message.parentMessageId) seen.add(message.parentMessageId);
3324
3474
  if (message.threadContext && message.rootMessageId) seen.add(message.rootMessageId);
@@ -4178,6 +4328,9 @@ export class ProxySessionController {
4178
4328
  loaded: LoadedSession, text: string, replyTarget?: MessageReplyTarget,
4179
4329
  localImagePaths?: string[], options: StartTurnOptions = {},
4180
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) };
4181
4334
  return this.settingsOperations.run(loaded.record.localSessionId, async () => {
4182
4335
  if (options.responseContinuationTurnId) {
4183
4336
  const current = this.store.getSession(loaded.record.localSessionId);
@@ -4210,6 +4363,10 @@ export class ProxySessionController {
4210
4363
  localImagePaths?: string[],
4211
4364
  options: StartTurnOptions = {},
4212
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);
4213
4370
  const currentRecord = this.store.getSession(loaded.record.localSessionId);
4214
4371
  const title = currentRecord?.title ?? normalizeTaskTitle(options.displayPrompt ?? text);
4215
4372
  if (!currentRecord?.title && title) this.store.updateRuntimeSession(loaded.record.localSessionId, { title });
@@ -4217,6 +4374,7 @@ export class ProxySessionController {
4217
4374
  const attemptId = options.attemptId ?? createId("attempt");
4218
4375
  if (options.attemptId) {
4219
4376
  this.store.updateTurnAttempt(attemptId, {
4377
+ executionGeneration,
4220
4378
  messageId: options.messageId ?? undefined,
4221
4379
  replyMessageId: replyTarget?.messageId ?? undefined,
4222
4380
  status: "recovering",
@@ -4230,12 +4388,25 @@ export class ProxySessionController {
4230
4388
  localImagePaths,
4231
4389
  messageId: options.messageId,
4232
4390
  replyMessageId: replyTarget?.messageId,
4391
+ executionGeneration,
4233
4392
  });
4234
4393
  }
4235
4394
  let turnId: string;
4236
4395
  let runtimeText = text;
4237
4396
  let cardPrompt = options.displayPrompt ?? text;
4238
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
+ };
4239
4410
  try {
4240
4411
  while (true) {
4241
4412
  let pendingTurnId: string | undefined;
@@ -4268,6 +4439,7 @@ export class ProxySessionController {
4268
4439
  this.store.updateTurnAttempt(attemptId, { pendingTurnId: pendingTurnId ?? null });
4269
4440
 
4270
4441
  try {
4442
+ this.assertExecutionGeneration(loaded.record.localSessionId, executionGeneration);
4271
4443
  if (options.approvedPlanTurnId && (this.planHandoffs.get(loaded.record.localSessionId) !== options.approvedPlanTurnId
4272
4444
  || this.sessionResets.has(loaded.record.localSessionId))) {
4273
4445
  throw new Error("方案执行已取消。");
@@ -4278,6 +4450,7 @@ export class ProxySessionController {
4278
4450
  || this.sessionResets.has(loaded.record.localSessionId) || !loaded.runtime.recoverResponseContinuation) {
4279
4451
  throw new Error("模型续接恢复已取消。");
4280
4452
  }
4453
+ this.store.beginTurnAttemptSubmission(attemptId, recordSubmission);
4281
4454
  turnId = await loaded.runtime.recoverResponseContinuation(loaded.record.localSessionId, options.responseContinuationTurnId, recovery.abort.signal);
4282
4455
  } else {
4283
4456
  if (options.scheduleRunId) {
@@ -4287,6 +4460,7 @@ export class ProxySessionController {
4287
4460
  this.assertScheduleTarget(this.store.schedules.require(run!.jobId));
4288
4461
  this.store.schedules.saveRun({ ...run!, status: "submitting" });
4289
4462
  }
4463
+ this.store.beginTurnAttemptSubmission(attemptId, recordSubmission);
4290
4464
  turnId = await loaded.runtime.startTurn(
4291
4465
  loaded.record.localSessionId,
4292
4466
  options.approvedPlanTurnId
@@ -4297,13 +4471,33 @@ export class ProxySessionController {
4297
4471
  break;
4298
4472
  } catch (error) {
4299
4473
  const message = error instanceof Error ? error.message : String(error);
4300
- const attempt = this.store.getTurnAttempt(attemptId);
4301
- if (options.scheduleRunId && attempt?.turnId && attempt.turnId !== options.approvedPlanTurnId) {
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) {
4302
4482
  turnId = attempt.turnId;
4303
4483
  if (isIncompleteTurnAttemptStatus(attempt.status)) this.store.updateTurnAttempt(attemptId, { status: "running" });
4304
4484
  break;
4305
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
+ }
4306
4499
  const retryAttempt = attempt
4500
+ && error instanceof TurnNotSubmittedError
4307
4501
  && !options.scheduleRunId
4308
4502
  && !options.responseContinuationTurnId
4309
4503
  && isRetryableLlmTurnFailure(message)
@@ -4342,7 +4536,7 @@ export class ProxySessionController {
4342
4536
  "Failed to finalize the pending thinking card before an LLM start retry.",
4343
4537
  );
4344
4538
  });
4345
- runtimeText = llmRetryRuntimePrompt(retryAttempt.promptText, retryAttempt.retryCount);
4539
+ runtimeText = retryAttempt.promptText;
4346
4540
  cardPrompt = llmRetryCardPrompt(options.displayPrompt ?? retryAttempt.promptText, retryAttempt.retryCount);
4347
4541
  }
4348
4542
  }
@@ -4350,14 +4544,26 @@ export class ProxySessionController {
4350
4544
  if (retriedStart) this.llmRetryingSessions.delete(loaded.record.localSessionId);
4351
4545
  }
4352
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
+ }
4353
4558
  this.store.updateTurnAttempt(attemptId, {
4354
4559
  pendingTurnId: null,
4355
4560
  turnId,
4561
+ submissionState: "submitted",
4356
4562
  ...(attempt && isIncompleteTurnAttemptStatus(attempt.status) ? { status: "running" as const } : {}),
4357
4563
  });
4358
4564
  const latest = this.store.getSession(loaded.record.localSessionId);
4359
4565
  const alreadyTerminal = latest?.lastTurnId === turnId
4360
- && ["completed", "cancelled", "failed"].includes(latest.lastTurnStatus ?? "");
4566
+ && ["completed", "cancelled", "failed", "unknown"].includes(latest.lastTurnStatus ?? "");
4361
4567
  if (!alreadyTerminal) {
4362
4568
  this.store.updateSession(loaded.record.localSessionId, { status: "running" });
4363
4569
  this.store.updateRuntimeSession(loaded.record.localSessionId, { lastTurnId: turnId, lastTurnStatus: "running" });
@@ -4372,6 +4578,10 @@ export class ProxySessionController {
4372
4578
  return turnId;
4373
4579
  }
4374
4580
 
4581
+ private assertExecutionGeneration(sessionId: string, generation: number): void {
4582
+ if (this.store.executionGeneration(sessionId) !== generation) throw new TurnStoppedBeforeSubmissionError();
4583
+ }
4584
+
4375
4585
  private async createSession(
4376
4586
  contextKey: string,
4377
4587
  agentName: string,
@@ -4392,6 +4602,7 @@ export class ProxySessionController {
4392
4602
  ? createProjectlessWorkspace({ prompt: initialTitle }).cwd
4393
4603
  : path.resolve(cwd ?? this.config.defaults.cwd);
4394
4604
  const record = this.store.createSession({ localSessionId, contextKey, agentName, cwd: sessionCwd, status: "starting" });
4605
+ const executionGeneration = this.store.executionGeneration(localSessionId);
4395
4606
  if (initialTitle || resolvedExecutionSettings.modelProvider || resolvedExecutionSettings.model
4396
4607
  || resolvedExecutionSettings.reasoningEffort || resolvedExecutionSettings.permissionMode) {
4397
4608
  this.store.updateRuntimeSession(localSessionId, {
@@ -4430,6 +4641,7 @@ export class ProxySessionController {
4430
4641
  this.persistRuntimeSession(record, session, session.activeTurnId ? "running" : "ready");
4431
4642
  this.outbound.updateSessionModel(localSessionId, session.model, session.modelProvider);
4432
4643
  const saved = this.store.getSession(localSessionId) ?? record;
4644
+ if (prepareTurn) this.assertExecutionGeneration(localSessionId, executionGeneration);
4433
4645
  if (announce) {
4434
4646
  const task = initialTitle ? `${initialTitle}(${session.remoteSessionId})` : session.remoteSessionId;
4435
4647
  await this.outbound.sendText(contextKey, `已创建 ${agent.title} 任务:${task}`);
@@ -5005,6 +5217,21 @@ export class ProxySessionController {
5005
5217
  }
5006
5218
 
5007
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
+ }
5008
5235
  if ("turnId" in event) {
5009
5236
  const recoveryAttempt = this.recoveryRetryStartedAt.size > 0
5010
5237
  ? this.store.findIncompleteTurnAttemptByTurnId(event.turnId) : undefined;
@@ -5023,6 +5250,7 @@ export class ProxySessionController {
5023
5250
  }
5024
5251
  if (event.type === "turn_started") {
5025
5252
  const attempt = this.store.bindTurnAttempt(event.sessionId, event.turnId);
5253
+ if (attempt) this.store.provenance.bindLatestTurn(attempt.attemptId, event.turnId);
5026
5254
  const scheduledRun = attempt ? this.store.schedules.getRun(attempt.attemptId) : undefined;
5027
5255
  if (scheduledRun) this.store.schedules.saveRun({ ...scheduledRun, status: "running", turnId: event.turnId });
5028
5256
  if (attempt?.recoveredFromTurnId && attempt.recoveredFromTurnId !== event.turnId) {
@@ -5055,20 +5283,11 @@ export class ProxySessionController {
5055
5283
  && Boolean(this.runtimes.forAgent(source.agentName).recoverResponseContinuation)
5056
5284
  && isResponseContinuationError(event.message);
5057
5285
  if (failedAttempt && responseContinuation) {
5058
- const retryAttempt = this.store.prepareTurnAttemptRetry(failedAttempt.attemptId, event.turnId);
5286
+ const retryAttempt = this.store.prepareTurnAttemptRetry(failedAttempt.attemptId, event.turnId, true);
5059
5287
  if (retryAttempt) {
5060
5288
  this.retriedFailureTurnIds.add(event.turnId);
5061
5289
  this.responseContinuations.set(event.sessionId, { turnId: event.turnId, abort: new AbortController() });
5062
- await this.retryFailedLlmTurn(event, retryAttempt, true);
5063
- return;
5064
- }
5065
- }
5066
- if (failedAttempt && !this.store.schedules.getRun(failedAttempt.attemptId) && !this.responseContinuations.has(event.sessionId)
5067
- && isRetryableLlmTurnFailure(event.message) && failedAttempt.retryCount < MAX_LLM_TURN_RETRIES) {
5068
- const retryAttempt = this.store.prepareTurnAttemptRetry(failedAttempt.attemptId, event.turnId);
5069
- if (retryAttempt) {
5070
- this.retriedFailureTurnIds.add(event.turnId);
5071
- await this.retryFailedLlmTurn(event, retryAttempt);
5290
+ await this.recoverFailedResponse(event, retryAttempt);
5072
5291
  return;
5073
5292
  }
5074
5293
  }
@@ -5093,10 +5312,23 @@ export class ProxySessionController {
5093
5312
  event.turnId,
5094
5313
  event.type === "turn_completed" ? "completed" : event.type === "turn_cancelled" ? "cancelled" : "failed",
5095
5314
  );
5096
- this.store.updateRuntimeSession(event.sessionId, {
5097
- lastTurnId: event.turnId,
5098
- lastTurnStatus: event.type === "turn_completed" ? "completed" : event.type === "turn_cancelled" ? "cancelled" : "failed",
5099
- });
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
+ }
5100
5332
  }
5101
5333
 
5102
5334
  const enrichedEvent: RuntimeEvent = event.type === "context_compaction"
@@ -5140,7 +5372,7 @@ export class ProxySessionController {
5140
5372
  const activeTurnId = latest
5141
5373
  ? this.runtimes.forAgent(latest.agentName).getSession(event.sessionId)?.activeTurnId
5142
5374
  : undefined;
5143
- if (latest?.lastTurnId === event.turnId && !activeTurnId) {
5375
+ if (latest?.lastTurnId === event.turnId && latest.status !== "closed" && !activeTurnId) {
5144
5376
  this.store.updateSession(event.sessionId, { status: event.type === "turn_failed" ? "failed" : "ready" });
5145
5377
  await this.applyPendingProviderWhenIdle(event.sessionId);
5146
5378
  await this.scheduleNextQueuedPrompt(event.sessionId);
@@ -5162,7 +5394,9 @@ export class ProxySessionController {
5162
5394
  this.store.markTurnAttemptTerminal(turnId, "completed");
5163
5395
  if (scheduledRun) {
5164
5396
  this.store.schedules.saveRun({ ...scheduledRun, status: "running" });
5165
- this.store.updateTurnAttempt(attempt.attemptId, { status: "recovering" });
5397
+ this.store.updateTurnAttempt(attempt.attemptId, {
5398
+ status: "recovering", turnId: null, submissionState: "not_submitted", recoveredFromTurnId: turnId,
5399
+ });
5166
5400
  }
5167
5401
  this.store.updateRuntimeSession(sessionId, { lastTurnId: turnId, lastTurnStatus: "completed" });
5168
5402
  let continued = false;
@@ -5193,6 +5427,8 @@ export class ProxySessionController {
5193
5427
  attempt.replyMessageId ? { messageId: attempt.replyMessageId, replyInThread: true } : undefined,
5194
5428
  undefined,
5195
5429
  { messageId: attempt.messageId, displayPrompt: "方案已确认,继续执行", approvedPlanTurnId: turnId,
5430
+ executionGeneration: attempt.executionGeneration,
5431
+ trigger: "plan_handoff", parentSourceTurnId: turnId,
5196
5432
  ...(scheduledRun ? { attemptId: attempt.attemptId, scheduleRunId: attempt.attemptId } : {}) },
5197
5433
  );
5198
5434
  }
@@ -5206,14 +5442,16 @@ export class ProxySessionController {
5206
5442
  this.store.audit(attempt.contextKey, "approved_plan_continued", { sessionId, turnId, nextTurnId });
5207
5443
  });
5208
5444
  } catch (error) {
5209
- failed = true;
5210
- this.logger.error({ error, sessionId, turnId }, "Failed to continue an approved plan.");
5211
- await this.outbound.sendText(attempt.contextKey,
5212
- "方案已确认,但后续执行启动失败:" + 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
+ }
5213
5451
  } finally {
5214
5452
  if (this.planHandoffs.get(sessionId) === turnId) this.planHandoffs.delete(sessionId);
5215
5453
  if (!continued) {
5216
- if (scheduledRun) {
5454
+ if (scheduledRun && this.store.getTurnAttempt(attempt.attemptId)?.status !== "unknown") {
5217
5455
  this.store.updateTurnAttempt(attempt.attemptId, { status: failed ? "failed" : "cancelled" });
5218
5456
  this.store.schedules.finish(attempt.attemptId, failed ? "failed" : "cancelled");
5219
5457
  }
@@ -5234,10 +5472,9 @@ export class ProxySessionController {
5234
5472
  }
5235
5473
  }
5236
5474
 
5237
- private async retryFailedLlmTurn(
5475
+ private async recoverFailedResponse(
5238
5476
  event: Extract<RuntimeEvent, { type: "turn_failed" }>,
5239
5477
  attempt: TurnAttemptRecord,
5240
- responseContinuation = false,
5241
5478
  ): Promise<void> {
5242
5479
  const retryNumber = attempt.retryCount;
5243
5480
  const session = this.store.getSession(event.sessionId);
@@ -5255,17 +5492,15 @@ export class ProxySessionController {
5255
5492
  attemptId: attempt.attemptId,
5256
5493
  failedTurnId: event.turnId,
5257
5494
  retryNumber,
5258
- maxRetries: responseContinuation ? 1 : MAX_LLM_TURN_RETRIES,
5259
- responseContinuation,
5495
+ maxRetries: 1,
5496
+ responseContinuation: true,
5260
5497
  error: event.message,
5261
5498
  });
5262
5499
 
5263
5500
  try {
5264
5501
  await this.outbound.onEvent({
5265
5502
  ...event,
5266
- message: responseContinuation
5267
- ? `${event.message}\n\n模型续接状态失效,正在恢复连接并继续(1/1)。`
5268
- : `${event.message}\n\n检测到临时模型服务错误,正在自动重试(${retryNumber}/${MAX_LLM_TURN_RETRIES})。`,
5503
+ message: `${event.message}\n\n模型续接状态失效,正在恢复连接并继续(1/1)。`,
5269
5504
  });
5270
5505
  } catch (error) {
5271
5506
  this.logger.warn(
@@ -5282,23 +5517,26 @@ export class ProxySessionController {
5282
5517
  const loaded = await this.loadSession(current, Boolean(this.store.getPendingProviderSettings(current.localSessionId)));
5283
5518
  const retryTurnId = await this.startTurn(
5284
5519
  loaded,
5285
- responseContinuation ? "" : llmRetryRuntimePrompt(attempt.promptText, retryNumber),
5520
+ "",
5286
5521
  replyTarget,
5287
- responseContinuation ? undefined : attempt.localImagePaths,
5522
+ undefined,
5288
5523
  {
5289
5524
  attemptId: attempt.attemptId,
5525
+ executionGeneration: attempt.executionGeneration,
5526
+ trigger: "response_continuation", parentSourceTurnId: event.turnId,
5290
5527
  messageId: attempt.messageId,
5291
- displayPrompt: responseContinuation ? `恢复模型续接:${attempt.promptText}` : llmRetryCardPrompt(attempt.promptText, retryNumber),
5528
+ displayPrompt: `恢复模型续接:${attempt.promptText}`,
5292
5529
  preserveAttemptOnFailure: true,
5293
- ...(responseContinuation ? { responseContinuationTurnId: event.turnId } : {}),
5530
+ responseContinuationTurnId: event.turnId,
5294
5531
  },
5295
5532
  );
5296
5533
  this.store.rebindPendingTurnMessages(session.localSessionId, event.turnId, retryTurnId);
5297
5534
  } catch (error) {
5298
- 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;
5299
5537
  this.store.updateTurnAttempt(attempt.attemptId, { status: aborted ? "cancelled" : "failed" });
5300
5538
  const latest = this.store.getSession(session.localSessionId);
5301
- if (!responseContinuation || (latest?.lastTurnId === event.turnId && latest.status !== "closed")) {
5539
+ if (latest?.lastTurnId === event.turnId && latest.status !== "closed") {
5302
5540
  this.store.updateSession(session.localSessionId, { status: aborted ? "ready" : "failed" });
5303
5541
  }
5304
5542
  await this.finalizeTurnMessageReactions(event.turnId, aborted ? "cancelled" : "failed").catch((reactionError: unknown) => {
@@ -5311,7 +5549,7 @@ export class ProxySessionController {
5311
5549
  { error, sessionId: session.localSessionId, retryNumber },
5312
5550
  "Failed to start an automatic LLM turn retry.",
5313
5551
  );
5314
- if (responseContinuation && !aborted) {
5552
+ if (!aborted) {
5315
5553
  await this.outbound.sendText(attempt.contextKey,
5316
5554
  `模型续接恢复未能启动:${displayRuntimeError(runtimeErrorMessage(error))}。请发送消息继续。`);
5317
5555
  }
@@ -5361,7 +5599,10 @@ export class ProxySessionController {
5361
5599
  }
5362
5600
 
5363
5601
  private async startNextQueuedPromptIfIdleNow(sessionId: string): Promise<void> {
5602
+ const executionGeneration = this.store.executionGeneration(sessionId);
5364
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;
5365
5606
  if (this.store.countQueuedPrompts(sessionId) === 0) return;
5366
5607
  const queuedHead = this.store.peekQueuedPrompt(sessionId);
5367
5608
  if (queuedHead && this.store.schedules.getRun(queuedHead.promptId)
@@ -5379,6 +5620,7 @@ export class ProxySessionController {
5379
5620
 
5380
5621
  await this.applyPendingProviderSettings(loaded);
5381
5622
  if (this.store.getPendingProviderSettings(sessionId)) return;
5623
+ this.assertExecutionGeneration(sessionId, executionGeneration);
5382
5624
  prompt = this.store.takeNextQueuedPrompt(sessionId);
5383
5625
  if (!prompt) return;
5384
5626
  const scheduledRun = this.store.schedules.getRun(prompt.promptId);
@@ -5408,11 +5650,24 @@ export class ProxySessionController {
5408
5650
  prompt.text,
5409
5651
  prompt.replyMessageId ? { messageId: prompt.replyMessageId, replyInThread: true } : undefined,
5410
5652
  prompt.localImagePaths,
5411
- { messageId: prompt.messageId, displayPrompt: prompt.displayPrompt,
5653
+ { messageId: prompt.messageId, displayPrompt: prompt.displayPrompt, executionGeneration,
5654
+ trigger: scheduledRun ? "schedule" : "queue", instructionId: prompt.promptId,
5412
5655
  ...(scheduledRun ? { attemptId: prompt.promptId, scheduleRunId: prompt.promptId } : {}) },
5413
5656
  );
5414
5657
  if (prompt.messageId) await this.bindMessageReactionToTurn(prompt.messageId, sessionId, turnId);
5415
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
+ }
5416
5671
  if (prompt) {
5417
5672
  const run = this.store.schedules.getRun(prompt.promptId);
5418
5673
  if (run && ["dispatching", "submitting"].includes(run.status)) {
@@ -5598,14 +5853,18 @@ export class ProxySessionController {
5598
5853
 
5599
5854
  private async cancel(contextKey: string): Promise<void> {
5600
5855
  const record = this.requireCurrentSession(contextKey);
5601
- await this.outbound.sendText(contextKey, STOP_TASK_STARTED_MESSAGE);
5602
5856
  await this.cancelSession(record);
5603
5857
  }
5604
5858
 
5605
5859
  private async cancelSession(record: SessionRecord): Promise<void> {
5860
+ this.store.requestSessionExecutionStop(record.localSessionId);
5861
+ const stopGeneration = this.store.executionGeneration(record.localSessionId);
5606
5862
  this.responseContinuations.get(record.localSessionId)?.abort.abort();
5607
5863
  this.responseContinuations.delete(record.localSessionId);
5608
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
+ });
5609
5868
  const runtime = this.runtimes.forAgent(record.agentName);
5610
5869
  if (runtime.kind === "codex" && record.remoteSessionId && runtime.interruptRemoteTurn) {
5611
5870
  if (runtime.getGoal && runtime.setGoal) {
@@ -5637,14 +5896,17 @@ export class ProxySessionController {
5637
5896
  }
5638
5897
  }
5639
5898
  if (!turnId) {
5899
+ this.finishUnsubmittedStops(record.localSessionId);
5640
5900
  await this.outbound.sendText(record.contextKey, "当前没有正在执行的任务。");
5641
5901
  return;
5642
5902
  }
5643
- 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);
5644
5906
  try {
5645
5907
  await runtime.interruptRemoteTurn(record.remoteSessionId, turnId);
5646
5908
  } catch (error) {
5647
- if (cancellationAttempt) this.store.restoreTurnAttemptAfterCancellationFailure(cancellationAttempt);
5909
+ // Keep the durable stop intent even when the interrupt response is lost.
5648
5910
  throw error;
5649
5911
  }
5650
5912
  this.store.audit(record.contextKey, "turn_interrupt_sent", {
@@ -5659,18 +5921,29 @@ export class ProxySessionController {
5659
5921
  const loaded = await this.loadSession(record);
5660
5922
  const turnId = loaded.session.activeTurnId;
5661
5923
  if (!turnId) {
5924
+ this.finishUnsubmittedStops(record.localSessionId);
5662
5925
  await this.outbound.sendText(record.contextKey, "当前没有正在执行的任务。");
5663
5926
  return;
5664
5927
  }
5665
- 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);
5666
5931
  try {
5667
5932
  await loaded.runtime.cancelTurn(record.localSessionId, turnId);
5668
5933
  } catch (error) {
5669
- if (cancellationAttempt) this.store.restoreTurnAttemptAfterCancellationFailure(cancellationAttempt);
5934
+ // Keep the durable stop intent even when the interrupt response is lost.
5670
5935
  throw error;
5671
5936
  }
5672
5937
  }
5673
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
+
5674
5947
  private async resetCurrentSessionToTurn(
5675
5948
  contextKey: string,
5676
5949
  sessionId: string,
@@ -6139,7 +6412,7 @@ export class ProxySessionController {
6139
6412
  `模型 ${cardCode(session.model ?? settings.model)}`,
6140
6413
  `思考强度 ${cardCode(session.reasoningEffort ?? settings.effort)}`,
6141
6414
  `权限 ${cardCode(session.permissionMode)}`,
6142
- `并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
6415
+ "只影响当前任务,从下一次请求生效。",
6143
6416
  ].join(",");
6144
6417
  if (options.updateMessageId) {
6145
6418
  await this.openExecutionSettingsNow(contextKey, "provider", {
@@ -6160,7 +6433,7 @@ export class ProxySessionController {
6160
6433
  if (!loaded.runtime.setExecutionSettings) throw new Error("当前运行时不支持 Provider 设置。");
6161
6434
  loaded.session = loaded.runtime.getSession(loaded.record.localSessionId) ?? loaded.session;
6162
6435
  const remoteSessionId = loaded.session.remoteSessionId;
6163
- 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> => {
6164
6437
  if (candidate.remoteSessionId !== remoteSessionId) {
6165
6438
  const saved = this.store.getSession(loaded.record.localSessionId);
6166
6439
  if (replacement?.emptyRemoteSessionId !== remoteSessionId || !saved || saved.remoteSessionId !== remoteSessionId
@@ -6172,23 +6445,14 @@ export class ProxySessionController {
6172
6445
  }
6173
6446
  }
6174
6447
  assertProviderSettingsApplied(candidate, settings);
6175
- const agent = this.ensureAgent(loaded.record.agentName);
6176
- const previousDefaults = agent.defaults;
6177
- await this.persistAgentExecutionDefaultsNow(loaded.record.localSessionId, candidate);
6178
- try {
6179
- this.store.updateRuntimeSession(loaded.record.localSessionId, {
6180
- remoteSessionId: candidate.remoteSessionId,
6181
- modelProvider: candidate.modelProvider,
6182
- model: candidate.model,
6183
- reasoningEffort: candidate.reasoningEffort,
6184
- permissionMode: candidate.permissionMode,
6185
- });
6186
- } catch (error) {
6187
- await this.lifecycle?.persistAgentExecutionDefaults?.(loaded.record.agentName, previousDefaults ?? {});
6188
- agent.defaults = previousDefaults;
6189
- throw error;
6190
- }
6191
- });
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
+ };
6192
6456
  const session = await loaded.runtime.setExecutionSettings(loaded.record.localSessionId, settings, persist);
6193
6457
  loaded.record = this.store.getSession(loaded.record.localSessionId) ?? loaded.record;
6194
6458
  this.settingsOnlySessions.delete(loaded.record.localSessionId);
@@ -6411,7 +6675,6 @@ export class ProxySessionController {
6411
6675
  }
6412
6676
  this.store.updateRuntimeSession(loaded.record.localSessionId, { model, reasoningEffort: nextEffort });
6413
6677
  this.outbound.updateSessionModel(loaded.record.localSessionId, model, loaded.session.modelProvider);
6414
- await this.persistAgentExecutionDefaults(loaded.record.localSessionId);
6415
6678
  });
6416
6679
  const effortMessage = nextEffort && nextEffort !== currentEffort
6417
6680
  ? `,思考强度已自动调整为 ${nextEffort}`
@@ -6420,13 +6683,13 @@ export class ProxySessionController {
6420
6683
  await this.openExecutionSettingsNow(contextKey, "model", {
6421
6684
  sessionId: loaded.record.localSessionId,
6422
6685
  updateMessageId: options.updateMessageId,
6423
- notice: `模型已切换为 ${cardCode(model)}${effortMessage},并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
6686
+ notice: `模型已切换为 ${cardCode(model)}${effortMessage},只影响当前任务,从下一次请求生效。`,
6424
6687
  });
6425
6688
  return;
6426
6689
  }
6427
6690
  await this.outbound.sendText(
6428
6691
  contextKey,
6429
- `模型已切换为 ${model}${effortMessage},并已保存为 ${loaded.record.agentName} Agent 的默认设置,从下一次请求生效。`,
6692
+ `模型已切换为 ${model}${effortMessage},只影响当前任务,从下一次请求生效。`,
6430
6693
  );
6431
6694
  }
6432
6695
 
@@ -6867,19 +7130,18 @@ export class ProxySessionController {
6867
7130
  await this.sessionHydrationOperations.run(loaded.record.localSessionId, async () => {
6868
7131
  await loaded.runtime.setReasoningEffort(loaded.record.localSessionId, effort);
6869
7132
  this.store.updateRuntimeSession(loaded.record.localSessionId, { reasoningEffort: effort });
6870
- await this.persistAgentExecutionDefaults(loaded.record.localSessionId);
6871
7133
  });
6872
7134
  if (options.updateMessageId) {
6873
7135
  await this.openExecutionSettingsNow(contextKey, "thinking", {
6874
7136
  sessionId: loaded.record.localSessionId,
6875
7137
  updateMessageId: options.updateMessageId,
6876
- notice: `思考强度已切换为 ${cardCode(effort)},并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
7138
+ notice: `思考强度已切换为 ${cardCode(effort)},只影响当前任务,从下一次请求生效。`,
6877
7139
  });
6878
7140
  return;
6879
7141
  }
6880
7142
  await this.outbound.sendText(
6881
7143
  contextKey,
6882
- `思考强度已切换为 ${effort},并已保存为 ${loaded.record.agentName} Agent 的默认设置,从下一次请求生效。`,
7144
+ `思考强度已切换为 ${effort},只影响当前任务,从下一次请求生效。`,
6883
7145
  );
6884
7146
  }
6885
7147
 
@@ -6911,23 +7173,22 @@ export class ProxySessionController {
6911
7173
  loaded.session = loaded.runtime.getSession(record.localSessionId) ?? loaded.session;
6912
7174
  loaded.session.permissionMode = mode;
6913
7175
  this.store.updateRuntimeSession(record.localSessionId, { permissionMode: mode });
6914
- await this.persistAgentExecutionDefaults(record.localSessionId);
6915
7176
  });
6916
7177
  if (options.updateMessageId) {
6917
7178
  await this.openExecutionSettingsNow(contextKey, "permission", {
6918
7179
  sessionId: loaded.record.localSessionId,
6919
7180
  updateMessageId: options.updateMessageId,
6920
7181
  notice: mode === "auto"
6921
- ? `已切换为自动执行模式,并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`
6922
- : `已切换为执行前确认模式,并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
7182
+ ? "已切换为自动执行模式,只影响当前任务,从下一次请求生效。"
7183
+ : "已切换为执行前确认模式,只影响当前任务,从下一次请求生效。",
6923
7184
  });
6924
7185
  return;
6925
7186
  }
6926
7187
  await this.outbound.sendText(
6927
7188
  contextKey,
6928
7189
  mode === "auto"
6929
- ? `已切换为自动执行模式,并已保存为 ${loaded.record.agentName} Agent 的默认设置。`
6930
- : `已切换为执行前确认模式,并已保存为 ${loaded.record.agentName} Agent 的默认设置。`,
7190
+ ? "已切换为自动执行模式,只影响当前任务,从下一次请求生效。"
7191
+ : "已切换为执行前确认模式,只影响当前任务,从下一次请求生效。",
6931
7192
  );
6932
7193
  }
6933
7194
 
@@ -7063,6 +7324,7 @@ export class ProxySessionController {
7063
7324
  && !this.store.getTurnPromptSummary(turnId)) {
7064
7325
  await this.outbound.sendInteractiveCard(contextKey, this.cardRenderer.renderTurnDetails(
7065
7326
  this.runningTurnSnapshot(current, turnId),
7327
+ undefined, this.store.provenance.forTurn(turnId, current.localSessionId),
7066
7328
  ));
7067
7329
  return;
7068
7330
  }
@@ -7656,7 +7918,7 @@ export class ProxySessionController {
7656
7918
  projectActions,
7657
7919
  cardEntry: {
7658
7920
  reference: entry.reference,
7659
- summary: `${offset + index + 1}. ${marker}${title} · ${entry.agentName}`,
7921
+ summary: `${offset + index + 1}. ${marker}${title} · ${entry.agentName}${entry.status === "待核实" ? " · 待核实" : ""}`,
7660
7922
  detailLines: [
7661
7923
  `**最新 Prompt**:${cardText(lastUserPrompt)}`,
7662
7924
  `<font color='grey'>最近更新:${cardText(entry.updatedLabel)}</font>`,
@@ -8257,11 +8519,11 @@ export class ProxySessionController {
8257
8519
  queued = this.store.countQueuedPrompts(current.localSessionId);
8258
8520
  snapshot = turnViewSnapshot(current.lastTurnId ? this.store.getTurnSnapshot(current.lastTurnId) : undefined);
8259
8521
  const waitingForApproval = snapshot?.turnId === current.lastTurnId && snapshot?.status === "waiting_for_approval";
8260
- const statusLabel = waitingForApproval ? "等待确认"
8522
+ const statusLabel = current.lastTurnStatus === "unknown" ? "待核实" : waitingForApproval ? "等待确认"
8261
8523
  : remoteActive && remote && localCurrent && !isBotOwnedActiveTurn(localCurrent, remote)
8262
8524
  ? "外部执行中"
8263
8525
  : sessionStatusLabel(current.status, activeTurnId);
8264
- const resultLabel = waitingForApproval ? "等待确认" : remoteActive
8526
+ const resultLabel = current.lastTurnStatus === "unknown" ? "待核实" : waitingForApproval ? "等待确认" : remoteActive
8265
8527
  ? "执行中"
8266
8528
  : remoteTurnStatusLabel(remote?.lastTurnStatus ?? current.lastTurnStatus);
8267
8529
  taskLines.push(
@@ -8287,12 +8549,10 @@ export class ProxySessionController {
8287
8549
  ...(current ? [{
8288
8550
  title: "最终结果",
8289
8551
  lines: finalResultLines(snapshot, remote),
8290
- localImages: true,
8291
8552
  }] : []),
8292
8553
  ...(current ? [{
8293
8554
  title: "执行详情",
8294
8555
  lines: executionDetailLines(localCurrent ?? current, snapshot, remote, activeTurnId, queued),
8295
- localImages: true,
8296
8556
  collapsible: true,
8297
8557
  elementId: "status_execution_details",
8298
8558
  }] : []),
@@ -8383,7 +8643,7 @@ export class ProxySessionController {
8383
8643
  `**创建时间 / 最近活动**:${formatRemoteTime(remote.createdAt)} / ${formatRemoteTime(latestRemoteTimestamp(remote.recencyAt, remote.updatedAt))}`,
8384
8644
  ],
8385
8645
  },
8386
- { title: "最终结果", lines: finalResultLines(undefined, remote), localImages: true },
8646
+ { title: "最终结果", lines: finalResultLines(undefined, remote) },
8387
8647
  {
8388
8648
  title: "执行详情",
8389
8649
  lines: [
@@ -8392,7 +8652,6 @@ export class ProxySessionController {
8392
8652
  ? "外部 Agent 正在执行;Agent Bot 只读取状态,不会接管。"
8393
8653
  : `发送 **/switch ${cardText(remote.id)}** 切换到此任务。`,
8394
8654
  ],
8395
- localImages: true,
8396
8655
  collapsible: true,
8397
8656
  elementId: "status_execution_details",
8398
8657
  },
@@ -8532,28 +8791,6 @@ export class ProxySessionController {
8532
8791
  return agent;
8533
8792
  }
8534
8793
 
8535
- private async persistAgentExecutionDefaults(localSessionId: string, candidate?: RuntimeSession): Promise<void> {
8536
- const record = this.store.getSession(localSessionId);
8537
- if (!record) throw new Error(`找不到任务:${localSessionId}`);
8538
- return this.agentDefaultsOperations.run(record.agentName, () => this.persistAgentExecutionDefaultsNow(localSessionId, candidate));
8539
- }
8540
-
8541
- private async persistAgentExecutionDefaultsNow(localSessionId: string, candidate?: RuntimeSession): Promise<void> {
8542
- const record = this.store.getSession(localSessionId);
8543
- if (!record) throw new Error(`找不到任务:${localSessionId}`);
8544
- const session = candidate ?? record;
8545
- const agent = this.ensureAgent(session.agentName);
8546
- const observed: AgentExecutionDefaults = {
8547
- ...(session.modelProvider?.trim() ? { modelProvider: session.modelProvider } : {}),
8548
- ...(session.model?.trim() ? { model: session.model } : {}),
8549
- ...(session.reasoningEffort?.trim() ? { reasoningEffort: session.reasoningEffort } : {}),
8550
- ...(session.permissionMode ? { permissionMode: session.permissionMode } : {}),
8551
- };
8552
- const defaults = { ...(agent.defaults ?? {}), ...observed };
8553
- await this.lifecycle?.persistAgentExecutionDefaults?.(session.agentName, defaults);
8554
- agent.defaults = defaults;
8555
- }
8556
-
8557
8794
  private agentLabel(agentName: string): string {
8558
8795
  return this.ensureAgent(agentName).title;
8559
8796
  }
@@ -9353,7 +9590,9 @@ function mergeTaskList(
9353
9590
  const local = localByRemoteId.get(agentRemoteKey(agentName, remote.id));
9354
9591
  if (local) representedLocalIds.add(local.localSessionId);
9355
9592
  const active = remote.status === "active" || remote.lastTurnStatus === "inProgress";
9356
- 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"
9357
9596
  ? local && isBotOwnedActiveTurn(local, remote) ? "执行中" : "外部执行中"
9358
9597
  : remoteSessionStatusLabel(remote.status);
9359
9598
  const recencyAt = remote.recencyAt ?? remote.updatedAt;
@@ -9385,7 +9624,7 @@ function mergeTaskList(
9385
9624
  agentName: local.agentName,
9386
9625
  title: local.title ?? "未命名任务",
9387
9626
  cwd: local.cwd,
9388
- status: sessionStatusLabel(local.status),
9627
+ status: local.lastTurnStatus === "unknown" ? "待核实" : sessionStatusLabel(local.status),
9389
9628
  active: local.status === "running",
9390
9629
  current: local.localSessionId === currentLocalSessionId,
9391
9630
  lastUserPrompt: latestLocalUserPrompts.get(local.localSessionId),
@@ -9590,6 +9829,7 @@ function remoteTurnStatusLabel(status?: string): string {
9590
9829
  failed: "失败",
9591
9830
  running: "执行中",
9592
9831
  cancelled: "已停止",
9832
+ unknown: "待核实",
9593
9833
  };
9594
9834
  return status ? labels[status] ?? status : "尚无执行记录";
9595
9835
  }
@@ -9606,6 +9846,7 @@ function turnViewStatusLabel(status: TurnViewState["status"]): string {
9606
9846
  running: "执行中",
9607
9847
  tool_running: "工具执行中",
9608
9848
  waiting_for_approval: "等待确认",
9849
+ unknown: "待核实",
9609
9850
  completed: "已完成",
9610
9851
  cancelled: "已停止",
9611
9852
  failed: "失败",
@@ -9709,6 +9950,8 @@ function mapRemoteTurnStatus(status?: RemoteSessionSummary["lastTurnStatus"]): s
9709
9950
 
9710
9951
  function mergeRemoteTaskStatus(record: SessionRecord, remote?: RemoteSessionSummary): SessionRecord {
9711
9952
  if (!remote) return record;
9953
+ if (record.lastTurnStatus === "unknown"
9954
+ && (!remote.lastTurnStatus || remote.lastTurnId !== record.lastTurnId)) return record;
9712
9955
  const remoteTurnStatus = mapRemoteTurnStatus(remote.lastTurnStatus);
9713
9956
  const createdAt = remote.createdAt === undefined
9714
9957
  ? record.createdAt
@@ -10138,30 +10381,13 @@ function recoveryCardPrompt(prompt: string): string {
10138
10381
  return `恢复重启前的任务:${prompt}`;
10139
10382
  }
10140
10383
 
10141
- function recoveryRuntimePrompt(prompt: string): string {
10142
- return [
10143
- "Agent Bot restarted while the previous turn was still running.",
10144
- "Continue the unfinished task in the current task and workspace.",
10145
- "Inspect the existing conversation, files, and completed tool effects first. Do not repeat completed or irreversible actions.",
10146
- "Finish the original request:",
10147
- "",
10148
- prompt,
10149
- ].join("\n");
10150
- }
10384
+
10151
10385
 
10152
10386
  function llmRetryCardPrompt(prompt: string, retryNumber: number): string {
10153
10387
  return `自动重试 ${retryNumber}/${MAX_LLM_TURN_RETRIES}:${prompt}`;
10154
10388
  }
10155
10389
 
10156
- function llmRetryRuntimePrompt(prompt: string, retryNumber: number): string {
10157
- return [
10158
- `Agent Bot is automatically retrying this request after a transient LLM service failure (${retryNumber}/${MAX_LLM_TURN_RETRIES}).`,
10159
- "Continue in the current task and workspace. Inspect the conversation, files, and completed tool effects before acting.",
10160
- "Do not repeat completed or irreversible actions. Finish the original request:",
10161
- "",
10162
- prompt,
10163
- ].join("\n");
10164
- }
10390
+
10165
10391
 
10166
10392
  function isRetryableLlmTurnFailure(message: string): boolean {
10167
10393
  const normalized = message.trim().toLowerCase();
@@ -10191,13 +10417,7 @@ function isRetryableLlmTurnFailure(message: string): boolean {
10191
10417
  }
10192
10418
 
10193
10419
  function remoteTurnMatchesAttempt(remote: RemoteSessionSummary | undefined, attempt: TurnAttemptRecord): boolean {
10194
- if (!remote?.lastTurnId) return false;
10195
- if (attempt.turnId) return remote.lastTurnId === attempt.turnId;
10196
- const remoteUpdatedAt = remote.updatedAt === undefined ? undefined : normalizeRemoteTimestamp(remote.updatedAt);
10197
- const acceptedAt = Date.parse(attempt.createdAt);
10198
- return remoteUpdatedAt !== undefined
10199
- && Number.isFinite(acceptedAt)
10200
- && remoteUpdatedAt >= acceptedAt - 1_000;
10420
+ return Boolean(attempt.turnId && remote?.lastTurnId === attempt.turnId);
10201
10421
  }
10202
10422
 
10203
10423
  function isRecoveryAttemptRecent(attempt: TurnAttemptRecord, cutoff: number): boolean {