@vybestack/llxprt-code-agents 0.10.0 → 0.11.0-nightly.260728.ffaa8d5d7

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 (227) hide show
  1. package/dist/src/agents/executor-test-helpers.js +2 -2
  2. package/dist/src/agents/executor-test-helpers.js.map +1 -1
  3. package/dist/src/agents/executor-tool-dispatch.js +16 -2
  4. package/dist/src/agents/executor-tool-dispatch.js.map +1 -1
  5. package/dist/src/agents/executor-validation.js +7 -1
  6. package/dist/src/agents/executor-validation.js.map +1 -1
  7. package/dist/src/agents/invocation.d.ts +2 -2
  8. package/dist/src/agents/invocation.js +6 -3
  9. package/dist/src/agents/invocation.js.map +1 -1
  10. package/dist/src/api/agent.d.ts +21 -2
  11. package/dist/src/api/agentImpl.d.ts +5 -0
  12. package/dist/src/api/agentImpl.js +12 -0
  13. package/dist/src/api/agentImpl.js.map +1 -1
  14. package/dist/src/api/config-schema.d.ts +20 -20
  15. package/dist/src/api/config-schema.js +1 -1
  16. package/dist/src/api/config-schema.js.map +1 -1
  17. package/dist/src/api/config-types.d.ts +1 -1
  18. package/dist/src/api/control/sessionControl.d.ts +205 -18
  19. package/dist/src/api/control/sessionControl.js +430 -56
  20. package/dist/src/api/control/sessionControl.js.map +1 -1
  21. package/dist/src/api/control/toolControl.js +21 -15
  22. package/dist/src/api/control/toolControl.js.map +1 -1
  23. package/dist/src/api/discovery.js +23 -1
  24. package/dist/src/api/discovery.js.map +1 -1
  25. package/dist/src/api/event-schema.d.ts +16 -0
  26. package/dist/src/api/event-schema.js +2 -0
  27. package/dist/src/api/event-schema.js.map +1 -1
  28. package/dist/src/api/eventAdapter.js +1 -1
  29. package/dist/src/api/eventAdapter.js.map +1 -1
  30. package/dist/src/app-services/command-api-map.js +5 -0
  31. package/dist/src/app-services/command-api-map.js.map +1 -1
  32. package/dist/src/app-services/memory.js +1 -1
  33. package/dist/src/app-services/memory.js.map +1 -1
  34. package/dist/src/compression/CompressionHandler.d.ts +42 -0
  35. package/dist/src/compression/CompressionHandler.js +129 -27
  36. package/dist/src/compression/CompressionHandler.js.map +1 -1
  37. package/dist/src/compression/HighDensityStrategy.d.ts +3 -7
  38. package/dist/src/compression/HighDensityStrategy.js +18 -28
  39. package/dist/src/compression/HighDensityStrategy.js.map +1 -1
  40. package/dist/src/compression/MiddleOutStrategy.d.ts +3 -3
  41. package/dist/src/compression/MiddleOutStrategy.js +29 -13
  42. package/dist/src/compression/MiddleOutStrategy.js.map +1 -1
  43. package/dist/src/compression/OneShotStrategy.d.ts +3 -3
  44. package/dist/src/compression/OneShotStrategy.js +16 -6
  45. package/dist/src/compression/OneShotStrategy.js.map +1 -1
  46. package/dist/src/compression/TopDownTruncationStrategy.d.ts +3 -2
  47. package/dist/src/compression/TopDownTruncationStrategy.js +15 -18
  48. package/dist/src/compression/TopDownTruncationStrategy.js.map +1 -1
  49. package/dist/src/compression/contextOverflowError.d.ts +3 -1
  50. package/dist/src/compression/contextOverflowError.js +4 -1
  51. package/dist/src/compression/contextOverflowError.js.map +1 -1
  52. package/dist/src/compression/pendingContextWindowEnforcement.d.ts +18 -4
  53. package/dist/src/compression/pendingContextWindowEnforcement.js +84 -2
  54. package/dist/src/compression/pendingContextWindowEnforcement.js.map +1 -1
  55. package/dist/src/compression/providerContentEnforcement.d.ts +2 -0
  56. package/dist/src/compression/providerContentEnforcement.js +55 -2
  57. package/dist/src/compression/providerContentEnforcement.js.map +1 -1
  58. package/dist/src/compression/toolResultTruncator.d.ts +109 -0
  59. package/dist/src/compression/toolResultTruncator.js +387 -0
  60. package/dist/src/compression/toolResultTruncator.js.map +1 -0
  61. package/dist/src/compression/utils.js +1 -1
  62. package/dist/src/compression/utils.js.map +1 -1
  63. package/dist/src/core/ConversationManager.d.ts +8 -4
  64. package/dist/src/core/ConversationManager.js +18 -17
  65. package/dist/src/core/ConversationManager.js.map +1 -1
  66. package/dist/src/core/MessageStreamOrchestrator.d.ts +0 -1
  67. package/dist/src/core/MessageStreamOrchestrator.js +27 -50
  68. package/dist/src/core/MessageStreamOrchestrator.js.map +1 -1
  69. package/dist/src/core/MessageStreamTerminalHandler.d.ts +0 -1
  70. package/dist/src/core/MessageStreamTerminalHandler.js +9 -3
  71. package/dist/src/core/MessageStreamTerminalHandler.js.map +1 -1
  72. package/dist/src/core/StreamProcessor.js +21 -4
  73. package/dist/src/core/StreamProcessor.js.map +1 -1
  74. package/dist/src/core/TodoContinuationService.js +1 -2
  75. package/dist/src/core/TodoContinuationService.js.map +1 -1
  76. package/dist/src/core/TokenUsageLogger.d.ts +52 -0
  77. package/dist/src/core/TokenUsageLogger.js +96 -0
  78. package/dist/src/core/TokenUsageLogger.js.map +1 -0
  79. package/dist/src/core/TurnProcessor.js +24 -3
  80. package/dist/src/core/TurnProcessor.js.map +1 -1
  81. package/dist/src/core/agenticLoop/AgenticLoop.d.ts +36 -0
  82. package/dist/src/core/agenticLoop/AgenticLoop.js +97 -13
  83. package/dist/src/core/agenticLoop/AgenticLoop.js.map +1 -1
  84. package/dist/src/core/agenticLoop/loopHelpers.d.ts +6 -1
  85. package/dist/src/core/agenticLoop/loopHelpers.js +16 -2
  86. package/dist/src/core/agenticLoop/loopHelpers.js.map +1 -1
  87. package/dist/src/core/agenticLoop/types.d.ts +8 -1
  88. package/dist/src/core/chatSession.d.ts +5 -0
  89. package/dist/src/core/chatSession.js +30 -0
  90. package/dist/src/core/chatSession.js.map +1 -1
  91. package/dist/src/core/client-test-helpers.js +7 -0
  92. package/dist/src/core/client-test-helpers.js.map +1 -1
  93. package/dist/src/core/client.js +1 -1
  94. package/dist/src/core/client.js.map +1 -1
  95. package/dist/src/core/clientToolGovernance.js +5 -4
  96. package/dist/src/core/clientToolGovernance.js.map +1 -1
  97. package/dist/src/core/coreToolScheduler-test-helpers.d.ts +2 -1
  98. package/dist/src/core/coreToolScheduler-test-helpers.js +1 -1
  99. package/dist/src/core/coreToolScheduler-test-helpers.js.map +1 -1
  100. package/dist/src/core/coreToolScheduler.d.ts +1 -1
  101. package/dist/src/core/coreToolScheduler.js +5 -5
  102. package/dist/src/core/coreToolScheduler.js.map +1 -1
  103. package/dist/src/core/imagePayloadBudget.d.ts +74 -0
  104. package/dist/src/core/imagePayloadBudget.js +87 -0
  105. package/dist/src/core/imagePayloadBudget.js.map +1 -0
  106. package/dist/src/core/messageStreamModelInfo.d.ts +16 -0
  107. package/dist/src/core/messageStreamModelInfo.js +65 -0
  108. package/dist/src/core/messageStreamModelInfo.js.map +1 -0
  109. package/dist/src/core/nonInteractiveToolExecutor.js +1 -1
  110. package/dist/src/core/nonInteractiveToolExecutor.js.map +1 -1
  111. package/dist/src/core/schemaDepthErrorEnrichment.js +1 -1
  112. package/dist/src/core/schemaDepthErrorEnrichment.js.map +1 -1
  113. package/dist/src/core/streamResponseHelpers.d.ts +6 -15
  114. package/dist/src/core/streamResponseHelpers.js +85 -13
  115. package/dist/src/core/streamResponseHelpers.js.map +1 -1
  116. package/dist/src/core/streamValidationHelpers.js +1 -1
  117. package/dist/src/core/streamValidationHelpers.js.map +1 -1
  118. package/dist/src/core/subagentExecution.js +24 -10
  119. package/dist/src/core/subagentExecution.js.map +1 -1
  120. package/dist/src/core/subagentRuntimeSetup.js +1 -1
  121. package/dist/src/core/subagentRuntimeSetup.js.map +1 -1
  122. package/dist/src/core/subagentToolProcessing.d.ts +1 -1
  123. package/dist/src/core/subagentToolProcessing.js +18 -3
  124. package/dist/src/core/subagentToolProcessing.js.map +1 -1
  125. package/dist/src/core/tokenUsageActualLogger.d.ts +27 -0
  126. package/dist/src/core/tokenUsageActualLogger.js +23 -0
  127. package/dist/src/core/tokenUsageActualLogger.js.map +1 -0
  128. package/dist/src/core/tokenUsageEstimateLogger.d.ts +20 -0
  129. package/dist/src/core/tokenUsageEstimateLogger.js +71 -0
  130. package/dist/src/core/tokenUsageEstimateLogger.js.map +1 -0
  131. package/dist/src/core/turn-test-helpers.d.ts +1 -0
  132. package/dist/src/core/turn-test-helpers.js +1 -1
  133. package/dist/src/core/turn-test-helpers.js.map +1 -1
  134. package/dist/src/core/turn.d.ts +3 -10
  135. package/dist/src/core/turn.js +33 -63
  136. package/dist/src/core/turn.js.map +1 -1
  137. package/dist/src/core/turnCitations.d.ts +17 -0
  138. package/dist/src/core/turnCitations.js +52 -0
  139. package/dist/src/core/turnCitations.js.map +1 -0
  140. package/dist/src/scheduler/confirmation-coordinator.d.ts +1 -1
  141. package/dist/src/scheduler/confirmation-coordinator.js +1 -1
  142. package/dist/src/scheduler/confirmation-coordinator.js.map +1 -1
  143. package/dist/src/scheduler/result-aggregator.js +1 -1
  144. package/dist/src/scheduler/result-aggregator.js.map +1 -1
  145. package/dist/src/scheduler/status-transitions.js +1 -1
  146. package/dist/src/scheduler/status-transitions.js.map +1 -1
  147. package/dist/src/scheduler/tool-dispatcher.js +1 -1
  148. package/dist/src/scheduler/tool-dispatcher.js.map +1 -1
  149. package/dist/src/scheduler/tool-executor.d.ts +2 -2
  150. package/dist/src/scheduler/tool-executor.js +2 -2
  151. package/dist/src/scheduler/tool-executor.js.map +1 -1
  152. package/dist/src/tools/task.d.ts +4 -2
  153. package/dist/src/tools/task.js +78 -66
  154. package/dist/src/tools/task.js.map +1 -1
  155. package/dist/src/tools/taskAsyncExecution.d.ts +3 -3
  156. package/dist/src/tools/taskAsyncExecution.js +9 -5
  157. package/dist/src/tools/taskAsyncExecution.js.map +1 -1
  158. package/dist/src/tools/taskResultHelpers.js +1 -1
  159. package/dist/src/tools/taskResultHelpers.js.map +1 -1
  160. package/dist/src/tools/taskToolGovernance.d.ts +24 -0
  161. package/dist/src/tools/taskToolGovernance.js +72 -1
  162. package/dist/src/tools/taskToolGovernance.js.map +1 -1
  163. package/package.json +8 -8
  164. package/src/agents/executor-test-helpers.ts +2 -2
  165. package/src/agents/executor-tool-dispatch.ts +26 -0
  166. package/src/agents/executor-validation.ts +7 -9
  167. package/src/agents/invocation.ts +8 -4
  168. package/src/api/agent.ts +22 -2
  169. package/src/api/agentImpl.ts +13 -0
  170. package/src/api/config-schema.ts +1 -1
  171. package/src/api/config-types.ts +1 -1
  172. package/src/api/control/sessionControl.ts +454 -57
  173. package/src/api/control/toolControl.ts +25 -16
  174. package/src/api/discovery.ts +23 -25
  175. package/src/api/event-schema.ts +2 -0
  176. package/src/api/eventAdapter.ts +1 -1
  177. package/src/app-services/command-api-map.ts +21 -0
  178. package/src/app-services/memory.ts +1 -1
  179. package/src/compression/CompressionHandler.ts +204 -44
  180. package/src/compression/HighDensityStrategy.ts +24 -34
  181. package/src/compression/MiddleOutStrategy.ts +49 -21
  182. package/src/compression/OneShotStrategy.ts +25 -9
  183. package/src/compression/TopDownTruncationStrategy.ts +24 -20
  184. package/src/compression/contextOverflowError.ts +9 -0
  185. package/src/compression/pendingContextWindowEnforcement.ts +162 -8
  186. package/src/compression/providerContentEnforcement.ts +109 -1
  187. package/src/compression/toolResultTruncator.ts +718 -0
  188. package/src/compression/utils.ts +1 -1
  189. package/src/core/ConversationManager.ts +31 -17
  190. package/src/core/MessageStreamOrchestrator.ts +38 -62
  191. package/src/core/MessageStreamTerminalHandler.ts +14 -4
  192. package/src/core/StreamProcessor.ts +28 -4
  193. package/src/core/TodoContinuationService.ts +0 -1
  194. package/src/core/TokenUsageLogger.ts +150 -0
  195. package/src/core/TurnProcessor.ts +41 -3
  196. package/src/core/agenticLoop/AgenticLoop.ts +115 -19
  197. package/src/core/agenticLoop/loopHelpers.ts +22 -1
  198. package/src/core/agenticLoop/types.ts +8 -1
  199. package/src/core/chatSession.ts +40 -0
  200. package/src/core/client-test-helpers.ts +7 -0
  201. package/src/core/client.ts +1 -1
  202. package/src/core/clientToolGovernance.ts +5 -4
  203. package/src/core/coreToolScheduler-test-helpers.ts +2 -0
  204. package/src/core/coreToolScheduler.ts +6 -6
  205. package/src/core/imagePayloadBudget.ts +162 -0
  206. package/src/core/messageStreamModelInfo.ts +84 -0
  207. package/src/core/nonInteractiveToolExecutor.ts +1 -1
  208. package/src/core/schemaDepthErrorEnrichment.ts +1 -1
  209. package/src/core/streamResponseHelpers.ts +126 -14
  210. package/src/core/streamValidationHelpers.ts +1 -1
  211. package/src/core/subagentExecution.ts +27 -14
  212. package/src/core/subagentRuntimeSetup.ts +1 -1
  213. package/src/core/subagentToolProcessing.ts +31 -3
  214. package/src/core/tokenUsageActualLogger.ts +49 -0
  215. package/src/core/tokenUsageEstimateLogger.ts +107 -0
  216. package/src/core/turn-test-helpers.ts +3 -1
  217. package/src/core/turn.ts +70 -82
  218. package/src/core/turnCitations.ts +66 -0
  219. package/src/scheduler/confirmation-coordinator.ts +2 -2
  220. package/src/scheduler/result-aggregator.ts +1 -1
  221. package/src/scheduler/status-transitions.ts +1 -1
  222. package/src/scheduler/tool-dispatcher.ts +1 -1
  223. package/src/scheduler/tool-executor.ts +4 -4
  224. package/src/tools/task.ts +97 -84
  225. package/src/tools/taskAsyncExecution.ts +12 -8
  226. package/src/tools/taskResultHelpers.ts +2 -1
  227. package/src/tools/taskToolGovernance.ts +89 -1
