@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/cli.js CHANGED
@@ -3381,7 +3381,7 @@ var program = new Command();
3381
3381
  // package.json
3382
3382
  var package_default = {
3383
3383
  name: "@moxt-ai/mobius",
3384
- version: "0.0.104",
3384
+ version: "0.0.106",
3385
3385
  description: "Mobius CLI for pairing and running local AI agent services.",
3386
3386
  type: "module",
3387
3387
  bin: {
@@ -27910,6 +27910,8 @@ var WORKSPACE_LIST_KIND = "workspace.list";
27910
27910
  var WORKSPACE_ENTRIES_KIND = "workspace.entries";
27911
27911
  var SESSION_PREPARE_KIND = "session.prepare";
27912
27912
  var SESSION_READY_KIND = "session.ready";
27913
+ var SESSION_QUERY_KIND = "session.query";
27914
+ var SESSION_QUERIED_KIND = "session.queried";
27913
27915
  var SESSION_CONFIGURE_KIND = "session.configure";
27914
27916
  var SESSION_CONFIG_UPDATED_KIND = "session.config.updated";
27915
27917
  var SESSION_USAGE_UPDATED_KIND = "session.usage.updated";
@@ -27951,6 +27953,26 @@ var workspaceEntrySchema = external_exports.strictObject({
27951
27953
  directoryId: DIRECTORY_IDENTIFIER,
27952
27954
  name: external_exports.string().min(1).max(255)
27953
27955
  }).readonly();
27956
+ var sessionMetadataSchema = external_exports.strictObject({
27957
+ additionalDirectories: external_exports.array(workspaceEntrySchema).max(16).readonly(),
27958
+ agentId: IDENTIFIER,
27959
+ directoryId: DIRECTORY_IDENTIFIER,
27960
+ directoryLabel: external_exports.string().min(1).max(2048),
27961
+ prompted: external_exports.boolean(),
27962
+ sessionId: IDENTIFIER,
27963
+ title: external_exports.string().max(500),
27964
+ updatedAt: external_exports.iso.datetime({ offset: true })
27965
+ }).readonly();
27966
+ var sessionQueryCommandSchema = external_exports.strictObject({
27967
+ kind: external_exports.literal(SESSION_QUERY_KIND),
27968
+ requestId: IDENTIFIER,
27969
+ sessionIds: external_exports.array(IDENTIFIER).min(1).max(500).readonly()
27970
+ }).readonly();
27971
+ var sessionsQueriedEventSchema = external_exports.strictObject({
27972
+ entries: external_exports.array(sessionMetadataSchema).max(500).readonly(),
27973
+ kind: external_exports.literal(SESSION_QUERIED_KIND),
27974
+ requestId: IDENTIFIER
27975
+ }).readonly();
27954
27976
  var fileReadCommandSchema = external_exports.strictObject({
27955
27977
  kind: external_exports.literal(FILE_READ_KIND),
27956
27978
  maxBytes: external_exports.number().int().positive().max(128 * 1024 * 1024),
@@ -28494,6 +28516,10 @@ var decodeWorkspaceListCommand = (encoded) => decode3(encoded, workspaceListComm
28494
28516
  var encodeWorkspaceListCommand = (message) => encode3(message, workspaceListCommandSchema);
28495
28517
  var decodeWorkspaceEntriesEvent = (encoded) => decode3(encoded, workspaceEntriesEventSchema);
28496
28518
  var encodeWorkspaceEntriesEvent = (message) => encode3(message, workspaceEntriesEventSchema);
28519
+ var decodeSessionQueryCommand = (encoded) => decode3(encoded, sessionQueryCommandSchema);
28520
+ var encodeSessionQueryCommand = (message) => encode3(message, sessionQueryCommandSchema);
28521
+ var decodeSessionsQueriedEvent = (encoded) => decode3(encoded, sessionsQueriedEventSchema);
28522
+ var encodeSessionsQueriedEvent = (message) => encode3(message, sessionsQueriedEventSchema);
28497
28523
  var decodeSessionPrepareCommand = (encoded) => decode3(encoded, sessionPrepareCommandSchema);
28498
28524
  var encodeSessionPrepareCommand = (message) => encode3(message, sessionPrepareCommandSchema);
28499
28525
  var decodeSessionReadyEvent = (encoded) => decode3(encoded, sessionReadyEventSchema);
@@ -28537,9 +28563,6 @@ var SESSION_CANCEL_KIND = "session.cancel";
28537
28563
  var RUNTIME_LIVENESS_READY_KIND = "runtime.liveness.ready";
28538
28564
  var RUNTIME_HEARTBEAT_KIND = "runtime.heartbeat";
28539
28565
  var RUNTIME_HEARTBEAT_ACK_KIND = "runtime.heartbeat.ack";
28540
- var RUNTIME_DELIVERY_KIND = "runtime.delivery";
28541
- var RUNTIME_DELIVERY_RECEIVED_KIND = "runtime.delivery.received";
28542
- var RUNTIME_DELIVERY_COMMITTED_KIND = "runtime.delivery.committed";
28543
28566
  var SESSION_STARTED_KIND = "session.started";
28544
28567
  var AGENT_MESSAGE_DELTA_KIND = "agent.message.delta";
28545
28568
  var AGENT_ACTIVITY_KIND = "agent.activity";
@@ -28563,7 +28586,6 @@ var DIRECTORY_IDENTIFIER_PATTERN2 = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/;
28563
28586
  var MAX_PROMPT_LENGTH = 1e4;
28564
28587
  var MAX_PROMPT_ATTACHMENT_LENGTH = 6e6;
28565
28588
  var MAX_EVENT_TEXT_LENGTH = 1e5;
28566
- var MAX_RUNTIME_DELIVERY_PAYLOAD_LENGTH = 8 * 1024 * 1024;
28567
28589
  var ACTIVITY_TYPES = /* @__PURE__ */ new Set(["plan", "progress", "reasoning", "tool"]);
28568
28590
  var NARRATION_ACTIVITY_TYPES = /* @__PURE__ */ new Set(["progress", "reasoning"]);
28569
28591
  var ACTIVITY_STATUSES = /* @__PURE__ */ new Set(["pending", "running", "completed", "failed"]);
@@ -28850,37 +28872,6 @@ function decodeRuntimeHeartbeatAckEvent(encoded) {
28850
28872
  kind: RUNTIME_HEARTBEAT_ACK_KIND
28851
28873
  };
28852
28874
  }
28853
- function decodeRuntimeDelivery(encoded) {
28854
- const value = parseJson2(encoded);
28855
- assertExactKeys(value, ["deliveryId", "kind", "payload", "sessionId"]);
28856
- assertKind(value, RUNTIME_DELIVERY_KIND);
28857
- return {
28858
- deliveryId: readIdentifier(value, "deliveryId"),
28859
- kind: RUNTIME_DELIVERY_KIND,
28860
- payload: readString(value, "payload", MAX_RUNTIME_DELIVERY_PAYLOAD_LENGTH),
28861
- sessionId: readIdentifier(value, "sessionId")
28862
- };
28863
- }
28864
- function decodeRuntimeDeliveryReceived(encoded) {
28865
- const value = parseJson2(encoded);
28866
- assertExactKeys(value, ["deliveryId", "kind", "sessionId"]);
28867
- assertKind(value, RUNTIME_DELIVERY_RECEIVED_KIND);
28868
- return {
28869
- deliveryId: readIdentifier(value, "deliveryId"),
28870
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
28871
- sessionId: readIdentifier(value, "sessionId")
28872
- };
28873
- }
28874
- function decodeRuntimeDeliveryCommitted(encoded) {
28875
- const value = parseJson2(encoded);
28876
- assertExactKeys(value, ["deliveryId", "kind", "sessionId"]);
28877
- assertKind(value, RUNTIME_DELIVERY_COMMITTED_KIND);
28878
- return {
28879
- deliveryId: readIdentifier(value, "deliveryId"),
28880
- kind: RUNTIME_DELIVERY_COMMITTED_KIND,
28881
- sessionId: readIdentifier(value, "sessionId")
28882
- };
28883
- }
28884
28875
  function decodeSessionStartedEvent(encoded) {
28885
28876
  const value = parseJson2(encoded);
28886
28877
  assertExactKeys(value, ["commandId", "epoch", "kind", "attemptId", "prompt", "sequence", "sessionId"]);
@@ -28993,15 +28984,6 @@ function encodeRuntimeHeartbeatEvent(message) {
28993
28984
  function encodeRuntimeHeartbeatAckEvent(message) {
28994
28985
  return JSON.stringify(decodeRuntimeHeartbeatAckEvent(JSON.stringify(message)));
28995
28986
  }
28996
- function encodeRuntimeDelivery(message) {
28997
- return JSON.stringify(decodeRuntimeDelivery(JSON.stringify(message)));
28998
- }
28999
- function encodeRuntimeDeliveryReceived(message) {
29000
- return JSON.stringify(decodeRuntimeDeliveryReceived(JSON.stringify(message)));
29001
- }
29002
- function encodeRuntimeDeliveryCommitted(message) {
29003
- return JSON.stringify(decodeRuntimeDeliveryCommitted(JSON.stringify(message)));
29004
- }
29005
28987
  function decodeAgentActivityNarrationEvent(encoded) {
29006
28988
  const value = parseJson2(encoded);
29007
28989
  assertExactKeys(value, ["activityId", "activityType", "commandId", "kind", "sequence", "sessionId", "text"]);
@@ -29115,6 +29097,7 @@ var NATIVE_SESSION_RESULT_KIND = "native.session.result";
29115
29097
  var NATIVE_SESSION_CANCEL_KIND = "native.session.cancel";
29116
29098
  var NATIVE_SESSION_TURN_FORK_REQUEST_KIND = "native.session.turn-fork.request";
29117
29099
  var NATIVE_SESSION_TURN_FORK_KIND = "native.session.turn-fork";
29100
+ var ACTIVE_TURN_TEXT_LIMIT = 1e6;
29118
29101
  var identifier = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
29119
29102
  var directoryId = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/);
29120
29103
  var envelope = {
@@ -29207,6 +29190,7 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
29207
29190
  ]);
29208
29191
  var nativeSessionEntrySchema = external_exports.strictObject({
29209
29192
  entryId: identifier,
29193
+ mobiusSessionIds: external_exports.array(identifier).max(500).readonly(),
29210
29194
  nativeSessionId: identifier,
29211
29195
  title: external_exports.string().max(500),
29212
29196
  directoryId,
@@ -29233,7 +29217,7 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
29233
29217
  turn: external_exports.strictObject({
29234
29218
  commandId: identifier,
29235
29219
  prompt: external_exports.string().max(1e5),
29236
- text: external_exports.string().max(1e5),
29220
+ text: external_exports.string().max(ACTIVE_TURN_TEXT_LIMIT),
29237
29221
  truncated: external_exports.boolean(),
29238
29222
  epoch: identifier,
29239
29223
  sequence: external_exports.number().int().nonnegative(),
@@ -29308,65 +29292,17 @@ var encodeNativeSessionTurnForkCommand = (value) => JSON.stringify(nativeSession
29308
29292
 
29309
29293
  // ../protocol/src/session-events.ts
29310
29294
  var SESSION_EVENT_KIND = "session.event";
29311
- var SESSION_EVENT_ACK_KIND = "session.event.ack";
29312
29295
  var SESSION_EVENT_COMMITTED_KIND = "session.event.committed";
29313
- var SESSION_EVENT_DEFERRED_KIND = "session.event.deferred";
29314
- var SESSION_EVENT_REJECTED_KIND = "session.event.rejected";
29315
- var SessionEventRejectionCode = {
29316
- SessionDeleted: "session_deleted",
29317
- SessionNotFound: "session_not_found",
29318
- SessionRejected: "session_rejected"
29319
- };
29320
29296
  var IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
29321
- var CURSOR_PATTERN = /^[A-Za-z0-9_-]{1,512}$/;
29322
29297
  var MAX_RECORDED_EVENT_LENGTH = 8 * 1024 * 1024;
29323
- var DECIMAL_SEQUENCE_PATTERN = /^(?:0|[1-9][0-9]*)$/;
29324
- var eventSourceSchema = external_exports.discriminatedUnion("kind", [
29325
- external_exports.strictObject({
29326
- attemptId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29327
- kind: external_exports.literal("attempt"),
29328
- sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
29329
- }).readonly(),
29330
- external_exports.strictObject({
29331
- kind: external_exports.literal("runtime"),
29332
- sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
29333
- }).readonly()
29334
- ]);
29335
29298
  var eventEnvelopeSchema = external_exports.strictObject({
29336
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29337
29299
  kind: external_exports.literal(SESSION_EVENT_KIND),
29338
29300
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
29339
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29340
- source: eventSourceSchema
29301
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
29341
29302
  }).readonly();
29342
29303
  var committedEventSchema = external_exports.strictObject({
29343
- cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
29344
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29345
29304
  kind: external_exports.literal(SESSION_EVENT_COMMITTED_KIND),
29346
29305
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
29347
- recordedAt: external_exports.string().datetime({ offset: true }),
29348
- sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
29349
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29350
- source: eventSourceSchema
29351
- }).readonly();
29352
- var eventAcknowledgementSchema = external_exports.strictObject({
29353
- cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
29354
- duplicate: external_exports.boolean(),
29355
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29356
- kind: external_exports.literal(SESSION_EVENT_ACK_KIND),
29357
- sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
29358
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
29359
- }).readonly();
29360
- var eventDeferredSchema = external_exports.strictObject({
29361
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29362
- kind: external_exports.literal(SESSION_EVENT_DEFERRED_KIND),
29363
- retryAfterMilliseconds: external_exports.number().int().min(100).max(6e4),
29364
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
29365
- }).readonly();
29366
- var eventRejectionSchema = external_exports.strictObject({
29367
- code: external_exports.enum(SessionEventRejectionCode),
29368
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29369
- kind: external_exports.literal(SESSION_EVENT_REJECTED_KIND),
29370
29306
  sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
29371
29307
  }).readonly();
29372
29308
  function decode5(encoded, schema) {
@@ -29395,12 +29331,6 @@ var encode4 = (message, schema) => {
29395
29331
  };
29396
29332
  var decodeSessionEventEnvelope = (encoded) => decode5(encoded, eventEnvelopeSchema);
29397
29333
  var encodeSessionEventEnvelope = (message) => encode4(message, eventEnvelopeSchema);
29398
- var decodeSessionEventAcknowledgement = (encoded) => decode5(encoded, eventAcknowledgementSchema);
29399
- var encodeSessionEventAcknowledgement = (message) => encode4(message, eventAcknowledgementSchema);
29400
- var decodeSessionEventDeferred = (encoded) => decode5(encoded, eventDeferredSchema);
29401
- var encodeSessionEventDeferred = (message) => encode4(message, eventDeferredSchema);
29402
- var decodeSessionEventRejection = (encoded) => decode5(encoded, eventRejectionSchema);
29403
- var encodeSessionEventRejection = (message) => encode4(message, eventRejectionSchema);
29404
29334
  function decodeRecordedSessionEvent(encoded) {
29405
29335
  const kind = decodeMessageKind(encoded);
29406
29336
  switch (kind) {
@@ -29530,6 +29460,11 @@ var serviceToDaemonSignatures = {
29530
29460
  decodeAgentSettingsDiscoverCommand
29531
29461
  ),
29532
29462
  [FILE_READ_KIND]: defineMessageSignature(FILE_READ_KIND, encodeFileReadCommand, decodeFileReadCommand),
29463
+ [SESSION_QUERY_KIND]: defineMessageSignature(
29464
+ SESSION_QUERY_KIND,
29465
+ encodeSessionQueryCommand,
29466
+ decodeSessionQueryCommand
29467
+ ),
29533
29468
  [NATIVE_SESSION_CANCEL_KIND]: defineMessageSignature(
29534
29469
  NATIVE_SESSION_CANCEL_KIND,
29535
29470
  encodeNativeSessionCancel,
@@ -29545,16 +29480,6 @@ var serviceToDaemonSignatures = {
29545
29480
  encodeNativeSessionTurnForkCommand,
29546
29481
  decodeNativeSessionTurnForkCommand
29547
29482
  ),
29548
- [RUNTIME_DELIVERY_KIND]: defineMessageSignature(
29549
- RUNTIME_DELIVERY_KIND,
29550
- encodeRuntimeDelivery,
29551
- decodeRuntimeDelivery
29552
- ),
29553
- [RUNTIME_DELIVERY_COMMITTED_KIND]: defineMessageSignature(
29554
- RUNTIME_DELIVERY_COMMITTED_KIND,
29555
- encodeRuntimeDeliveryCommitted,
29556
- decodeRuntimeDeliveryCommitted
29557
- ),
29558
29483
  [RUNTIME_HEARTBEAT_ACK_KIND]: defineMessageSignature(
29559
29484
  RUNTIME_HEARTBEAT_ACK_KIND,
29560
29485
  encodeRuntimeHeartbeatAckEvent,
@@ -29580,21 +29505,6 @@ var serviceToDaemonSignatures = {
29580
29505
  encodeSessionElicitationRespondCommand,
29581
29506
  decodeSessionElicitationRespondCommand
29582
29507
  ),
29583
- [SESSION_EVENT_ACK_KIND]: defineMessageSignature(
29584
- SESSION_EVENT_ACK_KIND,
29585
- encodeSessionEventAcknowledgement,
29586
- decodeSessionEventAcknowledgement
29587
- ),
29588
- [SESSION_EVENT_DEFERRED_KIND]: defineMessageSignature(
29589
- SESSION_EVENT_DEFERRED_KIND,
29590
- encodeSessionEventDeferred,
29591
- decodeSessionEventDeferred
29592
- ),
29593
- [SESSION_EVENT_REJECTED_KIND]: defineMessageSignature(
29594
- SESSION_EVENT_REJECTED_KIND,
29595
- encodeSessionEventRejection,
29596
- decodeSessionEventRejection
29597
- ),
29598
29508
  [SESSION_LIVE_HISTORY_LOAD_KIND]: defineMessageSignature(
29599
29509
  SESSION_LIVE_HISTORY_LOAD_KIND,
29600
29510
  encodeSessionLiveHistoryLoad,
@@ -29685,16 +29595,16 @@ var daemonToServiceSignatures = {
29685
29595
  [FILE_CHUNK_KIND]: defineMessageSignature(FILE_CHUNK_KIND, encodeFileChunkEvent, decodeFileChunkEvent),
29686
29596
  [FILE_END_KIND]: defineMessageSignature(FILE_END_KIND, encodeFileEndEvent, decodeFileEndEvent),
29687
29597
  [FILE_FAILED_KIND]: defineMessageSignature(FILE_FAILED_KIND, encodeFileFailedEvent, decodeFileFailedEvent),
29598
+ [SESSION_QUERIED_KIND]: defineMessageSignature(
29599
+ SESSION_QUERIED_KIND,
29600
+ encodeSessionsQueriedEvent,
29601
+ decodeSessionsQueriedEvent
29602
+ ),
29688
29603
  [NATIVE_SESSION_RESULT_KIND]: defineMessageSignature(
29689
29604
  NATIVE_SESSION_RESULT_KIND,
29690
29605
  encodeNativeSessionResult,
29691
29606
  decodeNativeSessionResult
29692
29607
  ),
29693
- [RUNTIME_DELIVERY_RECEIVED_KIND]: defineMessageSignature(
29694
- RUNTIME_DELIVERY_RECEIVED_KIND,
29695
- encodeRuntimeDeliveryReceived,
29696
- decodeRuntimeDeliveryReceived
29697
- ),
29698
29608
  [RUNTIME_HEARTBEAT_KIND]: defineMessageSignature(
29699
29609
  RUNTIME_HEARTBEAT_KIND,
29700
29610
  encodeRuntimeHeartbeatEvent,
@@ -30640,7 +30550,7 @@ var AuditStore = class {
30640
30550
  };
30641
30551
 
30642
30552
  // src/run-daemon.ts
30643
- import { randomUUID as randomUUID6 } from "node:crypto";
30553
+ import { randomUUID as randomUUID7 } from "node:crypto";
30644
30554
  import { styleText } from "node:util";
30645
30555
  import { WebSocket as WebSocket5 } from "undici";
30646
30556
 
@@ -30804,13 +30714,17 @@ var AcpStoredSession = class {
30804
30714
  nativeSessionId;
30805
30715
  prompted;
30806
30716
  sessionId;
30807
- constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted) {
30717
+ title;
30718
+ updatedAt;
30719
+ constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted, title2, updatedAt = (/* @__PURE__ */ new Date()).toISOString()) {
30808
30720
  this.additionalDirectories = [...additionalDirectories];
30809
30721
  this.agentId = agentId;
30810
30722
  this.cwd = cwd;
30811
30723
  this.nativeSessionId = nativeSessionId;
30812
30724
  this.prompted = prompted;
30813
30725
  this.sessionId = sessionId;
30726
+ this.title = title2;
30727
+ this.updatedAt = updatedAt;
30814
30728
  }
30815
30729
  };
30816
30730
  var AcpStoredSessionLookup = class {
@@ -30835,6 +30749,7 @@ var MemoryAcpSessionStore = class {
30835
30749
  findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
30836
30750
  (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
30837
30751
  );
30752
+ list = () => [...this.#sessions.values()].toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt));
30838
30753
  markDeleted = (agentId, nativeSessionId) => {
30839
30754
  const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
30840
30755
  for (const id of ids) {
@@ -32964,7 +32879,8 @@ var AcpProcessSession = class _AcpProcessSession {
32964
32879
  nativeSessionIdSchema.parse(origin.nativeSessionId),
32965
32880
  this.#cwd,
32966
32881
  this.#additionalDirectories,
32967
- true
32882
+ true,
32883
+ ""
32968
32884
  )
32969
32885
  ) : this.#store.read(this.#mobiusSessionId)
32970
32886
  );
@@ -33040,6 +32956,7 @@ var AcpProcessSession = class _AcpProcessSession {
33040
32956
  } else if (stored instanceof FoundAcpStoredSession && stored.session.agentId === this.#agentId && stored.session.cwd === this.#cwd && arraysEqual(stored.session.additionalDirectories, this.#additionalDirectories)) {
33041
32957
  this.selectNativeSession(stored.session.nativeSessionId);
33042
32958
  this.#prompted = stored.session.prompted;
32959
+ this.#sessionTitle = stored.session.title;
33043
32960
  this.#restored = true;
33044
32961
  if (this.#capabilities.resumeSession) {
33045
32962
  lifecycleResponse = await this.#metrics.measure(
@@ -33123,18 +33040,17 @@ var AcpProcessSession = class _AcpProcessSession {
33123
33040
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
33124
33041
  await this.#updateTail;
33125
33042
  signal.throwIfAborted();
33126
- if (this.#prompted) {
33127
- this.#store.write(
33128
- new AcpStoredSession(
33129
- this.#mobiusSessionId,
33130
- this.#agentId,
33131
- this.#nativeSessionId,
33132
- this.#cwd,
33133
- this.#additionalDirectories,
33134
- true
33135
- )
33136
- );
33137
- }
33043
+ this.#store.write(
33044
+ new AcpStoredSession(
33045
+ this.#mobiusSessionId,
33046
+ this.#agentId,
33047
+ this.#nativeSessionId,
33048
+ this.#cwd,
33049
+ this.#additionalDirectories,
33050
+ this.#prompted,
33051
+ this.#sessionTitle ?? ""
33052
+ )
33053
+ );
33138
33054
  };
33139
33055
  listNativeSessions = async (cursor, signal) => {
33140
33056
  if (!this.#capabilities.listSessions) {
@@ -33186,7 +33102,15 @@ var AcpProcessSession = class _AcpProcessSession {
33186
33102
  }
33187
33103
  const previousSessionId = this.#mobiusSessionId;
33188
33104
  this.#store.write(
33189
- new AcpStoredSession(sessionId, this.#agentId, sessionId, this.#cwd, this.#additionalDirectories, false)
33105
+ new AcpStoredSession(
33106
+ sessionId,
33107
+ this.#agentId,
33108
+ sessionId,
33109
+ this.#cwd,
33110
+ this.#additionalDirectories,
33111
+ false,
33112
+ ""
33113
+ )
33190
33114
  );
33191
33115
  this.#store.remove(previousSessionId);
33192
33116
  this.#mobiusSessionId = sessionId;
@@ -33308,6 +33232,9 @@ var AcpProcessSession = class _AcpProcessSession {
33308
33232
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
33309
33233
  }
33310
33234
  const prompt = this.buildPrompt(options);
33235
+ if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
33236
+ this.#sessionTitle = truncate3(options.prompt, 500);
33237
+ }
33311
33238
  this.#store.write(
33312
33239
  new AcpStoredSession(
33313
33240
  this.#mobiusSessionId,
@@ -33315,7 +33242,8 @@ var AcpProcessSession = class _AcpProcessSession {
33315
33242
  this.#nativeSessionId,
33316
33243
  this.#cwd,
33317
33244
  this.#additionalDirectories,
33318
- true
33245
+ true,
33246
+ this.#sessionTitle
33319
33247
  )
33320
33248
  );
33321
33249
  this.#prompted = true;
@@ -33743,6 +33671,19 @@ var AcpProcessSession = class _AcpProcessSession {
33743
33671
  if (Object.hasOwn(update, "updatedAt")) {
33744
33672
  this.#sessionUpdatedAt = truncate3(update.updatedAt ?? "", 128);
33745
33673
  }
33674
+ if (this.#nativeSessionId.length > 0) {
33675
+ this.#store.write(
33676
+ new AcpStoredSession(
33677
+ this.#mobiusSessionId,
33678
+ this.#agentId,
33679
+ this.#nativeSessionId,
33680
+ this.#cwd,
33681
+ this.#additionalDirectories,
33682
+ this.#prompted,
33683
+ this.#sessionTitle ?? ""
33684
+ )
33685
+ );
33686
+ }
33746
33687
  await this.#getObserver().onInfo({
33747
33688
  kind: SESSION_INFO_UPDATED_KIND,
33748
33689
  sessionId: this.#mobiusSessionId,
@@ -34645,6 +34586,11 @@ var AcpSessionManager = class {
34645
34586
  )
34646
34587
  ]);
34647
34588
  };
34589
+ findSessions = (sessionIds) => sessionIds.flatMap((sessionId) => {
34590
+ const stored = this.#store.read(sessionId);
34591
+ return stored instanceof FoundAcpStoredSession ? [stored.session] : [];
34592
+ });
34593
+ findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
34648
34594
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
34649
34595
  createNativeSession = async (options) => {
34650
34596
  const temporarySessionId = `new-${crypto.randomUUID()}`;
@@ -36998,21 +36944,17 @@ function daemonActivity(command, activity2) {
36998
36944
  toolKind: activity2.toolKind
36999
36945
  };
37000
36946
  }
37001
- function reportFailure(publisher, command, code, message, attemptId) {
37002
- publisher.recordAttempt(
37003
- command.sessionId,
37004
- {
37005
- code,
37006
- commandId: command.commandId,
37007
- kind: SESSION_FAILED_KIND,
37008
- message,
37009
- sessionId: command.sessionId
37010
- },
37011
- attemptId
37012
- );
36947
+ function reportFailure(publisher, command, code, message) {
36948
+ publisher.publish(command.sessionId, {
36949
+ code,
36950
+ commandId: command.commandId,
36951
+ kind: SESSION_FAILED_KIND,
36952
+ message,
36953
+ sessionId: command.sessionId
36954
+ });
37013
36955
  }
37014
- function settleAbandonedTurn(publisher, outbox, audit, cancellation) {
37015
- const attemptId = outbox.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
36956
+ function settleAbandonedTurn(publisher, operations, audit, cancellation) {
36957
+ const attemptId = operations.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
37016
36958
  if (attemptId === null) {
37017
36959
  console.warn("Mobius daemon ignored cancellation for an inactive turn");
37018
36960
  return;
@@ -37026,10 +36968,9 @@ function settleAbandonedTurn(publisher, outbox, audit, cancellation) {
37026
36968
  publisher,
37027
36969
  cancellation,
37028
36970
  "agent_execution_abandoned",
37029
- "The local Agent execution was abandoned before it completed",
37030
- attemptId
36971
+ "The local Agent execution was abandoned before it completed"
37031
36972
  );
37032
- outbox.transitionExecution(cancellation.commandId, "failed");
36973
+ operations.transitionExecution(cancellation.commandId, "failed");
37033
36974
  }
37034
36975
  function operationErrorCode(error62) {
37035
36976
  if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof PromptArtifactError) {
@@ -37159,7 +37100,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
37159
37100
  event: "session_configured",
37160
37101
  sessionId: command.sessionId
37161
37102
  });
37162
- publisher.recordRuntime(command.sessionId, {
37103
+ publisher.publish(command.sessionId, {
37163
37104
  configOptions,
37164
37105
  kind: "session.config.updated",
37165
37106
  requestId: command.requestId,
@@ -37184,7 +37125,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
37184
37125
  };
37185
37126
  if (command.transient !== true) {
37186
37127
  metrics.measureSync("readiness-commit", () => {
37187
- publisher.recordRuntime(command.sessionId, event);
37128
+ publisher.publish(command.sessionId, event);
37188
37129
  });
37189
37130
  }
37190
37131
  return event;
@@ -37332,7 +37273,7 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
37332
37273
  event: "session_configured",
37333
37274
  sessionId: command.sessionId
37334
37275
  });
37335
- publisher.recordRuntime(command.sessionId, {
37276
+ publisher.publish(command.sessionId, {
37336
37277
  configOptions,
37337
37278
  kind: "session.config.updated",
37338
37279
  requestId: command.requestId,
@@ -37345,26 +37286,22 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
37345
37286
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
37346
37287
  }
37347
37288
  }
37348
- async function executePrompt(outbox, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, sessionAvailable, timer, signal, recordLiveText) {
37289
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, waitForSessionAvailability, timer, signal, recordLiveText, cancellationRequested) {
37349
37290
  const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
37350
- publisher.recordAttempt(command.sessionId, daemonActivity(command, activity2), attemptId);
37291
+ publisher.publish(command.sessionId, daemonActivity(command, activity2));
37351
37292
  });
37352
37293
  const narration = new CoalescingNarrationPublisher(
37353
37294
  timer,
37354
37295
  (increment) => {
37355
- publisher.recordAttempt(
37356
- command.sessionId,
37357
- {
37358
- activityId: increment.activityId,
37359
- activityType: increment.activityType,
37360
- commandId: command.commandId,
37361
- kind: AGENT_ACTIVITY_NARRATION_KIND,
37362
- sequence: increment.sequence,
37363
- sessionId: command.sessionId,
37364
- text: increment.text
37365
- },
37366
- attemptId
37367
- );
37296
+ publisher.publish(command.sessionId, {
37297
+ activityId: increment.activityId,
37298
+ activityType: increment.activityType,
37299
+ commandId: command.commandId,
37300
+ kind: AGENT_ACTIVITY_NARRATION_KIND,
37301
+ sequence: increment.sequence,
37302
+ sessionId: command.sessionId,
37303
+ text: increment.text
37304
+ });
37368
37305
  },
37369
37306
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
37370
37307
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -37373,19 +37310,15 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
37373
37310
  timer,
37374
37311
  (messageId, delta) => {
37375
37312
  const stream = recordLiveText(delta);
37376
- publisher.recordAttempt(
37377
- command.sessionId,
37378
- {
37379
- commandId: command.commandId,
37380
- epoch: stream.epoch,
37381
- kind: AGENT_MESSAGE_DELTA_KIND,
37382
- messageId,
37383
- sequence: stream.sequence,
37384
- sessionId: command.sessionId,
37385
- text: delta
37386
- },
37387
- attemptId
37388
- );
37313
+ publisher.publish(command.sessionId, {
37314
+ commandId: command.commandId,
37315
+ epoch: stream.epoch,
37316
+ kind: AGENT_MESSAGE_DELTA_KIND,
37317
+ messageId,
37318
+ sequence: stream.sequence,
37319
+ sessionId: command.sessionId,
37320
+ text: delta
37321
+ });
37389
37322
  },
37390
37323
  AGENT_TEXT_COALESCING_MILLISECONDS,
37391
37324
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -37399,10 +37332,11 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
37399
37332
  signal
37400
37333
  );
37401
37334
  const agent = config2.catalog.find(command.agentId);
37402
- if (!sessionAvailable()) {
37335
+ const availability = await waitForSessionAvailability(signal);
37336
+ if (availability === "busy") {
37403
37337
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
37404
37338
  }
37405
- if (command.disposition === SessionPromptDisposition.Queue && !outbox.isTerminalExecution(command.targetCommandId, command.sessionId)) {
37339
+ if (availability === "queue-target-unavailable") {
37406
37340
  throw new AcpExecutionError(
37407
37341
  "The queued prompt target is unavailable",
37408
37342
  {},
@@ -37442,21 +37376,17 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
37442
37376
  event: "session_authorized",
37443
37377
  sessionId: command.sessionId
37444
37378
  });
37445
- outbox.transitionExecution(command.commandId, "running");
37379
+ operations.transitionExecution(command.commandId, "running");
37446
37380
  const stream = activateAttempt();
37447
- publisher.recordAttempt(
37448
- command.sessionId,
37449
- {
37450
- commandId: command.commandId,
37451
- epoch: stream.epoch,
37452
- kind: SESSION_STARTED_KIND,
37453
- attemptId,
37454
- prompt: command.prompt,
37455
- sequence: stream.sequence,
37456
- sessionId: command.sessionId
37457
- },
37458
- attemptId
37459
- );
37381
+ publisher.publish(command.sessionId, {
37382
+ commandId: command.commandId,
37383
+ epoch: stream.epoch,
37384
+ kind: SESSION_STARTED_KIND,
37385
+ attemptId,
37386
+ prompt: command.prompt,
37387
+ sequence: stream.sequence,
37388
+ sessionId: command.sessionId
37389
+ });
37460
37390
  const attachments = await resolvePromptArtifacts(config2, command, signal);
37461
37391
  let stopReason;
37462
37392
  if (command.disposition === SessionPromptDisposition.Steer) {
@@ -37501,17 +37431,13 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
37501
37431
  text.flush();
37502
37432
  narration.flush();
37503
37433
  activities.flush();
37504
- publisher.recordAttempt(
37505
- command.sessionId,
37506
- {
37507
- commandId: command.commandId,
37508
- kind: SESSION_COMPLETED_KIND,
37509
- sessionId: command.sessionId,
37510
- stopReason
37511
- },
37512
- attemptId
37513
- );
37514
- outbox.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
37434
+ publisher.publish(command.sessionId, {
37435
+ commandId: command.commandId,
37436
+ kind: SESSION_COMPLETED_KIND,
37437
+ sessionId: command.sessionId,
37438
+ stopReason
37439
+ });
37440
+ operations.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
37515
37441
  audit.record({
37516
37442
  commandId: command.commandId,
37517
37443
  event: stopReason === "cancelled" ? "session_cancelled" : "session_completed",
@@ -37521,6 +37447,21 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
37521
37447
  text.flush();
37522
37448
  narration.flush();
37523
37449
  activities.flush();
37450
+ if (signal.aborted && cancellationRequested()) {
37451
+ publisher.publish(command.sessionId, {
37452
+ commandId: command.commandId,
37453
+ kind: SESSION_COMPLETED_KIND,
37454
+ sessionId: command.sessionId,
37455
+ stopReason: "cancelled"
37456
+ });
37457
+ operations.transitionExecution(command.commandId, "cancelled");
37458
+ audit.record({
37459
+ commandId: command.commandId,
37460
+ event: "session_cancelled",
37461
+ sessionId: command.sessionId
37462
+ });
37463
+ return;
37464
+ }
37524
37465
  audit.record({
37525
37466
  commandId: command.commandId,
37526
37467
  event: "session_failed",
@@ -37531,10 +37472,9 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
37531
37472
  publisher,
37532
37473
  command,
37533
37474
  code === "session_operation_failed" ? "agent_execution_failed" : code,
37534
- code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62),
37535
- attemptId
37475
+ code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62)
37536
37476
  );
37537
- outbox.transitionExecution(command.commandId, "failed");
37477
+ operations.transitionExecution(command.commandId, "failed");
37538
37478
  console.error("Mobius daemon command failed", error62);
37539
37479
  }
37540
37480
  }
@@ -37676,7 +37616,6 @@ var DaemonInstallationObserver = class {
37676
37616
  import { randomUUID as randomUUID3 } from "node:crypto";
37677
37617
  import { fetch as fetch5 } from "undici";
37678
37618
  var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
37679
- var ACTIVE_TURN_TEXT_LIMIT = 1e5;
37680
37619
  var ActiveDaemonTurn = class {
37681
37620
  attemptId;
37682
37621
  command;
@@ -37722,11 +37661,16 @@ var ActiveDaemonTurn = class {
37722
37661
  matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
37723
37662
  requestCancellation = () => {
37724
37663
  if (this.#cancellationRequested) {
37725
- return false;
37664
+ return "already-requested";
37726
37665
  }
37727
37666
  this.#cancellationRequested = true;
37728
- return true;
37667
+ if (!this.#accepted) {
37668
+ this.#controller.abort(new Error("The queued Agent turn was cancelled"));
37669
+ return "pending";
37670
+ }
37671
+ return "running";
37729
37672
  };
37673
+ cancellationRequested = () => this.#cancellationRequested;
37730
37674
  get signal() {
37731
37675
  return this.#controller.signal;
37732
37676
  }
@@ -38452,6 +38396,7 @@ var NativeSessionService = class {
38452
38396
  });
38453
38397
  return {
38454
38398
  entryId,
38399
+ mobiusSessionIds: this.#sessions.findLinkedSessions(command.agentId, info.sessionId).filter((session) => session.prompted && session.cwd === authorized.cwd).map((session) => session.sessionId),
38455
38400
  nativeSessionId: info.sessionId,
38456
38401
  title: info.title ?? "Untitled session",
38457
38402
  directoryId: authorized.directoryId,
@@ -38669,6 +38614,29 @@ var NativeSessionService = class {
38669
38614
  history: opened.history
38670
38615
  };
38671
38616
  };
38617
+ querySessions = async (sessionIds, signal) => {
38618
+ const entries = [];
38619
+ for (const session of this.#sessions.findSessions(sessionIds)) {
38620
+ signal.throwIfAborted();
38621
+ const directory = await this.#directories.identify(this.#config.bindingId, session.cwd, signal);
38622
+ const additionalDirectories = [];
38623
+ for (const path3 of session.additionalDirectories) {
38624
+ const identified = await this.#directories.identify(this.#config.bindingId, path3, signal);
38625
+ additionalDirectories.push({ directoryId: identified.directoryId, name: identified.name });
38626
+ }
38627
+ entries.push({
38628
+ additionalDirectories,
38629
+ agentId: session.agentId,
38630
+ directoryId: directory.directoryId,
38631
+ directoryLabel: directory.label,
38632
+ prompted: session.prompted,
38633
+ sessionId: session.sessionId,
38634
+ title: session.title || "Untitled session",
38635
+ updatedAt: session.updatedAt
38636
+ });
38637
+ }
38638
+ return entries;
38639
+ };
38672
38640
  executeTurnFork = async (command, signal) => {
38673
38641
  signal.throwIfAborted();
38674
38642
  const cwd = await this.#directories.resolve(this.#config.bindingId, command.directoryId, signal);
@@ -38941,6 +38909,75 @@ function connectRelay(url2, signal) {
38941
38909
  });
38942
38910
  }
38943
38911
 
38912
+ // src/relay-connection/daemon-operation-state.ts
38913
+ import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
38914
+ var MAX_TERMINAL_RECEIPTS = 1024;
38915
+ function isTerminal(state) {
38916
+ return state === "succeeded" || state === "failed" || state === "cancelled";
38917
+ }
38918
+ var DaemonOperationState = class {
38919
+ #executions = /* @__PURE__ */ new Map();
38920
+ #terminalCount = 0;
38921
+ claimExecution = (commandId, sessionId, commandJson) => {
38922
+ const commandHash = createHash5("sha256").update(commandJson).digest("hex");
38923
+ const existing = this.#executions.get(commandId);
38924
+ if (existing !== void 0) {
38925
+ if (existing.sessionId !== sessionId || existing.commandHash !== commandHash) {
38926
+ throw new Error("The daemon command identity conflicts with its in-memory receipt");
38927
+ }
38928
+ return { attemptId: existing.attemptId, commandId, kind: "duplicate", state: existing.state };
38929
+ }
38930
+ const attemptId = randomUUID5();
38931
+ this.#executions.set(commandId, { attemptId, commandHash, sessionId, state: "dispatching" });
38932
+ return { attemptId, commandId, kind: "accepted", state: "dispatching" };
38933
+ };
38934
+ transitionExecution = (commandId, state) => {
38935
+ const current = this.#executions.get(commandId);
38936
+ if (current === void 0) {
38937
+ throw new Error("The daemon execution receipt does not exist");
38938
+ }
38939
+ if (current.state === state) {
38940
+ return;
38941
+ }
38942
+ const allowed = current.state === "dispatching" && (state === "running" || state === "failed" || state === "cancelled") || current.state === "running" && isTerminal(state);
38943
+ if (!allowed) {
38944
+ throw new Error("The daemon execution transition is invalid");
38945
+ }
38946
+ this.#executions.set(commandId, { ...current, state });
38947
+ if (isTerminal(state)) {
38948
+ this.#terminalCount += 1;
38949
+ this.pruneTerminalReceipts();
38950
+ }
38951
+ };
38952
+ /** Receipts disappear when the daemon process exits. */
38953
+ findUnsettledAttemptId = (commandId, sessionId) => {
38954
+ const receipt = this.#executions.get(commandId);
38955
+ return receipt?.sessionId === sessionId && !isTerminal(receipt.state) ? receipt.attemptId : null;
38956
+ };
38957
+ isTerminalExecution = (commandId, sessionId) => {
38958
+ const receipt = this.#executions.get(commandId);
38959
+ return receipt?.sessionId === sessionId && isTerminal(receipt.state);
38960
+ };
38961
+ close = () => {
38962
+ this.#executions.clear();
38963
+ this.#terminalCount = 0;
38964
+ };
38965
+ pruneTerminalReceipts = () => {
38966
+ if (this.#terminalCount <= MAX_TERMINAL_RECEIPTS) {
38967
+ return;
38968
+ }
38969
+ for (const [commandId, receipt] of this.#executions) {
38970
+ if (isTerminal(receipt.state)) {
38971
+ this.#executions.delete(commandId);
38972
+ this.#terminalCount -= 1;
38973
+ if (this.#terminalCount <= MAX_TERMINAL_RECEIPTS) {
38974
+ return;
38975
+ }
38976
+ }
38977
+ }
38978
+ };
38979
+ };
38980
+
38944
38981
  // src/relay-connection/diagnostics.ts
38945
38982
  var MAX_DIAGNOSTIC_TEXT_LENGTH = 256;
38946
38983
  function sanitizeDiagnosticText(value) {
@@ -39114,7 +39151,7 @@ var RelayConnectionDiagnostics = class {
39114
39151
  };
39115
39152
 
39116
39153
  // src/relay-connection/liveness.ts
39117
- import { randomUUID as randomUUID5 } from "node:crypto";
39154
+ import { randomUUID as randomUUID6 } from "node:crypto";
39118
39155
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
39119
39156
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
39120
39157
  var RelayLivenessState = class {
@@ -39203,7 +39240,7 @@ var RelayConnectionLiveness = class {
39203
39240
  }
39204
39241
  throw new Error("Heartbeat was scheduled in an invalid state");
39205
39242
  }
39206
- const heartbeatId = randomUUID5();
39243
+ const heartbeatId = randomUUID6();
39207
39244
  this.#state = new AwaitingHeartbeatAckState(
39208
39245
  heartbeatId,
39209
39246
  this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
@@ -39219,765 +39256,54 @@ var RelayConnectionLiveness = class {
39219
39256
  };
39220
39257
  };
39221
39258
 
39222
- // src/relay-connection/session-event-outbox.ts
39223
- import { createHash as createHash5 } from "node:crypto";
39224
- import { DatabaseSync } from "node:sqlite";
39225
- var DEFAULT_OUTBOX_LIMITS = {
39226
- criticalEventBytes: 40 * 1024 * 1024,
39227
- runtimeDeliveryBytes: 32 * 1024 * 1024,
39228
- runtimeDeliveryCount: 64,
39229
- standardEventBytes: 32 * 1024 * 1024
39230
- };
39231
- var MAX_TERMINAL_RECEIPTS = 1024;
39232
- var SessionEventOutboxCapacityError = class extends Error {
39233
- code = "session_event_outbox_full";
39234
- constructor() {
39235
- super("The in-memory Session event outbox is full");
39236
- this.name = "SessionEventOutboxCapacityError";
39237
- }
39238
- };
39239
- var RuntimeDeliveryInboxCapacityError = class extends Error {
39240
- code = "runtime_delivery_inbox_full";
39241
- constructor() {
39242
- super("The in-memory Runtime delivery inbox is full");
39243
- this.name = "RuntimeDeliveryInboxCapacityError";
39244
- }
39245
- };
39246
- var StoredRuntimeDelivery = class {
39247
- deliveryId;
39248
- duplicate;
39249
- payload;
39250
- sessionId;
39251
- state;
39252
- constructor(deliveryId, sessionId, payload, state, duplicate) {
39253
- this.deliveryId = deliveryId;
39254
- this.duplicate = duplicate;
39255
- this.payload = payload;
39256
- this.sessionId = sessionId;
39257
- this.state = state;
39258
- }
39259
- };
39260
- function readPendingEnvelope(row) {
39261
- if (typeof row !== "object" || row === null || Array.isArray(row)) {
39262
- throw new Error("SQLite returned an invalid session event outbox row");
39263
- }
39264
- const envelope2 = Reflect.get(row, "envelope_json");
39265
- if (typeof envelope2 !== "string") {
39266
- throw new Error("SQLite returned an invalid session event envelope");
39267
- }
39268
- return envelope2;
39269
- }
39270
- function rowNumber(row, field) {
39271
- const value = typeof row === "object" && row !== null ? Reflect.get(row, field) : void 0;
39272
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
39273
- throw new Error(`SQLite returned an invalid ${field} value`);
39274
- }
39275
- return value;
39276
- }
39277
- function rowString(row, field) {
39278
- const value = typeof row === "object" && row !== null ? Reflect.get(row, field) : void 0;
39279
- if (typeof value !== "string" || value.length === 0) {
39280
- throw new Error(`SQLite returned an invalid ${field} value`);
39281
- }
39282
- return value;
39283
- }
39284
- var SessionEventOutbox = class {
39285
- #database;
39286
- #limits;
39287
- constructor(limits = DEFAULT_OUTBOX_LIMITS) {
39288
- validateLimits(limits);
39289
- this.#limits = limits;
39290
- this.#database = new DatabaseSync(":memory:");
39291
- this.#database.exec(`
39292
- CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
39293
- ordinal INTEGER PRIMARY KEY AUTOINCREMENT,
39294
- event_id TEXT NOT NULL UNIQUE,
39295
- session_id TEXT NOT NULL,
39296
- source_key TEXT NOT NULL,
39297
- byte_length INTEGER NOT NULL,
39298
- envelope_json TEXT NOT NULL
39299
- ) STRICT;
39300
- CREATE INDEX IF NOT EXISTS relay_session_event_outbox_order
39301
- ON relay_session_event_outbox(ordinal);
39302
- CREATE TABLE IF NOT EXISTS relay_turn_receipts (
39303
- command_id TEXT PRIMARY KEY,
39304
- session_id TEXT NOT NULL,
39305
- command_hash TEXT NOT NULL,
39306
- attempt_id TEXT NOT NULL,
39307
- state TEXT NOT NULL CHECK (
39308
- state IN ('dispatching', 'running', 'succeeded', 'failed', 'cancelled')
39309
- )
39310
- ) STRICT;
39311
- CREATE TABLE IF NOT EXISTS relay_session_event_outbox_state (
39312
- singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
39313
- event_count INTEGER NOT NULL,
39314
- total_bytes INTEGER NOT NULL,
39315
- next_source_seq INTEGER NOT NULL
39316
- ) STRICT;
39317
- INSERT OR IGNORE INTO relay_session_event_outbox_state (
39318
- singleton, event_count, total_bytes, next_source_seq
39319
- ) VALUES (1, 0, 0, 1);
39320
- CREATE TABLE IF NOT EXISTS relay_runtime_deliveries (
39321
- delivery_id TEXT PRIMARY KEY,
39322
- session_id TEXT NOT NULL,
39323
- payload_json TEXT NOT NULL,
39324
- payload_bytes INTEGER NOT NULL,
39325
- state TEXT NOT NULL CHECK (
39326
- state IN ('received', 'relay_committed', 'processed')
39327
- ),
39328
- received_at INTEGER NOT NULL
39329
- ) STRICT;
39330
- `);
39331
- this.#database.exec(`
39332
- CREATE INDEX IF NOT EXISTS relay_session_event_outbox_source_order
39333
- ON relay_session_event_outbox(source_key, ordinal);
39334
- `);
39335
- }
39336
- claimExecution = (commandId, sessionId, commandJson) => {
39337
- const commandHash = createHash5("sha256").update(commandJson).digest("hex");
39338
- this.#database.exec("BEGIN IMMEDIATE");
39339
- try {
39340
- const existing = this.#database.prepare(
39341
- `SELECT session_id, command_hash, attempt_id, state
39342
- FROM relay_turn_receipts WHERE command_id = ?`
39343
- ).get(commandId);
39344
- if (typeof existing === "object" && existing !== null) {
39345
- const storedSessionId = Reflect.get(existing, "session_id");
39346
- const storedCommandHash = Reflect.get(existing, "command_hash");
39347
- const attemptId2 = Reflect.get(existing, "attempt_id");
39348
- const state = Reflect.get(existing, "state");
39349
- if (storedSessionId !== sessionId || storedCommandHash !== commandHash || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
39350
- throw new Error("The daemon command identity conflicts with its in-memory receipt");
39351
- }
39352
- this.#database.exec("COMMIT");
39353
- return { attemptId: attemptId2, commandId, kind: "duplicate", state };
39354
- }
39355
- const attemptId = crypto.randomUUID();
39356
- this.#database.prepare(
39357
- `INSERT INTO relay_turn_receipts (
39358
- command_id, session_id, command_hash, attempt_id, state
39359
- ) VALUES (?, ?, ?, ?, 'dispatching')`
39360
- ).run(commandId, sessionId, commandHash, attemptId);
39361
- this.#database.exec("COMMIT");
39362
- return {
39363
- attemptId,
39364
- commandId,
39365
- kind: "accepted",
39366
- state: "dispatching"
39367
- };
39368
- } catch (error62) {
39369
- this.#database.exec("ROLLBACK");
39370
- throw error62;
39371
- }
39372
- };
39373
- transitionExecution = (commandId, state) => {
39374
- const row = this.#database.prepare(`SELECT state FROM relay_turn_receipts WHERE command_id = ?`).get(commandId);
39375
- const current = typeof row === "object" && row !== null ? Reflect.get(row, "state") : void 0;
39376
- if (!isDaemonExecutionState(current)) {
39377
- throw new Error("The daemon execution receipt does not exist");
39378
- }
39379
- if (current === state) {
39380
- return;
39381
- }
39382
- const allowed = current === "dispatching" && (state === "running" || state === "failed" || state === "cancelled") || current === "running" && (state === "succeeded" || state === "failed" || state === "cancelled");
39383
- if (!allowed) {
39384
- throw new Error("The daemon execution transition is invalid");
39385
- }
39386
- this.#database.prepare(`UPDATE relay_turn_receipts SET state = ? WHERE command_id = ?`).run(state, commandId);
39387
- if (state === "succeeded" || state === "failed" || state === "cancelled") {
39388
- this.#database.prepare(
39389
- `DELETE FROM relay_turn_receipts
39390
- WHERE state IN ('succeeded', 'failed', 'cancelled')
39391
- AND rowid NOT IN (
39392
- SELECT rowid FROM relay_turn_receipts
39393
- WHERE state IN ('succeeded', 'failed', 'cancelled')
39394
- ORDER BY rowid DESC LIMIT ?
39395
- )`
39396
- ).run(MAX_TERMINAL_RECEIPTS);
39397
- }
39398
- };
39399
- /**
39400
- * The Attempt this live Runtime claimed for a command that has not reached a terminal state.
39401
- * Receipts disappear when the daemon process exits.
39402
- */
39403
- findUnsettledAttemptId = (commandId, sessionId) => {
39404
- const row = this.#database.prepare(`SELECT attempt_id, state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
39405
- if (typeof row !== "object" || row === null) {
39406
- return null;
39407
- }
39408
- const attemptId = Reflect.get(row, "attempt_id");
39409
- const state = Reflect.get(row, "state");
39410
- if (typeof attemptId !== "string" || attemptId.length === 0 || !isDaemonExecutionState(state)) {
39411
- return null;
39412
- }
39413
- return state === "dispatching" || state === "running" ? attemptId : null;
39414
- };
39415
- isTerminalExecution = (commandId, sessionId) => {
39416
- const row = this.#database.prepare(`SELECT state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
39417
- const state = typeof row === "object" && row !== null ? Reflect.get(row, "state") : void 0;
39418
- return state === "succeeded" || state === "failed" || state === "cancelled";
39419
- };
39420
- acknowledge = (acknowledgement) => this.#removeAcknowledgedEvent(acknowledgement.eventId, acknowledgement.sessionId);
39421
- quarantine = (rejection) => {
39422
- this.#database.exec("BEGIN IMMEDIATE");
39423
- try {
39424
- const stored = this.#database.prepare(
39425
- `SELECT byte_length FROM relay_session_event_outbox
39426
- WHERE event_id = ? AND session_id = ?`
39427
- ).get(rejection.eventId, rejection.sessionId);
39428
- if (stored === void 0) {
39429
- this.#database.exec("COMMIT");
39430
- return false;
39431
- }
39432
- const byteLength = rowNumber(stored, "byte_length");
39433
- const deletion = this.#database.prepare(
39434
- `DELETE FROM relay_session_event_outbox
39435
- WHERE event_id = ? AND session_id = ?`
39436
- ).run(rejection.eventId, rejection.sessionId);
39437
- if (deletion.changes !== 1) {
39438
- throw new Error("The rejected session event could not be removed from the in-memory outbox");
39439
- }
39440
- this.#decrementEventState(byteLength);
39441
- this.#database.exec("COMMIT");
39442
- return true;
39443
- } catch (error62) {
39444
- this.#database.exec("ROLLBACK");
39445
- throw error62;
39446
- }
39447
- };
39448
- close = () => {
39449
- this.#database.close();
39450
- };
39451
- enqueue = (sessionId, payload, attemptId = null) => {
39452
- return this.#enqueueBounded(sessionId, payload, attemptId ?? "", this.#limits.standardEventBytes);
39453
- };
39454
- enqueueCritical = (sessionId, payload, attemptId = "") => this.#enqueueBounded(sessionId, payload, attemptId, this.#limits.criticalEventBytes);
39455
- /**
39456
- * Bytes still available to standard Session events. The daemon uses this to shed
39457
- * superseded streaming events instead of filling the in-memory outbox, so a long Turn
39458
- * behind a slow Relay cannot make the next enqueue throw.
39459
- */
39460
- standardCapacityRemaining = () => {
39461
- const state = this.#database.prepare(
39462
- `SELECT total_bytes
39463
- FROM relay_session_event_outbox_state
39464
- WHERE singleton = 1`
39465
- ).get();
39466
- return this.#limits.standardEventBytes - rowNumber(state, "total_bytes");
39467
- };
39468
- claimRuntimeDelivery = (delivery) => {
39469
- const payloadBytes = new TextEncoder().encode(delivery.payload).byteLength;
39470
- this.#database.exec("BEGIN IMMEDIATE");
39471
- try {
39472
- const existing = this.#database.prepare(
39473
- `SELECT session_id, payload_json, state
39474
- FROM relay_runtime_deliveries
39475
- WHERE delivery_id = ?`
39476
- ).get(delivery.deliveryId);
39477
- if (existing !== void 0) {
39478
- const sessionId = rowString(existing, "session_id");
39479
- const payload = rowString(existing, "payload_json");
39480
- const state = runtimeDeliveryState(existing);
39481
- if (sessionId !== delivery.sessionId || payload !== delivery.payload) {
39482
- throw new Error("The Runtime delivery identity conflicts with its in-memory receipt");
39483
- }
39484
- this.#database.exec("COMMIT");
39485
- return new StoredRuntimeDelivery(delivery.deliveryId, sessionId, payload, state, true);
39486
- }
39487
- const usage = this.#database.prepare(
39488
- `SELECT COUNT(*) AS delivery_count,
39489
- COALESCE(SUM(payload_bytes), 0) AS delivery_bytes
39490
- FROM relay_runtime_deliveries`
39491
- ).get();
39492
- if (rowNumber(usage, "delivery_count") + 1 > this.#limits.runtimeDeliveryCount || rowNumber(usage, "delivery_bytes") + payloadBytes > this.#limits.runtimeDeliveryBytes) {
39493
- throw new RuntimeDeliveryInboxCapacityError();
39494
- }
39495
- this.#database.prepare(
39496
- `INSERT INTO relay_runtime_deliveries (
39497
- delivery_id, session_id, payload_json, payload_bytes, state, received_at
39498
- ) VALUES (?, ?, ?, ?, 'received', ?)`
39499
- ).run(delivery.deliveryId, delivery.sessionId, delivery.payload, payloadBytes, Date.now());
39500
- this.#database.exec("COMMIT");
39501
- return new StoredRuntimeDelivery(
39502
- delivery.deliveryId,
39503
- delivery.sessionId,
39504
- delivery.payload,
39505
- "received",
39506
- false
39507
- );
39508
- } catch (error62) {
39509
- this.#database.exec("ROLLBACK");
39510
- throw error62;
39511
- }
39512
- };
39513
- markRuntimeDeliveryCommitted = (deliveryId, sessionId) => {
39514
- this.#database.exec("BEGIN IMMEDIATE");
39515
- try {
39516
- const row = this.#database.prepare(
39517
- `SELECT state FROM relay_runtime_deliveries
39518
- WHERE delivery_id = ? AND session_id = ?`
39519
- ).get(deliveryId, sessionId);
39520
- if (row === void 0) {
39521
- this.#database.exec("COMMIT");
39522
- return false;
39523
- }
39524
- const state = runtimeDeliveryState(row);
39525
- if (state === "processed") {
39526
- this.#database.prepare(`DELETE FROM relay_runtime_deliveries WHERE delivery_id = ?`).run(deliveryId);
39527
- } else if (state === "received") {
39528
- this.#database.prepare(`UPDATE relay_runtime_deliveries SET state = 'relay_committed' WHERE delivery_id = ?`).run(deliveryId);
39529
- }
39530
- this.#database.exec("COMMIT");
39531
- return true;
39532
- } catch (error62) {
39533
- this.#database.exec("ROLLBACK");
39534
- throw error62;
39535
- }
39536
- };
39537
- markRuntimeDeliveryProcessed = (deliveryId, sessionId) => {
39538
- this.#database.exec("BEGIN IMMEDIATE");
39539
- try {
39540
- const row = this.#database.prepare(
39541
- `SELECT state FROM relay_runtime_deliveries
39542
- WHERE delivery_id = ? AND session_id = ?`
39543
- ).get(deliveryId, sessionId);
39544
- if (row === void 0) {
39545
- this.#database.exec("COMMIT");
39546
- return false;
39547
- }
39548
- const state = runtimeDeliveryState(row);
39549
- if (state === "relay_committed") {
39550
- this.#database.prepare(`DELETE FROM relay_runtime_deliveries WHERE delivery_id = ?`).run(deliveryId);
39551
- } else if (state === "received") {
39552
- this.#database.prepare(`UPDATE relay_runtime_deliveries SET state = 'processed' WHERE delivery_id = ?`).run(deliveryId);
39553
- }
39554
- this.#database.exec("COMMIT");
39555
- return true;
39556
- } catch (error62) {
39557
- this.#database.exec("ROLLBACK");
39558
- throw error62;
39559
- }
39560
- };
39561
- runtimeDeliveries = () => this.#database.prepare(
39562
- `SELECT delivery_id, session_id, payload_json, state
39563
- FROM relay_runtime_deliveries
39564
- ORDER BY received_at, delivery_id`
39565
- ).all().map(
39566
- (row) => new StoredRuntimeDelivery(
39567
- rowString(row, "delivery_id"),
39568
- rowString(row, "session_id"),
39569
- rowString(row, "payload_json"),
39570
- runtimeDeliveryState(row),
39571
- true
39572
- )
39573
- );
39574
- #enqueueBounded = (sessionId, payload, attemptId, maximumEventBytes) => {
39575
- const sourceKey = attemptId.length === 0 ? `runtime:${sessionId}` : `attempt:${sessionId}:${attemptId}`;
39576
- this.#database.exec("BEGIN IMMEDIATE");
39577
- try {
39578
- const state = this.#database.prepare(
39579
- `SELECT total_bytes, next_source_seq
39580
- FROM relay_session_event_outbox_state
39581
- WHERE singleton = 1`
39582
- ).get();
39583
- const nextSourceSeq = rowNumber(state, "next_source_seq");
39584
- if (nextSourceSeq < 1 || !Number.isSafeInteger(nextSourceSeq + 1)) {
39585
- throw new Error("SQLite returned an invalid event source sequence");
39586
- }
39587
- const envelope2 = {
39588
- eventId: crypto.randomUUID(),
39589
- kind: SESSION_EVENT_KIND,
39590
- payload,
39591
- sessionId,
39592
- source: attemptId.length === 0 ? { kind: "runtime", sourceSeq: nextSourceSeq.toString() } : {
39593
- attemptId,
39594
- kind: "attempt",
39595
- sourceSeq: nextSourceSeq.toString()
39596
- }
39597
- };
39598
- const encoded = encodeSessionEventEnvelope(envelope2);
39599
- const byteLength = new TextEncoder().encode(encoded).byteLength;
39600
- if (rowNumber(state, "total_bytes") + byteLength > maximumEventBytes) {
39601
- throw new SessionEventOutboxCapacityError();
39602
- }
39603
- this.#database.prepare(
39604
- `INSERT INTO relay_session_event_outbox (
39605
- event_id, session_id, source_key, byte_length, envelope_json
39606
- ) VALUES (?, ?, ?, ?, ?)`
39607
- ).run(envelope2.eventId, envelope2.sessionId, sourceKey, byteLength, encoded);
39608
- this.#database.prepare(
39609
- `UPDATE relay_session_event_outbox_state
39610
- SET event_count = event_count + 1,
39611
- total_bytes = total_bytes + ?,
39612
- next_source_seq = next_source_seq + 1
39613
- WHERE singleton = 1`
39614
- ).run(byteLength);
39615
- this.#database.exec("COMMIT");
39616
- return encoded;
39617
- } catch (error62) {
39618
- this.#database.exec("ROLLBACK");
39619
- throw error62;
39620
- }
39621
- };
39622
- #removeAcknowledgedEvent = (eventId, sessionId) => {
39623
- this.#database.exec("BEGIN IMMEDIATE");
39624
- try {
39625
- const stored = this.#database.prepare(
39626
- `SELECT byte_length FROM relay_session_event_outbox
39627
- WHERE event_id = ? AND session_id = ?`
39628
- ).get(eventId, sessionId);
39629
- if (stored === void 0) {
39630
- this.#database.exec("COMMIT");
39631
- return false;
39632
- }
39633
- const byteLength = rowNumber(stored, "byte_length");
39634
- const deletion = this.#database.prepare(
39635
- `DELETE FROM relay_session_event_outbox
39636
- WHERE event_id = ? AND session_id = ?`
39637
- ).run(eventId, sessionId);
39638
- if (deletion.changes !== 1) {
39639
- throw new Error("The acknowledged session event could not be removed from the in-memory outbox");
39640
- }
39641
- this.#decrementEventState(byteLength);
39642
- this.#database.exec("COMMIT");
39643
- return true;
39644
- } catch (error62) {
39645
- this.#database.exec("ROLLBACK");
39646
- throw error62;
39647
- }
39648
- };
39649
- #decrementEventState = (byteLength) => {
39650
- const result = this.#database.prepare(
39651
- `UPDATE relay_session_event_outbox_state
39652
- SET event_count = event_count - 1,
39653
- total_bytes = total_bytes - ?
39654
- WHERE singleton = 1 AND event_count > 0 AND total_bytes >= ?`
39655
- ).run(byteLength, byteLength);
39656
- if (result.changes !== 1) {
39657
- throw new Error("The Session event outbox capacity state is inconsistent");
39658
- }
39659
- };
39660
- pending = () => this.#database.prepare(
39661
- `SELECT envelope_json
39662
- FROM relay_session_event_outbox
39663
- ORDER BY ordinal`
39664
- ).all().map(readPendingEnvelope);
39665
- pendingBatch = (limit) => {
39666
- if (!Number.isSafeInteger(limit) || limit < 1) {
39667
- throw new Error("Session event replay batch limit must be a positive integer");
39668
- }
39669
- return this.#database.prepare(
39670
- `WITH ranked_events AS (
39671
- SELECT ordinal,
39672
- ROW_NUMBER() OVER (
39673
- PARTITION BY source_key
39674
- ORDER BY ordinal
39675
- ) AS source_position
39676
- FROM relay_session_event_outbox
39677
- )
39678
- SELECT outbox.envelope_json
39679
- FROM ranked_events AS ranked
39680
- INNER JOIN relay_session_event_outbox AS outbox
39681
- ON outbox.ordinal = ranked.ordinal
39682
- ORDER BY ranked.source_position, outbox.ordinal
39683
- LIMIT ?`
39684
- ).all(limit).map(readPendingEnvelope);
39685
- };
39686
- pendingSourceHeads = (limit, excludedEventIds, excludedSourceKeys) => {
39687
- if (!Number.isSafeInteger(limit) || limit < 1) {
39688
- throw new Error("Session event replay batch limit must be a positive integer");
39689
- }
39690
- const exclusions = [];
39691
- const parameters = [];
39692
- if (excludedEventIds.length > 0) {
39693
- exclusions.push(`event_id NOT IN (${excludedEventIds.map(() => "?").join(", ")})`);
39694
- parameters.push(...excludedEventIds);
39695
- }
39696
- if (excludedSourceKeys.length > 0) {
39697
- exclusions.push(`source_key NOT IN (${excludedSourceKeys.map(() => "?").join(", ")})`);
39698
- parameters.push(...excludedSourceKeys);
39699
- }
39700
- parameters.push(limit.toString());
39701
- const where = exclusions.length === 0 ? "" : `WHERE ${exclusions.join(" AND ")}`;
39702
- return this.#database.prepare(
39703
- `WITH available_events AS (
39704
- SELECT ordinal, source_key
39705
- FROM relay_session_event_outbox
39706
- ${where}
39707
- ), ranked_events AS (
39708
- SELECT ordinal,
39709
- ROW_NUMBER() OVER (
39710
- PARTITION BY source_key
39711
- ORDER BY ordinal
39712
- ) AS source_position
39713
- FROM available_events
39714
- )
39715
- SELECT outbox.envelope_json
39716
- FROM ranked_events AS ranked
39717
- INNER JOIN relay_session_event_outbox AS outbox
39718
- ON outbox.ordinal = ranked.ordinal
39719
- WHERE ranked.source_position = 1
39720
- ORDER BY outbox.ordinal
39721
- LIMIT ?`
39722
- ).all(...parameters).map(readPendingEnvelope);
39723
- };
39724
- };
39725
- function validateLimits(limits) {
39726
- const values = [
39727
- limits.criticalEventBytes,
39728
- limits.runtimeDeliveryBytes,
39729
- limits.runtimeDeliveryCount,
39730
- limits.standardEventBytes
39731
- ];
39732
- if (values.some((value) => !Number.isSafeInteger(value) || value < 1)) {
39733
- throw new Error("Session event outbox limits must be positive integers");
39734
- }
39735
- if (limits.criticalEventBytes < limits.standardEventBytes) {
39736
- throw new Error("Critical Session event capacity must include the standard capacity");
39737
- }
39738
- }
39739
- function runtimeDeliveryState(row) {
39740
- const state = rowString(row, "state");
39741
- if (state !== "received" && state !== "relay_committed" && state !== "processed") {
39742
- throw new Error("SQLite returned an invalid Runtime delivery state");
39743
- }
39744
- return state;
39745
- }
39746
- function isDaemonExecutionState(value) {
39747
- return value === "cancelled" || value === "dispatching" || value === "failed" || value === "running" || value === "succeeded";
39748
- }
39749
-
39750
39259
  // src/relay-connection/session-event-publisher.ts
39751
39260
  import { WebSocket as WebSocket4 } from "undici";
39752
- var DaemonSessionEventConnectionState = class {
39753
- };
39754
- var DisconnectedDaemonSessionEventState = class extends DaemonSessionEventConnectionState {
39755
- disconnect = () => this;
39756
- matches = () => false;
39757
- send = () => false;
39758
- };
39759
- var ConnectedDaemonSessionEventState = class extends DaemonSessionEventConnectionState {
39760
- #socket;
39761
- constructor(socket) {
39762
- super();
39763
- this.#socket = socket;
39764
- }
39765
- disconnect = (socket) => socket === this.#socket ? new DisconnectedDaemonSessionEventState() : this;
39766
- matches = (socket) => socket === this.#socket;
39767
- send = (message) => {
39768
- if (this.#socket.readyState !== WebSocket4.OPEN) {
39769
- return false;
39770
- }
39771
- try {
39772
- this.#socket.send(encodeDaemonToServiceMessage(message));
39773
- return true;
39774
- } catch {
39775
- return false;
39776
- }
39777
- };
39778
- };
39779
- var SESSION_EVENT_REPLAY_WINDOW = 16;
39780
- var SESSION_EVENT_SOURCE_REPLAY_WINDOW = 4;
39781
- var SESSION_EVENT_REPLAY_BYTE_LIMIT = 32 * 1024 * 1024;
39782
- function reservesSessionEventCapacity(event) {
39783
- if (event.kind === SESSION_COMPLETED_KIND || event.kind === SESSION_FAILED_KIND) {
39784
- return true;
39785
- }
39786
- return event.kind === AGENT_ACTIVITY_KIND && (event.activityType === "progress" || event.activityType === "reasoning") && (event.status === "completed" || event.status === "failed");
39787
- }
39788
- var InFlightSessionEvent = class {
39789
- byteLength;
39790
- sourceKey;
39791
- constructor(sourceKey, byteLength) {
39792
- this.byteLength = byteLength;
39793
- this.sourceKey = sourceKey;
39794
- }
39795
- };
39796
- function sessionEventSourceKey(envelope2) {
39797
- return envelope2.source.kind === "attempt" ? `attempt:${envelope2.sessionId}:${envelope2.source.attemptId}` : `runtime:${envelope2.sessionId}`;
39798
- }
39261
+ var MAX_LIVE_EVENT_BUFFERED_BYTES = 16 * 1024 * 1024;
39799
39262
  var DaemonSessionEventPublisher = class {
39800
- #outbox;
39801
- #inFlightEvents = /* @__PURE__ */ new Map();
39802
- #pausedSources = /* @__PURE__ */ new Map();
39803
- #shedEventKinds = /* @__PURE__ */ new Set();
39804
- #timer;
39805
- #inFlightBytes = 0;
39806
- #connection = new DisconnectedDaemonSessionEventState();
39807
- constructor(outbox, timer) {
39808
- this.#outbox = outbox;
39809
- this.#timer = timer;
39810
- }
39263
+ #socket = null;
39264
+ #reportedDrop = false;
39811
39265
  connect = (socket) => {
39812
- this.#connection = new ConnectedDaemonSessionEventState(socket);
39813
- this.#clearInFlight();
39814
- this.#publishNextBatch();
39266
+ this.#socket = socket;
39267
+ this.#reportedDrop = false;
39815
39268
  };
39816
39269
  disconnect = (socket) => {
39817
- if (!this.#connection.matches(socket)) {
39818
- return;
39819
- }
39820
- this.#connection = this.#connection.disconnect(socket);
39821
- this.#clearInFlight();
39822
- };
39823
- recordAttempt = (sessionId, event, attemptId) => {
39824
- const encoded = encodeRecordedSessionEvent(event);
39825
- if (reservesSessionEventCapacity(event)) {
39826
- this.#enqueueReserved(sessionId, encoded, attemptId, event.kind);
39827
- } else {
39828
- this.#enqueueStandard(sessionId, encoded, attemptId, event.kind);
39829
- }
39830
- this.#publishNextBatch();
39831
- };
39832
- recordRuntime = (sessionId, event) => {
39833
- this.#enqueueStandard(sessionId, encodeRecordedSessionEvent(event), "", event.kind);
39834
- this.#publishNextBatch();
39835
- };
39836
- /**
39837
- * Enqueue a standard event, shedding it instead of ending the daemon when the
39838
- * in-memory outbox is full.
39839
- *
39840
- * A capacity error used to escape the coalescing timer that publishes activities,
39841
- * so the process exited and every restart died on the same retained backlog. A full
39842
- * outbox is a recoverable runtime condition, not a fatal one: narration increments are
39843
- * superseded by the completed snapshot, so they are shed first, and any other streaming
39844
- * event is shed only at the wall rather than terminating the daemon.
39845
- */
39846
- #enqueueStandard = (sessionId, encoded, attemptId, kind) => {
39847
- if (kind === AGENT_ACTIVITY_NARRATION_KIND && this.#outbox.standardCapacityRemaining() <= 0) {
39848
- this.#reportShedEvent(kind);
39849
- return;
39850
- }
39851
- try {
39852
- this.#outbox.enqueue(sessionId, encoded, attemptId);
39853
- } catch (error62) {
39854
- if (!(error62 instanceof SessionEventOutboxCapacityError)) {
39855
- throw error62;
39856
- }
39857
- this.#reportShedEvent(kind);
39858
- }
39859
- };
39860
- /**
39861
- * Enqueue on the reserved budget, degrading to a reported drop instead of raising.
39862
- * Streaming events are shed before this budget is reached, so a Turn's terminal
39863
- * events and the completed snapshot that carries its narration still land; a drop
39864
- * here is the last resort for a backlog no acknowledgement can drain.
39865
- */
39866
- #enqueueReserved = (sessionId, encoded, attemptId, kind) => {
39867
- try {
39868
- this.#outbox.enqueueCritical(sessionId, encoded, attemptId);
39869
- } catch (error62) {
39870
- if (!(error62 instanceof SessionEventOutboxCapacityError)) {
39871
- throw error62;
39872
- }
39873
- this.#reportShedEvent(kind);
39874
- }
39875
- };
39876
- #reportShedEvent = (kind) => {
39877
- if (this.#shedEventKinds.has(kind)) {
39878
- return;
39270
+ if (this.#socket === socket) {
39271
+ this.#socket = null;
39879
39272
  }
39880
- this.#shedEventKinds.add(kind);
39881
- console.warn(`Mobius daemon is dropping queued "${kind}" events because the Session event outbox is full`);
39882
39273
  };
39883
- acknowledge = (acknowledgement) => {
39884
- if (!this.#outbox.acknowledge(acknowledgement)) {
39274
+ publish = (sessionId, event) => {
39275
+ const socket = this.#socket;
39276
+ if (socket === null || socket.readyState !== WebSocket4.OPEN) {
39277
+ this.#reportDrop();
39885
39278
  return;
39886
39279
  }
39887
- this.#removeInFlight(acknowledgement.eventId);
39888
- this.#publishNextBatch();
39889
- };
39890
- quarantine = (rejection) => {
39891
- const quarantined = this.#outbox.quarantine(rejection);
39892
- if (!quarantined) {
39893
- return false;
39894
- }
39895
- this.#removeInFlight(rejection.eventId);
39896
- this.#publishNextBatch();
39897
- return true;
39898
- };
39899
- defer = (deferred) => {
39900
- const inFlight = this.#inFlightEvents.get(deferred.eventId);
39901
- if (inFlight === void 0) {
39280
+ if (socket.bufferedAmount >= MAX_LIVE_EVENT_BUFFERED_BYTES) {
39281
+ this.#socket = null;
39282
+ socket.close(1013, "Live event backpressure");
39283
+ this.#reportDrop();
39902
39284
  return;
39903
39285
  }
39904
- this.#clearInFlightSource(inFlight.sourceKey);
39905
- if (!this.#pausedSources.has(inFlight.sourceKey)) {
39906
- this.#pausedSources.set(
39907
- inFlight.sourceKey,
39908
- this.#timer.schedule(() => {
39909
- this.#pausedSources.delete(inFlight.sourceKey);
39910
- this.#publishNextBatch();
39911
- }, deferred.retryAfterMilliseconds)
39286
+ try {
39287
+ socket.send(
39288
+ encodeDaemonToServiceMessage({
39289
+ kind: SESSION_EVENT_KIND,
39290
+ payload: encodeRecordedSessionEvent(event),
39291
+ sessionId
39292
+ })
39912
39293
  );
39294
+ } catch {
39295
+ this.#reportDrop();
39913
39296
  }
39914
- this.#publishNextBatch();
39915
39297
  };
39916
39298
  close = () => {
39917
- for (const task of this.#pausedSources.values()) {
39918
- task.cancel();
39919
- }
39920
- this.#pausedSources.clear();
39921
- this.#clearInFlight();
39299
+ this.#socket = null;
39922
39300
  };
39923
- #publishNextBatch = () => {
39924
- while (this.#inFlightEvents.size < SESSION_EVENT_REPLAY_WINDOW) {
39925
- const sourceCounts = /* @__PURE__ */ new Map();
39926
- for (const inFlight of this.#inFlightEvents.values()) {
39927
- sourceCounts.set(inFlight.sourceKey, (sourceCounts.get(inFlight.sourceKey) ?? 0) + 1);
39928
- }
39929
- const saturatedSources = [...sourceCounts.entries()].filter(([, count]) => count >= SESSION_EVENT_SOURCE_REPLAY_WINDOW).map(([sourceKey]) => sourceKey);
39930
- const batch = this.#outbox.pendingSourceHeads(
39931
- SESSION_EVENT_REPLAY_WINDOW - this.#inFlightEvents.size,
39932
- [...this.#inFlightEvents.keys()],
39933
- [...this.#pausedSources.keys(), ...saturatedSources]
39934
- );
39935
- let sent = 0;
39936
- for (const encoded of batch) {
39937
- const envelope2 = decodeSessionEventEnvelope(encoded);
39938
- const sourceKey = sessionEventSourceKey(envelope2);
39939
- const sourceCount = sourceCounts.get(sourceKey) ?? 0;
39940
- if (sourceCount >= SESSION_EVENT_SOURCE_REPLAY_WINDOW) {
39941
- continue;
39942
- }
39943
- const byteLength = new TextEncoder().encode(encoded).byteLength;
39944
- if (this.#inFlightBytes + byteLength > SESSION_EVENT_REPLAY_BYTE_LIMIT) {
39945
- continue;
39946
- }
39947
- if (!this.#connection.send(envelope2)) {
39948
- this.#clearInFlight();
39949
- return;
39950
- }
39951
- this.#inFlightEvents.set(envelope2.eventId, new InFlightSessionEvent(sourceKey, byteLength));
39952
- this.#inFlightBytes += byteLength;
39953
- sourceCounts.set(sourceKey, sourceCount + 1);
39954
- sent += 1;
39955
- }
39956
- if (sent === 0) {
39957
- return;
39958
- }
39959
- }
39960
- };
39961
- #removeInFlight = (eventId) => {
39962
- const inFlight = this.#inFlightEvents.get(eventId);
39963
- if (inFlight === void 0) {
39301
+ #reportDrop = () => {
39302
+ if (this.#reportedDrop) {
39964
39303
  return;
39965
39304
  }
39966
- this.#inFlightEvents.delete(eventId);
39967
- this.#inFlightBytes -= inFlight.byteLength;
39968
- };
39969
- #clearInFlight = () => {
39970
- this.#inFlightEvents.clear();
39971
- this.#inFlightBytes = 0;
39972
- };
39973
- #clearInFlightSource = (sourceKey) => {
39974
- for (const [eventId, inFlight] of this.#inFlightEvents) {
39975
- if (inFlight.sourceKey !== sourceKey) {
39976
- continue;
39977
- }
39978
- this.#inFlightEvents.delete(eventId);
39979
- this.#inFlightBytes -= inFlight.byteLength;
39980
- }
39305
+ this.#reportedDrop = true;
39306
+ console.warn("Mobius daemon dropped live Session events while the Relay was unavailable");
39981
39307
  };
39982
39308
  };
