@moxt-ai/mobius 0.0.104 → 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 +349 -1263
  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 +6 -6
  18. package/dist/daemon-session-commands.d.ts.map +1 -1
  19. package/dist/daemon-session-commands.js +43 -30
  20. package/dist/daemon-session-commands.js.map +1 -1
  21. package/dist/daemon-turn-reconciliation.d.ts +3 -2
  22. package/dist/daemon-turn-reconciliation.d.ts.map +1 -1
  23. package/dist/daemon-turn-reconciliation.js +8 -3
  24. package/dist/daemon-turn-reconciliation.js.map +1 -1
  25. package/dist/index.js +346 -1253
  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 -254
  47. package/dist/run-daemon.js.map +1 -1
  48. package/dist/runtime.js +350 -1257
  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,37 +20738,6 @@ 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
20743
  assertExactKeys(value, ["commandId", "epoch", "kind", "attemptId", "prompt", "sequence", "sessionId"]);
@@ -20859,15 +20850,6 @@ function encodeRuntimeHeartbeatEvent(message) {
20859
20850
  function encodeRuntimeHeartbeatAckEvent(message) {
20860
20851
  return JSON.stringify(decodeRuntimeHeartbeatAckEvent(JSON.stringify(message)));
20861
20852
  }
20862
- function encodeRuntimeDelivery(message) {
20863
- return JSON.stringify(decodeRuntimeDelivery(JSON.stringify(message)));
20864
- }
20865
- function encodeRuntimeDeliveryReceived(message) {
20866
- return JSON.stringify(decodeRuntimeDeliveryReceived(JSON.stringify(message)));
20867
- }
20868
- function encodeRuntimeDeliveryCommitted(message) {
20869
- return JSON.stringify(decodeRuntimeDeliveryCommitted(JSON.stringify(message)));
20870
- }
20871
20853
  function decodeAgentActivityNarrationEvent(encoded) {
20872
20854
  const value = parseJson2(encoded);
20873
20855
  assertExactKeys(value, ["activityId", "activityType", "commandId", "kind", "sequence", "sessionId", "text"]);
@@ -20981,6 +20963,7 @@ var NATIVE_SESSION_RESULT_KIND = "native.session.result";
20981
20963
  var NATIVE_SESSION_CANCEL_KIND = "native.session.cancel";
20982
20964
  var NATIVE_SESSION_TURN_FORK_REQUEST_KIND = "native.session.turn-fork.request";
20983
20965
  var NATIVE_SESSION_TURN_FORK_KIND = "native.session.turn-fork";
20966
+ var ACTIVE_TURN_TEXT_LIMIT = 1e6;
20984
20967
  var identifier = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
20985
20968
  var directoryId = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/);
20986
20969
  var envelope = {
@@ -21073,6 +21056,7 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
21073
21056
  ]);
