@keyou007/agent-bot 0.1.27-alpha.1 → 0.1.27-alpha.3

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 (118) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +55 -5
  3. package/README.zh.md +55 -5
  4. package/SECURITY.md +14 -0
  5. package/assets/workspace-sessions.js +648 -0
  6. package/assets/workspace.css +160 -0
  7. package/assets/workspace.js +1795 -0
  8. package/config.example.yaml +3 -2
  9. package/dist/codex/CodexEventMapper.js +35 -0
  10. package/dist/codex/CodexEventMapper.js.map +1 -1
  11. package/dist/codex/CodexRuntime.js +50 -4
  12. package/dist/codex/CodexRuntime.js.map +1 -1
  13. package/dist/codex/TraeTaskNotification.js +44 -0
  14. package/dist/codex/TraeTaskNotification.js.map +1 -0
  15. package/dist/config/SettingsStore.js +1 -1
  16. package/dist/config/SettingsStore.js.map +1 -1
  17. package/dist/config/loadConfig.js +3 -2
  18. package/dist/config/loadConfig.js.map +1 -1
  19. package/dist/config/paths.js +3 -0
  20. package/dist/config/paths.js.map +1 -1
  21. package/dist/feishu/CardRenderer.js +54 -10
  22. package/dist/feishu/CardRenderer.js.map +1 -1
  23. package/dist/feishu/FeishuMessageClient.js +2 -2
  24. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  25. package/dist/feishu/FeishuTurnPresenter.js +103 -16
  26. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  27. package/dist/index.js +61 -17
  28. package/dist/index.js.map +1 -1
  29. package/dist/local-files/DiagramPreview.js +1 -1
  30. package/dist/local-files/GitDiffPreview.js +11 -7
  31. package/dist/local-files/GitDiffPreview.js.map +1 -1
  32. package/dist/local-files/LocalFileViewerServer.js +359 -37
  33. package/dist/local-files/LocalFileViewerServer.js.map +1 -1
  34. package/dist/local-files/MarkdownFileLinks.js +5 -4
  35. package/dist/local-files/MarkdownFileLinks.js.map +1 -1
  36. package/dist/local-files/TurnPreviewPage.js +32 -10
  37. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  38. package/dist/local-files/WebPageTitle.js +85 -0
  39. package/dist/local-files/WebPageTitle.js.map +1 -0
  40. package/dist/local-files/WorkspaceFiles.js +553 -0
  41. package/dist/local-files/WorkspaceFiles.js.map +1 -0
  42. package/dist/local-files/WorkspaceOrigin.js +38 -0
  43. package/dist/local-files/WorkspaceOrigin.js.map +1 -0
  44. package/dist/local-files/WorkspacePage.js +19 -0
  45. package/dist/local-files/WorkspacePage.js.map +1 -0
  46. package/dist/local-files/WorkspaceSessions.js +689 -0
  47. package/dist/local-files/WorkspaceSessions.js.map +1 -0
  48. package/dist/presentation/TurnStateReducer.js +74 -13
  49. package/dist/presentation/TurnStateReducer.js.map +1 -1
  50. package/dist/presentation/turnActivity.js +41 -0
  51. package/dist/presentation/turnActivity.js.map +1 -0
  52. package/dist/presentation/turnStatus.js +11 -0
  53. package/dist/presentation/turnStatus.js.map +1 -1
  54. package/dist/presentation/visibleTurnActivities.js +4 -2
  55. package/dist/presentation/visibleTurnActivities.js.map +1 -1
  56. package/dist/proxy/ProxySessionController.js +150 -14
  57. package/dist/proxy/ProxySessionController.js.map +1 -1
  58. package/dist/runtime/types.js +1 -1
  59. package/dist/runtime/types.js.map +1 -1
  60. package/dist/state/InboundMessageStore.js +54 -0
  61. package/dist/state/InboundMessageStore.js.map +1 -0
  62. package/dist/state/StateStore.js +71 -1
  63. package/dist/state/StateStore.js.map +1 -1
  64. package/dist/state/TurnPreviewJournal.js +4 -2
  65. package/dist/state/TurnPreviewJournal.js.map +1 -1
  66. package/dist/state/migrations.js +20 -0
  67. package/dist/state/migrations.js.map +1 -1
  68. package/dist/supervision/SafeRestartNotifier.js +1 -0
  69. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  70. package/dist/supervision/SafeRestartScheduler.js +33 -16
  71. package/dist/supervision/SafeRestartScheduler.js.map +1 -1
  72. package/dist/terminal/TerminalLinks.js +32 -0
  73. package/dist/terminal/TerminalLinks.js.map +1 -1
  74. package/dist/terminal/TerminalPage.js +44 -24
  75. package/dist/terminal/TerminalPage.js.map +1 -1
  76. package/dist/terminal/TerminalServer.js +103 -39
  77. package/dist/terminal/TerminalServer.js.map +1 -1
  78. package/docs/technical-reference.md +1 -1
  79. package/docs/technical-reference.zh.md +2 -2
  80. package/npm-shrinkwrap.json +2 -2
  81. package/package.json +1 -1
  82. package/skills/agent-bot/SKILL.md +3 -1
  83. package/src/codex/CodexEventMapper.ts +39 -1
  84. package/src/codex/CodexRuntime.ts +54 -4
  85. package/src/codex/TraeTaskNotification.ts +49 -0
  86. package/src/config/SettingsStore.ts +1 -1
  87. package/src/config/loadConfig.ts +3 -2
  88. package/src/config/paths.ts +4 -0
  89. package/src/feishu/CardRenderer.ts +45 -11
  90. package/src/feishu/FeishuMessageClient.ts +2 -2
  91. package/src/feishu/FeishuTurnPresenter.ts +110 -20
  92. package/src/index.ts +62 -17
  93. package/src/local-files/DiagramPreview.ts +1 -1
  94. package/src/local-files/GitDiffPreview.ts +10 -7
  95. package/src/local-files/LocalFileViewerServer.ts +330 -37
  96. package/src/local-files/MarkdownFileLinks.ts +5 -3
  97. package/src/local-files/TurnPreviewPage.ts +35 -9
  98. package/src/local-files/WebPageTitle.ts +59 -0
  99. package/src/local-files/WorkspaceFiles.ts +468 -0
  100. package/src/local-files/WorkspaceOrigin.ts +31 -0
  101. package/src/local-files/WorkspacePage.ts +21 -0
  102. package/src/local-files/WorkspaceSessions.ts +587 -0
  103. package/src/presentation/TurnStateReducer.ts +76 -14
  104. package/src/presentation/turnActivity.ts +43 -0
  105. package/src/presentation/turnStatus.ts +14 -0
  106. package/src/presentation/turnViewTypes.ts +10 -1
  107. package/src/presentation/visibleTurnActivities.ts +4 -2
  108. package/src/proxy/ProxySessionController.ts +149 -13
  109. package/src/runtime/types.ts +17 -0
  110. package/src/state/InboundMessageStore.ts +72 -0
  111. package/src/state/StateStore.ts +80 -1
  112. package/src/state/TurnPreviewJournal.ts +4 -2
  113. package/src/state/migrations.ts +20 -0
  114. package/src/supervision/SafeRestartNotifier.ts +1 -0
  115. package/src/supervision/SafeRestartScheduler.ts +42 -18
  116. package/src/terminal/TerminalLinks.ts +26 -0
  117. package/src/terminal/TerminalPage.ts +44 -24
  118. package/src/terminal/TerminalServer.ts +98 -36
