@keyou007/agent-bot 0.1.27-alpha.2 → 0.1.27-alpha.4

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 (156) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +78 -13
  3. package/README.zh.md +78 -13
  4. package/assets/agent-bot.ico +0 -0
  5. package/assets/roboto-mono-OFL.txt +93 -0
  6. package/assets/roboto-mono-latin.woff2 +0 -0
  7. package/assets/workspace-drafts.js +88 -0
  8. package/assets/workspace-sessions.js +1935 -232
  9. package/assets/workspace.css +360 -35
  10. package/assets/workspace.js +2115 -249
  11. package/dist/cli/SelfUpdateObserver.js +124 -0
  12. package/dist/cli/SelfUpdateObserver.js.map +1 -0
  13. package/dist/cli/SelfUpdateRunner.js +267 -70
  14. package/dist/cli/SelfUpdateRunner.js.map +1 -1
  15. package/dist/cli/SelfUpdater.js +54 -15
  16. package/dist/cli/SelfUpdater.js.map +1 -1
  17. package/dist/cli/controlProtocol.js.map +1 -1
  18. package/dist/cli/help.js +6 -0
  19. package/dist/cli/help.js.map +1 -1
  20. package/dist/cli.js +85 -6
  21. package/dist/cli.js.map +1 -1
  22. package/dist/codex/CodexEventMapper.js +29 -5
  23. package/dist/codex/CodexEventMapper.js.map +1 -1
  24. package/dist/codex/CodexRuntime.js +3 -0
  25. package/dist/codex/CodexRuntime.js.map +1 -1
  26. package/dist/feishu/CardRenderer.js +45 -13
  27. package/dist/feishu/CardRenderer.js.map +1 -1
  28. package/dist/feishu/ConsoleFeishuClient.js +4 -0
  29. package/dist/feishu/ConsoleFeishuClient.js.map +1 -1
  30. package/dist/feishu/FeishuMarkdown.js +2 -14
  31. package/dist/feishu/FeishuMarkdown.js.map +1 -1
  32. package/dist/feishu/FeishuMessageClient.js +9 -0
  33. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  34. package/dist/feishu/FeishuTurnPresenter.js +26 -14
  35. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  36. package/dist/index.js +47 -12
  37. package/dist/index.js.map +1 -1
  38. package/dist/local-files/DiagramPreview.js +11 -6
  39. package/dist/local-files/DiagramPreview.js.map +1 -1
  40. package/dist/local-files/GitDiffPreview.js +40 -10
  41. package/dist/local-files/GitDiffPreview.js.map +1 -1
  42. package/dist/local-files/LiveMarkup.js +104 -0
  43. package/dist/local-files/LiveMarkup.js.map +1 -0
  44. package/dist/local-files/LocalFileViewerServer.js +219 -129
  45. package/dist/local-files/LocalFileViewerServer.js.map +1 -1
  46. package/dist/local-files/MarkdownExport.js +54 -0
  47. package/dist/local-files/MarkdownExport.js.map +1 -0
  48. package/dist/local-files/PreviewCodeFont.js +11 -0
  49. package/dist/local-files/PreviewCodeFont.js.map +1 -0
  50. package/dist/local-files/PreviewSyntaxHighlight.js +73 -0
  51. package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
  52. package/dist/local-files/ToolCommandDisplay.js +111 -0
  53. package/dist/local-files/ToolCommandDisplay.js.map +1 -0
  54. package/dist/local-files/TurnPreviewPage.js +23 -269
  55. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  56. package/dist/local-files/WorkspaceFileEvents.js +206 -0
  57. package/dist/local-files/WorkspaceFileEvents.js.map +1 -0
  58. package/dist/local-files/WorkspaceFiles.js +79 -3
  59. package/dist/local-files/WorkspaceFiles.js.map +1 -1
  60. package/dist/local-files/WorkspaceImages.js +15 -0
  61. package/dist/local-files/WorkspaceImages.js.map +1 -0
  62. package/dist/local-files/WorkspacePage.js +20 -5
  63. package/dist/local-files/WorkspacePage.js.map +1 -1
  64. package/dist/local-files/WorkspaceSessions.js +881 -79
  65. package/dist/local-files/WorkspaceSessions.js.map +1 -1
  66. package/dist/local-files/WorkspaceTimeline.js +105 -0
  67. package/dist/local-files/WorkspaceTimeline.js.map +1 -0
  68. package/dist/presentation/OutboundRouter.js +13 -6
  69. package/dist/presentation/OutboundRouter.js.map +1 -1
  70. package/dist/presentation/TurnStateReducer.js +28 -21
  71. package/dist/presentation/TurnStateReducer.js.map +1 -1
  72. package/dist/proxy/ProxySessionController.js +229 -92
  73. package/dist/proxy/ProxySessionController.js.map +1 -1
  74. package/dist/proxy/TaskMetadata.js +86 -0
  75. package/dist/proxy/TaskMetadata.js.map +1 -0
  76. package/dist/scheduling/ScheduleCards.js +10 -4
  77. package/dist/scheduling/ScheduleCards.js.map +1 -1
  78. package/dist/scheduling/ScheduleCommand.js +4 -0
  79. package/dist/scheduling/ScheduleCommand.js.map +1 -1
  80. package/dist/scheduling/ScheduledTaskStore.js +51 -12
  81. package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
  82. package/dist/scheduling/types.js +18 -4
  83. package/dist/scheduling/types.js.map +1 -1
  84. package/dist/state/StateStore.js +145 -19
  85. package/dist/state/StateStore.js.map +1 -1
  86. package/dist/state/TurnPreviewJournal.js +143 -36
  87. package/dist/state/TurnPreviewJournal.js.map +1 -1
  88. package/dist/state/TurnToolText.js +172 -0
  89. package/dist/state/TurnToolText.js.map +1 -0
  90. package/dist/state/migrations.js +4 -0
  91. package/dist/state/migrations.js.map +1 -1
  92. package/dist/supervision/SafeRestartNotifier.js +9 -6
  93. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  94. package/dist/terminal/TerminalPage.js +5 -0
  95. package/dist/terminal/TerminalPage.js.map +1 -1
  96. package/dist/updates/AutomaticUpdatePreparer.js +63 -12
  97. package/dist/updates/AutomaticUpdatePreparer.js.map +1 -1
  98. package/dist/updates/ManualUpdateController.js +7 -2
  99. package/dist/updates/ManualUpdateController.js.map +1 -1
  100. package/dist/utils/promptAttachments.js +20 -0
  101. package/dist/utils/promptAttachments.js.map +1 -0
  102. package/dist/utils/toolTimestamp.js +6 -0
  103. package/dist/utils/toolTimestamp.js.map +1 -0
  104. package/npm-shrinkwrap.json +2 -2
  105. package/package.json +1 -1
  106. package/skills/agent-bot/SKILL.md +23 -2
  107. package/src/cli/SelfUpdateObserver.ts +111 -0
  108. package/src/cli/SelfUpdateRunner.ts +271 -85
  109. package/src/cli/SelfUpdater.ts +53 -16
  110. package/src/cli/controlProtocol.ts +1 -0
  111. package/src/cli/help.ts +6 -0
  112. package/src/cli.ts +71 -5
  113. package/src/codex/CodexEventMapper.ts +25 -5
  114. package/src/codex/CodexRuntime.ts +4 -0
  115. package/src/feishu/CardRenderer.ts +48 -13
  116. package/src/feishu/ConsoleFeishuClient.ts +6 -1
  117. package/src/feishu/FeishuMarkdown.ts +2 -14
  118. package/src/feishu/FeishuMessageClient.ts +10 -0
  119. package/src/feishu/FeishuTurnPresenter.ts +22 -8
  120. package/src/feishu/types.ts +1 -0
  121. package/src/index.ts +47 -12
  122. package/src/local-files/DiagramPreview.ts +11 -6
  123. package/src/local-files/GitDiffPreview.ts +38 -10
  124. package/src/local-files/LiveMarkup.ts +103 -0
  125. package/src/local-files/LocalFileViewerServer.ts +207 -132
  126. package/src/local-files/MarkdownExport.ts +54 -0
  127. package/src/local-files/PreviewCodeFont.ts +12 -0
  128. package/src/local-files/PreviewSyntaxHighlight.ts +75 -0
  129. package/src/local-files/ToolCommandDisplay.ts +104 -0
  130. package/src/local-files/TurnPreviewPage.ts +23 -254
  131. package/src/local-files/WorkspaceFileEvents.ts +186 -0
  132. package/src/local-files/WorkspaceFiles.ts +72 -5
  133. package/src/local-files/WorkspaceImages.ts +10 -0
  134. package/src/local-files/WorkspacePage.ts +20 -5
  135. package/src/local-files/WorkspaceSessions.ts +811 -82
  136. package/src/local-files/WorkspaceTimeline.ts +109 -0
  137. package/src/presentation/OutboundRouter.ts +15 -4
  138. package/src/presentation/TurnStateReducer.ts +27 -18
  139. package/src/presentation/turnViewTypes.ts +2 -0
  140. package/src/proxy/ProxySessionController.ts +226 -77
  141. package/src/proxy/TaskMetadata.ts +81 -0
  142. package/src/runtime/types.ts +2 -1
  143. package/src/scheduling/ScheduleCards.ts +10 -4
  144. package/src/scheduling/ScheduleCommand.ts +4 -0
  145. package/src/scheduling/ScheduledTaskStore.ts +54 -9
  146. package/src/scheduling/types.ts +24 -4
  147. package/src/state/StateStore.ts +157 -20
  148. package/src/state/TurnPreviewJournal.ts +138 -34
  149. package/src/state/TurnToolText.ts +156 -0
  150. package/src/state/migrations.ts +4 -0
  151. package/src/supervision/SafeRestartNotifier.ts +9 -6
  152. package/src/terminal/TerminalPage.ts +5 -0
  153. package/src/updates/AutomaticUpdatePreparer.ts +52 -11
  154. package/src/updates/ManualUpdateController.ts +8 -3
  155. package/src/utils/promptAttachments.ts +24 -0
  156. package/src/utils/toolTimestamp.ts +5 -0