21074
21057
  var nativeSessionEntrySchema = external_exports.strictObject({
21075
21058
  entryId: identifier,
21059
+ mobiusSessionIds: external_exports.array(identifier).max(500).readonly(),
21076
21060
  nativeSessionId: identifier,
21077
21061
  title: external_exports.string().max(500),
21078
21062
  directoryId,
@@ -21099,7 +21083,7 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
21099
21083
  turn: external_exports.strictObject({
21100
21084
  commandId: identifier,
21101
21085
  prompt: external_exports.string().max(1e5),
21102
- text: external_exports.string().max(1e5),
21086
+ text: external_exports.string().max(ACTIVE_TURN_TEXT_LIMIT),
21103
21087
  truncated: external_exports.boolean(),
21104
21088
  epoch: identifier,
21105
21089
  sequence: external_exports.number().int().nonnegative(),
@@ -21174,65 +21158,17 @@ var encodeNativeSessionTurnForkCommand = (value) => JSON.stringify(nativeSession
21174
21158
 
21175
21159
  // ../protocol/src/session-events.ts
21176
21160
  var SESSION_EVENT_KIND = "session.event";
21177
- var SESSION_EVENT_ACK_KIND = "session.event.ack";
21178
21161
  var SESSION_EVENT_COMMITTED_KIND = "session.event.committed";
21179
- var SESSION_EVENT_DEFERRED_KIND = "session.event.deferred";
21180
- var SESSION_EVENT_REJECTED_KIND = "session.event.rejected";
21181
- var SessionEventRejectionCode = {
21182
- SessionDeleted: "session_deleted",
21183
- SessionNotFound: "session_not_found",
21184
- SessionRejected: "session_rejected"
21185
- };
21186
21162
  var IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
21187
- var CURSOR_PATTERN = /^[A-Za-z0-9_-]{1,512}$/;
21188
21163
  var MAX_RECORDED_EVENT_LENGTH = 8 * 1024 * 1024;
21189
- var DECIMAL_SEQUENCE_PATTERN = /^(?:0|[1-9][0-9]*)$/;
21190
- var eventSourceSchema = external_exports.discriminatedUnion("kind", [
21191
- external_exports.strictObject({
21192
- attemptId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21193
- kind: external_exports.literal("attempt"),
21194
- sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
21195
- }).readonly(),
21196
- external_exports.strictObject({
21197
- kind: external_exports.literal("runtime"),
21198
- sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
21199
- }).readonly()
21200
- ]);
21201
21164
  var eventEnvelopeSchema = external_exports.strictObject({
21202
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21203
21165
  kind: external_exports.literal(SESSION_EVENT_KIND),
21204
21166
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
21205
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21206
- source: eventSourceSchema
21167
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
21207
21168
  }).readonly();
21208
21169
  var committedEventSchema = external_exports.strictObject({
21209
- cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
21210
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21211
21170
  kind: external_exports.literal(SESSION_EVENT_COMMITTED_KIND),
21212
21171
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
21213
- recordedAt: external_exports.string().datetime({ offset: true }),
21214
- sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
21215
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21216
- source: eventSourceSchema
21217
- }).readonly();
21218
- var eventAcknowledgementSchema = external_exports.strictObject({
21219
- cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
21220
- duplicate: external_exports.boolean(),
21221
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21222
- kind: external_exports.literal(SESSION_EVENT_ACK_KIND),
21223
- sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
21224
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
21225
- }).readonly();
21226
- var eventDeferredSchema = external_exports.strictObject({
21227
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21228
- kind: external_exports.literal(SESSION_EVENT_DEFERRED_KIND),
21229
- retryAfterMilliseconds: external_exports.number().int().min(100).max(6e4),
21230
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
21231
- }).readonly();
21232
- var eventRejectionSchema = external_exports.strictObject({
21233
- code: external_exports.enum(SessionEventRejectionCode),
21234
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21235
- kind: external_exports.literal(SESSION_EVENT_REJECTED_KIND),
21236
21172
  sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
21237
21173
  }).readonly();
21238
21174
  function decode5(encoded, schema) {
@@ -21261,12 +21197,6 @@ var encode4 = (message, schema) => {
21261
21197
  };
21262
21198
  var decodeSessionEventEnvelope = (encoded) => decode5(encoded, eventEnvelopeSchema);
21263
21199
  var encodeSessionEventEnvelope = (message) => encode4(message, eventEnvelopeSchema);
21264
- var decodeSessionEventAcknowledgement = (encoded) => decode5(encoded, eventAcknowledgementSchema);
21265
- var encodeSessionEventAcknowledgement = (message) => encode4(message, eventAcknowledgementSchema);
21266
- var decodeSessionEventDeferred = (encoded) => decode5(encoded, eventDeferredSchema);
21267
- var encodeSessionEventDeferred = (message) => encode4(message, eventDeferredSchema);
21268
- var decodeSessionEventRejection = (encoded) => decode5(encoded, eventRejectionSchema);
21269
- var encodeSessionEventRejection = (message) => encode4(message, eventRejectionSchema);
21270
21200
  function decodeRecordedSessionEvent(encoded) {
21271
21201
  const kind = decodeMessageKind(encoded);
21272
21202
  switch (kind) {
@@ -21396,6 +21326,11 @@ var serviceToDaemonSignatures = {
21396
21326
  decodeAgentSettingsDiscoverCommand
21397
21327
  ),
21398
21328
  [FILE_READ_KIND]: defineMessageSignature(FILE_READ_KIND, encodeFileReadCommand, decodeFileReadCommand),
21329
+ [SESSION_QUERY_KIND]: defineMessageSignature(
21330
+ SESSION_QUERY_KIND,
21331
+ encodeSessionQueryCommand,
21332
+ decodeSessionQueryCommand
21333
+ ),
21399
21334
  [NATIVE_SESSION_CANCEL_KIND]: defineMessageSignature(
21400
21335
  NATIVE_SESSION_CANCEL_KIND,
21401
21336
  encodeNativeSessionCancel,
@@ -21411,16 +21346,6 @@ var serviceToDaemonSignatures = {
21411
21346
  encodeNativeSessionTurnForkCommand,
21412
21347
  decodeNativeSessionTurnForkCommand
21413
21348
  ),
21414
- [RUNTIME_DELIVERY_KIND]: defineMessageSignature(
21415
- RUNTIME_DELIVERY_KIND,
21416
- encodeRuntimeDelivery,
21417
- decodeRuntimeDelivery
21418
- ),
21419
- [RUNTIME_DELIVERY_COMMITTED_KIND]: defineMessageSignature(
21420
- RUNTIME_DELIVERY_COMMITTED_KIND,
21421
- encodeRuntimeDeliveryCommitted,
21422
- decodeRuntimeDeliveryCommitted
21423
- ),
21424
21349
  [RUNTIME_HEARTBEAT_ACK_KIND]: defineMessageSignature(
21425
21350
  RUNTIME_HEARTBEAT_ACK_KIND,
21426
21351
  encodeRuntimeHeartbeatAckEvent,
@@ -21446,21 +21371,6 @@ var serviceToDaemonSignatures = {
21446
21371
  encodeSessionElicitationRespondCommand,
21447
21372
  decodeSessionElicitationRespondCommand
21448
21373
  ),
21449
- [SESSION_EVENT_ACK_KIND]: defineMessageSignature(
21450
- SESSION_EVENT_ACK_KIND,
21451
- encodeSessionEventAcknowledgement,
21452
- decodeSessionEventAcknowledgement
21453
- ),
21454
- [SESSION_EVENT_DEFERRED_KIND]: defineMessageSignature(
21455
- SESSION_EVENT_DEFERRED_KIND,
21456
- encodeSessionEventDeferred,
21457
- decodeSessionEventDeferred
21458
- ),
21459
- [SESSION_EVENT_REJECTED_KIND]: defineMessageSignature(
21460
- SESSION_EVENT_REJECTED_KIND,
21461
- encodeSessionEventRejection,
21462
- decodeSessionEventRejection
21463
- ),
21464
21374
  [SESSION_LIVE_HISTORY_LOAD_KIND]: defineMessageSignature(
21465
21375
  SESSION_LIVE_HISTORY_LOAD_KIND,
21466
21376
  encodeSessionLiveHistoryLoad,
@@ -21551,16 +21461,16 @@ var daemonToServiceSignatures = {
21551
21461
  [FILE_CHUNK_KIND]: defineMessageSignature(FILE_CHUNK_KIND, encodeFileChunkEvent, decodeFileChunkEvent),
21552
21462
  [FILE_END_KIND]: defineMessageSignature(FILE_END_KIND, encodeFileEndEvent, decodeFileEndEvent),
21553
21463
  [FILE_FAILED_KIND]: defineMessageSignature(FILE_FAILED_KIND, encodeFileFailedEvent, decodeFileFailedEvent),
21464
+ [SESSION_QUERIED_KIND]: defineMessageSignature(
21465
+ SESSION_QUERIED_KIND,
21466
+ encodeSessionsQueriedEvent,
21467
+ decodeSessionsQueriedEvent
21468
+ ),
21554
21469
  [NATIVE_SESSION_RESULT_KIND]: defineMessageSignature(
21555
21470
  NATIVE_SESSION_RESULT_KIND,
21556
21471
  encodeNativeSessionResult,
21557
21472
  decodeNativeSessionResult
21558
21473
  ),
21559
- [RUNTIME_DELIVERY_RECEIVED_KIND]: defineMessageSignature(
21560
- RUNTIME_DELIVERY_RECEIVED_KIND,
21561
- encodeRuntimeDeliveryReceived,
21562
- decodeRuntimeDeliveryReceived
21563
- ),
21564
21474
  [RUNTIME_HEARTBEAT_KIND]: defineMessageSignature(
21565
21475
  RUNTIME_HEARTBEAT_KIND,
21566
21476
  encodeRuntimeHeartbeatEvent,
@@ -22616,13 +22526,17 @@ var AcpStoredSession = class {
22616
22526
  nativeSessionId;
22617
22527
  prompted;
22618
22528
  sessionId;
22619
- 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()) {
22620
22532
  this.additionalDirectories = [...additionalDirectories];
22621
22533
  this.agentId = agentId;
22622
22534
  this.cwd = cwd;
22623
22535
  this.nativeSessionId = nativeSessionId;
22624
22536
  this.prompted = prompted;
22625
22537
  this.sessionId = sessionId;
22538
+ this.title = title2;
22539
+ this.updatedAt = updatedAt;
22626
22540
  }
22627
22541
  };
22628
22542
  var AcpStoredSessionLookup = class {
@@ -22647,6 +22561,7 @@ var MemoryAcpSessionStore = class {
22647
22561
  findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
22648
22562
  (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
22649
22563
  );
22564
+ list = () => [...this.#sessions.values()].toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt));
22650
22565
  markDeleted = (agentId, nativeSessionId) => {
22651
22566
  const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
22652
22567
  for (const id of ids) {
@@ -24790,7 +24705,8 @@ var AcpProcessSession = class _AcpProcessSession {
24790
24705
  nativeSessionIdSchema.parse(origin.nativeSessionId),
24791
24706
  this.#cwd,
24792
24707
  this.#additionalDirectories,
24793
- true
24708
+ true,
24709
+ ""
24794
24710
  )
24795
24711
  ) : this.#store.read(this.#mobiusSessionId)
24796
24712
  );
@@ -24866,6 +24782,7 @@ var AcpProcessSession = class _AcpProcessSession {
24866
24782
  } else if (stored instanceof FoundAcpStoredSession && stored.session.agentId === this.#agentId && stored.session.cwd === this.#cwd && arraysEqual(stored.session.additionalDirectories, this.#additionalDirectories)) {
24867
24783
  this.selectNativeSession(stored.session.nativeSessionId);
24868
24784
  this.#prompted = stored.session.prompted;
24785
+ this.#sessionTitle = stored.session.title;
24869
24786
  this.#restored = true;
24870
24787
  if (this.#capabilities.resumeSession) {
24871
24788
  lifecycleResponse = await this.#metrics.measure(
@@ -24949,18 +24866,17 @@ var AcpProcessSession = class _AcpProcessSession {
24949
24866
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
24950
24867
  await this.#updateTail;
24951
24868
  signal.throwIfAborted();
24952
- if (this.#prompted) {
24953
- this.#store.write(
24954
- new AcpStoredSession(
24955
- this.#mobiusSessionId,
24956
- this.#agentId,
24957
- this.#nativeSessionId,
24958
- this.#cwd,
24959
- this.#additionalDirectories,
24960
- true
24961
- )
24962
- );
24963
- }
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
+ );
24964
24880
  };
24965
24881
  listNativeSessions = async (cursor, signal) => {
24966
24882
  if (!this.#capabilities.listSessions) {
@@ -25012,7 +24928,15 @@ var AcpProcessSession = class _AcpProcessSession {
25012
24928
  }
25013
24929
  const previousSessionId = this.#mobiusSessionId;
25014
24930
  this.#store.write(
25015
- 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
+ )
25016
24940
  );
25017
24941
  this.#store.remove(previousSessionId);
25018
24942
  this.#mobiusSessionId = sessionId;
@@ -25134,6 +25058,9 @@ var AcpProcessSession = class _AcpProcessSession {
25134
25058
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
25135
25059
  }
25136
25060
  const prompt = this.buildPrompt(options);
25061
+ if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
25062
+ this.#sessionTitle = truncate2(options.prompt, 500);
25063
+ }
25137
25064
  this.#store.write(
25138
25065
  new AcpStoredSession(
25139
25066
  this.#mobiusSessionId,
@@ -25141,7 +25068,8 @@ var AcpProcessSession = class _AcpProcessSession {
25141
25068
  this.#nativeSessionId,
25142
25069
  this.#cwd,
25143
25070
  this.#additionalDirectories,
25144
- true
25071
+ true,
25072
+ this.#sessionTitle
25145
25073
  )
25146
25074
  );
25147
25075
  this.#prompted = true;
@@ -25569,6 +25497,19 @@ var AcpProcessSession = class _AcpProcessSession {
25569
25497
  if (Object.hasOwn(update, "updatedAt")) {
25570
25498
  this.#sessionUpdatedAt = truncate2(update.updatedAt ?? "", 128);
25571
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
+ }
25572
25513
  await this.#getObserver().onInfo({
25573
25514
  kind: SESSION_INFO_UPDATED_KIND,
25574
25515
  sessionId: this.#mobiusSessionId,
@@ -26471,6 +26412,11 @@ var AcpSessionManager = class {
26471
26412
  )
26472
26413
  ]);
26473
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);
26474
26420
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
26475
26421
  createNativeSession = async (options) => {
26476
26422
  const temporarySessionId = `new-${crypto.randomUUID()}`;
@@ -31559,7 +31505,7 @@ function isRuntimeRelayRevocation(closeCode, closeReason) {
31559
31505
  }
31560
31506
 
31561
31507
  // src/run-daemon.ts
31562
- import { randomUUID as randomUUID6 } from "node:crypto";
31508
+ import { randomUUID as randomUUID7 } from "node:crypto";
31563
31509
  import { styleText } from "node:util";
31564
31510
  import { WebSocket as WebSocket5 } from "undici";
31565
31511
 
@@ -33558,21 +33504,17 @@ function daemonActivity(command, activity2) {
33558
33504
  toolKind: activity2.toolKind
33559
33505
  };
33560
33506
  }
33561
- function reportFailure(publisher, command, code, message, attemptId) {
33562
- publisher.recordAttempt(
33563
- command.sessionId,
33564
- {
33565
- code,
33566
- commandId: command.commandId,
33567
- kind: SESSION_FAILED_KIND,
33568
- message,
33569
- sessionId: command.sessionId
33570
- },
33571
- attemptId
33572
- );
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
+ });
33573
33515
  }
33574
- function settleAbandonedTurn(publisher, outbox, audit, cancellation) {
33575
- const attemptId = outbox.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
33516
+ function settleAbandonedTurn(publisher, operations, audit, cancellation) {
33517
+ const attemptId = operations.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
33576
33518
  if (attemptId === null) {
33577
33519
  console.warn("Mobius daemon ignored cancellation for an inactive turn");
33578
33520
  return;
@@ -33586,10 +33528,9 @@ function settleAbandonedTurn(publisher, outbox, audit, cancellation) {
33586
33528
  publisher,
33587
33529
  cancellation,
33588
33530
  "agent_execution_abandoned",
33589
- "The local Agent execution was abandoned before it completed",
33590
- attemptId
33531
+ "The local Agent execution was abandoned before it completed"
33591
33532
  );
33592
- outbox.transitionExecution(cancellation.commandId, "failed");
33533
+ operations.transitionExecution(cancellation.commandId, "failed");
33593
33534
  }
33594
33535
  function operationErrorCode(error62) {
33595
33536
  if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof PromptArtifactError) {
@@ -33719,7 +33660,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
33719
33660
  event: "session_configured",
33720
33661
  sessionId: command.sessionId
33721
33662
  });
33722
- publisher.recordRuntime(command.sessionId, {
33663
+ publisher.publish(command.sessionId, {
33723
33664
  configOptions,
33724
33665
  kind: "session.config.updated",
33725
33666
  requestId: command.requestId,
@@ -33744,7 +33685,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
33744
33685
  };
33745
33686
  if (command.transient !== true) {
33746
33687
  metrics.measureSync("readiness-commit", () => {
33747
- publisher.recordRuntime(command.sessionId, event);
33688
+ publisher.publish(command.sessionId, event);
33748
33689
  });
33749
33690
  }
33750
33691
  return event;
@@ -33892,7 +33833,7 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
33892
33833
  event: "session_configured",
33893
33834
  sessionId: command.sessionId
33894
33835
  });
33895
- publisher.recordRuntime(command.sessionId, {
33836
+ publisher.publish(command.sessionId, {
33896
33837
  configOptions,
33897
33838
  kind: "session.config.updated",
33898
33839
  requestId: command.requestId,
@@ -33905,26 +33846,22 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
33905
33846
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
33906
33847
  }
33907
33848
  }
33908
- async function executePrompt(outbox, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, sessionAvailable, timer, signal, recordLiveText) {
33849
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, waitForSessionAvailability, timer, signal, recordLiveText, cancellationRequested) {
33909
33850
  const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
33910
- publisher.recordAttempt(command.sessionId, daemonActivity(command, activity2), attemptId);
33851
+ publisher.publish(command.sessionId, daemonActivity(command, activity2));
33911
33852
  });
33912
33853
  const narration = new CoalescingNarrationPublisher(
33913
33854
  timer,
33914
33855
  (increment) => {
33915
- publisher.recordAttempt(
33916
- command.sessionId,
33917
- {
33918
- activityId: increment.activityId,
33919
- activityType: increment.activityType,
33920
- commandId: command.commandId,
33921
- kind: AGENT_ACTIVITY_NARRATION_KIND,
33922
- sequence: increment.sequence,
33923
- sessionId: command.sessionId,
33924
- text: increment.text
33925
- },
33926
- attemptId
33927
- );
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
+ });
33928
33865
  },
33929
33866
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
33930
33867
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -33933,19 +33870,15 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33933
33870
  timer,
33934
33871
  (messageId, delta) => {
33935
33872
  const stream = recordLiveText(delta);
33936
- publisher.recordAttempt(
33937
- command.sessionId,
33938
- {
33939
- commandId: command.commandId,
33940
- epoch: stream.epoch,
33941
- kind: AGENT_MESSAGE_DELTA_KIND,
33942
- messageId,
33943
- sequence: stream.sequence,
33944
- sessionId: command.sessionId,
33945
- text: delta
33946
- },
33947
- attemptId
33948
- );
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
+ });
33949
33882
  },
33950
33883
  AGENT_TEXT_COALESCING_MILLISECONDS,
33951
33884
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -33959,10 +33892,11 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33959
33892
  signal
33960
33893
  );
33961
33894
  const agent = config2.catalog.find(command.agentId);
33962
- if (!sessionAvailable()) {
33895
+ const availability = await waitForSessionAvailability(signal);
33896
+ if (availability === "busy") {
33963
33897
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
33964
33898
  }
33965
- if (command.disposition === SessionPromptDisposition.Queue && !outbox.isTerminalExecution(command.targetCommandId, command.sessionId)) {
33899
+ if (availability === "queue-target-unavailable") {
33966
33900
  throw new AcpExecutionError(
33967
33901
  "The queued prompt target is unavailable",
33968
33902
  {},
@@ -34002,21 +33936,17 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
34002
33936
  event: "session_authorized",
34003
33937
  sessionId: command.sessionId
34004
33938
  });
34005
- outbox.transitionExecution(command.commandId, "running");
33939
+ operations.transitionExecution(command.commandId, "running");
34006
33940
  const stream = activateAttempt();
34007
- publisher.recordAttempt(
34008
- command.sessionId,
34009
- {
34010
- commandId: command.commandId,
34011
- epoch: stream.epoch,
34012
- kind: SESSION_STARTED_KIND,
34013
- attemptId,
34014
- prompt: command.prompt,
34015
- sequence: stream.sequence,
34016
- sessionId: command.sessionId
34017
- },
34018
- attemptId
34019
- );
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
+ });
34020
33950
  const attachments = await resolvePromptArtifacts(config2, command, signal);
34021
33951
  let stopReason;
34022
33952
  if (command.disposition === SessionPromptDisposition.Steer) {
@@ -34061,17 +33991,13 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
34061
33991
  text.flush();
34062
33992
  narration.flush();
34063
33993
  activities.flush();
34064
- publisher.recordAttempt(
34065
- command.sessionId,
34066
- {
34067
- commandId: command.commandId,
34068
- kind: SESSION_COMPLETED_KIND,
34069
- sessionId: command.sessionId,
34070
- stopReason
34071
- },
34072
- attemptId
34073
- );
34074
- 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");
34075
34001
  audit.record({
34076
34002
  commandId: command.commandId,
34077
34003
  event: stopReason === "cancelled" ? "session_cancelled" : "session_completed",
@@ -34081,6 +34007,21 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
34081
34007
  text.flush();
34082
34008
  narration.flush();
34083
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
+ }
34084
34025
  audit.record({
34085
34026
  commandId: command.commandId,
34086
34027
  event: "session_failed",
@@ -34091,10 +34032,9 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
34091
34032
  publisher,
34092
34033
  command,
34093
34034
  code === "session_operation_failed" ? "agent_execution_failed" : code,
34094
- code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62),
34095
- attemptId
34035
+ code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62)
34096
34036
  );
34097
- outbox.transitionExecution(command.commandId, "failed");
34037
+ operations.transitionExecution(command.commandId, "failed");
34098
34038
  console.error("Mobius daemon command failed", error62);
34099
34039
  }
34100
34040
  }
@@ -34236,7 +34176,6 @@ var DaemonInstallationObserver = class {
34236
34176
  import { randomUUID as randomUUID3 } from "node:crypto";
34237
34177
  import { fetch as fetch5 } from "undici";
34238
34178
  var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
34239
- var ACTIVE_TURN_TEXT_LIMIT = 1e5;
34240
34179
  var ActiveDaemonTurn = class {
34241
34180
  attemptId;
34242
34181
  command;
@@ -34282,11 +34221,16 @@ var ActiveDaemonTurn = class {
34282
34221
  matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
34283
34222
  requestCancellation = () => {
34284
34223
  if (this.#cancellationRequested) {
34285
- return false;
34224
+ return "already-requested";
34286
34225
  }
34287
34226
  this.#cancellationRequested = true;
34288
- 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";
34289
34232
  };
34233
+ cancellationRequested = () => this.#cancellationRequested;
34290
34234
  get signal() {
34291
34235
  return this.#controller.signal;
34292
34236
  }
@@ -35012,6 +34956,7 @@ var NativeSessionService = class {
35012
34956
  });
35013
34957
  return {
35014
34958
  entryId,
34959
+ mobiusSessionIds: this.#sessions.findLinkedSessions(command.agentId, info.sessionId).filter((session) => session.prompted && session.cwd === authorized.cwd).map((session) => session.sessionId),
35015
34960
  nativeSessionId: info.sessionId,
35016
34961
  title: info.title ?? "Untitled session",
35017
34962
  directoryId: authorized.directoryId,
@@ -35229,6 +35174,29 @@ var NativeSessionService = class {
35229
35174
  history: opened.history
35230
35175
  };
35231
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
+ };
35232
35200
  executeTurnFork = async (command, signal) => {
35233
35201
  signal.throwIfAborted();
35234
35202
  const cwd = await this.#directories.resolve(this.#config.bindingId, command.directoryId, signal);
@@ -35481,6 +35449,75 @@ function connectRelay(url2, signal) {
35481
35449
  });
35482
35450
  }
35483
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
+
35484
35521
  // src/relay-connection/diagnostics.ts
35485
35522
  var MAX_DIAGNOSTIC_TEXT_LENGTH = 256;
35486
35523
  function sanitizeDiagnosticText(value) {
@@ -35654,7 +35691,7 @@ var RelayConnectionDiagnostics = class {
35654
35691
  };
35655
35692
 
35656
35693
  // src/relay-connection/liveness.ts
35657
- import { randomUUID as randomUUID5 } from "node:crypto";
35694
+ import { randomUUID as randomUUID6 } from "node:crypto";
35658
35695
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
35659
35696
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
35660
35697
  var RelayLivenessState = class {
@@ -35743,7 +35780,7 @@ var RelayConnectionLiveness = class {
35743
35780
  }
35744
35781
  throw new Error("Heartbeat was scheduled in an invalid state");
35745
35782
  }
35746
- const heartbeatId = randomUUID5();
35783
+ const heartbeatId = randomUUID6();
35747
35784
  this.#state = new AwaitingHeartbeatAckState(
35748
35785
  heartbeatId,
35749
35786
  this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
@@ -35759,765 +35796,54 @@ var RelayConnectionLiveness = class {
35759
35796
  };
35760
35797
  };
35761
35798
 
35762
- // src/relay-connection/session-event-outbox.ts
35763
- import { createHash as createHash5 } from "node:crypto";
35764
- import { DatabaseSync } from "node:sqlite";
35765
- var DEFAULT_OUTBOX_LIMITS = {
35766
- criticalEventBytes: 40 * 1024 * 1024,
35767
- runtimeDeliveryBytes: 32 * 1024 * 1024,
35768
- runtimeDeliveryCount: 64,
35769
- standardEventBytes: 32 * 1024 * 1024
35770
- };
35771
- var MAX_TERMINAL_RECEIPTS = 1024;
35772
- var SessionEventOutboxCapacityError = class extends Error {
35773
- code = "session_event_outbox_full";
35774
- constructor() {
35775
- super("The in-memory Session event outbox is full");
35776
- this.name = "SessionEventOutboxCapacityError";
35777
- }
35778
- };
35779
- var RuntimeDeliveryInboxCapacityError = class extends Error {
35780
- code = "runtime_delivery_inbox_full";
35781
- constructor() {
35782
- super("The in-memory Runtime delivery inbox is full");
35783
- this.name = "RuntimeDeliveryInboxCapacityError";
35784
- }
35785
- };
35786
- var StoredRuntimeDelivery = class {
35787
- deliveryId;
35788
- duplicate;
35789
- payload;
35790
- sessionId;
35791
- state;
35792
- constructor(deliveryId, sessionId, payload, state, duplicate) {
35793
- this.deliveryId = deliveryId;
35794
- this.duplicate = duplicate;
35795
- this.payload = payload;
35796
- this.sessionId = sessionId;
35797
- this.state = state;
35798
- }
35799
- };
35800
- function readPendingEnvelope(row) {
35801
- if (typeof row !== "object" || row === null || Array.isArray(row)) {
35802
- throw new Error("SQLite returned an invalid session event outbox row");
35803
- }
35804
- const envelope2 = Reflect.get(row, "envelope_json");
35805
- if (typeof envelope2 !== "string") {
35806
- throw new Error("SQLite returned an invalid session event envelope");
35807
- }
35808
- return envelope2;
35809
- }
35810
- function rowNumber(row, field) {
35811
- const value = typeof row === "object" && row !== null ? Reflect.get(row, field) : void 0;
35812
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
35813
- throw new Error(`SQLite returned an invalid ${field} value`);
35814
- }
35815
- return value;
35816
- }
35817
- function rowString(row, field) {
35818
- const value = typeof row === "object" && row !== null ? Reflect.get(row, field) : void 0;
35819
- if (typeof value !== "string" || value.length === 0) {
35820
- throw new Error(`SQLite returned an invalid ${field} value`);
35821
- }
35822
- return value;
35823
- }
35824
- var SessionEventOutbox = class {
35825
- #database;
35826
- #limits;
35827
- constructor(limits = DEFAULT_OUTBOX_LIMITS) {
35828
- validateLimits(limits);
35829
- this.#limits = limits;
35830
- this.#database = new DatabaseSync(":memory:");
35831
- this.#database.exec(`
35832
- CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
35833
- ordinal INTEGER PRIMARY KEY AUTOINCREMENT,
35834
- event_id TEXT NOT NULL UNIQUE,
35835
- session_id TEXT NOT NULL,
35836
- source_key TEXT NOT NULL,
35837
- byte_length INTEGER NOT NULL,
35838
- envelope_json TEXT NOT NULL
35839
- ) STRICT;
35840
- CREATE INDEX IF NOT EXISTS relay_session_event_outbox_order
35841
- ON relay_session_event_outbox(ordinal);
35842
- CREATE TABLE IF NOT EXISTS relay_turn_receipts (
35843
- command_id TEXT PRIMARY KEY,
35844
- session_id TEXT NOT NULL,
35845
- command_hash TEXT NOT NULL,
35846
- attempt_id TEXT NOT NULL,
35847
- state TEXT NOT NULL CHECK (
35848
- state IN ('dispatching', 'running', 'succeeded', 'failed', 'cancelled')
35849
- )
35850
- ) STRICT;
35851
- CREATE TABLE IF NOT EXISTS relay_session_event_outbox_state (
35852
- singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
35853
- event_count INTEGER NOT NULL,
35854
- total_bytes INTEGER NOT NULL,
35855
- next_source_seq INTEGER NOT NULL
35856
- ) STRICT;
35857
- INSERT OR IGNORE INTO relay_session_event_outbox_state (
35858
- singleton, event_count, total_bytes, next_source_seq
35859
- ) VALUES (1, 0, 0, 1);
35860
- CREATE TABLE IF NOT EXISTS relay_runtime_deliveries (
35861
- delivery_id TEXT PRIMARY KEY,
35862
- session_id TEXT NOT NULL,
35863
- payload_json TEXT NOT NULL,
35864
- payload_bytes INTEGER NOT NULL,
35865
- state TEXT NOT NULL CHECK (
35866
- state IN ('received', 'relay_committed', 'processed')
35867
- ),
35868
- received_at INTEGER NOT NULL
35869
- ) STRICT;
35870
- `);
35871
- this.#database.exec(`
35872
- CREATE INDEX IF NOT EXISTS relay_session_event_outbox_source_order
35873
- ON relay_session_event_outbox(source_key, ordinal);
35874
- `);
35875
- }
35876
- claimExecution = (commandId, sessionId, commandJson) => {
35877
- const commandHash = createHash5("sha256").update(commandJson).digest("hex");
35878
- this.#database.exec("BEGIN IMMEDIATE");
35879
- try {
35880
- const existing = this.#database.prepare(
35881
- `SELECT session_id, command_hash, attempt_id, state
35882
- FROM relay_turn_receipts WHERE command_id = ?`
35883
- ).get(commandId);
35884
- if (typeof existing === "object" && existing !== null) {
35885
- const storedSessionId = Reflect.get(existing, "session_id");
35886
- const storedCommandHash = Reflect.get(existing, "command_hash");
35887
- const attemptId2 = Reflect.get(existing, "attempt_id");
35888
- const state = Reflect.get(existing, "state");
35889
- if (storedSessionId !== sessionId || storedCommandHash !== commandHash || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
35890
- throw new Error("The daemon command identity conflicts with its in-memory receipt");
35891
- }
35892
- this.#database.exec("COMMIT");
35893
- return { attemptId: attemptId2, commandId, kind: "duplicate", state };
35894
- }
35895
- const attemptId = crypto.randomUUID();
35896
- this.#database.prepare(
35897
- `INSERT INTO relay_turn_receipts (
35898
- command_id, session_id, command_hash, attempt_id, state
35899
- ) VALUES (?, ?, ?, ?, 'dispatching')`
35900
- ).run(commandId, sessionId, commandHash, attemptId);
35901
- this.#database.exec("COMMIT");
35902
- return {
35903
- attemptId,
35904
- commandId,
35905
- kind: "accepted",
35906
- state: "dispatching"
35907
- };
35908
- } catch (error62) {
35909
- this.#database.exec("ROLLBACK");
35910
- throw error62;
35911
- }
35912
- };
35913
- transitionExecution = (commandId, state) => {
35914
- const row = this.#database.prepare(`SELECT state FROM relay_turn_receipts WHERE command_id = ?`).get(commandId);
35915
- const current = typeof row === "object" && row !== null ? Reflect.get(row, "state") : void 0;
35916
- if (!isDaemonExecutionState(current)) {
35917
- throw new Error("The daemon execution receipt does not exist");
35918
- }
35919
- if (current === state) {
35920
- return;
35921
- }
35922
- const allowed = current === "dispatching" && (state === "running" || state === "failed" || state === "cancelled") || current === "running" && (state === "succeeded" || state === "failed" || state === "cancelled");
35923
- if (!allowed) {
35924
- throw new Error("The daemon execution transition is invalid");
35925
- }
35926
- this.#database.prepare(`UPDATE relay_turn_receipts SET state = ? WHERE command_id = ?`).run(state, commandId);
35927
- if (state === "succeeded" || state === "failed" || state === "cancelled") {
35928
- this.#database.prepare(
35929
- `DELETE FROM relay_turn_receipts
35930
- WHERE state IN ('succeeded', 'failed', 'cancelled')
35931
- AND rowid NOT IN (
35932
- SELECT rowid FROM relay_turn_receipts
35933
- WHERE state IN ('succeeded', 'failed', 'cancelled')
35934
- ORDER BY rowid DESC LIMIT ?
35935
- )`
35936
- ).run(MAX_TERMINAL_RECEIPTS);
35937
- }
35938
- };
35939
- /**
35940
- * The Attempt this live Runtime claimed for a command that has not reached a terminal state.
35941
- * Receipts disappear when the daemon process exits.
35942
- */
35943
- findUnsettledAttemptId = (commandId, sessionId) => {
35944
- const row = this.#database.prepare(`SELECT attempt_id, state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
35945
- if (typeof row !== "object" || row === null) {
35946
- return null;
35947
- }
35948
- const attemptId = Reflect.get(row, "attempt_id");
35949
- const state = Reflect.get(row, "state");
35950
- if (typeof attemptId !== "string" || attemptId.length === 0 || !isDaemonExecutionState(state)) {
35951
- return null;
35952
- }
35953
- return state === "dispatching" || state === "running" ? attemptId : null;
35954
- };
35955
- isTerminalExecution = (commandId, sessionId) => {
35956
- const row = this.#database.prepare(`SELECT state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
35957
- const state = typeof row === "object" && row !== null ? Reflect.get(row, "state") : void 0;
35958
- return state === "succeeded" || state === "failed" || state === "cancelled";
35959
- };
35960
- acknowledge = (acknowledgement) => this.#removeAcknowledgedEvent(acknowledgement.eventId, acknowledgement.sessionId);
35961
- quarantine = (rejection) => {
35962
- this.#database.exec("BEGIN IMMEDIATE");
35963
- try {
35964
- const stored = this.#database.prepare(
35965
- `SELECT byte_length FROM relay_session_event_outbox
35966
- WHERE event_id = ? AND session_id = ?`
35967
- ).get(rejection.eventId, rejection.sessionId);
35968
- if (stored === void 0) {
35969
- this.#database.exec("COMMIT");
35970
- return false;
35971
- }
35972
- const byteLength = rowNumber(stored, "byte_length");
35973
- const deletion = this.#database.prepare(
35974
- `DELETE FROM relay_session_event_outbox
35975
- WHERE event_id = ? AND session_id = ?`
35976
- ).run(rejection.eventId, rejection.sessionId);
35977
- if (deletion.changes !== 1) {
35978
- throw new Error("The rejected session event could not be removed from the in-memory outbox");
35979
- }
35980
- this.#decrementEventState(byteLength);
35981
- this.#database.exec("COMMIT");
35982
- return true;
35983
- } catch (error62) {
35984
- this.#database.exec("ROLLBACK");
35985
- throw error62;
35986
- }
35987
- };
35988
- close = () => {
35989
- this.#database.close();
35990
- };
35991
- enqueue = (sessionId, payload, attemptId = null) => {
35992
- return this.#enqueueBounded(sessionId, payload, attemptId ?? "", this.#limits.standardEventBytes);
35993
- };
35994
- enqueueCritical = (sessionId, payload, attemptId = "") => this.#enqueueBounded(sessionId, payload, attemptId, this.#limits.criticalEventBytes);
35995
- /**
35996
- * Bytes still available to standard Session events. The daemon uses this to shed
35997
- * superseded streaming events instead of filling the in-memory outbox, so a long Turn
35998
- * behind a slow Relay cannot make the next enqueue throw.
35999
- */
36000
- standardCapacityRemaining = () => {
36001
- const state = this.#database.prepare(
36002
- `SELECT total_bytes
36003
- FROM relay_session_event_outbox_state
36004
- WHERE singleton = 1`
36005
- ).get();
36006
- return this.#limits.standardEventBytes - rowNumber(state, "total_bytes");
36007
- };
36008
- claimRuntimeDelivery = (delivery) => {
36009
- const payloadBytes = new TextEncoder().encode(delivery.payload).byteLength;
36010
- this.#database.exec("BEGIN IMMEDIATE");
36011
- try {
36012
- const existing = this.#database.prepare(
36013
- `SELECT session_id, payload_json, state
36014
- FROM relay_runtime_deliveries
36015
- WHERE delivery_id = ?`
36016
- ).get(delivery.deliveryId);
36017
- if (existing !== void 0) {
36018
- const sessionId = rowString(existing, "session_id");
36019
- const payload = rowString(existing, "payload_json");
36020
- const state = runtimeDeliveryState(existing);
36021
- if (sessionId !== delivery.sessionId || payload !== delivery.payload) {
36022
- throw new Error("The Runtime delivery identity conflicts with its in-memory receipt");
36023
- }
36024
- this.#database.exec("COMMIT");
36025
- return new StoredRuntimeDelivery(delivery.deliveryId, sessionId, payload, state, true);
36026
- }
36027
- const usage = this.#database.prepare(
36028
- `SELECT COUNT(*) AS delivery_count,
36029
- COALESCE(SUM(payload_bytes), 0) AS delivery_bytes
36030
- FROM relay_runtime_deliveries`
36031
- ).get();
36032
- if (rowNumber(usage, "delivery_count") + 1 > this.#limits.runtimeDeliveryCount || rowNumber(usage, "delivery_bytes") + payloadBytes > this.#limits.runtimeDeliveryBytes) {
36033
- throw new RuntimeDeliveryInboxCapacityError();
36034
- }
36035
- this.#database.prepare(
36036
- `INSERT INTO relay_runtime_deliveries (
36037
- delivery_id, session_id, payload_json, payload_bytes, state, received_at
36038
- ) VALUES (?, ?, ?, ?, 'received', ?)`
36039
- ).run(delivery.deliveryId, delivery.sessionId, delivery.payload, payloadBytes, Date.now());
36040
- this.#database.exec("COMMIT");
36041
- return new StoredRuntimeDelivery(
36042
- delivery.deliveryId,
36043
- delivery.sessionId,
36044
- delivery.payload,
36045
- "received",
36046
- false
36047
- );
36048
- } catch (error62) {
36049
- this.#database.exec("ROLLBACK");
36050
- throw error62;
36051
- }
36052
- };
36053
- markRuntimeDeliveryCommitted = (deliveryId, sessionId) => {
36054
- this.#database.exec("BEGIN IMMEDIATE");
36055
- try {
36056
- const row = this.#database.prepare(
36057
- `SELECT state FROM relay_runtime_deliveries
36058
- WHERE delivery_id = ? AND session_id = ?`
36059
- ).get(deliveryId, sessionId);
36060
- if (row === void 0) {
36061
- this.#database.exec("COMMIT");
36062
- return false;
36063
- }
36064
- const state = runtimeDeliveryState(row);
36065
- if (state === "processed") {
36066
- this.#database.prepare(`DELETE FROM relay_runtime_deliveries WHERE delivery_id = ?`).run(deliveryId);
36067
- } else if (state === "received") {
36068
- this.#database.prepare(`UPDATE relay_runtime_deliveries SET state = 'relay_committed' WHERE delivery_id = ?`).run(deliveryId);
36069
- }
36070
- this.#database.exec("COMMIT");
36071
- return true;
36072
- } catch (error62) {
36073
- this.#database.exec("ROLLBACK");
36074
- throw error62;
36075
- }
36076
- };
36077
- markRuntimeDeliveryProcessed = (deliveryId, sessionId) => {
36078
- this.#database.exec("BEGIN IMMEDIATE");
36079
- try {
36080
- const row = this.#database.prepare(
36081
- `SELECT state FROM relay_runtime_deliveries
36082
- WHERE delivery_id = ? AND session_id = ?`
36083
- ).get(deliveryId, sessionId);
36084
- if (row === void 0) {
36085
- this.#database.exec("COMMIT");
36086
- return false;
36087
- }
36088
- const state = runtimeDeliveryState(row);
36089
- if (state === "relay_committed") {
36090
- this.#database.prepare(`DELETE FROM relay_runtime_deliveries WHERE delivery_id = ?`).run(deliveryId);
36091
- } else if (state === "received") {
36092
- this.#database.prepare(`UPDATE relay_runtime_deliveries SET state = 'processed' WHERE delivery_id = ?`).run(deliveryId);
36093
- }
36094
- this.#database.exec("COMMIT");
36095
- return true;
36096
- } catch (error62) {
36097
- this.#database.exec("ROLLBACK");
36098
- throw error62;
36099
- }
36100
- };
36101
- runtimeDeliveries = () => this.#database.prepare(
36102
- `SELECT delivery_id, session_id, payload_json, state
36103
- FROM relay_runtime_deliveries
36104
- ORDER BY received_at, delivery_id`
36105
- ).all().map(
36106
- (row) => new StoredRuntimeDelivery(
36107
- rowString(row, "delivery_id"),
36108
- rowString(row, "session_id"),
36109
- rowString(row, "payload_json"),
36110
- runtimeDeliveryState(row),
36111
- true
36112
- )
36113
- );
36114
- #enqueueBounded = (sessionId, payload, attemptId, maximumEventBytes) => {
36115
- const sourceKey = attemptId.length === 0 ? `runtime:${sessionId}` : `attempt:${sessionId}:${attemptId}`;
36116
- this.#database.exec("BEGIN IMMEDIATE");
36117
- try {
36118
- const state = this.#database.prepare(
36119
- `SELECT total_bytes, next_source_seq
36120
- FROM relay_session_event_outbox_state
36121
- WHERE singleton = 1`
36122
- ).get();
36123
- const nextSourceSeq = rowNumber(state, "next_source_seq");
36124
- if (nextSourceSeq < 1 || !Number.isSafeInteger(nextSourceSeq + 1)) {
36125
- throw new Error("SQLite returned an invalid event source sequence");
36126
- }
36127
- const envelope2 = {
36128
- eventId: crypto.randomUUID(),
36129
- kind: SESSION_EVENT_KIND,
36130
- payload,
36131
- sessionId,
36132
- source: attemptId.length === 0 ? { kind: "runtime", sourceSeq: nextSourceSeq.toString() } : {
36133
- attemptId,
36134
- kind: "attempt",
36135
- sourceSeq: nextSourceSeq.toString()
36136
- }
36137
- };
36138
- const encoded = encodeSessionEventEnvelope(envelope2);
36139
- const byteLength = new TextEncoder().encode(encoded).byteLength;
36140
- if (rowNumber(state, "total_bytes") + byteLength > maximumEventBytes) {
36141
- throw new SessionEventOutboxCapacityError();
36142
- }
36143
- this.#database.prepare(
36144
- `INSERT INTO relay_session_event_outbox (
36145
- event_id, session_id, source_key, byte_length, envelope_json
36146
- ) VALUES (?, ?, ?, ?, ?)`
36147
- ).run(envelope2.eventId, envelope2.sessionId, sourceKey, byteLength, encoded);
36148
- this.#database.prepare(
36149
- `UPDATE relay_session_event_outbox_state
36150
- SET event_count = event_count + 1,
36151
- total_bytes = total_bytes + ?,
36152
- next_source_seq = next_source_seq + 1
36153
- WHERE singleton = 1`
36154
- ).run(byteLength);
36155
- this.#database.exec("COMMIT");
36156
- return encoded;
36157
- } catch (error62) {
36158
- this.#database.exec("ROLLBACK");
36159
- throw error62;
36160
- }
36161
- };
36162
- #removeAcknowledgedEvent = (eventId, sessionId) => {
36163
- this.#database.exec("BEGIN IMMEDIATE");
36164
- try {
36165
- const stored = this.#database.prepare(
36166
- `SELECT byte_length FROM relay_session_event_outbox
36167
- WHERE event_id = ? AND session_id = ?`
36168
- ).get(eventId, sessionId);
36169
- if (stored === void 0) {
36170
- this.#database.exec("COMMIT");
36171
- return false;
36172
- }
36173
- const byteLength = rowNumber(stored, "byte_length");
36174
- const deletion = this.#database.prepare(
36175
- `DELETE FROM relay_session_event_outbox
36176
- WHERE event_id = ? AND session_id = ?`
36177
- ).run(eventId, sessionId);
36178
- if (deletion.changes !== 1) {
36179
- throw new Error("The acknowledged session event could not be removed from the in-memory outbox");
36180
- }
36181
- this.#decrementEventState(byteLength);
36182
- this.#database.exec("COMMIT");
36183
- return true;
36184
- } catch (error62) {
36185
- this.#database.exec("ROLLBACK");
36186
- throw error62;
36187
- }
36188
- };
36189
- #decrementEventState = (byteLength) => {
36190
- const result = this.#database.prepare(
36191
- `UPDATE relay_session_event_outbox_state
36192
- SET event_count = event_count - 1,
36193
- total_bytes = total_bytes - ?
36194
- WHERE singleton = 1 AND event_count > 0 AND total_bytes >= ?`
36195
- ).run(byteLength, byteLength);
36196
- if (result.changes !== 1) {
36197
- throw new Error("The Session event outbox capacity state is inconsistent");
36198
- }
36199
- };
36200
- pending = () => this.#database.prepare(
36201
- `SELECT envelope_json
36202
- FROM relay_session_event_outbox
36203
- ORDER BY ordinal`
36204
- ).all().map(readPendingEnvelope);
36205
- pendingBatch = (limit) => {
36206
- if (!Number.isSafeInteger(limit) || limit < 1) {
36207
- throw new Error("Session event replay batch limit must be a positive integer");
36208
- }
36209
- return this.#database.prepare(
36210
- `WITH ranked_events AS (
36211
- SELECT ordinal,
36212
- ROW_NUMBER() OVER (
36213
- PARTITION BY source_key
36214
- ORDER BY ordinal
36215
- ) AS source_position
36216
- FROM relay_session_event_outbox
36217
- )
36218
- SELECT outbox.envelope_json
36219
- FROM ranked_events AS ranked
36220
- INNER JOIN relay_session_event_outbox AS outbox
36221
- ON outbox.ordinal = ranked.ordinal
36222
- ORDER BY ranked.source_position, outbox.ordinal
36223
- LIMIT ?`
36224
- ).all(limit).map(readPendingEnvelope);
36225
- };
36226
- pendingSourceHeads = (limit, excludedEventIds, excludedSourceKeys) => {
36227
- if (!Number.isSafeInteger(limit) || limit < 1) {
36228
- throw new Error("Session event replay batch limit must be a positive integer");
36229
- }
36230
- const exclusions = [];
36231
- const parameters = [];
36232
- if (excludedEventIds.length > 0) {
36233
- exclusions.push(`event_id NOT IN (${excludedEventIds.map(() => "?").join(", ")})`);
36234
- parameters.push(...excludedEventIds);
36235
- }
36236
- if (excludedSourceKeys.length > 0) {
36237
- exclusions.push(`source_key NOT IN (${excludedSourceKeys.map(() => "?").join(", ")})`);
36238
- parameters.push(...excludedSourceKeys);
36239
- }
36240
- parameters.push(limit.toString());
36241
- const where = exclusions.length === 0 ? "" : `WHERE ${exclusions.join(" AND ")}`;
36242
- return this.#database.prepare(
36243
- `WITH available_events AS (
36244
- SELECT ordinal, source_key
36245
- FROM relay_session_event_outbox
36246
- ${where}
36247
- ), ranked_events AS (
36248
- SELECT ordinal,
36249
- ROW_NUMBER() OVER (
36250
- PARTITION BY source_key
36251
- ORDER BY ordinal
36252
- ) AS source_position
36253
- FROM available_events
36254
- )
36255
- SELECT outbox.envelope_json
36256
- FROM ranked_events AS ranked
36257
- INNER JOIN relay_session_event_outbox AS outbox
36258
- ON outbox.ordinal = ranked.ordinal
36259
- WHERE ranked.source_position = 1
36260
- ORDER BY outbox.ordinal
36261
- LIMIT ?`
36262
- ).all(...parameters).map(readPendingEnvelope);
36263
- };
36264
- };
36265
- function validateLimits(limits) {
36266
- const values = [
36267
- limits.criticalEventBytes,
36268
- limits.runtimeDeliveryBytes,
36269
- limits.runtimeDeliveryCount,
36270
- limits.standardEventBytes
36271
- ];
36272
- if (values.some((value) => !Number.isSafeInteger(value) || value < 1)) {
36273
- throw new Error("Session event outbox limits must be positive integers");
36274
- }
36275
- if (limits.criticalEventBytes < limits.standardEventBytes) {
36276
- throw new Error("Critical Session event capacity must include the standard capacity");
36277
- }
36278
- }
36279
- function runtimeDeliveryState(row) {
36280
- const state = rowString(row, "state");
36281
- if (state !== "received" && state !== "relay_committed" && state !== "processed") {
36282
- throw new Error("SQLite returned an invalid Runtime delivery state");
36283
- }
36284
- return state;
36285
- }
36286
- function isDaemonExecutionState(value) {
36287
- return value === "cancelled" || value === "dispatching" || value === "failed" || value === "running" || value === "succeeded";
36288
- }
36289
-
36290
35799
  // src/relay-connection/session-event-publisher.ts
