@moxt-ai/mobius 0.0.123 → 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.
Files changed (40) hide show
  1. package/dist/acp/process-endpoint.d.ts +18 -0
  2. package/dist/acp/process-endpoint.d.ts.map +1 -0
  3. package/dist/acp/process-endpoint.js +191 -0
  4. package/dist/acp/process-endpoint.js.map +1 -0
  5. package/dist/acp/process-pool.d.ts +17 -0
  6. package/dist/acp/process-pool.d.ts.map +1 -0
  7. package/dist/acp/process-pool.js +107 -0
  8. package/dist/acp/process-pool.js.map +1 -0
  9. package/dist/acp/process-session.d.ts +5 -109
  10. package/dist/acp/process-session.d.ts.map +1 -1
  11. package/dist/acp/process-session.js +46 -444
  12. package/dist/acp/process-session.js.map +1 -1
  13. package/dist/acp/retained-sessions.d.ts +21 -0
  14. package/dist/acp/retained-sessions.d.ts.map +1 -0
  15. package/dist/acp/retained-sessions.js +107 -0
  16. package/dist/acp/retained-sessions.js.map +1 -0
  17. package/dist/acp/session-contracts.d.ts +104 -0
  18. package/dist/acp/session-contracts.d.ts.map +1 -0
  19. package/dist/acp/session-contracts.js +38 -0
  20. package/dist/acp/session-contracts.js.map +1 -0
  21. package/dist/acp/session-executions.d.ts +11 -0
  22. package/dist/acp/session-executions.d.ts.map +1 -0
  23. package/dist/acp/session-executions.js +76 -0
  24. package/dist/acp/session-executions.js.map +1 -0
  25. package/dist/acp/session-interactions.d.ts +22 -0
  26. package/dist/acp/session-interactions.d.ts.map +1 -0
  27. package/dist/acp/session-interactions.js +207 -0
  28. package/dist/acp/session-interactions.js.map +1 -0
  29. package/dist/acp/session-manager.d.ts +4 -2
  30. package/dist/acp/session-manager.d.ts.map +1 -1
  31. package/dist/acp/session-manager.js +192 -472
  32. package/dist/acp/session-manager.js.map +1 -1
  33. package/dist/cli.js +7525 -7468
  34. package/dist/cli.js.map +4 -4
  35. package/dist/daemon-turn-registry.d.ts +13 -13
  36. package/dist/index.js +7689 -7632
  37. package/dist/index.js.map +4 -4
  38. package/dist/runtime.js +7633 -7576
  39. package/dist/runtime.js.map +4 -4
  40. package/package.json +1 -1
@@ -1,58 +1,28 @@
1
+ import { AcpProcessSession } from "./process-session.js";
2
+ import { RetainedSessions } from "./retained-sessions.js";
3
+ import { SessionExecutions } from "./session-executions.js";
4
+ export { createWritableAcpStream } from "./process-endpoint.js";
1
5
  import { unmeasuredOperationMetrics } from "../infra/operation-metrics.js";
2
6
  import { isNativeChatSessionId } from "../native-sessions/chat-agent.js";
3
7
  import { AcpExecutionError } from "./acp-error.js";
4
- import { AcpProcessCapacityLock, waitForAcpProcessCapacity } from "./process-capacity.js";
8
+ import { AcpProcessPool } from "./process-pool.js";
5
9
  import { DeletedAcpStoredSession, FoundAcpStoredSession, MemoryAcpSessionStore, MissingAcpStoredSession, } from "./session-store.js";
6
- const MAX_ACP_PROCESSES = 10;
7
10
  const SESSION_CONTROL_TIMEOUT_MILLISECONDS = 30_000;
8
11
  export { AcpConfigurationValueUnavailableError, AcpExecutionError } from "./acp-error.js";