@@ -17,13 +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";
20
+ import { scheduleCommandSchema, scheduleDisplayPrompt } from "../scheduling/types.js";
21
+ import { appendDownloadedFiles, defaultResourcePromptFromCounts, queuedPromptContent } from "../utils/promptAttachments.js";
21
22
  import { renderSettingsCard } from "../feishu/SettingsCard.js";
22
23
  import { renderSchedule, renderScheduleList, renderScheduleForm } from "../scheduling/ScheduleCards.js";
23
24
  import { classifyFileContent } from "../local-files/LocalFileViewerServer.js";
24
25
  import { errorLogValue } from "../logging/errorLogValue.js";
25
26
  import { createTurnViewState, hydrateTurnViewState } from "../presentation/TurnStateReducer.js";
26
27
  import { buildTurnGraphRows } from "../presentation/turnGraph.js";
28
+ import { splitMarkdown } from "../presentation/splitMarkdown.js";
27
29
  import { displayRuntimeError, isResponseContinuationError } from "../runtime/responseErrors.js";
28
30
  import { TurnNotSubmittedError, TurnStoppedBeforeSubmissionError } from "../runtime/submissionErrors.js";
29
31
  import { isActiveShellCommandJob, ShellCommandJobManager, } from "../shell/ShellCommandJobManager.js";
@@ -326,10 +328,13 @@ export class ProxySessionController {
326
328
  const currentId = this.store.getUserContext(message.contextKey)?.currentSessionId;
327
329
  if (!this.store.inboundMessages.claim(message, currentId, currentId ? this.store.executionGeneration(currentId) : 0))
328
330
  return;
329
- if (this.inboundPaused || this.recoveryClosed)
331
+ if (!this.acceptingInboundMessages)
330
332
  return;
331
333
  await this.processAcceptedMessage(message);
332
334
  }
335
+ get acceptingInboundMessages() {
336
+ return !this.inboundPaused && !this.recoveryClosed;
337
+ }
333
338
  get pendingInboundMessages() {
334
339
  return this.inboundInFlight.size + this.inboundActionsInFlight;
335
340
  }
@@ -1230,14 +1235,19 @@ export class ProxySessionController {
1230
1235
  return `Task title changed to: ${normalizedTitle}`;
1231
1236
  }