36291
35800
  import { WebSocket as WebSocket4 } from "undici";
36292
- var DaemonSessionEventConnectionState = class {
36293
- };
36294
- var DisconnectedDaemonSessionEventState = class extends DaemonSessionEventConnectionState {
36295
- disconnect = () => this;
36296
- matches = () => false;
36297
- send = () => false;
36298
- };
36299
- var ConnectedDaemonSessionEventState = class extends DaemonSessionEventConnectionState {
36300
- #socket;
36301
- constructor(socket) {
36302
- super();
36303
- this.#socket = socket;
36304
- }
36305
- disconnect = (socket) => socket === this.#socket ? new DisconnectedDaemonSessionEventState() : this;
36306
- matches = (socket) => socket === this.#socket;
36307
- send = (message) => {
36308
- if (this.#socket.readyState !== WebSocket4.OPEN) {
36309
- return false;
36310
- }
36311
- try {
36312
- this.#socket.send(encodeDaemonToServiceMessage(message));
36313
- return true;
36314
- } catch {
36315
- return false;
36316
- }
36317
- };
36318
- };
36319
- var SESSION_EVENT_REPLAY_WINDOW = 16;
36320
- var SESSION_EVENT_SOURCE_REPLAY_WINDOW = 4;
36321
- var SESSION_EVENT_REPLAY_BYTE_LIMIT = 32 * 1024 * 1024;
36322
- function reservesSessionEventCapacity(event) {
36323
- if (event.kind === SESSION_COMPLETED_KIND || event.kind === SESSION_FAILED_KIND) {
36324
- return true;
36325
- }
36326
- return event.kind === AGENT_ACTIVITY_KIND && (event.activityType === "progress" || event.activityType === "reasoning") && (event.status === "completed" || event.status === "failed");
36327
- }
36328
- var InFlightSessionEvent = class {
36329
- byteLength;
36330
- sourceKey;
36331
- constructor(sourceKey, byteLength) {
36332
- this.byteLength = byteLength;
36333
- this.sourceKey = sourceKey;
36334
- }
36335
- };
36336
- function sessionEventSourceKey(envelope2) {
36337
- return envelope2.source.kind === "attempt" ? `attempt:${envelope2.sessionId}:${envelope2.source.attemptId}` : `runtime:${envelope2.sessionId}`;
36338
- }
35801
+ var MAX_LIVE_EVENT_BUFFERED_BYTES = 16 * 1024 * 1024;
36339
35802
  var DaemonSessionEventPublisher = class {
36340
- #outbox;
36341
- #inFlightEvents = /* @__PURE__ */ new Map();
36342
- #pausedSources = /* @__PURE__ */ new Map();
36343
- #shedEventKinds = /* @__PURE__ */ new Set();
36344
- #timer;
36345
- #inFlightBytes = 0;
36346
- #connection = new DisconnectedDaemonSessionEventState();
36347
- constructor(outbox, timer) {
36348
- this.#outbox = outbox;
36349
- this.#timer = timer;
36350
- }
35803
+ #socket = null;
35804
+ #reportedDrop = false;
36351
35805
  connect = (socket) => {
36352
- this.#connection = new ConnectedDaemonSessionEventState(socket);
36353
- this.#clearInFlight();
36354
- this.#publishNextBatch();
35806
+ this.#socket = socket;
35807
+ this.#reportedDrop = false;
36355
35808
  };
36356
35809
  disconnect = (socket) => {
36357
- if (!this.#connection.matches(socket)) {
36358
- return;
36359
- }
36360
- this.#connection = this.#connection.disconnect(socket);
36361
- this.#clearInFlight();
36362
- };
36363
- recordAttempt = (sessionId, event, attemptId) => {
36364
- const encoded = encodeRecordedSessionEvent(event);
36365
- if (reservesSessionEventCapacity(event)) {
36366
- this.#enqueueReserved(sessionId, encoded, attemptId, event.kind);
36367
- } else {
36368
- this.#enqueueStandard(sessionId, encoded, attemptId, event.kind);
36369
- }
36370
- this.#publishNextBatch();
36371
- };
36372
- recordRuntime = (sessionId, event) => {
36373
- this.#enqueueStandard(sessionId, encodeRecordedSessionEvent(event), "", event.kind);
36374
- this.#publishNextBatch();
36375
- };
36376
- /**
36377
- * Enqueue a standard event, shedding it instead of ending the daemon when the
36378
- * in-memory outbox is full.
36379
- *
36380
- * A capacity error used to escape the coalescing timer that publishes activities,
36381
- * so the process exited and every restart died on the same retained backlog. A full
36382
- * outbox is a recoverable runtime condition, not a fatal one: narration increments are
36383
- * superseded by the completed snapshot, so they are shed first, and any other streaming
36384
- * event is shed only at the wall rather than terminating the daemon.
36385
- */
36386
- #enqueueStandard = (sessionId, encoded, attemptId, kind) => {
36387
- if (kind === AGENT_ACTIVITY_NARRATION_KIND && this.#outbox.standardCapacityRemaining() <= 0) {
36388
- this.#reportShedEvent(kind);
36389
- return;
36390
- }
36391
- try {
36392
- this.#outbox.enqueue(sessionId, encoded, attemptId);
36393
- } catch (error62) {
36394
- if (!(error62 instanceof SessionEventOutboxCapacityError)) {
36395
- throw error62;
36396
- }
36397
- this.#reportShedEvent(kind);
36398
- }
36399
- };
36400
- /**
36401
- * Enqueue on the reserved budget, degrading to a reported drop instead of raising.
36402
- * Streaming events are shed before this budget is reached, so a Turn's terminal
36403
- * events and the completed snapshot that carries its narration still land; a drop
36404
- * here is the last resort for a backlog no acknowledgement can drain.
36405
- */
36406
- #enqueueReserved = (sessionId, encoded, attemptId, kind) => {
36407
- try {
36408
- this.#outbox.enqueueCritical(sessionId, encoded, attemptId);
36409
- } catch (error62) {
36410
- if (!(error62 instanceof SessionEventOutboxCapacityError)) {
36411
- throw error62;
36412
- }
36413
- this.#reportShedEvent(kind);
36414
- }
36415
- };
36416
- #reportShedEvent = (kind) => {
36417
- if (this.#shedEventKinds.has(kind)) {
36418
- return;
35810
+ if (this.#socket === socket) {
35811
+ this.#socket = null;
36419
35812
  }
36420
- this.#shedEventKinds.add(kind);
36421
- console.warn(`Mobius daemon is dropping queued "${kind}" events because the Session event outbox is full`);
36422
35813
  };
