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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +34 -6
  3. package/README.zh.md +34 -6
  4. package/config.example.yaml +1 -3
  5. package/dist/cli/help.js +2 -0
  6. package/dist/cli/help.js.map +1 -1
  7. package/dist/codex/CodexRuntime.js +15 -5
  8. package/dist/codex/CodexRuntime.js.map +1 -1
  9. package/dist/commands/CommandRouter.js +3 -0
  10. package/dist/commands/CommandRouter.js.map +1 -1
  11. package/dist/config/SettingsStore.js +341 -0
  12. package/dist/config/SettingsStore.js.map +1 -0
  13. package/dist/config/loadConfig.js +1 -2
  14. package/dist/config/loadConfig.js.map +1 -1
  15. package/dist/config/schema.js +0 -1
  16. package/dist/config/schema.js.map +1 -1
  17. package/dist/console/ConsoleTurnPresenter.js +3 -0
  18. package/dist/console/ConsoleTurnPresenter.js.map +1 -1
  19. package/dist/feishu/CardRenderer.js +34 -99
  20. package/dist/feishu/CardRenderer.js.map +1 -1
  21. package/dist/feishu/FeishuConnector.js +9 -0
  22. package/dist/feishu/FeishuConnector.js.map +1 -1
  23. package/dist/feishu/FeishuMessageClient.js +23 -18
  24. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  25. package/dist/feishu/FeishuTurnPresenter.js +36 -23
  26. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  27. package/dist/feishu/LocalCardImage.js +0 -4
  28. package/dist/feishu/LocalCardImage.js.map +1 -1
  29. package/dist/feishu/LocalImageMarkdown.js +59 -3
  30. package/dist/feishu/LocalImageMarkdown.js.map +1 -1
  31. package/dist/feishu/SettingsCard.js +199 -0
  32. package/dist/feishu/SettingsCard.js.map +1 -0
  33. package/dist/index.js +3 -6
  34. package/dist/index.js.map +1 -1
  35. package/dist/local-files/TurnPreviewPage.js +8 -4
  36. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  37. package/dist/presentation/TurnStateReducer.js +21 -2
  38. package/dist/presentation/TurnStateReducer.js.map +1 -1
  39. package/dist/presentation/turnStatus.js +34 -0
  40. package/dist/presentation/turnStatus.js.map +1 -0
  41. package/dist/proxy/ProxySessionController.js +409 -163
  42. package/dist/proxy/ProxySessionController.js.map +1 -1
  43. package/dist/runtime/submissionErrors.js +15 -0
  44. package/dist/runtime/submissionErrors.js.map +1 -0
  45. package/dist/state/ExecutionProvenanceStore.js +58 -0
  46. package/dist/state/ExecutionProvenanceStore.js.map +1 -0
  47. package/dist/state/StateStore.js +96 -33
  48. package/dist/state/StateStore.js.map +1 -1
  49. package/dist/state/migrations.js +12 -0
  50. package/dist/state/migrations.js.map +1 -1
  51. package/docs/technical-reference.md +11 -8
  52. package/docs/technical-reference.zh.md +11 -8
  53. package/npm-shrinkwrap.json +2 -2
  54. package/package.json +1 -1
  55. package/skills/agent-bot/SKILL.md +9 -3
  56. package/src/cli/help.ts +2 -0
  57. package/src/codex/CodexRuntime.ts +14 -5
  58. package/src/commands/CommandRouter.ts +3 -0
  59. package/src/commands/commandTypes.ts +1 -0
  60. package/src/config/SettingsStore.ts +588 -0
  61. package/src/config/loadConfig.ts +1 -2
  62. package/src/config/schema.ts +0 -1
  63. package/src/console/ConsoleTurnPresenter.ts +2 -0
  64. package/src/feishu/CardRenderer.ts +35 -114
  65. package/src/feishu/FeishuConnector.ts +9 -0
  66. package/src/feishu/FeishuMessageClient.ts +23 -22
  67. package/src/feishu/FeishuTurnPresenter.ts +33 -22
  68. package/src/feishu/LocalCardImage.ts +0 -6
  69. package/src/feishu/LocalImageMarkdown.ts +54 -3
  70. package/src/feishu/SettingsCard.ts +231 -0
  71. package/src/index.ts +3 -6
  72. package/src/local-files/TurnPreviewPage.ts +8 -4
  73. package/src/presentation/TurnStateReducer.ts +21 -2
  74. package/src/presentation/turnStatus.ts +38 -0
  75. package/src/presentation/turnViewTypes.ts +3 -0
  76. package/src/proxy/ProxySessionController.ts +382 -162
  77. package/src/runtime/submissionErrors.ts +15 -0
  78. package/src/runtime/types.ts +1 -0
  79. package/src/state/ExecutionProvenanceStore.ts +100 -0
  80. package/src/state/StateStore.ts +118 -33
  81. package/src/state/migrations.ts +12 -0
@@ -18,12 +18,14 @@ import { normalizeFeishuPostText } from "../feishu/InboundText.js";
18
18
  import { RECENT_CONTEXT_LIMIT, RECENT_CONTEXT_IMAGE_LIMIT, RECENT_CONTEXT_TEXT_LIMIT, recentContextPrompt } from "../feishu/RecentMessageContext.js";
19
19
  import { allowsFeishuUser } from "../feishu/ownerAccess.js";
20
20
  import { scheduleCommandSchema } from "../scheduling/types.js";
21
+ import { renderSettingsCard } from "../feishu/SettingsCard.js";
21
22
  import { renderSchedule, renderScheduleList, renderScheduleForm } from "../scheduling/ScheduleCards.js";
22
23
  import { classifyFileContent } from "../local-files/LocalFileViewerServer.js";
23
24
  import { errorLogValue } from "../logging/errorLogValue.js";
24
25
  import { createTurnViewState, hydrateTurnViewState } from "../presentation/TurnStateReducer.js";
25
26
  import { buildTurnGraphRows } from "../presentation/turnGraph.js";
26
27
  import { displayRuntimeError, isResponseContinuationError } from "../runtime/responseErrors.js";
28
+ import { TurnNotSubmittedError, TurnStoppedBeforeSubmissionError } from "../runtime/submissionErrors.js";
27
29
  import { isActiveShellCommandJob, ShellCommandJobManager, } from "../shell/ShellCommandJobManager.js";
28
30
  import { SessionOperationQueue } from "./SessionOperationQueue.js";
29
31
  import { createId } from "../utils/id.js";
@@ -130,6 +132,7 @@ const HELP_COMMAND_SECTIONS = [
130
132
  },
131
133
  { command: "/sessions", usage: "[关键词]", description: "查找本机任务" },
132
134
  { command: "/schedule", description: "创建和管理绑定现有任务的定时计划" },
