@moxt-ai/mobius 0.0.58 → 0.0.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { basename } from "node:path";
3
3
  import { styleText } from "node:util";
4
- import { AGENT_ACTIVITY_KIND, AGENT_CATALOG_REFRESH_FAILED_KIND, AGENT_CATALOG_REFRESH_KIND, AGENT_CATALOG_REFRESHED_KIND, AGENT_INSTALL_CANCEL_KIND, AGENT_INSTALL_CANCELLED_KIND, AGENT_INSTALL_COMPLETED_KIND, AGENT_INSTALL_FAILED_KIND, AGENT_INSTALL_PROGRESS_KIND, AGENT_INSTALL_REQUEST_KIND, AGENT_INSTALL_STARTED_KIND, AGENT_MESSAGE_DELTA_KIND, AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE, AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION, AGENT_MODEL_EFFORT_RESOLUTION_UNAVAILABLE, AGENT_SETTINGS_DISCOVER_KIND, AGENT_SETTINGS_DISCOVERED_KIND, AGENT_SETTINGS_DISCOVERY_FAILED_KIND, decodeAgentCatalogRefreshCommand, decodeAgentInstallCancelCommand, decodeAgentInstallRequestCommand, decodeAgentSettingsDiscoverCommand, decodeFileReadCommand, decodeMessageKind, decodeNativeSessionCancel, decodeNativeSessionCommand, decodeNativeSessionTurnForkCommand, decodeRuntimeDelivery, decodeRuntimeDeliveryCommitted, decodeRuntimeHeartbeatAckEvent, decodeRuntimeLivenessReadyEvent, decodeSessionCancelCommand, decodeSessionConfigureCommand, decodeSessionElicitationRespondCommand, decodeSessionEventAcknowledgement, decodeSessionEventDeferred, decodeSessionEventEnvelope, decodeSessionEventRejection, decodeSessionPermissionRespondCommand, decodeSessionPrepareCommand, decodeSessionPromptCommand, decodeWorkspaceListCommand, encodeAgentActivityEvent, encodeAgentCatalogRefreshedEvent, encodeAgentCatalogRefreshFailedEvent, encodeAgentContentEvent, encodeAgentInstallCancelledEvent, encodeAgentInstallCompletedEvent, encodeAgentInstallFailedEvent, encodeAgentInstallProgressEvent, encodeAgentInstallStartedEvent, encodeAgentMessageDeltaEvent, encodeAgentSettingsDiscoveredEvent, encodeAgentSettingsDiscoveryFailedEvent, encodeFileFailedEvent, encodeNativeSessionResult, encodeRuntimeDeliveryReceived, encodeSessionCommandsUpdatedEvent, encodeSessionCompletedEvent, encodeSessionConfigUpdatedEvent, encodeSessionElicitationRequestedEvent, encodeSessionElicitationResolvedEvent, encodeSessionFailedEvent, encodeSessionInfoUpdatedEvent, encodeSessionOperationFailedEvent, encodeSessionPermissionRequestedEvent, encodeSessionPermissionResolvedEvent, encodeSessionReadyEvent, encodeSessionStartedEvent, encodeSessionUsageUpdatedEvent, encodeWorkspaceEntriesEvent, FILE_FAILED_KIND, FILE_READ_KIND, NATIVE_SESSION_CANCEL_KIND, NATIVE_SESSION_REQUEST_KIND, NATIVE_SESSION_TURN_FORK_KIND, RUNTIME_DELIVERY_COMMITTED_KIND, RUNTIME_DELIVERY_KIND, RUNTIME_DELIVERY_RECEIVED_KIND, RUNTIME_HEARTBEAT_ACK_KIND, RUNTIME_LIVENESS_READY_KIND, SESSION_CANCEL_KIND, SESSION_COMPLETED_KIND, SESSION_CONFIGURE_KIND, SESSION_ELICITATION_RESPOND_KIND, SESSION_EVENT_ACK_KIND, SESSION_EVENT_DEFERRED_KIND, SESSION_EVENT_REJECTED_KIND, SESSION_FAILED_KIND, SESSION_PERMISSION_RESPOND_KIND, SESSION_PREPARE_KIND, SESSION_PROMPT_KIND, SESSION_STARTED_KIND, SessionPromptDisposition, WORKSPACE_LIST_KIND, } from "@moxt-ai/mobius-protocol";
4
+ import { AGENT_ACTIVITY_KIND, AGENT_CATALOG_REFRESH_FAILED_KIND, AGENT_CATALOG_REFRESH_KIND, AGENT_CATALOG_REFRESHED_KIND, AGENT_INSTALL_CANCEL_KIND, AGENT_INSTALL_CANCELLED_KIND, AGENT_INSTALL_COMPLETED_KIND, AGENT_INSTALL_FAILED_KIND, AGENT_INSTALL_PROGRESS_KIND, AGENT_INSTALL_REQUEST_KIND, AGENT_INSTALL_STARTED_KIND, AGENT_MESSAGE_DELTA_KIND, AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE, AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION, AGENT_MODEL_EFFORT_RESOLUTION_UNAVAILABLE, AGENT_SETTINGS_DISCOVER_KIND, AGENT_SETTINGS_DISCOVERED_KIND, AGENT_SETTINGS_DISCOVERY_FAILED_KIND, decodeServiceToDaemonMessage, decodeSessionEventEnvelope, encodeDaemonToServiceMessage, encodeRecordedSessionEvent, FILE_FAILED_KIND, FILE_READ_KIND, NATIVE_SESSION_CANCEL_KIND, NATIVE_SESSION_REQUEST_KIND, NATIVE_SESSION_TURN_FORK_KIND, RUNTIME_DELIVERY_COMMITTED_KIND, RUNTIME_DELIVERY_KIND, RUNTIME_DELIVERY_RECEIVED_KIND, RUNTIME_HEARTBEAT_ACK_KIND, RUNTIME_LIVENESS_READY_KIND, SESSION_CANCEL_KIND, SESSION_COMPLETED_KIND, SESSION_CONFIGURE_KIND, SESSION_ELICITATION_RESPOND_KIND, SESSION_EVENT_ACK_KIND, SESSION_EVENT_DEFERRED_KIND, SESSION_EVENT_REJECTED_KIND, SESSION_FAILED_KIND, SESSION_PERMISSION_RESPOND_KIND, SESSION_PREPARE_KIND, SESSION_PROMPT_KIND, SESSION_STARTED_KIND, SessionPromptDisposition, WORKSPACE_LIST_KIND, } from "@moxt-ai/mobius-protocol";
5
5
  import { fetch, WebSocket } from "undici";