36423
- acknowledge = (acknowledgement) => {
36424
- 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();
36425
35818
  return;
36426
35819
  }
36427
- this.#removeInFlight(acknowledgement.eventId);
36428
- this.#publishNextBatch();
36429
- };
36430
- quarantine = (rejection) => {
36431
- const quarantined = this.#outbox.quarantine(rejection);
36432
- if (!quarantined) {
36433
- return false;
36434
- }
36435
- this.#removeInFlight(rejection.eventId);
36436
- this.#publishNextBatch();
36437
- return true;
36438
- };
36439
- defer = (deferred) => {
36440
- const inFlight = this.#inFlightEvents.get(deferred.eventId);
36441
- 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();
36442
35824
  return;
36443
35825
  }
36444
- this.#clearInFlightSource(inFlight.sourceKey);
36445
- if (!this.#pausedSources.has(inFlight.sourceKey)) {
36446
- this.#pausedSources.set(
36447
- inFlight.sourceKey,
36448
- this.#timer.schedule(() => {
36449
- this.#pausedSources.delete(inFlight.sourceKey);
36450
- this.#publishNextBatch();
36451
- }, deferred.retryAfterMilliseconds)
35826
+ try {
35827
+ socket.send(
35828
+ encodeDaemonToServiceMessage({
35829
+ kind: SESSION_EVENT_KIND,
35830
+ payload: encodeRecordedSessionEvent(event),
35831
+ sessionId
35832
+ })
36452
35833
  );
35834
+ } catch {
35835
+ this.#reportDrop();
36453
35836
  }
