@covro/covro 0.13.0 → 0.13.1-dev.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/README.md +6 -4
  2. package/README.zh-CN.md +6 -4
  3. package/dist/cli/daemon.js +6 -3
  4. package/dist/cli/daemon.js.map +2 -2
  5. package/dist/codex/adapter.js +124 -40
  6. package/dist/codex/adapter.js.map +2 -2
  7. package/dist/codex/history-cursor.js +9 -0
  8. package/dist/codex/history-cursor.js.map +7 -0
  9. package/dist/codex/mapping.js +1 -0
  10. package/dist/codex/mapping.js.map +2 -2
  11. package/dist/drizzle/0012_turn_completion_reads.sql +5 -0
  12. package/dist/drizzle/meta/0012_snapshot.json +935 -0
  13. package/dist/drizzle/meta/_journal.json +7 -0
  14. package/dist/server/db/schema.js +9 -0
  15. package/dist/server/db/schema.js.map +2 -2
  16. package/dist/server/db/session-loops.js +3 -0
  17. package/dist/server/db/session-loops.js.map +2 -2
  18. package/dist/server/db/turn-completion-reads.js +20 -0
  19. package/dist/server/db/turn-completion-reads.js.map +7 -0
  20. package/dist/server/events.js +2 -1
  21. package/dist/server/events.js.map +2 -2
  22. package/dist/server/http.js +40 -0
  23. package/dist/server/http.js.map +2 -2
  24. package/dist/server/pending-questions.js +112 -0
  25. package/dist/server/pending-questions.js.map +7 -0
  26. package/dist/server/projection.js +27 -0
  27. package/dist/server/projection.js.map +2 -2
  28. package/dist/server/service.js +441 -57
  29. package/dist/server/service.js.map +3 -3
  30. package/dist/shared/pending-questions.js +23 -0
  31. package/dist/shared/pending-questions.js.map +7 -0
  32. package/dist/shared/session-loop.js.map +2 -2
  33. package/dist/shared/thread-summary.js +6 -3
  34. package/dist/shared/thread-summary.js.map +2 -2
  35. package/dist/shared/updates.js +5 -1
  36. package/dist/shared/updates.js.map +2 -2
  37. package/dist/updates/manager.js +96 -56
  38. package/dist/updates/manager.js.map +3 -3
  39. package/dist/web/assets/{abnfDiagram-WEYOIA3C-VKQzcff4.js → abnfDiagram-WEYOIA3C-CXKtu9-o.js} +1 -1
  40. package/dist/web/assets/{arc-COa63zsj.js → arc-BdjYMbNi.js} +1 -1
  41. package/dist/web/assets/{architecture-WOLXFQ4H-BFUhehor.js → architecture-WOLXFQ4H-C8t4DOFI.js} +1 -1
  42. package/dist/web/assets/{architectureDiagram-ZHVYKT53-C8N69nkM.js → architectureDiagram-ZHVYKT53-Cc60AJKI.js} +1 -1
  43. package/dist/web/assets/{blockDiagram-RJAE7QA3-otci22TD.js → blockDiagram-RJAE7QA3-DowHDVT9.js} +1 -1
  44. package/dist/web/assets/{c4Diagram-XDPPPE54-B94W81hB.js → c4Diagram-XDPPPE54-Tnsu1pna.js} +1 -1
  45. package/dist/web/assets/channel-DfO37ME1.js +1 -0
  46. package/dist/web/assets/{chunk-2E7WHVMD-CTUGLthN.js → chunk-2E7WHVMD-eAlSIXPv.js} +1 -1
  47. package/dist/web/assets/{chunk-4EMNKR2T-BvWl_5CT.js → chunk-4EMNKR2T-CmhkMYsp.js} +1 -1
  48. package/dist/web/assets/{chunk-55XCU76K-DBQltAmG.js → chunk-55XCU76K-9dacXylK.js} +1 -1
  49. package/dist/web/assets/{chunk-7S6XSTFO-DrTF1ZwS.js → chunk-7S6XSTFO-34Y1JIn0.js} +1 -1
  50. package/dist/web/assets/{chunk-AQDTSKZB-3StVe5-Q.js → chunk-AQDTSKZB-CG7DnIG0.js} +1 -1
  51. package/dist/web/assets/{chunk-DSNLSHJZ-Dn-DjnoN.js → chunk-DSNLSHJZ-Xl8wgMxB.js} +1 -1
  52. package/dist/web/assets/{chunk-HAGFOTED-DAwM_w8g.js → chunk-HAGFOTED-BPRUSFQR.js} +1 -1
  53. package/dist/web/assets/{chunk-HNE4Q36P-BlismgIE.js → chunk-HNE4Q36P-ZiupiHsw.js} +1 -1
  54. package/dist/web/assets/{chunk-NQOKRVIF-rzESIyWm.js → chunk-NQOKRVIF-sqtDdp_y.js} +1 -1
  55. package/dist/web/assets/{chunk-UHW7PFBP-DWsBWWze.js → chunk-UHW7PFBP-BVWjUtWH.js} +1 -1
  56. package/dist/web/assets/{chunk-VQ5W62QI-Lw-vq83A.js → chunk-VQ5W62QI-DITuWjWc.js} +1 -1
  57. package/dist/web/assets/{chunk-WQQL4CDK-jJ7h9zYn.js → chunk-WQQL4CDK-DkM_YMN2.js} +1 -1
  58. package/dist/web/assets/{chunk-XXDRQBXY-CKWP5PZ9.js → chunk-XXDRQBXY-PxXiVbvY.js} +1 -1
  59. package/dist/web/assets/{chunk-YZO67HFG-NYhXnQRx.js → chunk-YZO67HFG-BIkYtSfc.js} +1 -1
  60. package/dist/web/assets/{chunk-ZAUX2LTX-gUs1ZXjL.js → chunk-ZAUX2LTX-Bk4q3e23.js} +1 -1
  61. package/dist/web/assets/{chunk-ZCHMQSOR-E0NZEQ-O.js → chunk-ZCHMQSOR-C5sGqKAI.js} +1 -1
  62. package/dist/web/assets/{classDiagram-v2-4MYWR3UA-DfrMXinu.js → classDiagram-v2-4MYWR3UA-1cVKBUV_.js} +1 -1
  63. package/dist/web/assets/{cose-bilkent-JH36ORCC-DkOHEcIe.js → cose-bilkent-JH36ORCC-iHinujQv.js} +1 -1
  64. package/dist/web/assets/{cynefin-EF2NZ3EQ-CyLWLDQM.js → cynefin-EF2NZ3EQ-fq6mKatY.js} +1 -1
  65. package/dist/web/assets/{cynefinDiagram-WF24UDRP-BguYvVXt.js → cynefinDiagram-WF24UDRP-CIGiwJz4.js} +1 -1
  66. package/dist/web/assets/{dagre-NK4GIZVX-NZCpu-Ev.js → dagre-NK4GIZVX-B30dfmw6.js} +1 -1
  67. package/dist/web/assets/{diagram-CBK3MWTC-B6GfMqgY.js → diagram-CBK3MWTC-CWxKeAwb.js} +1 -1
  68. package/dist/web/assets/{diagram-I5XIIV2D-Dw813usy.js → diagram-I5XIIV2D-Ba9MInPb.js} +1 -1
  69. package/dist/web/assets/{diagram-ODIL2UCW-DAB6HXQB.js → diagram-ODIL2UCW-CB4yPAWh.js} +1 -1
  70. package/dist/web/assets/{diagram-PFBEJUXE-CtZ-OuIM.js → diagram-PFBEJUXE-CpWkrDHM.js} +1 -1
  71. package/dist/web/assets/{diagram-RJA3I4VV-D5_wwcuc.js → diagram-RJA3I4VV-BlzdIvzp.js} +1 -1
  72. package/dist/web/assets/{diagram-TYUNFSNR-BJ0niZEk.js → diagram-TYUNFSNR-DhP8DSgJ.js} +1 -1
  73. package/dist/web/assets/{dist-gv7Vie7q.js → dist-sYbUJuv2.js} +1 -1
  74. package/dist/web/assets/{ebnfDiagram-V4P3TTPT-bi8C34k_.js → ebnfDiagram-V4P3TTPT-BQZhJhUE.js} +1 -1
  75. package/dist/web/assets/{elk-QONTBCTQ-1CT1qIsk.js → elk-QONTBCTQ-beOX6XQE.js} +1 -1
  76. package/dist/web/assets/{erDiagram-KYQIGQAA-XbBBxMJ8.js → erDiagram-KYQIGQAA-2wJBvwOf.js} +1 -1
  77. package/dist/web/assets/{eventmodeling-K75KTNOO-CNIXgVS8.js → eventmodeling-K75KTNOO-QHYSBSiB.js} +1 -1
  78. package/dist/web/assets/flowDiagram-IUGLLWBU-DQpgoQhD.js +1 -0
  79. package/dist/web/assets/{ganttDiagram-R7GPNTJY-BfppzYjp.js → ganttDiagram-R7GPNTJY-D7BMJZQy.js} +1 -1
  80. package/dist/web/assets/{gitGraph-VSP46ZUC-C-r7tdkR.js → gitGraph-VSP46ZUC-DY68RJX8.js} +1 -1
  81. package/dist/web/assets/{gitGraphDiagram-PDYL7XHY-knE68g5s.js → gitGraphDiagram-PDYL7XHY-W9I_Fzam.js} +1 -1
  82. package/dist/web/assets/index-DM38fNEw.js +167 -0
  83. package/dist/web/assets/index-Dxa8FyZG.css +1 -0
  84. package/dist/web/assets/{info-OHQRW6UA-SNoUm1ts.js → info-OHQRW6UA-ByEOSl7U.js} +1 -1
  85. package/dist/web/assets/{infoDiagram-MVDRKAX5-DEGQzuOo.js → infoDiagram-MVDRKAX5-B0M4EHQH.js} +1 -1
  86. package/dist/web/assets/{ishikawaDiagram-HPEHV2GE-mn3lP7lV.js → ishikawaDiagram-HPEHV2GE-DNlLOcIv.js} +1 -1
  87. package/dist/web/assets/{journeyDiagram-BOSHW7O7-CQK-_yp_.js → journeyDiagram-BOSHW7O7-CA3l2bIl.js} +1 -1
  88. package/dist/web/assets/{kanban-definition-FNSA4HC5-CmRv0wjY.js → kanban-definition-FNSA4HC5-oTstz9Nh.js} +1 -1
  89. package/dist/web/assets/{line-YrC7SPSA.js → line-_o3jHE7B.js} +1 -1
  90. package/dist/web/assets/{linear-DL9cbtFk.js → linear-C3pv5_Hc.js} +1 -1
  91. package/dist/web/assets/{mermaid-parser.core-BQJtCXlM.js → mermaid-parser.core-DFsp5we8.js} +3 -3
  92. package/dist/web/assets/{mermaid.core-DtHU_ni4.js → mermaid.core-RCBjzbNc.js} +4 -4
  93. package/dist/web/assets/{mindmap-definition-6OY57UG3-CZ8mFL3Z.js → mindmap-definition-6OY57UG3-BYL5SWaF.js} +1 -1
  94. package/dist/web/assets/{packet-JDAUHWVQ-Bd2aL4cu.js → packet-JDAUHWVQ-BYzAau3S.js} +1 -1
  95. package/dist/web/assets/{pegDiagram-ECIUJNBX-BcPUwXjm.js → pegDiagram-ECIUJNBX-CDZ-7EQo.js} +1 -1
  96. package/dist/web/assets/{pie-XZMESJXO-C2KoVynh.js → pie-XZMESJXO-nODe9OSM.js} +1 -1
  97. package/dist/web/assets/{pieDiagram-GNMPY74T-CTsseMg3.js → pieDiagram-GNMPY74T-oXYs8QAh.js} +1 -1
  98. package/dist/web/assets/{quadrantDiagram-D57K4MC3-CkV6S8fH.js → quadrantDiagram-D57K4MC3-DwiXSOJh.js} +1 -1
  99. package/dist/web/assets/{radar-ABXABTNO-Cimh1CvS.js → radar-ABXABTNO-DfKzRwmb.js} +1 -1
  100. package/dist/web/assets/{railroad-I3PHUGI6-bdbRlage.js → railroad-I3PHUGI6-CjnCqajf.js} +1 -1
  101. package/dist/web/assets/{railroad-abnf-LNEFI6M7-DpuX1OPJ.js → railroad-abnf-LNEFI6M7-BC7OjMc0.js} +1 -1
  102. package/dist/web/assets/{railroad-ebnf-DWYD2UWJ-Czlsl9OW.js → railroad-ebnf-DWYD2UWJ-CDIEFnYt.js} +1 -1
  103. package/dist/web/assets/{railroad-peg-JR7BVNR7-DLH-s5Fb.js → railroad-peg-JR7BVNR7-D2ww2uLD.js} +1 -1
  104. package/dist/web/assets/{railroadDiagram-Y72NRBL7-CwrCsGc6.js → railroadDiagram-Y72NRBL7-lnP6zg-0.js} +1 -1
  105. package/dist/web/assets/{requirementDiagram-EQYSW5RA-YfvDd89_.js → requirementDiagram-EQYSW5RA-6PWA6btZ.js} +1 -1
  106. package/dist/web/assets/{sankeyDiagram-SY24JHO5-BsfTkJOP.js → sankeyDiagram-SY24JHO5-ILtro_zY.js} +1 -1
  107. package/dist/web/assets/{sequenceDiagram-BLEHNHQU-1wb-DVrk.js → sequenceDiagram-BLEHNHQU-Bf8N3m4Q.js} +1 -1
  108. package/dist/web/assets/{src-CdQyjtH_.js → src-BHmiNYeq.js} +1 -1
  109. package/dist/web/assets/{stateDiagram-v2-A6IESKWZ-DU8d20xl.js → stateDiagram-v2-A6IESKWZ-CcANNIZS.js} +1 -1
  110. package/dist/web/assets/{swimlanes-B3ENRKFQ-CuFkf7fA.js → swimlanes-B3ENRKFQ-QUB_h2I9.js} +1 -1
  111. package/dist/web/assets/swimlanesDiagram-AYQRV4AK-8-1zJkfB.js +8 -0
  112. package/dist/web/assets/{timeline-definition-JXYKGLGB-DZ5sFRaj.js → timeline-definition-JXYKGLGB-D4vzP-bU.js} +1 -1
  113. package/dist/web/assets/{treeView-D4JQ5SDB-BMX1NHKa.js → treeView-D4JQ5SDB-34fgNxgc.js} +1 -1
  114. package/dist/web/assets/{treemap-SAJKECNS-23EnrCnH.js → treemap-SAJKECNS-CBzhnkLA.js} +1 -1
  115. package/dist/web/assets/{usecaseDiagram-WPOLBNNX-BV_UOzMO.js → usecaseDiagram-WPOLBNNX-B6NsUKy_.js} +1 -1
  116. package/dist/web/assets/{vennDiagram-Q3Y3IDCW-Cax1nsaM.js → vennDiagram-Q3Y3IDCW-jU1aaLpP.js} +1 -1
  117. package/dist/web/assets/{wardley-7MLQ67FV-B3WjXYg5.js → wardley-7MLQ67FV-Cf2rHct4.js} +1 -1
  118. package/dist/web/assets/{wardleyDiagram-IVAIDKWA-JUrgn8Lo.js → wardleyDiagram-IVAIDKWA-2OCftPiz.js} +1 -1
  119. package/dist/web/assets/{xychartDiagram-4URNHDU4-DbCgOhE7.js → xychartDiagram-4URNHDU4-BQoVxc1P.js} +1 -1
  120. package/dist/web/index.html +2 -2
  121. package/package.json +5 -5
  122. package/dist/web/assets/channel-D2aytYVy.js +0 -1
  123. package/dist/web/assets/flowDiagram-IUGLLWBU-DJDqyrqb.js +0 -1
  124. package/dist/web/assets/index-BKzqPG6k.js +0 -166
  125. package/dist/web/assets/index-D4z03hlo.css +0 -1
  126. package/dist/web/assets/swimlanesDiagram-AYQRV4AK-C1UUPoDy.js +0 -8
