@moxt-ai/mobius 0.0.103 → 0.0.106

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/acp/process-session.d.ts.map +1 -1
  2. package/dist/acp/process-session.js +11 -6
  3. package/dist/acp/process-session.js.map +1 -1
  4. package/dist/acp/session-manager.d.ts +2 -0
  5. package/dist/acp/session-manager.d.ts.map +1 -1
  6. package/dist/acp/session-manager.js +5 -0
  7. package/dist/acp/session-manager.js.map +1 -1
  8. package/dist/acp/session-store.d.ts +5 -1
  9. package/dist/acp/session-store.d.ts.map +1 -1
  10. package/dist/acp/session-store.js +6 -1
  11. package/dist/acp/session-store.js.map +1 -1
  12. package/dist/cli.js +362 -1249
  13. package/dist/cli.js.map +4 -4
  14. package/dist/daemon-manager.d.ts.map +1 -1
  15. package/dist/daemon-manager.js +2 -9
  16. package/dist/daemon-manager.js.map +1 -1
  17. package/dist/daemon-session-commands.d.ts +8 -5
  18. package/dist/daemon-session-commands.d.ts.map +1 -1
  19. package/dist/daemon-session-commands.js +50 -31
  20. package/dist/daemon-session-commands.js.map +1 -1
  21. package/dist/daemon-turn-reconciliation.d.ts +7 -3
  22. package/dist/daemon-turn-reconciliation.d.ts.map +1 -1
  23. package/dist/daemon-turn-reconciliation.js +9 -3
  24. package/dist/daemon-turn-reconciliation.js.map +1 -1
  25. package/dist/index.js +359 -1239
  26. package/dist/index.js.map +4 -4
  27. package/dist/native-sessions/service.d.ts +2 -1
  28. package/dist/native-sessions/service.d.ts.map +1 -1
  29. package/dist/native-sessions/service.js +27 -0
  30. package/dist/native-sessions/service.js.map +1 -1
  31. package/dist/relay-connection/coalescing-narration-publisher.d.ts +3 -3
  32. package/dist/relay-connection/coalescing-narration-publisher.js +3 -3
  33. package/dist/relay-connection/coalescing-text-publisher.d.ts +3 -4
  34. package/dist/relay-connection/coalescing-text-publisher.d.ts.map +1 -1
  35. package/dist/relay-connection/coalescing-text-publisher.js +3 -4
  36. package/dist/relay-connection/coalescing-text-publisher.js.map +1 -1
  37. package/dist/relay-connection/daemon-operation-state.d.ts +18 -0
  38. package/dist/relay-connection/daemon-operation-state.d.ts.map +1 -0
  39. package/dist/relay-connection/daemon-operation-state.js +69 -0
  40. package/dist/relay-connection/daemon-operation-state.js.map +1 -0
  41. package/dist/relay-connection/session-event-publisher.d.ts +3 -9
  42. package/dist/relay-connection/session-event-publisher.d.ts.map +1 -1
  43. package/dist/relay-connection/session-event-publisher.js +30 -224
  44. package/dist/relay-connection/session-event-publisher.js.map +1 -1
  45. package/dist/run-daemon.d.ts.map +1 -1
  46. package/dist/run-daemon.js +49 -244
  47. package/dist/run-daemon.js.map +1 -1
  48. package/dist/runtime.js +363 -1243
  49. package/dist/runtime.js.map +4 -4
  50. package/package.json +1 -1
  51. package/dist/relay-connection/session-event-outbox.d.ts +0 -61
  52. package/dist/relay-connection/session-event-outbox.d.ts.map +0 -1
  53. package/dist/relay-connection/session-event-outbox.js +0 -546
  54. package/dist/relay-connection/session-event-outbox.js.map +0 -1
package/dist/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.103",
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,45 +28872,21 @@ 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
- assertExactKeys(value, ["commandId", "kind", "attemptId", "sessionId"]);
28877
+ assertExactKeys(value, ["commandId", "epoch", "kind", "attemptId", "prompt", "sequence", "sessionId"]);
28887
28878
  assertKind(value, SESSION_STARTED_KIND);
28879
+ const sequence = readSequence(value, "sequence");
28880
+ if (sequence !== 0) {
28881
+ throw new ProtocolMessageError("Invalid live start sequence");
28882
+ }
28888
28883
  return {
28889
28884
  commandId: readIdentifier(value, "commandId"),
28885
+ epoch: readIdentifier(value, "epoch"),
28890
28886
  kind: SESSION_STARTED_KIND,
28891
28887
  attemptId: readIdentifier(value, "attemptId"),
28888
+ prompt: readText(value, "prompt", MAX_PROMPT_LENGTH),
28889
+ sequence,
28892
28890
  sessionId: readIdentifier(value, "sessionId")
28893
28891
  };
28894
28892
  }
@@ -28986,15 +28984,6 @@ function encodeRuntimeHeartbeatEvent(message) {
28986
28984
  function encodeRuntimeHeartbeatAckEvent(message) {
28987
28985
  return JSON.stringify(decodeRuntimeHeartbeatAckEvent(JSON.stringify(message)));
28988
28986
  }
28989
- function encodeRuntimeDelivery(message) {
28990
- return JSON.stringify(decodeRuntimeDelivery(JSON.stringify(message)));
28991
- }
28992
- function encodeRuntimeDeliveryReceived(message) {
28993
- return JSON.stringify(decodeRuntimeDeliveryReceived(JSON.stringify(message)));
28994
- }
28995
- function encodeRuntimeDeliveryCommitted(message) {
28996
- return JSON.stringify(decodeRuntimeDeliveryCommitted(JSON.stringify(message)));
28997
- }
28998
28987
  function decodeAgentActivityNarrationEvent(encoded) {
28999
28988
  const value = parseJson2(encoded);
29000
28989
  assertExactKeys(value, ["activityId", "activityType", "commandId", "kind", "sequence", "sessionId", "text"]);
@@ -29108,6 +29097,7 @@ var NATIVE_SESSION_RESULT_KIND = "native.session.result";
29108
29097
  var NATIVE_SESSION_CANCEL_KIND = "native.session.cancel";
29109
29098
  var NATIVE_SESSION_TURN_FORK_REQUEST_KIND = "native.session.turn-fork.request";
29110
29099
  var NATIVE_SESSION_TURN_FORK_KIND = "native.session.turn-fork";
29100
+ var ACTIVE_TURN_TEXT_LIMIT = 1e6;
29111
29101
  var identifier = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
29112
29102
  var directoryId = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/);
29113
29103
  var envelope = {
@@ -29200,6 +29190,7 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
29200
29190
  ]);