@@ -1,10 +1,11 @@
1
- import type { AgentEvent, ApprovalDecision, ApprovalRequest, RemoteTurnDetails, ToolState } from "../runtime/types.js";
1
+ import { TASK_NOTIFICATION_ACTIVITY_PREFIX, type AgentEvent, type ApprovalDecision, type ApprovalRequest, type RemoteTurnDetails, type ToolState } from "../runtime/types.js";
2
2
  import { appendGeneratedImageMarkdown } from "../utils/generatedImageMarkdown.js";
3
3
  import type { MessageReplyTarget } from "../feishu/types.js";
4
4
  import { formatStorageSize } from "../utils/formatStorageSize.js";
5
5
  import type { FileSummary, TurnActivity, TurnReasoningItem, TurnViewState } from "./turnViewTypes.js";
6
6
  import { turnReasoningItems } from "./turnReasoning.js";
7
- import { canApplyTurnEvent } from "./turnStatus.js";
7
+ import { canApplyTurnEvent, modelQueueLabel } from "./turnStatus.js";
8
+ import { formatModelQueueDuration, isCommentaryActivity, normalizeTurnActivity } from "./turnActivity.js";
8
9
 
9
10
  const MAX_TEXT = 6_000;
10
11
  const MAX_COMPLETED_TOOLS = 20;