6
6
  import { AcpExecutionError, AcpSessionManager } from "./acp/session-manager.js";
7
7
  import { SqliteAcpSessionStore } from "./acp/session-store.js";
@@ -46,39 +46,39 @@ class DaemonAcpObserver {
46
46
  }
47
47
  importLocalArtifact = async (sessionId, artifact, signal) => (await uploadRuntimeArtifact(this.#config, sessionId, artifact, signal)).artifactId;
48
48
  onCommands = (event) => {
49
- this.#record(event.sessionId, encodeSessionCommandsUpdatedEvent(event));
49
+ this.#record(event.sessionId, event);
50
50
  return Promise.resolve();
51
51
  };
52
52
  onConfig = (event) => {
53
- this.#record(event.sessionId, encodeSessionConfigUpdatedEvent(event));
53
+ this.#record(event.sessionId, event);
54
54
  return Promise.resolve();
55
55
  };
56
56
  onContent = (event) => {
57
- this.#record(event.sessionId, encodeAgentContentEvent(event));
57
+ this.#record(event.sessionId, event);
58
58
  return Promise.resolve();
59
59
  };
60
60
  onElicitation = (event) => {
61
- this.#record(event.sessionId, encodeSessionElicitationRequestedEvent(event));
61
+ this.#record(event.sessionId, event);
62
62
  return Promise.resolve();
63
63
  };
64
64
  onElicitationResolved = (event) => {
65
- this.#record(event.sessionId, encodeSessionElicitationResolvedEvent(event));
65
+ this.#record(event.sessionId, event);
66
66
  return Promise.resolve();
67
67
  };
68
68
  onInfo = (event) => {
69
- this.#record(event.sessionId, encodeSessionInfoUpdatedEvent(event));
69
+ this.#record(event.sessionId, event);
70
70
  return Promise.resolve();
71
71
  };
72
72
  onPermission = (event) => {
73
- this.#record(event.sessionId, encodeSessionPermissionRequestedEvent(event));
73
+ this.#record(event.sessionId, event);
74
74
  return Promise.resolve();
75
75
  };
76
76
  onPermissionResolved = (event) => {
77
- this.#record(event.sessionId, encodeSessionPermissionResolvedEvent(event));
77
+ this.#record(event.sessionId, event);
78
78
  return Promise.resolve();
79
79
  };
80
80
  onUsage = (event) => {
81
- this.#record(event.sessionId, encodeSessionUsageUpdatedEvent(event));
81
+ this.#record(event.sessionId, event);
82
82
  return Promise.resolve();
83
83
  };
84
84
  }
@@ -128,45 +128,45 @@ class DaemonInstallationObserver {
128
128
  if (state instanceof RunningInstallation) {
129
129
  if (!this.#started.has(state.requestId)) {
130
130
  this.#started.add(state.requestId);
131
- this.#send(socket, encodeAgentInstallStartedEvent({
131
+ this.#send(socket, {
132
132
  agentId: state.agentId,
133
133
  kind: AGENT_INSTALL_STARTED_KIND,
134
134
  requestId: state.requestId,
135
- }));
135
+ });
136
136
  }
137
- this.#send(socket, encodeAgentInstallProgressEvent({
137
+ this.#send(socket, {
138
138
  agentId: state.agentId,
139
139
  kind: AGENT_INSTALL_PROGRESS_KIND,
140
140
  requestId: state.requestId,
141
141
  stage: state.stage,
142
- }));
142
+ });
143
143
  return Promise.resolve();
144
144
  }
145
145
  if (state instanceof SucceededInstallation) {
146
- this.#send(socket, encodeAgentInstallCompletedEvent({
146
+ this.#send(socket, {
147
147
  agentId: state.agentId,
148
148
  authenticationMayBeRequired: state.authenticationMayBeRequired,
149
149
  kind: AGENT_INSTALL_COMPLETED_KIND,
150
150
  requestId: state.requestId,
151
- }));
151
+ });
152
152
  return Promise.resolve();
153
153
  }
154
154
  if (state instanceof FailedInstallation) {
155
- this.#send(socket, encodeAgentInstallFailedEvent({
155
+ this.#send(socket, {
156
156
  agentId: state.agentId,
157
157
  code: state.code,
158
158
  kind: AGENT_INSTALL_FAILED_KIND,
159
159
  message: state.message,
160
160
  requestId: state.requestId,
161
- }));
161
+ });
162
162
  return Promise.resolve();
163
163
  }
164
164
  if (state instanceof CancelledInstallation) {
165
- this.#send(socket, encodeAgentInstallCancelledEvent({
165
+ this.#send(socket, {
166
166
  agentId: state.agentId,
167
167
  kind: AGENT_INSTALL_CANCELLED_KIND,
168
168
  requestId: state.requestId,
169
- }));
169
+ });
170
170
  return Promise.resolve();
171
171
  }
172
172
  throw new Error("Unsupported Agent integration installation state");
@@ -214,9 +214,38 @@ class ActiveDaemonTurn {
214
214
  }
