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

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 (159) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +102 -18
  3. package/README.zh.md +102 -18
  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 +2676 -243
  9. package/assets/workspace.css +553 -44
  10. package/assets/workspace.js +3429 -327
  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 +51 -22
  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 +106 -14
  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 +141 -122
  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 +53 -276
  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 +43 -0
  61. package/dist/local-files/WorkspaceImages.js.map +1 -0
  62. package/dist/local-files/WorkspacePage.js +24 -6
  63. package/dist/local-files/WorkspacePage.js.map +1 -1
  64. package/dist/local-files/WorkspaceSessions.js +1153 -104
  65. package/dist/local-files/WorkspaceSessions.js.map +1 -1
  66. package/dist/local-files/WorkspaceTimeline.js +129 -0
  67. package/dist/local-files/WorkspaceTimeline.js.map +1 -0
  68. package/dist/presentation/OutboundRouter.js +15 -6
  69. package/dist/presentation/OutboundRouter.js.map +1 -1
  70. package/dist/presentation/TurnStateReducer.js +31 -22
  71. package/dist/presentation/TurnStateReducer.js.map +1 -1
  72. package/dist/proxy/ProxySessionController.js +335 -113
  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 +53 -12
  81. package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
  82. package/dist/scheduling/types.js +19 -4
  83. package/dist/scheduling/types.js.map +1 -1
  84. package/dist/state/StateStore.js +213 -23
  85. package/dist/state/StateStore.js.map +1 -1
  86. package/dist/state/TurnPreviewJournal.js +157 -39
  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 +22 -0
  101. package/dist/utils/promptAttachments.js.map +1 -0
  102. package/dist/utils/promptQuotes.js +47 -0
  103. package/dist/utils/promptQuotes.js.map +1 -0
  104. package/dist/utils/toolTimestamp.js +6 -0
  105. package/dist/utils/toolTimestamp.js.map +1 -0
  106. package/npm-shrinkwrap.json +2 -2
  107. package/package.json +1 -1
  108. package/skills/agent-bot/SKILL.md +23 -2
  109. package/src/cli/SelfUpdateObserver.ts +111 -0
  110. package/src/cli/SelfUpdateRunner.ts +271 -85
  111. package/src/cli/SelfUpdater.ts +53 -16
  112. package/src/cli/controlProtocol.ts +1 -0
  113. package/src/cli/help.ts +6 -0
  114. package/src/cli.ts +71 -5
  115. package/src/codex/CodexEventMapper.ts +25 -5
  116. package/src/codex/CodexRuntime.ts +4 -0
  117. package/src/feishu/CardRenderer.ts +48 -13
  118. package/src/feishu/ConsoleFeishuClient.ts +6 -1
  119. package/src/feishu/FeishuMarkdown.ts +2 -14
  120. package/src/feishu/FeishuMessageClient.ts +10 -0
  121. package/src/feishu/FeishuTurnPresenter.ts +49 -16
  122. package/src/feishu/types.ts +1 -0
  123. package/src/index.ts +47 -12
  124. package/src/local-files/DiagramPreview.ts +11 -6
  125. package/src/local-files/GitDiffPreview.ts +107 -15
  126. package/src/local-files/LiveMarkup.ts +103 -0
  127. package/src/local-files/LocalFileViewerServer.ts +128 -125
  128. package/src/local-files/MarkdownExport.ts +54 -0
  129. package/src/local-files/PreviewCodeFont.ts +12 -0
  130. package/src/local-files/PreviewSyntaxHighlight.ts +75 -0
  131. package/src/local-files/ToolCommandDisplay.ts +104 -0
  132. package/src/local-files/TurnPreviewPage.ts +58 -261
  133. package/src/local-files/WorkspaceFileEvents.ts +186 -0
  134. package/src/local-files/WorkspaceFiles.ts +72 -5
  135. package/src/local-files/WorkspaceImages.ts +35 -0
  136. package/src/local-files/WorkspacePage.ts +24 -6
  137. package/src/local-files/WorkspaceSessions.ts +1057 -111
  138. package/src/local-files/WorkspaceTimeline.ts +135 -0
  139. package/src/presentation/OutboundRouter.ts +18 -4
  140. package/src/presentation/TurnStateReducer.ts +30 -19
  141. package/src/presentation/turnViewTypes.ts +3 -1
  142. package/src/proxy/ProxySessionController.ts +336 -96
  143. package/src/proxy/TaskMetadata.ts +81 -0
  144. package/src/runtime/types.ts +2 -1
  145. package/src/scheduling/ScheduleCards.ts +10 -4
  146. package/src/scheduling/ScheduleCommand.ts +4 -0
  147. package/src/scheduling/ScheduledTaskStore.ts +56 -9
  148. package/src/scheduling/types.ts +27 -4
  149. package/src/state/StateStore.ts +227 -24
  150. package/src/state/TurnPreviewJournal.ts +155 -38
  151. package/src/state/TurnToolText.ts +156 -0
  152. package/src/state/migrations.ts +4 -0
  153. package/src/supervision/SafeRestartNotifier.ts +9 -6
  154. package/src/terminal/TerminalPage.ts +5 -0
  155. package/src/updates/AutomaticUpdatePreparer.ts +52 -11
  156. package/src/updates/ManualUpdateController.ts +8 -3
  157. package/src/utils/promptAttachments.ts +27 -0
  158. package/src/utils/promptQuotes.ts +48 -0
  159. package/src/utils/toolTimestamp.ts +5 -0