@@ -98,6 +99,9 @@ export function hydrateTurnViewState(summary: TurnViewState, details: RemoteTurn
98
99
  return {
99
100
  ...state,
100
101
  status: details.status,
102
+ modelQueue: undefined,
103
+ modelQueueActivityId: undefined,
104
+ modelQueueStartedAt: undefined,
101
105
  completedAt,
102
106
  durationMs: details.durationMs ?? (completedAt === undefined || details.startedAt === undefined
103
107
  ? undefined : Math.max(0, completedAt - details.startedAt)),
@@ -110,7 +114,13 @@ export function hydrateTurnViewState(summary: TurnViewState, details: RemoteTurn
110
114
 
111
115
  export function reduceTurnEvent(state: TurnViewState, event: AgentEvent, complete = false): TurnViewState {
112
116
  if (!canApplyTurnEvent(state, event)) return state;
113
- const next = reduceEvent(state, event);
117
+ const endingQueue = state.modelQueue && (event.type === "turn_completed" || event.type === "turn_cancelled"
118
+ || event.type === "turn_failed" || event.type === "turn_status_unknown");
119
+ const input = endingQueue ? reduceModelQueue(state, {
120
+ type: "model_queue_updated", sessionId: state.sessionId, turnId: state.turnId, queue: { state: "ready" },
121
+ reason: event.type === "turn_status_unknown" ? "disconnected" : "turn_ended",
122
+ }) : state;
123
+ const next = reduceEvent(input, event);
114
124
  if (!complete) return next;
115
125
  if (event.type === "turn_completed") next.finalResponse = event.finalResponse;
116
126
  if (event.type === "agent_text_delta") next.assistantText = state.assistantText + event.text;
@@ -143,7 +153,10 @@ function reduceEvent(state: TurnViewState, event: AgentEvent): TurnViewState {
143
153
 
144
154
  switch (event.type) {
145
155
  case "turn_started":
146
- return { ...state, status: "running", startedAt: event.startedAt };
156
+ return { ...state, status: "running", startedAt: event.startedAt,
157
+ modelQueue: undefined, modelQueueActivityId: undefined, modelQueueStartedAt: undefined };
158
+ case "model_queue_updated":
159
+ return reduceModelQueue(state, event);
147
160
  case "agent_text_delta":
148
161
  return {
149
162
  ...state,
@@ -191,7 +204,7 @@ function reduceEvent(state: TurnViewState, event: AgentEvent): TurnViewState {
191
204
  const activityUpdate = upsertActivity(
192
205
  state.activities ?? [],
193
206
  (state.activities ?? []).findIndex((activity) => activity.id === activityId),
194
- { kind: "assistant", id: activityId, text },
207
+ { kind: "system", category: "context_compaction", id: activityId, text },
195
208
  );
196
209
  return {
197
210
  ...state,
@@ -249,7 +262,7 @@ function reduceEvent(state: TurnViewState, event: AgentEvent): TurnViewState {
249
262
  const activityUpdate = upsertActivity(
250
263
  state.activities ?? [],
251
264
  (state.activities ?? []).findIndex((activity) => activity.id === activityId),
252
- { kind: "assistant", id: activityId, text },
265
+ { kind: "system", category: "context_compaction", id: activityId, text },
253
266
  );
254
267
  return {
255
268
  ...state,
@@ -302,6 +315,16 @@ function reduceEvent(state: TurnViewState, event: AgentEvent): TurnViewState {
302
315
  ...(previewState.reasoningItems ? { reasoningItems: previewState.reasoningItems } : {}),
303
316
  activities: activityUpdate.activities,
304
317
  activitiesTruncated: state.activitiesTruncated || activityUpdate.truncated,
318
+ ...(event.activityId?.startsWith(TASK_NOTIFICATION_ACTIVITY_PREFIX) && (state.taskNotificationCard || (
319
+ !state.prompt && !state.promptImagePaths?.length && !state.replyTarget && !state.continuedFromTurnId
320
+ && !state.plan.length && !state.approval && !state.totalToolCount
321
+ && activities.every((activity) => activity.id.startsWith("model-queue:"))
322
+ )) ? {
323
+ taskNotificationCard: [
324
+ ...(state.taskNotificationCard ?? []).filter((entry) => entry.id !== event.activityId),
325
+ { id: event.activityId, text: bound(event.text) },
326
+ ].slice(-4),
327
+ } : {}),
305
328
  };
306
329
  }
307
330
  case "plan_updated":
@@ -346,6 +369,7 @@ function reduceEvent(state: TurnViewState, event: AgentEvent): TurnViewState {
346
369
  return {
347
370
  ...state,
348
371
  status: "completed",
372
+ modelQueue: undefined,
349
373
  statusMessage: undefined,
350
374
  error: undefined,
351
375
  activeTool: undefined,
@@ -364,6 +388,7 @@ function reduceEvent(state: TurnViewState, event: AgentEvent): TurnViewState {
364
388
  return {
365
389
  ...state,
366
390
  status: "cancelled",
391
+ modelQueue: undefined,
367
392
  statusMessage: event.message,
368
393
  activeTool: undefined,
369
394
  approval: undefined,
@@ -376,6 +401,7 @@ function reduceEvent(state: TurnViewState, event: AgentEvent): TurnViewState {
376
401
  return {
377
402
  ...state,
378
403
  status: "failed",
404
+ modelQueue: undefined,
379
405
  statusMessage: undefined,
380
406
  activeTool: undefined,
381
407
  approval: undefined,
@@ -388,6 +414,7 @@ function reduceEvent(state: TurnViewState, event: AgentEvent): TurnViewState {
388
414
  return {
389
415
  ...state,
390
416
  status: "unknown",
417
+ modelQueue: undefined,
391
418
  statusMessage: event.message,
392
419
  activeTool: undefined,
393
420
  approval: undefined,
@@ -408,7 +435,41 @@ export function continueTurnView(state: TurnViewState, turnId: string, startedAt
408
435
  return { ...state, turnId, previewTurnId: state.previewTurnId ?? state.turnId,
409
436
  continuedFromTurnId: state.turnId, continuedToTurnId: undefined, segmentStartedAt: startedAt,
410
437
  status: "running", completedAt: undefined, durationMs: undefined, finalResponse: undefined,
411
- error: undefined, statusMessage: undefined, approval: undefined, activeTool: undefined, assistantText: "", progressText: undefined };
438
+ error: undefined, statusMessage: undefined, modelQueue: undefined, modelQueueActivityId: undefined,
439
+ modelQueueStartedAt: undefined, approval: undefined, activeTool: undefined, assistantText: "", progressText: undefined };
440
+ }
441
+
442
+ function reduceModelQueue(state: TurnViewState, event: Extract<AgentEvent, { type: "model_queue_updated" }>): TurnViewState {
443
+ const ready = event.queue.state === "ready";
444
+ if (ready && !state.modelQueueActivityId) return { ...state, modelQueue: undefined, modelQueueStartedAt: undefined };
445
+ const count = state.modelQueueCount ?? 0;
446
+ const activityId = state.modelQueueActivityId ?? `model-queue:${event.turnId}:${count + 1}`;
447
+ // Older queue events have no timestamps; replay them without inventing a wait duration.
448
+ const startedAt = state.modelQueueStartedAt ?? (!ready && !state.modelQueue ? event.timestampMs : undefined);
449
+ const durationMs = startedAt === undefined || event.timestampMs === undefined
450
+ ? undefined : Math.max(0, event.timestampMs - startedAt);
451
+ const subject = (ready ? state.modelQueue : event.queue)?.operation === "contextCompaction" ? "上下文压缩" : "模型";
452
+ const waiting = modelQueueLabel({ status: "running", modelQueue: event.queue });
453
+ const durationText = durationMs === undefined ? "" : ` · 耗时 ${formatModelQueueDuration(durationMs)}`;
454
+ const text = ready
455
+ ? event.reason === "disconnected" ? `${subject}排队状态待核实。`
456
+ : event.reason === "turn_ended" ? `本轮已结束,${subject}排队记录已关闭${durationText}。`
457
+ : `${subject}排队结束${durationText},继续处理。`
458
+ : `${waiting}。`;
459
+ const activities = state.activities ?? [];
460
+ const update = upsertActivity(activities, activities.findIndex((activity) => activity.id === activityId), {
461
+ kind: "system", category: "model_queue", id: activityId, text,
462
+ });
463
+ return {
464
+ ...state,
465
+ modelQueue: ready ? undefined : { ...event.queue },
466
+ modelQueueActivityId: ready ? undefined : activityId,
467
+ modelQueueStartedAt: ready ? undefined : startedAt,
468
+ modelQueueCount: state.modelQueueActivityId ? count : count + 1,
469
+ progressText: text,
470
+ activities: update.activities,
471
+ activitiesTruncated: state.activitiesTruncated || update.truncated,
472
+ };
412
473
  }
413
474
 
414
475
  function approvalHistoryText(request: ApprovalRequest, decision?: ApprovalDecision, automatic = false): string {
@@ -739,8 +800,8 @@ function contextCompactionCompletedText(
739
800
  storageBytes: number | undefined,
740
801
  ): string {
741
802
  const subject = count > 1
742
- ? `Codex 已完成本轮第 ${count} 次上下文压缩`
743
- : "Codex 已完成上下文压缩";
803
+ ? `已完成本轮第 ${count} 次上下文压缩`
804
+ : "已完成上下文压缩";
744
805
  const details = [
745
806
  durationMs === undefined ? undefined : `耗时 ${formatCompactionDuration(durationMs)}`,
746
807
  contextCompactionSizeText(beforeTokens, afterTokens),
@@ -755,8 +816,8 @@ function contextCompactionRunningText(
755
816
  storageBytes: number | undefined,
756
817
  ): string {
757
818
  const context = beforeTokens === undefined
758
- ? "Codex 正在压缩上下文…"
759
- : `Codex 正在压缩上下文(压缩前 ${formatInteger(beforeTokens)} tokens)…`;
819
+ ? "正在压缩上下文…"
820
+ : `正在压缩上下文(压缩前 ${formatInteger(beforeTokens)} tokens)…`;
760
821
  const metrics = contextCompactionTaskMetricsText(turnCount, storageBytes);
761
822
  return metrics ? `${context} · ${metrics}` : context;
762
823
  }
@@ -799,9 +860,10 @@ function formatInteger(value: number): string {
799
860
 
800
861
  /** Bound the hot card projection, never the journal or final-delivery payload. */
801
862
  export function compactTurnView(state: TurnViewState): TurnViewState {
802
- const recent = state.activities.slice(-77);
803
- const commentary = state.activities.slice(0, -77).filter((a) => a.kind === "assistant").slice(-3);
804
- const retained = state.activities.length > 80 ? [...commentary, ...recent] : state.activities;
863
+ const normalized = state.activities.map(normalizeTurnActivity);
864
+ const recent = normalized.slice(-77);
865
+ const commentary = normalized.slice(0, -77).filter(isCommentaryActivity).slice(-3);
866
+ const retained = normalized.length > 80 ? [...commentary, ...recent] : normalized;
805
867
  const activities = retained.map((a) => a.kind === "tool"
806
868
  ? { ...a, tool: boundTool(a.tool) } : { ...a, text: bound(a.text) });
807
869
  const ids = new Set(activities.filter((a) => a.kind === "tool").map((a) => a.id));
@@ -0,0 +1,43 @@
1
+ import type { TurnActivity, TurnViewState } from "./turnViewTypes.js";
2
+ import { modelQueueLabel } from "./turnStatus.js";
3
+
4
+ export const USER_ACTIVITY_ICON = "\u{1f64b}";
5
+
6
+ export function normalizeTurnActivity(activity: TurnActivity): TurnActivity {
7
+ let normalized = activity;
8
+ // Recognize saved system records by their generated IDs, never by message text.
9
+ if (activity.kind === "assistant") {
10
+ if (activity.id.startsWith("context-compaction:")) normalized = { ...activity, kind: "system", category: "context_compaction" };
11
+ if (activity.id.startsWith("model-queue:")) normalized = { ...activity, kind: "system", category: "model_queue" };
12
+ }
13
+ if (normalized.kind === "system" && normalized.category === "context_compaction") {
14
+ const text = normalized.text.replace(/^Codex (?=正在压缩上下文|已完成(?:本轮第 \d+ 次)?上下文压缩)/u, "");
15
+ if (text !== normalized.text) return { ...normalized, text };
16
+ }
17
+ return normalized;
18
+ }
19
+
20
+ export function isCommentaryActivity(activity: TurnActivity): boolean {
21
+ const normalized = normalizeTurnActivity(activity);
22
+ return normalized.kind === "assistant"
23
+ || (normalized.kind === "reasoning" && normalized.id.startsWith("commentary:"));
24
+ }
25
+
26
+ export function systemActivityQuote(text: string): string {
27
+ return text.split(/\r?\n/u).map((line) => line ? `> ${line}` : ">").join("\n");
28
+ }
29
+
30
+ export function liveModelQueueActivity(state: TurnViewState): { id: string; label: string; startedAt: number } | undefined {
31
+ const label = modelQueueLabel(state);
32
+ const startedAt = state.modelQueueStartedAt;
33
+ if (!label || !state.modelQueueActivityId || startedAt === undefined || !Number.isFinite(startedAt)) return undefined;
34
+ return { id: state.modelQueueActivityId, label, startedAt };
35
+ }
36
+
37
+ export function formatModelQueueDuration(durationMs: number): string {
38
+ const seconds = Math.max(0, Math.floor(durationMs / 1000));
39
+ const hours = Math.floor(seconds / 3600);
40
+ const minutes = Math.floor((seconds % 3600) / 60);
41
+ const time = `${String(minutes).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}`;
42
+ return hours > 0 ? `${String(hours).padStart(2, "0")}:${time}` : time;
43
+ }
@@ -10,6 +10,20 @@ export function isSettledTurnStatus(status: string): boolean {
10
10
  return status === "unknown" || isTerminalTurnStatus(status);
11
11
  }
12
12
 
13
+ export function modelQueueLabel(
14
+ state: Pick<TurnViewState, "status" | "modelQueue">,
15
+ language: "zh" | "en" = "zh",
16
+ ): string | undefined {
17
+ const queue = state.modelQueue;
18
+ if (!queue || queue.state === "ready" || isSettledTurnStatus(state.status) || state.status === "waiting_for_approval") return undefined;
19
+ const label = queue.operation === "contextCompaction"
20
+ ? language === "zh" ? "上下文压缩排队中" : "Context compaction queued"
21
+ : language === "zh" ? "模型排队中" : "Model queued";
22
+ return queue.position !== undefined && Number.isSafeInteger(queue.position) && queue.position >= 0
23
+ ? `${label} · ${language === "zh" ? `第 ${queue.position} 位` : `Position ${queue.position}`}`
24
+ : label;
25
+ }
26
+
13
27
  export function canApplyTurnEvent(
14
28
  state: Pick<TurnViewState, "sessionId" | "turnId" | "status">,
15
29
  event: AgentEvent,
@@ -1,5 +1,5 @@
1
1
  import type { MessageReplyTarget } from "../feishu/types.js";
2
- import type { ApprovalRequest, PlanStep, ToolState } from "../runtime/types.js";
2
+ import type { ApprovalRequest, ModelQueueStatus, PlanStep, ToolState } from "../runtime/types.js";
3
3
 
4
4
  export type TurnViewStatus =
5
5
  | "starting"
@@ -17,8 +17,11 @@ export interface FileSummary {
17
17
  deletions?: number;
18
18
  }
19
19
 
20
+ export type SystemActivityCategory = "context_compaction" | "model_queue";
21
+
20
22
  export type TurnActivity =
21
23
  | { kind: "assistant"; id: string; text: string }
24
+ | { kind: "system"; category: SystemActivityCategory; id: string; text: string }
22
25
  | { kind: "user"; id: string; text: string; localImagePaths?: string[] }
23
26
  | { kind: "reasoning"; id: string; text: string }
24
27
  | { kind: "tool"; id: string; tool: ToolState };
@@ -53,6 +56,10 @@ export interface TurnViewState {
53
56
  projectCwd?: string;
54
57
  replyTarget?: MessageReplyTarget;
55
58
  status: TurnViewStatus;
59
+ modelQueue?: ModelQueueStatus;
60
+ modelQueueActivityId?: string;
61
+ modelQueueStartedAt?: number;
62
+ modelQueueCount?: number;
56
63
  /** Execution uncertainty, independent of transport connectivity and final delivery. */
57
64
  statusMessage?: string;
58
65
  startedAt: number;
@@ -79,6 +86,8 @@ export interface TurnViewState {
79
86
  contextCompactionTurnCount?: number;
80
87
  contextCompactionStorageBytes?: number;
81
88
  progressText?: string;
89
+ /** Compact notification summaries retained for the dedicated card and delivery recovery. */
90
+ taskNotificationCard?: Array<{ id: string; text: string }>;
82
91
  assistantText: string;
83
92
  plan: PlanStep[];
84
93
  activities: TurnActivity[];
@@ -1,9 +1,11 @@
1
1
  import { RUNTIME_WARNING_PREFIXES, sameRuntimeError } from "../runtime/responseErrors.js";
2
2
  import type { TurnActivity, TurnViewState } from "./turnViewTypes.js";
3
+ import { normalizeTurnActivity } from "./turnActivity.js";
3
4
 
4
5
  export function visibleTurnActivities(state: TurnViewState): TurnActivity[] {
5
- if (state.status !== "failed" || !state.error) return state.activities;
6
- return state.activities.filter((activity) => {
6
+ const activities = state.activities.map(normalizeTurnActivity);
7
+ if (state.status !== "failed" || !state.error) return activities;
8
+ return activities.filter((activity) => {
7
9
  if (activity.id !== `commentary:runtime-error:${state.turnId}`
8
10
  || (activity.kind !== "assistant" && activity.kind !== "reasoning")) return true;
9
11
  const prefix = RUNTIME_WARNING_PREFIXES.find((value) => activity.text.startsWith(value));
@@ -610,6 +610,9 @@ export class ProxySessionController {
610
610
  private readonly recoveryActivityHeartbeat: NodeJS.Timeout;
611
611
  private startupRecovery?: Promise<void>;
612
612
  private queuedPromptsRestored = false;
613
+ private inboundPaused = false;
614
+ private readonly inboundInFlight = new Set<string>();
615
+ private inboundActionsInFlight = 0;
613
616
 
614
617
  constructor(
615
618
  private readonly config: AppConfig,
@@ -647,9 +650,6 @@ export class ProxySessionController {
647
650
  }
648
651
 
649
652
  async onMessage(message: IncomingMessage): Promise<void> {
650
- let forwardedImages: Array<{ messageId: string; imageKey: string }> = [];
651
- let forwardedFiles: Array<{ messageId: string; fileKey: string; fileName: string }> = [];
652
- let coalescedForwardAttachment = false;
653
653
  if (!message.contextKey.startsWith("console:") && !allowsFeishuUser(this.config, message.userId)) {
654
654
  this.logger.debug(
655
655
  { messageId: message.messageId },
@@ -668,9 +668,38 @@ export class ProxySessionController {
668
668
  );
669
669
  return;
670
670
  }
671
- // For accepted messages, claim durable deduplication before acknowledgement so event
672
- // retries cannot add duplicate reactions.
673
- if (!this.store.claimInboundEvent(message.messageId, "message")) return;
671
+ const currentId = this.store.getUserContext(message.contextKey)?.currentSessionId;
672
+ if (!this.store.inboundMessages.claim(message, currentId, currentId ? this.store.executionGeneration(currentId) : 0)) return;
673
+ if (this.inboundPaused || this.recoveryClosed) return;
674
+ await this.processAcceptedMessage(message);
675
+ }
676
+
677
+ get pendingInboundMessages(): number {
678
+ return this.inboundInFlight.size + this.inboundActionsInFlight;
679
+ }
680
+
681
+ pauseInboundMessages(): void {
682
+ this.inboundPaused = true;
683
+ }
684
+
685
+ resumeInboundMessages(): void {
686
+ this.inboundPaused = false;
687
+ }
688
+
689
+ private async processAcceptedMessage(message: IncomingMessage, recoveryGuard?: () => boolean): Promise<void> {
690
+ this.inboundInFlight.add(message.messageId);
691
+ try {
692
+ await this.handleAcceptedMessage(message, recoveryGuard);
693
+ } finally {
694
+ this.inboundInFlight.delete(message.messageId);
695
+ if (!this.recoveryClosed) this.store.inboundMessages.finish(message.messageId);
696
+ }
697
+ }
698
+
699
+ private async handleAcceptedMessage(message: IncomingMessage, recoveryGuard?: () => boolean): Promise<void> {
700
+ let forwardedImages: Array<{ messageId: string; imageKey: string }> = [];
701
+ let forwardedFiles: Array<{ messageId: string; fileKey: string; fileName: string }> = [];
702
+ let coalescedForwardAttachment = false;
674
703
  if (!message.text.trim().startsWith("/")) {
675
704
  const currentId = this.store.getUserContext(message.contextKey)?.currentSessionId;
676
705
  if (currentId) this.recoverySupersededSessions.add(currentId);
@@ -705,6 +734,7 @@ export class ProxySessionController {
705
734
  message.messageId,
706
735
  MESSAGE_RECEIVED_REACTION,
707
736
  );
737
+ if (this.recoveryClosed) return;
708
738
  if (reactionId) {
709
739
  this.store.saveMessageReaction(message.messageId, message.contextKey, reactionId, MESSAGE_RECEIVED_REACTION);
710
740
  }
@@ -716,6 +746,11 @@ export class ProxySessionController {
716
746
  }
717
747
  await this.waitForCurrentSessionReset(message.contextKey);
718
748
  if (this.recoveryClosed) return;
749
+ if (recoveryGuard && !recoveryGuard()) {
750
+ await this.reportUnprocessedMessage(message, "已有后续指令或任务状态发生变化");
751
+ return;
752
+ }
753
+ this.store.inboundMessages.beginDispatch(message.messageId);
719
754
  if (attachmentReservation && this.completeReferenceInstruction(message, attachmentReservation)) {
720
755
  this.store.audit(message.contextKey, "referenced_message_coalesced", {
721
756
  messageId: message.messageId,
@@ -963,6 +998,10 @@ export class ProxySessionController {
963
998
  await this.outbound.withReplyTarget(message.contextKey, replyTarget, async () => {
964
999
  try {
965
1000
  await this.waitForCurrentSessionReset(message.contextKey);
1001
+ if (recoveryGuard && !recoveryGuard()) {
1002
+ await this.reportUnprocessedMessage(message, "已有后续指令或任务状态发生变化");
1003
+ return;
1004
+ }
966
1005
  if (command.type === "prompt") await this.ensureThreadFork(message);
967
1006
  await this.execute(
968
1007
  message.contextKey,
@@ -994,6 +1033,10 @@ export class ProxySessionController {
994
1033
  await this.waitForCurrentSessionReset(message.contextKey);
995
1034
  return this.outbound.withReplyTarget(message.contextKey, replyTarget, async () => {
996
1035
  try {
1036
+ if (recoveryGuard && !recoveryGuard()) {
1037
+ await this.reportUnprocessedMessage(message, "已有后续指令或任务状态发生变化");
1038
+ return;
1039
+ }
997
1040
  let executableCommand = command;
998
1041
  let executableImagePaths = localImagePaths;
999
1042
  let executableMessage = message;
@@ -1061,6 +1104,15 @@ export class ProxySessionController {
1061
1104
  }
1062
1105
 
1063
1106
  async onCardAction(action: CardAction): Promise<void> {
1107
+ this.inboundActionsInFlight += 1;
1108
+ try {
1109
+ await this.handleCardAction(action);
1110
+ } finally {
1111
+ this.inboundActionsInFlight -= 1;
1112
+ }
1113
+ }
1114
+
1115
+ private async handleCardAction(action: CardAction): Promise<void> {
1064
1116
  if (!allowsFeishuUser(this.config, action.userId)) {
1065
1117
  this.logger.debug(
1066
1118
  { actionId: action.actionId },
@@ -1068,6 +1120,10 @@ export class ProxySessionController {
1068
1120
  );
1069
1121
  return;
1070
1122
  }
1123
+ if (this.inboundPaused || this.recoveryClosed) {
1124
+ await this.outbound.sendText(action.contextKey, "Agent Bot 正在重启,请恢复在线后重新操作。");
1125
+ return;
1126
+ }
1071
1127
  if (!this.store.claimInboundEvent(action.actionId, "card_action")) return;
1072
1128
  let resolvedAction: CardAction;
1073
1129
  try {
@@ -1486,9 +1542,22 @@ export class ProxySessionController {
1486
1542
  clearInterval(this.recoveryActivityHeartbeat);
1487
1543
  }
1488
1544
 
1489
- async controlStopTask(localSessionId: string): Promise<string> {
1545
+ async controlStopTask(localSessionId: string, expectedTurnId?: string): Promise<string> {
1490
1546
  const record = this.store.getSession(localSessionId);
1491
1547
  if (!record || record.status === "closed") throw new Error(`Task not found: ${localSessionId}`);
1548
+ if (expectedTurnId) {
1549
+ const runtime = this.runtimes.forAgent(record.agentName);
1550
+ if (!record.remoteSessionId || !runtime.interruptRemoteTurn
1551
+ || runtime.getSession(localSessionId)?.activeTurnId !== expectedTurnId) return "stale";
1552
+ // The App Server interrupt targets this exact turn, not whichever turn is current later.
1553
+ this.store.requestSessionExecutionStop(localSessionId);
1554
+ this.responseContinuations.get(localSessionId)?.abort.abort();
1555
+ this.responseContinuations.delete(localSessionId);
1556
+ this.planHandoffs.delete(localSessionId);
1557
+ await runtime.interruptRemoteTurn(record.remoteSessionId, expectedTurnId);
1558
+ this.store.audit(record.contextKey, "turn_interrupt_sent", { localSessionId, turnId: expectedTurnId, source: "workspace" });
1559
+ return "accepted";
1560
+ }
1492
1561
  await this.cancelSession(record);
1493
1562
  return `Task stop requested: ${record.title ?? record.remoteSessionId ?? record.localSessionId}`;
1494
1563
  }
@@ -1580,7 +1649,9 @@ export class ProxySessionController {
1580
1649
  return `Task title changed to: ${normalizedTitle}`;
1581
1650
  }
1582
1651
 
1583
- async controlSendTaskPrompt(localSessionId: string, text: string): Promise<string> {
1652
+ async controlSendTaskPrompt(localSessionId: string, text: string, workspace?: {
1653
+ requestId: string; onPosting(): void; onPosted(): void;
1654
+ }): Promise<string> {
1584
1655
  const promptText = text.trim();
1585
1656
  if (!promptText) throw new Error("The Prompt cannot be empty.");
1586
1657
  const record = this.store.getSession(localSessionId);
@@ -1619,11 +1690,14 @@ export class ProxySessionController {
1619
1690
  scopedRecord.model,
1620
1691
  scopedRecord.modelProvider,
1621
1692
  );
1693
+ if (workspace && this.store.getSession(localSessionId)?.status === "closed") throw new Error("任务已归档。");
1694
+ workspace?.onPosting();
1622
1695
  const promptMessageId = await this.outbound.withReplyTarget(
1623
1696
  responseContextKey,
1624
1697
  existingReplyTarget,
1625
1698
  () => this.outbound.sendText(responseContextKey, promptText),
1626
1699
  );
1700
+ workspace?.onPosted();
1627
1701
  const turnReplyTarget = isThreadContextKey(responseContextKey)
1628
1702
  ? promptMessageId
1629
1703
  ? { messageId: promptMessageId, replyInThread: true as const }
@@ -1632,7 +1706,8 @@ export class ProxySessionController {
1632
1706
  await this.promptSession(scopedRecord, responseContextKey, promptText, undefined, turnReplyTarget);
1633
1707
  this.store.audit(responseContextKey, "task_prompt_sent", {
1634
1708
  localSessionId,
1635
- source: "cli",
1709
+ source: workspace ? "workspace" : "cli",
1710
+ requestId: workspace?.requestId,
1636
1711
  });
1637
1712
  });
1638
1713
  this.messageQueues.set(responseContextKey, next);
@@ -2439,7 +2514,7 @@ export class ProxySessionController {
2439
2514
  );
2440
2515
  return;
2441
2516
  case "nosteer":
2442
- await this.enqueueNoSteerPrompt(contextKey, command.text, messageId, replyTarget);
2517
+ await this.enqueueNoSteerPrompt(contextKey, command.text, messageId, replyTarget, localImagePaths);
2443
2518
  return;
2444
2519
  case "sessions":
2445
2520
  await this.outbound.sendText(contextKey, LIST_SESSIONS_STARTED_MESSAGE);
@@ -2571,6 +2646,7 @@ export class ProxySessionController {
2571
2646
  }
2572
2647
 
2573
2648
  private async runStartupRecovery(): Promise<void> {
2649
+ await this.recoverUnprocessedMessages();
2574
2650
  await this.finishPersistedCancellationRequests();
2575
2651
  await this.recoverShellCommandJobs();
2576
2652
  const recoveryCutoff = Date.now() - RECOVERY_ACTIVITY_WINDOW_MS;
@@ -2612,6 +2688,61 @@ export class ProxySessionController {
2612
2688
  this.restorePersistedQueuedPrompts();
2613
2689
  }
2614
2690
 
2691
+ private async recoverUnprocessedMessages(): Promise<void> {
2692
+ for (const pending of this.store.inboundMessages.listPending()) {
2693
+ if (this.recoveryClosed || this.inboundPaused) return;
2694
+ const message = pending.message;
2695
+ if (this.inboundInFlight.has(message.messageId) || !this.outbound.canRoute(message.contextKey)) continue;
2696
+ if (!this.store.inboundMessages.isPending(message.messageId)) continue;
2697
+ if (this.store.inboundMessages.hasDurableWork(message.messageId)) {
2698
+ this.store.inboundMessages.finish(message.messageId);
2699
+ continue;
2700
+ }
2701
+ const currentId = this.store.getUserContext(message.contextKey)?.currentSessionId;
2702
+ const superseded = currentId !== pending.localSessionId
2703
+ || (currentId && this.store.executionGeneration(currentId) !== pending.executionGeneration)
2704
+ || this.store.inboundMessages.hasNewerMessage(message.messageId, message.contextKey, pending.localSessionId);
2705
+ const messageAt = Math.min(Date.parse(pending.createdAt), message.createdAt ?? Infinity);
2706
+ const recent = messageAt >= Date.now() - RECOVERY_ACTIVITY_WINDOW_MS;
2707
+ const allowed = message.contextKey.startsWith("console:") || allowsFeishuUser(this.config, message.userId);
2708
+ const muted = message.chatType === "group" && this.store.chatRequiresMention(baseChatContextKey(message.contextKey))
2709
+ && message.mentionedBot !== true;
2710
+ if (!allowed || muted) {
2711
+ this.store.inboundMessages.finish(message.messageId);
2712
+ continue;
2713
+ }
2714
+ const isStop = /^\/stop\s*$/iu.test(message.text.trim());
2715
+ if (pending.status === "received" && recent && !superseded && (!message.text.trimStart().startsWith("/") || isStop)) {
2716
+ this.logger.warn({ messageId: message.messageId, contextKey: message.contextKey }, "Recovering a received but unprocessed message.");
2717
+ await this.processAcceptedMessage(message, () => {
2718
+ const current = this.store.getUserContext(message.contextKey)?.currentSessionId;
2719
+ return current === pending.localSessionId
2720
+ && (!current || this.store.executionGeneration(current) === pending.executionGeneration)
2721
+ && !this.store.inboundMessages.hasNewerMessage(message.messageId, message.contextKey, pending.localSessionId)
2722
+ && messageAt >= Date.now() - RECOVERY_ACTIVITY_WINDOW_MS;
2723
+ }).catch((error: unknown) => {
2724
+ this.logger.warn({ error, messageId: message.messageId }, "Failed to recover an unprocessed message.");
2725
+ });
2726
+ continue;
2727
+ }
2728
+ if (isStop && pending.localSessionId && recent && !superseded) this.recoverySupersededSessions.add(pending.localSessionId);
2729
+ const reason = superseded ? "已有后续指令或任务绑定发生变化" : !recent ? "已超过 20 分钟" : "处理结果无法确认";
2730
+ await this.reportUnprocessedMessage(message, reason).then(() => {
2731
+ this.store.inboundMessages.finish(message.messageId);
2732
+ }).catch((error: unknown) => {
2733
+ this.logger.warn({ error, messageId: message.messageId }, "Failed to notify about an interrupted inbound message.");
2734
+ });
2735
+ }
2736
+ }
2737
+
2738
+ private async reportUnprocessedMessage(message: IncomingMessage, reason: string): Promise<void> {
2739
+ const replyTarget = message.replyInThread ? { messageId: message.messageId, replyInThread: true as const } : undefined;
2740
+ await this.finalizeStandaloneMessageReaction(message.messageId, "failed");
2741
+ await this.outbound.withReplyTarget(message.contextKey, replyTarget, () => this.outbound.sendText(
2742
+ message.contextKey, `重启前有一条消息未确认提交(${reason}),未自动重发。需要继续时请重新发送该消息。`,
2743
+ ));
2744
+ }
2745
+
2615
2746
  private async finishPersistedCancellationRequests(): Promise<void> {
2616
2747
  for (const attempt of this.store.listCancellationRequestedTurnAttempts()) {
2617
2748
  if (attempt.executionGeneration === this.store.executionGeneration(attempt.localSessionId)) {
@@ -3353,13 +3484,15 @@ export class ProxySessionController {
3353
3484
  const activeTurnId = loaded.session.activeTurnId;
3354
3485
  if (activeTurnId) {
3355
3486
  const activeContextKey = this.store.getTurnContextKey(activeTurnId);
3356
- if (activeContextKey && activeContextKey !== contextKey) {
3487
+ const notificationTurn = Boolean(turnViewSnapshot(this.store.getTurnSnapshot(activeTurnId))?.taskNotificationCard);
3488
+ if ((activeContextKey && activeContextKey !== contextKey) || notificationTurn) {
3357
3489
  this.persistQueuedPrompt(record.localSessionId, contextKey, text, {
3358
3490
  localImagePaths,
3359
3491
  messageId,
3360
3492
  replyTarget,
3361
3493
  displayPrompt,
3362
3494
  });
3495
+ if (notificationTurn) await this.presentPromptQueueCard(record.localSessionId, contextKey);
3363
3496
  return;
3364
3497
  }
3365
3498
  try {
@@ -3383,7 +3516,8 @@ export class ProxySessionController {
3383
3516
  if (messageId) await this.bindMessageReactionToTurn(messageId, record.localSessionId, turnId);
3384
3517
  return;
3385
3518
  }
3386
- if (current.activeTurnId !== activeTurnId) {
3519
+ const notificationTurn = Boolean(turnViewSnapshot(this.store.getTurnSnapshot(current.activeTurnId))?.taskNotificationCard);
3520
+ if (current.activeTurnId !== activeTurnId && !notificationTurn) {
3387
3521
  try {
3388
3522
  this.assertExecutionGeneration(record.localSessionId, executionGeneration);
3389
3523
  await loaded.runtime.steerTurn(
@@ -3416,6 +3550,7 @@ export class ProxySessionController {
3416
3550
  replyTarget,
3417
3551
  displayPrompt,
3418
3552
  });
3553
+ if (notificationTurn) await this.presentPromptQueueCard(record.localSessionId, contextKey);
3419
3554
  return;
3420
3555
  }
3421
3556
  }
@@ -3446,9 +3581,10 @@ export class ProxySessionController {
3446
3581
  text: string,
3447
3582
  messageId?: string,
3448
3583
  replyTarget?: MessageReplyTarget,
3584
+ localImagePaths?: string[],
3449
3585
  ): Promise<void> {
3450
3586
  const record = this.requireCurrentSession(contextKey);
3451
- const queued = this.persistQueuedPrompt(record.localSessionId, contextKey, text, { messageId, replyTarget });
3587
+ const queued = this.persistQueuedPrompt(record.localSessionId, contextKey, text, { messageId, replyTarget, localImagePaths });
3452
3588
  this.store.audit(contextKey, "queued_prompt_added", {
3453
3589
  promptId: queued.promptId,
3454
3590
  localSessionId: record.localSessionId,
@@ -68,8 +68,25 @@ export interface ApprovalRequest {
68
68
  options: Array<{ id: ApprovalDecision; label: string }>;
69
69
  }
70
70
 
71
+ export interface ModelQueueStatus {
72
+ state: "queued" | "waiting" | "ready";
73
+ position?: number;
74
+ message?: string;
75
+ operation?: "contextCompaction";
76
+ }
77
+
78
+ export const TASK_NOTIFICATION_ACTIVITY_PREFIX = "commentary:task-notification:";
79
+
71
80
  export type AgentEvent =
72
81
  | { type: "turn_started"; sessionId: string; turnId: string; startedAt: number }
82
+ | {
83
+ type: "model_queue_updated";
84
+ sessionId: string;
85
+ turnId: string;
86
+ queue: ModelQueueStatus;
87
+ timestampMs?: number;
88
+ reason?: "output" | "turn_ended" | "disconnected";
89
+ }
73
90
  | { type: "agent_text_delta"; sessionId: string; turnId: string; text: string; replacesActivityId?: string }
74
91
  | {
75
92
  type: "token_usage_updated";