135
+ { command: "/settings", description: "配置 Agent Bot 和各 Agent 默认值(仅所有者)" },
133
136
  {
134
137
  command: "/archive",
135
138
  usage: "[序号或任务 ID]",
@@ -239,9 +242,9 @@ export class ProxySessionController {
239
242
  queuedPromptCards = new Map();
240
243
  queuedPromptCardWrites = new Map();
241
244
  settingsOperations = new SessionOperationQueue();
245
+ globalSettingsOperations = new SessionOperationQueue();
242
246
  // Loads may run inside settingsOperations; never acquire that queue while hydrating.
243
247
  sessionHydrationOperations = new SessionOperationQueue();
244
- agentDefaultsOperations = new SessionOperationQueue();
245
248
  sessionResets = new Map();
246
249
  resetHistoryOperations = new Map();
247
250
  remoteTurnHistoryRefreshes = new Map();
@@ -598,8 +601,14 @@ export class ProxySessionController {
598
601
  if (command.type === "prompt" && message.chatType === "group" && message.mentionedBot
599
602
  && this.store.chatRequiresMention(baseChatContextKey(message.contextKey))) {
600
603
  const current = this.currentSession(message.contextKey);
601
- if (current)
602
- this.store.rememberRecentContextMessages(current.localSessionId, current.remoteSessionId ?? "", message.contextKey, message.messageId, [...recentContextIds, message.messageId, ...[referencedMessageId, injectedRootMessageId].filter((id) => Boolean(id))]);
604
+ if (current) {
605
+ try {
606
+ this.store.rememberRecentContextMessages(current.localSessionId, current.remoteSessionId ?? "", message.contextKey, message.messageId, [...recentContextIds, message.messageId, ...[referencedMessageId, injectedRootMessageId].filter((id) => Boolean(id))]);
607
+ }
608
+ catch (error) {
609
+ this.logger.warn({ error, localSessionId: current.localSessionId, messageId: message.messageId }, "Failed to save recent context receipts after accepting the prompt.");
610
+ }
611
+ }
603
612
  }
604
613
  if (injectedRootMessageId) {
605
614
  const current = this.currentSession(message.contextKey);
@@ -660,7 +669,10 @@ export class ProxySessionController {
660
669
  await this.outbound.withReplyTarget(contextKey, replyTarget, async () => {
661
670
  try {
662
671
  const kind = String(scopedAction.value.action ?? "");
663
- if (kind.startsWith("schedule_")) {
672
+ if (kind.startsWith("bot_settings_")) {
673
+ await this.handleSettingsAction(scopedAction, replyTarget);
674
+ }
675
+ else if (kind.startsWith("schedule_")) {
664
676
  await this.handleScheduleAction(scopedAction, replyTarget);
665
677
  }
666
678
  else if (kind === "terminal_authorize") {
@@ -861,7 +873,6 @@ export class ProxySessionController {
861
873
  }
862
874
  else if (kind === "session_stop") {
863
875
  const sessionId = String(scopedAction.value.sessionId ?? "");
864
- await this.outbound.sendText(contextKey, STOP_TASK_STARTED_MESSAGE);
865
876
  await this.stopSessionReference(contextKey, sessionId);
866
877
  if (scopedAction.value.cardView === "status")
867
878
  await this.refreshStatusCardFromAction(scopedAction, sessionId);
@@ -1341,6 +1352,73 @@ export class ProxySessionController {
1341
1352
  this.assertScheduleTarget(job);
1342
1353
  return this.store.schedules.change(job.id, job.revision, command.operation);
1343
1354
  }
1355
+ requireSettingsOwner(userId) {
1356
+ if (!this.config.feishu.userOpenId || userId !== this.config.feishu.userOpenId) {
1357
+ throw new Error("只有 Agent Bot 所有者可以管理全局配置。");
1358
+ }
1359
+ if (!this.lifecycle?.settings)
1360
+ throw new Error("当前运行方式不支持配置面板。");
1361
+ return this.lifecycle.settings;
1362
+ }
1363
+ async handleSettingsAction(action, replyTarget) {
1364
+ const settings = this.requireSettingsOwner(action.userId);
1365
+ return this.globalSettingsOperations.run("profile", () => this.handleSettingsActionNow(settings, action, replyTarget));
1366
+ }
1367
+ async settingsCatalog(snapshot, selectedProvider) {
1368
+ if (!snapshot.agentName)
1369
+ return undefined;
1370
+ let providers;
1371
+ try {
1372
+ const runtime = this.runtimes.forAgent(snapshot.agentName);
1373
+ providers = await runtime.listModelProviders?.() ?? [];
1374
+ const requested = selectedProvider ?? snapshot.modelProvider;
1375
+ const provider = requested || providers.find((entry) => entry.isDefault)?.id;
1376
+ const result = await this.modelOptions(runtime, provider, selectedProvider === undefined || selectedProvider === (snapshot.modelProvider ?? "") ? snapshot.model : undefined);
1377
+ return { models: result.models, providers,
1378
+ ...(result.warning || result.models.length === 0
1379
+ ? { warning: "模型列表暂不可完整获取;保留当前配置,也可选择使用 Agent 默认。" } : {}) };
1380
+ }
1381
+ catch {
1382
+ return { models: [], providers, warning: "无法获取模型列表;保留当前配置,也可选择使用 Agent 默认。" };
1383
+ }
1384
+ }
1385
+ async handleSettingsActionNow(settings, action, replyTarget) {
1386
+ const kind = action.value.action;
1387
+ if (kind === "bot_settings_restart") {
1388
+ await this.lifecycle.restart(action.contextKey, false, replyTarget);
1389
+ return;
1390
+ }
1391
+ if (!["bot_settings_show", "bot_settings_agent", "bot_settings_change"].includes(String(kind)))
1392
+ throw new Error("无效的配置操作。");
1393
+ const messageId = requiredCardMessageId(action.messageId);
1394
+ const agentValue = kind === "bot_settings_agent" ? action.value.option : action.value.agentName;
1395
+ const agentName = typeof agentValue === "string" ? agentValue : undefined;
1396
+ const current = settings.read(action.value.section, agentName);
1397
+ const selectedProvider = kind === "bot_settings_change" && action.value.field === "modelProvider" && typeof action.value.option === "string"
1398
+ ? (action.value.option === "__agent_default__" ? "" : action.value.option) : undefined;
1399
+ const catalog = await this.settingsCatalog(current, selectedProvider);
1400
+ if (settings.read(current.section, current.agentName).revision !== current.revision)
1401
+ throw new Error("配置已变化,请刷新面板后重新编辑。");
1402
+ let snapshot = settings.read(current.section, current.agentName, catalog);
1403
+ let notice;
1404
+ if (kind === "bot_settings_change") {
1405
+ const field = snapshot.fields.find((entry) => entry.name === action.value.field);
1406
+ const value = field?.kind === "boolean" ? action.value.checked
1407
+ : field?.kind === "select" ? action.value.option : action.value.inputValue;
1408
+ try {
1409
+ snapshot = settings.saveField(snapshot.section, snapshot.agentName, action.value.field, action.value.revision, value, catalog);
1410
+ if (["modelProvider", "model"].includes(String(action.value.field))
1411
+ && current.agentName && settings.read("agents", current.agentName).values.reasoningEffort === ""
1412
+ && current.reasoningEffort)
1413
+ notice = "已自动保存,思考强度已恢复 Agent 默认;安全重启后生效。";
1414
+ }
1415
+ catch (error) {
1416
+ snapshot = settings.read(current.section, current.agentName, await this.settingsCatalog(current));
1417
+ notice = `未保存:${error instanceof Error ? error.message : "配置保存失败,请重试。"}`;
1418
+ }
1419
+ }
1420
+ await this.outbound.updateInteractiveCard(action.contextKey, messageId, renderSettingsCard(snapshot, action.contextKey, notice));
1421
+ }
1344
1422
  createSchedule(input, localSessionId, contextKey, replyMessageId) {
1345
1423
  if (!this.config.feishu.userOpenId)
1346
1424
  throw new Error("请先配置 Agent Bot 所有者,才能创建定时任务。");
@@ -1693,6 +1771,17 @@ export class ProxySessionController {
1693
1771
  throw new Error(unboundThreadTaskMessage());
1694
1772
  }
1695
1773
  switch (command.type) {
1774
+ case "settings": {
1775
+ const settings = this.requireSettingsOwner(userId);
1776
+ await this.globalSettingsOperations.run("profile", async () => {
1777
+ const current = settings.read();
1778
+ const catalog = await this.settingsCatalog(current);
1779
+ if (settings.read().revision !== current.revision)
1780
+ throw new Error("配置已变化,请重新打开设置。");
1781
+ await this.outbound.sendInteractiveCard(contextKey, renderSettingsCard(settings.read("general", undefined, catalog), contextKey));
1782
+ });
1783
+ return;
1784
+ }
1696
1785
  case "schedule": {
1697
1786
  if (!this.config.feishu.userOpenId || userId !== this.config.feishu.userOpenId)
1698
1787
  throw new Error("只有 Agent Bot 所有者可以管理定时任务。");
@@ -1948,6 +2037,10 @@ export class ProxySessionController {
1948
2037
  for (const attempt of this.store.listCancellationRequestedTurnAttempts()) {
1949
2038
  const session = this.store.getSession(attempt.localSessionId);
1950
2039
  if (!attempt.turnId) {
2040
+ if (attempt.submissionState !== "not_submitted") {
2041
+ await this.markAttemptUnknown(attempt, "停止意图已保存,但提交结果未知;未自动重发。请核实远端执行状态。");
2042
+ continue;
2043
+ }
1951
2044
  this.store.updateTurnAttempt(attempt.attemptId, { status: "cancelled" });
1952
2045
  if (session?.status === "starting" || session?.status === "running") {
1953
2046
  this.store.updateSession(session.localSessionId, { status: "ready" });
@@ -1958,13 +2051,27 @@ export class ProxySessionController {
1958
2051
  this.outbound.registerSession(session.localSessionId, attempt.contextKey, session.title, session.cwd, this.agentLabel(session.agentName), session.model, session.modelProvider);
1959
2052
  }
1960
2053
  try {
1961
- await this.handleRuntimeEvent({
1962
- type: "turn_cancelled",
1963
- sessionId: attempt.localSessionId,
1964
- turnId: attempt.turnId,
1965
- });
2054
+ if (!session?.remoteSessionId)
2055
+ throw new Error("Missing remote session for cancellation verification.");
2056
+ const runtime = this.runtimes.forAgent(session.agentName);
2057
+ const remote = await runtime.readRemoteSession?.(session.remoteSessionId);
2058
+ if (!remote || remote.lastTurnId !== attempt.turnId)
2059
+ throw new Error("Original turn status is unverified.");
2060
+ if (isRemoteSessionActive(remote)) {
2061
+ if (!runtime.interruptRemoteTurn)
2062
+ throw new Error("Remote interruption is unavailable.");
2063
+ await runtime.interruptRemoteTurn(session.remoteSessionId, attempt.turnId);
2064
+ await this.loadSession(session);
2065
+ }
2066
+ else if (["completed", "failed", "interrupted"].includes(remote.lastTurnStatus ?? "")) {
2067
+ await this.loadSession(session);
2068
+ await runtime.synchronizeSession(session.localSessionId);
2069
+ }
2070
+ else
2071
+ throw new Error("Original turn termination is unverified.");
1966
2072
  }
1967
2073
  catch (error) {
2074
+ await this.markAttemptUnknown(attempt, "停止意图已保存,但尚不能确认原轮次已结束。未自动续跑,请核实执行记录。");
1968
2075
  this.logger.warn({ error, attemptId: attempt.attemptId, turnId: attempt.turnId }, "Failed to finish a persisted user-requested turn cancellation.");
1969
2076
  }
1970
2077
  }
@@ -1975,6 +2082,10 @@ export class ProxySessionController {
1975
2082
  continue;
1976
2083
  if (this.store.findIncompleteTurnAttemptForSession(session.localSessionId))
1977
2084
  continue;
2085
+ if (this.store.hasUnknownTurnAttemptForSession(session.localSessionId))
2086
+ continue;
2087
+ if (this.store.hasCancellationRequestedForSession(session.localSessionId))
2088
+ continue;
1978
2089
  const lastTurn = session.lastTurnId
1979
2090
  ? {
1980
2091
  turnId: session.lastTurnId,
@@ -1997,6 +2108,8 @@ export class ProxySessionController {
1997
2108
  if (!latest && session.status === "ready")
1998
2109
  continue;
1999
2110
  const snapshot = turnViewSnapshot(latest?.snapshot);
2111
+ if (snapshot?.status === "unknown")
2112
+ continue;
2000
2113
  if (snapshot && isTerminalTurnViewStatus(snapshot.status)) {
2001
2114
  this.store.updateSession(session.localSessionId, {
2002
2115
  status: snapshot.status === "failed" ? "failed" : "ready",
@@ -2021,12 +2134,17 @@ export class ProxySessionController {
2021
2134
  pendingTurnId,
2022
2135
  turnId,
2023
2136
  status: turnId ? "running" : "accepted",
2137
+ submissionState: turnId ? "submitted" : "submission_unknown",
2024
2138
  createdAt: latest?.updatedAt ?? session.updatedAt,
2025
2139
  updatedAt: latest?.updatedAt ?? session.updatedAt,
2026
2140
  });
2027
2141
  }
2028
2142
  }
2029
2143
  async expireStaleTurnAttempt(attempt, message = "执行中断已超过 10 分钟,未自动恢复。") {
2144
+ if (attempt.submissionState !== "not_submitted") {
2145
+ await this.markAttemptUnknown(attempt, `${message} 原执行结果待核实,未自动重发。`);
2146
+ return;
2147
+ }
2030
2148
  clearTimeout(this.recoveryRetryTimers.get(attempt.attemptId));
2031
2149
  this.recoveryRetryTimers.delete(attempt.attemptId);
2032
2150
  this.recoveryRetryStartedAt.delete(attempt.attemptId);
@@ -2119,6 +2237,13 @@ export class ProxySessionController {
2119
2237
  async recoverTurnAttempt(attempt, announce = true) {
2120
2238
  if (this.recoveryClosed)
2121
2239
  return;
2240
+ if (attempt.executionGeneration !== this.store.executionGeneration(attempt.localSessionId)) {
2241
+ if (attempt.submissionState === "not_submitted")
2242
+ this.store.updateTurnAttempt(attempt.attemptId, { status: "cancelled" });
2243
+ else
2244
+ await this.markAttemptUnknown(attempt, "停止意图已保存,原执行结果待核实,未自动续跑。");
2245
+ return;
2246
+ }
2122
2247
  const session = this.store.getSession(attempt.localSessionId);
2123
2248
  if (!session || session.status === "closed") {
2124
2249
  this.store.updateTurnAttempt(attempt.attemptId, { status: "interrupted" });
@@ -2167,7 +2292,7 @@ export class ProxySessionController {
2167
2292
  await this.reconcileRecoveredRemoteTurn(attempt, session, remote.lastTurnId);
2168
2293
  return;
2169
2294
  }
2170
- if (remote && remoteTurnBelongsToAttempt && remote.lastTurnStatus === "failed") {
2295
+ if (remote && remoteTurnBelongsToAttempt && (remote.lastTurnStatus === "failed" || remote.lastTurnStatus === "interrupted")) {
2171
2296
  await this.reconcileRecoveredRemoteTurn(attempt, session, remote.lastTurnId);
2172
2297
  return;
2173
2298
  }
@@ -2190,16 +2315,38 @@ export class ProxySessionController {
2190
2315
  await this.continueInterruptedAttempt(attempt, session, sourceTurnId, replyTarget);
2191
2316
  }
2192
2317
  async markScheduledAttemptUnknown(attempt, detail) {
2193
- this.store.updateTurnAttempt(attempt.attemptId, { status: "interrupted" });
2318
+ await this.markAttemptUnknown(attempt, detail);
2194
2319
  this.store.schedules.finish(attempt.attemptId, "unknown", detail);
2195
2320
  const run = this.store.schedules.getRun(attempt.attemptId);
2196
2321
  const job = this.store.schedules.get(run.jobId);
2197
- if (attempt.pendingTurnId) {
2198
- await this.outbound.interruptTurnForRecovery(attempt.localSessionId, attempt.contextKey, attempt.pendingTurnId, detail);
2199
- }
2200
2322
  if (job)
2201
2323
  await this.notifySchedule(job, `定时任务「${job.spec.name}」:${detail}`);
2202
2324
  }
2325
+ async markAttemptUnknown(attempt, message) {
2326
+ clearTimeout(this.recoveryRetryTimers.get(attempt.attemptId));
2327
+ this.recoveryRetryTimers.delete(attempt.attemptId);
2328
+ this.recoveryRetryStartedAt.delete(attempt.attemptId);
2329
+ this.recoveredLiveAttempts.delete(attempt.attemptId);
2330
+ const session = this.store.getSession(attempt.localSessionId);
2331
+ const turnId = attempt.turnId ?? attempt.pendingTurnId;
2332
+ this.store.updateTurnAttempt(attempt.attemptId, { status: "unknown" });
2333
+ if (this.store.schedules.getRun(attempt.attemptId))
2334
+ this.store.schedules.finish(attempt.attemptId, "unknown", message);
2335
+ if (!session || session.status === "closed")
2336
+ return;
2337
+ this.outbound.registerSession(session.localSessionId, attempt.contextKey, session.title, session.cwd, this.agentLabel(session.agentName), session.model, session.modelProvider);
2338
+ const active = this.runtimes.forAgent(session.agentName).getSession(session.localSessionId)?.activeTurnId;
2339
+ if (!session.lastTurnId || session.lastTurnId === turnId || session.lastTurnId === attempt.recoveredFromTurnId
2340
+ || (!attempt.turnId && !active)) {
2341
+ this.store.updateRuntimeSession(session.localSessionId, { lastTurnId: turnId, lastTurnStatus: "unknown" });
2342
+ if (!active)
2343
+ this.store.updateSession(session.localSessionId, { status: "ready" });
2344
+ }
2345
+ if (turnId)
2346
+ await this.outbound.onEvent({ type: "turn_status_unknown", sessionId: session.localSessionId, turnId, message });
2347
+ else
2348
+ await this.outbound.sendText(attempt.contextKey, message);
2349
+ }
2203
2350
  async reconcileRecoveredRemoteTurn(attempt, session, remoteTurnId) {
2204
2351
  if (remoteTurnId && !attempt.turnId) {
2205
2352
  this.store.updateTurnAttempt(attempt.attemptId, { turnId: remoteTurnId, status: "running" });
@@ -2312,13 +2459,18 @@ export class ProxySessionController {
2312
2459
  }
2313
2460
  }
2314
2461
  async continueInterruptedAttempt(attempt, session, sourceTurnId, replyTarget) {
2462
+ if (attempt.submissionState !== "not_submitted" || sourceTurnId) {
2463
+ await this.markAttemptUnknown(attempt, "原执行结果待核实,未自动重发。请检查执行记录后发送消息继续。");
2464
+ return;
2465
+ }
2315
2466
  const oldCardTurnId = attempt.pendingTurnId ?? sourceTurnId;
2316
2467
  if (oldCardTurnId) {
2317
2468
  await this.outbound.interruptTurnForRecovery(session.localSessionId, attempt.contextKey, oldCardTurnId, "Agent Bot 重启中断了这次执行,正在新的思考卡片中继续。").catch((error) => {
2318
2469
  this.logger.warn({ error, attemptId: attempt.attemptId, turnId: oldCardTurnId }, "Failed to close the interrupted thinking card before recovery.");
2319
2470
  });
2320
2471
  }
2321
- this.store.prepareTurnAttemptRecovery(attempt.attemptId, oldCardTurnId);
2472
+ if (!this.store.prepareTurnAttemptRecovery(attempt.attemptId, oldCardTurnId))
2473
+ return;
2322
2474
  this.store.updateSession(session.localSessionId, { status: "ready" });
2323
2475
  if (sourceTurnId) {
2324
2476
  this.store.updateRuntimeSession(session.localSessionId, {
@@ -2328,9 +2480,11 @@ export class ProxySessionController {
2328
2480
  }
2329
2481
  const current = this.store.getSession(session.localSessionId) ?? session;
2330
2482
  const loaded = await this.loadSession({ ...current, contextKey: attempt.contextKey }, Boolean(this.store.getPendingProviderSettings(current.localSessionId)));
2331
- const recoveryText = recoveryRuntimePrompt(attempt.promptText);
2483
+ const recoveryText = attempt.promptText;
2332
2484
  const turnId = await this.startTurn(loaded, recoveryText, replyTarget, attempt.localImagePaths, {
2333
2485
  attemptId: attempt.attemptId,
2486
+ executionGeneration: attempt.executionGeneration,
2487
+ trigger: "recovery",
2334
2488
  messageId: attempt.messageId,
2335
2489
  displayPrompt: recoveryCardPrompt(attempt.promptText),
2336
2490
  preserveAttemptOnFailure: true,
@@ -2366,6 +2520,7 @@ export class ProxySessionController {
2366
2520
  await this.promptSession(record, contextKey, text, messageId, replyTarget, localImagePaths, displayPrompt);
2367
2521
  }
2368
2522
  async promptSession(record, contextKey, text, messageId, replyTarget, localImagePaths, displayPrompt) {
2523
+ const executionGeneration = this.store.executionGeneration(record.localSessionId);
2369
2524
  if (this.llmRetryingSessions.has(record.localSessionId) || this.planHandoffs.has(record.localSessionId)) {
2370
2525
  const queued = this.persistQueuedPrompt(record.localSessionId, contextKey, text, {
2371
2526
  localImagePaths,
@@ -2412,6 +2567,8 @@ export class ProxySessionController {
2412
2567
  this.logger.warn({ error, sessionId: record.localSessionId }, "Failed to synchronize session before prompt.");
2413
2568
  }
2414
2569
  }
2570
+ this.assertExecutionGeneration(record.localSessionId, executionGeneration);
2571
+ this.store.acknowledgeUnknownTurnAttempts(record.localSessionId);
2415
2572
  const activeTurnId = loaded.session.activeTurnId;
2416
2573
  if (activeTurnId) {
2417
2574
  const activeContextKey = this.store.getTurnContextKey(activeTurnId);
@@ -2432,6 +2589,9 @@ export class ProxySessionController {
2432
2589
  return;
2433
2590
  }
2434
2591
  catch (error) {
2592
+ if (!(error instanceof TurnNotSubmittedError)) {
2593
+ throw new Error("追加消息的提交结果待核实,未自动重发或入队。请检查执行记录后继续。", { cause: error });
2594
+ }
2435
2595
  this.logger.debug({ error, sessionId: record.localSessionId, activeTurnId }, "Steering failed; reconciling the App Server thread.");
2436
2596
  let current = loaded.runtime.getSession(record.localSessionId);
2437
2597
  try {
@@ -2441,13 +2601,14 @@ export class ProxySessionController {
2441
2601
  this.logger.warn({ error: syncError, sessionId: record.localSessionId }, "Failed to synchronize after steering failure.");
2442
2602
  }
2443
2603
  if (!current?.activeTurnId) {
2444
- const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt });
2604
+ const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt, executionGeneration });
2445
2605
  if (messageId)
2446
2606
  await this.bindMessageReactionToTurn(messageId, record.localSessionId, turnId);
2447
2607
  return;
2448
2608
  }
2449
2609
  if (current.activeTurnId !== activeTurnId) {
2450
2610
  try {
2611
+ this.assertExecutionGeneration(record.localSessionId, executionGeneration);
2451
2612
  await loaded.runtime.steerTurn(record.localSessionId, current.activeTurnId, runtimePrompt(text, localImagePaths));
2452
2613
  await this.presentSteerMessage(record.localSessionId, current.activeTurnId, displayPrompt ?? text, messageId, localImagePaths);
2453
2614
  if (messageId)
@@ -2455,6 +2616,9 @@ export class ProxySessionController {
2455
2616
  return;
2456
2617
  }
2457
2618
  catch (retryError) {
2619
+ if (!(retryError instanceof TurnNotSubmittedError)) {
2620
+ throw new Error("追加消息的提交结果待核实,未自动重发或入队。", { cause: retryError });
2621
+ }
2458
2622
  this.logger.warn({ error: retryError, sessionId: record.localSessionId, activeTurnId: current.activeTurnId }, "Failed to steer the reconciled App Server turn; queueing prompt.");
2459
2623
  }
2460
2624
  }
@@ -2467,7 +2631,7 @@ export class ProxySessionController {
2467
2631
  return;
2468
2632
  }
2469
2633
  }
2470
- const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt });
2634
+ const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt, executionGeneration });
2471
2635
  if (messageId)
2472
2636
  await this.bindMessageReactionToTurn(messageId, record.localSessionId, turnId);
2473
2637
  }
@@ -2612,12 +2776,13 @@ export class ProxySessionController {
2612
2776
  }
2613
2777
  if (message.threadContext && !message.threadId)
2614
2778
  throw new Error("无法识别当前话题,已停止补充上下文以避免读取其他话题。");
2779
+ const current = this.currentSession(message.contextKey);
2780
+ const stopIds = current ? new Set([
2781
+ ...this.store.recentContextMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey, false),
2782
+ ...this.store.recentSubmittedMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey),
2783
+ ]) : new Set();
2784
+ const seen = current ? this.store.recentContextMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey) : new Set();
2615
2785
  try {
2616
- const current = this.currentSession(message.contextKey);
2617
- const stopIds = current ? new Set([
2618
- ...this.store.recentContextMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey, false),
2619
- ...this.store.recentSubmittedMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey),
2620
- ]) : new Set();
2621
2786
  const messages = await this.outbound.readRecentMessages(message.contextKey, {
2622
2787
  chatId: message.chatId,
2623
2788
  ...(message.threadId ? { threadId: message.threadId } : {}),
@@ -2625,7 +2790,6 @@ export class ProxySessionController {
2625
2790
  beforeTimestamp: message.createdAt,
2626
2791
  ...(stopIds.size ? { stopBeforeMessageIds: [...stopIds] } : {}),
2627
2792
  });
2628
- const seen = current ? this.store.recentContextMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey) : new Set();
2629
2793
  seen.add(message.messageId);
2630
2794
  if (message.parentMessageId)
2631
2795
  seen.add(message.parentMessageId);
@@ -3363,6 +3527,9 @@ export class ProxySessionController {
3363
3527
  };
3364
3528
  }
3365
3529
  async startTurn(loaded, text, replyTarget, localImagePaths, options = {}) {
3530
+ options = { ...options, executionGeneration: options.executionGeneration
3531
+ ?? (options.attemptId ? this.store.getTurnAttempt(options.attemptId)?.executionGeneration : undefined)
3532
+ ?? this.store.executionGeneration(loaded.record.localSessionId) };
3366
3533
  return this.settingsOperations.run(loaded.record.localSessionId, async () => {
3367
3534
  if (options.responseContinuationTurnId) {
3368
3535
  const current = this.store.getSession(loaded.record.localSessionId);
@@ -3389,6 +3556,10 @@ export class ProxySessionController {
3389
3556
  });
3390
3557
  }
3391
3558
  async startTurnNow(loaded, text, replyTarget, localImagePaths, options = {}) {
3559
+ const executionGeneration = options.executionGeneration
3560
+ ?? (options.attemptId ? this.store.getTurnAttempt(options.attemptId)?.executionGeneration : undefined)
3561
+ ?? this.store.executionGeneration(loaded.record.localSessionId);
3562
+ this.assertExecutionGeneration(loaded.record.localSessionId, executionGeneration);
3392
3563
  const currentRecord = this.store.getSession(loaded.record.localSessionId);
3393
3564
  const title = currentRecord?.title ?? normalizeTaskTitle(options.displayPrompt ?? text);
3394
3565
  if (!currentRecord?.title && title)
@@ -3398,6 +3569,7 @@ export class ProxySessionController {
3398
3569
  const attemptId = options.attemptId ?? createId("attempt");
3399
3570
  if (options.attemptId) {
3400
3571
  this.store.updateTurnAttempt(attemptId, {
3572
+ executionGeneration,
3401
3573
  messageId: options.messageId ?? undefined,
3402
3574
  replyMessageId: replyTarget?.messageId ?? undefined,
3403
3575
  status: "recovering",
@@ -3412,12 +3584,25 @@ export class ProxySessionController {
3412
3584
  localImagePaths,
3413
3585
  messageId: options.messageId,
3414
3586
  replyMessageId: replyTarget?.messageId,
3587
+ executionGeneration,
3415
3588
  });
3416
3589
  }
3417
3590
  let turnId;
3418
3591
  let runtimeText = text;
3419
3592
  let cardPrompt = options.displayPrompt ?? text;
3420
3593
  let retriedStart = false;
3594
+ const recordSubmission = () => {
3595
+ const runtimeSession = loaded.runtime.getSession(loaded.record.localSessionId) ?? loaded.session;
3596
+ const run = options.scheduleRunId ? this.store.schedules.getRun(options.scheduleRunId) : undefined;
3597
+ this.store.provenance.recordSubmission({
3598
+ attemptId, localSessionId: loaded.record.localSessionId,
3599
+ instructionId: options.instructionId ?? options.messageId,
3600
+ trigger: retriedStart ? "retry" : options.trigger ?? (options.scheduleRunId ? "schedule" : "user"),
3601
+ parentSourceTurnId: options.parentSourceTurnId,
3602
+ scheduledFor: run?.scheduledFor,
3603
+ settings: runtimeSession,
3604
+ });
3605
+ };
3421
3606
  try {
3422
3607
  while (true) {
3423
3608
  let pendingTurnId;
@@ -3443,6 +3628,7 @@ export class ProxySessionController {
3443
3628
  }
3444
3629
  this.store.updateTurnAttempt(attemptId, { pendingTurnId: pendingTurnId ?? null });
3445
3630
  try {
3631
+ this.assertExecutionGeneration(loaded.record.localSessionId, executionGeneration);
3446
3632
  if (options.approvedPlanTurnId && (this.planHandoffs.get(loaded.record.localSessionId) !== options.approvedPlanTurnId
3447
3633
  || this.sessionResets.has(loaded.record.localSessionId))) {
3448
3634
  throw new Error("方案执行已取消。");
@@ -3453,6 +3639,7 @@ export class ProxySessionController {
3453
3639
  || this.sessionResets.has(loaded.record.localSessionId) || !loaded.runtime.recoverResponseContinuation) {
3454
3640
  throw new Error("模型续接恢复已取消。");
3455
3641
  }
3642
+ this.store.beginTurnAttemptSubmission(attemptId, recordSubmission);
3456
3643
  turnId = await loaded.runtime.recoverResponseContinuation(loaded.record.localSessionId, options.responseContinuationTurnId, recovery.abort.signal);
3457
3644
  }
3458
3645
  else {
@@ -3464,6 +3651,7 @@ export class ProxySessionController {
3464
3651
  this.assertScheduleTarget(this.store.schedules.require(run.jobId));
3465
3652
  this.store.schedules.saveRun({ ...run, status: "submitting" });
3466
3653
  }
3654
+ this.store.beginTurnAttemptSubmission(attemptId, recordSubmission);
3467
3655
  turnId = await loaded.runtime.startTurn(loaded.record.localSessionId, options.approvedPlanTurnId
3468
3656
  ? { text: runtimeText, collaborationMode: "default" }
3469
3657
  : runtimePrompt(runtimeText, localImagePaths));
@@ -3472,14 +3660,38 @@ export class ProxySessionController {
3472
3660
  }
3473
3661
  catch (error) {
3474
3662
  const message = error instanceof Error ? error.message : String(error);
3475
- const attempt = this.store.getTurnAttempt(attemptId);
3476
- if (options.scheduleRunId && attempt?.turnId && attempt.turnId !== options.approvedPlanTurnId) {
3663
+ let attempt = this.store.getTurnAttempt(attemptId);
3664
+ if (error instanceof TurnStoppedBeforeSubmissionError) {
3665
+ this.store.updateTurnAttempt(attemptId, { status: "cancelled" });
3666
+ if (pendingTurnId)
3667
+ await this.outbound.onEvent({ type: "turn_cancelled", sessionId: loaded.record.localSessionId, turnId: pendingTurnId });
3668
+ throw error;
3669
+ }
3670
+ if (attempt?.status === "unknown")
3671
+ throw error;
3672
+ if (attempt?.turnId && attempt.turnId !== options.approvedPlanTurnId) {
3477
3673
  turnId = attempt.turnId;
3478
3674
  if (isIncompleteTurnAttemptStatus(attempt.status))
3479
3675
  this.store.updateTurnAttempt(attemptId, { status: "running" });
3480
3676
  break;
3481
3677
  }
3678
+ if (error instanceof TurnNotSubmittedError && attempt && !attempt.turnId) {
3679
+ this.store.updateTurnAttempt(attemptId, { submissionState: "not_submitted" });
3680
+ attempt = this.store.getTurnAttempt(attemptId);
3681
+ }
3682
+ if (attempt?.status === "cancelling") {
3683
+ if (attempt.submissionState === "not_submitted")
3684
+ this.store.updateTurnAttempt(attemptId, { status: "cancelled" });
3685
+ else
3686
+ await this.markAttemptUnknown(attempt, "停止意图已保存,但请求结果未知。未自动重发,请核实执行记录。");
3687
+ throw error;
3688
+ }
3689
+ if (attempt?.submissionState === "submission_unknown") {
3690
+ await this.markAttemptUnknown(attempt, "请求已发出,但无法确认执行结果;未自动重发。请核实后发送消息继续。");
3691
+ throw error;
3692
+ }
3482
3693
  const retryAttempt = attempt
3694
+ && error instanceof TurnNotSubmittedError
3483
3695
  && !options.scheduleRunId
3484
3696
  && !options.responseContinuationTurnId
3485
3697
  && isRetryableLlmTurnFailure(message)
@@ -3512,7 +3724,7 @@ export class ProxySessionController {
3512
3724
  await this.outbound.failPendingTurn(loaded.record.localSessionId, `${message}\n\n检测到临时模型服务错误,正在自动重试(${retryAttempt.retryCount}/${MAX_LLM_TURN_RETRIES})。`).catch((presentationError) => {
3513
3725
  this.logger.warn({ error: presentationError, sessionId: loaded.record.localSessionId }, "Failed to finalize the pending thinking card before an LLM start retry.");
3514
3726
  });
3515
- runtimeText = llmRetryRuntimePrompt(retryAttempt.promptText, retryAttempt.retryCount);
3727
+ runtimeText = retryAttempt.promptText;
3516
3728
  cardPrompt = llmRetryCardPrompt(options.displayPrompt ?? retryAttempt.promptText, retryAttempt.retryCount);
3517
3729
  }
3518
3730
  }
@@ -3522,14 +3734,27 @@ export class ProxySessionController {
3522
3734
  this.llmRetryingSessions.delete(loaded.record.localSessionId);
3523
3735
  }
3524
3736
  const attempt = this.store.getTurnAttempt(attemptId);
3737
+ this.store.provenance.bindLatestTurn(attemptId, turnId);
3738
+ if (this.store.executionGeneration(loaded.record.localSessionId) !== executionGeneration) {
3739
+ this.store.updateTurnAttempt(attemptId, { turnId, submissionState: "submitted", status: "cancelling" });
3740
+ try {
3741
+ await loaded.runtime.cancelTurn(loaded.record.localSessionId, turnId);
3742
+ }
3743
+ catch (error) {
3744
+ await this.markAttemptUnknown(this.store.getTurnAttempt(attemptId), "停止请求已保存,但无法确认刚启动轮次已停止。请核实执行记录。");
3745
+ throw error;
3746
+ }
3747
+ return turnId;
3748
+ }
3525
3749
  this.store.updateTurnAttempt(attemptId, {
3526
3750
  pendingTurnId: null,
3527
3751
  turnId,
3752
+ submissionState: "submitted",
3528
3753
  ...(attempt && isIncompleteTurnAttemptStatus(attempt.status) ? { status: "running" } : {}),
3529
3754
  });
3530
3755
  const latest = this.store.getSession(loaded.record.localSessionId);
3531
3756
  const alreadyTerminal = latest?.lastTurnId === turnId
3532
- && ["completed", "cancelled", "failed"].includes(latest.lastTurnStatus ?? "");
3757
+ && ["completed", "cancelled", "failed", "unknown"].includes(latest.lastTurnStatus ?? "");
3533
3758
  if (!alreadyTerminal) {
3534
3759
  this.store.updateSession(loaded.record.localSessionId, { status: "running" });
3535
3760
  this.store.updateRuntimeSession(loaded.record.localSessionId, { lastTurnId: turnId, lastTurnStatus: "running" });
@@ -3543,6 +3768,10 @@ export class ProxySessionController {
3543
3768
  }
3544
3769
  return turnId;
3545
3770
  }
3771
+ assertExecutionGeneration(sessionId, generation) {
3772
+ if (this.store.executionGeneration(sessionId) !== generation)
3773
+ throw new TurnStoppedBeforeSubmissionError();
3774
+ }
3546
3775
  async createSession(contextKey, agentName, cwd, announce, prepareTurn, prompt, replyTarget, requestedTitle, executionSettings = {}, activate = true) {
3547
3776
  const agent = this.ensureAgent(agentName);
3548
3777
  const resolvedExecutionSettings = mergeExecutionSettings(agent.defaults ?? {}, executionSettings);
@@ -3552,6 +3781,7 @@ export class ProxySessionController {
3552
3781
  ? createProjectlessWorkspace({ prompt: initialTitle }).cwd
3553
3782
  : path.resolve(cwd ?? this.config.defaults.cwd);
3554
3783
  const record = this.store.createSession({ localSessionId, contextKey, agentName, cwd: sessionCwd, status: "starting" });
3784
+ const executionGeneration = this.store.executionGeneration(localSessionId);
3555
3785
  if (initialTitle || resolvedExecutionSettings.modelProvider || resolvedExecutionSettings.model
3556
3786
  || resolvedExecutionSettings.reasoningEffort || resolvedExecutionSettings.permissionMode) {
3557
3787
  this.store.updateRuntimeSession(localSessionId, {
@@ -3583,6 +3813,8 @@ export class ProxySessionController {
3583
3813
  this.persistRuntimeSession(record, session, session.activeTurnId ? "running" : "ready");
3584
3814
  this.outbound.updateSessionModel(localSessionId, session.model, session.modelProvider);
3585
3815
  const saved = this.store.getSession(localSessionId) ?? record;
3816
+ if (prepareTurn)
3817
+ this.assertExecutionGeneration(localSessionId, executionGeneration);
3586
3818
  if (announce) {
3587
3819
  const task = initialTitle ? `${initialTitle}(${session.remoteSessionId})` : session.remoteSessionId;
3588
3820
  await this.outbound.sendText(contextKey, `已创建 ${agent.title} 任务:${task}`);
@@ -4020,6 +4252,25 @@ export class ProxySessionController {
4020
4252
  });
4021
4253
  }
4022
4254
  async handleRuntimeEvent(event) {
4255
+ if (event.type === "turn_started" || event.type === "turn_completed" || event.type === "turn_cancelled"
4256
+ || event.type === "turn_failed" || event.type === "turn_status_unknown") {
4257
+ const current = this.store.getSession(event.sessionId);
4258
+ if (event.type === "turn_started" && current?.status === "closed")
4259
+ return;
4260
+ const saved = turnViewSnapshot(this.store.getTurnSnapshot(event.turnId));
4261
+ const knownStatus = saved?.status ?? (current?.lastTurnId === event.turnId ? current.lastTurnStatus : undefined);
4262
+ if (knownStatus === "unknown" && event.type === "turn_started")
4263
+ return;
4264
+ const terminalStatus = event.type === "turn_completed" ? "completed"
4265
+ : event.type === "turn_cancelled" ? "cancelled" : event.type === "turn_failed" ? "failed" : undefined;
4266
+ if (knownStatus && ["completed", "cancelled", "failed"].includes(knownStatus)
4267
+ && (event.type === "turn_started" || event.type === "turn_status_unknown"
4268
+ || (terminalStatus && terminalStatus !== knownStatus && terminalStatus !== "completed")))
4269
+ return;
4270
+ if (event.type === "turn_started" && current?.lastTurnId && current.lastTurnId !== event.turnId
4271
+ && (saved || this.store.getTurnRuntimeOrigin(event.turnId)))
4272
+ return;
4273
+ }
4023
4274
  if ("turnId" in event) {
4024
4275
  const recoveryAttempt = this.recoveryRetryStartedAt.size > 0
4025
4276
  ? this.store.findIncompleteTurnAttemptByTurnId(event.turnId) : undefined;
@@ -4033,6 +4284,8 @@ export class ProxySessionController {
4033
4284
  }
4034
4285
  if (event.type === "turn_started") {
4035
4286
  const attempt = this.store.bindTurnAttempt(event.sessionId, event.turnId);
4287
+ if (attempt)
4288
+ this.store.provenance.bindLatestTurn(attempt.attemptId, event.turnId);
4036
4289
  const scheduledRun = attempt ? this.store.schedules.getRun(attempt.attemptId) : undefined;
4037
4290
  if (scheduledRun)
4038
4291
  this.store.schedules.saveRun({ ...scheduledRun, status: "running", turnId: event.turnId });
@@ -4064,20 +4317,11 @@ export class ProxySessionController {
4064
4317
  && Boolean(this.runtimes.forAgent(source.agentName).recoverResponseContinuation)
4065
4318
  && isResponseContinuationError(event.message);
4066
4319
  if (failedAttempt && responseContinuation) {
4067
- const retryAttempt = this.store.prepareTurnAttemptRetry(failedAttempt.attemptId, event.turnId);
4320
+ const retryAttempt = this.store.prepareTurnAttemptRetry(failedAttempt.attemptId, event.turnId, true);
4068
4321
  if (retryAttempt) {
4069
4322
  this.retriedFailureTurnIds.add(event.turnId);
4070
4323
  this.responseContinuations.set(event.sessionId, { turnId: event.turnId, abort: new AbortController() });
4071
- await this.retryFailedLlmTurn(event, retryAttempt, true);
4072
- return;
4073
- }
4074
- }
4075
- if (failedAttempt && !this.store.schedules.getRun(failedAttempt.attemptId) && !this.responseContinuations.has(event.sessionId)
4076
- && isRetryableLlmTurnFailure(event.message) && failedAttempt.retryCount < MAX_LLM_TURN_RETRIES) {
4077
- const retryAttempt = this.store.prepareTurnAttemptRetry(failedAttempt.attemptId, event.turnId);
4078
- if (retryAttempt) {
4079
- this.retriedFailureTurnIds.add(event.turnId);
4080
- await this.retryFailedLlmTurn(event, retryAttempt);
4324
+ await this.recoverFailedResponse(event, retryAttempt);
4081
4325
  return;
4082
4326
  }
4083
4327
  }
@@ -4100,10 +4344,26 @@ export class ProxySessionController {
4100
4344
  this.recoveredLiveAttempts.delete(attempt.attemptId);
4101
4345
  }
4102
4346
  this.store.markTurnAttemptTerminal(event.turnId, event.type === "turn_completed" ? "completed" : event.type === "turn_cancelled" ? "cancelled" : "failed");
4103
- this.store.updateRuntimeSession(event.sessionId, {
4104
- lastTurnId: event.turnId,
4105
- lastTurnStatus: event.type === "turn_completed" ? "completed" : event.type === "turn_cancelled" ? "cancelled" : "failed",
4106
- });
4347
+ const current = this.store.getSession(event.sessionId);
4348
+ if (!current?.lastTurnId || current.lastTurnId === event.turnId) {
4349
+ this.store.updateRuntimeSession(event.sessionId, {
4350
+ lastTurnId: event.turnId,
4351
+ lastTurnStatus: event.type === "turn_completed" ? "completed" : event.type === "turn_cancelled" ? "cancelled" : "failed",
4352
+ });
4353
+ }
4354
+ }
4355
+ else if (event.type === "turn_status_unknown") {
4356
+ const pending = this.store.findIncompleteTurnAttemptForSession(event.sessionId);
4357
+ const attempt = this.store.findIncompleteTurnAttemptByTurnId(event.turnId);
4358
+ if (attempt)
4359
+ this.store.updateTurnAttempt(attempt.attemptId, { status: "unknown" });
4360
+ const current = this.store.getSession(event.sessionId);
4361
+ if (!current?.lastTurnId || current.lastTurnId === event.turnId || pending?.pendingTurnId === event.turnId) {
4362
+ this.store.updateRuntimeSession(event.sessionId, { lastTurnId: event.turnId, lastTurnStatus: "unknown" });
4363
+ const active = current && this.runtimes.forAgent(current.agentName).getSession(event.sessionId)?.activeTurnId;
4364
+ if (current?.status !== "closed" && !active)
4365
+ this.store.updateSession(event.sessionId, { status: "ready" });
4366
+ }
4107
4367
  }
4108
4368
  const enrichedEvent = event.type === "context_compaction"
4109
4369
  ? {
@@ -4143,7 +4403,7 @@ export class ProxySessionController {
4143
4403
  const activeTurnId = latest
4144
4404
  ? this.runtimes.forAgent(latest.agentName).getSession(event.sessionId)?.activeTurnId
4145
4405
  : undefined;
4146
- if (latest?.lastTurnId === event.turnId && !activeTurnId) {
4406
+ if (latest?.lastTurnId === event.turnId && latest.status !== "closed" && !activeTurnId) {
4147
4407
  this.store.updateSession(event.sessionId, { status: event.type === "turn_failed" ? "failed" : "ready" });
4148
4408
  await this.applyPendingProviderWhenIdle(event.sessionId);
4149
4409
  await this.scheduleNextQueuedPrompt(event.sessionId);
@@ -4162,7 +4422,9 @@ export class ProxySessionController {
4162
4422
  this.store.markTurnAttemptTerminal(turnId, "completed");
4163
4423
  if (scheduledRun) {
4164
4424
  this.store.schedules.saveRun({ ...scheduledRun, status: "running" });
4165
- this.store.updateTurnAttempt(attempt.attemptId, { status: "recovering" });
4425
+ this.store.updateTurnAttempt(attempt.attemptId, {
4426
+ status: "recovering", turnId: null, submissionState: "not_submitted", recoveredFromTurnId: turnId,
4427
+ });
4166
4428
  }
4167
4429
  this.store.updateRuntimeSession(sessionId, { lastTurnId: turnId, lastTurnStatus: "completed" });
4168
4430
  let continued = false;
@@ -4194,6 +4456,8 @@ export class ProxySessionController {
4194
4456
  if (this.planHandoffs.get(sessionId) !== turnId || this.sessionResets.has(sessionId))
4195
4457
  return;
4196
4458
  nextTurnId = await this.startTurnNow(loaded, "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.", attempt.replyMessageId ? { messageId: attempt.replyMessageId, replyInThread: true } : undefined, undefined, { messageId: attempt.messageId, displayPrompt: "方案已确认,继续执行", approvedPlanTurnId: turnId,
4459
+ executionGeneration: attempt.executionGeneration,
4460
+ trigger: "plan_handoff", parentSourceTurnId: turnId,
4197
4461
  ...(scheduledRun ? { attemptId: attempt.attemptId, scheduleRunId: attempt.attemptId } : {}) });
4198
4462
  }
4199
4463
  continued = true;
@@ -4207,15 +4471,17 @@ export class ProxySessionController {
4207
4471
  });
4208
4472
  }
4209
4473
  catch (error) {
4210
- failed = true;
4211
- this.logger.error({ error, sessionId, turnId }, "Failed to continue an approved plan.");
4212
- await this.outbound.sendText(attempt.contextKey, "方案已确认,但后续执行启动失败:" + runtimeErrorMessage(error) + "。请发送消息继续。");
4474
+ failed = !(error instanceof TurnStoppedBeforeSubmissionError);
4475
+ if (failed) {
4476
+ this.logger.error({ error, sessionId, turnId }, "Failed to continue an approved plan.");
4477
+ await this.outbound.sendText(attempt.contextKey, "方案已确认,但后续执行启动失败:" + runtimeErrorMessage(error) + "。请发送消息继续。");
4478
+ }
4213
4479
  }
4214
4480
  finally {
4215
4481
  if (this.planHandoffs.get(sessionId) === turnId)
4216
4482
  this.planHandoffs.delete(sessionId);
4217
4483
  if (!continued) {
4218
- if (scheduledRun) {
4484
+ if (scheduledRun && this.store.getTurnAttempt(attempt.attemptId)?.status !== "unknown") {
4219
4485
  this.store.updateTurnAttempt(attempt.attemptId, { status: failed ? "failed" : "cancelled" });
4220
4486
  this.store.schedules.finish(attempt.attemptId, failed ? "failed" : "cancelled");
4221
4487
  }
@@ -4236,7 +4502,7 @@ export class ProxySessionController {
4236
4502
  await this.scheduleNextQueuedPrompt(sessionId);
4237
4503
  }
4238
4504
  }
4239
- async retryFailedLlmTurn(event, attempt, responseContinuation = false) {
4505
+ async recoverFailedResponse(event, attempt) {
4240
4506
  const retryNumber = attempt.retryCount;
4241
4507
  const session = this.store.getSession(event.sessionId);
4242
4508
  if (!session || session.status === "closed") {
@@ -4252,16 +4518,14 @@ export class ProxySessionController {
4252
4518
  attemptId: attempt.attemptId,
4253
4519
  failedTurnId: event.turnId,
4254
4520
  retryNumber,
4255
- maxRetries: responseContinuation ? 1 : MAX_LLM_TURN_RETRIES,
4256
- responseContinuation,
4521
+ maxRetries: 1,
4522
+ responseContinuation: true,
4257
4523
  error: event.message,
4258
4524
  });
4259
4525
  try {
4260
4526
  await this.outbound.onEvent({
4261
4527
  ...event,
4262
- message: responseContinuation
4263
- ? `${event.message}\n\n模型续接状态失效,正在恢复连接并继续(1/1)。`
4264
- : `${event.message}\n\n检测到临时模型服务错误,正在自动重试(${retryNumber}/${MAX_LLM_TURN_RETRIES})。`,
4528
+ message: `${event.message}\n\n模型续接状态失效,正在恢复连接并继续(1/1)。`,
4265
4529
  });
4266
4530
  }
4267
4531
  catch (error) {
@@ -4273,27 +4537,31 @@ export class ProxySessionController {
4273
4537
  try {
4274
4538
  const current = this.store.getSession(session.localSessionId) ?? session;
4275
4539
  const loaded = await this.loadSession(current, Boolean(this.store.getPendingProviderSettings(current.localSessionId)));
4276
- const retryTurnId = await this.startTurn(loaded, responseContinuation ? "" : llmRetryRuntimePrompt(attempt.promptText, retryNumber), replyTarget, responseContinuation ? undefined : attempt.localImagePaths, {
4540
+ const retryTurnId = await this.startTurn(loaded, "", replyTarget, undefined, {
4277
4541
  attemptId: attempt.attemptId,
4542
+ executionGeneration: attempt.executionGeneration,
4543
+ trigger: "response_continuation", parentSourceTurnId: event.turnId,
4278
4544
  messageId: attempt.messageId,
4279
- displayPrompt: responseContinuation ? `恢复模型续接:${attempt.promptText}` : llmRetryCardPrompt(attempt.promptText, retryNumber),
4545
+ displayPrompt: `恢复模型续接:${attempt.promptText}`,
4280
4546
  preserveAttemptOnFailure: true,
4281
- ...(responseContinuation ? { responseContinuationTurnId: event.turnId } : {}),
4547
+ responseContinuationTurnId: event.turnId,
4282
4548
  });
4283
4549
  this.store.rebindPendingTurnMessages(session.localSessionId, event.turnId, retryTurnId);
4284
4550
  }
4285
4551
  catch (error) {
4286
- const aborted = responseContinuation && !this.responseContinuations.has(session.localSessionId);
4552
+ const aborted = !this.responseContinuations.has(session.localSessionId);
4553
+ if (this.store.getTurnAttempt(attempt.attemptId)?.status === "unknown")
4554
+ return;
4287
4555
  this.store.updateTurnAttempt(attempt.attemptId, { status: aborted ? "cancelled" : "failed" });
4288
4556
  const latest = this.store.getSession(session.localSessionId);
4289
- if (!responseContinuation || (latest?.lastTurnId === event.turnId && latest.status !== "closed")) {
4557
+ if (latest?.lastTurnId === event.turnId && latest.status !== "closed") {
4290
4558
  this.store.updateSession(session.localSessionId, { status: aborted ? "ready" : "failed" });
4291
4559
  }
4292
4560
  await this.finalizeTurnMessageReactions(event.turnId, aborted ? "cancelled" : "failed").catch((reactionError) => {
4293
4561
  this.logger.warn({ error: reactionError, sessionId: session.localSessionId, turnId: event.turnId }, "Failed to finalize reactions after an LLM retry could not start.");
4294
4562
  });
4295
4563
  this.logger.error({ error, sessionId: session.localSessionId, retryNumber }, "Failed to start an automatic LLM turn retry.");
4296
- if (responseContinuation && !aborted) {
4564
+ if (!aborted) {
4297
4565
  await this.outbound.sendText(attempt.contextKey, `模型续接恢复未能启动:${displayRuntimeError(runtimeErrorMessage(error))}。请发送消息继续。`);
4298
4566
  }
4299
4567
  await this.scheduleNextQueuedPrompt(session.localSessionId);
@@ -4340,8 +4608,13 @@ export class ProxySessionController {
4340
4608
  return this.settingsOperations.run(sessionId, () => this.startNextQueuedPromptIfIdleNow(sessionId));
4341
4609
  }
4342
4610
  async startNextQueuedPromptIfIdleNow(sessionId) {
4611
+ const executionGeneration = this.store.executionGeneration(sessionId);
4343
4612
  if (this.planHandoffs.has(sessionId) || this.sessionResets.has(sessionId))
4344
4613
  return;
4614
+ if (this.store.hasUnknownTurnAttemptForSession(sessionId))
4615
+ return;
4616
+ if (this.store.hasCancellationRequestedForSession(sessionId))
4617
+ return;
4345
4618
  if (this.store.countQueuedPrompts(sessionId) === 0)
4346
4619
  return;
4347
4620
  const queuedHead = this.store.peekQueuedPrompt(sessionId);
@@ -4363,6 +4636,7 @@ export class ProxySessionController {
4363
4636
  await this.applyPendingProviderSettings(loaded);
4364
4637
  if (this.store.getPendingProviderSettings(sessionId))
4365
4638
  return;
4639
+ this.assertExecutionGeneration(sessionId, executionGeneration);
4366
4640
  prompt = this.store.takeNextQueuedPrompt(sessionId);
4367
4641
  if (!prompt)
4368
4642
  return;
@@ -4390,12 +4664,25 @@ export class ProxySessionController {
4390
4664
  throw error;
4391
4665
  }
4392
4666
  }
4393
- const turnId = await this.startTurnNow(loaded, prompt.text, prompt.replyMessageId ? { messageId: prompt.replyMessageId, replyInThread: true } : undefined, prompt.localImagePaths, { messageId: prompt.messageId, displayPrompt: prompt.displayPrompt,
4667
+ const turnId = await this.startTurnNow(loaded, prompt.text, prompt.replyMessageId ? { messageId: prompt.replyMessageId, replyInThread: true } : undefined, prompt.localImagePaths, { messageId: prompt.messageId, displayPrompt: prompt.displayPrompt, executionGeneration,
4668
+ trigger: scheduledRun ? "schedule" : "queue", instructionId: prompt.promptId,
4394
4669
  ...(scheduledRun ? { attemptId: prompt.promptId, scheduleRunId: prompt.promptId } : {}) });
4395
4670
  if (prompt.messageId)
4396
4671
  await this.bindMessageReactionToTurn(prompt.messageId, sessionId, turnId);
4397
4672
  }
4398
4673
  catch (error) {
4674
+ if (error instanceof TurnStoppedBeforeSubmissionError) {
4675
+ if (prompt) {
4676
+ this.store.enqueuePrompt(prompt);
4677
+ const run = this.store.schedules.getRun(prompt.promptId);
4678
+ if (run) {
4679
+ this.store.schedules.saveRun({ ...run, status: "queued" });
4680
+ this.store.updateTurnAttempt(run.id, { status: "accepted", executionGeneration: this.store.executionGeneration(sessionId) });
4681
+ }
4682
+ await this.refreshPromptQueueCards(sessionId);
4683
+ }
4684
+ return;
4685
+ }
4399
4686
  if (prompt) {
4400
4687
  const run = this.store.schedules.getRun(prompt.promptId);
4401
4688
  if (run && ["dispatching", "submitting"].includes(run.status)) {
@@ -4561,13 +4848,17 @@ export class ProxySessionController {
4561
4848
  }
4562
4849
  async cancel(contextKey) {
4563
4850
  const record = this.requireCurrentSession(contextKey);
4564
- await this.outbound.sendText(contextKey, STOP_TASK_STARTED_MESSAGE);
4565
4851
  await this.cancelSession(record);
4566
4852
  }
4567
4853
  async cancelSession(record) {
4854
+ this.store.requestSessionExecutionStop(record.localSessionId);
4855
+ const stopGeneration = this.store.executionGeneration(record.localSessionId);
4568
4856
  this.responseContinuations.get(record.localSessionId)?.abort.abort();
4569
4857
  this.responseContinuations.delete(record.localSessionId);
4570
4858
  this.planHandoffs.delete(record.localSessionId);
4859
+ await this.outbound.sendText(record.contextKey, STOP_TASK_STARTED_MESSAGE).catch((error) => {
4860
+ this.logger.warn({ error, sessionId: record.localSessionId }, "Failed to deliver the stop acknowledgement; still sending interrupt.");
4861
+ });
4571
4862
  const runtime = this.runtimes.forAgent(record.agentName);
4572
4863
  if (runtime.kind === "codex" && record.remoteSessionId && runtime.interruptRemoteTurn) {
4573
4864
  if (runtime.getGoal && runtime.setGoal) {
@@ -4599,16 +4890,19 @@ export class ProxySessionController {
4599
4890
  }
4600
4891
  }
4601
4892
  if (!turnId) {
4893
+ this.finishUnsubmittedStops(record.localSessionId);
4602
4894
  await this.outbound.sendText(record.contextKey, "当前没有正在执行的任务。");
4603
4895
  return;
4604
4896
  }
4605
- const cancellationAttempt = this.store.requestTurnAttemptCancellation(turnId);
4897
+ const latestAttempt = this.store.findIncompleteTurnAttemptByTurnId(turnId);
4898
+ if (latestAttempt && latestAttempt.executionGeneration >= stopGeneration)
4899
+ return;
4900
+ this.store.requestTurnAttemptCancellation(turnId);
4606
4901
  try {
4607
4902
  await runtime.interruptRemoteTurn(record.remoteSessionId, turnId);
4608
4903
  }
4609
4904
  catch (error) {
4610
- if (cancellationAttempt)
4611
- this.store.restoreTurnAttemptAfterCancellationFailure(cancellationAttempt);
4905
+ // Keep the durable stop intent even when the interrupt response is lost.
4612
4906
  throw error;
4613
4907
  }
4614
4908
  this.store.audit(record.contextKey, "turn_interrupt_sent", {
@@ -4622,19 +4916,29 @@ export class ProxySessionController {
4622
4916
  const loaded = await this.loadSession(record);
4623
4917
  const turnId = loaded.session.activeTurnId;
4624
4918
  if (!turnId) {
4919
+ this.finishUnsubmittedStops(record.localSessionId);
4625
4920
  await this.outbound.sendText(record.contextKey, "当前没有正在执行的任务。");
4626
4921
  return;
4627
4922
  }
4628
- const cancellationAttempt = this.store.requestTurnAttemptCancellation(turnId);
4923
+ const latestAttempt = this.store.findIncompleteTurnAttemptByTurnId(turnId);
4924
+ if (latestAttempt && latestAttempt.executionGeneration >= stopGeneration)
4925
+ return;
4926
+ this.store.requestTurnAttemptCancellation(turnId);
4629
4927
  try {
4630
4928
  await loaded.runtime.cancelTurn(record.localSessionId, turnId);
4631
4929
  }
4632
4930
  catch (error) {
4633
- if (cancellationAttempt)
4634
- this.store.restoreTurnAttemptAfterCancellationFailure(cancellationAttempt);
4931
+ // Keep the durable stop intent even when the interrupt response is lost.
4635
4932
  throw error;
4636
4933
  }
4637
4934
  }
4935
+ finishUnsubmittedStops(sessionId) {
4936
+ for (const attempt of this.store.listCancellationRequestedTurnAttempts()) {
4937
+ if (attempt.localSessionId === sessionId && attempt.submissionState === "not_submitted") {
4938
+ this.store.updateTurnAttempt(attempt.attemptId, { status: "cancelled" });
4939
+ }
4940
+ }
4941
+ }
4638
4942
  async resetCurrentSessionToTurn(contextKey, sessionId, turnId) {
4639
4943
  if (!sessionId || !turnId)
4640
4944
  throw new Error("无效的 Reset 请求。请使用最新的思考卡片重试。");
@@ -5006,7 +5310,7 @@ export class ProxySessionController {
5006
5310
  `模型 ${cardCode(session.model ?? settings.model)}`,
5007
5311
  `思考强度 ${cardCode(session.reasoningEffort ?? settings.effort)}`,
5008
5312
  `权限 ${cardCode(session.permissionMode)}`,
5009
- `并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
5313
+ "只影响当前任务,从下一次请求生效。",
5010
5314
  ].join(",");
5011
5315
  if (options.updateMessageId) {
5012
5316
  await this.openExecutionSettingsNow(contextKey, "provider", {
@@ -5027,7 +5331,7 @@ export class ProxySessionController {
5027
5331
  throw new Error("当前运行时不支持 Provider 设置。");
5028
5332
  loaded.session = loaded.runtime.getSession(loaded.record.localSessionId) ?? loaded.session;
5029
5333
  const remoteSessionId = loaded.session.remoteSessionId;
5030
- const persist = (candidate, replacement) => this.agentDefaultsOperations.run(loaded.record.agentName, async () => {
5334
+ const persist = async (candidate, replacement) => {
5031
5335
  if (candidate.remoteSessionId !== remoteSessionId) {
5032
5336
  const saved = this.store.getSession(loaded.record.localSessionId);
5033
5337
  if (replacement?.emptyRemoteSessionId !== remoteSessionId || !saved || saved.remoteSessionId !== remoteSessionId
@@ -5039,24 +5343,14 @@ export class ProxySessionController {
5039
5343
  }
5040
5344
  }
5041
5345
  assertProviderSettingsApplied(candidate, settings);
5042
- const agent = this.ensureAgent(loaded.record.agentName);
5043
- const previousDefaults = agent.defaults;
5044
- await this.persistAgentExecutionDefaultsNow(loaded.record.localSessionId, candidate);
5045
- try {
5046
- this.store.updateRuntimeSession(loaded.record.localSessionId, {
5047
- remoteSessionId: candidate.remoteSessionId,
5048
- modelProvider: candidate.modelProvider,
5049
- model: candidate.model,
5050
- reasoningEffort: candidate.reasoningEffort,
5051
- permissionMode: candidate.permissionMode,
5052
- });
5053
- }
5054
- catch (error) {
5055
- await this.lifecycle?.persistAgentExecutionDefaults?.(loaded.record.agentName, previousDefaults ?? {});
5056
- agent.defaults = previousDefaults;
5057
- throw error;
5058
- }
5059
- });
5346
+ this.store.updateRuntimeSession(loaded.record.localSessionId, {
5347
+ remoteSessionId: candidate.remoteSessionId,
5348
+ modelProvider: candidate.modelProvider,
5349
+ model: candidate.model,
5350
+ reasoningEffort: candidate.reasoningEffort,
5351
+ permissionMode: candidate.permissionMode,
5352
+ });
5353
+ };
5060
5354
  const session = await loaded.runtime.setExecutionSettings(loaded.record.localSessionId, settings, persist);
5061
5355
  loaded.record = this.store.getSession(loaded.record.localSessionId) ?? loaded.record;
5062
5356
  this.settingsOnlySessions.delete(loaded.record.localSessionId);
@@ -5272,7 +5566,6 @@ export class ProxySessionController {
5272
5566
  }
5273
5567
  this.store.updateRuntimeSession(loaded.record.localSessionId, { model, reasoningEffort: nextEffort });
5274
5568
  this.outbound.updateSessionModel(loaded.record.localSessionId, model, loaded.session.modelProvider);
5275
- await this.persistAgentExecutionDefaults(loaded.record.localSessionId);
5276
5569
  });
5277
5570
  const effortMessage = nextEffort && nextEffort !== currentEffort
5278
5571
  ? `,思考强度已自动调整为 ${nextEffort}`
@@ -5281,11 +5574,11 @@ export class ProxySessionController {
5281
5574
  await this.openExecutionSettingsNow(contextKey, "model", {
5282
5575
  sessionId: loaded.record.localSessionId,
5283
5576
  updateMessageId: options.updateMessageId,
5284
- notice: `模型已切换为 ${cardCode(model)}${effortMessage},并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
5577
+ notice: `模型已切换为 ${cardCode(model)}${effortMessage},只影响当前任务,从下一次请求生效。`,
5285
5578
  });
5286
5579
  return;
5287
5580
  }
5288
- await this.outbound.sendText(contextKey, `模型已切换为 ${model}${effortMessage},并已保存为 ${loaded.record.agentName} Agent 的默认设置,从下一次请求生效。`);
5581
+ await this.outbound.sendText(contextKey, `模型已切换为 ${model}${effortMessage},只影响当前任务,从下一次请求生效。`);
5289
5582
  }
5290
5583
  async goal(contextKey, command) {
5291
5584
  const objective = command.action === "set" || command.action === "edit" ? command.objective : undefined;
@@ -5678,17 +5971,16 @@ export class ProxySessionController {
5678
5971
  await this.sessionHydrationOperations.run(loaded.record.localSessionId, async () => {
5679
5972
  await loaded.runtime.setReasoningEffort(loaded.record.localSessionId, effort);
5680
5973
  this.store.updateRuntimeSession(loaded.record.localSessionId, { reasoningEffort: effort });
5681
- await this.persistAgentExecutionDefaults(loaded.record.localSessionId);
5682
5974
  });
5683
5975
  if (options.updateMessageId) {
5684
5976
  await this.openExecutionSettingsNow(contextKey, "thinking", {
5685
5977
  sessionId: loaded.record.localSessionId,
5686
5978
  updateMessageId: options.updateMessageId,
5687
- notice: `思考强度已切换为 ${cardCode(effort)},并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
5979
+ notice: `思考强度已切换为 ${cardCode(effort)},只影响当前任务,从下一次请求生效。`,
5688
5980
  });
5689
5981
  return;
5690
5982
  }
5691
- await this.outbound.sendText(contextKey, `思考强度已切换为 ${effort},并已保存为 ${loaded.record.agentName} Agent 的默认设置,从下一次请求生效。`);
5983
+ await this.outbound.sendText(contextKey, `思考强度已切换为 ${effort},只影响当前任务,从下一次请求生效。`);
5692
5984
  }
5693
5985
  async permissions(contextKey, mode, options = {}) {
5694
5986
  const record = options.sessionId ? this.requireSession(contextKey, options.sessionId) : this.requireCurrentSession(contextKey);
@@ -5713,21 +6005,20 @@ export class ProxySessionController {
5713
6005
  loaded.session = loaded.runtime.getSession(record.localSessionId) ?? loaded.session;
5714
6006
  loaded.session.permissionMode = mode;
5715
6007
  this.store.updateRuntimeSession(record.localSessionId, { permissionMode: mode });
5716
- await this.persistAgentExecutionDefaults(record.localSessionId);
5717
6008
  });
5718
6009
  if (options.updateMessageId) {
5719
6010
  await this.openExecutionSettingsNow(contextKey, "permission", {
5720
6011
  sessionId: loaded.record.localSessionId,
5721
6012
  updateMessageId: options.updateMessageId,
5722
6013
  notice: mode === "auto"
5723
- ? `已切换为自动执行模式,并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`
5724
- : `已切换为执行前确认模式,并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
6014
+ ? "已切换为自动执行模式,只影响当前任务,从下一次请求生效。"
6015
+ : "已切换为执行前确认模式,只影响当前任务,从下一次请求生效。",
5725
6016
  });
5726
6017
  return;
5727
6018
  }
5728
6019
  await this.outbound.sendText(contextKey, mode === "auto"
5729
- ? `已切换为自动执行模式,并已保存为 ${loaded.record.agentName} Agent 的默认设置。`
5730
- : `已切换为执行前确认模式,并已保存为 ${loaded.record.agentName} Agent 的默认设置。`);
6020
+ ? "已切换为自动执行模式,只影响当前任务,从下一次请求生效。"
6021
+ : "已切换为执行前确认模式,只影响当前任务,从下一次请求生效。");
5731
6022
  }
5732
6023
  taskTurnIds(current) {
5733
6024
  const ids = this.store.listTaskTurnGraphIndex(current.localSessionId).map((turn) => turn.turnId);
@@ -5873,7 +6164,7 @@ export class ProxySessionController {
5873
6164
  }
5874
6165
  if (current.lastTurnStatus === "running" && current.lastTurnId === turnId
5875
6166
  && !this.store.getTurnPromptSummary(turnId)) {
5876
- await this.outbound.sendInteractiveCard(contextKey, this.cardRenderer.renderTurnDetails(this.runningTurnSnapshot(current, turnId)));
6167
+ await this.outbound.sendInteractiveCard(contextKey, this.cardRenderer.renderTurnDetails(this.runningTurnSnapshot(current, turnId), undefined, this.store.provenance.forTurn(turnId, current.localSessionId)));
5877
6168
  return;
5878
6169
  }
5879
6170
  await this.loadTurnDetails(turnId);
@@ -6436,7 +6727,7 @@ export class ProxySessionController {
6436
6727
  projectActions,
6437
6728
  cardEntry: {
6438
6729
  reference: entry.reference,
6439
- summary: `${offset + index + 1}. ${marker}${title} · ${entry.agentName}`,
6730
+ summary: `${offset + index + 1}. ${marker}${title} · ${entry.agentName}${entry.status === "待核实" ? " · 待核实" : ""}`,
6440
6731
  detailLines: [
6441
6732
  `**最新 Prompt**:${cardText(lastUserPrompt)}`,
6442
6733
  `<font color='grey'>最近更新:${cardText(entry.updatedLabel)}</font>`,
@@ -6973,11 +7264,11 @@ export class ProxySessionController {
6973
7264
  queued = this.store.countQueuedPrompts(current.localSessionId);
6974
7265
  snapshot = turnViewSnapshot(current.lastTurnId ? this.store.getTurnSnapshot(current.lastTurnId) : undefined);
6975
7266
  const waitingForApproval = snapshot?.turnId === current.lastTurnId && snapshot?.status === "waiting_for_approval";
6976
- const statusLabel = waitingForApproval ? "等待确认"
7267
+ const statusLabel = current.lastTurnStatus === "unknown" ? "待核实" : waitingForApproval ? "等待确认"
6977
7268
  : remoteActive && remote && localCurrent && !isBotOwnedActiveTurn(localCurrent, remote)
6978
7269
  ? "外部执行中"
6979
7270
  : sessionStatusLabel(current.status, activeTurnId);
6980
- const resultLabel = waitingForApproval ? "等待确认" : remoteActive
7271
+ const resultLabel = current.lastTurnStatus === "unknown" ? "待核实" : waitingForApproval ? "等待确认" : remoteActive
6981
7272
  ? "执行中"
6982
7273
  : remoteTurnStatusLabel(remote?.lastTurnStatus ?? current.lastTurnStatus);
6983
7274
  taskLines.push(`**标题**:${cardCode(current.title ?? "未命名任务")}`, `**工作目录**:${cardCode(current.cwd)}`, `**Provider / 模型 / 思考强度**:${cardCode(current.modelProvider ?? "Agent 默认")} / ${cardCode(current.model ?? "默认")} / ${cardCode(current.reasoningEffort ?? "自动")}`, `**状态 / 最近结果**:${statusLabel} / ${resultLabel}`, `**Agent**:${cardCode(agent.title)}`, `**权限 / 任务范围**:${current.permissionMode === "confirm" ? "执行前确认" : "自动执行"} / ${detectProjectlessWorkspace(current.cwd) ? "未指定项目" : "指定项目"}`, `**App Server 任务 ID**:${cardCode(current.remoteSessionId ?? "尚未创建")}`, statusTaskMetricsLine(metrics?.turnCount ?? this.store.countTaskTurns(current.localSessionId), metrics?.storageBytes), `**当前执行 / 排队消息**:${activeTurnId ? cardCode(activeTurnId) : "无"} / ${queued} 条`, `**创建时间 / 最近活动**:${formatStatusTime(current.createdAt)} / ${formatStatusTime(current.updatedAt)}`);
@@ -6991,12 +7282,10 @@ export class ProxySessionController {
6991
7282
  ...(current ? [{
6992
7283
  title: "最终结果",
6993
7284
  lines: finalResultLines(snapshot, remote),
6994
- localImages: true,
6995
7285
  }] : []),
6996
7286
  ...(current ? [{
6997
7287
  title: "执行详情",
6998
7288
  lines: executionDetailLines(localCurrent ?? current, snapshot, remote, activeTurnId, queued),
6999
- localImages: true,
7000
7289
  collapsible: true,
7001
7290
  elementId: "status_execution_details",
7002
7291
  }] : []),
@@ -7077,7 +7366,7 @@ export class ProxySessionController {
7077
7366
  `**创建时间 / 最近活动**:${formatRemoteTime(remote.createdAt)} / ${formatRemoteTime(latestRemoteTimestamp(remote.recencyAt, remote.updatedAt))}`,
7078
7367
  ],
7079
7368
  },
7080
- { title: "最终结果", lines: finalResultLines(undefined, remote), localImages: true },
7369
+ { title: "最终结果", lines: finalResultLines(undefined, remote) },
7081
7370
  {
7082
7371
  title: "执行详情",
7083
7372
  lines: [
@@ -7086,7 +7375,6 @@ export class ProxySessionController {
7086
7375
  ? "外部 Agent 正在执行;Agent Bot 只读取状态,不会接管。"
7087
7376
  : `发送 **/switch ${cardText(remote.id)}** 切换到此任务。`,
7088
7377
  ],
7089
- localImages: true,
7090
7378
  collapsible: true,
7091
7379
  elementId: "status_execution_details",
7092
7380
  },
@@ -7195,28 +7483,6 @@ export class ProxySessionController {
7195
7483
  throw new Error(`未知 agent:${agentName}`);
7196
7484
  return agent;
7197
7485
  }
7198
- async persistAgentExecutionDefaults(localSessionId, candidate) {
7199
- const record = this.store.getSession(localSessionId);
7200
- if (!record)
7201
- throw new Error(`找不到任务:${localSessionId}`);
7202
- return this.agentDefaultsOperations.run(record.agentName, () => this.persistAgentExecutionDefaultsNow(localSessionId, candidate));
7203
- }
7204
- async persistAgentExecutionDefaultsNow(localSessionId, candidate) {
7205
- const record = this.store.getSession(localSessionId);
7206
- if (!record)
7207
- throw new Error(`找不到任务:${localSessionId}`);
7208
- const session = candidate ?? record;
7209
- const agent = this.ensureAgent(session.agentName);
7210
- const observed = {
7211
- ...(session.modelProvider?.trim() ? { modelProvider: session.modelProvider } : {}),
7212
- ...(session.model?.trim() ? { model: session.model } : {}),
7213
- ...(session.reasoningEffort?.trim() ? { reasoningEffort: session.reasoningEffort } : {}),
7214
- ...(session.permissionMode ? { permissionMode: session.permissionMode } : {}),
7215
- };
7216
- const defaults = { ...(agent.defaults ?? {}), ...observed };
7217
- await this.lifecycle?.persistAgentExecutionDefaults?.(session.agentName, defaults);
7218
- agent.defaults = defaults;
7219
- }
7220
7486
  agentLabel(agentName) {
7221
7487
  return this.ensureAgent(agentName).title;
7222
7488
  }
@@ -7824,9 +8090,11 @@ function mergeTaskList(localSessions, remoteSessions, currentLocalSessionId, lat
7824
8090
  if (local)
7825
8091
  representedLocalIds.add(local.localSessionId);
7826
8092
  const active = remote.status === "active" || remote.lastTurnStatus === "inProgress";
7827
- const status = remote.status === "active" || remote.lastTurnStatus === "inProgress"
7828
- ? local && isBotOwnedActiveTurn(local, remote) ? "执行中" : "外部执行中"
7829
- : remoteSessionStatusLabel(remote.status);
8093
+ const status = local?.lastTurnStatus === "unknown"
8094
+ && (!remote.lastTurnStatus || remote.lastTurnId !== local.lastTurnId) ? "待核实"
8095
+ : remote.status === "active" || remote.lastTurnStatus === "inProgress"
8096
+ ? local && isBotOwnedActiveTurn(local, remote) ? "执行中" : "外部执行中"
8097
+ : remoteSessionStatusLabel(remote.status);
7830
8098
  const recencyAt = remote.recencyAt ?? remote.updatedAt;
7831
8099
  return {
7832
8100
  reference: remoteSessionReference(agentName, remote.id),
@@ -7856,7 +8124,7 @@ function mergeTaskList(localSessions, remoteSessions, currentLocalSessionId, lat
7856
8124
  agentName: local.agentName,
7857
8125
  title: local.title ?? "未命名任务",
7858
8126
  cwd: local.cwd,
7859
- status: sessionStatusLabel(local.status),
8127
+ status: local.lastTurnStatus === "unknown" ? "待核实" : sessionStatusLabel(local.status),
7860
8128
  active: local.status === "running",
7861
8129
  current: local.localSessionId === currentLocalSessionId,
7862
8130
  lastUserPrompt: latestLocalUserPrompts.get(local.localSessionId),
@@ -8056,6 +8324,7 @@ function remoteTurnStatusLabel(status) {
8056
8324
  failed: "失败",
8057
8325
  running: "执行中",
8058
8326
  cancelled: "已停止",
8327
+ unknown: "待核实",
8059
8328
  };
8060
8329
  return status ? labels[status] ?? status : "尚无执行记录";
8061
8330
  }
@@ -8072,6 +8341,7 @@ function turnViewStatusLabel(status) {
8072
8341
  running: "执行中",
8073
8342
  tool_running: "工具执行中",
8074
8343
  waiting_for_approval: "等待确认",
8344
+ unknown: "待核实",
8075
8345
  completed: "已完成",
8076
8346
  cancelled: "已停止",
8077
8347
  failed: "失败",
@@ -8169,6 +8439,9 @@ function mapRemoteTurnStatus(status) {
8169
8439
  function mergeRemoteTaskStatus(record, remote) {
8170
8440
  if (!remote)
8171
8441
  return record;
8442
+ if (record.lastTurnStatus === "unknown"
8443
+ && (!remote.lastTurnStatus || remote.lastTurnId !== record.lastTurnId))
8444
+ return record;
8172
8445
  const remoteTurnStatus = mapRemoteTurnStatus(remote.lastTurnStatus);
8173
8446
  const createdAt = remote.createdAt === undefined
8174
8447
  ? record.createdAt
@@ -8557,28 +8830,9 @@ function selectProviderReasoningEffort(model, previousEffort) {
8557
8830
  function recoveryCardPrompt(prompt) {
8558
8831
  return `恢复重启前的任务:${prompt}`;
8559
8832
  }
8560
- function recoveryRuntimePrompt(prompt) {
8561
- return [
8562
- "Agent Bot restarted while the previous turn was still running.",
8563
- "Continue the unfinished task in the current task and workspace.",
8564
- "Inspect the existing conversation, files, and completed tool effects first. Do not repeat completed or irreversible actions.",
8565
- "Finish the original request:",
8566
- "",
8567
- prompt,
8568
- ].join("\n");
8569
- }
8570
8833
  function llmRetryCardPrompt(prompt, retryNumber) {
8571
8834
  return `自动重试 ${retryNumber}/${MAX_LLM_TURN_RETRIES}:${prompt}`;
8572
8835
  }
8573
- function llmRetryRuntimePrompt(prompt, retryNumber) {
8574
- return [
8575
- `Agent Bot is automatically retrying this request after a transient LLM service failure (${retryNumber}/${MAX_LLM_TURN_RETRIES}).`,
8576
- "Continue in the current task and workspace. Inspect the conversation, files, and completed tool effects before acting.",
8577
- "Do not repeat completed or irreversible actions. Finish the original request:",
8578
- "",
8579
- prompt,
8580
- ].join("\n");
8581
- }
8582
8836
  function isRetryableLlmTurnFailure(message) {
8583
8837
  const normalized = message.trim().toLowerCase();
8584
8838
  if (!normalized)
@@ -8607,15 +8861,7 @@ function isRetryableLlmTurnFailure(message) {
8607
8861
  ].some((pattern) => pattern.test(normalized));
8608
8862
  }
8609
8863
  function remoteTurnMatchesAttempt(remote, attempt) {
8610
- if (!remote?.lastTurnId)
8611
- return false;
8612
- if (attempt.turnId)
8613
- return remote.lastTurnId === attempt.turnId;
8614
- const remoteUpdatedAt = remote.updatedAt === undefined ? undefined : normalizeRemoteTimestamp(remote.updatedAt);
8615
- const acceptedAt = Date.parse(attempt.createdAt);
8616
- return remoteUpdatedAt !== undefined
8617
- && Number.isFinite(acceptedAt)
8618
- && remoteUpdatedAt >= acceptedAt - 1_000;
8864
+ return Boolean(attempt.turnId && remote?.lastTurnId === attempt.turnId);
8619
8865
  }
8620
8866
  function isRecoveryAttemptRecent(attempt, cutoff) {
8621
8867
  const updatedAt = Date.parse(attempt.updatedAt);