maka-agent 0.2.0-dev.49.20260924 → 0.2.0-dev.50.20260925

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 (34) hide show
  1. package/LICENSE +35 -0
  2. package/dist/acp/maka-acp-agent.js +71 -11
  3. package/dist/acp/session-event-mapper.js +59 -3
  4. package/dist/acp/session-interactions.js +33 -3
  5. package/dist/acp/session-mcp.js +160 -11
  6. package/dist/acp/session-registry.js +1014 -242
  7. package/dist/acp/turn-observation.js +260 -0
  8. package/dist/mcp-capability-publication.js +17 -1
  9. package/dist/pi-transcript-tools.js +8 -3
  10. package/dist/runtime-host-session-channel.js +71 -47
  11. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  12. package/node_modules/@maka/core/dist/relative-time.js +9 -1
  13. package/node_modules/@maka/core/dist/session.js +0 -15
  14. package/node_modules/@maka/core/dist/tool-quiet-preview.js +31 -0
  15. package/node_modules/@maka/core/dist/transcript-search.js +0 -1
  16. package/node_modules/@maka/runtime/dist/conversation-copy.js +7 -1
  17. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +0 -1
  18. package/node_modules/@maka/runtime-host/dist/client/client-capability-channel.js +3 -1
  19. package/node_modules/@maka/runtime-host/dist/client/connection.js +2 -2
  20. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +0 -3
  21. package/node_modules/@maka/runtime-host/dist/protocol/client-capability.js +19 -1
  22. package/node_modules/@maka/runtime-host/dist/protocol/index.js +4 -1
  23. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +1 -2
  24. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +122 -9
  25. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +11 -6
  26. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +5 -0
  27. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +0 -16
  28. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +3 -38
  29. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +0 -3
  30. package/node_modules/@maka/storage/dist/interaction-store.js +0 -13
  31. package/node_modules/@maka/storage/dist/runtime-partial-values.js +5 -1
  32. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +1 -3
  33. package/node_modules/@maka/storage/dist/usage-screen.js +101 -35
  34. package/package.json +1 -1
@@ -20,8 +20,8 @@ import { randomUUID } from 'node:crypto';
20
20
  import { realpath } from 'node:fs/promises';
21
21
  import { isAbsolute, normalize } from 'node:path';
22
22
  import { RequestError, } from '@agentclientprotocol/sdk';
23
- import { isRuntimeHostTerminalTurn } from '@maka/runtime-host/adapter';
24
- import { readRuntimeHostConnectionCatalog, readRuntimeHostSessionCatalogPage, RuntimeHostCatalogReadError, RuntimeHostOperationError, RuntimeHostRequestInterruptedError, RuntimeHostSubscriptionError, RuntimeHostSessionCatalogRevisionChangedError, } from '@maka/runtime-host/client';
23
+ import { isRuntimeHostTerminalTurn, } from '@maka/runtime-host/adapter';
24
+ import { abortable, readRuntimeHostConnectionCatalog, readRuntimeHostSessionCatalogPage, RuntimeHostCatalogReadError, RuntimeHostOperationError, RuntimeHostRequestInterruptedError, RuntimeHostSubscriptionError, RuntimeHostSessionCatalogRevisionChangedError, } from '@maka/runtime-host/client';
25
25
  import { SESSION_CATALOG_CURSOR_MAX_BYTES, SESSION_CATALOG_CWD_MAX_BYTES, HOST_OPERATION_SPECS, } from '@maka/runtime-host/protocol';
26
26
  import { RuntimeHostSessionChannel } from '../runtime-host-session-channel.js';
27
27
  import { RuntimeHostSessionUpdateError, getRuntimeHostSession, requireRuntimeHostSessionProjection, updateRuntimeHostSession, } from '../runtime-host-session-update.js';
@@ -30,10 +30,22 @@ import { AcpSessionEventMapper } from './session-event-mapper.js';
30
30
  import { mapAcpPromptContent, publishAcpPromptAttachments } from './prompt-content.js';
31
31
  import { AcpSessionMcp, createAcpMcpConfig } from './session-mcp.js';
32
32
  import { AcpSessionInteractions } from './session-interactions.js';
33
+ import { AcpTurnObservation, AcpAdmittedTurnObservation } from './turn-observation.js';
33
34
  const ACP_SESSION_CURSOR_MAX_BYTES = 8 * 1024;
34
35
  const ADMISSION_QUERY_MAX_ATTEMPTS = 5;
35
36
  const ADMISSION_QUERY_TIMEOUT_MS = 1_000;
36
37
  const ADMISSION_QUERY_RETRY_MS = 25;
38
+ const TURN_STOP_TIMEOUT_MS = 30_000;
39
+ const COPY_RECONCILIATION_TIMEOUT_MS = 30_000;
40
+ const UNAVAILABLE_INTERACTION_CLIENT = {
41
+ capabilities: {},
42
+ requestPermission: async () => {
43
+ throw RequestError.methodNotFound('session/request_permission');
44
+ },
45
+ createElicitation: async () => {
46
+ throw RequestError.methodNotFound('elicitation/create');
47
+ },
48
+ };
37
49
  /** Owns all Runtime Host resources associated with one ACP connection. */
