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

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 (35) hide show
  1. package/dist/acp/goal-plan-operations.js +142 -0
  2. package/dist/acp/goal-plan-routes.js +33 -0
  3. package/dist/acp/maka-acp-agent.js +41 -1
  4. package/dist/acp/session-domain-observation.js +185 -0
  5. package/dist/acp/session-event-mapper.js +1 -1
  6. package/dist/acp/session-registry.js +417 -9
  7. package/dist/acp/tool-event-mapper.js +36 -3
  8. package/dist/runtime-host-session-channel.js +4 -0
  9. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  10. package/node_modules/@maka/core/dist/openai-urls.js +51 -0
  11. package/node_modules/@maka/core/dist/relative-time.js +1 -9
  12. package/node_modules/@maka/core/package.json +1 -0
  13. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +10 -8
  14. package/node_modules/@maka/runtime/dist/builtin-tools.js +2 -2
  15. package/node_modules/@maka/runtime/dist/filesystem-executor.js +3 -2
  16. package/node_modules/@maka/runtime/dist/filesystem-worker/protocol.js +7 -4
  17. package/node_modules/@maka/runtime/dist/glob-search.js +18 -5
  18. package/node_modules/@maka/runtime/dist/model-factory.js +27 -1
  19. package/node_modules/@maka/runtime/dist/model-fetcher.js +2 -1
  20. package/node_modules/@maka/runtime/dist/model-runtime.js +5 -3
  21. package/node_modules/@maka/runtime/dist/provider-urls.js +1 -18
  22. package/node_modules/@maka/runtime/dist/scheduled-task-tools.js +27 -2
  23. package/node_modules/@maka/runtime/dist/test-connection.js +2 -2
  24. package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +16 -6
  25. package/node_modules/@maka/runtime-host/dist/protocol/index.js +3 -1
  26. package/node_modules/@maka/runtime-host/dist/protocol/scheduled-task.js +8 -1
  27. package/node_modules/@maka/runtime-host/dist/protocol/session-catalog-change.js +24 -6
  28. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +16 -3
  29. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +20 -16
  30. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +18 -1
  31. package/node_modules/@maka/runtime-host/dist/server/host-change-feed.js +15 -22
  32. package/node_modules/@maka/runtime-host/dist/server/interaction-coordinator.js +30 -3
  33. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +1 -1
  34. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +16 -3
  35. package/package.json +1 -1
@@ -31,10 +31,16 @@ import { mapAcpPromptContent, publishAcpPromptAttachments } from './prompt-conte
31
31
  import { AcpSessionMcp, createAcpMcpConfig } from './session-mcp.js';
32
32
  import { AcpSessionInteractions } from './session-interactions.js';
33
33
  import { AcpTurnObservation, AcpAdmittedTurnObservation } from './turn-observation.js';
34
+ import { AcpGoalPlanOperations, } from './goal-plan-operations.js';
35
+ import { AcpSessionDomainObservation, } from './session-domain-observation.js';
34
36
  const ACP_SESSION_CURSOR_MAX_BYTES = 8 * 1024;
35
37
  const ADMISSION_QUERY_MAX_ATTEMPTS = 5;
36
38
  const ADMISSION_QUERY_TIMEOUT_MS = 1_000;
37
39
  const ADMISSION_QUERY_RETRY_MS = 25;
40
+ const EXTENSION_REQUEST_TIMEOUT_MS = 30_000;
41
+ const ARTIFACT_CLEANUP_TIMEOUT_MS = 5_000;
42
+ const ARTIFACT_UPLOAD_TTL_MS = 5 * 60_000;
43
+ const MAX_TRACKED_ARTIFACT_UPLOADS = 64;
38
44
  const TURN_STOP_TIMEOUT_MS = 30_000;
39
45
  const COPY_RECONCILIATION_TIMEOUT_MS = 30_000;
40
46
  const UNAVAILABLE_INTERACTION_CLIENT = {
@@ -46,6 +52,9 @@ const UNAVAILABLE_INTERACTION_CLIENT = {
46
52
  throw RequestError.methodNotFound('elicitation/create');
47
53
  },
48
54
  };
55
+ function artifactUploadKey(sessionId, uploadId) {
56
+ return JSON.stringify([sessionId, uploadId]);
57
+ }
49
58
  /** Owns all Runtime Host resources associated with one ACP connection. */