@@ -5,6 +5,11 @@ import {
5
5
  } from "./global-instructions.js";
6
6
  import { questionAnswers } from "../shared/question-resolution.js";
7
7
  import { asyncQuestionId, parseQuestionReplies } from "../shared/async-questions.js";
8
+ import {
9
+ pendingQuestionCatalog,
10
+ questionEvidence
11
+ } from "./pending-questions.js";
12
+ import { canTrackQuestions } from "../shared/pending-questions.js";
8
13
  import { QuestionTrackingStore } from "./db/question-tracking.js";
9
14
  import { nullLogger } from "../logging/logger.js";
10
15
  import { errorFields } from "../logging/fields.js";
@@ -32,17 +37,19 @@ import {
32
37
  validateElicitationResolution,
33
38
  validatePermissionResolution
34
39
  } from "../shared/elicitation.js";
35
- import { toThreadSummary } from "../shared/thread-summary.js";
40
+ import { completedTurnId, toThreadSummary } from "../shared/thread-summary.js";
36
41
  import {
37
42
  requestDigest,
38
43
  StoreConflict
39
44
  } from "./db/operations.js";
40
45
  import { EventHub } from "./events.js";
41
46
  import { TurnUsageStore } from "./db/turn-usage.js";
47
+ import { TurnCompletionReads } from "./db/turn-completion-reads.js";
42
48
  import { Projection, isActive, isTerminal } from "./projection.js";