36454
- this.#publishNextBatch();
36455
35837
  };
36456
35838
  close = () => {
36457
- for (const task of this.#pausedSources.values()) {
36458
- task.cancel();
36459
- }
36460
- this.#pausedSources.clear();
36461
- this.#clearInFlight();
36462
- };
36463
- #publishNextBatch = () => {
36464
- while (this.#inFlightEvents.size < SESSION_EVENT_REPLAY_WINDOW) {
36465
- const sourceCounts = /* @__PURE__ */ new Map();
36466
- for (const inFlight of this.#inFlightEvents.values()) {
36467
- sourceCounts.set(inFlight.sourceKey, (sourceCounts.get(inFlight.sourceKey) ?? 0) + 1);
36468
- }
36469
- const saturatedSources = [...sourceCounts.entries()].filter(([, count]) => count >= SESSION_EVENT_SOURCE_REPLAY_WINDOW).map(([sourceKey]) => sourceKey);
36470
- const batch = this.#outbox.pendingSourceHeads(
36471
- SESSION_EVENT_REPLAY_WINDOW - this.#inFlightEvents.size,
36472
- [...this.#inFlightEvents.keys()],
36473
- [...this.#pausedSources.keys(), ...saturatedSources]
36474
- );
36475
- let sent = 0;
36476
- for (const encoded of batch) {
36477
- const envelope2 = decodeSessionEventEnvelope(encoded);
36478
- const sourceKey = sessionEventSourceKey(envelope2);
36479
- const sourceCount = sourceCounts.get(sourceKey) ?? 0;
36480
- if (sourceCount >= SESSION_EVENT_SOURCE_REPLAY_WINDOW) {
36481
- continue;
36482
- }
36483
- const byteLength = new TextEncoder().encode(encoded).byteLength;
36484
- if (this.#inFlightBytes + byteLength > SESSION_EVENT_REPLAY_BYTE_LIMIT) {
36485
- continue;
36486
- }
36487
- if (!this.#connection.send(envelope2)) {
36488
- this.#clearInFlight();
36489
- return;
36490
- }
36491
- this.#inFlightEvents.set(envelope2.eventId, new InFlightSessionEvent(sourceKey, byteLength));
36492
- this.#inFlightBytes += byteLength;
36493
- sourceCounts.set(sourceKey, sourceCount + 1);
36494
- sent += 1;
36495
- }
36496
- if (sent === 0) {
36497
- return;
36498
- }
36499
- }
35839
+ this.#socket = null;
36500
35840
  };