50
59
  export class AcpSessionRegistry {
51
60
  #connect;
@@ -56,16 +65,25 @@ export class AcpSessionRegistry {
56
65
  #mcps = new Map();
57
66
  #creationAbort = new AbortController();
58
67
  #attachmentInteractions = new Map();
68
+ #domainObservations = new Map();
69
+ #goalPlan;
59
70
  #attachments = new Map();
60
71
  #attachmentOpenControllers = new Map();
61
72
  #attachmentConfigurations = new Map();
62
73
  #pendingConfigSets = new Map();
63
74
  #attachmentWaiters = new Map();
64
75
  #turnObservations = new Map();
76
+ #pendingPlanAdmissions = new Map();
65
77
  #discardedAttachments = new WeakSet();
66
78
  #externalObservationContexts = new Map();
67
79
  #externalContextLeases = new Map();
68
80
  #sessionCloseTasks = new Map();
81
+ #artifactUploads = new Map();
82
+ #artifactOperations = new Map();
83
+ // Retain cleanup waits across Host replacement so a late abort cannot race a reused ID.
84
+ #artifactCleanupTasks = new Map();
85
+ #artifactConnectionIdentity;
86
+ #artifactConnectionDisposer;
69
87
  #sessionCloseGenerations = new Map();
70
88
  #sessionLoadTails = new Map();
71
89
  #sessionLoadControllers = new Map();
@@ -81,6 +99,154 @@ export class AcpSessionRegistry {
81
99
  this.#connect = options.connect;
82
100
  this.#newSessionId = options.newSessionId ?? randomUUID;
83
101
  this.#newTurnId = options.newTurnId ?? randomUUID;
102
+ this.#goalPlan = new AcpGoalPlanOperations({
103
+ prepare: (sessionId, context, turnId, observe) => this.#prepareGoalPlan(sessionId, context, turnId, observe),
104
+ assertCurrent: (sessionId) => {
105
+ this.#assertOpen('subscription.open');
106
+ this.#assertOwned(sessionId);
107
+ },
108
+ mapError: (error, operation, extra) => requestErrorFromRuntimeHost(error, operation, extra),
109
+ });
110
+ }
111
+ goalQuery(input, context) {
112
+ return this.#track(this.#goalPlan.goalQuery(input, context));
113
+ }
114
+ goalArm(input, context) {
115
+ return this.#track(this.#goalPlan.goalArm(input, context));
116
+ }
117
+ goalControl(input, context) {
118
+ return this.#track(this.#goalPlan.goalControl(input, context));
119
+ }
120
+ planQuery(input, context) {
121
+ return this.#track(this.#goalPlan.planQuery(input, context));
122
+ }
123
+ planControl(input, context) {
124
+ return this.#track(this.#goalPlan.planControl(input, context));
125
+ }
126
+ planTurnStart(input, context) {
127
+ return this.#track(this.#goalPlan.planTurnStart(input, context));
128
+ }
129
+ async #prepareGoalPlan(sessionId, context, turnId, observe = true) {
130
+ this.#assertOpen('subscription.open');
131
+ this.#assertOwned(sessionId);
132
+ context.signal.throwIfAborted();
133
+ const generation = this.#sessionCloseGenerations.get(sessionId) ?? 0;
134
+ const connection = await this.#getConnection('subscription.open');
135
+ this.#assertOwned(sessionId);
136
+ context.signal.throwIfAborted();
137
+ if (!observe)
138
+ return { connection, commit: () => undefined, rollback: () => undefined };
139
+ const restoreContext = this.#installExternalContext(sessionId, context);
140
+ const restoreClient = this.#attachmentInteractions
141
+ .get(sessionId)
142
+ ?.setClient(context.interactions ?? UNAVAILABLE_INTERACTION_CLIENT);
143
+ const creatingAttachment = !this.#attachments.has(sessionId);
144
+ let observation;
145
+ let observedReplay = false;
146
+ let admissionFinished = false;
147
+ let attachment;
148
+ const finishAdmission = (retain, error) => {
149
+ if (!observation || admissionFinished)
150
+ return;
151
+ admissionFinished = true;
152
+ const state = this.#pendingPlanAdmissions.get(observation);
153
+ if (!state)
154
+ return;
155
+ state.retained ||= retain;
156
+ state.users -= 1;
157
+ if (state.users > 0)
158
+ return;
159
+ this.#pendingPlanAdmissions.delete(observation);
160
+ if (state.retained)
161
+ return;
162
+ observation.failStartRequest(error);
163
+ observation.dispose();
164
+ this.#removeTurnObservation(observation);
165
+ if (error && turnId)
166
+ attachment?.failTurn(turnId, error);
167
+ };
168
+ const rollback = (error) => {
169
+ finishAdmission(false, error);
170
+ restoreContext.rollback();
171
+ restoreClient?.rollback();
172
+ if (creatingAttachment &&
173
+ !this.#hasAttachmentConsumers(sessionId) &&
174
+ !this.#turnObservations.get(sessionId)?.size &&
175
+ !this.#externalObservationContexts.has(sessionId)) {
176
+ const task = this.#detachAttachment(sessionId);
177
+ void task?.then((channel) => channel.close(), () => undefined);
178
+ }
179
+ };
180
+ try {
181
+ const prepared = await this.#prepareExternalObservation(sessionId, context, connection, 'subscription.open', turnId);
182
+ attachment = prepared.attachment;
183
+ observation = prepared.observation;
184
+ observedReplay = prepared.observedReplay ?? false;
185
+ if (observation) {
186
+ const state = this.#pendingPlanAdmissions.get(observation) ?? {
187
+ users: 0,
188
+ retained: false,
189
+ };
190
+ state.users += 1;
191
+ this.#pendingPlanAdmissions.set(observation, state);
192
+ }
193
+ if ((this.#sessionCloseGenerations.get(sessionId) ?? 0) !== generation)
194
+ throw unknownSessionError();
195
+ if (context.notifyGoalStatus || context.notifyPlanChanged) {
196
+ this.#domainObservations.get(sessionId)?.initialize(attachment.snapshot.goal);
197
+ }
198
+ return {
199
+ connection,
200
+ ...(observedReplay ? { observedReplay } : {}),
201
+ ...(observation ? { observation } : {}),
202
+ ...(observation
203
+ ? { reconcileAdmission: () => this.#queryPromptAdmission(observation, connection) }
204
+ : {}),
205
+ ...(observation
206
+ ? {
207
+ cancelObservation: () => {
208
+ const state = this.#pendingPlanAdmissions.get(observation);
209
+ if (state?.users === 1 && !state.retained)
210
+ void this.#cancelPrompt(observation).catch(() => undefined);
211
+ },
212
+ }
213
+ : {}),
214
+ commit: () => {
215
+ finishAdmission(true);
216
+ restoreContext.commit();
217
+ restoreClient?.commit();
218
+ },
219
+ rollback,
220
+ };
221
+ }
222
+ catch (error) {
223
+ rollback(error);
224
+ if (error instanceof RequestError)
225
+ throw error;
226
+ throw requestErrorFromRuntimeHost(error, 'subscription.open');
227
+ }
228
+ }
229
+ /** Shared non-prompt preparation for explicit Turn resume and Plan admission. */
230
+ async #prepareExternalObservation(sessionId, context, connection, operation, turnId) {
231
+ await this.#mcps.get(sessionId)?.ready(context.signal);
232
+ const attachment = await this.#ensureAttachment(sessionId, connection, context);
233
+ context.signal.throwIfAborted();
234
+ this.#assertOpen(operation);
235
+ this.#assertOwned(sessionId);
236
+ if (!turnId)
237
+ return { attachment };
238
+ const root = attachment.snapshot.rootTurn;
239
+ if (root?.turnId === turnId && isRuntimeHostTerminalTurn(root))
240
+ return { attachment, observedReplay: true };
241
+ const observation = await this.#adoptTurn(sessionId, turnId, attachment, true);
242
+ if (!observation)
243
+ throw registryClosedError(operation);
244
+ // Load/resume already observes an admitted Host Turn without local admission
245
+ // bookkeeping. Let the Host validate the replay while preserving that sole
246
+ // consumer, including when this request is rejected or its result is lost.
247
+ if (!(observation instanceof AcpAdmittedTurnObservation))
248
+ return { attachment, observedReplay: true };
249
+ return { attachment, observation };
84
250
  }
