@moxt-ai/mobius 0.0.125 → 0.0.126

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.
@@ -1,4 +1,6 @@
1
1
  import { AcpProcessSession } from "./process-session.js";
2
+ import { RetainedSessions } from "./retained-sessions.js";
3
+ import { SessionExecutions } from "./session-executions.js";
2
4
  export { createWritableAcpStream } from "./process-endpoint.js";
3
5
  import { unmeasuredOperationMetrics } from "../infra/operation-metrics.js";
4
6
  import { isNativeChatSessionId } from "../native-sessions/chat-agent.js";
@@ -11,18 +13,16 @@ export { AcpAgentSettingsSnapshot, AcpPreparedSession, NullAcpSessionObserver, }
11
13
  import { AcpAgentSettingsSnapshot, NullAcpSessionObserver, } from "./session-contracts.js";
12
14
  export class AcpSessionManager {
13
15
  #processes = new AcpProcessPool();
14
- #activeCommandIds = new Map();
16
+ #sessions = new RetainedSessions({ touch: this.#processes.touch, changed: this.#processes.notifyChanged });
17
+ #nativeBrowserSessions = new RetainedSessions({
18
+ touch: this.#processes.touch,
19
+ changed: this.#processes.notifyChanged,
20
+ });
21
+ #executions = new SessionExecutions();
15
22
  #agentSettingsObserver = new NullAcpSessionObserver();
16
23
  #nativeOperations = new Set();
17
24
  #nativeBrowserObserver = new NullAcpSessionObserver();
18
- #nativeBrowserPreparing = new Map();
19
- #nativeBrowserSessions = new Map();
20
25
  #nativeBrowserStore = new MemoryAcpSessionStore();
21
- #nativeBrowserUseCounts = new Map();
22
- #cancellationRequests = new Map();
23
- #preparing = new Map();
24
- #sessionUseCounts = new Map();
25
- #sessions = new Map();
26
26
  #store;
27
27
  #nativeHistoryReader;
28
28
  #sessionIdentity;
@@ -36,62 +36,6 @@ export class AcpSessionManager {
36
36
  setObserver = (observer) => {
37
37
  this.#observer = observer;
38
38
  };
39
- #touchSession(sessionId) {
40
- const runtime = this.#sessions.get(sessionId);
41
- if (runtime === undefined) {
42
- return;
43
- }
44
- this.#processes.touch(runtime);
45
- }
46
- #touchExpectedSession(sessionId, expected) {
47
- if (this.#sessions.get(sessionId) !== expected) {
48
- return;
49
- }
50
- this.#processes.touch(expected);
51
- }
52
- #touchNativeBrowserSession(sessionId) {
53
- const runtime = this.#nativeBrowserSessions.get(sessionId);
54
- if (runtime === undefined) {
55
- return;
56
- }
57
- this.#processes.touch(runtime);
58
- }
59
- #touchExpectedNativeBrowserSession(sessionId, expected) {
60
- if (this.#nativeBrowserSessions.get(sessionId) !== expected) {
61
- return;
62
- }
63
- this.#processes.touch(expected);
64
- }
65
- #beginSessionUse(sessionId) {
66
- this.#sessionUseCounts.set(sessionId, (this.#sessionUseCounts.get(sessionId) ?? 0) + 1);
67
- this.#touchSession(sessionId);
68
- }
69
- #endSessionUse(sessionId) {
70
- const count = this.#sessionUseCounts.get(sessionId) ?? 0;
71
- if (count <= 1) {
72
- this.#sessionUseCounts.delete(sessionId);
73
- }
74
- else {
75
- this.#sessionUseCounts.set(sessionId, count - 1);
76
- }
77
- this.#touchSession(sessionId);
78
- this.#processes.notifyChanged();
79
- }
80
- #beginNativeBrowserUse(sessionId) {
81
- this.#nativeBrowserUseCounts.set(sessionId, (this.#nativeBrowserUseCounts.get(sessionId) ?? 0) + 1);
82
- this.#touchNativeBrowserSession(sessionId);
83
- }
84
- #endNativeBrowserUse(sessionId) {
85
- const count = this.#nativeBrowserUseCounts.get(sessionId) ?? 0;
86
- if (count <= 1) {
87
- this.#nativeBrowserUseCounts.delete(sessionId);
88
- }
89
- else {
90
- this.#nativeBrowserUseCounts.set(sessionId, count - 1);
91
- }
92
- this.#touchNativeBrowserSession(sessionId);
93
- this.#processes.notifyChanged();
94
- }
95
39
  #isNativeSessionOperationActive(sessionId) {