1232
1237
  async controlSendTaskPrompt(localSessionId, text, workspace) {
1233
- const promptText = text.trim();
1234
- if (!promptText)
1238
+ const images = workspace?.localImagePaths;
1239
+ const files = workspace?.files;
1240
+ const promptText = text.trim() || (files?.length ? defaultResourcePromptFromCounts(images?.length ?? 0, files.length) : "");
1241
+ const echoedPrompt = files?.length ? `${promptText}\n\n附件:${files.map((file) => file.fileName).join("、")}` : promptText;
1242
+ if (!promptText && !images?.length)
1235
1243
  throw new Error("The Prompt cannot be empty.");
1236
1244
  const record = this.store.getSession(localSessionId);
1237
1245
  if (!record || record.status === "closed")
1238
1246
  throw new Error(`Task not found: ${localSessionId}`);
1239
1247
  const runtime = this.runtimes.forAgent(record.agentName);
1240
1248
  const activeTurnId = runtime.getSession(localSessionId)?.activeTurnId;
1249
+ const expectedTurnId = workspace?.expectedTurnId;
1250
+ assertWorkspaceSteerTurn(expectedTurnId, activeTurnId);
1241
1251
  const routedContextKey = this.outbound.getSessionContextKey(localSessionId);
1242
1252
  const responseContextKey = (activeTurnId ? this.store.getTurnContextKey(activeTurnId) ?? routedContextKey : undefined)
1243
1253
  ?? (record.lastTurnId ? this.store.getTurnContextKey(record.lastTurnId) : undefined)
@@ -1261,18 +1271,28 @@ export class ProxySessionController {
1261
1271
  ?? { ...record, contextKey: responseContextKey };
1262
1272
  const previous = this.messageQueues.get(responseContextKey) ?? Promise.resolve();
1263
1273
  const next = previous.catch(() => undefined).then(async () => {
1264
- this.outbound.registerSession(scopedRecord.localSessionId, responseContextKey, scopedRecord.title, scopedRecord.cwd, this.agentLabel(scopedRecord.agentName), scopedRecord.model, scopedRecord.modelProvider);
1274
+ this.outbound.registerSession(scopedRecord.localSessionId, responseContextKey, scopedRecord.title, scopedRecord.cwd, this.agentLabel(scopedRecord.agentName), scopedRecord.model, scopedRecord.modelProvider, scopedRecord.reasoningEffort);
1265
1275
  if (workspace && this.store.getSession(localSessionId)?.status === "closed")
1266
1276
  throw new Error("任务已归档。");
1267
- workspace?.onPosting();
1268
- const promptMessageId = await this.outbound.withReplyTarget(responseContextKey, existingReplyTarget, () => this.outbound.sendText(responseContextKey, promptText));
1277
+ assertWorkspaceSteerTurn(expectedTurnId, runtime.getSession(localSessionId)?.activeTurnId);
1278
+ const executionGeneration = expectedTurnId ? this.store.executionGeneration(localSessionId) : undefined;
1279
+ const promptMessageId = await this.outbound.withReplyTarget(responseContextKey, existingReplyTarget, () => {
1280
+ if (images?.length)
1281
+ return this.outbound.sendPromptImages(responseContextKey, echoedPrompt, images, () => workspace?.onPosting());
1282
+ workspace?.onPosting();
1283
+ return this.outbound.sendText(responseContextKey, echoedPrompt);
1284
+ });
1269
1285
  workspace?.onPosted();
1286
+ if (executionGeneration !== undefined) {
1287
+ this.assertExecutionGeneration(localSessionId, executionGeneration);
1288
+ assertWorkspaceSteerTurn(expectedTurnId, runtime.getSession(localSessionId)?.activeTurnId);
1289
+ }
1270
1290
  const turnReplyTarget = isThreadContextKey(responseContextKey)
1271
1291
  ? promptMessageId
1272
1292
  ? { messageId: promptMessageId, replyInThread: true }
1273
1293
  : existingReplyTarget
1274
1294
  : undefined;
1275
- await this.promptSession(scopedRecord, responseContextKey, promptText, undefined, turnReplyTarget);
1295
+ await this.promptSession(scopedRecord, responseContextKey, files?.length ? appendDownloadedFiles(promptText, files) : promptText, undefined, turnReplyTarget, images, files?.length ? promptText : undefined, workspace);
1276
1296
  this.store.audit(responseContextKey, "task_prompt_sent", {
1277
1297
  localSessionId,
1278
1298
  source: workspace ? "workspace" : "cli",
@@ -1373,6 +1393,33 @@ export class ProxySessionController {
1373
1393
  : {};
1374
1394
  return this.outbound.withReplyTarget(contextKey, replyTarget, () => this.createSession(contextKey, agentName, cwd, true, false, undefined, undefined, requestedTitle, settings));
1375
1395
  }
1396
+ controlWorkspaceAgents() {
1397
+ const agents = Object.entries(this.config.agents).filter(([, agent]) => agent.kind === "app-server")
1398
+ .map(([name, agent]) => ({ name, title: agent.title }));
1399
+ return { agents, defaultAgent: agents.find(({ name }) => name === this.config.defaults.agent)?.name ?? agents[0]?.name };
1400
+ }
1401
+ async controlWorkspaceDraftSettings(agentName) {
1402
+ const agent = this.ensureAgent(agentName);
1403
+ if (agent.kind !== "app-server")
1404
+ throw new Error("请选择支持 Workspace 的 App Server Agent。");
1405
+ const { model, modelProvider, reasoningEffort } = agent.defaults ?? {};
1406
+ const models = await this.runtimes.forAgent(agentName).listModels(modelProvider, model);
1407
+ return { model, provider: modelProvider, thinking: reasoningEffort, models };
1408
+ }
1409
+ controlCreateWorkspaceTask(localSessionId, owner, title, agentName, cwd, model, reasoningEffort) {
1410
+ const agent = this.ensureAgent(agentName);
1411
+ if (agent.kind !== "app-server")
1412
+ throw new Error("请选择支持 Workspace 的 App Server Agent。");
1413
+ const settings = model
1414
+ ? { ...agent.defaults, model, reasoningEffort }
1415
+ : mergeExecutionSettings(agent.defaults ?? {}, { reasoningEffort });
1416
+ const initialTitle = normalizeTaskTitle(title);
1417
+ const contextKey = `open_id:${owner}`;
1418
+ const root = cwd ?? createProjectlessWorkspace({ prompt: initialTitle }).cwd;
1419
+ this.store.createSession({ localSessionId, contextKey, agentName, cwd: root, status: "ready" });
1420
+ this.store.updateRuntimeSession(localSessionId, { ...settings, title: initialTitle, runtimeKind: this.runtimes.forAgent(agentName).kind });
1421
+ return this.store.getSession(localSessionId);
1422
+ }
1376
1423
  async controlForkTask(localSessionId) {
1377
1424
  const source = this.requireControlSession(localSessionId);
1378
1425
  const contextKey = this.controlSessionContextKey(source);
@@ -1391,6 +1438,14 @@ export class ProxySessionController {
1391
1438
  task: this.store.getSession(forked.record.localSessionId) ?? forked.record,
1392
1439
  };
1393
1440
  }
1441
+ async controlForkWorkspaceTask(localSessionId, turnId) {
1442
+ const source = this.requireControlSession(localSessionId);
1443
+ const plan = this.prepareForkSessionFromTurn(source, turnId, undefined, "当前任务");
1444
+ const origin = this.store.getTurnRuntimeOrigin(turnId);
1445
+ if (origin?.agentName === source.agentName)
1446
+ plan.remoteSessionId = origin.remoteSessionId;
1447
+ return (await this.forkSessionIntoContext(this.controlSessionContextKey(source), plan, false)).record;
1448
+ }
1394
1449
  async controlSwitchTask(localSessionId, targetLocalSessionId, previous = false) {
1395
1450
  const anchor = this.requireControlSession(localSessionId);
1396
1451
  const contextKey = this.controlSessionContextKey(anchor);
@@ -1404,9 +1459,21 @@ export class ProxySessionController {
1404
1459
  return;
1405
1460
  await this.scheduleNextQueuedPrompt(localSessionId);
1406
1461
  }
1407
- async notifySchedule(job, text) {
1462
+ async notifySchedule(job, text, images) {
1408
1463
  const target = job.replyMessageId ? { messageId: job.replyMessageId, replyInThread: true } : undefined;
1409
- await this.outbound.withReplyTarget(job.contextKey, target, () => this.outbound.sendText(job.contextKey, text));
1464
+ await this.outbound.withReplyTarget(job.contextKey, target, async () => {
1465
+ const parts = splitMarkdown(text);
1466
+ if (images?.length) {
1467
+ const last = parts.pop() ?? "";
1468
+ for (const part of parts)
1469
+ await this.outbound.sendText(job.contextKey, part);
1470
+ await this.outbound.sendPromptImages(job.contextKey, last, images);
1471
+ }
1472
+ else {
1473
+ for (const part of parts)
1474
+ await this.outbound.sendText(job.contextKey, part);
1475
+ }
1476
+ });
1410
1477
  }
1411
1478
  async controlSchedule(command, localSessionId) {
1412
1479
  command = scheduleCommandSchema.parse(command);
@@ -1440,17 +1507,10 @@ export class ProxySessionController {
1440
1507
  await this.outbound.withReplyTarget(job.contextKey, target, () => this.showSchedule(updated));
1441
1508
  return updated;
1442
1509
  }
1443
- if (command.operation === "run") {
1444
- this.assertScheduleTarget(job);
1445
- const run = this.store.schedules.dispatch(job, Date.now(), Date.now(), { manual: true });
1446
- await this.drainScheduledPrompts(job.localSessionId);
1447
- return run;
1510
+ if (command.operation === "run" || command.operation === "resume" || command.operation === "pause" || command.operation === "delete") {
1511
+ return this.controlWorkspaceScheduleAction(job, command.operation);
1448
1512
  }
1449
- if (!["pause", "resume", "delete"].includes(command.operation))
1450
- throw new Error("无效的定时任务操作。");
1451
- if (command.operation === "resume")
1452
- this.assertScheduleTarget(job);
1453
- return this.store.schedules.change(job.id, job.revision, command.operation);
1513
+ throw new Error("无效的定时任务操作。");
1454
1514
  }
1455
1515
  requireSettingsOwner(userId) {
1456
1516
  if (!this.config.feishu.userOpenId || userId !== this.config.feishu.userOpenId) {
@@ -1519,13 +1579,33 @@ export class ProxySessionController {
1519
1579
  }
1520
1580
  await this.outbound.updateInteractiveCard(action.contextKey, messageId, renderSettingsCard(snapshot, action.contextKey, notice));
1521
1581
  }
1522
- createSchedule(input, localSessionId, contextKey, replyMessageId) {
1582
+ controlCreateWorkspaceSchedule(localSessionId, input, request, upload) {
1583
+ const task = this.requireControlSession(localSessionId);
1584
+ return this.createSchedule(input, localSessionId, this.controlSessionContextKey(task), this.controlSessionReplyTarget(task)?.messageId, request, upload);
1585
+ }
1586
+ controlEditWorkspaceSchedule(job, input) {
1587
+ this.assertScheduleTarget(job);
1588
+ const status = job.status === "paused" || job.status === "draft" ? job.status : "enabled";
1589
+ return this.store.schedules.edit(job.id, job.revision, input, undefined, status);
1590
+ }
1591
+ async controlWorkspaceScheduleAction(job, action) {
1592
+ if (action === "confirm" || action === "resume" || action === "run")
1593
+ this.assertScheduleTarget(job);
1594
+ if (action !== "run")
1595
+ return this.store.schedules.change(job.id, job.revision, action);
1596
+ const run = this.store.schedules.dispatch(job, Date.now(), Date.now(), { manual: true });
1597
+ await this.drainScheduledPrompts(job.localSessionId);
1598
+ return run;
1599
+ }
1600
+ createSchedule(input, localSessionId, contextKey, replyMessageId, enableRequest, upload) {
1523
1601
  if (!this.config.feishu.userOpenId)
1524
1602
  throw new Error("请先配置 Agent Bot 所有者,才能创建定时任务。");
1525
1603
  this.requireSession(contextKey, localSessionId);
1526
1604
  if (isThreadContextKey(contextKey) && !replyMessageId)
1527
1605
  throw new Error("缺少话题回复位置,请在原话题中创建计划。");
1528
- return this.store.schedules.create(input, { localSessionId, contextKey, replyMessageId, ownerId: this.config.feishu.userOpenId });
1606
+ if (enableRequest && !this.outbound.canRoute(contextKey))
1607
+ throw new Error("任务的原始会话不可用,无法创建定时计划。");
1608
+ return this.store.schedules.create(input, { localSessionId, contextKey, replyMessageId, ownerId: this.config.feishu.userOpenId }, undefined, enableRequest, upload);
1529
1609
  }
1530
1610
  assertScheduleTarget(job) {
1531
1611
  if (job.ownerId !== this.config.feishu.userOpenId)
@@ -1598,7 +1678,11 @@ export class ProxySessionController {
1598
1678
  const string = (key) => typeof form[key] === "string" ? form[key] : "";
1599
1679
  const input = { name: string("name"), prompt: string("prompt"), timeZone: string("timeZone"),
1600
1680
  maxDelayMinutes: Number(string("maxDelayMinutes")), catchUpMinutes: Number(string("catchUpMinutes")),
1681
+ ...(string("startsAt").trim() ? { startsAt: string("startsAt") } : {}),
1682
+ ...(string("endsAt").trim() ? { endsAt: string("endsAt") } : {}),
1601
1683
  ...(string("cron").trim() ? { cron: string("cron") } : {}), ...(string("at").trim() ? { at: string("at") } : {}) };
1684
+ if (job?.spec.prompt && job.spec.prompt.length > 1000 && !input.prompt.trim())
1685
+ input.prompt = job.spec.prompt;
1602
1686
  const updated = job ? this.store.schedules.edit(job.id, job.revision, input)
1603
1687
  : this.createSchedule(input, String(action.value.sessionId ?? ""), action.contextKey, replyTarget?.messageId);
1604
1688
  return this.showSchedule(updated, messageId);
@@ -1616,23 +1700,47 @@ export class ProxySessionController {
1616
1700
  const updated = this.store.schedules.change(job.id, job.revision, operation);
1617
1701
  await this.showSchedule(updated, messageId);
1618
1702
  }
1619
- async controlQueueTaskPrompt(localSessionId, text) {
1620
- const promptText = text.trim();
1621
- if (!promptText)
1703
+ async controlQueueTaskPrompt(localSessionId, text, localImagePaths, workspaceRequestId, files) {
1704
+ const promptText = text.trim() || (files?.length ? defaultResourcePromptFromCounts(localImagePaths?.length ?? 0, files.length) : "");
1705
+ if (!promptText && !localImagePaths?.length)
1622
1706
  throw new Error("The queued Prompt cannot be empty.");
1623
1707
  const record = this.requireControlSession(localSessionId);
1624
1708
  const contextKey = this.controlSessionContextKey(record);
1625
1709
  const replyTarget = this.controlSessionReplyTarget(record);
1626
- const queued = this.persistQueuedPrompt(record.localSessionId, contextKey, promptText, { replyTarget });
1710
+ const queued = this.persistQueuedPrompt(record.localSessionId, contextKey, files?.length ? appendDownloadedFiles(promptText, files) : promptText, {
1711
+ replyTarget, localImagePaths, promptId: workspaceRequestId ? `workspace:${workspaceRequestId}` : undefined,
1712
+ displayPrompt: files?.length ? promptText : undefined,
1713
+ });
1627
1714
  this.store.audit(contextKey, "queued_prompt_added", {
1628
1715
  promptId: queued.promptId,
1629
1716
  localSessionId: record.localSessionId,
1630
- source: "cli",
1717
+ source: workspaceRequestId ? "workspace" : "cli",
1631
1718
  });
1632
1719
  const queuedCount = this.store.countQueuedPrompts(record.localSessionId);
1633
1720
  await this.scheduleNextQueuedPrompt(record.localSessionId);
1721
+ if (this.store.hasQueuedPrompt(queued.promptId))
1722
+ await this.refreshPromptQueueCards(record.localSessionId);
1634
1723
  return { promptId: queued.promptId, queued: queuedCount };
1635
1724
  }
1725
+ async controlCancelWorkspaceQueue(localSessionId, promptId, request) {
1726
+ const task = this.requireControlSession(localSessionId);
1727
+ const { cancelled, prompt } = this.store.cancelWorkspaceQueuedPrompt(promptId, localSessionId, request);
1728
+ if (prompt)
1729
+ await this.finishQueuedPromptCancellation(prompt, this.controlSessionContextKey(task)).catch(error => {
1730
+ this.logger.warn({ error, localSessionId, promptId }, "Failed to refresh a cancelled Workspace prompt.");
1731
+ });
1732
+ return cancelled;
1733
+ }
1734
+ async controlEditWorkspaceQueue(prompt, content) {
1735
+ this.requireControlSession(prompt.localSessionId);
1736
+ if (!this.store.updateQueuedPrompt(prompt, content))
1737
+ return false;
1738
+ this.store.audit(prompt.contextKey, "queued_prompt_edited", {
1739
+ promptId: prompt.promptId, localSessionId: prompt.localSessionId, source: "workspace",
1740
+ });
1741
+ await this.refreshPromptQueueCards(prompt.localSessionId);
1742
+ return true;
1743
+ }
1636
1744
  controlTaskAgent(localSessionId, agentName) {
1637
1745
  const record = this.requireControlSession(localSessionId);
1638
1746
  const contextKey = this.controlSessionContextKey(record);
@@ -1646,7 +1754,7 @@ export class ProxySessionController {
1646
1754
  agents: Object.entries(this.config.agents).map(([name, agent]) => ({ name, title: agent.title })),
1647
1755
  };
1648
1756
  }
1649
- async controlTaskSettings(localSessionId, setting, value) {
1757
+ async controlTaskSettings(localSessionId, setting, value, options = {}) {
1650
1758
  const record = this.requireControlSession(localSessionId);
1651
1759
  if (setting && !value?.trim())
1652
1760
  throw new Error(`task ${setting} requires a value.`);
@@ -1654,17 +1762,17 @@ export class ProxySessionController {
1654
1762
  if (setting && nextValue) {
1655
1763
  const contextKey = this.controlSessionContextKey(record);
1656
1764
  await this.outbound.withReplyTarget(contextKey, this.controlSessionReplyTarget(record), async () => {
1657
- const options = { sessionId: record.localSessionId };
1765
+ const target = { sessionId: record.localSessionId, quiet: options.quiet };
1658
1766
  if (setting === "provider")
1659
- await this.selectProvider(contextKey, nextValue, options);
1767
+ await this.selectProvider(contextKey, nextValue, target);
1660
1768
  else if (setting === "model")
1661
- await this.model(contextKey, nextValue, options);
1769
+ await this.model(contextKey, nextValue, target);
1662
1770
  else if (setting === "thinking")
1663
- await this.thinking(contextKey, nextValue, options);
1771
+ await this.thinking(contextKey, nextValue, target);
1664
1772
  else {
1665
1773
  if (nextValue !== "auto" && nextValue !== "confirm")
1666
1774
  throw new Error("task permissions accepts auto or confirm.");
1667
- await this.permissions(contextKey, nextValue, options);
1775
+ await this.permissions(contextKey, nextValue, target);
1668
1776
  }
1669
1777
  });
1670
1778
  }
@@ -1748,11 +1856,12 @@ export class ProxySessionController {
1748
1856
  }),
1749
1857
  };
1750
1858
  }
1751
- async controlResetTaskToTurn(localSessionId, turnId) {
1859
+ async controlResetTaskToTurn(localSessionId, turnId, options) {
1752
1860
  const record = this.requireControlSession(localSessionId);
1753
1861
  const contextKey = this.controlSessionContextKey(record);
1754
1862
  await this.runSessionReset(record.localSessionId, async () => {
1755
- await this.outbound.sendText(contextKey, TURN_RESET_STARTED_MESSAGE);
1863
+ if (!options?.quiet)
1864
+ await this.outbound.sendText(contextKey, TURN_RESET_STARTED_MESSAGE);
1756
1865
  await this.performSessionReset(contextKey, record, turnId, false);
1757
1866
  });
1758
1867
  return this.store.getSession(record.localSessionId) ?? record;
@@ -2063,7 +2172,7 @@ export class ProxySessionController {
2063
2172
  : context.contextKey;
2064
2173
  if (!this.outbound.canRoute(turnContextKey))
2065
2174
  continue;
2066
- this.outbound.registerSession(session.localSessionId, turnContextKey, session.title, session.cwd, this.agentLabel(session.agentName), session.model, session.modelProvider);
2175
+ this.outbound.registerSession(session.localSessionId, turnContextKey, session.title, session.cwd, this.agentLabel(session.agentName), session.model, session.modelProvider, session.reasoningEffort);
2067
2176
  if (!session.lastTurnId)
2068
2177
  continue;
2069
2178
  void this.outbound.resumeDelivery(session.localSessionId, turnContextKey, session.lastTurnId).catch((error) => {
@@ -2092,19 +2201,26 @@ export class ProxySessionController {
2092
2201
  });
2093
2202
  }
2094
2203
  }
2095
- async recoverInterruptedTasks() {
2204
+ async recoverInterruptedTasks(updateRecoveryAttemptIds = []) {
2096
2205
  if (this.startupRecovery)
2097
2206
  return this.startupRecovery;
2098
- const recovery = this.runStartupRecovery();
2207
+ const recovery = this.runStartupRecovery(new Set(updateRecoveryAttemptIds));
2099
2208
  this.startupRecovery = recovery;
2100
2209
  return recovery;
2101
2210
  }
2102
- async runStartupRecovery() {
2211
+ async runStartupRecovery(updateRecoveryAttempts) {
2103
2212
  await this.recoverUnprocessedMessages();
2104
2213
  await this.finishPersistedCancellationRequests();
2105
2214
  await this.recoverShellCommandJobs();
2106
2215
  const recoveryCutoff = Date.now() - RECOVERY_ACTIVITY_WINDOW_MS;
2107
2216
  const cutoff = new Date(recoveryCutoff).toISOString();
2217
+ for (const attemptId of updateRecoveryAttempts) {
2218
+ const attempt = this.store.getTurnAttempt(attemptId);
2219
+ const session = attempt && this.store.getSession(attempt.localSessionId);
2220
+ if (attempt && session && this.canContinueAfterRestart(attempt, session)) {
2221
+ this.store.prepareInterruptedTurnAttemptRecovery(attemptId, new Date(0).toISOString());
2222
+ }
2223
+ }
2108
2224
  for (const attempt of this.store.listRecentlyInterruptedTurnAttempts(cutoff)) {
2109
2225
  const session = this.store.getSession(attempt.localSessionId);
2110
2226
  if (session && this.canContinueAfterRestart(attempt, session)) {
@@ -2113,12 +2229,12 @@ export class ProxySessionController {
2113
2229
  }
2114
2230
  this.backfillTurnAttemptsForUpgrade();
2115
2231
  const attempts = this.store.listIncompleteTurnAttempts();
2116
- const recentAttempts = attempts.filter((attempt) => isRecoveryAttemptRecent(attempt, recoveryCutoff));
2232
+ const recentAttempts = attempts.filter((attempt) => updateRecoveryAttempts.has(attempt.attemptId) || isRecoveryAttemptRecent(attempt, recoveryCutoff));
2117
2233
  if (recentAttempts.length > 0) {
2118
2234
  this.logger.warn({ attemptIds: recentAttempts.map((attempt) => attempt.attemptId) }, "Recovering unfinished Agent Bot tasks after startup.");
2119
2235
  }
2120
2236
  for (const attempt of attempts) {
2121
- if (!isRecoveryAttemptRecent(attempt, recoveryCutoff)) {
2237
+ if (!updateRecoveryAttempts.has(attempt.attemptId) && !isRecoveryAttemptRecent(attempt, recoveryCutoff)) {
2122
2238
  await this.expireStaleTurnAttempt(attempt);
2123
2239
  continue;
2124
2240
  }
@@ -2216,7 +2332,7 @@ export class ProxySessionController {
2216
2332
  continue;
2217
2333
  }
2218
2334
  if (session) {
2219
- this.outbound.registerSession(session.localSessionId, attempt.contextKey, session.title, session.cwd, this.agentLabel(session.agentName), session.model, session.modelProvider);
2335
+ this.outbound.registerSession(session.localSessionId, attempt.contextKey, session.title, session.cwd, this.agentLabel(session.agentName), session.model, session.modelProvider, session.reasoningEffort);
2220
2336
  }
2221
2337
  try {
2222
2338
  if (!session?.remoteSessionId)
@@ -2435,7 +2551,7 @@ export class ProxySessionController {
2435
2551
  const replyTarget = attempt.replyMessageId
2436
2552
  ? { messageId: attempt.replyMessageId, replyInThread: true }
2437
2553
  : undefined;
2438
- this.outbound.registerSession(session.localSessionId, contextKey, session.title, session.cwd, this.agentLabel(session.agentName), session.model, session.modelProvider);
2554
+ this.outbound.registerSession(session.localSessionId, contextKey, session.title, session.cwd, this.agentLabel(session.agentName), session.model, session.modelProvider, session.reasoningEffort);
2439
2555
  if (announce) {
2440
2556
  await this.outbound.withReplyTarget(contextKey, replyTarget, () => this.outbound.sendText(contextKey, "检测到重启前存在未完成任务,正在核对远端执行状态并尝试恢复。")).catch((error) => {
2441
2557
  this.logger.warn({ error, attemptId: attempt.attemptId, contextKey }, "Failed to send the task recovery notification.");
@@ -2601,7 +2717,7 @@ export class ProxySessionController {
2601
2717
  this.store.schedules.finish(attempt.attemptId, "unknown", message);
2602
2718
  if (!session || session.status === "closed")
2603
2719
  return;
2604
- this.outbound.registerSession(session.localSessionId, attempt.contextKey, session.title, session.cwd, this.agentLabel(session.agentName), session.model, session.modelProvider);
2720
+ this.outbound.registerSession(session.localSessionId, attempt.contextKey, session.title, session.cwd, this.agentLabel(session.agentName), session.model, session.modelProvider, session.reasoningEffort);
2605
2721
  const active = this.runtimes.forAgent(session.agentName).getSession(session.localSessionId)?.activeTurnId;
2606
2722
  if (!session.lastTurnId || session.lastTurnId === turnId || session.lastTurnId === attempt.recoveredFromTurnId
2607
2723
  || (!attempt.turnId && !active)) {
@@ -2797,15 +2913,19 @@ export class ProxySessionController {
2797
2913
  }
2798
2914
  await this.promptSession(record, contextKey, text, messageId, replyTarget, localImagePaths, displayPrompt);
2799
2915
  }
2800
- async promptSession(record, contextKey, text, messageId, replyTarget, localImagePaths, displayPrompt) {
2916
+ async promptSession(record, contextKey, text, messageId, replyTarget, localImagePaths, displayPrompt, workspace) {
2801
2917
  this.recoverySupersededSessions.add(record.localSessionId);
2802
2918
  const executionGeneration = this.store.executionGeneration(record.localSessionId);
2919
+ const workspaceRequestId = workspace?.requestId;
2920
+ const workspaceMessageId = workspaceRequestId ? `workspace:${workspaceRequestId}` : undefined;
2921
+ const startOptions = { messageId, displayPrompt, executionGeneration, workspaceRequestId };
2803
2922
  if (this.llmRetryingSessions.has(record.localSessionId) || this.planHandoffs.has(record.localSessionId)) {
2804
2923
  const queued = this.persistQueuedPrompt(record.localSessionId, contextKey, text, {
2805
2924
  localImagePaths,
2806
2925
  messageId,
2807
2926
  replyTarget,
2808
2927
  displayPrompt,
2928
+ promptId: workspaceMessageId,
2809
2929
  });
2810
2930
  this.store.audit(contextKey, "queued_prompt_added_during_llm_retry", {
2811
2931
  promptId: queued.promptId,
@@ -2816,8 +2936,8 @@ export class ProxySessionController {
2816
2936
  }
2817
2937
  const configuredRuntime = this.runtimes.forAgent(record.agentName);
2818
2938
  if (!configuredRuntime.getSession(record.localSessionId)) {
2819
- this.outbound.registerSession(record.localSessionId, contextKey, record.title, record.cwd, this.agentLabel(record.agentName), record.model, record.modelProvider);
2820
- await this.outbound.startPendingTurn(record.localSessionId, contextKey, record.title, replyTarget, displayPrompt ?? text, localImagePaths);
2939
+ this.outbound.registerSession(record.localSessionId, contextKey, record.title, record.cwd, this.agentLabel(record.agentName), record.model, record.modelProvider, record.reasoningEffort);
2940
+ await this.outbound.startPendingTurn(record.localSessionId, contextKey, record.title, replyTarget, displayPrompt ?? text, localImagePaths, workspaceRequestId);
2821
2941
  }
2822
2942
  let loaded;
2823
2943
  try {
@@ -2847,8 +2967,9 @@ export class ProxySessionController {
2847
2967
  }
2848
2968
  }
2849
2969
  this.assertExecutionGeneration(record.localSessionId, executionGeneration);
2850
- this.store.acknowledgeUnknownTurnAttempts(record.localSessionId);
2851
2970
  const activeTurnId = loaded.session.activeTurnId;
2971
+ assertWorkspaceSteerTurn(workspace?.expectedTurnId, activeTurnId);
2972
+ this.store.acknowledgeUnknownTurnAttempts(record.localSessionId);
2852
2973
  if (activeTurnId) {
2853
2974
  const activeContextKey = this.store.getTurnContextKey(activeTurnId);
2854
2975
  const notificationTurn = Boolean(turnViewSnapshot(this.store.getTurnSnapshot(activeTurnId))?.taskNotificationCard);
@@ -2858,6 +2979,7 @@ export class ProxySessionController {
2858
2979
  messageId,
2859
2980
  replyTarget,
2860
2981
  displayPrompt,
2982
+ promptId: workspaceMessageId,
2861
2983
  });
2862
2984
  if (notificationTurn)
2863
2985
  await this.presentPromptQueueCard(record.localSessionId, contextKey);
@@ -2865,7 +2987,7 @@ export class ProxySessionController {
2865
2987
  }
2866
2988
  try {
2867
2989
  await loaded.runtime.steerTurn(record.localSessionId, activeTurnId, runtimePrompt(text, localImagePaths));
2868
- await this.presentSteerMessage(record.localSessionId, activeTurnId, displayPrompt ?? text, messageId, localImagePaths);
2990
+ await this.presentSteerMessage(record.localSessionId, activeTurnId, displayPrompt ?? text, workspaceMessageId ?? messageId, localImagePaths);
2869
2991
  if (messageId)
2870
2992
  await this.bindMessageReactionToTurn(messageId, record.localSessionId, activeTurnId);
2871
2993
  return;
@@ -2874,6 +2996,8 @@ export class ProxySessionController {
2874
2996
  if (!(error instanceof TurnNotSubmittedError)) {
2875
2997
  throw new Error("追加消息的提交结果待核实,未自动重发或入队。请检查执行记录后继续。", { cause: error });
2876
2998
  }
2999
+ if (workspace?.expectedTurnId)
3000
+ throw error;
2877
3001
  this.logger.debug({ error, sessionId: record.localSessionId, activeTurnId }, "Steering failed; reconciling the App Server thread.");
2878
3002
  let current = loaded.runtime.getSession(record.localSessionId);
2879
3003
  try {
@@ -2883,7 +3007,7 @@ export class ProxySessionController {
2883
3007
  this.logger.warn({ error: syncError, sessionId: record.localSessionId }, "Failed to synchronize after steering failure.");
2884
3008
  }
2885
3009
  if (!current?.activeTurnId) {
2886
- const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt, executionGeneration });
3010
+ const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, startOptions);
2887
3011
  if (messageId)
2888
3012
  await this.bindMessageReactionToTurn(messageId, record.localSessionId, turnId);
2889
3013
  return;
@@ -2893,7 +3017,7 @@ export class ProxySessionController {
2893
3017
  try {
2894
3018
  this.assertExecutionGeneration(record.localSessionId, executionGeneration);
2895
3019
  await loaded.runtime.steerTurn(record.localSessionId, current.activeTurnId, runtimePrompt(text, localImagePaths));
2896
- await this.presentSteerMessage(record.localSessionId, current.activeTurnId, displayPrompt ?? text, messageId, localImagePaths);
3020
+ await this.presentSteerMessage(record.localSessionId, current.activeTurnId, displayPrompt ?? text, workspaceMessageId ?? messageId, localImagePaths);
2897
3021
  if (messageId)
2898
3022
  await this.bindMessageReactionToTurn(messageId, record.localSessionId, current.activeTurnId);
2899
3023
  return;
@@ -2910,13 +3034,14 @@ export class ProxySessionController {
2910
3034
  messageId,
2911
3035
  replyTarget,
2912
3036
  displayPrompt,
3037
+ promptId: workspaceMessageId,
2913
3038
  });
2914
3039
  if (notificationTurn)
2915
3040
  await this.presentPromptQueueCard(record.localSessionId, contextKey);
2916
3041
  return;
2917
3042
  }
2918
3043
  }
2919
- const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, { messageId, displayPrompt, executionGeneration });
3044
+ const turnId = await this.startTurn(loaded, text, replyTarget, localImagePaths, startOptions);
2920
3045
  if (messageId)
2921
3046
  await this.bindMessageReactionToTurn(messageId, record.localSessionId, turnId);
2922
3047
  }
@@ -2941,7 +3066,7 @@ export class ProxySessionController {
2941
3066
  }
2942
3067
  persistQueuedPrompt(localSessionId, contextKey, text, options = {}) {
2943
3068
  return this.store.enqueuePrompt({
2944
- promptId: createId("prompt"),
3069
+ promptId: options.promptId ?? createId("prompt"),
2945
3070
  localSessionId,
2946
3071
  contextKey,
2947
3072
  text,
@@ -2960,15 +3085,16 @@ export class ProxySessionController {
2960
3085
  if (action.messageId)
2961
3086
  this.rememberPromptQueueCard(sessionId, action.contextKey, action.messageId);
2962
3087
  const cancelled = this.store.cancelQueuedPrompt(promptId, sessionId);
2963
- if (cancelled?.messageId)
2964
- await this.finalizeStandaloneMessageReaction(cancelled.messageId, "cancelled");
2965
- if (cancelled) {
2966
- this.store.audit(action.contextKey, "queued_prompt_cancelled", {
2967
- promptId,
2968
- localSessionId: sessionId,
2969
- });
2970
- }
2971
- await this.refreshPromptQueueCards(sessionId);
3088
+ if (cancelled)
3089
+ await this.finishQueuedPromptCancellation(cancelled, action.contextKey);
3090
+ else
3091
+ await this.refreshPromptQueueCards(sessionId);
3092
+ }
3093
+ async finishQueuedPromptCancellation(prompt, contextKey) {
3094
+ if (prompt.messageId)
3095
+ await this.finalizeStandaloneMessageReaction(prompt.messageId, "cancelled");
3096
+ this.store.audit(contextKey, "queued_prompt_cancelled", { promptId: prompt.promptId, localSessionId: prompt.localSessionId });
3097
+ await this.refreshPromptQueueCards(prompt.localSessionId);
2972
3098
  }
2973
3099
  async presentPromptQueueCard(localSessionId, contextKey) {
2974
3100
  await this.serializePromptQueueCardWrite(localSessionId, async () => {
@@ -3013,6 +3139,7 @@ export class ProxySessionController {
3013
3139
  prompts: this.store.listQueuedPrompts(localSessionId).map((prompt) => ({
3014
3140
  id: prompt.promptId,
3015
3141
  text: prompt.displayPrompt ?? prompt.text,
3142
+ hasImages: Boolean(prompt.localImagePaths?.length),
3016
3143
  })),
3017
3144
  });
3018
3145
  }
@@ -3190,7 +3317,7 @@ export class ProxySessionController {
3190
3317
  permissionMode: source.permissionMode ?? "auto",
3191
3318
  });
3192
3319
  this.store.setCurrentSession(message.contextKey, localSessionId);
3193
- this.outbound.registerSession(localSessionId, message.contextKey, forkTitle, source.cwd, this.agentLabel(source.agentName), source.model, source.modelProvider);
3320
+ this.outbound.registerSession(localSessionId, message.contextKey, forkTitle, source.cwd, this.agentLabel(source.agentName), source.model, source.modelProvider, source.reasoningEffort);
3194
3321
  try {
3195
3322
  const forked = await runtime.forkSession({
3196
3323
  localSessionId,
@@ -3453,7 +3580,7 @@ export class ProxySessionController {
3453
3580
  forkedFromHistoricalTurn: sourceWasRunning && source.lastTurnId !== lastTurnId,
3454
3581
  };
3455
3582
  }
3456
- async forkSessionIntoContext(contextKey, plan) {
3583
+ async forkSessionIntoContext(contextKey, plan, activate = true) {
3457
3584
  const localSessionId = createId("sess");
3458
3585
  const record = this.store.createSession({
3459
3586
  localSessionId,
@@ -3488,7 +3615,7 @@ export class ProxySessionController {
3488
3615
  lastTurnId: plan.lastTurnId,
3489
3616
  lastTurnStatus: plan.lastTurnStatus,
3490
3617
  });
3491
- this.outbound.registerSession(localSessionId, contextKey, forked.title ?? plan.forkTitle, plan.cwd, this.agentLabel(plan.agentName), forked.model ?? plan.model, forked.modelProvider ?? plan.modelProvider);
3618
+ this.outbound.registerSession(localSessionId, contextKey, forked.title ?? plan.forkTitle, plan.cwd, this.agentLabel(plan.agentName), forked.model ?? plan.model, forked.modelProvider ?? plan.modelProvider, forked.reasoningEffort ?? plan.reasoningEffort);
3492
3619
  this.store.audit(contextKey, "session_forked", {
3493
3620
  sourceLocalSessionId: plan.source?.localSessionId,
3494
3621
  sourceRemoteSessionId: plan.remoteSessionId,
@@ -3500,7 +3627,8 @@ export class ProxySessionController {
3500
3627
  forkedLocalSessionId: localSessionId,
3501
3628
  forkedRemoteSessionId: forked.remoteSessionId,
3502
3629
  });
3503
- this.store.setCurrentSession(contextKey, localSessionId);
3630
+ if (activate)
3631
+ this.store.setCurrentSession(contextKey, localSessionId);
3504
3632
  return {
3505
3633
  record: this.store.getSession(localSessionId) ?? record,
3506
3634
  session: forked,
@@ -3893,8 +4021,8 @@ export class ProxySessionController {
3893
4021
  let pendingTurnId;
3894
4022
  try {
3895
4023
  const session = loaded.runtime.getSession(loaded.record.localSessionId) ?? loaded.session;
3896
- this.outbound.updateSessionModel(loaded.record.localSessionId, session.model, session.modelProvider);
3897
- pendingTurnId = await this.outbound.startPendingTurn(loaded.record.localSessionId, loaded.record.contextKey, title, replyTarget, cardPrompt, localImagePaths);
4024
+ this.outbound.updateSessionModel(loaded.record.localSessionId, session.model, session.modelProvider, session.reasoningEffort);
4025
+ pendingTurnId = await this.outbound.startPendingTurn(loaded.record.localSessionId, loaded.record.contextKey, title, replyTarget, cardPrompt, localImagePaths, options.workspaceRequestId);
3898
4026
  }
3899
4027
  catch (error) {
3900
4028
  if (options.scheduleRunId) {
@@ -4081,7 +4209,7 @@ export class ProxySessionController {
4081
4209
  }
4082
4210
  if (activate)
4083
4211
  this.store.setCurrentSession(contextKey, localSessionId);
4084
- this.outbound.registerSession(localSessionId, contextKey, initialTitle, sessionCwd, this.agentLabel(agentName), resolvedExecutionSettings.model, resolvedExecutionSettings.modelProvider);
4212
+ this.outbound.registerSession(localSessionId, contextKey, initialTitle, sessionCwd, this.agentLabel(agentName), resolvedExecutionSettings.model, resolvedExecutionSettings.modelProvider, resolvedExecutionSettings.reasoningEffort);
4085
4213
  const runtime = this.runtimes.forAgent(agentName);
4086
4214
  try {
4087
4215
  if (prepareTurn) {
@@ -4098,7 +4226,7 @@ export class ProxySessionController {
4098
4226
  permissionMode: resolvedExecutionSettings.permissionMode ?? "auto",
4099
4227
  });
4100
4228
  this.persistRuntimeSession(record, session, session.activeTurnId ? "running" : "ready");
4101
- this.outbound.updateSessionModel(localSessionId, session.model, session.modelProvider);
4229
+ this.outbound.updateSessionModel(localSessionId, session.model, session.modelProvider, session.reasoningEffort);
4102
4230
  const saved = this.store.getSession(localSessionId) ?? record;
4103
4231
  if (prepareTurn)
4104
4232
  this.assertExecutionGeneration(localSessionId, executionGeneration);
@@ -4215,7 +4343,7 @@ export class ProxySessionController {
4215
4343
  // A live Turn keeps its original delivery route. The new group's next Turn
4216
4344
  // establishes its own route through startPendingTurn.
4217
4345
  if (task.status !== "running" && !runtime.getSession(task.localSessionId)?.activeTurnId) {
4218
- this.outbound.registerSession(task.localSessionId, group.contextKey, task.title, task.cwd, this.agentLabel(agentName), task.model, task.modelProvider);
4346
+ this.outbound.registerSession(task.localSessionId, group.contextKey, task.title, task.cwd, this.agentLabel(agentName), task.model, task.modelProvider, task.reasoningEffort);
4219
4347
  }
4220
4348
  this.store.audit(sourceContextKey, "session_switch_group", {
4221
4349
  localSessionId: task.localSessionId, remoteSessionId, groupContextKey: group.contextKey,
@@ -4442,7 +4570,7 @@ export class ProxySessionController {
4442
4570
  return this.loadSession(record, forSettings);
4443
4571
  }
4444
4572
  }
4445
- this.outbound.registerSession(record.localSessionId, record.contextKey, record.title, record.cwd, this.agentLabel(record.agentName), record.model, record.modelProvider);
4573
+ this.outbound.registerSession(record.localSessionId, record.contextKey, record.title, record.cwd, this.agentLabel(record.agentName), record.model, record.modelProvider, record.reasoningEffort);
4446
4574
  const loading = this.sessionHydrationOperations.run(record.localSessionId, async () => {
4447
4575
  const latest = this.store.getSession(record.localSessionId);
4448
4576
  if (latest)
@@ -4952,6 +5080,7 @@ export class ProxySessionController {
4952
5080
  if (!prompt)
4953
5081
  return;
4954
5082
  const scheduledRun = this.store.schedules.getRun(prompt.promptId);
5083
+ let workspaceRequestId = prompt.promptId.startsWith("workspace:") ? prompt.promptId.slice("workspace:".length) : undefined;
4955
5084
  const record = this.store.getSessionForContext(sessionId, prompt.contextKey) ?? baseRecord;
4956
5085
  loaded = { ...loaded, record };
4957
5086
  await this.refreshPromptQueueCards(sessionId);
@@ -4960,23 +5089,33 @@ export class ProxySessionController {
4960
5089
  || this.lifecycle?.canStartScheduledTasks?.() === false)
4961
5090
  throw new Error("定时任务已取消、过期或正在安全重启。");
4962
5091
  const job = this.store.schedules.require(scheduledRun.jobId);
5092
+ if (job.attachments?.files.length)
5093
+ workspaceRequestId = scheduledRun.id.slice("schedule_run_".length);
4963
5094
  this.assertScheduleTarget(job);
5095
+ let missingAttachment = false;
4964
5096
  try {
4965
- await this.notifySchedule(job, prompt.text);
5097
+ const attachmentPaths = [...(job.attachments?.images ?? []), ...(job.attachments?.files.map(file => file.filePath) ?? [])];
5098
+ const available = await Promise.all(attachmentPaths.map(async (file) => (await fs.stat(file).catch(() => undefined))?.isFile()));
5099
+ missingAttachment = available.some(value => !value);
5100
+ if (missingAttachment)
5101
+ throw new Error("定时任务的附件已不可用。");
5102
+ await this.notifySchedule(job, scheduleDisplayPrompt(job, queuedPromptContent(prompt).text), prompt.localImagePaths);
4966
5103
  }
4967
5104
  catch (error) {
5105
+ const reason = missingAttachment ? "定时任务的附件已不可用" : "原会话的 Prompt 发送失败";
4968
5106
  const currentJob = this.store.schedules.get(job.id);
4969
5107
  if (currentJob?.status === "enabled") {
4970
5108
  const paused = this.store.schedules.change(job.id, currentJob.revision, "pause");
4971
- this.store.schedules.update({ ...paused, notice: "原会话的 Prompt 发送失败,计划已暂停。请修复后恢复。" });
5109
+ this.store.schedules.update({ ...paused, notice: `${reason},计划已暂停。请修复后恢复。` });
4972
5110
  }
4973
- this.store.schedules.finish(scheduledRun.id, "failed", "无法向原会话发送 Prompt,未提交模型。");
5111
+ this.store.schedules.finish(scheduledRun.id, "failed", missingAttachment ? `${reason},未提交模型。` : "无法向原会话发送 Prompt,未提交模型。");
4974
5112
  this.store.updateTurnAttempt(scheduledRun.id, { status: "failed" });
4975
5113
  throw error;
4976
5114
  }
4977
5115
  }
4978
5116
  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,
4979
5117
  trigger: scheduledRun ? "schedule" : "queue", instructionId: prompt.promptId,
5118
+ workspaceRequestId,
4980
5119
  ...(scheduledRun ? { attemptId: prompt.promptId, scheduleRunId: prompt.promptId } : {}) });
4981
5120
  if (prompt.messageId)
4982
5121
  await this.bindMessageReactionToTurn(prompt.messageId, sessionId, turnId);
@@ -5375,7 +5514,7 @@ export class ProxySessionController {
5375
5514
  lastTurnId: turnId,
5376
5515
  lastTurnStatus: "completed",
5377
5516
  });
5378
- this.outbound.registerSession(current.localSessionId, contextKey, forked.title ?? current.title, current.cwd, this.agentLabel(current.agentName), forked.model ?? current.model, forked.modelProvider ?? current.modelProvider);
5517
+ this.outbound.registerSession(current.localSessionId, contextKey, forked.title ?? current.title, current.cwd, this.agentLabel(current.agentName), forked.model ?? current.model, forked.modelProvider ?? current.modelProvider, forked.reasoningEffort ?? current.reasoningEffort);
5379
5518
  this.store.audit(contextKey, "session_reset_to_turn", {
5380
5519
  localSessionId: current.localSessionId,
5381
5520
  previousRemoteSessionId,
@@ -5665,7 +5804,7 @@ export class ProxySessionController {
5665
5804
  const session = await loaded.runtime.setExecutionSettings(loaded.record.localSessionId, settings, persist);
5666
5805
  loaded.record = this.store.getSession(loaded.record.localSessionId) ?? loaded.record;
5667
5806
  this.settingsOnlySessions.delete(loaded.record.localSessionId);
5668
- this.outbound.updateSessionModel(loaded.record.localSessionId, session.model, session.modelProvider);
5807
+ this.outbound.updateSessionModel(loaded.record.localSessionId, session.model, session.modelProvider, session.reasoningEffort);
5669
5808
  return session;
5670
5809
  }
5671
5810
  async reconcilePreparedSettingsSession(loaded) {
@@ -5709,7 +5848,7 @@ export class ProxySessionController {
5709
5848
  if (options.updateMessageId) {
5710
5849
  await this.openExecutionSettingsNow(contextKey, activeTab, options);
5711
5850
  }
5712
- else {
5851
+ else if (!options.quiet) {
5713
5852
  await this.outbound.sendText(contextKey, this.pendingProviderNotice(pending).replaceAll("`", ""));
5714
5853
  }
5715
5854
  }
@@ -5738,7 +5877,7 @@ export class ProxySessionController {
5738
5877
  if (rolledBack) {
5739
5878
  loaded.session = restored;
5740
5879
  this.store.deletePendingProviderSettings(pending.localSessionId);
5741
- this.outbound.updateSessionModel(pending.localSessionId, previous.model, previous.modelProvider);
5880
+ this.outbound.updateSessionModel(pending.localSessionId, previous.model, previous.modelProvider, previous.reasoningEffort);
5742
5881
  notice = `切换到 Provider ${cardCode(pending.settings.modelProvider)}、模型 ${cardCode(pending.settings.model)} 失败:${runtimeErrorMessage(error)} 已回退到 Provider ${cardCode(previous.modelProvider ?? "Agent 默认")}、模型 ${cardCode(previous.model ?? "默认")},后续轮次继续使用原设置。`;
5743
5882
  }
5744
5883
  else {
@@ -5876,7 +6015,7 @@ export class ProxySessionController {
5876
6015
  await loaded.runtime.setReasoningEffort(loaded.record.localSessionId, nextEffort);
5877
6016
  }
5878
6017
  this.store.updateRuntimeSession(loaded.record.localSessionId, { model, reasoningEffort: nextEffort });
5879
- this.outbound.updateSessionModel(loaded.record.localSessionId, model, loaded.session.modelProvider);
6018
+ this.outbound.updateSessionModel(loaded.record.localSessionId, model, loaded.session.modelProvider, nextEffort);
5880
6019
  });
5881
6020
  const effortMessage = nextEffort && nextEffort !== currentEffort
5882
6021
  ? `,思考强度已自动调整为 ${nextEffort}`
@@ -5889,6 +6028,8 @@ export class ProxySessionController {
5889
6028
  });
5890
6029
  return;
5891
6030
  }
6031
+ if (options.quiet)
6032
+ return;
5892
6033
  await this.outbound.sendText(contextKey, `模型已切换为 ${model}${effortMessage},只影响当前任务,从下一次请求生效。`);
5893
6034
  }
5894
6035
  async goal(contextKey, command) {
@@ -6291,6 +6432,8 @@ export class ProxySessionController {
6291
6432
  });
6292
6433
  return;
6293
6434
  }
6435
+ if (options.quiet)
6436
+ return;
6294
6437
  await this.outbound.sendText(contextKey, `思考强度已切换为 ${effort},只影响当前任务,从下一次请求生效。`);
6295
6438
  }
6296
6439
  async permissions(contextKey, mode, options = {}) {
@@ -7214,7 +7357,7 @@ export class ProxySessionController {
7214
7357
  await this.assertSessionTurnOwnership(existing, runtime);
7215
7358
  this.store.attachSessionToContext(contextKey, existing.localSessionId);
7216
7359
  this.store.setCurrentSession(contextKey, existing.localSessionId);
7217
- this.outbound.registerSession(existing.localSessionId, contextKey, existing.title, existing.cwd, this.agentLabel(existing.agentName), existing.model, existing.modelProvider);
7360
+ this.outbound.registerSession(existing.localSessionId, contextKey, existing.title, existing.cwd, this.agentLabel(existing.agentName), existing.model, existing.modelProvider, existing.reasoningEffort);
7218
7361
  await this.outbound.sendText(contextKey, `已切换到任务:${existing.title ?? existing.remoteSessionId ?? taskId}`);
7219
7362
  return;
7220
7363
  }
@@ -7241,7 +7384,7 @@ export class ProxySessionController {
7241
7384
  lastTurnStatus: mapRemoteTurnStatus(remote.lastTurnStatus),
7242
7385
  });
7243
7386
  this.store.setCurrentSession(contextKey, localSessionId);
7244
- this.outbound.registerSession(localSessionId, contextKey, remote.title ?? remote.preview, remote.cwd, this.agentLabel(agentName), remote.model, remote.modelProvider);
7387
+ this.outbound.registerSession(localSessionId, contextKey, remote.title ?? remote.preview, remote.cwd, this.agentLabel(agentName), remote.model, remote.modelProvider, remote.reasoningEffort);
7245
7388
  await this.outbound.sendText(contextKey, `已切换到任务:${remote.title ?? remote.preview ?? remote.id}。历史消息不会重新发送。`);
7246
7389
  }
7247
7390
  async stopSessionReference(contextKey, taskId) {
@@ -8795,6 +8938,10 @@ function latestRemoteTimestamp(...values) {
8795
8938
  .map(normalizeRemoteTimestamp);
8796
8939
  return timestamps.length > 0 ? Math.max(...timestamps) : undefined;
8797
8940
  }
8941
+ function assertWorkspaceSteerTurn(expected, active) {
8942
+ if (expected && expected !== active)
8943
+ throw new TurnNotSubmittedError("原轮次已结束或切换,未追加消息。");
8944
+ }
8798
8945
  function isTurnStillRunning(status) {
8799
8946
  return status === "starting"
8800
8947
  || status === "running"
@@ -9081,19 +9228,9 @@ function renderLocalTurnReference(snapshot, messageKind) {
9081
9228
  ? `[消息类型:AgentBot 思考卡片]\n${truncateMiddle(content, 48_000)}`
9082
9229
  : undefined;
9083
9230
  }
9084
- function appendDownloadedFiles(prompt, files) {
9085
- return `${prompt}\n\n参考文件(已下载到本地):\n${files.map((file, index) => `[文件 ${index + 1}:${file.fileName}] ${file.filePath}`).join("\n")}`;
9086
- }
9087
9231
  function defaultResourcePrompt(message) {
9088
9232
  return defaultResourcePromptFromCounts(message.images?.length ?? 0, message.files?.length ?? 0);
9089
9233
  }
9090
- function defaultResourcePromptFromCounts(imageCount, fileCount) {
9091
- if (imageCount > 0 && fileCount > 0)
9092
- return "请查看附带的图片和文件";
9093
- if (fileCount > 0)
9094
- return fileCount === 1 ? "请查看这个文件" : "请查看这些文件";
9095
- return imageCount === 1 ? "请查看这张图片" : "请查看这些图片";
9096
- }
9097
9234
  function isCommandMessage(message) {
9098
9235
  const text = normalizeFeishuPostText(message.text).trimStart();
9099
9236
  return text.startsWith("/") || text.startsWith("!");