29201
29191
  var nativeSessionEntrySchema = external_exports.strictObject({
29202
29192
  entryId: identifier,
29193
+ mobiusSessionIds: external_exports.array(identifier).max(500).readonly(),
29203
29194
  nativeSessionId: identifier,
29204
29195
  title: external_exports.string().max(500),
29205
29196
  directoryId,
@@ -29226,7 +29217,7 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
29226
29217
  turn: external_exports.strictObject({
29227
29218
  commandId: identifier,
29228
29219
  prompt: external_exports.string().max(1e5),
29229
- text: external_exports.string().max(1e5),
29220
+ text: external_exports.string().max(ACTIVE_TURN_TEXT_LIMIT),
29230
29221
  truncated: external_exports.boolean(),
29231
29222
  epoch: identifier,
29232
29223
  sequence: external_exports.number().int().nonnegative(),
@@ -29301,65 +29292,17 @@ var encodeNativeSessionTurnForkCommand = (value) => JSON.stringify(nativeSession
29301
29292
 
29302
29293
  // ../protocol/src/session-events.ts
29303
29294
  var SESSION_EVENT_KIND = "session.event";
29304
- var SESSION_EVENT_ACK_KIND = "session.event.ack";
29305
29295
  var SESSION_EVENT_COMMITTED_KIND = "session.event.committed";
29306
- var SESSION_EVENT_DEFERRED_KIND = "session.event.deferred";
29307
- var SESSION_EVENT_REJECTED_KIND = "session.event.rejected";
29308
- var SessionEventRejectionCode = {
29309
- SessionDeleted: "session_deleted",
29310
- SessionNotFound: "session_not_found",
29311
- SessionRejected: "session_rejected"
29312
- };
29313
29296
  var IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
29314
- var CURSOR_PATTERN = /^[A-Za-z0-9_-]{1,512}$/;
29315
29297
  var MAX_RECORDED_EVENT_LENGTH = 8 * 1024 * 1024;
29316
- var DECIMAL_SEQUENCE_PATTERN = /^(?:0|[1-9][0-9]*)$/;
29317
- var eventSourceSchema = external_exports.discriminatedUnion("kind", [
29318
- external_exports.strictObject({
29319
- attemptId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29320
- kind: external_exports.literal("attempt"),
29321
- sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
29322
- }).readonly(),
29323
- external_exports.strictObject({
29324
- kind: external_exports.literal("runtime"),
29325
- sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
29326
- }).readonly()
29327
- ]);
29328
29298
  var eventEnvelopeSchema = external_exports.strictObject({
29329
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29330
29299
  kind: external_exports.literal(SESSION_EVENT_KIND),
29331
29300
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
29332
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29333
- source: eventSourceSchema
29301
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
29334
29302
  }).readonly();
29335
29303
  var committedEventSchema = external_exports.strictObject({
29336
- cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
29337
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29338
29304
  kind: external_exports.literal(SESSION_EVENT_COMMITTED_KIND),
29339
29305
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
29340
- recordedAt: external_exports.string().datetime({ offset: true }),
29341
- sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
29342
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29343
- source: eventSourceSchema
29344
- }).readonly();
29345
- var eventAcknowledgementSchema = external_exports.strictObject({
29346
- cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
29347
- duplicate: external_exports.boolean(),
29348
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29349
- kind: external_exports.literal(SESSION_EVENT_ACK_KIND),
29350
- sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
29351
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
29352
- }).readonly();
29353
- var eventDeferredSchema = external_exports.strictObject({
29354
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29355
- kind: external_exports.literal(SESSION_EVENT_DEFERRED_KIND),
29356
- retryAfterMilliseconds: external_exports.number().int().min(100).max(6e4),
29357
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
29358
- }).readonly();
29359
- var eventRejectionSchema = external_exports.strictObject({
29360
- code: external_exports.enum(SessionEventRejectionCode),
29361
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
29362
- kind: external_exports.literal(SESSION_EVENT_REJECTED_KIND),
29363
29306
  sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
29364
29307
  }).readonly();
29365
29308
  function decode5(encoded, schema) {
@@ -29388,12 +29331,6 @@ var encode4 = (message, schema) => {
29388
29331
  };
29389
29332
  var decodeSessionEventEnvelope = (encoded) => decode5(encoded, eventEnvelopeSchema);
29390
29333
  var encodeSessionEventEnvelope = (message) => encode4(message, eventEnvelopeSchema);
29391
- var decodeSessionEventAcknowledgement = (encoded) => decode5(encoded, eventAcknowledgementSchema);
29392
- var encodeSessionEventAcknowledgement = (message) => encode4(message, eventAcknowledgementSchema);
29393
- var decodeSessionEventDeferred = (encoded) => decode5(encoded, eventDeferredSchema);
29394
- var encodeSessionEventDeferred = (message) => encode4(message, eventDeferredSchema);
29395
- var decodeSessionEventRejection = (encoded) => decode5(encoded, eventRejectionSchema);
29396
- var encodeSessionEventRejection = (message) => encode4(message, eventRejectionSchema);
29397
29334
  function decodeRecordedSessionEvent(encoded) {
29398
29335
  const kind = decodeMessageKind(encoded);
29399
29336
  switch (kind) {
@@ -29523,6 +29460,11 @@ var serviceToDaemonSignatures = {
29523
29460
  decodeAgentSettingsDiscoverCommand
29524
29461
  ),
29525
29462
  [FILE_READ_KIND]: defineMessageSignature(FILE_READ_KIND, encodeFileReadCommand, decodeFileReadCommand),
29463
+ [SESSION_QUERY_KIND]: defineMessageSignature(
29464
+ SESSION_QUERY_KIND,
29465
+ encodeSessionQueryCommand,
29466
+ decodeSessionQueryCommand
29467
+ ),
29526
29468
  [NATIVE_SESSION_CANCEL_KIND]: defineMessageSignature(
29527
29469
  NATIVE_SESSION_CANCEL_KIND,
29528
29470
  encodeNativeSessionCancel,
@@ -29538,16 +29480,6 @@ var serviceToDaemonSignatures = {
29538
29480
  encodeNativeSessionTurnForkCommand,
29539
29481
  decodeNativeSessionTurnForkCommand
29540
29482
  ),
29541
- [RUNTIME_DELIVERY_KIND]: defineMessageSignature(
29542
- RUNTIME_DELIVERY_KIND,
29543
- encodeRuntimeDelivery,
29544
- decodeRuntimeDelivery
29545
- ),
29546
- [RUNTIME_DELIVERY_COMMITTED_KIND]: defineMessageSignature(
29547
- RUNTIME_DELIVERY_COMMITTED_KIND,
29548
- encodeRuntimeDeliveryCommitted,
29549
- decodeRuntimeDeliveryCommitted
29550
- ),
29551
29483
  [RUNTIME_HEARTBEAT_ACK_KIND]: defineMessageSignature(
29552
29484
  RUNTIME_HEARTBEAT_ACK_KIND,
29553
29485
  encodeRuntimeHeartbeatAckEvent,
@@ -29573,21 +29505,6 @@ var serviceToDaemonSignatures = {
29573
29505
  encodeSessionElicitationRespondCommand,
29574
29506
  decodeSessionElicitationRespondCommand
29575
29507
  ),
29576
- [SESSION_EVENT_ACK_KIND]: defineMessageSignature(
29577
- SESSION_EVENT_ACK_KIND,
29578
- encodeSessionEventAcknowledgement,
29579
- decodeSessionEventAcknowledgement
29580
- ),
29581
- [SESSION_EVENT_DEFERRED_KIND]: defineMessageSignature(
29582
- SESSION_EVENT_DEFERRED_KIND,
29583
- encodeSessionEventDeferred,
29584
- decodeSessionEventDeferred
29585
- ),
29586
- [SESSION_EVENT_REJECTED_KIND]: defineMessageSignature(
29587
- SESSION_EVENT_REJECTED_KIND,
29588
- encodeSessionEventRejection,
29589
- decodeSessionEventRejection
29590
- ),
29591
29508
  [SESSION_LIVE_HISTORY_LOAD_KIND]: defineMessageSignature(
29592
29509
  SESSION_LIVE_HISTORY_LOAD_KIND,
29593
29510
  encodeSessionLiveHistoryLoad,
@@ -29678,16 +29595,16 @@ var daemonToServiceSignatures = {
29678
29595
  [FILE_CHUNK_KIND]: defineMessageSignature(FILE_CHUNK_KIND, encodeFileChunkEvent, decodeFileChunkEvent),
29679
29596
  [FILE_END_KIND]: defineMessageSignature(FILE_END_KIND, encodeFileEndEvent, decodeFileEndEvent),
29680
29597
  [FILE_FAILED_KIND]: defineMessageSignature(FILE_FAILED_KIND, encodeFileFailedEvent, decodeFileFailedEvent),
29598
+ [SESSION_QUERIED_KIND]: defineMessageSignature(
29599
+ SESSION_QUERIED_KIND,
29600
+ encodeSessionsQueriedEvent,
29601
+ decodeSessionsQueriedEvent
29602
+ ),
29681
29603
  [NATIVE_SESSION_RESULT_KIND]: defineMessageSignature(
29682
29604
  NATIVE_SESSION_RESULT_KIND,
29683
29605
  encodeNativeSessionResult,
29684
29606
  decodeNativeSessionResult
29685
29607
  ),
29686
- [RUNTIME_DELIVERY_RECEIVED_KIND]: defineMessageSignature(
29687
- RUNTIME_DELIVERY_RECEIVED_KIND,
29688
- encodeRuntimeDeliveryReceived,
29689
- decodeRuntimeDeliveryReceived
29690
- ),
29691
29608
  [RUNTIME_HEARTBEAT_KIND]: defineMessageSignature(
29692
29609
  RUNTIME_HEARTBEAT_KIND,
29693
29610
  encodeRuntimeHeartbeatEvent,
@@ -30633,7 +30550,7 @@ var AuditStore = class {
30633
30550
  };
30634
30551
 
30635
30552
  // src/run-daemon.ts
30636
- import { randomUUID as randomUUID6 } from "node:crypto";
30553
+ import { randomUUID as randomUUID7 } from "node:crypto";
30637
30554
  import { styleText } from "node:util";
30638
30555
  import { WebSocket as WebSocket5 } from "undici";
30639
30556
 
@@ -30797,13 +30714,17 @@ var AcpStoredSession = class {
30797
30714
  nativeSessionId;
30798
30715
  prompted;
30799
30716
  sessionId;
30800
- 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()) {
30801
30720
  this.additionalDirectories = [...additionalDirectories];
30802
30721
  this.agentId = agentId;
30803
30722
  this.cwd = cwd;
30804
30723
  this.nativeSessionId = nativeSessionId;
30805
30724
  this.prompted = prompted;
30806
30725
  this.sessionId = sessionId;
30726
+ this.title = title2;
30727
+ this.updatedAt = updatedAt;
30807
30728
  }
30808
30729
  };
30809
30730
  var AcpStoredSessionLookup = class {
@@ -30828,6 +30749,7 @@ var MemoryAcpSessionStore = class {
30828
30749
  findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
30829
30750
  (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
30830
30751
  );
30752
+ list = () => [...this.#sessions.values()].toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt));
30831
30753
  markDeleted = (agentId, nativeSessionId) => {
30832
30754
  const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
30833
30755
  for (const id of ids) {
@@ -32957,7 +32879,8 @@ var AcpProcessSession = class _AcpProcessSession {
32957
32879
  nativeSessionIdSchema.parse(origin.nativeSessionId),
32958
32880
  this.#cwd,
32959
32881
  this.#additionalDirectories,
32960
- true
32882
+ true,
32883
+ ""
32961
32884
  )
32962
32885
  ) : this.#store.read(this.#mobiusSessionId)
32963
32886
  );
@@ -33033,6 +32956,7 @@ var AcpProcessSession = class _AcpProcessSession {
33033
32956
  } else if (stored instanceof FoundAcpStoredSession && stored.session.agentId === this.#agentId && stored.session.cwd === this.#cwd && arraysEqual(stored.session.additionalDirectories, this.#additionalDirectories)) {
33034
32957
  this.selectNativeSession(stored.session.nativeSessionId);
33035
32958
  this.#prompted = stored.session.prompted;
32959
+ this.#sessionTitle = stored.session.title;
33036
32960
  this.#restored = true;
33037
32961
  if (this.#capabilities.resumeSession) {
33038
32962
  lifecycleResponse = await this.#metrics.measure(
@@ -33116,18 +33040,17 @@ var AcpProcessSession = class _AcpProcessSession {
33116
33040
  this.#configOptions = this.#sessionConfigProtocol.normalizeLifecycle(lifecycleResponse);
33117
33041
  await this.#updateTail;
33118
33042
  signal.throwIfAborted();
33119
- if (this.#prompted) {
33120
- this.#store.write(
33121
- new AcpStoredSession(
33122
- this.#mobiusSessionId,
33123
- this.#agentId,
33124
- this.#nativeSessionId,
33125
- this.#cwd,
33126
- this.#additionalDirectories,
33127
- true
33128
- )
33129
- );
33130
- }
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
+ );
33131
33054
  };
33132
33055
  listNativeSessions = async (cursor, signal) => {
33133
33056
  if (!this.#capabilities.listSessions) {
@@ -33179,7 +33102,15 @@ var AcpProcessSession = class _AcpProcessSession {
33179
33102
  }
33180
33103
  const previousSessionId = this.#mobiusSessionId;
33181
33104
  this.#store.write(
33182
- 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
+ )
33183
33114
  );
33184
33115
  this.#store.remove(previousSessionId);
33185
33116
  this.#mobiusSessionId = sessionId;
@@ -33301,6 +33232,9 @@ var AcpProcessSession = class _AcpProcessSession {
33301
33232
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
33302
33233
  }
33303
33234
  const prompt = this.buildPrompt(options);
33235
+ if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
33236
+ this.#sessionTitle = truncate3(options.prompt, 500);
33237
+ }
33304
33238
  this.#store.write(
33305
33239
  new AcpStoredSession(
33306
33240
  this.#mobiusSessionId,
@@ -33308,7 +33242,8 @@ var AcpProcessSession = class _AcpProcessSession {
33308
33242
  this.#nativeSessionId,
33309
33243
  this.#cwd,
33310
33244
  this.#additionalDirectories,
33311
- true
33245
+ true,
33246
+ this.#sessionTitle
33312
33247
  )
33313
33248
  );
33314
33249
  this.#prompted = true;
@@ -33736,6 +33671,19 @@ var AcpProcessSession = class _AcpProcessSession {
33736
33671
  if (Object.hasOwn(update, "updatedAt")) {
33737
33672
  this.#sessionUpdatedAt = truncate3(update.updatedAt ?? "", 128);
33738
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
+ }
33739
33687
  await this.#getObserver().onInfo({
33740
33688
  kind: SESSION_INFO_UPDATED_KIND,
33741
33689
  sessionId: this.#mobiusSessionId,
@@ -34638,6 +34586,11 @@ var AcpSessionManager = class {
34638
34586
  )
34639
34587
  ]);
34640
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);
34641
34594
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
34642
34595
  createNativeSession = async (options) => {
34643
34596
  const temporarySessionId = `new-${crypto.randomUUID()}`;
@@ -36991,21 +36944,17 @@ function daemonActivity(command, activity2) {
36991
36944
  toolKind: activity2.toolKind
36992
36945
  };
36993
36946
  }
36994
- function reportFailure(publisher, command, code, message, attemptId) {
36995
- publisher.recordAttempt(
36996
- command.sessionId,
36997
- {
36998
- code,
36999
- commandId: command.commandId,
37000
- kind: SESSION_FAILED_KIND,
37001
- message,
37002
- sessionId: command.sessionId
37003
- },
37004
- attemptId
37005
- );
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
+ });
37006
36955
  }
37007
- function settleAbandonedTurn(publisher, outbox, audit, cancellation) {
37008
- const attemptId = outbox.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
36956
+ function settleAbandonedTurn(publisher, operations, audit, cancellation) {
36957
+ const attemptId = operations.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
37009
36958
  if (attemptId === null) {
37010
36959
  console.warn("Mobius daemon ignored cancellation for an inactive turn");
37011
36960
  return;
@@ -37019,10 +36968,9 @@ function settleAbandonedTurn(publisher, outbox, audit, cancellation) {
37019
36968
  publisher,
37020
36969
  cancellation,
37021
36970
  "agent_execution_abandoned",
37022
- "The local Agent execution was abandoned before it completed",
37023
- attemptId
36971
+ "The local Agent execution was abandoned before it completed"
37024
36972
  );
37025
- outbox.transitionExecution(cancellation.commandId, "failed");
36973
+ operations.transitionExecution(cancellation.commandId, "failed");
37026
36974
  }
37027
36975
  function operationErrorCode(error62) {
37028
36976
  if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof PromptArtifactError) {
@@ -37152,7 +37100,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
37152
37100
  event: "session_configured",
37153
37101
  sessionId: command.sessionId
37154
37102
  });
37155
- publisher.recordRuntime(command.sessionId, {
37103
+ publisher.publish(command.sessionId, {
37156
37104
  configOptions,
37157
37105
  kind: "session.config.updated",
37158
37106
  requestId: command.requestId,
@@ -37177,7 +37125,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
37177
37125
  };
37178
37126
  if (command.transient !== true) {
37179
37127
  metrics.measureSync("readiness-commit", () => {
37180
- publisher.recordRuntime(command.sessionId, event);
37128
+ publisher.publish(command.sessionId, event);
37181
37129
  });
37182
37130
  }
37183
37131
  return event;
@@ -37325,7 +37273,7 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
37325
37273
  event: "session_configured",
37326
37274
  sessionId: command.sessionId
37327
37275
  });
37328
- publisher.recordRuntime(command.sessionId, {
37276
+ publisher.publish(command.sessionId, {
37329
37277
  configOptions,
37330
37278
  kind: "session.config.updated",
37331
37279
  requestId: command.requestId,
@@ -37338,26 +37286,22 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
37338
37286
  reportOperationFailure(socket, command.requestId, command.sessionId, error62);
37339
37287
  }
37340
37288
  }
37341
- async function executePrompt(outbox, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, timer, signal, recordLiveText) {
37289
+ async function executePrompt(operations, publisher, command, config2, directories, audit, sessions, attemptId, activateAttempt, waitForSessionAvailability, timer, signal, recordLiveText, cancellationRequested) {
37342
37290
  const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
37343
- publisher.recordAttempt(command.sessionId, daemonActivity(command, activity2), attemptId);
37291
+ publisher.publish(command.sessionId, daemonActivity(command, activity2));
37344
37292
  });
37345
37293
  const narration = new CoalescingNarrationPublisher(
37346
37294
  timer,
37347
37295
  (increment) => {
37348
- publisher.recordAttempt(
37349
- command.sessionId,
37350
- {
37351
- activityId: increment.activityId,
37352
- activityType: increment.activityType,
37353
- commandId: command.commandId,
37354
- kind: AGENT_ACTIVITY_NARRATION_KIND,
37355
- sequence: increment.sequence,
37356
- sessionId: command.sessionId,
37357
- text: increment.text
37358
- },
37359
- attemptId
37360
- );
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
+ });
37361
37305
  },
37362
37306
  AGENT_ACTIVITY_COALESCING_MILLISECONDS,
37363
37307
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -37366,19 +37310,15 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
37366
37310
  timer,
37367
37311
  (messageId, delta) => {
37368
37312
  const stream = recordLiveText(delta);
37369
- publisher.recordAttempt(
37370
- command.sessionId,
37371
- {
37372
- commandId: command.commandId,
37373
- epoch: stream.epoch,
37374
- kind: AGENT_MESSAGE_DELTA_KIND,
37375
- messageId,
37376
- sequence: stream.sequence,
37377
- sessionId: command.sessionId,
37378
- text: delta
37379
- },
37380
- attemptId
37381
- );
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
+ });
37382
37322
  },
37383
37323
  AGENT_TEXT_COALESCING_MILLISECONDS,
37384
37324
  AGENT_TEXT_MAXIMUM_LENGTH
@@ -37386,13 +37326,17 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
37386
37326
  try {
37387
37327
  const resolved = await resolveSessionDirectories(
37388
37328
  directories,
37389
- config2.bindingId,
37329
+ command.bindingId,
37390
37330
  command.directoryId,
37391
37331
  command.additionalDirectoryIds,
37392
37332
  signal
37393
37333
  );
37394
37334
  const agent = config2.catalog.find(command.agentId);
37395
- if (command.disposition === SessionPromptDisposition.Queue && !outbox.isTerminalExecution(command.targetCommandId, command.sessionId)) {
37335
+ const availability = await waitForSessionAvailability(signal);
37336
+ if (availability === "busy") {
37337
+ throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
37338
+ }
37339
+ if (availability === "queue-target-unavailable") {
37396
37340
  throw new AcpExecutionError(
37397
37341
  "The queued prompt target is unavailable",
37398
37342
  {},
@@ -37432,18 +37376,17 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
37432
37376
  event: "session_authorized",
37433
37377
  sessionId: command.sessionId
37434
37378
  });
37435
- outbox.transitionExecution(command.commandId, "running");
37436
- publisher.recordAttempt(
37437
- command.sessionId,
37438
- {
37439
- commandId: command.commandId,
37440
- kind: SESSION_STARTED_KIND,
37441
- attemptId,
37442
- sessionId: command.sessionId
37443
- },
37444
- attemptId
37445
- );
37446
- activateAttempt();
37379
+ operations.transitionExecution(command.commandId, "running");
37380
+ const stream = activateAttempt();
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
+ });
37447
37390
  const attachments = await resolvePromptArtifacts(config2, command, signal);
37448
37391
  let stopReason;
37449
37392
  if (command.disposition === SessionPromptDisposition.Steer) {
@@ -37488,17 +37431,13 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
37488
37431
  text.flush();
37489
37432
  narration.flush();
37490
37433
  activities.flush();
37491
- publisher.recordAttempt(
37492
- command.sessionId,
37493
- {
37494
- commandId: command.commandId,
37495
- kind: SESSION_COMPLETED_KIND,
37496
- sessionId: command.sessionId,
37497
- stopReason
37498
- },
37499
- attemptId
37500
- );
37501
- 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");
37502
37441
  audit.record({
37503
37442
  commandId: command.commandId,
37504
37443
  event: stopReason === "cancelled" ? "session_cancelled" : "session_completed",
@@ -37508,6 +37447,21 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
37508
37447
  text.flush();
37509
37448
  narration.flush();
37510
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
+ }
37511
37465
  audit.record({
37512
37466
  commandId: command.commandId,
37513
37467
  event: "session_failed",
@@ -37518,10 +37472,9 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
37518
37472
  publisher,
37519
37473
  command,
37520
37474
  code === "session_operation_failed" ? "agent_execution_failed" : code,
37521
- code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62),
37522
- attemptId
37475
+ code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62)
37523
37476
  );
37524
- outbox.transitionExecution(command.commandId, "failed");
37477
+ operations.transitionExecution(command.commandId, "failed");
37525
37478
  console.error("Mobius daemon command failed", error62);
37526
37479
  }
37527
37480
  }
@@ -37663,7 +37616,6 @@ var DaemonInstallationObserver = class {
37663
37616
  import { randomUUID as randomUUID3 } from "node:crypto";
37664
37617
  import { fetch as fetch5 } from "undici";
37665
37618
  var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
37666
- var ACTIVE_TURN_TEXT_LIMIT = 1e5;
37667
37619
  var ActiveDaemonTurn = class {
37668
37620
  attemptId;
37669
37621
  command;
@@ -37686,6 +37638,7 @@ var ActiveDaemonTurn = class {
37686
37638
  finish = () => this.#finished.resolve();
37687
37639
  accept = () => {
37688
37640
  this.#accepted = true;
37641
+ return { epoch: this.#epoch, sequence: 0 };
37689
37642
  };
37690
37643
  recordText = (delta) => {
37691
37644
  this.#sequence += 1;
@@ -37708,11 +37661,16 @@ var ActiveDaemonTurn = class {
37708
37661
  matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
37709
37662
  requestCancellation = () => {
37710
37663
  if (this.#cancellationRequested) {
37711
- return false;
37664
+ return "already-requested";
37712
37665
  }
37713
37666
  this.#cancellationRequested = true;
37714
- 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";
37715
37672
  };
37673
+ cancellationRequested = () => this.#cancellationRequested;
37716
37674
  get signal() {
37717
37675
  return this.#controller.signal;
37718
37676
  }
@@ -38438,6 +38396,7 @@ var NativeSessionService = class {
38438
38396
  });
38439
38397
  return {
38440
38398
  entryId,
38399
+ mobiusSessionIds: this.#sessions.findLinkedSessions(command.agentId, info.sessionId).filter((session) => session.prompted && session.cwd === authorized.cwd).map((session) => session.sessionId),
38441
38400
  nativeSessionId: info.sessionId,
38442
38401
  title: info.title ?? "Untitled session",
38443
38402
  directoryId: authorized.directoryId,
@@ -38655,6 +38614,29 @@ var NativeSessionService = class {
38655
38614
  history: opened.history
38656
38615
  };
38657
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
+ };
38658
38640
  executeTurnFork = async (command, signal) => {
38659
38641
  signal.throwIfAborted();
38660
38642
  const cwd = await this.#directories.resolve(this.#config.bindingId, command.directoryId, signal);
@@ -38927,6 +38909,75 @@ function connectRelay(url2, signal) {
38927
38909
  });
38928
38910
  }
38929
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
+
38930
38981
  // src/relay-connection/diagnostics.ts
38931
38982
  var MAX_DIAGNOSTIC_TEXT_LENGTH = 256;
38932
38983
  function sanitizeDiagnosticText(value) {
@@ -39100,7 +39151,7 @@ var RelayConnectionDiagnostics = class {
39100
39151
  };
39101
39152
 
39102
39153
  // src/relay-connection/liveness.ts
39103
- import { randomUUID as randomUUID5 } from "node:crypto";
39154
+ import { randomUUID as randomUUID6 } from "node:crypto";
39104
39155
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
39105
39156
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
39106
39157
  var RelayLivenessState = class {
@@ -39189,7 +39240,7 @@ var RelayConnectionLiveness = class {
39189
39240
  }
39190
39241
  throw new Error("Heartbeat was scheduled in an invalid state");
39191
39242
  }
39192
- const heartbeatId = randomUUID5();
39243
+ const heartbeatId = randomUUID6();
39193
39244
  this.#state = new AwaitingHeartbeatAckState(
39194
39245
  heartbeatId,
39195
39246
  this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
@@ -39205,765 +39256,54 @@ var RelayConnectionLiveness = class {
39205
39256
  };
39206
39257
  };
39207
39258
 
39208
- // src/relay-connection/session-event-outbox.ts
39209
- import { createHash as createHash5 } from "node:crypto";
39210
- import { DatabaseSync } from "node:sqlite";
39211
- var DEFAULT_OUTBOX_LIMITS = {
39212
- criticalEventBytes: 40 * 1024 * 1024,
39213
- runtimeDeliveryBytes: 32 * 1024 * 1024,
39214
- runtimeDeliveryCount: 64,
39215
- standardEventBytes: 32 * 1024 * 1024
39216
- };
39217
- var MAX_TERMINAL_RECEIPTS = 1024;
39218
- var SessionEventOutboxCapacityError = class extends Error {
39219
- code = "session_event_outbox_full";
39220
- constructor() {
39221
- super("The in-memory Session event outbox is full");
39222
- this.name = "SessionEventOutboxCapacityError";
39223
- }
39224
- };
39225
- var RuntimeDeliveryInboxCapacityError = class extends Error {
39226
- code = "runtime_delivery_inbox_full";
39227
- constructor() {
39228
- super("The in-memory Runtime delivery inbox is full");
39229
- this.name = "RuntimeDeliveryInboxCapacityError";
39230
- }
39231
- };
39232
- var StoredRuntimeDelivery = class {
39233
- deliveryId;
39234
- duplicate;
39235
- payload;
39236
- sessionId;
39237
- state;
39238
- constructor(deliveryId, sessionId, payload, state, duplicate) {
39239
- this.deliveryId = deliveryId;
39240
- this.duplicate = duplicate;
39241
- this.payload = payload;
39242
- this.sessionId = sessionId;
39243
- this.state = state;
39244
- }
39245
- };
39246
- function readPendingEnvelope(row) {
39247
- if (typeof row !== "object" || row === null || Array.isArray(row)) {
39248
- throw new Error("SQLite returned an invalid session event outbox row");
39249
- }
39250
- const envelope2 = Reflect.get(row, "envelope_json");
39251
- if (typeof envelope2 !== "string") {
39252
- throw new Error("SQLite returned an invalid session event envelope");
39253
- }
39254
- return envelope2;
39255
- }
39256
- function rowNumber(row, field) {
39257
- const value = typeof row === "object" && row !== null ? Reflect.get(row, field) : void 0;
39258
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
39259
- throw new Error(`SQLite returned an invalid ${field} value`);
39260
- }
39261
- return value;
39262
- }
39263
- function rowString(row, field) {
39264
- const value = typeof row === "object" && row !== null ? Reflect.get(row, field) : void 0;
39265
- if (typeof value !== "string" || value.length === 0) {
39266
- throw new Error(`SQLite returned an invalid ${field} value`);
39267
- }
39268
- return value;
39269
- }
39270
- var SessionEventOutbox = class {
39271
- #database;
39272
- #limits;
39273
- constructor(limits = DEFAULT_OUTBOX_LIMITS) {
39274
- validateLimits(limits);
39275
- this.#limits = limits;
39276
- this.#database = new DatabaseSync(":memory:");
39277
- this.#database.exec(`
39278
- CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
39279
- ordinal INTEGER PRIMARY KEY AUTOINCREMENT,
39280
- event_id TEXT NOT NULL UNIQUE,
39281
- session_id TEXT NOT NULL,
39282
- source_key TEXT NOT NULL,
39283
- byte_length INTEGER NOT NULL,
39284
- envelope_json TEXT NOT NULL
39285
- ) STRICT;
39286
- CREATE INDEX IF NOT EXISTS relay_session_event_outbox_order
39287
- ON relay_session_event_outbox(ordinal);
39288
- CREATE TABLE IF NOT EXISTS relay_turn_receipts (
39289
- command_id TEXT PRIMARY KEY,
39290
- session_id TEXT NOT NULL,
39291
- command_hash TEXT NOT NULL,
39292
- attempt_id TEXT NOT NULL,
39293
- state TEXT NOT NULL CHECK (
39294
- state IN ('dispatching', 'running', 'succeeded', 'failed', 'cancelled')
39295
- )
39296
- ) STRICT;
39297
- CREATE TABLE IF NOT EXISTS relay_session_event_outbox_state (
39298
- singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
39299
- event_count INTEGER NOT NULL,
39300
- total_bytes INTEGER NOT NULL,
39301
- next_source_seq INTEGER NOT NULL
39302
- ) STRICT;
39303
- INSERT OR IGNORE INTO relay_session_event_outbox_state (
39304
- singleton, event_count, total_bytes, next_source_seq
39305
- ) VALUES (1, 0, 0, 1);
39306
- CREATE TABLE IF NOT EXISTS relay_runtime_deliveries (
39307
- delivery_id TEXT PRIMARY KEY,
39308
- session_id TEXT NOT NULL,
39309
- payload_json TEXT NOT NULL,
39310
- payload_bytes INTEGER NOT NULL,
39311
- state TEXT NOT NULL CHECK (
39312
- state IN ('received', 'relay_committed', 'processed')
39313
- ),
39314
- received_at INTEGER NOT NULL
39315
- ) STRICT;
39316
- `);
39317
- this.#database.exec(`
39318
- CREATE INDEX IF NOT EXISTS relay_session_event_outbox_source_order
39319
- ON relay_session_event_outbox(source_key, ordinal);
39320
- `);
39321
- }
39322
- claimExecution = (commandId, sessionId, commandJson) => {
39323
- const commandHash = createHash5("sha256").update(commandJson).digest("hex");
39324
- this.#database.exec("BEGIN IMMEDIATE");
39325
- try {
39326
- const existing = this.#database.prepare(
39327
- `SELECT session_id, command_hash, attempt_id, state
39328
- FROM relay_turn_receipts WHERE command_id = ?`
39329
- ).get(commandId);
39330
- if (typeof existing === "object" && existing !== null) {
39331
- const storedSessionId = Reflect.get(existing, "session_id");
39332
- const storedCommandHash = Reflect.get(existing, "command_hash");
39333
- const attemptId2 = Reflect.get(existing, "attempt_id");
39334
- const state = Reflect.get(existing, "state");
39335
- if (storedSessionId !== sessionId || storedCommandHash !== commandHash || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
39336
- throw new Error("The daemon command identity conflicts with its in-memory receipt");
39337
- }
39338
- this.#database.exec("COMMIT");
39339
- return { attemptId: attemptId2, commandId, kind: "duplicate", state };
39340
- }
39341
- const attemptId = crypto.randomUUID();
39342
- this.#database.prepare(
39343
- `INSERT INTO relay_turn_receipts (
39344
- command_id, session_id, command_hash, attempt_id, state
39345
- ) VALUES (?, ?, ?, ?, 'dispatching')`
39346
- ).run(commandId, sessionId, commandHash, attemptId);
39347
- this.#database.exec("COMMIT");
39348
- return {
39349
- attemptId,
39350
- commandId,
39351
- kind: "accepted",
39352
- state: "dispatching"
39353
- };
39354
- } catch (error62) {
39355
- this.#database.exec("ROLLBACK");
39356
- throw error62;
39357
- }
39358
- };
39359
- transitionExecution = (commandId, state) => {
39360
- const row = this.#database.prepare(`SELECT state FROM relay_turn_receipts WHERE command_id = ?`).get(commandId);
39361
- const current = typeof row === "object" && row !== null ? Reflect.get(row, "state") : void 0;
39362
- if (!isDaemonExecutionState(current)) {
39363
- throw new Error("The daemon execution receipt does not exist");
39364
- }
39365
- if (current === state) {
39366
- return;
39367
- }
39368
- const allowed = current === "dispatching" && (state === "running" || state === "failed" || state === "cancelled") || current === "running" && (state === "succeeded" || state === "failed" || state === "cancelled");
39369
- if (!allowed) {
39370
- throw new Error("The daemon execution transition is invalid");
39371
- }
39372
- this.#database.prepare(`UPDATE relay_turn_receipts SET state = ? WHERE command_id = ?`).run(state, commandId);
39373
- if (state === "succeeded" || state === "failed" || state === "cancelled") {
39374
- this.#database.prepare(
39375
- `DELETE FROM relay_turn_receipts
39376
- WHERE state IN ('succeeded', 'failed', 'cancelled')
39377
- AND rowid NOT IN (
39378
- SELECT rowid FROM relay_turn_receipts
39379
- WHERE state IN ('succeeded', 'failed', 'cancelled')
39380
- ORDER BY rowid DESC LIMIT ?
39381
- )`
39382
- ).run(MAX_TERMINAL_RECEIPTS);
39383
- }
39384
- };
39385
- /**
39386
- * The Attempt this live Runtime claimed for a command that has not reached a terminal state.
39387
- * Receipts disappear when the daemon process exits.
39388
- */
39389
- findUnsettledAttemptId = (commandId, sessionId) => {
39390
- const row = this.#database.prepare(`SELECT attempt_id, state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
39391
- if (typeof row !== "object" || row === null) {
39392
- return null;
39393
- }
39394
- const attemptId = Reflect.get(row, "attempt_id");
39395
- const state = Reflect.get(row, "state");
39396
- if (typeof attemptId !== "string" || attemptId.length === 0 || !isDaemonExecutionState(state)) {
39397
- return null;
39398
- }
39399
- return state === "dispatching" || state === "running" ? attemptId : null;
39400
- };
39401
- isTerminalExecution = (commandId, sessionId) => {
39402
- const row = this.#database.prepare(`SELECT state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
39403
- const state = typeof row === "object" && row !== null ? Reflect.get(row, "state") : void 0;
39404
- return state === "succeeded" || state === "failed" || state === "cancelled";
39405
- };
39406
- acknowledge = (acknowledgement) => this.#removeAcknowledgedEvent(acknowledgement.eventId, acknowledgement.sessionId);
39407
- quarantine = (rejection) => {
39408
- this.#database.exec("BEGIN IMMEDIATE");
39409
- try {
39410
- const stored = this.#database.prepare(
39411
- `SELECT byte_length FROM relay_session_event_outbox
39412
- WHERE event_id = ? AND session_id = ?`
39413
- ).get(rejection.eventId, rejection.sessionId);
39414
- if (stored === void 0) {
39415
- this.#database.exec("COMMIT");
39416
- return false;
39417
- }
39418
- const byteLength = rowNumber(stored, "byte_length");
39419
- const deletion = this.#database.prepare(
39420
- `DELETE FROM relay_session_event_outbox
39421
- WHERE event_id = ? AND session_id = ?`
39422
- ).run(rejection.eventId, rejection.sessionId);
39423
- if (deletion.changes !== 1) {
39424
- throw new Error("The rejected session event could not be removed from the in-memory outbox");
39425
- }
39426
- this.#decrementEventState(byteLength);
39427
- this.#database.exec("COMMIT");
39428
- return true;
39429
- } catch (error62) {
39430
- this.#database.exec("ROLLBACK");
39431
- throw error62;
39432
- }
39433
- };
39434
- close = () => {
39435
- this.#database.close();
39436
- };
39437
- enqueue = (sessionId, payload, attemptId = null) => {
39438
- return this.#enqueueBounded(sessionId, payload, attemptId ?? "", this.#limits.standardEventBytes);
39439
- };
39440
- enqueueCritical = (sessionId, payload, attemptId = "") => this.#enqueueBounded(sessionId, payload, attemptId, this.#limits.criticalEventBytes);
39441
- /**
39442
- * Bytes still available to standard Session events. The daemon uses this to shed
39443
- * superseded streaming events instead of filling the in-memory outbox, so a long Turn
39444
- * behind a slow Relay cannot make the next enqueue throw.
39445
- */
39446
- standardCapacityRemaining = () => {
39447
- const state = this.#database.prepare(
39448
- `SELECT total_bytes
39449
- FROM relay_session_event_outbox_state
39450
- WHERE singleton = 1`
39451
- ).get();
39452
- return this.#limits.standardEventBytes - rowNumber(state, "total_bytes");
39453
- };
39454
- claimRuntimeDelivery = (delivery) => {
39455
- const payloadBytes = new TextEncoder().encode(delivery.payload).byteLength;
39456
- this.#database.exec("BEGIN IMMEDIATE");
39457
- try {
39458
- const existing = this.#database.prepare(
39459
- `SELECT session_id, payload_json, state
39460
- FROM relay_runtime_deliveries
39461
- WHERE delivery_id = ?`
39462
- ).get(delivery.deliveryId);
39463
- if (existing !== void 0) {
39464
- const sessionId = rowString(existing, "session_id");
39465
- const payload = rowString(existing, "payload_json");
39466
- const state = runtimeDeliveryState(existing);
39467
- if (sessionId !== delivery.sessionId || payload !== delivery.payload) {
39468
- throw new Error("The Runtime delivery identity conflicts with its in-memory receipt");
39469
- }
39470
- this.#database.exec("COMMIT");
39471
- return new StoredRuntimeDelivery(delivery.deliveryId, sessionId, payload, state, true);
39472
- }
39473
- const usage = this.#database.prepare(
39474
- `SELECT COUNT(*) AS delivery_count,
39475
- COALESCE(SUM(payload_bytes), 0) AS delivery_bytes
39476
- FROM relay_runtime_deliveries`
39477
- ).get();
39478
- if (rowNumber(usage, "delivery_count") + 1 > this.#limits.runtimeDeliveryCount || rowNumber(usage, "delivery_bytes") + payloadBytes > this.#limits.runtimeDeliveryBytes) {
39479
- throw new RuntimeDeliveryInboxCapacityError();
39480
- }
39481
- this.#database.prepare(
39482
- `INSERT INTO relay_runtime_deliveries (
39483
- delivery_id, session_id, payload_json, payload_bytes, state, received_at
39484
- ) VALUES (?, ?, ?, ?, 'received', ?)`
39485
- ).run(delivery.deliveryId, delivery.sessionId, delivery.payload, payloadBytes, Date.now());
39486
- this.#database.exec("COMMIT");
39487
- return new StoredRuntimeDelivery(
39488
- delivery.deliveryId,
39489
- delivery.sessionId,
39490
- delivery.payload,
39491
- "received",
39492
- false
39493
- );
39494
- } catch (error62) {
39495
- this.#database.exec("ROLLBACK");
39496
- throw error62;
39497
- }
39498
- };
39499
- markRuntimeDeliveryCommitted = (deliveryId, sessionId) => {
39500
- this.#database.exec("BEGIN IMMEDIATE");
39501
- try {
39502
- const row = this.#database.prepare(
39503
- `SELECT state FROM relay_runtime_deliveries
39504
- WHERE delivery_id = ? AND session_id = ?`
39505
- ).get(deliveryId, sessionId);
39506
- if (row === void 0) {
39507
- this.#database.exec("COMMIT");
39508
- return false;
39509
- }
39510
- const state = runtimeDeliveryState(row);
39511
- if (state === "processed") {
39512
- this.#database.prepare(`DELETE FROM relay_runtime_deliveries WHERE delivery_id = ?`).run(deliveryId);
39513
- } else if (state === "received") {
39514
- this.#database.prepare(`UPDATE relay_runtime_deliveries SET state = 'relay_committed' WHERE delivery_id = ?`).run(deliveryId);
39515
- }
39516
- this.#database.exec("COMMIT");
39517
- return true;
39518
- } catch (error62) {
39519
- this.#database.exec("ROLLBACK");
39520
- throw error62;
39521
- }
39522
- };
39523
- markRuntimeDeliveryProcessed = (deliveryId, sessionId) => {
39524
- this.#database.exec("BEGIN IMMEDIATE");
39525
- try {
39526
- const row = this.#database.prepare(
39527
- `SELECT state FROM relay_runtime_deliveries
39528
- WHERE delivery_id = ? AND session_id = ?`
39529
- ).get(deliveryId, sessionId);
39530
- if (row === void 0) {
39531
- this.#database.exec("COMMIT");
39532
- return false;
39533
- }
39534
- const state = runtimeDeliveryState(row);
39535
- if (state === "relay_committed") {
39536
- this.#database.prepare(`DELETE FROM relay_runtime_deliveries WHERE delivery_id = ?`).run(deliveryId);
39537
- } else if (state === "received") {
39538
- this.#database.prepare(`UPDATE relay_runtime_deliveries SET state = 'processed' WHERE delivery_id = ?`).run(deliveryId);
39539
- }
39540
- this.#database.exec("COMMIT");
39541
- return true;
39542
- } catch (error62) {
39543
- this.#database.exec("ROLLBACK");
39544
- throw error62;
39545
- }
39546
- };
39547
- runtimeDeliveries = () => this.#database.prepare(
39548
- `SELECT delivery_id, session_id, payload_json, state
39549
- FROM relay_runtime_deliveries
39550
- ORDER BY received_at, delivery_id`
39551
- ).all().map(
39552
- (row) => new StoredRuntimeDelivery(
39553
- rowString(row, "delivery_id"),
39554
- rowString(row, "session_id"),
39555
- rowString(row, "payload_json"),
39556
- runtimeDeliveryState(row),
39557
- true
39558
- )
39559
- );
39560
- #enqueueBounded = (sessionId, payload, attemptId, maximumEventBytes) => {
39561
- const sourceKey = attemptId.length === 0 ? `runtime:${sessionId}` : `attempt:${sessionId}:${attemptId}`;
39562
- this.#database.exec("BEGIN IMMEDIATE");
39563
- try {
39564
- const state = this.#database.prepare(
39565
- `SELECT total_bytes, next_source_seq
39566
- FROM relay_session_event_outbox_state
39567
- WHERE singleton = 1`
39568
- ).get();
39569
- const nextSourceSeq = rowNumber(state, "next_source_seq");
39570
- if (nextSourceSeq < 1 || !Number.isSafeInteger(nextSourceSeq + 1)) {
39571
- throw new Error("SQLite returned an invalid event source sequence");
39572
- }
39573
- const envelope2 = {
39574
- eventId: crypto.randomUUID(),
39575
- kind: SESSION_EVENT_KIND,
39576
- payload,
39577
- sessionId,
39578
- source: attemptId.length === 0 ? { kind: "runtime", sourceSeq: nextSourceSeq.toString() } : {
39579
- attemptId,
39580
- kind: "attempt",
39581
- sourceSeq: nextSourceSeq.toString()
39582
- }
39583
- };
39584
- const encoded = encodeSessionEventEnvelope(envelope2);
39585
- const byteLength = new TextEncoder().encode(encoded).byteLength;
39586
- if (rowNumber(state, "total_bytes") + byteLength > maximumEventBytes) {
39587
- throw new SessionEventOutboxCapacityError();
39588
- }
39589
- this.#database.prepare(
39590
- `INSERT INTO relay_session_event_outbox (
39591
- event_id, session_id, source_key, byte_length, envelope_json
39592
- ) VALUES (?, ?, ?, ?, ?)`
39593
- ).run(envelope2.eventId, envelope2.sessionId, sourceKey, byteLength, encoded);
39594
- this.#database.prepare(
39595
- `UPDATE relay_session_event_outbox_state
39596
- SET event_count = event_count + 1,
39597
- total_bytes = total_bytes + ?,
39598
- next_source_seq = next_source_seq + 1
39599
- WHERE singleton = 1`
39600
- ).run(byteLength);
39601
- this.#database.exec("COMMIT");
39602
- return encoded;
39603
- } catch (error62) {
39604
- this.#database.exec("ROLLBACK");
39605
- throw error62;
39606
- }
39607
- };
39608
- #removeAcknowledgedEvent = (eventId, sessionId) => {
39609
- this.#database.exec("BEGIN IMMEDIATE");
39610
- try {
39611
- const stored = this.#database.prepare(
39612
- `SELECT byte_length FROM relay_session_event_outbox
39613
- WHERE event_id = ? AND session_id = ?`
39614
- ).get(eventId, sessionId);
39615
- if (stored === void 0) {
39616
- this.#database.exec("COMMIT");
39617
- return false;
39618
- }
39619
- const byteLength = rowNumber(stored, "byte_length");
39620
- const deletion = this.#database.prepare(
39621
- `DELETE FROM relay_session_event_outbox
39622
- WHERE event_id = ? AND session_id = ?`
39623
- ).run(eventId, sessionId);
39624
- if (deletion.changes !== 1) {
39625
- throw new Error("The acknowledged session event could not be removed from the in-memory outbox");
39626
- }
39627
- this.#decrementEventState(byteLength);
39628
- this.#database.exec("COMMIT");
39629
- return true;
39630
- } catch (error62) {
39631
- this.#database.exec("ROLLBACK");
39632
- throw error62;
39633
- }
39634
- };
39635
- #decrementEventState = (byteLength) => {
39636
- const result = this.#database.prepare(
39637
- `UPDATE relay_session_event_outbox_state
39638
- SET event_count = event_count - 1,
39639
- total_bytes = total_bytes - ?
39640
- WHERE singleton = 1 AND event_count > 0 AND total_bytes >= ?`
39641
- ).run(byteLength, byteLength);
39642
- if (result.changes !== 1) {
39643
- throw new Error("The Session event outbox capacity state is inconsistent");
39644
- }
39645
- };
39646
- pending = () => this.#database.prepare(
39647
- `SELECT envelope_json
39648
- FROM relay_session_event_outbox
39649
- ORDER BY ordinal`
39650
- ).all().map(readPendingEnvelope);
39651
- pendingBatch = (limit) => {
39652
- if (!Number.isSafeInteger(limit) || limit < 1) {
39653
- throw new Error("Session event replay batch limit must be a positive integer");
39654
- }
39655
- return this.#database.prepare(
39656
- `WITH ranked_events AS (
39657
- SELECT ordinal,
39658
- ROW_NUMBER() OVER (
39659
- PARTITION BY source_key
39660
- ORDER BY ordinal
39661
- ) AS source_position
39662
- FROM relay_session_event_outbox
39663
- )
39664
- SELECT outbox.envelope_json
39665
- FROM ranked_events AS ranked
39666
- INNER JOIN relay_session_event_outbox AS outbox
39667
- ON outbox.ordinal = ranked.ordinal
39668
- ORDER BY ranked.source_position, outbox.ordinal
39669
- LIMIT ?`
39670
- ).all(limit).map(readPendingEnvelope);
39671
- };
39672
- pendingSourceHeads = (limit, excludedEventIds, excludedSourceKeys) => {
39673
- if (!Number.isSafeInteger(limit) || limit < 1) {
39674
- throw new Error("Session event replay batch limit must be a positive integer");
39675
- }
39676
- const exclusions = [];
39677
- const parameters = [];
39678
- if (excludedEventIds.length > 0) {
39679
- exclusions.push(`event_id NOT IN (${excludedEventIds.map(() => "?").join(", ")})`);
39680
- parameters.push(...excludedEventIds);
39681
- }
39682
- if (excludedSourceKeys.length > 0) {
39683
- exclusions.push(`source_key NOT IN (${excludedSourceKeys.map(() => "?").join(", ")})`);
39684
- parameters.push(...excludedSourceKeys);
39685
- }
39686
- parameters.push(limit.toString());
39687
- const where = exclusions.length === 0 ? "" : `WHERE ${exclusions.join(" AND ")}`;
39688
- return this.#database.prepare(
39689
- `WITH available_events AS (
39690
- SELECT ordinal, source_key
39691
- FROM relay_session_event_outbox
39692
- ${where}
39693
- ), ranked_events AS (
39694
- SELECT ordinal,
39695
- ROW_NUMBER() OVER (
39696
- PARTITION BY source_key
39697
- ORDER BY ordinal
39698
- ) AS source_position
39699
- FROM available_events
39700
- )
39701
- SELECT outbox.envelope_json
39702
- FROM ranked_events AS ranked
39703
- INNER JOIN relay_session_event_outbox AS outbox
39704
- ON outbox.ordinal = ranked.ordinal
39705
- WHERE ranked.source_position = 1
39706
- ORDER BY outbox.ordinal
39707
- LIMIT ?`
39708
- ).all(...parameters).map(readPendingEnvelope);
39709
- };
39710
- };
39711
- function validateLimits(limits) {
39712
- const values = [
39713
- limits.criticalEventBytes,
39714
- limits.runtimeDeliveryBytes,
39715
- limits.runtimeDeliveryCount,
39716
- limits.standardEventBytes
39717
- ];
39718
- if (values.some((value) => !Number.isSafeInteger(value) || value < 1)) {
39719
- throw new Error("Session event outbox limits must be positive integers");
39720
- }
39721
- if (limits.criticalEventBytes < limits.standardEventBytes) {
39722
- throw new Error("Critical Session event capacity must include the standard capacity");
39723
- }
39724
- }
39725
- function runtimeDeliveryState(row) {
39726
- const state = rowString(row, "state");
39727
- if (state !== "received" && state !== "relay_committed" && state !== "processed") {
39728
- throw new Error("SQLite returned an invalid Runtime delivery state");
39729
- }
39730
- return state;
39731
- }
39732
- function isDaemonExecutionState(value) {
39733
- return value === "cancelled" || value === "dispatching" || value === "failed" || value === "running" || value === "succeeded";
39734
- }
39735
-
39736
39259
  // src/relay-connection/session-event-publisher.ts
