@moxt-ai/mobius 0.0.103 → 0.0.106

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 (54) hide show
  1. package/dist/acp/process-session.d.ts.map +1 -1
  2. package/dist/acp/process-session.js +11 -6
  3. package/dist/acp/process-session.js.map +1 -1
  4. package/dist/acp/session-manager.d.ts +2 -0
  5. package/dist/acp/session-manager.d.ts.map +1 -1
  6. package/dist/acp/session-manager.js +5 -0
  7. package/dist/acp/session-manager.js.map +1 -1
  8. package/dist/acp/session-store.d.ts +5 -1
  9. package/dist/acp/session-store.d.ts.map +1 -1
  10. package/dist/acp/session-store.js +6 -1
  11. package/dist/acp/session-store.js.map +1 -1
  12. package/dist/cli.js +362 -1249
  13. package/dist/cli.js.map +4 -4
  14. package/dist/daemon-manager.d.ts.map +1 -1
  15. package/dist/daemon-manager.js +2 -9
  16. package/dist/daemon-manager.js.map +1 -1
  17. package/dist/daemon-session-commands.d.ts +8 -5
  18. package/dist/daemon-session-commands.d.ts.map +1 -1
  19. package/dist/daemon-session-commands.js +50 -31
  20. package/dist/daemon-session-commands.js.map +1 -1
  21. package/dist/daemon-turn-reconciliation.d.ts +7 -3
  22. package/dist/daemon-turn-reconciliation.d.ts.map +1 -1
  23. package/dist/daemon-turn-reconciliation.js +9 -3
  24. package/dist/daemon-turn-reconciliation.js.map +1 -1
  25. package/dist/index.js +359 -1239
  26. package/dist/index.js.map +4 -4
  27. package/dist/native-sessions/service.d.ts +2 -1
  28. package/dist/native-sessions/service.d.ts.map +1 -1
  29. package/dist/native-sessions/service.js +27 -0
  30. package/dist/native-sessions/service.js.map +1 -1
  31. package/dist/relay-connection/coalescing-narration-publisher.d.ts +3 -3
  32. package/dist/relay-connection/coalescing-narration-publisher.js +3 -3
  33. package/dist/relay-connection/coalescing-text-publisher.d.ts +3 -4
  34. package/dist/relay-connection/coalescing-text-publisher.d.ts.map +1 -1
  35. package/dist/relay-connection/coalescing-text-publisher.js +3 -4
  36. package/dist/relay-connection/coalescing-text-publisher.js.map +1 -1
  37. package/dist/relay-connection/daemon-operation-state.d.ts +18 -0
  38. package/dist/relay-connection/daemon-operation-state.d.ts.map +1 -0
  39. package/dist/relay-connection/daemon-operation-state.js +69 -0
  40. package/dist/relay-connection/daemon-operation-state.js.map +1 -0
  41. package/dist/relay-connection/session-event-publisher.d.ts +3 -9
  42. package/dist/relay-connection/session-event-publisher.d.ts.map +1 -1
  43. package/dist/relay-connection/session-event-publisher.js +30 -224
  44. package/dist/relay-connection/session-event-publisher.js.map +1 -1
  45. package/dist/run-daemon.d.ts.map +1 -1
  46. package/dist/run-daemon.js +49 -244
  47. package/dist/run-daemon.js.map +1 -1
  48. package/dist/runtime.js +363 -1243
  49. package/dist/runtime.js.map +4 -4
  50. package/package.json +1 -1
  51. package/dist/relay-connection/session-event-outbox.d.ts +0 -61
  52. package/dist/relay-connection/session-event-outbox.d.ts.map +0 -1
  53. package/dist/relay-connection/session-event-outbox.js +0 -546
  54. package/dist/relay-connection/session-event-outbox.js.map +0 -1
package/dist/runtime.js CHANGED
@@ -24431,6 +24431,8 @@ var WORKSPACE_LIST_KIND = "workspace.list";
24431
24431
  var WORKSPACE_ENTRIES_KIND = "workspace.entries";
24432
24432
  var SESSION_PREPARE_KIND = "session.prepare";
24433
24433
  var SESSION_READY_KIND = "session.ready";
24434
+ var SESSION_QUERY_KIND = "session.query";
24435
+ var SESSION_QUERIED_KIND = "session.queried";
24434
24436
  var SESSION_CONFIGURE_KIND = "session.configure";
24435
24437
  var SESSION_CONFIG_UPDATED_KIND = "session.config.updated";
24436
24438
  var SESSION_USAGE_UPDATED_KIND = "session.usage.updated";
@@ -24472,6 +24474,26 @@ var workspaceEntrySchema = external_exports.strictObject({
24472
24474
  directoryId: DIRECTORY_IDENTIFIER,
24473
24475
  name: external_exports.string().min(1).max(255)
24474
24476
  }).readonly();