@@ -9,7 +9,8 @@ import { migrations } from "./migrations.js";
9
9
  import { ExecutionProvenanceStore } from "./ExecutionProvenanceStore.js";
10
10
  import { InboundMessageStore } from "./InboundMessageStore.js";
11
11
  import type { UpdateCheckSchedule, UpdateNotice } from "../updates/types.js";
12
- import type { ConversationTurn, RuntimeExecutionSettings } from "../runtime/types.js";
12
+ import type { ConversationTurn, PlanStep, RuntimeExecutionSettings } from "../runtime/types.js";
13
+ import { previewToolHeading } from "../local-files/ToolCommandDisplay.js";
13
14
 
14
15
  export interface PendingProviderSettings {
15
16
  localSessionId: string;
@@ -294,6 +295,7 @@ interface TurnAttemptRow {
294
295
 
295
296
  export class StateStore {
296
297
  private readonly db: Database.Database;
298
+ private readonly queuedPromptDispatches = new Map<string, QueuedPromptRecord>();
297
299
  readonly previews: TurnPreviewJournal;
298
300
  readonly schedules: ScheduledTaskStore;
299
301
  readonly provenance: ExecutionProvenanceStore;
@@ -303,6 +305,10 @@ export class StateStore {
303
305
  this.previews = new TurnPreviewJournal(path.join(path.dirname(sqlitePath), "turn-previews"), onPreviewError);
304
306
  fs.mkdirSync(path.dirname(sqlitePath), { recursive: true });
305
307
  this.db = new Database(sqlitePath);
308
+ this.db.function("workspace_tool_heading", { deterministic: true }, (title: string | null, kind: string | null, command: string | null) => {
309
+ const heading = previewToolHeading({ title: title ?? "", kind: kind ?? "工具", command: command ?? undefined }, "命令");
310
+ return JSON.stringify({ ...heading, title: heading.title.slice(0, 240) });
311
+ });
306
312
  this.db.pragma("journal_mode = WAL");
307
313
  for (const migration of migrations) {
308
314
  this.db.exec(migration);
@@ -648,6 +654,33 @@ export class StateStore {
648
654
  return rows.map(mapQueuedPrompt);
649
655
  }
650
656
 
657
+ // Keep the claimed prompt readable in Workspace while its chat entry is being published.
658
+ trackQueuedPromptDispatch(prompt: QueuedPromptRecord): () => void {
659
+ this.queuedPromptDispatches.set(prompt.promptId, prompt);
660
+ return () => {
661
+ if (this.queuedPromptDispatches.get(prompt.promptId) === prompt) this.queuedPromptDispatches.delete(prompt.promptId);
662
+ };
663
+ }
664
+
665
+ listQueuedPromptDispatches(localSessionId: string): QueuedPromptRecord[] {
666
+ return [...this.queuedPromptDispatches.values()].filter(prompt => prompt.localSessionId === localSessionId);
667
+ }
668
+
669
+ getQueuedPrompt(localSessionId: string, promptId: string): QueuedPromptRecord | undefined {
670
+ const row = this.db.prepare("SELECT * FROM queued_prompts WHERE local_session_id = ? AND prompt_id = ?")
671
+ .get(localSessionId, promptId) as QueuedPromptRow | undefined;
672
+ return row ? mapQueuedPrompt(row) : undefined;
673
+ }
674
+
675
+ updateQueuedPrompt(previous: QueuedPromptRecord, content: Pick<QueuedPromptRecord, "text" | "displayPrompt">): boolean {
676
+ const updated = this.db.prepare(`
677
+ UPDATE queued_prompts SET prompt_text = ?, display_prompt = ?
678
+ WHERE local_session_id = ? AND prompt_id = ? AND prompt_text = ? AND display_prompt IS ?
679
+ `).run(content.text, content.displayPrompt ?? null, previous.localSessionId, previous.promptId,
680
+ previous.text, previous.displayPrompt ?? null);
681
+ return updated.changes === 1;
682
+ }
683
+
651
684
  hasQueuedPrompt(promptId: string): boolean {
652
685
  return Boolean(this.db.prepare("SELECT 1 FROM queued_prompts WHERE prompt_id = ?").get(promptId));
653
686
  }
@@ -687,6 +720,7 @@ export class StateStore {
687
720
  if (!row) return undefined;
688
721
  this.db.prepare("DELETE FROM queued_prompts WHERE prompt_id = ?").run(row.prompt_id);
689
722
  if (!this.schedules.claimStart(row.prompt_id)) continue;
723
+ const prompt = mapQueuedPrompt(row);
690
724
  if (this.schedules.getRun(row.prompt_id)) {
691
725
  const existing = this.getTurnAttempt(row.prompt_id);
692
726
  if (existing) {
@@ -698,15 +732,44 @@ export class StateStore {
698
732
  executionGeneration: this.executionGeneration(localSessionId) });
699
733
  } else {
700
734
  this.createTurnAttempt({ attemptId: row.prompt_id, localSessionId, contextKey: row.context_key,
701
- promptText: row.prompt_text, replyMessageId: row.reply_message_id ?? undefined });
735
+ promptText: row.prompt_text, localImagePaths: prompt.localImagePaths,
736
+ replyMessageId: row.reply_message_id ?? undefined });
702
737
  }
703
738
  }
704
- return mapQueuedPrompt(row);
739
+ return prompt;
705
740
  }
706
741
  });