39737
39260
  import { WebSocket as WebSocket4 } from "undici";
39738
- var DaemonSessionEventConnectionState = class {
39739
- };
39740
- var DisconnectedDaemonSessionEventState = class extends DaemonSessionEventConnectionState {
39741
- disconnect = () => this;
39742
- matches = () => false;
39743
- send = () => false;
39744
- };
39745
- var ConnectedDaemonSessionEventState = class extends DaemonSessionEventConnectionState {
39746
- #socket;
39747
- constructor(socket) {
39748
- super();
39749
- this.#socket = socket;
39750
- }
39751
- disconnect = (socket) => socket === this.#socket ? new DisconnectedDaemonSessionEventState() : this;
39752
- matches = (socket) => socket === this.#socket;
39753
- send = (message) => {
39754
- if (this.#socket.readyState !== WebSocket4.OPEN) {
39755
- return false;
39756
- }
39757
- try {
39758
- this.#socket.send(encodeDaemonToServiceMessage(message));
39759
- return true;
39760
- } catch {
39761
- return false;
39762
- }
39763
- };
39764
- };
39765
- var SESSION_EVENT_REPLAY_WINDOW = 16;
39766
- var SESSION_EVENT_SOURCE_REPLAY_WINDOW = 4;
39767
- var SESSION_EVENT_REPLAY_BYTE_LIMIT = 32 * 1024 * 1024;
39768
- function reservesSessionEventCapacity(event) {
39769
- if (event.kind === SESSION_COMPLETED_KIND || event.kind === SESSION_FAILED_KIND) {
39770
- return true;
39771
- }
39772
- return event.kind === AGENT_ACTIVITY_KIND && (event.activityType === "progress" || event.activityType === "reasoning") && (event.status === "completed" || event.status === "failed");
39773
- }
39774
- var InFlightSessionEvent = class {
39775
- byteLength;
39776
- sourceKey;
39777
- constructor(sourceKey, byteLength) {
39778
- this.byteLength = byteLength;
39779
- this.sourceKey = sourceKey;
39780
- }
39781
- };
39782
- function sessionEventSourceKey(envelope2) {
39783
- return envelope2.source.kind === "attempt" ? `attempt:${envelope2.sessionId}:${envelope2.source.attemptId}` : `runtime:${envelope2.sessionId}`;
39784
- }
39261
+ var MAX_LIVE_EVENT_BUFFERED_BYTES = 16 * 1024 * 1024;
39785
39262
  var DaemonSessionEventPublisher = class {
39786
- #outbox;
39787
- #inFlightEvents = /* @__PURE__ */ new Map();
39788
- #pausedSources = /* @__PURE__ */ new Map();
39789
- #shedEventKinds = /* @__PURE__ */ new Set();
39790
- #timer;
39791
- #inFlightBytes = 0;
39792
- #connection = new DisconnectedDaemonSessionEventState();
39793
- constructor(outbox, timer) {
39794
- this.#outbox = outbox;
39795
- this.#timer = timer;
39796
- }
39263
+ #socket = null;
39264
+ #reportedDrop = false;
39797
39265
  connect = (socket) => {
39798
- this.#connection = new ConnectedDaemonSessionEventState(socket);
39799
- this.#clearInFlight();
39800
- this.#publishNextBatch();
39266
+ this.#socket = socket;
39267
+ this.#reportedDrop = false;
39801
39268
  };
39802
39269
  disconnect = (socket) => {
39803
- if (!this.#connection.matches(socket)) {
39804
- return;
39805
- }
39806
- this.#connection = this.#connection.disconnect(socket);
39807
- this.#clearInFlight();
39808
- };
39809
- recordAttempt = (sessionId, event, attemptId) => {
39810
- const encoded = encodeRecordedSessionEvent(event);
39811
- if (reservesSessionEventCapacity(event)) {
39812
- this.#enqueueReserved(sessionId, encoded, attemptId, event.kind);
39813
- } else {
39814
- this.#enqueueStandard(sessionId, encoded, attemptId, event.kind);
39815
- }
39816
- this.#publishNextBatch();
39817
- };
39818
- recordRuntime = (sessionId, event) => {
39819
- this.#enqueueStandard(sessionId, encodeRecordedSessionEvent(event), "", event.kind);
39820
- this.#publishNextBatch();
39821
- };
39822
- /**
39823
- * Enqueue a standard event, shedding it instead of ending the daemon when the
39824
- * in-memory outbox is full.
39825
- *
39826
- * A capacity error used to escape the coalescing timer that publishes activities,
39827
- * so the process exited and every restart died on the same retained backlog. A full
39828
- * outbox is a recoverable runtime condition, not a fatal one: narration increments are
39829
- * superseded by the completed snapshot, so they are shed first, and any other streaming
39830
- * event is shed only at the wall rather than terminating the daemon.
39831
- */
39832
- #enqueueStandard = (sessionId, encoded, attemptId, kind) => {
39833
- if (kind === AGENT_ACTIVITY_NARRATION_KIND && this.#outbox.standardCapacityRemaining() <= 0) {
39834
- this.#reportShedEvent(kind);
39835
- return;
39836
- }
39837
- try {
39838
- this.#outbox.enqueue(sessionId, encoded, attemptId);
39839
- } catch (error62) {
39840
- if (!(error62 instanceof SessionEventOutboxCapacityError)) {
39841
- throw error62;
39842
- }
39843
- this.#reportShedEvent(kind);
39844
- }
39845
- };
39846
- /**
39847
- * Enqueue on the reserved budget, degrading to a reported drop instead of raising.
39848
- * Streaming events are shed before this budget is reached, so a Turn's terminal
39849
- * events and the completed snapshot that carries its narration still land; a drop
39850
- * here is the last resort for a backlog no acknowledgement can drain.
39851
- */
39852
- #enqueueReserved = (sessionId, encoded, attemptId, kind) => {
39853
- try {
39854
- this.#outbox.enqueueCritical(sessionId, encoded, attemptId);
39855
- } catch (error62) {
39856
- if (!(error62 instanceof SessionEventOutboxCapacityError)) {
39857
- throw error62;
39858
- }
39859
- this.#reportShedEvent(kind);
39860
- }
39861
- };
39862
- #reportShedEvent = (kind) => {
39863
- if (this.#shedEventKinds.has(kind)) {
39864
- return;
39270
+ if (this.#socket === socket) {
39271
+ this.#socket = null;
39865
39272
  }
39866
- this.#shedEventKinds.add(kind);
39867
- console.warn(`Mobius daemon is dropping queued "${kind}" events because the Session event outbox is full`);
39868
39273
  };