9
- export { AcpAgentSettingsSnapshot, AcpPreparedSession, createWritableAcpStream, NullAcpSessionObserver, } from "./process-session.js";
10
- import { AcpAgentSettingsSnapshot, AcpProcessSession, NullAcpSessionObserver, } from "./process-session.js";
11
- class AcpProcessEvictionCandidate {
12
- }
13
- class MissingAcpProcessEvictionCandidate extends AcpProcessEvictionCandidate {
14
- }
15
- class FoundAcpProcessEvictionCandidate extends AcpProcessEvictionCandidate {
16
- runtime;
17
- constructor(runtime) {
18
- super();
19
- this.runtime = runtime;
20
- }
21
- }
22
- class FoundAcpSessionProcessEvictionCandidate extends FoundAcpProcessEvictionCandidate {
23
- sessionId;
24
- constructor(sessionId, runtime) {
25
- super(runtime);
26
- this.sessionId = sessionId;
27
- }
28
- }
29
- class FoundAcpNativeBrowserProcessEvictionCandidate extends FoundAcpProcessEvictionCandidate {
30
- sessionId;
31
- constructor(sessionId, runtime) {
32
- super(runtime);
33
- this.sessionId = sessionId;
34
- }
35
- }
12
+ export { AcpAgentSettingsSnapshot, AcpPreparedSession, NullAcpSessionObserver, } from "./session-contracts.js";
13
+ import { AcpAgentSettingsSnapshot, NullAcpSessionObserver, } from "./session-contracts.js";
36
14
  export class AcpSessionManager {
37
- #activeCommandIds = new Map();
15
+ #processes = new AcpProcessPool();
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();
38
22
  #agentSettingsObserver = new NullAcpSessionObserver();
39
23
  #nativeOperations = new Set();
40
24
  #nativeBrowserObserver = new NullAcpSessionObserver();
41
- #nativeBrowserPreparing = new Map();
42
- #nativeBrowserSessions = new Map();
43
25
  #nativeBrowserStore = new MemoryAcpSessionStore();
44
- #nativeBrowserUseCounts = new Map();
45
- #activeSessionIds = new Set();
46
- #cancellationRequests = new Map();
47
- #preparing = new Map();
48
- #processCapacityChanged = Promise.withResolvers();
49
- #processCapacityLock = new AcpProcessCapacityLock();
50
- #retainedProcesses = new Map();
51
- #retiringProcessCount = 0;
52
- #sessionUseCounts = new Map();
53
- #sessions = new Map();
54
- #startingProcessCount = 0;
55
- #transientProcessCount = 0;
56
26
  #store;
57
27
  #nativeHistoryReader;
58
28
  #sessionIdentity;
@@ -66,128 +36,29 @@ export class AcpSessionManager {
66
36
  setObserver = (observer) => {
67
37
  this.#observer = observer;
68
38
  };
69
- #notifyProcessCapacityChanged() {
70
- const changed = this.#processCapacityChanged;
71
- this.#processCapacityChanged = Promise.withResolvers();
72
- changed.resolve();
73
- }
74
- #touchSession(sessionId) {
75
- const runtime = this.#sessions.get(sessionId);
76
- if (runtime === undefined) {
77
- return;
78
- }
79
- this.#touchProcess(runtime);
80
- }
81
- #touchExpectedSession(sessionId, expected) {
82
- if (this.#sessions.get(sessionId) !== expected) {
83
- return;
84
- }
85
- this.#touchProcess(expected);
86
- }
87
- #touchNativeBrowserSession(sessionId) {
88
- const runtime = this.#nativeBrowserSessions.get(sessionId);
89
- if (runtime === undefined) {
90
- return;
91
- }
92
- this.#touchProcess(runtime);
93
- }
94
- #touchExpectedNativeBrowserSession(sessionId, expected) {
95
- if (this.#nativeBrowserSessions.get(sessionId) !== expected) {
96
- return;
97
- }
98
- this.#touchProcess(expected);
99
- }
100
- #touchProcess(runtime) {
101
- const retained = this.#retainedProcesses.get(runtime);
102
- if (retained === undefined) {
103
- return;
104
- }
105
- this.#retainedProcesses.delete(runtime);
106
- this.#retainedProcesses.set(runtime, retained);
107
- }
108
- #beginSessionUse(sessionId) {
109
- this.#sessionUseCounts.set(sessionId, (this.#sessionUseCounts.get(sessionId) ?? 0) + 1);
110
- this.#touchSession(sessionId);
111
- }
112
- #endSessionUse(sessionId) {
113
- const count = this.#sessionUseCounts.get(sessionId) ?? 0;
114
- if (count <= 1) {
115
- this.#sessionUseCounts.delete(sessionId);
116
- }
117
- else {
118
- this.#sessionUseCounts.set(sessionId, count - 1);
119
- }
120
- this.#touchSession(sessionId);
121
- this.#notifyProcessCapacityChanged();
122
- }
123
- #beginNativeBrowserUse(sessionId) {
124
- this.#nativeBrowserUseCounts.set(sessionId, (this.#nativeBrowserUseCounts.get(sessionId) ?? 0) + 1);
125
- this.#touchNativeBrowserSession(sessionId);
126
- }
127
- #endNativeBrowserUse(sessionId) {
128
- const count = this.#nativeBrowserUseCounts.get(sessionId) ?? 0;
129
- if (count <= 1) {
130
- this.#nativeBrowserUseCounts.delete(sessionId);
131
- }
132
- else {
133
- this.#nativeBrowserUseCounts.set(sessionId, count - 1);
134
- }
135
- this.#touchNativeBrowserSession(sessionId);
136
- this.#notifyProcessCapacityChanged();
137
- }
138
39
  #isNativeSessionOperationActive(sessionId) {
139
40
  const stored = this.#store.read(sessionId);
