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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +60 -5
  3. package/README.zh.md +60 -5
  4. package/config.example.yaml +1 -3
  5. package/dist/cli/controlProtocol.js.map +1 -1
  6. package/dist/cli/help.js +14 -0
  7. package/dist/cli/help.js.map +1 -1
  8. package/dist/cli.js +32 -0
  9. package/dist/cli.js.map +1 -1
  10. package/dist/codex/CodexRuntime.js +15 -5
  11. package/dist/codex/CodexRuntime.js.map +1 -1
  12. package/dist/commands/CommandRouter.js +7 -0
  13. package/dist/commands/CommandRouter.js.map +1 -1
  14. package/dist/config/SettingsStore.js +341 -0
  15. package/dist/config/SettingsStore.js.map +1 -0
  16. package/dist/config/loadConfig.js +1 -2
  17. package/dist/config/loadConfig.js.map +1 -1
  18. package/dist/config/schema.js +0 -1
  19. package/dist/config/schema.js.map +1 -1
  20. package/dist/console/ConsoleTurnPresenter.js +3 -0
  21. package/dist/console/ConsoleTurnPresenter.js.map +1 -1
  22. package/dist/feishu/CardRenderer.js +32 -96
  23. package/dist/feishu/CardRenderer.js.map +1 -1
  24. package/dist/feishu/FeishuConnector.js +9 -0
  25. package/dist/feishu/FeishuConnector.js.map +1 -1
  26. package/dist/feishu/FeishuMessageClient.js +35 -14
  27. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  28. package/dist/feishu/FeishuTurnPresenter.js +36 -23
  29. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  30. package/dist/feishu/LocalCardImage.js.map +1 -1
  31. package/dist/feishu/LocalImageMarkdown.js +59 -3
  32. package/dist/feishu/LocalImageMarkdown.js.map +1 -1
  33. package/dist/feishu/SettingsCard.js +199 -0
  34. package/dist/feishu/SettingsCard.js.map +1 -0
  35. package/dist/index.js +17 -6
  36. package/dist/index.js.map +1 -1
  37. package/dist/local-files/TurnPreviewPage.js +8 -4
  38. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  39. package/dist/presentation/TurnStateReducer.js +21 -2
  40. package/dist/presentation/TurnStateReducer.js.map +1 -1
  41. package/dist/presentation/turnStatus.js +34 -0
  42. package/dist/presentation/turnStatus.js.map +1 -0
  43. package/dist/proxy/ProxySessionController.js +688 -153
  44. package/dist/proxy/ProxySessionController.js.map +1 -1
  45. package/dist/runtime/submissionErrors.js +15 -0
  46. package/dist/runtime/submissionErrors.js.map +1 -0
  47. package/dist/scheduling/ScheduleCards.js +240 -0
  48. package/dist/scheduling/ScheduleCards.js.map +1 -0
  49. package/dist/scheduling/ScheduleCommand.js +67 -0
  50. package/dist/scheduling/ScheduleCommand.js.map +1 -0
  51. package/dist/scheduling/ScheduledTaskStore.js +226 -0
  52. package/dist/scheduling/ScheduledTaskStore.js.map +1 -0
  53. package/dist/scheduling/TaskScheduler.js +132 -0
  54. package/dist/scheduling/TaskScheduler.js.map +1 -0
  55. package/dist/scheduling/types.js +89 -0
  56. package/dist/scheduling/types.js.map +1 -0
  57. package/dist/state/ExecutionProvenanceStore.js +58 -0
  58. package/dist/state/ExecutionProvenanceStore.js.map +1 -0
  59. package/dist/state/StateStore.js +145 -45
  60. package/dist/state/StateStore.js.map +1 -1
  61. package/dist/state/migrations.js +37 -0
  62. package/dist/state/migrations.js.map +1 -1
  63. package/dist/supervision/SafeRestartNotifier.js +1 -1
  64. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  65. package/docs/technical-reference.md +11 -8
  66. package/docs/technical-reference.zh.md +11 -8
  67. package/npm-shrinkwrap.json +24 -2
  68. package/package.json +2 -1
  69. package/skills/agent-bot/SKILL.md +33 -3
  70. package/src/cli/controlProtocol.ts +1 -0
  71. package/src/cli/help.ts +14 -0
  72. package/src/cli.ts +25 -0
  73. package/src/codex/CodexRuntime.ts +14 -5
  74. package/src/commands/CommandRouter.ts +7 -0
  75. package/src/commands/commandTypes.ts +2 -0
  76. package/src/config/SettingsStore.ts +588 -0
  77. package/src/config/loadConfig.ts +1 -2
  78. package/src/config/schema.ts +0 -1
  79. package/src/console/ConsoleTurnPresenter.ts +2 -0
  80. package/src/feishu/CardRenderer.ts +33 -110
  81. package/src/feishu/FeishuConnector.ts +9 -0
  82. package/src/feishu/FeishuMessageClient.ts +39 -17
  83. package/src/feishu/FeishuTurnPresenter.ts +33 -22
  84. package/src/feishu/LocalCardImage.ts +0 -1
  85. package/src/feishu/LocalImageMarkdown.ts +54 -3
  86. package/src/feishu/SettingsCard.ts +231 -0
  87. package/src/index.ts +17 -6
  88. package/src/local-files/TurnPreviewPage.ts +8 -4
  89. package/src/presentation/TurnStateReducer.ts +21 -2
  90. package/src/presentation/turnStatus.ts +38 -0
  91. package/src/presentation/turnViewTypes.ts +3 -0
  92. package/src/proxy/ProxySessionController.ts +628 -152
  93. package/src/runtime/submissionErrors.ts +15 -0
  94. package/src/runtime/types.ts +1 -0
  95. package/src/scheduling/ScheduleCards.ts +317 -0
  96. package/src/scheduling/ScheduleCommand.ts +76 -0
  97. package/src/scheduling/ScheduledTaskStore.ts +332 -0
  98. package/src/scheduling/TaskScheduler.ts +171 -0
  99. package/src/scheduling/types.ts +151 -0
  100. package/src/state/ExecutionProvenanceStore.ts +100 -0
  101. package/src/state/StateStore.ts +167 -44
  102. package/src/state/migrations.ts +37 -0
  103. package/src/supervision/SafeRestartNotifier.ts +1 -1
@@ -17,11 +17,15 @@ import { formatGroupNameDate, formatNewGroupName, parseTaskNameFromGroupName, }
17
17
  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
+ import { scheduleCommandSchema } from "../scheduling/types.js";
21
+ import { renderSettingsCard } from "../feishu/SettingsCard.js";
22
+ import { renderSchedule, renderScheduleList, renderScheduleForm } from "../scheduling/ScheduleCards.js";
20
23
  import { classifyFileContent } from "../local-files/LocalFileViewerServer.js";
21
24
  import { errorLogValue } from "../logging/errorLogValue.js";
22
25
  import { createTurnViewState, hydrateTurnViewState } from "../presentation/TurnStateReducer.js";
23
26
  import { buildTurnGraphRows } from "../presentation/turnGraph.js";
24
27
  import { displayRuntimeError, isResponseContinuationError } from "../runtime/responseErrors.js";
28
+ import { TurnNotSubmittedError, TurnStoppedBeforeSubmissionError } from "../runtime/submissionErrors.js";
25
29
  import { isActiveShellCommandJob, ShellCommandJobManager, } from "../shell/ShellCommandJobManager.js";
26
30
  import { SessionOperationQueue } from "./SessionOperationQueue.js";
27
31
  import { createId } from "../utils/id.js";
@@ -127,6 +131,8 @@ const HELP_COMMAND_SECTIONS = [
127
131
  requiresArgument: true,
128
132
  },
129
133
  { command: "/sessions", usage: "[关键词]", description: "查找本机任务" },
