@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/runtime.js CHANGED
@@ -24431,6 +24431,8 @@ var WORKSPACE_LIST_KIND = "workspace.list";
24431
24431
  var WORKSPACE_ENTRIES_KIND = "workspace.entries";
24432
24432
  var SESSION_PREPARE_KIND = "session.prepare";
24433
24433
  var SESSION_READY_KIND = "session.ready";
24434
+ var SESSION_QUERY_KIND = "session.query";
24435
+ var SESSION_QUERIED_KIND = "session.queried";
24434
24436
  var SESSION_CONFIGURE_KIND = "session.configure";
24435
24437
  var SESSION_CONFIG_UPDATED_KIND = "session.config.updated";
24436
24438
  var SESSION_USAGE_UPDATED_KIND = "session.usage.updated";
@@ -24472,6 +24474,26 @@ var workspaceEntrySchema = external_exports.strictObject({
24472
24474
  directoryId: DIRECTORY_IDENTIFIER,
24473
24475
  name: external_exports.string().min(1).max(255)
24474
24476
  }).readonly();
24477
+ var sessionMetadataSchema = external_exports.strictObject({
24478
+ additionalDirectories: external_exports.array(workspaceEntrySchema).max(16).readonly(),
24479
+ agentId: IDENTIFIER,
24480
+ directoryId: DIRECTORY_IDENTIFIER,
24481
+ directoryLabel: external_exports.string().min(1).max(2048),
24482
+ prompted: external_exports.boolean(),
24483
+ sessionId: IDENTIFIER,
24484
+ title: external_exports.string().max(500),
24485
+ updatedAt: external_exports.iso.datetime({ offset: true })
24486
+ }).readonly();
24487
+ var sessionQueryCommandSchema = external_exports.strictObject({
24488
+ kind: external_exports.literal(SESSION_QUERY_KIND),
24489
+ requestId: IDENTIFIER,
24490
+ sessionIds: external_exports.array(IDENTIFIER).min(1).max(500).readonly()
24491
+ }).readonly();
24492
+ var sessionsQueriedEventSchema = external_exports.strictObject({
24493
+ entries: external_exports.array(sessionMetadataSchema).max(500).readonly(),
24494
+ kind: external_exports.literal(SESSION_QUERIED_KIND),
24495
+ requestId: IDENTIFIER
24496
+ }).readonly();
24475
24497
  var fileReadCommandSchema = external_exports.strictObject({
24476
24498
  kind: external_exports.literal(FILE_READ_KIND),
24477
24499
  maxBytes: external_exports.number().int().positive().max(128 * 1024 * 1024),
@@ -25015,6 +25037,10 @@ var decodeWorkspaceListCommand = (encoded) => decode3(encoded, workspaceListComm
25015
25037
  var encodeWorkspaceListCommand = (message) => encode3(message, workspaceListCommandSchema);
25016
25038
  var decodeWorkspaceEntriesEvent = (encoded) => decode3(encoded, workspaceEntriesEventSchema);
25017
25039
  var encodeWorkspaceEntriesEvent = (message) => encode3(message, workspaceEntriesEventSchema);
25040
+ var decodeSessionQueryCommand = (encoded) => decode3(encoded, sessionQueryCommandSchema);
25041
+ var encodeSessionQueryCommand = (message) => encode3(message, sessionQueryCommandSchema);
25042
+ var decodeSessionsQueriedEvent = (encoded) => decode3(encoded, sessionsQueriedEventSchema);
25043
+ var encodeSessionsQueriedEvent = (message) => encode3(message, sessionsQueriedEventSchema);
25018
25044
  var decodeSessionPrepareCommand = (encoded) => decode3(encoded, sessionPrepareCommandSchema);
25019
25045
  var encodeSessionPrepareCommand = (message) => encode3(message, sessionPrepareCommandSchema);
25020
25046
  var decodeSessionReadyEvent = (encoded) => decode3(encoded, sessionReadyEventSchema);
@@ -25058,9 +25084,6 @@ var SESSION_CANCEL_KIND = "session.cancel";
25058
25084
  var RUNTIME_LIVENESS_READY_KIND = "runtime.liveness.ready";
25059
25085
  var RUNTIME_HEARTBEAT_KIND = "runtime.heartbeat";
25060
25086
  var RUNTIME_HEARTBEAT_ACK_KIND = "runtime.heartbeat.ack";
25061
- var RUNTIME_DELIVERY_KIND = "runtime.delivery";
25062
- var RUNTIME_DELIVERY_RECEIVED_KIND = "runtime.delivery.received";
25063
- var RUNTIME_DELIVERY_COMMITTED_KIND = "runtime.delivery.committed";
25064
25087
  var SESSION_STARTED_KIND = "session.started";
25065
25088
  var AGENT_MESSAGE_DELTA_KIND = "agent.message.delta";
25066
25089
  var AGENT_ACTIVITY_KIND = "agent.activity";
@@ -25084,7 +25107,6 @@ var DIRECTORY_IDENTIFIER_PATTERN2 = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/;
25084
25107
  var MAX_PROMPT_LENGTH = 1e4;
25085
25108
  var MAX_PROMPT_ATTACHMENT_LENGTH = 6e6;
25086
25109
  var MAX_EVENT_TEXT_LENGTH = 1e5;
25087
- var MAX_RUNTIME_DELIVERY_PAYLOAD_LENGTH = 8 * 1024 * 1024;
25088
25110
  var ACTIVITY_TYPES = /* @__PURE__ */ new Set(["plan", "progress", "reasoning", "tool"]);
25089
25111
  var NARRATION_ACTIVITY_TYPES = /* @__PURE__ */ new Set(["progress", "reasoning"]);
25090
25112
  var ACTIVITY_STATUSES = /* @__PURE__ */ new Set(["pending", "running", "completed", "failed"]);
@@ -25371,37 +25393,6 @@ function decodeRuntimeHeartbeatAckEvent(encoded) {
25371
25393
  kind: RUNTIME_HEARTBEAT_ACK_KIND
25372
25394
  };
25373
25395
  }
25374
- function decodeRuntimeDelivery(encoded) {
25375
- const value = parseJson2(encoded);
25376
- assertExactKeys(value, ["deliveryId", "kind", "payload", "sessionId"]);
25377
- assertKind(value, RUNTIME_DELIVERY_KIND);
25378
- return {
25379
- deliveryId: readIdentifier(value, "deliveryId"),
25380
- kind: RUNTIME_DELIVERY_KIND,
25381
- payload: readString(value, "payload", MAX_RUNTIME_DELIVERY_PAYLOAD_LENGTH),
25382
- sessionId: readIdentifier(value, "sessionId")
25383
- };
25384
- }
25385
- function decodeRuntimeDeliveryReceived(encoded) {
25386
- const value = parseJson2(encoded);
25387
- assertExactKeys(value, ["deliveryId", "kind", "sessionId"]);
25388
- assertKind(value, RUNTIME_DELIVERY_RECEIVED_KIND);
25389
- return {
25390
- deliveryId: readIdentifier(value, "deliveryId"),
25391
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
25392
- sessionId: readIdentifier(value, "sessionId")
25393
- };
25394
- }
25395
- function decodeRuntimeDeliveryCommitted(encoded) {
25396
- const value = parseJson2(encoded);
25397
- assertExactKeys(value, ["deliveryId", "kind", "sessionId"]);
25398
- assertKind(value, RUNTIME_DELIVERY_COMMITTED_KIND);
25399
- return {
25400
- deliveryId: readIdentifier(value, "deliveryId"),
25401
- kind: RUNTIME_DELIVERY_COMMITTED_KIND,
25402
- sessionId: readIdentifier(value, "sessionId")
25403
- };
25404
- }
25405
25396
  function decodeSessionStartedEvent(encoded) {
25406
25397
  const value = parseJson2(encoded);
25407
25398
  assertExactKeys(value, ["commandId", "epoch", "kind", "attemptId", "prompt", "sequence", "sessionId"]);
@@ -25514,15 +25505,6 @@ function encodeRuntimeHeartbeatEvent(message) {
25514
25505
  function encodeRuntimeHeartbeatAckEvent(message) {
25515
25506
  return JSON.stringify(decodeRuntimeHeartbeatAckEvent(JSON.stringify(message)));
25516
25507
  }
25517
- function encodeRuntimeDelivery(message) {
25518
- return JSON.stringify(decodeRuntimeDelivery(JSON.stringify(message)));
25519
- }
25520
- function encodeRuntimeDeliveryReceived(message) {
25521
- return JSON.stringify(decodeRuntimeDeliveryReceived(JSON.stringify(message)));
25522
- }
25523
- function encodeRuntimeDeliveryCommitted(message) {
25524
- return JSON.stringify(decodeRuntimeDeliveryCommitted(JSON.stringify(message)));
25525
- }
25526
25508
  function decodeAgentActivityNarrationEvent(encoded) {
25527
25509
  const value = parseJson2(encoded);
25528
25510
  assertExactKeys(value, ["activityId", "activityType", "commandId", "kind", "sequence", "sessionId", "text"]);
@@ -25636,6 +25618,7 @@ var NATIVE_SESSION_RESULT_KIND = "native.session.result";
25636
25618
  var NATIVE_SESSION_CANCEL_KIND = "native.session.cancel";
25637
25619
  var NATIVE_SESSION_TURN_FORK_REQUEST_KIND = "native.session.turn-fork.request";
25638
25620
  var NATIVE_SESSION_TURN_FORK_KIND = "native.session.turn-fork";
25621
+ var ACTIVE_TURN_TEXT_LIMIT = 1e6;
25639
25622
  var identifier = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
25640
25623
  var directoryId = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/);
25641
25624
  var envelope = {
@@ -25728,6 +25711,7 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
25728
25711
  ]);
25729
25712
  var nativeSessionEntrySchema = external_exports.strictObject({
25730
25713
  entryId: identifier,
25714
+ mobiusSessionIds: external_exports.array(identifier).max(500).readonly(),
25731
25715
  nativeSessionId: identifier,
25732
25716
  title: external_exports.string().max(500),
25733
25717
  directoryId,
@@ -25754,7 +25738,7 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
25754
25738
  turn: external_exports.strictObject({
25755
25739
  commandId: identifier,
25756
25740
  prompt: external_exports.string().max(1e5),
25757
- text: external_exports.string().max(1e5),
25741
+ text: external_exports.string().max(ACTIVE_TURN_TEXT_LIMIT),
25758
25742
  truncated: external_exports.boolean(),
25759
25743
  epoch: identifier,
25760
25744
  sequence: external_exports.number().int().nonnegative(),
@@ -25829,65 +25813,17 @@ var encodeNativeSessionTurnForkCommand = (value) => JSON.stringify(nativeSession
25829
25813
 
25830
25814
  // ../protocol/src/session-events.ts
25831
25815
  var SESSION_EVENT_KIND = "session.event";
25832
- var SESSION_EVENT_ACK_KIND = "session.event.ack";
25833
25816
  var SESSION_EVENT_COMMITTED_KIND = "session.event.committed";
25834
- var SESSION_EVENT_DEFERRED_KIND = "session.event.deferred";
25835
- var SESSION_EVENT_REJECTED_KIND = "session.event.rejected";
25836
- var SessionEventRejectionCode = {
25837
- SessionDeleted: "session_deleted",
25838
- SessionNotFound: "session_not_found",
25839
- SessionRejected: "session_rejected"
25840
- };
25841
25817
  var IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
25842
- var CURSOR_PATTERN = /^[A-Za-z0-9_-]{1,512}$/;
25843
25818
  var MAX_RECORDED_EVENT_LENGTH = 8 * 1024 * 1024;
25844
- var DECIMAL_SEQUENCE_PATTERN = /^(?:0|[1-9][0-9]*)$/;
25845
- var eventSourceSchema = external_exports.discriminatedUnion("kind", [
25846
- external_exports.strictObject({
25847
- attemptId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25848
- kind: external_exports.literal("attempt"),
25849
- sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
25850
- }).readonly(),
25851
- external_exports.strictObject({
25852
- kind: external_exports.literal("runtime"),
25853
- sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
25854
- }).readonly()
25855
- ]);
25856
25819
  var eventEnvelopeSchema = external_exports.strictObject({
25857
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25858
25820
  kind: external_exports.literal(SESSION_EVENT_KIND),
25859
25821
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
25860
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25861
- source: eventSourceSchema
25822
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
25862
25823
  }).readonly();
25863
25824
  var committedEventSchema = external_exports.strictObject({
25864
- cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
25865
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25866
25825
  kind: external_exports.literal(SESSION_EVENT_COMMITTED_KIND),
25867
25826
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
25868
- recordedAt: external_exports.string().datetime({ offset: true }),
25869
- sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
25870
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25871
- source: eventSourceSchema
25872
- }).readonly();
25873
- var eventAcknowledgementSchema = external_exports.strictObject({
25874
- cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
25875
- duplicate: external_exports.boolean(),
25876
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25877
- kind: external_exports.literal(SESSION_EVENT_ACK_KIND),
25878
- sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
25879
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
25880
- }).readonly();
25881
- var eventDeferredSchema = external_exports.strictObject({
25882
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25883
- kind: external_exports.literal(SESSION_EVENT_DEFERRED_KIND),
25884
- retryAfterMilliseconds: external_exports.number().int().min(100).max(6e4),
25885
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
25886
- }).readonly();
25887
- var eventRejectionSchema = external_exports.strictObject({
25888
- code: external_exports.enum(SessionEventRejectionCode),
25889
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
25890
- kind: external_exports.literal(SESSION_EVENT_REJECTED_KIND),
25891
25827
  sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
25892
25828
  }).readonly();
25893
25829
  function decode5(encoded, schema) {
@@ -25916,12 +25852,6 @@ var encode4 = (message, schema) => {
25916
25852
  };
25917
25853
  var decodeSessionEventEnvelope = (encoded) => decode5(encoded, eventEnvelopeSchema);
25918
25854
  var encodeSessionEventEnvelope = (message) => encode4(message, eventEnvelopeSchema);
25919
- var decodeSessionEventAcknowledgement = (encoded) => decode5(encoded, eventAcknowledgementSchema);
25920
- var encodeSessionEventAcknowledgement = (message) => encode4(message, eventAcknowledgementSchema);
25921
- var decodeSessionEventDeferred = (encoded) => decode5(encoded, eventDeferredSchema);
25922
- var encodeSessionEventDeferred = (message) => encode4(message, eventDeferredSchema);
25923
- var decodeSessionEventRejection = (encoded) => decode5(encoded, eventRejectionSchema);
25924
- var encodeSessionEventRejection = (message) => encode4(message, eventRejectionSchema);
25925
25855
  function decodeRecordedSessionEvent(encoded) {
25926
25856
  const kind = decodeMessageKind(encoded);
25927
25857
  switch (kind) {
@@ -26051,6 +25981,11 @@ var serviceToDaemonSignatures = {
26051
25981
  decodeAgentSettingsDiscoverCommand
26052
25982
  ),
26053
25983
  [FILE_READ_KIND]: defineMessageSignature(FILE_READ_KIND, encodeFileReadCommand, decodeFileReadCommand),
25984
+ [SESSION_QUERY_KIND]: defineMessageSignature(
25985
+ SESSION_QUERY_KIND,
25986
+ encodeSessionQueryCommand,
25987
+ decodeSessionQueryCommand
25988
+ ),
26054
25989
  [NATIVE_SESSION_CANCEL_KIND]: defineMessageSignature(
26055
25990
  NATIVE_SESSION_CANCEL_KIND,
26056
25991
  encodeNativeSessionCancel,
@@ -26066,16 +26001,6 @@ var serviceToDaemonSignatures = {
26066
26001
  encodeNativeSessionTurnForkCommand,
26067
26002
  decodeNativeSessionTurnForkCommand
26068
26003
  ),
26069
- [RUNTIME_DELIVERY_KIND]: defineMessageSignature(
26070
- RUNTIME_DELIVERY_KIND,
26071
- encodeRuntimeDelivery,
26072
- decodeRuntimeDelivery
26073
- ),
26074
- [RUNTIME_DELIVERY_COMMITTED_KIND]: defineMessageSignature(
26075
- RUNTIME_DELIVERY_COMMITTED_KIND,
26076
- encodeRuntimeDeliveryCommitted,
26077
- decodeRuntimeDeliveryCommitted
26078
- ),
26079
26004
  [RUNTIME_HEARTBEAT_ACK_KIND]: defineMessageSignature(
26080
26005
  RUNTIME_HEARTBEAT_ACK_KIND,
26081
26006
  encodeRuntimeHeartbeatAckEvent,
@@ -26101,21 +26026,6 @@ var serviceToDaemonSignatures = {
26101
26026
  encodeSessionElicitationRespondCommand,
26102
26027
  decodeSessionElicitationRespondCommand
26103
26028
  ),
26104
- [SESSION_EVENT_ACK_KIND]: defineMessageSignature(
26105
- SESSION_EVENT_ACK_KIND,
26106
- encodeSessionEventAcknowledgement,
26107
- decodeSessionEventAcknowledgement
26108
- ),
26109
- [SESSION_EVENT_DEFERRED_KIND]: defineMessageSignature(
26110
- SESSION_EVENT_DEFERRED_KIND,
26111
- encodeSessionEventDeferred,
26112
- decodeSessionEventDeferred
26113
- ),
26114
- [SESSION_EVENT_REJECTED_KIND]: defineMessageSignature(
26115
- SESSION_EVENT_REJECTED_KIND,
26116
- encodeSessionEventRejection,
26117
- decodeSessionEventRejection
26118
- ),
26119
26029
  [SESSION_LIVE_HISTORY_LOAD_KIND]: defineMessageSignature(
26120
26030
  SESSION_LIVE_HISTORY_LOAD_KIND,
26121
26031
  encodeSessionLiveHistoryLoad,
@@ -26206,16 +26116,16 @@ var daemonToServiceSignatures = {
26206
26116
  [FILE_CHUNK_KIND]: defineMessageSignature(FILE_CHUNK_KIND, encodeFileChunkEvent, decodeFileChunkEvent),
26207
26117
  [FILE_END_KIND]: defineMessageSignature(FILE_END_KIND, encodeFileEndEvent, decodeFileEndEvent),
26208
26118
  [FILE_FAILED_KIND]: defineMessageSignature(FILE_FAILED_KIND, encodeFileFailedEvent, decodeFileFailedEvent),
26119
+ [SESSION_QUERIED_KIND]: defineMessageSignature(
26120
+ SESSION_QUERIED_KIND,
26121
+ encodeSessionsQueriedEvent,
26122
+ decodeSessionsQueriedEvent
26123
+ ),
26209
26124
  [NATIVE_SESSION_RESULT_KIND]: defineMessageSignature(
26210
26125
  NATIVE_SESSION_RESULT_KIND,
26211
26126
  encodeNativeSessionResult,
26212
26127
  decodeNativeSessionResult
26213
26128
  ),
26214
- [RUNTIME_DELIVERY_RECEIVED_KIND]: defineMessageSignature(
26215
- RUNTIME_DELIVERY_RECEIVED_KIND,
26216
- encodeRuntimeDeliveryReceived,
26217
- decodeRuntimeDeliveryReceived
26218
- ),
26219
26129
  [RUNTIME_HEARTBEAT_KIND]: defineMessageSignature(
26220
26130
  RUNTIME_HEARTBEAT_KIND,
26221
26131
  encodeRuntimeHeartbeatEvent,
@@ -26324,7 +26234,7 @@ function createDaemonConfig(connection, agents = [], installableAgents = [], loc
26324
26234
  }
26325
26235
 
26326
26236
  // src/run-daemon.ts
26327
- import { randomUUID as randomUUID5 } from "node:crypto";
26237
+ import { randomUUID as randomUUID6 } from "node:crypto";
26328
26238
  import { styleText } from "node:util";
26329
26239
  import { WebSocket as WebSocket5 } from "undici";
26330
26240
 
@@ -26488,13 +26398,17 @@ var AcpStoredSession = class {
26488
26398
  nativeSessionId;
26489
26399
  prompted;
26490
26400
  sessionId;
26491
- constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted) {
26401
+ title;
26402
+ updatedAt;
26403
+ constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted, title2, updatedAt = (/* @__PURE__ */ new Date()).toISOString()) {
26492
26404
  this.additionalDirectories = [...additionalDirectories];
26493
26405
  this.agentId = agentId;
26494
26406
  this.cwd = cwd;
26495
26407
  this.nativeSessionId = nativeSessionId;
26496
26408
  this.prompted = prompted;
26497
26409
  this.sessionId = sessionId;
26410
+ this.title = title2;
26411
+ this.updatedAt = updatedAt;
26498
26412
  }
26499
26413
  };
26500
26414
  var AcpStoredSessionLookup = class {
@@ -26519,6 +26433,7 @@ var MemoryAcpSessionStore = class {
26519
26433
  findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
26520
26434
  (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
26521
26435
  );
26436
+ list = () => [...this.#sessions.values()].toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt));
26522
26437
  markDeleted = (agentId, nativeSessionId) => {
26523
26438
  const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
26524
26439
  for (const id of ids) {
@@ -28648,7 +28563,8 @@ var AcpProcessSession = class _AcpProcessSession {
28648
28563
  nativeSessionIdSchema.parse(origin.nativeSessionId),
28649
28564
  this.#cwd,
28650
28565
  this.#additionalDirectories,
28651
- true
28566
+ true,
28567
+ ""
28652
28568
  )
28653
28569
  ) : this.#store.read(this.#mobiusSessionId)
28654
28570
  );
@@ -28724,6 +28640,7 @@ var AcpProcessSession = class _AcpProcessSession {
28724
28640
  } else if (stored instanceof FoundAcpStoredSession && stored.session.agentId === this.#agentId && stored.session.cwd === this.#cwd && arraysEqual(stored.session.additionalDirectories, this.#additionalDirectories)) {
28725
28641
  this.selectNativeSession(stored.session.nativeSessionId);
28726
28642
  this.#prompted = stored.session.prompted;
28643
+ this.#sessionTitle = stored.session.title;
28727
28644
  this.#restored = true;
28728
28645
  if (this.#capabilities.resumeSession) {
28729
28646
  lifecycleResponse = await this.#metrics.measure(
@@ -28807,18 +28724,17 @@ var AcpProcessSession = class _AcpProcessSession {
28807
28724
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
28808
28725
  await this.#updateTail;
28809
28726
  signal.throwIfAborted();
28810
- if (this.#prompted) {
28811
- this.#store.write(
28812
- new AcpStoredSession(
28813
- this.#mobiusSessionId,
28814
- this.#agentId,
28815
- this.#nativeSessionId,
28816
- this.#cwd,
28817
- this.#additionalDirectories,
28818
- true
28819
- )
28820
- );
28821
- }
28727
+ this.#store.write(
28728
+ new AcpStoredSession(
28729
+ this.#mobiusSessionId,
28730
+ this.#agentId,
28731
+ this.#nativeSessionId,
28732
+ this.#cwd,
28733
+ this.#additionalDirectories,
28734
+ this.#prompted,
28735
+ this.#sessionTitle ?? ""
28736
+ )
28737
+ );
28822
28738
  };
28823
28739
  listNativeSessions = async (cursor, signal) => {
28824
28740
  if (!this.#capabilities.listSessions) {
@@ -28870,7 +28786,15 @@ var AcpProcessSession = class _AcpProcessSession {
28870
28786
  }
28871
28787
  const previousSessionId = this.#mobiusSessionId;
28872
28788
  this.#store.write(
28873
- new AcpStoredSession(sessionId, this.#agentId, sessionId, this.#cwd, this.#additionalDirectories, false)
28789
+ new AcpStoredSession(
28790
+ sessionId,
28791
+ this.#agentId,
28792
+ sessionId,
28793
+ this.#cwd,
28794
+ this.#additionalDirectories,
28795
+ false,
28796
+ ""
28797
+ )
28874
28798
  );
28875
28799
  this.#store.remove(previousSessionId);
28876
28800
  this.#mobiusSessionId = sessionId;
@@ -28992,6 +28916,9 @@ var AcpProcessSession = class _AcpProcessSession {
28992
28916
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
28993
28917
  }
28994
28918
  const prompt = this.buildPrompt(options);
28919
+ if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
28920
+ this.#sessionTitle = truncate3(options.prompt, 500);
28921
+ }
28995
28922
  this.#store.write(
28996
28923
  new AcpStoredSession(
28997
28924
  this.#mobiusSessionId,
@@ -28999,7 +28926,8 @@ var AcpProcessSession = class _AcpProcessSession {
28999
28926
  this.#nativeSessionId,
29000
28927
  this.#cwd,
29001
28928
  this.#additionalDirectories,
29002
- true
28929
+ true,
28930
+ this.#sessionTitle
29003
28931
  )
29004
28932
  );
29005
28933
  this.#prompted = true;
@@ -29427,6 +29355,19 @@ var AcpProcessSession = class _AcpProcessSession {
29427
29355
  if (Object.hasOwn(update, "updatedAt")) {
29428
29356
  this.#sessionUpdatedAt = truncate3(update.updatedAt ?? "", 128);
29429
29357
  }
29358
+ if (this.#nativeSessionId.length > 0) {
29359
+ this.#store.write(
29360
+ new AcpStoredSession(
29361
+ this.#mobiusSessionId,
29362
+ this.#agentId,
29363
+ this.#nativeSessionId,
29364
+ this.#cwd,
29365
+ this.#additionalDirectories,
29366
+ this.#prompted,
29367
+ this.#sessionTitle ?? ""
29368
+ )
29369
+ );
29370
+ }
29430
29371
  await this.#getObserver().onInfo({
29431
29372
  kind: SESSION_INFO_UPDATED_KIND,
29432
29373
  sessionId: this.#mobiusSessionId,
@@ -30329,6 +30270,11 @@ var AcpSessionManager = class {
30329
30270
  )
30330
30271
  ]);
30331
30272
  };
30273
+ findSessions = (sessionIds) => sessionIds.flatMap((sessionId) => {
30274
+ const stored = this.#store.read(sessionId);
30275
+ return stored instanceof FoundAcpStoredSession ? [stored.session] : [];
30276
+ });
30277
+ findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
30332
30278
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
30333
30279
  createNativeSession = async (options) => {
30334
30280
  const temporarySessionId = `new-${crypto.randomUUID()}`;
@@ -32682,21 +32628,17 @@ function daemonActivity(command, activity2) {
32682
32628
  toolKind: activity2.toolKind
32683
32629
  };
32684
32630
  }
32685
- function reportFailure(publisher, command, code, message, attemptId) {
32686
- publisher.recordAttempt(
32687
- command.sessionId,
32688
- {
32689
- code,
32690
- commandId: command.commandId,
32691
- kind: SESSION_FAILED_KIND,
32692
- message,
32693
- sessionId: command.sessionId
32694
- },
32695
- attemptId
32696
- );
32631
+ function reportFailure(publisher, command, code, message) {
32632
+ publisher.publish(command.sessionId, {
32633
+ code,
32634
+ commandId: command.commandId,
32635
+ kind: SESSION_FAILED_KIND,
32636
+ message,
32637
+ sessionId: command.sessionId
32638
+ });
32697
32639
  }
32698
- function settleAbandonedTurn(publisher, outbox, audit, cancellation) {
32699
- const attemptId = outbox.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
32640
+ function settleAbandonedTurn(publisher, operations, audit, cancellation) {
32641
+ const attemptId = operations.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
32700
32642
  if (attemptId === null) {
32701
32643
  console.warn("Mobius daemon ignored cancellation for an inactive turn");
32702
32644
  return;
@@ -32710,10 +32652,9 @@ function settleAbandonedTurn(publisher, outbox, audit, cancellation) {
32710
32652
  publisher,
32711
32653
  cancellation,
32712
32654
  "agent_execution_abandoned",
32713
- "The local Agent execution was abandoned before it completed",
32714
- attemptId
32655
+ "The local Agent execution was abandoned before it completed"
32715
32656
  );
32716
- outbox.transitionExecution(cancellation.commandId, "failed");
32657
+ operations.transitionExecution(cancellation.commandId, "failed");
32717
32658
  }
32718
32659
  function operationErrorCode(error62) {
32719
32660
  if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof PromptArtifactError) {
@@ -32843,7 +32784,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
32843
32784
  event: "session_configured",
32844
32785
  sessionId: command.sessionId
32845
32786
  });
32846
- publisher.recordRuntime(command.sessionId, {
32787
+ publisher.publish(command.sessionId, {
32847
32788
  configOptions,
32848
32789
  kind: "session.config.updated",
32849
32790
  requestId: command.requestId,
@@ -32868,7 +32809,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
32868
32809
  };
32869
32810
  if (command.transient !== true) {
32870
32811
  metrics.measureSync("readiness-commit", () => {
32871
- publisher.recordRuntime(command.sessionId, event);
32812
+ publisher.publish(command.sessionId, event);
32872
32813
  });
32873
32814
  }
32874
32815
  return event;
@@ -33016,7 +32957,7 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
33016
32957
  event: "session_configured",
33017
32958
  sessionId: command.sessionId
33018
32959
  });
33019
- publisher.recordRuntime(command.sessionId, {
32960
+ publisher.publish(command.sessionId, {
33020
32961
  configOptions,
33021
32962
  kind: "session.config.updated",
33022
32963
  requestId: command.requestId,
@@ -33029,26 +32970,22 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
33029
32970
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
33030
32971
  }
33031
32972
  }
33032
- async function executePrompt(outbox, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, sessionAvailable, timer, signal, recordLiveText) {
32973
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, waitForSessionAvailability, timer, signal, recordLiveText, cancellationRequested) {
33033
32974
  const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
33034
- publisher.recordAttempt(command.sessionId, daemonActivity(command, activity2), attemptId);
32975
+ publisher.publish(command.sessionId, daemonActivity(command, activity2));
33035
32976
  });
33036
32977
  const narration = new CoalescingNarrationPublisher(
33037
32978
  timer,
33038
32979
  (increment) => {
33039
- publisher.recordAttempt(
33040
- command.sessionId,
33041
- {
33042
- activityId: increment.activityId,
33043
- activityType: increment.activityType,
33044
- commandId: command.commandId,
33045
- kind: AGENT_ACTIVITY_NARRATION_KIND,
33046
- sequence: increment.sequence,
33047
- sessionId: command.sessionId,
33048
- text: increment.text
33049
- },
33050
- attemptId
33051
- );
32980
+ publisher.publish(command.sessionId, {
32981
+ activityId: increment.activityId,
32982
+ activityType: increment.activityType,
32983
+ commandId: command.commandId,
32984
+ kind: AGENT_ACTIVITY_NARRATION_KIND,
32985
+ sequence: increment.sequence,
32986
+ sessionId: command.sessionId,
32987
+ text: increment.text
32988
+ });
33052
32989
  },
33053
32990
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
33054
32991
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -33057,19 +32994,15 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33057
32994
  timer,
33058
32995
  (messageId, delta) => {
33059
32996
  const stream = recordLiveText(delta);
33060
- publisher.recordAttempt(
33061
- command.sessionId,
33062
- {
33063
- commandId: command.commandId,
33064
- epoch: stream.epoch,
33065
- kind: AGENT_MESSAGE_DELTA_KIND,
33066
- messageId,
33067
- sequence: stream.sequence,
33068
- sessionId: command.sessionId,
33069
- text: delta
33070
- },
33071
- attemptId
33072
- );
32997
+ publisher.publish(command.sessionId, {
32998
+ commandId: command.commandId,
32999
+ epoch: stream.epoch,
33000
+ kind: AGENT_MESSAGE_DELTA_KIND,
33001
+ messageId,
33002
+ sequence: stream.sequence,
33003
+ sessionId: command.sessionId,
33004
+ text: delta
33005
+ });
33073
33006
  },
33074
33007
  AGENT_TEXT_COALESCING_MILLISECONDS,
33075
33008
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -33083,10 +33016,11 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33083
33016
  signal
33084
33017
  );
33085
33018
  const agent = config2.catalog.find(command.agentId);
33086
- if (!sessionAvailable()) {
33019
+ const availability = await waitForSessionAvailability(signal);
33020
+ if (availability === "busy") {
33087
33021
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
33088
33022
  }
33089
- if (command.disposition === SessionPromptDisposition.Queue && !outbox.isTerminalExecution(command.targetCommandId, command.sessionId)) {
33023
+ if (availability === "queue-target-unavailable") {
33090
33024
  throw new AcpExecutionError(
33091
33025
  "The queued prompt target is unavailable",
33092
33026
  {},
@@ -33126,21 +33060,17 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33126
33060
  event: "session_authorized",
33127
33061
  sessionId: command.sessionId
33128
33062
  });
33129
- outbox.transitionExecution(command.commandId, "running");
33063
+ operations.transitionExecution(command.commandId, "running");
33130
33064
  const stream = activateAttempt();
33131
- publisher.recordAttempt(
33132
- command.sessionId,
33133
- {
33134
- commandId: command.commandId,
33135
- epoch: stream.epoch,
33136
- kind: SESSION_STARTED_KIND,
33137
- attemptId,
33138
- prompt: command.prompt,
33139
- sequence: stream.sequence,
33140
- sessionId: command.sessionId
33141
- },
33142
- attemptId
33143
- );
33065
+ publisher.publish(command.sessionId, {
33066
+ commandId: command.commandId,
33067
+ epoch: stream.epoch,
33068
+ kind: SESSION_STARTED_KIND,
33069
+ attemptId,
33070
+ prompt: command.prompt,
33071
+ sequence: stream.sequence,
33072
+ sessionId: command.sessionId
33073
+ });
33144
33074
  const attachments = await resolvePromptArtifacts(config2, command, signal);
33145
33075
  let stopReason;
33146
33076
  if (command.disposition === SessionPromptDisposition.Steer) {
@@ -33185,17 +33115,13 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33185
33115
  text.flush();
33186
33116
  narration.flush();
33187
33117
  activities.flush();
33188
- publisher.recordAttempt(
33189
- command.sessionId,
33190
- {
33191
- commandId: command.commandId,
33192
- kind: SESSION_COMPLETED_KIND,
33193
- sessionId: command.sessionId,
33194
- stopReason
33195
- },
33196
- attemptId
33197
- );
33198
- outbox.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
33118
+ publisher.publish(command.sessionId, {
33119
+ commandId: command.commandId,
33120
+ kind: SESSION_COMPLETED_KIND,
33121
+ sessionId: command.sessionId,
33122
+ stopReason
33123
+ });
33124
+ operations.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
33199
33125
  audit.record({
33200
33126
  commandId: command.commandId,
33201
33127
  event: stopReason === "cancelled" ? "session_cancelled" : "session_completed",
@@ -33205,6 +33131,21 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33205
33131
  text.flush();
33206
33132
  narration.flush();
33207
33133
  activities.flush();
33134
+ if (signal.aborted && cancellationRequested()) {
33135
+ publisher.publish(command.sessionId, {
33136
+ commandId: command.commandId,
33137
+ kind: SESSION_COMPLETED_KIND,
33138
+ sessionId: command.sessionId,
33139
+ stopReason: "cancelled"
33140
+ });
33141
+ operations.transitionExecution(command.commandId, "cancelled");
33142
+ audit.record({
33143
+ commandId: command.commandId,
33144
+ event: "session_cancelled",
33145
+ sessionId: command.sessionId
33146
+ });
33147
+ return;
33148
+ }
33208
33149
  audit.record({
33209
33150
  commandId: command.commandId,
33210
33151
  event: "session_failed",
@@ -33215,10 +33156,9 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
33215
33156
  publisher,
33216
33157
  command,
33217
33158
  code === "session_operation_failed" ? "agent_execution_failed" : code,
33218
- code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62),
33219
- attemptId
33159
+ code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62)
33220
33160
  );
33221
- outbox.transitionExecution(command.commandId, "failed");
33161
+ operations.transitionExecution(command.commandId, "failed");
33222
33162
  console.error("Mobius daemon command failed", error62);
33223
33163
  }
33224
33164
  }
@@ -33360,7 +33300,6 @@ var DaemonInstallationObserver = class {
33360
33300
  import { randomUUID as randomUUID2 } from "node:crypto";
33361
33301
  import { fetch as fetch4 } from "undici";
33362
33302
  var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
33363
- var ACTIVE_TURN_TEXT_LIMIT = 1e5;
33364
33303
  var ActiveDaemonTurn = class {
33365
33304
  attemptId;
33366
33305
  command;
@@ -33406,11 +33345,16 @@ var ActiveDaemonTurn = class {
33406
33345
  matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
33407
33346
  requestCancellation = () => {
33408
33347
  if (this.#cancellationRequested) {
33409
- return false;
33348
+ return "already-requested";
33410
33349
  }
33411
33350
  this.#cancellationRequested = true;
33412
- return true;
33351
+ if (!this.#accepted) {
33352
+ this.#controller.abort(new Error("The queued Agent turn was cancelled"));
33353
+ return "pending";
33354
+ }
33355
+ return "running";
33413
33356
  };
33357
+ cancellationRequested = () => this.#cancellationRequested;
33414
33358
  get signal() {
33415
33359
  return this.#controller.signal;
33416
33360
  }
@@ -34136,6 +34080,7 @@ var NativeSessionService = class {
34136
34080
  });
34137
34081
  return {
34138
34082
  entryId,
34083
+ mobiusSessionIds: this.#sessions.findLinkedSessions(command.agentId, info.sessionId).filter((session) => session.prompted && session.cwd === authorized.cwd).map((session) => session.sessionId),
34139
34084
  nativeSessionId: info.sessionId,
34140
34085
  title: info.title ?? "Untitled session",
34141
34086
  directoryId: authorized.directoryId,
@@ -34353,6 +34298,29 @@ var NativeSessionService = class {
34353
34298
  history: opened.history
34354
34299
  };
34355
34300
  };
34301
+ querySessions = async (sessionIds, signal) => {
34302
+ const entries = [];
34303
+ for (const session of this.#sessions.findSessions(sessionIds)) {
34304
+ signal.throwIfAborted();
34305
+ const directory = await this.#directories.identify(this.#config.bindingId, session.cwd, signal);
34306
+ const additionalDirectories = [];
34307
+ for (const path2 of session.additionalDirectories) {
34308
+ const identified = await this.#directories.identify(this.#config.bindingId, path2, signal);
34309
+ additionalDirectories.push({ directoryId: identified.directoryId, name: identified.name });
34310
+ }
34311
+ entries.push({
34312
+ additionalDirectories,
34313
+ agentId: session.agentId,
34314
+ directoryId: directory.directoryId,
34315
+ directoryLabel: directory.label,
34316
+ prompted: session.prompted,
34317
+ sessionId: session.sessionId,
34318
+ title: session.title || "Untitled session",
34319
+ updatedAt: session.updatedAt
34320
+ });
34321
+ }
34322
+ return entries;
34323
+ };
34356
34324
  executeTurnFork = async (command, signal) => {
34357
34325
  signal.throwIfAborted();
34358
34326
  const cwd = await this.#directories.resolve(this.#config.bindingId, command.directoryId, signal);
@@ -34625,6 +34593,75 @@ function connectRelay(url2, signal) {
34625
34593
  });
34626
34594
  }
34627
34595
 
34596
+ // src/relay-connection/daemon-operation-state.ts
34597
+ import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
34598
+ var MAX_TERMINAL_RECEIPTS = 1024;
34599
+ function isTerminal(state) {
34600
+ return state === "succeeded" || state === "failed" || state === "cancelled";
34601
+ }
34602
+ var DaemonOperationState = class {
34603
+ #executions = /* @__PURE__ */ new Map();
34604
+ #terminalCount = 0;
34605
+ claimExecution = (commandId, sessionId, commandJson) => {
34606
+ const commandHash = createHash4("sha256").update(commandJson).digest("hex");
34607
+ const existing = this.#executions.get(commandId);
34608
+ if (existing !== void 0) {
34609
+ if (existing.sessionId !== sessionId || existing.commandHash !== commandHash) {
34610
+ throw new Error("The daemon command identity conflicts with its in-memory receipt");
34611
+ }
34612
+ return { attemptId: existing.attemptId, commandId, kind: "duplicate", state: existing.state };
34613
+ }
34614
+ const attemptId = randomUUID4();
34615
+ this.#executions.set(commandId, { attemptId, commandHash, sessionId, state: "dispatching" });
34616
+ return { attemptId, commandId, kind: "accepted", state: "dispatching" };
34617
+ };
34618
+ transitionExecution = (commandId, state) => {
34619
+ const current = this.#executions.get(commandId);
34620
+ if (current === void 0) {
34621
+ throw new Error("The daemon execution receipt does not exist");
34622
+ }
34623
+ if (current.state === state) {
34624
+ return;
34625
+ }
34626
+ const allowed = current.state === "dispatching" && (state === "running" || state === "failed" || state === "cancelled") || current.state === "running" && isTerminal(state);
34627
+ if (!allowed) {
34628
+ throw new Error("The daemon execution transition is invalid");
34629
+ }
34630
+ this.#executions.set(commandId, { ...current, state });
34631
+ if (isTerminal(state)) {
34632
+ this.#terminalCount += 1;
34633
+ this.pruneTerminalReceipts();
34634
+ }
34635
+ };
34636
+ /** Receipts disappear when the daemon process exits. */
34637
+ findUnsettledAttemptId = (commandId, sessionId) => {
34638
+ const receipt = this.#executions.get(commandId);
34639
+ return receipt?.sessionId === sessionId && !isTerminal(receipt.state) ? receipt.attemptId : null;
34640
+ };
34641
+ isTerminalExecution = (commandId, sessionId) => {
34642
+ const receipt = this.#executions.get(commandId);
34643
+ return receipt?.sessionId === sessionId && isTerminal(receipt.state);
34644
+ };
34645
+ close = () => {
34646
+ this.#executions.clear();
34647
+ this.#terminalCount = 0;
34648
+ };
34649
+ pruneTerminalReceipts = () => {
34650
+ if (this.#terminalCount <= MAX_TERMINAL_RECEIPTS) {
34651
+ return;
34652
+ }
34653
+ for (const [commandId, receipt] of this.#executions) {
34654
+ if (isTerminal(receipt.state)) {
34655
+ this.#executions.delete(commandId);
34656
+ this.#terminalCount -= 1;
34657
+ if (this.#terminalCount <= MAX_TERMINAL_RECEIPTS) {
34658
+ return;
34659
+ }
34660
+ }
34661
+ }
34662
+ };
34663
+ };
34664
+
34628
34665
  // src/relay-connection/diagnostics.ts
34629
34666
  var MAX_DIAGNOSTIC_TEXT_LENGTH = 256;
34630
34667
  function sanitizeDiagnosticText(value) {
@@ -34798,7 +34835,7 @@ var RelayConnectionDiagnostics = class {
34798
34835
  };
34799
34836
 
34800
34837
  // src/relay-connection/liveness.ts
34801
- import { randomUUID as randomUUID4 } from "node:crypto";
34838
+ import { randomUUID as randomUUID5 } from "node:crypto";
34802
34839
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
34803
34840
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
34804
34841
  var RelayLivenessState = class {
@@ -34887,7 +34924,7 @@ var RelayConnectionLiveness = class {
34887
34924
  }
34888
34925
  throw new Error("Heartbeat was scheduled in an invalid state");
34889
34926
  }
34890
- const heartbeatId = randomUUID4();
34927
+ const heartbeatId = randomUUID5();
34891
34928
  this.#state = new AwaitingHeartbeatAckState(
34892
34929
  heartbeatId,
34893
34930
  this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
@@ -34903,765 +34940,54 @@ var RelayConnectionLiveness = class {
34903
34940
  };
34904
34941
  };
34905
34942
 
34906
- // src/relay-connection/session-event-outbox.ts
34907
- import { createHash as createHash4 } from "node:crypto";
34908
- import { DatabaseSync } from "node:sqlite";
34909
- var DEFAULT_OUTBOX_LIMITS = {
34910
- criticalEventBytes: 40 * 1024 * 1024,
34911
- runtimeDeliveryBytes: 32 * 1024 * 1024,
34912
- runtimeDeliveryCount: 64,
34913
- standardEventBytes: 32 * 1024 * 1024
34914
- };
34915
- var MAX_TERMINAL_RECEIPTS = 1024;
34916
- var SessionEventOutboxCapacityError = class extends Error {
34917
- code = "session_event_outbox_full";
34918
- constructor() {
34919
- super("The in-memory Session event outbox is full");
34920
- this.name = "SessionEventOutboxCapacityError";
34921
- }
34922
- };
34923
- var RuntimeDeliveryInboxCapacityError = class extends Error {
34924
- code = "runtime_delivery_inbox_full";
34925
- constructor() {
34926
- super("The in-memory Runtime delivery inbox is full");
34927
- this.name = "RuntimeDeliveryInboxCapacityError";
34928
- }
34929
- };
34930
- var StoredRuntimeDelivery = class {
34931
- deliveryId;
34932
- duplicate;
34933
- payload;
34934
- sessionId;
34935
- state;
34936
- constructor(deliveryId, sessionId, payload, state, duplicate) {
34937
- this.deliveryId = deliveryId;
34938
- this.duplicate = duplicate;
34939
- this.payload = payload;
34940
- this.sessionId = sessionId;
34941
- this.state = state;
34942
- }
34943
- };
34944
- function readPendingEnvelope(row) {
34945
- if (typeof row !== "object" || row === null || Array.isArray(row)) {
34946
- throw new Error("SQLite returned an invalid session event outbox row");
34947
- }
34948
- const envelope2 = Reflect.get(row, "envelope_json");
34949
- if (typeof envelope2 !== "string") {
34950
- throw new Error("SQLite returned an invalid session event envelope");
34951
- }
34952
- return envelope2;
34953
- }
34954
- function rowNumber(row, field) {
34955
- const value = typeof row === "object" && row !== null ? Reflect.get(row, field) : void 0;
34956
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
34957
- throw new Error(`SQLite returned an invalid ${field} value`);
34958
- }
34959
- return value;
34960
- }
34961
- function rowString(row, field) {
34962
- const value = typeof row === "object" && row !== null ? Reflect.get(row, field) : void 0;
34963
- if (typeof value !== "string" || value.length === 0) {
34964
- throw new Error(`SQLite returned an invalid ${field} value`);
34965
- }
34966
- return value;
34967
- }
34968
- var SessionEventOutbox = class {
34969
- #database;
34970
- #limits;
34971
- constructor(limits = DEFAULT_OUTBOX_LIMITS) {
34972
- validateLimits(limits);
34973
- this.#limits = limits;
34974
- this.#database = new DatabaseSync(":memory:");
34975
- this.#database.exec(`
34976
- CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
34977
- ordinal INTEGER PRIMARY KEY AUTOINCREMENT,
34978
- event_id TEXT NOT NULL UNIQUE,
34979
- session_id TEXT NOT NULL,
34980
- source_key TEXT NOT NULL,
34981
- byte_length INTEGER NOT NULL,
34982
- envelope_json TEXT NOT NULL
34983
- ) STRICT;
34984
- CREATE INDEX IF NOT EXISTS relay_session_event_outbox_order
34985
- ON relay_session_event_outbox(ordinal);
34986
- CREATE TABLE IF NOT EXISTS relay_turn_receipts (
34987
- command_id TEXT PRIMARY KEY,
34988
- session_id TEXT NOT NULL,
34989
- command_hash TEXT NOT NULL,
34990
- attempt_id TEXT NOT NULL,
34991
- state TEXT NOT NULL CHECK (
34992
- state IN ('dispatching', 'running', 'succeeded', 'failed', 'cancelled')
34993
- )
34994
- ) STRICT;
34995
- CREATE TABLE IF NOT EXISTS relay_session_event_outbox_state (
34996
- singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
34997
- event_count INTEGER NOT NULL,
34998
- total_bytes INTEGER NOT NULL,
34999
- next_source_seq INTEGER NOT NULL
35000
- ) STRICT;
35001
- INSERT OR IGNORE INTO relay_session_event_outbox_state (
35002
- singleton, event_count, total_bytes, next_source_seq
35003
- ) VALUES (1, 0, 0, 1);
35004
- CREATE TABLE IF NOT EXISTS relay_runtime_deliveries (
35005
- delivery_id TEXT PRIMARY KEY,
35006
- session_id TEXT NOT NULL,
35007
- payload_json TEXT NOT NULL,
35008
- payload_bytes INTEGER NOT NULL,
35009
- state TEXT NOT NULL CHECK (
35010
- state IN ('received', 'relay_committed', 'processed')
35011
- ),
35012
- received_at INTEGER NOT NULL
35013
- ) STRICT;
35014
- `);
35015
- this.#database.exec(`
35016
- CREATE INDEX IF NOT EXISTS relay_session_event_outbox_source_order
35017
- ON relay_session_event_outbox(source_key, ordinal);
35018
- `);
35019
- }
35020
- claimExecution = (commandId, sessionId, commandJson) => {
35021
- const commandHash = createHash4("sha256").update(commandJson).digest("hex");
35022
- this.#database.exec("BEGIN IMMEDIATE");
35023
- try {
35024
- const existing = this.#database.prepare(
35025
- `SELECT session_id, command_hash, attempt_id, state
35026
- FROM relay_turn_receipts WHERE command_id = ?`
35027
- ).get(commandId);
35028
- if (typeof existing === "object" && existing !== null) {
35029
- const storedSessionId = Reflect.get(existing, "session_id");
35030
- const storedCommandHash = Reflect.get(existing, "command_hash");
35031
- const attemptId2 = Reflect.get(existing, "attempt_id");
35032
- const state = Reflect.get(existing, "state");
35033
- if (storedSessionId !== sessionId || storedCommandHash !== commandHash || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
35034
- throw new Error("The daemon command identity conflicts with its in-memory receipt");
35035
- }
35036
- this.#database.exec("COMMIT");
35037
- return { attemptId: attemptId2, commandId, kind: "duplicate", state };
35038
- }
35039
- const attemptId = crypto.randomUUID();
35040
- this.#database.prepare(
35041
- `INSERT INTO relay_turn_receipts (
35042
- command_id, session_id, command_hash, attempt_id, state
35043
- ) VALUES (?, ?, ?, ?, 'dispatching')`
35044
- ).run(commandId, sessionId, commandHash, attemptId);
35045
- this.#database.exec("COMMIT");
35046
- return {
35047
- attemptId,
35048
- commandId,
35049
- kind: "accepted",
35050
- state: "dispatching"
35051
- };
35052
- } catch (error62) {
35053
- this.#database.exec("ROLLBACK");
35054
- throw error62;
35055
- }
35056
- };
35057
- transitionExecution = (commandId, state) => {
35058
- const row = this.#database.prepare(`SELECT state FROM relay_turn_receipts WHERE command_id = ?`).get(commandId);
35059
- const current = typeof row === "object" && row !== null ? Reflect.get(row, "state") : void 0;
35060
- if (!isDaemonExecutionState(current)) {
35061
- throw new Error("The daemon execution receipt does not exist");
35062
- }
35063
- if (current === state) {
35064
- return;
35065
- }
35066
- const allowed = current === "dispatching" && (state === "running" || state === "failed" || state === "cancelled") || current === "running" && (state === "succeeded" || state === "failed" || state === "cancelled");
35067
- if (!allowed) {
35068
- throw new Error("The daemon execution transition is invalid");
35069
- }
35070
- this.#database.prepare(`UPDATE relay_turn_receipts SET state = ? WHERE command_id = ?`).run(state, commandId);
35071
- if (state === "succeeded" || state === "failed" || state === "cancelled") {
35072
- this.#database.prepare(
35073
- `DELETE FROM relay_turn_receipts
35074
- WHERE state IN ('succeeded', 'failed', 'cancelled')
35075
- AND rowid NOT IN (
35076
- SELECT rowid FROM relay_turn_receipts
35077
- WHERE state IN ('succeeded', 'failed', 'cancelled')
35078
- ORDER BY rowid DESC LIMIT ?
35079
- )`
35080
- ).run(MAX_TERMINAL_RECEIPTS);
35081
- }
35082
- };
35083
- /**
35084
- * The Attempt this live Runtime claimed for a command that has not reached a terminal state.
35085
- * Receipts disappear when the daemon process exits.
35086
- */
35087
- findUnsettledAttemptId = (commandId, sessionId) => {
35088
- const row = this.#database.prepare(`SELECT attempt_id, state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
35089
- if (typeof row !== "object" || row === null) {
35090
- return null;
35091
- }
35092
- const attemptId = Reflect.get(row, "attempt_id");
35093
- const state = Reflect.get(row, "state");
35094
- if (typeof attemptId !== "string" || attemptId.length === 0 || !isDaemonExecutionState(state)) {
35095
- return null;
35096
- }
35097
- return state === "dispatching" || state === "running" ? attemptId : null;
35098
- };
35099
- isTerminalExecution = (commandId, sessionId) => {
35100
- const row = this.#database.prepare(`SELECT state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
35101
- const state = typeof row === "object" && row !== null ? Reflect.get(row, "state") : void 0;
35102
- return state === "succeeded" || state === "failed" || state === "cancelled";
35103
- };
35104
- acknowledge = (acknowledgement) => this.#removeAcknowledgedEvent(acknowledgement.eventId, acknowledgement.sessionId);
35105
- quarantine = (rejection) => {
35106
- this.#database.exec("BEGIN IMMEDIATE");
35107
- try {
35108
- const stored = this.#database.prepare(
35109
- `SELECT byte_length FROM relay_session_event_outbox
35110
- WHERE event_id = ? AND session_id = ?`
35111
- ).get(rejection.eventId, rejection.sessionId);
35112
- if (stored === void 0) {
35113
- this.#database.exec("COMMIT");
35114
- return false;
35115
- }
35116
- const byteLength = rowNumber(stored, "byte_length");
35117
- const deletion = this.#database.prepare(
35118
- `DELETE FROM relay_session_event_outbox
35119
- WHERE event_id = ? AND session_id = ?`
35120
- ).run(rejection.eventId, rejection.sessionId);
35121
- if (deletion.changes !== 1) {
35122
- throw new Error("The rejected session event could not be removed from the in-memory outbox");
35123
- }
35124
- this.#decrementEventState(byteLength);
35125
- this.#database.exec("COMMIT");
35126
- return true;
35127
- } catch (error62) {
35128
- this.#database.exec("ROLLBACK");
35129
- throw error62;
35130
- }
35131
- };
35132
- close = () => {
35133
- this.#database.close();
35134
- };
35135
- enqueue = (sessionId, payload, attemptId = null) => {
35136
- return this.#enqueueBounded(sessionId, payload, attemptId ?? "", this.#limits.standardEventBytes);
35137
- };
35138
- enqueueCritical = (sessionId, payload, attemptId = "") => this.#enqueueBounded(sessionId, payload, attemptId, this.#limits.criticalEventBytes);
35139
- /**
35140
- * Bytes still available to standard Session events. The daemon uses this to shed
35141
- * superseded streaming events instead of filling the in-memory outbox, so a long Turn
35142
- * behind a slow Relay cannot make the next enqueue throw.
35143
- */
35144
- standardCapacityRemaining = () => {
35145
- const state = this.#database.prepare(
35146
- `SELECT total_bytes
35147
- FROM relay_session_event_outbox_state
35148
- WHERE singleton = 1`
35149
- ).get();
35150
- return this.#limits.standardEventBytes - rowNumber(state, "total_bytes");
35151
- };
35152
- claimRuntimeDelivery = (delivery) => {
35153
- const payloadBytes = new TextEncoder().encode(delivery.payload).byteLength;
35154
- this.#database.exec("BEGIN IMMEDIATE");
35155
- try {
35156
- const existing = this.#database.prepare(
35157
- `SELECT session_id, payload_json, state
35158
- FROM relay_runtime_deliveries
35159
- WHERE delivery_id = ?`
35160
- ).get(delivery.deliveryId);
35161
- if (existing !== void 0) {
35162
- const sessionId = rowString(existing, "session_id");
35163
- const payload = rowString(existing, "payload_json");
35164
- const state = runtimeDeliveryState(existing);
35165
- if (sessionId !== delivery.sessionId || payload !== delivery.payload) {
35166
- throw new Error("The Runtime delivery identity conflicts with its in-memory receipt");
35167
- }
35168
- this.#database.exec("COMMIT");
35169
- return new StoredRuntimeDelivery(delivery.deliveryId, sessionId, payload, state, true);
35170
- }
35171
- const usage = this.#database.prepare(
35172
- `SELECT COUNT(*) AS delivery_count,
35173
- COALESCE(SUM(payload_bytes), 0) AS delivery_bytes
35174
- FROM relay_runtime_deliveries`
35175
- ).get();
35176
- if (rowNumber(usage, "delivery_count") + 1 > this.#limits.runtimeDeliveryCount || rowNumber(usage, "delivery_bytes") + payloadBytes > this.#limits.runtimeDeliveryBytes) {
35177
- throw new RuntimeDeliveryInboxCapacityError();
35178
- }
35179
- this.#database.prepare(
35180
- `INSERT INTO relay_runtime_deliveries (
35181
- delivery_id, session_id, payload_json, payload_bytes, state, received_at
35182
- ) VALUES (?, ?, ?, ?, 'received', ?)`
35183
- ).run(delivery.deliveryId, delivery.sessionId, delivery.payload, payloadBytes, Date.now());
35184
- this.#database.exec("COMMIT");
35185
- return new StoredRuntimeDelivery(
35186
- delivery.deliveryId,
35187
- delivery.sessionId,
35188
- delivery.payload,
35189
- "received",
35190
- false
35191
- );
35192
- } catch (error62) {
35193
- this.#database.exec("ROLLBACK");
35194
- throw error62;
35195
- }
35196
- };
35197
- markRuntimeDeliveryCommitted = (deliveryId, sessionId) => {
35198
- this.#database.exec("BEGIN IMMEDIATE");
35199
- try {
35200
- const row = this.#database.prepare(
35201
- `SELECT state FROM relay_runtime_deliveries
35202
- WHERE delivery_id = ? AND session_id = ?`
35203
- ).get(deliveryId, sessionId);
35204
- if (row === void 0) {
35205
- this.#database.exec("COMMIT");
35206
- return false;
35207
- }
35208
- const state = runtimeDeliveryState(row);
35209
- if (state === "processed") {
35210
- this.#database.prepare(`DELETE FROM relay_runtime_deliveries WHERE delivery_id = ?`).run(deliveryId);
35211
- } else if (state === "received") {
35212
- this.#database.prepare(`UPDATE relay_runtime_deliveries SET state = 'relay_committed' WHERE delivery_id = ?`).run(deliveryId);
35213
- }
35214
- this.#database.exec("COMMIT");
35215
- return true;
35216
- } catch (error62) {
35217
- this.#database.exec("ROLLBACK");
35218
- throw error62;
35219
- }
35220
- };
35221
- markRuntimeDeliveryProcessed = (deliveryId, sessionId) => {
35222
- this.#database.exec("BEGIN IMMEDIATE");
35223
- try {
35224
- const row = this.#database.prepare(
35225
- `SELECT state FROM relay_runtime_deliveries
35226
- WHERE delivery_id = ? AND session_id = ?`
35227
- ).get(deliveryId, sessionId);
35228
- if (row === void 0) {
35229
- this.#database.exec("COMMIT");
35230
- return false;
35231
- }
35232
- const state = runtimeDeliveryState(row);
35233
- if (state === "relay_committed") {
35234
- this.#database.prepare(`DELETE FROM relay_runtime_deliveries WHERE delivery_id = ?`).run(deliveryId);
35235
- } else if (state === "received") {
35236
- this.#database.prepare(`UPDATE relay_runtime_deliveries SET state = 'processed' WHERE delivery_id = ?`).run(deliveryId);
35237
- }
35238
- this.#database.exec("COMMIT");
35239
- return true;
35240
- } catch (error62) {
35241
- this.#database.exec("ROLLBACK");
35242
- throw error62;
35243
- }
35244
- };
35245
- runtimeDeliveries = () => this.#database.prepare(
35246
- `SELECT delivery_id, session_id, payload_json, state
35247
- FROM relay_runtime_deliveries
35248
- ORDER BY received_at, delivery_id`
35249
- ).all().map(
35250
- (row) => new StoredRuntimeDelivery(
35251
- rowString(row, "delivery_id"),
35252
- rowString(row, "session_id"),
35253
- rowString(row, "payload_json"),
35254
- runtimeDeliveryState(row),
35255
- true
35256
- )
35257
- );
35258
- #enqueueBounded = (sessionId, payload, attemptId, maximumEventBytes) => {
35259
- const sourceKey = attemptId.length === 0 ? `runtime:${sessionId}` : `attempt:${sessionId}:${attemptId}`;
35260
- this.#database.exec("BEGIN IMMEDIATE");
35261
- try {
35262
- const state = this.#database.prepare(
35263
- `SELECT total_bytes, next_source_seq
35264
- FROM relay_session_event_outbox_state
35265
- WHERE singleton = 1`
35266
- ).get();
35267
- const nextSourceSeq = rowNumber(state, "next_source_seq");
35268
- if (nextSourceSeq < 1 || !Number.isSafeInteger(nextSourceSeq + 1)) {
35269
- throw new Error("SQLite returned an invalid event source sequence");
35270
- }
35271
- const envelope2 = {
35272
- eventId: crypto.randomUUID(),
35273
- kind: SESSION_EVENT_KIND,
35274
- payload,
35275
- sessionId,
35276
- source: attemptId.length === 0 ? { kind: "runtime", sourceSeq: nextSourceSeq.toString() } : {
35277
- attemptId,
35278
- kind: "attempt",
35279
- sourceSeq: nextSourceSeq.toString()
35280
- }
35281
- };
35282
- const encoded = encodeSessionEventEnvelope(envelope2);
35283
- const byteLength = new TextEncoder().encode(encoded).byteLength;
35284
- if (rowNumber(state, "total_bytes") + byteLength > maximumEventBytes) {
35285
- throw new SessionEventOutboxCapacityError();
35286
- }
35287
- this.#database.prepare(
35288
- `INSERT INTO relay_session_event_outbox (
35289
- event_id, session_id, source_key, byte_length, envelope_json
35290
- ) VALUES (?, ?, ?, ?, ?)`
35291
- ).run(envelope2.eventId, envelope2.sessionId, sourceKey, byteLength, encoded);
35292
- this.#database.prepare(
35293
- `UPDATE relay_session_event_outbox_state
35294
- SET event_count = event_count + 1,
35295
- total_bytes = total_bytes + ?,
35296
- next_source_seq = next_source_seq + 1
35297
- WHERE singleton = 1`
35298
- ).run(byteLength);
35299
- this.#database.exec("COMMIT");
35300
- return encoded;
35301
- } catch (error62) {
35302
- this.#database.exec("ROLLBACK");
35303
- throw error62;
35304
- }
35305
- };
35306
- #removeAcknowledgedEvent = (eventId, sessionId) => {
35307
- this.#database.exec("BEGIN IMMEDIATE");
35308
- try {
35309
- const stored = this.#database.prepare(
35310
- `SELECT byte_length FROM relay_session_event_outbox
35311
- WHERE event_id = ? AND session_id = ?`
35312
- ).get(eventId, sessionId);
35313
- if (stored === void 0) {
35314
- this.#database.exec("COMMIT");
35315
- return false;
35316
- }
35317
- const byteLength = rowNumber(stored, "byte_length");
35318
- const deletion = this.#database.prepare(
35319
- `DELETE FROM relay_session_event_outbox
35320
- WHERE event_id = ? AND session_id = ?`
35321
- ).run(eventId, sessionId);
35322
- if (deletion.changes !== 1) {
35323
- throw new Error("The acknowledged session event could not be removed from the in-memory outbox");
35324
- }
35325
- this.#decrementEventState(byteLength);
35326
- this.#database.exec("COMMIT");
35327
- return true;
35328
- } catch (error62) {
35329
- this.#database.exec("ROLLBACK");
35330
- throw error62;
35331
- }
35332
- };
35333
- #decrementEventState = (byteLength) => {
35334
- const result = this.#database.prepare(
35335
- `UPDATE relay_session_event_outbox_state
35336
- SET event_count = event_count - 1,
35337
- total_bytes = total_bytes - ?
35338
- WHERE singleton = 1 AND event_count > 0 AND total_bytes >= ?`
35339
- ).run(byteLength, byteLength);
35340
- if (result.changes !== 1) {
35341
- throw new Error("The Session event outbox capacity state is inconsistent");
35342
- }
35343
- };
35344
- pending = () => this.#database.prepare(
35345
- `SELECT envelope_json
35346
- FROM relay_session_event_outbox
35347
- ORDER BY ordinal`
35348
- ).all().map(readPendingEnvelope);
35349
- pendingBatch = (limit) => {
35350
- if (!Number.isSafeInteger(limit) || limit < 1) {
35351
- throw new Error("Session event replay batch limit must be a positive integer");
35352
- }
35353
- return this.#database.prepare(
35354
- `WITH ranked_events AS (
35355
- SELECT ordinal,
35356
- ROW_NUMBER() OVER (
35357
- PARTITION BY source_key
35358
- ORDER BY ordinal
35359
- ) AS source_position
35360
- FROM relay_session_event_outbox
35361
- )
35362
- SELECT outbox.envelope_json
35363
- FROM ranked_events AS ranked
35364
- INNER JOIN relay_session_event_outbox AS outbox
35365
- ON outbox.ordinal = ranked.ordinal
35366
- ORDER BY ranked.source_position, outbox.ordinal
35367
- LIMIT ?`
35368
- ).all(limit).map(readPendingEnvelope);
35369
- };
35370
- pendingSourceHeads = (limit, excludedEventIds, excludedSourceKeys) => {
35371
- if (!Number.isSafeInteger(limit) || limit < 1) {
35372
- throw new Error("Session event replay batch limit must be a positive integer");
35373
- }
35374
- const exclusions = [];
35375
- const parameters = [];
35376
- if (excludedEventIds.length > 0) {
35377
- exclusions.push(`event_id NOT IN (${excludedEventIds.map(() => "?").join(", ")})`);
35378
- parameters.push(...excludedEventIds);
35379
- }
35380
- if (excludedSourceKeys.length > 0) {
35381
- exclusions.push(`source_key NOT IN (${excludedSourceKeys.map(() => "?").join(", ")})`);
35382
- parameters.push(...excludedSourceKeys);
35383
- }
35384
- parameters.push(limit.toString());
35385
- const where = exclusions.length === 0 ? "" : `WHERE ${exclusions.join(" AND ")}`;
35386
- return this.#database.prepare(
35387
- `WITH available_events AS (
35388
- SELECT ordinal, source_key
35389
- FROM relay_session_event_outbox
35390
- ${where}
35391
- ), ranked_events AS (
35392
- SELECT ordinal,
35393
- ROW_NUMBER() OVER (
35394
- PARTITION BY source_key
35395
- ORDER BY ordinal
35396
- ) AS source_position
35397
- FROM available_events
35398
- )
35399
- SELECT outbox.envelope_json
35400
- FROM ranked_events AS ranked
35401
- INNER JOIN relay_session_event_outbox AS outbox
35402
- ON outbox.ordinal = ranked.ordinal
35403
- WHERE ranked.source_position = 1
35404
- ORDER BY outbox.ordinal
35405
- LIMIT ?`
35406
- ).all(...parameters).map(readPendingEnvelope);
35407
- };
35408
- };
35409
- function validateLimits(limits) {
35410
- const values = [
35411
- limits.criticalEventBytes,
35412
- limits.runtimeDeliveryBytes,
35413
- limits.runtimeDeliveryCount,
35414
- limits.standardEventBytes
35415
- ];
35416
- if (values.some((value) => !Number.isSafeInteger(value) || value < 1)) {
35417
- throw new Error("Session event outbox limits must be positive integers");
35418
- }
35419
- if (limits.criticalEventBytes < limits.standardEventBytes) {
35420
- throw new Error("Critical Session event capacity must include the standard capacity");
35421
- }
35422
- }
35423
- function runtimeDeliveryState(row) {
35424
- const state = rowString(row, "state");
35425
- if (state !== "received" && state !== "relay_committed" && state !== "processed") {
35426
- throw new Error("SQLite returned an invalid Runtime delivery state");
35427
- }
35428
- return state;
35429
- }
35430
- function isDaemonExecutionState(value) {
35431
- return value === "cancelled" || value === "dispatching" || value === "failed" || value === "running" || value === "succeeded";
35432
- }
35433
-
35434
34943
  // src/relay-connection/session-event-publisher.ts
