@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/index.js CHANGED
@@ -19776,6 +19776,8 @@ var WORKSPACE_LIST_KIND = "workspace.list";
19776
19776
  var WORKSPACE_ENTRIES_KIND = "workspace.entries";
19777
19777
  var SESSION_PREPARE_KIND = "session.prepare";
19778
19778
  var SESSION_READY_KIND = "session.ready";
19779
+ var SESSION_QUERY_KIND = "session.query";
19780
+ var SESSION_QUERIED_KIND = "session.queried";
19779
19781
  var SESSION_CONFIGURE_KIND = "session.configure";
19780
19782
  var SESSION_CONFIG_UPDATED_KIND = "session.config.updated";
19781
19783
  var SESSION_USAGE_UPDATED_KIND = "session.usage.updated";
@@ -19817,6 +19819,26 @@ var workspaceEntrySchema = external_exports.strictObject({
19817
19819
  directoryId: DIRECTORY_IDENTIFIER,
19818
19820
  name: external_exports.string().min(1).max(255)
19819
19821
  }).readonly();
19822
+ var sessionMetadataSchema = external_exports.strictObject({
19823
+ additionalDirectories: external_exports.array(workspaceEntrySchema).max(16).readonly(),
19824
+ agentId: IDENTIFIER,
19825
+ directoryId: DIRECTORY_IDENTIFIER,
19826
+ directoryLabel: external_exports.string().min(1).max(2048),
19827
+ prompted: external_exports.boolean(),
19828
+ sessionId: IDENTIFIER,
19829
+ title: external_exports.string().max(500),
19830
+ updatedAt: external_exports.iso.datetime({ offset: true })
19831
+ }).readonly();
19832
+ var sessionQueryCommandSchema = external_exports.strictObject({
19833
+ kind: external_exports.literal(SESSION_QUERY_KIND),
19834
+ requestId: IDENTIFIER,
19835
+ sessionIds: external_exports.array(IDENTIFIER).min(1).max(500).readonly()
19836
+ }).readonly();
19837
+ var sessionsQueriedEventSchema = external_exports.strictObject({
19838
+ entries: external_exports.array(sessionMetadataSchema).max(500).readonly(),
19839
+ kind: external_exports.literal(SESSION_QUERIED_KIND),
19840
+ requestId: IDENTIFIER
19841
+ }).readonly();
19820
19842
  var fileReadCommandSchema = external_exports.strictObject({
19821
19843
  kind: external_exports.literal(FILE_READ_KIND),
19822
19844
  maxBytes: external_exports.number().int().positive().max(128 * 1024 * 1024),
@@ -20360,6 +20382,10 @@ var decodeWorkspaceListCommand = (encoded) => decode3(encoded, workspaceListComm
20360
20382
  var encodeWorkspaceListCommand = (message) => encode3(message, workspaceListCommandSchema);
20361
20383
  var decodeWorkspaceEntriesEvent = (encoded) => decode3(encoded, workspaceEntriesEventSchema);
20362
20384
  var encodeWorkspaceEntriesEvent = (message) => encode3(message, workspaceEntriesEventSchema);
20385
+ var decodeSessionQueryCommand = (encoded) => decode3(encoded, sessionQueryCommandSchema);
20386
+ var encodeSessionQueryCommand = (message) => encode3(message, sessionQueryCommandSchema);
20387
+ var decodeSessionsQueriedEvent = (encoded) => decode3(encoded, sessionsQueriedEventSchema);
20388
+ var encodeSessionsQueriedEvent = (message) => encode3(message, sessionsQueriedEventSchema);
20363
20389
  var decodeSessionPrepareCommand = (encoded) => decode3(encoded, sessionPrepareCommandSchema);
20364
20390
  var encodeSessionPrepareCommand = (message) => encode3(message, sessionPrepareCommandSchema);
20365
20391
  var decodeSessionReadyEvent = (encoded) => decode3(encoded, sessionReadyEventSchema);
@@ -20403,9 +20429,6 @@ var SESSION_CANCEL_KIND = "session.cancel";
20403
20429
  var RUNTIME_LIVENESS_READY_KIND = "runtime.liveness.ready";
20404
20430
  var RUNTIME_HEARTBEAT_KIND = "runtime.heartbeat";
20405
20431
  var RUNTIME_HEARTBEAT_ACK_KIND = "runtime.heartbeat.ack";
20406
- var RUNTIME_DELIVERY_KIND = "runtime.delivery";
20407
- var RUNTIME_DELIVERY_RECEIVED_KIND = "runtime.delivery.received";
20408
- var RUNTIME_DELIVERY_COMMITTED_KIND = "runtime.delivery.committed";
20409
20432
  var SESSION_STARTED_KIND = "session.started";
20410
20433
  var AGENT_MESSAGE_DELTA_KIND = "agent.message.delta";
20411
20434
  var AGENT_ACTIVITY_KIND = "agent.activity";
@@ -20429,7 +20452,6 @@ var DIRECTORY_IDENTIFIER_PATTERN2 = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/;
20429
20452
  var MAX_PROMPT_LENGTH = 1e4;
20430
20453
  var MAX_PROMPT_ATTACHMENT_LENGTH = 6e6;
20431
20454
  var MAX_EVENT_TEXT_LENGTH = 1e5;
20432
- var MAX_RUNTIME_DELIVERY_PAYLOAD_LENGTH = 8 * 1024 * 1024;
20433
20455
  var ACTIVITY_TYPES = /* @__PURE__ */ new Set(["plan", "progress", "reasoning", "tool"]);
20434
20456
  var NARRATION_ACTIVITY_TYPES = /* @__PURE__ */ new Set(["progress", "reasoning"]);
20435
20457
  var ACTIVITY_STATUSES = /* @__PURE__ */ new Set(["pending", "running", "completed", "failed"]);
@@ -20716,45 +20738,21 @@ function decodeRuntimeHeartbeatAckEvent(encoded) {
20716
20738
  kind: RUNTIME_HEARTBEAT_ACK_KIND
20717
20739
  };
20718
20740
  }
20719
- function decodeRuntimeDelivery(encoded) {
20720
- const value = parseJson2(encoded);
20721
- assertExactKeys(value, ["deliveryId", "kind", "payload", "sessionId"]);
20722
- assertKind(value, RUNTIME_DELIVERY_KIND);
20723
- return {
20724
- deliveryId: readIdentifier(value, "deliveryId"),
20725
- kind: RUNTIME_DELIVERY_KIND,
20726
- payload: readString(value, "payload", MAX_RUNTIME_DELIVERY_PAYLOAD_LENGTH),
20727
- sessionId: readIdentifier(value, "sessionId")
20728
- };
20729
- }
20730
- function decodeRuntimeDeliveryReceived(encoded) {
20731
- const value = parseJson2(encoded);
20732
- assertExactKeys(value, ["deliveryId", "kind", "sessionId"]);
20733
- assertKind(value, RUNTIME_DELIVERY_RECEIVED_KIND);
20734
- return {
20735
- deliveryId: readIdentifier(value, "deliveryId"),
20736
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
20737
- sessionId: readIdentifier(value, "sessionId")
20738
- };
20739
- }
20740
- function decodeRuntimeDeliveryCommitted(encoded) {
20741
- const value = parseJson2(encoded);
20742
- assertExactKeys(value, ["deliveryId", "kind", "sessionId"]);
20743
- assertKind(value, RUNTIME_DELIVERY_COMMITTED_KIND);
20744
- return {
20745
- deliveryId: readIdentifier(value, "deliveryId"),
20746
- kind: RUNTIME_DELIVERY_COMMITTED_KIND,
20747
- sessionId: readIdentifier(value, "sessionId")
20748
- };
20749
- }
20750
20741
  function decodeSessionStartedEvent(encoded) {
20751
20742
  const value = parseJson2(encoded);
20752
- assertExactKeys(value, ["commandId", "kind", "attemptId", "sessionId"]);
20743
+ assertExactKeys(value, ["commandId", "epoch", "kind", "attemptId", "prompt", "sequence", "sessionId"]);
20753
20744
  assertKind(value, SESSION_STARTED_KIND);
20745
+ const sequence = readSequence(value, "sequence");
20746
+ if (sequence !== 0) {
20747
+ throw new ProtocolMessageError("Invalid live start sequence");
20748
+ }
20754
20749
  return {
20755
20750
  commandId: readIdentifier(value, "commandId"),
20751
+ epoch: readIdentifier(value, "epoch"),
20756
20752
  kind: SESSION_STARTED_KIND,
20757
20753
  attemptId: readIdentifier(value, "attemptId"),
20754
+ prompt: readText(value, "prompt", MAX_PROMPT_LENGTH),
20755
+ sequence,
20758
20756
  sessionId: readIdentifier(value, "sessionId")
20759
20757
  };
20760
20758
  }
@@ -20852,15 +20850,6 @@ function encodeRuntimeHeartbeatEvent(message) {
20852
20850
  function encodeRuntimeHeartbeatAckEvent(message) {
20853
20851
  return JSON.stringify(decodeRuntimeHeartbeatAckEvent(JSON.stringify(message)));
20854
20852
  }
20855
- function encodeRuntimeDelivery(message) {
20856
- return JSON.stringify(decodeRuntimeDelivery(JSON.stringify(message)));
20857
- }
20858
- function encodeRuntimeDeliveryReceived(message) {
20859
- return JSON.stringify(decodeRuntimeDeliveryReceived(JSON.stringify(message)));
20860
- }
20861
- function encodeRuntimeDeliveryCommitted(message) {
20862
- return JSON.stringify(decodeRuntimeDeliveryCommitted(JSON.stringify(message)));
20863
- }
20864
20853
  function decodeAgentActivityNarrationEvent(encoded) {
20865
20854
  const value = parseJson2(encoded);
20866
20855
  assertExactKeys(value, ["activityId", "activityType", "commandId", "kind", "sequence", "sessionId", "text"]);
@@ -20974,6 +20963,7 @@ var NATIVE_SESSION_RESULT_KIND = "native.session.result";
20974
20963
  var NATIVE_SESSION_CANCEL_KIND = "native.session.cancel";
20975
20964
  var NATIVE_SESSION_TURN_FORK_REQUEST_KIND = "native.session.turn-fork.request";
20976
20965
  var NATIVE_SESSION_TURN_FORK_KIND = "native.session.turn-fork";
20966
+ var ACTIVE_TURN_TEXT_LIMIT = 1e6;
20977
20967
  var identifier = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
20978
20968
  var directoryId = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/);
20979
20969
  var envelope = {
@@ -21066,6 +21056,7 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
21066
21056
  ]);
21067
21057
  var nativeSessionEntrySchema = external_exports.strictObject({
21068
21058
  entryId: identifier,
21059
+ mobiusSessionIds: external_exports.array(identifier).max(500).readonly(),
21069
21060
  nativeSessionId: identifier,
21070
21061
  title: external_exports.string().max(500),
21071
21062
  directoryId,
@@ -21092,7 +21083,7 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
21092
21083
  turn: external_exports.strictObject({
21093
21084
  commandId: identifier,
21094
21085
  prompt: external_exports.string().max(1e5),
21095
- text: external_exports.string().max(1e5),
21086
+ text: external_exports.string().max(ACTIVE_TURN_TEXT_LIMIT),
21096
21087
  truncated: external_exports.boolean(),
21097
21088
  epoch: identifier,
21098
21089
  sequence: external_exports.number().int().nonnegative(),
@@ -21167,65 +21158,17 @@ var encodeNativeSessionTurnForkCommand = (value) => JSON.stringify(nativeSession
21167
21158
 
21168
21159
  // ../protocol/src/session-events.ts
21169
21160
  var SESSION_EVENT_KIND = "session.event";
21170
- var SESSION_EVENT_ACK_KIND = "session.event.ack";
21171
21161
  var SESSION_EVENT_COMMITTED_KIND = "session.event.committed";
21172
- var SESSION_EVENT_DEFERRED_KIND = "session.event.deferred";
21173
- var SESSION_EVENT_REJECTED_KIND = "session.event.rejected";
21174
- var SessionEventRejectionCode = {
21175
- SessionDeleted: "session_deleted",
21176
- SessionNotFound: "session_not_found",
21177
- SessionRejected: "session_rejected"
21178
- };
21179
21162
  var IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
21180
- var CURSOR_PATTERN = /^[A-Za-z0-9_-]{1,512}$/;
21181
21163
  var MAX_RECORDED_EVENT_LENGTH = 8 * 1024 * 1024;
21182
- var DECIMAL_SEQUENCE_PATTERN = /^(?:0|[1-9][0-9]*)$/;
21183
- var eventSourceSchema = external_exports.discriminatedUnion("kind", [
21184
- external_exports.strictObject({
21185
- attemptId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21186
- kind: external_exports.literal("attempt"),
21187
- sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
21188
- }).readonly(),
21189
- external_exports.strictObject({
21190
- kind: external_exports.literal("runtime"),
21191
- sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
21192
- }).readonly()
21193
- ]);
21194
21164
  var eventEnvelopeSchema = external_exports.strictObject({
21195
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21196
21165
  kind: external_exports.literal(SESSION_EVENT_KIND),
21197
21166
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
21198
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21199
- source: eventSourceSchema
21167
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
21200
21168
  }).readonly();
21201
21169
  var committedEventSchema = external_exports.strictObject({
21202
- cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
21203
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21204
21170
  kind: external_exports.literal(SESSION_EVENT_COMMITTED_KIND),
21205
21171
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
21206
- recordedAt: external_exports.string().datetime({ offset: true }),
21207
- sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
21208
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21209
- source: eventSourceSchema
21210
- }).readonly();
21211
- var eventAcknowledgementSchema = external_exports.strictObject({
21212
- cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
21213
- duplicate: external_exports.boolean(),
21214
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21215
- kind: external_exports.literal(SESSION_EVENT_ACK_KIND),
21216
- sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
21217
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
21218
- }).readonly();
21219
- var eventDeferredSchema = external_exports.strictObject({
21220
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21221
- kind: external_exports.literal(SESSION_EVENT_DEFERRED_KIND),
21222
- retryAfterMilliseconds: external_exports.number().int().min(100).max(6e4),
21223
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
21224
- }).readonly();
21225
- var eventRejectionSchema = external_exports.strictObject({
21226
- code: external_exports.enum(SessionEventRejectionCode),
21227
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21228
- kind: external_exports.literal(SESSION_EVENT_REJECTED_KIND),
21229
21172
  sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
21230
21173
  }).readonly();
21231
21174
  function decode5(encoded, schema) {
@@ -21254,12 +21197,6 @@ var encode4 = (message, schema) => {
21254
21197
  };
21255
21198
  var decodeSessionEventEnvelope = (encoded) => decode5(encoded, eventEnvelopeSchema);
21256
21199
  var encodeSessionEventEnvelope = (message) => encode4(message, eventEnvelopeSchema);
21257
- var decodeSessionEventAcknowledgement = (encoded) => decode5(encoded, eventAcknowledgementSchema);
21258
- var encodeSessionEventAcknowledgement = (message) => encode4(message, eventAcknowledgementSchema);
21259
- var decodeSessionEventDeferred = (encoded) => decode5(encoded, eventDeferredSchema);
21260
- var encodeSessionEventDeferred = (message) => encode4(message, eventDeferredSchema);
21261
- var decodeSessionEventRejection = (encoded) => decode5(encoded, eventRejectionSchema);
21262
- var encodeSessionEventRejection = (message) => encode4(message, eventRejectionSchema);
21263
21200
  function decodeRecordedSessionEvent(encoded) {
21264
21201
  const kind = decodeMessageKind(encoded);
21265
21202
  switch (kind) {
@@ -21389,6 +21326,11 @@ var serviceToDaemonSignatures = {
21389
21326
  decodeAgentSettingsDiscoverCommand
21390
21327
  ),
21391
21328
  [FILE_READ_KIND]: defineMessageSignature(FILE_READ_KIND, encodeFileReadCommand, decodeFileReadCommand),
21329
+ [SESSION_QUERY_KIND]: defineMessageSignature(
21330
+ SESSION_QUERY_KIND,
21331
+ encodeSessionQueryCommand,
21332
+ decodeSessionQueryCommand
21333
+ ),
21392
21334
  [NATIVE_SESSION_CANCEL_KIND]: defineMessageSignature(
21393
21335
  NATIVE_SESSION_CANCEL_KIND,
21394
21336
  encodeNativeSessionCancel,
@@ -21404,16 +21346,6 @@ var serviceToDaemonSignatures = {
21404
21346
  encodeNativeSessionTurnForkCommand,
21405
21347
  decodeNativeSessionTurnForkCommand
21406
21348
  ),
21407
- [RUNTIME_DELIVERY_KIND]: defineMessageSignature(
21408
- RUNTIME_DELIVERY_KIND,
21409
- encodeRuntimeDelivery,
21410
- decodeRuntimeDelivery
21411
- ),
21412
- [RUNTIME_DELIVERY_COMMITTED_KIND]: defineMessageSignature(
21413
- RUNTIME_DELIVERY_COMMITTED_KIND,
21414
- encodeRuntimeDeliveryCommitted,
21415
- decodeRuntimeDeliveryCommitted
21416
- ),
21417
21349
  [RUNTIME_HEARTBEAT_ACK_KIND]: defineMessageSignature(
21418
21350
  RUNTIME_HEARTBEAT_ACK_KIND,
21419
21351
  encodeRuntimeHeartbeatAckEvent,
@@ -21439,21 +21371,6 @@ var serviceToDaemonSignatures = {
21439
21371
  encodeSessionElicitationRespondCommand,
21440
21372
  decodeSessionElicitationRespondCommand
21441
21373
  ),
21442
- [SESSION_EVENT_ACK_KIND]: defineMessageSignature(
21443
- SESSION_EVENT_ACK_KIND,
21444
- encodeSessionEventAcknowledgement,
21445
- decodeSessionEventAcknowledgement
21446
- ),
21447
- [SESSION_EVENT_DEFERRED_KIND]: defineMessageSignature(
21448
- SESSION_EVENT_DEFERRED_KIND,
21449
- encodeSessionEventDeferred,
21450
- decodeSessionEventDeferred
21451
- ),
21452
- [SESSION_EVENT_REJECTED_KIND]: defineMessageSignature(
21453
- SESSION_EVENT_REJECTED_KIND,
21454
- encodeSessionEventRejection,
21455
- decodeSessionEventRejection
21456
- ),
21457
21374
  [SESSION_LIVE_HISTORY_LOAD_KIND]: defineMessageSignature(
21458
21375
  SESSION_LIVE_HISTORY_LOAD_KIND,
21459
21376
  encodeSessionLiveHistoryLoad,
@@ -21544,16 +21461,16 @@ var daemonToServiceSignatures = {
21544
21461
  [FILE_CHUNK_KIND]: defineMessageSignature(FILE_CHUNK_KIND, encodeFileChunkEvent, decodeFileChunkEvent),
21545
21462
  [FILE_END_KIND]: defineMessageSignature(FILE_END_KIND, encodeFileEndEvent, decodeFileEndEvent),
21546
21463
  [FILE_FAILED_KIND]: defineMessageSignature(FILE_FAILED_KIND, encodeFileFailedEvent, decodeFileFailedEvent),
21464
+ [SESSION_QUERIED_KIND]: defineMessageSignature(
21465
+ SESSION_QUERIED_KIND,
21466
+ encodeSessionsQueriedEvent,
21467
+ decodeSessionsQueriedEvent
21468
+ ),
21547
21469
  [NATIVE_SESSION_RESULT_KIND]: defineMessageSignature(
21548
21470
  NATIVE_SESSION_RESULT_KIND,
21549
21471
  encodeNativeSessionResult,
21550
21472
  decodeNativeSessionResult
21551
21473
  ),
21552
- [RUNTIME_DELIVERY_RECEIVED_KIND]: defineMessageSignature(
21553
- RUNTIME_DELIVERY_RECEIVED_KIND,
21554
- encodeRuntimeDeliveryReceived,
21555
- decodeRuntimeDeliveryReceived
21556
- ),
21557
21474
  [RUNTIME_HEARTBEAT_KIND]: defineMessageSignature(
21558
21475
  RUNTIME_HEARTBEAT_KIND,
21559
21476
  encodeRuntimeHeartbeatEvent,
@@ -22609,13 +22526,17 @@ var AcpStoredSession = class {
22609
22526
  nativeSessionId;
22610
22527
  prompted;
22611
22528
  sessionId;
22612
- constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted) {
22529
+ title;
22530
+ updatedAt;
22531
+ constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted, title2, updatedAt = (/* @__PURE__ */ new Date()).toISOString()) {
22613
22532
  this.additionalDirectories = [...additionalDirectories];
22614
22533
  this.agentId = agentId;
22615
22534
  this.cwd = cwd;
22616
22535
  this.nativeSessionId = nativeSessionId;
22617
22536
  this.prompted = prompted;
22618
22537
  this.sessionId = sessionId;
22538
+ this.title = title2;
22539
+ this.updatedAt = updatedAt;
22619
22540
  }
22620
22541
  };
22621
22542
  var AcpStoredSessionLookup = class {
@@ -22640,6 +22561,7 @@ var MemoryAcpSessionStore = class {
22640
22561
  findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
22641
22562
  (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
22642
22563
  );
22564
+ list = () => [...this.#sessions.values()].toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt));
22643
22565
  markDeleted = (agentId, nativeSessionId) => {
22644
22566
  const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
22645
22567
  for (const id of ids) {
@@ -24783,7 +24705,8 @@ var AcpProcessSession = class _AcpProcessSession {
24783
24705
  nativeSessionIdSchema.parse(origin.nativeSessionId),
24784
24706
  this.#cwd,
24785
24707
  this.#additionalDirectories,
24786
- true
24708
+ true,
24709
+ ""
24787
24710
  )
24788
24711
  ) : this.#store.read(this.#mobiusSessionId)
24789
24712
  );
@@ -24859,6 +24782,7 @@ var AcpProcessSession = class _AcpProcessSession {
24859
24782
  } else if (stored instanceof FoundAcpStoredSession && stored.session.agentId === this.#agentId && stored.session.cwd === this.#cwd && arraysEqual(stored.session.additionalDirectories, this.#additionalDirectories)) {
24860
24783
  this.selectNativeSession(stored.session.nativeSessionId);
24861
24784
  this.#prompted = stored.session.prompted;
24785
+ this.#sessionTitle = stored.session.title;
24862
24786
  this.#restored = true;
24863
24787
  if (this.#capabilities.resumeSession) {
24864
24788
  lifecycleResponse = await this.#metrics.measure(
@@ -24942,18 +24866,17 @@ var AcpProcessSession = class _AcpProcessSession {
24942
24866
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
24943
24867
  await this.#updateTail;
24944
24868
  signal.throwIfAborted();
24945
- if (this.#prompted) {
24946
- this.#store.write(
24947
- new AcpStoredSession(
24948
- this.#mobiusSessionId,
24949
- this.#agentId,
24950
- this.#nativeSessionId,
24951
- this.#cwd,
24952
- this.#additionalDirectories,
24953
- true
24954
- )
24955
- );
24956
- }
24869
+ this.#store.write(
24870
+ new AcpStoredSession(
24871
+ this.#mobiusSessionId,
24872
+ this.#agentId,
24873
+ this.#nativeSessionId,
24874
+ this.#cwd,
24875
+ this.#additionalDirectories,
24876
+ this.#prompted,
24877
+ this.#sessionTitle ?? ""
24878
+ )
24879
+ );
24957
24880
  };
24958
24881
  listNativeSessions = async (cursor, signal) => {
24959
24882
  if (!this.#capabilities.listSessions) {
@@ -25005,7 +24928,15 @@ var AcpProcessSession = class _AcpProcessSession {
25005
24928
  }
25006
24929
  const previousSessionId = this.#mobiusSessionId;
25007
24930
  this.#store.write(
25008
- new AcpStoredSession(sessionId, this.#agentId, sessionId, this.#cwd, this.#additionalDirectories, false)
24931
+ new AcpStoredSession(
24932
+ sessionId,
24933
+ this.#agentId,
24934
+ sessionId,
24935
+ this.#cwd,
24936
+ this.#additionalDirectories,
24937
+ false,
24938
+ ""
24939
+ )
25009
24940
  );
25010
24941
  this.#store.remove(previousSessionId);
25011
24942
  this.#mobiusSessionId = sessionId;
@@ -25127,6 +25058,9 @@ var AcpProcessSession = class _AcpProcessSession {
25127
25058
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
25128
25059
  }
25129
25060
  const prompt = this.buildPrompt(options);
25061
+ if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
25062
+ this.#sessionTitle = truncate2(options.prompt, 500);
25063
+ }
25130
25064
  this.#store.write(
25131
25065
  new AcpStoredSession(
25132
25066
  this.#mobiusSessionId,
@@ -25134,7 +25068,8 @@ var AcpProcessSession = class _AcpProcessSession {
25134
25068
  this.#nativeSessionId,
25135
25069
  this.#cwd,
25136
25070
  this.#additionalDirectories,
25137
- true
25071
+ true,
25072
+ this.#sessionTitle
25138
25073
  )
25139
25074
  );
25140
25075
  this.#prompted = true;
@@ -25562,6 +25497,19 @@ var AcpProcessSession = class _AcpProcessSession {
25562
25497
  if (Object.hasOwn(update, "updatedAt")) {
25563
25498
  this.#sessionUpdatedAt = truncate2(update.updatedAt ?? "", 128);
25564
25499
  }
25500
+ if (this.#nativeSessionId.length > 0) {
25501
+ this.#store.write(
25502
+ new AcpStoredSession(
25503
+ this.#mobiusSessionId,
25504
+ this.#agentId,
25505
+ this.#nativeSessionId,
25506
+ this.#cwd,
25507
+ this.#additionalDirectories,
25508
+ this.#prompted,
25509
+ this.#sessionTitle ?? ""
25510
+ )
25511
+ );
25512
+ }
25565
25513
  await this.#getObserver().onInfo({
25566
25514
  kind: SESSION_INFO_UPDATED_KIND,
25567
25515
  sessionId: this.#mobiusSessionId,
@@ -26464,6 +26412,11 @@ var AcpSessionManager = class {
26464
26412
  )
26465
26413
  ]);
26466
26414
  };
26415
+ findSessions = (sessionIds) => sessionIds.flatMap((sessionId) => {
26416
+ const stored = this.#store.read(sessionId);
26417
+ return stored instanceof FoundAcpStoredSession ? [stored.session] : [];
26418
+ });
26419
+ findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
26467
26420
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
26468
26421
  createNativeSession = async (options) => {
26469
26422
  const temporarySessionId = `new-${crypto.randomUUID()}`;
@@ -31552,7 +31505,7 @@ function isRuntimeRelayRevocation(closeCode, closeReason) {
31552
31505
  }
31553
31506
 
31554
31507
  // src/run-daemon.ts
31555
- import { randomUUID as randomUUID6 } from "node:crypto";
31508
+ import { randomUUID as randomUUID7 } from "node:crypto";
31556
31509
  import { styleText } from "node:util";
31557
31510
  import { WebSocket as WebSocket5 } from "undici";
31558
31511
 
@@ -33551,21 +33504,17 @@ function daemonActivity(command, activity2) {
33551
33504
  toolKind: activity2.toolKind
33552
33505
  };
33553
33506
  }
33554
- function reportFailure(publisher, command, code, message, attemptId) {
33555
- publisher.recordAttempt(
33556
- command.sessionId,
33557
- {
33558
- code,
33559
- commandId: command.commandId,
33560
- kind: SESSION_FAILED_KIND,
33561
- message,
33562
- sessionId: command.sessionId
33563
- },
33564
- attemptId
33565
- );
33507
+ function reportFailure(publisher, command, code, message) {
33508
+ publisher.publish(command.sessionId, {
33509
+ code,
33510
+ commandId: command.commandId,
33511
+ kind: SESSION_FAILED_KIND,
33512
+ message,
33513
+ sessionId: command.sessionId
33514
+ });
33566
33515
  }
33567
- function settleAbandonedTurn(publisher, outbox, audit, cancellation) {
33568
- const attemptId = outbox.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
33516
+ function settleAbandonedTurn(publisher, operations, audit, cancellation) {
33517
+ const attemptId = operations.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
33569
33518
  if (attemptId === null) {
33570
33519
  console.warn("Mobius daemon ignored cancellation for an inactive turn");
33571
33520
  return;
@@ -33579,10 +33528,9 @@ function settleAbandonedTurn(publisher, outbox, audit, cancellation) {
33579
33528
  publisher,
33580
33529
  cancellation,
33581
33530
  "agent_execution_abandoned",
33582
- "The local Agent execution was abandoned before it completed",
33583
- attemptId
33531
+ "The local Agent execution was abandoned before it completed"
33584
33532
  );
33585
- outbox.transitionExecution(cancellation.commandId, "failed");
33533
+ operations.transitionExecution(cancellation.commandId, "failed");
33586
33534
  }
33587
33535
  function operationErrorCode(error62) {
33588
33536
  if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof PromptArtifactError) {
@@ -33712,7 +33660,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
33712
33660
  event: "session_configured",
33713
33661
  sessionId: command.sessionId
33714
33662
  });
33715
- publisher.recordRuntime(command.sessionId, {
33663
+ publisher.publish(command.sessionId, {
33716
33664
  configOptions,
33717
33665
  kind: "session.config.updated",
33718
33666
  requestId: command.requestId,
@@ -33737,7 +33685,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
33737
33685
  };
33738
33686
  if (command.transient !== true) {
33739
33687
  metrics.measureSync("readiness-commit", () => {
33740
- publisher.recordRuntime(command.sessionId, event);
33688
+ publisher.publish(command.sessionId, event);
33741
33689
  });
33742
33690
  }
33743
33691
  return event;
@@ -33885,7 +33833,7 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
33885
33833
  event: "session_configured",
33886
33834
  sessionId: command.sessionId
33887
33835
  });
33888
- publisher.recordRuntime(command.sessionId, {
33836
+ publisher.publish(command.sessionId, {
33889
33837
  configOptions,
33890
33838
  kind: "session.config.updated",
33891
33839
  requestId: command.requestId,
@@ -33898,26 +33846,22 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
33898
33846
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
33899
33847
  }
33900
33848
  }
33901
- async function executePrompt(outbox, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, timer, signal, recordLiveText) {
33849
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, waitForSessionAvailability, timer, signal, recordLiveText, cancellationRequested) {
33902
33850
  const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
33903
- publisher.recordAttempt(command.sessionId, daemonActivity(command, activity2), attemptId);
33851
+ publisher.publish(command.sessionId, daemonActivity(command, activity2));
33904
33852
  });
33905
33853
  const narration = new CoalescingNarrationPublisher(
33906
33854
  timer,
33907
33855
  (increment) => {
33908
- publisher.recordAttempt(
33909
- command.sessionId,
33910
- {
33911
- activityId: increment.activityId,
33912
- activityType: increment.activityType,
33913
- commandId: command.commandId,
33914
- kind: AGENT_ACTIVITY_NARRATION_KIND,
33915
- sequence: increment.sequence,
33916
- sessionId: command.sessionId,
33917
- text: increment.text
33918
- },
33919
- attemptId
33920
- );
33856
+ publisher.publish(command.sessionId, {
33857
+ activityId: increment.activityId,
33858
+ activityType: increment.activityType,
33859
+ commandId: command.commandId,
33860
+ kind: AGENT_ACTIVITY_NARRATION_KIND,
33861
+ sequence: increment.sequence,
33862
+ sessionId: command.sessionId,
33863
+ text: increment.text
33864
+ });
33921
33865
  },
33922
33866
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
33923
33867
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -33926,19 +33870,15 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33926
33870
  timer,
33927
33871
  (messageId, delta) => {
33928
33872
  const stream = recordLiveText(delta);
33929
- publisher.recordAttempt(
33930
- command.sessionId,
33931
- {
33932
- commandId: command.commandId,
33933
- epoch: stream.epoch,
33934
- kind: AGENT_MESSAGE_DELTA_KIND,
33935
- messageId,
33936
- sequence: stream.sequence,
33937
- sessionId: command.sessionId,
33938
- text: delta
33939
- },
33940
- attemptId
33941
- );
33873
+ publisher.publish(command.sessionId, {
33874
+ commandId: command.commandId,
33875
+ epoch: stream.epoch,
33876
+ kind: AGENT_MESSAGE_DELTA_KIND,
33877
+ messageId,
33878
+ sequence: stream.sequence,
33879
+ sessionId: command.sessionId,
33880
+ text: delta
33881
+ });
33942
33882
  },
33943
33883
  AGENT_TEXT_COALESCING_MILLISECONDS,
33944
33884
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -33946,13 +33886,17 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33946
33886
  try {
33947
33887
  const resolved = await resolveSessionDirectories(
33948
33888
  directories,
33949
- config2.bindingId,
33889
+ command.bindingId,
33950
33890
  command.directoryId,
33951
33891
  command.additionalDirectoryIds,
33952
33892
  signal
33953
33893
  );
33954
33894
  const agent = config2.catalog.find(command.agentId);
33955
- if (command.disposition === SessionPromptDisposition.Queue && !outbox.isTerminalExecution(command.targetCommandId, command.sessionId)) {
33895
+ const availability = await waitForSessionAvailability(signal);
33896
+ if (availability === "busy") {
33897
+ throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
33898
+ }
33899
+ if (availability === "queue-target-unavailable") {
33956
33900
  throw new AcpExecutionError(
33957
33901
  "The queued prompt target is unavailable",
33958
33902
  {},
@@ -33992,18 +33936,17 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33992
33936
  event: "session_authorized",
33993
33937
  sessionId: command.sessionId
33994
33938
  });
33995
- outbox.transitionExecution(command.commandId, "running");
33996
- publisher.recordAttempt(
33997
- command.sessionId,
33998
- {
33999
- commandId: command.commandId,
34000
- kind: SESSION_STARTED_KIND,
34001
- attemptId,
34002
- sessionId: command.sessionId
34003
- },
34004
- attemptId
34005
- );
34006
- activateAttempt();
33939
+ operations.transitionExecution(command.commandId, "running");
33940
+ const stream = activateAttempt();
33941
+ publisher.publish(command.sessionId, {
33942
+ commandId: command.commandId,
33943
+ epoch: stream.epoch,
33944
+ kind: SESSION_STARTED_KIND,
33945
+ attemptId,
33946
+ prompt: command.prompt,
33947
+ sequence: stream.sequence,
33948
+ sessionId: command.sessionId
33949
+ });
34007
33950
  const attachments = await resolvePromptArtifacts(config2, command, signal);
34008
33951
  let stopReason;
34009
33952
  if (command.disposition === SessionPromptDisposition.Steer) {
@@ -34048,17 +33991,13 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
34048
33991
  text.flush();
34049
33992
  narration.flush();
34050
33993
  activities.flush();
34051
- publisher.recordAttempt(
34052
- command.sessionId,
34053
- {
34054
- commandId: command.commandId,
34055
- kind: SESSION_COMPLETED_KIND,
34056
- sessionId: command.sessionId,
34057
- stopReason
34058
- },
34059
- attemptId
34060
- );
34061
- outbox.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
33994
+ publisher.publish(command.sessionId, {
33995
+ commandId: command.commandId,
33996
+ kind: SESSION_COMPLETED_KIND,
33997
+ sessionId: command.sessionId,
33998
+ stopReason
33999
+ });
34000
+ operations.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
34062
34001
  audit.record({
34063
34002
  commandId: command.commandId,
34064
34003
  event: stopReason === "cancelled" ? "session_cancelled" : "session_completed",
@@ -34068,6 +34007,21 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
34068
34007
  text.flush();
34069
34008
  narration.flush();
34070
34009
  activities.flush();
34010
+ if (signal.aborted && cancellationRequested()) {
34011
+ publisher.publish(command.sessionId, {
34012
+ commandId: command.commandId,
34013
+ kind: SESSION_COMPLETED_KIND,
34014
+ sessionId: command.sessionId,
34015
+ stopReason: "cancelled"
34016
+ });
34017
+ operations.transitionExecution(command.commandId, "cancelled");
34018
+ audit.record({
34019
+ commandId: command.commandId,
34020
+ event: "session_cancelled",
34021
+ sessionId: command.sessionId
34022
+ });
34023
+ return;
34024
+ }
34071
34025
  audit.record({
34072
34026
  commandId: command.commandId,
34073
34027
  event: "session_failed",
@@ -34078,10 +34032,9 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
34078
34032
  publisher,
34079
34033
  command,
34080
34034
  code === "session_operation_failed" ? "agent_execution_failed" : code,
34081
- code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62),
34082
- attemptId
34035
+ code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62)
34083
34036
  );
34084
- outbox.transitionExecution(command.commandId, "failed");
34037
+ operations.transitionExecution(command.commandId, "failed");
34085
34038
  console.error("Mobius daemon command failed", error62);
34086
34039
  }
34087
34040
  }
@@ -34223,7 +34176,6 @@ var DaemonInstallationObserver = class {
34223
34176
  import { randomUUID as randomUUID3 } from "node:crypto";
34224
34177
  import { fetch as fetch5 } from "undici";
34225
34178
  var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
34226
- var ACTIVE_TURN_TEXT_LIMIT = 1e5;
34227
34179
  var ActiveDaemonTurn = class {
34228
34180
  attemptId;
34229
34181
  command;
@@ -34246,6 +34198,7 @@ var ActiveDaemonTurn = class {
34246
34198
  finish = () => this.#finished.resolve();
34247
34199
  accept = () => {
34248
34200
  this.#accepted = true;
34201
+ return { epoch: this.#epoch, sequence: 0 };
34249
34202
  };
34250
34203
  recordText = (delta) => {
34251
34204
  this.#sequence += 1;
@@ -34268,11 +34221,16 @@ var ActiveDaemonTurn = class {
34268
34221
  matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
34269
34222
  requestCancellation = () => {
34270
34223
  if (this.#cancellationRequested) {
34271
- return false;
34224
+ return "already-requested";
34272
34225
  }
34273
34226
  this.#cancellationRequested = true;
34274
- return true;
34227
+ if (!this.#accepted) {
34228
+ this.#controller.abort(new Error("The queued Agent turn was cancelled"));
34229
+ return "pending";
34230
+ }
34231
+ return "running";
34275
34232
  };
34233
+ cancellationRequested = () => this.#cancellationRequested;
34276
34234
  get signal() {
34277
34235
  return this.#controller.signal;
34278
34236
  }
@@ -34998,6 +34956,7 @@ var NativeSessionService = class {
34998
34956
  });
34999
34957
  return {
35000
34958
  entryId,
34959
+ mobiusSessionIds: this.#sessions.findLinkedSessions(command.agentId, info.sessionId).filter((session) => session.prompted && session.cwd === authorized.cwd).map((session) => session.sessionId),
35001
34960
  nativeSessionId: info.sessionId,
35002
34961
  title: info.title ?? "Untitled session",
35003
34962
  directoryId: authorized.directoryId,
@@ -35215,6 +35174,29 @@ var NativeSessionService = class {
35215
35174
  history: opened.history
35216
35175
  };
35217
35176
  };
35177
+ querySessions = async (sessionIds, signal) => {
35178
+ const entries = [];
35179
+ for (const session of this.#sessions.findSessions(sessionIds)) {
35180
+ signal.throwIfAborted();
35181
+ const directory = await this.#directories.identify(this.#config.bindingId, session.cwd, signal);
35182
+ const additionalDirectories = [];
35183
+ for (const path2 of session.additionalDirectories) {
35184
+ const identified = await this.#directories.identify(this.#config.bindingId, path2, signal);
35185
+ additionalDirectories.push({ directoryId: identified.directoryId, name: identified.name });
35186
+ }
35187
+ entries.push({
35188
+ additionalDirectories,
35189
+ agentId: session.agentId,
35190
+ directoryId: directory.directoryId,
35191
+ directoryLabel: directory.label,
35192
+ prompted: session.prompted,
35193
+ sessionId: session.sessionId,
35194
+ title: session.title || "Untitled session",
35195
+ updatedAt: session.updatedAt
35196
+ });
35197
+ }
35198
+ return entries;
35199
+ };
35218
35200
  executeTurnFork = async (command, signal) => {
35219
35201
  signal.throwIfAborted();
35220
35202
  const cwd = await this.#directories.resolve(this.#config.bindingId, command.directoryId, signal);
@@ -35467,6 +35449,75 @@ function connectRelay(url2, signal) {
35467
35449
  });
35468
35450
  }
35469
35451
 
35452
+ // src/relay-connection/daemon-operation-state.ts
35453
+ import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
35454
+ var MAX_TERMINAL_RECEIPTS = 1024;
35455
+ function isTerminal(state) {
35456
+ return state === "succeeded" || state === "failed" || state === "cancelled";
35457
+ }
35458
+ var DaemonOperationState = class {
35459
+ #executions = /* @__PURE__ */ new Map();
35460
+ #terminalCount = 0;
35461
+ claimExecution = (commandId, sessionId, commandJson) => {
35462
+ const commandHash = createHash5("sha256").update(commandJson).digest("hex");
35463
+ const existing = this.#executions.get(commandId);
35464
+ if (existing !== void 0) {
35465
+ if (existing.sessionId !== sessionId || existing.commandHash !== commandHash) {
35466
+ throw new Error("The daemon command identity conflicts with its in-memory receipt");
35467
+ }
35468
+ return { attemptId: existing.attemptId, commandId, kind: "duplicate", state: existing.state };
35469
+ }
35470
+ const attemptId = randomUUID5();
35471
+ this.#executions.set(commandId, { attemptId, commandHash, sessionId, state: "dispatching" });
35472
+ return { attemptId, commandId, kind: "accepted", state: "dispatching" };
35473
+ };
35474
+ transitionExecution = (commandId, state) => {
35475
+ const current = this.#executions.get(commandId);
35476
+ if (current === void 0) {
35477
+ throw new Error("The daemon execution receipt does not exist");
35478
+ }
35479
+ if (current.state === state) {
35480
+ return;
35481
+ }
35482
+ const allowed = current.state === "dispatching" && (state === "running" || state === "failed" || state === "cancelled") || current.state === "running" && isTerminal(state);
35483
+ if (!allowed) {
35484
+ throw new Error("The daemon execution transition is invalid");
35485
+ }
35486
+ this.#executions.set(commandId, { ...current, state });
35487
+ if (isTerminal(state)) {
35488
+ this.#terminalCount += 1;
35489
+ this.pruneTerminalReceipts();
35490
+ }
35491
+ };
35492
+ /** Receipts disappear when the daemon process exits. */
35493
+ findUnsettledAttemptId = (commandId, sessionId) => {
35494
+ const receipt = this.#executions.get(commandId);
35495
+ return receipt?.sessionId === sessionId && !isTerminal(receipt.state) ? receipt.attemptId : null;
35496
+ };
35497
+ isTerminalExecution = (commandId, sessionId) => {
35498
+ const receipt = this.#executions.get(commandId);
35499
+ return receipt?.sessionId === sessionId && isTerminal(receipt.state);
35500
+ };
35501
+ close = () => {
35502
+ this.#executions.clear();
35503
+ this.#terminalCount = 0;
35504
+ };
35505
+ pruneTerminalReceipts = () => {
35506
+ if (this.#terminalCount <= MAX_TERMINAL_RECEIPTS) {
35507
+ return;
35508
+ }
35509
+ for (const [commandId, receipt] of this.#executions) {
35510
+ if (isTerminal(receipt.state)) {
35511
+ this.#executions.delete(commandId);
35512
+ this.#terminalCount -= 1;
35513
+ if (this.#terminalCount <= MAX_TERMINAL_RECEIPTS) {
35514
+ return;
35515
+ }
35516
+ }
35517
+ }
35518
+ };
35519
+ };
35520
+
35470
35521
  // src/relay-connection/diagnostics.ts
35471
35522
  var MAX_DIAGNOSTIC_TEXT_LENGTH = 256;
35472
35523
  function sanitizeDiagnosticText(value) {
@@ -35640,7 +35691,7 @@ var RelayConnectionDiagnostics = class {
35640
35691
  };
35641
35692
 
35642
35693
  // src/relay-connection/liveness.ts
35643
- import { randomUUID as randomUUID5 } from "node:crypto";
35694
+ import { randomUUID as randomUUID6 } from "node:crypto";
35644
35695
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
35645
35696
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
35646
35697
  var RelayLivenessState = class {
@@ -35729,7 +35780,7 @@ var RelayConnectionLiveness = class {
35729
35780
  }
35730
35781
  throw new Error("Heartbeat was scheduled in an invalid state");
35731
35782
  }
35732
- const heartbeatId = randomUUID5();
35783
+ const heartbeatId = randomUUID6();
35733
35784
  this.#state = new AwaitingHeartbeatAckState(
35734
35785
  heartbeatId,
35735
35786
  this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
@@ -35745,765 +35796,54 @@ var RelayConnectionLiveness = class {
35745
35796
  };
35746
35797
  };
35747
35798
 
35748
- // src/relay-connection/session-event-outbox.ts
35749
- import { createHash as createHash5 } from "node:crypto";
35750
- import { DatabaseSync } from "node:sqlite";
35751
- var DEFAULT_OUTBOX_LIMITS = {
35752
- criticalEventBytes: 40 * 1024 * 1024,
35753
- runtimeDeliveryBytes: 32 * 1024 * 1024,
35754
- runtimeDeliveryCount: 64,
35755
- standardEventBytes: 32 * 1024 * 1024
35756
- };
35757
- var MAX_TERMINAL_RECEIPTS = 1024;
35758
- var SessionEventOutboxCapacityError = class extends Error {
35759
- code = "session_event_outbox_full";
35760
- constructor() {
35761
- super("The in-memory Session event outbox is full");
35762
- this.name = "SessionEventOutboxCapacityError";
35763
- }
35764
- };
35765
- var RuntimeDeliveryInboxCapacityError = class extends Error {
35766
- code = "runtime_delivery_inbox_full";
35767
- constructor() {
35768
- super("The in-memory Runtime delivery inbox is full");
35769
- this.name = "RuntimeDeliveryInboxCapacityError";
35770
- }
35771
- };
35772
- var StoredRuntimeDelivery = class {
35773
- deliveryId;
35774
- duplicate;
35775
- payload;
35776
- sessionId;
35777
- state;
35778
- constructor(deliveryId, sessionId, payload, state, duplicate) {
35779
- this.deliveryId = deliveryId;
35780
- this.duplicate = duplicate;
35781
- this.payload = payload;
35782
- this.sessionId = sessionId;
35783
- this.state = state;
35784
- }
35785
- };
35786
- function readPendingEnvelope(row) {
35787
- if (typeof row !== "object" || row === null || Array.isArray(row)) {
35788
- throw new Error("SQLite returned an invalid session event outbox row");
35789
- }
35790
- const envelope2 = Reflect.get(row, "envelope_json");
35791
- if (typeof envelope2 !== "string") {
35792
- throw new Error("SQLite returned an invalid session event envelope");
35793
- }
35794
- return envelope2;
35795
- }
35796
- function rowNumber(row, field) {
35797
- const value = typeof row === "object" && row !== null ? Reflect.get(row, field) : void 0;
35798
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
35799
- throw new Error(`SQLite returned an invalid ${field} value`);
35800
- }
35801
- return value;
35802
- }
35803
- function rowString(row, field) {
35804
- const value = typeof row === "object" && row !== null ? Reflect.get(row, field) : void 0;
35805
- if (typeof value !== "string" || value.length === 0) {
35806
- throw new Error(`SQLite returned an invalid ${field} value`);
35807
- }
35808
- return value;
35809
- }
35810
- var SessionEventOutbox = class {
35811
- #database;
35812
- #limits;
35813
- constructor(limits = DEFAULT_OUTBOX_LIMITS) {
35814
- validateLimits(limits);
35815
- this.#limits = limits;
35816
- this.#database = new DatabaseSync(":memory:");
35817
- this.#database.exec(`
35818
- CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
35819
- ordinal INTEGER PRIMARY KEY AUTOINCREMENT,
35820
- event_id TEXT NOT NULL UNIQUE,
35821
- session_id TEXT NOT NULL,
35822
- source_key TEXT NOT NULL,
35823
- byte_length INTEGER NOT NULL,
35824
- envelope_json TEXT NOT NULL
35825
- ) STRICT;
35826
- CREATE INDEX IF NOT EXISTS relay_session_event_outbox_order
35827
- ON relay_session_event_outbox(ordinal);
35828
- CREATE TABLE IF NOT EXISTS relay_turn_receipts (
35829
- command_id TEXT PRIMARY KEY,
35830
- session_id TEXT NOT NULL,
35831
- command_hash TEXT NOT NULL,
35832
- attempt_id TEXT NOT NULL,
35833
- state TEXT NOT NULL CHECK (
35834
- state IN ('dispatching', 'running', 'succeeded', 'failed', 'cancelled')
35835
- )
35836
- ) STRICT;
35837
- CREATE TABLE IF NOT EXISTS relay_session_event_outbox_state (
35838
- singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
35839
- event_count INTEGER NOT NULL,
35840
- total_bytes INTEGER NOT NULL,
35841
- next_source_seq INTEGER NOT NULL
35842
- ) STRICT;
35843
- INSERT OR IGNORE INTO relay_session_event_outbox_state (
35844
- singleton, event_count, total_bytes, next_source_seq
35845
- ) VALUES (1, 0, 0, 1);
35846
- CREATE TABLE IF NOT EXISTS relay_runtime_deliveries (
35847
- delivery_id TEXT PRIMARY KEY,
35848
- session_id TEXT NOT NULL,
35849
- payload_json TEXT NOT NULL,
35850
- payload_bytes INTEGER NOT NULL,
35851
- state TEXT NOT NULL CHECK (
35852
- state IN ('received', 'relay_committed', 'processed')
35853
- ),
35854
- received_at INTEGER NOT NULL
35855
- ) STRICT;
35856
- `);
35857
- this.#database.exec(`
35858
- CREATE INDEX IF NOT EXISTS relay_session_event_outbox_source_order
35859
- ON relay_session_event_outbox(source_key, ordinal);
35860
- `);
35861
- }
35862
- claimExecution = (commandId, sessionId, commandJson) => {
35863
- const commandHash = createHash5("sha256").update(commandJson).digest("hex");
35864
- this.#database.exec("BEGIN IMMEDIATE");
35865
- try {
35866
- const existing = this.#database.prepare(
35867
- `SELECT session_id, command_hash, attempt_id, state
35868
- FROM relay_turn_receipts WHERE command_id = ?`
35869
- ).get(commandId);
35870
- if (typeof existing === "object" && existing !== null) {
35871
- const storedSessionId = Reflect.get(existing, "session_id");
35872
- const storedCommandHash = Reflect.get(existing, "command_hash");
35873
- const attemptId2 = Reflect.get(existing, "attempt_id");
35874
- const state = Reflect.get(existing, "state");
35875
- if (storedSessionId !== sessionId || storedCommandHash !== commandHash || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
35876
- throw new Error("The daemon command identity conflicts with its in-memory receipt");
35877
- }
35878
- this.#database.exec("COMMIT");
35879
- return { attemptId: attemptId2, commandId, kind: "duplicate", state };
35880
- }
35881
- const attemptId = crypto.randomUUID();
35882
- this.#database.prepare(
35883
- `INSERT INTO relay_turn_receipts (
35884
- command_id, session_id, command_hash, attempt_id, state
35885
- ) VALUES (?, ?, ?, ?, 'dispatching')`
35886
- ).run(commandId, sessionId, commandHash, attemptId);
35887
- this.#database.exec("COMMIT");
35888
- return {
35889
- attemptId,
35890
- commandId,
35891
- kind: "accepted",
35892
- state: "dispatching"
35893
- };
35894
- } catch (error62) {
35895
- this.#database.exec("ROLLBACK");
35896
- throw error62;
35897
- }
35898
- };
35899
- transitionExecution = (commandId, state) => {
35900
- const row = this.#database.prepare(`SELECT state FROM relay_turn_receipts WHERE command_id = ?`).get(commandId);
35901
- const current = typeof row === "object" && row !== null ? Reflect.get(row, "state") : void 0;
35902
- if (!isDaemonExecutionState(current)) {
35903
- throw new Error("The daemon execution receipt does not exist");
35904
- }
35905
- if (current === state) {
35906
- return;
35907
- }
35908
- const allowed = current === "dispatching" && (state === "running" || state === "failed" || state === "cancelled") || current === "running" && (state === "succeeded" || state === "failed" || state === "cancelled");
35909
- if (!allowed) {
35910
- throw new Error("The daemon execution transition is invalid");
35911
- }
35912
- this.#database.prepare(`UPDATE relay_turn_receipts SET state = ? WHERE command_id = ?`).run(state, commandId);
35913
- if (state === "succeeded" || state === "failed" || state === "cancelled") {
35914
- this.#database.prepare(
35915
- `DELETE FROM relay_turn_receipts
35916
- WHERE state IN ('succeeded', 'failed', 'cancelled')
35917
- AND rowid NOT IN (
35918
- SELECT rowid FROM relay_turn_receipts
35919
- WHERE state IN ('succeeded', 'failed', 'cancelled')
35920
- ORDER BY rowid DESC LIMIT ?
35921
- )`
35922
- ).run(MAX_TERMINAL_RECEIPTS);
35923
- }
35924
- };
35925
- /**
35926
- * The Attempt this live Runtime claimed for a command that has not reached a terminal state.
35927
- * Receipts disappear when the daemon process exits.
35928
- */
35929
- findUnsettledAttemptId = (commandId, sessionId) => {
35930
- const row = this.#database.prepare(`SELECT attempt_id, state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
35931
- if (typeof row !== "object" || row === null) {
35932
- return null;
35933
- }
35934
- const attemptId = Reflect.get(row, "attempt_id");
35935
- const state = Reflect.get(row, "state");
35936
- if (typeof attemptId !== "string" || attemptId.length === 0 || !isDaemonExecutionState(state)) {
35937
- return null;
35938
- }
35939
- return state === "dispatching" || state === "running" ? attemptId : null;
35940
- };
35941
- isTerminalExecution = (commandId, sessionId) => {
35942
- const row = this.#database.prepare(`SELECT state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
35943
- const state = typeof row === "object" && row !== null ? Reflect.get(row, "state") : void 0;
35944
- return state === "succeeded" || state === "failed" || state === "cancelled";
35945
- };
35946
- acknowledge = (acknowledgement) => this.#removeAcknowledgedEvent(acknowledgement.eventId, acknowledgement.sessionId);
35947
- quarantine = (rejection) => {
35948
- this.#database.exec("BEGIN IMMEDIATE");
35949
- try {
35950
- const stored = this.#database.prepare(
35951
- `SELECT byte_length FROM relay_session_event_outbox
35952
- WHERE event_id = ? AND session_id = ?`
35953
- ).get(rejection.eventId, rejection.sessionId);
35954
- if (stored === void 0) {
35955
- this.#database.exec("COMMIT");
35956
- return false;
35957
- }
35958
- const byteLength = rowNumber(stored, "byte_length");
35959
- const deletion = this.#database.prepare(
35960
- `DELETE FROM relay_session_event_outbox
35961
- WHERE event_id = ? AND session_id = ?`
35962
- ).run(rejection.eventId, rejection.sessionId);
35963
- if (deletion.changes !== 1) {
35964
- throw new Error("The rejected session event could not be removed from the in-memory outbox");
35965
- }
35966
- this.#decrementEventState(byteLength);
35967
- this.#database.exec("COMMIT");
35968
- return true;
35969
- } catch (error62) {
35970
- this.#database.exec("ROLLBACK");
35971
- throw error62;
35972
- }
35973
- };
35974
- close = () => {
35975
- this.#database.close();
35976
- };
35977
- enqueue = (sessionId, payload, attemptId = null) => {
35978
- return this.#enqueueBounded(sessionId, payload, attemptId ?? "", this.#limits.standardEventBytes);
35979
- };
35980
- enqueueCritical = (sessionId, payload, attemptId = "") => this.#enqueueBounded(sessionId, payload, attemptId, this.#limits.criticalEventBytes);
35981
- /**
35982
- * Bytes still available to standard Session events. The daemon uses this to shed
35983
- * superseded streaming events instead of filling the in-memory outbox, so a long Turn
35984
- * behind a slow Relay cannot make the next enqueue throw.
35985
- */
35986
- standardCapacityRemaining = () => {
35987
- const state = this.#database.prepare(
35988
- `SELECT total_bytes
35989
- FROM relay_session_event_outbox_state
35990
- WHERE singleton = 1`
35991
- ).get();
35992
- return this.#limits.standardEventBytes - rowNumber(state, "total_bytes");
35993
- };
35994
- claimRuntimeDelivery = (delivery) => {
35995
- const payloadBytes = new TextEncoder().encode(delivery.payload).byteLength;
35996
- this.#database.exec("BEGIN IMMEDIATE");
35997
- try {
35998
- const existing = this.#database.prepare(
35999
- `SELECT session_id, payload_json, state
36000
- FROM relay_runtime_deliveries
36001
- WHERE delivery_id = ?`
36002
- ).get(delivery.deliveryId);
36003
- if (existing !== void 0) {
36004
- const sessionId = rowString(existing, "session_id");
36005
- const payload = rowString(existing, "payload_json");
36006
- const state = runtimeDeliveryState(existing);
36007
- if (sessionId !== delivery.sessionId || payload !== delivery.payload) {
36008
- throw new Error("The Runtime delivery identity conflicts with its in-memory receipt");
36009
- }
36010
- this.#database.exec("COMMIT");
36011
- return new StoredRuntimeDelivery(delivery.deliveryId, sessionId, payload, state, true);
36012
- }
36013
- const usage = this.#database.prepare(
36014
- `SELECT COUNT(*) AS delivery_count,
36015
- COALESCE(SUM(payload_bytes), 0) AS delivery_bytes
36016
- FROM relay_runtime_deliveries`
36017
- ).get();
36018
- if (rowNumber(usage, "delivery_count") + 1 > this.#limits.runtimeDeliveryCount || rowNumber(usage, "delivery_bytes") + payloadBytes > this.#limits.runtimeDeliveryBytes) {
36019
- throw new RuntimeDeliveryInboxCapacityError();
36020
- }
36021
- this.#database.prepare(
36022
- `INSERT INTO relay_runtime_deliveries (
36023
- delivery_id, session_id, payload_json, payload_bytes, state, received_at
36024
- ) VALUES (?, ?, ?, ?, 'received', ?)`
36025
- ).run(delivery.deliveryId, delivery.sessionId, delivery.payload, payloadBytes, Date.now());
36026
- this.#database.exec("COMMIT");
36027
- return new StoredRuntimeDelivery(
36028
- delivery.deliveryId,
36029
- delivery.sessionId,
36030
- delivery.payload,
36031
- "received",
36032
- false
36033
- );
36034
- } catch (error62) {
36035
- this.#database.exec("ROLLBACK");
36036
- throw error62;
36037
- }
36038
- };
36039
- markRuntimeDeliveryCommitted = (deliveryId, sessionId) => {
36040
- this.#database.exec("BEGIN IMMEDIATE");
36041
- try {
36042
- const row = this.#database.prepare(
36043
- `SELECT state FROM relay_runtime_deliveries
36044
- WHERE delivery_id = ? AND session_id = ?`
36045
- ).get(deliveryId, sessionId);
36046
- if (row === void 0) {
36047
- this.#database.exec("COMMIT");
36048
- return false;
36049
- }
36050
- const state = runtimeDeliveryState(row);
36051
- if (state === "processed") {
36052
- this.#database.prepare(`DELETE FROM relay_runtime_deliveries WHERE delivery_id = ?`).run(deliveryId);
36053
- } else if (state === "received") {
36054
- this.#database.prepare(`UPDATE relay_runtime_deliveries SET state = 'relay_committed' WHERE delivery_id = ?`).run(deliveryId);
36055
- }
36056
- this.#database.exec("COMMIT");
36057
- return true;
36058
- } catch (error62) {
36059
- this.#database.exec("ROLLBACK");
36060
- throw error62;
36061
- }
36062
- };
36063
- markRuntimeDeliveryProcessed = (deliveryId, sessionId) => {
36064
- this.#database.exec("BEGIN IMMEDIATE");
36065
- try {
36066
- const row = this.#database.prepare(
36067
- `SELECT state FROM relay_runtime_deliveries
36068
- WHERE delivery_id = ? AND session_id = ?`
36069
- ).get(deliveryId, sessionId);
36070
- if (row === void 0) {
36071
- this.#database.exec("COMMIT");
36072
- return false;
36073
- }
36074
- const state = runtimeDeliveryState(row);
36075
- if (state === "relay_committed") {
36076
- this.#database.prepare(`DELETE FROM relay_runtime_deliveries WHERE delivery_id = ?`).run(deliveryId);
36077
- } else if (state === "received") {
36078
- this.#database.prepare(`UPDATE relay_runtime_deliveries SET state = 'processed' WHERE delivery_id = ?`).run(deliveryId);
36079
- }
36080
- this.#database.exec("COMMIT");
36081
- return true;
36082
- } catch (error62) {
36083
- this.#database.exec("ROLLBACK");
36084
- throw error62;
36085
- }
36086
- };
36087
- runtimeDeliveries = () => this.#database.prepare(
36088
- `SELECT delivery_id, session_id, payload_json, state
36089
- FROM relay_runtime_deliveries
36090
- ORDER BY received_at, delivery_id`
36091
- ).all().map(
36092
- (row) => new StoredRuntimeDelivery(
36093
- rowString(row, "delivery_id"),
36094
- rowString(row, "session_id"),
36095
- rowString(row, "payload_json"),
36096
- runtimeDeliveryState(row),
36097
- true
36098
- )
36099
- );
36100
- #enqueueBounded = (sessionId, payload, attemptId, maximumEventBytes) => {
36101
- const sourceKey = attemptId.length === 0 ? `runtime:${sessionId}` : `attempt:${sessionId}:${attemptId}`;
36102
- this.#database.exec("BEGIN IMMEDIATE");
36103
- try {
36104
- const state = this.#database.prepare(
36105
- `SELECT total_bytes, next_source_seq
36106
- FROM relay_session_event_outbox_state
36107
- WHERE singleton = 1`
36108
- ).get();
36109
- const nextSourceSeq = rowNumber(state, "next_source_seq");
36110
- if (nextSourceSeq < 1 || !Number.isSafeInteger(nextSourceSeq + 1)) {
36111
- throw new Error("SQLite returned an invalid event source sequence");
36112
- }
36113
- const envelope2 = {
36114
- eventId: crypto.randomUUID(),
36115
- kind: SESSION_EVENT_KIND,
36116
- payload,
36117
- sessionId,
36118
- source: attemptId.length === 0 ? { kind: "runtime", sourceSeq: nextSourceSeq.toString() } : {
36119
- attemptId,
36120
- kind: "attempt",
36121
- sourceSeq: nextSourceSeq.toString()
36122
- }
36123
- };
36124
- const encoded = encodeSessionEventEnvelope(envelope2);
36125
- const byteLength = new TextEncoder().encode(encoded).byteLength;
36126
- if (rowNumber(state, "total_bytes") + byteLength > maximumEventBytes) {
36127
- throw new SessionEventOutboxCapacityError();
36128
- }
36129
- this.#database.prepare(
36130
- `INSERT INTO relay_session_event_outbox (
36131
- event_id, session_id, source_key, byte_length, envelope_json
36132
- ) VALUES (?, ?, ?, ?, ?)`
36133
- ).run(envelope2.eventId, envelope2.sessionId, sourceKey, byteLength, encoded);
36134
- this.#database.prepare(
36135
- `UPDATE relay_session_event_outbox_state
36136
- SET event_count = event_count + 1,
36137
- total_bytes = total_bytes + ?,
36138
- next_source_seq = next_source_seq + 1
36139
- WHERE singleton = 1`
36140
- ).run(byteLength);
36141
- this.#database.exec("COMMIT");
36142
- return encoded;
36143
- } catch (error62) {
36144
- this.#database.exec("ROLLBACK");
36145
- throw error62;
36146
- }
36147
- };
36148
- #removeAcknowledgedEvent = (eventId, sessionId) => {
36149
- this.#database.exec("BEGIN IMMEDIATE");
36150
- try {
36151
- const stored = this.#database.prepare(
36152
- `SELECT byte_length FROM relay_session_event_outbox
36153
- WHERE event_id = ? AND session_id = ?`
36154
- ).get(eventId, sessionId);
36155
- if (stored === void 0) {
36156
- this.#database.exec("COMMIT");
36157
- return false;
36158
- }
36159
- const byteLength = rowNumber(stored, "byte_length");
36160
- const deletion = this.#database.prepare(
36161
- `DELETE FROM relay_session_event_outbox
36162
- WHERE event_id = ? AND session_id = ?`
36163
- ).run(eventId, sessionId);
36164
- if (deletion.changes !== 1) {
36165
- throw new Error("The acknowledged session event could not be removed from the in-memory outbox");
36166
- }
36167
- this.#decrementEventState(byteLength);
36168
- this.#database.exec("COMMIT");
36169
- return true;
36170
- } catch (error62) {
36171
- this.#database.exec("ROLLBACK");
36172
- throw error62;
36173
- }
36174
- };
36175
- #decrementEventState = (byteLength) => {
36176
- const result = this.#database.prepare(
36177
- `UPDATE relay_session_event_outbox_state
36178
- SET event_count = event_count - 1,
36179
- total_bytes = total_bytes - ?
36180
- WHERE singleton = 1 AND event_count > 0 AND total_bytes >= ?`
36181
- ).run(byteLength, byteLength);
36182
- if (result.changes !== 1) {
36183
- throw new Error("The Session event outbox capacity state is inconsistent");
36184
- }
36185
- };
36186
- pending = () => this.#database.prepare(
36187
- `SELECT envelope_json
36188
- FROM relay_session_event_outbox
36189
- ORDER BY ordinal`
36190
- ).all().map(readPendingEnvelope);
36191
- pendingBatch = (limit) => {
36192
- if (!Number.isSafeInteger(limit) || limit < 1) {
36193
- throw new Error("Session event replay batch limit must be a positive integer");
36194
- }
36195
- return this.#database.prepare(
36196
- `WITH ranked_events AS (
36197
- SELECT ordinal,
36198
- ROW_NUMBER() OVER (
36199
- PARTITION BY source_key
36200
- ORDER BY ordinal
36201
- ) AS source_position
36202
- FROM relay_session_event_outbox
36203
- )
36204
- SELECT outbox.envelope_json
36205
- FROM ranked_events AS ranked
36206
- INNER JOIN relay_session_event_outbox AS outbox
36207
- ON outbox.ordinal = ranked.ordinal
36208
- ORDER BY ranked.source_position, outbox.ordinal
36209
- LIMIT ?`
36210
- ).all(limit).map(readPendingEnvelope);
36211
- };
36212
- pendingSourceHeads = (limit, excludedEventIds, excludedSourceKeys) => {
36213
- if (!Number.isSafeInteger(limit) || limit < 1) {
36214
- throw new Error("Session event replay batch limit must be a positive integer");
36215
- }
36216
- const exclusions = [];
36217
- const parameters = [];
36218
- if (excludedEventIds.length > 0) {
36219
- exclusions.push(`event_id NOT IN (${excludedEventIds.map(() => "?").join(", ")})`);
36220
- parameters.push(...excludedEventIds);
36221
- }
36222
- if (excludedSourceKeys.length > 0) {
36223
- exclusions.push(`source_key NOT IN (${excludedSourceKeys.map(() => "?").join(", ")})`);
36224
- parameters.push(...excludedSourceKeys);
36225
- }
36226
- parameters.push(limit.toString());
36227
- const where = exclusions.length === 0 ? "" : `WHERE ${exclusions.join(" AND ")}`;
36228
- return this.#database.prepare(
36229
- `WITH available_events AS (
36230
- SELECT ordinal, source_key
36231
- FROM relay_session_event_outbox
36232
- ${where}
36233
- ), ranked_events AS (
36234
- SELECT ordinal,
36235
- ROW_NUMBER() OVER (
36236
- PARTITION BY source_key
36237
- ORDER BY ordinal
36238
- ) AS source_position
36239
- FROM available_events
36240
- )
36241
- SELECT outbox.envelope_json
36242
- FROM ranked_events AS ranked
36243
- INNER JOIN relay_session_event_outbox AS outbox
36244
- ON outbox.ordinal = ranked.ordinal
36245
- WHERE ranked.source_position = 1
36246
- ORDER BY outbox.ordinal
36247
- LIMIT ?`
36248
- ).all(...parameters).map(readPendingEnvelope);
36249
- };
36250
- };
36251
- function validateLimits(limits) {
36252
- const values = [
36253
- limits.criticalEventBytes,
36254
- limits.runtimeDeliveryBytes,
36255
- limits.runtimeDeliveryCount,
36256
- limits.standardEventBytes
36257
- ];
36258
- if (values.some((value) => !Number.isSafeInteger(value) || value < 1)) {
36259
- throw new Error("Session event outbox limits must be positive integers");
36260
- }
36261
- if (limits.criticalEventBytes < limits.standardEventBytes) {
36262
- throw new Error("Critical Session event capacity must include the standard capacity");
36263
- }
36264
- }
36265
- function runtimeDeliveryState(row) {
36266
- const state = rowString(row, "state");
36267
- if (state !== "received" && state !== "relay_committed" && state !== "processed") {
36268
- throw new Error("SQLite returned an invalid Runtime delivery state");
36269
- }
36270
- return state;
36271
- }
36272
- function isDaemonExecutionState(value) {
36273
- return value === "cancelled" || value === "dispatching" || value === "failed" || value === "running" || value === "succeeded";
36274
- }
36275
-
36276
35799
  // src/relay-connection/session-event-publisher.ts
36277
35800
  import { WebSocket as WebSocket4 } from "undici";
36278
- var DaemonSessionEventConnectionState = class {
36279
- };
36280
- var DisconnectedDaemonSessionEventState = class extends DaemonSessionEventConnectionState {
36281
- disconnect = () => this;
36282
- matches = () => false;
36283
- send = () => false;
36284
- };
36285
- var ConnectedDaemonSessionEventState = class extends DaemonSessionEventConnectionState {
36286
- #socket;
36287
- constructor(socket) {
36288
- super();
36289
- this.#socket = socket;
36290
- }
36291
- disconnect = (socket) => socket === this.#socket ? new DisconnectedDaemonSessionEventState() : this;
36292
- matches = (socket) => socket === this.#socket;
36293
- send = (message) => {
36294
- if (this.#socket.readyState !== WebSocket4.OPEN) {
36295
- return false;
36296
- }
36297
- try {
36298
- this.#socket.send(encodeDaemonToServiceMessage(message));
36299
- return true;
36300
- } catch {
36301
- return false;
36302
- }
36303
- };
36304
- };
36305
- var SESSION_EVENT_REPLAY_WINDOW = 16;
36306
- var SESSION_EVENT_SOURCE_REPLAY_WINDOW = 4;
36307
- var SESSION_EVENT_REPLAY_BYTE_LIMIT = 32 * 1024 * 1024;
36308
- function reservesSessionEventCapacity(event) {
36309
- if (event.kind === SESSION_COMPLETED_KIND || event.kind === SESSION_FAILED_KIND) {
36310
- return true;
36311
- }
36312
- return event.kind === AGENT_ACTIVITY_KIND && (event.activityType === "progress" || event.activityType === "reasoning") && (event.status === "completed" || event.status === "failed");
36313
- }
36314
- var InFlightSessionEvent = class {
36315
- byteLength;
36316
- sourceKey;
36317
- constructor(sourceKey, byteLength) {
36318
- this.byteLength = byteLength;
36319
- this.sourceKey = sourceKey;
36320
- }
36321
- };
36322
- function sessionEventSourceKey(envelope2) {
36323
- return envelope2.source.kind === "attempt" ? `attempt:${envelope2.sessionId}:${envelope2.source.attemptId}` : `runtime:${envelope2.sessionId}`;
36324
- }
35801
+ var MAX_LIVE_EVENT_BUFFERED_BYTES = 16 * 1024 * 1024;
36325
35802
  var DaemonSessionEventPublisher = class {
36326
- #outbox;
36327
- #inFlightEvents = /* @__PURE__ */ new Map();
36328
- #pausedSources = /* @__PURE__ */ new Map();
36329
- #shedEventKinds = /* @__PURE__ */ new Set();
36330
- #timer;
36331
- #inFlightBytes = 0;
36332
- #connection = new DisconnectedDaemonSessionEventState();
36333
- constructor(outbox, timer) {
36334
- this.#outbox = outbox;
36335
- this.#timer = timer;
36336
- }
35803
+ #socket = null;
35804
+ #reportedDrop = false;
36337
35805
  connect = (socket) => {
36338
- this.#connection = new ConnectedDaemonSessionEventState(socket);
36339
- this.#clearInFlight();
36340
- this.#publishNextBatch();
35806
+ this.#socket = socket;
35807
+ this.#reportedDrop = false;
36341
35808
  };
36342
35809
  disconnect = (socket) => {
36343
- if (!this.#connection.matches(socket)) {
36344
- return;
36345
- }
36346
- this.#connection = this.#connection.disconnect(socket);
36347
- this.#clearInFlight();
36348
- };
36349
- recordAttempt = (sessionId, event, attemptId) => {
36350
- const encoded = encodeRecordedSessionEvent(event);
36351
- if (reservesSessionEventCapacity(event)) {
36352
- this.#enqueueReserved(sessionId, encoded, attemptId, event.kind);
36353
- } else {
36354
- this.#enqueueStandard(sessionId, encoded, attemptId, event.kind);
36355
- }
36356
- this.#publishNextBatch();
36357
- };
36358
- recordRuntime = (sessionId, event) => {
36359
- this.#enqueueStandard(sessionId, encodeRecordedSessionEvent(event), "", event.kind);
36360
- this.#publishNextBatch();
36361
- };
36362
- /**
36363
- * Enqueue a standard event, shedding it instead of ending the daemon when the
36364
- * in-memory outbox is full.
36365
- *
36366
- * A capacity error used to escape the coalescing timer that publishes activities,
36367
- * so the process exited and every restart died on the same retained backlog. A full
36368
- * outbox is a recoverable runtime condition, not a fatal one: narration increments are
36369
- * superseded by the completed snapshot, so they are shed first, and any other streaming
36370
- * event is shed only at the wall rather than terminating the daemon.
36371
- */
36372
- #enqueueStandard = (sessionId, encoded, attemptId, kind) => {
36373
- if (kind === AGENT_ACTIVITY_NARRATION_KIND && this.#outbox.standardCapacityRemaining() <= 0) {
36374
- this.#reportShedEvent(kind);
36375
- return;
36376
- }
36377
- try {
36378
- this.#outbox.enqueue(sessionId, encoded, attemptId);
36379
- } catch (error62) {
36380
- if (!(error62 instanceof SessionEventOutboxCapacityError)) {
36381
- throw error62;
36382
- }
36383
- this.#reportShedEvent(kind);
36384
- }
36385
- };
36386
- /**
36387
- * Enqueue on the reserved budget, degrading to a reported drop instead of raising.
36388
- * Streaming events are shed before this budget is reached, so a Turn's terminal
36389
- * events and the completed snapshot that carries its narration still land; a drop
36390
- * here is the last resort for a backlog no acknowledgement can drain.
36391
- */
36392
- #enqueueReserved = (sessionId, encoded, attemptId, kind) => {
36393
- try {
36394
- this.#outbox.enqueueCritical(sessionId, encoded, attemptId);
36395
- } catch (error62) {
36396
- if (!(error62 instanceof SessionEventOutboxCapacityError)) {
36397
- throw error62;
36398
- }
36399
- this.#reportShedEvent(kind);
36400
- }
36401
- };
36402
- #reportShedEvent = (kind) => {
36403
- if (this.#shedEventKinds.has(kind)) {
36404
- return;
35810
+ if (this.#socket === socket) {
35811
+ this.#socket = null;
36405
35812
  }
36406
- this.#shedEventKinds.add(kind);
36407
- console.warn(`Mobius daemon is dropping queued "${kind}" events because the Session event outbox is full`);
36408
35813
  };
36409
- acknowledge = (acknowledgement) => {
36410
- if (!this.#outbox.acknowledge(acknowledgement)) {
35814
+ publish = (sessionId, event) => {
35815
+ const socket = this.#socket;
35816
+ if (socket === null || socket.readyState !== WebSocket4.OPEN) {
35817
+ this.#reportDrop();
36411
35818
  return;
36412
35819
  }
36413
- this.#removeInFlight(acknowledgement.eventId);
36414
- this.#publishNextBatch();
36415
- };
36416
- quarantine = (rejection) => {
36417
- const quarantined = this.#outbox.quarantine(rejection);
36418
- if (!quarantined) {
36419
- return false;
36420
- }
36421
- this.#removeInFlight(rejection.eventId);
36422
- this.#publishNextBatch();
36423
- return true;
36424
- };
36425
- defer = (deferred) => {
36426
- const inFlight = this.#inFlightEvents.get(deferred.eventId);
36427
- if (inFlight === void 0) {
35820
+ if (socket.bufferedAmount >= MAX_LIVE_EVENT_BUFFERED_BYTES) {
35821
+ this.#socket = null;
35822
+ socket.close(1013, "Live event backpressure");
35823
+ this.#reportDrop();
36428
35824
  return;
36429
35825
  }
36430
- this.#clearInFlightSource(inFlight.sourceKey);
36431
- if (!this.#pausedSources.has(inFlight.sourceKey)) {
36432
- this.#pausedSources.set(
36433
- inFlight.sourceKey,
36434
- this.#timer.schedule(() => {
36435
- this.#pausedSources.delete(inFlight.sourceKey);
36436
- this.#publishNextBatch();
36437
- }, deferred.retryAfterMilliseconds)
35826
+ try {
35827
+ socket.send(
35828
+ encodeDaemonToServiceMessage({
35829
+ kind: SESSION_EVENT_KIND,
35830
+ payload: encodeRecordedSessionEvent(event),
35831
+ sessionId
35832
+ })
36438
35833
  );
35834
+ } catch {
35835
+ this.#reportDrop();
36439
35836
  }
36440
- this.#publishNextBatch();
36441
35837
  };
36442
35838
  close = () => {
36443
- for (const task of this.#pausedSources.values()) {
36444
- task.cancel();
36445
- }
36446
- this.#pausedSources.clear();
36447
- this.#clearInFlight();
36448
- };
36449
- #publishNextBatch = () => {
36450
- while (this.#inFlightEvents.size < SESSION_EVENT_REPLAY_WINDOW) {
36451
- const sourceCounts = /* @__PURE__ */ new Map();
36452
- for (const inFlight of this.#inFlightEvents.values()) {
36453
- sourceCounts.set(inFlight.sourceKey, (sourceCounts.get(inFlight.sourceKey) ?? 0) + 1);
36454
- }
36455
- const saturatedSources = [...sourceCounts.entries()].filter(([, count]) => count >= SESSION_EVENT_SOURCE_REPLAY_WINDOW).map(([sourceKey]) => sourceKey);
36456
- const batch = this.#outbox.pendingSourceHeads(
36457
- SESSION_EVENT_REPLAY_WINDOW - this.#inFlightEvents.size,
36458
- [...this.#inFlightEvents.keys()],
36459
- [...this.#pausedSources.keys(), ...saturatedSources]
36460
- );
36461
- let sent = 0;
36462
- for (const encoded of batch) {
36463
- const envelope2 = decodeSessionEventEnvelope(encoded);
36464
- const sourceKey = sessionEventSourceKey(envelope2);
36465
- const sourceCount = sourceCounts.get(sourceKey) ?? 0;
36466
- if (sourceCount >= SESSION_EVENT_SOURCE_REPLAY_WINDOW) {
36467
- continue;
36468
- }
36469
- const byteLength = new TextEncoder().encode(encoded).byteLength;
36470
- if (this.#inFlightBytes + byteLength > SESSION_EVENT_REPLAY_BYTE_LIMIT) {
36471
- continue;
36472
- }
36473
- if (!this.#connection.send(envelope2)) {
36474
- this.#clearInFlight();
36475
- return;
36476
- }
36477
- this.#inFlightEvents.set(envelope2.eventId, new InFlightSessionEvent(sourceKey, byteLength));
36478
- this.#inFlightBytes += byteLength;
36479
- sourceCounts.set(sourceKey, sourceCount + 1);
36480
- sent += 1;
36481
- }
36482
- if (sent === 0) {
36483
- return;
36484
- }
36485
- }
35839
+ this.#socket = null;
36486
35840
  };
36487
- #removeInFlight = (eventId) => {
36488
- const inFlight = this.#inFlightEvents.get(eventId);
36489
- if (inFlight === void 0) {
35841
+ #reportDrop = () => {
35842
+ if (this.#reportedDrop) {
36490
35843
  return;
36491
35844
  }
36492
- this.#inFlightEvents.delete(eventId);
36493
- this.#inFlightBytes -= inFlight.byteLength;
36494
- };
36495
- #clearInFlight = () => {
36496
- this.#inFlightEvents.clear();
36497
- this.#inFlightBytes = 0;
36498
- };
36499
- #clearInFlightSource = (sourceKey) => {
36500
- for (const [eventId, inFlight] of this.#inFlightEvents) {
36501
- if (inFlight.sourceKey !== sourceKey) {
36502
- continue;
36503
- }
36504
- this.#inFlightEvents.delete(eventId);
36505
- this.#inFlightBytes -= inFlight.byteLength;
36506
- }
35845
+ this.#reportedDrop = true;
35846
+ console.warn("Mobius daemon dropped live Session events while the Relay was unavailable");
36507
35847
  };
36508
35848
  };
36509
35849
 
@@ -36577,7 +35917,7 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
36577
35917
  {
36578
35918
  agentId: agent.id,
36579
35919
  kind: AGENT_INSTALL_REQUEST_KIND,
36580
- requestId: `automatic-integration-${randomUUID6()}`
35920
+ requestId: `automatic-integration-${randomUUID7()}`
36581
35921
  },
36582
35922
  signal
36583
35923
  );