134
+ { command: "/schedule", description: "创建和管理绑定现有任务的定时计划" },
135
+ { command: "/settings", description: "配置 Agent Bot 和各 Agent 默认值(仅所有者)" },
130
136
  {
131
137
  command: "/archive",
132
138
  usage: "[序号或任务 ID]",
@@ -236,9 +242,9 @@ export class ProxySessionController {
236
242
  queuedPromptCards = new Map();
237
243
  queuedPromptCardWrites = new Map();
238
244
  settingsOperations = new SessionOperationQueue();
245
+ globalSettingsOperations = new SessionOperationQueue();
239
246
  // Loads may run inside settingsOperations; never acquire that queue while hydrating.
240
247
  sessionHydrationOperations = new SessionOperationQueue();
241
- agentDefaultsOperations = new SessionOperationQueue();
242
248
  sessionResets = new Map();
243
249
  resetHistoryOperations = new Map();
244
250
  remoteTurnHistoryRefreshes = new Map();
@@ -595,8 +601,14 @@ export class ProxySessionController {
595
601
  if (command.type === "prompt" && message.chatType === "group" && message.mentionedBot
596
602
  && this.store.chatRequiresMention(baseChatContextKey(message.contextKey))) {
597
603
  const current = this.currentSession(message.contextKey);
598
- if (current)
599
- 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
+ }
600
612
  }
601
613
  if (injectedRootMessageId) {
602
614
  const current = this.currentSession(message.contextKey);
@@ -657,7 +669,13 @@ export class ProxySessionController {
657
669
  await this.outbound.withReplyTarget(contextKey, replyTarget, async () => {
658
670
  try {
659
671
  const kind = String(scopedAction.value.action ?? "");
660
- if (kind === "terminal_authorize") {
672
+ if (kind.startsWith("bot_settings_")) {
673
+ await this.handleSettingsAction(scopedAction, replyTarget);
674
+ }
675
+ else if (kind.startsWith("schedule_")) {
676
+ await this.handleScheduleAction(scopedAction, replyTarget);
677
+ }
678
+ else if (kind === "terminal_authorize") {
661
679
  if (!this.lifecycle?.authorizeTerminal)
662
680
  throw new Error("网页终端未启用。");
663
681
  await this.outbound.sendText(contextKey, await this.lifecycle.authorizeTerminal(scopedAction));
@@ -855,7 +873,6 @@ export class ProxySessionController {
855
873
  }
856
874
  else if (kind === "session_stop") {
857
875
  const sessionId = String(scopedAction.value.sessionId ?? "");
858
- await this.outbound.sendText(contextKey, STOP_TASK_STARTED_MESSAGE);
859
876
  await this.stopSessionReference(contextKey, sessionId);
860
877
  if (scopedAction.value.cardView === "status")
861
878
  await this.refreshStatusCardFromAction(scopedAction, sessionId);
@@ -1282,6 +1299,223 @@ export class ProxySessionController {
1282
1299
  await this.outbound.withReplyTarget(contextKey, replyTarget, () => this.switchSession(contextKey, target));
1283
1300
  return this.requireCurrentSession(contextKey);
1284
1301
  }
1302
+ async drainScheduledPrompts(localSessionId) {
1303
+ if (this.lifecycle?.canStartScheduledTasks?.() === false)
1304
+ return;
1305
+ await this.scheduleNextQueuedPrompt(localSessionId);
1306
+ }
1307
+ async notifySchedule(job, text) {
1308
+ const target = job.replyMessageId ? { messageId: job.replyMessageId, replyInThread: true } : undefined;
1309
+ await this.outbound.withReplyTarget(job.contextKey, target, () => this.outbound.sendText(job.contextKey, text));
1310
+ }
1311
+ async controlSchedule(command, localSessionId) {
1312
+ command = scheduleCommandSchema.parse(command);
1313
+ if (command.operation === "list")
1314
+ return this.store.schedules.list(undefined, 100);
1315
+ if (command.operation === "add") {
1316
+ if (!localSessionId || !command.input)
1317
+ throw new Error("需要目标任务和计划参数。");
1318
+ const session = this.requireControlSession(localSessionId);
1319
+ const contextKey = this.controlSessionContextKey(session);
1320
+ const target = this.controlSessionReplyTarget(session);
1321
+ const job = this.createSchedule(command.input, session.localSessionId, contextKey, target?.messageId);
1322
+ await this.outbound.withReplyTarget(contextKey, target, () => this.showSchedule(job));
1323
+ return job;
1324
+ }
1325
+ const saved = this.store.schedules.get(command.id ?? "");
1326
+ if (saved && command.operation === "show")
1327
+ return saved;
1328
+ if (saved && command.operation === "history")
1329
+ return this.store.schedules.runs(saved.id);
1330
+ const job = this.store.schedules.require(command.id ?? "");
1331
+ if (command.operation === "show")
1332
+ return job;
1333
+ if (command.operation === "history")
1334
+ return this.store.schedules.runs(job.id);
1335
+ if (command.operation === "edit") {
1336
+ if (!command.input)
1337
+ throw new Error("需要计划参数。");
1338
+ const updated = this.store.schedules.edit(job.id, job.revision, command.input);
1339
+ const target = job.replyMessageId ? { messageId: job.replyMessageId, replyInThread: true } : undefined;
1340
+ await this.outbound.withReplyTarget(job.contextKey, target, () => this.showSchedule(updated));
1341
+ return updated;
1342
+ }
1343
+ if (command.operation === "run") {
1344
+ this.assertScheduleTarget(job);
1345
+ const run = this.store.schedules.dispatch(job, Date.now(), Date.now(), { manual: true });
1346
+ await this.drainScheduledPrompts(job.localSessionId);
1347
+ return run;
1348
+ }
1349
+ if (!["pause", "resume", "delete"].includes(command.operation))
1350
+ throw new Error("无效的定时任务操作。");
1351
+ if (command.operation === "resume")
1352
+ this.assertScheduleTarget(job);
1353
+ return this.store.schedules.change(job.id, job.revision, command.operation);
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
+ }
1422
+ createSchedule(input, localSessionId, contextKey, replyMessageId) {
1423
+ if (!this.config.feishu.userOpenId)
1424
+ throw new Error("请先配置 Agent Bot 所有者,才能创建定时任务。");
1425
+ this.requireSession(contextKey, localSessionId);
1426
+ if (isThreadContextKey(contextKey) && !replyMessageId)
1427
+ throw new Error("缺少话题回复位置,请在原话题中创建计划。");
1428
+ return this.store.schedules.create(input, { localSessionId, contextKey, replyMessageId, ownerId: this.config.feishu.userOpenId });
1429
+ }
1430
+ assertScheduleTarget(job) {
1431
+ if (job.ownerId !== this.config.feishu.userOpenId)
1432
+ throw new Error("计划所有者已变化,请重新创建计划。");
1433
+ const session = this.store.getSession(job.localSessionId);
1434
+ if (!session || session.status === "closed")
1435
+ throw new Error("目标任务已关闭,不能执行该计划。");
1436
+ if (!this.outbound.canRoute(job.contextKey))
1437
+ throw new Error("计划的原始会话不可用。");
1438
+ }
1439
+ async showSchedule(job, messageId, history = false) {
1440
+ const title = this.store.getSession(job.localSessionId)?.title ?? job.localSessionId;
1441
+ const card = renderSchedule(job, title, this.store.schedules.runs(job.id, history ? 10 : 1), history);
1442
+ if (messageId)
1443
+ await this.outbound.updateInteractiveCard(job.contextKey, messageId, card);
1444
+ else
1445
+ await this.outbound.sendInteractiveCard(job.contextKey, card);
1446
+ }
1447
+ async showScheduleList(contextKey, page = 0, messageId) {
1448
+ if (!Number.isSafeInteger(page) || page < 0 || page > 10_000)
1449
+ throw new Error("无效的计划页码。");
1450
+ const card = renderScheduleList(this.store.schedules.list(contextKey, 11, page * 10), contextKey, page);
1451
+ if (messageId)
1452
+ await this.outbound.updateInteractiveCard(contextKey, messageId, card);
1453
+ else
1454
+ await this.outbound.sendInteractiveCard(contextKey, card);
1455
+ }
1456
+ async handleScheduleAction(action, replyTarget) {
1457
+ if (!this.config.feishu.userOpenId || action.userId !== this.config.feishu.userOpenId)
1458
+ throw new Error("只有 Agent Bot 所有者可以管理定时任务。");
1459
+ const operation = String(action.value.action).slice("schedule_".length);
1460
+ const messageId = requiredCardMessageId(action.messageId);
1461
+ if (operation === "list")
1462
+ return this.showScheduleList(action.contextKey, Number(action.value.page ?? 0), messageId);
1463
+ if (operation === "new") {
1464
+ const session = this.requireCurrentSession(action.contextKey);
1465
+ return this.outbound.updateInteractiveCard(action.contextKey, messageId, renderScheduleForm(action.contextKey, undefined, session.localSessionId));
1466
+ }
1467
+ const id = String(action.value.scheduleId ?? "");
1468
+ const job = id ? (["show", "history"].includes(operation) ? this.store.schedules.get(id) : this.store.schedules.require(id)) : undefined;
1469
+ if (job && (job.contextKey !== action.contextKey || job.ownerId !== action.userId))
1470
+ throw new Error("此会话无权操作该计划。");
1471
+ if (operation === "show" || operation === "history") {
1472
+ if (!job)
1473
+ throw new Error("计划不存在。");
1474
+ return this.showSchedule(job, messageId, operation === "history");
1475
+ }
1476
+ if (job && job.revision !== Number(action.value.revision))
1477
+ throw new Error("计划卡片已过期,请刷新。");
1478
+ if (operation === "resolve" && job) {
1479
+ const run = this.store.schedules.getRun(String(action.value.runId ?? ""));
1480
+ if (!run || run.jobId !== job.id || run.status !== "unknown")
1481
+ throw new Error("本次运行状态已变化,请刷新。");
1482
+ const session = this.store.getSession(job.localSessionId);
1483
+ if (session && run.turnId && this.runtimes.forAgent(session.agentName).getSession(session.localSessionId)?.activeTurnId === run.turnId) {
1484
+ throw new Error("本次运行仍活跃,请先停止或等待完成。");
1485
+ }
1486
+ this.store.schedules.finish(run.id, "cancelled", "用户已核实本次运行结束,解除调度阻塞。");
1487
+ return this.showSchedule(job, messageId, true);
1488
+ }
1489
+ if (operation === "edit") {
1490
+ if (!job)
1491
+ throw new Error("计划不存在。");
1492
+ return this.outbound.updateInteractiveCard(action.contextKey, messageId, renderScheduleForm(action.contextKey, job));
1493
+ }
1494
+ if (operation === "submit") {
1495
+ const form = action.value.formValue;
1496
+ if (!form || typeof form !== "object")
1497
+ throw new Error("缺少计划表单。");
1498
+ const string = (key) => typeof form[key] === "string" ? form[key] : "";
1499
+ const input = { name: string("name"), prompt: string("prompt"), timeZone: string("timeZone"),
1500
+ maxDelayMinutes: Number(string("maxDelayMinutes")), catchUpMinutes: Number(string("catchUpMinutes")),
1501
+ ...(string("cron").trim() ? { cron: string("cron") } : {}), ...(string("at").trim() ? { at: string("at") } : {}) };
1502
+ const updated = job ? this.store.schedules.edit(job.id, job.revision, input)
1503
+ : this.createSchedule(input, String(action.value.sessionId ?? ""), action.contextKey, replyTarget?.messageId);
1504
+ return this.showSchedule(updated, messageId);
1505
+ }
1506
+ if (!job)
1507
+ throw new Error("计划不存在。");
1508
+ if (operation === "run") {
1509
+ await this.controlSchedule({ operation: "run", id: job.id });
1510
+ return this.showSchedule(this.store.schedules.require(job.id), messageId, true);
1511
+ }
1512
+ if (!["confirm", "pause", "resume", "delete"].includes(operation))
1513
+ throw new Error("无效的定时任务操作。");
1514
+ if (operation === "confirm" || operation === "resume")
1515
+ this.assertScheduleTarget(job);
1516
+ const updated = this.store.schedules.change(job.id, job.revision, operation);
1517
+ await this.showSchedule(updated, messageId);
1518
+ }
1285
1519
  async controlQueueTaskPrompt(localSessionId, text) {
1286
1520
  const promptText = text.trim();
1287
1521
  if (!promptText)
@@ -1537,6 +1771,42 @@ export class ProxySessionController {
1537
1771
  throw new Error(unboundThreadTaskMessage());
1538
1772
  }
1539
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
+ }
1785
+ case "schedule": {
1786
+ if (!this.config.feishu.userOpenId || userId !== this.config.feishu.userOpenId)
1787
+ throw new Error("只有 Agent Bot 所有者可以管理定时任务。");
1788
+ if (command.command.operation === "list") {
1789
+ await this.showScheduleList(contextKey);
1790
+ return;
1791
+ }
1792
+ if (command.command.operation === "add") {
1793
+ const session = this.requireCurrentSession(contextKey);
1794
+ const job = this.createSchedule(command.command.input, session.localSessionId, contextKey, replyTarget?.messageId);
1795
+ await this.showSchedule(job);
1796
+ return;
1797
+ }
1798
+ const job = ["show", "history"].includes(command.command.operation)
1799
+ ? this.store.schedules.get(command.command.id ?? "") : this.store.schedules.require(command.command.id ?? "");
1800
+ if (!job)
1801
+ throw new Error("计划不存在。");
1802
+ if (job.contextKey !== contextKey || job.ownerId !== userId)
1803
+ throw new Error("此会话无权操作该计划。");
1804
+ await this.controlSchedule(command.command);
1805
+ if (command.command.operation === "edit")
1806
+ return;
1807
+ await this.showSchedule(this.store.schedules.get(job.id), undefined, command.command.operation === "history");
1808
+ return;
1809
+ }
1540
1810
  case "shell":
1541
1811
  await this.runShellCommand(contextKey, command.command, messageId, incomingMessage);
1542
1812
  return;
@@ -1767,6 +2037,10 @@ export class ProxySessionController {
1767
2037
  for (const attempt of this.store.listCancellationRequestedTurnAttempts()) {
1768
2038
  const session = this.store.getSession(attempt.localSessionId);
1769
2039
  if (!attempt.turnId) {
2040
+ if (attempt.submissionState !== "not_submitted") {
2041
+ await this.markAttemptUnknown(attempt, "停止意图已保存,但提交结果未知;未自动重发。请核实远端执行状态。");
2042
+ continue;
2043
+ }
1770
2044
  this.store.updateTurnAttempt(attempt.attemptId, { status: "cancelled" });
1771
2045
  if (session?.status === "starting" || session?.status === "running") {
1772
2046
  this.store.updateSession(session.localSessionId, { status: "ready" });
@@ -1777,13 +2051,27 @@ export class ProxySessionController {
1777
2051
  this.outbound.registerSession(session.localSessionId, attempt.contextKey, session.title, session.cwd, this.agentLabel(session.agentName), session.model, session.modelProvider);
1778
2052
  }
1779
2053
  try {
1780
- await this.handleRuntimeEvent({
1781
- type: "turn_cancelled",
1782
- sessionId: attempt.localSessionId,
1783
- turnId: attempt.turnId,
1784
- });
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.");
1785
2072
  }
1786
2073
  catch (error) {
2074
+ await this.markAttemptUnknown(attempt, "停止意图已保存,但尚不能确认原轮次已结束。未自动续跑,请核实执行记录。");
1787
2075
  this.logger.warn({ error, attemptId: attempt.attemptId, turnId: attempt.turnId }, "Failed to finish a persisted user-requested turn cancellation.");
1788
2076
  }
1789
2077
  }
@@ -1794,6 +2082,10 @@ export class ProxySessionController {
1794
2082
  continue;
1795
2083
  if (this.store.findIncompleteTurnAttemptForSession(session.localSessionId))
1796
2084
  continue;
2085
+ if (this.store.hasUnknownTurnAttemptForSession(session.localSessionId))
2086
+ continue;
2087
+ if (this.store.hasCancellationRequestedForSession(session.localSessionId))
2088
+ continue;
1797
2089
  const lastTurn = session.lastTurnId
1798
2090
  ? {
1799
2091
  turnId: session.lastTurnId,
@@ -1816,6 +2108,8 @@ export class ProxySessionController {
1816
2108
  if (!latest && session.status === "ready")
1817
2109
  continue;
1818
2110
  const snapshot = turnViewSnapshot(latest?.snapshot);
2111
+ if (snapshot?.status === "unknown")
2112
+ continue;
1819
2113
  if (snapshot && isTerminalTurnViewStatus(snapshot.status)) {
1820
2114
  this.store.updateSession(session.localSessionId, {
1821
2115
  status: snapshot.status === "failed" ? "failed" : "ready",
@@ -1825,6 +2119,10 @@ export class ProxySessionController {
1825
2119
  const persistedTurnId = latest?.turnId;
1826
2120
  const pendingTurnId = persistedTurnId?.startsWith("pending_") ? persistedTurnId : undefined;
1827
2121
  const turnId = pendingTurnId ? undefined : persistedTurnId ?? session.lastTurnId;
2122
+ if (persistedTurnId && this.store.schedules.ownsTurn(persistedTurnId))
2123
+ continue;
2124
+ if (turnId && this.store.schedules.ownsTurn(turnId))
2125
+ continue;
1828
2126
  const replyTarget = snapshot?.replyTarget?.replyInThread ? snapshot.replyTarget : undefined;
1829
2127
  this.store.createTurnAttempt({
1830
2128
  attemptId: createId("attempt"),
@@ -1836,12 +2134,17 @@ export class ProxySessionController {
1836
2134
  pendingTurnId,
1837
2135
  turnId,
1838
2136
  status: turnId ? "running" : "accepted",
2137
+ submissionState: turnId ? "submitted" : "submission_unknown",
1839
2138
  createdAt: latest?.updatedAt ?? session.updatedAt,
1840
2139
  updatedAt: latest?.updatedAt ?? session.updatedAt,
1841
2140
  });
1842
2141
  }
1843
2142
  }
1844
2143
  async expireStaleTurnAttempt(attempt, message = "执行中断已超过 10 分钟,未自动恢复。") {
2144
+ if (attempt.submissionState !== "not_submitted") {
2145
+ await this.markAttemptUnknown(attempt, `${message} 原执行结果待核实,未自动重发。`);
2146
+ return;
2147
+ }
1845
2148
  clearTimeout(this.recoveryRetryTimers.get(attempt.attemptId));
1846
2149
  this.recoveryRetryTimers.delete(attempt.attemptId);
1847
2150
  this.recoveryRetryStartedAt.delete(attempt.attemptId);
@@ -1934,11 +2237,24 @@ export class ProxySessionController {
1934
2237
  async recoverTurnAttempt(attempt, announce = true) {
1935
2238
  if (this.recoveryClosed)
1936
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
+ }
1937
2247
  const session = this.store.getSession(attempt.localSessionId);
1938
2248
  if (!session || session.status === "closed") {
1939
2249
  this.store.updateTurnAttempt(attempt.attemptId, { status: "interrupted" });
1940
2250
  return;
1941
2251
  }
2252
+ const scheduledRun = this.store.schedules.getRun(attempt.attemptId);
2253
+ if (scheduledRun?.status === "unknown"
2254
+ || (scheduledRun && !attempt.turnId && ["cancelled", "expired", "failed", "skipped", "completed"].includes(scheduledRun.status))) {
2255
+ this.store.updateTurnAttempt(attempt.attemptId, { status: scheduledRun.status === "cancelled" ? "cancelled" : "interrupted" });
2256
+ return;
2257
+ }
1942
2258
  const contextKey = attempt.contextKey || session.contextKey;
1943
2259
  const replyTarget = attempt.replyMessageId
1944
2260
  ? { messageId: attempt.replyMessageId, replyInThread: true }
@@ -1952,6 +2268,10 @@ export class ProxySessionController {
1952
2268
  }
1953
2269
  const runtime = this.runtimes.forAgent(session.agentName);
1954
2270
  const sourceTurnId = attempt.turnId;
2271
+ if (this.store.schedules.getRun(attempt.attemptId) && (!sourceTurnId || runtime.kind === "acp")) {
2272
+ await this.markScheduledAttemptUnknown(attempt, "重启后无法确认本次运行状态,未自动重发。请核实执行记录。");
2273
+ return;
2274
+ }
1955
2275
  if (runtime.kind === "acp") {
1956
2276
  await this.continueInterruptedAttempt(attempt, session, sourceTurnId, replyTarget);
1957
2277
  return;
@@ -1972,7 +2292,7 @@ export class ProxySessionController {
1972
2292
  await this.reconcileRecoveredRemoteTurn(attempt, session, remote.lastTurnId);
1973
2293
  return;
1974
2294
  }
1975
- if (remote && remoteTurnBelongsToAttempt && remote.lastTurnStatus === "failed") {
2295
+ if (remote && remoteTurnBelongsToAttempt && (remote.lastTurnStatus === "failed" || remote.lastTurnStatus === "interrupted")) {
1976
2296
  await this.reconcileRecoveredRemoteTurn(attempt, session, remote.lastTurnId);
1977
2297
  return;
1978
2298
  }
@@ -1988,8 +2308,45 @@ export class ProxySessionController {
1988
2308
  this.scheduleRecoveryRetry(attempt.attemptId);
1989
2309
  return;
1990
2310
  }
2311
+ if (this.store.schedules.getRun(attempt.attemptId)) {
2312
+ await this.markScheduledAttemptUnknown(attempt, "原轮次状态待核实,未自动重发。请核实执行记录。");
2313
+ return;
2314
+ }
1991
2315
  await this.continueInterruptedAttempt(attempt, session, sourceTurnId, replyTarget);
1992
2316
  }
2317
+ async markScheduledAttemptUnknown(attempt, detail) {
2318
+ await this.markAttemptUnknown(attempt, detail);
2319
+ this.store.schedules.finish(attempt.attemptId, "unknown", detail);
2320
+ const run = this.store.schedules.getRun(attempt.attemptId);
2321
+ const job = this.store.schedules.get(run.jobId);
2322
+ if (job)
2323
+ await this.notifySchedule(job, `定时任务「${job.spec.name}」:${detail}`);
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
+ }
1993
2350
  async reconcileRecoveredRemoteTurn(attempt, session, remoteTurnId) {
1994
2351
  if (remoteTurnId && !attempt.turnId) {
1995
2352
  this.store.updateTurnAttempt(attempt.attemptId, { turnId: remoteTurnId, status: "running" });
@@ -2102,13 +2459,18 @@ export class ProxySessionController {
2102
2459
  }
2103
2460
  }
2104
2461
  async continueInterruptedAttempt(attempt, session, sourceTurnId, replyTarget) {
2462
+ if (attempt.submissionState !== "not_submitted" || sourceTurnId) {
2463
+ await this.markAttemptUnknown(attempt, "原执行结果待核实,未自动重发。请检查执行记录后发送消息继续。");
2464
+ return;
2465
+ }
2105
2466
  const oldCardTurnId = attempt.pendingTurnId ?? sourceTurnId;
2106
2467
  if (oldCardTurnId) {
2107
2468
  await this.outbound.interruptTurnForRecovery(session.localSessionId, attempt.contextKey, oldCardTurnId, "Agent Bot 重启中断了这次执行,正在新的思考卡片中继续。").catch((error) => {
2108
2469
  this.logger.warn({ error, attemptId: attempt.attemptId, turnId: oldCardTurnId }, "Failed to close the interrupted thinking card before recovery.");
2109
2470
  });
2110
2471
  }
2111
- this.store.prepareTurnAttemptRecovery(attempt.attemptId, oldCardTurnId);
2472
+ if (!this.store.prepareTurnAttemptRecovery(attempt.attemptId, oldCardTurnId))
2473
+ return;
2112
2474
  this.store.updateSession(session.localSessionId, { status: "ready" });
2113
2475
  if (sourceTurnId) {
2114
2476
  this.store.updateRuntimeSession(session.localSessionId, {
@@ -2118,9 +2480,11 @@ export class ProxySessionController {
2118
2480
  }
2119
2481
  const current = this.store.getSession(session.localSessionId) ?? session;
2120
2482
  const loaded = await this.loadSession({ ...current, contextKey: attempt.contextKey }, Boolean(this.store.getPendingProviderSettings(current.localSessionId)));
2121
- const recoveryText = recoveryRuntimePrompt(attempt.promptText);
2483
+ const recoveryText = attempt.promptText;
2122
2484
  const turnId = await this.startTurn(loaded, recoveryText, replyTarget, attempt.localImagePaths, {
2123
2485
  attemptId: attempt.attemptId,
2486
+ executionGeneration: attempt.executionGeneration,
2487
+ trigger: "recovery",
2124
2488
  messageId: attempt.messageId,
2125
2489
  displayPrompt: recoveryCardPrompt(attempt.promptText),
2126
2490
  preserveAttemptOnFailure: true,
@@ -2156,6 +2520,7 @@ export class ProxySessionController {
2156
2520
  await this.promptSession(record, contextKey, text, messageId, replyTarget, localImagePaths, displayPrompt);
2157
2521
  }
2158
2522
  async promptSession(record, contextKey, text, messageId, replyTarget, localImagePaths, displayPrompt) {
2523
+ const executionGeneration = this.store.executionGeneration(record.localSessionId);
2159
2524
  if (this.llmRetryingSessions.has(record.localSessionId) || this.planHandoffs.has(record.localSessionId)) {
2160
2525
  const queued = this.persistQueuedPrompt(record.localSessionId, contextKey, text, {
2161
2526
  localImagePaths,
@@ -2202,6 +2567,8 @@ export class ProxySessionController {
2202
2567
  this.logger.warn({ error, sessionId: record.localSessionId }, "Failed to synchronize session before prompt.");
2203
2568
  }
2204
2569
  }
2570
+ this.assertExecutionGeneration(record.localSessionId, executionGeneration);
2571
+ this.store.acknowledgeUnknownTurnAttempts(record.localSessionId);
2205
2572
  const activeTurnId = loaded.session.activeTurnId;
2206
2573
  if (activeTurnId) {
2207
2574
  const activeContextKey = this.store.getTurnContextKey(activeTurnId);
@@ -2222,6 +2589,9 @@ export class ProxySessionController {
2222
2589
  return;
2223
2590
  }
2224
2591
  catch (error) {
2592
+ if (!(error instanceof TurnNotSubmittedError)) {
2593
+ throw new Error("追加消息的提交结果待核实,未自动重发或入队。请检查执行记录后继续。", { cause: error });
2594
+ }
2225
2595
  this.logger.debug({ error, sessionId: record.localSessionId, activeTurnId }, "Steering failed; reconciling the App Server thread.");
2226
2596
  let current = loaded.runtime.getSession(record.localSessionId);
2227
2597
  try {
@@ -2231,13 +2601,14 @@ export class ProxySessionController {
2231
2601
  this.logger.warn({ error: syncError, sessionId: record.localSessionId }, "Failed to synchronize after steering failure.");
2232
2602
  }
2233
2603
  if (!current?.activeTurnId) {
2234
- const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt });
2604
+ const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt, executionGeneration });
2235
2605
  if (messageId)
2236
2606
  await this.bindMessageReactionToTurn(messageId, record.localSessionId, turnId);
2237
2607
  return;
2238
2608
  }
2239
2609
  if (current.activeTurnId !== activeTurnId) {
2240
2610
  try {
2611
+ this.assertExecutionGeneration(record.localSessionId, executionGeneration);
2241
2612
  await loaded.runtime.steerTurn(record.localSessionId, current.activeTurnId, runtimePrompt(text, localImagePaths));
2242
2613
  await this.presentSteerMessage(record.localSessionId, current.activeTurnId, displayPrompt ?? text, messageId, localImagePaths);
2243
2614
  if (messageId)
@@ -2245,6 +2616,9 @@ export class ProxySessionController {
2245
2616
  return;
2246
2617
  }
2247
2618
  catch (retryError) {
2619
+ if (!(retryError instanceof TurnNotSubmittedError)) {
2620
+ throw new Error("追加消息的提交结果待核实,未自动重发或入队。", { cause: retryError });
2621
+ }
2248
2622
  this.logger.warn({ error: retryError, sessionId: record.localSessionId, activeTurnId: current.activeTurnId }, "Failed to steer the reconciled App Server turn; queueing prompt.");
2249
2623
  }
2250
2624
  }
@@ -2257,7 +2631,7 @@ export class ProxySessionController {
2257
2631
  return;
2258
2632
  }
2259
2633
  }
2260
- const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt });
2634
+ const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt, executionGeneration });
2261
2635
  if (messageId)
2262
2636
  await this.bindMessageReactionToTurn(messageId, record.localSessionId, turnId);
2263
2637
  }
@@ -2402,12 +2776,13 @@ export class ProxySessionController {
2402
2776
  }
2403
2777
  if (message.threadContext && !message.threadId)
2404
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();
2405
2785
  try {
2406
- const current = this.currentSession(message.contextKey);
2407
- const stopIds = current ? new Set([
2408
- ...this.store.recentContextMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey, false),
2409
- ...this.store.recentSubmittedMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey),
2410
- ]) : new Set();
2411
2786
  const messages = await this.outbound.readRecentMessages(message.contextKey, {
2412
2787
  chatId: message.chatId,
2413
2788
  ...(message.threadId ? { threadId: message.threadId } : {}),
@@ -2415,7 +2790,6 @@ export class ProxySessionController {
2415
2790
  beforeTimestamp: message.createdAt,
2416
2791
  ...(stopIds.size ? { stopBeforeMessageIds: [...stopIds] } : {}),
2417
2792
  });
2418
- const seen = current ? this.store.recentContextMessageIds(current.localSessionId, current.remoteSessionId ?? "", message.contextKey) : new Set();
2419
2793
  seen.add(message.messageId);
2420
2794
  if (message.parentMessageId)
2421
2795
  seen.add(message.parentMessageId);
@@ -3153,6 +3527,9 @@ export class ProxySessionController {
3153
3527
  };
3154
3528
  }
3155
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) };
3156
3533
  return this.settingsOperations.run(loaded.record.localSessionId, async () => {
3157
3534
  if (options.responseContinuationTurnId) {
3158
3535
  const current = this.store.getSession(loaded.record.localSessionId);
@@ -3179,6 +3556,10 @@ export class ProxySessionController {
3179
3556
  });
3180
3557
  }
3181
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);
3182
3563
  const currentRecord = this.store.getSession(loaded.record.localSessionId);
3183
3564
  const title = currentRecord?.title ?? normalizeTaskTitle(options.displayPrompt ?? text);
3184
3565
  if (!currentRecord?.title && title)
@@ -3188,6 +3569,7 @@ export class ProxySessionController {
3188
3569
  const attemptId = options.attemptId ?? createId("attempt");
3189
3570
  if (options.attemptId) {
3190
3571
  this.store.updateTurnAttempt(attemptId, {
3572
+ executionGeneration,
3191
3573
  messageId: options.messageId ?? undefined,
3192
3574
  replyMessageId: replyTarget?.messageId ?? undefined,
3193
3575
  status: "recovering",
@@ -3202,12 +3584,25 @@ export class ProxySessionController {
3202
3584
  localImagePaths,
3203
3585
  messageId: options.messageId,
3204
3586
  replyMessageId: replyTarget?.messageId,
3587
+ executionGeneration,
3205
3588
  });
3206
3589
  }
3207
3590
  let turnId;
3208
3591
  let runtimeText = text;
3209
3592
  let cardPrompt = options.displayPrompt ?? text;
3210
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
+ };
3211
3606
  try {
3212
3607
  while (true) {
3213
3608
  let pendingTurnId;
@@ -3217,6 +3612,15 @@ export class ProxySessionController {
3217
3612
  pendingTurnId = await this.outbound.startPendingTurn(loaded.record.localSessionId, loaded.record.contextKey, title, replyTarget, cardPrompt, localImagePaths);
3218
3613
  }
3219
3614
  catch (error) {
3615
+ if (options.scheduleRunId) {
3616
+ const run = this.store.schedules.getRun(options.scheduleRunId);
3617
+ const job = this.store.schedules.get(run.jobId);
3618
+ if (job?.status === "enabled") {
3619
+ const paused = this.store.schedules.change(job.id, job.revision, "pause");
3620
+ this.store.schedules.update({ ...paused, notice: "原会话的思考卡片创建失败,计划已暂停。请修复后恢复。" });
3621
+ }
3622
+ this.store.schedules.finish(run.id, "failed", "无法创建原会话的思考卡片,未提交模型。");
3623
+ }
3220
3624
  this.store.updateTurnAttempt(attemptId, {
3221
3625
  status: options.preserveAttemptOnFailure ? "recovering" : "failed",
3222
3626
  });
@@ -3224,6 +3628,7 @@ export class ProxySessionController {
3224
3628
  }
3225
3629
  this.store.updateTurnAttempt(attemptId, { pendingTurnId: pendingTurnId ?? null });
3226
3630
  try {
3631
+ this.assertExecutionGeneration(loaded.record.localSessionId, executionGeneration);
3227
3632
  if (options.approvedPlanTurnId && (this.planHandoffs.get(loaded.record.localSessionId) !== options.approvedPlanTurnId
3228
3633
  || this.sessionResets.has(loaded.record.localSessionId))) {
3229
3634
  throw new Error("方案执行已取消。");
@@ -3234,9 +3639,19 @@ export class ProxySessionController {
3234
3639
  || this.sessionResets.has(loaded.record.localSessionId) || !loaded.runtime.recoverResponseContinuation) {
3235
3640
  throw new Error("模型续接恢复已取消。");
3236
3641
  }
3642
+ this.store.beginTurnAttemptSubmission(attemptId, recordSubmission);
3237
3643
  turnId = await loaded.runtime.recoverResponseContinuation(loaded.record.localSessionId, options.responseContinuationTurnId, recovery.abort.signal);
3238
3644
  }
3239
3645
  else {
3646
+ if (options.scheduleRunId) {
3647
+ const run = this.store.schedules.getRun(options.scheduleRunId);
3648
+ if ((!options.approvedPlanTurnId && !this.store.schedules.canSubmit(options.scheduleRunId))
3649
+ || this.lifecycle?.canStartScheduledTasks?.() === false)
3650
+ throw new Error("定时任务已取消、过期或正在安全重启。");
3651
+ this.assertScheduleTarget(this.store.schedules.require(run.jobId));
3652
+ this.store.schedules.saveRun({ ...run, status: "submitting" });
3653
+ }
3654
+ this.store.beginTurnAttemptSubmission(attemptId, recordSubmission);
3240
3655
  turnId = await loaded.runtime.startTurn(loaded.record.localSessionId, options.approvedPlanTurnId
3241
3656
  ? { text: runtimeText, collaborationMode: "default" }
3242
3657
  : runtimePrompt(runtimeText, localImagePaths));
@@ -3245,8 +3660,39 @@ export class ProxySessionController {
3245
3660
  }
3246
3661
  catch (error) {
3247
3662
  const message = error instanceof Error ? error.message : String(error);
3248
- const attempt = this.store.getTurnAttempt(attemptId);
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) {
3673
+ turnId = attempt.turnId;
3674
+ if (isIncompleteTurnAttemptStatus(attempt.status))
3675
+ this.store.updateTurnAttempt(attemptId, { status: "running" });
3676
+ break;
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
+ }
3249
3693
  const retryAttempt = attempt
3694
+ && error instanceof TurnNotSubmittedError
3695
+ && !options.scheduleRunId
3250
3696
  && !options.responseContinuationTurnId
3251
3697
  && isRetryableLlmTurnFailure(message)
3252
3698
  && attempt.retryCount < MAX_LLM_TURN_RETRIES
@@ -3278,7 +3724,7 @@ export class ProxySessionController {
3278
3724
  await this.outbound.failPendingTurn(loaded.record.localSessionId, `${message}\n\n检测到临时模型服务错误,正在自动重试(${retryAttempt.retryCount}/${MAX_LLM_TURN_RETRIES})。`).catch((presentationError) => {
3279
3725
  this.logger.warn({ error: presentationError, sessionId: loaded.record.localSessionId }, "Failed to finalize the pending thinking card before an LLM start retry.");
3280
3726
  });
3281
- runtimeText = llmRetryRuntimePrompt(retryAttempt.promptText, retryAttempt.retryCount);
3727
+ runtimeText = retryAttempt.promptText;
3282
3728
  cardPrompt = llmRetryCardPrompt(options.displayPrompt ?? retryAttempt.promptText, retryAttempt.retryCount);
3283
3729
  }
3284
3730
  }
@@ -3288,20 +3734,44 @@ export class ProxySessionController {
3288
3734
  this.llmRetryingSessions.delete(loaded.record.localSessionId);
3289
3735
  }
3290
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
+ }
3291
3749
  this.store.updateTurnAttempt(attemptId, {
3292
3750
  pendingTurnId: null,
3293
3751
  turnId,
3752
+ submissionState: "submitted",
3294
3753
  ...(attempt && isIncompleteTurnAttemptStatus(attempt.status) ? { status: "running" } : {}),
3295
3754
  });
3296
3755
  const latest = this.store.getSession(loaded.record.localSessionId);
3297
3756
  const alreadyTerminal = latest?.lastTurnId === turnId
3298
- && ["completed", "cancelled", "failed"].includes(latest.lastTurnStatus ?? "");
3757
+ && ["completed", "cancelled", "failed", "unknown"].includes(latest.lastTurnStatus ?? "");
3299
3758
  if (!alreadyTerminal) {
3300
3759
  this.store.updateSession(loaded.record.localSessionId, { status: "running" });
3301
3760
  this.store.updateRuntimeSession(loaded.record.localSessionId, { lastTurnId: turnId, lastTurnStatus: "running" });
3302
3761
  }
3762
+ if (options.scheduleRunId) {
3763
+ const run = this.store.schedules.getRun(options.scheduleRunId);
3764
+ const completedAttempt = this.store.getTurnAttempt(attemptId);
3765
+ const status = completedAttempt?.status;
3766
+ this.store.schedules.saveRun({ ...run, turnId,
3767
+ status: status === "completed" || status === "failed" || status === "cancelled" ? status : "running" });
3768
+ }
3303
3769
  return turnId;
3304
3770
  }
3771
+ assertExecutionGeneration(sessionId, generation) {
3772
+ if (this.store.executionGeneration(sessionId) !== generation)
3773
+ throw new TurnStoppedBeforeSubmissionError();
3774
+ }
3305
3775
  async createSession(contextKey, agentName, cwd, announce, prepareTurn, prompt, replyTarget, requestedTitle, executionSettings = {}, activate = true) {
3306
3776
  const agent = this.ensureAgent(agentName);
3307
3777
  const resolvedExecutionSettings = mergeExecutionSettings(agent.defaults ?? {}, executionSettings);
@@ -3311,6 +3781,7 @@ export class ProxySessionController {
3311
3781
  ? createProjectlessWorkspace({ prompt: initialTitle }).cwd
3312
3782
  : path.resolve(cwd ?? this.config.defaults.cwd);
3313
3783
  const record = this.store.createSession({ localSessionId, contextKey, agentName, cwd: sessionCwd, status: "starting" });
3784
+ const executionGeneration = this.store.executionGeneration(localSessionId);
3314
3785
  if (initialTitle || resolvedExecutionSettings.modelProvider || resolvedExecutionSettings.model
3315
3786
  || resolvedExecutionSettings.reasoningEffort || resolvedExecutionSettings.permissionMode) {
3316
3787
  this.store.updateRuntimeSession(localSessionId, {
@@ -3342,6 +3813,8 @@ export class ProxySessionController {
3342
3813
  this.persistRuntimeSession(record, session, session.activeTurnId ? "running" : "ready");
3343
3814
  this.outbound.updateSessionModel(localSessionId, session.model, session.modelProvider);
3344
3815
  const saved = this.store.getSession(localSessionId) ?? record;
3816
+ if (prepareTurn)
3817
+ this.assertExecutionGeneration(localSessionId, executionGeneration);
3345
3818
  if (announce) {
3346
3819
  const task = initialTitle ? `${initialTitle}(${session.remoteSessionId})` : session.remoteSessionId;
3347
3820
  await this.outbound.sendText(contextKey, `已创建 ${agent.title} 任务:${task}`);
@@ -3779,6 +4252,25 @@ export class ProxySessionController {
3779
4252
  });
3780
4253
  }
3781
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
+ }
3782
4274
  if ("turnId" in event) {
3783
4275
  const recoveryAttempt = this.recoveryRetryStartedAt.size > 0
3784
4276
  ? this.store.findIncompleteTurnAttemptByTurnId(event.turnId) : undefined;
@@ -3792,6 +4284,11 @@ export class ProxySessionController {
3792
4284
  }
3793
4285
  if (event.type === "turn_started") {
3794
4286
  const attempt = this.store.bindTurnAttempt(event.sessionId, event.turnId);
4287
+ if (attempt)
4288
+ this.store.provenance.bindLatestTurn(attempt.attemptId, event.turnId);
4289
+ const scheduledRun = attempt ? this.store.schedules.getRun(attempt.attemptId) : undefined;
4290
+ if (scheduledRun)
4291
+ this.store.schedules.saveRun({ ...scheduledRun, status: "running", turnId: event.turnId });
3795
4292
  if (attempt?.recoveredFromTurnId && attempt.recoveredFromTurnId !== event.turnId) {
3796
4293
  this.store.rebindPendingTurnMessages(event.sessionId, attempt.recoveredFromTurnId, event.turnId);
3797
4294
  }
@@ -3820,20 +4317,11 @@ export class ProxySessionController {
3820
4317
  && Boolean(this.runtimes.forAgent(source.agentName).recoverResponseContinuation)
3821
4318
  && isResponseContinuationError(event.message);
3822
4319
  if (failedAttempt && responseContinuation) {
3823
- const retryAttempt = this.store.prepareTurnAttemptRetry(failedAttempt.attemptId, event.turnId);
4320
+ const retryAttempt = this.store.prepareTurnAttemptRetry(failedAttempt.attemptId, event.turnId, true);
3824
4321
  if (retryAttempt) {
3825
4322
  this.retriedFailureTurnIds.add(event.turnId);
3826
4323
  this.responseContinuations.set(event.sessionId, { turnId: event.turnId, abort: new AbortController() });
3827
- await this.retryFailedLlmTurn(event, retryAttempt, true);
3828
- return;
3829
- }
3830
- }
3831
- if (failedAttempt && !this.responseContinuations.has(event.sessionId)
3832
- && isRetryableLlmTurnFailure(event.message) && failedAttempt.retryCount < MAX_LLM_TURN_RETRIES) {
3833
- const retryAttempt = this.store.prepareTurnAttemptRetry(failedAttempt.attemptId, event.turnId);
3834
- if (retryAttempt) {
3835
- this.retriedFailureTurnIds.add(event.turnId);
3836
- await this.retryFailedLlmTurn(event, retryAttempt);
4324
+ await this.recoverFailedResponse(event, retryAttempt);
3837
4325
  return;
3838
4326
  }
3839
4327
  }
@@ -3856,10 +4344,26 @@ export class ProxySessionController {
3856
4344
  this.recoveredLiveAttempts.delete(attempt.attemptId);
3857
4345
  }
3858
4346
  this.store.markTurnAttemptTerminal(event.turnId, event.type === "turn_completed" ? "completed" : event.type === "turn_cancelled" ? "cancelled" : "failed");
3859
- this.store.updateRuntimeSession(event.sessionId, {
3860
- lastTurnId: event.turnId,
3861
- lastTurnStatus: event.type === "turn_completed" ? "completed" : event.type === "turn_cancelled" ? "cancelled" : "failed",
3862
- });
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
+ }
3863
4367
  }
3864
4368
  const enrichedEvent = event.type === "context_compaction"
3865
4369
  ? {
@@ -3899,7 +4403,7 @@ export class ProxySessionController {
3899
4403
  const activeTurnId = latest
3900
4404
  ? this.runtimes.forAgent(latest.agentName).getSession(event.sessionId)?.activeTurnId
3901
4405
  : undefined;
3902
- if (latest?.lastTurnId === event.turnId && !activeTurnId) {
4406
+ if (latest?.lastTurnId === event.turnId && latest.status !== "closed" && !activeTurnId) {
3903
4407
  this.store.updateSession(event.sessionId, { status: event.type === "turn_failed" ? "failed" : "ready" });
3904
4408
  await this.applyPendingProviderWhenIdle(event.sessionId);
3905
4409
  await this.scheduleNextQueuedPrompt(event.sessionId);
@@ -3914,7 +4418,14 @@ export class ProxySessionController {
3914
4418
  if (!source || source.status === "closed" || source.lastTurnId !== turnId)
3915
4419
  return;
3916
4420
  this.planHandoffs.set(sessionId, turnId);
4421
+ const scheduledRun = this.store.schedules.getRun(attempt.attemptId);
3917
4422
  this.store.markTurnAttemptTerminal(turnId, "completed");
4423
+ if (scheduledRun) {
4424
+ this.store.schedules.saveRun({ ...scheduledRun, status: "running" });
4425
+ this.store.updateTurnAttempt(attempt.attemptId, {
4426
+ status: "recovering", turnId: null, submissionState: "not_submitted", recoveredFromTurnId: turnId,
4427
+ });
4428
+ }
3918
4429
  this.store.updateRuntimeSession(sessionId, { lastTurnId: turnId, lastTurnStatus: "completed" });
3919
4430
  let continued = false;
3920
4431
  let failed = false;
@@ -3944,7 +4455,10 @@ export class ProxySessionController {
3944
4455
  throw new Error("Provider 切换尚未完成。");
3945
4456
  if (this.planHandoffs.get(sessionId) !== turnId || this.sessionResets.has(sessionId))
3946
4457
  return;
3947
- 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 });
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,
4461
+ ...(scheduledRun ? { attemptId: attempt.attemptId, scheduleRunId: attempt.attemptId } : {}) });
3948
4462
  }
3949
4463
  continued = true;
3950
4464
  this.store.rebindPendingTurnMessages(sessionId, turnId, nextTurnId);
@@ -3957,14 +4471,20 @@ export class ProxySessionController {
3957
4471
  });
3958
4472
  }
3959
4473
  catch (error) {
3960
- failed = true;
3961
- this.logger.error({ error, sessionId, turnId }, "Failed to continue an approved plan.");
3962
- 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
+ }
3963
4479
  }
3964
4480
  finally {
3965
4481
  if (this.planHandoffs.get(sessionId) === turnId)
3966
4482
  this.planHandoffs.delete(sessionId);
3967
4483
  if (!continued) {
4484
+ if (scheduledRun && this.store.getTurnAttempt(attempt.attemptId)?.status !== "unknown") {
4485
+ this.store.updateTurnAttempt(attempt.attemptId, { status: failed ? "failed" : "cancelled" });
4486
+ this.store.schedules.finish(attempt.attemptId, failed ? "failed" : "cancelled");
4487
+ }
3968
4488
  try {
3969
4489
  await this.outbound.onEvent(failed
3970
4490
  ? { type: "turn_failed", sessionId, turnId, message: "方案已确认,但后续执行未能启动。" }
@@ -3982,7 +4502,7 @@ export class ProxySessionController {
3982
4502
  await this.scheduleNextQueuedPrompt(sessionId);
3983
4503
  }
3984
4504
  }
3985
- async retryFailedLlmTurn(event, attempt, responseContinuation = false) {
4505
+ async recoverFailedResponse(event, attempt) {
3986
4506
  const retryNumber = attempt.retryCount;
3987
4507
  const session = this.store.getSession(event.sessionId);
3988
4508
  if (!session || session.status === "closed") {
@@ -3998,16 +4518,14 @@ export class ProxySessionController {
3998
4518
  attemptId: attempt.attemptId,
3999
4519
  failedTurnId: event.turnId,
4000
4520
  retryNumber,
4001
- maxRetries: responseContinuation ? 1 : MAX_LLM_TURN_RETRIES,
4002
- responseContinuation,
4521
+ maxRetries: 1,
4522
+ responseContinuation: true,
4003
4523
  error: event.message,
4004
4524
  });
4005
4525
  try {
4006
4526
  await this.outbound.onEvent({
4007
4527
  ...event,
4008
- message: responseContinuation
4009
- ? `${event.message}\n\n模型续接状态失效,正在恢复连接并继续(1/1)。`
4010
- : `${event.message}\n\n检测到临时模型服务错误,正在自动重试(${retryNumber}/${MAX_LLM_TURN_RETRIES})。`,
4528
+ message: `${event.message}\n\n模型续接状态失效,正在恢复连接并继续(1/1)。`,
4011
4529
  });
4012
4530
  }
4013
4531
  catch (error) {
@@ -4019,27 +4537,31 @@ export class ProxySessionController {
4019
4537
  try {
4020
4538
  const current = this.store.getSession(session.localSessionId) ?? session;
4021
4539
  const loaded = await this.loadSession(current, Boolean(this.store.getPendingProviderSettings(current.localSessionId)));
4022
- 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, {
4023
4541
  attemptId: attempt.attemptId,
4542
+ executionGeneration: attempt.executionGeneration,
4543
+ trigger: "response_continuation", parentSourceTurnId: event.turnId,
4024
4544
  messageId: attempt.messageId,
4025
- displayPrompt: responseContinuation ? `恢复模型续接:${attempt.promptText}` : llmRetryCardPrompt(attempt.promptText, retryNumber),
4545
+ displayPrompt: `恢复模型续接:${attempt.promptText}`,
4026
4546
  preserveAttemptOnFailure: true,
4027
- ...(responseContinuation ? { responseContinuationTurnId: event.turnId } : {}),
4547
+ responseContinuationTurnId: event.turnId,
4028
4548
  });
4029
4549
  this.store.rebindPendingTurnMessages(session.localSessionId, event.turnId, retryTurnId);
4030
4550
  }
4031
4551
  catch (error) {
4032
- 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;
4033
4555
  this.store.updateTurnAttempt(attempt.attemptId, { status: aborted ? "cancelled" : "failed" });
4034
4556
  const latest = this.store.getSession(session.localSessionId);
4035
- if (!responseContinuation || (latest?.lastTurnId === event.turnId && latest.status !== "closed")) {
4557
+ if (latest?.lastTurnId === event.turnId && latest.status !== "closed") {
4036
4558
  this.store.updateSession(session.localSessionId, { status: aborted ? "ready" : "failed" });
4037
4559
  }
4038
4560
  await this.finalizeTurnMessageReactions(event.turnId, aborted ? "cancelled" : "failed").catch((reactionError) => {
4039
4561
  this.logger.warn({ error: reactionError, sessionId: session.localSessionId, turnId: event.turnId }, "Failed to finalize reactions after an LLM retry could not start.");
4040
4562
  });
4041
4563
  this.logger.error({ error, sessionId: session.localSessionId, retryNumber }, "Failed to start an automatic LLM turn retry.");
4042
- if (responseContinuation && !aborted) {
4564
+ if (!aborted) {
4043
4565
  await this.outbound.sendText(attempt.contextKey, `模型续接恢复未能启动:${displayRuntimeError(runtimeErrorMessage(error))}。请发送消息继续。`);
4044
4566
  }
4045
4567
  await this.scheduleNextQueuedPrompt(session.localSessionId);
@@ -4086,10 +4608,19 @@ export class ProxySessionController {
4086
4608
  return this.settingsOperations.run(sessionId, () => this.startNextQueuedPromptIfIdleNow(sessionId));
4087
4609
  }
4088
4610
  async startNextQueuedPromptIfIdleNow(sessionId) {
4611
+ const executionGeneration = this.store.executionGeneration(sessionId);
4089
4612
  if (this.planHandoffs.has(sessionId) || this.sessionResets.has(sessionId))
4090
4613
  return;
4614
+ if (this.store.hasUnknownTurnAttemptForSession(sessionId))
4615
+ return;
4616
+ if (this.store.hasCancellationRequestedForSession(sessionId))
4617
+ return;
4091
4618
  if (this.store.countQueuedPrompts(sessionId) === 0)
4092
4619
  return;
4620
+ const queuedHead = this.store.peekQueuedPrompt(sessionId);
4621
+ if (queuedHead && this.store.schedules.getRun(queuedHead.promptId)
4622
+ && this.lifecycle?.canStartScheduledTasks?.() === false)
4623
+ return;
4093
4624
  const baseRecord = this.store.getSession(sessionId);
4094
4625
  if (!baseRecord || baseRecord.status === "closed")
4095
4626
  return;
@@ -4105,17 +4636,59 @@ export class ProxySessionController {
4105
4636
  await this.applyPendingProviderSettings(loaded);
4106
4637
  if (this.store.getPendingProviderSettings(sessionId))
4107
4638
  return;
4639
+ this.assertExecutionGeneration(sessionId, executionGeneration);
4108
4640
  prompt = this.store.takeNextQueuedPrompt(sessionId);
4109
4641
  if (!prompt)
4110
4642
  return;
4643
+ const scheduledRun = this.store.schedules.getRun(prompt.promptId);
4111
4644
  const record = this.store.getSessionForContext(sessionId, prompt.contextKey) ?? baseRecord;
4112
4645
  loaded = { ...loaded, record };
4113
4646
  await this.refreshPromptQueueCards(sessionId);
4114
- const turnId = await this.startTurnNow(loaded, prompt.text, prompt.replyMessageId ? { messageId: prompt.replyMessageId, replyInThread: true } : undefined, prompt.localImagePaths, { messageId: prompt.messageId, displayPrompt: prompt.displayPrompt });
4647
+ if (scheduledRun) {
4648
+ if (!this.store.schedules.canSubmit(scheduledRun.id)
4649
+ || this.lifecycle?.canStartScheduledTasks?.() === false)
4650
+ throw new Error("定时任务已取消、过期或正在安全重启。");
4651
+ const job = this.store.schedules.require(scheduledRun.jobId);
4652
+ this.assertScheduleTarget(job);
4653
+ try {
4654
+ await this.notifySchedule(job, prompt.text);
4655
+ }
4656
+ catch (error) {
4657
+ const currentJob = this.store.schedules.get(job.id);
4658
+ if (currentJob?.status === "enabled") {
4659
+ const paused = this.store.schedules.change(job.id, currentJob.revision, "pause");
4660
+ this.store.schedules.update({ ...paused, notice: "原会话的 Prompt 发送失败,计划已暂停。请修复后恢复。" });
4661
+ }
4662
+ this.store.schedules.finish(scheduledRun.id, "failed", "无法向原会话发送 Prompt,未提交模型。");
4663
+ this.store.updateTurnAttempt(scheduledRun.id, { status: "failed" });
4664
+ throw error;
4665
+ }
4666
+ }
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,
4669
+ ...(scheduledRun ? { attemptId: prompt.promptId, scheduleRunId: prompt.promptId } : {}) });
4115
4670
  if (prompt.messageId)
4116
4671
  await this.bindMessageReactionToTurn(prompt.messageId, sessionId, turnId);
4117
4672
  }
4118
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
+ }
4686
+ if (prompt) {
4687
+ const run = this.store.schedules.getRun(prompt.promptId);
4688
+ if (run && ["dispatching", "submitting"].includes(run.status)) {
4689
+ this.store.schedules.finish(run.id, run.status === "submitting" ? "unknown" : "failed", runtimeErrorMessage(error));
4690
+ }
4691
+ }
4119
4692
  this.logger.warn({
4120
4693
  error,
4121
4694
  errorMessage: runtimeErrorMessage(error),
@@ -4275,13 +4848,17 @@ export class ProxySessionController {
4275
4848
  }
4276
4849
  async cancel(contextKey) {
4277
4850
  const record = this.requireCurrentSession(contextKey);
4278
- await this.outbound.sendText(contextKey, STOP_TASK_STARTED_MESSAGE);
4279
4851
  await this.cancelSession(record);
4280
4852
  }
4281
4853
  async cancelSession(record) {
4854
+ this.store.requestSessionExecutionStop(record.localSessionId);
4855
+ const stopGeneration = this.store.executionGeneration(record.localSessionId);
4282
4856
  this.responseContinuations.get(record.localSessionId)?.abort.abort();
4283
4857
  this.responseContinuations.delete(record.localSessionId);
4284
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
+ });
4285
4862
  const runtime = this.runtimes.forAgent(record.agentName);
4286
4863
  if (runtime.kind === "codex" && record.remoteSessionId && runtime.interruptRemoteTurn) {
4287
4864
  if (runtime.getGoal && runtime.setGoal) {
@@ -4313,16 +4890,19 @@ export class ProxySessionController {
4313
4890
  }
4314
4891
  }
4315
4892
  if (!turnId) {
4893
+ this.finishUnsubmittedStops(record.localSessionId);
4316
4894
  await this.outbound.sendText(record.contextKey, "当前没有正在执行的任务。");
4317
4895
  return;
4318
4896
  }
4319
- 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);
4320
4901
  try {
4321
4902
  await runtime.interruptRemoteTurn(record.remoteSessionId, turnId);
4322
4903
  }
4323
4904
  catch (error) {
4324
- if (cancellationAttempt)
4325
- this.store.restoreTurnAttemptAfterCancellationFailure(cancellationAttempt);
4905
+ // Keep the durable stop intent even when the interrupt response is lost.
4326
4906
  throw error;
4327
4907
  }
4328
4908
  this.store.audit(record.contextKey, "turn_interrupt_sent", {
@@ -4336,19 +4916,29 @@ export class ProxySessionController {
4336
4916
  const loaded = await this.loadSession(record);
4337
4917
  const turnId = loaded.session.activeTurnId;
4338
4918
  if (!turnId) {
4919
+ this.finishUnsubmittedStops(record.localSessionId);
4339
4920
  await this.outbound.sendText(record.contextKey, "当前没有正在执行的任务。");
4340
4921
  return;
4341
4922
  }
4342
- 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);
4343
4927
  try {
4344
4928
  await loaded.runtime.cancelTurn(record.localSessionId, turnId);
4345
4929
  }
4346
4930
  catch (error) {
4347
- if (cancellationAttempt)
4348
- this.store.restoreTurnAttemptAfterCancellationFailure(cancellationAttempt);
4931
+ // Keep the durable stop intent even when the interrupt response is lost.
4349
4932
  throw error;
4350
4933
  }
4351
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
+ }
4352
4942
  async resetCurrentSessionToTurn(contextKey, sessionId, turnId) {
4353
4943
  if (!sessionId || !turnId)
4354
4944
  throw new Error("无效的 Reset 请求。请使用最新的思考卡片重试。");
@@ -4720,7 +5310,7 @@ export class ProxySessionController {
4720
5310
  `模型 ${cardCode(session.model ?? settings.model)}`,
4721
5311
  `思考强度 ${cardCode(session.reasoningEffort ?? settings.effort)}`,
4722
5312
  `权限 ${cardCode(session.permissionMode)}`,
4723
- `并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
5313
+ "只影响当前任务,从下一次请求生效。",
4724
5314
  ].join(",");
4725
5315
  if (options.updateMessageId) {
4726
5316
  await this.openExecutionSettingsNow(contextKey, "provider", {
@@ -4741,7 +5331,7 @@ export class ProxySessionController {
4741
5331
  throw new Error("当前运行时不支持 Provider 设置。");
4742
5332
  loaded.session = loaded.runtime.getSession(loaded.record.localSessionId) ?? loaded.session;
4743
5333
  const remoteSessionId = loaded.session.remoteSessionId;
4744
- const persist = (candidate, replacement) => this.agentDefaultsOperations.run(loaded.record.agentName, async () => {
5334
+ const persist = async (candidate, replacement) => {
4745
5335
  if (candidate.remoteSessionId !== remoteSessionId) {
4746
5336
  const saved = this.store.getSession(loaded.record.localSessionId);
4747
5337
  if (replacement?.emptyRemoteSessionId !== remoteSessionId || !saved || saved.remoteSessionId !== remoteSessionId
@@ -4753,24 +5343,14 @@ export class ProxySessionController {
4753
5343
  }
4754
5344
  }
4755
5345
  assertProviderSettingsApplied(candidate, settings);
4756
- const agent = this.ensureAgent(loaded.record.agentName);
4757
- const previousDefaults = agent.defaults;
4758
- await this.persistAgentExecutionDefaultsNow(loaded.record.localSessionId, candidate);
4759
- try {
4760
- this.store.updateRuntimeSession(loaded.record.localSessionId, {
4761
- remoteSessionId: candidate.remoteSessionId,
4762
- modelProvider: candidate.modelProvider,
4763
- model: candidate.model,
4764
- reasoningEffort: candidate.reasoningEffort,
4765
- permissionMode: candidate.permissionMode,
4766
- });
4767
- }
4768
- catch (error) {
4769
- await this.lifecycle?.persistAgentExecutionDefaults?.(loaded.record.agentName, previousDefaults ?? {});
4770
- agent.defaults = previousDefaults;
4771
- throw error;
4772
- }
4773
- });
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
+ };
4774
5354
  const session = await loaded.runtime.setExecutionSettings(loaded.record.localSessionId, settings, persist);
4775
5355
  loaded.record = this.store.getSession(loaded.record.localSessionId) ?? loaded.record;
4776
5356
  this.settingsOnlySessions.delete(loaded.record.localSessionId);
@@ -4986,7 +5566,6 @@ export class ProxySessionController {
4986
5566
  }
4987
5567
  this.store.updateRuntimeSession(loaded.record.localSessionId, { model, reasoningEffort: nextEffort });
4988
5568
  this.outbound.updateSessionModel(loaded.record.localSessionId, model, loaded.session.modelProvider);
4989
- await this.persistAgentExecutionDefaults(loaded.record.localSessionId);
4990
5569
  });
4991
5570
  const effortMessage = nextEffort && nextEffort !== currentEffort
4992
5571
  ? `,思考强度已自动调整为 ${nextEffort}`
@@ -4995,11 +5574,11 @@ export class ProxySessionController {
4995
5574
  await this.openExecutionSettingsNow(contextKey, "model", {
4996
5575
  sessionId: loaded.record.localSessionId,
4997
5576
  updateMessageId: options.updateMessageId,
4998
- notice: `模型已切换为 ${cardCode(model)}${effortMessage},并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
5577
+ notice: `模型已切换为 ${cardCode(model)}${effortMessage},只影响当前任务,从下一次请求生效。`,
4999
5578
  });
5000
5579
  return;
5001
5580
  }
5002
- await this.outbound.sendText(contextKey, `模型已切换为 ${model}${effortMessage},并已保存为 ${loaded.record.agentName} Agent 的默认设置,从下一次请求生效。`);
5581
+ await this.outbound.sendText(contextKey, `模型已切换为 ${model}${effortMessage},只影响当前任务,从下一次请求生效。`);
5003
5582
  }
5004
5583
  async goal(contextKey, command) {
5005
5584
  const objective = command.action === "set" || command.action === "edit" ? command.objective : undefined;
@@ -5392,17 +5971,16 @@ export class ProxySessionController {
5392
5971
  await this.sessionHydrationOperations.run(loaded.record.localSessionId, async () => {
5393
5972
  await loaded.runtime.setReasoningEffort(loaded.record.localSessionId, effort);
5394
5973
  this.store.updateRuntimeSession(loaded.record.localSessionId, { reasoningEffort: effort });
5395
- await this.persistAgentExecutionDefaults(loaded.record.localSessionId);
5396
5974
  });
5397
5975
  if (options.updateMessageId) {
5398
5976
  await this.openExecutionSettingsNow(contextKey, "thinking", {
5399
5977
  sessionId: loaded.record.localSessionId,
5400
5978
  updateMessageId: options.updateMessageId,
5401
- notice: `思考强度已切换为 ${cardCode(effort)},并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
5979
+ notice: `思考强度已切换为 ${cardCode(effort)},只影响当前任务,从下一次请求生效。`,
5402
5980
  });
5403
5981
  return;
5404
5982
  }
5405
- await this.outbound.sendText(contextKey, `思考强度已切换为 ${effort},并已保存为 ${loaded.record.agentName} Agent 的默认设置,从下一次请求生效。`);
5983
+ await this.outbound.sendText(contextKey, `思考强度已切换为 ${effort},只影响当前任务,从下一次请求生效。`);
5406
5984
  }
5407
5985
  async permissions(contextKey, mode, options = {}) {
5408
5986
  const record = options.sessionId ? this.requireSession(contextKey, options.sessionId) : this.requireCurrentSession(contextKey);
@@ -5427,21 +6005,20 @@ export class ProxySessionController {
5427
6005
  loaded.session = loaded.runtime.getSession(record.localSessionId) ?? loaded.session;
5428
6006
  loaded.session.permissionMode = mode;
5429
6007
  this.store.updateRuntimeSession(record.localSessionId, { permissionMode: mode });
5430
- await this.persistAgentExecutionDefaults(record.localSessionId);
5431
6008
  });
5432
6009
  if (options.updateMessageId) {
5433
6010
  await this.openExecutionSettingsNow(contextKey, "permission", {
5434
6011
  sessionId: loaded.record.localSessionId,
5435
6012
  updateMessageId: options.updateMessageId,
5436
6013
  notice: mode === "auto"
5437
- ? `已切换为自动执行模式,并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`
5438
- : `已切换为执行前确认模式,并已保存为 ${cardCode(loaded.record.agentName)} Agent 的默认设置,从下一次请求生效。`,
6014
+ ? "已切换为自动执行模式,只影响当前任务,从下一次请求生效。"
6015
+ : "已切换为执行前确认模式,只影响当前任务,从下一次请求生效。",
5439
6016
  });
5440
6017
  return;
5441
6018
  }
5442
6019
  await this.outbound.sendText(contextKey, mode === "auto"
5443
- ? `已切换为自动执行模式,并已保存为 ${loaded.record.agentName} Agent 的默认设置。`
5444
- : `已切换为执行前确认模式,并已保存为 ${loaded.record.agentName} Agent 的默认设置。`);
6020
+ ? "已切换为自动执行模式,只影响当前任务,从下一次请求生效。"
6021
+ : "已切换为执行前确认模式,只影响当前任务,从下一次请求生效。");
5445
6022
  }
5446
6023
  taskTurnIds(current) {
5447
6024
  const ids = this.store.listTaskTurnGraphIndex(current.localSessionId).map((turn) => turn.turnId);
@@ -5587,7 +6164,7 @@ export class ProxySessionController {
5587
6164
  }
5588
6165
  if (current.lastTurnStatus === "running" && current.lastTurnId === turnId
5589
6166
  && !this.store.getTurnPromptSummary(turnId)) {
5590
- 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)));
5591
6168
  return;
5592
6169
  }
5593
6170
  await this.loadTurnDetails(turnId);
@@ -6150,7 +6727,7 @@ export class ProxySessionController {
6150
6727
  projectActions,
6151
6728
  cardEntry: {
6152
6729
  reference: entry.reference,
6153
- summary: `${offset + index + 1}. ${marker}${title} · ${entry.agentName}`,
6730
+ summary: `${offset + index + 1}. ${marker}${title} · ${entry.agentName}${entry.status === "待核实" ? " · 待核实" : ""}`,
6154
6731
  detailLines: [
6155
6732
  `**最新 Prompt**:${cardText(lastUserPrompt)}`,
6156
6733
  `<font color='grey'>最近更新:${cardText(entry.updatedLabel)}</font>`,
@@ -6687,11 +7264,11 @@ export class ProxySessionController {
6687
7264
  queued = this.store.countQueuedPrompts(current.localSessionId);
6688
7265
  snapshot = turnViewSnapshot(current.lastTurnId ? this.store.getTurnSnapshot(current.lastTurnId) : undefined);
6689
7266
  const waitingForApproval = snapshot?.turnId === current.lastTurnId && snapshot?.status === "waiting_for_approval";
6690
- const statusLabel = waitingForApproval ? "等待确认"
7267
+ const statusLabel = current.lastTurnStatus === "unknown" ? "待核实" : waitingForApproval ? "等待确认"
6691
7268
  : remoteActive && remote && localCurrent && !isBotOwnedActiveTurn(localCurrent, remote)
6692
7269
  ? "外部执行中"
6693
7270
  : sessionStatusLabel(current.status, activeTurnId);
6694
- const resultLabel = waitingForApproval ? "等待确认" : remoteActive
7271
+ const resultLabel = current.lastTurnStatus === "unknown" ? "待核实" : waitingForApproval ? "等待确认" : remoteActive
6695
7272
  ? "执行中"
6696
7273
  : remoteTurnStatusLabel(remote?.lastTurnStatus ?? current.lastTurnStatus);
6697
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)}`);
@@ -6906,28 +7483,6 @@ export class ProxySessionController {
6906
7483
  throw new Error(`未知 agent:${agentName}`);
6907
7484
  return agent;
6908
7485
  }
6909
- async persistAgentExecutionDefaults(localSessionId, candidate) {
6910
- const record = this.store.getSession(localSessionId);
6911
- if (!record)
6912
- throw new Error(`找不到任务:${localSessionId}`);
6913
- return this.agentDefaultsOperations.run(record.agentName, () => this.persistAgentExecutionDefaultsNow(localSessionId, candidate));
6914
- }
6915
- async persistAgentExecutionDefaultsNow(localSessionId, candidate) {
6916
- const record = this.store.getSession(localSessionId);
6917
- if (!record)
6918
- throw new Error(`找不到任务:${localSessionId}`);
6919
- const session = candidate ?? record;
6920
- const agent = this.ensureAgent(session.agentName);
6921
- const observed = {
6922
- ...(session.modelProvider?.trim() ? { modelProvider: session.modelProvider } : {}),
6923
- ...(session.model?.trim() ? { model: session.model } : {}),
6924
- ...(session.reasoningEffort?.trim() ? { reasoningEffort: session.reasoningEffort } : {}),
6925
- ...(session.permissionMode ? { permissionMode: session.permissionMode } : {}),
6926
- };
6927
- const defaults = { ...(agent.defaults ?? {}), ...observed };
6928
- await this.lifecycle?.persistAgentExecutionDefaults?.(session.agentName, defaults);
6929
- agent.defaults = defaults;
6930
- }
6931
7486
  agentLabel(agentName) {
6932
7487
  return this.ensureAgent(agentName).title;
6933
7488
  }
@@ -7535,9 +8090,11 @@ function mergeTaskList(localSessions, remoteSessions, currentLocalSessionId, lat
7535
8090
  if (local)
7536
8091
  representedLocalIds.add(local.localSessionId);
7537
8092
  const active = remote.status === "active" || remote.lastTurnStatus === "inProgress";
7538
- const status = remote.status === "active" || remote.lastTurnStatus === "inProgress"
7539
- ? local && isBotOwnedActiveTurn(local, remote) ? "执行中" : "外部执行中"
7540
- : 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);
7541
8098
  const recencyAt = remote.recencyAt ?? remote.updatedAt;
7542
8099
  return {
7543
8100
  reference: remoteSessionReference(agentName, remote.id),
@@ -7567,7 +8124,7 @@ function mergeTaskList(localSessions, remoteSessions, currentLocalSessionId, lat
7567
8124
  agentName: local.agentName,
7568
8125
  title: local.title ?? "未命名任务",
7569
8126
  cwd: local.cwd,
7570
- status: sessionStatusLabel(local.status),
8127
+ status: local.lastTurnStatus === "unknown" ? "待核实" : sessionStatusLabel(local.status),
7571
8128
  active: local.status === "running",
7572
8129
  current: local.localSessionId === currentLocalSessionId,
7573
8130
  lastUserPrompt: latestLocalUserPrompts.get(local.localSessionId),
@@ -7767,6 +8324,7 @@ function remoteTurnStatusLabel(status) {
7767
8324
  failed: "失败",
7768
8325
  running: "执行中",
7769
8326
  cancelled: "已停止",
8327
+ unknown: "待核实",
7770
8328
  };
7771
8329
  return status ? labels[status] ?? status : "尚无执行记录";
7772
8330
  }
@@ -7783,6 +8341,7 @@ function turnViewStatusLabel(status) {
7783
8341
  running: "执行中",
7784
8342
  tool_running: "工具执行中",
7785
8343
  waiting_for_approval: "等待确认",
8344
+ unknown: "待核实",
7786
8345
  completed: "已完成",
7787
8346
  cancelled: "已停止",
7788
8347
  failed: "失败",
@@ -7880,6 +8439,9 @@ function mapRemoteTurnStatus(status) {
7880
8439
  function mergeRemoteTaskStatus(record, remote) {
7881
8440
  if (!remote)
7882
8441
  return record;
8442
+ if (record.lastTurnStatus === "unknown"
8443
+ && (!remote.lastTurnStatus || remote.lastTurnId !== record.lastTurnId))
8444
+ return record;
7883
8445
  const remoteTurnStatus = mapRemoteTurnStatus(remote.lastTurnStatus);
7884
8446
  const createdAt = remote.createdAt === undefined
7885
8447
  ? record.createdAt
@@ -8268,28 +8830,9 @@ function selectProviderReasoningEffort(model, previousEffort) {
8268
8830
  function recoveryCardPrompt(prompt) {
8269
8831
  return `恢复重启前的任务:${prompt}`;
8270
8832
  }
8271
- function recoveryRuntimePrompt(prompt) {
8272
- return [
8273
- "Agent Bot restarted while the previous turn was still running.",
8274
- "Continue the unfinished task in the current task and workspace.",
8275
- "Inspect the existing conversation, files, and completed tool effects first. Do not repeat completed or irreversible actions.",
8276
- "Finish the original request:",
8277
- "",
8278
- prompt,
8279
- ].join("\n");
8280
- }
8281
8833
  function llmRetryCardPrompt(prompt, retryNumber) {
8282
8834
  return `自动重试 ${retryNumber}/${MAX_LLM_TURN_RETRIES}:${prompt}`;
8283
8835
  }
8284
- function llmRetryRuntimePrompt(prompt, retryNumber) {
8285
- return [
8286
- `Agent Bot is automatically retrying this request after a transient LLM service failure (${retryNumber}/${MAX_LLM_TURN_RETRIES}).`,
8287
- "Continue in the current task and workspace. Inspect the conversation, files, and completed tool effects before acting.",
8288
- "Do not repeat completed or irreversible actions. Finish the original request:",
8289
- "",
8290
- prompt,
8291
- ].join("\n");
8292
- }
8293
8836
  function isRetryableLlmTurnFailure(message) {
8294
8837
  const normalized = message.trim().toLowerCase();
8295
8838
  if (!normalized)
@@ -8318,15 +8861,7 @@ function isRetryableLlmTurnFailure(message) {
8318
8861
  ].some((pattern) => pattern.test(normalized));
8319
8862
  }
8320
8863
  function remoteTurnMatchesAttempt(remote, attempt) {
8321
- if (!remote?.lastTurnId)
8322
- return false;
8323
- if (attempt.turnId)
8324
- return remote.lastTurnId === attempt.turnId;
8325
- const remoteUpdatedAt = remote.updatedAt === undefined ? undefined : normalizeRemoteTimestamp(remote.updatedAt);
8326
- const acceptedAt = Date.parse(attempt.createdAt);
8327
- return remoteUpdatedAt !== undefined
8328
- && Number.isFinite(acceptedAt)
8329
- && remoteUpdatedAt >= acceptedAt - 1_000;
8864
+ return Boolean(attempt.turnId && remote?.lastTurnId === attempt.turnId);
8330
8865
  }
8331
8866
  function isRecoveryAttemptRecent(attempt, cutoff) {
8332
8867
  const updatedAt = Date.parse(attempt.updatedAt);