@@ -18,18 +18,32 @@
18
18
  * converts the loaded Content[] to IContent[] before the client restore path.
19
19
  * - Recording is backed by SessionRecordingService; setRecording(true) starts a
20
20
  * service and seeds it with the current history so a file is materialized,
21
- * setRecording(false) flushes + disposes it.
21
+ * then subscribes a RecordingIntegration to the client's HistoryService so
22
+ * EVERY subsequent turn's content is appended to the JSONL file (continuous
23
+ * recording, not a one-shot snapshot). setRecording(false) disposes the
24
+ * integration + service.
22
25
  * - resume is backed by resumeSession (CONTINUE_LATEST for 'latest'); a success
23
- * feeds the reconstructed IContent history through the client restore path and
24
- * adopts the returned recording service.
26
+ * feeds the reconstructed IContent history through the client restore path,
27
+ * adopts the returned recording service, subscribes a fresh RecordingIntegration
28
+ * so post-resume turns keep appending to the resumed file, and returns the
29
+ * restored IContent[] so callers (e.g. the Zed loadSession path) can replay it.
25
30
  */
26
31
  import { readdirSync, readFileSync, statSync } from 'node:fs';
27
- import { join } from 'node:path';
28
- import { Logger, SessionRecordingService, resumeSession, CONTINUE_LATEST, getProjectHash, } from '@vybestack/llxprt-code-core';
32
+ import { basename, join } from 'node:path';
33
+ import { Logger, SessionRecordingService, RecordingIntegration, resumeSession, CONTINUE_LATEST, } from '@vybestack/llxprt-code-core';
29
34
  import { ContentConverters } from '@vybestack/llxprt-code-core/services/history/ContentConverters.js';