39983
39309
 
@@ -40051,7 +39377,7 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
40051
39377
  {
40052
39378
  agentId: agent.id,
40053
39379
  kind: AGENT_INSTALL_REQUEST_KIND,
40054
- requestId: `automatic-integration-${randomUUID6()}`
39380
+ requestId: `automatic-integration-${randomUUID7()}`
40055
39381
  },
40056
39382
  signal
40057
39383
  );
@@ -40096,9 +39422,8 @@ async function refreshAgentCatalog(config2, resolveEnvironment, signal) {
40096
39422
  throw error62;
40097
39423
  }
40098
39424
  }
40099
- async function runRelayConnection(config2, directories, audit, sessions, installations, installationObserver, nativeSessions, outbox, publisher, activeTurns, activeAttemptIds, connectionEpoch, diagnostics, onConnected, signal, timer, resolveAgentCatalogEnvironment) {
39425
+ async function runRelayConnection(config2, directories, audit, sessions, installations, installationObserver, nativeSessions, operations, publisher, activeTurns, connectionEpoch, diagnostics, onConnected, signal, timer, resolveAgentCatalogEnvironment) {
40100
39426
  const relayUrl = new URL(config2.relayUrl);
40101
- relayUrl.searchParams.set("deliveryReceipts", "1");
40102
39427
  relayUrl.searchParams.set("liveness", "1");
40103
39428
  const socket = await connectRelay(relayUrl, signal);
40104
39429
  const reconnectingTurns = [...activeTurns.values()];
@@ -40149,226 +39474,48 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40149
39474
  closeRelaySocket(socket, code, reason);
40150
39475
  rejectConnection(failure2);
40151
39476
  };
40152
- const processingDeliveryIds = /* @__PURE__ */ new Set();
40153
- const sessionAvailable = (command) => {
40154
- if (command.disposition === SessionPromptDisposition.Steer) {
40155
- return true;
40156
- }
40157
- const first = [...activeTurns.values()].find(
40158
- (turn) => turn.command.sessionId === command.sessionId && turn.command.disposition !== SessionPromptDisposition.Steer
40159
- );
40160
- return first === void 0 || first.command.commandId === command.commandId;
40161
- };
40162
- const processDeliveredPrompt = async (delivery, command, trackActiveAttempt, execute) => {
40163
- if (command.sessionId !== delivery.sessionId) {
40164
- throw new Error("Runtime delivery Session identity does not match its payload");
40165
- }
40166
- const active = activeTurns.get(command.commandId);
40167
- if (active !== void 0) {
40168
- await active.completion;
40169
- return;
40170
- }
40171
- const receipt = outbox.claimExecution(command.commandId, command.sessionId, delivery.payload);
40172
- if (receipt.kind === "duplicate") {
40173
- if (receipt.state === "running") {
40174
- reportFailure(
40175
- publisher,
40176
- command,
40177
- "agent_execution_interrupted",
40178
- "The local Agent execution was interrupted before it completed",
40179
- receipt.attemptId
40180
- );
40181
- outbox.transitionExecution(command.commandId, "failed");
40182
- return;
40183
- }
40184
- if (receipt.state !== "dispatching") {
40185
- return;
40186
- }
40187
- }
40188
- const turn = new ActiveDaemonTurn(command, receipt.attemptId);
40189
- activeTurns.set(command.commandId, turn);
40190
- const activateAttempt = () => {
40191
- const stream = turn.accept();
40192
- if (trackActiveAttempt) {
40193
- activeAttemptIds.set(command.sessionId, receipt.attemptId);
40194
- }
40195
- return stream;
40196
- };
40197
- try {
40198
- await execute(receipt.attemptId, activateAttempt, turn.signal, turn);
40199
- } finally {
40200
- activeTurns.delete(command.commandId);
40201
- if (activeAttemptIds.get(command.sessionId) === receipt.attemptId) {
40202
- activeAttemptIds.delete(command.sessionId);
40203
- }
40204
- turn.finish();
40205
- }
39477
+ const waitForTurnCompletion = (turn, waitSignal) => {
39478
+ waitSignal.throwIfAborted();
39479
+ return new Promise((resolve9, reject2) => {
39480
+ let settled = false;
39481
+ const finish = (result) => {
39482
+ if (settled) {
39483
+ return;
39484
+ }
39485
+ settled = true;
39486
+ waitSignal.removeEventListener("abort", onAbort);
39487
+ if (result.kind === "completed") {
39488
+ resolve9();
39489
+ } else {
39490
+ reject2(result.error);
39491
+ }
39492
+ };
39493
+ const onAbort = () => finish({ error: waitSignal.reason, kind: "failed" });
39494
+ waitSignal.addEventListener("abort", onAbort, { once: true });
39495
+ void turn.completion.then(
39496
+ () => finish({ kind: "completed" }),
39497
+ (error62) => finish({ error: error62, kind: "failed" })
39498
+ );
39499
+ });
40206
39500
  };
40207
- const processDeliveredPayload = async (delivery) => {
40208
- const message = decodeServiceToDaemonMessage(delivery.payload);
40209
- const kind = message.kind;
40210
- if (kind === SESSION_CANCEL_KIND) {
40211
- const cancellation = message;
40212
- if (cancellation.sessionId !== delivery.sessionId) {
40213
- throw new Error("Runtime delivery Session identity does not match its payload");
40214
- }
40215
- const turn = activeTurns.get(cancellation.commandId);
40216
- if (turn === void 0 || !turn.matches(cancellation)) {
40217
- settleAbandonedTurn(publisher, outbox, audit, cancellation);
40218
- return;
40219
- }
40220
- if (!turn.requestCancellation()) {
40221
- return;
40222
- }
40223
- audit.record({
40224
- commandId: cancellation.commandId,
40225
- event: "session_cancellation_requested",
40226
- sessionId: cancellation.sessionId
40227
- });
40228
- await sessions.cancelPrompt(cancellation.sessionId);
40229
- return;
39501
+ const waitForSessionAvailability = async (command, waitSignal) => {
39502
+ if (command.disposition === SessionPromptDisposition.Steer) {
39503
+ return "available";
40230
39504
  }
40231
- if (kind === SESSION_CONFIGURE_KIND) {
40232
- const command = message;
40233
- if (command.sessionId !== delivery.sessionId) {
40234
- throw new Error("Runtime delivery Session identity does not match its payload");
40235
- }
40236
- await executeSessionConfigure(
40237
- publisher,
40238
- socket,
40239
- command,
40240
- config2,
40241
- directories,
40242
- audit,
40243
- sessions,
40244
- connectionController.signal
39505
+ for (; ; ) {
39506
+ const first = [...activeTurns.values()].find(
39507
+ (turn) => turn.command.sessionId === command.sessionId && turn.command.disposition !== SessionPromptDisposition.Steer
40245
39508
  );
40246
- return;
40247
- }
40248
- if (kind === SESSION_PERMISSION_RESPOND_KIND) {
40249
- const command = message;
40250
- if (command.sessionId !== delivery.sessionId) {
40251
- throw new Error("Runtime delivery Session identity does not match its payload");
39509
+ if (first === void 0 || first.command.commandId === command.commandId) {
39510
+ return command.disposition !== SessionPromptDisposition.Queue || operations.isTerminalExecution(command.targetCommandId, command.sessionId) ? "available" : "queue-target-unavailable";
40252
39511
  }
40253
- try {
40254
- await sessions.respondPermission(command);
40255
- audit.record({
40256
- commandId: command.interactionId,
40257
- event: "session_permission_resolved",
40258
- sessionId: command.sessionId
40259
- });
40260
- } catch (error62) {
40261
- reportOperationFailure(socket, command.interactionId, command.sessionId, error62);
39512
+ if (command.disposition !== SessionPromptDisposition.Queue) {
39513
+ return "busy";
40262
39514
  }
40263
- return;
40264
- }
40265
- if (kind === SESSION_ELICITATION_RESPOND_KIND) {
40266
- const command = message;
40267
- if (command.sessionId !== delivery.sessionId) {
40268
- throw new Error("Runtime delivery Session identity does not match its payload");
40269
- }
40270
- try {
40271
- await sessions.respondElicitation(command);
40272
- audit.record({
40273
- commandId: command.interactionId,
40274
- event: "session_elicitation_resolved",
40275
- sessionId: command.sessionId
40276
- });
40277
- } catch (error62) {
40278
- reportOperationFailure(socket, command.interactionId, command.sessionId, error62);
40279
- }
40280
- return;
40281
- }
40282
- if (kind === SESSION_PROMPT_KIND) {
40283
- const command = message;
40284
- await processDeliveredPrompt(
40285
- delivery,
40286
- command,
40287
- command.disposition !== SessionPromptDisposition.Steer,
40288
- (attemptId, activateAttempt, executionSignal, turn) => executePrompt(
40289
- outbox,
40290
- publisher,
40291
- command,
40292
- config2,
40293
- directories,
40294
- audit,
40295
- sessions,
40296
- attemptId,
40297
- activateAttempt,
40298
- () => sessionAvailable(command),
40299
- timer,
40300
- executionSignal,
40301
- turn.recordText
40302
- )
40303
- );
40304
- return;
40305
- }
40306
- throw new Error("Runtime delivery contains an unsupported protocol message");
40307
- };
40308
- const processRuntimeDelivery = (delivery, state) => {
40309
- if (state === "processed" || processingDeliveryIds.has(delivery.deliveryId)) {
40310
- return;
40311
- }
40312
- processingDeliveryIds.add(delivery.deliveryId);
40313
- void processDeliveredPayload(delivery).then(() => {
40314
- outbox.markRuntimeDeliveryProcessed(delivery.deliveryId, delivery.sessionId);
40315
- }).catch((error62) => {
40316
- if (connectionController.signal.aborted) {
40317
- return;
40318
- }
40319
- console.error("Mobius daemon could not process a in-memory Runtime delivery", error62);
40320
- failAndClose(
40321
- new Error("Runtime delivery processing failed", { cause: error62 }),
40322
- 4008,
40323
- "Invalid Runtime delivery",
40324
- "delivery"
40325
- );
40326
- }).finally(() => processingDeliveryIds.delete(delivery.deliveryId));
40327
- };
40328
- const receiveRuntimeDelivery = (delivery) => {
40329
- const payload = decodeServiceToDaemonMessage(delivery.payload);
40330
- const payloadKind = payload.kind;
40331
- let payloadSessionId = "";
40332
- if (payloadKind === SESSION_CANCEL_KIND) {
40333
- payloadSessionId = payload.sessionId;
40334
- } else if (payloadKind === SESSION_CONFIGURE_KIND) {
40335
- payloadSessionId = payload.sessionId;
40336
- } else if (payloadKind === SESSION_PERMISSION_RESPOND_KIND) {
40337
- payloadSessionId = payload.sessionId;
40338
- } else if (payloadKind === SESSION_ELICITATION_RESPOND_KIND) {
40339
- payloadSessionId = payload.sessionId;
40340
- } else if (payloadKind === SESSION_PROMPT_KIND) {
40341
- payloadSessionId = payload.sessionId;
40342
- } else {
40343
- throw new Error("Runtime delivery contains an unsupported protocol message");
40344
- }
40345
- if (payloadSessionId !== delivery.sessionId) {
40346
- throw new Error("Runtime delivery Session identity does not match its payload");
40347
- }
40348
- const stored = outbox.claimRuntimeDelivery(delivery);
40349
- send(socket, {
40350
- deliveryId: delivery.deliveryId,
40351
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
40352
- sessionId: delivery.sessionId
40353
- });
40354
- processRuntimeDelivery(delivery, stored.state);
40355
- };
40356
- const resumeRuntimeDeliveries = () => {
40357
- for (const stored of outbox.runtimeDeliveries()) {
40358
- const delivery = {
40359
- deliveryId: stored.deliveryId,
40360
- kind: RUNTIME_DELIVERY_KIND,
40361
- payload: stored.payload,
40362
- sessionId: stored.sessionId
40363
- };
40364
- if (stored.state !== "relay_committed") {
40365
- send(socket, {
40366
- deliveryId: stored.deliveryId,
40367
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
40368
- sessionId: stored.sessionId
40369
- });
39515
+ if (first.command.commandId !== command.targetCommandId) {
39516
+ return "queue-target-unavailable";
40370
39517
  }
40371
- processRuntimeDelivery(delivery, stored.state);
39518
+ await waitForTurnCompletion(first, waitSignal);
40372
39519
  }
40373
39520
  };
40374
39521
  const connectionLiveness = new RelayConnectionLiveness(timer, {
@@ -40427,39 +39574,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40427
39574
  try {
40428
39575
  const message = decodeServiceToDaemonMessage(encoded);
40429
39576
  const kind = message.kind;
40430
- if (kind === RUNTIME_DELIVERY_COMMITTED_KIND) {
40431
- const committed = message;
40432
- if (!outbox.markRuntimeDeliveryCommitted(committed.deliveryId, committed.sessionId)) {
40433
- console.warn("Mobius daemon ignored confirmation for an unknown Runtime delivery");
40434
- }
40435
- return;
40436
- }
40437
- if (kind === RUNTIME_DELIVERY_KIND) {
40438
- receiveRuntimeDelivery(message);
40439
- return;
40440
- }
40441
- if (kind === SESSION_EVENT_ACK_KIND) {
40442
- publisher.acknowledge(message);
40443
- return;
40444
- }
40445
- if (kind === SESSION_EVENT_DEFERRED_KIND) {
40446
- publisher.defer(message);
40447
- return;
40448
- }
40449
- if (kind === SESSION_EVENT_REJECTED_KIND) {
40450
- const rejection = message;
40451
- if (publisher.quarantine(rejection)) {
40452
- audit.record({
40453
- commandId: rejection.eventId,
40454
- details: { code: rejection.code },
40455
- event: "session_event_rejected",
40456
- sessionId: rejection.sessionId
40457
- });
40458
- } else {
40459
- console.warn("Mobius daemon ignored a rejection for an unknown session event");
40460
- }
40461
- return;
40462
- }
40463
39577
  if (kind === SESSION_LIVE_HISTORY_LOAD_KIND) {
40464
39578
  const command2 = decodeSessionLiveHistoryLoad(encoded);
40465
39579
  void executeSessionLiveHistoryLoad(
@@ -40937,7 +40051,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40937
40051
  const cancellation = message;
40938
40052
  const turn2 = activeTurns.get(cancellation.commandId);
40939
40053
  if (turn2 === void 0 || !turn2.matches(cancellation)) {
40940
- settleAbandonedTurn(publisher, outbox, audit, cancellation);
40054
+ settleAbandonedTurn(publisher, operations, audit, cancellation);
40941
40055
  return;
40942
40056
  }
40943
40057
  if (!turn2.requestCancellation()) {
@@ -41033,14 +40147,14 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41033
40147
  if (activeTurns.has(command.commandId)) {
41034
40148
  return;
41035
40149
  }
41036
- const receipt = outbox.claimExecution(command.commandId, command.sessionId, encoded);
40150
+ const receipt = operations.claimExecution(command.commandId, command.sessionId, encoded);
41037
40151
  if (receipt.kind === "duplicate") {
41038
40152
  return;
41039
40153
  }
41040
40154
  const turn = new ActiveDaemonTurn(command, receipt.attemptId);
41041
40155
  activeTurns.set(command.commandId, turn);
41042
40156
  void executePrompt(
41043
- outbox,
40157
+ operations,
41044
40158
  publisher,
41045
40159
  command,
41046
40160
  config2,
@@ -41048,32 +40162,20 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41048
40162
  audit,
41049
40163
  sessions,
41050
40164
  receipt.attemptId,
41051
- () => {
41052
- const stream = turn.accept();
41053
- if (command.disposition !== SessionPromptDisposition.Steer) {
41054
- activeAttemptIds.set(command.sessionId, receipt.attemptId);
41055
- }
41056
- return stream;
41057
- },
41058
- () => sessionAvailable(command),
40165
+ turn.accept,
40166
+ (waitSignal) => waitForSessionAvailability(command, waitSignal),
41059
40167
  timer,
41060
40168
  turn.signal,
41061
- turn.recordText
40169
+ turn.recordText,
40170
+ turn.cancellationRequested
41062
40171
  ).catch((error62) => {
41063
40172
  console.error("Mobius daemon turn failed", error62);
41064
40173
  }).finally(() => {
41065
40174
  activeTurns.delete(command.commandId);
41066
- if (activeAttemptIds.get(command.sessionId) === receipt.attemptId) {
41067
- activeAttemptIds.delete(command.sessionId);
41068
- }
41069
40175
  turn.finish();
41070
40176
  });
41071
40177
  } catch (error62) {
41072
40178
  console.error("Mobius daemon rejected a message", error62);
41073
- if (error62 instanceof RuntimeDeliveryInboxCapacityError) {
41074
- failAndClose(error62, 4013, "Runtime delivery queue full", "delivery_backpressure");
41075
- return;
41076
- }
41077
40179
  failAndClose(
41078
40180
  new Error("Relay sent an invalid protocol message", { cause: error62 }),
41079
40181
  4008,
@@ -41091,7 +40193,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41091
40193
  return;
41092
40194
  }
41093
40195
  publisher.connect(socket);
41094
- resumeRuntimeDeliveries();
41095
40196
  },
41096
40197
  (error62) => {
41097
40198
  if (finished) {
@@ -41113,7 +40214,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41113
40214
  turn.abortDaemon();
41114
40215
  }
41115
40216
  publisher.connect(socket);
41116
- resumeRuntimeDeliveries();
41117
40217
  return;
41118
40218
  }
41119
40219
  failAndClose(
@@ -41150,17 +40250,11 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
41150
40250
  stateDirectory
41151
40251
  });
41152
40252
  const sessionStore = new MemoryAcpSessionStore();
41153
- const outbox = new SessionEventOutbox();
41154
- const publisher = new DaemonSessionEventPublisher(outbox, timer);
40253
+ const operations = new DaemonOperationState();
40254
+ const publisher = new DaemonSessionEventPublisher();
41155
40255
  const activeTurns = /* @__PURE__ */ new Map();
41156
- const activeAttemptIds = /* @__PURE__ */ new Map();
41157
40256
  const recordSessionEvent = (sessionId, event) => {
41158
- const attemptId = activeAttemptIds.get(sessionId);
41159
- if (attemptId === void 0) {
41160
- publisher.recordRuntime(sessionId, event);
41161
- return;
41162
- }
41163
- publisher.recordAttempt(sessionId, event, attemptId);
40257
+ publisher.publish(sessionId, event);
41164
40258
  };
41165
40259
  const sessions = new AcpSessionManager(
41166
40260
  new DaemonAcpObserver(recordSessionEvent),
@@ -41265,10 +40359,9 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
41265
40359
  installations,
41266
40360
  installationObserver,
41267
40361
  nativeSessions,
41268
- outbox,
40362
+ operations,
41269
40363
  publisher,
41270
40364
  activeTurns,
41271
- activeAttemptIds,
41272
40365
  connectionEpoch,
41273
40366
  diagnostics,
41274
40367
  () => {
@@ -41314,7 +40407,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
41314
40407
  try {
41315
40408
  publisher.close();
41316
40409
  } finally {
41317
- outbox.close();
40410
+ operations.close();
41318
40411
  }
41319
40412
  }
41320
40413
  }
@@ -41490,9 +40583,6 @@ function decodeResponse(value) {
41490
40583
  }
41491
40584
  if (value["kind"] === "listed" && Array.isArray(value["pairs"]) && value["pairs"].every(isManagedRuntimeSummary)) {
41492
40585
  const managerVersion = value["managerVersion"];
41493
- if (managerVersion === void 0) {
41494
- return { kind: "legacy-listed", pairs: value["pairs"] };
41495
- }
41496
40586
  if (typeof managerVersion === "string" && managerVersion.length > 0 && managerVersion.length <= 128) {
41497
40587
  return { kind: "listed", managerVersion, pairs: value["pairs"] };
41498
40588
  }
@@ -41791,11 +40881,7 @@ async function requestManager(installation, managerVersion, command, signal) {
41791
40881
  if (command.kind === "list") {
41792
40882
  return listed;
41793
40883
  }
41794
- const response = await sendControlRequest(installation.stateDirectory, command, deadline);
41795
- if (response.kind === "legacy-listed") {
41796
- throw new Error("The Mobius manager returned an unexpected response");
41797
- }
41798
- return response;
40884
+ return await sendControlRequest(installation.stateDirectory, command, deadline);
41799
40885
  }
41800
40886
  async function ensureMatchingManager(stateDirectory, managerVersion, signal) {
41801
40887
  let managerStarted = false;
@@ -41809,7 +40895,7 @@ async function ensureMatchingManager(stateDirectory, managerVersion, signal) {
41809
40895
  }
41810
40896
  return response;
41811
40897
  }
41812
- if (response.kind !== "listed" && response.kind !== "legacy-listed") {
40898
+ if (response.kind !== "listed") {
41813
40899
  if (response.kind === "error") {
41814
40900
  throw new Error(response.message);
41815
40901
  }