140
41
  return (stored instanceof FoundAcpStoredSession &&
141
42
  this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`));
142
43
  }
143
- #leastRecentlyUsedEvictionCandidate() {
144
- for (const candidate of this.#retainedProcesses.values()) {
145
- if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
146
- if (this.#activeSessionIds.has(candidate.sessionId) ||
147
- this.#cancellationRequests.has(candidate.sessionId) ||
148
- this.#preparing.has(candidate.sessionId) ||
149
- (this.#sessionUseCounts.get(candidate.sessionId) ?? 0) > 0 ||
150
- this.#isNativeSessionOperationActive(candidate.sessionId)) {
151
- continue;
152
- }
153
- return candidate;
154
- }
155
- if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate &&
156
- !this.#nativeBrowserPreparing.has(candidate.sessionId) &&
157
- (this.#nativeBrowserUseCounts.get(candidate.sessionId) ?? 0) === 0) {
158
- return candidate;
159
- }
160
- }
161
- return new MissingAcpProcessEvictionCandidate();
162
- }
163
- #ownedProcessCount() {
164
- return (this.#retainedProcesses.size +
165
- this.#startingProcessCount +
166
- this.#transientProcessCount +
167
- this.#retiringProcessCount);
168
- }
169
- async #retireProcess(runtime, retained, close) {
170
- if (retained) {
171
- this.#retainedProcesses.delete(runtime);
172
- this.#retiringProcessCount += 1;
173
- }
174
- try {
175
- await close();
176
- }
177
- finally {
178
- if (retained) {
179
- this.#retiringProcessCount -= 1;
180
- this.#notifyProcessCapacityChanged();
181
- }
182
- }
44
+ #retention(sessionId, kind) {
45
+ if (kind === "execution") {
46
+ return {
47
+ isBusy: () => this.#executions.isBusy(sessionId) ||
48
+ this.#sessions.isBusy(sessionId) ||
49
+ this.#isNativeSessionOperationActive(sessionId),
50
+ retire: (runtime) => this.#retireSessionProcess(sessionId, runtime, () => runtime.close()),
51
+ };
52
+ }
53
+ return {
54
+ isBusy: () => this.#nativeBrowserSessions.isBusy(sessionId),
55
+ retire: (runtime) => this.#retireNativeBrowserProcess(sessionId, runtime, () => runtime.close()),
56
+ };
183
57
  }
184
58
  async #retireSessionProcess(sessionId, runtime, close) {
185
- const retained = this.#sessions.get(sessionId) === runtime;
186
- if (retained) {
187
- this.#sessions.delete(sessionId);
188
- }
59
+ const retained = this.#sessions.detach(sessionId, runtime);
189
60
  try {
190
- await this.#retireProcess(runtime, retained, close);
61
+ await this.#processes.retire(runtime, close);
191
62
  }
192
63
  finally {
193
64
  if (retained && this.#sessionIdentity === "native") {
@@ -200,209 +71,93 @@ export class AcpSessionManager {
200
71
  }
201
72
  }
202
73
  async #retireNativeBrowserProcess(sessionId, runtime, close) {
203
- const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
74
+ const retained = this.#nativeBrowserSessions.detach(sessionId, runtime);
204
75
  if (retained) {
205
- this.#nativeBrowserSessions.delete(sessionId);
206
76
  this.#nativeBrowserStore.remove(sessionId);
207
77
  }
208
- await this.#retireProcess(runtime, retained, close);
209
- }
210
- async #reserveProcessCapacity(signal) {
211
- const lease = await this.#processCapacityLock.acquire(signal);
212
- try {
213
- for (;;) {
214
- signal.throwIfAborted();
215
- if (this.#ownedProcessCount() < MAX_ACP_PROCESSES) {
216
- this.#startingProcessCount += 1;
217
- return;
218
- }
219
- const candidate = this.#leastRecentlyUsedEvictionCandidate();
220
- if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
221
- await this.#retireSessionProcess(candidate.sessionId, candidate.runtime, async () => await candidate.runtime.close());
222
- continue;
223
- }
224
- if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate) {
225
- await this.#retireNativeBrowserProcess(candidate.sessionId, candidate.runtime, async () => await candidate.runtime.close());
226
- continue;
227
- }
228
- const changed = this.#processCapacityChanged.promise;
229
- await waitForAcpProcessCapacity(changed, signal);
230
- }
231
- }
232
- finally {
233
- lease.release();
234
- }
78
+ await this.#processes.retire(runtime, close);
235
79
  }
236
80
  async #startRetainedSessionProcess(options, start) {
237
- await this.#reserveProcessCapacity(options.signal);
238
- try {
239
- const runtime = await start();
240
- this.#startingProcessCount -= 1;
241
- this.#sessions.set(options.sessionId, runtime);
242
- this.#retainedProcesses.set(runtime, new FoundAcpSessionProcessEvictionCandidate(options.sessionId, runtime));
243
- this.#notifyProcessCapacityChanged();
244
- return runtime;
245
- }
246
- catch (error) {
247
- this.#startingProcessCount -= 1;
248
- this.#notifyProcessCapacityChanged();
249
- throw error;
250
- }
81
+ const runtime = await this.#processes.startRetained(options.signal, start, this.#retention(options.sessionId, "execution"));
82
+ this.#sessions.retain(options.sessionId, runtime);
83
+ return runtime;
251
84
  }
252
85
  async #startRetainedNativeBrowserProcess(options, start) {
253
- await this.#reserveProcessCapacity(options.signal);
254
- try {
255
- const runtime = await start();
256
- this.#startingProcessCount -= 1;
257
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
258
- this.#retainedProcesses.set(runtime, new FoundAcpNativeBrowserProcessEvictionCandidate(options.sessionId, runtime));
259
- this.#notifyProcessCapacityChanged();
260
- return runtime;
261
- }
262
- catch (error) {
263
- this.#startingProcessCount -= 1;
264
- this.#notifyProcessCapacityChanged();
265
- throw error;
266
- }
267
- }
268
- async #runWithTransientProcess(signal, start, operation, close) {
269
- await this.#reserveProcessCapacity(signal);
270
- let runtime;
271
- try {
272
- runtime = await start();
273
- }
274
- catch (error) {
275
- this.#startingProcessCount -= 1;
276
- this.#notifyProcessCapacityChanged();
277
- throw error;
278
- }
279
- this.#startingProcessCount -= 1;
280
- this.#transientProcessCount += 1;
281
- this.#notifyProcessCapacityChanged();
282
- try {
283
- return await operation(runtime);
284
- }
285
- finally {
286
- try {
287
- await close(runtime);
288
- }
289
- finally {
290
- this.#transientProcessCount -= 1;
291
- this.#notifyProcessCapacityChanged();
292
- }
293
- }
86
+ const runtime = await this.#processes.startRetained(options.signal, start, this.#retention(options.sessionId, "browser"));
87
+ this.#nativeBrowserSessions.retain(options.sessionId, runtime);
88
+ return runtime;
294
89
  }
295
90
  async #startNativeBrowserPreparation(options) {
296
- const operation = (async () => {
297
- try {
298
- return await this.#startRetainedNativeBrowserProcess(options, async () => await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, this.#nativeBrowserStore));
299
- }
300
- finally {
301
- this.#nativeBrowserPreparing.delete(options.sessionId);
302
- this.#notifyProcessCapacityChanged();
303
- }
304
- })();
305
- this.#nativeBrowserPreparing.set(options.sessionId, operation);
306
- 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
+ });
307
94
  }
308
95
  async #replaceNativeBrowserPreparation(existing, options) {
309
- const operation = (async () => {
310
- try {
311
- await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
312
- return await this.#startRetainedNativeBrowserProcess(options, async () => await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, this.#nativeBrowserStore));
313
- }
314
- finally {
315
- this.#nativeBrowserPreparing.delete(options.sessionId);
316
- this.#notifyProcessCapacityChanged();
317
- }
318
- })();
319
- this.#nativeBrowserPreparing.set(options.sessionId, operation);
320
- 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
+ });
321
100
  }
322
101
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
323
- const operation = (async () => {
324
- try {
325
- return await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options.origin === undefined &&
326
- this.#sessionIdentity === "native" &&
327
- isNativeChatSessionId(options.agent.id, options.sessionId) &&
328
- this.#store.read(options.sessionId) instanceof MissingAcpStoredSession
329
- ? { ...options, origin: { kind: "import", nativeSessionId: options.sessionId } }
330
- : options, () => this.#observer, this.#store, metrics));
331
- }
332
- finally {
333
- this.#preparing.delete(options.sessionId);
334
- this.#notifyProcessCapacityChanged();
335
- }
336
- })();
337
- this.#preparing.set(options.sessionId, operation);
338
- 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
+ });
339
110
  }
340
111
  async #replacePreparation(existing, options, metrics) {
341
- const operation = (async () => {
342
- try {
343
- await this.#retireSessionProcess(options.sessionId, existing, async () => await metrics.measure("runtime-replacement-close", async () => await existing.close()));
344
- this.#store.remove(options.sessionId);
345
- return await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics));
346
- }
347
- finally {
348
- this.#preparing.delete(options.sessionId);
349
- this.#notifyProcessCapacityChanged();
350
- }
351
- })();
352
- this.#preparing.set(options.sessionId, operation);
353
- 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
+ });
354
117
  }
355
118
  async #replaceExecutionPreparation(existing, options) {
356
119
  const desiredConfigOptions = existing.prepared().configOptions;
357
- 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));
358
123
  try {
359
- await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
360
- const runtime = await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options, () => this.#observer, this.#store));
361
- try {
362
- for (const desired of desiredConfigOptions) {
363
- const current = runtime.prepared().configOptions.find((option) => option.id === desired.id);
364
- if (current === undefined || current.type !== desired.type) {
365
- continue;
366
- }
367
- if (desired.type === "boolean") {
368
- if (current.booleanValue !== desired.booleanValue) {
369
- await runtime.configure({
370
- ...options,
371
- booleanValue: desired.booleanValue,
372
- configId: desired.id,
373
- requestId: `execution-prepare-${desired.id}`,
374
- value: "",
375
- valueType: "boolean",
376
- });
377
- }
378
- continue;
379
- }
380
- if (current.currentValue !== desired.currentValue &&
381
- 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) {
382
131
  await runtime.configure({
383
132
  ...options,
384
- booleanValue: false,
133
+ booleanValue: desired.booleanValue,
385
134
  configId: desired.id,
386
135
  requestId: `execution-prepare-${desired.id}`,
387
- value: desired.currentValue,
388
- valueType: "select",
136
+ value: "",
137
+ valueType: "boolean",
389
138
  });
390
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
+ });
391
152
  }
392
153
  }
393
- catch (error) {
394
- await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
395
- throw error;
396
- }
397
- return runtime;
398
154
  }
399
- finally {
400
- this.#preparing.delete(options.sessionId);
401
- this.#notifyProcessCapacityChanged();
155
+ catch (error) {
156
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
157
+ throw error;
402
158
  }
403
- })();
404
- this.#preparing.set(options.sessionId, operation);
405
- return await operation;
159
+ return runtime;
160
+ });
406
161
  }
407
162
  prepareSession = async (options, metrics = unmeasuredOperationMetrics) => {
408
163
  const stored = metrics.measureSync("session-state-read", () => this.#store.read(options.sessionId));
@@ -413,11 +168,11 @@ export class AcpSessionManager {
413
168
  this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`)) {
414
169
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
415
170
  }