35
+ import { DebugLogger } from '@vybestack/llxprt-code-core/debug/index.js';
30
36
  const CHECKPOINT_PREFIX = 'checkpoint-';
31
37
  const CHECKPOINT_SUFFIX = '.json';
32
38
  const RECORDING_FORMAT = 'jsonl';
39
+ /**
40
+ * Module logger mirroring the neighboring toolControl.ts precedent
41
+ * (a module-scoped core DebugLogger). Used to surface an otherwise-silent
42
+ * recording-subscription gap so lost continuous recording is diagnosable.
43
+ * @plan:PLAN-20260617-COREAPI.P20
44
+ * @requirement:REQ-010
45
+ */
46
+ const logger = new DebugLogger('llxprt:agents:session-control');
33
47
  export class SessionControl {
34
48
  deps;
35
49
  /**
@@ -47,6 +61,18 @@ export class SessionControl {
47
61
  * @requirement:REQ-010
48
62
  */
49
63
  recording = null;
64
+ /**
65
+ * The live RecordingIntegration bridging the client's HistoryService
66
+ * 'contentAdded'/compression events onto the active recording service, or
67
+ * null when recording is disabled. This is what makes recording CONTINUOUS
68
+ * (every subsequent turn is appended) rather than a one-shot snapshot. It is
69
+ * created + subscribed by startRecording/resume and disposed (unsubscribed)
70
+ * by releaseRecording so no history-event listener leaks past a stop/resume/
71
+ * dispose.
72
+ * @plan:PLAN-20260617-COREAPI.P20
73
+ * @requirement:REQ-010
74
+ */
75
+ integration = null;
50
76
  /**
51
77
  * The on-disk session lock acquired by a successful resume, or null when no
52
78
  * resume holds a lock. Released (and cleared) when a new resume replaces it,
@@ -55,9 +81,52 @@ export class SessionControl {
55
81
  * @requirement:REQ-010
56
82
  */
57
83
  currentLockHandle = null;
84
+ /**
85
+ * Promise-chain mutex (FINDING A1) serializing the state-mutating public
86
+ * operations (resume, setRecording enable/disable, dispose) so they never
87
+ * interleave their multi-await recording/integration/lock swaps. Without it a
88
+ * concurrent resume()/setRecording()/dispose() could adopt+dispose the same
89
+ * recording service or session lock across each other's await points
90
+ * (use-after-free / orphaned lock). runExclusive chains onto this so each op
91
+ * runs strictly after the prior one settles; it always settles (never
92
+ * rejects) so a failed op cannot poison the chain for the next caller.
93
+ * @plan:PLAN-20260617-COREAPI.P20
94
+ * @requirement:REQ-010
95
+ */
96
+ opChain = Promise.resolve();
97
+ /**
98
+ * True when {@link integration} is committed as the live integration but its
99
+ * subscription to the client HistoryService could not be established yet (the
100
+ * HistoryService was unavailable at attach time), so continuous recording is
101
+ * currently dead (FINDING A3). The next state-mutating operation re-attempts
102
+ * the subscription via {@link ensureSubscribed}; cleared once subscribed or
103
+ * when the integration is disposed.
104
+ * @plan:PLAN-20260617-COREAPI.P20
105
+ * @requirement:REQ-010
106
+ */
107
+ integrationNeedsSubscribe = false;
58
108
  constructor(deps) {
59
109
  this.deps = deps;
60
110
  }
111
+ /**
112
+ * Runs `fn` under the {@link opChain} serializer (FINDING A1) so the
113
+ * state-mutating public operations execute strictly one-at-a-time. The chain
114
+ * link is made to always settle (errors swallowed for the CHAIN only) so a
115
+ * rejected operation does not break serialization for the next caller, while
116
+ * the caller of runExclusive still receives the real result/rejection of its
117
+ * own `fn`.
118
+ * @plan:PLAN-20260617-COREAPI.P20
119
+ * @requirement:REQ-010
120
+ */
121
+ runExclusive(fn) {
122
+ const priorSettled = this.opChain;
123
+ const run = (async () => {
124
+ await priorSettled;
125
+ return fn();
126
+ })();
127
+ this.opChain = run.then(() => undefined, () => undefined);
128
+ return run;
129
+ }
61
130
  /**
62
131
  * Resumes a previously recorded session via the core resumeSession flow.
63
132
  * `target:'latest'` resolves to CONTINUE_LATEST; any other target is a
@@ -65,22 +134,74 @@ export class SessionControl {
65
134
  * core SessionDiscovery resolves). On success the returned recording service
66
135
  * is adopted as the live recording (installed on Config as the active
67
136
  * recording, same swap semantics as setRecording) and the returned session
68
- * lock is retained, both stored into the instance fields SYNCHRONOUSLY before
69
- * any await. The prior recording service and session lock are then released,
70
- * and the reconstructed IContent history is fed through the client restore
71
- * path. Adopting the resumed recording + lock before any throwable await
72
- * guarantees that if prior teardown or restoreHistory fails, the resumed
73
- * recording service and on-disk session lock remain owned by the fields and
74
- * are released by dispose()/teardownActiveSession(), so neither the prior nor
75
- * the resumed resources leak on any path. On failure a clear typed Error is
137
+ * lock is retained. The resumed resources remain local while the prior
138
+ * recording service and session lock are released and the reconstructed
139
+ * IContent history is fed through the client restore path. Only after the new
140
+ * integration subscribes successfully are the recording and lock committed to
141
+ * the instance fields; every earlier failure disposes/releases the locals, so
142
+ * neither the prior nor the resumed resources leak on any path. On failure a
143
+ * clear typed Error is
76
144
  * thrown carrying the core error (never a not-implemented signal).
145
+ *
146
+ * After the resumed history is restored into the client, a fresh
147
+ * RecordingIntegration is subscribed to the client's HistoryService so
148
+ * post-resume turns keep appending to the resumed JSONL file (continuous
149
+ * recording across the resume boundary). The prior integration (if any) is
150
+ * disposed alongside the prior recording so no history-event listener leaks.
151
+ *
152
+ * Returns the reconstructed IContent[] history so callers that need to replay
153
+ * the restored conversation (e.g. the Zed ACP loadSession path streaming
154
+ * session/update notifications) can consume it directly WITHOUT a lossy
155
+ * getHistory() Gemini Content[] round-trip. Callers that ignore the return
156
+ * value remain source-compatible.
77
157
  * @plan:PLAN-20260617-COREAPI.P20
78
158
  * @requirement:REQ-010
79
159
  */
80
160
  async resume(target, _options) {
161
+ // FINDING A1: serialize through the op-chain mutex so a concurrent
162
+ // resume/setRecording/dispose cannot interleave their multi-await
163
+ // recording/integration/lock swaps (use-after-free / orphaned lock).
164
+ return this.runExclusive(() => this.resumeInternal(target));
165
+ }
166
+ /**
167
+ * The serialized resume body (runs inside {@link runExclusive}). Ordering is
168
+ * failure-safe (FINDINGS A2/A3):
169
+ *
170
+ * 1. ensureSubscribed() first re-attempts any previously-dead integration
171
+ * subscription (A3) so a resume that follows a null-history enable does not
172
+ * start from a silently-dead recording.
173
+ * 2. resumeSession() builds the resumed recording (already seeded with the
174
+ * resumed history) + acquires its session lock. These are held in LOCALS,
175
+ * NOT committed to the instance fields yet.
176
+ * 3. The PRIOR integration is disposed (unsubscribed) BEFORE restoreHistory so
177
+ * the restoreHistory-driven 'contentAdded' events (HistoryService.addAll
178
+ * emits one per item) are NOT double-recorded into the prior file; the
179
+ * prior recording service + lock are torn down here too. A prior-teardown
180
+ * failure releases the freshly-acquired resumed resources and rethrows so
181
+ * nothing leaks (mirrors the old FINDING F7 surface-first ordering).
182
+ * 4. restoreHistory() runs with NO integration subscribed (prior disposed,
183
+ * resumed not yet subscribed) so the resumed items — already in the resumed
184
+ * recording file — are not re-recorded.
185
+ * 5. A fresh integration is built + subscribed BEFORE committing the fields /
186
+ * Config (FINDING A2, mirroring the startRecording F8 ordering). Only after
187
+ * a successful subscribe are this.recording / Config / this.integration /
188
+ * the lock committed. On subscribe failure the resumed recording + lock are
189
+ * disposed/released and the fields are left CLEANLY DISABLED (Config is NOT
190
+ * left pointing at the resumed service, no lock file leaks) — half-enabled
191
+ * recording (turns silently dropped) can no longer occur.
192
+ *
193
+ * Prior state cannot be "left intact" on a late failure because step 3 must
194
+ * tear it down early to avoid the restoreHistory double-record; the safe
195
+ * fallback is therefore a clean DISABLED state, never a stale reference to a
196
+ * disposed service/lock.
197
+ * @plan:PLAN-20260617-COREAPI.P20
198
+ * @requirement:REQ-010
199
+ */
200
+ async resumeInternal(target) {
201
+ await this.ensureSubscribed();
81
202
  const request = {
82
203
  continueRef: target === 'latest' ? CONTINUE_LATEST : target,
83
- projectHash: getProjectHash(this.deps.config.getProjectRoot()),
204
+ projectHash: this.persistenceProjectHash(),
84
205
  chatsDir: this.chatsDir(),
85
206
  currentProvider: this.deps.getProvider(),
86
207
  currentModel: this.deps.getModel(),
@@ -90,38 +211,179 @@ export class SessionControl {
90
211
  if (!result.ok) {
91
212
  throw new Error(`Failed to resume session: ${result.error}`);
92
213
  }
93
- // Capture the prior recording service + session lock, then adopt the resumed
94
- // recording + lock into the instance fields (and install the recording on
95
- // Config) SYNCHRONOUSLY — before any await. Adopting before any throwable
96
- // await guarantees the resumed recording service and on-disk session lock are
97
- // owned by the fields on every subsequent throw path (prior-resource teardown
98
- // OR restoreHistory), so dispose()/teardownActiveSession() can always release
99
- // them and neither the prior nor the resumed resources can leak.
100
- const priorRecording = this.recording;
101
- const priorLockHandle = this.currentLockHandle;
214
+ // Tear down the prior recording/integration/lock BEFORE restoreHistory (see
215
+ // step 3 in the doc). On a prior-teardown failure, release the freshly
216
+ // acquired resumed resources (still only in locals) and rethrow so neither
217
+ // the prior nor the resumed resources leak, ending cleanly disabled.
218
+ try {
219
+ await this.teardownPriorBeforeResume();
220
+ }
221
+ catch (error) {
222
+ await this.disposeServiceQuietly(result.recording);
223
+ await this.releaseLockQuietly(result.lockHandle);
224
+ throw error;
225
+ }
226
+ // restoreHistory with NO integration subscribed (no double-record). On
227
+ // failure the resumed resources are released and state stays disabled.
228
+ try {
229
+ await this.deps.resolveClient().restoreHistory(result.history);
230
+ }
231
+ catch (error) {
232
+ await this.disposeServiceQuietly(result.recording);
233
+ await this.releaseLockQuietly(result.lockHandle);
234
+ throw error;
235
+ }
236
+ // FINDING A2: subscribe BEFORE committing. On subscribe failure dispose the
237
+ // integration + resumed recording, release the resumed lock, and rethrow —
238
+ // the fields/Config are never pointed at a non-integrated resumed service.
239
+ const integration = new RecordingIntegration(result.recording);
240
+ let subscribed;
241
+ try {
242
+ subscribed = this.attachIntegrationToHistory(integration);
243
+ }
244
+ catch (error) {
245
+ this.disposeIntegrationQuietly(integration);
246
+ await this.disposeServiceQuietly(result.recording);
247
+ await this.releaseLockQuietly(result.lockHandle);
248
+ throw error;
249
+ }
250
+ // Commit the resumed resources only now that the integration is live.
102
251
  this.recording = result.recording;
103
252
  this.deps.config.setSessionRecordingService(result.recording);
253
+ this.integration = integration;
254
+ this.integrationNeedsSubscribe = !subscribed;
104
255
  this.currentLockHandle = result.lockHandle;
105
- // Release the prior recording service + session lock now that the resumed
106
- // resources are owned. The captured prior locals are disposed/released
107
- // directly (NOT via releaseRecording/releaseLockHandle, which act on the
108
- // fields that now hold the resumed resources). Each step is guarded so a
109
- // single prior-teardown failure does not skip the other; a collected failure
110
- // is surfaced after the resumed history is restored.
111
- const teardownErrors = [];
112
- await this.guard(teardownErrors, async () => {
256
+ return result.history;
257
+ }
258
+ /**
259
+ * Disposes the prior integration (unsubscribing it so an imminent
260
+ * restoreHistory does not double-record into the prior file), then disposes
261
+ * the prior recording service and releases the prior session lock, clearing
262
+ * all three fields. Each step is guarded so a single failure does not skip the
263
+ * others; the first collected failure is rethrown so the caller (resumeInternal)
264
+ * can release the freshly acquired resumed resources and surface the failure.
265
+ * The fields are cleared to null up front so that even on a partial-teardown
266
+ * throw no field is left referencing a disposed/released resource.
267
+ * @plan:PLAN-20260617-COREAPI.P20
268
+ * @requirement:REQ-010
269
+ */
270
+ async teardownPriorBeforeResume() {
271
+ const priorRecording = this.recording;
272
+ const priorIntegration = this.integration;
273
+ const priorLockHandle = this.currentLockHandle;
274
+ this.recording = null;
275
+ this.integration = null;
276
+ this.integrationNeedsSubscribe = false;
277
+ this.currentLockHandle = null;
278
+ this.deps.config.setSessionRecordingService(undefined);
279
+ const errors = [];
280
+ if (priorIntegration !== null) {
281
+ this.guardSync(errors, () => priorIntegration.dispose());
282
+ }
283
+ await this.guard(errors, async () => {
113
284
  if (priorRecording !== null) {
114
285
  await priorRecording.dispose();
115
286
  }
116
287
  });
117
- await this.guard(teardownErrors, async () => {
288
+ await this.guard(errors, async () => {
118
289
  if (priorLockHandle !== null) {
119
290
  await priorLockHandle.release();
120
291
  }
121
292
  });
122
- await this.deps.resolveClient().restoreHistory(result.history);
123
- if (teardownErrors.length > 0) {
124
- throw teardownErrors[0];
293
+ if (errors.length > 0) {
294
+ throw errors[0];
295
+ }
296
+ }
297
+ /**
298
+ * Re-attempts a previously-deferred integration subscription (FINDING A3).
299
+ * When a prior startRecording/resume committed an integration but could not
300
+ * subscribe it (the client HistoryService was unavailable at attach time,
301
+ * leaving continuous recording dead), the next state-mutating operation calls
302
+ * this at its start (inside {@link runExclusive}) to re-attach it now that the
303
+ * HistoryService may exist. No-op when nothing is pending or the service is
304
+ * still unavailable (the flag is kept for a later attempt). A subscribe throw
305
+ * is self-healing: the dead integration is disposed + cleared and the flag
306
+ * reset so the operation can proceed to build a fresh subscription rather than
307
+ * failing permanently on a poisoned listener.
308
+ * @plan:PLAN-20260617-COREAPI.P20
309
+ * @requirement:REQ-010
310
+ */
311
+ async ensureSubscribed() {
312
+ if (!this.integrationNeedsSubscribe) {
313
+ return;
314
+ }
315
+ const integration = this.integration;
316
+ if (integration === null) {
317
+ this.integrationNeedsSubscribe = false;
318
+ return;
319
+ }
320
+ const historyService = this.deps.resolveClient().getHistoryService();
321
+ if (historyService === null) {
322
+ return;
323
+ }
324
+ try {
325
+ integration.subscribeToHistory(historyService);
326
+ this.integrationNeedsSubscribe = false;
327
+ }
328
+ catch (error) {
329
+ const deadRecording = this.recording;
330
+ const deadLockHandle = this.currentLockHandle;
331
+ this.recording = null;
332
+ this.integration = null;
333
+ this.integrationNeedsSubscribe = false;
334
+ this.currentLockHandle = null;
335
+ this.deps.config.setSessionRecordingService(undefined);
336
+ this.disposeIntegrationQuietly(integration);
337
+ if (deadRecording !== null) {
338
+ await this.disposeServiceQuietly(deadRecording);
339
+ }
340
+ if (deadLockHandle !== null) {
341
+ await this.releaseLockQuietly(deadLockHandle);
342
+ }
343
+ logger.warn(() => `ensureSubscribed: re-attach failed for session ${this.deps.sessionId()}; ` +
344
+ `dropped the dead integration so the operation can rebuild it: ${error instanceof Error ? error.message : String(error)}`);
345
+ throw error;
346
+ }
347
+ }
348
+ /** Best-effort integration dispose for failure/rollback paths. */
349
+ disposeIntegrationQuietly(integration) {
350
+ try {
351
+ integration.dispose();
352
+ }
353
+ catch {
354
+ // Best-effort: the triggering error is rethrown by the caller.
355
+ }
356
+ }
357
+ /**
358
+ * Best-effort dispose of a recording service on a resume failure/rollback
359
+ * path, swallowing any dispose error (the original failure is the one to
360
+ * surface). Used only for the freshly acquired resumed service that is NOT yet
361
+ * committed to the instance fields.
362
+ * @plan:PLAN-20260617-COREAPI.P20
363
+ * @requirement:REQ-010
364
+ */
365
+ async disposeServiceQuietly(service) {
366
+ try {
367
+ await service.dispose();
368
+ }
369
+ catch {
370
+ // Best-effort: the triggering error is rethrown by the caller.
371
+ }
372
+ }
373
+ /**
374
+ * Best-effort release of a session lock on a resume failure/rollback path,
375
+ * swallowing any release error. Used only for the freshly acquired resumed
376
+ * lock that is NOT yet committed to the instance fields, so the on-disk lock
377
+ * file is removed even when the resume is aborted.
378
+ * @plan:PLAN-20260617-COREAPI.P20
379
+ * @requirement:REQ-010
380
+ */
381
+ async releaseLockQuietly(handle) {
382
+ try {
383
+ await handle.release();
384
+ }
385
+ catch {
386
+ // Best-effort: the triggering error is rethrown by the caller.
125
387
  }
126
388
  }
127
389
  /**
@@ -202,11 +464,16 @@ export class SessionControl {
202
464
  * @requirement:REQ-010
203
465
  */
204
466
  async setRecording(state) {
205
- if (state.enabled) {
206
- await this.startRecording();
207
- return;
208
- }
209
- await this.stopRecording();
467
+ // FINDING A1: serialize enable/disable through the op-chain mutex so they
468
+ // never interleave with a concurrent resume()/dispose() (crossed
469
+ // recording/lock state).
470
+ await this.runExclusive(async () => {
471
+ if (state.enabled) {
472
+ await this.startRecording();
473
+ return;
474
+ }
475
+ await this.stopRecording();
476
+ });
210
477
  }
211
478
  /**
212
479
  * Returns the current recording state. enabled reflects the live service's
@@ -228,21 +495,43 @@ export class SessionControl {
228
495
  // ─── Recording helpers ───────────────────────────────────────────────────
229
496
  /**
230
497
  * Starts a fresh recording service for this session, replacing any prior one
231
- * (the prior service is flushed + disposed first). The current history is
232
- * recorded as content events so the file materializes and getRecording().path
233
- * is defined. The freshly built service is installed on Config via
234
- * setSessionRecordingService so the rest of the system (which reads the active
235
- * recording via config.getSessionRecordingService) observes the swap.
498
+ * (the prior service + integration are flushed + disposed first). The current
499
+ * history is recorded as content events so the file materializes and
500
+ * getRecording().path is defined. The freshly built service is installed on
501
+ * Config via setSessionRecordingService so the rest of the system (which reads
502
+ * the active recording via config.getSessionRecordingService) observes the
503
+ * swap. A RecordingIntegration is then subscribed to the client's
504
+ * HistoryService so EVERY subsequent turn's 'contentAdded' event is appended
505
+ * to the JSONL file — this is what makes recording continuous rather than a
506
+ * one-shot snapshot.
507
+ *
508
+ * HistoryService availability: the agents-package client eagerly creates +
509
+ * stores a HistoryService at construction (storeHistoryServiceForReuse) and
510
+ * reuses that SAME instance across turns (createChatSessionSafe reuses the
511
+ * stored service), so getHistoryService() is non-null here and the single
512
+ * subscription established now captures all future turns. If it is
513
+ * nonetheless null at this moment (no client/chat), the integration is still
514
+ * created and Config still owns the service; the subscription is deferred
515
+ * (integrationNeedsSubscribe) and the next startRecording/resume re-attempts
516
+ * it via {@link ensureSubscribed} (FINDING A3).
517
+ *
518
+ * Called only from within {@link runExclusive} (via setRecording), so it is
519
+ * already serialized against resume/dispose.
236
520
  * @plan:PLAN-20260617-COREAPI.P20
237
521
  * @requirement:REQ-010
238
522
  */
239
523
  async startRecording() {
524
+ // FINDING A3: re-attach any previously-dead integration before replacing it,
525
+ // so a pending-subscribe flag from an earlier null-history enable does not
526
+ // survive across the fresh service swap.
527
+ await this.ensureSubscribed();
240
528
  await this.stopRecording();
241
529
  const service = new SessionRecordingService({
242
530
  sessionId: this.deps.sessionId(),
243
- projectHash: getProjectHash(this.deps.config.getProjectRoot()),
531
+ projectHash: this.persistenceProjectHash(),
244
532
  chatsDir: this.chatsDir(),
245
533
  workspaceDirs: this.workspaceDirs(),
534
+ cwd: this.deps.config.getProjectRoot(),
246
535
  provider: this.deps.getProvider(),
247
536
  model: this.deps.getModel(),
248
537
  });
@@ -251,8 +540,56 @@ export class SessionControl {
251
540
  service.recordContent(item);
252
541
  }
253
542
  await service.flush();
543
+ // FINDING F8: build + subscribe the integration BEFORE committing
544
+ // this.recording and the Config recording service, so a subscribe failure
545
+ // cannot leave recording PARTIALLY enabled (fields/Config set with no live
546
+ // integration). On failure dispose the integration AND the freshly built
547
+ // service (neither is referenced by any field yet) and rethrow; the instance
548
+ // fields stay untouched so recording remains cleanly disabled.
549
+ const integration = new RecordingIntegration(service);
550
+ let subscribed;
551
+ try {
552
+ subscribed = this.attachIntegrationToHistory(integration);
553
+ }
554
+ catch (error) {
555
+ this.disposeIntegrationQuietly(integration);
556
+ await this.disposeServiceQuietly(service);
557
+ throw error;
558
+ }
254
559
  this.recording = service;
255
560
  this.deps.config.setSessionRecordingService(service);
561
+ this.integration = integration;
562
+ // FINDING A3: when the HistoryService was unavailable the integration is
563
+ // committed but dead; flag it so a later operation re-attaches it rather
564
+ // than leaving continuous recording permanently off.
565
+ this.integrationNeedsSubscribe = !subscribed;
566
+ }
567
+ /**
568
+ * Subscribes `integration` to the client's HistoryService so future
569
+ * 'contentAdded'/compression events are appended continuously; when no
570
+ * HistoryService is available yet the integration is left unsubscribed and a
571
+ * warning is logged (a later start/resume re-attempts the subscription via
572
+ * {@link ensureSubscribed}, FINDING A3). Pure attach step shared by
573
+ * startRecording and resumeInternal; it commits NO instance state so callers
574
+ * control ownership/rollback. Returns true when the subscription was
575
+ * established, false when it was deferred (no HistoryService yet) so the
576
+ * caller can set integrationNeedsSubscribe.
577
+ * @plan:PLAN-20260617-COREAPI.P20
578
+ * @requirement:REQ-010
579
+ */
580
+ attachIntegrationToHistory(integration) {
581
+ const historyService = this.deps.resolveClient().getHistoryService();
582
+ if (historyService !== null) {
583
+ integration.subscribeToHistory(historyService);
584
+ return true;
585
+ }
586
+ // No HistoryService yet: the integration is left unsubscribed, so NO
587
+ // subsequent turn is appended until a later start/resume re-attempts the
588
+ // subscription. Left silent this is an invisible continuous-recording
589
+ // loss; warn so it is diagnosable AND flag it for bounded re-attach.
590
+ logger.warn(() => `attachIntegrationToHistory: HistoryService unavailable for session ${this.deps.sessionId()}; ` +
591
+ `recording integration left unsubscribed (subsequent turns will not be recorded until re-subscribed)`);
592
+ return false;
256
593
  }
257
594
  /**
258
595
  * Flushes + disposes the live recording service (if any), clears it from
@@ -266,19 +603,33 @@ export class SessionControl {
266
603
  await this.teardownActiveSession();
267
604
  }
268
605
  /**
269
- * Disposes the live recording service (if any), clears the private field, and
270
- * clears it from Config. No-op when no recording is active.
606
+ * Disposes the live RecordingIntegration (unsubscribing its HistoryService
607
+ * listeners) and the live recording service (if any), clears the private
608
+ * fields, and clears the service from Config. The integration is disposed
609
+ * FIRST so no 'contentAdded' event can reach a service mid-disposal. No-op
610
+ * when no recording is active.
271
611
  * @plan:PLAN-20260617-COREAPI.P20
272
612
  * @requirement:REQ-010
273
613
  */
274
614
  async releaseRecording() {
615
+ const integration = this.integration;
275
616
  const service = this.recording;
276
- if (service === null) {
277
- return;
278
- }
617
+ this.integration = null;
618
+ this.integrationNeedsSubscribe = false;
279
619
  this.recording = null;
280
620
  this.deps.config.setSessionRecordingService(undefined);
281
- await service.dispose();
621
+ const errors = [];
622
+ if (integration !== null) {
623
+ this.guardSync(errors, () => integration.dispose());
624
+ }
625
+ await this.guard(errors, async () => {
626
+ if (service !== null) {
627
+ await service.dispose();
628
+ }
629
+ });
630
+ if (errors.length > 0) {
631
+ throw errors[0];
632
+ }
282
633
  }
283
634
  /**
284
635
  * Releases the on-disk session lock held by a prior resume (if any) and clears
@@ -308,6 +659,21 @@ export class SessionControl {
308
659
  errors.push(e);
309
660
  }
310
661
  }
662
+ /**
663
+ * Synchronous variant of {@link guard} for non-awaitable teardown/subscription
664
+ * steps (integration dispose/subscribe) so a single failure is collected
665
+ * rather than short-circuiting the remaining steps.
666
+ * @plan:PLAN-20260617-COREAPI.P20
667
+ * @requirement:REQ-010
668
+ */
669
+ guardSync(errors, fn) {
670
+ try {
671
+ fn();
672
+ }
673
+ catch (e) {
674
+ errors.push(e);
675
+ }
676
+ }
311
677
  // ─── Surface teardown ──────────────────────────────────────────────────────
312
678
  /**
313
679
  * Disposes the active recording service (if any) and releases the held
@@ -318,7 +684,10 @@ export class SessionControl {
318
684
  * @requirement:REQ-010
319
685
  */
320
686
  async dispose() {
321
- await this.teardownActiveSession();
687
+ // FINDING A1: serialize teardown through the op-chain mutex so dispose never
688
+ // races a concurrent resume()/setRecording() adopting resources it is
689
+ // releasing (double-dispose / released-then-adopted lock).
690
+ await this.runExclusive(() => this.teardownActiveSession());
322
691
  }
323
692
  /**
324
693
  * Releases the active recording service and the held session lock, guarding
@@ -432,15 +801,20 @@ export class SessionControl {
432
801
  return [];
433
802
  }
434
803
  }
804
+ persistenceProjectHash() {
805
+ return basename(this.deps.config.storage.getProjectTempDir());
806
+ }
435
807
  // ─── Path derivation ─────────────────────────────────────────────────────
436
808
  /**
437
- * Derives the chats directory (where session recordings live) from the
438
- * project storage temp dir, matching the CLI's derivation.
809
+ * The chats directory (where session recordings live), delegated to
810
+ * Storage.getProjectChatsDir() — the single source of truth every
811
+ * reader/prober shares, so the recording writer and the probes can never
812
+ * drift apart on the location.
439
813
  * @plan:PLAN-20260617-COREAPI.P20
440
814
  * @requirement:REQ-010
441
815
  */
442
816
  chatsDir() {
443
- return join(this.deps.config.storage.getProjectTempDir(), 'chats');
817
+ return this.deps.config.storage.getProjectChatsDir();
444
818
  }
445
819
  /**
446
820
  * Returns the workspace directories from the live workspace context.