43
49
  import { BackgroundTasks } from "./background-tasks.js";
44
50
  import { ProjectClones } from "./project-clones.js";
45
51
  import { renderThreadExport } from "./thread-export.js";
52
+ import { HISTORY_PAGE_SIZE, historyCursor } from "../codex/history-cursor.js";
46
53
  import { readLocalImage } from "./images.js";
47
54
  import { temporaryFileRoots } from "./local-files.js";
48
55
  import { readLocalMarkdown } from "./markdown.js";
@@ -51,6 +58,17 @@ import { readLocalJson } from "./json-files.js";
51
58
  import { sessionCreationResult } from "./session-creation.js";
52
59
  import { createSessionLoopSchema, createSessionSchema } from "../shared/validation.js";
53
60
  import { SessionLoopStore, sessionLoopView } from "./db/session-loops.js";
61
+ function deferLiveToolOutput(item) {
62
+ if (item.status !== "completed" || item.outputDeferred || item.error) return item;
63
+ if (item.type === "commandExecution" && item.output)
64
+ return { ...item, output: "", outputDeferred: true };
65
+ if (item.type !== "mcpToolCall" || !item.details || typeof item.details !== "object") return item;
66
+ const details = item.details;
67
+ const result = details.result;
68
+ if (details.error != null || !Array.isArray(result?.content) || !result.content.length || result.structuredContent != null || result._meta != null || !result.content.every((part) => part?.type === "text" && typeof part.text === "string") || !result.content.some((part) => part.text.length))
69
+ return item;
70
+ return { ...item, outputDeferred: true, details: { ...details, result: null } };
71
+ }
54
72
  class GatewayService {
55
73
  constructor(options) {
56
74
  this.options = options;
@@ -58,6 +76,7 @@ class GatewayService {
58
76
  this.logger = (options.logger ?? nullLogger).child({ component: "operations" });
59
77
  this.store = options.store;
60
78
  this.turnUsage = new TurnUsageStore(this.store.database);
79
+ this.turnCompletionReads = new TurnCompletionReads(this.store.database);
61
80
  this.questionTracking = new QuestionTrackingStore(
62
81
  this.store.database,
63
82
  this.logger.child({ component: "question_tracking" })
@@ -109,7 +128,9 @@ class GatewayService {
109
128
  projection;
110
129
  store;
111
130
  turnUsage;
131
+ turnCompletionReads;
112
132
  questionTracking;
133
+ questionHistories = /* @__PURE__ */ new Map();
113
134
  projects;
114
135
  workspaces;
115
136
  codex;
@@ -679,7 +700,24 @@ class GatewayService {
679
700
  async listThreadSummaries(projectId, cursor, archived = false) {
680
701
  const boundary = this.events.cursor();
681
702
  const page = await this.listThreads(projectId, cursor, archived);
682
- return { data: page.data.map(toThreadSummary), nextCursor: page.nextCursor, cursor: boundary };
703
+ return {
704
+ data: page.data.map((thread) => this.threadSummary(thread)),
705
+ nextCursor: page.nextCursor,
706
+ cursor: boundary
707
+ };
708
+ }
709
+ async readTurnCompletion(threadId, turnId) {
710
+ await this.loadThread(threadId);
711
+ const thread = this.projection.get(threadId);
712
+ this.workspaces.assertOwnership(thread.projectId, thread.cwd, threadId);
713
+ const summary = this.threadSummary(this.threadView(thread, false));
714
+ if (completedTurnId(summary) === turnId) {
715
+ if (this.turnCompletionReads.record(threadId, turnId))
716
+ this.logger.info("completion.read", { threadId, turnId });
717
+ summary.lastTurnRead = true;
718
+ this.publishThreadSummary(summary, true);
719
+ }
720
+ return { threadId, summary, cursor: this.events.cursor() };
683
721
  }
684
722
  async setThreadArchived(threadId, input) {
685
723
  return this.perform("thread.archive", threadId, input, async () => {
@@ -724,7 +762,7 @@ class GatewayService {
724
762
  result: {
725
763
  threadId,
726
764
  archived: input.archived,
727
- summary: toThreadSummary(this.threadView(this.projection.get(threadId))),
765
+ summary: this.threadSummary(this.threadView(this.projection.get(threadId))),
728
766
  cursor: this.events.cursor()
729
767
  }
730
768
  };
@@ -767,7 +805,7 @@ class GatewayService {
767
805
  result: {
768
806
  threadId,
769
807
  name,
770
- summary: toThreadSummary(this.threadView(this.projection.get(threadId))),
808
+ summary: this.threadSummary(this.threadView(this.projection.get(threadId))),
771
809
  cursor: this.events.cursor()
772
810
  }
773
811
  };
@@ -827,37 +865,210 @@ class GatewayService {
827
865
  if (this.codex.ready) await this.refreshThreadMetadata(threadId);
828
866
  this.workspaces.assertOwnership(cached.projectId, cached.cwd, cached.id);
829
867
  await this.refreshGoal(cached);
830
- return { ...this.threadView(cached), turns: [], actions: [] };
868
+ return {
869
+ ...this.threadView(cached, false, false),
870
+ pendingQuestions: void 0,
871
+ turns: [],
872
+ actions: []
873
+ };
831
874
  }
832
875
  const metadata = this.threadView(this.normalize(await this.codex.readThreadMetadata(threadId)));
833
876
  await this.refreshGoal(metadata);
834
877
  metadata.historyVisible = this.historyVisible(metadata);
835
878
  return { ...metadata, turns: [], actions: [] };
836
879
  }
837
- async refreshThreadDetail(threadId) {
880
+ async getThread(threadId) {
881
+ return this.detailThreadView(await this.openThread(threadId, true));
882
+ }
883
+ async openThread(threadId, waitForExecution) {
838
884
  const cached = this.projection.get(threadId);
839
- await this.loadThread(threadId);
885
+ await this.loadThread(threadId, { raw: true, waitForExecution });
886
+ const marker = this.store.activeForThread(threadId);
887
+ if (marker && !waitForExecution) void this.refreshExecution(marker);
840
888
  if (cached && this.codex.ready) await this.refreshThreadMetadata(threadId);
841
889
  const thread = this.projection.get(threadId);
842
890
  this.workspaces.assertOwnership(thread.projectId, thread.cwd, thread.id);
843
891
  await this.refreshGoal(thread);
892
+ this.workspaces.assertOwnership(thread.projectId, thread.cwd, thread.id);
844
893
  return thread;
845
894
  }
846
- async getThread(threadId) {
847
- return this.threadView(await this.refreshThreadDetail(threadId));
848
- }
849
895
  getThreadAttention(threadId) {
850
896
  const thread = this.projection.get(threadId);
851
897
  if (!thread) return [];
852
898
  this.workspaces.assertOwnership(thread.projectId, thread.cwd, thread.id);
853
- return pendingAttention(this.threadView(thread));
899
+ return pendingAttention(this.threadView(thread, false, false));
854
900
  }
855
- async getThreadSnapshot(threadId) {
856
- await this.refreshThreadDetail(threadId);
857
- const thread = this.projection.get(threadId);
901
+ scanQuestionHistory(thread, retry = false) {
902
+ const { id, projectId } = thread;
903
+ const cursor = thread.history?.olderCursor;
904
+ if (!cursor || thread.archived || !this.codex.ready || !this.codex.readThreadPage) return;
905
+ const epoch = this.codex.epoch;
906
+ const previous = this.questionHistories.get(id);
907
+ if (previous?.epoch === epoch && previous.cursor === cursor && (previous.status !== "error" || !retry && Date.now() < (previous.retryAt ?? 0)))
908
+ return;
909
+ const entry = {
910
+ epoch,
911
+ cursor,
912
+ status: "loading",
913
+ turns: previous?.turns ?? /* @__PURE__ */ new Map(),
914
+ observed: previous?.observed
915
+ };
916
+ this.questionHistories.set(id, entry);
917
+ const current = () => this.questionHistories.get(id) === entry && this.codex.epoch === epoch;
918
+ const logger = this.logger.child({
919
+ component: "question_history",
920
+ ...logContext(),
921
+ threadId: id,
922
+ codexEpoch: epoch
923
+ });
924
+ const started = Date.now();
925
+ logger.debug("question.history_scan_started");
926
+ void (async () => {
927
+ const pages = [];
928
+ const seen = /* @__PURE__ */ new Set();
929
+ let next = cursor;
930
+ while (next && current()) {
931
+ if (seen.has(next) || seen.size >= 1e3)
932
+ throw new AppError(
933
+ "QUESTION_HISTORY_INCOMPLETE",
934
+ "Invalid question history pagination",
935
+ 409
936
+ );
937
+ seen.add(next);
938
+ const page = await this.codex.readThreadPage(id, next, { deferOutput: true });
939
+ if (!current()) return;
940
+ if (page.id !== id || page.historyTruncated || !page.history)
941
+ throw new AppError("QUESTION_HISTORY_INCOMPLETE", "Incomplete question history", 409);
942
+ this.workspaces.assertOwnership(projectId, page.cwd, id);
943
+ const source = next;
944
+ pages.push(page.turns.map((turn) => ({ turn: questionEvidence(turn), cursor: source })));
945
+ next = page.history.olderCursor;
946
+ }
947
+ if (!current()) return;
948
+ entry.turns = new Map(
949
+ pages.reverse().flat().map((source) => [source.turn.id, source])
950
+ );
951
+ entry.status = "ready";
952
+ this.publishThread(id);
953
+ logger.debug("question.history_scan_finished", {
954
+ count: seen.size,
955
+ durationMs: Date.now() - started,
956
+ outcome: "succeeded"
957
+ });
958
+ })().catch((problem) => {
959
+ if (!current()) return;
960
+ entry.status = "error";
961
+ entry.retryAt = Date.now() + 3e4;
962
+ logger.warn("question.history_scan_finished", {
963
+ durationMs: Date.now() - started,
964
+ outcome: "failed",
965
+ ...errorFields(problem)
966
+ });
967
+ this.publishThread(id);
968
+ });
969
+ }
970
+ questionHistory(threadId) {
971
+ const history = this.questionHistories.get(threadId);
972
+ return history?.epoch === this.codex.epoch ? history : void 0;
973
+ }
974
+ questionState(thread) {
975
+ const history = this.questionHistory(thread.id);
976
+ const cursor = thread.history?.olderCursor;
977
+ return pendingQuestionCatalog(
978
+ thread,
979
+ cursor && history && cursor !== history.cursor ? { ...history, status: "loading" } : history
980
+ ).state;
981
+ }
982
+ async questionCatalog(threadId) {
983
+ const thread = this.projection.get(threadId) ?? await this.openThread(threadId, false);
858
984
  this.workspaces.assertOwnership(thread.projectId, thread.cwd, thread.id);
985
+ this.scanQuestionHistory(thread);
986
+ return {
987
+ thread,
988
+ ...pendingQuestionCatalog(
989
+ this.threadView(thread, false, false),
990
+ this.questionHistory(threadId)
991
+ )
992
+ };
993
+ }
994
+ async getPendingQuestions(threadId, cursor, retry = false) {
995
+ const { data, state, thread } = await this.questionCatalog(threadId);
996
+ if (retry && !cursor && state.history === "error") {
997
+ this.scanQuestionHistory(thread, true);
998
+ if (this.questionHistory(threadId)?.status === "loading") {
999
+ this.publishThread(threadId);
1000
+ state.history = "loading";
1001
+ }
1002
+ }
1003
+ let offset = 0;
1004
+ if (cursor !== void 0) {
1005
+ const [version, position, extra] = cursor.split(".");
1006
+ offset = Number(position);
1007
+ if (version !== state.version || extra !== void 0 || !Number.isSafeInteger(offset) || offset < 1 || offset >= data.length)
1008
+ throw new AppError("QUESTION_LIST_CHANGED", "The pending questions changed", 409);
1009
+ }
1010
+ const end = offset + 40;
1011
+ return {
1012
+ data: data.slice(offset, end),
1013
+ nextCursor: end < data.length ? `${state.version}.${end}` : null,
1014
+ history: state.history
1015
+ };
1016
+ }
1017
+ async locateQuestion(threadId, target) {
1018
+ const find = async () => {
1019
+ const catalog = await this.questionCatalog(threadId);
1020
+ const row2 = catalog.data.find(
1021
+ (row3) => row3.id === target.questionId && row3.target.kind === target.kind && row3.target.id === target.id && row3.turnId === target.turnId
1022
+ );
1023
+ if (!row2) throw new AppError("QUESTION_EXPIRED", "\u8BE5\u95EE\u9898\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5237\u65B0\u4F1A\u8BDD", 409);
1024
+ return { ...catalog, row: row2 };
1025
+ };
1026
+ const epoch = this.codex.epoch;
1027
+ const { row, thread } = await find();
1028
+ if (row.target.kind === "action") return {};
1029
+ const source = this.questionHistory(threadId)?.turns.get(row.turnId);
1030
+ let turn = thread.turns.find((turn2) => turn2.id === row.turnId);
1031
+ let cursor;
1032
+ if (!turn && source) {
1033
+ try {
1034
+ const page = await this.getThreadHistory(threadId, source.cursor);
1035
+ if (page.id === threadId) turn = page.turns.find((turn2) => turn2.id === row.turnId);
1036
+ if (turn) cursor = source.cursor;
1037
+ } catch (problem) {
1038
+ if (!(problem instanceof AppError && problem.code === "HISTORY_CURSOR_EXPIRED"))
1039
+ throw problem;
1040
+ }
1041
+ if (!turn && this.codex.readThreadTurnItems && this.codex.epoch === epoch) {
1042
+ const metadata = this.normalize(await this.codex.readThreadMetadata(threadId));
1043
+ if (metadata.id !== threadId || metadata.archived)
1044
+ throw new AppError("QUESTION_EXPIRED", "\u8BE5\u95EE\u9898\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5237\u65B0\u4F1A\u8BDD", 409);
1045
+ this.workspaces.assertOwnership(thread.projectId, metadata.cwd, threadId);
1046
+ turn = {
1047
+ ...source.turn,
1048
+ items: await this.codex.readThreadTurnItems(threadId, source.turn.id)
1049
+ };
1050
+ }
1051
+ }
1052
+ const { replies } = await find();
1053
+ if (this.codex.epoch !== epoch)
1054
+ throw new AppError("QUESTION_EXPIRED", "\u8BE5\u95EE\u9898\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5237\u65B0\u4F1A\u8BDD", 409);
1055
+ const item = turn?.items.find((item2) => item2.id === row.target.id);
1056
+ if (!turn || turn.threadId !== threadId || !canTrackQuestions(turn.status) || !item?.questions?.some((_, index) => asyncQuestionId(item.id, index) === row.id))
1057
+ throw new AppError("QUESTION_EXPIRED", "\u8BE5\u95EE\u9898\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5237\u65B0\u4F1A\u8BDD", 409);
1058
+ return {
1059
+ turn,
1060
+ cursor,
1061
+ turnNumber: row.turnNumber,
1062
+ replies: [
1063
+ item.id,
1064
+ ...item.questions.map((_, index) => asyncQuestionId(item.id, index))
1065
+ ].flatMap((id) => replies.get(id) ?? [])
1066
+ };
1067
+ }
1068
+ async getThreadSnapshot(threadId) {
1069
+ const thread = await this.openThread(threadId, false);
859
1070
  return {
860
- data: this.threadView(thread),
1071
+ data: this.detailThreadView(thread),
861
1072
  cursor: this.events.cursor()
862
1073
  };
863
1074
  }
@@ -869,14 +1080,34 @@ class GatewayService {
869
1080
  this.workspaces.assertOwnership(metadata.projectId, metadata.cwd, metadata.id);
870
1081
  if (!this.codex.readThreadPage)
871
1082
  throw new AppError("HISTORY_UNAVAILABLE", "\u5F53\u524D Codex \u4E0D\u652F\u6301\u5386\u53F2\u5206\u9875", 409);
872
- const page = this.normalize(await this.codex.readThreadPage(threadId, cursor));
1083
+ const page = this.normalize(
1084
+ await this.codex.readThreadPage(threadId, cursor, { deferOutput: true })
1085
+ );
873
1086
  this.workspaces.assertOwnership(page.projectId, page.cwd, page.id);
874
1087
  const links = this.retryLinks(threadId);
875
1088
  for (const turn of page.turns) {
876
1089
  const root = links.get(turn.id);
877
1090
  if (root) turn.retryOf = root;
878
1091
  }
879
- return this.threadView(page);
1092
+ return { ...this.threadView(page, true, false), pendingQuestions: void 0 };
1093
+ }
1094
+ async getThreadItem(threadId, turnId, itemId) {
1095
+ this.ensureReady();
1096
+ const epoch = this.codex.epoch;
1097
+ const metadata = await this.codex.readThreadMetadata(threadId);
1098
+ if (metadata.id !== threadId || this.codex.epoch !== epoch)
1099
+ throw new AppError("THREAD_ITEM_NOT_FOUND", "\u5DE5\u5177\u8F93\u51FA\u4E0D\u53EF\u7528\u3002", 404);
1100
+ const thread = this.normalize(metadata);
1101
+ this.workspaces.assertOwnership(thread.projectId, thread.cwd, threadId);
1102
+ if (thread.historyMode !== "paginated" || !this.codex.readThreadItem)
1103
+ throw new AppError("HISTORY_UNAVAILABLE", "\u5F53\u524D Codex \u4E0D\u652F\u6301\u6309\u6761\u8BFB\u53D6\u5386\u53F2\u3002", 409);
1104
+ const item = await this.codex.readThreadItem(threadId, turnId, itemId);
1105
+ this.workspaces.assertOwnership(thread.projectId, thread.cwd, threadId);
1106
+ if (this.codex.epoch !== epoch)
1107
+ throw new AppError("HISTORY_CURSOR_EXPIRED", "\u8BFB\u53D6\u671F\u95F4 Codex \u5DF2\u91CD\u542F\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u4F1A\u8BDD\u3002", 409);
1108
+ if (item.id !== itemId || !["commandExecution", "mcpToolCall"].includes(item.type))
1109
+ throw new AppError("THREAD_ITEM_NOT_FOUND", "\u5DE5\u5177\u8F93\u51FA\u4E0D\u53EF\u7528\u3002", 404);
1110
+ return this.projection.limit(item);
880
1111
  }
881
1112
  async exportThread(threadId) {
882
1113
  this.ensureReady();
@@ -932,24 +1163,25 @@ class GatewayService {
932
1163
  this.workspaces.assertOwnership(link.projectId, link.cwd, threadId);
933
1164
  return file;
934
1165
  }
935
- async loadThread(threadId) {
1166
+ async loadThread(threadId, options) {
1167
+ const view = (thread) => options?.raw ? thread : this.threadView(thread);
936
1168
  const cached = this.projection.get(threadId);
937
1169
  if (cached) {
938
1170
  this.workspaces.assertOwnership(cached.projectId, cached.cwd, cached.id);
939
1171
  const marker = this.store.activeForThread(threadId);
940
1172
  if (marker && this.codex.ready) {
941
- await this.refreshExecution(marker);
942
- return this.threadView(cached);
1173
+ if (options?.waitForExecution !== false) await this.refreshExecution(marker);
1174
+ return view(cached);
943
1175
  }
944
1176
  if ((cached.managed || isActive(cached.status)) && cached.status !== "unknown" || !this.codex.ready)
945
- return this.threadView(cached);
1177
+ return view(cached);
946
1178
  }
947
1179
  const existing = this.reads.get(threadId);
948
- if (existing) return this.threadView(await existing);
1180
+ if (existing) return view(await existing);
949
1181
  const revision = this.projection.revision(threadId);
950
1182
  const loading = (async () => {
951
1183
  const thread = this.normalize(
952
- await (this.codex.readThreadPage?.(threadId) ?? this.codex.readThread(threadId))
1184
+ await (this.codex.readThreadPage?.(threadId, void 0, { deferOutput: true }) ?? this.codex.readThread(threadId))
953
1185
  );
954
1186
  const current = this.projection.get(threadId);
955
1187
  const preserveCurrent = current && (cached === void 0 || this.projection.revision(threadId) !== revision);
@@ -964,7 +1196,7 @@ class GatewayService {
964
1196
  })();
965
1197
  this.reads.set(threadId, loading);
966
1198
  try {
967
- return this.threadView(await loading);
1199
+ return view(await loading);
968
1200
  } finally {
969
1201
  this.reads.delete(threadId);
970
1202
  }
@@ -1080,7 +1312,9 @@ class GatewayService {
1080
1312
  delete current.resumeError;
1081
1313
  pending = (async () => {
1082
1314
  try {
1083
- const resumed = await this.codex.resumeThread(threadId, ownership.cwd, input.settings);
1315
+ const resumed = await this.codex.resumeThread(threadId, ownership.cwd, input.settings, {
1316
+ deferOutput: true
1317
+ });
1084
1318
  if (this.codex.epoch !== epoch || !this.codex.ready)
1085
1319
  throw new Error("\u6062\u590D\u8BF7\u6C42\u5DF2\u53D1\u9001\uFF0C\u4F46 Codex \u5B9E\u4F8B\u5DF2\u53D8\u5316\uFF0C\u8BF7\u6838\u5BF9\u63D0\u4EA4");
1086
1320
  this.projection.thread(
@@ -1111,7 +1345,7 @@ class GatewayService {
1111
1345
  async forkThread(threadId, input) {
1112
1346
  return this.perform("thread.fork", threadId, input, async () => {
1113
1347
  this.ensureReady();
1114
- const source = this.projection.get(threadId) ?? await this.codex.readThread(threadId);
1348
+ const source = this.projection.get(threadId) ?? await (this.codex.readThreadPage?.(threadId) ?? this.codex.readThread(threadId));
1115
1349
  const link = this.store.getThreadLink(threadId);
1116
1350
  const ownership = link ? this.workspaces.assertOwnership(link.projectId, source.cwd, threadId) : this.workspaces.findOwner(source.cwd, source.id);
1117
1351
  this.ensureCompatibilityConfirmed();
@@ -1126,7 +1360,10 @@ class GatewayService {
1126
1360
  this.store.dispatch(input.clientOperationId);
1127
1361
  this.pendingThreadCreations.set(input.clientOperationId, forkCwd);
1128
1362
  const settingsSequence = this.runtimeSettingsSequence;
1129
- const forked = await this.codex.forkThread(threadId, forkCwd, input.settings);
1363
+ const forked = await this.codex.forkThread(threadId, forkCwd, input.settings, {
1364
+ recentOnly: true,
1365
+ deferOutput: true
1366
+ });
1130
1367
  if (forked.id === threadId || this.codex.epoch !== epoch || !this.codex.ready)
1131
1368
  throw new Error("\u5206\u53C9\u8BF7\u6C42\u5DF2\u53D1\u9001\uFF0C\u4F46\u8FD4\u56DE\u7684\u65B0\u4F1A\u8BDD\u65E0\u6CD5\u786E\u8BA4\uFF0C\u8BF7\u6838\u5BF9\u5386\u53F2");
1132
1369
  let normalized;
@@ -1165,13 +1402,73 @@ class GatewayService {
1165
1402
  if (!link) throw new AppError("THREAD_NOT_FOUND", "Session not found", 404);
1166
1403
  return this.workspaces.assertOwnership(link.projectId, link.cwd, threadId);
1167
1404
  }
1405
+ requireOwnedLoop(threadId, loopId) {
1406
+ const row = this.loops.get(loopId);
1407
+ if (!row || row.threadId !== threadId || row.workspaceKey !== this.loopWorkspace(threadId).workspaceKey)
1408
+ throw new AppError("LOOP_NOT_FOUND", "Loop not found", 404);
1409
+ return row;
1410
+ }
1168
1411
  async listSessionLoops(threadId) {
1169
1412
  if (!this.store.getThreadLink(threadId)) await this.loadThread(threadId);
1170
1413
  const workspace = this.loopWorkspace(threadId);
1171
1414
  return this.loops.list(threadId, workspace.workspaceKey);
1172
1415
  }
1416
+ async listLoopTasks() {
1417
+ const threadIds = this.loops.threadIds();
1418
+ const metadata = /* @__PURE__ */ new Map();
1419
+ const missing = /* @__PURE__ */ new Set();
1420
+ if (this.codex.ready) {
1421
+ for (let start = 0; start < threadIds.length; start += 4) {
1422
+ await Promise.all(
1423
+ threadIds.slice(start, start + 4).map(async (id) => {
1424
+ if (this.projection.get(id)) return;
1425
+ try {
1426
+ const workspace = this.loopWorkspace(id);
1427
+ if (!this.loops.list(id, workspace.workspaceKey).length) return;
1428
+ } catch {
1429
+ return;
1430
+ }
1431
+ try {
1432
+ metadata.set(id, await this.codex.readThreadMetadata(id));
1433
+ } catch (error) {
1434
+ if (this.asAppError(error).code === "THREAD_NOT_FOUND") missing.add(id);
1435
+ }
1436
+ })
1437
+ );
1438
+ }
1439
+ }
1440
+ const now = Date.now();
1441
+ return threadIds.flatMap((id) => {
1442
+ const thread = this.projection.get(id) ?? metadata.get(id);
1443
+ if (thread && thread.id !== id || !thread && missing.has(id)) return [];
1444
+ try {
1445
+ const workspace = this.loopWorkspace(id);
1446
+ const workspaceKey = workspace.workspaceKey;
1447
+ if (thread) {
1448
+ const actual = this.workspaces.assertOwnership(workspace.projectId, thread.cwd, id);
1449
+ if (actual.cwd !== workspace.cwd && actual.workspaceKey !== workspaceKey) return [];
1450
+ }
1451
+ const projectName = workspace.projectId === null ? null : this.projects.describe(workspace.projectId).name;
1452
+ const busy = thread !== void 0 && isActive(thread.status) || Boolean(this.store.activeForThread(id)) || this.capacityRetries.pending(id);
1453
+ return this.loops.list(id, workspaceKey).filter((loop) => loop.reason !== "deleted").map((loop) => ({
1454
+ ...loop,
1455
+ projectId: workspace.projectId,
1456
+ projectName,
1457
+ threadTitle: thread?.title || id,
1458
+ archived: thread?.archived ?? loop.reason === "archived",
1459
+ waiting: loop.status === "active" && loop.nextRunAt <= now && busy
1460
+ }));
1461
+ } catch (error) {
1462
+ if (!(error instanceof AppError) && !(error instanceof Error && "code" in error))
1463
+ throw error;
1464
+ return [];
1465
+ }
1466
+ });
1467
+ }
1173
1468
  async createSessionLoop(threadId, input) {
1174
1469
  input = createSessionLoopSchema.parse(input);
1470
+ if (this.loops.get(input.clientOperationId))
1471
+ this.requireOwnedLoop(threadId, input.clientOperationId);
1175
1472
  return this.perform("loop.create", threadId, input, async () => {
1176
1473
  const thread = await this.loadThread(threadId);
1177
1474
  this.ensureManaged(thread);
@@ -1209,12 +1506,10 @@ class GatewayService {
1209
1506
  });
1210
1507
  }
1211
1508
  async controlSessionLoop(threadId, loopId, input) {
1509
+ const owned = this.requireOwnedLoop(threadId, loopId);
1212
1510
  return this.perform("loop.control", threadId, { ...input, loopId }, async () => {
1213
1511
  const thread = input.action === "resume" ? await this.loadThread(threadId) : void 0;
1214
- const { workspaceKey } = this.loopWorkspace(threadId);
1215
- const row = this.loops.get(loopId);
1216
- if (!row || row.threadId !== threadId || row.workspaceKey !== workspaceKey)
1217
- throw new AppError("LOOP_NOT_FOUND", "Loop not found", 404);
1512
+ const row = thread ? this.requireOwnedLoop(threadId, loopId) : owned;
1218
1513
  const now = Date.now();
1219
1514
  const canChange = row.version === input.version && (input.action === "cancel" ? row.status === "active" || row.status === "paused" : input.action === "pause" ? row.status === "active" : row.status === "paused" && thread?.archived !== true && row.lastResult !== "unknown");
1220
1515
  if (!canChange)
@@ -1824,7 +2119,7 @@ class GatewayService {
1824
2119
  await this.loadThread(threadId);
1825
2120
  const history = this.normalize(await this.codex.readThread(threadId));
1826
2121
  this.workspaces.assertOwnership(history.projectId, history.cwd, history.id);
1827
- this.projection.thread(history, true);
2122
+ this.mergeQuestionHistory(history);
1828
2123
  const states = this.questionTracking.states(threadId);
1829
2124
  for (const id of new Set(input.questionIds)) {
1830
2125
  const question = this.findAsyncQuestion(history, id);
@@ -1842,16 +2137,44 @@ class GatewayService {
1842
2137
  return { result: { threadId, questionIds: ids } };
1843
2138
  });
1844
2139
  }
2140
+ mergeQuestionHistory(history) {
2141
+ const index = this.questionHistory(history.id);
2142
+ if (index && !history.historyTruncated) index.observed = history.turns.map(questionEvidence);
2143
+ const current = this.projection.get(history.id);
2144
+ if (!current || history.historyMode !== "paginated" && !current.history) {
2145
+ this.projection.thread(history, true);
2146
+ return;
2147
+ }
2148
+ const visibleTurns = new Set(current.turns.map((turn) => turn.id));
2149
+ this.projection.thread(
2150
+ {
2151
+ ...history,
2152
+ history: current.history,
2153
+ turns: history.turns.filter((turn) => visibleTurns.has(turn.id))
2154
+ },
2155
+ true
2156
+ );
2157
+ if (index) this.publishThread(history.id);
2158
+ }
1845
2159
  questionItems(history) {
1846
2160
  return [...history.turns, ...this.projection.get(history.id)?.turns ?? []].flatMap(
1847
2161
  (turn) => turn.items
1848
2162
  );
1849
2163
  }
1850
2164
  findAsyncQuestion(history, id) {
1851
- for (const item of this.questionItems(history)) {
1852
- if (item.type !== "agentMessage") continue;
1853
- const index = item.questions?.findIndex((_, index2) => asyncQuestionId(item.id, index2) === id);
1854
- if (index !== void 0 && index >= 0) return { item, question: item.questions[index] };
2165
+ const turns = new Map(
2166
+ (this.projection.get(history.id)?.turns ?? []).map((turn) => [turn.id, turn])
2167
+ );
2168
+ for (const native of history.turns) turns.set(native.id, native);
2169
+ for (const turn of turns.values()) {
2170
+ if (!canTrackQuestions(turn.status)) continue;
2171
+ for (const item of turn.items) {
2172
+ if (item.type !== "agentMessage") continue;
2173
+ const index = item.questions?.findIndex(
2174
+ (_, index2) => asyncQuestionId(item.id, index2) === id
2175
+ );
2176
+ if (index !== void 0 && index >= 0) return { item, question: item.questions[index] };
2177
+ }
1855
2178
  }
1856
2179
  }
1857
2180
  questionAnswered(history, id) {
@@ -1869,7 +2192,7 @@ class GatewayService {
1869
2192
  if (!replies) return;
1870
2193
  const history = this.normalize(await this.codex.readThread(threadId));
1871
2194
  this.workspaces.assertOwnership(history.projectId, history.cwd, history.id);
1872
- this.projection.thread(history, true);
2195
+ this.mergeQuestionHistory(history);
1873
2196
  const states = this.questionTracking.states(threadId);
1874
2197
  const ids = [];
1875
2198
  for (const reply of replies) {
@@ -1892,6 +2215,11 @@ class GatewayService {
1892
2215
  getOperation(id) {
1893
2216
  const row = this.store.get(id);
1894
2217
  if (!row) throw new AppError("OPERATION_NOT_FOUND", "\u672A\u627E\u5230\u8BE5\u64CD\u4F5C", 404);
2218
+ if (row.kind === "loop.create" || row.kind === "loop.control") {
2219
+ const result = row.result;
2220
+ if (result?.id) this.requireOwnedLoop(row.target, result.id);
2221
+ else this.loopWorkspace(row.target);
2222
+ }
1895
2223
  return this.operation(row);
1896
2224
  }
1897
2225
  async reconcileOperation(targetOperationId, input) {
@@ -1954,7 +2282,7 @@ class GatewayService {
1954
2282
  } else await this.getThread(threadId);
1955
2283
  return this.events.subscribe(
1956
2284
  threadId,
1957
- () => this.threadView(this.projection.get(threadId)),
2285
+ () => this.detailThreadView(this.projection.get(threadId)),
1958
2286
  after,
1959
2287
  listener,
1960
2288
  incremental,
@@ -1966,6 +2294,7 @@ class GatewayService {
1966
2294
  this.stopLoopScheduler();
1967
2295
  await Promise.allSettled([...this.instructionWrites, ...this.defaultWrites]);
1968
2296
  this.capacityRetries.clearAll();
2297
+ this.questionHistories.clear();
1969
2298
  await this.projectClones.close();
1970
2299
  this.store.recover();
1971
2300
  this.projection.runtimeReset();
@@ -2108,10 +2437,13 @@ class GatewayService {
2108
2437
  const revision = this.projection.revision(marker.threadId);
2109
2438
  const reading = (async () => {
2110
2439
  try {
2111
- const actual = await this.codex.readThread(marker.threadId);
2112
- const latest = this.store.activeForThread(marker.threadId);
2113
- if (!this.codex.ready || this.codex.epoch !== epoch || actual.id !== marker.threadId || latest?.operationId !== marker.operationId || latest.turnId !== marker.turnId || latest.codexEpoch !== marker.codexEpoch || this.projection.revision(marker.threadId) !== revision)
2114
- return;
2440
+ const current = () => {
2441
+ const latest2 = this.store.activeForThread(marker.threadId);
2442
+ return this.codex.ready && this.codex.epoch === epoch && latest2?.operationId === marker.operationId && latest2.turnId === marker.turnId && latest2.codexEpoch === marker.codexEpoch && this.projection.revision(marker.threadId) === revision ? latest2 : void 0;
2443
+ };
2444
+ const actual = await (marker.turnId && this.codex.readExecutionHistory?.(marker.threadId, marker.turnId) || this.codex.readThread(marker.threadId));
2445
+ const latest = current();
2446
+ if (!latest || actual.id !== marker.threadId) return;
2115
2447
  const link = this.store.getThreadLink(marker.threadId);
2116
2448
  const ownership = link ? this.workspaces.assertOwnership(link.projectId, actual.cwd, actual.id) : this.workspaces.findOwner(actual.cwd, actual.id);
2117
2449
  if (ownership.workspaceKey !== marker.workspaceKey) return;
@@ -2121,13 +2453,21 @@ class GatewayService {
2121
2453
  )
2122
2454
  );
2123
2455
  const turn = candidates.length === 1 ? candidates[0] : void 0;
2124
- if (turn && isActive(turn.status) && latest.state === "active" && this.projection.get(marker.threadId)?.status === "unknown") {
2125
- this.projection.thread(this.normalize(actual));
2456
+ if (!turn) return;
2457
+ const restoreActive = isActive(turn.status) && latest.state === "active" && this.projection.get(marker.threadId)?.status === "unknown";
2458
+ const ended = isTerminal(turn.status) && !isActive(actual.status) && !actual.turns.some((entry) => isActive(entry.status));
2459
+ if (!restoreActive && !ended) return;
2460
+ const page = actual.historyMode === "paginated" && this.codex.readThreadPage ? await this.codex.readThreadPage(marker.threadId, void 0, { deferOutput: true }) : actual;
2461
+ if (!current() || page.id !== marker.threadId) return;
2462
+ if (this.workspaces.assertOwnership(ownership.projectId, page.cwd, page.id).workspaceKey !== marker.workspaceKey)
2463
+ return;
2464
+ if (ended && (isActive(page.status) || page.turns.some((entry) => isActive(entry.status))))
2465
+ return;
2466
+ if (restoreActive) {
2467
+ this.projection.thread(this.normalize(page));
2126
2468
  this.publishThread(marker.threadId);
2127
2469
  return;
2128
2470
  }
2129
- if (!turn || !isTerminal(turn.status) || isActive(actual.status) || actual.turns.some((entry) => isActive(entry.status)))
2130
- return;
2131
2471
  if (!marker.turnId) this.store.attachTurn(marker.operationId, turn.id);
2132
2472
  this.store.finishTurn(marker.threadId, turn.id, marker.codexEpoch);
2133
2473
  this.logger.info("execution.recovered", {
@@ -2137,11 +2477,18 @@ class GatewayService {
2137
2477
  codexEpoch: marker.codexEpoch,
2138
2478
  reason: marker.turnId ? "terminal_history" : "native_message_identity"
2139
2479
  });
2140
- this.projection.thread(this.normalize(actual));
2480
+ this.projection.thread(this.normalize(page));
2481
+ if (!page.turns.some((entry) => entry.id === turn.id) && this.projection.get(marker.threadId)?.turns.some((entry) => entry.id === turn.id))
2482
+ this.projection.turn(marker.threadId, turn);
2141
2483
  this.projection.expireTurn(marker.threadId, turn.id);
2142
2484
  this.publishThread(marker.threadId);
2143
2485
  this.events.publish("operation", this.getOperation(marker.operationId), marker.threadId);
2144
- } catch {
2486
+ } catch (error) {
2487
+ this.logger.debug("execution.recovery_read_failed", {
2488
+ threadId: marker.threadId,
2489
+ operationId: marker.operationId,
2490
+ ...errorFields(error)
2491
+ });
2145
2492
  }
2146
2493
  })();
2147
2494
  this.executionReads.set(marker.operationId, reading);
@@ -2260,18 +2607,27 @@ class GatewayService {
2260
2607
  publishThread(threadId, streamed) {
2261
2608
  const thread = this.projection.get(threadId);
2262
2609
  if (!thread) return;
2263
- const view = this.threadView(thread, false);
2610
+ const view = this.detailThreadView(thread, false, !streamed || !thread.pendingQuestions);
2611
+ if (view.pendingQuestions) thread.pendingQuestions = view.pendingQuestions;
2264
2612
  this.events.publishThread(view, streamed);
2265
- const summary = toThreadSummary(view);
2266
- const encoded = JSON.stringify(summary);
2267
- if (this.summaries.get(threadId) === encoded) return;
2268
2613
  try {
2269
2614
  this.workspaces.assertOwnership(thread.projectId, thread.cwd, thread.id);
2270
2615
  } catch {
2271
2616
  return;
2272
2617
  }
2273
- this.summaries.set(threadId, encoded);
2274
- this.events.publishSummary(summary);
2618
+ this.publishThreadSummary(this.threadSummary({ ...view, turns: thread.turns }));
2619
+ }
2620
+ threadSummary(view) {
2621
+ const summary = toThreadSummary(view);
2622
+ const turnId = completedTurnId(summary);
2623
+ if (turnId) summary.lastTurnRead = this.turnCompletionReads.has(view.id, turnId);
2624
+ return summary;
2625
+ }
2626
+ publishThreadSummary(summary, advanceCursor = false) {
2627
+ const encoded = JSON.stringify(summary);
2628
+ if (this.summaries.get(summary.id) === encoded) return;
2629
+ this.summaries.set(summary.id, encoded);
2630
+ this.events.publishSummary(summary, advanceCursor);
2275
2631
  }
2276
2632
  historyVisible(thread) {
2277
2633
  return Boolean(
@@ -2286,7 +2642,33 @@ class GatewayService {
2286
2642
  }
2287
2643
  return links;
2288
2644
  }
2289
- threadView(thread, copy = true) {
2645
+ detailThreadView(thread, copy = true, includeQuestions = true) {
2646
+ if (thread.historyMode !== "paginated") return this.threadView(thread, copy, includeQuestions);
2647
+ const bounded = thread.turns.length > HISTORY_PAGE_SIZE;
2648
+ const history = bounded ? {
2649
+ olderCursor: historyCursor(thread.id, this.codex.epoch, {
2650
+ beforeTurnId: thread.turns[thread.turns.length - HISTORY_PAGE_SIZE].id
2651
+ })
2652
+ } : thread.history;
2653
+ let turns = bounded ? thread.turns.slice(-HISTORY_PAGE_SIZE) : thread.turns;
2654
+ if (this.codex.canReadDeferredOutput?.()) {
2655
+ turns = turns.map(
2656
+ (turn) => isTerminal(turn.status) ? {
2657
+ ...turn,
2658
+ items: turn.items.map(deferLiveToolOutput)
2659
+ } : turn
2660
+ );
2661
+ }
2662
+ const result = this.threadView({ ...thread, turns, history }, copy, false);
2663
+ if (includeQuestions)
2664
+ result.pendingQuestions = this.questionState({
2665
+ ...result,
2666
+ turns: thread.turns,
2667
+ history: thread.history
2668
+ });
2669
+ return result;
2670
+ }
2671
+ threadView(thread, copy = true, includeQuestions = true) {
2290
2672
  const submissions = new Map(
2291
2673
  this.store.pendingMessages(thread.id).map((message) => [message.id, message])
2292
2674
  );
@@ -2320,6 +2702,7 @@ class GatewayService {
2320
2702
  actions.set(action.actionId, action);
2321
2703
  result.actions = [...actions.values()];
2322
2704
  result.archived = thread.archived ?? false;
2705
+ if (includeQuestions) result.pendingQuestions = this.questionState(result);
2323
2706
  result.historyVisible = this.historyVisible(thread);
2324
2707
  const marker = this.store.activeForThread(thread.id);
2325
2708
  delete result.execution;
@@ -2391,6 +2774,7 @@ class GatewayService {
2391
2774
  this.runtimeSettingsUpdates.clear();
2392
2775
  this.turnBaselines.clear();
2393
2776
  this.resumes.clear();
2777
+ this.questionHistories.clear();
2394
2778
  this.store.recover();
2395
2779
  this.projection.runtimeReset();
2396
2780
  for (const thread2 of this.projection.values()) this.publishThread(thread2.id);
@@ -2419,7 +2803,7 @@ class GatewayService {
2419
2803
  const known = this.projection.actions.has(action.actionId);
2420
2804
  const owner = action.threadId ? this.projection.get(action.threadId) : void 0;
2421
2805
  const previous = new Set(
2422
- owner ? pendingAttention(this.threadView(owner)).map(attentionKey) : []
2806
+ owner ? pendingAttention(this.threadView(owner, false, false)).map(attentionKey) : []
2423
2807
  );
2424
2808
  this.projection.action(action);
2425
2809
  if (action.kind === "questions") this.questionTracking.saveAction(action);
@@ -2449,7 +2833,7 @@ class GatewayService {
2449
2833
  return;
2450
2834
  }
2451
2835
  const previousAttention = new Set(
2452
- event.type === "item" || event.type === "turn" ? pendingAttention(this.threadView(thread)).map(attentionKey) : []
2836
+ event.type === "item" || event.type === "turn" ? pendingAttention(this.threadView(thread, false, false)).map(attentionKey) : []
2453
2837
  );
2454
2838
  if (event.type === "tokenUsage") {
2455
2839
  if (this.projection.tokenUsage(thread.id, event.usage)) this.publishThread(thread.id);