85
251
  async create(params, signal) {
86
252
  this.#assertOpen('session.create');
@@ -224,6 +390,198 @@ export class AcpSessionRegistry {
224
390
  void task.then(forget, forget);
225
391
  return task;
226
392
  }
393
+ async artifactQuery(input) {
394
+ return this.#artifactRequest('artifact.query', input);
395
+ }
396
+ async artifactIngest(input) {
397
+ return this.#artifactRequest('artifact.ingest', input);
398
+ }
399
+ async artifactDelete(input) {
400
+ return this.#artifactRequest('artifact.delete', input);
401
+ }
402
+ async memoryQuery(input) {
403
+ return this.#hostRequest('memory.query', input);
404
+ }
405
+ async memoryMutate(input) {
406
+ const sessionId = 'scope' in input && input.scope.kind === 'session' ? input.scope.sessionId : undefined;
407
+ if (sessionId)
408
+ this.#assertOwned(sessionId);
409
+ return this.#hostRequest('memory.mutate', input, sessionId ? () => this.#assertOwned(sessionId) : undefined);
410
+ }
411
+ #artifactRequest(operation, input) {
412
+ this.#assertOpen(operation);
413
+ this.#assertOwned(input.sessionId);
414
+ const request = this.#hostRequest(operation, input, () => this.#assertOwned(input.sessionId));
415
+ let pending = this.#artifactOperations.get(input.sessionId);
416
+ if (!pending) {
417
+ pending = new Set();
418
+ this.#artifactOperations.set(input.sessionId, pending);
419
+ }
420
+ pending.add(request);
421
+ void request
422
+ .finally(() => {
423
+ pending.delete(request);
424
+ if (pending.size === 0)
425
+ this.#artifactOperations.delete(input.sessionId);
426
+ })
427
+ .catch(() => undefined);
428
+ return request;
429
+ }
430
+ async #hostRequest(operation, input, beforeDispatch) {
431
+ this.#assertOpen(operation);
432
+ return this.#track((async () => {
433
+ let trackedIngest;
434
+ try {
435
+ const connection = await this.#getConnection(operation);
436
+ this.#assertOpen(operation);
437
+ beforeDispatch?.();
438
+ if (operation === 'artifact.ingest') {
439
+ const upload = input;
440
+ let cleaning;
441
+ while ((cleaning = this.#artifactCleanupTasks.get(artifactUploadKey(upload.sessionId, upload.uploadId)))) {
442
+ await cleaning;
443
+ this.#assertOpen(operation);
444
+ beforeDispatch?.();
445
+ }
446
+ if (upload.kind === 'begin') {
447
+ this.#watchArtifactConnection(connection);
448
+ let uploads = this.#artifactUploads.get(upload.sessionId);
449
+ if (!uploads) {
450
+ uploads = new Map();
451
+ this.#artifactUploads.set(upload.sessionId, uploads);
452
+ }
453
+ if (!uploads.has(upload.uploadId) && uploads.size >= MAX_TRACKED_ARTIFACT_UPLOADS) {
454
+ await this.#pruneExpiredArtifactUploads(connection, upload.sessionId, uploads);
455
+ this.#assertOpen(operation);
456
+ beforeDispatch?.();
457
+ if (this.#artifactUploads.get(upload.sessionId) !== uploads) {
458
+ uploads = this.#artifactUploads.get(upload.sessionId) ?? new Map();
459
+ this.#artifactUploads.set(upload.sessionId, uploads);
460
+ }
461
+ }
462
+ if (!uploads.has(upload.uploadId) && uploads.size >= MAX_TRACKED_ARTIFACT_UPLOADS) {
463
+ throw RequestError.internalError({ source: 'adapter', operation, code: 'upload_tracking_capacity' }, 'Too many unresolved Artifact uploads');
464
+ }
465
+ // Remember before dispatch: an interrupted response can hide an opened upload.
466
+ let state = uploads.get(upload.uploadId);
467
+ if (!state) {
468
+ state = {
469
+ touchedAt: Date.now(),
470
+ pendingRequests: 0,
471
+ mayBeOpen: false,
472
+ };
473
+ uploads.set(upload.uploadId, state);
474
+ }
475
+ }
476
+ trackedIngest = this.#artifactUploads.get(upload.sessionId)?.get(upload.uploadId);
477
+ if (trackedIngest)
478
+ trackedIngest.pendingRequests += 1;
479
+ }
480
+ const result = await connection.request(operation, input, EXTENSION_REQUEST_TIMEOUT_MS);
481
+ if (operation === 'artifact.ingest') {
482
+ const upload = input;
483
+ const uploads = this.#artifactUploads.get(upload.sessionId);
484
+ if (upload.kind === 'abort' ||
485
+ upload.kind === 'commit' ||
486
+ (upload.kind === 'begin' && result.kind === 'committed')) {
487
+ const state = uploads?.get(upload.uploadId);
488
+ if (state) {
489
+ state.mayBeOpen = false;
490
+ }
491
+ }
492
+ else if (upload.kind === 'begin' && trackedIngest) {
493
+ trackedIngest.mayBeOpen = true;
494
+ trackedIngest.touchedAt = Date.now();
495
+ let currentUploads = this.#artifactUploads.get(upload.sessionId);
496
+ if (!currentUploads) {
497
+ currentUploads = new Map();
498
+ this.#artifactUploads.set(upload.sessionId, currentUploads);
499
+ }
500
+ if (!currentUploads.has(upload.uploadId)) {
501
+ currentUploads.set(upload.uploadId, trackedIngest);
502
+ }
503
+ }
504
+ else if (upload.kind === 'chunk') {
505
+ const state = uploads?.get(upload.uploadId);
506
+ if (state)
507
+ state.touchedAt = Date.now();
508
+ }
509
+ }
510
+ return result;
511
+ }
512
+ catch (error) {
513
+ if (operation === 'artifact.ingest') {
514
+ const upload = input;
515
+ const uploads = this.#artifactUploads.get(upload.sessionId);
516
+ if (upload.kind === 'begin' && trackedIngest) {
517
+ if (error instanceof RuntimeHostRequestInterruptedError &&
518
+ error.dispatch === 'dispatched') {
519
+ trackedIngest.mayBeOpen = true;
520
+ }
521
+ }
522
+ else if (upload.kind === 'commit' &&
523
+ error instanceof RuntimeHostOperationError &&
524
+ (error.code === 'not_found' ||
525
+ (error.code === 'operation_conflict' &&
526
+ error.message === 'Attachment content digest does not match'))) {
527
+ const state = uploads?.get(upload.uploadId);
528
+ if (state) {
529
+ state.mayBeOpen = false;
530
+ }
531
+ }
532
+ }
533
+ if (error instanceof RequestError)
534
+ throw error;
535
+ throw requestErrorFromRuntimeHost(error, operation);
536
+ }
537
+ finally {
538
+ if (trackedIngest) {
539
+ trackedIngest.pendingRequests -= 1;
540
+ const upload = input;
541
+ const uploads = this.#artifactUploads.get(upload.sessionId);
542
+ if (!trackedIngest.mayBeOpen && trackedIngest.pendingRequests === 0) {
543
+ if (uploads?.get(upload.uploadId) === trackedIngest)
544
+ uploads.delete(upload.uploadId);
545
+ }
546
+ }
547
+ }
548
+ })());
549
+ }
550
+ async #pruneExpiredArtifactUploads(connection, sessionId, uploads) {
551
+ const expired = [...uploads].filter(([uploadId, state]) => state.pendingRequests === 0 &&
552
+ !this.#artifactCleanupTasks.has(artifactUploadKey(sessionId, uploadId)) &&
553
+ Date.now() - state.touchedAt > ARTIFACT_UPLOAD_TTL_MS + EXTENSION_REQUEST_TIMEOUT_MS);
554
+ const cleanups = expired.map(([uploadId, state]) => {
555
+ const key = artifactUploadKey(sessionId, uploadId);
556
+ const cleanup = Promise.resolve()
557
+ .then(() => connection.request('artifact.ingest', { kind: 'abort', sessionId, uploadId }, ARTIFACT_CLEANUP_TIMEOUT_MS))
558
+ .then(() => {
559
+ if (uploads.get(uploadId) === state)
560
+ uploads.delete(uploadId);
561
+ }, () => undefined)
562
+ .finally(() => {
563
+ if (this.#artifactCleanupTasks.get(key) === cleanup) {
564
+ this.#artifactCleanupTasks.delete(key);
565
+ }
566
+ });
567
+ this.#artifactCleanupTasks.set(key, cleanup);
568
+ return cleanup;
569
+ });
570
+ await Promise.all(cleanups);
571
+ }
572
+ #watchArtifactConnection(connection) {
573
+ if (this.#artifactConnectionDisposer)
574
+ return;
575
+ this.#artifactConnectionDisposer = connection.subscribeConnectionAvailability((availability) => {
576
+ const identity = availability.kind === 'connected'
577
+ ? JSON.stringify([availability.hostEpoch, availability.connectionId])
578
+ : undefined;
579
+ if (identity !== this.#artifactConnectionIdentity) {
580
+ this.#artifactConnectionIdentity = identity;
581
+ this.#artifactUploads.clear();
582
+ }
583
+ });
584
+ }
227
585
  dispose() {
228
586
  this.#closing = true;
229
587
  this.#connectAbortController?.abort();
@@ -619,6 +977,13 @@ export class AcpSessionRegistry {
619
977
  },
620
978
  });