24477
+ var sessionMetadataSchema = external_exports.strictObject({
24478
+ additionalDirectories: external_exports.array(workspaceEntrySchema).max(16).readonly(),
24479
+ agentId: IDENTIFIER,
24480
+ directoryId: DIRECTORY_IDENTIFIER,
24481
+ directoryLabel: external_exports.string().min(1).max(2048),
24482
+ prompted: external_exports.boolean(),
24483
+ sessionId: IDENTIFIER,
24484
+ title: external_exports.string().max(500),
24485
+ updatedAt: external_exports.iso.datetime({ offset: true })
24486
+ }).readonly();
24487
+ var sessionQueryCommandSchema = external_exports.strictObject({
24488
+ kind: external_exports.literal(SESSION_QUERY_KIND),
24489
+ requestId: IDENTIFIER,
24490
+ sessionIds: external_exports.array(IDENTIFIER).min(1).max(500).readonly()
24491
+ }).readonly();
24492
+ var sessionsQueriedEventSchema = external_exports.strictObject({
24493
+ entries: external_exports.array(sessionMetadataSchema).max(500).readonly(),
24494
+ kind: external_exports.literal(SESSION_QUERIED_KIND),
24495
+ requestId: IDENTIFIER
24496
+ }).readonly();
24475
24497
  var fileReadCommandSchema = external_exports.strictObject({
24476
24498
  kind: external_exports.literal(FILE_READ_KIND),
24477
24499
  maxBytes: external_exports.number().int().positive().max(128 * 1024 * 1024),
@@ -25015,6 +25037,10 @@ var decodeWorkspaceListCommand = (encoded) => decode3(encoded, workspaceListComm
25015
25037
  var encodeWorkspaceListCommand = (message) => encode3(message, workspaceListCommandSchema);
25016
25038
  var decodeWorkspaceEntriesEvent = (encoded) => decode3(encoded, workspaceEntriesEventSchema);
25017
25039
  var encodeWorkspaceEntriesEvent = (message) => encode3(message, workspaceEntriesEventSchema);
25040
+ var decodeSessionQueryCommand = (encoded) => decode3(encoded, sessionQueryCommandSchema);
25041
+ var encodeSessionQueryCommand = (message) => encode3(message, sessionQueryCommandSchema);
25042
+ var decodeSessionsQueriedEvent = (encoded) => decode3(encoded, sessionsQueriedEventSchema);
25043
+ var encodeSessionsQueriedEvent = (message) => encode3(message, sessionsQueriedEventSchema);
25018
25044
  var decodeSessionPrepareCommand = (encoded) => decode3(encoded, sessionPrepareCommandSchema);
25019
25045
  var encodeSessionPrepareCommand = (message) => encode3(message, sessionPrepareCommandSchema);
25020
25046
  var decodeSessionReadyEvent = (encoded) => decode3(encoded, sessionReadyEventSchema);
@@ -25058,9 +25084,6 @@ var SESSION_CANCEL_KIND = "session.cancel";
25058
25084
  var RUNTIME_LIVENESS_READY_KIND = "runtime.liveness.ready";
25059
25085
  var RUNTIME_HEARTBEAT_KIND = "runtime.heartbeat";
25060
25086
  var RUNTIME_HEARTBEAT_ACK_KIND = "runtime.heartbeat.ack";
25061
- var RUNTIME_DELIVERY_KIND = "runtime.delivery";
25062
- var RUNTIME_DELIVERY_RECEIVED_KIND = "runtime.delivery.received";
25063
- var RUNTIME_DELIVERY_COMMITTED_KIND = "runtime.delivery.committed";
25064
25087
  var SESSION_STARTED_KIND = "session.started";
25065
25088
  var AGENT_MESSAGE_DELTA_KIND = "agent.message.delta";
25066
25089
  var AGENT_ACTIVITY_KIND = "agent.activity";
@@ -25084,7 +25107,6 @@ var DIRECTORY_IDENTIFIER_PATTERN2 = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/;
25084
25107
  var MAX_PROMPT_LENGTH = 1e4;
25085
25108
  var MAX_PROMPT_ATTACHMENT_LENGTH = 6e6;
25086
25109
  var MAX_EVENT_TEXT_LENGTH = 1e5;
25087
- var MAX_RUNTIME_DELIVERY_PAYLOAD_LENGTH = 8 * 1024 * 1024;
25088
25110
  var ACTIVITY_TYPES = /* @__PURE__ */ new Set(["plan", "progress", "reasoning", "tool"]);
25089
25111
  var NARRATION_ACTIVITY_TYPES = /* @__PURE__ */ new Set(["progress", "reasoning"]);
25090
25112
  var ACTIVITY_STATUSES = /* @__PURE__ */ new Set(["pending", "running", "completed", "failed"]);
@@ -25371,45 +25393,21 @@ function decodeRuntimeHeartbeatAckEvent(encoded) {
25371
25393
  kind: RUNTIME_HEARTBEAT_ACK_KIND
25372
25394
  };
25373
25395
  }
25374
- function decodeRuntimeDelivery(encoded) {
25375
- const value = parseJson2(encoded);
25376
- assertExactKeys(value, ["deliveryId", "kind", "payload", "sessionId"]);
25377
- assertKind(value, RUNTIME_DELIVERY_KIND);
25378
- return {
25379
- deliveryId: readIdentifier(value, "deliveryId"),
25380
- kind: RUNTIME_DELIVERY_KIND,
25381
- payload: readString(value, "payload", MAX_RUNTIME_DELIVERY_PAYLOAD_LENGTH),
25382
- sessionId: readIdentifier(value, "sessionId")
25383
- };
25384
- }
25385
- function decodeRuntimeDeliveryReceived(encoded) {
25386
- const value = parseJson2(encoded);
25387
- assertExactKeys(value, ["deliveryId", "kind", "sessionId"]);
25388
- assertKind(value, RUNTIME_DELIVERY_RECEIVED_KIND);
25389
- return {
25390
- deliveryId: readIdentifier(value, "deliveryId"),
25391
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
25392
- sessionId: readIdentifier(value, "sessionId")
25393
- };
25394
- }
25395
- function decodeRuntimeDeliveryCommitted(encoded) {
25396
- const value = parseJson2(encoded);
25397
- assertExactKeys(value, ["deliveryId", "kind", "sessionId"]);
25398
- assertKind(value, RUNTIME_DELIVERY_COMMITTED_KIND);
25399
- return {
25400
- deliveryId: readIdentifier(value, "deliveryId"),
25401
- kind: RUNTIME_DELIVERY_COMMITTED_KIND,
25402
- sessionId: readIdentifier(value, "sessionId")
25403
- };
25404
- }
25405
25396
  function decodeSessionStartedEvent(encoded) {
25406
25397
  const value = parseJson2(encoded);
25407
- assertExactKeys(value, ["commandId", "kind", "attemptId", "sessionId"]);
25398
+ assertExactKeys(value, ["commandId", "epoch", "kind", "attemptId", "prompt", "sequence", "sessionId"]);
25408
25399
  assertKind(value, SESSION_STARTED_KIND);
25400
+ const sequence = readSequence(value, "sequence");
25401
+ if (sequence !== 0) {
25402
+ throw new ProtocolMessageError("Invalid live start sequence");
25403
+ }
25409
25404
  return {
25410
25405
  commandId: readIdentifier(value, "commandId"),
25406
+ epoch: readIdentifier(value, "epoch"),
25411
25407
  kind: SESSION_STARTED_KIND,
25412
25408
  attemptId: readIdentifier(value, "attemptId"),
25409
+ prompt: readText(value, "prompt", MAX_PROMPT_LENGTH),
25410
+ sequence,
25413
25411
  sessionId: readIdentifier(value, "sessionId")
25414
25412
  };
25415
25413
  }
@@ -25507,15 +25505,6 @@ function encodeRuntimeHeartbeatEvent(message) {
25507
25505
  function encodeRuntimeHeartbeatAckEvent(message) {
25508
25506
  return JSON.stringify(decodeRuntimeHeartbeatAckEvent(JSON.stringify(message)));
25509
25507
  }
25510
- function encodeRuntimeDelivery(message) {
25511
- return JSON.stringify(decodeRuntimeDelivery(JSON.stringify(message)));
25512
- }
25513
- function encodeRuntimeDeliveryReceived(message) {
25514
- return JSON.stringify(decodeRuntimeDeliveryReceived(JSON.stringify(message)));
25515
- }
25516
- function encodeRuntimeDeliveryCommitted(message) {
25517
- return JSON.stringify(decodeRuntimeDeliveryCommitted(JSON.stringify(message)));
25518
- }
25519
25508
  function decodeAgentActivityNarrationEvent(encoded) {
25520
25509
  const value = parseJson2(encoded);
25521
25510
  assertExactKeys(value, ["activityId", "activityType", "commandId", "kind", "sequence", "sessionId", "text"]);
@@ -25629,6 +25618,7 @@ var NATIVE_SESSION_RESULT_KIND = "native.session.result";
25629
25618
  var NATIVE_SESSION_CANCEL_KIND = "native.session.cancel";
25630
25619
  var NATIVE_SESSION_TURN_FORK_REQUEST_KIND = "native.session.turn-fork.request";
25631
25620
  var NATIVE_SESSION_TURN_FORK_KIND = "native.session.turn-fork";
25621
+ var ACTIVE_TURN_TEXT_LIMIT = 1e6;
25632
25622
  var identifier = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
25633
25623
  var directoryId = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/);
25634
25624
  var envelope = {
@@ -25721,6 +25711,7 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
25721
25711
  ]);
25722
25712
  var nativeSessionEntrySchema = external_exports.strictObject({
25723
25713
  entryId: identifier,
25714
+ mobiusSessionIds: external_exports.array(identifier).max(500).readonly(),
25724
25715
  nativeSessionId: identifier,
25725
25716
  title: external_exports.string().max(500),
25726
25717
  directoryId,
@@ -25747,7 +25738,7 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
25747
25738
  turn: external_exports.strictObject({
25748
25739
  commandId: identifier,
25749
25740
  prompt: external_exports.string().max(1e5),
25750
- text: external_exports.string().max(1e5),
25741
+ text: external_exports.string().max(ACTIVE_TURN_TEXT_LIMIT),
25751
25742
  truncated: external_exports.boolean(),
25752
25743
  epoch: identifier,
25753
25744
  sequence: external_exports.number().int().nonnegative(),
@@ -25822,65 +25813,17 @@ var encodeNativeSessionTurnForkCommand = (value) => JSON.stringify(nativeSession
25822
25813
 
25823
25814
  // ../protocol/src/session-events.ts
25824
25815
  var SESSION_EVENT_KIND = "session.event";
25825
- var SESSION_EVENT_ACK_KIND = "session.event.ack";
25826
25816
  var SESSION_EVENT_COMMITTED_KIND = "session.event.committed";
25827
- var SESSION_EVENT_DEFERRED_KIND = "session.event.deferred";
25828
- var SESSION_EVENT_REJECTED_KIND = "session.event.rejected";
25829
- var SessionEventRejectionCode = {
25830
- SessionDeleted: "session_deleted",
25831
- SessionNotFound: "session_not_found",
25832
- SessionRejected: "session_rejected"
25833
- };
25834
25817
  var IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
25835
- var CURSOR_PATTERN = /^[A-Za-z0-9_-]{1,512}$/;
25836
25818
  var MAX_RECORDED_EVENT_LENGTH = 8 * 1024 * 1024;
25837
- var DECIMAL_SEQUENCE_PATTERN = /^(?:0|[1-9][0-9]*)$/;
25838
- var eventSourceSchema = external_exports.discriminatedUnion("kind", [
25839
- external_exports.strictObject({
25840
- attemptId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25841
- kind: external_exports.literal("attempt"),
25842
- sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
25843
- }).readonly(),
25844
- external_exports.strictObject({
25845
- kind: external_exports.literal("runtime"),
25846
- sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
25847
- }).readonly()
25848
- ]);
25849
25819
  var eventEnvelopeSchema = external_exports.strictObject({
25850
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25851
25820
  kind: external_exports.literal(SESSION_EVENT_KIND),
25852
25821
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
25853
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25854
- source: eventSourceSchema
25822
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
25855
25823
  }).readonly();
25856
25824
  var committedEventSchema = external_exports.strictObject({
25857
- cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
25858
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25859
25825
  kind: external_exports.literal(SESSION_EVENT_COMMITTED_KIND),
25860
25826
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
25861
- recordedAt: external_exports.string().datetime({ offset: true }),
25862
- sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
25863
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25864
- source: eventSourceSchema
25865
- }).readonly();
25866
- var eventAcknowledgementSchema = external_exports.strictObject({
25867
- cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
25868
- duplicate: external_exports.boolean(),
25869
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25870
- kind: external_exports.literal(SESSION_EVENT_ACK_KIND),
25871
- sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
25872
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
25873
- }).readonly();
25874
- var eventDeferredSchema = external_exports.strictObject({
25875
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25876
- kind: external_exports.literal(SESSION_EVENT_DEFERRED_KIND),
25877
- retryAfterMilliseconds: external_exports.number().int().min(100).max(6e4),
25878
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
25879
- }).readonly();
25880
- var eventRejectionSchema = external_exports.strictObject({
25881
- code: external_exports.enum(SessionEventRejectionCode),
25882
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25883
- kind: external_exports.literal(SESSION_EVENT_REJECTED_KIND),
25884
25827
  sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
25885
25828
  }).readonly();
25886
25829
  function decode5(encoded, schema) {
@@ -25909,12 +25852,6 @@ var encode4 = (message, schema) => {
25909
25852
  };
25910
25853
  var decodeSessionEventEnvelope = (encoded) => decode5(encoded, eventEnvelopeSchema);
25911
25854
  var encodeSessionEventEnvelope = (message) => encode4(message, eventEnvelopeSchema);
25912
- var decodeSessionEventAcknowledgement = (encoded) => decode5(encoded, eventAcknowledgementSchema);
25913
- var encodeSessionEventAcknowledgement = (message) => encode4(message, eventAcknowledgementSchema);
25914
- var decodeSessionEventDeferred = (encoded) => decode5(encoded, eventDeferredSchema);
25915
- var encodeSessionEventDeferred = (message) => encode4(message, eventDeferredSchema);
25916
- var decodeSessionEventRejection = (encoded) => decode5(encoded, eventRejectionSchema);
25917
- var encodeSessionEventRejection = (message) => encode4(message, eventRejectionSchema);
25918
25855
  function decodeRecordedSessionEvent(encoded) {
25919
25856
  const kind = decodeMessageKind(encoded);
25920
25857
  switch (kind) {
@@ -26044,6 +25981,11 @@ var serviceToDaemonSignatures = {
26044
25981
  decodeAgentSettingsDiscoverCommand
26045
25982
  ),
26046
25983
  [FILE_READ_KIND]: defineMessageSignature(FILE_READ_KIND, encodeFileReadCommand, decodeFileReadCommand),
25984
+ [SESSION_QUERY_KIND]: defineMessageSignature(
25985
+ SESSION_QUERY_KIND,
25986
+ encodeSessionQueryCommand,
25987
+ decodeSessionQueryCommand
25988
+ ),
26047
25989
  [NATIVE_SESSION_CANCEL_KIND]: defineMessageSignature(
26048
25990
  NATIVE_SESSION_CANCEL_KIND,
26049
25991
  encodeNativeSessionCancel,
@@ -26059,16 +26001,6 @@ var serviceToDaemonSignatures = {
26059
26001
  encodeNativeSessionTurnForkCommand,
26060
26002
  decodeNativeSessionTurnForkCommand
26061
26003
  ),
26062
- [RUNTIME_DELIVERY_KIND]: defineMessageSignature(
26063
- RUNTIME_DELIVERY_KIND,
26064
- encodeRuntimeDelivery,
26065
- decodeRuntimeDelivery
26066
- ),
26067
- [RUNTIME_DELIVERY_COMMITTED_KIND]: defineMessageSignature(
26068
- RUNTIME_DELIVERY_COMMITTED_KIND,
26069
- encodeRuntimeDeliveryCommitted,
26070
- decodeRuntimeDeliveryCommitted
26071
- ),
26072
26004
  [RUNTIME_HEARTBEAT_ACK_KIND]: defineMessageSignature(
26073
26005
  RUNTIME_HEARTBEAT_ACK_KIND,
26074
26006
  encodeRuntimeHeartbeatAckEvent,
@@ -26094,21 +26026,6 @@ var serviceToDaemonSignatures = {
26094
26026
  encodeSessionElicitationRespondCommand,
26095
26027
  decodeSessionElicitationRespondCommand
26096
26028
  ),
26097
- [SESSION_EVENT_ACK_KIND]: defineMessageSignature(
26098
- SESSION_EVENT_ACK_KIND,
26099
- encodeSessionEventAcknowledgement,
26100
- decodeSessionEventAcknowledgement
26101
- ),
26102
- [SESSION_EVENT_DEFERRED_KIND]: defineMessageSignature(
26103
- SESSION_EVENT_DEFERRED_KIND,
26104
- encodeSessionEventDeferred,
26105
- decodeSessionEventDeferred
26106
- ),
26107
- [SESSION_EVENT_REJECTED_KIND]: defineMessageSignature(
26108
- SESSION_EVENT_REJECTED_KIND,
26109
- encodeSessionEventRejection,
26110
- decodeSessionEventRejection
26111
- ),
26112
26029
  [SESSION_LIVE_HISTORY_LOAD_KIND]: defineMessageSignature(
26113
26030
  SESSION_LIVE_HISTORY_LOAD_KIND,
26114
26031
  encodeSessionLiveHistoryLoad,
@@ -26199,16 +26116,16 @@ var daemonToServiceSignatures = {
26199
26116
  [FILE_CHUNK_KIND]: defineMessageSignature(FILE_CHUNK_KIND, encodeFileChunkEvent, decodeFileChunkEvent),
26200
26117
  [FILE_END_KIND]: defineMessageSignature(FILE_END_KIND, encodeFileEndEvent, decodeFileEndEvent),
26201
26118
  [FILE_FAILED_KIND]: defineMessageSignature(FILE_FAILED_KIND, encodeFileFailedEvent, decodeFileFailedEvent),
26119
+ [SESSION_QUERIED_KIND]: defineMessageSignature(
26120
+ SESSION_QUERIED_KIND,
26121
+ encodeSessionsQueriedEvent,
26122
+ decodeSessionsQueriedEvent
26123
+ ),
26202
26124
  [NATIVE_SESSION_RESULT_KIND]: defineMessageSignature(
26203
26125
  NATIVE_SESSION_RESULT_KIND,
26204
26126
  encodeNativeSessionResult,
26205
26127
  decodeNativeSessionResult
26206
26128
  ),
26207
- [RUNTIME_DELIVERY_RECEIVED_KIND]: defineMessageSignature(
26208
- RUNTIME_DELIVERY_RECEIVED_KIND,
26209
- encodeRuntimeDeliveryReceived,
26210
- decodeRuntimeDeliveryReceived
26211
- ),
26212
26129
  [RUNTIME_HEARTBEAT_KIND]: defineMessageSignature(
26213
26130
  RUNTIME_HEARTBEAT_KIND,
26214
26131
  encodeRuntimeHeartbeatEvent,
@@ -26317,7 +26234,7 @@ function createDaemonConfig(connection, agents = [], installableAgents = [], loc
26317
26234
  }
26318
26235
 
26319
26236
  // src/run-daemon.ts
26320
- import { randomUUID as randomUUID5 } from "node:crypto";
26237
+ import { randomUUID as randomUUID6 } from "node:crypto";
26321
26238
  import { styleText } from "node:util";
26322
26239
  import { WebSocket as WebSocket5 } from "undici";
26323
26240
 
@@ -26481,13 +26398,17 @@ var AcpStoredSession = class {
26481
26398
  nativeSessionId;
26482
26399
  prompted;
26483
26400
  sessionId;
26484
- constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted) {
26401
+ title;
26402
+ updatedAt;
26403
+ constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted, title2, updatedAt = (/* @__PURE__ */ new Date()).toISOString()) {
26485
26404
  this.additionalDirectories = [...additionalDirectories];
26486
26405
  this.agentId = agentId;
26487
26406
  this.cwd = cwd;
26488
26407
  this.nativeSessionId = nativeSessionId;
26489
26408
  this.prompted = prompted;
26490
26409
  this.sessionId = sessionId;
26410
+ this.title = title2;
26411
+ this.updatedAt = updatedAt;
26491
26412
  }
26492
26413
  };
26493
26414
  var AcpStoredSessionLookup = class {
@@ -26512,6 +26433,7 @@ var MemoryAcpSessionStore = class {
26512
26433
  findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
26513
26434
  (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
26514
26435
  );
26436
+ list = () => [...this.#sessions.values()].toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt));
26515
26437
  markDeleted = (agentId, nativeSessionId) => {
26516
26438
  const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
26517
26439
  for (const id of ids) {
@@ -28641,7 +28563,8 @@ var AcpProcessSession = class _AcpProcessSession {
28641
28563
  nativeSessionIdSchema.parse(origin.nativeSessionId),
28642
28564
  this.#cwd,
28643
28565
  this.#additionalDirectories,
28644
- true
28566
+ true,
28567
+ ""
28645
28568
  )
28646
28569
  ) : this.#store.read(this.#mobiusSessionId)
28647
28570
  );
@@ -28717,6 +28640,7 @@ var AcpProcessSession = class _AcpProcessSession {
28717
28640
  } else if (stored instanceof FoundAcpStoredSession && stored.session.agentId === this.#agentId && stored.session.cwd === this.#cwd && arraysEqual(stored.session.additionalDirectories, this.#additionalDirectories)) {
28718
28641
  this.selectNativeSession(stored.session.nativeSessionId);
28719
28642
  this.#prompted = stored.session.prompted;
28643
+ this.#sessionTitle = stored.session.title;
28720
28644
  this.#restored = true;
28721
28645
  if (this.#capabilities.resumeSession) {
28722
28646
  lifecycleResponse = await this.#metrics.measure(
@@ -28800,18 +28724,17 @@ var AcpProcessSession = class _AcpProcessSession {
28800
28724
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
28801
28725
  await this.#updateTail;
28802
28726
  signal.throwIfAborted();
28803
- if (this.#prompted) {
28804
- this.#store.write(
28805
- new AcpStoredSession(
28806
- this.#mobiusSessionId,
28807
- this.#agentId,
28808
- this.#nativeSessionId,
28809
- this.#cwd,
28810
- this.#additionalDirectories,
28811
- true
28812
- )
28813
- );
28814
- }
28727
+ this.#store.write(
28728
+ new AcpStoredSession(
28729
+ this.#mobiusSessionId,
28730
+ this.#agentId,
28731
+ this.#nativeSessionId,
28732
+ this.#cwd,
28733
+ this.#additionalDirectories,
28734
+ this.#prompted,
28735
+ this.#sessionTitle ?? ""
28736
+ )
28737
+ );
28815
28738
  };
28816
28739
  listNativeSessions = async (cursor, signal) => {
28817
28740
  if (!this.#capabilities.listSessions) {
@@ -28863,7 +28786,15 @@ var AcpProcessSession = class _AcpProcessSession {
28863
28786
  }
28864
28787
  const previousSessionId = this.#mobiusSessionId;
28865
28788
  this.#store.write(
28866
- new AcpStoredSession(sessionId, this.#agentId, sessionId, this.#cwd, this.#additionalDirectories, false)
28789
+ new AcpStoredSession(
28790
+ sessionId,
28791
+ this.#agentId,
28792
+ sessionId,
28793
+ this.#cwd,
28794
+ this.#additionalDirectories,
28795
+ false,
28796
+ ""
28797
+ )
28867
28798
  );
28868
28799
  this.#store.remove(previousSessionId);
28869
28800
  this.#mobiusSessionId = sessionId;
@@ -28985,6 +28916,9 @@ var AcpProcessSession = class _AcpProcessSession {
28985
28916
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
28986
28917
  }
28987
28918
  const prompt = this.buildPrompt(options);
28919
+ if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
28920
+ this.#sessionTitle = truncate3(options.prompt, 500);
28921
+ }
28988
28922
  this.#store.write(
28989
28923
  new AcpStoredSession(
28990
28924
  this.#mobiusSessionId,
@@ -28992,7 +28926,8 @@ var AcpProcessSession = class _AcpProcessSession {
28992
28926
  this.#nativeSessionId,
28993
28927
  this.#cwd,
28994
28928
  this.#additionalDirectories,
28995
- true
28929
+ true,
28930
+ this.#sessionTitle
28996
28931
  )
28997
28932
  );
28998
28933
  this.#prompted = true;
@@ -29420,6 +29355,19 @@ var AcpProcessSession = class _AcpProcessSession {
29420
29355
  if (Object.hasOwn(update, "updatedAt")) {
29421
29356
  this.#sessionUpdatedAt = truncate3(update.updatedAt ?? "", 128);
29422
29357
  }
29358
+ if (this.#nativeSessionId.length > 0) {
29359
+ this.#store.write(
29360
+ new AcpStoredSession(
29361
+ this.#mobiusSessionId,
29362
+ this.#agentId,
29363
+ this.#nativeSessionId,
29364
+ this.#cwd,
29365
+ this.#additionalDirectories,
29366
+ this.#prompted,
29367
+ this.#sessionTitle ?? ""
29368
+ )
29369
+ );
29370
+ }
29423
29371
  await this.#getObserver().onInfo({
29424
29372
  kind: SESSION_INFO_UPDATED_KIND,
29425
29373
  sessionId: this.#mobiusSessionId,
@@ -30322,6 +30270,11 @@ var AcpSessionManager = class {
30322
30270
  )
30323
30271
  ]);
30324
30272
  };
30273
+ findSessions = (sessionIds) => sessionIds.flatMap((sessionId) => {
30274
+ const stored = this.#store.read(sessionId);
30275
+ return stored instanceof FoundAcpStoredSession ? [stored.session] : [];
30276
+ });
30277
+ findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
30325
30278
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
30326
30279
  createNativeSession = async (options) => {
30327
30280
  const temporarySessionId = `new-${crypto.randomUUID()}`;
@@ -32675,21 +32628,17 @@ function daemonActivity(command, activity2) {
32675
32628
  toolKind: activity2.toolKind
32676
32629
  };
32677
32630
  }
32678
- function reportFailure(publisher, command, code, message, attemptId) {
32679
- publisher.recordAttempt(
32680
- command.sessionId,
32681
- {
32682
- code,
32683
- commandId: command.commandId,
32684
- kind: SESSION_FAILED_KIND,
32685
- message,
32686
- sessionId: command.sessionId
32687
- },
32688
- attemptId
32689
- );
32631
+ function reportFailure(publisher, command, code, message) {
32632
+ publisher.publish(command.sessionId, {
32633
+ code,
32634
+ commandId: command.commandId,
32635
+ kind: SESSION_FAILED_KIND,
32636
+ message,
32637
+ sessionId: command.sessionId
32638
+ });
32690
32639
  }
32691
- function settleAbandonedTurn(publisher, outbox, audit, cancellation) {
32692
- const attemptId = outbox.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
32640
+ function settleAbandonedTurn(publisher, operations, audit, cancellation) {
32641
+ const attemptId = operations.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
32693
32642
  if (attemptId === null) {
32694
32643
  console.warn("Mobius daemon ignored cancellation for an inactive turn");
32695
32644
  return;
@@ -32703,10 +32652,9 @@ function settleAbandonedTurn(publisher, outbox, audit, cancellation) {
32703
32652
  publisher,
32704
32653
  cancellation,
32705
32654
  "agent_execution_abandoned",
32706
- "The local Agent execution was abandoned before it completed",
32707
- attemptId
32655
+ "The local Agent execution was abandoned before it completed"
32708
32656
  );
32709
- outbox.transitionExecution(cancellation.commandId, "failed");
32657
+ operations.transitionExecution(cancellation.commandId, "failed");
32710
32658
  }
32711
32659
  function operationErrorCode(error62) {
32712
32660
  if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof PromptArtifactError) {
@@ -32836,7 +32784,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
32836
32784
  event: "session_configured",
32837
32785
  sessionId: command.sessionId
32838
32786
  });
32839
- publisher.recordRuntime(command.sessionId, {
32787
+ publisher.publish(command.sessionId, {
32840
32788
  configOptions,
32841
32789
  kind: "session.config.updated",
32842
32790
  requestId: command.requestId,
@@ -32861,7 +32809,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
32861
32809
  };
32862
32810
  if (command.transient !== true) {
32863
32811
  metrics.measureSync("readiness-commit", () => {
32864
- publisher.recordRuntime(command.sessionId, event);
32812
+ publisher.publish(command.sessionId, event);
32865
32813
  });
32866
32814
  }
32867
32815
  return event;
@@ -33009,7 +32957,7 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
33009
32957
  event: "session_configured",
33010
32958
  sessionId: command.sessionId
33011
32959
  });
33012
- publisher.recordRuntime(command.sessionId, {
32960
+ publisher.publish(command.sessionId, {
33013
32961
  configOptions,
33014
32962
  kind: "session.config.updated",
33015
32963
  requestId: command.requestId,
@@ -33022,26 +32970,22 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
33022
32970
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
33023
32971
  }
33024
32972
  }
33025
- async function executePrompt(outbox, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, timer, signal, recordLiveText) {
32973
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, waitForSessionAvailability, timer, signal, recordLiveText, cancellationRequested) {
33026
32974
  const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
33027
- publisher.recordAttempt(command.sessionId, daemonActivity(command, activity2), attemptId);
32975
+ publisher.publish(command.sessionId, daemonActivity(command, activity2));
33028
32976
  });
33029
32977
  const narration = new CoalescingNarrationPublisher(
33030
32978
  timer,
33031
32979
  (increment) => {
33032
- publisher.recordAttempt(
33033
- command.sessionId,
33034
- {
33035
- activityId: increment.activityId,
33036
- activityType: increment.activityType,
33037
- commandId: command.commandId,
33038
- kind: AGENT_ACTIVITY_NARRATION_KIND,
33039
- sequence: increment.sequence,
33040
- sessionId: command.sessionId,
33041
- text: increment.text
33042
- },
33043
- attemptId
33044
- );
32980
+ publisher.publish(command.sessionId, {
32981
+ activityId: increment.activityId,
32982
+ activityType: increment.activityType,
32983
+ commandId: command.commandId,
32984
+ kind: AGENT_ACTIVITY_NARRATION_KIND,
32985
+ sequence: increment.sequence,
32986
+ sessionId: command.sessionId,
32987
+ text: increment.text
32988
+ });
33045
32989
  },
33046
32990
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
33047
32991
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -33050,19 +32994,15 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33050
32994
  timer,
33051
32995
  (messageId, delta) => {
33052
32996
  const stream = recordLiveText(delta);
33053
- publisher.recordAttempt(
33054
- command.sessionId,
33055
- {
33056
- commandId: command.commandId,
33057
- epoch: stream.epoch,
33058
- kind: AGENT_MESSAGE_DELTA_KIND,
33059
- messageId,
33060
- sequence: stream.sequence,
33061
- sessionId: command.sessionId,
33062
- text: delta
33063
- },
33064
- attemptId
33065
- );
32997
+ publisher.publish(command.sessionId, {
32998
+ commandId: command.commandId,
32999
+ epoch: stream.epoch,
33000
+ kind: AGENT_MESSAGE_DELTA_KIND,
33001
+ messageId,
33002
+ sequence: stream.sequence,
33003
+ sessionId: command.sessionId,
33004
+ text: delta
33005
+ });
33066
33006
  },
33067
33007
  AGENT_TEXT_COALESCING_MILLISECONDS,
33068
33008
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -33070,13 +33010,17 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33070
33010
  try {
33071
33011
  const resolved = await resolveSessionDirectories(
33072
33012
  directories,
33073
- config2.bindingId,
33013
+ command.bindingId,
33074
33014
  command.directoryId,
33075
33015
  command.additionalDirectoryIds,
33076
33016
  signal
33077
33017
  );
33078
33018
  const agent = config2.catalog.find(command.agentId);
33079
- if (command.disposition === SessionPromptDisposition.Queue && !outbox.isTerminalExecution(command.targetCommandId, command.sessionId)) {
33019
+ const availability = await waitForSessionAvailability(signal);
33020
+ if (availability === "busy") {
33021
+ throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
33022
+ }
33023
+ if (availability === "queue-target-unavailable") {
33080
33024
  throw new AcpExecutionError(
33081
33025
  "The queued prompt target is unavailable",
33082
33026
  {},
@@ -33116,18 +33060,17 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33116
33060
  event: "session_authorized",
33117
33061
  sessionId: command.sessionId
33118
33062
  });
33119
- outbox.transitionExecution(command.commandId, "running");
33120
- publisher.recordAttempt(
33121
- command.sessionId,
33122
- {
33123
- commandId: command.commandId,
33124
- kind: SESSION_STARTED_KIND,
33125
- attemptId,
33126
- sessionId: command.sessionId
33127
- },
33128
- attemptId
33129
- );
33130
- activateAttempt();
33063
+ operations.transitionExecution(command.commandId, "running");
33064
+ const stream = activateAttempt();
33065
+ publisher.publish(command.sessionId, {
33066
+ commandId: command.commandId,
33067
+ epoch: stream.epoch,
33068
+ kind: SESSION_STARTED_KIND,
33069
+ attemptId,
33070
+ prompt: command.prompt,
33071
+ sequence: stream.sequence,
33072
+ sessionId: command.sessionId
33073
+ });
33131
33074
  const attachments = await resolvePromptArtifacts(config2, command, signal);
33132
33075
  let stopReason;
33133
33076
  if (command.disposition === SessionPromptDisposition.Steer) {
@@ -33172,17 +33115,13 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33172
33115
  text.flush();
33173
33116
  narration.flush();
33174
33117
  activities.flush();
33175
- publisher.recordAttempt(
33176
- command.sessionId,
33177
- {
33178
- commandId: command.commandId,
33179
- kind: SESSION_COMPLETED_KIND,
33180
- sessionId: command.sessionId,
33181
- stopReason
33182
- },
33183
- attemptId
33184
- );
33185
- outbox.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
33118
+ publisher.publish(command.sessionId, {
33119
+ commandId: command.commandId,
33120
+ kind: SESSION_COMPLETED_KIND,
33121
+ sessionId: command.sessionId,
33122
+ stopReason
33123
+ });
33124
+ operations.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
33186
33125
  audit.record({
33187
33126
  commandId: command.commandId,
33188
33127
  event: stopReason === "cancelled" ? "session_cancelled" : "session_completed",
@@ -33192,6 +33131,21 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33192
33131
  text.flush();
33193
33132
  narration.flush();
33194
33133
  activities.flush();
33134
+ if (signal.aborted && cancellationRequested()) {
33135
+ publisher.publish(command.sessionId, {
33136
+ commandId: command.commandId,
33137
+ kind: SESSION_COMPLETED_KIND,
33138
+ sessionId: command.sessionId,
33139
+ stopReason: "cancelled"
33140
+ });
33141
+ operations.transitionExecution(command.commandId, "cancelled");
33142
+ audit.record({
33143
+ commandId: command.commandId,
33144
+ event: "session_cancelled",
33145
+ sessionId: command.sessionId
33146
+ });
33147
+ return;
33148
+ }
33195
33149
  audit.record({
33196
33150
  commandId: command.commandId,
33197
33151
  event: "session_failed",
@@ -33202,10 +33156,9 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33202
33156
  publisher,
33203
33157
  command,
33204
33158
  code === "session_operation_failed" ? "agent_execution_failed" : code,
33205
- code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62),
33206
- attemptId
33159
+ code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62)
33207
33160
  );
33208
- outbox.transitionExecution(command.commandId, "failed");
33161
+ operations.transitionExecution(command.commandId, "failed");
33209
33162
  console.error("Mobius daemon command failed", error62);
33210
33163
  }
33211
33164
  }
@@ -33347,7 +33300,6 @@ var DaemonInstallationObserver = class {
33347
33300
  import { randomUUID as randomUUID2 } from "node:crypto";
33348
33301
  import { fetch as fetch4 } from "undici";
33349
33302
  var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
33350
- var ACTIVE_TURN_TEXT_LIMIT = 1e5;
33351
33303
  var ActiveDaemonTurn = class {
33352
33304
  attemptId;
33353
33305
  command;
@@ -33370,6 +33322,7 @@ var ActiveDaemonTurn = class {
33370
33322
  finish = () => this.#finished.resolve();
33371
33323
  accept = () => {
33372
33324
  this.#accepted = true;
33325
+ return { epoch: this.#epoch, sequence: 0 };
33373
33326
  };
33374
33327
  recordText = (delta) => {
33375
33328
  this.#sequence += 1;
@@ -33392,11 +33345,16 @@ var ActiveDaemonTurn = class {
33392
33345
  matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
33393
33346
  requestCancellation = () => {
33394
33347
  if (this.#cancellationRequested) {
33395
- return false;
33348
+ return "already-requested";
33396
33349
  }
33397
33350
  this.#cancellationRequested = true;
33398
- return true;
33351
+ if (!this.#accepted) {
33352
+ this.#controller.abort(new Error("The queued Agent turn was cancelled"));
33353
+ return "pending";
33354
+ }
33355
+ return "running";
33399
33356
  };
33357
+ cancellationRequested = () => this.#cancellationRequested;
33400
33358
  get signal() {
33401
33359
  return this.#controller.signal;
33402
33360
  }
@@ -34122,6 +34080,7 @@ var NativeSessionService = class {
34122
34080
  });
34123
34081
  return {
34124
34082
  entryId,
34083
+ mobiusSessionIds: this.#sessions.findLinkedSessions(command.agentId, info.sessionId).filter((session) => session.prompted && session.cwd === authorized.cwd).map((session) => session.sessionId),
34125
34084
  nativeSessionId: info.sessionId,
34126
34085
  title: info.title ?? "Untitled session",
34127
34086
  directoryId: authorized.directoryId,
@@ -34339,6 +34298,29 @@ var NativeSessionService = class {
34339
34298
  history: opened.history
34340
34299
  };
34341
34300
  };
34301
+ querySessions = async (sessionIds, signal) => {
34302
+ const entries = [];
34303
+ for (const session of this.#sessions.findSessions(sessionIds)) {
34304
+ signal.throwIfAborted();
34305
+ const directory = await this.#directories.identify(this.#config.bindingId, session.cwd, signal);
34306
+ const additionalDirectories = [];
34307
+ for (const path2 of session.additionalDirectories) {
34308
+ const identified = await this.#directories.identify(this.#config.bindingId, path2, signal);
34309
+ additionalDirectories.push({ directoryId: identified.directoryId, name: identified.name });
34310
+ }
34311
+ entries.push({
34312
+ additionalDirectories,
34313
+ agentId: session.agentId,
34314
+ directoryId: directory.directoryId,
34315
+ directoryLabel: directory.label,
34316
+ prompted: session.prompted,
34317
+ sessionId: session.sessionId,
34318
+ title: session.title || "Untitled session",
34319
+ updatedAt: session.updatedAt
34320
+ });
34321
+ }
34322
+ return entries;
34323
+ };
34342
34324
  executeTurnFork = async (command, signal) => {
34343
34325
  signal.throwIfAborted();
34344
34326
  const cwd = await this.#directories.resolve(this.#config.bindingId, command.directoryId, signal);
@@ -34611,6 +34593,75 @@ function connectRelay(url2, signal) {
34611
34593
  });
34612
34594
  }
34613
34595
 
34596
+ // src/relay-connection/daemon-operation-state.ts
34597
+ import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
34598
+ var MAX_TERMINAL_RECEIPTS = 1024;
34599
+ function isTerminal(state) {
34600
+ return state === "succeeded" || state === "failed" || state === "cancelled";
34601
+ }
34602
+ var DaemonOperationState = class {
34603
+ #executions = /* @__PURE__ */ new Map();
34604
+ #terminalCount = 0;
34605
+ claimExecution = (commandId, sessionId, commandJson) => {
34606
+ const commandHash = createHash4("sha256").update(commandJson).digest("hex");
34607
+ const existing = this.#executions.get(commandId);
34608
+ if (existing !== void 0) {
34609
+ if (existing.sessionId !== sessionId || existing.commandHash !== commandHash) {
34610
+ throw new Error("The daemon command identity conflicts with its in-memory receipt");
34611
+ }
34612
+ return { attemptId: existing.attemptId, commandId, kind: "duplicate", state: existing.state };
34613
+ }
34614
+ const attemptId = randomUUID4();
34615
+ this.#executions.set(commandId, { attemptId, commandHash, sessionId, state: "dispatching" });
34616
+ return { attemptId, commandId, kind: "accepted", state: "dispatching" };
34617
+ };
34618
+ transitionExecution = (commandId, state) => {
34619
+ const current = this.#executions.get(commandId);
34620
+ if (current === void 0) {
34621
+ throw new Error("The daemon execution receipt does not exist");
34622
+ }
34623
+ if (current.state === state) {
34624
+ return;
34625
+ }
34626
+ const allowed = current.state === "dispatching" && (state === "running" || state === "failed" || state === "cancelled") || current.state === "running" && isTerminal(state);
34627
+ if (!allowed) {
34628
+ throw new Error("The daemon execution transition is invalid");
34629
+ }
34630
+ this.#executions.set(commandId, { ...current, state });
34631
+ if (isTerminal(state)) {
34632
+ this.#terminalCount += 1;
34633
+ this.pruneTerminalReceipts();
34634
+ }
34635
+ };
34636
+ /** Receipts disappear when the daemon process exits. */
34637
+ findUnsettledAttemptId = (commandId, sessionId) => {
34638
+ const receipt = this.#executions.get(commandId);
34639
+ return receipt?.sessionId === sessionId && !isTerminal(receipt.state) ? receipt.attemptId : null;
34640
+ };
34641
+ isTerminalExecution = (commandId, sessionId) => {
34642
+ const receipt = this.#executions.get(commandId);
34643
+ return receipt?.sessionId === sessionId && isTerminal(receipt.state);
34644
+ };
34645
+ close = () => {
34646
+ this.#executions.clear();
34647
+ this.#terminalCount = 0;
34648
+ };
34649
+ pruneTerminalReceipts = () => {
34650
+ if (this.#terminalCount <= MAX_TERMINAL_RECEIPTS) {
34651
+ return;
34652
+ }
34653
+ for (const [commandId, receipt] of this.#executions) {
34654
+ if (isTerminal(receipt.state)) {
34655
+ this.#executions.delete(commandId);
34656
+ this.#terminalCount -= 1;
34657
+ if (this.#terminalCount <= MAX_TERMINAL_RECEIPTS) {
34658
+ return;
34659
+ }
34660
+ }
34661
+ }
34662
+ };
34663
+ };
34664
+
34614
34665
  // src/relay-connection/diagnostics.ts
34615
34666
  var MAX_DIAGNOSTIC_TEXT_LENGTH = 256;
34616
34667
  function sanitizeDiagnosticText(value) {
@@ -34784,7 +34835,7 @@ var RelayConnectionDiagnostics = class {
34784
34835
  };
34785
34836
 
34786
34837
  // src/relay-connection/liveness.ts
34787
- import { randomUUID as randomUUID4 } from "node:crypto";
34838
+ import { randomUUID as randomUUID5 } from "node:crypto";
34788
34839
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
34789
34840
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
34790
34841
  var RelayLivenessState = class {
@@ -34873,7 +34924,7 @@ var RelayConnectionLiveness = class {
34873
34924
  }
34874
34925
  throw new Error("Heartbeat was scheduled in an invalid state");
34875
34926
  }
34876
- const heartbeatId = randomUUID4();
34927
+ const heartbeatId = randomUUID5();
34877
34928
  this.#state = new AwaitingHeartbeatAckState(
34878
34929
  heartbeatId,
34879
34930
  this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
@@ -34889,765 +34940,54 @@ var RelayConnectionLiveness = class {
34889
34940
  };
34890
34941
  };
34891
34942
 
34892
- // src/relay-connection/session-event-outbox.ts
34893
- import { createHash as createHash4 } from "node:crypto";
34894
- import { DatabaseSync } from "node:sqlite";
34895
- var DEFAULT_OUTBOX_LIMITS = {
34896
- criticalEventBytes: 40 * 1024 * 1024,
34897
- runtimeDeliveryBytes: 32 * 1024 * 1024,
34898
- runtimeDeliveryCount: 64,
34899
- standardEventBytes: 32 * 1024 * 1024
34900
- };
34901
- var MAX_TERMINAL_RECEIPTS = 1024;
34902
- var SessionEventOutboxCapacityError = class extends Error {
34903
- code = "session_event_outbox_full";
34904
- constructor() {
34905
- super("The in-memory Session event outbox is full");
34906
- this.name = "SessionEventOutboxCapacityError";
34907
- }
34908
- };
34909
- var RuntimeDeliveryInboxCapacityError = class extends Error {
34910
- code = "runtime_delivery_inbox_full";
34911
- constructor() {
34912
- super("The in-memory Runtime delivery inbox is full");
34913
- this.name = "RuntimeDeliveryInboxCapacityError";
34914
- }
34915
- };
34916
- var StoredRuntimeDelivery = class {
34917
- deliveryId;
34918
- duplicate;
34919
- payload;
34920
- sessionId;
34921
- state;
34922
- constructor(deliveryId, sessionId, payload, state, duplicate) {
34923
- this.deliveryId = deliveryId;
34924
- this.duplicate = duplicate;
34925
- this.payload = payload;
34926
- this.sessionId = sessionId;
34927
- this.state = state;
34928
- }
34929
- };
34930
- function readPendingEnvelope(row) {
34931
- if (typeof row !== "object" || row === null || Array.isArray(row)) {
34932
- throw new Error("SQLite returned an invalid session event outbox row");
34933
- }
34934
- const envelope2 = Reflect.get(row, "envelope_json");
34935
- if (typeof envelope2 !== "string") {
34936
- throw new Error("SQLite returned an invalid session event envelope");
34937
- }
34938
- return envelope2;
34939
- }
34940
- function rowNumber(row, field) {
34941
- const value = typeof row === "object" && row !== null ? Reflect.get(row, field) : void 0;
34942
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
34943
- throw new Error(`SQLite returned an invalid ${field} value`);
34944
- }
34945
- return value;
34946
- }
34947
- function rowString(row, field) {
34948
- const value = typeof row === "object" && row !== null ? Reflect.get(row, field) : void 0;
34949
- if (typeof value !== "string" || value.length === 0) {
34950
- throw new Error(`SQLite returned an invalid ${field} value`);
34951
- }
34952
- return value;
34953
- }
34954
- var SessionEventOutbox = class {
34955
- #database;
34956
- #limits;
34957
- constructor(limits = DEFAULT_OUTBOX_LIMITS) {
34958
- validateLimits(limits);
34959
- this.#limits = limits;
34960
- this.#database = new DatabaseSync(":memory:");
34961
- this.#database.exec(`
34962
- CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
34963
- ordinal INTEGER PRIMARY KEY AUTOINCREMENT,
34964
- event_id TEXT NOT NULL UNIQUE,
34965
- session_id TEXT NOT NULL,
34966
- source_key TEXT NOT NULL,
34967
- byte_length INTEGER NOT NULL,
34968
- envelope_json TEXT NOT NULL
34969
- ) STRICT;
34970
- CREATE INDEX IF NOT EXISTS relay_session_event_outbox_order
34971
- ON relay_session_event_outbox(ordinal);
34972
- CREATE TABLE IF NOT EXISTS relay_turn_receipts (
34973
- command_id TEXT PRIMARY KEY,
34974
- session_id TEXT NOT NULL,
34975
- command_hash TEXT NOT NULL,
34976
- attempt_id TEXT NOT NULL,
34977
- state TEXT NOT NULL CHECK (
34978
- state IN ('dispatching', 'running', 'succeeded', 'failed', 'cancelled')
34979
- )
34980
- ) STRICT;
34981
- CREATE TABLE IF NOT EXISTS relay_session_event_outbox_state (
34982
- singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
34983
- event_count INTEGER NOT NULL,
34984
- total_bytes INTEGER NOT NULL,
34985
- next_source_seq INTEGER NOT NULL
34986
- ) STRICT;
34987
- INSERT OR IGNORE INTO relay_session_event_outbox_state (
34988
- singleton, event_count, total_bytes, next_source_seq
34989
- ) VALUES (1, 0, 0, 1);
34990
- CREATE TABLE IF NOT EXISTS relay_runtime_deliveries (
34991
- delivery_id TEXT PRIMARY KEY,
34992
- session_id TEXT NOT NULL,
34993
- payload_json TEXT NOT NULL,
34994
- payload_bytes INTEGER NOT NULL,
34995
- state TEXT NOT NULL CHECK (
34996
- state IN ('received', 'relay_committed', 'processed')
34997
- ),
34998
- received_at INTEGER NOT NULL
34999
- ) STRICT;
35000
- `);
35001
- this.#database.exec(`
35002
- CREATE INDEX IF NOT EXISTS relay_session_event_outbox_source_order
35003
- ON relay_session_event_outbox(source_key, ordinal);
35004
- `);
35005
- }
35006
- claimExecution = (commandId, sessionId, commandJson) => {
35007
- const commandHash = createHash4("sha256").update(commandJson).digest("hex");
35008
- this.#database.exec("BEGIN IMMEDIATE");
35009
- try {
35010
- const existing = this.#database.prepare(
35011
- `SELECT session_id, command_hash, attempt_id, state
35012
- FROM relay_turn_receipts WHERE command_id = ?`
35013
- ).get(commandId);
35014
- if (typeof existing === "object" && existing !== null) {
35015
- const storedSessionId = Reflect.get(existing, "session_id");
35016
- const storedCommandHash = Reflect.get(existing, "command_hash");
35017
- const attemptId2 = Reflect.get(existing, "attempt_id");
35018
- const state = Reflect.get(existing, "state");
35019
- if (storedSessionId !== sessionId || storedCommandHash !== commandHash || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
35020
- throw new Error("The daemon command identity conflicts with its in-memory receipt");
35021
- }
35022
- this.#database.exec("COMMIT");
35023
- return { attemptId: attemptId2, commandId, kind: "duplicate", state };
35024
- }
35025
- const attemptId = crypto.randomUUID();
35026
- this.#database.prepare(
35027
- `INSERT INTO relay_turn_receipts (
35028
- command_id, session_id, command_hash, attempt_id, state
35029
- ) VALUES (?, ?, ?, ?, 'dispatching')`
35030
- ).run(commandId, sessionId, commandHash, attemptId);
35031
- this.#database.exec("COMMIT");
35032
- return {
35033
- attemptId,
35034
- commandId,
35035
- kind: "accepted",
35036
- state: "dispatching"
35037
- };
35038
- } catch (error62) {
35039
- this.#database.exec("ROLLBACK");
35040
- throw error62;
35041
- }
35042
- };
35043
- transitionExecution = (commandId, state) => {
35044
- const row = this.#database.prepare(`SELECT state FROM relay_turn_receipts WHERE command_id = ?`).get(commandId);
35045
- const current = typeof row === "object" && row !== null ? Reflect.get(row, "state") : void 0;
35046
- if (!isDaemonExecutionState(current)) {
35047
- throw new Error("The daemon execution receipt does not exist");
35048
- }
35049
- if (current === state) {
35050
- return;
35051
- }
35052
- const allowed = current === "dispatching" && (state === "running" || state === "failed" || state === "cancelled") || current === "running" && (state === "succeeded" || state === "failed" || state === "cancelled");
35053
- if (!allowed) {
35054
- throw new Error("The daemon execution transition is invalid");
35055
- }
35056
- this.#database.prepare(`UPDATE relay_turn_receipts SET state = ? WHERE command_id = ?`).run(state, commandId);
35057
- if (state === "succeeded" || state === "failed" || state === "cancelled") {
35058
- this.#database.prepare(
35059
- `DELETE FROM relay_turn_receipts
35060
- WHERE state IN ('succeeded', 'failed', 'cancelled')
35061
- AND rowid NOT IN (
35062
- SELECT rowid FROM relay_turn_receipts
35063
- WHERE state IN ('succeeded', 'failed', 'cancelled')
35064
- ORDER BY rowid DESC LIMIT ?
35065
- )`
35066
- ).run(MAX_TERMINAL_RECEIPTS);
35067
- }
35068
- };
35069
- /**
35070
- * The Attempt this live Runtime claimed for a command that has not reached a terminal state.
35071
- * Receipts disappear when the daemon process exits.
35072
- */
35073
- findUnsettledAttemptId = (commandId, sessionId) => {
35074
- const row = this.#database.prepare(`SELECT attempt_id, state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
35075
- if (typeof row !== "object" || row === null) {
35076
- return null;
35077
- }
35078
- const attemptId = Reflect.get(row, "attempt_id");
35079
- const state = Reflect.get(row, "state");
35080
- if (typeof attemptId !== "string" || attemptId.length === 0 || !isDaemonExecutionState(state)) {
35081
- return null;
35082
- }
35083
- return state === "dispatching" || state === "running" ? attemptId : null;
35084
- };
35085
- isTerminalExecution = (commandId, sessionId) => {
35086
- const row = this.#database.prepare(`SELECT state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
35087
- const state = typeof row === "object" && row !== null ? Reflect.get(row, "state") : void 0;
35088
- return state === "succeeded" || state === "failed" || state === "cancelled";
35089
- };
35090
- acknowledge = (acknowledgement) => this.#removeAcknowledgedEvent(acknowledgement.eventId, acknowledgement.sessionId);
35091
- quarantine = (rejection) => {
35092
- this.#database.exec("BEGIN IMMEDIATE");
35093
- try {
35094
- const stored = this.#database.prepare(
35095
- `SELECT byte_length FROM relay_session_event_outbox
35096
- WHERE event_id = ? AND session_id = ?`
35097
- ).get(rejection.eventId, rejection.sessionId);
35098
- if (stored === void 0) {
35099
- this.#database.exec("COMMIT");
35100
- return false;
35101
- }
35102
- const byteLength = rowNumber(stored, "byte_length");
35103
- const deletion = this.#database.prepare(
35104
- `DELETE FROM relay_session_event_outbox
35105
- WHERE event_id = ? AND session_id = ?`
35106
- ).run(rejection.eventId, rejection.sessionId);
35107
- if (deletion.changes !== 1) {
35108
- throw new Error("The rejected session event could not be removed from the in-memory outbox");
35109
- }
35110
- this.#decrementEventState(byteLength);
35111
- this.#database.exec("COMMIT");
35112
- return true;
35113
- } catch (error62) {
35114
- this.#database.exec("ROLLBACK");
35115
- throw error62;
35116
- }
35117
- };
35118
- close = () => {
35119
- this.#database.close();
35120
- };
35121
- enqueue = (sessionId, payload, attemptId = null) => {
35122
- return this.#enqueueBounded(sessionId, payload, attemptId ?? "", this.#limits.standardEventBytes);
35123
- };
35124
- enqueueCritical = (sessionId, payload, attemptId = "") => this.#enqueueBounded(sessionId, payload, attemptId, this.#limits.criticalEventBytes);
35125
- /**
35126
- * Bytes still available to standard Session events. The daemon uses this to shed
35127
- * superseded streaming events instead of filling the in-memory outbox, so a long Turn
35128
- * behind a slow Relay cannot make the next enqueue throw.
35129
- */
35130
- standardCapacityRemaining = () => {
35131
- const state = this.#database.prepare(
35132
- `SELECT total_bytes
35133
- FROM relay_session_event_outbox_state
35134
- WHERE singleton = 1`
35135
- ).get();
35136
- return this.#limits.standardEventBytes - rowNumber(state, "total_bytes");
35137
- };
35138
- claimRuntimeDelivery = (delivery) => {
35139
- const payloadBytes = new TextEncoder().encode(delivery.payload).byteLength;
35140
- this.#database.exec("BEGIN IMMEDIATE");
35141
- try {
35142
- const existing = this.#database.prepare(
35143
- `SELECT session_id, payload_json, state
35144
- FROM relay_runtime_deliveries
35145
- WHERE delivery_id = ?`
35146
- ).get(delivery.deliveryId);
35147
- if (existing !== void 0) {
35148
- const sessionId = rowString(existing, "session_id");
35149
- const payload = rowString(existing, "payload_json");
35150
- const state = runtimeDeliveryState(existing);
35151
- if (sessionId !== delivery.sessionId || payload !== delivery.payload) {
35152
- throw new Error("The Runtime delivery identity conflicts with its in-memory receipt");
35153
- }
35154
- this.#database.exec("COMMIT");
35155
- return new StoredRuntimeDelivery(delivery.deliveryId, sessionId, payload, state, true);
35156
- }
35157
- const usage = this.#database.prepare(
35158
- `SELECT COUNT(*) AS delivery_count,
35159
- COALESCE(SUM(payload_bytes), 0) AS delivery_bytes
35160
- FROM relay_runtime_deliveries`
35161
- ).get();
35162
- if (rowNumber(usage, "delivery_count") + 1 > this.#limits.runtimeDeliveryCount || rowNumber(usage, "delivery_bytes") + payloadBytes > this.#limits.runtimeDeliveryBytes) {
35163
- throw new RuntimeDeliveryInboxCapacityError();
35164
- }
35165
- this.#database.prepare(
35166
- `INSERT INTO relay_runtime_deliveries (
35167
- delivery_id, session_id, payload_json, payload_bytes, state, received_at
35168
- ) VALUES (?, ?, ?, ?, 'received', ?)`
35169
- ).run(delivery.deliveryId, delivery.sessionId, delivery.payload, payloadBytes, Date.now());
35170
- this.#database.exec("COMMIT");
35171
- return new StoredRuntimeDelivery(
35172
- delivery.deliveryId,
35173
- delivery.sessionId,
35174
- delivery.payload,
35175
- "received",
35176
- false
35177
- );
35178
- } catch (error62) {
35179
- this.#database.exec("ROLLBACK");
35180
- throw error62;
35181
- }
35182
- };
35183
- markRuntimeDeliveryCommitted = (deliveryId, sessionId) => {
35184
- this.#database.exec("BEGIN IMMEDIATE");
35185
- try {
35186
- const row = this.#database.prepare(
35187
- `SELECT state FROM relay_runtime_deliveries
35188
- WHERE delivery_id = ? AND session_id = ?`
35189
- ).get(deliveryId, sessionId);
35190
- if (row === void 0) {
35191
- this.#database.exec("COMMIT");
35192
- return false;
35193
- }
35194
- const state = runtimeDeliveryState(row);
35195
- if (state === "processed") {
35196
- this.#database.prepare(`DELETE FROM relay_runtime_deliveries WHERE delivery_id = ?`).run(deliveryId);
35197
- } else if (state === "received") {
35198
- this.#database.prepare(`UPDATE relay_runtime_deliveries SET state = 'relay_committed' WHERE delivery_id = ?`).run(deliveryId);
35199
- }
35200
- this.#database.exec("COMMIT");
35201
- return true;
35202
- } catch (error62) {
35203
- this.#database.exec("ROLLBACK");
35204
- throw error62;
35205
- }
35206
- };
35207
- markRuntimeDeliveryProcessed = (deliveryId, sessionId) => {
35208
- this.#database.exec("BEGIN IMMEDIATE");
35209
- try {
35210
- const row = this.#database.prepare(
35211
- `SELECT state FROM relay_runtime_deliveries
35212
- WHERE delivery_id = ? AND session_id = ?`
35213
- ).get(deliveryId, sessionId);
35214
- if (row === void 0) {
35215
- this.#database.exec("COMMIT");
35216
- return false;
35217
- }
35218
- const state = runtimeDeliveryState(row);
35219
- if (state === "relay_committed") {
35220
- this.#database.prepare(`DELETE FROM relay_runtime_deliveries WHERE delivery_id = ?`).run(deliveryId);
35221
- } else if (state === "received") {
35222
- this.#database.prepare(`UPDATE relay_runtime_deliveries SET state = 'processed' WHERE delivery_id = ?`).run(deliveryId);
35223
- }
35224
- this.#database.exec("COMMIT");
35225
- return true;
35226
- } catch (error62) {
35227
- this.#database.exec("ROLLBACK");
35228
- throw error62;
35229
- }
35230
- };
35231
- runtimeDeliveries = () => this.#database.prepare(
35232
- `SELECT delivery_id, session_id, payload_json, state
35233
- FROM relay_runtime_deliveries
35234
- ORDER BY received_at, delivery_id`
35235
- ).all().map(
35236
- (row) => new StoredRuntimeDelivery(
35237
- rowString(row, "delivery_id"),
35238
- rowString(row, "session_id"),
35239
- rowString(row, "payload_json"),
35240
- runtimeDeliveryState(row),
35241
- true
35242
- )
35243
- );
35244
- #enqueueBounded = (sessionId, payload, attemptId, maximumEventBytes) => {
35245
- const sourceKey = attemptId.length === 0 ? `runtime:${sessionId}` : `attempt:${sessionId}:${attemptId}`;
35246
- this.#database.exec("BEGIN IMMEDIATE");
35247
- try {
35248
- const state = this.#database.prepare(
35249
- `SELECT total_bytes, next_source_seq
35250
- FROM relay_session_event_outbox_state
35251
- WHERE singleton = 1`
35252
- ).get();
35253
- const nextSourceSeq = rowNumber(state, "next_source_seq");
35254
- if (nextSourceSeq < 1 || !Number.isSafeInteger(nextSourceSeq + 1)) {
35255
- throw new Error("SQLite returned an invalid event source sequence");
35256
- }
35257
- const envelope2 = {
35258
- eventId: crypto.randomUUID(),
35259
- kind: SESSION_EVENT_KIND,
35260
- payload,
35261
- sessionId,
35262
- source: attemptId.length === 0 ? { kind: "runtime", sourceSeq: nextSourceSeq.toString() } : {
35263
- attemptId,
35264
- kind: "attempt",
35265
- sourceSeq: nextSourceSeq.toString()
35266
- }
35267
- };
35268
- const encoded = encodeSessionEventEnvelope(envelope2);
35269
- const byteLength = new TextEncoder().encode(encoded).byteLength;
35270
- if (rowNumber(state, "total_bytes") + byteLength > maximumEventBytes) {
35271
- throw new SessionEventOutboxCapacityError();
35272
- }
35273
- this.#database.prepare(
35274
- `INSERT INTO relay_session_event_outbox (
35275
- event_id, session_id, source_key, byte_length, envelope_json
35276
- ) VALUES (?, ?, ?, ?, ?)`
35277
- ).run(envelope2.eventId, envelope2.sessionId, sourceKey, byteLength, encoded);
35278
- this.#database.prepare(
35279
- `UPDATE relay_session_event_outbox_state
35280
- SET event_count = event_count + 1,
35281
- total_bytes = total_bytes + ?,
35282
- next_source_seq = next_source_seq + 1
35283
- WHERE singleton = 1`
35284
- ).run(byteLength);
35285
- this.#database.exec("COMMIT");
35286
- return encoded;
35287
- } catch (error62) {
35288
- this.#database.exec("ROLLBACK");
35289
- throw error62;
35290
- }
35291
- };
35292
- #removeAcknowledgedEvent = (eventId, sessionId) => {
35293
- this.#database.exec("BEGIN IMMEDIATE");
35294
- try {
35295
- const stored = this.#database.prepare(
35296
- `SELECT byte_length FROM relay_session_event_outbox
35297
- WHERE event_id = ? AND session_id = ?`
35298
- ).get(eventId, sessionId);
35299
- if (stored === void 0) {
35300
- this.#database.exec("COMMIT");
35301
- return false;
35302
- }
35303
- const byteLength = rowNumber(stored, "byte_length");
35304
- const deletion = this.#database.prepare(
35305
- `DELETE FROM relay_session_event_outbox
35306
- WHERE event_id = ? AND session_id = ?`
35307
- ).run(eventId, sessionId);
35308
- if (deletion.changes !== 1) {
35309
- throw new Error("The acknowledged session event could not be removed from the in-memory outbox");
35310
- }
35311
- this.#decrementEventState(byteLength);
35312
- this.#database.exec("COMMIT");
35313
- return true;
35314
- } catch (error62) {
35315
- this.#database.exec("ROLLBACK");
35316
- throw error62;
35317
- }
35318
- };
35319
- #decrementEventState = (byteLength) => {
35320
- const result = this.#database.prepare(
35321
- `UPDATE relay_session_event_outbox_state
35322
- SET event_count = event_count - 1,
35323
- total_bytes = total_bytes - ?
35324
- WHERE singleton = 1 AND event_count > 0 AND total_bytes >= ?`
35325
- ).run(byteLength, byteLength);
35326
- if (result.changes !== 1) {
35327
- throw new Error("The Session event outbox capacity state is inconsistent");
35328
- }
35329
- };
35330
- pending = () => this.#database.prepare(
35331
- `SELECT envelope_json
35332
- FROM relay_session_event_outbox
35333
- ORDER BY ordinal`
35334
- ).all().map(readPendingEnvelope);
35335
- pendingBatch = (limit) => {
35336
- if (!Number.isSafeInteger(limit) || limit < 1) {
35337
- throw new Error("Session event replay batch limit must be a positive integer");
35338
- }
35339
- return this.#database.prepare(
35340
- `WITH ranked_events AS (
35341
- SELECT ordinal,
35342
- ROW_NUMBER() OVER (
35343
- PARTITION BY source_key
35344
- ORDER BY ordinal
35345
- ) AS source_position
35346
- FROM relay_session_event_outbox
35347
- )
35348
- SELECT outbox.envelope_json
35349
- FROM ranked_events AS ranked
35350
- INNER JOIN relay_session_event_outbox AS outbox
35351
- ON outbox.ordinal = ranked.ordinal
35352
- ORDER BY ranked.source_position, outbox.ordinal
35353
- LIMIT ?`
35354
- ).all(limit).map(readPendingEnvelope);
35355
- };
35356
- pendingSourceHeads = (limit, excludedEventIds, excludedSourceKeys) => {
35357
- if (!Number.isSafeInteger(limit) || limit < 1) {
35358
- throw new Error("Session event replay batch limit must be a positive integer");
35359
- }
35360
- const exclusions = [];
35361
- const parameters = [];
35362
- if (excludedEventIds.length > 0) {
35363
- exclusions.push(`event_id NOT IN (${excludedEventIds.map(() => "?").join(", ")})`);
35364
- parameters.push(...excludedEventIds);
35365
- }
35366
- if (excludedSourceKeys.length > 0) {
35367
- exclusions.push(`source_key NOT IN (${excludedSourceKeys.map(() => "?").join(", ")})`);
35368
- parameters.push(...excludedSourceKeys);
35369
- }
35370
- parameters.push(limit.toString());
35371
- const where = exclusions.length === 0 ? "" : `WHERE ${exclusions.join(" AND ")}`;
35372
- return this.#database.prepare(
35373
- `WITH available_events AS (
35374
- SELECT ordinal, source_key
35375
- FROM relay_session_event_outbox
35376
- ${where}
35377
- ), ranked_events AS (
35378
- SELECT ordinal,
35379
- ROW_NUMBER() OVER (
35380
- PARTITION BY source_key
35381
- ORDER BY ordinal
35382
- ) AS source_position
35383
- FROM available_events
35384
- )
35385
- SELECT outbox.envelope_json
35386
- FROM ranked_events AS ranked
35387
- INNER JOIN relay_session_event_outbox AS outbox
35388
- ON outbox.ordinal = ranked.ordinal
35389
- WHERE ranked.source_position = 1
35390
- ORDER BY outbox.ordinal
35391
- LIMIT ?`
35392
- ).all(...parameters).map(readPendingEnvelope);
35393
- };
35394
- };
35395
- function validateLimits(limits) {
35396
- const values = [
35397
- limits.criticalEventBytes,
35398
- limits.runtimeDeliveryBytes,
35399
- limits.runtimeDeliveryCount,
35400
- limits.standardEventBytes
35401
- ];
35402
- if (values.some((value) => !Number.isSafeInteger(value) || value < 1)) {
35403
- throw new Error("Session event outbox limits must be positive integers");
35404
- }
35405
- if (limits.criticalEventBytes < limits.standardEventBytes) {
35406
- throw new Error("Critical Session event capacity must include the standard capacity");
35407
- }
35408
- }
35409
- function runtimeDeliveryState(row) {
35410
- const state = rowString(row, "state");
35411
- if (state !== "received" && state !== "relay_committed" && state !== "processed") {
35412
- throw new Error("SQLite returned an invalid Runtime delivery state");
35413
- }
35414
- return state;
35415
- }
35416
- function isDaemonExecutionState(value) {
35417
- return value === "cancelled" || value === "dispatching" || value === "failed" || value === "running" || value === "succeeded";
35418
- }
35419
-
35420
34943
  // src/relay-connection/session-event-publisher.ts
35421
34944
  import { WebSocket as WebSocket4 } from "undici";
35422
- var DaemonSessionEventConnectionState = class {
35423
- };
35424
- var DisconnectedDaemonSessionEventState = class extends DaemonSessionEventConnectionState {
35425
- disconnect = () => this;
35426
- matches = () => false;
35427
- send = () => false;
35428
- };
35429
- var ConnectedDaemonSessionEventState = class extends DaemonSessionEventConnectionState {
35430
- #socket;
35431
- constructor(socket) {
35432
- super();
35433
- this.#socket = socket;
35434
- }
35435
- disconnect = (socket) => socket === this.#socket ? new DisconnectedDaemonSessionEventState() : this;
35436
- matches = (socket) => socket === this.#socket;
35437
- send = (message) => {
35438
- if (this.#socket.readyState !== WebSocket4.OPEN) {
35439
- return false;
35440
- }
35441
- try {
35442
- this.#socket.send(encodeDaemonToServiceMessage(message));
35443
- return true;
35444
- } catch {
35445
- return false;
35446
- }
35447
- };
35448
- };
35449
- var SESSION_EVENT_REPLAY_WINDOW = 16;
35450
- var SESSION_EVENT_SOURCE_REPLAY_WINDOW = 4;
35451
- var SESSION_EVENT_REPLAY_BYTE_LIMIT = 32 * 1024 * 1024;
35452
- function reservesSessionEventCapacity(event) {
35453
- if (event.kind === SESSION_COMPLETED_KIND || event.kind === SESSION_FAILED_KIND) {
35454
- return true;
35455
- }
35456
- return event.kind === AGENT_ACTIVITY_KIND && (event.activityType === "progress" || event.activityType === "reasoning") && (event.status === "completed" || event.status === "failed");
35457
- }
35458
- var InFlightSessionEvent = class {
35459
- byteLength;
35460
- sourceKey;
35461
- constructor(sourceKey, byteLength) {
35462
- this.byteLength = byteLength;
35463
- this.sourceKey = sourceKey;
35464
- }
35465
- };
35466
- function sessionEventSourceKey(envelope2) {
35467
- return envelope2.source.kind === "attempt" ? `attempt:${envelope2.sessionId}:${envelope2.source.attemptId}` : `runtime:${envelope2.sessionId}`;
35468
- }
34945
+ var MAX_LIVE_EVENT_BUFFERED_BYTES = 16 * 1024 * 1024;
35469
34946
  var DaemonSessionEventPublisher = class {
35470
- #outbox;
35471
- #inFlightEvents = /* @__PURE__ */ new Map();
35472
- #pausedSources = /* @__PURE__ */ new Map();
35473
- #shedEventKinds = /* @__PURE__ */ new Set();
35474
- #timer;
35475
- #inFlightBytes = 0;
35476
- #connection = new DisconnectedDaemonSessionEventState();
35477
- constructor(outbox, timer) {
35478
- this.#outbox = outbox;
35479
- this.#timer = timer;
35480
- }
34947
+ #socket = null;
34948
+ #reportedDrop = false;
35481
34949
  connect = (socket) => {
35482
- this.#connection = new ConnectedDaemonSessionEventState(socket);
35483
- this.#clearInFlight();
35484
- this.#publishNextBatch();
34950
+ this.#socket = socket;
34951
+ this.#reportedDrop = false;
35485
34952
  };
35486
34953
  disconnect = (socket) => {
35487
- if (!this.#connection.matches(socket)) {
35488
- return;
35489
- }
35490
- this.#connection = this.#connection.disconnect(socket);
35491
- this.#clearInFlight();
35492
- };
35493
- recordAttempt = (sessionId, event, attemptId) => {
35494
- const encoded = encodeRecordedSessionEvent(event);
35495
- if (reservesSessionEventCapacity(event)) {
35496
- this.#enqueueReserved(sessionId, encoded, attemptId, event.kind);
35497
- } else {
35498
- this.#enqueueStandard(sessionId, encoded, attemptId, event.kind);
35499
- }
35500
- this.#publishNextBatch();
35501
- };
35502
- recordRuntime = (sessionId, event) => {
35503
- this.#enqueueStandard(sessionId, encodeRecordedSessionEvent(event), "", event.kind);
35504
- this.#publishNextBatch();
35505
- };
35506
- /**
35507
- * Enqueue a standard event, shedding it instead of ending the daemon when the
35508
- * in-memory outbox is full.
35509
- *
35510
- * A capacity error used to escape the coalescing timer that publishes activities,
35511
- * so the process exited and every restart died on the same retained backlog. A full
35512
- * outbox is a recoverable runtime condition, not a fatal one: narration increments are
35513
- * superseded by the completed snapshot, so they are shed first, and any other streaming
35514
- * event is shed only at the wall rather than terminating the daemon.
35515
- */
35516
- #enqueueStandard = (sessionId, encoded, attemptId, kind) => {
35517
- if (kind === AGENT_ACTIVITY_NARRATION_KIND && this.#outbox.standardCapacityRemaining() <= 0) {
35518
- this.#reportShedEvent(kind);
35519
- return;
35520
- }
35521
- try {
35522
- this.#outbox.enqueue(sessionId, encoded, attemptId);
35523
- } catch (error62) {
35524
- if (!(error62 instanceof SessionEventOutboxCapacityError)) {
35525
- throw error62;
35526
- }
35527
- this.#reportShedEvent(kind);
35528
- }
35529
- };
35530
- /**
35531
- * Enqueue on the reserved budget, degrading to a reported drop instead of raising.
35532
- * Streaming events are shed before this budget is reached, so a Turn's terminal
35533
- * events and the completed snapshot that carries its narration still land; a drop
35534
- * here is the last resort for a backlog no acknowledgement can drain.
35535
- */
35536
- #enqueueReserved = (sessionId, encoded, attemptId, kind) => {
35537
- try {
35538
- this.#outbox.enqueueCritical(sessionId, encoded, attemptId);
35539
- } catch (error62) {
35540
- if (!(error62 instanceof SessionEventOutboxCapacityError)) {
35541
- throw error62;
35542
- }
35543
- this.#reportShedEvent(kind);
35544
- }
35545
- };
35546
- #reportShedEvent = (kind) => {
35547
- if (this.#shedEventKinds.has(kind)) {
35548
- return;
34954
+ if (this.#socket === socket) {
34955
+ this.#socket = null;
35549
34956
  }
35550
- this.#shedEventKinds.add(kind);
35551
- console.warn(`Mobius daemon is dropping queued "${kind}" events because the Session event outbox is full`);
35552
34957
  };
35553
- acknowledge = (acknowledgement) => {
35554
- if (!this.#outbox.acknowledge(acknowledgement)) {
34958
+ publish = (sessionId, event) => {
34959
+ const socket = this.#socket;
34960
+ if (socket === null || socket.readyState !== WebSocket4.OPEN) {
34961
+ this.#reportDrop();
35555
34962
  return;
35556
34963
  }
35557
- this.#removeInFlight(acknowledgement.eventId);
35558
- this.#publishNextBatch();
35559
- };
35560
- quarantine = (rejection) => {
35561
- const quarantined = this.#outbox.quarantine(rejection);
35562
- if (!quarantined) {
35563
- return false;
35564
- }
35565
- this.#removeInFlight(rejection.eventId);
35566
- this.#publishNextBatch();
35567
- return true;
35568
- };
35569
- defer = (deferred) => {
35570
- const inFlight = this.#inFlightEvents.get(deferred.eventId);
35571
- if (inFlight === void 0) {
34964
+ if (socket.bufferedAmount >= MAX_LIVE_EVENT_BUFFERED_BYTES) {
34965
+ this.#socket = null;
34966
+ socket.close(1013, "Live event backpressure");
34967
+ this.#reportDrop();
35572
34968
  return;
35573
34969
  }
35574
- this.#clearInFlightSource(inFlight.sourceKey);
35575
- if (!this.#pausedSources.has(inFlight.sourceKey)) {
35576
- this.#pausedSources.set(
35577
- inFlight.sourceKey,
35578
- this.#timer.schedule(() => {
35579
- this.#pausedSources.delete(inFlight.sourceKey);
35580
- this.#publishNextBatch();
35581
- }, deferred.retryAfterMilliseconds)
34970
+ try {
34971
+ socket.send(
34972
+ encodeDaemonToServiceMessage({
34973
+ kind: SESSION_EVENT_KIND,
34974
+ payload: encodeRecordedSessionEvent(event),
34975
+ sessionId
34976
+ })
35582
34977
  );
34978
+ } catch {
34979
+ this.#reportDrop();
35583
34980
  }
35584
- this.#publishNextBatch();
35585
34981
  };
35586
34982
  close = () => {
35587
- for (const task of this.#pausedSources.values()) {
35588
- task.cancel();
35589
- }
35590
- this.#pausedSources.clear();
35591
- this.#clearInFlight();
35592
- };
35593
- #publishNextBatch = () => {
35594
- while (this.#inFlightEvents.size < SESSION_EVENT_REPLAY_WINDOW) {
35595
- const sourceCounts = /* @__PURE__ */ new Map();
35596
- for (const inFlight of this.#inFlightEvents.values()) {
35597
- sourceCounts.set(inFlight.sourceKey, (sourceCounts.get(inFlight.sourceKey) ?? 0) + 1);
35598
- }
35599
- const saturatedSources = [...sourceCounts.entries()].filter(([, count]) => count >= SESSION_EVENT_SOURCE_REPLAY_WINDOW).map(([sourceKey]) => sourceKey);
35600
- const batch = this.#outbox.pendingSourceHeads(
35601
- SESSION_EVENT_REPLAY_WINDOW - this.#inFlightEvents.size,
35602
- [...this.#inFlightEvents.keys()],
35603
- [...this.#pausedSources.keys(), ...saturatedSources]
35604
- );
35605
- let sent = 0;
35606
- for (const encoded of batch) {
35607
- const envelope2 = decodeSessionEventEnvelope(encoded);
35608
- const sourceKey = sessionEventSourceKey(envelope2);
35609
- const sourceCount = sourceCounts.get(sourceKey) ?? 0;
35610
- if (sourceCount >= SESSION_EVENT_SOURCE_REPLAY_WINDOW) {
35611
- continue;
35612
- }
35613
- const byteLength = new TextEncoder().encode(encoded).byteLength;
35614
- if (this.#inFlightBytes + byteLength > SESSION_EVENT_REPLAY_BYTE_LIMIT) {
35615
- continue;
35616
- }
35617
- if (!this.#connection.send(envelope2)) {
35618
- this.#clearInFlight();
35619
- return;
35620
- }
35621
- this.#inFlightEvents.set(envelope2.eventId, new InFlightSessionEvent(sourceKey, byteLength));
35622
- this.#inFlightBytes += byteLength;
35623
- sourceCounts.set(sourceKey, sourceCount + 1);
35624
- sent += 1;
35625
- }
35626
- if (sent === 0) {
35627
- return;
35628
- }
35629
- }
34983
+ this.#socket = null;
35630
34984
  };
35631
- #removeInFlight = (eventId) => {
35632
- const inFlight = this.#inFlightEvents.get(eventId);
35633
- if (inFlight === void 0) {
34985
+ #reportDrop = () => {
34986
+ if (this.#reportedDrop) {
35634
34987
  return;
35635
34988
  }
35636
- this.#inFlightEvents.delete(eventId);
35637
- this.#inFlightBytes -= inFlight.byteLength;
35638
- };
35639
- #clearInFlight = () => {
35640
- this.#inFlightEvents.clear();
35641
- this.#inFlightBytes = 0;
35642
- };
35643
- #clearInFlightSource = (sourceKey) => {
35644
- for (const [eventId, inFlight] of this.#inFlightEvents) {
35645
- if (inFlight.sourceKey !== sourceKey) {
35646
- continue;
35647
- }
35648
- this.#inFlightEvents.delete(eventId);
35649
- this.#inFlightBytes -= inFlight.byteLength;
35650
- }
34989
+ this.#reportedDrop = true;
34990
+ console.warn("Mobius daemon dropped live Session events while the Relay was unavailable");
35651
34991
  };
35652
34992
  };
35653
34993
 
@@ -35721,7 +35061,7 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
35721
35061
  {
35722
35062
  agentId: agent.id,
35723
35063
  kind: AGENT_INSTALL_REQUEST_KIND,
35724
- requestId: `automatic-integration-${randomUUID5()}`
35064
+ requestId: `automatic-integration-${randomUUID6()}`
35725
35065
  },
35726
35066
  signal
35727
35067
  );