35435
34944
  import { WebSocket as WebSocket4 } from "undici";
35436
- var DaemonSessionEventConnectionState = class {
35437
- };
35438
- var DisconnectedDaemonSessionEventState = class extends DaemonSessionEventConnectionState {
35439
- disconnect = () => this;
35440
- matches = () => false;
35441
- send = () => false;
35442
- };
35443
- var ConnectedDaemonSessionEventState = class extends DaemonSessionEventConnectionState {
35444
- #socket;
35445
- constructor(socket) {
35446
- super();
35447
- this.#socket = socket;
35448
- }
35449
- disconnect = (socket) => socket === this.#socket ? new DisconnectedDaemonSessionEventState() : this;
35450
- matches = (socket) => socket === this.#socket;
35451
- send = (message) => {
35452
- if (this.#socket.readyState !== WebSocket4.OPEN) {
35453
- return false;
35454
- }
35455
- try {
35456
- this.#socket.send(encodeDaemonToServiceMessage(message));
35457
- return true;
35458
- } catch {
35459
- return false;
35460
- }
35461
- };
35462
- };
35463
- var SESSION_EVENT_REPLAY_WINDOW = 16;
35464
- var SESSION_EVENT_SOURCE_REPLAY_WINDOW = 4;
35465
- var SESSION_EVENT_REPLAY_BYTE_LIMIT = 32 * 1024 * 1024;
35466
- function reservesSessionEventCapacity(event) {
35467
- if (event.kind === SESSION_COMPLETED_KIND || event.kind === SESSION_FAILED_KIND) {
35468
- return true;
35469
- }
35470
- return event.kind === AGENT_ACTIVITY_KIND && (event.activityType === "progress" || event.activityType === "reasoning") && (event.status === "completed" || event.status === "failed");
35471
- }
35472
- var InFlightSessionEvent = class {
35473
- byteLength;
35474
- sourceKey;
35475
- constructor(sourceKey, byteLength) {
35476
- this.byteLength = byteLength;
35477
- this.sourceKey = sourceKey;
35478
- }
35479
- };
35480
- function sessionEventSourceKey(envelope2) {
35481
- return envelope2.source.kind === "attempt" ? `attempt:${envelope2.sessionId}:${envelope2.source.attemptId}` : `runtime:${envelope2.sessionId}`;
35482
- }
34945
+ var MAX_LIVE_EVENT_BUFFERED_BYTES = 16 * 1024 * 1024;
35483
34946
  var DaemonSessionEventPublisher = class {
35484
- #outbox;
35485
- #inFlightEvents = /* @__PURE__ */ new Map();
35486
- #pausedSources = /* @__PURE__ */ new Map();
35487
- #shedEventKinds = /* @__PURE__ */ new Set();
35488
- #timer;
35489
- #inFlightBytes = 0;
35490
- #connection = new DisconnectedDaemonSessionEventState();
35491
- constructor(outbox, timer) {
35492
- this.#outbox = outbox;
35493
- this.#timer = timer;
35494
- }
34947
+ #socket = null;
34948
+ #reportedDrop = false;
35495
34949
  connect = (socket) => {
35496
- this.#connection = new ConnectedDaemonSessionEventState(socket);
35497
- this.#clearInFlight();
35498
- this.#publishNextBatch();
34950
+ this.#socket = socket;
34951
+ this.#reportedDrop = false;
35499
34952
  };
35500
34953
  disconnect = (socket) => {
35501
- if (!this.#connection.matches(socket)) {
35502
- return;
35503
- }
35504
- this.#connection = this.#connection.disconnect(socket);
35505
- this.#clearInFlight();
35506
- };
35507
- recordAttempt = (sessionId, event, attemptId) => {
35508
- const encoded = encodeRecordedSessionEvent(event);
35509
- if (reservesSessionEventCapacity(event)) {
35510
- this.#enqueueReserved(sessionId, encoded, attemptId, event.kind);
35511
- } else {
35512
- this.#enqueueStandard(sessionId, encoded, attemptId, event.kind);
35513
- }
35514
- this.#publishNextBatch();
35515
- };
35516
- recordRuntime = (sessionId, event) => {
35517
- this.#enqueueStandard(sessionId, encodeRecordedSessionEvent(event), "", event.kind);
35518
- this.#publishNextBatch();
35519
- };
35520
- /**
35521
- * Enqueue a standard event, shedding it instead of ending the daemon when the
35522
- * in-memory outbox is full.
35523
- *
35524
- * A capacity error used to escape the coalescing timer that publishes activities,
35525
- * so the process exited and every restart died on the same retained backlog. A full
35526
- * outbox is a recoverable runtime condition, not a fatal one: narration increments are
35527
- * superseded by the completed snapshot, so they are shed first, and any other streaming
35528
- * event is shed only at the wall rather than terminating the daemon.
35529
- */
35530
- #enqueueStandard = (sessionId, encoded, attemptId, kind) => {
35531
- if (kind === AGENT_ACTIVITY_NARRATION_KIND && this.#outbox.standardCapacityRemaining() <= 0) {
35532
- this.#reportShedEvent(kind);
35533
- return;
35534
- }
35535
- try {
35536
- this.#outbox.enqueue(sessionId, encoded, attemptId);
35537
- } catch (error62) {
35538
- if (!(error62 instanceof SessionEventOutboxCapacityError)) {
35539
- throw error62;
35540
- }
35541
- this.#reportShedEvent(kind);
35542
- }
35543
- };
35544
- /**
35545
- * Enqueue on the reserved budget, degrading to a reported drop instead of raising.
35546
- * Streaming events are shed before this budget is reached, so a Turn's terminal
35547
- * events and the completed snapshot that carries its narration still land; a drop
35548
- * here is the last resort for a backlog no acknowledgement can drain.
35549
- */
35550
- #enqueueReserved = (sessionId, encoded, attemptId, kind) => {
35551
- try {
35552
- this.#outbox.enqueueCritical(sessionId, encoded, attemptId);
35553
- } catch (error62) {
35554
- if (!(error62 instanceof SessionEventOutboxCapacityError)) {
35555
- throw error62;
35556
- }
35557
- this.#reportShedEvent(kind);
35558
- }
35559
- };
35560
- #reportShedEvent = (kind) => {
35561
- if (this.#shedEventKinds.has(kind)) {
35562
- return;
34954
+ if (this.#socket === socket) {
34955
+ this.#socket = null;
35563
34956
  }
35564
- this.#shedEventKinds.add(kind);
35565
- console.warn(`Mobius daemon is dropping queued "${kind}" events because the Session event outbox is full`);
35566
34957
  };