39869
- acknowledge = (acknowledgement) => {
39870
- 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();
39871
39278
  return;
39872
39279
  }
39873
- this.#removeInFlight(acknowledgement.eventId);
39874
- this.#publishNextBatch();
39875
- };
39876
- quarantine = (rejection) => {
39877
- const quarantined = this.#outbox.quarantine(rejection);
39878
- if (!quarantined) {
39879
- return false;
39880
- }
39881
- this.#removeInFlight(rejection.eventId);
39882
- this.#publishNextBatch();
39883
- return true;
39884
- };
39885
- defer = (deferred) => {
39886
- const inFlight = this.#inFlightEvents.get(deferred.eventId);
39887
- 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();
39888
39284
  return;
39889
39285
  }
39890
- this.#clearInFlightSource(inFlight.sourceKey);
39891
- if (!this.#pausedSources.has(inFlight.sourceKey)) {
39892
- this.#pausedSources.set(
39893
- inFlight.sourceKey,
39894
- this.#timer.schedule(() => {
39895
- this.#pausedSources.delete(inFlight.sourceKey);
39896
- this.#publishNextBatch();
39897
- }, deferred.retryAfterMilliseconds)
39286
+ try {
39287
+ socket.send(
39288
+ encodeDaemonToServiceMessage({
39289
+ kind: SESSION_EVENT_KIND,
39290
+ payload: encodeRecordedSessionEvent(event),
39291
+ sessionId
39292
+ })
39898
39293
  );
39294
+ } catch {
39295
+ this.#reportDrop();
39899
39296
  }
