@covro/covro 0.13.1-dev.1 → 0.13.1-dev.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 (133) 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 +126 -41
  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 +2 -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/0013_adaptive_session_loops.sql +29 -0
  13. package/dist/drizzle/meta/0012_snapshot.json +935 -0
  14. package/dist/drizzle/meta/0013_snapshot.json +957 -0
  15. package/dist/drizzle/meta/_journal.json +14 -0
  16. package/dist/server/adaptive-loop.js +65 -0
  17. package/dist/server/adaptive-loop.js.map +7 -0
  18. package/dist/server/db/schema.js +14 -2
  19. package/dist/server/db/schema.js.map +2 -2
  20. package/dist/server/db/session-loops.js +39 -4
  21. package/dist/server/db/session-loops.js.map +3 -3
  22. package/dist/server/db/turn-completion-reads.js +20 -0
  23. package/dist/server/db/turn-completion-reads.js.map +7 -0
  24. package/dist/server/events.js +2 -1
  25. package/dist/server/events.js.map +2 -2
  26. package/dist/server/http.js +40 -0
  27. package/dist/server/http.js.map +2 -2
  28. package/dist/server/pending-questions.js +112 -0
  29. package/dist/server/pending-questions.js.map +7 -0
  30. package/dist/server/projection.js +27 -0
  31. package/dist/server/projection.js.map +2 -2
  32. package/dist/server/service.js +492 -68
  33. package/dist/server/service.js.map +3 -3
  34. package/dist/shared/pending-questions.js +23 -0
  35. package/dist/shared/pending-questions.js.map +7 -0
  36. package/dist/shared/session-loop.js +17 -2
  37. package/dist/shared/session-loop.js.map +2 -2
  38. package/dist/shared/thread-summary.js +6 -3
  39. package/dist/shared/thread-summary.js.map +2 -2
  40. package/dist/shared/updates.js +5 -1
  41. package/dist/shared/updates.js.map +2 -2
  42. package/dist/shared/validation.js +11 -2
  43. package/dist/shared/validation.js.map +2 -2
  44. package/dist/updates/manager.js +96 -56
  45. package/dist/updates/manager.js.map +3 -3
  46. package/dist/web/assets/{abnfDiagram-WEYOIA3C-YbRP_P6X.js → abnfDiagram-WEYOIA3C-Cm3_7441.js} +1 -1
  47. package/dist/web/assets/{arc-Bu_TnvX1.js → arc-ClH0TpME.js} +1 -1
  48. package/dist/web/assets/{architecture-WOLXFQ4H-B5QcWPNh.js → architecture-WOLXFQ4H-B3NyA-jK.js} +1 -1
  49. package/dist/web/assets/{architectureDiagram-ZHVYKT53-DlEiMnDk.js → architectureDiagram-ZHVYKT53-BWIPL818.js} +1 -1
  50. package/dist/web/assets/{blockDiagram-RJAE7QA3-BaTXvDwo.js → blockDiagram-RJAE7QA3-sqqkoRzX.js} +1 -1
  51. package/dist/web/assets/{c4Diagram-XDPPPE54-CepOIeg3.js → c4Diagram-XDPPPE54-Dc6kjjZZ.js} +1 -1
  52. package/dist/web/assets/channel-0Xi8DOc2.js +1 -0
  53. package/dist/web/assets/{chunk-2E7WHVMD-MBCK-6QH.js → chunk-2E7WHVMD-DuLhaggn.js} +1 -1
  54. package/dist/web/assets/{chunk-4EMNKR2T-Bzhd6O0D.js → chunk-4EMNKR2T-D67vr6sg.js} +1 -1
  55. package/dist/web/assets/{chunk-55XCU76K-zk-NTr-Q.js → chunk-55XCU76K-I3QGXiTl.js} +1 -1
  56. package/dist/web/assets/{chunk-7S6XSTFO-D97Zn3VI.js → chunk-7S6XSTFO-B_upSo8l.js} +1 -1
  57. package/dist/web/assets/{chunk-AQDTSKZB-DQew0wpu.js → chunk-AQDTSKZB-DIWtJsbi.js} +1 -1
  58. package/dist/web/assets/{chunk-DSNLSHJZ-BerE9brS.js → chunk-DSNLSHJZ-B_vpHJc8.js} +1 -1
  59. package/dist/web/assets/{chunk-HAGFOTED-BrKzyaKz.js → chunk-HAGFOTED-lIjPIRtr.js} +1 -1
  60. package/dist/web/assets/{chunk-HNE4Q36P-EzqXAxSN.js → chunk-HNE4Q36P-BpTeyf_J.js} +1 -1
  61. package/dist/web/assets/{chunk-NQOKRVIF-naYBKXhx.js → chunk-NQOKRVIF-DYJ8kaAg.js} +1 -1
  62. package/dist/web/assets/{chunk-UHW7PFBP-C8SwfPmB.js → chunk-UHW7PFBP-BfY_irnY.js} +1 -1
  63. package/dist/web/assets/{chunk-VQ5W62QI-Dk8GB8kO.js → chunk-VQ5W62QI-BkNzvuI8.js} +1 -1
  64. package/dist/web/assets/{chunk-WQQL4CDK-DtLKUwlv.js → chunk-WQQL4CDK-BtqJXmOo.js} +1 -1
  65. package/dist/web/assets/{chunk-XXDRQBXY-CdoZcH03.js → chunk-XXDRQBXY-BY-O69Bi.js} +1 -1
  66. package/dist/web/assets/{chunk-YZO67HFG-CotRRiG-.js → chunk-YZO67HFG-D1I_j7tC.js} +1 -1
  67. package/dist/web/assets/{chunk-ZAUX2LTX-vAw5fLpg.js → chunk-ZAUX2LTX-DL2b4R2Y.js} +1 -1
  68. package/dist/web/assets/{chunk-ZCHMQSOR-Dw57DalW.js → chunk-ZCHMQSOR-CDzn6CVC.js} +1 -1
  69. package/dist/web/assets/{classDiagram-v2-4MYWR3UA-COROoHI2.js → classDiagram-v2-4MYWR3UA-4VUeEzXQ.js} +1 -1
  70. package/dist/web/assets/{cose-bilkent-JH36ORCC-Caa9HNwa.js → cose-bilkent-JH36ORCC-6lfGbuuy.js} +1 -1
  71. package/dist/web/assets/{cynefin-EF2NZ3EQ-DwYv7yvY.js → cynefin-EF2NZ3EQ-Cn9qeoAw.js} +1 -1
  72. package/dist/web/assets/{cynefinDiagram-WF24UDRP-DosX9Lx0.js → cynefinDiagram-WF24UDRP-DXyQPYol.js} +1 -1
  73. package/dist/web/assets/{dagre-NK4GIZVX-CL6X0gMM.js → dagre-NK4GIZVX-BTSudZOE.js} +1 -1
  74. package/dist/web/assets/{diagram-CBK3MWTC-BaabgAfv.js → diagram-CBK3MWTC-C8H8WQh_.js} +1 -1
  75. package/dist/web/assets/{diagram-I5XIIV2D-D2MvXxl-.js → diagram-I5XIIV2D-BPl_blTl.js} +1 -1
  76. package/dist/web/assets/{diagram-ODIL2UCW-CbRBexbT.js → diagram-ODIL2UCW-DJ2SEsae.js} +1 -1
  77. package/dist/web/assets/{diagram-PFBEJUXE-BSIba12r.js → diagram-PFBEJUXE-B4u0U2GK.js} +1 -1
  78. package/dist/web/assets/{diagram-RJA3I4VV-DnWBuBja.js → diagram-RJA3I4VV-BhKwCfAs.js} +1 -1
  79. package/dist/web/assets/{diagram-TYUNFSNR-1BPksd6B.js → diagram-TYUNFSNR-CgrHoyrh.js} +1 -1
  80. package/dist/web/assets/{dist-Dy9RL-sq.js → dist-CjpsoZ40.js} +1 -1
  81. package/dist/web/assets/{ebnfDiagram-V4P3TTPT-CubMSBoK.js → ebnfDiagram-V4P3TTPT-CB4zWk85.js} +1 -1
  82. package/dist/web/assets/{elk-QONTBCTQ-CHep-cFs.js → elk-QONTBCTQ-L5PHm2DH.js} +1 -1
  83. package/dist/web/assets/{erDiagram-KYQIGQAA-DjI6FD10.js → erDiagram-KYQIGQAA-CEwIhbVE.js} +1 -1
  84. package/dist/web/assets/{eventmodeling-K75KTNOO-CRO-i8KP.js → eventmodeling-K75KTNOO-Bjzmrres.js} +1 -1
  85. package/dist/web/assets/flowDiagram-IUGLLWBU-CXaSnnrc.js +1 -0
  86. package/dist/web/assets/{ganttDiagram-R7GPNTJY-BAga12Hu.js → ganttDiagram-R7GPNTJY-ChPbWI-3.js} +1 -1
  87. package/dist/web/assets/{gitGraph-VSP46ZUC-C1qVLDKw.js → gitGraph-VSP46ZUC-DW2xQaiJ.js} +1 -1
  88. package/dist/web/assets/{gitGraphDiagram-PDYL7XHY-CTW0lgs5.js → gitGraphDiagram-PDYL7XHY-DSo2eCKp.js} +1 -1
  89. package/dist/web/assets/index-B_Yx9O_i.css +1 -0
  90. package/dist/web/assets/index-DXnAm2xU.js +167 -0
  91. package/dist/web/assets/{info-OHQRW6UA-COurwpim.js → info-OHQRW6UA-Ck0yjuqE.js} +1 -1
  92. package/dist/web/assets/{infoDiagram-MVDRKAX5-CvHni8IO.js → infoDiagram-MVDRKAX5-DY6BUG6l.js} +1 -1
  93. package/dist/web/assets/{ishikawaDiagram-HPEHV2GE-Dmed93t1.js → ishikawaDiagram-HPEHV2GE-DVcE7lYM.js} +1 -1
  94. package/dist/web/assets/{journeyDiagram-BOSHW7O7-C12zGbfa.js → journeyDiagram-BOSHW7O7-JZST9Ufa.js} +1 -1
  95. package/dist/web/assets/{kanban-definition-FNSA4HC5-D9VScv-E.js → kanban-definition-FNSA4HC5-Ds_oLHX2.js} +1 -1
  96. package/dist/web/assets/{line-BZQ7WzsH.js → line-5Gfv73DZ.js} +1 -1
  97. package/dist/web/assets/{linear-DKoR6jdr.js → linear-DZfck41d.js} +1 -1
  98. package/dist/web/assets/{mermaid-parser.core-DPUDnYsm.js → mermaid-parser.core-CAD9eh4N.js} +3 -3
  99. package/dist/web/assets/{mermaid.core-BT5MJ4aB.js → mermaid.core-DgWrXR5j.js} +4 -4
  100. package/dist/web/assets/{mindmap-definition-6OY57UG3-CYTBc0ha.js → mindmap-definition-6OY57UG3-GgW3Dtk6.js} +1 -1
  101. package/dist/web/assets/{packet-JDAUHWVQ-D9zctSES.js → packet-JDAUHWVQ-Ipb7W_lT.js} +1 -1
  102. package/dist/web/assets/{pegDiagram-ECIUJNBX-WA4MsFVp.js → pegDiagram-ECIUJNBX-CX7GYhJm.js} +1 -1
  103. package/dist/web/assets/{pie-XZMESJXO-B0IqJmMC.js → pie-XZMESJXO-Ci-6RhBA.js} +1 -1
  104. package/dist/web/assets/{pieDiagram-GNMPY74T-XC73X9Qu.js → pieDiagram-GNMPY74T-m57FY_bP.js} +1 -1
  105. package/dist/web/assets/{quadrantDiagram-D57K4MC3-X51JeKah.js → quadrantDiagram-D57K4MC3-C2ZQck1p.js} +1 -1
  106. package/dist/web/assets/{radar-ABXABTNO-DfPmLJjD.js → radar-ABXABTNO-C4l84uE8.js} +1 -1
  107. package/dist/web/assets/{railroad-I3PHUGI6-CEGQ2XNy.js → railroad-I3PHUGI6-Ckwfx4cX.js} +1 -1
  108. package/dist/web/assets/{railroad-abnf-LNEFI6M7-BxiHTczQ.js → railroad-abnf-LNEFI6M7-D_DNx5kS.js} +1 -1
  109. package/dist/web/assets/{railroad-ebnf-DWYD2UWJ-Dj7X5UAi.js → railroad-ebnf-DWYD2UWJ-B1ORNy6J.js} +1 -1
  110. package/dist/web/assets/{railroad-peg-JR7BVNR7-CHuDm4LG.js → railroad-peg-JR7BVNR7-DGOhMJJh.js} +1 -1
  111. package/dist/web/assets/{railroadDiagram-Y72NRBL7-BWVk20jh.js → railroadDiagram-Y72NRBL7-L4M8uZpo.js} +1 -1
  112. package/dist/web/assets/{requirementDiagram-EQYSW5RA-AQmFFlr4.js → requirementDiagram-EQYSW5RA-8F80H05x.js} +1 -1
  113. package/dist/web/assets/{sankeyDiagram-SY24JHO5-PYzMOXlm.js → sankeyDiagram-SY24JHO5-Dpa_pRZ5.js} +1 -1
  114. package/dist/web/assets/{sequenceDiagram-BLEHNHQU-CcADT5Sq.js → sequenceDiagram-BLEHNHQU-DbVDK7kH.js} +1 -1
  115. package/dist/web/assets/{src-DLG4hAZs.js → src-BlRy1tgJ.js} +1 -1
  116. package/dist/web/assets/{stateDiagram-v2-A6IESKWZ-B9_3w0Uv.js → stateDiagram-v2-A6IESKWZ-B7a0NTBq.js} +1 -1
  117. package/dist/web/assets/{swimlanes-B3ENRKFQ-DI2a1SsD.js → swimlanes-B3ENRKFQ-DJ5Sqgur.js} +1 -1
  118. package/dist/web/assets/swimlanesDiagram-AYQRV4AK-DXfJkwXT.js +8 -0
  119. package/dist/web/assets/{timeline-definition-JXYKGLGB-CvOwLjkl.js → timeline-definition-JXYKGLGB-BArwn9JD.js} +1 -1
  120. package/dist/web/assets/{treeView-D4JQ5SDB-CL3KpHPd.js → treeView-D4JQ5SDB-Ch-gELLa.js} +1 -1
  121. package/dist/web/assets/{treemap-SAJKECNS-Bd1Bg6B4.js → treemap-SAJKECNS-LdgX1gF7.js} +1 -1
  122. package/dist/web/assets/{usecaseDiagram-WPOLBNNX-a_y59pdQ.js → usecaseDiagram-WPOLBNNX-p-ifo0Fs.js} +1 -1
  123. package/dist/web/assets/{vennDiagram-Q3Y3IDCW-CqhNRSnR.js → vennDiagram-Q3Y3IDCW-8n2LdHdC.js} +1 -1
  124. package/dist/web/assets/{wardley-7MLQ67FV-B21UbXfY.js → wardley-7MLQ67FV-CUzBp3AH.js} +1 -1
  125. package/dist/web/assets/{wardleyDiagram-IVAIDKWA-BHLCG4J2.js → wardleyDiagram-IVAIDKWA-BRGuWBAn.js} +1 -1
  126. package/dist/web/assets/{xychartDiagram-4URNHDU4-CT6o_Lw5.js → xychartDiagram-4URNHDU4-CeINTq-L.js} +1 -1
  127. package/dist/web/index.html +2 -2
  128. package/package.json +4 -4
  129. package/dist/web/assets/channel-DZM3KEg4.js +0 -1
  130. package/dist/web/assets/flowDiagram-IUGLLWBU-C9ssIbIh.js +0 -1
  131. package/dist/web/assets/index-D4z03hlo.css +0 -1
  132. package/dist/web/assets/index-DMTboMSf.js +0 -166
  133. package/dist/web/assets/swimlanesDiagram-AYQRV4AK-D-7cnri3.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";