35567
- acknowledge = (acknowledgement) => {
35568
- if (!this.#outbox.acknowledge(acknowledgement)) {
34958
+ publish = (sessionId, event) => {
34959
+ const socket = this.#socket;
34960
+ if (socket === null || socket.readyState !== WebSocket4.OPEN) {
34961
+ this.#reportDrop();
35569
34962
  return;
35570
34963
  }
35571
- this.#removeInFlight(acknowledgement.eventId);
35572
- this.#publishNextBatch();
35573
- };
35574
- quarantine = (rejection) => {
35575
- const quarantined = this.#outbox.quarantine(rejection);
35576
- if (!quarantined) {
35577
- return false;
35578
- }
35579
- this.#removeInFlight(rejection.eventId);
35580
- this.#publishNextBatch();
35581
- return true;
35582
- };
35583
- defer = (deferred) => {
35584
- const inFlight = this.#inFlightEvents.get(deferred.eventId);
35585
- if (inFlight === void 0) {
34964
+ if (socket.bufferedAmount >= MAX_LIVE_EVENT_BUFFERED_BYTES) {
34965
+ this.#socket = null;
34966
+ socket.close(1013, "Live event backpressure");
34967
+ this.#reportDrop();
35586
34968
  return;
35587
34969
  }
35588
- this.#clearInFlightSource(inFlight.sourceKey);
35589
- if (!this.#pausedSources.has(inFlight.sourceKey)) {
35590
- this.#pausedSources.set(
35591
- inFlight.sourceKey,
35592
- this.#timer.schedule(() => {
35593
- this.#pausedSources.delete(inFlight.sourceKey);
35594
- this.#publishNextBatch();
35595
- }, deferred.retryAfterMilliseconds)
34970
+ try {
34971
+ socket.send(
34972
+ encodeDaemonToServiceMessage({
34973
+ kind: SESSION_EVENT_KIND,
34974
+ payload: encodeRecordedSessionEvent(event),
34975
+ sessionId
34976
+ })
35596
34977
  );
34978
+ } catch {
34979
+ this.#reportDrop();
35597
34980
  }
35598
- this.#publishNextBatch();
35599
34981
  };
35600
34982
  close = () => {
35601
- for (const task of this.#pausedSources.values()) {
35602
- task.cancel();
35603
- }
35604
- this.#pausedSources.clear();
35605
- this.#clearInFlight();
35606
- };
35607
- #publishNextBatch = () => {
35608
- while (this.#inFlightEvents.size < SESSION_EVENT_REPLAY_WINDOW) {
35609
- const sourceCounts = /* @__PURE__ */ new Map();
35610
- for (const inFlight of this.#inFlightEvents.values()) {
35611
- sourceCounts.set(inFlight.sourceKey, (sourceCounts.get(inFlight.sourceKey) ?? 0) + 1);
35612
- }
35613
- const saturatedSources = [...sourceCounts.entries()].filter(([, count]) => count >= SESSION_EVENT_SOURCE_REPLAY_WINDOW).map(([sourceKey]) => sourceKey);
35614
- const batch = this.#outbox.pendingSourceHeads(
35615
- SESSION_EVENT_REPLAY_WINDOW - this.#inFlightEvents.size,
35616
- [...this.#inFlightEvents.keys()],
35617
- [...this.#pausedSources.keys(), ...saturatedSources]
35618
- );
35619
- let sent = 0;
35620
- for (const encoded of batch) {
35621
- const envelope2 = decodeSessionEventEnvelope(encoded);
35622
- const sourceKey = sessionEventSourceKey(envelope2);
35623
- const sourceCount = sourceCounts.get(sourceKey) ?? 0;
35624
- if (sourceCount >= SESSION_EVENT_SOURCE_REPLAY_WINDOW) {
35625
- continue;
35626
- }
35627
- const byteLength = new TextEncoder().encode(encoded).byteLength;
35628
- if (this.#inFlightBytes + byteLength > SESSION_EVENT_REPLAY_BYTE_LIMIT) {
35629
- continue;
35630
- }
35631
- if (!this.#connection.send(envelope2)) {
35632
- this.#clearInFlight();
35633
- return;
35634
- }
35635
- this.#inFlightEvents.set(envelope2.eventId, new InFlightSessionEvent(sourceKey, byteLength));
35636
- this.#inFlightBytes += byteLength;
35637
- sourceCounts.set(sourceKey, sourceCount + 1);
35638
- sent += 1;
35639
- }
35640
- if (sent === 0) {
35641
- return;
35642
- }
35643
- }
34983
+ this.#socket = null;
35644
34984
  };
35645
- #removeInFlight = (eventId) => {
35646
- const inFlight = this.#inFlightEvents.get(eventId);
35647
- if (inFlight === void 0) {
34985
+ #reportDrop = () => {
34986
+ if (this.#reportedDrop) {
35648
34987
  return;
35649
34988
  }
35650
- this.#inFlightEvents.delete(eventId);
35651
- this.#inFlightBytes -= inFlight.byteLength;
35652
- };
35653
- #clearInFlight = () => {
35654
- this.#inFlightEvents.clear();
35655
- this.#inFlightBytes = 0;
35656
- };
35657
- #clearInFlightSource = (sourceKey) => {
35658
- for (const [eventId, inFlight] of this.#inFlightEvents) {
35659
- if (inFlight.sourceKey !== sourceKey) {
35660
- continue;
35661
- }
35662
- this.#inFlightEvents.delete(eventId);
35663
- this.#inFlightBytes -= inFlight.byteLength;
35664
- }
34989
+ this.#reportedDrop = true;
34990
+ console.warn("Mobius daemon dropped live Session events while the Relay was unavailable");
35665
34991
  };