36501
- #removeInFlight = (eventId) => {
36502
- const inFlight = this.#inFlightEvents.get(eventId);
36503
- if (inFlight === void 0) {
35841
+ #reportDrop = () => {
35842
+ if (this.#reportedDrop) {
36504
35843
  return;
36505
35844
  }
36506
- this.#inFlightEvents.delete(eventId);
36507
- this.#inFlightBytes -= inFlight.byteLength;
36508
- };
36509
- #clearInFlight = () => {
36510
- this.#inFlightEvents.clear();
36511
- this.#inFlightBytes = 0;
36512
- };
36513
- #clearInFlightSource = (sourceKey) => {
36514
- for (const [eventId, inFlight] of this.#inFlightEvents) {
36515
- if (inFlight.sourceKey !== sourceKey) {
36516
- continue;
36517
- }
36518
- this.#inFlightEvents.delete(eventId);
36519
- this.#inFlightBytes -= inFlight.byteLength;
36520
- }
35845
+ this.#reportedDrop = true;
35846
+ console.warn("Mobius daemon dropped live Session events while the Relay was unavailable");
36521
35847
  };
36522
35848
  };
36523
35849
 
@@ -36591,7 +35917,7 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
36591
35917
  {
36592
35918
  agentId: agent.id,
36593
35919
  kind: AGENT_INSTALL_REQUEST_KIND,
36594
- requestId: `automatic-integration-${randomUUID6()}`
35920
+ requestId: `automatic-integration-${randomUUID7()}`
36595
35921
  },