@@ -50,7 +57,24 @@ import { readLocalText } from "./text-files.js";
50
57
  import { readLocalJson } from "./json-files.js";
51
58
  import { sessionCreationResult } from "./session-creation.js";
52
59
  import { createSessionLoopSchema, createSessionSchema } from "../shared/validation.js";
60
+ import {
61
+ adaptiveLoopAnswer,
62
+ adaptiveLoopOutputSchema,
63
+ adaptiveLoopPrompt,
64
+ readAdaptiveLoopDecision
65
+ } from "./adaptive-loop.js";
53
66
  import { SessionLoopStore, sessionLoopView } from "./db/session-loops.js";
67
+ function deferLiveToolOutput(item) {
68
+ if (item.status !== "completed" || item.outputDeferred || item.error) return item;
69
+ if (item.type === "commandExecution" && item.output)
70
+ return { ...item, output: "", outputDeferred: true };
71
+ if (item.type !== "mcpToolCall" || !item.details || typeof item.details !== "object") return item;
72
+ const details = item.details;
73
+ const result = details.result;
74
+ 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))
75
+ return item;
76
+ return { ...item, outputDeferred: true, details: { ...details, result: null } };
77
+ }
54
78
  class GatewayService {
55
79
  constructor(options) {
56
80
  this.options = options;
@@ -58,6 +82,7 @@ class GatewayService {
58
82
  this.logger = (options.logger ?? nullLogger).child({ component: "operations" });
59
83
  this.store = options.store;
60
84
  this.turnUsage = new TurnUsageStore(this.store.database);
85
+ this.turnCompletionReads = new TurnCompletionReads(this.store.database);
61
86
  this.questionTracking = new QuestionTrackingStore(
62
87
  this.store.database,
63
88
  this.logger.child({ component: "question_tracking" })
@@ -109,7 +134,9 @@ class GatewayService {
109
134
  projection;
110
135
  store;
111
136
  turnUsage;
137
+ turnCompletionReads;
112
138
  questionTracking;
139
+ questionHistories = /* @__PURE__ */ new Map();
113
140
  projects;
114
141
  workspaces;
115
142
  codex;
@@ -679,7 +706,24 @@ class GatewayService {
679
706
  async listThreadSummaries(projectId, cursor, archived = false) {
680
707
  const boundary = this.events.cursor();
681
708
  const page = await this.listThreads(projectId, cursor, archived);
682
- return { data: page.data.map(toThreadSummary), nextCursor: page.nextCursor, cursor: boundary };
709
+ return {
710
+ data: page.data.map((thread) => this.threadSummary(thread)),
711
+ nextCursor: page.nextCursor,
712
+ cursor: boundary
713
+ };
714
+ }
715
+ async readTurnCompletion(threadId, turnId) {
716
+ await this.loadThread(threadId);
717
+ const thread = this.projection.get(threadId);
718
+ this.workspaces.assertOwnership(thread.projectId, thread.cwd, threadId);
719
+ const summary = this.threadSummary(this.threadView(thread, false));
720
+ if (completedTurnId(summary) === turnId) {
721
+ if (this.turnCompletionReads.record(threadId, turnId))
722
+ this.logger.info("completion.read", { threadId, turnId });
723
+ summary.lastTurnRead = true;
724
+ this.publishThreadSummary(summary, true);
725
+ }
726
+ return { threadId, summary, cursor: this.events.cursor() };
683
727
  }
684
728
  async setThreadArchived(threadId, input) {
685
729
  return this.perform("thread.archive", threadId, input, async () => {
@@ -724,7 +768,7 @@ class GatewayService {
724
768
  result: {
725
769
  threadId,
726
770
  archived: input.archived,
727
- summary: toThreadSummary(this.threadView(this.projection.get(threadId))),
771
+ summary: this.threadSummary(this.threadView(this.projection.get(threadId))),
728
772
  cursor: this.events.cursor()
729
773
  }
730
774
  };
@@ -767,7 +811,7 @@ class GatewayService {
767
811
  result: {
768
812
  threadId,
769
813
  name,
770
- summary: toThreadSummary(this.threadView(this.projection.get(threadId))),
814
+ summary: this.threadSummary(this.threadView(this.projection.get(threadId))),
771
815
  cursor: this.events.cursor()
772
816
  }
773
817
  };
@@ -827,37 +871,210 @@ class GatewayService {
827
871
  if (this.codex.ready) await this.refreshThreadMetadata(threadId);
828
872
  this.workspaces.assertOwnership(cached.projectId, cached.cwd, cached.id);
829
873
  await this.refreshGoal(cached);
830
- return { ...this.threadView(cached), turns: [], actions: [] };
874
+ return {
875
+ ...this.threadView(cached, false, false),
876
+ pendingQuestions: void 0,
877
+ turns: [],
878
+ actions: []
879
+ };
831
880
  }
832
881
  const metadata = this.threadView(this.normalize(await this.codex.readThreadMetadata(threadId)));
833
882
  await this.refreshGoal(metadata);
834
883
  metadata.historyVisible = this.historyVisible(metadata);
835
884
  return { ...metadata, turns: [], actions: [] };
836
885
  }
837
- async refreshThreadDetail(threadId) {
886
+ async getThread(threadId) {
887
+ return this.detailThreadView(await this.openThread(threadId, true));
888
+ }
889
+ async openThread(threadId, waitForExecution) {
838
890
  const cached = this.projection.get(threadId);
839
- await this.loadThread(threadId);
891
+ await this.loadThread(threadId, { raw: true, waitForExecution });
892
+ const marker = this.store.activeForThread(threadId);
893
+ if (marker && !waitForExecution) void this.refreshExecution(marker);
840
894
  if (cached && this.codex.ready) await this.refreshThreadMetadata(threadId);
841
895
  const thread = this.projection.get(threadId);
842
896
  this.workspaces.assertOwnership(thread.projectId, thread.cwd, thread.id);
843
897
  await this.refreshGoal(thread);
898
+ this.workspaces.assertOwnership(thread.projectId, thread.cwd, thread.id);
844
899
  return thread;
845
900
  }
846
- async getThread(threadId) {
847
- return this.threadView(await this.refreshThreadDetail(threadId));
848
- }
849
901
  getThreadAttention(threadId) {
850
902
  const thread = this.projection.get(threadId);
851
903
  if (!thread) return [];
852
904
  this.workspaces.assertOwnership(thread.projectId, thread.cwd, thread.id);
853
- return pendingAttention(this.threadView(thread));
905
+ return pendingAttention(this.threadView(thread, false, false));
854
906
  }
855
- async getThreadSnapshot(threadId) {
856
- await this.refreshThreadDetail(threadId);
857
- const thread = this.projection.get(threadId);
907
+ scanQuestionHistory(thread, retry = false) {
908
+ const { id, projectId } = thread;
909
+ const cursor = thread.history?.olderCursor;
910
+ if (!cursor || thread.archived || !this.codex.ready || !this.codex.readThreadPage) return;
911
+ const epoch = this.codex.epoch;
912
+ const previous = this.questionHistories.get(id);
913
+ if (previous?.epoch === epoch && previous.cursor === cursor && (previous.status !== "error" || !retry && Date.now() < (previous.retryAt ?? 0)))
914
+ return;
915
+ const entry = {
916
+ epoch,
917
+ cursor,
918
+ status: "loading",
919
+ turns: previous?.turns ?? /* @__PURE__ */ new Map(),
920
+ observed: previous?.observed
921
+ };
922
+ this.questionHistories.set(id, entry);
923
+ const current = () => this.questionHistories.get(id) === entry && this.codex.epoch === epoch;
924
+ const logger = this.logger.child({
925
+ component: "question_history",
926
+ ...logContext(),
927
+ threadId: id,
928
+ codexEpoch: epoch
929
+ });
930
+ const started = Date.now();
931
+ logger.debug("question.history_scan_started");
932
+ void (async () => {
933
+ const pages = [];
934
+ const seen = /* @__PURE__ */ new Set();
935
+ let next = cursor;
936
+ while (next && current()) {
937
+ if (seen.has(next) || seen.size >= 1e3)
938
+ throw new AppError(
939
+ "QUESTION_HISTORY_INCOMPLETE",
940
+ "Invalid question history pagination",
941
+ 409
942
+ );
943
+ seen.add(next);
944
+ const page = await this.codex.readThreadPage(id, next, { deferOutput: true });
945
+ if (!current()) return;
946
+ if (page.id !== id || page.historyTruncated || !page.history)
947
+ throw new AppError("QUESTION_HISTORY_INCOMPLETE", "Incomplete question history", 409);
948
+ this.workspaces.assertOwnership(projectId, page.cwd, id);
949
+ const source = next;
950
+ pages.push(page.turns.map((turn) => ({ turn: questionEvidence(turn), cursor: source })));
951
+ next = page.history.olderCursor;
952
+ }
953
+ if (!current()) return;
954
+ entry.turns = new Map(
955
+ pages.reverse().flat().map((source) => [source.turn.id, source])
956
+ );
957
+ entry.status = "ready";
958
+ this.publishThread(id);
959
+ logger.debug("question.history_scan_finished", {
960
+ count: seen.size,
961
+ durationMs: Date.now() - started,
962
+ outcome: "succeeded"
963
+ });
964
+ })().catch((problem) => {
965
+ if (!current()) return;
966
+ entry.status = "error";
967
+ entry.retryAt = Date.now() + 3e4;
968
+ logger.warn("question.history_scan_finished", {
969
+ durationMs: Date.now() - started,
970
+ outcome: "failed",
971
+ ...errorFields(problem)
972
+ });
973
+ this.publishThread(id);
974
+ });
975
+ }
976
+ questionHistory(threadId) {
977
+ const history = this.questionHistories.get(threadId);
978
+ return history?.epoch === this.codex.epoch ? history : void 0;
979
+ }
980
+ questionState(thread) {
981
+ const history = this.questionHistory(thread.id);
982
+ const cursor = thread.history?.olderCursor;
983
+ return pendingQuestionCatalog(
984
+ thread,
985
+ cursor && history && cursor !== history.cursor ? { ...history, status: "loading" } : history
986
+ ).state;
987
+ }
988
+ async questionCatalog(threadId) {
989
+ const thread = this.projection.get(threadId) ?? await this.openThread(threadId, false);
858
990
  this.workspaces.assertOwnership(thread.projectId, thread.cwd, thread.id);
991
+ this.scanQuestionHistory(thread);
992
+ return {
993
+ thread,
994
+ ...pendingQuestionCatalog(
995
+ this.threadView(thread, false, false),
996
+ this.questionHistory(threadId)
997
+ )
998
+ };
999
+ }
1000
+ async getPendingQuestions(threadId, cursor, retry = false) {
1001
+ const { data, state, thread } = await this.questionCatalog(threadId);
1002
+ if (retry && !cursor && state.history === "error") {
1003
+ this.scanQuestionHistory(thread, true);
1004
+ if (this.questionHistory(threadId)?.status === "loading") {
1005
+ this.publishThread(threadId);
1006
+ state.history = "loading";
1007
+ }
1008
+ }
1009
+ let offset = 0;
1010
+ if (cursor !== void 0) {
1011
+ const [version, position, extra] = cursor.split(".");
1012
+ offset = Number(position);
1013
+ if (version !== state.version || extra !== void 0 || !Number.isSafeInteger(offset) || offset < 1 || offset >= data.length)
1014
+ throw new AppError("QUESTION_LIST_CHANGED", "The pending questions changed", 409);
1015
+ }
1016
+ const end = offset + 40;
859
1017
  return {
860
- data: this.threadView(thread),
1018
+ data: data.slice(offset, end),
1019
+ nextCursor: end < data.length ? `${state.version}.${end}` : null,
1020
+ history: state.history
1021
+ };
1022
+ }
1023
+ async locateQuestion(threadId, target) {
1024
+ const find = async () => {
1025
+ const catalog = await this.questionCatalog(threadId);
1026
+ const row2 = catalog.data.find(
1027
+ (row3) => row3.id === target.questionId && row3.target.kind === target.kind && row3.target.id === target.id && row3.turnId === target.turnId
1028
+ );
1029
+ if (!row2) throw new AppError("QUESTION_EXPIRED", "\u8BE5\u95EE\u9898\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5237\u65B0\u4F1A\u8BDD", 409);
1030
+ return { ...catalog, row: row2 };
1031
+ };
1032
+ const epoch = this.codex.epoch;
1033
+ const { row, thread } = await find();
1034
+ if (row.target.kind === "action") return {};
1035
+ const source = this.questionHistory(threadId)?.turns.get(row.turnId);
1036
+ let turn = thread.turns.find((turn2) => turn2.id === row.turnId);
1037
+ let cursor;
1038
+ if (!turn && source) {
1039
+ try {
1040
+ const page = await this.getThreadHistory(threadId, source.cursor);
1041
+ if (page.id === threadId) turn = page.turns.find((turn2) => turn2.id === row.turnId);
1042
+ if (turn) cursor = source.cursor;
1043
+ } catch (problem) {
1044
+ if (!(problem instanceof AppError && problem.code === "HISTORY_CURSOR_EXPIRED"))
1045
+ throw problem;
1046
+ }
1047
+ if (!turn && this.codex.readThreadTurnItems && this.codex.epoch === epoch) {
1048
+ const metadata = this.normalize(await this.codex.readThreadMetadata(threadId));
1049
+ if (metadata.id !== threadId || metadata.archived)
1050
+ throw new AppError("QUESTION_EXPIRED", "\u8BE5\u95EE\u9898\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5237\u65B0\u4F1A\u8BDD", 409);
1051
+ this.workspaces.assertOwnership(thread.projectId, metadata.cwd, threadId);
1052
+ turn = {
1053
+ ...source.turn,
1054
+ items: await this.codex.readThreadTurnItems(threadId, source.turn.id)
1055
+ };
1056
+ }
1057
+ }
1058
+ const { replies } = await find();
1059
+ if (this.codex.epoch !== epoch)
1060
+ throw new AppError("QUESTION_EXPIRED", "\u8BE5\u95EE\u9898\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5237\u65B0\u4F1A\u8BDD", 409);
1061
+ const item = turn?.items.find((item2) => item2.id === row.target.id);
1062
+ if (!turn || turn.threadId !== threadId || !canTrackQuestions(turn.status) || !item?.questions?.some((_, index) => asyncQuestionId(item.id, index) === row.id))
1063
+ throw new AppError("QUESTION_EXPIRED", "\u8BE5\u95EE\u9898\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5237\u65B0\u4F1A\u8BDD", 409);
1064
+ return {
1065
+ turn,
1066
+ cursor,
1067
+ turnNumber: row.turnNumber,
1068
+ replies: [
1069
+ item.id,
1070
+ ...item.questions.map((_, index) => asyncQuestionId(item.id, index))
1071
+ ].flatMap((id) => replies.get(id) ?? [])
1072
+ };
1073
+ }
1074
+ async getThreadSnapshot(threadId) {
1075
+ const thread = await this.openThread(threadId, false);
1076
+ return {
1077
+ data: this.detailThreadView(thread),
861
1078
  cursor: this.events.cursor()
862
1079
  };
863
1080
  }
@@ -869,14 +1086,34 @@ class GatewayService {
869
1086
  this.workspaces.assertOwnership(metadata.projectId, metadata.cwd, metadata.id);
870
1087
  if (!this.codex.readThreadPage)
871
1088
  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));
1089
+ const page = this.normalize(
1090
+ await this.codex.readThreadPage(threadId, cursor, { deferOutput: true })
1091
+ );
873
1092
  this.workspaces.assertOwnership(page.projectId, page.cwd, page.id);
874
1093
  const links = this.retryLinks(threadId);
875
1094
  for (const turn of page.turns) {
876
1095
  const root = links.get(turn.id);
877
1096
  if (root) turn.retryOf = root;
878
1097
  }
879
- return this.threadView(page);
1098
+ return { ...this.threadView(page, true, false), pendingQuestions: void 0 };
1099
+ }
1100
+ async getThreadItem(threadId, turnId, itemId) {
1101
+ this.ensureReady();
1102
+ const epoch = this.codex.epoch;
1103
+ const metadata = await this.codex.readThreadMetadata(threadId);
1104
+ if (metadata.id !== threadId || this.codex.epoch !== epoch)
1105
+ throw new AppError("THREAD_ITEM_NOT_FOUND", "\u5DE5\u5177\u8F93\u51FA\u4E0D\u53EF\u7528\u3002", 404);
1106
+ const thread = this.normalize(metadata);
1107
+ this.workspaces.assertOwnership(thread.projectId, thread.cwd, threadId);
1108
+ if (thread.historyMode !== "paginated" || !this.codex.readThreadItem)
1109
+ throw new AppError("HISTORY_UNAVAILABLE", "\u5F53\u524D Codex \u4E0D\u652F\u6301\u6309\u6761\u8BFB\u53D6\u5386\u53F2\u3002", 409);
1110
+ const item = await this.codex.readThreadItem(threadId, turnId, itemId);
1111
+ this.workspaces.assertOwnership(thread.projectId, thread.cwd, threadId);
1112
+ if (this.codex.epoch !== epoch)
1113
+ throw new AppError("HISTORY_CURSOR_EXPIRED", "\u8BFB\u53D6\u671F\u95F4 Codex \u5DF2\u91CD\u542F\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u4F1A\u8BDD\u3002", 409);
1114
+ if (item.id !== itemId || !["commandExecution", "mcpToolCall"].includes(item.type))
1115
+ throw new AppError("THREAD_ITEM_NOT_FOUND", "\u5DE5\u5177\u8F93\u51FA\u4E0D\u53EF\u7528\u3002", 404);
1116
+ return this.projection.limit(item);
880
1117
  }
881
1118
  async exportThread(threadId) {
882
1119
  this.ensureReady();
@@ -932,24 +1169,25 @@ class GatewayService {
932
1169
  this.workspaces.assertOwnership(link.projectId, link.cwd, threadId);
933
1170
  return file;
934
1171
  }
935
- async loadThread(threadId) {
1172
+ async loadThread(threadId, options) {
1173
+ const view = (thread) => options?.raw ? thread : this.threadView(thread);
936
1174
  const cached = this.projection.get(threadId);
937
1175
  if (cached) {
938
1176
  this.workspaces.assertOwnership(cached.projectId, cached.cwd, cached.id);
939
1177
  const marker = this.store.activeForThread(threadId);
940
1178
  if (marker && this.codex.ready) {
941
- await this.refreshExecution(marker);
942
- return this.threadView(cached);
1179
+ if (options?.waitForExecution !== false) await this.refreshExecution(marker);
1180
+ return view(cached);
943
1181
  }
944
1182
  if ((cached.managed || isActive(cached.status)) && cached.status !== "unknown" || !this.codex.ready)
945
- return this.threadView(cached);
1183
+ return view(cached);
946
1184
  }
947
1185
  const existing = this.reads.get(threadId);
948
- if (existing) return this.threadView(await existing);
1186
+ if (existing) return view(await existing);
949
1187
  const revision = this.projection.revision(threadId);
950
1188
  const loading = (async () => {
951
1189
  const thread = this.normalize(
952
- await (this.codex.readThreadPage?.(threadId) ?? this.codex.readThread(threadId))
1190
+ await (this.codex.readThreadPage?.(threadId, void 0, { deferOutput: true }) ?? this.codex.readThread(threadId))
953
1191
  );
954
1192
  const current = this.projection.get(threadId);
955
1193
  const preserveCurrent = current && (cached === void 0 || this.projection.revision(threadId) !== revision);
@@ -964,7 +1202,7 @@ class GatewayService {
964
1202
  })();
965
1203
  this.reads.set(threadId, loading);
966
1204
  try {
967
- return this.threadView(await loading);
1205
+ return view(await loading);
968
1206
  } finally {
969
1207
  this.reads.delete(threadId);
970
1208
  }
@@ -1080,7 +1318,9 @@ class GatewayService {
1080
1318
  delete current.resumeError;
1081
1319
  pending = (async () => {
1082
1320
  try {
1083
- const resumed = await this.codex.resumeThread(threadId, ownership.cwd, input.settings);
1321
+ const resumed = await this.codex.resumeThread(threadId, ownership.cwd, input.settings, {
1322
+ deferOutput: true
1323
+ });
1084
1324
  if (this.codex.epoch !== epoch || !this.codex.ready)
1085
1325
  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
1326
  this.projection.thread(
@@ -1111,7 +1351,7 @@ class GatewayService {
1111
1351
  async forkThread(threadId, input) {
1112
1352
  return this.perform("thread.fork", threadId, input, async () => {
1113
1353
  this.ensureReady();
1114
- const source = this.projection.get(threadId) ?? await this.codex.readThread(threadId);
1354
+ const source = this.projection.get(threadId) ?? await (this.codex.readThreadPage?.(threadId) ?? this.codex.readThread(threadId));
1115
1355
  const link = this.store.getThreadLink(threadId);
1116
1356
  const ownership = link ? this.workspaces.assertOwnership(link.projectId, source.cwd, threadId) : this.workspaces.findOwner(source.cwd, source.id);
1117
1357
  this.ensureCompatibilityConfirmed();
@@ -1126,7 +1366,10 @@ class GatewayService {
1126
1366
  this.store.dispatch(input.clientOperationId);
1127
1367
  this.pendingThreadCreations.set(input.clientOperationId, forkCwd);
1128
1368
  const settingsSequence = this.runtimeSettingsSequence;
1129
- const forked = await this.codex.forkThread(threadId, forkCwd, input.settings);
1369
+ const forked = await this.codex.forkThread(threadId, forkCwd, input.settings, {
1370
+ recentOnly: true,
1371
+ deferOutput: true
1372
+ });
1130
1373
  if (forked.id === threadId || this.codex.epoch !== epoch || !this.codex.ready)
1131
1374
  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
1375
  let normalized;
@@ -1165,13 +1408,73 @@ class GatewayService {
1165
1408
  if (!link) throw new AppError("THREAD_NOT_FOUND", "Session not found", 404);
1166
1409
  return this.workspaces.assertOwnership(link.projectId, link.cwd, threadId);
1167
1410
  }
1411
+ requireOwnedLoop(threadId, loopId) {
1412
+ const row = this.loops.get(loopId);
1413
+ if (!row || row.threadId !== threadId || row.workspaceKey !== this.loopWorkspace(threadId).workspaceKey)
1414
+ throw new AppError("LOOP_NOT_FOUND", "Loop not found", 404);
1415
+ return row;
1416
+ }
1168
1417
  async listSessionLoops(threadId) {
1169
1418
  if (!this.store.getThreadLink(threadId)) await this.loadThread(threadId);
1170
1419
  const workspace = this.loopWorkspace(threadId);
1171
1420
  return this.loops.list(threadId, workspace.workspaceKey);
1172
1421
  }
1422
+ async listLoopTasks() {
1423
+ const threadIds = this.loops.threadIds();
1424
+ const metadata = /* @__PURE__ */ new Map();
1425
+ const missing = /* @__PURE__ */ new Set();
1426
+ if (this.codex.ready) {
1427
+ for (let start = 0; start < threadIds.length; start += 4) {
1428
+ await Promise.all(
1429
+ threadIds.slice(start, start + 4).map(async (id) => {
1430
+ if (this.projection.get(id)) return;
1431
+ try {
1432
+ const workspace = this.loopWorkspace(id);
1433
+ if (!this.loops.list(id, workspace.workspaceKey).length) return;
1434
+ } catch {
1435
+ return;
1436
+ }
1437
+ try {
1438
+ metadata.set(id, await this.codex.readThreadMetadata(id));
1439
+ } catch (error) {
1440
+ if (this.asAppError(error).code === "THREAD_NOT_FOUND") missing.add(id);
1441
+ }
1442
+ })
1443
+ );
1444
+ }
1445
+ }
1446
+ const now = Date.now();
1447
+ return threadIds.flatMap((id) => {
1448
+ const thread = this.projection.get(id) ?? metadata.get(id);
1449
+ if (thread && thread.id !== id || !thread && missing.has(id)) return [];
1450
+ try {
1451
+ const workspace = this.loopWorkspace(id);
1452
+ const workspaceKey = workspace.workspaceKey;
1453
+ if (thread) {
1454
+ const actual = this.workspaces.assertOwnership(workspace.projectId, thread.cwd, id);
1455
+ if (actual.cwd !== workspace.cwd && actual.workspaceKey !== workspaceKey) return [];
1456
+ }
1457
+ const projectName = workspace.projectId === null ? null : this.projects.describe(workspace.projectId).name;
1458
+ const busy = thread !== void 0 && isActive(thread.status) || Boolean(this.store.activeForThread(id)) || this.capacityRetries.pending(id);
1459
+ return this.loops.list(id, workspaceKey).filter((loop) => loop.reason !== "deleted").map((loop) => ({
1460
+ ...loop,
1461
+ projectId: workspace.projectId,
1462
+ projectName,
1463
+ threadTitle: thread?.title || id,
1464
+ archived: thread?.archived ?? loop.reason === "archived",
1465
+ waiting: loop.status === "active" && loop.nextRunAt !== null && loop.nextRunAt <= now && (busy || this.loopDispatchDeferred())
1466
+ }));
1467
+ } catch (error) {
1468
+ if (!(error instanceof AppError) && !(error instanceof Error && "code" in error))
1469
+ throw error;
1470
+ return [];
1471
+ }
1472
+ });
1473
+ }
1173
1474
  async createSessionLoop(threadId, input) {
1174
1475
  input = createSessionLoopSchema.parse(input);
1476
+ if (this.loops.get(input.clientOperationId))
1477
+ this.requireOwnedLoop(threadId, input.clientOperationId);
1175
1478
  return this.perform("loop.create", threadId, input, async () => {
1176
1479
  const thread = await this.loadThread(threadId);
1177
1480
  this.ensureManaged(thread);
@@ -1200,21 +1503,20 @@ class GatewayService {
1200
1503
  workspaceKey: workspace.workspaceKey,
1201
1504
  settings,
1202
1505
  prompt: input.prompt,
1203
- intervalMs: input.intervalMs,
1506
+ mode: input.mode ?? "fixed",
1507
+ intervalMs: input.intervalMs ?? null,
1204
1508
  status: "active",
1205
- nextRunAt: now + input.intervalMs
1509
+ nextRunAt: now + (input.intervalMs ?? 0)
1206
1510
  })
1207
1511
  );
1208
1512
  return { result: sessionLoopView(this.loops.get(input.clientOperationId)) };
1209
1513
  });
1210
1514
  }
1211
1515
  async controlSessionLoop(threadId, loopId, input) {
1516
+ const owned = this.requireOwnedLoop(threadId, loopId);
1212
1517
  return this.perform("loop.control", threadId, { ...input, loopId }, async () => {
1213
1518
  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);
1519
+ const row = thread ? this.requireOwnedLoop(threadId, loopId) : owned;
1218
1520
  const now = Date.now();
1219
1521
  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
1522
  if (!canChange)
@@ -1314,24 +1616,55 @@ class GatewayService {
1314
1616
  return;
1315
1617
  }
1316
1618
  const turnId = operation?.result?.turnId ?? marker?.turnId ?? row.lastTurnId;
1317
- const turn = turnId ? thread.turns.find((entry) => entry.id === turnId) : thread.turns.find(
1619
+ let turn = turnId ? thread.turns.find((entry) => entry.id === turnId) : thread.turns.find(
1318
1620
  (entry) => entry.items.some((item) => item.type === "userMessage" && item.clientId === operationId)
1319
1621
  );
1320
1622
  if (turn && isTerminal(turn.status)) {
1321
- this.loops.record(row, turn.status, turn.id);
1623
+ const status = turn.status;
1624
+ const completedTurnId2 = turn.id;
1625
+ if (row.mode === "adaptive" && status === "completed") {
1626
+ const answer = adaptiveLoopAnswer(turn);
1627
+ if (!answer?.text || answer.truncated) {
1628
+ const history = this.normalize(
1629
+ await (this.codex.readThreadPage?.(row.threadId) ?? this.codex.readThread(row.threadId))
1630
+ );
1631
+ if (history.id !== row.threadId || this.loopWorkspace(row.threadId).workspaceKey !== row.workspaceKey)
1632
+ return;
1633
+ turn = history.turns.find((entry) => entry.id === completedTurnId2) ?? turn;
1634
+ }
1635
+ }
1636
+ this.completeLoopRun(row, status, completedTurnId2, turn);
1322
1637
  } else if (operation?.reconciledAt != null) {
1323
- this.loops.record(row, "reconciled", turnId ?? null);
1638
+ this.completeLoopRun(row, "reconciled", turnId ?? null);
1324
1639
  } else if (operation?.state === "failed") {
1325
- this.loops.record(row, "failed", turnId ?? null);
1640
+ this.completeLoopRun(row, "failed", turnId ?? null);
1326
1641
  } else if (operation?.state === "unknown" || marker?.state === "unknown") {
1327
1642
  this.loops.record(row, "unknown", turnId ?? null);
1328
1643
  this.loops.suspend(row, "uncertain");
1329
1644
  }
1330
1645
  }
1646
+ completeLoopRun(row, result, turnId, turn) {
1647
+ if (row.mode === "fixed") {
1648
+ this.loops.record(row, result, turnId);
1649
+ return;
1650
+ }
1651
+ const decision = result === "completed" && turn ? readAdaptiveLoopDecision(turn) : void 0;
1652
+ const outcome = this.loops.settleAdaptive(row, result, turnId, decision, Date.now());
1653
+ if (!outcome) return;
1654
+ const context = { threadId: row.threadId, operationId: row.lastOperationId, turnId, outcome };
1655
+ if (outcome === "paused")
1656
+ this.logger.warn("loop.adaptive_paused", {
1657
+ ...context,
1658
+ reason: result === "completed" ? "invalid_decision" : "run_failed"
1659
+ });
1660
+ else this.logger.info("loop.adaptive_settled", context);
1661
+ }
1331
1662
  recordLoopTurn(operationId, status, turnId) {
1332
1663
  const row = this.loops.byRun(operationId);
1333
- if (row && !this.capacityRetries.pending(row.threadId))
1334
- this.loops.record(row, status, turnId);
1664
+ if (!row || this.capacityRetries.pending(row.threadId)) return;
1665
+ if (row.mode === "fixed") this.loops.record(row, status, turnId);
1666
+ else if (row.lastResult === "running" || row.lastResult === "unknown")
1667
+ this.loops.record(row, row.lastResult, turnId);
1335
1668
  }
1336
1669
  assertLoopIdle(thread, row) {
1337
1670
  if (this.loopDispatchDeferred()) throw new AppError("LOOP_WAITING", "The service is busy", 409);
@@ -1393,7 +1726,7 @@ class GatewayService {
1393
1726
  break;
1394
1727
  default: {
1395
1728
  const dispatched = this.loops.byRun(operationId);
1396
- if (dispatched) this.loops.record(dispatched, "failed", null);
1729
+ if (dispatched) this.completeLoopRun(dispatched, "failed", null);
1397
1730
  else this.loops.suspend(row, "unavailable");
1398
1731
  }
1399
1732
  }
@@ -1436,6 +1769,7 @@ class GatewayService {
1436
1769
  const retryLoop = retry?.previousOperationId ? this.loops.byRun(retry.previousOperationId) : void 0;
1437
1770
  if (retryLoop && this.loopDispatchDeferred())
1438
1771
  throw new AppError("LOOP_WAITING", "The service is busy", 409);
1772
+ const adaptive = (loop ?? retryLoop)?.mode === "adaptive";
1439
1773
  const claimLoop = loop ? (tx) => this.loops.claim(tx, loop, input.clientOperationId, Date.now()) : retryLoop && retry?.previousOperationId ? (tx) => this.loops.retry(
1440
1774
  tx,
1441
1775
  retryLoop.id,
@@ -1470,11 +1804,12 @@ class GatewayService {
1470
1804
  const turn = await this.codex.startTurn(
1471
1805
  threadId,
1472
1806
  ownership.cwd,
1473
- message.text,
1807
+ adaptive && message.text ? adaptiveLoopPrompt(message.text) : message.text,
1474
1808
  input.settings,
1475
1809
  input.images,
1476
1810
  skills.length ? skills : void 0,
1477
- input.clientOperationId
1811
+ input.clientOperationId,
1812
+ ...adaptive ? [adaptiveLoopOutputSchema] : []
1478
1813
  );
1479
1814
  this.store.attachTurn(input.clientOperationId, turn.id);
1480
1815
  this.turnBaselines.delete(input.clientOperationId);
@@ -1824,7 +2159,7 @@ class GatewayService {
1824
2159
  await this.loadThread(threadId);
1825
2160
  const history = this.normalize(await this.codex.readThread(threadId));
1826
2161
  this.workspaces.assertOwnership(history.projectId, history.cwd, history.id);
1827
- this.projection.thread(history, true);
2162
+ this.mergeQuestionHistory(history);
1828
2163
  const states = this.questionTracking.states(threadId);
1829
2164
  for (const id of new Set(input.questionIds)) {
1830
2165
  const question = this.findAsyncQuestion(history, id);
@@ -1842,16 +2177,44 @@ class GatewayService {
1842
2177
  return { result: { threadId, questionIds: ids } };
1843
2178
  });
1844
2179
  }
2180
+ mergeQuestionHistory(history) {
2181
+ const index = this.questionHistory(history.id);
2182
+ if (index && !history.historyTruncated) index.observed = history.turns.map(questionEvidence);
2183
+ const current = this.projection.get(history.id);
2184
+ if (!current || history.historyMode !== "paginated" && !current.history) {
2185
+ this.projection.thread(history, true);
2186
+ return;
2187
+ }
2188
+ const visibleTurns = new Set(current.turns.map((turn) => turn.id));
2189
+ this.projection.thread(
2190
+ {
2191
+ ...history,
2192
+ history: current.history,
2193
+ turns: history.turns.filter((turn) => visibleTurns.has(turn.id))
2194
+ },
2195
+ true
2196
+ );
2197
+ if (index) this.publishThread(history.id);
2198
+ }
1845
2199
  questionItems(history) {
1846
2200
  return [...history.turns, ...this.projection.get(history.id)?.turns ?? []].flatMap(
1847
2201
  (turn) => turn.items
1848
2202
  );
1849
2203
  }
1850
2204
  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] };
2205
+ const turns = new Map(
2206
+ (this.projection.get(history.id)?.turns ?? []).map((turn) => [turn.id, turn])
2207
+ );
2208
+ for (const native of history.turns) turns.set(native.id, native);
2209
+ for (const turn of turns.values()) {
2210
+ if (!canTrackQuestions(turn.status)) continue;
2211
+ for (const item of turn.items) {
2212
+ if (item.type !== "agentMessage") continue;
2213
+ const index = item.questions?.findIndex(
2214
+ (_, index2) => asyncQuestionId(item.id, index2) === id
2215
+ );
2216
+ if (index !== void 0 && index >= 0) return { item, question: item.questions[index] };
2217
+ }
1855
2218
  }
1856
2219
  }
1857
2220
  questionAnswered(history, id) {
@@ -1869,7 +2232,7 @@ class GatewayService {
1869
2232
  if (!replies) return;
1870
2233
  const history = this.normalize(await this.codex.readThread(threadId));
1871
2234
  this.workspaces.assertOwnership(history.projectId, history.cwd, history.id);
1872
- this.projection.thread(history, true);
2235
+ this.mergeQuestionHistory(history);
1873
2236
  const states = this.questionTracking.states(threadId);
1874
2237
  const ids = [];
1875
2238
  for (const reply of replies) {
@@ -1892,6 +2255,11 @@ class GatewayService {
1892
2255
  getOperation(id) {
1893
2256
  const row = this.store.get(id);
1894
2257
  if (!row) throw new AppError("OPERATION_NOT_FOUND", "\u672A\u627E\u5230\u8BE5\u64CD\u4F5C", 404);
2258
+ if (row.kind === "loop.create" || row.kind === "loop.control") {
2259
+ const result = row.result;
2260
+ if (result?.id) this.requireOwnedLoop(row.target, result.id);
2261
+ else this.loopWorkspace(row.target);
2262
+ }
1895
2263
  return this.operation(row);
1896
2264
  }
1897
2265
  async reconcileOperation(targetOperationId, input) {
@@ -1954,7 +2322,7 @@ class GatewayService {
1954
2322
  } else await this.getThread(threadId);
1955
2323
  return this.events.subscribe(
1956
2324
  threadId,
1957
- () => this.threadView(this.projection.get(threadId)),
2325
+ () => this.detailThreadView(this.projection.get(threadId)),
1958
2326
  after,
1959
2327
  listener,
1960
2328
  incremental,
@@ -1966,6 +2334,7 @@ class GatewayService {
1966
2334
  this.stopLoopScheduler();
1967
2335
  await Promise.allSettled([...this.instructionWrites, ...this.defaultWrites]);
1968
2336
  this.capacityRetries.clearAll();
2337
+ this.questionHistories.clear();
1969
2338
  await this.projectClones.close();
1970
2339
  this.store.recover();
1971
2340
  this.projection.runtimeReset();
@@ -2108,10 +2477,13 @@ class GatewayService {
2108
2477
  const revision = this.projection.revision(marker.threadId);
2109
2478
  const reading = (async () => {
2110
2479
  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;
2480
+ const current = () => {
2481
+ const latest2 = this.store.activeForThread(marker.threadId);
2482
+ 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;
2483
+ };
2484
+ const actual = await (marker.turnId && this.codex.readExecutionHistory?.(marker.threadId, marker.turnId) || this.codex.readThread(marker.threadId));
2485
+ const latest = current();
2486
+ if (!latest || actual.id !== marker.threadId) return;
2115
2487
  const link = this.store.getThreadLink(marker.threadId);
2116
2488
  const ownership = link ? this.workspaces.assertOwnership(link.projectId, actual.cwd, actual.id) : this.workspaces.findOwner(actual.cwd, actual.id);
2117
2489
  if (ownership.workspaceKey !== marker.workspaceKey) return;
@@ -2121,13 +2493,21 @@ class GatewayService {
2121
2493
  )
2122
2494
  );
2123
2495
  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));
2496
+ if (!turn) return;
2497
+ const restoreActive = isActive(turn.status) && latest.state === "active" && this.projection.get(marker.threadId)?.status === "unknown";
2498
+ const ended = isTerminal(turn.status) && !isActive(actual.status) && !actual.turns.some((entry) => isActive(entry.status));
2499
+ if (!restoreActive && !ended) return;
2500
+ const page = actual.historyMode === "paginated" && this.codex.readThreadPage ? await this.codex.readThreadPage(marker.threadId, void 0, { deferOutput: true }) : actual;
2501
+ if (!current() || page.id !== marker.threadId) return;
2502
+ if (this.workspaces.assertOwnership(ownership.projectId, page.cwd, page.id).workspaceKey !== marker.workspaceKey)
2503
+ return;
2504
+ if (ended && (isActive(page.status) || page.turns.some((entry) => isActive(entry.status))))
2505
+ return;
2506
+ if (restoreActive) {
2507
+ this.projection.thread(this.normalize(page));
2126
2508
  this.publishThread(marker.threadId);
2127
2509
  return;
2128
2510
  }
2129
- if (!turn || !isTerminal(turn.status) || isActive(actual.status) || actual.turns.some((entry) => isActive(entry.status)))
2130
- return;
2131
2511
  if (!marker.turnId) this.store.attachTurn(marker.operationId, turn.id);
2132
2512
  this.store.finishTurn(marker.threadId, turn.id, marker.codexEpoch);
2133
2513
  this.logger.info("execution.recovered", {
@@ -2137,11 +2517,18 @@ class GatewayService {
2137
2517
  codexEpoch: marker.codexEpoch,
2138
2518
  reason: marker.turnId ? "terminal_history" : "native_message_identity"
2139
2519
  });
2140
- this.projection.thread(this.normalize(actual));
2520
+ this.projection.thread(this.normalize(page));
2521
+ if (!page.turns.some((entry) => entry.id === turn.id) && this.projection.get(marker.threadId)?.turns.some((entry) => entry.id === turn.id))
2522
+ this.projection.turn(marker.threadId, turn);
2141
2523
  this.projection.expireTurn(marker.threadId, turn.id);
2142
2524
  this.publishThread(marker.threadId);
2143
2525
  this.events.publish("operation", this.getOperation(marker.operationId), marker.threadId);
2144
- } catch {
2526
+ } catch (error) {
2527
+ this.logger.debug("execution.recovery_read_failed", {
2528
+ threadId: marker.threadId,
2529
+ operationId: marker.operationId,
2530
+ ...errorFields(error)
2531
+ });
2145
2532
  }
2146
2533
  })();
2147
2534
  this.executionReads.set(marker.operationId, reading);
@@ -2260,18 +2647,27 @@ class GatewayService {
2260
2647
  publishThread(threadId, streamed) {
2261
2648
  const thread = this.projection.get(threadId);
2262
2649
  if (!thread) return;
2263
- const view = this.threadView(thread, false);
2650
+ const view = this.detailThreadView(thread, false, !streamed || !thread.pendingQuestions);
2651
+ if (view.pendingQuestions) thread.pendingQuestions = view.pendingQuestions;
2264
2652
  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
2653
  try {
2269
2654
  this.workspaces.assertOwnership(thread.projectId, thread.cwd, thread.id);
2270
2655
  } catch {
2271
2656
  return;
2272
2657
  }
2273
- this.summaries.set(threadId, encoded);
2274
- this.events.publishSummary(summary);
2658
+ this.publishThreadSummary(this.threadSummary({ ...view, turns: thread.turns }));
2659
+ }
2660
+ threadSummary(view) {
2661
+ const summary = toThreadSummary(view);
2662
+ const turnId = completedTurnId(summary);
2663
+ if (turnId) summary.lastTurnRead = this.turnCompletionReads.has(view.id, turnId);
2664
+ return summary;
2665
+ }
2666
+ publishThreadSummary(summary, advanceCursor = false) {
2667
+ const encoded = JSON.stringify(summary);
2668
+ if (this.summaries.get(summary.id) === encoded) return;
2669
+ this.summaries.set(summary.id, encoded);
2670
+ this.events.publishSummary(summary, advanceCursor);
2275
2671
  }
2276
2672
  historyVisible(thread) {
2277
2673
  return Boolean(
@@ -2286,7 +2682,33 @@ class GatewayService {
2286
2682
  }
2287
2683
  return links;
2288
2684
  }
2289
- threadView(thread, copy = true) {
2685
+ detailThreadView(thread, copy = true, includeQuestions = true) {
2686
+ if (thread.historyMode !== "paginated") return this.threadView(thread, copy, includeQuestions);
2687
+ const bounded = thread.turns.length > HISTORY_PAGE_SIZE;
2688
+ const history = bounded ? {
2689
+ olderCursor: historyCursor(thread.id, this.codex.epoch, {
2690
+ beforeTurnId: thread.turns[thread.turns.length - HISTORY_PAGE_SIZE].id
2691
+ })
2692
+ } : thread.history;
2693
+ let turns = bounded ? thread.turns.slice(-HISTORY_PAGE_SIZE) : thread.turns;
2694
+ if (this.codex.canReadDeferredOutput?.()) {
2695
+ turns = turns.map(
2696
+ (turn) => isTerminal(turn.status) ? {
2697
+ ...turn,
2698
+ items: turn.items.map(deferLiveToolOutput)
2699
+ } : turn
2700
+ );
2701
+ }
2702
+ const result = this.threadView({ ...thread, turns, history }, copy, false);
2703
+ if (includeQuestions)
2704
+ result.pendingQuestions = this.questionState({
2705
+ ...result,
2706
+ turns: thread.turns,
2707
+ history: thread.history
2708
+ });
2709
+ return result;
2710
+ }
2711
+ threadView(thread, copy = true, includeQuestions = true) {
2290
2712
  const submissions = new Map(
2291
2713
  this.store.pendingMessages(thread.id).map((message) => [message.id, message])
2292
2714
  );
@@ -2320,6 +2742,7 @@ class GatewayService {
2320
2742
  actions.set(action.actionId, action);
2321
2743
  result.actions = [...actions.values()];
2322
2744
  result.archived = thread.archived ?? false;
2745
+ if (includeQuestions) result.pendingQuestions = this.questionState(result);
2323
2746
  result.historyVisible = this.historyVisible(thread);
2324
2747
  const marker = this.store.activeForThread(thread.id);
2325
2748
  delete result.execution;
@@ -2391,6 +2814,7 @@ class GatewayService {
2391
2814
  this.runtimeSettingsUpdates.clear();
2392
2815
  this.turnBaselines.clear();
2393
2816
  this.resumes.clear();
2817
+ this.questionHistories.clear();
2394
2818
  this.store.recover();
2395
2819
  this.projection.runtimeReset();
2396
2820
  for (const thread2 of this.projection.values()) this.publishThread(thread2.id);
@@ -2419,7 +2843,7 @@ class GatewayService {
2419
2843
  const known = this.projection.actions.has(action.actionId);
2420
2844
  const owner = action.threadId ? this.projection.get(action.threadId) : void 0;
2421
2845
  const previous = new Set(
2422
- owner ? pendingAttention(this.threadView(owner)).map(attentionKey) : []
2846
+ owner ? pendingAttention(this.threadView(owner, false, false)).map(attentionKey) : []
2423
2847
  );
2424
2848
  this.projection.action(action);
2425
2849
  if (action.kind === "questions") this.questionTracking.saveAction(action);
@@ -2449,7 +2873,7 @@ class GatewayService {
2449
2873
  return;
2450
2874
  }
2451
2875
  const previousAttention = new Set(
2452
- event.type === "item" || event.type === "turn" ? pendingAttention(this.threadView(thread)).map(attentionKey) : []
2876
+ event.type === "item" || event.type === "turn" ? pendingAttention(this.threadView(thread, false, false)).map(attentionKey) : []
2453
2877
  );
2454
2878
  if (event.type === "tokenUsage") {
2455
2879
  if (this.projection.tokenUsage(thread.id, event.usage)) this.publishThread(thread.id);