621
979
  this.#attachmentInteractions.set(sessionId, interactions);
980
+ const domainObservation = new AcpSessionDomainObservation({
981
+ sessionId,
982
+ queryPlan: () => connection.request('plan.query', { kind: 'list_start', sessionId }),
983
+ goalNotify: () => this.#externalObservationContexts.get(sessionId)?.notifyGoalStatus,
984
+ planNotify: () => this.#externalObservationContexts.get(sessionId)?.notifyPlanChanged,
985
+ });
986
+ this.#domainObservations.set(sessionId, domainObservation);
622
987
  task = RuntimeHostSessionChannel.open({
623
988
  connection,
624
989
  signal: openingController.signal,
@@ -632,6 +997,19 @@ export class AcpSessionRegistry {
632
997
  });
633
998
  },
634
999
  onRuntimeResourceChanged: () => undefined,
1000
+ onSessionDomainChanged: (frame) => {
1001
+ if (frame.domain === 'plan' &&
1002
+ this.#externalObservationContexts.get(sessionId)?.notifyPlanChanged)
1003
+ domainObservation.planChanged();
1004
+ },
1005
+ onCanonicalReplacement: (snapshot) => {
1006
+ if (attachment && this.#discardedAttachments.has(attachment))
1007
+ return;
1008
+ if (this.#externalObservationContexts.get(sessionId)?.notifyPlanChanged ||
1009
+ this.#externalObservationContexts.get(sessionId)?.notifyGoalStatus) {
1010
+ domainObservation.canonicalReplacement(snapshot.goal);
1011
+ }
1012
+ },
635
1013
  onSnapshotChanged: (snapshot) => {
636
1014
  if (attachment && this.#discardedAttachments.has(attachment))
637
1015
  return;
@@ -711,7 +1089,7 @@ export class AcpSessionRegistry {
711
1089
  ?.reconcile()
712
1090
  .catch(() => undefined);
713
1091
  },
714
- onGoalChanged: () => undefined,
1092
+ onGoalChanged: (goal) => domainObservation.goalChanged(goal),
715
1093
  onFailed: failAttachment,
716
1094
  onRecovered: () => {
717
1095
  for (const active of this.#admittedTurns(sessionId)) {
@@ -749,9 +1127,16 @@ export class AcpSessionRegistry {
749
1127
  channel.activate(attachedTurnId && this.#observation(sessionId, attachedTurnId)
750
1128
  ? attachedTurnId
751
1129
  : undefined);
1130
+ if (this.#externalObservationContexts.get(sessionId)?.notifyGoalStatus ||
1131
+ this.#externalObservationContexts.get(sessionId)?.notifyPlanChanged) {
1132
+ domainObservation.initialize(channel.snapshot.goal);
1133
+ }
752
1134
  return channel;
753
1135
  })
754
1136
  .catch((error) => {
1137
+ domainObservation.dispose();
1138
+ if (this.#domainObservations.get(sessionId) === domainObservation)
1139
+ this.#domainObservations.delete(sessionId);
755
1140
  interactions.close();
756
1141
  if (this.#attachmentInteractions.get(sessionId) === interactions) {
757
1142
  this.#attachmentInteractions.delete(sessionId);
@@ -796,6 +1181,8 @@ export class AcpSessionRegistry {
796
1181
  this.#attachmentOpenControllers.get(sessionId)?.abort();
797
1182
  this.#attachmentInteractions.get(sessionId)?.close();
798
1183
  this.#attachmentInteractions.delete(sessionId);
1184
+ this.#domainObservations.get(sessionId)?.dispose();
1185
+ this.#domainObservations.delete(sessionId);
799
1186
  this.#attachmentConfigurations.delete(sessionId);
800
1187
  this.#attachments.delete(sessionId);
801
1188
  return expected;
@@ -818,6 +1205,18 @@ export class AcpSessionRegistry {
818
1205
  }
819
1206
  const attachmentTask = this.#detachAttachment(sessionId);
820
1207
  let closeError;
1208
+ const artifactOperations = this.#artifactOperations.get(sessionId);
1209
+ if (artifactOperations)
1210
+ await Promise.allSettled([...artifactOperations]);
1211
+ const uploads = this.#artifactUploads.get(sessionId);
1212
+ this.#artifactUploads.delete(sessionId);
1213
+ if (uploads && this.#connection) {
1214
+ const aborts = await Promise.allSettled([...uploads.keys()].map((uploadId) => this.#connection.request('artifact.ingest', { kind: 'abort', sessionId, uploadId }, ARTIFACT_CLEANUP_TIMEOUT_MS)));
1215
+ const failedAbort = aborts.find((result) => result.status === 'rejected');
1216
+ if (failedAbort) {
1217
+ closeError = requestErrorFromRuntimeHost(failedAbort.reason, 'artifact.ingest');
1218
+ }
1219
+ }
821
1220
  if (attachmentTask) {
822
1221
  try {
823
1222
  // A rejected open has no retained resource; close still releases ownership.
@@ -825,7 +1224,7 @@ export class AcpSessionRegistry {
825
1224
  await attachment?.close();
826
1225
  }
827
1226
  catch (error) {
828
- closeError = error;
1227
+ closeError ??= error;
829
1228
  }
830
1229
  }
831
1230
  const mcp = this.#detachMcp(sessionId);
@@ -1003,14 +1402,11 @@ export class AcpSessionRegistry {
1003
1402
  };
1004
1403
  context.signal.addEventListener('abort', onAbort, { once: true });
1005
1404
  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))
1405
+ const prepared = await this.#prepareExternalObservation(params.sessionId, context, connection, 'turn.resume.start', turnId);
1406
+ attachment = prepared.attachment;
1407
+ observation = prepared.observation;
1408
+ if (!observation)
1012
1409
  throw registryClosedError('turn.resume.start');
1013
- observation = adopted;
1014
1410
  if (context.signal.aborted)
1015
1411
  onAbort();
1016
1412
  if (observation.cancelled)
@@ -1400,6 +1796,9 @@ export class AcpSessionRegistry {
1400
1796
  lifetime.throwIfAborted();
1401
1797
  this.#assertOpen('subscription.open');
1402
1798
  this.#assertOwned(params.sessionId);
1799
+ if (context.notifyGoalStatus || context.notifyPlanChanged) {
1800
+ this.#domainObservations.get(params.sessionId)?.initialize(attachment.snapshot.goal);
1801
+ }
1403
1802
  if ((this.#sessionCloseGenerations.get(params.sessionId) ?? 0) !== generation) {
1404
1803
  throw unknownSessionError();
1405
1804
  }
@@ -1669,6 +2068,9 @@ export class AcpSessionRegistry {
1669
2068
  };
1670
2069
  }
1671
2070
  async #dispose() {
2071
+ for (const observer of this.#domainObservations.values())
2072
+ observer.dispose();
2073
+ this.#domainObservations.clear();
1672
2074
  this.#externalObservationContexts.clear();
1673
2075
  this.#externalContextLeases.clear();
1674
2076
  for (const observations of this.#turnObservations.values()) {
@@ -1724,10 +2126,16 @@ export class AcpSessionRegistry {
1724
2126
  ...this.#inFlightOperations,
1725
2127
  ...configurations.map(({ tail }) => tail),
1726
2128
  ]);
2129
+ this.#pendingPlanAdmissions.clear();
2130
+ this.#artifactOperations.clear();
2131
+ this.#artifactCleanupTasks.clear();
2132
+ this.#artifactUploads.clear();
1727
2133
  this.#ownedSessionIds.clear();
1728
2134
  this.#historyReplayDelivery.clear();
1729
2135
  }
1730
2136
  #closeOwnedConnection() {
2137
+ this.#artifactConnectionDisposer?.();
2138
+ this.#artifactConnectionDisposer = undefined;
1731
2139
  const connection = this.#connection;
1732
2140
  const connectTask = this.#connectTask;
1733
2141
  if (!connection && !connectTask)
@@ -21,6 +21,8 @@ import { RequestError, } from '@agentclientprotocol/sdk';
21
21
  import { decodeToolStepProgress, } from '@maka/core/events';
22
22
  import { projectToolArgsPreview } from '@maka/core/tool-quiet-preview';
23
23
  import { toolResultActivityStatus } from '@maka/core/tool-result-status';
24
+ import { isCanonicalArtifactEntityId } from '@maka/core/artifacts';
25
+ import { formatAttachmentResourceRef } from '@maka/core/attachments';
24
26
  import { BoundedChunkBuffer } from '../bounded-chunk-buffer.js';
25
27
  import { formatToolResultContent } from '../pi-transcript-format.js';
26
28
  // Presentation limits, not Host execution/admission limits. The per-tool values
@@ -33,10 +35,12 @@ const AUXILIARY_CHARS = 4096;
33
35
  /** Tool presentation only. Turn completion remains the Session channel's decision. */
34
36
  export class AcpToolEventMapper {
35
37
  notify;
38
+ sessionId;
36
39
  #tools = new Map();
37
40
  #retainedChars = 0;
38
- constructor(notify) {
41
+ constructor(notify, sessionId) {
39
42
  this.notify = notify;
43
+ this.sessionId = sessionId;
40
44
  }
41
45
  async accept(event) {
42
46
  const tool = this.#ensure(event.turnId, event.toolUseId);
@@ -223,12 +227,18 @@ export class AcpToolEventMapper {
223
227
  }
224
228
  else {
225
229
  tool.authoritative = true;
226
- const presentation = bounded(formatToolResultContent(result), TOOL_CHARS, '\n[Result truncated]');
230
+ const artifacts = artifactReferences(result, this.sessionId);
231
+ if (artifacts.length > 0)
232
+ tool.meta.artifacts = artifacts;
233
+ else
234
+ delete tool.meta.artifacts;
235
+ const artifactHints = artifacts.map(({ artifactId, resourceRef }) => `Artifact ${artifactId}: ${resourceRef} (read with _maka/artifact/query)`);
236
+ const presentation = bounded(formatToolResultContent(result), TOOL_CHARS - artifactHints.join('\n').length - (artifactHints.length > 0 ? 1 : 0), '\n[Result truncated]');
227
237
  const raw = JSON.stringify(result);
228
238
  tool.meta.resultTruncated = presentation.dropped > 0;
229
239
  tool.meta.resultDroppedChars = presentation.dropped;
230
240
  await this.#publish(tool, {
231
- content: textContent(presentation.text),
241
+ content: textContent([...artifactHints, presentation.text].join('\n')),
232
242
  ...(raw.length <= TOOL_CHARS && presentation.dropped === 0 ? { rawOutput: result } : {}),
233
243
  });
234
244
  }
@@ -351,6 +361,29 @@ export class AcpToolEventMapper {
351
361
  tool.retainedChars = chars;
352
362
  }
353
363
  }
364
+ function artifactReferences(result, sessionId) {
365
+ if (!sessionId)
366
+ return [];
367
+ let artifactId;
368
+ if (result.kind === 'image' &&
369
+ result.ref.kind === 'session_file' &&
370
+ result.ref.sessionId === sessionId)
371
+ artifactId = result.ref.relativePath;
372
+ else if (result.kind === 'archived_tool_result' && result.status === 'not_loaded')
373
+ artifactId = result.artifactId;
374
+ if (!isCanonicalArtifactEntityId(artifactId))
375
+ return [];
376
+ return [
377
+ {
378
+ artifactId,
379
+ resourceRef: formatAttachmentResourceRef({
380
+ kind: 'session_file',
381
+ sessionId,
382
+ relativePath: artifactId,
383
+ }),
384
+ },
385
+ ];
386
+ }
354
387
  function fixedStateChars(tool) {
355
388
  return (tool.inputPreview.length +
356
389
  tool.preview.length +
@@ -43,6 +43,7 @@ export class RuntimeHostSessionChannel {
43
43
  #onTranscriptSettlement;
44
44
  #onTranscriptReplaced;
45
45
  #onGoalChanged;
46
+ #onCanonicalReplacement;
46
47
  #onSnapshotChanged;
47
48
  #onFailed;
48
49
  #onRecovered;
@@ -84,6 +85,7 @@ export class RuntimeHostSessionChannel {
84
85
  this.#onTranscriptSettlement = options.onTranscriptSettlement;
85
86
  this.#onTranscriptReplaced = options.onTranscriptReplaced;
86
87
  this.#onGoalChanged = options.onGoalChanged;
88
+ this.#onCanonicalReplacement = options.onCanonicalReplacement;
87
89
  this.#onSnapshotChanged = options.onSnapshotChanged;
88
90
  this.#onFailed = options.onFailed;
89
91
  this.#onRecovered = options.onRecovered;
@@ -569,6 +571,8 @@ export class RuntimeHostSessionChannel {
569
571
  }
570
572
  this.#projector = new RuntimeHostSessionProjector(nextSnapshot, createRuntimeHostSessionProjectionSeed(this.messages, nextSnapshot), this.#now, this.#subscription.activeAssistantStreams);
571
573
  this.#onSnapshotChanged?.(structuredClone(this.#projector.snapshot));
574
+ if (replacedLiveState)
575
+ this.#onCanonicalReplacement?.(structuredClone(this.#projector.snapshot));
572
576
  // A canonical replacement is a sequence cut. No queued event from the
573
577
  // retired subscription may replay after the transcript/snapshot has
574
578
  // established newer state; active, terminal, and interaction state is