36596
35922
  signal
36597
35923
  );
@@ -36636,9 +35962,8 @@ async function refreshAgentCatalog(config2, resolveEnvironment, signal) {
36636
35962
  throw error62;
36637
35963
  }
36638
35964
  }
36639
- 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) {
36640
35966
  const relayUrl = new URL(config2.relayUrl);
36641
- relayUrl.searchParams.set("deliveryReceipts", "1");
36642
35967
  relayUrl.searchParams.set("liveness", "1");
36643
35968
  const socket = await connectRelay(relayUrl, signal);
36644
35969
  const reconnectingTurns = [...activeTurns.values()];
@@ -36689,226 +36014,48 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36689
36014
  closeRelaySocket(socket, code, reason);
36690
36015
  rejectConnection(failure2);
36691
36016
  };
36692
- const processingDeliveryIds = /* @__PURE__ */ new Set();
36693
- const sessionAvailable = (command) => {
36694
- if (command.disposition === SessionPromptDisposition.Steer) {
36695
- return true;
36696
- }
36697
- const first = [...activeTurns.values()].find(
36698
- (turn) => turn.command.sessionId === command.sessionId && turn.command.disposition !== SessionPromptDisposition.Steer
36699
- );
36700
- return first === void 0 || first.command.commandId === command.commandId;
36701
- };
36702
- const processDeliveredPrompt = async (delivery, command, trackActiveAttempt, execute) => {
36703
- if (command.sessionId !== delivery.sessionId) {
36704
- throw new Error("Runtime delivery Session identity does not match its payload");
36705
- }
36706
- const active = activeTurns.get(command.commandId);
36707
- if (active !== void 0) {
36708
- await active.completion;
36709
- return;
36710
- }
36711
- const receipt = outbox.claimExecution(command.commandId, command.sessionId, delivery.payload);
36712
- if (receipt.kind === "duplicate") {
36713
- if (receipt.state === "running") {
36714
- reportFailure(
36715
- publisher,
36716
- command,
36717
- "agent_execution_interrupted",
36718
- "The local Agent execution was interrupted before it completed",
36719
- receipt.attemptId
36720
- );
36721
- outbox.transitionExecution(command.commandId, "failed");
36722
- return;
36723
- }
36724
- if (receipt.state !== "dispatching") {
36725
- return;
36726
- }
36727
- }
36728
- const turn = new ActiveDaemonTurn(command, receipt.attemptId);
36729
- activeTurns.set(command.commandId, turn);
36730
- const activateAttempt = () => {
36731
- const stream = turn.accept();
36732
- if (trackActiveAttempt) {
36733
- activeAttemptIds.set(command.sessionId, receipt.attemptId);
36734
- }
36735
- return stream;
36736
- };
36737
- try {
36738
- await execute(receipt.attemptId, activateAttempt, turn.signal, turn);
36739
- } finally {
36740
- activeTurns.delete(command.commandId);
36741
- if (activeAttemptIds.get(command.sessionId) === receipt.attemptId) {
36742
- activeAttemptIds.delete(command.sessionId);
36743
- }
36744
- turn.finish();
36745
- }
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
+ });
36746
36040
  };