416
- const pending = this.#preparing.get(options.sessionId);
171
+ const pending = this.#sessions.pending(options.sessionId);
417
172
  if (pending !== undefined) {
418
173
  const runtime = await metrics.measure("session-preparation-wait", async () => await pending);
419
174
  if (runtime.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
420
- this.#touchExpectedSession(options.sessionId, runtime);
175
+ this.#sessions.touch(options.sessionId, runtime);
421
176
  return runtime.prepared();
422
177
  }
423
178
  return await this.prepareSession(options, metrics);
@@ -425,7 +180,7 @@ export class AcpSessionManager {
425
180
  const existing = this.#sessions.get(options.sessionId);
426
181
  if (existing !== undefined) {
427
182
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
428
- this.#touchExpectedSession(options.sessionId, existing);
183
+ this.#sessions.touch(options.sessionId, existing);
429
184
  return existing.prepared();
430
185
  }
431
186
  if (!existing.canRebind()) {
@@ -442,7 +197,7 @@ export class AcpSessionManager {
442
197
  * authoritative settings. Its identity and store are private to this
443
198
  * operation and never become a Mobius Session.
444
199
  */
445
- inspectAgentSettings = async (options) => await this.#runWithTransientProcess(options.signal, async () => await AcpProcessSession.start({
200
+ inspectAgentSettings = async (options) => await this.#processes.runTransient(options.signal, async () => await AcpProcessSession.start({
446
201
  ...options,
447
202
  sessionId: `agent-settings-${crypto.randomUUID()}`,
448
203
  }, () => this.#agentSettingsObserver, new MemoryAcpSessionStore()), async (runtime) => {
@@ -466,11 +221,11 @@ export class AcpSessionManager {
466
221
  * Use inspectAgentSettings for Agent-scoped settings discovery.
467
222
  */
468
223
  inspectSession = async (options, metrics = unmeasuredOperationMetrics) => {
469
- 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) {
470
226
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
471
227
  }
472
- this.#beginSessionUse(options.sessionId);
473
- try {
228
+ return await this.#sessions.use(options.sessionId, async () => {
474
229
  const runtime = await this.#startPreparation(options, metrics);
475
230
  try {
476
231
  return runtime.prepared();
@@ -483,13 +238,10 @@ export class AcpSessionManager {
483
238
  this.#store.remove(options.sessionId);
484
239
  }
485
240
  }
486
- }
487
- finally {
488
- this.#endSessionUse(options.sessionId);
489
- }
241
+ });
490
242
  };
491
243
  prepareExecutionSession = async (options) => {
492
- const pending = this.#preparing.get(options.sessionId);
244
+ const pending = this.#sessions.pending(options.sessionId);
493
245
  if (pending !== undefined) {
494
246
  await pending;
495
247
  return await this.prepareExecutionSession(options);
@@ -502,7 +254,7 @@ export class AcpSessionManager {
502
254
  throw new AcpExecutionError("The agent or workspace cannot change after a conversation has started", {}, "session_identity_mismatch");
503
255
  }
504
256
  if (existing.usesEnvironment(options.agent.environment)) {
505
- this.#touchExpectedSession(options.sessionId, existing);
257
+ this.#sessions.touch(options.sessionId, existing);
506
258
  return existing.prepared();
507
259
  }
508
260
  if (existing.hasRunningTurn()) {
@@ -511,11 +263,11 @@ export class AcpSessionManager {
511
263
  return (await this.#replaceExecutionPreparation(existing, options)).prepared();
512
264
  };
513
265
  prepareNativeSessionBrowser = async (options) => {
514
- const pending = this.#nativeBrowserPreparing.get(options.sessionId);
266
+ const pending = this.#nativeBrowserSessions.pending(options.sessionId);
515
267
  if (pending !== undefined) {
516
268
  const runtime = await pending;
517
269
  if (runtime.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
518
- this.#touchExpectedNativeBrowserSession(options.sessionId, runtime);
270
+ this.#nativeBrowserSessions.touch(options.sessionId, runtime);
519
271
  return runtime.prepared();
520
272
  }
521
273
  return await this.prepareNativeSessionBrowser(options);
@@ -523,7 +275,7 @@ export class AcpSessionManager {
523
275
  const existing = this.#nativeBrowserSessions.get(options.sessionId);
524
276
  if (existing !== undefined) {
525
277
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
526
- this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
278
+ this.#nativeBrowserSessions.touch(options.sessionId, existing);
527
279
  return existing.prepared();
528
280
  }
529
281
  if (!existing.canRebind()) {
@@ -536,48 +288,35 @@ export class AcpSessionManager {
536
288
  return runtime.prepared();
537
289
  };
538
290
  configureSession = async (options) => {
539
- this.#beginSessionUse(options.sessionId);
540
- try {
291
+ return await this.#sessions.use(options.sessionId, async () => {
541
292
  const runtime = await this.ensureSession(options);
542
293
  return await runtime.configure(options);
543
- }
544
- finally {
545
- this.#endSessionUse(options.sessionId);
546
- }
294
+ });
547
295
  };
548
296
  cancelPrompt = async (sessionId) => {
549
- const existing = this.#cancellationRequests.get(sessionId);
550
- if (existing !== undefined) {
551
- await existing;
552
- return;
553
- }
554
- const cancellation = (async () => {
297
+ await this.#executions.cancel(sessionId, async () => {
555
298
  const runtime = this.#sessions.get(sessionId);
556
299
  if (runtime !== undefined) {
557
300
  try {
558
301
  await runtime.cancel();
559
302
  }
560
303
  finally {
561
- if (this.#sessions.get(sessionId) === runtime) {
562
- this.#sessions.delete(sessionId);
563
- this.#retainedProcesses.delete(runtime);
564
- this.#notifyProcessCapacityChanged();
304
+ if (this.#sessions.detach(sessionId, runtime)) {
305
+ this.#processes.releaseClosed(runtime);
565
306
  }
566
307
  }
567
308
  }
568
- })();
569
- this.#cancellationRequests.set(sessionId, cancellation);
570
- await cancellation;
309
+ });
571
310
  };
572
311
  steerPrompt = async (options) => {
573
- if (this.#activeCommandIds.get(options.sessionId) !== options.targetCommandId) {
312
+ if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
574
313
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
575
314
  }
576
- const pending = this.#preparing.get(options.sessionId);
315
+ const pending = this.#sessions.pending(options.sessionId);
577
316
  if (pending !== undefined) {
578
317
  await pending;
579
318
  }
580
- if (this.#activeCommandIds.get(options.sessionId) !== options.targetCommandId) {
319
+ if (this.#executions.command(options.sessionId) !== options.targetCommandId) {
581
320
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
582
321
  }
583
322
  const runtime = this.#sessions.get(options.sessionId);
@@ -609,29 +348,27 @@ export class AcpSessionManager {
609
348
  this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`)) {
610
349
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
611
350
  }
612
- if (this.#activeSessionIds.has(options.sessionId)) {
613
- throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
614
- }
615
- this.#activeSessionIds.add(options.sessionId);
616
- this.#activeCommandIds.set(options.sessionId, options.commandId);
351
+ this.#executions.begin(options.sessionId, options.commandId);
617
352
  try {
618
- if (this.#cancellationRequests.has(options.sessionId)) {
353
+ if (this.#executions.cancellation(options.sessionId) !== undefined) {
619
354
  return { stopReason: "cancelled" };
620
355
  }
621
356
  const runtime = await this.ensureSession(options);
622
357
  if (this.#nativeOperations.has(`${options.agent.id}:${runtime.nativeSessionId()}`)) {
623
358
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
624
359
  }
625
- if (this.#cancellationRequests.has(options.sessionId)) {
360
+ if (this.#executions.cancellation(options.sessionId) !== undefined) {
626
361
  return { stopReason: "cancelled" };
627
362
  }
628
363
  try {
629
364
  const result = await runtime.prompt(options);
630
- return this.#cancellationRequests.has(options.sessionId) ? { stopReason: "cancelled" } : result;
365
+ return this.#executions.cancellation(options.sessionId) !== undefined
366
+ ? { stopReason: "cancelled" }
367
+ : result;
631
368
  }
632
369
  catch (error) {
633
- if (this.#cancellationRequests.has(options.sessionId)) {
634
- await this.#cancellationRequests.get(options.sessionId);
370
+ if (this.#executions.cancellation(options.sessionId) !== undefined) {
371
+ await this.#executions.cancellation(options.sessionId);
635
372
  return { stopReason: "cancelled" };
636
373
  }
637
374
  throw error;
@@ -642,7 +379,7 @@ export class AcpSessionManager {
642
379
  if (failedRuntime !== undefined) {
643
380
  await this.#retireSessionProcess(options.sessionId, failedRuntime, async () => await failedRuntime.close());
644
381
  }
645
- if (this.#cancellationRequests.has(options.sessionId)) {
382
+ if (this.#executions.cancellation(options.sessionId) !== undefined) {
646
383
  return { stopReason: "cancelled" };
647
384
  }
648
385
  if (error instanceof AcpExecutionError) {
@@ -654,16 +391,12 @@ export class AcpSessionManager {
654
391
  }
655
392
  finally {
656
393
  try {
657
- await this.#cancellationRequests.get(options.sessionId);
394
+ await this.#executions.cancellation(options.sessionId);
658
395
  }
659
396
  finally {
660
- this.#activeSessionIds.delete(options.sessionId);
661
- if (this.#activeCommandIds.get(options.sessionId) === options.commandId) {
662
- this.#activeCommandIds.delete(options.sessionId);
663
- }
664
- this.#cancellationRequests.delete(options.sessionId);
665
- this.#touchSession(options.sessionId);
666
- this.#notifyProcessCapacityChanged();
397
+ this.#executions.finish(options.sessionId, options.commandId);
398
+ this.#sessions.touch(options.sessionId);
399
+ this.#processes.notifyChanged();
667
400
  }
668
401
  }
669
402
  };
@@ -698,34 +431,34 @@ export class AcpSessionManager {
698
431
  createNativeSession = async (options) => {
699
432
  const temporarySessionId = `new-${crypto.randomUUID()}`;
700
433
  const temporaryOptions = { ...options, sessionId: temporarySessionId };
701
- this.#beginSessionUse(temporarySessionId);
702
- try {
703
- const runtime = await this.#startPreparation(temporaryOptions);
704
- let adopted = false;
434
+ return await this.#sessions.use(temporarySessionId, async () => {
705
435
  try {
706
- const nativeSessionId = runtime.nativeSessionId();
707
- if (!isNativeChatSessionId(options.agent.id, nativeSessionId) ||
708
- this.#sessions.has(nativeSessionId) ||
709
- !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
710
- 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
+ }
711
456
  }
712
- runtime.adoptNativeSessionId(nativeSessionId);
713
- this.#sessions.delete(temporarySessionId);
714
- this.#sessions.set(nativeSessionId, runtime);
715
- this.#retainedProcesses.set(runtime, new FoundAcpSessionProcessEvictionCandidate(nativeSessionId, runtime));
716
- adopted = true;
717
- return nativeSessionId;
718
457
  }
719
458
  finally {
720
- if (!adopted) {
721
- await this.#retireSessionProcess(temporarySessionId, runtime, async () => await runtime.closeProcess());
722
- }
459
+ this.#store.remove(temporarySessionId);
723
460
  }
724
- }
725
- finally {
726
- this.#store.remove(temporarySessionId);
727
- this.#endSessionUse(temporarySessionId);
728
- }
461
+ });
729
462
  };
730
463
  ensureSession = async (options) => {
731
464
  const existing = this.#sessions.get(options.sessionId);
@@ -733,7 +466,7 @@ export class AcpSessionManager {
733
466
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
734
467
  throw new AcpExecutionError("The agent or workspace cannot change after a conversation has started", {}, "session_identity_mismatch");
735
468
  }
736
- this.#touchExpectedSession(options.sessionId, existing);
469
+ this.#sessions.touch(options.sessionId, existing);
737
470
  return existing;
738
471
  }
739
472
  await this.prepareSession(options);
@@ -749,7 +482,7 @@ export class AcpSessionManager {
749
482
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
750
483
  throw new AcpExecutionError("The agent or workspace cannot change after a conversation has started", {}, "session_identity_mismatch");
751
484
  }
752
- this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
485
+ this.#nativeBrowserSessions.touch(options.sessionId, existing);
753
486
  return existing;
754
487
  }
755
488
  await this.prepareNativeSessionBrowser(options);
@@ -760,24 +493,21 @@ export class AcpSessionManager {
760
493
  return started;
761
494
  }
762
495
  listNativeSessions = async (options, cursor) => {
763
- this.#beginNativeBrowserUse(options.sessionId);
764
- try {
496
+ return await this.#nativeBrowserSessions.use(options.sessionId, async () => {
765
497
  return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
766
- }
767
- finally {
768
- this.#endNativeBrowserUse(options.sessionId);
769
- }
498
+ });
770
499
  };
771
500
  previewNativeSession = async (options, nativeSessionId) => {
772
501
  const key = `${options.agent.id}:${nativeSessionId}`;
773
502
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
774
503
  if (this.#nativeOperations.has(key) ||
775
- linked.some((entry) => this.#activeSessionIds.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)) {
776
506
  throw new AcpExecutionError("Wait for the native session's running operation to finish", {}, "session_busy");
777
507
  }
778
508
  this.#nativeOperations.add(key);
779
509
  try {
780
- return await this.#runWithTransientProcess(options.signal, async () => await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, new MemoryAcpSessionStore()), async (runtime) => {
510
+ return await this.#processes.runTransient(options.signal, async () => await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, new MemoryAcpSessionStore()), async (runtime) => {
781
511
  runtime.selectNativeSession(nativeSessionId);
782
512
  return await runtime.loadHistory(options.signal);
783
513
  }, async (runtime) => await runtime.closeProcess());
@@ -787,8 +517,7 @@ export class AcpSessionManager {
787
517
  }
788
518
  };
789
519
  loadSessionHistory = async (options) => {
790
- this.#beginSessionUse(options.sessionId);
791
- try {
520
+ return await this.#sessions.use(options.sessionId, async () => {
792
521
  const runtime = await this.ensureSession(options);
793
522
  const stored = this.#store.read(options.sessionId);
794
523
  if (stored instanceof FoundAcpStoredSession && this.#nativeHistoryReader !== null) {
@@ -798,10 +527,7 @@ export class AcpSessionManager {
798
527
  }
799
528
  }
800
529
  return await runtime.loadHistory(options.signal);
801
- }
802
- finally {
803
- this.#endSessionUse(options.sessionId);
804
- }
530
+ });
805
531
  };
806
532
  openNativeSession = async (options, origin) => {
807
533
  const key = `${options.agent.id}:${origin.nativeSessionId}`;
@@ -809,18 +535,18 @@ export class AcpSessionManager {
809
535
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
810
536
  }
811
537
  const linked = this.#store.findNative(options.agent.id, origin.nativeSessionId);
812
- if (linked.some((entry) => this.#activeSessionIds.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)) {
813
540
  throw new AcpExecutionError("Wait for the native session's running operation to finish", {}, "session_busy");
814
541
  }
815
542
  const existing = linked[0];
816
543
  if (origin.kind === "import" && existing !== undefined) {
817
- this.#beginSessionUse(existing.sessionId);
818
- try {
544
+ return await this.#sessions.use(existing.sessionId, async () => {
819
545
  const runtime = await this.ensureSession({
820
546
  ...options,
821
547
  sessionId: existing.sessionId,
822
548
  });
823
- if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
549
+ if (this.#executions.command(existing.sessionId) !== undefined || this.#nativeOperations.has(key)) {
824
550
  throw new AcpExecutionError("Wait for the native session's running operation to finish", {}, "session_busy");
825
551
  }
826
552
  this.#nativeOperations.add(key);
@@ -832,57 +558,54 @@ export class AcpSessionManager {
832
558
  }
833
559
  finally {
834
560
  this.#nativeOperations.delete(key);
835
- this.#notifyProcessCapacityChanged();
561
+ this.#processes.notifyChanged();
836
562
  }
837
- }
838
- finally {
839
- this.#endSessionUse(existing.sessionId);
840
- }
563
+ });
841
564
  }
842
- if (this.#sessions.has(options.sessionId) ||
843
- this.#preparing.has(options.sessionId) ||
565
+ if (this.#sessions.get(options.sessionId) !== undefined ||
566
+ this.#sessions.pending(options.sessionId) !== undefined ||
844
567
  this.#store.read(options.sessionId) instanceof FoundAcpStoredSession ||
845
568
  this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
846
569
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
847
570
  }
848
- this.#beginSessionUse(options.sessionId);
849
- this.#nativeOperations.add(key);
850
- try {
851
- const runtime = await this.#startPreparation({ ...options, origin });
852
- const openedKey = `${options.agent.id}:${runtime.nativeSessionId()}`;
853
- this.#nativeOperations.add(openedKey);
571
+ return await this.#sessions.use(options.sessionId, async () => {
572
+ this.#nativeOperations.add(key);
854
573
  try {
855
- return {
856
- sessionId: options.sessionId,
857
- prepared: runtime.prepared(),
858
- };
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
+ }
859
587
  }
860
- finally {
861
- this.#nativeOperations.delete(openedKey);
862
- this.#notifyProcessCapacityChanged();
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;
863
595
  }
864
- }
865
- catch (error) {
866
- this.#store.remove(options.sessionId);
867
- const runtime = this.#sessions.get(options.sessionId);
868
- if (runtime !== undefined) {
869
- await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
596
+ finally {
597
+ this.#nativeOperations.delete(key);
870
598
  }
871
- throw error;
872
- }
873
- finally {
874
- this.#nativeOperations.delete(key);
875
- this.#endSessionUse(options.sessionId);
876
- }
599
+ });
877
600
  };
878
601
  deleteNativeSession = async (options, nativeSessionId) => {
879
- this.#beginNativeBrowserUse(options.sessionId);
880
- try {
602
+ return await this.#nativeBrowserSessions.use(options.sessionId, async () => {
881
603
  const runtime = await this.#ensureNativeSessionBrowser(options);
882
604
  const key = `${options.agent.id}:${nativeSessionId}`;
883
605
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
884
606
  if (this.#nativeOperations.has(key) ||
885
- linked.some((entry) => this.#activeSessionIds.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)) {
886
609
  throw new AcpExecutionError("Wait for the native session's running operation to finish", {}, "session_busy");
887
610
  }
888
611
  this.#nativeOperations.add(key);
@@ -903,12 +626,9 @@ export class AcpSessionManager {
903
626
  }
904
627
  finally {
905
628
  this.#nativeOperations.delete(key);
906
- this.#notifyProcessCapacityChanged();
629
+ this.#processes.notifyChanged();
907
630
  }
908
- }
909
- finally {
910
- this.#endNativeBrowserUse(options.sessionId);
911
- }
631
+ });
912
632
  };
913
633
  }
914
634
  //# sourceMappingURL=session-manager.js.map