39900
- this.#publishNextBatch();
39901
39297
  };
39902
39298
  close = () => {
39903
- for (const task of this.#pausedSources.values()) {
39904
- task.cancel();
39905
- }
39906
- this.#pausedSources.clear();
39907
- this.#clearInFlight();
39299
+ this.#socket = null;
39908
39300
  };
39909
- #publishNextBatch = () => {
39910
- while (this.#inFlightEvents.size < SESSION_EVENT_REPLAY_WINDOW) {
39911
- const sourceCounts = /* @__PURE__ */ new Map();
39912
- for (const inFlight of this.#inFlightEvents.values()) {
39913
- sourceCounts.set(inFlight.sourceKey, (sourceCounts.get(inFlight.sourceKey) ?? 0) + 1);
39914
- }
39915
- const saturatedSources = [...sourceCounts.entries()].filter(([, count]) => count >= SESSION_EVENT_SOURCE_REPLAY_WINDOW).map(([sourceKey]) => sourceKey);
39916
- const batch = this.#outbox.pendingSourceHeads(
39917
- SESSION_EVENT_REPLAY_WINDOW - this.#inFlightEvents.size,
39918
- [...this.#inFlightEvents.keys()],
39919
- [...this.#pausedSources.keys(), ...saturatedSources]
39920
- );
39921
- let sent = 0;
39922
- for (const encoded of batch) {
39923
- const envelope2 = decodeSessionEventEnvelope(encoded);
39924
- const sourceKey = sessionEventSourceKey(envelope2);
39925
- const sourceCount = sourceCounts.get(sourceKey) ?? 0;
39926
- if (sourceCount >= SESSION_EVENT_SOURCE_REPLAY_WINDOW) {
39927
- continue;
39928
- }
39929
- const byteLength = new TextEncoder().encode(encoded).byteLength;
39930
- if (this.#inFlightBytes + byteLength > SESSION_EVENT_REPLAY_BYTE_LIMIT) {
39931
- continue;
39932
- }
39933
- if (!this.#connection.send(envelope2)) {
39934
- this.#clearInFlight();
39935
- return;
39936
- }
39937
- this.#inFlightEvents.set(envelope2.eventId, new InFlightSessionEvent(sourceKey, byteLength));
39938
- this.#inFlightBytes += byteLength;
39939
- sourceCounts.set(sourceKey, sourceCount + 1);
39940
- sent += 1;
39941
- }
39942
- if (sent === 0) {
39943
- return;
39944
- }
39945
- }
39946
- };
39947
- #removeInFlight = (eventId) => {
39948
- const inFlight = this.#inFlightEvents.get(eventId);
39949
- if (inFlight === void 0) {
39301
+ #reportDrop = () => {
39302
+ if (this.#reportedDrop) {
39950
39303
  return;
39951
39304
  }
39952
- this.#inFlightEvents.delete(eventId);
39953
- this.#inFlightBytes -= inFlight.byteLength;
39954
- };
39955
- #clearInFlight = () => {
39956
- this.#inFlightEvents.clear();
39957
- this.#inFlightBytes = 0;
39958
- };
39959
- #clearInFlightSource = (sourceKey) => {
39960
- for (const [eventId, inFlight] of this.#inFlightEvents) {
39961
- if (inFlight.sourceKey !== sourceKey) {
39962
- continue;
39963
- }
39964
- this.#inFlightEvents.delete(eventId);
39965
- this.#inFlightBytes -= inFlight.byteLength;
39966
- }
39305
+ this.#reportedDrop = true;
39306
+ console.warn("Mobius daemon dropped live Session events while the Relay was unavailable");
39967
39307
  };