215
215
  class ActiveTurnReconciliationError extends Error {
216
216
  code = "active_turn_reconciliation_failed";
217
+ diagnosticDetails;
218
+ relayErrorCode;
219
+ terminal;
217
220
  constructor(message, options = {}) {
218
221
  super(message, options);
219
222
  this.name = "ActiveTurnReconciliationError";
223
+ this.relayErrorCode = options.relayErrorCode ?? null;
224
+ this.terminal = options.terminal ?? false;
225
+ this.diagnosticDetails = this.relayErrorCode === null ? {} : { relayErrorCode: this.relayErrorCode };
226
+ }
227
+ }
228
+ /**
229
+ * The Relay reports a reconciliation conflict when the Attempt is no longer owned by this Runtime or has
230
+ * already reached a terminal state. Retrying cannot change that outcome, so the daemon must abandon the
231
+ * stale turn instead of replacing its connection forever.
232
+ */
233
+ const TERMINAL_RECONCILIATION_RELAY_CODES = new Set(["session_conflict"]);
234
+ async function relayErrorCode(response) {
235
+ try {
236
+ const body = JSON.parse(await response.text());
237
+ if (typeof body !== "object" || body === null) {
238
+ return null;
239
+ }
240
+ const error = Reflect.get(body, "error");
241
+ if (typeof error !== "object" || error === null) {
242
+ return null;
243
+ }
244
+ const code = Reflect.get(error, "code");
245
+ return typeof code === "string" && code.length > 0 ? code : null;
246
+ }
247
+ catch {
248
+ return null;
220
249
  }
221
250
  }
222
251
  function activeTurnReconciliationEndpoint(config, turn) {
@@ -257,10 +286,14 @@ async function reconcileActiveTurn(config, turn, signal) {
257
286
  ? "The active Agent turn reconciliation timed out"
258
287
  : "The active Agent turn could not be reconciled", { cause: error });
259
288
  }
260
- await response.body?.cancel();
261
289
  if (!response.ok) {
262
- throw new ActiveTurnReconciliationError(`The Relay rejected the active Agent turn reconciliation with status ${response.status.toString()}`);
290
+ const errorCode = await relayErrorCode(response);
291
+ const terminal = errorCode !== null && TERMINAL_RECONCILIATION_RELAY_CODES.has(errorCode);
292
+ throw new ActiveTurnReconciliationError(terminal
293
+ ? `The Relay reported that the active Agent turn can no longer be reconciled (${errorCode})`
294
+ : `The Relay rejected the active Agent turn reconciliation with status ${response.status.toString()}`, { relayErrorCode: errorCode, terminal });
263
295
  }
296
+ await response.body?.cancel();
264
297
  }