38
50
  export class AcpSessionRegistry {
39
51
  #connect;
@@ -48,8 +60,17 @@ export class AcpSessionRegistry {
48
60
  #attachmentOpenControllers = new Map();
49
61
  #attachmentConfigurations = new Map();
50
62
  #pendingConfigSets = new Map();
51
- #activePrompts = new Map();
63
+ #attachmentWaiters = new Map();
64
+ #turnObservations = new Map();
65
+ #discardedAttachments = new WeakSet();
66
+ #externalObservationContexts = new Map();
67
+ #externalContextLeases = new Map();
52
68
  #sessionCloseTasks = new Map();
69
+ #sessionCloseGenerations = new Map();
70
+ #sessionLoadTails = new Map();
71
+ #sessionLoadControllers = new Map();
72
+ #historyReplays = new Set();
73
+ #historyReplayDelivery = new Map();
53
74
  #connection;
54
75
  #connectTask;
55
76
  #connectAbortController;
@@ -67,6 +88,24 @@ export class AcpSessionRegistry {
67
88
  const mcpConfig = createAcpMcpConfig(params);
68
89
  return this.#track(this.#create(params, mcpConfig, signal));
69
90
  }
91
+ async load(params, context) {
92
+ this.#assertOpen('subscription.open');
93
+ validateNewSessionParams(params);
94
+ const mcpConfig = createAcpMcpConfig(params);
95
+ await this.#sessionCloseTasks.get(params.sessionId)?.catch(() => undefined);
96
+ this.#assertOpen('subscription.open');
97
+ const generation = this.#sessionCloseGenerations.get(params.sessionId) ?? 0;
98
+ return this.#track(this.#queueLoad(params.sessionId, () => this.#load(params, context, mcpConfig, true, generation)));
99
+ }
100
+ async resume(params, context) {
101
+ this.#assertOpen('subscription.open');
102
+ validateNewSessionParams(params);
103
+ const mcpConfig = createAcpMcpConfig({ ...params, mcpServers: params.mcpServers ?? [] });
104
+ await this.#sessionCloseTasks.get(params.sessionId)?.catch(() => undefined);
105
+ this.#assertOpen('subscription.open');
106
+ const generation = this.#sessionCloseGenerations.get(params.sessionId) ?? 0;
107
+ return this.#track(this.#queueLoad(params.sessionId, () => this.#load(params, context, mcpConfig, false, generation)));
108
+ }
70
109
  async list(params) {
71
110
  this.#assertOpen('session.catalog.query');
72
111
  return this.#track(this.#list(params));
@@ -111,13 +150,67 @@ export class AcpSessionRegistry {
111
150
  return;
112
151
  await this.#cancelSession(params.sessionId);
113
152
  }
153
+ async resumeTurn(params, context) {
154
+ this.#assertOpen('turn.resume.query');
155
+ this.#assertOwned(params.sessionId);
156
+ return this.#track(this.#resumeTurn(params, context));
157
+ }
158
+ async queryCopySource(params) {
159
+ this.#assertOpen('session.turns.query');
160
+ this.#assertOwned(params.sessionId);
161
+ return this.#track(this.#queryCopySource(params));
162
+ }
163
+ async #queryCopySource(params) {
164
+ const connection = await this.#getConnection('session.turns.query');
165
+ this.#assertOwned(params.sessionId);
166
+ let session;
167
+ try {
168
+ session = await getRuntimeHostSession(connection, params.sessionId);
169
+ }
170
+ catch (error) {
171
+ throw requestErrorFromSessionUpdate(error, 'session.catalog.query');
172
+ }
173
+ if (!session)
174
+ throw unknownSessionError();
175
+ this.#assertOwned(params.sessionId);
176
+ try {
177
+ const page = await connection.request('session.turns.query', params);
178
+ this.#assertOwned(params.sessionId);
179
+ // Read the revision before the page: concurrent source changes leave a
180
+ // stale CAS token, which Host rejects instead of silently copying new data.
181
+ return { ...page, expectedSourceRevision: session.revision };
182
+ }
183
+ catch (error) {
184
+ if (error instanceof RequestError)
185
+ throw error;
186
+ throw requestErrorFromRuntimeHost(error, 'session.turns.query');
187
+ }
188
+ }
189
+ async branch(params) {
190
+ return this.#track(this.#copySession('session.branch.create', params));
191
+ }
192
+ async createRevision(params) {
193
+ return this.#track(this.#copySession('session.revision.create', params));
194
+ }
195
+ async abandonRevision(params) {
196
+ this.#assertOpen('session.revision.abandon');
197
+ this.#assertOwned(params.targetSessionId);
198
+ const task = this.#track(this.#abandonRevision(params));
199
+ return task;
200
+ }
114
201
  async close(params) {
115
202
  this.#assertOpen('session.close');
116
203
  const existing = this.#sessionCloseTasks.get(params.sessionId);
117
204
  if (existing)
118
205
  return existing;
119
- this.#assertOwned(params.sessionId);
206
+ if (!this.#ownedSessionIds.has(params.sessionId) &&
207
+ !this.#sessionLoadTails.has(params.sessionId)) {
208
+ throw unknownSessionError();
209
+ }
210
+ this.#sessionCloseGenerations.set(params.sessionId, (this.#sessionCloseGenerations.get(params.sessionId) ?? 0) + 1);
211
+ this.#sessionLoadControllers.get(params.sessionId)?.abort();
120
212
  this.#ownedSessionIds.delete(params.sessionId);
213
+ this.#historyReplayDelivery.delete(params.sessionId);
121
214
  const configuration = this.#attachmentConfigurations.get(params.sessionId);
122
215
  const delivery = configuration?.delivery;
123
216
  this.#attachmentConfigurations.delete(params.sessionId);
@@ -135,35 +228,26 @@ export class AcpSessionRegistry {
135
228
  this.#closing = true;
136
229
  this.#connectAbortController?.abort();
137
230
  this.#creationAbort.abort();
231
+ for (const controller of this.#sessionLoadControllers.values())
232
+ controller.abort();
138
233
  this.#disposeTask ??= this.#dispose();
139
234
  return this.#disposeTask;
140
235
  }
141
236
  async #prompt(params, context) {
142
237
  const turnId = this.#newTurnId();
143
- const projectionAbort = new AbortController();
144
- const reconciliationAbort = new AbortController();
145
- const active = {
238
+ const active = new AcpAdmittedTurnObservation({
146
239
  sessionId: params.sessionId,
147
240
  turnId,
148
- mapper: new AcpSessionEventMapper({
149
- sessionId: params.sessionId,
150
- notify: async (notification) => {
151
- if (!this.#closing && this.#ownedSessionIds.has(params.sessionId)) {
152
- await context.notify(notification);
153
- }
154
- },
155
- signal: projectionAbort.signal,
156
- }),
157
- waiters: new Set(),
158
- projectionAbort,
159
- reconciliationAbort,
160
- dispatchStarted: false,
161
- startRequestSettled: false,
162
- admissionSettled: false,
163
- cancelled: false,
164
- finished: false,
165
- };
166
- this.#addActivePrompt(active);
241
+ notify: async (notification) => {
242
+ if (!this.#closing && this.#ownedSessionIds.has(params.sessionId)) {
243
+ await context.notify(notification);
244
+ this.#recordLiveHistoryDelivery(params.sessionId, notification, active);
245
+ }
246
+ },
247
+ });
248
+ if (this.#historyReplays.has(params.sessionId))
249
+ void active.holdLive().catch(() => undefined);
250
+ this.#setTurnObservation(active);
167
251
  const onAbort = () => {
168
252
  void this.#cancelPrompt(active).catch(() => undefined);
169
253
  };
@@ -188,7 +272,10 @@ export class AcpSessionRegistry {
188
272
  const connection = await this.#getConnection('subscription.open');
189
273
  let attachment;
190
274
  try {
191
- attachment = await this.#ensureAttachment(params.sessionId, connection, context);
275
+ attachment = await this.#ensureAttachment(params.sessionId, connection, {
276
+ ...context,
277
+ signal: active.projectionAbort.signal,
278
+ });
192
279
  }
193
280
  catch (error) {
194
281
  if (active.cancelled)
@@ -196,7 +283,7 @@ export class AcpSessionRegistry {
196
283
  throw error;
197
284
  }
198
285
  active.attachment = attachment;
199
- this.#wake(active);
286
+ active.wake();
200
287
  if (active.cancelled)
201
288
  return { stopReason: await this.#cancelledStopReason(active) };
202
289
  try {
@@ -224,20 +311,15 @@ export class AcpSessionRegistry {
224
311
  await this.#mcps.get(params.sessionId)?.ready(active.projectionAbort.signal);
225
312
  if (active.cancelled)
226
313
  return { stopReason: await this.#cancelledStopReason(active) };
227
- active.transcript = attachment.trackPromptTranscript(turnId);
228
- const observation = this.#consumePromptEvents(active, attachment.eventsForTurn(turnId));
314
+ this.#assertOwned(params.sessionId);
315
+ const observation = active.start(attachment);
229
316
  // Mark the observer as handled immediately: turn.start may still be in flight
230
317
  // when the live subscription reports a failure.
231
318
  void observation.catch(() => undefined);
232
- active.dispatchStarted = true;
233
- this.#wake(active);
319
+ active.markDispatched();
234
320
  try {
235
321
  const result = await connection.request('turn.start', startInput);
236
- active.startRequestSettled = true;
237
- active.admissionSettled = true;
238
- if (result.kind === 'started')
239
- active.startedTurn = result.turn;
240
- this.#wake(active);
322
+ active.settleStartRequest(result.kind === 'started' ? result.turn : undefined);
241
323
  if (result.kind === 'blocked') {
242
324
  const error = new Error('Runtime Host blocked the requested Turn');
243
325
  attachment.failTurn(turnId, error);
@@ -247,12 +329,10 @@ export class AcpSessionRegistry {
247
329
  catch (error) {
248
330
  // A lost dispatched response does not establish whether Host admitted
249
331
  // this Turn. Retain this attempt until subscription or query facts do.
250
- active.startRequestSettled = true;
251
- active.admissionSettled ||= !(error instanceof RuntimeHostRequestInterruptedError && error.dispatch === 'dispatched');
252
- if (!active.admissionSettled) {
332
+ active.failStartRequest(error);
333
+ if (!active.admission.settled) {
253
334
  this.#queryPromptAdmission(active, connection);
254
335
  }
255
- this.#wake(active);
256
336
  attachment.failTurn(turnId, error);
257
337
  if (!active.cancelled)
258
338
  throw requestErrorFromRuntimeHost(error, 'turn.start');
@@ -270,8 +350,8 @@ export class AcpSessionRegistry {
270
350
  await active.stopTask.catch(() => undefined);
271
351
  if (active.cancelled)
272
352
  return { stopReason: await this.#cancelledStopReason(active) };
273
- if (active.admissionFailure)
274
- throw active.admissionFailure;
353
+ if (active.admission.failure)
354
+ throw active.admission.failure;
275
355
  if (error instanceof RequestError)
276
356
  throw error;
277
357
  throw requestErrorFromRuntimeHost(error, 'subscription.open');
@@ -281,78 +361,27 @@ export class AcpSessionRegistry {
281
361
  // A terminal subscription event can precede the Stop response. Retain this
282
362
  // prompt so close/dispose cannot release its connection while Stop is in flight.
283
363
  await active.stopTask?.catch(() => undefined);
284
- active.projectionAbort.abort();
285
- active.reconciliationAbort.abort();
286
- active.transcript?.dispose();
364
+ active.dispose();
287
365
  this.#attachmentInteractions.get(active.sessionId)?.settleTurn(active.turnId);
288
366
  const observed = active.attachment?.snapshot.rootTurn;
289
367
  if (observed?.turnId === active.turnId && isRuntimeHostTerminalTurn(observed)) {
290
368
  this.#attachmentInteractions.get(active.sessionId)?.terminalTurn(active.turnId);
291
369
  }
292
- active.finished = true;
293
- this.#wake(active);
294
- this.#removeActivePrompt(active);
295
- }
296
- }
297
- async #consumePromptEvents(active, events) {
298
- let terminalStatus = 'completed';
299
- try {
300
- for await (const event of events) {
301
- if (event.type === 'abort')
302
- terminalStatus = 'cancelled';
303
- else if (event.type === 'error' && !event.recoverable)
304
- terminalStatus = 'failed';
305
- if (terminalStatus !== 'completed')
306
- active.reconciliationAbort.abort();
307
- if (!active.cancelled)
308
- await active.mapper.accept(event);
309
- }
310
- if (active.cancelled)
311
- return this.#cancelledStopReason(active);
312
- if (terminalStatus === 'completed')
313
- await this.#reconcilePrompt(active, true);
314
- else
315
- active.reconciliationAbort.abort();
316
- if (active.projectionFailure)
317
- throw active.projectionFailure;
318
- await active.mapper.finishTools(active.turnId, terminalStatus);
319
- await active.mapper.flush();
320
- return active.cancelled ? this.#cancelledStopReason(active) : 'end_turn';
321
- }
322
- catch (error) {
323
- if (active.cancelled)
324
- return this.#cancelledStopReason(active);
325
- throw error;
326
- }
327
- }
328
- async #reconcilePrompt(active, replay = false) {
329
- if (active.cancelled || active.finished || !active.transcript)
330
- return;
331
- try {
332
- await active.transcript.reconcile((messages) => active.mapper.acceptTranscriptMessages(active.turnId, messages), AbortSignal.any([active.projectionAbort.signal, active.reconciliationAbort.signal]),
333
- // One final replay observes revisions below the consumed cut before end_turn.
334
- { replay });
335
- }
336
- catch (error) {
337
- if (active.cancelled ||
338
- active.finished ||
339
- active.projectionAbort.signal.aborted ||
340
- active.reconciliationAbort.signal.aborted)
341
- return;
342
- active.projectionFailure ??= error;
343
- active.attachment?.failTurn(active.turnId, error);
344
- throw error;
370
+ active.wake();
371
+ this.#removeTurnObservation(active);
345
372
  }
346
373
  }
347
374
  async #cancelledStopReason(active) {
348
- // A failed notification must not change the outcome of an explicit Host
349
- // cancellation. The projection failure still fails uncancelled prompts.
350
- await active.mapper.flush().catch(() => undefined);
351
- return 'cancelled';
375
+ return active.cancelledStopReason();
352
376
  }
353
377
  #cancelSession(sessionId) {
354
- const active = [...(this.#activePrompts.get(sessionId) ?? [])];
378
+ const active = this.#admittedTurns(sessionId);
355
379
  const cancellations = active.map((prompt) => this.#cancelPrompt(prompt));
380
+ for (const observation of this.#turnObservations.get(sessionId)?.values() ?? []) {
381
+ if (!(observation instanceof AcpAdmittedTurnObservation) && observation.stopTask) {
382
+ cancellations.push(observation.stopTask);
383
+ }
384
+ }
356
385
  this.#attachmentOpenControllers.get(sessionId)?.abort();
357
386
  const attachment = this.#attachments.get(sessionId);
358
387
  if (attachment) {
@@ -363,22 +392,44 @@ export class AcpSessionRegistry {
363
392
  if (root &&
364
393
  !isRuntimeHostTerminalTurn(root) &&
365
394
  !active.some((prompt) => prompt.turnId === root.turnId)) {
366
- await this.#connection?.request('turn.stop', {
367
- sessionId: root.sessionId,
368
- turnId: root.turnId,
369
- runId: root.runId,
370
- });
395
+ const observation = this.#observation(sessionId, root.turnId);
396
+ if (observation && observation.attachment === opened) {
397
+ observation.stopTask ??= this.#stopAttachedTurn(opened, root);
398
+ await observation.stopTask;
399
+ }
400
+ else {
401
+ await this.#stopAttachedTurn(opened, root);
402
+ }
371
403
  }
372
404
  }, () => undefined));
373
405
  }
374
406
  return Promise.allSettled(cancellations);
375
407
  }
408
+ #stopAttachedTurn(attachment, root) {
409
+ const current = attachment.snapshot.rootTurn;
410
+ if (!current ||
411
+ current.sessionId !== root.sessionId ||
412
+ current.turnId !== root.turnId ||
413
+ current.runId !== root.runId ||
414
+ isRuntimeHostTerminalTurn(current))
415
+ return Promise.resolve();
416
+ const observation = this.#observation(root.sessionId, root.turnId);
417
+ if (observation && observation.runId !== undefined && observation.runId !== root.runId)
418
+ return Promise.resolve();
419
+ if (observation && observation.attachment === attachment) {
420
+ observation.cancelled = true;
421
+ observation.projectionAbort.abort();
422
+ observation.reconciliationAbort.abort();
423
+ }
424
+ // Fence before sending Stop: a failed delivery cannot authorize a late answer.
425
+ this.#attachmentInteractions.get(root.sessionId)?.cancelTurn(root.turnId);
426
+ return (this.#connection
427
+ ?.request('turn.stop', { sessionId: root.sessionId, turnId: root.turnId, runId: root.runId }, TURN_STOP_TIMEOUT_MS)
428
+ .then(() => undefined) ?? Promise.resolve());
429
+ }
376
430
  async #cancelPrompt(active) {
377
431
  active.cancelled = true;
378
- this.#wake(active);
379
- if ([...(this.#activePrompts.get(active.sessionId) ?? [])].every((prompt) => prompt.cancelled && !prompt.dispatchStarted)) {
380
- this.#attachmentOpenControllers.get(active.sessionId)?.abort();
381
- }
432
+ active.wake();
382
433
  active.projectionAbort.abort();
383
434
  active.reconciliationAbort.abort();
384
435
  this.#attachmentInteractions.get(active.sessionId)?.cancelTurn(active.turnId);
@@ -394,13 +445,13 @@ export class AcpSessionRegistry {
394
445
  ]);
395
446
  }
396
447
  async #stopPromptWhenObservable(active) {
397
- if (!active.dispatchStarted)
448
+ if (!active.admission.dispatchStarted)
398
449
  return;
399
450
  while (!active.finished) {
400
451
  const observed = active.attachment?.snapshot.rootTurn;
401
452
  // Subscription teardown can precede the start response. Keep the admitted
402
453
  // identity until exact Stop completes, even when observation has ended.
403
- const root = observed?.turnId === active.turnId ? observed : active.startedTurn;
454
+ const root = observed?.turnId === active.turnId ? observed : active.admission.startedTurn;
404
455
  if (root) {
405
456
  if (isRuntimeHostTerminalTurn(root))
406
457
  return;
@@ -408,11 +459,7 @@ export class AcpSessionRegistry {
408
459
  if (!connection)
409
460
  return;
410
461
  try {
411
- await connection.request('turn.stop', {
412
- sessionId: root.sessionId,
413
- turnId: root.turnId,
414
- runId: root.runId,
415
- });
462
+ await connection.request('turn.stop', { sessionId: root.sessionId, turnId: root.turnId, runId: root.runId }, TURN_STOP_TIMEOUT_MS);
416
463
  }
417
464
  catch (error) {
418
465
  console.error('[acp] Host Stop delivery failed:', error);
@@ -420,71 +467,92 @@ export class AcpSessionRegistry {
420
467
  }
421
468
  return;
422
469
  }
423
- if (active.admissionSettled && active.startRequestSettled)
470
+ if (active.admission.settled && active.admission.startRequestSettled)
424
471
  return;
425
- if (active.admissionFailure) {
426
- console.error('[acp] Host Turn admission remains unknown:', active.admissionFailure);
427
- throw active.admissionFailure;
472
+ if (active.admission.failure) {
473
+ console.error('[acp] Host Turn admission remains unknown:', active.admission.failure);
474
+ throw active.admission.failure;
428
475
  }
429
- await this.#waitForPromptChange(active);
476
+ await active.waitForChange();
430
477
  }
431
478
  }
432
479
  #queryPromptAdmission(active, connection) {
433
480
  // Recovery and the lost start response can both request this read. Keep one
434
- // bounded retry task; neither a healthy subscription nor a failed query
435
- // establishes whether a dispatched start was admitted.
436
- active.admissionQuery ??= this.#readPromptAdmission(active, connection);
481
+ // bounded retry task; neither a healthy subscription nor a query failure
482
+ // other than not_found establishes whether a dispatched start was admitted.
483
+ active.admission.query ??= this.#readPromptAdmission(active, connection);
437
484
  }
438
485
  async #readPromptAdmission(active, connection) {
439
486
  let lastError;
440
487
  for (let attempt = 0; attempt < ADMISSION_QUERY_MAX_ATTEMPTS; attempt += 1) {
441
- if (active.finished || active.admissionSettled || (this.#closing && attempt > 0))
488
+ if (active.finished || active.admission.settled || (this.#closing && attempt > 0))
442
489
  return;
443
490
  const observed = active.attachment?.snapshot.rootTurn;
444
491
  if (observed?.turnId === active.turnId) {
445
- active.startedTurn = observed;
446
- active.admissionSettled = true;
447
- this.#wake(active);
492
+ active.observeStartedTurn(observed);
448
493
  return;
449
494
  }
450
495
  try {
451
496
  const turn = await connection.request('turn.query', { sessionId: active.sessionId, turnId: active.turnId }, ADMISSION_QUERY_TIMEOUT_MS);
452
- if (!active.finished && !active.admissionSettled) {
453
- active.startedTurn = turn;
454
- active.admissionSettled = true;
455
- this.#wake(active);
497
+ if (!active.finished && !active.admission.settled) {
498
+ active.observeStartedTurn(turn);
456
499
  }
457
500
  return;
458
501
  }
459
502
  catch (error) {
460
503
  if (error instanceof RuntimeHostOperationError && error.code === 'not_found') {
461
- active.admissionSettled = true;
462
- this.#wake(active);
504
+ const observed = active.attachment?.snapshot.rootTurn;
505
+ active.settleAbsentTurn(observed?.turnId === active.turnId ? observed : undefined);
463
506
  return;
464
507
  }
465
508
  lastError = error;
466
509
  }
467
- if (active.finished || active.admissionSettled || this.#closing)
510
+ if (active.finished || active.admission.settled || this.#closing)
468
511
  return;
469
512
  if (attempt + 1 < ADMISSION_QUERY_MAX_ATTEMPTS) {
470
- await this.#waitForPromptChange(active, ADMISSION_QUERY_RETRY_MS * 2 ** attempt);
513
+ await active.waitForChange(ADMISSION_QUERY_RETRY_MS * 2 ** attempt);
471
514
  }
472
515
  }
473
516
  if (active.attachment?.snapshot.rootTurn?.turnId === active.turnId) {
474
- this.#wake(active);
517
+ active.wake();
475
518
  return;
476
519
  }
477
- active.admissionFailure = RequestError.internalError({
520
+ active.failAdmission(RequestError.internalError({
478
521
  source: 'runtime_host',
479
522
  operation: 'turn.query',
480
523
  code: 'outcome_unknown',
481
524
  reason: 'admission_query_failed',
482
525
  attempts: ADMISSION_QUERY_MAX_ATTEMPTS,
483
526
  cause: runtimeHostErrorData(lastError, 'turn.query'),
484
- }, 'Runtime Host Turn admission could not be established; Stop could not be confirmed');
485
- this.#wake(active);
527
+ }, 'Runtime Host Turn admission could not be established; Stop could not be confirmed'));
486
528
  }
487
529
  async #ensureAttachment(sessionId, connection, context) {
530
+ context.signal.throwIfAborted();
531
+ let waiters = this.#attachmentWaiters.get(sessionId);
532
+ if (!waiters) {
533
+ waiters = new Set();
534
+ this.#attachmentWaiters.set(sessionId, waiters);
535
+ }
536
+ const waiter = {};
537
+ waiters.add(waiter);
538
+ try {
539
+ return await abortable(() => this.#openAttachment(sessionId, connection, context), context.signal);
540
+ }
541
+ finally {
542
+ waiters.delete(waiter);
543
+ if (waiters.size === 0 && this.#attachmentWaiters.get(sessionId) === waiters) {
544
+ this.#attachmentWaiters.delete(sessionId);
545
+ if (context.signal.aborted && !this.#hasAttachmentConsumers(sessionId)) {
546
+ this.#attachmentOpenControllers.get(sessionId)?.abort();
547
+ }
548
+ }
549
+ }
550
+ }
551
+ #hasAttachmentConsumers(sessionId) {
552
+ return ((this.#attachmentWaiters.get(sessionId)?.size ?? 0) > 0 ||
553
+ this.#admittedTurns(sessionId).some((active) => !active.cancelled && !active.finished));
554
+ }
555
+ async #openAttachment(sessionId, connection, context) {
488
556
  const existing = this.#attachments.get(sessionId);
489
557
  if (existing)
490
558
  return existing;
@@ -510,43 +578,43 @@ export class AcpSessionRegistry {
510
578
  const interactions = new AcpSessionInteractions({
511
579
  sessionId,
512
580
  connection,
513
- client: context.interactions ?? {
514
- capabilities: {},
515
- requestPermission: async () => {
516
- throw RequestError.methodNotFound('session/request_permission');
517
- },
518
- createElicitation: async () => {
519
- throw RequestError.methodNotFound('elicitation/create');
520
- },
521
- },
581
+ client: context.interactions ?? UNAVAILABLE_INTERACTION_CLIENT,
522
582
  onPending: async (pending) => {
523
- for (const active of this.#activePrompts.get(sessionId) ?? []) {
524
- if (active.turnId === pending.turnId && !active.cancelled) {
525
- await active.mapper.pendingInteraction(pending);
526
- }
583
+ const observation = this.#observation(sessionId, pending.turnId);
584
+ if (observation && !observation.cancelled) {
585
+ await observation.pendingInteraction(pending);
527
586
  }
528
587
  },
529
588
  onAnswered: (answered, pending) => attachment?.publishInteractionAnswer(answered, pending),
530
589
  onResolved: async (resolved, pending) => {
531
- for (const active of this.#activePrompts.get(sessionId) ?? []) {
532
- if (active.turnId === pending.turnId && !active.cancelled && !active.finished) {
533
- await active.mapper.resolvedInteraction(resolved, pending);
534
- }
590
+ const observation = this.#observation(sessionId, pending.turnId);
591
+ if (observation && !observation.cancelled && !observation.finished) {
592
+ await observation.resolvedInteraction(resolved, pending);
535
593
  }
536
594
  },
537
595
  onFailure: (pending, error) => {
538
- const active = [...(this.#activePrompts.get(sessionId) ?? [])].find((prompt) => prompt.turnId === pending.turnId && !prompt.finished);
539
- if (active?.attachment) {
540
- active.projectionFailure ??= error;
541
- active.attachment.failTurn(active.turnId, error);
596
+ const observation = this.#observation(sessionId, pending.turnId);
597
+ if (observation?.attachment) {
598
+ if (!(observation instanceof AcpAdmittedTurnObservation)) {
599
+ console.error('[acp] Attached interaction presentation failed:', error);
600
+ return;
601
+ }
602
+ observation.projectionFailure ??= error;
603
+ observation.attachment.failTurn(observation.turnId, error);
542
604
  }
543
605
  else if (!attachment)
544
606
  failAttachment(error);
545
607
  },
546
608
  onCancelled: (pending) => {
547
- for (const active of this.#activePrompts.get(sessionId) ?? []) {
548
- if (active.turnId === pending.turnId)
609
+ let localPrompt = false;
610
+ for (const active of this.#admittedTurns(sessionId)) {
611
+ if (active.turnId === pending.turnId) {
612
+ localPrompt = true;
549
613
  void this.#cancelPrompt(active).catch(() => undefined);
614
+ }
615
+ }
616
+ if (!localPrompt && this.#observation(sessionId, pending.turnId)) {
617
+ void this.#cancelSession(sessionId).catch(() => undefined);
550
618
  }
551
619
  },
552
620
  });
@@ -557,13 +625,33 @@ export class AcpSessionRegistry {
557
625
  openInitialSessionSubscription: connection.openSessionSubscriptionOnce.bind(connection),
558
626
  sessionId,
559
627
  now: Date.now,
560
- onTurnStarted: () => undefined,
628
+ onTurnStarted: (turn) => {
629
+ if (attachment)
630
+ void this.#adoptTurn(sessionId, turn.turnId, attachment, false, turn.runId, attachment.terminalTurn(turn.turnId)).catch((error) => {
631
+ console.error('[acp] Attached Turn observation failed:', error);
632
+ });
633
+ },
561
634
  onRuntimeResourceChanged: () => undefined,
562
635
  onSnapshotChanged: (snapshot) => {
636
+ if (attachment && this.#discardedAttachments.has(attachment))
637
+ return;
563
638
  this.#wakeSession(sessionId);
564
639
  if (snapshot.rootTurn && isRuntimeHostTerminalTurn(snapshot.rootTurn)) {
565
640
  interactions.terminalTurn(snapshot.rootTurn.turnId);
566
641
  }
642
+ const root = snapshot.rootTurn;
643
+ const observation = root && this.#observation(sessionId, root.turnId);
644
+ const prompt = observation instanceof AcpAdmittedTurnObservation ? observation : undefined;
645
+ const observedRunId = observation?.runId ??
646
+ prompt?.admission.startedTurn?.runId ??
647
+ observation?.terminalTurn?.runId;
648
+ if (root && observation && (observedRunId === undefined || observedRunId === root.runId)) {
649
+ if (isRuntimeHostTerminalTurn(root))
650
+ observation.terminalTurn = root;
651
+ if (prompt) {
652
+ prompt.observeStartedTurn(root);
653
+ }
654
+ }
567
655
  if (configuration.metadataRevision === undefined) {
568
656
  configuration.metadataRevision = snapshot.session.metadataRevision;
569
657
  return;
@@ -588,17 +676,20 @@ export class AcpSessionRegistry {
588
676
  });
589
677
  },
590
678
  onTranscriptReplaced: (turnId, messages) => {
591
- for (const active of this.#activePrompts.get(sessionId) ?? []) {
592
- if (active.turnId === turnId && !active.cancelled) {
593
- void active.mapper.replaceTranscript(turnId, messages).catch((error) => {
594
- active.attachment?.failTurn(turnId, error);
595
- });
596
- }
679
+ if (attachment && this.#discardedAttachments.has(attachment))
680
+ return;
681
+ const observation = this.#observation(sessionId, turnId);
682
+ if (observation && !observation.cancelled) {
683
+ void observation.replaceTranscript(messages).catch((error) => {
684
+ observation.attachment?.failTurn(turnId, error);
685
+ });
597
686
  }
598
687
  },
599
688
  onInteractionPending: (pending) => {
689
+ if (attachment && this.#discardedAttachments.has(attachment))
690
+ return;
600
691
  if (!interactions.fencesTurn(pending.turnId) &&
601
- ![...(this.#activePrompts.get(sessionId) ?? [])].some((active) => active.turnId === pending.turnId && active.dispatchStarted)) {
692
+ !this.#observation(sessionId, pending.turnId)) {
602
693
  // An idle attachment can observe another client's Turn; it does not
603
694
  // transfer that Turn's interaction authority to this ACP client.
604
695
  return;
@@ -606,24 +697,27 @@ export class AcpSessionRegistry {
606
697
  void interactions.pending(pending);
607
698
  },
608
699
  onInteractionResolved: (pending) => {
700
+ if (attachment && this.#discardedAttachments.has(attachment))
701
+ return;
609
702
  if (!interactions.fencesTurn(pending.turnId) &&
610
- ![...(this.#activePrompts.get(sessionId) ?? [])].some((active) => active.turnId === pending.turnId && active.dispatchStarted))
703
+ !this.#observation(sessionId, pending.turnId))
611
704
  return;
612
705
  void interactions.resolved(pending);
613
706
  },
614
707
  onTranscriptSettlement: (turnId) => {
615
- for (const active of this.#activePrompts.get(sessionId) ?? []) {
616
- if (active.turnId === turnId)
617
- void this.#reconcilePrompt(active).catch(() => undefined);
618
- }
708
+ if (attachment && this.#discardedAttachments.has(attachment))
709
+ return;
710
+ void this.#observation(sessionId, turnId)
711
+ ?.reconcile()
712
+ .catch(() => undefined);
619
713
  },
620
714
  onGoalChanged: () => undefined,
621
715
  onFailed: failAttachment,
622
716
  onRecovered: () => {
623
- for (const active of this.#activePrompts.get(sessionId) ?? []) {
717
+ for (const active of this.#admittedTurns(sessionId)) {
624
718
  if (active.attachment !== attachment ||
625
- !active.startRequestSettled ||
626
- active.admissionSettled) {
719
+ !active.admission.startRequestSettled ||
720
+ active.admission.settled) {
627
721
  continue;
628
722
  }
629
723
  // Recovery may hydrate a snapshot taken before start admission.
@@ -632,22 +726,29 @@ export class AcpSessionRegistry {
632
726
  if (attachment?.snapshot.rootTurn?.turnId !== active.turnId) {
633
727
  this.#queryPromptAdmission(active, connection);
634
728
  }
635
- this.#wake(active);
729
+ active.wake();
636
730
  }
637
731
  },
638
732
  })
639
- .then(({ channel }) => {
640
- channel.activate();
733
+ .then(async ({ channel, attachedTurnId }) => {
641
734
  attachment = channel;
642
735
  if (earlyFailure) {
643
736
  this.#retireFailedAttachment(sessionId, task, channel, earlyFailure);
644
737
  throw earlyFailure;
645
738
  }
646
739
  if (this.#closing || !this.#ownedSessionIds.has(sessionId)) {
647
- return channel.close().then(() => {
648
- throw this.#closing ? registryClosedError('subscription.open') : unknownSessionError();
649
- });
740
+ await channel.close();
741
+ throw this.#closing ? registryClosedError('subscription.open') : unknownSessionError();
650
742
  }
743
+ if (attachedTurnId) {
744
+ const root = channel.snapshot.rootTurn;
745
+ await this.#adoptTurn(sessionId, attachedTurnId, channel, false, root?.turnId === attachedTurnId
746
+ ? root.runId
747
+ : channel.terminalTurn(attachedTurnId)?.runId, channel.terminalTurn(attachedTurnId));
748
+ }
749
+ channel.activate(attachedTurnId && this.#observation(sessionId, attachedTurnId)
750
+ ? attachedTurnId
751
+ : undefined);
651
752
  return channel;
652
753
  })
653
754
  .catch((error) => {
@@ -672,28 +773,50 @@ export class AcpSessionRegistry {
672
773
  return task;
673
774
  }
674
775
  #retireFailedAttachment(sessionId, task, attachment, error) {
675
- if (this.#attachments.get(sessionId) === task) {
676
- this.#attachments.delete(sessionId);
677
- this.#attachmentConfigurations.delete(sessionId);
678
- this.#attachmentInteractions.get(sessionId)?.close();
679
- this.#attachmentInteractions.delete(sessionId);
680
- }
681
- for (const active of this.#activePrompts.get(sessionId) ?? []) {
776
+ this.#detachAttachment(sessionId, task);
777
+ for (const active of this.#admittedTurns(sessionId)) {
682
778
  if (active.attachment !== attachment)
683
779
  continue;
684
780
  // Losing observation cannot settle a dispatched start. Its pending
685
781
  // response or bounded admission query still owns the exact Stop identity.
686
782
  attachment.failTurn(active.turnId, error);
687
- this.#wake(active);
783
+ active.wake();
784
+ }
785
+ for (const observation of this.#turnObservations.get(sessionId)?.values() ?? []) {
786
+ if (observation.attachment !== attachment ||
787
+ observation instanceof AcpAdmittedTurnObservation)
788
+ continue;
789
+ observation.attachment.failTurn(observation.turnId, error);
688
790
  }
689
791
  void attachment.close().catch(() => undefined);
690
792
  }
691
- async #closeSession(sessionId, delivery) {
692
- const cancellation = await this.#cancelSession(sessionId);
793
+ #detachAttachment(sessionId, expected = this.#attachments.get(sessionId)) {
794
+ if (!expected || this.#attachments.get(sessionId) !== expected)
795
+ return;
796
+ this.#attachmentOpenControllers.get(sessionId)?.abort();
693
797
  this.#attachmentInteractions.get(sessionId)?.close();
694
798
  this.#attachmentInteractions.delete(sessionId);
695
- const attachmentTask = this.#attachments.get(sessionId);
799
+ this.#attachmentConfigurations.delete(sessionId);
696
800
  this.#attachments.delete(sessionId);
801
+ return expected;
802
+ }
803
+ #detachMcp(sessionId, expected = this.#mcps.get(sessionId)) {
804
+ if (!expected || this.#mcps.get(sessionId) !== expected)
805
+ return;
806
+ this.#mcps.delete(sessionId);
807
+ return expected;
808
+ }
809
+ async #closeSession(sessionId, delivery) {
810
+ const cancellation = await this.#cancelSession(sessionId);
811
+ this.#externalObservationContexts.delete(sessionId);
812
+ this.#externalContextLeases.delete(sessionId);
813
+ for (const observation of this.#turnObservations.get(sessionId)?.values() ?? []) {
814
+ if (!(observation instanceof AcpAdmittedTurnObservation)) {
815
+ observation.dispose();
816
+ this.#removeTurnObservation(observation);
817
+ }
818
+ }
819
+ const attachmentTask = this.#detachAttachment(sessionId);
697
820
  let closeError;
698
821
  if (attachmentTask) {
699
822
  try {
@@ -705,8 +828,7 @@ export class AcpSessionRegistry {
705
828
  closeError = error;
706
829
  }
707
830
  }
708
- const mcp = this.#mcps.get(sessionId);
709
- this.#mcps.delete(sessionId);
831
+ const mcp = this.#detachMcp(sessionId);
710
832
  try {
711
833
  await mcp?.close();
712
834
  }
@@ -721,41 +843,391 @@ export class AcpSessionRegistry {
721
843
  throw closeError;
722
844
  return {};
723
845
  }
724
- #addActivePrompt(active) {
725
- const prompts = this.#activePrompts.get(active.sessionId);
726
- if (prompts)
727
- prompts.add(active);
846
+ async #adoptTurn(sessionId, turnId, attachment, trackAdmission = false, expectedRunId, initialTerminalTurn) {
847
+ const context = this.#externalObservationContexts.get(sessionId);
848
+ if (!context ||
849
+ this.#closing ||
850
+ this.#discardedAttachments.has(attachment) ||
851
+ !this.#ownedSessionIds.has(sessionId))
852
+ return;
853
+ const existing = this.#observation(sessionId, turnId);
854
+ if (existing) {
855
+ this.#replayPendingInteractions(sessionId, turnId, attachment, existing);
856
+ return existing;
857
+ }
858
+ const runId = expectedRunId ??
859
+ (attachment.snapshot.rootTurn?.turnId === turnId
860
+ ? attachment.snapshot.rootTurn.runId
861
+ : undefined);
862
+ const Observation = trackAdmission ? AcpAdmittedTurnObservation : AcpTurnObservation;
863
+ const observation = new Observation({
864
+ sessionId,
865
+ turnId,
866
+ ...(runId === undefined ? {} : { runId }),
867
+ notify: async (notification) => {
868
+ const current = this.#externalObservationContexts.get(sessionId);
869
+ if (!this.#closing && this.#ownedSessionIds.has(sessionId) && current) {
870
+ await current.notify(notification);
871
+ this.#recordLiveHistoryDelivery(sessionId, notification, observation);
872
+ }
873
+ },
874
+ });
875
+ if (initialTerminalTurn?.runId === runId)
876
+ observation.terminalTurn = initialTerminalTurn;
877
+ if (this.#historyReplays.has(sessionId))
878
+ void observation.holdLive().catch(() => undefined);
879
+ const admission = observation instanceof AcpAdmittedTurnObservation ? observation : undefined;
880
+ if (admission)
881
+ this.#setTurnObservation(admission);
728
882
  else
729
- this.#activePrompts.set(active.sessionId, new Set([active]));
883
+ this.#setTurnObservation(observation);
884
+ try {
885
+ await observation.seed(attachment.messages);
886
+ if (this.#observation(sessionId, turnId) !== observation ||
887
+ this.#closing ||
888
+ this.#discardedAttachments.has(attachment)) {
889
+ observation.dispose();
890
+ if (admission)
891
+ this.#removeTurnObservation(admission);
892
+ else
893
+ this.#removeTurnObservation(observation);
894
+ return;
895
+ }
896
+ const task = observation.start(attachment);
897
+ this.#replayPendingInteractions(sessionId, turnId, attachment, observation);
898
+ const interactions = this.#attachmentInteractions.get(sessionId);
899
+ void task
900
+ .then(async () => {
901
+ if (observation.finished ||
902
+ this.#observation(sessionId, turnId) !== observation ||
903
+ this.#discardedAttachments.has(attachment))
904
+ return;
905
+ const root = observation.terminalTurn;
906
+ const outcome = root ?? observation.terminalOutcome;
907
+ const runId = root?.runId ?? observation.runId;
908
+ if (outcome && runId) {
909
+ await this.#externalObservationContexts.get(sessionId)?.notifyTurnStatus?.({
910
+ sessionId,
911
+ turnId,
912
+ runId,
913
+ status: outcome.status,
914
+ ...(outcome.status === 'failed'
915
+ ? { failureClass: outcome.failureClass ?? 'runtime_error' }
916
+ : {}),
917
+ });
918
+ }
919
+ }, async (error) => {
920
+ if (!this.#closing &&
921
+ !observation.finished &&
922
+ this.#observation(sessionId, turnId) === observation &&
923
+ !this.#discardedAttachments.has(attachment)) {
924
+ console.error('[acp] Attached Turn observation failed:', error);
925
+ const root = attachment.snapshot.rootTurn;
926
+ if (root?.turnId === turnId &&
927
+ (observation.runId === undefined || root.runId === observation.runId) &&
928
+ !isRuntimeHostTerminalTurn(root)) {
929
+ observation.stopTask ??= this.#stopAttachedTurn(attachment, root);
930
+ void observation.stopTask.catch((stopError) => {
931
+ console.error('[acp] Host Stop delivery failed:', stopError);
932
+ });
933
+ }
934
+ await this.#externalObservationContexts.get(sessionId)?.notifyTurnStatus?.({
935
+ sessionId,
936
+ turnId,
937
+ runId: root?.turnId === turnId ? root.runId : '',
938
+ status: 'observation_failed',
939
+ });
940
+ }
941
+ })
942
+ .catch((error) => {
943
+ console.error('[acp] Attached Turn status delivery failed:', error);
944
+ })
945
+ .finally(async () => {
946
+ if (admission) {
947
+ while (admission.admission.dispatchStarted &&
948
+ !admission.admission.startRequestSettled &&
949
+ !this.#closing) {
950
+ await admission.waitForChange();
951
+ }
952
+ }
953
+ await observation.stopTask?.catch(() => undefined);
954
+ if (admission)
955
+ this.#removeTurnObservation(admission);
956
+ interactions?.settleTurn(turnId);
957
+ observation.dispose();
958
+ this.#removeTurnObservation(observation);
959
+ });
960
+ return observation;
961
+ }
962
+ catch (error) {
963
+ observation.dispose();
964
+ if (admission)
965
+ this.#removeTurnObservation(admission);
966
+ else
967
+ this.#removeTurnObservation(observation);
968
+ throw error;
969
+ }
970
+ }
971
+ #replayPendingInteractions(sessionId, turnId, attachment, observation) {
972
+ if (observation.finished || this.#discardedAttachments.has(attachment))
973
+ return;
974
+ const interactions = this.#attachmentInteractions.get(sessionId);
975
+ for (const pending of attachment.snapshot.interactions.pending) {
976
+ if (pending.turnId === turnId)
977
+ void interactions?.pending(pending);
978
+ }
979
+ }
980
+ async #resumeTurn(params, context) {
981
+ context.signal.throwIfAborted();
982
+ const connection = await this.#getConnection('turn.resume.query');
983
+ let plan;
984
+ try {
985
+ plan = await connection.request('turn.resume.query', params);
986
+ }
987
+ catch (error) {
988
+ throw requestErrorFromRuntimeHost(error, 'turn.resume.query');
989
+ }
990
+ if (plan.disposition === 'parked')
991
+ return { kind: 'parked', plan };
992
+ const restoreContext = this.#installExternalContext(params.sessionId, context);
993
+ const restoreClient = this.#attachmentInteractions
994
+ .get(params.sessionId)
995
+ ?.setClient(context.interactions ?? UNAVAILABLE_INTERACTION_CLIENT);
996
+ let observation;
997
+ let attachment;
998
+ const turnId = this.#newTurnId();
999
+ let dispatched = false;
1000
+ const onAbort = () => {
1001
+ if (observation)
1002
+ void this.#cancelPrompt(observation).catch(() => undefined);
1003
+ };
1004
+ context.signal.addEventListener('abort', onAbort, { once: true });
1005
+ try {
1006
+ await this.#mcps.get(params.sessionId)?.ready(context.signal);
1007
+ attachment = await this.#ensureAttachment(params.sessionId, connection, context);
1008
+ context.signal.throwIfAborted();
1009
+ this.#assertOwned(params.sessionId);
1010
+ const adopted = await this.#adoptTurn(params.sessionId, turnId, attachment, true);
1011
+ if (!(adopted instanceof AcpAdmittedTurnObservation))
1012
+ throw registryClosedError('turn.resume.start');
1013
+ observation = adopted;
1014
+ if (context.signal.aborted)
1015
+ onAbort();
1016
+ if (observation.cancelled)
1017
+ throw RequestError.internalError({ source: 'adapter', operation: 'turn.resume.start', code: 'cancelled' }, 'Turn resume was cancelled before admission');
1018
+ dispatched = true;
1019
+ observation.markDispatched();
1020
+ const result = await connection.request('turn.resume.start', {
1021
+ sessionId: params.sessionId,
1022
+ turnId,
1023
+ sourceRunId: plan.sourceRunId,
1024
+ sourceRuntimeEventHighWater: plan.sourceRuntimeEventHighWater,
1025
+ });
1026
+ observation.settleStartRequest(result.kind === 'started' ? result.turn : undefined);
1027
+ if (result.kind === 'parked') {
1028
+ observation.dispose();
1029
+ this.#removeTurnObservation(observation);
1030
+ attachment.failTurn(turnId, new Error(`Turn resume parked: ${result.plan.reason}`));
1031
+ restoreContext.commit();
1032
+ restoreClient?.commit();
1033
+ return { kind: 'parked', plan: result.plan };
1034
+ }
1035
+ await observation.stopTask?.catch(() => undefined);
1036
+ restoreContext.commit();
1037
+ restoreClient?.commit();
1038
+ return {
1039
+ kind: 'started',
1040
+ turn: result.turn,
1041
+ sourceRunId: plan.sourceRunId,
1042
+ sourceRuntimeEventHighWater: plan.sourceRuntimeEventHighWater,
1043
+ };
1044
+ }
1045
+ catch (error) {
1046
+ let failure = error;
1047
+ if (observation) {
1048
+ observation.failStartRequest(error);
1049
+ }
1050
+ if (dispatched &&
1051
+ error instanceof RuntimeHostRequestInterruptedError &&
1052
+ error.dispatch === 'dispatched' &&
1053
+ observation) {
1054
+ this.#queryPromptAdmission(observation, connection);
1055
+ await observation.admission.query;
1056
+ if (observation.admission.startedTurn) {
1057
+ restoreContext.commit();
1058
+ restoreClient?.commit();
1059
+ return {
1060
+ kind: 'started',
1061
+ turn: observation.admission.startedTurn,
1062
+ sourceRunId: plan.sourceRunId,
1063
+ sourceRuntimeEventHighWater: plan.sourceRuntimeEventHighWater,
1064
+ };
1065
+ }
1066
+ const admissionError = RequestError.internalError({
1067
+ source: 'runtime_host',
1068
+ operation: 'turn.resume.start',
1069
+ code: 'outcome_unknown',
1070
+ sessionId: params.sessionId,
1071
+ turnId,
1072
+ sourceRunId: plan.sourceRunId,
1073
+ }, 'Runtime Host Turn resume admission could not be established');
1074
+ if (!observation.admission.rejected) {
1075
+ // The dispatched Turn may still be running, so its context and
1076
+ // interaction client remain the current attachment authority.
1077
+ restoreContext.commit();
1078
+ restoreClient?.commit();
1079
+ throw admissionError;
1080
+ }
1081
+ failure = admissionError;
1082
+ }
1083
+ if (observation) {
1084
+ observation.dispose();
1085
+ this.#removeTurnObservation(observation);
1086
+ attachment?.failTurn(turnId, failure);
1087
+ }
1088
+ restoreContext.rollback();
1089
+ restoreClient?.rollback();
1090
+ if (failure instanceof RequestError)
1091
+ throw failure;
1092
+ throw requestErrorFromRuntimeHost(failure, 'turn.resume.start', { turnId });
1093
+ }
1094
+ finally {
1095
+ context.signal.removeEventListener('abort', onAbort);
1096
+ }
1097
+ }
1098
+ async #copySession(operation, params) {
1099
+ this.#assertOpen(operation);
1100
+ this.#assertOwned(params.sourceSessionId);
1101
+ if (this.#ownedSessionIds.has(params.targetSessionId)) {
1102
+ throw RequestError.invalidParams({ field: 'targetSessionId', reason: 'already_owned' }, 'Target Session is already owned by this ACP connection');
1103
+ }
1104
+ const connection = await this.#getConnection(operation);
1105
+ this.#assertOwned(params.sourceSessionId);
1106
+ let result;
1107
+ try {
1108
+ result = await connection.request(operation, params);
1109
+ }
1110
+ catch (error) {
1111
+ if (error instanceof RuntimeHostRequestInterruptedError &&
1112
+ error.dispatch === 'dispatched' &&
1113
+ !this.#closing) {
1114
+ // The target ID alone is not proof of ownership: a lost response may
1115
+ // have been an operation_conflict with another caller's target. The
1116
+ // Host's exact copy request is idempotent by target and fingerprint.
1117
+ try {
1118
+ result = await connection.request(operation, params, COPY_RECONCILIATION_TIMEOUT_MS);
1119
+ }
1120
+ catch (reconciliationError) {
1121
+ throw requestErrorFromRuntimeHost(reconciliationError, operation, {
1122
+ targetSessionId: params.targetSessionId,
1123
+ });
1124
+ }
1125
+ }
1126
+ else {
1127
+ throw requestErrorFromRuntimeHost(error, operation, {
1128
+ targetSessionId: params.targetSessionId,
1129
+ });
1130
+ }
1131
+ }
1132
+ if (result.kind === 'committed' && !this.#closing) {
1133
+ this.#ownedSessionIds.add(params.targetSessionId);
1134
+ }
1135
+ return result;
1136
+ }
1137
+ async #abandonRevision(params) {
1138
+ const connection = await this.#getConnection('session.revision.abandon');
1139
+ this.#assertOwned(params.targetSessionId);
1140
+ let result;
1141
+ try {
1142
+ result = await connection.request('session.revision.abandon', params);
1143
+ }
1144
+ catch (error) {
1145
+ throw requestErrorFromRuntimeHost(error, 'session.revision.abandon');
1146
+ }
1147
+ if (result.kind === 'abandoned') {
1148
+ this.#sessionCloseGenerations.set(params.targetSessionId, (this.#sessionCloseGenerations.get(params.targetSessionId) ?? 0) + 1);
1149
+ this.#sessionLoadControllers.get(params.targetSessionId)?.abort();
1150
+ this.#ownedSessionIds.delete(params.targetSessionId);
1151
+ this.#historyReplayDelivery.delete(params.targetSessionId);
1152
+ this.#externalObservationContexts.delete(params.targetSessionId);
1153
+ this.#externalContextLeases.delete(params.targetSessionId);
1154
+ for (const observation of this.#turnObservations.get(params.targetSessionId)?.values() ??
1155
+ []) {
1156
+ observation.cancelled = true;
1157
+ observation.dispose();
1158
+ if (observation instanceof AcpAdmittedTurnObservation)
1159
+ observation.wake();
1160
+ else
1161
+ this.#removeTurnObservation(observation);
1162
+ }
1163
+ const attachment = this.#detachAttachment(params.targetSessionId);
1164
+ const mcp = this.#detachMcp(params.targetSessionId);
1165
+ await Promise.allSettled([
1166
+ attachment?.then((channel) => channel.close(), () => undefined),
1167
+ mcp?.close(),
1168
+ ]);
1169
+ }
1170
+ return result;
1171
+ }
1172
+ #admittedTurns(sessionId) {
1173
+ return [...(this.#turnObservations.get(sessionId)?.values() ?? [])].filter((observation) => observation instanceof AcpAdmittedTurnObservation);
1174
+ }
1175
+ #installExternalContext(sessionId, context) {
1176
+ const lease = {
1177
+ context,
1178
+ previous: this.#externalContextLeases.get(sessionId),
1179
+ valid: true,
1180
+ };
1181
+ this.#externalContextLeases.set(sessionId, lease);
1182
+ this.#externalObservationContexts.set(sessionId, context);
1183
+ return {
1184
+ rollback: () => {
1185
+ lease.valid = false;
1186
+ if (this.#externalContextLeases.get(sessionId) !== lease)
1187
+ return;
1188
+ let previous = lease.previous;
1189
+ while (previous && !previous.valid)
1190
+ previous = previous.previous;
1191
+ if (previous) {
1192
+ this.#externalContextLeases.set(sessionId, previous);
1193
+ this.#externalObservationContexts.set(sessionId, previous.context);
1194
+ }
1195
+ else {
1196
+ this.#externalContextLeases.delete(sessionId);
1197
+ this.#externalObservationContexts.delete(sessionId);
1198
+ }
1199
+ },
1200
+ commit: () => {
1201
+ lease.previous = undefined;
1202
+ },
1203
+ };
1204
+ }
1205
+ #setTurnObservation(observation) {
1206
+ let observations = this.#turnObservations.get(observation.sessionId);
1207
+ if (!observations) {
1208
+ observations = new Map();
1209
+ this.#turnObservations.set(observation.sessionId, observations);
1210
+ }
1211
+ observations.set(observation.turnId, observation);
1212
+ }
1213
+ #removeTurnObservation(observation) {
1214
+ const observations = this.#turnObservations.get(observation.sessionId);
1215
+ if (observations?.get(observation.turnId) !== observation)
1216
+ return;
1217
+ observations.delete(observation.turnId);
1218
+ if (observations.size === 0)
1219
+ this.#turnObservations.delete(observation.sessionId);
1220
+ if (observation instanceof AcpAdmittedTurnObservation &&
1221
+ !this.#hasAttachmentConsumers(observation.sessionId)) {
1222
+ this.#attachmentOpenControllers.get(observation.sessionId)?.abort();
1223
+ }
730
1224
  }
731
- #removeActivePrompt(active) {
732
- const prompts = this.#activePrompts.get(active.sessionId);
733
- prompts?.delete(active);
734
- if (prompts?.size === 0)
735
- this.#activePrompts.delete(active.sessionId);
1225
+ #observation(sessionId, turnId) {
1226
+ return this.#turnObservations.get(sessionId)?.get(turnId);
736
1227
  }
737
1228
  #wakeSession(sessionId) {
738
- for (const active of this.#activePrompts.get(sessionId) ?? [])
739
- this.#wake(active);
740
- }
741
- #wake(active) {
742
- for (const resolve of active.waiters)
743
- resolve();
744
- active.waiters.clear();
745
- }
746
- #waitForPromptChange(active, timeoutMs) {
747
- return new Promise((resolve) => {
748
- let timer;
749
- const wake = () => {
750
- if (timer !== undefined)
751
- clearTimeout(timer);
752
- active.waiters.delete(wake);
753
- resolve();
754
- };
755
- active.waiters.add(wake);
756
- if (timeoutMs !== undefined)
757
- timer = setTimeout(wake, timeoutMs);
758
- });
1229
+ for (const active of this.#admittedTurns(sessionId))
1230
+ active.wake();
759
1231
  }
760
1232
  #assertOwned(sessionId) {
761
1233
  if (!this.#ownedSessionIds.has(sessionId))
@@ -819,6 +1291,282 @@ export class AcpSessionRegistry {
819
1291
  this.#ownedSessionIds.add(sessionId);
820
1292
  return { sessionId, ...(configOptions ? { configOptions } : {}) };
821
1293
  }
1294
+ async #load(params, context, mcpConfig, replayHistory, requestedGeneration) {
1295
+ if ((this.#sessionCloseGenerations.get(params.sessionId) ?? 0) !== requestedGeneration) {
1296
+ throw unknownSessionError();
1297
+ }
1298
+ const existingReplayDelivery = this.#historyReplayDelivery.get(params.sessionId);
1299
+ const replayDelivery = replayHistory
1300
+ ? (existingReplayDelivery ?? {
1301
+ textByMessage: new Map(),
1302
+ otherUpdates: new Set(),
1303
+ })
1304
+ : undefined;
1305
+ if (replayDelivery && !existingReplayDelivery) {
1306
+ // An attached Turn may have streamed before load started. Retain its
1307
+ // absolute message prefix so later live chunks are not mistaken for one.
1308
+ for (const observation of this.#turnObservations.get(params.sessionId)?.values() ?? []) {
1309
+ for (const [key, prefix] of observation.deliveredTextByMessage) {
1310
+ replayDelivery.textByMessage.set(key, prefix);
1311
+ }
1312
+ }
1313
+ }
1314
+ if (replayDelivery)
1315
+ this.#historyReplayDelivery.set(params.sessionId, replayDelivery);
1316
+ const loadController = new AbortController();
1317
+ this.#sessionLoadControllers.set(params.sessionId, loadController);
1318
+ const lifetime = AbortSignal.any([
1319
+ context.signal,
1320
+ loadController.signal,
1321
+ this.#creationAbort.signal,
1322
+ ]);
1323
+ const generation = this.#sessionCloseGenerations.get(params.sessionId) ?? 0;
1324
+ const alreadyOwned = this.#ownedSessionIds.has(params.sessionId);
1325
+ const heldObservations = new Set();
1326
+ let restoreContext;
1327
+ let restoreClient;
1328
+ const previousMcp = this.#mcps.get(params.sessionId);
1329
+ const previousMcpConfig = previousMcp?.config;
1330
+ let previousMcpReconfigureAttempted = false;
1331
+ let installedMcp;
1332
+ let newAttachment;
1333
+ try {
1334
+ lifetime.throwIfAborted();
1335
+ const connection = await this.#getConnection('session.catalog.query');
1336
+ let session;
1337
+ try {
1338
+ session = await getRuntimeHostSession(connection, params.sessionId);
1339
+ }
1340
+ catch (error) {
1341
+ throw requestErrorFromSessionUpdate(error, 'session.catalog.query');
1342
+ }
1343
+ if (!session) {
1344
+ throw RequestError.invalidParams({ source: 'runtime_host', operation: 'session.catalog.query', code: 'not_found' }, 'Runtime Host Session was not found');
1345
+ }
1346
+ if (session.isArchived) {
1347
+ throw RequestError.invalidParams({ source: 'runtime_host', operation: 'session.catalog.query', code: 'archived' }, 'Archived Runtime Host Sessions cannot be loaded');
1348
+ }
1349
+ const cwd = await normalizeCwd(params.cwd);
1350
+ if (cwd !== session.workspace.hostCwd) {
1351
+ throw RequestError.invalidParams({ field: 'cwd', reason: 'session_cwd_mismatch' }, 'cwd does not match the existing Session workspace');
1352
+ }
1353
+ lifetime.throwIfAborted();
1354
+ const configOptions = await this.#projectConfigOptions(connection, session);
1355
+ if ((this.#sessionCloseGenerations.get(params.sessionId) ?? 0) !== generation) {
1356
+ throw unknownSessionError();
1357
+ }
1358
+ if (previousMcp) {
1359
+ previousMcpReconfigureAttempted = true;
1360
+ await previousMcp.reconfigure(mcpConfig, lifetime, async () => {
1361
+ const latest = await getRuntimeHostSession(connection, params.sessionId);
1362
+ if (!latest)
1363
+ throw unknownSessionError();
1364
+ if (latest.status === 'running' ||
1365
+ latest.status === 'waiting_for_user' ||
1366
+ (latest.liveRunState?.runningTurnIds.length ?? 0) > 0 ||
1367
+ this.#admittedTurns(params.sessionId).length > 0) {
1368
+ throw RequestError.internalError({ source: 'adapter', operation: 'mcp.prepare', code: 'session_busy' }, 'Cannot replace Session MCP configuration during an active Turn');
1369
+ }
1370
+ });
1371
+ }
1372
+ else {
1373
+ installedMcp = new AcpSessionMcp(params.sessionId, mcpConfig, connection);
1374
+ this.#mcps.set(params.sessionId, installedMcp);
1375
+ await installedMcp.prepare(lifetime);
1376
+ }
1377
+ if ((this.#sessionCloseGenerations.get(params.sessionId) ?? 0) !== generation) {
1378
+ throw unknownSessionError();
1379
+ }
1380
+ this.#ownedSessionIds.add(params.sessionId);
1381
+ if (replayHistory) {
1382
+ this.#historyReplays.add(params.sessionId);
1383
+ for (const observation of this.#turnObservations.get(params.sessionId)?.values() ?? []) {
1384
+ heldObservations.add(observation);
1385
+ }
1386
+ await Promise.all([...heldObservations].map((observation) => observation.holdLive()));
1387
+ }
1388
+ restoreContext = this.#installExternalContext(params.sessionId, context);
1389
+ restoreClient = this.#attachmentInteractions
1390
+ .get(params.sessionId)
1391
+ ?.setClient(context.interactions ?? UNAVAILABLE_INTERACTION_CLIENT);
1392
+ const creatingAttachment = !this.#attachments.has(params.sessionId);
1393
+ const attachmentPromise = this.#ensureAttachment(params.sessionId, connection, {
1394
+ ...context,
1395
+ signal: lifetime,
1396
+ });
1397
+ if (creatingAttachment)
1398
+ newAttachment = this.#attachments.get(params.sessionId);
1399
+ const attachment = await attachmentPromise;
1400
+ lifetime.throwIfAborted();
1401
+ this.#assertOpen('subscription.open');
1402
+ this.#assertOwned(params.sessionId);
1403
+ if ((this.#sessionCloseGenerations.get(params.sessionId) ?? 0) !== generation) {
1404
+ throw unknownSessionError();
1405
+ }
1406
+ // A retained attachment may have observed this Turn before load/resume
1407
+ // installed its presentation context. Attach its existing event consumer
1408
+ // now; opening a second channel would lose the queue and interaction state.
1409
+ const root = attachment.snapshot.rootTurn;
1410
+ if (root &&
1411
+ !isRuntimeHostTerminalTurn(root) &&
1412
+ !attachment.hasQueuedStartedTurn(root.turnId)) {
1413
+ await this.#adoptTurn(params.sessionId, root.turnId, attachment, false, root.runId);
1414
+ lifetime.throwIfAborted();
1415
+ this.#assertOpen('subscription.open');
1416
+ this.#assertOwned(params.sessionId);
1417
+ if ((this.#sessionCloseGenerations.get(params.sessionId) ?? 0) !== generation) {
1418
+ throw unknownSessionError();
1419
+ }
1420
+ }
1421
+ if (replayHistory) {
1422
+ const mappers = new Map();
1423
+ await attachment.replayTranscript(async (messages) => {
1424
+ const active = this.#turnObservations.get(params.sessionId);
1425
+ for (const observation of active?.values() ?? []) {
1426
+ if (!heldObservations.has(observation)) {
1427
+ heldObservations.add(observation);
1428
+ await observation.holdLive();
1429
+ }
1430
+ await observation.seed(messages);
1431
+ }
1432
+ for (const message of messages) {
1433
+ lifetime.throwIfAborted();
1434
+ if (!message.turnId)
1435
+ continue;
1436
+ let mapper = mappers.get(message.turnId);
1437
+ if (!mapper) {
1438
+ mapper = new AcpSessionEventMapper({
1439
+ sessionId: params.sessionId,
1440
+ notify: (notification) => this.#deliverHistoryNotification(notification, context.notify, replayDelivery),
1441
+ signal: lifetime,
1442
+ });
1443
+ mappers.set(message.turnId, mapper);
1444
+ }
1445
+ await mapper.acceptHistoricalMessage(message);
1446
+ if (message.type === 'turn_state' && message.status !== 'running') {
1447
+ await mapper.finishTools(message.turnId, message.status === 'aborted' ? 'cancelled' : message.status);
1448
+ await mapper.flush();
1449
+ mappers.delete(message.turnId);
1450
+ }
1451
+ }
1452
+ }, lifetime);
1453
+ await Promise.all([...mappers.values()].map((mapper) => mapper.flush()));
1454
+ }
1455
+ restoreContext.commit();
1456
+ restoreClient?.commit();
1457
+ if (replayHistory)
1458
+ this.#historyReplayDelivery.delete(params.sessionId);
1459
+ return { configOptions };
1460
+ }
1461
+ catch (error) {
1462
+ const sharedAttachment = newAttachment &&
1463
+ this.#attachments.get(params.sessionId) === newAttachment &&
1464
+ this.#hasAttachmentConsumers(params.sessionId);
1465
+ if (sharedAttachment) {
1466
+ // A concurrent prompt has adopted this prepared Session. Its attachment,
1467
+ // ownership and MCP provider must outlive this cancelled/failed load.
1468
+ restoreContext?.rollback();
1469
+ restoreClient?.rollback();
1470
+ if (error instanceof RequestError)
1471
+ throw error;
1472
+ throw requestErrorFromRuntimeHost(error, 'subscription.open');
1473
+ }
1474
+ if (newAttachment && this.#attachments.get(params.sessionId) === newAttachment) {
1475
+ const channel = await newAttachment.catch(() => undefined);
1476
+ if (channel) {
1477
+ this.#discardedAttachments.add(channel);
1478
+ for (const observation of this.#turnObservations.get(params.sessionId)?.values() ?? []) {
1479
+ if (observation.attachment !== channel)
1480
+ continue;
1481
+ observation.dispose();
1482
+ this.#removeTurnObservation(observation);
1483
+ }
1484
+ }
1485
+ this.#detachAttachment(params.sessionId, newAttachment);
1486
+ await channel?.close().catch(() => undefined);
1487
+ }
1488
+ if (installedMcp && this.#mcps.get(params.sessionId) === installedMcp) {
1489
+ await this.#detachMcp(params.sessionId, installedMcp)
1490
+ ?.close()
1491
+ .catch(() => undefined);
1492
+ }
1493
+ else if (previousMcp &&
1494
+ previousMcpReconfigureAttempted &&
1495
+ previousMcpConfig &&
1496
+ this.#mcps.get(params.sessionId) === previousMcp) {
1497
+ await previousMcp.reconfigure(previousMcpConfig).catch(() => undefined);
1498
+ }
1499
+ restoreContext?.rollback();
1500
+ restoreClient?.rollback();
1501
+ if (!alreadyOwned)
1502
+ this.#ownedSessionIds.delete(params.sessionId);
1503
+ if (error instanceof RequestError)
1504
+ throw error;
1505
+ throw requestErrorFromRuntimeHost(error, 'subscription.open');
1506
+ }
1507
+ finally {
1508
+ if (this.#sessionLoadControllers.get(params.sessionId) === loadController) {
1509
+ this.#sessionLoadControllers.delete(params.sessionId);
1510
+ }
1511
+ if (replayHistory)
1512
+ this.#historyReplays.delete(params.sessionId);
1513
+ for (const observation of heldObservations)
1514
+ observation.releaseLive();
1515
+ for (const observation of this.#turnObservations.get(params.sessionId)?.values() ?? []) {
1516
+ observation.releaseLive();
1517
+ }
1518
+ }
1519
+ }
1520
+ #recordLiveHistoryDelivery(sessionId, notification, observation) {
1521
+ const prefix = observation.recordDeliveredText(notification);
1522
+ const delivery = this.#historyReplayDelivery.get(sessionId);
1523
+ if (!delivery)
1524
+ return;
1525
+ const chunk = historyTextChunk(notification);
1526
+ if (chunk) {
1527
+ const previous = delivery.textByMessage.get(chunk.key) ?? '';
1528
+ delivery.textByMessage.set(chunk.key, prefix?.startsWith(previous) ? prefix : previous + chunk.text);
1529
+ }
1530
+ else {
1531
+ delivery.otherUpdates.add(JSON.stringify(notification.update));
1532
+ }
1533
+ }
1534
+ async #deliverHistoryNotification(notification, notify, delivery) {
1535
+ const chunk = historyTextChunk(notification);
1536
+ if (chunk) {
1537
+ const previous = delivery.textByMessage.get(chunk.key) ?? '';
1538
+ const text = chunk.text.startsWith(previous) ? chunk.text.slice(previous.length) : chunk.text;
1539
+ if (!text)
1540
+ return;
1541
+ await notify({
1542
+ ...notification,
1543
+ update: {
1544
+ ...notification.update,
1545
+ content: { type: 'text', text },
1546
+ },
1547
+ });
1548
+ delivery.textByMessage.set(chunk.key, chunk.text.startsWith(previous) ? chunk.text : previous + chunk.text);
1549
+ return;
1550
+ }
1551
+ const key = JSON.stringify(notification.update);
1552
+ if (delivery.otherUpdates.has(key))
1553
+ return;
1554
+ await notify(notification);
1555
+ delivery.otherUpdates.add(key);
1556
+ }
1557
+ #queueLoad(sessionId, operation) {
1558
+ const previous = this.#sessionLoadTails.get(sessionId) ?? Promise.resolve();
1559
+ const result = previous.catch(() => undefined).then(operation);
1560
+ this.#sessionLoadTails.set(sessionId, result);
1561
+ void result.then(() => {
1562
+ if (this.#sessionLoadTails.get(sessionId) === result)
1563
+ this.#sessionLoadTails.delete(sessionId);
1564
+ }, () => {
1565
+ if (this.#sessionLoadTails.get(sessionId) === result)
1566
+ this.#sessionLoadTails.delete(sessionId);
1567
+ });
1568
+ return result;
1569
+ }
822
1570
  async #setConfigOption(params, configuration) {
823
1571
  const connection = await this.#getConnection('session.configuration.update');
824
1572
  let committed;
@@ -921,10 +1669,19 @@ export class AcpSessionRegistry {
921
1669
  };
922
1670
  }
923
1671
  async #dispose() {
924
- const sessionIds = new Set([...this.#activePrompts.keys(), ...this.#attachments.keys()]);
925
- const activePrompts = [...sessionIds].flatMap((sessionId) => [
926
- ...(this.#activePrompts.get(sessionId) ?? []),
1672
+ this.#externalObservationContexts.clear();
1673
+ this.#externalContextLeases.clear();
1674
+ for (const observations of this.#turnObservations.values()) {
1675
+ for (const observation of observations.values()) {
1676
+ if (!(observation instanceof AcpAdmittedTurnObservation))
1677
+ observation.dispose();
1678
+ }
1679
+ }
1680
+ const sessionIds = new Set([...this.#turnObservations.keys(), ...this.#attachments.keys()]);
1681
+ const observations = [...this.#turnObservations.values()].flatMap((turns) => [
1682
+ ...turns.values(),
927
1683
  ]);
1684
+ const activePrompts = [...sessionIds].flatMap((sessionId) => this.#admittedTurns(sessionId));
928
1685
  const cancellations = [...sessionIds].map((sessionId) => this.#cancelSession(sessionId));
929
1686
  for (const interactions of this.#attachmentInteractions.values())
930
1687
  interactions.close();
@@ -935,23 +1692,27 @@ export class AcpSessionRegistry {
935
1692
  this.#attachmentConfigurations.clear();
936
1693
  await Promise.allSettled(attachments.map(async (attachment) => (await attachment).close()));
937
1694
  await Promise.allSettled(activePrompts.map(async (active) => {
938
- while (active.dispatchStarted && !active.startRequestSettled && !active.finished) {
939
- await this.#waitForPromptChange(active);
1695
+ while (active.admission.dispatchStarted &&
1696
+ !active.admission.startRequestSettled &&
1697
+ !active.finished) {
1698
+ await active.waitForChange();
940
1699
  }
941
1700
  }));
942
1701
  const unknownAdmissions = activePrompts.filter((active) => {
943
1702
  const observed = active.attachment?.snapshot.rootTurn;
944
- const hasStopIdentity = observed?.turnId === active.turnId || active.startedTurn !== undefined;
945
- return active.dispatchStarted && !active.admissionSettled && !hasStopIdentity;
1703
+ const hasStopIdentity = observed?.turnId === active.turnId || active.admission.startedTurn !== undefined;
1704
+ return active.admission.dispatchStarted && !active.admission.settled && !hasStopIdentity;
946
1705
  });
1706
+ await Promise.allSettled(observations
1707
+ .filter((observation) => unknownAdmissions.every((active) => active !== observation))
1708
+ .map((observation) => observation.stopTask));
947
1709
  if (unknownAdmissions.length > 0) {
948
1710
  // At shutdown the attachment is already closed and each start request has
949
1711
  // settled, leaving recovery/query as the only remaining fact source.
950
1712
  // Close the owned connection so those reads cannot deadlock EOF cleanup.
951
1713
  await Promise.allSettled([this.#closeOwnedConnection()]);
952
1714
  for (const active of unknownAdmissions) {
953
- active.admissionSettled = true;
954
- this.#wake(active);
1715
+ active.settleOnClose();
955
1716
  }
956
1717
  }
957
1718
  await Promise.allSettled(cancellations);
@@ -964,6 +1725,7 @@ export class AcpSessionRegistry {
964
1725
  ...configurations.map(({ tail }) => tail),
965
1726
  ]);
966
1727
  this.#ownedSessionIds.clear();
1728
+ this.#historyReplayDelivery.clear();
967
1729
  }
968
1730
  #closeOwnedConnection() {
969
1731
  const connection = this.#connection;
@@ -1196,3 +1958,13 @@ function isoTimestamp(timestamp) {
1196
1958
  const date = new Date(timestamp);
1197
1959
  return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
1198
1960
  }
1961
+ function historyTextChunk(notification) {
1962
+ const update = notification.update;
1963
+ if (update.sessionUpdate !== 'user_message_chunk' &&
1964
+ update.sessionUpdate !== 'agent_message_chunk' &&
1965
+ update.sessionUpdate !== 'agent_thought_chunk')
1966
+ return;
1967
+ if (update.content.type !== 'text' || !update.messageId)
1968
+ return;
1969
+ return { key: `${update.sessionUpdate}:${update.messageId}`, text: update.content.text };
1970
+ }