39968
39308
  };
39969
39309
 
@@ -40037,7 +39377,7 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
40037
39377
  {
40038
39378
  agentId: agent.id,
40039
39379
  kind: AGENT_INSTALL_REQUEST_KIND,
40040
- requestId: `automatic-integration-${randomUUID6()}`
39380
+ requestId: `automatic-integration-${randomUUID7()}`
40041
39381
  },
40042
39382
  signal
40043
39383
  );
@@ -40082,9 +39422,8 @@ async function refreshAgentCatalog(config2, resolveEnvironment, signal) {
40082
39422
  throw error62;
40083
39423
  }
40084
39424
  }
40085
- 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) {
40086
39426
  const relayUrl = new URL(config2.relayUrl);
40087
- relayUrl.searchParams.set("deliveryReceipts", "1");
40088
39427
  relayUrl.searchParams.set("liveness", "1");
40089
39428
  const socket = await connectRelay(relayUrl, signal);
40090
39429
  const reconnectingTurns = [...activeTurns.values()];
@@ -40135,215 +39474,48 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40135
39474
  closeRelaySocket(socket, code, reason);
40136
39475
  rejectConnection(failure2);
40137
39476
  };
40138
- const processingDeliveryIds = /* @__PURE__ */ new Set();
40139
- const processDeliveredPrompt = async (delivery, command, trackActiveAttempt, execute) => {
40140
- if (command.sessionId !== delivery.sessionId) {
40141
- throw new Error("Runtime delivery Session identity does not match its payload");
40142
- }
40143
- const active = activeTurns.get(command.commandId);
40144
- if (active !== void 0) {
40145
- await active.completion;
40146
- return;
40147
- }
40148
- const receipt = outbox.claimExecution(command.commandId, command.sessionId, delivery.payload);
40149
- if (receipt.kind === "duplicate") {
40150
- if (receipt.state === "running") {
40151
- reportFailure(
40152
- publisher,
40153
- command,
40154
- "agent_execution_interrupted",
40155
- "The local Agent execution was interrupted before it completed",
40156
- receipt.attemptId
40157
- );
40158
- outbox.transitionExecution(command.commandId, "failed");
40159
- return;
40160
- }
40161
- if (receipt.state !== "dispatching") {
40162
- return;
40163
- }
40164
- }
40165
- const turn = new ActiveDaemonTurn(command, receipt.attemptId);
40166
- activeTurns.set(command.commandId, turn);
40167
- const activateAttempt = () => {
40168
- turn.accept();
40169
- if (trackActiveAttempt) {
40170
- activeAttemptIds.set(command.sessionId, receipt.attemptId);
40171
- }
40172
- };
40173
- try {
40174
- await execute(receipt.attemptId, activateAttempt, turn.signal, turn);
40175
- } finally {
40176
- activeTurns.delete(command.commandId);
40177
- if (activeAttemptIds.get(command.sessionId) === receipt.attemptId) {
40178
- activeAttemptIds.delete(command.sessionId);
40179
- }
40180
- turn.finish();
40181
- }
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
+ });
40182
39500
  };