707
742
  return take();
708
743
  }
709
744
 
745
+ claimQueuedPromptForImmediateSend(prompt: QueuedPromptRecord): boolean {
746
+ return this.db.transaction(() => {
747
+ const current = this.getQueuedPrompt(prompt.localSessionId, prompt.promptId);
748
+ if (!current || current.text !== prompt.text || current.displayPrompt !== prompt.displayPrompt) return false;
749
+ const run = this.schedules.getRun(prompt.promptId);
750
+ if (run) {
751
+ const attempt = this.getTurnAttempt(run.id);
752
+ if (attempt && (attempt.submissionState !== "not_submitted" || attempt.turnId)) return false;
753
+ if (!this.schedules.claimStart(run.id)) return false;
754
+ this.schedules.saveRun({ ...this.schedules.getRun(run.id)!, status: "submitting" });
755
+ }
756
+ this.db.prepare("DELETE FROM queued_prompts WHERE local_session_id = ? AND prompt_id = ?").run(prompt.localSessionId, prompt.promptId);
757
+ return true;
758
+ })();
759
+ }
760
+
761
+ restoreQueuedPromptAfterImmediateSend(prompt: QueuedPromptRecord): void {
762
+ this.db.transaction(() => {
763
+ const run = this.schedules.getRun(prompt.promptId);
764
+ if (run) {
765
+ if (run.status !== "submitting") return;
766
+ this.schedules.saveRun({ ...run, status: "queued", startedAt: undefined });
767
+ if (!this.schedules.canSubmit(run.id)) return;
768
+ }
769
+ if (!this.hasQueuedPrompt(prompt.promptId)) this.enqueuePrompt(prompt);
770
+ })();
771
+ }
772
+
710
773
  cancelQueuedPrompt(promptId: string, localSessionId: string): QueuedPromptRecord | undefined {
711
774
  const cancel = this.db.transaction(() => {
712
775
  const row = this.db.prepare(`
@@ -721,6 +784,21 @@ export class StateStore {
721
784
  return cancel();
722
785
  }
723
786
 
787
+ cancelWorkspaceQueuedPrompt(promptId: string, localSessionId: string, request: string) {
788
+ return this.db.transaction(() => {
789
+ const fingerprint = JSON.stringify(["cancel-queued-prompt", localSessionId, promptId]);
790
+ const previous = this.workspaceRequest(request);
791
+ if (previous) {
792
+ if (previous.fingerprint !== fingerprint) throw new Error("该请求标识已用于另一项操作。");
793
+ return { cancelled: previous.status === "accepted", prompt: undefined };
794
+ }
795
+ this.beginWorkspaceRequest(request, localSessionId, fingerprint);
796
+ const prompt = this.cancelQueuedPrompt(promptId, localSessionId);
797
+ this.updateWorkspaceRequest(request, prompt ? "accepted" : "stale");
798
+ return { cancelled: Boolean(prompt), prompt };
799
+ })();
800
+ }
801
+
724
802
  createTurnAttempt(input: {
725
803
  attemptId: string;
726
804
  localSessionId: string;
@@ -739,7 +817,11 @@ export class StateStore {
739
817
  status?: Extract<TurnAttemptStatus, "accepted" | "running" | "recovering">;
740
818
  createdAt?: string;
741
819
  updatedAt?: string;
742
- }): TurnAttemptRecord {
820
+ }, beforeCreate?: () => void): TurnAttemptRecord {
821
+ if (beforeCreate) return this.db.transaction(() => {
822
+ beforeCreate();
823
+ return this.createTurnAttempt(input);
824
+ })();
743
825
  const createdAt = input.createdAt ?? new Date().toISOString();
744
826
  const updatedAt = input.updatedAt ?? createdAt;
745
827
  const status = input.status ?? (input.turnId ? "running" : "accepted");
@@ -1290,6 +1372,27 @@ export class StateStore {
1290
1372
  })();
1291
1373
  }
1292
1374
 
1375
+ listTaskMetadata(localSessionId: string, kind: string): { key: string; value: string }[] {
1376
+ return this.db.prepare("SELECT key, value FROM task_metadata WHERE local_session_id = ? AND kind = ? ORDER BY value")
1377
+ .all(localSessionId, kind) as { key: string; value: string }[];
1378
+ }
1379
+
1380
+ getTaskMetadata(localSessionId: string, kind: string, key: string): string | undefined {
1381
+ const row = this.db.prepare("SELECT value FROM task_metadata WHERE local_session_id = ? AND kind = ? AND key = ?")
1382
+ .get(localSessionId, kind, key) as { value: string } | undefined;
1383
+ return row?.value;
1384
+ }
1385
+
1386
+ setTaskMetadata(localSessionId: string, kind: string, key: string, value: string): void {
1387
+ this.db.prepare(`INSERT INTO task_metadata (local_session_id, kind, key, value) VALUES (?, ?, ?, ?)
1388
+ ON CONFLICT (local_session_id, kind, key) DO UPDATE SET value = excluded.value`).run(localSessionId, kind, key, value);
1389
+ }
1390
+
1391
+ removeTaskMetadata(localSessionId: string, kind: string, key: string): boolean {
1392
+ return this.db.prepare("DELETE FROM task_metadata WHERE local_session_id = ? AND kind = ? AND key = ?")
1393
+ .run(localSessionId, kind, key).changes > 0;
1394
+ }
1395
+
1293
1396
  workspaceRequest(id: string) {
1294
1397
  return this.db.prepare(`SELECT local_session_id AS localSessionId, fingerprint, status, posted, message
1295
1398
  FROM workspace_requests WHERE id = ?`).get(id) as
@@ -1306,6 +1409,10 @@ export class StateStore {
1306
1409
  .run(status, Number(posted), message ?? null, id);
1307
1410
  }
1308
1411
 
1412
+ markWorkspaceRequestPosted(id: string): void {
1413
+ this.db.prepare("UPDATE workspace_requests SET posted = 1 WHERE id = ?").run(id);
1414
+ }
1415
+
1309
1416
  workspaceTurnHead(task: SessionRecord): string | undefined {
1310
1417
  if (task.lastTurnId && task.status !== "running" && task.status !== "starting"
1311
1418
  && this.db.prepare("SELECT 1 FROM turn_snapshots WHERE turn_id = ?").get(task.lastTurnId)) return task.lastTurnId;
@@ -1318,53 +1425,145 @@ export class StateStore {
1318
1425
  workspaceTurnPage(localSessionId: string, head: string | undefined, before?: string, limit = 20): {
1319
1426
  ids: string[]; more: boolean; beforeMissing: boolean;
1320
1427
  } {
1428
+ const ids: string[] = [];
1429
+ let found = !before;
1430
+ for (const id of this.workspaceTurnChain(localSessionId, head)) {
1431
+ if (found) ids.push(id);
1432
+ if (id === before) found = true;
1433
+ if (ids.length > limit) break;
1434
+ }
1435
+ return { ids: ids.slice(0, limit), more: ids.length > limit, beforeMissing: !found };
1436
+ }
1437
+
1438
+ workspaceTurnsAfter(localSessionId: string, head: string | undefined, after: string, limit: number): {
1439
+ ids: string[]; more: boolean; cursorMissing: boolean;
1440
+ } {
1441
+ if (after === head) return { ids: [], more: false, cursorMissing: false };
1442
+ // Walk the current branch from its head, retaining only the closest successors of the cursor.
1443
+ const nearest: string[] = [];
1444
+ for (const id of this.workspaceTurnChain(localSessionId, head)) {
1445
+ if (id === after) return { ids: nearest.slice(-limit).reverse(), more: nearest.length > limit, cursorMissing: false };
1446
+ if (nearest.length > limit) nearest.shift();
1447
+ nearest.push(id);
1448
+ }
1449
+ return { ids: [], more: false, cursorMissing: true };
1450
+ }
1451
+
1452
+ workspaceConversationMetrics(localSessionId: string, head: string | undefined) {
1453
+ const readUsage = this.db.prepare(`SELECT json_extract(snapshot_json, '$.tokenUsageTotalCumulative') AS totalTokens
1454
+ FROM turn_snapshots WHERE turn_id = ? AND local_session_id = ?`);
1455
+ let turnCount = 0;
1456
+ let totalTokens: number | undefined;
1457
+ for (const id of this.workspaceTurnChain(localSessionId, head)) {
1458
+ turnCount++;
1459
+ if (totalTokens !== undefined || turnCount > 20) continue;
1460
+ // Use the latest published total from this task, including while its next turn is starting.
1461
+ const tokens = (readUsage.get(id, localSessionId) as { totalTokens?: unknown } | undefined)?.totalTokens;
1462
+ if (typeof tokens === "number" && Number.isSafeInteger(tokens) && tokens >= 0) totalTokens = tokens;
1463
+ }
1464
+ return { turnCount, totalTokens };
1465
+ }
1466
+
1467
+ private *workspaceTurnChain(localSessionId: string, head: string | undefined): IterableIterator<string> {
1321
1468
  const read = this.db.prepare(`SELECT s.local_session_id AS owner, p.turn_id AS linked, p.parent_turn_id AS parent
1322
1469
  FROM turn_snapshots s LEFT JOIN turn_parent_links p ON p.turn_id = s.turn_id WHERE s.turn_id = ?`);
1323
1470
  type Node = { owner: string; linked: string | null; parent: string | null };
1324
1471
  let id = head;
1325
- let fallback = true;
1326
- const ids: string[] = [], seen = new Set<string>();
1327
- let found = !before;
1328
- while (id && !seen.has(id) && seen.size < 20_000 && ids.length <= limit) {
1472
+ const seen = new Set<string>(), backfilled = new Set<string>();
1473
+ while (id && !seen.has(id) && seen.size < 20_000) {
1329
1474
  seen.add(id);
1330
1475
  let node = read.get(id) as Node | undefined;
1331
1476
  if (!node || seen.size === 1 && node.owner !== localSessionId && !this.hasTaskHistoryTurn(localSessionId, id)) break;
1332
- if (fallback && !node.linked) {
1477
+ if (!node.linked && !backfilled.has(node.owner)) {
1333
1478
  this.backfillTurnParents(node.owner);
1479
+ backfilled.add(node.owner);
1334
1480
  node = read.get(id) as Node;
1335
- fallback = false;
1336
1481
  }
1337
- if (found) ids.push(id);
1338
- if (id === before) found = true;
1482
+ yield id;
1339
1483
  id = node.parent ?? (seen.size === 1 && node.owner === localSessionId
1340
1484
  ? this.findForkSourceTurnId(localSessionId) : undefined);
1341
1485
  }
1342
- return { ids: ids.slice(0, limit), more: ids.length > limit, beforeMissing: !found };
1343
1486
  }
1344
1487
 
1345
1488
  workspaceTurnText(turnId: string) {
1346
- return this.db.prepare(`SELECT updated_at AS revision,
1489
+ return this.db.prepare(`SELECT updated_at AS revision, local_session_id AS ownerTask,
1347
1490
  substr(json_extract(snapshot_json, '$.prompt'), 1, 24001) AS prompt,
1348
1491
  snapshot_json -> '$.promptImagePaths' AS promptImages,
1349
- substr(json_extract(snapshot_json, '$.finalResponse'), 1, 48001) AS answer,
1350
- substr(json_extract(snapshot_json, '$.assistantText'), 1, 48001) AS live,
1492
+ json_extract(snapshot_json, '$.promptRequestId') AS promptRequestId,
1493
+ json_extract(snapshot_json, '$.finalResponse') AS answer,
1494
+ json_extract(snapshot_json, '$.assistantText') AS live,
1351
1495
  substr(json_extract(snapshot_json, '$.error'), 1, 3000) AS error,
1352
1496
  substr(json_extract(snapshot_json, '$.statusMessage'), 1, 3000) AS notice,
1353
1497
  json_extract(snapshot_json, '$.status') AS status,
1354
1498
  json_extract(snapshot_json, '$.startedAt') AS startedAt,
1499
+ json_extract(snapshot_json, '$.completedAt') AS completedAt,
1500
+ json_extract(snapshot_json, '$.durationMs') AS durationMs,
1501
+ json_extract(snapshot_json, '$.totalTokens') AS totalTokens,
1502
+ json_extract(snapshot_json, '$.cachedInputTokens') AS cachedInputTokens,
1503
+ json_extract(snapshot_json, '$.totalTokensIncludingCache') AS totalTokensIncludingCache,
1504
+ json_extract(snapshot_json, '$.modelCallCount') AS modelCallCount,
1505
+ json_extract(snapshot_json, '$.totalToolCount') AS totalToolCount,
1355
1506
  json_extract(snapshot_json, '$.historyDetail') AS detail,
1356
- (SELECT json_group_array(json_object('kind', kind, 'id', id, 'text', body, 'images', json(images))) FROM (
1357
- SELECT json_extract(value, '$.kind') AS kind, json_extract(value, '$.id') AS id,
1358
- substr(json_extract(value, '$.text'), 1, 4000) AS body,
1359
- value -> '$.localImagePaths' AS images
1360
- FROM json_each(snapshot_json, '$.activities')
1361
- WHERE json_extract(value, '$.kind') IN ('user', 'assistant') LIMIT 30)) AS dialogue
1507
+ coalesce(json_array_length(snapshot_json, '$.fileSummary'), 0) AS changeCount,
1508
+ snapshot_json -> '$.fileSummary' AS changeSummary,
1509
+ json_extract(snapshot_json, '$.previewTurnId') AS journalId,
1510
+ json_extract(snapshot_json, '$.continuedToTurnId') AS continuedToTurnId,
1511
+ coalesce(json_extract(snapshot_json, '$.activitiesTruncated'), 0) AS compact,
1512
+ (SELECT json_group_array(json_object('kind', kind, 'id', id, 'text', body, 'images', json(images),
1513
+ 'heading', json(heading), 'toolKind', toolKind, 'status', status, 'startedAt', activityStart, 'completedAt', toolEnd) ORDER BY ordinal) FROM (
1514
+ SELECT key AS ordinal, json_extract(value, '$.kind') AS kind, json_extract(value, '$.id') AS id,
1515
+ json_extract(value, '$.text') AS body, value -> '$.localImagePaths' AS images,
1516
+ CASE WHEN json_extract(value, '$.kind') = 'tool' THEN workspace_tool_heading(json_extract(value, '$.tool.title'),
1517
+ json_extract(value, '$.tool.kind'), json_extract(value, '$.tool.command')) END AS heading,
1518
+ json_extract(value, '$.tool.kind') AS toolKind, json_extract(value, '$.tool.status') AS status,
1519
+ coalesce(json_extract(value, '$.tool.startedAt'), json_extract(value, '$.startedAt')) AS activityStart,
1520
+ json_extract(value, '$.tool.completedAt') AS toolEnd
1521
+ FROM json_each(snapshot_json, '$.activities'))) AS activities,
1522
+ (SELECT json_group_array(json_object('id', id, 'after', after, 'parts', json(parts))
1523
+ ORDER BY ordinal) FROM (
1524
+ SELECT item.key AS ordinal, json_extract(item.value, '$.itemId') AS id,
1525
+ json_extract(item.value, '$.afterActivityId') AS after,
1526
+ (SELECT json_group_array(json_object('index', section, 'text', snippet) ORDER BY section) FROM (
1527
+ SELECT part.key AS section, substr(part.value, 1, 512) AS snippet
1528
+ FROM json_each(item.value, '$.summary') AS part
1529
+ WHERE part.type = 'text' AND trim(part.value) != '')) AS parts
1530
+ FROM json_each(snapshot_json, '$.reasoningItems') AS item)) AS reasoning
1362
1531
  FROM turn_snapshots WHERE turn_id = ?`).get(turnId) as {
1363
- revision: string; prompt: string | null; promptImages: string | null; answer: string | null; live: string | null;
1364
- error: string | null; notice: string | null; status: string; startedAt: number; detail: string | null; dialogue: string;
1532
+ revision: string; ownerTask: string; prompt: string | null; promptImages: string | null; promptRequestId: string | null; answer: string | null; live: string | null;
1533
+ error: string | null; notice: string | null; status: string; startedAt: number; completedAt: number | null;
1534
+ durationMs: number | null; detail: string | null;
1535
+ totalTokens: number | null; cachedInputTokens: number | null; totalTokensIncludingCache: number | null;
1536
+ modelCallCount: number | null; totalToolCount: number | null;
1537
+ changeCount: number; changeSummary: string | null; journalId: string | null; continuedToTurnId: string | null;
1538
+ compact: number; activities: string; reasoning: string;
1365
1539
  } | undefined;
1366
1540
  }
1367
1541
 
1542
+ workspaceTurnPlan(turnId: string): PlanStep[] {
1543
+ const row = this.db.prepare("SELECT snapshot_json -> '$.plan' AS plan FROM turn_snapshots WHERE turn_id = ?")
1544
+ .get(turnId) as { plan: string | null } | undefined;
1545
+ return row?.plan ? JSON.parse(row.plan) ?? [] : [];
1546
+ }
1547
+
1548
+ workspaceTurnExecution(turnId: string) {
1549
+ return this.db.prepare(`SELECT
1550
+ json_extract(snapshot_json, '$.startedAt') AS startedAt,
1551
+ json_extract(snapshot_json, '$.model') AS model,
1552
+ json_extract(snapshot_json, '$.reasoningEffort') AS thinking,
1553
+ json_extract(snapshot_json, '$.totalTokens') AS totalTokens,
1554
+ json_extract(snapshot_json, '$.cachedInputTokens') AS cachedInputTokens,
1555
+ json_extract(snapshot_json, '$.totalTokensIncludingCache') AS totalTokensIncludingCache
1556
+ FROM turn_snapshots WHERE turn_id = ?`).get(turnId) as
1557
+ { startedAt: number | null; model: string | null; thinking: string | null;
1558
+ totalTokens: number | null; cachedInputTokens: number | null; totalTokensIncludingCache: number | null } | undefined;
1559
+ }
1560
+
1561
+ workspaceTurnAnswer(turnId: string): string | undefined {
1562
+ const row = this.db.prepare("SELECT json_extract(snapshot_json, '$.finalResponse') AS answer FROM turn_snapshots WHERE turn_id = ?")
1563
+ .get(turnId) as { answer: string | null } | undefined;
1564
+ return row?.answer ?? undefined;
1565
+ }
1566
+
1368
1567
  getTurnSnapshot(turnId: string): unknown {
1369
1568
  const row = this.db
1370
1569
  .prepare("SELECT snapshot_json FROM turn_snapshots WHERE turn_id = ?")
@@ -2475,6 +2674,10 @@ export class StateStore {
2475
2674
  .run(canonical.local_session_id, duplicate.local_session_id);
2476
2675
  this.db.prepare("DELETE FROM context_sessions WHERE local_session_id = ?")
2477
2676
  .run(duplicate.local_session_id);
2677
+ this.db.prepare(`INSERT OR IGNORE INTO task_metadata (local_session_id, kind, key, value)
2678
+ SELECT ?, kind, key, value FROM task_metadata WHERE local_session_id = ?`)
2679
+ .run(canonical.local_session_id, duplicate.local_session_id);
2680
+ this.db.prepare("DELETE FROM task_metadata WHERE local_session_id = ?").run(duplicate.local_session_id);
2478
2681
  this.db.prepare("DELETE FROM sessions WHERE local_session_id = ?")
2479
2682
  .run(duplicate.local_session_id);
2480
2683
  }