96
40
  const stored = this.#store.read(sessionId);
97
41
  return (stored instanceof FoundAcpStoredSession &&
@@ -100,24 +44,19 @@ export class AcpSessionManager {
100
44
  #retention(sessionId, kind) {
101
45
  if (kind === "execution") {
102
46
  return {
103
- isBusy: () => this.#activeCommandIds.has(sessionId) ||
104
- this.#cancellationRequests.has(sessionId) ||
105
- this.#preparing.has(sessionId) ||
106
- (this.#sessionUseCounts.get(sessionId) ?? 0) > 0 ||
47
+ isBusy: () => this.#executions.isBusy(sessionId) ||
48
+ this.#sessions.isBusy(sessionId) ||
107
49
  this.#isNativeSessionOperationActive(sessionId),
108
50
  retire: (runtime) => this.#retireSessionProcess(sessionId, runtime, () => runtime.close()),
109
51
  };
110
52
  }
111
53
  return {
112
- isBusy: () => this.#nativeBrowserPreparing.has(sessionId) || (this.#nativeBrowserUseCounts.get(sessionId) ?? 0) > 0,
54
+ isBusy: () => this.#nativeBrowserSessions.isBusy(sessionId),
113
55
  retire: (runtime) => this.#retireNativeBrowserProcess(sessionId, runtime, () => runtime.close()),
114
56
  };
115
57
  }
116
58
  async #retireSessionProcess(sessionId, runtime, close) {
117
- const retained = this.#sessions.get(sessionId) === runtime;
118
- if (retained) {
119
- this.#sessions.delete(sessionId);
120
- }
59
+ const retained = this.#sessions.detach(sessionId, runtime);
121
60
  try {
122
61
  await this.#processes.retire(runtime, close);
123
62
  }
@@ -132,134 +71,93 @@ export class AcpSessionManager {
132
71
  }
133
72
  }
134
73
  async #retireNativeBrowserProcess(sessionId, runtime, close) {
135
- const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
74
+ const retained = this.#nativeBrowserSessions.detach(sessionId, runtime);
136
75
  if (retained) {
137
- this.#nativeBrowserSessions.delete(sessionId);
138
76
  this.#nativeBrowserStore.remove(sessionId);
139
77
  }
140
78
  await this.#processes.retire(runtime, close);
141
79
  }
142
80
  async #startRetainedSessionProcess(options, start) {
143
81
  const runtime = await this.#processes.startRetained(options.signal, start, this.#retention(options.sessionId, "execution"));
144
- this.#sessions.set(options.sessionId, runtime);
82
+ this.#sessions.retain(options.sessionId, runtime);
145
83
  return runtime;
146
84
  }
147
85
  async #startRetainedNativeBrowserProcess(options, start) {
148
86
  const runtime = await this.#processes.startRetained(options.signal, start, this.#retention(options.sessionId, "browser"));
149
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
87
+ this.#nativeBrowserSessions.retain(options.sessionId, runtime);
150
88
  return runtime;
151
89
  }
152
90
  async #startNativeBrowserPreparation(options) {
153
- const operation = (async () => {
154
- try {
155
- return await this.#startRetainedNativeBrowserProcess(options, async () => await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, this.#nativeBrowserStore));
156
- }
157
- finally {
158
- this.#nativeBrowserPreparing.delete(options.sessionId);
159
- this.#processes.notifyChanged();
160
- }
161
- })();
162
- this.#nativeBrowserPreparing.set(options.sessionId, operation);
163
- return await operation;
91
+ return await this.#nativeBrowserSessions.prepare(options.sessionId, async () => {
92
+ return await this.#startRetainedNativeBrowserProcess(options, async () => await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, this.#nativeBrowserStore));
93
+ });
164
94
  }
165
95
  async #replaceNativeBrowserPreparation(existing, options) {