35666
34992
  };
35667
34993
 
@@ -35735,7 +35061,7 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
35735
35061
  {
35736
35062
  agentId: agent.id,
35737
35063
  kind: AGENT_INSTALL_REQUEST_KIND,
35738
- requestId: `automatic-integration-${randomUUID5()}`
35064
+ requestId: `automatic-integration-${randomUUID6()}`
35739
35065
  },
35740
35066
  signal
35741
35067
  );
@@ -35780,9 +35106,8 @@ async function refreshAgentCatalog(config2, resolveEnvironment, signal) {
35780
35106
  throw error62;
35781
35107
  }
35782
35108
  }
35783
- async function runRelayConnection(config2, directories, audit, sessions, installations, installationObserver, nativeSessions, outbox, publisher, activeTurns, activeAttemptIds, connectionEpoch, diagnostics, onConnected, signal, timer, resolveAgentCatalogEnvironment) {
35109
+ async function runRelayConnection(config2, directories, audit, sessions, installations, installationObserver, nativeSessions, operations, publisher, activeTurns, connectionEpoch, diagnostics, onConnected, signal, timer, resolveAgentCatalogEnvironment) {
35784
35110
  const relayUrl = new URL(config2.relayUrl);
35785
- relayUrl.searchParams.set("deliveryReceipts", "1");
35786
35111
  relayUrl.searchParams.set("liveness", "1");
35787
35112
  const socket = await connectRelay(relayUrl, signal);
35788
35113
  const reconnectingTurns = [...activeTurns.values()];
@@ -35833,226 +35158,48 @@ async function runRelayConnection(config2, directories, audit, sessions, install
35833
35158
  closeRelaySocket(socket, code, reason);
35834
35159
  rejectConnection(failure2);
35835
35160
  };
35836
- const processingDeliveryIds = /* @__PURE__ */ new Set();
35837
- const sessionAvailable = (command) => {
35838
- if (command.disposition === SessionPromptDisposition.Steer) {
35839
- return true;
35840
- }
35841
- const first = [...activeTurns.values()].find(
35842
- (turn) => turn.command.sessionId === command.sessionId && turn.command.disposition !== SessionPromptDisposition.Steer
35843
- );
35844
- return first === void 0 || first.command.commandId === command.commandId;
35845
- };
35846
- const processDeliveredPrompt = async (delivery, command, trackActiveAttempt, execute) => {
35847
- if (command.sessionId !== delivery.sessionId) {
35848
- throw new Error("Runtime delivery Session identity does not match its payload");
35849
- }
35850
- const active = activeTurns.get(command.commandId);
35851
- if (active !== void 0) {
35852
- await active.completion;
35853
- return;
35854
- }
35855
- const receipt = outbox.claimExecution(command.commandId, command.sessionId, delivery.payload);
35856
- if (receipt.kind === "duplicate") {
35857
- if (receipt.state === "running") {
35858
- reportFailure(
35859
- publisher,
35860
- command,
35861
- "agent_execution_interrupted",
35862
- "The local Agent execution was interrupted before it completed",
35863
- receipt.attemptId
35864
- );
35865
- outbox.transitionExecution(command.commandId, "failed");
35866
- return;
35867
- }
35868
- if (receipt.state !== "dispatching") {
35869
- return;
35870
- }
35871
- }
35872
- const turn = new ActiveDaemonTurn(command, receipt.attemptId);
35873
- activeTurns.set(command.commandId, turn);
35874
- const activateAttempt = () => {
35875
- const stream = turn.accept();
35876
- if (trackActiveAttempt) {
35877
- activeAttemptIds.set(command.sessionId, receipt.attemptId);
35878
- }
35879
- return stream;
35880
- };
35881
- try {
35882
- await execute(receipt.attemptId, activateAttempt, turn.signal, turn);
35883
- } finally {
35884
- activeTurns.delete(command.commandId);
35885
- if (activeAttemptIds.get(command.sessionId) === receipt.attemptId) {
35886
- activeAttemptIds.delete(command.sessionId);
35887
- }
35888
- turn.finish();
35889
- }
35161
+ const waitForTurnCompletion = (turn, waitSignal) => {
35162
+ waitSignal.throwIfAborted();
35163
+ return new Promise((resolve9, reject2) => {
35164
+ let settled = false;
35165
+ const finish = (result) => {
35166
+ if (settled) {
35167
+ return;
35168
+ }
35169
+ settled = true;
35170
+ waitSignal.removeEventListener("abort", onAbort);
35171
+ if (result.kind === "completed") {
35172
+ resolve9();
35173
+ } else {
35174
+ reject2(result.error);
35175
+ }
35176
+ };
35177
+ const onAbort = () => finish({ error: waitSignal.reason, kind: "failed" });
35178
+ waitSignal.addEventListener("abort", onAbort, { once: true });
35179
+ void turn.completion.then(
35180
+ () => finish({ kind: "completed" }),
35181
+ (error62) => finish({ error: error62, kind: "failed" })
35182
+ );
35183
+ });
35890
35184
  };
35891
- const processDeliveredPayload = async (delivery) => {
35892
- const message = decodeServiceToDaemonMessage(delivery.payload);
35893
- const kind = message.kind;
35894
- if (kind === SESSION_CANCEL_KIND) {
35895
- const cancellation = message;
35896
- if (cancellation.sessionId !== delivery.sessionId) {
35897
- throw new Error("Runtime delivery Session identity does not match its payload");
35898
- }
35899
- const turn = activeTurns.get(cancellation.commandId);
35900
- if (turn === void 0 || !turn.matches(cancellation)) {
35901
- settleAbandonedTurn(publisher, outbox, audit, cancellation);
35902
- return;
35903
- }
35904
- if (!turn.requestCancellation()) {
35905
- return;
35906
- }
35907
- audit.record({
35908
- commandId: cancellation.commandId,
35909
- event: "session_cancellation_requested",
35910
- sessionId: cancellation.sessionId
35911
- });
35912
- await sessions.cancelPrompt(cancellation.sessionId);
35913
- return;
35185
+ const waitForSessionAvailability = async (command, waitSignal) => {
35186
+ if (command.disposition === SessionPromptDisposition.Steer) {
35187
+ return "available";
35914
35188
  }
35915
- if (kind === SESSION_CONFIGURE_KIND) {
35916
- const command = message;
35917
- if (command.sessionId !== delivery.sessionId) {
35918
- throw new Error("Runtime delivery Session identity does not match its payload");
35919
- }
35920
- await executeSessionConfigure(
35921
- publisher,
35922
- socket,
35923
- command,
35924
- config2,
35925
- directories,
35926
- audit,
35927
- sessions,
35928
- connectionController.signal
35189
+ for (; ; ) {
35190
+ const first = [...activeTurns.values()].find(
35191
+ (turn) => turn.command.sessionId === command.sessionId && turn.command.disposition !== SessionPromptDisposition.Steer
35929
35192
  );
35930
- return;
35931
- }
35932
- if (kind === SESSION_PERMISSION_RESPOND_KIND) {
35933
- const command = message;
35934
- if (command.sessionId !== delivery.sessionId) {
35935
- throw new Error("Runtime delivery Session identity does not match its payload");
35193
+ if (first === void 0 || first.command.commandId === command.commandId) {
35194
+ return command.disposition !== SessionPromptDisposition.Queue || operations.isTerminalExecution(command.targetCommandId, command.sessionId) ? "available" : "queue-target-unavailable";
35936
35195
  }
35937
- try {
35938
- await sessions.respondPermission(command);
35939
- audit.record({
35940
- commandId: command.interactionId,
35941
- event: "session_permission_resolved",
35942
- sessionId: command.sessionId
35943
- });
35944
- } catch (error62) {
35945
- reportOperationFailure(socket, command.interactionId, command.sessionId, error62);
35946
- }
35947
- return;
35948
- }
35949
- if (kind === SESSION_ELICITATION_RESPOND_KIND) {
35950
- const command = message;
35951
- if (command.sessionId !== delivery.sessionId) {
35952
- throw new Error("Runtime delivery Session identity does not match its payload");
35953
- }
35954
- try {
35955
- await sessions.respondElicitation(command);
35956
- audit.record({
35957
- commandId: command.interactionId,
35958
- event: "session_elicitation_resolved",
35959
- sessionId: command.sessionId
35960
- });
35961
- } catch (error62) {
35962
- reportOperationFailure(socket, command.interactionId, command.sessionId, error62);
35196
+ if (command.disposition !== SessionPromptDisposition.Queue) {
35197
+ return "busy";
35963
35198
  }
35964
- return;
35965
- }
35966
- if (kind === SESSION_PROMPT_KIND) {
35967
- const command = message;
35968
- await processDeliveredPrompt(
35969
- delivery,
35970
- command,
35971
- command.disposition !== SessionPromptDisposition.Steer,
35972
- (attemptId, activateAttempt, executionSignal, turn) => executePrompt(
35973
- outbox,
35974
- publisher,
35975
- command,
35976
- config2,
35977
- directories,
35978
- audit,
35979
- sessions,
35980
- attemptId,
35981
- activateAttempt,
35982
- () => sessionAvailable(command),
35983
- timer,
35984
- executionSignal,
35985
- turn.recordText
35986
- )
35987
- );
35988
- return;
35989
- }
35990
- throw new Error("Runtime delivery contains an unsupported protocol message");
35991
- };
35992
- const processRuntimeDelivery = (delivery, state) => {
35993
- if (state === "processed" || processingDeliveryIds.has(delivery.deliveryId)) {
35994
- return;
35995
- }
35996
- processingDeliveryIds.add(delivery.deliveryId);
35997
- void processDeliveredPayload(delivery).then(() => {
35998
- outbox.markRuntimeDeliveryProcessed(delivery.deliveryId, delivery.sessionId);
35999
- }).catch((error62) => {
36000
- if (connectionController.signal.aborted) {
36001
- return;
36002
- }
36003
- console.error("Mobius daemon could not process a in-memory Runtime delivery", error62);
36004
- failAndClose(
36005
- new Error("Runtime delivery processing failed", { cause: error62 }),
36006
- 4008,
36007
- "Invalid Runtime delivery",
36008
- "delivery"
36009
- );
36010
- }).finally(() => processingDeliveryIds.delete(delivery.deliveryId));
36011
- };
36012
- const receiveRuntimeDelivery = (delivery) => {
36013
- const payload = decodeServiceToDaemonMessage(delivery.payload);
36014
- const payloadKind = payload.kind;
36015
- let payloadSessionId = "";
36016
- if (payloadKind === SESSION_CANCEL_KIND) {
36017
- payloadSessionId = payload.sessionId;
36018
- } else if (payloadKind === SESSION_CONFIGURE_KIND) {
36019
- payloadSessionId = payload.sessionId;
36020
- } else if (payloadKind === SESSION_PERMISSION_RESPOND_KIND) {
36021
- payloadSessionId = payload.sessionId;
36022
- } else if (payloadKind === SESSION_ELICITATION_RESPOND_KIND) {
36023
- payloadSessionId = payload.sessionId;
36024
- } else if (payloadKind === SESSION_PROMPT_KIND) {
36025
- payloadSessionId = payload.sessionId;
36026
- } else {
36027
- throw new Error("Runtime delivery contains an unsupported protocol message");
36028
- }
36029
- if (payloadSessionId !== delivery.sessionId) {
36030
- throw new Error("Runtime delivery Session identity does not match its payload");
36031
- }
36032
- const stored = outbox.claimRuntimeDelivery(delivery);
36033
- send(socket, {
36034
- deliveryId: delivery.deliveryId,
36035
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
36036
- sessionId: delivery.sessionId
36037
- });
36038
- processRuntimeDelivery(delivery, stored.state);
36039
- };
36040
- const resumeRuntimeDeliveries = () => {
36041
- for (const stored of outbox.runtimeDeliveries()) {
36042
- const delivery = {
36043
- deliveryId: stored.deliveryId,
36044
- kind: RUNTIME_DELIVERY_KIND,
36045
- payload: stored.payload,
36046
- sessionId: stored.sessionId
36047
- };
36048
- if (stored.state !== "relay_committed") {
36049
- send(socket, {
36050
- deliveryId: stored.deliveryId,
36051
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
36052
- sessionId: stored.sessionId
36053
- });
35199
+ if (first.command.commandId !== command.targetCommandId) {
35200
+ return "queue-target-unavailable";
36054
35201
  }
36055
- processRuntimeDelivery(delivery, stored.state);
35202
+ await waitForTurnCompletion(first, waitSignal);
36056
35203
  }
36057
35204
  };
36058
35205
  const connectionLiveness = new RelayConnectionLiveness(timer, {
@@ -36111,39 +35258,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36111
35258
  try {
36112
35259
  const message = decodeServiceToDaemonMessage(encoded);
36113
35260
  const kind = message.kind;
36114
- if (kind === RUNTIME_DELIVERY_COMMITTED_KIND) {
36115
- const committed = message;
36116
- if (!outbox.markRuntimeDeliveryCommitted(committed.deliveryId, committed.sessionId)) {
36117
- console.warn("Mobius daemon ignored confirmation for an unknown Runtime delivery");
36118
- }
36119
- return;
36120
- }
36121
- if (kind === RUNTIME_DELIVERY_KIND) {
36122
- receiveRuntimeDelivery(message);
36123
- return;
36124
- }
36125
- if (kind === SESSION_EVENT_ACK_KIND) {
36126
- publisher.acknowledge(message);
36127
- return;
36128
- }
36129
- if (kind === SESSION_EVENT_DEFERRED_KIND) {
36130
- publisher.defer(message);
36131
- return;
36132
- }
36133
- if (kind === SESSION_EVENT_REJECTED_KIND) {
36134
- const rejection = message;
36135
- if (publisher.quarantine(rejection)) {
36136
- audit.record({
36137
- commandId: rejection.eventId,
36138
- details: { code: rejection.code },
36139
- event: "session_event_rejected",
36140
- sessionId: rejection.sessionId
36141
- });
36142
- } else {
36143
- console.warn("Mobius daemon ignored a rejection for an unknown session event");
36144
- }
36145
- return;
36146
- }
36147
35261
  if (kind === SESSION_LIVE_HISTORY_LOAD_KIND) {
36148
35262
  const command2 = decodeSessionLiveHistoryLoad(encoded);
36149
35263
  void executeSessionLiveHistoryLoad(
@@ -36621,7 +35735,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36621
35735
  const cancellation = message;
36622
35736
  const turn2 = activeTurns.get(cancellation.commandId);
36623
35737
  if (turn2 === void 0 || !turn2.matches(cancellation)) {
36624
- settleAbandonedTurn(publisher, outbox, audit, cancellation);
35738
+ settleAbandonedTurn(publisher, operations, audit, cancellation);
36625
35739
  return;
36626
35740
  }
36627
35741
  if (!turn2.requestCancellation()) {
@@ -36717,14 +35831,14 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36717
35831
  if (activeTurns.has(command.commandId)) {
36718
35832
  return;
36719
35833
  }
36720
- const receipt = outbox.claimExecution(command.commandId, command.sessionId, encoded);
35834
+ const receipt = operations.claimExecution(command.commandId, command.sessionId, encoded);
36721
35835
  if (receipt.kind === "duplicate") {
36722
35836
  return;
36723
35837
  }
36724
35838
  const turn = new ActiveDaemonTurn(command, receipt.attemptId);
36725
35839
  activeTurns.set(command.commandId, turn);
36726
35840
  void executePrompt(
36727
- outbox,
35841
+ operations,
36728
35842
  publisher,
36729
35843
  command,
36730
35844
  config2,
@@ -36732,32 +35846,20 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36732
35846
  audit,
36733
35847
  sessions,
36734
35848
  receipt.attemptId,
36735
- () => {
36736
- const stream = turn.accept();
36737
- if (command.disposition !== SessionPromptDisposition.Steer) {
36738
- activeAttemptIds.set(command.sessionId, receipt.attemptId);
36739
- }
36740
- return stream;
36741
- },
36742
- () => sessionAvailable(command),
35849
+ turn.accept,
35850
+ (waitSignal) => waitForSessionAvailability(command, waitSignal),
36743
35851
  timer,
36744
35852
  turn.signal,
36745
- turn.recordText
35853
+ turn.recordText,
35854
+ turn.cancellationRequested
36746
35855
  ).catch((error62) => {
36747
35856
  console.error("Mobius daemon turn failed", error62);
36748
35857
  }).finally(() => {
36749
35858
  activeTurns.delete(command.commandId);
36750
- if (activeAttemptIds.get(command.sessionId) === receipt.attemptId) {
36751
- activeAttemptIds.delete(command.sessionId);
36752
- }
36753
35859
  turn.finish();
36754
35860
  });
36755
35861
  } catch (error62) {
36756
35862
  console.error("Mobius daemon rejected a message", error62);
36757
- if (error62 instanceof RuntimeDeliveryInboxCapacityError) {
36758
- failAndClose(error62, 4013, "Runtime delivery queue full", "delivery_backpressure");
36759
- return;
36760
- }
36761
35863
  failAndClose(
36762
35864
  new Error("Relay sent an invalid protocol message", { cause: error62 }),
36763
35865
  4008,
@@ -36775,7 +35877,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36775
35877
  return;
36776
35878
  }
36777
35879
  publisher.connect(socket);
36778
- resumeRuntimeDeliveries();
36779
35880
  },
36780
35881
  (error62) => {
36781
35882
  if (finished) {
@@ -36797,7 +35898,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
36797
35898
  turn.abortDaemon();
36798
35899
  }
36799
35900
  publisher.connect(socket);
36800
- resumeRuntimeDeliveries();
36801
35901
  return;
36802
35902
  }
36803
35903
  failAndClose(
@@ -36834,17 +35934,11 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
36834
35934
  stateDirectory
36835
35935
  });
36836
35936
  const sessionStore = new MemoryAcpSessionStore();
36837
- const outbox = new SessionEventOutbox();
36838
- const publisher = new DaemonSessionEventPublisher(outbox, timer);
35937
+ const operations = new DaemonOperationState();
35938
+ const publisher = new DaemonSessionEventPublisher();
36839
35939
  const activeTurns = /* @__PURE__ */ new Map();
36840
- const activeAttemptIds = /* @__PURE__ */ new Map();
36841
35940
  const recordSessionEvent = (sessionId, event) => {
36842
- const attemptId = activeAttemptIds.get(sessionId);
36843
- if (attemptId === void 0) {
36844
- publisher.recordRuntime(sessionId, event);
36845
- return;
36846
- }
36847
- publisher.recordAttempt(sessionId, event, attemptId);
35941
+ publisher.publish(sessionId, event);
36848
35942
  };
36849
35943
  const sessions = new AcpSessionManager(
36850
35944
  new DaemonAcpObserver(recordSessionEvent),
@@ -36949,10 +36043,9 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
36949
36043
  installations,
36950
36044
  installationObserver,
36951
36045
  nativeSessions,
36952
- outbox,
36046
+ operations,
36953
36047
  publisher,
36954
36048
  activeTurns,
36955
- activeAttemptIds,
36956
36049
  connectionEpoch,
36957
36050
  diagnostics,
36958
36051
  () => {
@@ -36998,7 +36091,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
36998
36091
  try {
36999
36092
  publisher.close();
37000
36093
  } finally {
37001
- outbox.close();
36094
+ operations.close();
37002
36095
  }
37003
36096
  }
37004
36097
  }
@@ -37014,7 +36107,7 @@ import { basename as basename7, resolve as resolve6 } from "node:path";
37014
36107
  import { fetch as fetch5 } from "undici";
37015
36108
 
37016
36109
  // src/storage/runtime-installation-store.ts
37017
- import { createHash as createHash5, randomUUID as randomUUID6 } from "node:crypto";
36110
+ import { createHash as createHash5, randomUUID as randomUUID7 } from "node:crypto";
37018
36111
  import { mkdir as mkdir4, open as open5, readdir as readdir3, rename as rename3, unlink, writeFile as writeFile3 } from "node:fs/promises";
37019
36112
  import { dirname as dirname4, join as join17, resolve as resolve5 } from "node:path";
37020
36113
  var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
@@ -37145,10 +36238,10 @@ function parseRelayOrigin(value) {
37145
36238
  return origin;
37146
36239
  }
37147
36240
  function connectionId() {
37148
- return `mcn_${randomUUID6().replaceAll("-", "")}`;
36241
+ return `mcn_${randomUUID7().replaceAll("-", "")}`;
37149
36242
  }
37150
36243
  function installationId() {
37151
- return `min_${randomUUID6().replaceAll("-", "")}`;
36244
+ return `min_${randomUUID7().replaceAll("-", "")}`;
37152
36245
  }
37153
36246
  function channelIndexFileName(channelId) {
37154
36247
  return `mci_${createHash5("sha256").update(channelId).digest("hex")}.json`;
@@ -37260,7 +36353,7 @@ async function readJsonFile(path2, signal, missingCode) {
37260
36353
  async function writeJsonAtomically(path2, value, signal) {
37261
36354
  signal.throwIfAborted();
37262
36355
  const directory = dirname4(path2);
37263
- const temporaryPath = join17(directory, `.${randomUUID6()}.tmp`);
36356
+ const temporaryPath = join17(directory, `.${randomUUID7()}.tmp`);
37264
36357
  try {
37265
36358
  await mkdir4(directory, { mode: 448, recursive: true });
37266
36359
  signal.throwIfAborted();