40183
- const processDeliveredPayload = async (delivery) => {
40184
- const message = decodeServiceToDaemonMessage(delivery.payload);
40185
- const kind = message.kind;
40186
- if (kind === SESSION_CANCEL_KIND) {
40187
- const cancellation = message;
40188
- if (cancellation.sessionId !== delivery.sessionId) {
40189
- throw new Error("Runtime delivery Session identity does not match its payload");
40190
- }
40191
- const turn = activeTurns.get(cancellation.commandId);
40192
- if (turn === void 0 || !turn.matches(cancellation)) {
40193
- settleAbandonedTurn(publisher, outbox, audit, cancellation);
40194
- return;
40195
- }
40196
- if (!turn.requestCancellation()) {
40197
- return;
40198
- }
40199
- audit.record({
40200
- commandId: cancellation.commandId,
40201
- event: "session_cancellation_requested",
40202
- sessionId: cancellation.sessionId
40203
- });
40204
- await sessions.cancelPrompt(cancellation.sessionId);
40205
- return;
39501
+ const waitForSessionAvailability = async (command, waitSignal) => {
39502
+ if (command.disposition === SessionPromptDisposition.Steer) {
39503
+ return "available";
40206
39504
  }
40207
- if (kind === SESSION_CONFIGURE_KIND) {
40208
- const command = message;
40209
- if (command.sessionId !== delivery.sessionId) {
40210
- throw new Error("Runtime delivery Session identity does not match its payload");
40211
- }
40212
- await executeSessionConfigure(
40213
- publisher,
40214
- socket,
40215
- command,
40216
- config2,
40217
- directories,
40218
- audit,
40219
- sessions,
40220
- connectionController.signal
39505
+ for (; ; ) {
39506
+ const first = [...activeTurns.values()].find(
39507
+ (turn) => turn.command.sessionId === command.sessionId && turn.command.disposition !== SessionPromptDisposition.Steer
40221
39508
  );
40222
- return;
40223
- }
40224
- if (kind === SESSION_PERMISSION_RESPOND_KIND) {
40225
- const command = message;
40226
- if (command.sessionId !== delivery.sessionId) {
40227
- throw new Error("Runtime delivery Session identity does not match its payload");
40228
- }
40229
- try {
40230
- await sessions.respondPermission(command);
40231
- audit.record({
40232
- commandId: command.interactionId,
40233
- event: "session_permission_resolved",
40234
- sessionId: command.sessionId
40235
- });
40236
- } catch (error62) {
40237
- reportOperationFailure(socket, command.interactionId, command.sessionId, error62);
40238
- }
40239
- return;
40240
- }
40241
- if (kind === SESSION_ELICITATION_RESPOND_KIND) {
40242
- const command = message;
40243
- if (command.sessionId !== delivery.sessionId) {
40244
- 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";
40245
39511
  }
40246
- try {
40247
- await sessions.respondElicitation(command);
40248
- audit.record({
40249
- commandId: command.interactionId,
40250
- event: "session_elicitation_resolved",
40251
- sessionId: command.sessionId
40252
- });
40253
- } catch (error62) {
40254
- reportOperationFailure(socket, command.interactionId, command.sessionId, error62);
39512
+ if (command.disposition !== SessionPromptDisposition.Queue) {
39513
+ return "busy";
40255
39514
  }
40256
- return;
40257
- }
40258
- if (kind === SESSION_PROMPT_KIND) {
40259
- const command = message;
40260
- await processDeliveredPrompt(
40261
- delivery,
40262
- command,
40263
- command.disposition !== SessionPromptDisposition.Steer,
40264
- (attemptId, activateAttempt, executionSignal, turn) => executePrompt(
40265
- outbox,
40266
- publisher,
40267
- command,
40268
- config2,
40269
- directories,
40270
- audit,
40271
- sessions,
40272
- attemptId,
40273
- activateAttempt,
40274
- timer,
40275
- executionSignal,
40276
- turn.recordText
40277
- )
40278
- );
40279
- return;
40280
- }
40281
- throw new Error("Runtime delivery contains an unsupported protocol message");
40282
- };
40283
- const processRuntimeDelivery = (delivery, state) => {
40284
- if (state === "processed" || processingDeliveryIds.has(delivery.deliveryId)) {
40285
- return;
40286
- }
40287
- processingDeliveryIds.add(delivery.deliveryId);
40288
- void processDeliveredPayload(delivery).then(() => {
40289
- outbox.markRuntimeDeliveryProcessed(delivery.deliveryId, delivery.sessionId);
40290
- }).catch((error62) => {
40291
- if (connectionController.signal.aborted) {
40292
- return;
40293
- }
40294
- console.error("Mobius daemon could not process a in-memory Runtime delivery", error62);
40295
- failAndClose(
40296
- new Error("Runtime delivery processing failed", { cause: error62 }),
40297
- 4008,
40298
- "Invalid Runtime delivery",
40299
- "delivery"
40300
- );
40301
- }).finally(() => processingDeliveryIds.delete(delivery.deliveryId));
40302
- };
40303
- const receiveRuntimeDelivery = (delivery) => {
40304
- const payload = decodeServiceToDaemonMessage(delivery.payload);
40305
- const payloadKind = payload.kind;
40306
- let payloadSessionId = "";
40307
- if (payloadKind === SESSION_CANCEL_KIND) {
40308
- payloadSessionId = payload.sessionId;
40309
- } else if (payloadKind === SESSION_CONFIGURE_KIND) {
40310
- payloadSessionId = payload.sessionId;
40311
- } else if (payloadKind === SESSION_PERMISSION_RESPOND_KIND) {
40312
- payloadSessionId = payload.sessionId;
40313
- } else if (payloadKind === SESSION_ELICITATION_RESPOND_KIND) {
40314
- payloadSessionId = payload.sessionId;
40315
- } else if (payloadKind === SESSION_PROMPT_KIND) {
40316
- payloadSessionId = payload.sessionId;
40317
- } else {
40318
- throw new Error("Runtime delivery contains an unsupported protocol message");
40319
- }
40320
- if (payloadSessionId !== delivery.sessionId) {
40321
- throw new Error("Runtime delivery Session identity does not match its payload");
40322
- }
40323
- const stored = outbox.claimRuntimeDelivery(delivery);
40324
- send(socket, {
40325
- deliveryId: delivery.deliveryId,
40326
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
40327
- sessionId: delivery.sessionId
40328
- });
40329
- processRuntimeDelivery(delivery, stored.state);
40330
- };
40331
- const resumeRuntimeDeliveries = () => {
40332
- for (const stored of outbox.runtimeDeliveries()) {
40333
- const delivery = {
40334
- deliveryId: stored.deliveryId,
40335
- kind: RUNTIME_DELIVERY_KIND,
40336
- payload: stored.payload,
40337
- sessionId: stored.sessionId
40338
- };
40339
- if (stored.state !== "relay_committed") {
40340
- send(socket, {
40341
- deliveryId: stored.deliveryId,
40342
- kind: RUNTIME_DELIVERY_RECEIVED_KIND,
40343
- sessionId: stored.sessionId
40344
- });
39515
+ if (first.command.commandId !== command.targetCommandId) {
39516
+ return "queue-target-unavailable";
40345
39517
  }
40346
- processRuntimeDelivery(delivery, stored.state);
39518
+ await waitForTurnCompletion(first, waitSignal);
40347
39519
  }
40348
39520
  };
40349
39521
  const connectionLiveness = new RelayConnectionLiveness(timer, {
@@ -40402,39 +39574,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40402
39574
  try {
40403
39575
  const message = decodeServiceToDaemonMessage(encoded);
40404
39576
  const kind = message.kind;
40405
- if (kind === RUNTIME_DELIVERY_COMMITTED_KIND) {
40406
- const committed = message;
40407
- if (!outbox.markRuntimeDeliveryCommitted(committed.deliveryId, committed.sessionId)) {
40408
- console.warn("Mobius daemon ignored confirmation for an unknown Runtime delivery");
40409
- }
40410
- return;
40411
- }
40412
- if (kind === RUNTIME_DELIVERY_KIND) {
40413
- receiveRuntimeDelivery(message);
40414
- return;
40415
- }
40416
- if (kind === SESSION_EVENT_ACK_KIND) {
40417
- publisher.acknowledge(message);
40418
- return;
40419
- }
40420
- if (kind === SESSION_EVENT_DEFERRED_KIND) {
40421
- publisher.defer(message);
40422
- return;
40423
- }
40424
- if (kind === SESSION_EVENT_REJECTED_KIND) {
40425
- const rejection = message;
40426
- if (publisher.quarantine(rejection)) {
40427
- audit.record({
40428
- commandId: rejection.eventId,
40429
- details: { code: rejection.code },
40430
- event: "session_event_rejected",
40431
- sessionId: rejection.sessionId
40432
- });
40433
- } else {
40434
- console.warn("Mobius daemon ignored a rejection for an unknown session event");
40435
- }
40436
- return;
40437
- }
40438
39577
  if (kind === SESSION_LIVE_HISTORY_LOAD_KIND) {
40439
39578
  const command2 = decodeSessionLiveHistoryLoad(encoded);
40440
39579
  void executeSessionLiveHistoryLoad(
@@ -40912,7 +40051,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40912
40051
  const cancellation = message;
40913
40052
  const turn2 = activeTurns.get(cancellation.commandId);
40914
40053
  if (turn2 === void 0 || !turn2.matches(cancellation)) {
40915
- settleAbandonedTurn(publisher, outbox, audit, cancellation);
40054
+ settleAbandonedTurn(publisher, operations, audit, cancellation);
40916
40055
  return;
40917
40056
  }
40918
40057
  if (!turn2.requestCancellation()) {
@@ -41008,14 +40147,14 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41008
40147
  if (activeTurns.has(command.commandId)) {
41009
40148
  return;
41010
40149
  }
41011
- const receipt = outbox.claimExecution(command.commandId, command.sessionId, encoded);
40150
+ const receipt = operations.claimExecution(command.commandId, command.sessionId, encoded);
41012
40151
  if (receipt.kind === "duplicate") {
41013
40152
  return;
41014
40153
  }
41015
40154
  const turn = new ActiveDaemonTurn(command, receipt.attemptId);
41016
40155
  activeTurns.set(command.commandId, turn);
41017
40156
  void executePrompt(
41018
- outbox,
40157
+ operations,
41019
40158
  publisher,
41020
40159
  command,
41021
40160
  config2,
@@ -41023,30 +40162,20 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41023
40162
  audit,
41024
40163
  sessions,
41025
40164
  receipt.attemptId,
41026
- () => {
41027
- turn.accept();
41028
- if (command.disposition !== SessionPromptDisposition.Steer) {
41029
- activeAttemptIds.set(command.sessionId, receipt.attemptId);
41030
- }
41031
- },
40165
+ turn.accept,
40166
+ (waitSignal) => waitForSessionAvailability(command, waitSignal),
41032
40167
  timer,
41033
40168
  turn.signal,
41034
- turn.recordText
40169
+ turn.recordText,
40170
+ turn.cancellationRequested
41035
40171
  ).catch((error62) => {
41036
40172
  console.error("Mobius daemon turn failed", error62);
41037
40173
  }).finally(() => {
41038
40174
  activeTurns.delete(command.commandId);
41039
- if (activeAttemptIds.get(command.sessionId) === receipt.attemptId) {
41040
- activeAttemptIds.delete(command.sessionId);
41041
- }
41042
40175
  turn.finish();
41043
40176
  });
41044
40177
  } catch (error62) {
41045
40178
  console.error("Mobius daemon rejected a message", error62);
41046
- if (error62 instanceof RuntimeDeliveryInboxCapacityError) {
41047
- failAndClose(error62, 4013, "Runtime delivery queue full", "delivery_backpressure");
41048
- return;
41049
- }
41050
40179
  failAndClose(
41051
40180
  new Error("Relay sent an invalid protocol message", { cause: error62 }),
41052
40181
  4008,
@@ -41064,7 +40193,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41064
40193
  return;
41065
40194
  }
41066
40195
  publisher.connect(socket);
41067
- resumeRuntimeDeliveries();
41068
40196
  },
41069
40197
  (error62) => {
41070
40198
  if (finished) {
@@ -41086,7 +40214,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41086
40214
  turn.abortDaemon();
41087
40215
  }
41088
40216
  publisher.connect(socket);
41089
- resumeRuntimeDeliveries();
41090
40217
  return;
41091
40218
  }
41092
40219
  failAndClose(
@@ -41123,17 +40250,11 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
41123
40250
  stateDirectory
41124
40251
  });
41125
40252
  const sessionStore = new MemoryAcpSessionStore();
41126
- const outbox = new SessionEventOutbox();
41127
- const publisher = new DaemonSessionEventPublisher(outbox, timer);
40253
+ const operations = new DaemonOperationState();
40254
+ const publisher = new DaemonSessionEventPublisher();
41128
40255
  const activeTurns = /* @__PURE__ */ new Map();
41129
- const activeAttemptIds = /* @__PURE__ */ new Map();
41130
40256
  const recordSessionEvent = (sessionId, event) => {
41131
- const attemptId = activeAttemptIds.get(sessionId);
41132
- if (attemptId === void 0) {
41133
- publisher.recordRuntime(sessionId, event);
41134
- return;
41135
- }
41136
- publisher.recordAttempt(sessionId, event, attemptId);
40257
+ publisher.publish(sessionId, event);
41137
40258
  };
41138
40259
  const sessions = new AcpSessionManager(
41139
40260
  new DaemonAcpObserver(recordSessionEvent),
@@ -41238,10 +40359,9 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
41238
40359
  installations,
41239
40360
  installationObserver,
41240
40361
  nativeSessions,
41241
- outbox,
40362
+ operations,
41242
40363
  publisher,
41243
40364
  activeTurns,
41244
- activeAttemptIds,
41245
40365
  connectionEpoch,
41246
40366
  diagnostics,
41247
40367
  () => {
@@ -41287,7 +40407,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
41287
40407
  try {
41288
40408
  publisher.close();
41289
40409
  } finally {
41290
- outbox.close();
40410
+ operations.close();
41291
40411
  }
41292
40412
  }
41293
40413
  }
@@ -41463,9 +40583,6 @@ function decodeResponse(value) {
41463
40583
  }
41464
40584
  if (value["kind"] === "listed" && Array.isArray(value["pairs"]) && value["pairs"].every(isManagedRuntimeSummary)) {
41465
40585
  const managerVersion = value["managerVersion"];
41466
- if (managerVersion === void 0) {
41467
- return { kind: "legacy-listed", pairs: value["pairs"] };
41468
- }
41469
40586
  if (typeof managerVersion === "string" && managerVersion.length > 0 && managerVersion.length <= 128) {
41470
40587
  return { kind: "listed", managerVersion, pairs: value["pairs"] };
41471
40588
  }
@@ -41764,11 +40881,7 @@ async function requestManager(installation, managerVersion, command, signal) {
41764
40881
  if (command.kind === "list") {
41765
40882
  return listed;
41766
40883
  }
41767
- const response = await sendControlRequest(installation.stateDirectory, command, deadline);
41768
- if (response.kind === "legacy-listed") {
41769
- throw new Error("The Mobius manager returned an unexpected response");
41770
- }
41771
- return response;
40884
+ return await sendControlRequest(installation.stateDirectory, command, deadline);
41772
40885
  }
41773
40886
  async function ensureMatchingManager(stateDirectory, managerVersion, signal) {
41774
40887
  let managerStarted = false;
@@ -41782,7 +40895,7 @@ async function ensureMatchingManager(stateDirectory, managerVersion, signal) {
41782
40895
  }
41783
40896
  return response;
41784
40897
  }
41785
- if (response.kind !== "listed" && response.kind !== "legacy-listed") {
40898
+ if (response.kind !== "listed") {
41786
40899
  if (response.kind === "error") {
41787
40900
  throw new Error(response.message);
41788
40901
  }