36747
- const processDeliveredPayload = async (delivery) => {
36748
- const message = decodeServiceToDaemonMessage(delivery.payload);
36749
- const kind = message.kind;
36750
- if (kind === SESSION_CANCEL_KIND) {
36751
- const cancellation = message;
36752
- if (cancellation.sessionId !== delivery.sessionId) {
36753
- throw new Error("Runtime delivery Session identity does not match its payload");
36754
- }
36755
- const turn = activeTurns.get(cancellation.commandId);
36756
- if (turn === void 0 || !turn.matches(cancellation)) {
36757
- settleAbandonedTurn(publisher, outbox, audit, cancellation);
36758
- return;
36759
- }
36760
- if (!turn.requestCancellation()) {
36761
- return;
36762
- }
36763
- audit.record({
36764
- commandId: cancellation.commandId,
36765
- event: "session_cancellation_requested",
36766
- sessionId: cancellation.sessionId
36767
- });
36768
- await sessions.cancelPrompt(cancellation.sessionId);
36769
- return;
36041
+ const waitForSessionAvailability = async (command, waitSignal) => {
36042
+ if (command.disposition === SessionPromptDisposition.Steer) {
36043
+ return "available";
36770
36044
  }
36771
- if (kind === SESSION_CONFIGURE_KIND) {
36772
- const command = message;
36773
- if (command.sessionId !== delivery.sessionId) {
36774
- throw new Error("Runtime delivery Session identity does not match its payload");
36775
- }
36776
- await executeSessionConfigure(
36777
- publisher,
36778
- socket,
36779
- command,
36780
- config2,
36781
- directories,
36782
- audit,
36783
- sessions,
36784
- connectionController.signal
36045
+ for (; ; ) {
36046
+ const first = [...activeTurns.values()].find(
36047
+ (turn) => turn.command.sessionId === command.sessionId && turn.command.disposition !== SessionPromptDisposition.Steer
36785
36048
  );
36786
- return;
36787
- }
36788
- if (kind === SESSION_PERMISSION_RESPOND_KIND) {
36789
- const command = message;
36790
- if (command.sessionId !== delivery.sessionId) {
36791
- 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";
36792
36051
  }
36793
- try {
36794
- await sessions.respondPermission(command);
36795
- audit.record({
36796
- commandId: command.interactionId,
36797
- event: "session_permission_resolved",
36798
- sessionId: command.sessionId
36799
- });
36800
- } catch (error62) {
36801
- reportOperationFailure(socket, command.interactionId, command.sessionId, error62);
36802
- }
36803
- return;
36804
- }
36805
- if (kind === SESSION_ELICITATION_RESPOND_KIND) {
36806
- const command = message;
36807
- if (command.sessionId !== delivery.sessionId) {
36808
- throw new Error("Runtime delivery Session identity does not match its payload");
36809
- }
36810
- try {
36811
- await sessions.respondElicitation(command);
36812
- audit.record({
36813
- commandId: command.interactionId,
36814
- event: "session_elicitation_resolved",
36815
- sessionId: command.sessionId
36816
- });
36817
- } catch (error62) {
36818
- reportOperationFailure(socket, command.interactionId, command.sessionId, error62);
36052
+ if (command.disposition !== SessionPromptDisposition.Queue) {
36053
+ return "busy";
36819
36054
  }
36820
- return;
36821
- }
36822
- if (kind === SESSION_PROMPT_KIND) {
36823
- const command = message;
36824
- await processDeliveredPrompt(
36825
- delivery,
36826
- command,
36827
- command.disposition !== SessionPromptDisposition.Steer,
36828
- (attemptId, activateAttempt, executionSignal, turn) => executePrompt(
36829
- outbox,
36830
- publisher,
36831
- command,
36832
- config2,
36833
- directories,
36834
- audit,
36835
- sessions,
36836
- attemptId,
36837
- activateAttempt,
36838
- () => sessionAvailable(command),
36839
- timer,
36840
- executionSignal,
36841
- turn.recordText
36842
- )
36843
- );
36844
- return;
36845
- }
36846
- throw new Error("Runtime delivery contains an unsupported protocol message");
36847
- };
36848
- const processRuntimeDelivery = (delivery, state) => {
36849
- if (state === "processed" || processingDeliveryIds.has(delivery.deliveryId)) {
36850
- return;
36851
- }
36852
- processingDeliveryIds.add(delivery.deliveryId);
36853
- void processDeliveredPayload(delivery).then(() => {
36854
- outbox.markRuntimeDeliveryProcessed(delivery.deliveryId, delivery.sessionId);
36855
- }).catch((error62) => {
36856
- if (connectionController.signal.aborted) {
36857
- return;
36858
- }
36859
- console.error("Mobius daemon could not process a in-memory Runtime delivery", error62);
36860
- failAndClose(
36861
- new Error("Runtime delivery processing failed", { cause: error62 }),
36862
- 4008,
36863
- "Invalid Runtime delivery",
36864
- "delivery"
36865
- );
36866
- }).finally(() => processingDeliveryIds.delete(delivery.deliveryId));
36867
- };
36868
- const receiveRuntimeDelivery = (delivery) => {
36869
- const payload = decodeServiceToDaemonMessage(delivery.payload);
36870
- const payloadKind = payload.kind;
36871
- let payloadSessionId = "";
36872
- if (payloadKind === SESSION_CANCEL_KIND) {
36873
- payloadSessionId = payload.sessionId;
36874
- } else if (payloadKind === SESSION_CONFIGURE_KIND) {
36875
- payloadSessionId = payload.sessionId;
36876
- } else if (payloadKind === SESSION_PERMISSION_RESPOND_KIND) {
36877
- payloadSessionId = payload.sessionId;
36878
- } else if (payloadKind === SESSION_ELICITATION_RESPOND_KIND) {
36879
- payloadSessionId = payload.sessionId;
36880
- } else if (payloadKind === SESSION_PROMPT_KIND) {
36881
- payloadSessionId = payload.sessionId;
36882
- } else {
36883
- throw new Error("Runtime delivery contains an unsupported protocol message");
36884
- }
36885
- if (payloadSessionId !== delivery.sessionId) {
36886
- throw new Error("Runtime delivery Session identity does not match its payload");
36887
- }
36888
- const stored = outbox.claimRuntimeDelivery(delivery);
36889
- send(socket, {
36890
- deliveryId: delivery.deliveryId,
36891
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
36892
- sessionId: delivery.sessionId
36893
- });
36894
- processRuntimeDelivery(delivery, stored.state);
36895
- };
36896
- const resumeRuntimeDeliveries = () => {
36897
- for (const stored of outbox.runtimeDeliveries()) {
36898
- const delivery = {
36899
- deliveryId: stored.deliveryId,
36900
- kind: RUNTIME_DELIVERY_KIND,
36901
- payload: stored.payload,
36902
- sessionId: stored.sessionId
36903
- };
36904
- if (stored.state !== "relay_committed") {
36905
- send(socket, {
36906
- deliveryId: stored.deliveryId,
36907
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
36908
- sessionId: stored.sessionId
36909
- });
36055
+ if (first.command.commandId !== command.targetCommandId) {
36056
+ return "queue-target-unavailable";
36910
36057
  }
36911
- processRuntimeDelivery(delivery, stored.state);
36058
+ await waitForTurnCompletion(first, waitSignal);
36912
36059
  }
36913
36060
  };
36914
36061
  const connectionLiveness = new RelayConnectionLiveness(timer, {
@@ -36967,39 +36114,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36967
36114
  try {
36968
36115
  const message = decodeServiceToDaemonMessage(encoded);
36969
36116
  const kind = message.kind;
36970
- if (kind === RUNTIME_DELIVERY_COMMITTED_KIND) {
36971
- const committed = message;
36972
- if (!outbox.markRuntimeDeliveryCommitted(committed.deliveryId, committed.sessionId)) {
36973
- console.warn("Mobius daemon ignored confirmation for an unknown Runtime delivery");
36974
- }
36975
- return;
36976
- }
36977
- if (kind === RUNTIME_DELIVERY_KIND) {
36978
- receiveRuntimeDelivery(message);
36979
- return;
36980
- }
36981
- if (kind === SESSION_EVENT_ACK_KIND) {
36982
- publisher.acknowledge(message);
36983
- return;
36984
- }
36985
- if (kind === SESSION_EVENT_DEFERRED_KIND) {
36986
- publisher.defer(message);
36987
- return;
36988
- }
36989
- if (kind === SESSION_EVENT_REJECTED_KIND) {
36990
- const rejection = message;
36991
- if (publisher.quarantine(rejection)) {
36992
- audit.record({
36993
- commandId: rejection.eventId,
36994
- details: { code: rejection.code },
36995
- event: "session_event_rejected",
36996
- sessionId: rejection.sessionId
36997
- });
36998
- } else {
36999
- console.warn("Mobius daemon ignored a rejection for an unknown session event");
37000
- }
37001
- return;
37002
- }
37003
36117
  if (kind === SESSION_LIVE_HISTORY_LOAD_KIND) {
37004
36118
  const command2 = decodeSessionLiveHistoryLoad(encoded);
37005
36119
  void executeSessionLiveHistoryLoad(
@@ -37477,7 +36591,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
37477
36591
  const cancellation = message;
37478
36592
  const turn2 = activeTurns.get(cancellation.commandId);
37479
36593
  if (turn2 === void 0 || !turn2.matches(cancellation)) {
37480
- settleAbandonedTurn(publisher, outbox, audit, cancellation);
36594
+ settleAbandonedTurn(publisher, operations, audit, cancellation);
37481
36595
  return;
37482
36596
  }
37483
36597
  if (!turn2.requestCancellation()) {
@@ -37573,14 +36687,14 @@ async function runRelayConnection(config2, directories, audit, sessions, install
37573
36687
  if (activeTurns.has(command.commandId)) {
37574
36688
  return;
37575
36689
  }
37576
- const receipt = outbox.claimExecution(command.commandId, command.sessionId, encoded);
36690
+ const receipt = operations.claimExecution(command.commandId, command.sessionId, encoded);
37577
36691
  if (receipt.kind === "duplicate") {
37578
36692
  return;
37579
36693
  }
37580
36694
  const turn = new ActiveDaemonTurn(command, receipt.attemptId);
37581
36695
  activeTurns.set(command.commandId, turn);
37582
36696
  void executePrompt(
37583
- outbox,
36697
+ operations,
37584
36698
  publisher,
37585
36699
  command,
37586
36700
  config2,
@@ -37588,32 +36702,20 @@ async function runRelayConnection(config2, directories, audit, sessions, install
37588
36702
  audit,
37589
36703
  sessions,
37590
36704
  receipt.attemptId,
37591
- () => {
37592
- const stream = turn.accept();
37593
- if (command.disposition !== SessionPromptDisposition.Steer) {
37594
- activeAttemptIds.set(command.sessionId, receipt.attemptId);
37595
- }
37596
- return stream;
37597
- },
37598
- () => sessionAvailable(command),
36705
+ turn.accept,
36706
+ (waitSignal) => waitForSessionAvailability(command, waitSignal),
37599
36707
  timer,
37600
36708
  turn.signal,
37601
- turn.recordText
36709
+ turn.recordText,
36710
+ turn.cancellationRequested
37602
36711
  ).catch((error62) => {
37603
36712
  console.error("Mobius daemon turn failed", error62);
37604
36713
  }).finally(() => {
37605
36714
  activeTurns.delete(command.commandId);
37606
- if (activeAttemptIds.get(command.sessionId) === receipt.attemptId) {
37607
- activeAttemptIds.delete(command.sessionId);
37608
- }
37609
36715
  turn.finish();
37610
36716
  });
37611
36717
  } catch (error62) {
37612
36718
  console.error("Mobius daemon rejected a message", error62);
37613
- if (error62 instanceof RuntimeDeliveryInboxCapacityError) {
37614
- failAndClose(error62, 4013, "Runtime delivery queue full", "delivery_backpressure");
37615
- return;
37616
- }
37617
36719
  failAndClose(
37618
36720
  new Error("Relay sent an invalid protocol message", { cause: error62 }),
37619
36721
  4008,
@@ -37631,7 +36733,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
37631
36733
  return;
37632
36734
  }
37633
36735
  publisher.connect(socket);
37634
- resumeRuntimeDeliveries();
37635
36736
  },
37636
36737
  (error62) => {
37637
36738
  if (finished) {
@@ -37653,7 +36754,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
37653
36754
  turn.abortDaemon();
37654
36755
  }
37655
36756
  publisher.connect(socket);
37656
- resumeRuntimeDeliveries();
37657
36757
  return;
37658
36758
  }
37659
36759
  failAndClose(
@@ -37690,17 +36790,11 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
37690
36790
  stateDirectory
37691
36791
  });
37692
36792
  const sessionStore = new MemoryAcpSessionStore();
37693
- const outbox = new SessionEventOutbox();
37694
- const publisher = new DaemonSessionEventPublisher(outbox, timer);
36793
+ const operations = new DaemonOperationState();
36794
+ const publisher = new DaemonSessionEventPublisher();
37695
36795
  const activeTurns = /* @__PURE__ */ new Map();
37696
- const activeAttemptIds = /* @__PURE__ */ new Map();
37697
36796
  const recordSessionEvent = (sessionId, event) => {
37698
- const attemptId = activeAttemptIds.get(sessionId);
37699
- if (attemptId === void 0) {
37700
- publisher.recordRuntime(sessionId, event);
37701
- return;
37702
- }
37703
- publisher.recordAttempt(sessionId, event, attemptId);
36797
+ publisher.publish(sessionId, event);
37704
36798
  };
37705
36799
  const sessions = new AcpSessionManager(
37706
36800
  new DaemonAcpObserver(recordSessionEvent),
@@ -37805,10 +36899,9 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
37805
36899
  installations,
37806
36900
  installationObserver,
37807
36901
  nativeSessions,
37808
- outbox,
36902
+ operations,
37809
36903
  publisher,
37810
36904
  activeTurns,
37811
- activeAttemptIds,
37812
36905
  connectionEpoch,
37813
36906
  diagnostics,
37814
36907
  () => {
@@ -37854,7 +36947,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
37854
36947
  try {
37855
36948
  publisher.close();
37856
36949
  } finally {
37857
- outbox.close();
36950
+ operations.close();
37858
36951
  }
37859
36952
  }
37860
36953
  }