@@ -36622,9 +35962,8 @@ async function refreshAgentCatalog(config2, resolveEnvironment, signal) {
36622
35962
  throw error62;
36623
35963
  }
36624
35964
  }
36625
- async function runRelayConnection(config2, directories, audit, sessions, installations, installationObserver, nativeSessions, outbox, publisher, activeTurns, activeAttemptIds, connectionEpoch, diagnostics, onConnected, signal, timer, resolveAgentCatalogEnvironment) {
35965
+ async function runRelayConnection(config2, directories, audit, sessions, installations, installationObserver, nativeSessions, operations, publisher, activeTurns, connectionEpoch, diagnostics, onConnected, signal, timer, resolveAgentCatalogEnvironment) {
36626
35966
  const relayUrl = new URL(config2.relayUrl);
36627
- relayUrl.searchParams.set("deliveryReceipts", "1");
36628
35967
  relayUrl.searchParams.set("liveness", "1");
36629
35968
  const socket = await connectRelay(relayUrl, signal);
36630
35969
  const reconnectingTurns = [...activeTurns.values()];
@@ -36675,215 +36014,48 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36675
36014
  closeRelaySocket(socket, code, reason);
36676
36015
  rejectConnection(failure2);
36677
36016
  };
36678
- const processingDeliveryIds = /* @__PURE__ */ new Set();
36679
- const processDeliveredPrompt = async (delivery, command, trackActiveAttempt, execute) => {
36680
- if (command.sessionId !== delivery.sessionId) {
36681
- throw new Error("Runtime delivery Session identity does not match its payload");
36682
- }
36683
- const active = activeTurns.get(command.commandId);
36684
- if (active !== void 0) {
36685
- await active.completion;
36686
- return;
36687
- }
36688
- const receipt = outbox.claimExecution(command.commandId, command.sessionId, delivery.payload);
36689
- if (receipt.kind === "duplicate") {
36690
- if (receipt.state === "running") {
36691
- reportFailure(
36692
- publisher,
36693
- command,
36694
- "agent_execution_interrupted",
36695
- "The local Agent execution was interrupted before it completed",
36696
- receipt.attemptId
36697
- );
36698
- outbox.transitionExecution(command.commandId, "failed");
36699
- return;
36700
- }
36701
- if (receipt.state !== "dispatching") {
36702
- return;
36703
- }
36704
- }
36705
- const turn = new ActiveDaemonTurn(command, receipt.attemptId);
36706
- activeTurns.set(command.commandId, turn);
36707
- const activateAttempt = () => {
36708
- turn.accept();
36709
- if (trackActiveAttempt) {
36710
- activeAttemptIds.set(command.sessionId, receipt.attemptId);
36711
- }
36712
- };
36713
- try {
36714
- await execute(receipt.attemptId, activateAttempt, turn.signal, turn);
36715
- } finally {
36716
- activeTurns.delete(command.commandId);
36717
- if (activeAttemptIds.get(command.sessionId) === receipt.attemptId) {
36718
- activeAttemptIds.delete(command.sessionId);
36719
- }
36720
- turn.finish();
36721
- }
36017
+ const waitForTurnCompletion = (turn, waitSignal) => {
36018
+ waitSignal.throwIfAborted();
36019
+ return new Promise((resolve9, reject2) => {
36020
+ let settled = false;
36021
+ const finish = (result) => {
36022
+ if (settled) {
36023
+ return;
36024
+ }
36025
+ settled = true;
36026
+ waitSignal.removeEventListener("abort", onAbort);
36027
+ if (result.kind === "completed") {
36028
+ resolve9();
36029
+ } else {
36030
+ reject2(result.error);
36031
+ }
36032
+ };
36033
+ const onAbort = () => finish({ error: waitSignal.reason, kind: "failed" });
36034
+ waitSignal.addEventListener("abort", onAbort, { once: true });
36035
+ void turn.completion.then(
36036
+ () => finish({ kind: "completed" }),
36037
+ (error62) => finish({ error: error62, kind: "failed" })
36038
+ );
36039
+ });
36722
36040
  };
36723
- const processDeliveredPayload = async (delivery) => {
36724
- const message = decodeServiceToDaemonMessage(delivery.payload);
36725
- const kind = message.kind;
36726
- if (kind === SESSION_CANCEL_KIND) {
36727
- const cancellation = message;
36728
- if (cancellation.sessionId !== delivery.sessionId) {
36729
- throw new Error("Runtime delivery Session identity does not match its payload");
36730
- }
36731
- const turn = activeTurns.get(cancellation.commandId);
36732
- if (turn === void 0 || !turn.matches(cancellation)) {
36733
- settleAbandonedTurn(publisher, outbox, audit, cancellation);
36734
- return;
36735
- }
36736
- if (!turn.requestCancellation()) {
36737
- return;
36738
- }
36739
- audit.record({
36740
- commandId: cancellation.commandId,
36741
- event: "session_cancellation_requested",
36742
- sessionId: cancellation.sessionId
36743
- });
36744
- await sessions.cancelPrompt(cancellation.sessionId);
36745
- return;
36041
+ const waitForSessionAvailability = async (command, waitSignal) => {
36042
+ if (command.disposition === SessionPromptDisposition.Steer) {
36043
+ return "available";
36746
36044
  }
36747
- if (kind === SESSION_CONFIGURE_KIND) {
36748
- const command = message;
36749
- if (command.sessionId !== delivery.sessionId) {
36750
- throw new Error("Runtime delivery Session identity does not match its payload");
36751
- }
36752
- await executeSessionConfigure(
36753
- publisher,
36754
- socket,
36755
- command,
36756
- config2,
36757
- directories,
36758
- audit,
36759
- sessions,
36760
- connectionController.signal
36045
+ for (; ; ) {
36046
+ const first = [...activeTurns.values()].find(
36047
+ (turn) => turn.command.sessionId === command.sessionId && turn.command.disposition !== SessionPromptDisposition.Steer
36761
36048
  );
36762
- return;
36763
- }
36764
- if (kind === SESSION_PERMISSION_RESPOND_KIND) {
36765
- const command = message;
36766
- if (command.sessionId !== delivery.sessionId) {
36767
- throw new Error("Runtime delivery Session identity does not match its payload");
36768
- }
36769
- try {
36770
- await sessions.respondPermission(command);
36771
- audit.record({
36772
- commandId: command.interactionId,
36773
- event: "session_permission_resolved",
36774
- sessionId: command.sessionId
36775
- });
36776
- } catch (error62) {
36777
- reportOperationFailure(socket, command.interactionId, command.sessionId, error62);
36778
- }
36779
- return;
36780
- }
36781
- if (kind === SESSION_ELICITATION_RESPOND_KIND) {
36782
- const command = message;
36783
- if (command.sessionId !== delivery.sessionId) {
36784
- throw new Error("Runtime delivery Session identity does not match its payload");
36049
+ if (first === void 0 || first.command.commandId === command.commandId) {
36050
+ return command.disposition !== SessionPromptDisposition.Queue || operations.isTerminalExecution(command.targetCommandId, command.sessionId) ? "available" : "queue-target-unavailable";
36785
36051
  }
36786
- try {
36787
- await sessions.respondElicitation(command);
36788
- audit.record({
36789
- commandId: command.interactionId,
36790
- event: "session_elicitation_resolved",
36791
- sessionId: command.sessionId
36792
- });
36793
- } catch (error62) {
36794
- reportOperationFailure(socket, command.interactionId, command.sessionId, error62);
36052
+ if (command.disposition !== SessionPromptDisposition.Queue) {
36053
+ return "busy";
36795
36054
  }
36796
- return;
36797
- }
36798
- if (kind === SESSION_PROMPT_KIND) {
36799
- const command = message;
36800
- await processDeliveredPrompt(
36801
- delivery,
36802
- command,
36803
- command.disposition !== SessionPromptDisposition.Steer,
36804
- (attemptId, activateAttempt, executionSignal, turn) => executePrompt(
36805
- outbox,
36806
- publisher,
36807
- command,
36808
- config2,
36809
- directories,
36810
- audit,
36811
- sessions,
36812
- attemptId,
36813
- activateAttempt,
36814
- timer,
36815
- executionSignal,
36816
- turn.recordText
36817
- )
36818
- );
36819
- return;
36820
- }
36821
- throw new Error("Runtime delivery contains an unsupported protocol message");
36822
- };
36823
- const processRuntimeDelivery = (delivery, state) => {
36824
- if (state === "processed" || processingDeliveryIds.has(delivery.deliveryId)) {
36825
- return;
36826
- }
36827
- processingDeliveryIds.add(delivery.deliveryId);
36828
- void processDeliveredPayload(delivery).then(() => {
36829
- outbox.markRuntimeDeliveryProcessed(delivery.deliveryId, delivery.sessionId);
36830
- }).catch((error62) => {
36831
- if (connectionController.signal.aborted) {
36832
- return;
36833
- }
36834
- console.error("Mobius daemon could not process a in-memory Runtime delivery", error62);
36835
- failAndClose(
36836
- new Error("Runtime delivery processing failed", { cause: error62 }),
36837
- 4008,
36838
- "Invalid Runtime delivery",
36839
- "delivery"
36840
- );
36841
- }).finally(() => processingDeliveryIds.delete(delivery.deliveryId));
36842
- };
36843
- const receiveRuntimeDelivery = (delivery) => {
36844
- const payload = decodeServiceToDaemonMessage(delivery.payload);
36845
- const payloadKind = payload.kind;
36846
- let payloadSessionId = "";
36847
- if (payloadKind === SESSION_CANCEL_KIND) {
36848
- payloadSessionId = payload.sessionId;
36849
- } else if (payloadKind === SESSION_CONFIGURE_KIND) {
36850
- payloadSessionId = payload.sessionId;
36851
- } else if (payloadKind === SESSION_PERMISSION_RESPOND_KIND) {
36852
- payloadSessionId = payload.sessionId;
36853
- } else if (payloadKind === SESSION_ELICITATION_RESPOND_KIND) {
36854
- payloadSessionId = payload.sessionId;
36855
- } else if (payloadKind === SESSION_PROMPT_KIND) {
36856
- payloadSessionId = payload.sessionId;
36857
- } else {
36858
- throw new Error("Runtime delivery contains an unsupported protocol message");
36859
- }
36860
- if (payloadSessionId !== delivery.sessionId) {
36861
- throw new Error("Runtime delivery Session identity does not match its payload");
36862
- }
36863
- const stored = outbox.claimRuntimeDelivery(delivery);
36864
- send(socket, {
36865
- deliveryId: delivery.deliveryId,
36866
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
36867
- sessionId: delivery.sessionId
36868
- });
36869
- processRuntimeDelivery(delivery, stored.state);
36870
- };
36871
- const resumeRuntimeDeliveries = () => {
36872
- for (const stored of outbox.runtimeDeliveries()) {
36873
- const delivery = {
36874
- deliveryId: stored.deliveryId,
36875
- kind: RUNTIME_DELIVERY_KIND,
36876
- payload: stored.payload,
36877
- sessionId: stored.sessionId
36878
- };
36879
- if (stored.state !== "relay_committed") {
36880
- send(socket, {
36881
- deliveryId: stored.deliveryId,
36882
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
36883
- sessionId: stored.sessionId
36884
- });
36055
+ if (first.command.commandId !== command.targetCommandId) {
36056
+ return "queue-target-unavailable";
36885
36057
  }
36886
- processRuntimeDelivery(delivery, stored.state);
36058
+ await waitForTurnCompletion(first, waitSignal);
36887
36059
  }
36888
36060
  };
36889
36061
  const connectionLiveness = new RelayConnectionLiveness(timer, {
@@ -36942,39 +36114,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36942
36114
  try {
36943
36115
  const message = decodeServiceToDaemonMessage(encoded);
36944
36116
  const kind = message.kind;
36945
- if (kind === RUNTIME_DELIVERY_COMMITTED_KIND) {
36946
- const committed = message;
36947
- if (!outbox.markRuntimeDeliveryCommitted(committed.deliveryId, committed.sessionId)) {
36948
- console.warn("Mobius daemon ignored confirmation for an unknown Runtime delivery");
36949
- }
36950
- return;
36951
- }
36952
- if (kind === RUNTIME_DELIVERY_KIND) {
36953
- receiveRuntimeDelivery(message);
36954
- return;
36955
- }
36956
- if (kind === SESSION_EVENT_ACK_KIND) {
36957
- publisher.acknowledge(message);
36958
- return;
36959
- }
36960
- if (kind === SESSION_EVENT_DEFERRED_KIND) {
36961
- publisher.defer(message);
36962
- return;
36963
- }
36964
- if (kind === SESSION_EVENT_REJECTED_KIND) {
36965
- const rejection = message;
36966
- if (publisher.quarantine(rejection)) {
36967
- audit.record({
36968
- commandId: rejection.eventId,
36969
- details: { code: rejection.code },
36970
- event: "session_event_rejected",
36971
- sessionId: rejection.sessionId
36972
- });
36973
- } else {
36974
- console.warn("Mobius daemon ignored a rejection for an unknown session event");
36975
- }
36976
- return;
36977
- }
36978
36117
  if (kind === SESSION_LIVE_HISTORY_LOAD_KIND) {
36979
36118
  const command2 = decodeSessionLiveHistoryLoad(encoded);
36980
36119
  void executeSessionLiveHistoryLoad(
@@ -37452,7 +36591,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
37452
36591
  const cancellation = message;
37453
36592
  const turn2 = activeTurns.get(cancellation.commandId);
37454
36593
  if (turn2 === void 0 || !turn2.matches(cancellation)) {
37455
- settleAbandonedTurn(publisher, outbox, audit, cancellation);
36594
+ settleAbandonedTurn(publisher, operations, audit, cancellation);
37456
36595
  return;
37457
36596
  }
37458
36597
  if (!turn2.requestCancellation()) {
@@ -37548,14 +36687,14 @@ async function runRelayConnection(config2, directories, audit, sessions, install
37548
36687
  if (activeTurns.has(command.commandId)) {
37549
36688
  return;
37550
36689
  }
37551
- const receipt = outbox.claimExecution(command.commandId, command.sessionId, encoded);
36690
+ const receipt = operations.claimExecution(command.commandId, command.sessionId, encoded);
37552
36691
  if (receipt.kind === "duplicate") {
37553
36692
  return;
37554
36693
  }
37555
36694
  const turn = new ActiveDaemonTurn(command, receipt.attemptId);
37556
36695
  activeTurns.set(command.commandId, turn);
37557
36696
  void executePrompt(
37558
- outbox,
36697
+ operations,
37559
36698
  publisher,
37560
36699
  command,
37561
36700
  config2,
@@ -37563,30 +36702,20 @@ async function runRelayConnection(config2, directories, audit, sessions, install
37563
36702
  audit,
37564
36703
  sessions,
37565
36704
  receipt.attemptId,
37566
- () => {
37567
- turn.accept();
37568
- if (command.disposition !== SessionPromptDisposition.Steer) {
37569
- activeAttemptIds.set(command.sessionId, receipt.attemptId);
37570
- }
37571
- },
36705
+ turn.accept,
36706
+ (waitSignal) => waitForSessionAvailability(command, waitSignal),
37572
36707
  timer,
37573
36708
  turn.signal,
37574
- turn.recordText
36709
+ turn.recordText,
36710
+ turn.cancellationRequested
37575
36711
  ).catch((error62) => {
37576
36712
  console.error("Mobius daemon turn failed", error62);
37577
36713
  }).finally(() => {
37578
36714
  activeTurns.delete(command.commandId);
37579
- if (activeAttemptIds.get(command.sessionId) === receipt.attemptId) {
37580
- activeAttemptIds.delete(command.sessionId);
37581
- }
37582
36715
  turn.finish();
37583
36716
  });
37584
36717
  } catch (error62) {
37585
36718
  console.error("Mobius daemon rejected a message", error62);
37586
- if (error62 instanceof RuntimeDeliveryInboxCapacityError) {
37587
- failAndClose(error62, 4013, "Runtime delivery queue full", "delivery_backpressure");
37588
- return;
37589
- }
37590
36719
  failAndClose(
37591
36720
  new Error("Relay sent an invalid protocol message", { cause: error62 }),
37592
36721
  4008,
@@ -37604,7 +36733,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
37604
36733
  return;
37605
36734
  }
37606
36735
  publisher.connect(socket);
37607
- resumeRuntimeDeliveries();
37608
36736
  },
37609
36737
  (error62) => {
37610
36738
  if (finished) {
@@ -37626,7 +36754,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
37626
36754
  turn.abortDaemon();
37627
36755
  }
37628
36756
  publisher.connect(socket);
37629
- resumeRuntimeDeliveries();
37630
36757
  return;
37631
36758
  }
37632
36759
  failAndClose(
@@ -37663,17 +36790,11 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
37663
36790
  stateDirectory
37664
36791
  });
37665
36792
  const sessionStore = new MemoryAcpSessionStore();
37666
- const outbox = new SessionEventOutbox();
37667
- const publisher = new DaemonSessionEventPublisher(outbox, timer);
36793
+ const operations = new DaemonOperationState();
36794
+ const publisher = new DaemonSessionEventPublisher();
37668
36795
  const activeTurns = /* @__PURE__ */ new Map();
37669
- const activeAttemptIds = /* @__PURE__ */ new Map();
37670
36796
  const recordSessionEvent = (sessionId, event) => {
37671
- const attemptId = activeAttemptIds.get(sessionId);
37672
- if (attemptId === void 0) {
37673
- publisher.recordRuntime(sessionId, event);
37674
- return;
37675
- }
37676
- publisher.recordAttempt(sessionId, event, attemptId);
36797
+ publisher.publish(sessionId, event);
37677
36798
  };
37678
36799
  const sessions = new AcpSessionManager(
37679
36800
  new DaemonAcpObserver(recordSessionEvent),
@@ -37778,10 +36899,9 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
37778
36899
  installations,
37779
36900
  installationObserver,
37780
36901
  nativeSessions,
37781
- outbox,
36902
+ operations,
37782
36903
  publisher,
37783
36904
  activeTurns,
37784
- activeAttemptIds,
37785
36905
  connectionEpoch,
37786
36906
  diagnostics,
37787
36907
  () => {
@@ -37827,7 +36947,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
37827
36947
  try {
37828
36948
  publisher.close();
37829
36949
  } finally {
37830
- outbox.close();
36950
+ operations.close();
37831
36951
  }
37832
36952
  }
37833
36953
  }