166
- const operation = (async () => {
167
- try {
168
- await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
169
- return await this.#startRetainedNativeBrowserProcess(options, async () => await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, this.#nativeBrowserStore));
170
- }
171
- finally {
172
- this.#nativeBrowserPreparing.delete(options.sessionId);
173
- this.#processes.notifyChanged();
174
- }
175
- })();
176
- this.#nativeBrowserPreparing.set(options.sessionId, operation);
177
- return await operation;
96
+ return await this.#nativeBrowserSessions.prepare(options.sessionId, async () => {
97
+ await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
98
+ return await this.#startRetainedNativeBrowserProcess(options, async () => await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, this.#nativeBrowserStore));
99
+ });
178
100
  }
179
101
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
180
- const operation = (async () => {
181
- try {
182
- return await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options.origin === undefined &&
183
- this.#sessionIdentity === "native" &&
184
- isNativeChatSessionId(options.agent.id, options.sessionId) &&
185
- this.#store.read(options.sessionId) instanceof MissingAcpStoredSession
186
- ? { ...options, origin: { kind: "import", nativeSessionId: options.sessionId } }
187
- : options, () => this.#observer, this.#store, metrics));
188
- }
189
- finally {
190
- this.#preparing.delete(options.sessionId);
191
- this.#processes.notifyChanged();
192
- }
193
- })();
194
- this.#preparing.set(options.sessionId, operation);
195
- return await operation;
102
+ return await this.#sessions.prepare(options.sessionId, async () => {
103
+ return await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options.origin === undefined &&
104
+ this.#sessionIdentity === "native" &&
105
+ isNativeChatSessionId(options.agent.id, options.sessionId) &&
106
+ this.#store.read(options.sessionId) instanceof MissingAcpStoredSession
107
+ ? { ...options, origin: { kind: "import", nativeSessionId: options.sessionId } }
108
+ : options, () => this.#observer, this.#store, metrics));
109
+ });
196
110
  }
197
111
  async #replacePreparation(existing, options, metrics) {
198
- const operation = (async () => {
199
- try {
200
- await this.#retireSessionProcess(options.sessionId, existing, async () => await metrics.measure("runtime-replacement-close", async () => await existing.close()));
201
- this.#store.remove(options.sessionId);
202
- return await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics));
203
- }
204
- finally {
205
- this.#preparing.delete(options.sessionId);
206
- this.#processes.notifyChanged();
207
- }
208
- })();
209
- this.#preparing.set(options.sessionId, operation);
210
- return await operation;
112
+ return await this.#sessions.prepare(options.sessionId, async () => {
113
+ await this.#retireSessionProcess(options.sessionId, existing, async () => await metrics.measure("runtime-replacement-close", async () => await existing.close()));
114
+ this.#store.remove(options.sessionId);
115
+ return await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics));
116
+ });
211
117
  }
212
118
  async #replaceExecutionPreparation(existing, options) {
213
119
  const desiredConfigOptions = existing.prepared().configOptions;