265
298
  async function reconcileActiveTurns(config, turns, signal) {
266
299
  await Promise.all(turns.map(async (turn) => await reconcileActiveTurn(config, turn, signal)));
@@ -269,7 +302,7 @@ function send(socket, message) {
269
302
  if (socket.readyState !== WebSocket.OPEN) {
270
303
  throw new Error("Relay connection is not open");
271
304
  }
272
- socket.send(message);
305
+ socket.send(encodeDaemonToServiceMessage(message));
273
306
  }
274
307
  function closeRelaySocket(socket, code, reason) {
275
308
  try {
@@ -305,7 +338,7 @@ class ConnectedDaemonSessionEventState extends DaemonSessionEventConnectionState
305
338
  return false;
306
339
  }
307
340
  try {
308
- this.#socket.send(message);
341
+ this.#socket.send(encodeDaemonToServiceMessage(message));
309
342
  return true;
310
343
  }
311
344
  catch {
@@ -353,18 +386,18 @@ class DaemonSessionEventPublisher {
353
386
  this.#connection = this.#connection.disconnect(socket);
354
387
  this.#clearInFlight();
355
388
  };
356
- recordAttempt = (sessionId, payload, attemptId) => {
357
- const kind = decodeMessageKind(payload);
358
- if (kind === SESSION_COMPLETED_KIND || kind === SESSION_FAILED_KIND) {
359
- this.#outbox.enqueueCritical(sessionId, payload, attemptId);
389
+ recordAttempt = (sessionId, event, attemptId) => {
390
+ const encoded = encodeRecordedSessionEvent(event);
391
+ if (event.kind === SESSION_COMPLETED_KIND || event.kind === SESSION_FAILED_KIND) {
392
+ this.#outbox.enqueueCritical(sessionId, encoded, attemptId);
360
393
  }
361
394
  else {
362
- this.#outbox.enqueue(sessionId, payload, attemptId);
395
+ this.#outbox.enqueue(sessionId, encoded, attemptId);
363
396
  }
364
397
  this.#publishNextBatch();
365
398
  };
366
- recordRuntime = (sessionId, payload) => {
367
- this.#outbox.enqueue(sessionId, payload);
399
+ recordRuntime = (sessionId, event) => {
400
+ this.#outbox.enqueue(sessionId, encodeRecordedSessionEvent(event));
368
401
  this.#publishNextBatch();
369
402
  };
370
403
  acknowledge = (acknowledgement) => {
@@ -426,7 +459,7 @@ class DaemonSessionEventPublisher {
426
459
  if (this.#inFlightBytes + byteLength > SESSION_EVENT_REPLAY_BYTE_LIMIT) {
427
460
  continue;
428
461
  }
429
- if (!this.#connection.send(encoded)) {
462
+ if (!this.#connection.send(envelope)) {
430
463
  this.#clearInFlight();
431
464
  return;
432
465
  }
@@ -514,8 +547,8 @@ class CoalescingDaemonActivityPublisher {
514
547
  }
515
548
  };
516
549
  }
517
- function encodeDaemonActivity(command, activity) {
518
- return encodeAgentActivityEvent({
550
+ function daemonActivity(command, activity) {
551
+ return {
519
552
  activityId: activity.activityId,
520
553
  activityType: activity.activityType,
521
554
  commandId: command.commandId,
@@ -531,16 +564,16 @@ function encodeDaemonActivity(command, activity) {
531
564
  status: activity.status,
532
565
  title: activity.title,
533
566
  toolKind: activity.toolKind,
534
- });
567
+ };
535
568
  }
536
569
  function reportFailure(publisher, command, code, message, attemptId) {
537
- publisher.recordAttempt(command.sessionId, encodeSessionFailedEvent({
570
+ publisher.recordAttempt(command.sessionId, {
538
571
  code,
539
572
  commandId: command.commandId,
540
573
  kind: SESSION_FAILED_KIND,
541
574
  message,
542
575
  sessionId: command.sessionId,
543
- }), attemptId);
576
+ }, attemptId);
544
577
  }
545
578
  function operationErrorCode(error) {
546
579
  if (error instanceof AcpExecutionError ||
@@ -564,14 +597,14 @@ function reportOperationFailure(socket, requestId, sessionId, error, runtimeTimi
564
597
  if (socket.readyState !== WebSocket.OPEN) {
565
598
  return;
566
599
  }
567
- send(socket, encodeSessionOperationFailedEvent({
600
+ send(socket, {
568
601
  code: operationErrorCode(error),
569
602
  kind: "session.operation.failed",
570
603
  message: operationErrorMessage(error),
571
604
  requestId,
572
605
  ...(runtimeTimings.length === 0 ? {} : { runtimeTimings }),
573
606
  sessionId,
574
- }));
607
+ });
575
608
  }
576
609
  async function resolveSessionDirectories(directories, bindingId, directoryId, additionalDirectoryIds, signal) {
577
610
  const cwd = await directories.resolve(bindingId, directoryId, signal);
@@ -763,7 +796,7 @@ async function executeWorkspaceList(socket, command, directories, audit, signal)
763
796
  event: "workspace_list_authorized",
764
797
  sessionId: "workspace-browser",
765
798
  });
766
- send(socket, encodeWorkspaceEntriesEvent({
799
+ send(socket, {
767
800
  bindingId: command.bindingId,
768
801
  directoryId: listing.directoryId,
769
802
  directoryLabel: listing.directoryLabel,
@@ -771,7 +804,7 @@ async function executeWorkspaceList(socket, command, directories, audit, signal)
771
804
  kind: "workspace.entries",
772
805
  parentDirectoryId: listing.parentDirectoryId,
773
806
  requestId: command.requestId,
774
- }));
807
+ });
775
808
  }
776
809
  catch (error) {
777
810
  reportOperationFailure(socket, command.requestId, "", error);
@@ -816,12 +849,12 @@ async function executeSessionPrepare(publisher, socket, command, config, directo
816
849
  event: "session_configured",
817
850
  sessionId: command.sessionId,
818
851
  });
819
- publisher.recordRuntime(command.sessionId, encodeSessionConfigUpdatedEvent({
852
+ publisher.recordRuntime(command.sessionId, {
820
853
  configOptions,
821
854
  kind: "session.config.updated",
822
855
  requestId: command.requestId,
823
856
  sessionId: command.sessionId,
824
- }));
857
+ });
825
858
  }
826
859
  const event = {
827
860
  additionalDirectories: resolved.additionalDirectoryEntries,
@@ -840,14 +873,14 @@ async function executeSessionPrepare(publisher, socket, command, config, directo
840
873
  runtimeTimings: metrics.snapshot(),
841
874
  };
842
875
  metrics.measureSync("readiness-commit", () => {
843
- publisher.recordRuntime(command.sessionId, encodeSessionReadyEvent(event));
876
+ publisher.recordRuntime(command.sessionId, event);
844
877
  });
845
878
  return event;
846
879
  });
847
- send(socket, encodeSessionReadyEvent({
880
+ send(socket, {
848
881
  ...readyEvent,
849
882
  runtimeTimings: metrics.snapshot(),
850
- }));
883
+ });
851
884
  }
852
885
  catch (error) {
853
886
  audit.record({
@@ -882,12 +915,12 @@ async function executeSessionConfigure(publisher, socket, command, config, direc
882
915
  event: "session_configured",
883
916
  sessionId: command.sessionId,
884
917
  });
885
- publisher.recordRuntime(command.sessionId, encodeSessionConfigUpdatedEvent({
918
+ publisher.recordRuntime(command.sessionId, {
886
919
  configOptions,
887
920
  kind: "session.config.updated",
888
921
  requestId: command.requestId,
889
922
  sessionId: command.sessionId,
890
- }));
923
+ });
891
924
  }
892
925
  catch (error) {
893
926
  if (signal.aborted) {
@@ -898,16 +931,16 @@ async function executeSessionConfigure(publisher, socket, command, config, direc
898
931
  }
899
932
  async function executePrompt(outbox, publisher, command, config, directories, audit, sessions, attemptId, activateAttempt, timer, signal) {
900
933
  const activities = new CoalescingDaemonActivityPublisher(timer, (activity) => {
901
- publisher.recordAttempt(command.sessionId, encodeDaemonActivity(command, activity), attemptId);
934
+ publisher.recordAttempt(command.sessionId, daemonActivity(command, activity), attemptId);
902
935
  });
903
936
  const text = new CoalescingTextPublisher(timer, (messageId, delta) => {
904
- publisher.recordAttempt(command.sessionId, encodeAgentMessageDeltaEvent({
937
+ publisher.recordAttempt(command.sessionId, {
905
938
  commandId: command.commandId,
906
939
  kind: AGENT_MESSAGE_DELTA_KIND,
907
940
  messageId,
908
941
  sessionId: command.sessionId,
909
942
  text: delta,
910
- }), attemptId);
943
+ }, attemptId);
911
944
  }, AGENT_TEXT_COALESCING_MILLISECONDS, AGENT_TEXT_MAXIMUM_LENGTH);
912
945
  try {
913
946
  const resolved = await resolveSessionDirectories(directories, config.bindingId, command.directoryId, command.additionalDirectoryIds, signal);
@@ -942,12 +975,12 @@ async function executePrompt(outbox, publisher, command, config, directories, au
942
975
  sessionId: command.sessionId,
943
976
  });
944
977
  outbox.transitionExecution(command.commandId, "running");
945
- publisher.recordAttempt(command.sessionId, encodeSessionStartedEvent({
978
+ publisher.recordAttempt(command.sessionId, {
946
979
  commandId: command.commandId,
947
980
  kind: SESSION_STARTED_KIND,
948
981
  attemptId,
949
982
  sessionId: command.sessionId,
950
- }), attemptId);
983
+ }, attemptId);
951
984
  activateAttempt();
952
985
  const attachments = await resolvePromptArtifacts(config, command, signal);
953
986
  let stopReason;
@@ -989,12 +1022,12 @@ async function executePrompt(outbox, publisher, command, config, directories, au
989
1022
  }
990
1023
  text.flush();
991
1024
  activities.flush();
992
- publisher.recordAttempt(command.sessionId, encodeSessionCompletedEvent({
1025
+ publisher.recordAttempt(command.sessionId, {
993
1026
  commandId: command.commandId,
994
1027
  kind: SESSION_COMPLETED_KIND,
995
1028
  sessionId: command.sessionId,
996
1029
  stopReason,
997
- }), attemptId);
1030
+ }, attemptId);
998
1031
  outbox.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
999
1032
  audit.record({
1000
1033
  commandId: command.commandId,
@@ -1370,9 +1403,10 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1370
1403
  }
1371
1404
  };
1372
1405
  const processDeliveredPayload = async (delivery) => {
1373
- const kind = decodeMessageKind(delivery.payload);
1406
+ const message = decodeServiceToDaemonMessage(delivery.payload);
1407
+ const kind = message.kind;
1374
1408
  if (kind === SESSION_CANCEL_KIND) {
1375
- const cancellation = decodeSessionCancelCommand(delivery.payload);
1409
+ const cancellation = message;
1376
1410
  if (cancellation.sessionId !== delivery.sessionId) {
1377
1411
  throw new Error("Runtime delivery Session identity does not match its payload");
1378
1412
  }
@@ -1389,7 +1423,7 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1389
1423
  return;
1390
1424
  }
1391
1425
  if (kind === SESSION_CONFIGURE_KIND) {
1392
- const command = decodeSessionConfigureCommand(delivery.payload);
1426
+ const command = message;
1393
1427
  if (command.sessionId !== delivery.sessionId) {
1394
1428
  throw new Error("Runtime delivery Session identity does not match its payload");
1395
1429
  }
@@ -1397,7 +1431,7 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1397
1431
  return;
1398
1432
  }
1399
1433
  if (kind === SESSION_PERMISSION_RESPOND_KIND) {
1400
- const command = decodeSessionPermissionRespondCommand(delivery.payload);
1434
+ const command = message;
1401
1435
  if (command.sessionId !== delivery.sessionId) {
1402
1436
  throw new Error("Runtime delivery Session identity does not match its payload");
1403
1437
  }
@@ -1415,7 +1449,7 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1415
1449
  return;
1416
1450
  }
1417
1451
  if (kind === SESSION_ELICITATION_RESPOND_KIND) {
1418
- const command = decodeSessionElicitationRespondCommand(delivery.payload);
1452
+ const command = message;
1419
1453
  if (command.sessionId !== delivery.sessionId) {
1420
1454
  throw new Error("Runtime delivery Session identity does not match its payload");
1421
1455
  }
@@ -1433,7 +1467,7 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1433
1467
  return;
1434
1468
  }
1435
1469
  if (kind === SESSION_PROMPT_KIND) {
1436
- const command = decodeSessionPromptCommand(delivery.payload);
1470
+ const command = message;
1437
1471
  await processDeliveredPrompt(delivery, command, command.disposition !== SessionPromptDisposition.Steer, (attemptId, activateAttempt, executionSignal) => executePrompt(outbox, publisher, command, config, directories, audit, sessions, attemptId, activateAttempt, timer, executionSignal));
1438
1472
  return;
1439
1473
  }
@@ -1458,22 +1492,23 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1458
1492
  .finally(() => processingDeliveryIds.delete(delivery.deliveryId));
1459
1493
  };
1460
1494
  const receiveRuntimeDelivery = (delivery) => {
1461
- const payloadKind = decodeMessageKind(delivery.payload);
1495
+ const payload = decodeServiceToDaemonMessage(delivery.payload);
1496
+ const payloadKind = payload.kind;
1462
1497
  let payloadSessionId = "";
1463
1498
  if (payloadKind === SESSION_CANCEL_KIND) {
1464
- payloadSessionId = decodeSessionCancelCommand(delivery.payload).sessionId;
1499
+ payloadSessionId = payload.sessionId;
1465
1500
  }
1466
1501
  else if (payloadKind === SESSION_CONFIGURE_KIND) {
1467
- payloadSessionId = decodeSessionConfigureCommand(delivery.payload).sessionId;
1502
+ payloadSessionId = payload.sessionId;
1468
1503
  }
1469
1504
  else if (payloadKind === SESSION_PERMISSION_RESPOND_KIND) {
1470
- payloadSessionId = decodeSessionPermissionRespondCommand(delivery.payload).sessionId;
1505
+ payloadSessionId = payload.sessionId;
1471
1506
  }
1472
1507
  else if (payloadKind === SESSION_ELICITATION_RESPOND_KIND) {
1473
- payloadSessionId = decodeSessionElicitationRespondCommand(delivery.payload).sessionId;
1508
+ payloadSessionId = payload.sessionId;
1474
1509
  }
1475
1510
  else if (payloadKind === SESSION_PROMPT_KIND) {
1476
- payloadSessionId = decodeSessionPromptCommand(delivery.payload).sessionId;
1511
+ payloadSessionId = payload.sessionId;
1477
1512
  }
1478
1513
  else {
1479
1514
  throw new Error("Runtime delivery contains an unsupported protocol message");
@@ -1482,11 +1517,11 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1482
1517
  throw new Error("Runtime delivery Session identity does not match its payload");
1483
1518
  }
1484
1519
  const stored = outbox.claimRuntimeDelivery(delivery);
1485
- send(socket, encodeRuntimeDeliveryReceived({
1520
+ send(socket, {
1486
1521
  deliveryId: delivery.deliveryId,
1487
1522
  kind: RUNTIME_DELIVERY_RECEIVED_KIND,
1488
1523
  sessionId: delivery.sessionId,
1489
- }));
1524
+ });
1490
1525
  processRuntimeDelivery(delivery, stored.state);
1491
1526
  };
1492
1527
  const resumeRuntimeDeliveries = () => {
@@ -1498,11 +1533,11 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1498
1533
  sessionId: stored.sessionId,
1499
1534
  };
1500
1535
  if (stored.state !== "relay_committed") {
1501
- send(socket, encodeRuntimeDeliveryReceived({
1536
+ send(socket, {
1502
1537
  deliveryId: stored.deliveryId,
1503
1538
  kind: RUNTIME_DELIVERY_RECEIVED_KIND,
1504
1539
  sessionId: stored.sessionId,
1505
- }));
1540
+ });
1506
1541
  }
1507
1542
  processRuntimeDelivery(delivery, stored.state);
1508
1543
  }
@@ -1557,28 +1592,29 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1557
1592
  return;
1558
1593
  }
1559
1594
  try {
1560
- const kind = decodeMessageKind(encoded);
1595
+ const message = decodeServiceToDaemonMessage(encoded);
1596
+ const kind = message.kind;
1561
1597
  if (kind === RUNTIME_DELIVERY_COMMITTED_KIND) {
1562
- const committed = decodeRuntimeDeliveryCommitted(encoded);
1598
+ const committed = message;
1563
1599
  if (!outbox.markRuntimeDeliveryCommitted(committed.deliveryId, committed.sessionId)) {
1564
1600
  console.warn("Mobius daemon ignored confirmation for an unknown Runtime delivery");
1565
1601
  }
1566
1602
  return;
1567
1603
  }
1568
1604
  if (kind === RUNTIME_DELIVERY_KIND) {
1569
- receiveRuntimeDelivery(decodeRuntimeDelivery(encoded));
1605
+ receiveRuntimeDelivery(message);
1570
1606
  return;
1571
1607
  }
1572
1608
  if (kind === SESSION_EVENT_ACK_KIND) {
1573
- publisher.acknowledge(decodeSessionEventAcknowledgement(encoded));
1609
+ publisher.acknowledge(message);
1574
1610
  return;
1575
1611
  }
1576
1612
  if (kind === SESSION_EVENT_DEFERRED_KIND) {
1577
- publisher.defer(decodeSessionEventDeferred(encoded));
1613
+ publisher.defer(message);
1578
1614
  return;
1579
1615
  }
1580
1616
  if (kind === SESSION_EVENT_REJECTED_KIND) {
1581
- const rejection = decodeSessionEventRejection(encoded);
1617
+ const rejection = message;
1582
1618
  if (publisher.quarantine(rejection)) {
1583
1619
  audit.record({
1584
1620
  commandId: rejection.eventId,
@@ -1593,7 +1629,7 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1593
1629
  return;
1594
1630
  }
1595
1631
  if (kind === NATIVE_SESSION_CANCEL_KIND) {
1596
- const command = decodeNativeSessionCancel(encoded);
1632
+ const command = message;
1597
1633
  const pending = nativeRequests.get(command.requestId);
1598
1634
  if (pending?.sessionId === command.sessionId) {
1599
1635
  pending.controller.abort(new AcpExecutionError("Native session operation cancelled", {}, "native_session_cancelled"));
@@ -1601,27 +1637,27 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1601
1637
  return;
1602
1638
  }
1603
1639
  if (kind === AGENT_SETTINGS_DISCOVER_KIND) {
1604
- const command = decodeAgentSettingsDiscoverCommand(encoded);
1640
+ const command = message;
1605
1641
  const existing = [...agentSettingsDiscoveries.values()].find((request) => request.agentId === command.agentId && !request.controller.signal.aborted);
1606
1642
  if (agentSettingsDiscoveries.has(command.requestId) || existing !== undefined) {
1607
1643
  if (socket.readyState === WebSocket.OPEN) {
1608
- send(socket, encodeAgentSettingsDiscoveryFailedEvent({
1644
+ send(socket, {
1609
1645
  code: "agent_settings_discovery_busy",
1610
1646
  kind: AGENT_SETTINGS_DISCOVERY_FAILED_KIND,
1611
1647
  message: "Another settings discovery is already running for this Agent",
1612
1648
  requestId: command.requestId,
1613
- }));
1649
+ });
1614
1650
  }
1615
1651
  return;
1616
1652
  }
1617
1653
  if (agentSettingsDiscoveries.size >= 4) {
1618
1654
  if (socket.readyState === WebSocket.OPEN) {
1619
- send(socket, encodeAgentSettingsDiscoveryFailedEvent({
1655
+ send(socket, {
1620
1656
  code: "agent_settings_discovery_busy",
1621
1657
  kind: AGENT_SETTINGS_DISCOVERY_FAILED_KIND,
1622
1658
  message: "Too many Agent settings discoveries are running",
1623
1659
  requestId: command.requestId,
1624
- }));
1660
+ });
1625
1661
  }
1626
1662
  return;
1627
1663
  }
@@ -1638,7 +1674,7 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1638
1674
  sessionId: `agent-settings:${command.agentId}`,
1639
1675
  });
1640
1676
  if (socket.readyState === WebSocket.OPEN) {
1641
- send(socket, encodeAgentSettingsDiscoveredEvent(result));
1677
+ send(socket, result);
1642
1678
  }
1643
1679
  }
1644
1680
  catch (error) {
@@ -1653,12 +1689,12 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1653
1689
  sessionId: `agent-settings:${command.agentId}`,
1654
1690
  });
1655
1691
  if (socket.readyState === WebSocket.OPEN) {
1656
- send(socket, encodeAgentSettingsDiscoveryFailedEvent({
1692
+ send(socket, {
1657
1693
  code: operationErrorCode(failure),
1658
1694
  kind: AGENT_SETTINGS_DISCOVERY_FAILED_KIND,
1659
1695
  message: operationErrorMessage(failure),
1660
1696
  requestId: command.requestId,
1661
- }));
1697
+ });
1662
1698
  }
1663
1699
  }
1664
1700
  finally {
@@ -1674,15 +1710,15 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1674
1710
  return;
1675
1711
  }
1676
1712
  if (kind === AGENT_CATALOG_REFRESH_KIND) {
1677
- const command = decodeAgentCatalogRefreshCommand(encoded);
1713
+ const command = message;
1678
1714
  if (agentCatalogRefreshes.has(command.requestId) || agentCatalogRefreshes.size > 0) {
1679
1715
  if (socket.readyState === WebSocket.OPEN) {
1680
- send(socket, encodeAgentCatalogRefreshFailedEvent({
1716
+ send(socket, {
1681
1717
  code: "agent_catalog_refresh_busy",
1682
1718
  kind: AGENT_CATALOG_REFRESH_FAILED_KIND,
1683
1719
  message: "Another local Agent catalog refresh is already running",
1684
1720
  requestId: command.requestId,
1685
- }));
1721
+ });
1686
1722
  }
1687
1723
  return;
1688
1724
  }
@@ -1698,10 +1734,10 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1698
1734
  sessionId: "agent-catalog",
1699
1735
  });
1700
1736
  if (socket.readyState === WebSocket.OPEN) {
1701
- send(socket, encodeAgentCatalogRefreshedEvent({
1737
+ send(socket, {
1702
1738
  kind: AGENT_CATALOG_REFRESHED_KIND,
1703
1739
  requestId: command.requestId,
1704
- }));
1740
+ });
1705
1741
  }
1706
1742
  }
1707
1743
  catch (error) {
@@ -1716,12 +1752,12 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1716
1752
  sessionId: "agent-catalog",
1717
1753
  });
1718
1754
  if (socket.readyState === WebSocket.OPEN) {
1719
- send(socket, encodeAgentCatalogRefreshFailedEvent({
1755
+ send(socket, {
1720
1756
  code: operationErrorCode(failure),
1721
1757
  kind: AGENT_CATALOG_REFRESH_FAILED_KIND,
1722
1758
  message: operationErrorMessage(failure),
1723
1759
  requestId: command.requestId,
1724
- }));
1760
+ });
1725
1761
  }
1726
1762
  }
1727
1763
  finally {
@@ -1733,7 +1769,7 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1733
1769
  return;
1734
1770
  }
1735
1771
  if (kind === NATIVE_SESSION_REQUEST_KIND) {
1736
- const command = decodeNativeSessionCommand(encoded);
1772
+ const command = message;
1737
1773
  const previous = [...nativeRequests.values()].filter((request) => request.agentId === command.agentId);
1738
1774
  if (nativeRequests.has(command.requestId) ||
1739
1775
  nativeRequests.size >= 4 ||
@@ -1765,7 +1801,7 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1765
1801
  operationSignal.throwIfAborted();
1766
1802
  const result = await nativeSessions.execute(command, operationSignal);
1767
1803
  if (socket.readyState === WebSocket.OPEN) {
1768
- send(socket, encodeNativeSessionResult(result));
1804
+ send(socket, result);
1769
1805
  }
1770
1806
  }
1771
1807
  catch (error) {
@@ -1795,7 +1831,7 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1795
1831
  return;
1796
1832
  }
1797
1833
  if (kind === NATIVE_SESSION_TURN_FORK_KIND) {
1798
- const command = decodeNativeSessionTurnForkCommand(encoded);
1834
+ const command = message;
1799
1835
  const previous = [...nativeRequests.values()].filter((request) => request.agentId === command.agentId);
1800
1836
  if (nativeRequests.has(command.requestId) ||
1801
1837
  nativeRequests.size >= 4 ||
@@ -1825,7 +1861,7 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1825
1861
  operationSignal.throwIfAborted();
1826
1862
  const result = await nativeSessions.executeTurnFork(command, operationSignal);
1827
1863
  if (socket.readyState === WebSocket.OPEN) {
1828
- send(socket, encodeNativeSessionResult(result));
1864
+ send(socket, result);
1829
1865
  }
1830
1866
  }
1831
1867
  catch (error) {
@@ -1855,32 +1891,31 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1855
1891
  return;
1856
1892
  }
1857
1893
  if (kind === RUNTIME_LIVENESS_READY_KIND) {
1858
- decodeRuntimeLivenessReadyEvent(encoded);
1859
1894
  connectionLiveness.start();
1860
1895
  return;
1861
1896
  }
1862
1897
  if (kind === RUNTIME_HEARTBEAT_ACK_KIND) {
1863
- connectionLiveness.acknowledge(decodeRuntimeHeartbeatAckEvent(encoded));
1898
+ connectionLiveness.acknowledge(message);
1864
1899
  return;
1865
1900
  }
1866
1901
  if (kind === FILE_READ_KIND) {
1867
- const command = decodeFileReadCommand(encoded);
1902
+ const command = message;
1868
1903
  void streamLocalFile(command, (message) => send(socket, message), connectionController.signal).catch((error) => {
1869
1904
  if (socket.readyState !== WebSocket.OPEN || connectionController.signal.aborted) {
1870
1905
  return;
1871
1906
  }
1872
- send(socket, encodeFileFailedEvent({
1907
+ send(socket, {
1873
1908
  code: "file_unavailable",
1874
1909
  kind: FILE_FAILED_KIND,
1875
1910
  message: error instanceof Error ? error.message : "The local file is unavailable",
1876
1911
  requestId: command.requestId,
1877
1912
  sessionId: command.sessionId,
1878
- }));
1913
+ });
1879
1914
  });
1880
1915
  return;
1881
1916
  }
1882
1917
  if (kind === SESSION_CANCEL_KIND) {
1883
- const cancellation = decodeSessionCancelCommand(encoded);
1918
+ const cancellation = message;
1884
1919
  const turn = activeTurns.get(cancellation.commandId);
1885
1920
  if (turn === undefined || !turn.matches(cancellation)) {
1886
1921
  console.warn("Mobius daemon ignored cancellation for an inactive turn");
@@ -1900,22 +1935,22 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1900
1935
  return;
1901
1936
  }
1902
1937
  if (kind === WORKSPACE_LIST_KIND) {
1903
- const command = decodeWorkspaceListCommand(encoded);
1938
+ const command = message;
1904
1939
  void executeWorkspaceList(socket, command, directories, audit, connectionController.signal);
1905
1940
  return;
1906
1941
  }
1907
1942
  if (kind === SESSION_PREPARE_KIND) {
1908
- const command = decodeSessionPrepareCommand(encoded);
1943
+ const command = message;
1909
1944
  void executeSessionPrepare(publisher, socket, command, config, directories, audit, sessions, connectionController.signal);
1910
1945
  return;
1911
1946
  }
1912
1947
  if (kind === SESSION_CONFIGURE_KIND) {
1913
- const command = decodeSessionConfigureCommand(encoded);
1948
+ const command = message;
1914
1949
  void executeSessionConfigure(publisher, socket, command, config, directories, audit, sessions, connectionController.signal);
1915
1950
  return;
1916
1951
  }
1917
1952
  if (kind === SESSION_PERMISSION_RESPOND_KIND) {
1918
- const command = decodeSessionPermissionRespondCommand(encoded);
1953
+ const command = message;
1919
1954
  void sessions
1920
1955
  .respondPermission(command)
1921
1956
  .then(() => {
@@ -1931,7 +1966,7 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1931
1966
  return;
1932
1967
  }
1933
1968
  if (kind === SESSION_ELICITATION_RESPOND_KIND) {
1934
- const command = decodeSessionElicitationRespondCommand(encoded);
1969
+ const command = message;
1935
1970
  void sessions
1936
1971
  .respondElicitation(command)
1937
1972
  .then(() => {
@@ -1947,14 +1982,14 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1947
1982
  return;
1948
1983
  }
1949
1984
  if (kind === AGENT_INSTALL_REQUEST_KIND) {
1950
- const command = decodeAgentInstallRequestCommand(encoded);
1985
+ const command = message;
1951
1986
  void installations.request(command, signal).catch((error) => {
1952
1987
  console.error("Mobius Agent integration installation failed", error);
1953
1988
  });
1954
1989
  return;
1955
1990
  }
1956
1991
  if (kind === AGENT_INSTALL_CANCEL_KIND) {
1957
- const command = decodeAgentInstallCancelCommand(encoded);
1992
+ const command = message;
1958
1993
  void installations.cancel(command.requestId).catch((error) => {
1959
1994
  reportOperationFailure(socket, command.requestId, "", error);
1960
1995
  });
@@ -1963,7 +1998,7 @@ async function runRelayConnection(config, directories, audit, sessions, installa
1963
1998
  if (kind !== SESSION_PROMPT_KIND) {
1964
1999
  throw new Error("Unsupported protocol message");
1965
2000
  }
1966
- const command = decodeSessionPromptCommand(encoded);
2001
+ const command = message;
1967
2002
  if (activeTurns.has(command.commandId)) {
1968
2003
  return;
1969
2004
  }
@@ -2012,6 +2047,19 @@ async function runRelayConnection(config, directories, audit, sessions, installa
2012
2047
  return;
2013
2048
  }
2014
2049
  console.error("Mobius daemon could not reconcile active Agent turns", error);
2050
+ if (error instanceof ActiveTurnReconciliationError && error.terminal) {
2051
+ // The Relay has already settled these Attempts, so this Runtime can never reconcile them.
2052
+ // Abandoning the stale turns lets the connection recover instead of looping on code 4009.
2053
+ diagnostics.reconciliationAbandoned(connectionEpoch, error.relayErrorCode, reconnectingTurns.length);
2054
+ console.error("Mobius daemon abandoned Agent turns the Relay already settled", error.relayErrorCode);
2055
+ for (const turn of reconnectingTurns) {
2056
+ activeTurns.delete(turn.command.commandId);
2057
+ turn.abortDaemon();
2058
+ }
2059
+ publisher.connect(socket);
2060
+ resumeRuntimeDeliveries();
2061
+ return;
2062
+ }
2015
2063
  failAndClose(new Error("Active Agent turn reconciliation failed", { cause: error }), ACTIVE_TURN_RECONCILIATION_CLOSE_CODE, "Active Agent turn reconciliation failed", "reconciliation");
2016
2064
  });
2017
2065
  if (signal.aborted) {
@@ -2045,13 +2093,13 @@ export async function runDaemon(config, audit, signal, timer = systemDaemonTimer
2045
2093
  const publisher = new DaemonSessionEventPublisher(outbox, timer);
2046
2094
  const activeTurns = new Map();
2047
2095
  const activeAttemptIds = new Map();
2048
- const recordSessionEvent = (sessionId, payload) => {
2096
+ const recordSessionEvent = (sessionId, event) => {
2049
2097
  const attemptId = activeAttemptIds.get(sessionId);
2050
2098
  if (attemptId === undefined) {
2051
- publisher.recordRuntime(sessionId, payload);
2099
+ publisher.recordRuntime(sessionId, event);
2052
2100
  return;
2053
2101
  }
2054
- publisher.recordAttempt(sessionId, payload, attemptId);
2102
+ publisher.recordAttempt(sessionId, event, attemptId);
2055
2103
  };
2056
2104
  const sessions = new AcpSessionManager(new DaemonAcpObserver(config, recordSessionEvent), sessionStore);
2057
2105
  const directories = new WorkspaceDirectoryService(config.bindingId, config.defaultWorkspace);