@@ -35766,9 +35106,8 @@ async function refreshAgentCatalog(config2, resolveEnvironment, signal) {
35766
35106
  throw error62;
35767
35107
  }
35768
35108
  }
35769
- async function runRelayConnection(config2, directories, audit, sessions, installations, installationObserver, nativeSessions, outbox, publisher, activeTurns, activeAttemptIds, connectionEpoch, diagnostics, onConnected, signal, timer, resolveAgentCatalogEnvironment) {
35109
+ async function runRelayConnection(config2, directories, audit, sessions, installations, installationObserver, nativeSessions, operations, publisher, activeTurns, connectionEpoch, diagnostics, onConnected, signal, timer, resolveAgentCatalogEnvironment) {
35770
35110
  const relayUrl = new URL(config2.relayUrl);
35771
- relayUrl.searchParams.set("deliveryReceipts", "1");
35772
35111
  relayUrl.searchParams.set("liveness", "1");
35773
35112
  const socket = await connectRelay(relayUrl, signal);
35774
35113
  const reconnectingTurns = [...activeTurns.values()];
@@ -35819,215 +35158,48 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35819
35158
  closeRelaySocket(socket, code, reason);
35820
35159
  rejectConnection(failure2);
35821
35160
  };
35822
- const processingDeliveryIds = /* @__PURE__ */ new Set();
35823
- const processDeliveredPrompt = async (delivery, command, trackActiveAttempt, execute) => {
35824
- if (command.sessionId !== delivery.sessionId) {
35825
- throw new Error("Runtime delivery Session identity does not match its payload");
35826
- }
35827
- const active = activeTurns.get(command.commandId);
35828
- if (active !== void 0) {
35829
- await active.completion;
35830
- return;
35831
- }
35832
- const receipt = outbox.claimExecution(command.commandId, command.sessionId, delivery.payload);
35833
- if (receipt.kind === "duplicate") {
35834
- if (receipt.state === "running") {
35835
- reportFailure(
35836
- publisher,
35837
- command,
35838
- "agent_execution_interrupted",
35839
- "The local Agent execution was interrupted before it completed",
35840
- receipt.attemptId
35841
- );
35842
- outbox.transitionExecution(command.commandId, "failed");
35843
- return;
35844
- }
35845
- if (receipt.state !== "dispatching") {
35846
- return;
35847
- }
35848
- }
35849
- const turn = new ActiveDaemonTurn(command, receipt.attemptId);
35850
- activeTurns.set(command.commandId, turn);
35851
- const activateAttempt = () => {
35852
- turn.accept();
35853
- if (trackActiveAttempt) {
35854
- activeAttemptIds.set(command.sessionId, receipt.attemptId);
35855
- }
35856
- };
35857
- try {
35858
- await execute(receipt.attemptId, activateAttempt, turn.signal, turn);
35859
- } finally {
35860
- activeTurns.delete(command.commandId);
35861
- if (activeAttemptIds.get(command.sessionId) === receipt.attemptId) {
35862
- activeAttemptIds.delete(command.sessionId);
35863
- }
35864
- turn.finish();
35865
- }
35161
+ const waitForTurnCompletion = (turn, waitSignal) => {
35162
+ waitSignal.throwIfAborted();
35163
+ return new Promise((resolve9, reject2) => {
35164
+ let settled = false;
35165
+ const finish = (result) => {
35166
+ if (settled) {
35167
+ return;
35168
+ }
35169
+ settled = true;
35170
+ waitSignal.removeEventListener("abort", onAbort);
35171
+ if (result.kind === "completed") {
35172
+ resolve9();
35173
+ } else {
35174
+ reject2(result.error);
35175
+ }
35176
+ };
35177
+ const onAbort = () => finish({ error: waitSignal.reason, kind: "failed" });
35178
+ waitSignal.addEventListener("abort", onAbort, { once: true });
35179
+ void turn.completion.then(
35180
+ () => finish({ kind: "completed" }),
35181
+ (error62) => finish({ error: error62, kind: "failed" })
35182
+ );
35183
+ });
35866
35184
  };
35867
- const processDeliveredPayload = async (delivery) => {
35868
- const message = decodeServiceToDaemonMessage(delivery.payload);
35869
- const kind = message.kind;
35870
- if (kind === SESSION_CANCEL_KIND) {
35871
- const cancellation = message;
35872
- if (cancellation.sessionId !== delivery.sessionId) {
35873
- throw new Error("Runtime delivery Session identity does not match its payload");
35874
- }
35875
- const turn = activeTurns.get(cancellation.commandId);
35876
- if (turn === void 0 || !turn.matches(cancellation)) {
35877
- settleAbandonedTurn(publisher, outbox, audit, cancellation);
35878
- return;
35879
- }
35880
- if (!turn.requestCancellation()) {
35881
- return;
35882
- }
35883
- audit.record({
35884
- commandId: cancellation.commandId,
35885
- event: "session_cancellation_requested",
35886
- sessionId: cancellation.sessionId
35887
- });
35888
- await sessions.cancelPrompt(cancellation.sessionId);
35889
- return;
35185
+ const waitForSessionAvailability = async (command, waitSignal) => {
35186
+ if (command.disposition === SessionPromptDisposition.Steer) {
35187
+ return "available";
35890
35188
  }
35891
- if (kind === SESSION_CONFIGURE_KIND) {
35892
- const command = message;
35893
- if (command.sessionId !== delivery.sessionId) {
35894
- throw new Error("Runtime delivery Session identity does not match its payload");
35895
- }
35896
- await executeSessionConfigure(
35897
- publisher,
35898
- socket,
35899
- command,
35900
- config2,
35901
- directories,
35902
- audit,
35903
- sessions,
35904
- connectionController.signal
35189
+ for (; ; ) {
35190
+ const first = [...activeTurns.values()].find(
35191
+ (turn) => turn.command.sessionId === command.sessionId && turn.command.disposition !== SessionPromptDisposition.Steer
35905
35192
  );
35906
- return;
35907
- }
35908
- if (kind === SESSION_PERMISSION_RESPOND_KIND) {
35909
- const command = message;
35910
- if (command.sessionId !== delivery.sessionId) {
35911
- throw new Error("Runtime delivery Session identity does not match its payload");
35912
- }
35913
- try {
35914
- await sessions.respondPermission(command);
35915
- audit.record({
35916
- commandId: command.interactionId,
35917
- event: "session_permission_resolved",
35918
- sessionId: command.sessionId
35919
- });
35920
- } catch (error62) {
35921
- reportOperationFailure(socket, command.interactionId, command.sessionId, error62);
35922
- }
35923
- return;
35924
- }
35925
- if (kind === SESSION_ELICITATION_RESPOND_KIND) {
35926
- const command = message;
35927
- if (command.sessionId !== delivery.sessionId) {
35928
- throw new Error("Runtime delivery Session identity does not match its payload");
35193
+ if (first === void 0 || first.command.commandId === command.commandId) {
35194
+ return command.disposition !== SessionPromptDisposition.Queue || operations.isTerminalExecution(command.targetCommandId, command.sessionId) ? "available" : "queue-target-unavailable";
35929
35195
  }
35930
- try {
35931
- await sessions.respondElicitation(command);
35932
- audit.record({
35933
- commandId: command.interactionId,
35934
- event: "session_elicitation_resolved",
35935
- sessionId: command.sessionId
35936
- });
35937
- } catch (error62) {
35938
- reportOperationFailure(socket, command.interactionId, command.sessionId, error62);
35196
+ if (command.disposition !== SessionPromptDisposition.Queue) {
35197
+ return "busy";
35939
35198
  }
35940
- return;
35941
- }
35942
- if (kind === SESSION_PROMPT_KIND) {
35943
- const command = message;
35944
- await processDeliveredPrompt(
35945
- delivery,
35946
- command,
35947
- command.disposition !== SessionPromptDisposition.Steer,
35948
- (attemptId, activateAttempt, executionSignal, turn) => executePrompt(
35949
- outbox,
35950
- publisher,
35951
- command,
35952
- config2,
35953
- directories,
35954
- audit,
35955
- sessions,
35956
- attemptId,
35957
- activateAttempt,
35958
- timer,
35959
- executionSignal,
35960
- turn.recordText
35961
- )
35962
- );
35963
- return;
35964
- }
35965
- throw new Error("Runtime delivery contains an unsupported protocol message");
35966
- };
35967
- const processRuntimeDelivery = (delivery, state) => {
35968
- if (state === "processed" || processingDeliveryIds.has(delivery.deliveryId)) {
35969
- return;
35970
- }
35971
- processingDeliveryIds.add(delivery.deliveryId);
35972
- void processDeliveredPayload(delivery).then(() => {
35973
- outbox.markRuntimeDeliveryProcessed(delivery.deliveryId, delivery.sessionId);
35974
- }).catch((error62) => {
35975
- if (connectionController.signal.aborted) {
35976
- return;
35977
- }
35978
- console.error("Mobius daemon could not process a in-memory Runtime delivery", error62);
35979
- failAndClose(
35980
- new Error("Runtime delivery processing failed", { cause: error62 }),
35981
- 4008,
35982
- "Invalid Runtime delivery",
35983
- "delivery"
35984
- );
35985
- }).finally(() => processingDeliveryIds.delete(delivery.deliveryId));
35986
- };
35987
- const receiveRuntimeDelivery = (delivery) => {
35988
- const payload = decodeServiceToDaemonMessage(delivery.payload);
35989
- const payloadKind = payload.kind;
35990
- let payloadSessionId = "";
35991
- if (payloadKind === SESSION_CANCEL_KIND) {
35992
- payloadSessionId = payload.sessionId;
35993
- } else if (payloadKind === SESSION_CONFIGURE_KIND) {
35994
- payloadSessionId = payload.sessionId;
35995
- } else if (payloadKind === SESSION_PERMISSION_RESPOND_KIND) {
35996
- payloadSessionId = payload.sessionId;
35997
- } else if (payloadKind === SESSION_ELICITATION_RESPOND_KIND) {
35998
- payloadSessionId = payload.sessionId;
35999
- } else if (payloadKind === SESSION_PROMPT_KIND) {
36000
- payloadSessionId = payload.sessionId;
36001
- } else {
36002
- throw new Error("Runtime delivery contains an unsupported protocol message");
36003
- }
36004
- if (payloadSessionId !== delivery.sessionId) {
36005
- throw new Error("Runtime delivery Session identity does not match its payload");
36006
- }
36007
- const stored = outbox.claimRuntimeDelivery(delivery);
36008
- send(socket, {
36009
- deliveryId: delivery.deliveryId,
36010
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
36011
- sessionId: delivery.sessionId
36012
- });
36013
- processRuntimeDelivery(delivery, stored.state);
36014
- };
36015
- const resumeRuntimeDeliveries = () => {
36016
- for (const stored of outbox.runtimeDeliveries()) {
36017
- const delivery = {
36018
- deliveryId: stored.deliveryId,
36019
- kind: RUNTIME_DELIVERY_KIND,
36020
- payload: stored.payload,
36021
- sessionId: stored.sessionId
36022
- };
36023
- if (stored.state !== "relay_committed") {
36024
- send(socket, {
36025
- deliveryId: stored.deliveryId,
36026
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
36027
- sessionId: stored.sessionId
36028
- });
35199
+ if (first.command.commandId !== command.targetCommandId) {
35200
+ return "queue-target-unavailable";
36029
35201
  }
36030
- processRuntimeDelivery(delivery, stored.state);
35202
+ await waitForTurnCompletion(first, waitSignal);
36031
35203
  }
36032
35204
  };
36033
35205
  const connectionLiveness = new RelayConnectionLiveness(timer, {
@@ -36086,39 +35258,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36086
35258
  try {
36087
35259
  const message = decodeServiceToDaemonMessage(encoded);
36088
35260
  const kind = message.kind;
36089
- if (kind === RUNTIME_DELIVERY_COMMITTED_KIND) {
36090
- const committed = message;
36091
- if (!outbox.markRuntimeDeliveryCommitted(committed.deliveryId, committed.sessionId)) {
36092
- console.warn("Mobius daemon ignored confirmation for an unknown Runtime delivery");
36093
- }
36094
- return;
36095
- }
36096
- if (kind === RUNTIME_DELIVERY_KIND) {
36097
- receiveRuntimeDelivery(message);
36098
- return;
36099
- }
36100
- if (kind === SESSION_EVENT_ACK_KIND) {
36101
- publisher.acknowledge(message);
36102
- return;
36103
- }
36104
- if (kind === SESSION_EVENT_DEFERRED_KIND) {
36105
- publisher.defer(message);
36106
- return;
36107
- }
36108
- if (kind === SESSION_EVENT_REJECTED_KIND) {
36109
- const rejection = message;
36110
- if (publisher.quarantine(rejection)) {
36111
- audit.record({
36112
- commandId: rejection.eventId,
36113
- details: { code: rejection.code },
36114
- event: "session_event_rejected",
36115
- sessionId: rejection.sessionId
36116
- });
36117
- } else {
36118
- console.warn("Mobius daemon ignored a rejection for an unknown session event");
36119
- }
36120
- return;
36121
- }
36122
35261
  if (kind === SESSION_LIVE_HISTORY_LOAD_KIND) {
36123
35262
  const command2 = decodeSessionLiveHistoryLoad(encoded);
36124
35263
  void executeSessionLiveHistoryLoad(
@@ -36596,7 +35735,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36596
35735
  const cancellation = message;
36597
35736
  const turn2 = activeTurns.get(cancellation.commandId);
36598
35737
  if (turn2 === void 0 || !turn2.matches(cancellation)) {
36599
- settleAbandonedTurn(publisher, outbox, audit, cancellation);
35738
+ settleAbandonedTurn(publisher, operations, audit, cancellation);
36600
35739
  return;
36601
35740
  }
36602
35741
  if (!turn2.requestCancellation()) {
@@ -36692,14 +35831,14 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36692
35831
  if (activeTurns.has(command.commandId)) {
36693
35832
  return;
36694
35833
  }
36695
- const receipt = outbox.claimExecution(command.commandId, command.sessionId, encoded);
35834
+ const receipt = operations.claimExecution(command.commandId, command.sessionId, encoded);
36696
35835
  if (receipt.kind === "duplicate") {
36697
35836
  return;
36698
35837
  }
36699
35838
  const turn = new ActiveDaemonTurn(command, receipt.attemptId);
36700
35839
  activeTurns.set(command.commandId, turn);
36701
35840
  void executePrompt(
36702
- outbox,
35841
+ operations,
36703
35842
  publisher,
36704
35843
  command,
36705
35844
  config2,
@@ -36707,30 +35846,20 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36707
35846
  audit,
36708
35847
  sessions,
36709
35848
  receipt.attemptId,
36710
- () => {
36711
- turn.accept();
36712
- if (command.disposition !== SessionPromptDisposition.Steer) {
36713
- activeAttemptIds.set(command.sessionId, receipt.attemptId);
36714
- }
36715
- },
35849
+ turn.accept,
35850
+ (waitSignal) => waitForSessionAvailability(command, waitSignal),
36716
35851
  timer,
36717
35852
  turn.signal,
36718
- turn.recordText
35853
+ turn.recordText,
35854
+ turn.cancellationRequested
36719
35855
  ).catch((error62) => {
36720
35856
  console.error("Mobius daemon turn failed", error62);
36721
35857
  }).finally(() => {
36722
35858
  activeTurns.delete(command.commandId);
36723
- if (activeAttemptIds.get(command.sessionId) === receipt.attemptId) {
36724
- activeAttemptIds.delete(command.sessionId);
36725
- }
36726
35859
  turn.finish();
36727
35860
  });
36728
35861
  } catch (error62) {
36729
35862
  console.error("Mobius daemon rejected a message", error62);
36730
- if (error62 instanceof RuntimeDeliveryInboxCapacityError) {
36731
- failAndClose(error62, 4013, "Runtime delivery queue full", "delivery_backpressure");
36732
- return;
36733
- }
36734
35863
  failAndClose(
36735
35864
  new Error("Relay sent an invalid protocol message", { cause: error62 }),
36736
35865
  4008,
@@ -36748,7 +35877,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36748
35877
  return;
36749
35878
  }
36750
35879
  publisher.connect(socket);
36751
- resumeRuntimeDeliveries();
36752
35880
  },
36753
35881
  (error62) => {
36754
35882
  if (finished) {
@@ -36770,7 +35898,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36770
35898
  turn.abortDaemon();
36771
35899
  }
36772
35900
  publisher.connect(socket);
36773
- resumeRuntimeDeliveries();
36774
35901
  return;
36775
35902
  }
36776
35903
  failAndClose(
@@ -36807,17 +35934,11 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
36807
35934
  stateDirectory
36808
35935
  });
36809
35936
  const sessionStore = new MemoryAcpSessionStore();
36810
- const outbox = new SessionEventOutbox();
36811
- const publisher = new DaemonSessionEventPublisher(outbox, timer);
35937
+ const operations = new DaemonOperationState();
35938
+ const publisher = new DaemonSessionEventPublisher();
36812
35939
  const activeTurns = /* @__PURE__ */ new Map();
36813
- const activeAttemptIds = /* @__PURE__ */ new Map();
36814
35940
  const recordSessionEvent = (sessionId, event) => {
36815
- const attemptId = activeAttemptIds.get(sessionId);
36816
- if (attemptId === void 0) {
36817
- publisher.recordRuntime(sessionId, event);
36818
- return;
36819
- }
36820
- publisher.recordAttempt(sessionId, event, attemptId);
35941
+ publisher.publish(sessionId, event);
36821
35942
  };
36822
35943
  const sessions = new AcpSessionManager(
36823
35944
  new DaemonAcpObserver(recordSessionEvent),
@@ -36922,10 +36043,9 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
36922
36043
  installations,
36923
36044
  installationObserver,
36924
36045
  nativeSessions,
36925
- outbox,
36046
+ operations,
36926
36047
  publisher,
36927
36048
  activeTurns,
36928
- activeAttemptIds,
36929
36049
  connectionEpoch,
36930
36050
  diagnostics,
36931
36051
  () => {
@@ -36971,7 +36091,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
36971
36091
  try {
36972
36092
  publisher.close();
36973
36093
  } finally {
36974
- outbox.close();
36094
+ operations.close();
36975
36095
  }
36976
36096
  }
36977
36097
  }
@@ -36987,7 +36107,7 @@ import { basename as basename7, resolve as resolve6 } from "node:path";
36987
36107
  import { fetch as fetch5 } from "undici";
36988
36108
 
36989
36109
  // src/storage/runtime-installation-store.ts
36990
- import { createHash as createHash5, randomUUID as randomUUID6 } from "node:crypto";
36110
+ import { createHash as createHash5, randomUUID as randomUUID7 } from "node:crypto";
36991
36111
  import { mkdir as mkdir4, open as open5, readdir as readdir3, rename as rename3, unlink, writeFile as writeFile3 } from "node:fs/promises";
36992
36112
  import { dirname as dirname4, join as join17, resolve as resolve5 } from "node:path";
36993
36113
  var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
@@ -37118,10 +36238,10 @@ function parseRelayOrigin(value) {
37118
36238
  return origin;
37119
36239
  }
37120
36240
  function connectionId() {
37121
- return `mcn_${randomUUID6().replaceAll("-", "")}`;
36241
+ return `mcn_${randomUUID7().replaceAll("-", "")}`;
37122
36242
  }
37123
36243
  function installationId() {
37124
- return `min_${randomUUID6().replaceAll("-", "")}`;
36244
+ return `min_${randomUUID7().replaceAll("-", "")}`;
37125
36245
  }
37126
36246
  function channelIndexFileName(channelId) {
37127
36247
  return `mci_${createHash5("sha256").update(channelId).digest("hex")}.json`;
@@ -37233,7 +36353,7 @@ async function readJsonFile(path2, signal, missingCode) {
37233
36353
  async function writeJsonAtomically(path2, value, signal) {
37234
36354
  signal.throwIfAborted();
37235
36355
  const directory = dirname4(path2);
37236
- const temporaryPath = join17(directory, `.${randomUUID6()}.tmp`);
36356
+ const temporaryPath = join17(directory, `.${randomUUID7()}.tmp`);
37237
36357
  try {
37238
36358
  await mkdir4(directory, { mode: 448, recursive: true });
37239
36359
  signal.throwIfAborted();