214
- const operation = (async () => {
120
+ return await this.#sessions.prepare(options.sessionId, async () => {
121
+ await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
122
+ const runtime = await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options, () => this.#observer, this.#store));
215
123
  try {
216
- await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
217
- const runtime = await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options, () => this.#observer, this.#store));
218
- try {
219
- for (const desired of desiredConfigOptions) {
220
- const current = runtime.prepared().configOptions.find((option) => option.id === desired.id);
221
- if (current === undefined || current.type !== desired.type) {
222
- continue;
223
- }
224
- if (desired.type === "boolean") {
225
- if (current.booleanValue !== desired.booleanValue) {
226
- await runtime.configure({
227
- ...options,
228
- booleanValue: desired.booleanValue,
229
- configId: desired.id,
230
- requestId: `execution-prepare-${desired.id}`,
231
- value: "",
232
- valueType: "boolean",
233
- });
234
- }
235
- continue;
236
- }
237
- if (current.currentValue !== desired.currentValue &&
238
- current.values.some((value) => value.value === desired.currentValue)) {
124
+ for (const desired of desiredConfigOptions) {
125
+ const current = runtime.prepared().configOptions.find((option) => option.id === desired.id);
126
+ if (current === undefined || current.type !== desired.type) {
127
+ continue;
128
+ }
129
+ if (desired.type === "boolean") {
130
+ if (current.booleanValue !== desired.booleanValue) {
239
131
  await runtime.configure({
240
132
  ...options,
241
- booleanValue: false,
133
+ booleanValue: desired.booleanValue,
242
134
  configId: desired.id,
243
135
  requestId: `execution-prepare-${desired.id}`,
244
- value: desired.currentValue,
245
- valueType: "select",
136
+ value: "",
137
+ valueType: "boolean",
246
138
  });
247
139
  }
140
+ continue;
141
+ }
142
+ if (current.currentValue !== desired.currentValue &&
143
+ current.values.some((value) => value.value === desired.currentValue)) {
144
+ await runtime.configure({
145
+ ...options,
146
+ booleanValue: false,
147
+ configId: desired.id,
148
+ requestId: `execution-prepare-${desired.id}`,
149
+ value: desired.currentValue,
150
+ valueType: "select",
151
+ });
248
152
  }
249
153
  }
250
- catch (error) {
251
- await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
252
- throw error;
253
- }
254
- return runtime;
255
154
  }
256
- finally {
257
- this.#preparing.delete(options.sessionId);
258
- this.#processes.notifyChanged();
155
+ catch (error) {
156
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
157
+ throw error;
259
158
  }
260
- })();
261
- this.#preparing.set(options.sessionId, operation);
262
- return await operation;
159
+ return runtime;
160
+ });
263
161
  }
264
162
  prepareSession = async (options, metrics = unmeasuredOperationMetrics) => {
265
163
  const stored = metrics.measureSync("session-state-read", () => this.#store.read(options.sessionId));
@@ -270,11 +168,11 @@ export class AcpSessionManager {
270
168
  this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`)) {
271
169
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
272
170
  }
273
- const pending = this.#preparing.get(options.sessionId);
171
+ const pending = this.#sessions.pending(options.sessionId);
274
172
  if (pending !== undefined) {
275
173
  const runtime = await metrics.measure("session-preparation-wait", async () => await pending);
276
174
  if (runtime.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
277
- this.#touchExpectedSession(options.sessionId, runtime);
175
+ this.#sessions.touch(options.sessionId, runtime);
278
176
  return runtime.prepared();
279
177
  }
280
178
  return await this.prepareSession(options, metrics);
@@ -282,7 +180,7 @@ export class AcpSessionManager {
282
180
  const existing = this.#sessions.get(options.sessionId);
283
181
  if (existing !== undefined) {
284
182
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
285
- this.#touchExpectedSession(options.sessionId, existing);
183
+ this.#sessions.touch(options.sessionId, existing);
286
184
  return existing.prepared();
287
185
  }
288
186
  if (!existing.canRebind()) {
@@ -323,11 +221,11 @@ export class AcpSessionManager {
323
221
  * Use inspectAgentSettings for Agent-scoped settings discovery.
324
222
  */
325
223
  inspectSession = async (options, metrics = unmeasuredOperationMetrics) => {
326
- if (this.#preparing.has(options.sessionId) || this.#sessions.has(options.sessionId)) {
224
+ if (this.#sessions.pending(options.sessionId) !== undefined ||
225
+ this.#sessions.get(options.sessionId) !== undefined) {
327
226
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
328
227
  }
329
- this.#beginSessionUse(options.sessionId);
330
- try {
228
+ return await this.#sessions.use(options.sessionId, async () => {
331
229
  const runtime = await this.#startPreparation(options, metrics);
332
230
  try {
333
231
  return runtime.prepared();
@@ -340,13 +238,10 @@ export class AcpSessionManager {
340
238
  this.#store.remove(options.sessionId);
341
239
  }
342
240
  }
343
- }
344
- finally {
345
- this.#endSessionUse(options.sessionId);
346
- }
241
+ });
347
242
  };
348
243
  prepareExecutionSession = async (options) => {
349
- const pending = this.#preparing.get(options.sessionId);
244
+ const pending = this.#sessions.pending(options.sessionId);
350
245
  if (pending !== undefined) {
351
246
  await pending;
352
247
  return await this.prepareExecutionSession(options);
@@ -359,7 +254,7 @@ export class AcpSessionManager {
359
254
  throw new AcpExecutionError("The agent or workspace cannot change after a conversation has started", {}, "session_identity_mismatch");
360
255
  }
361
256
  if (existing.usesEnvironment(options.agent.environment)) {
362
- this.#touchExpectedSession(options.sessionId, existing);
257
+ this.#sessions.touch(options.sessionId, existing);
363
258
  return existing.prepared();
364
259
  }
365
260
  if (existing.hasRunningTurn()) {
@@ -368,11 +263,11 @@ export class AcpSessionManager {
368
263
  return (await this.#replaceExecutionPreparation(existing, options)).prepared();
369
264
  };
370
265
  prepareNativeSessionBrowser = async (options) => {
371
- const pending = this.#nativeBrowserPreparing.get(options.sessionId);
266
+ const pending = this.#nativeBrowserSessions.pending(options.sessionId);
372
267
  if (pending !== undefined) {
373
268
  const runtime = await pending;
374
269
  if (runtime.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
375
- this.#touchExpectedNativeBrowserSession(options.sessionId, runtime);
270
+ this.#nativeBrowserSessions.touch(options.sessionId, runtime);
376
271
  return runtime.prepared();
377
272
  }
378
273
  return await this.prepareNativeSessionBrowser(options);
@@ -380,7 +275,7 @@ export class AcpSessionManager {
380
275
  const existing = this.#nativeBrowserSessions.get(options.sessionId);
381
276
  if (existing !== undefined) {
382
277
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
383
- this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
278
+ this.#nativeBrowserSessions.touch(options.sessionId, existing);
384
279
  return existing.prepared();
385
280
  }
386
281
  if (!existing.canRebind()) {
@@ -393,47 +288,35 @@ export class AcpSessionManager {
393
288
  return runtime.prepared();
394
289
  };
395
290
  configureSession = async (options) => {
396
- this.#beginSessionUse(options.sessionId);
397
- try {
291
+ return await this.#sessions.use(options.sessionId, async () => {
398
292
  const runtime = await this.ensureSession(options);
399
293
  return await runtime.configure(options);
400
- }
401
- finally {
402
- this.#endSessionUse(options.sessionId);
403
- }
294
+ });
404
295
  };
405
296
  cancelPrompt = async (sessionId) => {
406
- const existing = this.#cancellationRequests.get(sessionId);
407
- if (existing !== undefined) {
408
- await existing;
409
- return;
410
- }
411
- const cancellation = (async () => {
297
+ await this.#executions.cancel(sessionId, async () => {
412
298
  const runtime = this.#sessions.get(sessionId);
413
299
  if (runtime !== undefined) {
414
300
  try {
415
301
  await runtime.cancel();
416
302
  }
417
303
  finally {
418
- if (this.#sessions.get(sessionId) === runtime) {
419
- this.#sessions.delete(sessionId);
304
+ if (this.#sessions.detach(sessionId, runtime)) {
420
305
  this.#processes.releaseClosed(runtime);
421
306
  }
422
307
  }
423
308
  }
424
- })();
425
- this.#cancellationRequests.set(sessionId, cancellation);
426
- await cancellation;
309
+ });
427
310
  };
428
311
  steerPrompt = async (options) => {
429
- if (this.#activeCommandIds.get(options.sessionId) !== options.targetCommandId) {
312
+ if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
430
313
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
431
314
  }
432
- const pending = this.#preparing.get(options.sessionId);
315
+ const pending = this.#sessions.pending(options.sessionId);
433
316
  if (pending !== undefined) {
434
317
  await pending;
435
318
  }
436
- if (this.#activeCommandIds.get(options.sessionId) !== options.targetCommandId) {
319
+ if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
437
320
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
438
321
  }
439
322
  const runtime = this.#sessions.get(options.sessionId);
@@ -465,28 +348,27 @@ export class AcpSessionManager {
465
348
  this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`)) {
466
349
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
467
350
  }
468
- if (this.#activeCommandIds.has(options.sessionId)) {
469
- throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
470
- }
471
- this.#activeCommandIds.set(options.sessionId, options.commandId);
351
+ this.#executions.begin(options.sessionId, options.commandId);
472
352
  try {
473
- if (this.#cancellationRequests.has(options.sessionId)) {
353
+ if (this.#executions.cancellation(options.sessionId) !== undefined) {
474
354
  return { stopReason: "cancelled" };
475
355
  }
476
356
  const runtime = await this.ensureSession(options);
477
357
  if (this.#nativeOperations.has(`${options.agent.id}:${runtime.nativeSessionId()}`)) {
478
358
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
479
359
  }
480
- if (this.#cancellationRequests.has(options.sessionId)) {
360
+ if (this.#executions.cancellation(options.sessionId) !== undefined) {
481
361
  return { stopReason: "cancelled" };
482
362
  }
483
363
  try {
484
364
  const result = await runtime.prompt(options);
485
- return this.#cancellationRequests.has(options.sessionId) ? { stopReason: "cancelled" } : result;
365
+ return this.#executions.cancellation(options.sessionId) !== undefined
366
+ ? { stopReason: "cancelled" }
367
+ : result;
486
368
  }
487
369
  catch (error) {
488
- if (this.#cancellationRequests.has(options.sessionId)) {
489
- await this.#cancellationRequests.get(options.sessionId);
370
+ if (this.#executions.cancellation(options.sessionId) !== undefined) {
371
+ await this.#executions.cancellation(options.sessionId);
490
372
  return { stopReason: "cancelled" };
491
373
  }
492
374
  throw error;
@@ -497,7 +379,7 @@ export class AcpSessionManager {
497
379
  if (failedRuntime !== undefined) {
498
380
  await this.#retireSessionProcess(options.sessionId, failedRuntime, async () => await failedRuntime.close());
499
381
  }
500
- if (this.#cancellationRequests.has(options.sessionId)) {
382
+ if (this.#executions.cancellation(options.sessionId) !== undefined) {
501
383
  return { stopReason: "cancelled" };
502
384
  }
503
385
  if (error instanceof AcpExecutionError) {
@@ -509,14 +391,11 @@ export class AcpSessionManager {
509
391
  }
510
392
  finally {
511
393
  try {
512
- await this.#cancellationRequests.get(options.sessionId);
394
+ await this.#executions.cancellation(options.sessionId);
513
395
  }
514
396
  finally {
515
- if (this.#activeCommandIds.get(options.sessionId) === options.commandId) {
516
- this.#activeCommandIds.delete(options.sessionId);
517
- }
518
- this.#cancellationRequests.delete(options.sessionId);
519
- this.#touchSession(options.sessionId);
397
+ this.#executions.finish(options.sessionId, options.commandId);
398
+ this.#sessions.touch(options.sessionId);
520
399
  this.#processes.notifyChanged();
521
400
  }
522
401
  }
@@ -552,34 +431,34 @@ export class AcpSessionManager {
552
431
  createNativeSession = async (options) => {
553
432
  const temporarySessionId = `new-${crypto.randomUUID()}`;
554
433
  const temporaryOptions = { ...options, sessionId: temporarySessionId };
555
- this.#beginSessionUse(temporarySessionId);
556
- try {
557
- const runtime = await this.#startPreparation(temporaryOptions);
558
- let adopted = false;
434
+ return await this.#sessions.use(temporarySessionId, async () => {
559
435
  try {
560
- const nativeSessionId = runtime.nativeSessionId();
561
- if (!isNativeChatSessionId(options.agent.id, nativeSessionId) ||
562
- this.#sessions.has(nativeSessionId) ||
563
- !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
564
- throw new AcpExecutionError("The Agent returned an invalid new Session ID", {}, "invalid_native_session_response");
436
+ const runtime = await this.#startPreparation(temporaryOptions);
437
+ let adopted = false;
438
+ try {
439
+ const nativeSessionId = runtime.nativeSessionId();
440
+ if (!isNativeChatSessionId(options.agent.id, nativeSessionId) ||
441
+ this.#sessions.get(nativeSessionId) !== undefined ||
442
+ !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
443
+ throw new AcpExecutionError("The Agent returned an invalid new Session ID", {}, "invalid_native_session_response");
444
+ }
445
+ runtime.adoptNativeSessionId(nativeSessionId);
446
+ this.#sessions.detach(temporarySessionId, runtime);
447
+ this.#sessions.retain(nativeSessionId, runtime);
448
+ this.#processes.retain(runtime, this.#retention(nativeSessionId, "execution"));
449
+ adopted = true;
450
+ return nativeSessionId;
451
+ }
452
+ finally {
453
+ if (!adopted) {
454
+ await this.#retireSessionProcess(temporarySessionId, runtime, async () => await runtime.closeProcess());
455
+ }
565
456
  }
566
- runtime.adoptNativeSessionId(nativeSessionId);
567
- this.#sessions.delete(temporarySessionId);
568
- this.#sessions.set(nativeSessionId, runtime);
569
- this.#processes.retain(runtime, this.#retention(nativeSessionId, "execution"));
570
- adopted = true;
571
- return nativeSessionId;
572
457
  }
573
458
  finally {
574
- if (!adopted) {
575
- await this.#retireSessionProcess(temporarySessionId, runtime, async () => await runtime.closeProcess());
576
- }
459
+ this.#store.remove(temporarySessionId);
577
460
  }
578
- }
579
- finally {
580
- this.#store.remove(temporarySessionId);
581
- this.#endSessionUse(temporarySessionId);
582
- }
461
+ });
583
462
  };
584
463
  ensureSession = async (options) => {
585
464
  const existing = this.#sessions.get(options.sessionId);
@@ -587,7 +466,7 @@ export class AcpSessionManager {
587
466
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
588
467
  throw new AcpExecutionError("The agent or workspace cannot change after a conversation has started", {}, "session_identity_mismatch");
589
468
  }
590
- this.#touchExpectedSession(options.sessionId, existing);
469
+ this.#sessions.touch(options.sessionId, existing);
591
470
  return existing;
592
471
  }
593
472
  await this.prepareSession(options);
@@ -603,7 +482,7 @@ export class AcpSessionManager {
603
482
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
604
483
  throw new AcpExecutionError("The agent or workspace cannot change after a conversation has started", {}, "session_identity_mismatch");
605
484
  }
606
- this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
485
+ this.#nativeBrowserSessions.touch(options.sessionId, existing);
607
486
  return existing;
608
487
  }
609
488
  await this.prepareNativeSessionBrowser(options);
@@ -614,19 +493,16 @@ export class AcpSessionManager {
614
493
  return started;
615
494
  }
616
495
  listNativeSessions = async (options, cursor) => {
617
- this.#beginNativeBrowserUse(options.sessionId);
618
- try {
496
+ return await this.#nativeBrowserSessions.use(options.sessionId, async () => {
619
497
  return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
620
- }
621
- finally {
622
- this.#endNativeBrowserUse(options.sessionId);
623
- }
498
+ });
624
499
  };
625
500
  previewNativeSession = async (options, nativeSessionId) => {
626
501
  const key = `${options.agent.id}:${nativeSessionId}`;
627
502
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
628
503
  if (this.#nativeOperations.has(key) ||
629
- linked.some((entry) => this.#activeCommandIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId))) {
504
+ linked.some((entry) => this.#executions.command(entry.sessionId) !== undefined ||
505
+ this.#sessions.pending(entry.sessionId) !== undefined)) {
630
506
  throw new AcpExecutionError("Wait for the native session's running operation to finish", {}, "session_busy");
631
507
  }
632
508
  this.#nativeOperations.add(key);
@@ -641,8 +517,7 @@ export class AcpSessionManager {
641
517
  }
642
518
  };
643
519
  loadSessionHistory = async (options) => {
644
- this.#beginSessionUse(options.sessionId);
645
- try {
520
+ return await this.#sessions.use(options.sessionId, async () => {
646
521
  const runtime = await this.ensureSession(options);
647
522
  const stored = this.#store.read(options.sessionId);
648
523
  if (stored instanceof FoundAcpStoredSession && this.#nativeHistoryReader !== null) {
@@ -652,10 +527,7 @@ export class AcpSessionManager {
652
527
  }
653
528
  }
654
529
  return await runtime.loadHistory(options.signal);
655
- }
656
- finally {
657
- this.#endSessionUse(options.sessionId);
658
- }
530
+ });
659
531
  };
660
532
  openNativeSession = async (options, origin) => {
661
533
  const key = `${options.agent.id}:${origin.nativeSessionId}`;
@@ -663,18 +535,18 @@ export class AcpSessionManager {
663
535
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
664
536
  }
665
537
  const linked = this.#store.findNative(options.agent.id, origin.nativeSessionId);
666
- if (linked.some((entry) => this.#activeCommandIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId))) {
538
+ if (linked.some((entry) => this.#executions.command(entry.sessionId) !== undefined ||
539
+ this.#sessions.pending(entry.sessionId) !== undefined)) {
667
540
  throw new AcpExecutionError("Wait for the native session's running operation to finish", {}, "session_busy");
668
541
  }
669
542
  const existing = linked[0];
670
543
  if (origin.kind === "import" && existing !== undefined) {
671
- this.#beginSessionUse(existing.sessionId);
672
- try {
544
+ return await this.#sessions.use(existing.sessionId, async () => {
673
545
  const runtime = await this.ensureSession({
674
546
  ...options,
675
547
  sessionId: existing.sessionId,
676
548
  });
677
- if (this.#activeCommandIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
549
+ if (this.#executions.command(existing.sessionId) !== undefined || this.#nativeOperations.has(key)) {
678
550
  throw new AcpExecutionError("Wait for the native session's running operation to finish", {}, "session_busy");
679
551
  }
680
552
  this.#nativeOperations.add(key);
@@ -688,55 +560,52 @@ export class AcpSessionManager {
688
560
  this.#nativeOperations.delete(key);
689
561
  this.#processes.notifyChanged();
690
562
  }
691
- }
692
- finally {
693
- this.#endSessionUse(existing.sessionId);
694
- }
563
+ });
695
564
  }
696
- if (this.#sessions.has(options.sessionId) ||
697
- this.#preparing.has(options.sessionId) ||
565
+ if (this.#sessions.get(options.sessionId) !== undefined ||
566
+ this.#sessions.pending(options.sessionId) !== undefined ||
698
567
  this.#store.read(options.sessionId) instanceof FoundAcpStoredSession ||
699
568
  this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
700
569
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
701
570
  }
702
- this.#beginSessionUse(options.sessionId);
703
- this.#nativeOperations.add(key);
704
- try {
705
- const runtime = await this.#startPreparation({ ...options, origin });
706
- const openedKey = `${options.agent.id}:${runtime.nativeSessionId()}`;
707
- this.#nativeOperations.add(openedKey);
571
+ return await this.#sessions.use(options.sessionId, async () => {
572
+ this.#nativeOperations.add(key);
708
573
  try {
709
- return {
710
- sessionId: options.sessionId,
711
- prepared: runtime.prepared(),
712
- };
574
+ const runtime = await this.#startPreparation({ ...options, origin });
575
+ const openedKey = `${options.agent.id}:${runtime.nativeSessionId()}`;
576
+ this.#nativeOperations.add(openedKey);
577
+ try {
578
+ return {
579
+ sessionId: options.sessionId,
580
+ prepared: runtime.prepared(),
581
+ };
582
+ }
583
+ finally {
584
+ this.#nativeOperations.delete(openedKey);
585
+ this.#processes.notifyChanged();
586
+ }
713
587
  }
714
- finally {
715
- this.#nativeOperations.delete(openedKey);
716
- this.#processes.notifyChanged();
588
+ catch (error) {
589
+ this.#store.remove(options.sessionId);
590
+ const runtime = this.#sessions.get(options.sessionId);
591
+ if (runtime !== undefined) {
592
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
593
+ }
594
+ throw error;
717
595
  }
718
- }
719
- catch (error) {
720
- this.#store.remove(options.sessionId);
721
- const runtime = this.#sessions.get(options.sessionId);
722
- if (runtime !== undefined) {
723
- await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
596
+ finally {
597
+ this.#nativeOperations.delete(key);
724
598
  }
725
- throw error;
726
- }
727
- finally {
728
- this.#nativeOperations.delete(key);
729
- this.#endSessionUse(options.sessionId);
730
- }
599
+ });
731
600
  };
732
601
  deleteNativeSession = async (options, nativeSessionId) => {
733
- this.#beginNativeBrowserUse(options.sessionId);
734
- try {
602
+ return await this.#nativeBrowserSessions.use(options.sessionId, async () => {
735
603
  const runtime = await this.#ensureNativeSessionBrowser(options);
736
604
  const key = `${options.agent.id}:${nativeSessionId}`;
737
605
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
738
606
  if (this.#nativeOperations.has(key) ||
739
- linked.some((entry) => this.#activeCommandIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId))) {
607
+ linked.some((entry) => this.#executions.command(entry.sessionId) !== undefined ||
608
+ this.#sessions.pending(entry.sessionId) !== undefined)) {
740
609
  throw new AcpExecutionError("Wait for the native session's running operation to finish", {}, "session_busy");
741
610
  }
742
611
  this.#nativeOperations.add(key);
@@ -759,10 +628,7 @@ export class AcpSessionManager {
759
628
  this.#nativeOperations.delete(key);
760
629
  this.#processes.notifyChanged();
761
630
  }
762
- }
763
- finally {
764
- this.#endNativeBrowserUse(options.sessionId);
765
- }
631
+ });
766
632
  };
767
633
  }
768
634
  //# sourceMappingURL=session-manager.js.map