@moxt-ai/mobius 0.0.176 → 0.0.178

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 (59) hide show
  1. package/dist/acp/agent-connection.d.ts +1 -3
  2. package/dist/acp/agent-connection.d.ts.map +1 -1
  3. package/dist/acp/agent-connection.js +3 -4
  4. package/dist/acp/agent-connection.js.map +1 -1
  5. package/dist/acp/agent-runtime-manager.d.ts +2 -1
  6. package/dist/acp/agent-runtime-manager.d.ts.map +1 -1
  7. package/dist/acp/agent-runtime-manager.js +12 -9
  8. package/dist/acp/agent-runtime-manager.js.map +1 -1
  9. package/dist/acp/agent-session.d.ts +4 -3
  10. package/dist/acp/agent-session.d.ts.map +1 -1
  11. package/dist/acp/agent-session.js +54 -32
  12. package/dist/acp/agent-session.js.map +1 -1
  13. package/dist/acp/codex/agent.d.ts.map +1 -1
  14. package/dist/acp/codex/agent.js +1 -13
  15. package/dist/acp/codex/agent.js.map +1 -1
  16. package/dist/acp/session-contracts.d.ts +3 -1
  17. package/dist/acp/session-contracts.d.ts.map +1 -1
  18. package/dist/acp/session-contracts.js.map +1 -1
  19. package/dist/cli.js +241 -617
  20. package/dist/cli.js.map +4 -4
  21. package/dist/daemon-command-handler.d.ts +1 -3
  22. package/dist/daemon-command-handler.d.ts.map +1 -1
  23. package/dist/daemon-command-handler.js +11 -9
  24. package/dist/daemon-command-handler.js.map +1 -1
  25. package/dist/daemon-command-results.d.ts +2 -3
  26. package/dist/daemon-command-results.d.ts.map +1 -1
  27. package/dist/daemon-command-results.js +4 -12
  28. package/dist/daemon-command-results.js.map +1 -1
  29. package/dist/daemon-prompt-executor.d.ts +2 -6
  30. package/dist/daemon-prompt-executor.d.ts.map +1 -1
  31. package/dist/daemon-prompt-executor.js +20 -73
  32. package/dist/daemon-prompt-executor.js.map +1 -1
  33. package/dist/daemon-session-commands.d.ts +2 -3
  34. package/dist/daemon-session-commands.d.ts.map +1 -1
  35. package/dist/daemon-session-commands.js +3 -15
  36. package/dist/daemon-session-commands.js.map +1 -1
  37. package/dist/index.js +240 -616
  38. package/dist/index.js.map +4 -4
  39. package/dist/relay-connection/run-relay-connection.d.ts.map +1 -1
  40. package/dist/relay-connection/run-relay-connection.js +0 -1
  41. package/dist/relay-connection/run-relay-connection.js.map +1 -1
  42. package/dist/relay-connection/session-event-publisher.d.ts +7 -3
  43. package/dist/relay-connection/session-event-publisher.d.ts.map +1 -1
  44. package/dist/relay-connection/session-event-publisher.js +35 -27
  45. package/dist/relay-connection/session-event-publisher.js.map +1 -1
  46. package/dist/run-daemon.d.ts.map +1 -1
  47. package/dist/run-daemon.js +5 -6
  48. package/dist/run-daemon.js.map +1 -1
  49. package/dist/runtime.js +240 -616
  50. package/dist/runtime.js.map +4 -4
  51. package/dist/session-event-log-v2.d.ts +7 -5
  52. package/dist/session-event-log-v2.d.ts.map +1 -1
  53. package/dist/session-event-log-v2.js +83 -12
  54. package/dist/session-event-log-v2.js.map +1 -1
  55. package/package.json +1 -1
  56. package/dist/relay-connection/coalescing-agent-event-publisher.d.ts +0 -32
  57. package/dist/relay-connection/coalescing-agent-event-publisher.d.ts.map +0 -1
  58. package/dist/relay-connection/coalescing-agent-event-publisher.js +0 -116
  59. package/dist/relay-connection/coalescing-agent-event-publisher.js.map +0 -1
package/dist/index.js CHANGED
@@ -20368,8 +20368,6 @@ function decodeValue(value, schema) {
20368
20368
  }
20369
20369
  return result.data;
20370
20370
  }
20371
- var decodeAgentDisplayContentValue = (value) => decodeValue(value, displayContentSchema);
20372
- var decodeRecordedAgentContentValue = (value) => decodeValue(value, recordedDisplayContentSchema);
20373
20371
  var decodePromptImagesValue = (value) => decodeValue(value, external_exports.array(promptImageSchema).max(8).readonly());
20374
20372
  var decodePromptResourcesValue = (value) => decodeValue(value, external_exports.array(promptResourceSchema).max(16).readonly());
20375
20373
  var decodeSessionConfigurationSelections = (value) => decodeValue(value, sessionConfigurationSelectionsSchema);
@@ -20411,20 +20409,13 @@ var encodeSessionReadyEvent = (message) => encode3(message, sessionReadyEventSch
20411
20409
  var decodeSessionConfigureCommand = (encoded) => decode3(encoded, sessionConfigureCommandSchema);
20412
20410
  var encodeSessionConfigureCommand = (message) => encode3(message, sessionConfigureCommandSchema);
20413
20411
  var decodeSessionConfigUpdatedEvent = (encoded) => decode3(encoded, sessionConfigUpdatedEventSchema);
20414
- var decodeSessionUsageUpdatedEvent = (encoded) => decode3(encoded, sessionUsageUpdatedEventSchema);
20415
- var decodeSessionCommandsUpdatedEvent = (encoded) => decode3(encoded, sessionCommandsUpdatedEventSchema);
20416
- var decodeSessionInfoUpdatedEvent = (encoded) => decode3(encoded, sessionInfoUpdatedEventSchema);
20417
- var decodeSessionPermissionRequestedEvent = (encoded) => decode3(encoded, sessionPermissionRequestedEventSchema);
20412
+ var encodeSessionConfigUpdatedEvent = (message) => encode3(message, sessionConfigUpdatedEventSchema);
20418
20413
  var decodeSessionPermissionRespondCommand = (encoded) => decode3(encoded, sessionPermissionRespondCommandSchema);
20419
20414
  var encodeSessionPermissionRespondCommand = (message) => encode3(message, sessionPermissionRespondCommandSchema);
20420
- var decodeSessionPermissionResolvedEvent = (encoded) => decode3(encoded, sessionPermissionResolvedEventSchema);
20421
- var decodeSessionElicitationRequestedEvent = (encoded) => decode3(encoded, sessionElicitationRequestedEventSchema);
20422
20415
  var decodeSessionElicitationRespondCommand = (encoded) => decode3(encoded, sessionElicitationRespondCommandSchema);
20423
20416
  var encodeSessionElicitationRespondCommand = (message) => encode3(message, sessionElicitationRespondCommandSchema);
20424
- var decodeSessionElicitationResolvedEvent = (encoded) => decode3(encoded, sessionElicitationResolvedEventSchema);
20425
20417
  var decodeSessionOperationFailedEvent = (encoded) => decode3(encoded, sessionOperationFailedEventSchema);
20426
20418
  var encodeSessionOperationFailedEvent = (message) => encode3(message, sessionOperationFailedEventSchema);
20427
- var decodeAgentContentEvent = (encoded) => decode3(encoded, agentContentEventSchema);
20428
20419
  var decodeAgentInstallRequestCommand = (encoded) => decode3(encoded, agentInstallRequestCommandSchema);
20429
20420
  var encodeAgentInstallRequestCommand = (message) => encode3(message, agentInstallRequestCommandSchema);
20430
20421
  var decodeAgentInstallCancelCommand = (encoded) => decode3(encoded, agentInstallCancelCommandSchema);
@@ -20450,7 +20441,6 @@ var RUNTIME_HEARTBEAT_KIND = "runtime.heartbeat";
20450
20441
  var RUNTIME_HEARTBEAT_ACK_KIND = "runtime.heartbeat.ack";
20451
20442
  var RUNTIME_PING_KIND = "runtime.ping";
20452
20443
  var RUNTIME_PONG_KIND = "runtime.pong";
20453
- var SESSION_STARTED_KIND = "session.started";
20454
20444
  var SESSION_QUEUED_KIND = "session.queued";
20455
20445
  var AGENT_MESSAGE_DELTA_KIND = "agent.message.delta";
20456
20446
  var AGENT_ACTIVITY_KIND = "agent.activity";
@@ -20460,8 +20450,6 @@ var AGENT_ACTIVITY_RECORDED_FIELD_LIMIT = 4e6;
20460
20450
  var AGENT_ACTIVITY_RECORDED_DETAIL_LIMIT = 6e6;
20461
20451
  var AGENT_ACTIVITY_LOCATION_LIMIT = 12;
20462
20452
  var AGENT_ACTIVITY_LOCATION_LENGTH_LIMIT = 1024;
20463
- var SESSION_COMPLETED_KIND = "session.completed";
20464
- var SESSION_FAILED_KIND = "session.failed";
20465
20453
  var SessionPromptDisposition = Object.freeze({
20466
20454
  Queue: "queue",
20467
20455
  Reject: "reject",
@@ -20472,23 +20460,6 @@ var SessionPromptDisposition = Object.freeze({
20472
20460
  var DIRECTORY_IDENTIFIER_PATTERN2 = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/;
20473
20461
  var MAX_PROMPT_LENGTH = 1e4;
20474
20462
  var MAX_PROMPT_ATTACHMENT_LENGTH = 6e6;
20475
- var MAX_EVENT_TEXT_LENGTH = 1e5;
20476
- var ACTIVITY_TYPES = /* @__PURE__ */ new Set(["notice", "plan", "progress", "reasoning", "tool"]);
20477
- var NARRATION_ACTIVITY_TYPES = /* @__PURE__ */ new Set(["progress", "reasoning"]);
20478
- var ACTIVITY_STATUSES = /* @__PURE__ */ new Set(["pending", "running", "completed", "failed"]);
20479
- var TOOL_KINDS = /* @__PURE__ */ new Set([
20480
- "",
20481
- "delete",
20482
- "edit",
20483
- "execute",
20484
- "fetch",
20485
- "move",
20486
- "other",
20487
- "read",
20488
- "search",
20489
- "switch_mode",
20490
- "think"
20491
- ]);
20492
20463
  var ProtocolMessageError = class extends Error {
20493
20464
  code = "invalid_protocol_message";
20494
20465
  constructor(message, options = {}) {
@@ -20538,13 +20509,6 @@ function readText(value, key, maximumLength) {
20538
20509
  }
20539
20510
  return field;
20540
20511
  }
20541
- function readAllowedString(value, key, allowedValues) {
20542
- const field = readText(value, key, 64);
20543
- if (!allowedValues.has(field)) {
20544
- throw new ProtocolMessageError(`Invalid value field: ${key}`);
20545
- }
20546
- return field;
20547
- }
20548
20512
  function readPromptDisposition(value) {
20549
20513
  const field = value["disposition"];
20550
20514
  if (field === void 0 || field === SessionPromptDisposition.Reject) {
@@ -20558,32 +20522,6 @@ function readPromptDisposition(value) {
20558
20522
  }
20559
20523
  throw new ProtocolMessageError("Invalid value field: disposition");
20560
20524
  }
20561
- function readSequence(value, key) {
20562
- const field = value[key];
20563
- if (typeof field !== "number" || !Number.isSafeInteger(field) || field < 0) {
20564
- throw new ProtocolMessageError(`Invalid integer field: ${key}`);
20565
- }
20566
- return field;
20567
- }
20568
- function readLocations(value) {
20569
- const field = value["locations"];
20570
- if (!Array.isArray(field) || field.length > AGENT_ACTIVITY_LOCATION_LIMIT) {
20571
- throw new ProtocolMessageError("Invalid locations field");
20572
- }
20573
- const locations = [];
20574
- const unique = /* @__PURE__ */ new Set();
20575
- for (const location of field) {
20576
- if (typeof location !== "string" || location.length === 0 || location.length > AGENT_ACTIVITY_LOCATION_LENGTH_LIMIT) {
20577
- throw new ProtocolMessageError("Invalid activity location");
20578
- }
20579
- if (unique.has(location)) {
20580
- throw new ProtocolMessageError("Duplicate activity location");
20581
- }
20582
- unique.add(location);
20583
- locations.push(location);
20584
- }
20585
- return locations;
20586
- }
20587
20525
  function readDirectoryIdentifiers(value, key, maximumCount) {
20588
20526
  const field = value[key];
20589
20527
  if (!Array.isArray(field) || field.length > maximumCount) {
@@ -20600,54 +20538,6 @@ function readDirectoryIdentifiers(value, key, maximumCount) {
20600
20538
  }
20601
20539
  return identifiers;
20602
20540
  }
20603
- function readActivityContent(value) {
20604
- const field = value["content"];
20605
- if (!Array.isArray(field) || field.length > 100) {
20606
- throw new ProtocolMessageError("Invalid activity content field");
20607
- }
20608
- return field.map((entry) => decodeAgentDisplayContentValue(entry));
20609
- }
20610
- function readActivityDetail(value) {
20611
- const field = value["detail"];
20612
- if (!isRecord(field)) {
20613
- throw new ProtocolMessageError("Invalid activity detail field");
20614
- }
20615
- const kind = readString(field, "kind", 32);
20616
- if (kind === "available") {
20617
- return {
20618
- artifactId: readIdentifier(field, "artifactId"),
20619
- kind
20620
- };
20621
- }
20622
- if (kind === "unrecorded") {
20623
- return { kind };
20624
- }
20625
- if (kind === "truncated") {
20626
- const capturedBytes = readSequence(field, "capturedBytes");
20627
- const originalBytes = readSequence(field, "originalBytes");
20628
- if (capturedBytes > originalBytes) {
20629
- throw new ProtocolMessageError("Invalid truncated activity detail size");
20630
- }
20631
- return { capturedBytes, kind, originalBytes };
20632
- }
20633
- if (kind === "recorded") {
20634
- const contentValue = field["content"];
20635
- if (!Array.isArray(contentValue) || contentValue.length > 100) {
20636
- throw new ProtocolMessageError("Invalid recorded activity content");
20637
- }
20638
- const detail = {
20639
- content: contentValue.map((entry) => decodeRecordedAgentContentValue(entry)),
20640
- input: readText(field, "input", AGENT_ACTIVITY_RECORDED_FIELD_LIMIT),
20641
- kind,
20642
- output: readText(field, "output", AGENT_ACTIVITY_RECORDED_FIELD_LIMIT)
20643
- };
20644
- if (JSON.stringify(detail).length > AGENT_ACTIVITY_RECORDED_DETAIL_LIMIT) {
20645
- throw new ProtocolMessageError("Recorded activity detail is too large");
20646
- }
20647
- return detail;
20648
- }
20649
- throw new ProtocolMessageError("Invalid activity detail availability");
20650
- }
20651
20541
  function readIdentifier(value, key) {
20652
20542
  try {
20653
20543
  return decodeIdentifier(value[key]);
@@ -20772,82 +20662,6 @@ function decodeRuntimePongEvent(encoded) {
20772
20662
  assertKind(value, RUNTIME_PONG_KIND);
20773
20663
  return { kind: RUNTIME_PONG_KIND, requestId: readIdentifier(value, "requestId") };
20774
20664
  }
20775
- function decodeSessionStartedEvent(encoded) {
20776
- const value = parseJson2(encoded);
20777
- assertKind(value, SESSION_STARTED_KIND);
20778
- const sequence = readSequence(value, "sequence");
20779
- if (sequence !== 0) {
20780
- throw new ProtocolMessageError("Invalid live start sequence");
20781
- }
20782
- return {
20783
- commandId: readIdentifier(value, "commandId"),
20784
- epoch: readIdentifier(value, "epoch"),
20785
- kind: SESSION_STARTED_KIND,
20786
- attemptId: readIdentifier(value, "attemptId"),
20787
- prompt: readText(value, "prompt", MAX_PROMPT_LENGTH),
20788
- sequence,
20789
- sessionId: readIdentifier(value, "sessionId")
20790
- };
20791
- }
20792
- function decodeAgentMessageDeltaEvent(encoded) {
20793
- const value = parseJson2(encoded);
20794
- assertKind(value, AGENT_MESSAGE_DELTA_KIND);
20795
- const sequence = readSequence(value, "sequence");
20796
- if (sequence === 0) {
20797
- throw new ProtocolMessageError("Invalid live sequence");
20798
- }
20799
- return {
20800
- commandId: readIdentifier(value, "commandId"),
20801
- epoch: readIdentifier(value, "epoch"),
20802
- kind: AGENT_MESSAGE_DELTA_KIND,
20803
- messageId: value["messageId"] === void 0 ? "" : readText(value, "messageId", 255),
20804
- sequence,
20805
- sessionId: readIdentifier(value, "sessionId"),
20806
- text: readString(value, "text", MAX_EVENT_TEXT_LENGTH)
20807
- };
20808
- }
20809
- function decodeAgentActivityEvent(encoded) {
20810
- const value = parseJson2(encoded);
20811
- assertKind(value, AGENT_ACTIVITY_KIND);
20812
- return {
20813
- activityId: readIdentifier(value, "activityId"),
20814
- activityType: readAllowedString(value, "activityType", ACTIVITY_TYPES),
20815
- commandId: readIdentifier(value, "commandId"),
20816
- content: readActivityContent(value),
20817
- detail: readActivityDetail(value),
20818
- input: readText(value, "input", AGENT_ACTIVITY_DETAIL_LIMIT),
20819
- kind: AGENT_ACTIVITY_KIND,
20820
- locations: readLocations(value),
20821
- name: readText(value, "name", 128),
20822
- output: readText(value, "output", AGENT_ACTIVITY_DETAIL_LIMIT),
20823
- sequence: readSequence(value, "sequence"),
20824
- sessionId: readIdentifier(value, "sessionId"),
20825
- status: readAllowedString(value, "status", ACTIVITY_STATUSES),
20826
- title: readString(value, "title", 500),
20827
- toolKind: readAllowedString(value, "toolKind", TOOL_KINDS)
20828
- };
20829
- }
20830
- function decodeSessionCompletedEvent(encoded) {
20831
- const value = parseJson2(encoded);
20832
- assertKind(value, SESSION_COMPLETED_KIND);
20833
- return {
20834
- commandId: readIdentifier(value, "commandId"),
20835
- kind: SESSION_COMPLETED_KIND,
20836
- sessionId: readIdentifier(value, "sessionId"),
20837
- stopReason: readString(value, "stopReason", 64)
20838
- };
20839
- }
20840
- function decodeSessionFailedEvent(encoded) {
20841
- const value = parseJson2(encoded);
20842
- assertKind(value, SESSION_FAILED_KIND);
20843
- return {
20844
- code: readIdentifier(value, "code"),
20845
- commandId: readIdentifier(value, "commandId"),
20846
- kind: SESSION_FAILED_KIND,
20847
- message: readString(value, "message", 500),
20848
- sessionId: readIdentifier(value, "sessionId")
20849
- };
20850
- }
20851
20665
  function encodeSessionPromptCommand(message) {
20852
20666
  return JSON.stringify(decodeSessionPromptCommand(JSON.stringify(message)));
20853
20667
  }
@@ -20875,19 +20689,6 @@ function encodeRuntimePingCommand(message) {
20875
20689
  function encodeRuntimePongEvent(message) {
20876
20690
  return JSON.stringify(decodeRuntimePongEvent(JSON.stringify(message)));
20877
20691
  }
20878
- function decodeAgentActivityNarrationEvent(encoded) {
20879
- const value = parseJson2(encoded);
20880
- assertKind(value, AGENT_ACTIVITY_NARRATION_KIND);
20881
- return {
20882
- activityId: readIdentifier(value, "activityId"),
20883
- activityType: readAllowedString(value, "activityType", NARRATION_ACTIVITY_TYPES),
20884
- commandId: readIdentifier(value, "commandId"),
20885
- kind: AGENT_ACTIVITY_NARRATION_KIND,
20886
- sequence: readSequence(value, "sequence"),
20887
- sessionId: readIdentifier(value, "sessionId"),
20888
- text: readText(value, "text", MAX_EVENT_TEXT_LENGTH)
20889
- };
20890
- }
20891
20692
 
20892
20693
  // ../protocol/src/session-history.ts
20893
20694
  var SESSION_HISTORY_CHARACTER_LIMIT = 256e3;
@@ -21153,6 +20954,7 @@ var MAX_CONTENT_LENGTH = 1e6;
21153
20954
  var MAX_JSON_DEPTH = 16;
21154
20955
  var MAX_JSON_KEYS = 1e3;
21155
20956
  var SESSION_EVENT_V2_KIND = "session.event.v2";
20957
+ var SESSION_EVENT_V2_BATCH_MAX_SIZE = 1e3;
21156
20958
  var boundedString = external_exports.string().max(MAX_CONTENT_LENGTH);
21157
20959
  var shortString = external_exports.string().max(2048);
21158
20960
  var externalContentKeySchema = external_exports.string().regex(/^[a-f0-9]{64}$/u);
@@ -21456,6 +21258,11 @@ var acpSessionUpdateV2Schema = external_exports.discriminatedUnion("sessionUpdat
21456
21258
  }).readonly()
21457
21259
  ]);
21458
21260
  var lifecycleBase = { commandId: identifierStringSchema };
21261
+ var promptExecutionContextV2Schema = external_exports.object({
21262
+ agentId: identifierStringSchema,
21263
+ directoryId: shortString,
21264
+ additionalDirectoryIds: external_exports.array(identifierStringSchema).max(16).readonly()
21265
+ }).readonly();
21459
21266
  var lifecycleMetadataV2Schema = external_exports.discriminatedUnion("kind", [
21460
21267
  external_exports.object({ kind: external_exports.literal("session.queue.changed") }).readonly(),
21461
21268
  external_exports.object({ event: sessionPermissionRequestedEventSchema, kind: external_exports.literal("session.permission.requested") }).readonly(),
@@ -21465,7 +21272,8 @@ var lifecycleMetadataV2Schema = external_exports.discriminatedUnion("kind", [
21465
21272
  external_exports.object({
21466
21273
  ...lifecycleBase,
21467
21274
  content: external_exports.array(contentBlockV2Schema).min(1).max(100).readonly(),
21468
- kind: external_exports.literal("prompt.requested")
21275
+ kind: external_exports.literal("prompt.requested"),
21276
+ context: promptExecutionContextV2Schema.optional()
21469
21277
  }).readonly(),
21470
21278
  external_exports.object({ ...lifecycleBase, attemptId: identifierStringSchema, epoch: identifierStringSchema, kind: external_exports.literal("prompt.started") }).readonly(),
21471
21279
  external_exports.object({ ...lifecycleBase, kind: external_exports.literal("prompt.completed"), stopReason: shortString }).readonly(),
@@ -21518,6 +21326,7 @@ var sessionEventV2Schema = external_exports.discriminatedUnion("type", [
21518
21326
  type: external_exports.literal("lifecycle-metadata")
21519
21327
  }).readonly()
21520
21328
  ]);
21329
+ var sessionEventBatchV2Schema = external_exports.array(sessionEventV2Schema).min(1).max(SESSION_EVENT_V2_BATCH_MAX_SIZE).readonly();
21521
21330
  var sessionExportV2Schema = external_exports.object({
21522
21331
  binding: external_exports.object({
21523
21332
  bindingId: identifierStringSchema,
@@ -21560,7 +21369,7 @@ var mobiusSessionExportV2Schema = external_exports.object({
21560
21369
  formatVersion: external_exports.literal("2"),
21561
21370
  session: sessionExportV2Schema
21562
21371
  }).readonly();
21563
- var sessionEventEnvelopeV2Schema = external_exports.object({ event: sessionEventV2Schema, kind: external_exports.literal(SESSION_EVENT_V2_KIND) }).readonly();
21372
+ var sessionEventEnvelopeV2Schema = external_exports.object({ events: sessionEventBatchV2Schema, kind: external_exports.literal(SESSION_EVENT_V2_KIND) }).readonly();
21564
21373
  var sessionEventLogPageV2Schema = external_exports.object({
21565
21374
  daemonGenerationId: identifierStringSchema,
21566
21375
  events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
@@ -21605,94 +21414,6 @@ var decodeSessionEventEnvelopeV2 = (value) => decode5(value, sessionEventEnvelop
21605
21414
  var encodeSessionEventEnvelopeV2 = (value) => encode4(value, sessionEventEnvelopeV2Schema);
21606
21415
  var decodeAcpSessionUpdateV2 = (value) => decode5(value, acpSessionUpdateV2Schema);
21607
21416
 
21608
- // ../protocol/src/session-events.ts
21609
- var SESSION_EVENT_KIND = "session.event";
21610
- var SESSION_FORKED_KIND = "session.forked";
21611
- var MAX_RECORDED_EVENT_LENGTH = 8 * 1024 * 1024;
21612
- var sessionEventEnvelopeSchema = external_exports.object({
21613
- kind: external_exports.literal(SESSION_EVENT_KIND),
21614
- payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
21615
- sessionId: identifierStringSchema
21616
- }).readonly();
21617
- var SESSION_QUEUE_CHANGED_KIND = "session.queue.changed";
21618
- var sessionQueueChangedSchema = external_exports.object({ kind: external_exports.literal(SESSION_QUEUE_CHANGED_KIND), sessionId: identifierStringSchema }).readonly();
21619
- var sessionForkedSchema = external_exports.object({
21620
- kind: external_exports.literal(SESSION_FORKED_KIND),
21621
- sessionId: identifierStringSchema,
21622
- sourceSessionId: identifierStringSchema,
21623
- throughCommandId: identifierStringSchema
21624
- }).readonly();
21625
- function decode6(encoded, schema) {
21626
- let value;
21627
- try {
21628
- value = JSON.parse(encoded);
21629
- } catch (cause) {
21630
- throw new ProtocolMessageError("Message is not valid JSON", { cause });
21631
- }
21632
- const decoded = schema.safeParse(value);
21633
- if (!decoded.success) {
21634
- throw new ProtocolMessageError("Message does not match its schema", {
21635
- cause: decoded.error
21636
- });
21637
- }
21638
- return decoded.data;
21639
- }
21640
- var encode5 = (message, schema) => {
21641
- const decoded = schema.safeParse(message);
21642
- if (!decoded.success) {
21643
- throw new ProtocolMessageError("Message does not match its schema", {
21644
- cause: decoded.error
21645
- });
21646
- }
21647
- return JSON.stringify(decoded.data);
21648
- };
21649
- var decodeSessionEventEnvelope = (encoded) => decode6(encoded, sessionEventEnvelopeSchema);
21650
- var encodeSessionEventEnvelope = (message) => encode5(message, sessionEventEnvelopeSchema);
21651
- function decodeRecordedSessionEvent(encoded) {
21652
- const kind = decodeMessageKind(encoded);
21653
- switch (kind) {
21654
- case SESSION_QUEUE_CHANGED_KIND:
21655
- return decode6(encoded, sessionQueueChangedSchema);
21656
- case SESSION_FORKED_KIND:
21657
- return decode6(encoded, sessionForkedSchema);
21658
- case AGENT_ACTIVITY_KIND:
21659
- return decodeAgentActivityEvent(encoded);
21660
- case AGENT_ACTIVITY_NARRATION_KIND:
21661
- return decodeAgentActivityNarrationEvent(encoded);
21662
- case AGENT_CONTENT_KIND:
21663
- return decodeAgentContentEvent(encoded);
21664
- case AGENT_MESSAGE_DELTA_KIND:
21665
- return decodeAgentMessageDeltaEvent(encoded);
21666
- case SESSION_COMMANDS_UPDATED_KIND:
21667
- return decodeSessionCommandsUpdatedEvent(encoded);
21668
- case SESSION_COMPLETED_KIND:
21669
- return decodeSessionCompletedEvent(encoded);
21670
- case SESSION_CONFIG_UPDATED_KIND:
21671
- return decodeSessionConfigUpdatedEvent(encoded);
21672
- case SESSION_ELICITATION_REQUESTED_KIND:
21673
- return decodeSessionElicitationRequestedEvent(encoded);
21674
- case SESSION_ELICITATION_RESOLVED_KIND:
21675
- return decodeSessionElicitationResolvedEvent(encoded);
21676
- case SESSION_FAILED_KIND:
21677
- return decodeSessionFailedEvent(encoded);
21678
- case SESSION_INFO_UPDATED_KIND:
21679
- return decodeSessionInfoUpdatedEvent(encoded);
21680
- case SESSION_PERMISSION_REQUESTED_KIND:
21681
- return decodeSessionPermissionRequestedEvent(encoded);
21682
- case SESSION_PERMISSION_RESOLVED_KIND:
21683
- return decodeSessionPermissionResolvedEvent(encoded);
21684
- case SESSION_READY_KIND:
21685
- return decodeSessionReadyEvent(encoded);
21686
- case SESSION_STARTED_KIND:
21687
- return decodeSessionStartedEvent(encoded);
21688
- case SESSION_USAGE_UPDATED_KIND:
21689
- return decodeSessionUsageUpdatedEvent(encoded);
21690
- default:
21691
- throw new UnsupportedProtocolMessageKindError("daemon-to-service", kind);
21692
- }
21693
- }
21694
- var encodeRecordedSessionEvent = (event) => JSON.stringify(decodeRecordedSessionEvent(JSON.stringify(event)));
21695
-
21696
21417
  // ../protocol/src/session-live-history.ts
21697
21418
  var SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND = "session.live-history.v2.page.load";
21698
21419
  var SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND = "session.live-history.v2.page.loaded";
@@ -21714,7 +21435,7 @@ var sessionLiveHistoryV2PageLoadedSchema = external_exports.object({
21714
21435
  requestId: identifierStringSchema,
21715
21436
  sessionId: identifierStringSchema
21716
21437
  }).readonly();
21717
- function decode7(schema, encoded) {
21438
+ function decode6(schema, encoded) {
21718
21439
  try {
21719
21440
  const value = JSON.parse(encoded);
21720
21441
  return schema.parse(value);
@@ -21722,8 +21443,8 @@ function decode7(schema, encoded) {
21722
21443
  throw new ProtocolMessageError("Invalid live Session history message", { cause });
21723
21444
  }
21724
21445
  }
21725
- var decodeSessionLiveHistoryV2PageLoad = (encoded) => decode7(sessionLiveHistoryV2PageLoadSchema, encoded);
21726
- var decodeSessionLiveHistoryV2PageLoaded = (encoded) => decode7(sessionLiveHistoryV2PageLoadedSchema, encoded);
21446
+ var decodeSessionLiveHistoryV2PageLoad = (encoded) => decode6(sessionLiveHistoryV2PageLoadSchema, encoded);
21447
+ var decodeSessionLiveHistoryV2PageLoaded = (encoded) => decode6(sessionLiveHistoryV2PageLoadedSchema, encoded);
21727
21448
  var encodeSessionLiveHistoryV2PageLoad = (value) => JSON.stringify(sessionLiveHistoryV2PageLoadSchema.parse(value));
21728
21449
  var encodeSessionLiveHistoryV2PageLoaded = (value) => JSON.stringify(sessionLiveHistoryV2PageLoadedSchema.parse(value));
21729
21450
 
@@ -21837,6 +21558,11 @@ function decodeServiceToDaemonMessage(encoded) {
21837
21558
  return signature.decoder(encoded);
21838
21559
  }
21839
21560
  var daemonToServiceSignatures = {
21561
+ [SESSION_CONFIG_UPDATED_KIND]: defineMessageSignature(
21562
+ SESSION_CONFIG_UPDATED_KIND,
21563
+ encodeSessionConfigUpdatedEvent,
21564
+ decodeSessionConfigUpdatedEvent
21565
+ ),
21840
21566
  [AGENT_INSTALL_CANCELLED_KIND]: defineMessageSignature(
21841
21567
  AGENT_INSTALL_CANCELLED_KIND,
21842
21568
  encodeAgentInstallCancelledEvent,
@@ -21907,11 +21633,6 @@ var daemonToServiceSignatures = {
21907
21633
  decodeRuntimeHeartbeatEvent
21908
21634
  ),
21909
21635
  [RUNTIME_PONG_KIND]: defineMessageSignature(RUNTIME_PONG_KIND, encodeRuntimePongEvent, decodeRuntimePongEvent),
21910
- [SESSION_EVENT_KIND]: defineMessageSignature(
21911
- SESSION_EVENT_KIND,
21912
- encodeSessionEventEnvelope,
21913
- decodeSessionEventEnvelope
21914
- ),
21915
21636
  [SESSION_EVENT_V2_KIND]: defineMessageSignature(
21916
21637
  SESSION_EVENT_V2_KIND,
21917
21638
  encodeSessionEventEnvelopeV2,
@@ -23620,14 +23341,13 @@ var AgentConnection = class {
23620
23341
  get inProcessAgent() {
23621
23342
  return this.#process.kind === "in-process" ? this.#process.endpoint : null;
23622
23343
  }
23623
- captureProcessTree = async () => this.#process.kind === "child" ? await captureProcessTree(this.#process.child) : [];
23624
- closeProcess = async (capturedProcesses = []) => {
23344
+ closeProcess = async () => {
23625
23345
  try {
23626
23346
  if (this.#process.kind === "in-process") {
23627
23347
  await this.#process.endpoint.close();
23628
23348
  return;
23629
23349
  }
23630
- await stopProcessTree(this.#process.child, capturedProcesses);
23350
+ await stopProcessTree(this.#process.child);
23631
23351
  } finally {
23632
23352
  this.connection.close();
23633
23353
  }
@@ -30437,7 +30157,7 @@ var AgentSession = class _AgentSession {
30437
30157
  commandId: () => this.#turn.commandId,
30438
30158
  assertNativeSession: (sessionId) => this.assertNativeSession(sessionId),
30439
30159
  observer: getObserver,
30440
- recordSessionEventV2: this.#recordLifecycleEventV2
30160
+ recordSessionEventV2: this.recordLifecycleEventV2
30441
30161
  });
30442
30162
  this.#connection = new AgentConnection(agent, cwd, this);
30443
30163
  this.#contentExternalizer = contentExternalizer;
@@ -31020,7 +30740,14 @@ var AgentSession = class _AgentSession {
31020
30740
  if (this.#turn.running) {
31021
30741
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
31022
30742
  }
31023
- const completedHistory = this.#capabilities.loadSession ? await this.#completedHistory(options.signal, "ACP agent exited while loading history before a prompt") : null;
30743
+ if (!this.#capabilities.loadSession && this.#sessionLoad.kind === "not-requested") {
30744
+ this.#sessionLoad = {
30745
+ kind: "loaded",
30746
+ history: new AcpHistoryReplay(this.#store.eventsV2, this.#mobiusSessionId),
30747
+ response: {}
30748
+ };
30749
+ }
30750
+ const completedHistory = this.#capabilities.loadSession ? await this.#completedHistory(options.signal, "ACP agent exited while loading history before a prompt") : this.#sessionLoad.kind === "loaded" ? this.#sessionLoad.history : null;
31024
30751
  const prompt = this.buildPrompt(options);
31025
30752
  if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
31026
30753
  this.#sessionTitle = truncate2(options.prompt, 500);
@@ -31049,11 +30776,16 @@ var AgentSession = class _AgentSession {
31049
30776
  this.#turnHistory = completedHistory === null ? null : new AcpHistoryReplay(this.#store.eventsV2, this.#mobiusSessionId);
31050
30777
  const lifecycleV2 = options.lifecycleV2;
31051
30778
  if (lifecycleV2 !== void 0) {
31052
- await this.#recordLifecycleEventV2({
31053
- payload: { commandId: options.commandId, content: lifecycleV2.content, kind: "prompt.requested" },
30779
+ await this.recordLifecycleEventV2({
30780
+ payload: {
30781
+ commandId: options.commandId,
30782
+ content: lifecycleV2.content,
30783
+ kind: "prompt.requested",
30784
+ ...lifecycleV2.context === void 0 ? {} : { context: lifecycleV2.context }
30785
+ },
31054
30786
  type: "lifecycle-metadata"
31055
30787
  });
31056
- await this.#recordLifecycleEventV2({
30788
+ await this.recordLifecycleEventV2({
31057
30789
  payload: {
31058
30790
  attemptId: lifecycleV2.attemptId,
31059
30791
  commandId: options.commandId,
@@ -31116,7 +30848,7 @@ var AgentSession = class _AgentSession {
31116
30848
  )
31117
30849
  );
31118
30850
  if (lifecycleV2 !== void 0) {
31119
- await this.#recordLifecycleEventV2({
30851
+ await this.recordLifecycleEventV2({
31120
30852
  payload: { commandId: options.commandId, kind: "prompt.completed", stopReason: result.stopReason },
31121
30853
  type: "lifecycle-metadata"
31122
30854
  });
@@ -31126,8 +30858,8 @@ var AgentSession = class _AgentSession {
31126
30858
  await running.activities.finish();
31127
30859
  const failure2 = error62 instanceof AcpExecutionError ? error62 : new AcpExecutionError("ACP agent execution failed", { cause: error62 });
31128
30860
  if (lifecycleV2 !== void 0) {
31129
- await this.#recordLifecycleEventV2({
31130
- payload: {
30861
+ await this.recordLifecycleEventV2({
30862
+ payload: options.cancellationRequested?.() === true ? { commandId: options.commandId, kind: "prompt.completed", stopReason: "cancelled" } : {
31131
30863
  attemptId: lifecycleV2.attemptId,
31132
30864
  code: failure2.code,
31133
30865
  commandId: options.commandId,
@@ -31163,11 +30895,16 @@ var AgentSession = class _AgentSession {
31163
30895
  const prompt = this.buildPrompt(options);
31164
30896
  const lifecycleV2 = options.lifecycleV2;
31165
30897
  if (lifecycleV2 !== void 0) {
31166
- await this.#recordLifecycleEventV2({
31167
- payload: { commandId: options.commandId, content: lifecycleV2.content, kind: "prompt.requested" },
30898
+ await this.recordLifecycleEventV2({
30899
+ payload: {
30900
+ commandId: options.commandId,
30901
+ content: lifecycleV2.content,
30902
+ kind: "prompt.requested",
30903
+ ...lifecycleV2.context === void 0 ? {} : { context: lifecycleV2.context }
30904
+ },
31168
30905
  type: "lifecycle-metadata"
31169
30906
  });
31170
- await this.#recordLifecycleEventV2({
30907
+ await this.recordLifecycleEventV2({
31171
30908
  payload: {
31172
30909
  attemptId: lifecycleV2.attemptId,
31173
30910
  commandId: options.commandId,
@@ -31197,7 +30934,7 @@ var AgentSession = class _AgentSession {
31197
30934
  const outcome = response["outcome"];
31198
30935
  if (outcome === "injected" || outcome === "startedNewTurn") {
31199
30936
  if (lifecycleV2 !== void 0) {
31200
- await this.#recordLifecycleEventV2({
30937
+ await this.recordLifecycleEventV2({
31201
30938
  payload: { commandId: options.commandId, kind: "prompt.completed", stopReason: "steered" },
31202
30939
  type: "lifecycle-metadata"
31203
30940
  });
@@ -31222,7 +30959,7 @@ var AgentSession = class _AgentSession {
31222
30959
  } catch (error62) {
31223
30960
  const failure2 = error62 instanceof AcpExecutionError ? error62 : new AcpExecutionError("ACP agent execution failed", { cause: error62 });
31224
30961
  if (lifecycleV2 !== void 0) {
31225
- await this.#recordLifecycleEventV2({
30962
+ await this.recordLifecycleEventV2({
31226
30963
  payload: {
31227
30964
  attemptId: lifecycleV2.attemptId,
31228
30965
  code: failure2.code,
@@ -31237,16 +30974,11 @@ var AgentSession = class _AgentSession {
31237
30974
  }
31238
30975
  };
31239
30976
  cancel = async () => {
31240
- const capturedProcesses = await this.#connection.captureProcessTree();
31241
- try {
31242
- await this.#interactions.cancelPendingInteractions();
31243
- if (this.#turn.running) {
31244
- await this.#connection.connection.agent.notify(methods3.agent.session.cancel, {
31245
- sessionId: this.#updates.sessionId()
31246
- });
31247
- }
31248
- } finally {
31249
- await this.closeProcess(capturedProcesses);
30977
+ await this.#interactions.cancelPendingInteractions();
30978
+ if (this.#turn.running) {
30979
+ await this.#connection.connection.agent.notify(methods3.agent.session.cancel, {
30980
+ sessionId: this.#updates.sessionId()
30981
+ });
31250
30982
  }
31251
30983
  };
31252
30984
  respondPermission = (options) => this.#interactions.respondPermission(options);
@@ -31255,7 +30987,14 @@ var AgentSession = class _AgentSession {
31255
30987
  onElicitation = (request, signal) => this.#interactions.onElicitation(request, signal);
31256
30988
  onElicitationComplete = (notification) => this.#interactions.onElicitationComplete(notification);
31257
30989
  onUpdate = (notification) => this.#updates.receive(notification);
31258
- #recordLifecycleEventV2 = async (event) => {
30990
+ recordControlEventV2 = async (event) => {
30991
+ if (this.#sessionLoad.kind !== "loaded") {
30992
+ return false;
30993
+ }
30994
+ await this.recordLifecycleEventV2(event);
30995
+ return true;
30996
+ };
30997
+ recordLifecycleEventV2 = async (event) => {
31259
30998
  if (event.type !== "lifecycle-metadata" || this.#sessionLoad.kind !== "loaded") {
31260
30999
  return;
31261
31000
  }
@@ -31439,7 +31178,7 @@ var AgentSession = class _AgentSession {
31439
31178
  await this.closeProcess();
31440
31179
  }
31441
31180
  };
31442
- closeProcess = (capturedProcesses = []) => this.#connection.closeProcess(capturedProcesses);
31181
+ closeProcess = () => this.#connection.closeProcess();
31443
31182
  race = (operation, exitMessage, signal) => this.#connection.race(operation, exitMessage, signal);
31444
31183
  assertNativeSession = (sessionId) => {
31445
31184
  if (sessionId !== this.#updates.sessionId()) {
@@ -32318,6 +32057,13 @@ var AgentRuntimeManager = class {
32318
32057
  this.#contentExternalizer = contentExternalizer;
32319
32058
  this.#queryProcesses = new AgentQueryProcesses(this.#processes, contentExternalizer);
32320
32059
  }
32060
+ recordLifecycleEventV2 = async (sessionId, event) => {
32061
+ const runtime = this.#executionProcesses.get(sessionId);
32062
+ if (runtime === void 0) {
32063
+ return false;
32064
+ }
32065
+ return await runtime.recordControlEventV2(event);
32066
+ };
32321
32067
  setObserver = (observer) => {
32322
32068
  this.#observer = observer;
32323
32069
  };
@@ -32573,13 +32319,7 @@ var AgentRuntimeManager = class {
32573
32319
  await this.#executions.cancel(sessionId, async () => {
32574
32320
  const runtime = this.#executionProcesses.get(sessionId);
32575
32321
  if (runtime !== void 0) {
32576
- try {
32577
- await runtime.cancel();
32578
- } finally {
32579
- if (this.#executionProcesses.detach(sessionId, runtime)) {
32580
- this.#processes.releaseClosed(runtime);
32581
- }
32582
- }
32322
+ await runtime.cancel();
32583
32323
  }
32584
32324
  });
32585
32325
  };
@@ -32647,7 +32387,10 @@ var AgentRuntimeManager = class {
32647
32387
  return { stopReason: "cancelled" };
32648
32388
  }
32649
32389
  try {
32650
- const result = await runtime.prompt(options2);
32390
+ const result = await runtime.prompt({
32391
+ ...options2,
32392
+ cancellationRequested: () => this.#executions.cancellation(options2.sessionId) !== void 0
32393
+ });
32651
32394
  return this.#executions.cancellation(options2.sessionId) !== void 0 ? { stopReason: "cancelled" } : result;
32652
32395
  } catch (error62) {
32653
32396
  if (this.#executions.cancellation(options2.sessionId) !== void 0) {
@@ -34843,14 +34586,6 @@ var CodexAcpAgent = class {
34843
34586
  if (isCompactPrompt(context.params.prompt)) {
34844
34587
  return await this.#compact(context.signal);
34845
34588
  }
34846
- const messageId = crypto.randomUUID();
34847
- for (const content of context.params.prompt) {
34848
- await this.#emit({
34849
- content,
34850
- messageId,
34851
- sessionUpdate: "user_message_chunk"
34852
- });
34853
- }
34854
34589
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
34855
34590
  }).onRequest(
34856
34591
  "_session/steering",
@@ -35336,10 +35071,6 @@ var CodexAcpAgent = class {
35336
35071
  if (steering.length === 0) {
35337
35072
  throw new AcpExecutionError("Codex received an empty steering request", {}, "invalid_request");
35338
35073
  }
35339
- const messageId = crypto.randomUUID();
35340
- for (const block of steering) {
35341
- await this.#emit({ content: block.content, messageId, sessionUpdate: "user_message_chunk" });
35342
- }
35343
35074
  const response = turnSteerResponseSchema.parse(
35344
35075
  await this.#appServer.request(
35345
35076
  "turn/steer",
@@ -35376,7 +35107,7 @@ var CodexAcpAgent = class {
35376
35107
  };
35377
35108
  #completeTurn = async (turn) => {
35378
35109
  const active = this.#turn;
35379
- if (active === null) {
35110
+ if (active === null || active.turn.id !== turn.id) {
35380
35111
  return;
35381
35112
  }
35382
35113
  await this.#updateTail;
@@ -39033,16 +38764,7 @@ function send(socket, message) {
39033
38764
  }
39034
38765
  socket.send(encodeDaemonToServiceMessage(message));
39035
38766
  }
39036
- function reportFailure(publisher, command, code, message) {
39037
- publisher.publish(command.sessionId, {
39038
- code,
39039
- commandId: command.commandId,
39040
- kind: SESSION_FAILED_KIND,
39041
- message,
39042
- sessionId: command.sessionId
39043
- });
39044
- }
39045
- function settleAbandonedTurn(publisher, operations, audit, cancellation) {
38767
+ async function settleAbandonedTurn(eventLog, operations, audit, cancellation) {
39046
38768
  const attemptId = operations.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
39047
38769
  if (attemptId === null) {
39048
38770
  console.warn("Mobius daemon ignored cancellation for an inactive turn");
@@ -39053,13 +38775,14 @@ function settleAbandonedTurn(publisher, operations, audit, cancellation) {
39053
38775
  event: "session_abandoned_turn_settled",
39054
38776
  sessionId: cancellation.sessionId
39055
38777
  });
39056
- reportFailure(
39057
- publisher,
39058
- cancellation,
38778
+ await eventLog.failed(
38779
+ cancellation.sessionId,
38780
+ cancellation.commandId,
39059
38781
  "agent_execution_abandoned",
39060
38782
  "The local Agent execution was abandoned before it completed"
39061
38783
  );
39062
38784
  operations.transitionExecution(cancellation.commandId, "failed");
38785
+ eventLog.publishTerminal(cancellation.sessionId, cancellation.commandId);
39063
38786
  }
39064
38787
  function operationErrorCode(error62) {
39065
38788
  if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof PromptArtifactError) {
@@ -42148,112 +41871,6 @@ function warnIgnoredSetting(audit, event, commandId, sessionId, agentId, selecti
42148
41871
  `);
42149
41872
  }
42150
41873
 
42151
- // src/relay-connection/coalescing-agent-event-publisher.ts
42152
- var AGENT_EVENT_COALESCING_MILLISECONDS = 100;
42153
- var AGENT_EVENT_TEXT_MAXIMUM_LENGTH = 1e5;
42154
- var CoalescingAgentEventPublisher = class {
42155
- #entries = [];
42156
- #publish;
42157
- #publishedActivityIds = /* @__PURE__ */ new Set();
42158
- #scheduled = null;
42159
- #timer;
42160
- constructor(timer, publish) {
42161
- this.#publish = publish;
42162
- this.#timer = timer;
42163
- }
42164
- flush = () => {
42165
- this.#scheduled?.cancel();
42166
- this.#scheduled = null;
42167
- const entries = this.#entries;
42168
- this.#entries = [];
42169
- for (const entry of entries) {
42170
- this.#publish(entry);
42171
- }
42172
- };
42173
- recordActivity = (activity2) => {
42174
- const latest = this.#entries.at(-1);
42175
- this.#entries = latest?.kind === "activity" && latest.activity.activityId === activity2.activityId ? [...this.#entries.slice(0, -1), { activity: activity2, kind: "activity" }] : [...this.#entries, { activity: activity2, kind: "activity" }];
42176
- const first = !this.#publishedActivityIds.has(activity2.activityId);
42177
- this.#publishedActivityIds.add(activity2.activityId);
42178
- if (first || activity2.status !== "pending" && activity2.status !== "running") {
42179
- this.flush();
42180
- } else {
42181
- this.schedule();
42182
- }
42183
- return Promise.resolve();
42184
- };
42185
- recordNarration = (increment) => {
42186
- if (increment.text.length === 0) {
42187
- return Promise.resolve();
42188
- }
42189
- let remaining = increment.text;
42190
- while (remaining.length > 0) {
42191
- const latest = this.#entries.at(-1);
42192
- if (latest?.kind === "narration" && latest.increment.activityId === increment.activityId) {
42193
- const available = AGENT_EVENT_TEXT_MAXIMUM_LENGTH - latest.increment.text.length;
42194
- if (available > 0) {
42195
- this.#entries = [
42196
- ...this.#entries.slice(0, -1),
42197
- {
42198
- increment: {
42199
- ...increment,
42200
- text: `${latest.increment.text}${remaining.slice(0, available)}`
42201
- },
42202
- kind: "narration"
42203
- }
42204
- ];
42205
- remaining = remaining.slice(available);
42206
- continue;
42207
- }
42208
- }
42209
- this.#entries = [
42210
- ...this.#entries,
42211
- {
42212
- increment: { ...increment, text: remaining.slice(0, AGENT_EVENT_TEXT_MAXIMUM_LENGTH) },
42213
- kind: "narration"
42214
- }
42215
- ];
42216
- remaining = remaining.slice(AGENT_EVENT_TEXT_MAXIMUM_LENGTH);
42217
- }
42218
- this.schedule();
42219
- return Promise.resolve();
42220
- };
42221
- recordText = (text2, messageId) => {
42222
- if (text2.length === 0) {
42223
- return Promise.resolve();
42224
- }
42225
- let remaining = text2;
42226
- while (remaining.length > 0) {
42227
- const latest = this.#entries.at(-1);
42228
- if (latest?.kind === "text" && latest.messageId === messageId) {
42229
- const available = AGENT_EVENT_TEXT_MAXIMUM_LENGTH - latest.text.length;
42230
- if (available > 0) {
42231
- this.#entries = [
42232
- ...this.#entries.slice(0, -1),
42233
- { ...latest, text: `${latest.text}${remaining.slice(0, available)}` }
42234
- ];
42235
- remaining = remaining.slice(available);
42236
- continue;
42237
- }
42238
- }
42239
- this.#entries = [
42240
- ...this.#entries,
42241
- {
42242
- kind: "text",
42243
- messageId,
42244
- text: remaining.slice(0, AGENT_EVENT_TEXT_MAXIMUM_LENGTH)
42245
- }
42246
- ];
42247
- remaining = remaining.slice(AGENT_EVENT_TEXT_MAXIMUM_LENGTH);
42248
- }
42249
- this.schedule();
42250
- return Promise.resolve();
42251
- };
42252
- schedule() {
42253
- this.#scheduled ??= this.#timer.schedule(this.flush, AGENT_EVENT_COALESCING_MILLISECONDS);
42254
- }
42255
- };
42256
-
42257
41874
  // src/daemon-prompt-executor.ts
42258
41875
  function daemonActivity(command, activity2) {
42259
41876
  return {
@@ -42276,7 +41893,6 @@ function daemonActivity(command, activity2) {
42276
41893
  }
42277
41894
  async function executePrompt({
42278
41895
  operations,
42279
- publisher,
42280
41896
  eventLogV2,
42281
41897
  command,
42282
41898
  config: config2,
@@ -42286,36 +41902,11 @@ async function executePrompt({
42286
41902
  attemptId,
42287
41903
  activateAttempt,
42288
41904
  waitForSessionAvailability,
42289
- timer,
42290
41905
  signal,
42291
- recordLiveEvent,
41906
+ recordTurnEvent,
42292
41907
  recordSteeringPrompt,
42293
41908
  cancellationRequested
42294
41909
  }) {
42295
- const events = new CoalescingAgentEventPublisher(timer, (event) => {
42296
- if (event.kind === "text") {
42297
- publisher.publish(
42298
- command.sessionId,
42299
- recordLiveEvent({ kind: AGENT_MESSAGE_DELTA_KIND, messageId: event.messageId, text: event.text })
42300
- );
42301
- return;
42302
- }
42303
- if (event.kind === "narration") {
42304
- const recorded = {
42305
- activityId: event.increment.activityId,
42306
- activityType: event.increment.activityType,
42307
- commandId: command.commandId,
42308
- kind: AGENT_ACTIVITY_NARRATION_KIND,
42309
- sequence: event.increment.sequence,
42310
- sessionId: command.sessionId,
42311
- text: event.increment.text
42312
- };
42313
- publisher.publish(command.sessionId, recordLiveEvent(recorded));
42314
- return;
42315
- }
42316
- const activity2 = daemonActivity(command, event.activity);
42317
- publisher.publish(command.sessionId, recordLiveEvent(activity2));
42318
- });
42319
41910
  try {
42320
41911
  const resolved = await resolveSessionDirectories(
42321
41912
  directories,
@@ -42383,33 +41974,6 @@ async function executePrompt({
42383
41974
  }
42384
41975
  const stream = activateAttempt();
42385
41976
  const lifecycleV2 = eventLogV2.started(command.sessionId, command.commandId, attemptId, stream.epoch);
42386
- if (!prepared.prompted) {
42387
- const listing = await directories.list(config2.bindingId, command.directoryId, signal);
42388
- publisher.publish(command.sessionId, {
42389
- additionalDirectories: resolved.additionalDirectoryEntries,
42390
- agentId: command.agentId,
42391
- agentName: prepared.agentName,
42392
- agentVersion: prepared.agentVersion,
42393
- capabilities: prepared.capabilities,
42394
- commands: prepared.commands,
42395
- configOptions: prepared.configOptions,
42396
- directoryId: command.directoryId,
42397
- directoryLabel: listing.directoryLabel,
42398
- kind: SESSION_READY_KIND,
42399
- requestId: command.commandId,
42400
- restored: prepared.restored,
42401
- sessionId: command.sessionId
42402
- });
42403
- }
42404
- publisher.publish(command.sessionId, {
42405
- commandId: command.commandId,
42406
- epoch: stream.epoch,
42407
- kind: SESSION_STARTED_KIND,
42408
- attemptId,
42409
- prompt: command.prompt,
42410
- sequence: stream.sequence,
42411
- sessionId: command.sessionId
42412
- });
42413
41977
  const attachments = await resolvePromptArtifacts(config2, command, signal);
42414
41978
  let stopReason;
42415
41979
  if (availability.disposition === SessionPromptDisposition.Steer) {
@@ -42436,9 +42000,20 @@ async function executePrompt({
42436
42000
  disposition: availability.disposition,
42437
42001
  images: attachments.images,
42438
42002
  lifecycleV2,
42439
- onActivity: events.recordActivity,
42440
- onNarration: events.recordNarration,
42441
- onText: events.recordText,
42003
+ onActivity: async (activity2) => {
42004
+ recordTurnEvent(daemonActivity(command, activity2));
42005
+ },
42006
+ onNarration: async (increment) => {
42007
+ recordTurnEvent({
42008
+ ...increment,
42009
+ commandId: command.commandId,
42010
+ sessionId: command.sessionId,
42011
+ kind: AGENT_ACTIVITY_NARRATION_KIND
42012
+ });
42013
+ },
42014
+ onText: async (text2, messageId) => {
42015
+ recordTurnEvent({ kind: AGENT_MESSAGE_DELTA_KIND, text: text2, messageId });
42016
+ },
42442
42017
  prompt: command.prompt,
42443
42018
  resources: attachments.resources,
42444
42019
  sessionId: command.sessionId,
@@ -42447,14 +42022,7 @@ async function executePrompt({
42447
42022
  });
42448
42023
  stopReason = result.stopReason;
42449
42024
  }
42450
- events.flush();
42451
- publisher.publish(command.sessionId, {
42452
- commandId: command.commandId,
42453
- kind: SESSION_COMPLETED_KIND,
42454
- sessionId: command.sessionId,
42455
- stopReason
42456
- });
42457
- eventLogV2.completed(command.sessionId, command.commandId, stopReason);
42025
+ await eventLogV2.completed(command.sessionId, command.commandId, stopReason);
42458
42026
  operations.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
42459
42027
  audit.record({
42460
42028
  commandId: command.commandId,
@@ -42462,15 +42030,8 @@ async function executePrompt({
42462
42030
  sessionId: command.sessionId
42463
42031
  });
42464
42032
  } catch (error62) {
42465
- events.flush();
42466
42033
  if (signal.aborted && cancellationRequested()) {
42467
- publisher.publish(command.sessionId, {
42468
- commandId: command.commandId,
42469
- kind: SESSION_COMPLETED_KIND,
42470
- sessionId: command.sessionId,
42471
- stopReason: "cancelled"
42472
- });
42473
- eventLogV2.completed(command.sessionId, command.commandId, "cancelled");
42034
+ await eventLogV2.completed(command.sessionId, command.commandId, "cancelled");
42474
42035
  operations.transitionExecution(command.commandId, "cancelled");
42475
42036
  audit.record({
42476
42037
  commandId: command.commandId,
@@ -42487,8 +42048,7 @@ async function executePrompt({
42487
42048
  const code = operationErrorCode(error62);
42488
42049
  const failureCode = code === "session_operation_failed" ? "agent_execution_failed" : code;
42489
42050
  const failureMessage = code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62);
42490
- eventLogV2.failed(command.sessionId, command.commandId, failureCode, failureMessage);
42491
- reportFailure(publisher, command, failureCode, failureMessage);
42051
+ await eventLogV2.failed(command.sessionId, command.commandId, failureCode, failureMessage);
42492
42052
  operations.transitionExecution(command.commandId, "failed");
42493
42053
  console.error("Mobius daemon command failed", error62);
42494
42054
  }
@@ -42516,7 +42076,7 @@ async function executeWorkspaceList(socket, command, directories, audit, signal)
42516
42076
  reportOperationFailure(socket, command.requestId, "", error62);
42517
42077
  }
42518
42078
  }
42519
- async function executeSessionPrepare(publisher, socket, command, config2, directories, audit, sessions, diagnostics, signal) {
42079
+ async function executeSessionPrepare(socket, command, config2, directories, audit, sessions, diagnostics, signal) {
42520
42080
  const metrics = new AccumulatingOperationMetrics();
42521
42081
  try {
42522
42082
  const readyEvent = await metrics.measure("prepare-total", async () => {
@@ -42566,12 +42126,6 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
42566
42126
  event: "session_configured",
42567
42127
  sessionId: command.sessionId
42568
42128
  });
42569
- publisher.publish(command.sessionId, {
42570
- configOptions,
42571
- kind: "session.config.updated",
42572
- requestId: command.requestId,
42573
- sessionId: command.sessionId
42574
- });
42575
42129
  }
42576
42130
  const event = {
42577
42131
  additionalDirectories: resolved.additionalDirectoryEntries,
@@ -42589,11 +42143,6 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
42589
42143
  sessionId: command.sessionId,
42590
42144
  runtimeTimings: metrics.snapshot()
42591
42145
  };
42592
- if (command.transient !== true) {
42593
- metrics.measureSync("readiness-commit", () => {
42594
- publisher.publish(command.sessionId, event);
42595
- });
42596
- }
42597
42146
  return event;
42598
42147
  });
42599
42148
  send(socket, {
@@ -42623,7 +42172,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
42623
42172
  reportOperationFailure(socket, command.requestId, command.sessionId, error62, metrics.snapshot());
42624
42173
  }
42625
42174
  }
42626
- async function executeSessionConfigure(publisher, socket, command, config2, directories, audit, sessions, signal) {
42175
+ async function executeSessionConfigure(socket, command, config2, directories, audit, sessions, signal) {
42627
42176
  try {
42628
42177
  const resolved = await resolveSessionDirectories(
42629
42178
  directories,
@@ -42649,7 +42198,7 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
42649
42198
  event: "session_configured",
42650
42199
  sessionId: command.sessionId
42651
42200
  });
42652
- publisher.publish(command.sessionId, {
42201
+ send(socket, {
42653
42202
  configOptions,
42654
42203
  kind: "session.config.updated",
42655
42204
  requestId: command.requestId,
@@ -42769,7 +42318,6 @@ function createDaemonCommandHandler({
42769
42318
  installations,
42770
42319
  nativeSessions,
42771
42320
  operations,
42772
- publisher,
42773
42321
  eventLogV2,
42774
42322
  externalContent,
42775
42323
  activeTurns,
@@ -42790,8 +42338,9 @@ function createDaemonCommandHandler({
42790
42338
  timer
42791
42339
  });
42792
42340
  const queueChanged = (sessionId) => {
42793
- publisher.publish(sessionId, { kind: "session.queue.changed", sessionId });
42794
- eventLogV2.queueChanged(sessionId);
42341
+ void eventLogV2.queueChanged(sessionId).catch((error62) => {
42342
+ console.error("Could not record queue change", error62);
42343
+ });
42795
42344
  };
42796
42345
  const nativeRequestHandler = createNativeSessionRequestHandler({
42797
42346
  audit,
@@ -42860,7 +42409,9 @@ function createDaemonCommandHandler({
42860
42409
  const cancellation = message;
42861
42410
  const turn2 = activeTurns.get(cancellation.commandId);
42862
42411
  if (turn2 === void 0 || !turn2.matches(cancellation)) {
42863
- settleAbandonedTurn(publisher, operations, audit, cancellation);
42412
+ void settleAbandonedTurn(eventLogV2, operations, audit, cancellation).catch((error62) => {
42413
+ console.error("Could not settle abandoned turn", error62);
42414
+ });
42864
42415
  return;
42865
42416
  }
42866
42417
  const cancellationState = turn2.requestCancellation();
@@ -42900,22 +42451,12 @@ function createDaemonCommandHandler({
42900
42451
  }
42901
42452
  if (kind === SESSION_PREPARE_KIND) {
42902
42453
  const command2 = message;
42903
- void executeSessionPrepare(
42904
- publisher,
42905
- socket,
42906
- command2,
42907
- config2,
42908
- directories,
42909
- audit,
42910
- sessions,
42911
- diagnostics,
42912
- signal
42913
- );
42454
+ void executeSessionPrepare(socket, command2, config2, directories, audit, sessions, diagnostics, signal);
42914
42455
  return;
42915
42456
  }
42916
42457
  if (kind === SESSION_CONFIGURE_KIND) {
42917
42458
  const command2 = message;
42918
- void executeSessionConfigure(publisher, socket, command2, config2, directories, audit, sessions, signal);
42459
+ void executeSessionConfigure(socket, command2, config2, directories, audit, sessions, signal);
42919
42460
  return;
42920
42461
  }
42921
42462
  if (kind === SESSION_LIST_KIND) {
@@ -43017,7 +42558,6 @@ function createDaemonCommandHandler({
43017
42558
  eventLogV2.requested(command);
43018
42559
  void executePrompt({
43019
42560
  operations,
43020
- publisher,
43021
42561
  eventLogV2,
43022
42562
  command,
43023
42563
  config: config2,
@@ -43034,15 +42574,15 @@ function createDaemonCommandHandler({
43034
42574
  sessionId: command.sessionId
43035
42575
  });
43036
42576
  }),
43037
- timer,
43038
42577
  signal: turn.signal,
43039
- recordLiveEvent: turn.recordEvent,
42578
+ recordTurnEvent: turn.recordEvent,
43040
42579
  recordSteeringPrompt: () => activeTurns.recordSteeringPrompt(command),
43041
42580
  cancellationRequested: turn.cancellationRequested
43042
42581
  }).catch((error62) => {
43043
42582
  console.error("Mobius daemon turn failed", error62);
43044
42583
  }).finally(() => {
43045
42584
  activeTurns.finish(turn);
42585
+ eventLogV2.publishTerminal(command.sessionId, command.commandId);
43046
42586
  if (command.disposition === SessionPromptDisposition.Queue) {
43047
42587
  queueChanged(command.sessionId);
43048
42588
  }
@@ -43306,7 +42846,6 @@ async function runRelayConnection({
43306
42846
  installations,
43307
42847
  nativeSessions,
43308
42848
  operations,
43309
- publisher,
43310
42849
  eventLogV2,
43311
42850
  externalContent,
43312
42851
  activeTurns,
@@ -43458,29 +42997,39 @@ async function runRelayConnection({
43458
42997
  // src/relay-connection/session-event-publisher.ts
43459
42998
  import { WebSocket as WebSocket8 } from "undici";
43460
42999
  var MAX_BUFFERED_BYTES = 32 * 1024 * 1024;
43000
+ var SESSION_EVENT_V2_BATCH_WINDOW_MILLISECONDS = 200;
43461
43001
  var DaemonSessionEventPublisher = class {
43002
+ #pendingV2Events = [];
43003
+ #pendingV2Task = null;
43462
43004
  #socket = null;
43005
+ #timer;
43006
+ constructor(timer) {
43007
+ this.#timer = timer;
43008
+ }
43463
43009
  connect = (socket) => {
43010
+ this.dropPendingV2Events();
43464
43011
  this.#socket = socket;
43465
43012
  };
43466
43013
  disconnect = (socket) => {
43467
43014
  if (this.#socket === socket) {
43468
43015
  this.#socket = null;
43016
+ this.dropPendingV2Events();
43469
43017
  }
43470
43018
  };
43471
43019
  close = () => {
43472
43020
  this.#socket = null;
43021
+ this.dropPendingV2Events();
43473
43022
  };
43474
- publish = (sessionId, event) => {
43023
+ publishOperationFailure = (sessionId, requestId, code, message) => {
43024
+ this.#send({ kind: "session.operation.failed", sessionId, requestId, code, message });
43025
+ };
43026
+ publishStatus = (event) => this.#send(event);
43027
+ #send = (message) => {
43475
43028
  const socket = this.#socket;
43476
43029
  if (socket === null || socket.readyState !== WebSocket8.OPEN) {
43477
43030
  return;
43478
43031
  }
43479
- const encoded = encodeDaemonToServiceMessage({
43480
- kind: SESSION_EVENT_KIND,
43481
- payload: encodeRecordedSessionEvent(event),
43482
- sessionId
43483
- });
43032
+ const encoded = encodeDaemonToServiceMessage(message);
43484
43033
  if (socket.bufferedAmount + Buffer.byteLength(encoded, "utf8") > MAX_BUFFERED_BYTES) {
43485
43034
  socket.close(1013, "Live event transport overloaded");
43486
43035
  return;
@@ -43490,32 +43039,35 @@ var DaemonSessionEventPublisher = class {
43490
43039
  } catch {
43491
43040
  }
43492
43041
  };
43493
- publishBatch = (sessionId, events) => {
43494
- for (const event of events) {
43495
- this.publish(sessionId, event);
43496
- }
43497
- };
43498
- publishStatus = (event) => {
43042
+ publishV2 = (event) => {
43499
43043
  const socket = this.#socket;
43500
43044
  if (socket === null || socket.readyState !== WebSocket8.OPEN) {
43501
43045
  return;
43502
43046
  }
43503
- const encoded = encodeDaemonToServiceMessage(event);
43504
- if (socket.bufferedAmount + Buffer.byteLength(encoded, "utf8") > MAX_BUFFERED_BYTES) {
43505
- socket.close(1013, "Live event transport overloaded");
43047
+ this.#pendingV2Events.push(event);
43048
+ if (this.#pendingV2Events.length >= SESSION_EVENT_V2_BATCH_MAX_SIZE) {
43049
+ this.flushV2Events(socket);
43506
43050
  return;
43507
43051
  }
43508
- try {
43509
- socket.send(encoded);
43510
- } catch {
43511
- }
43052
+ this.#pendingV2Task ??= this.#timer.schedule(
43053
+ () => this.flushV2Events(socket),
43054
+ SESSION_EVENT_V2_BATCH_WINDOW_MILLISECONDS
43055
+ );
43512
43056
  };
43513
- publishV2 = (event) => {
43514
- const socket = this.#socket;
43515
- if (socket === null || socket.readyState !== WebSocket8.OPEN) {
43057
+ dropPendingV2Events = () => {
43058
+ this.#pendingV2Task?.cancel();
43059
+ this.#pendingV2Task = null;
43060
+ this.#pendingV2Events = [];
43061
+ };
43062
+ flushV2Events = (socket) => {
43063
+ this.#pendingV2Task?.cancel();
43064
+ this.#pendingV2Task = null;
43065
+ const events = this.#pendingV2Events;
43066
+ this.#pendingV2Events = [];
43067
+ if (events.length === 0 || this.#socket !== socket || socket.readyState !== WebSocket8.OPEN) {
43516
43068
  return;
43517
43069
  }
43518
- const encoded = encodeDaemonToServiceMessage({ event, kind: SESSION_EVENT_V2_KIND });
43070
+ const encoded = encodeDaemonToServiceMessage({ events, kind: SESSION_EVENT_V2_KIND });
43519
43071
  if (socket.bufferedAmount + Buffer.byteLength(encoded, "utf8") > MAX_BUFFERED_BYTES) {
43520
43072
  socket.close(1013, "Live event transport overloaded");
43521
43073
  return;
@@ -43575,8 +43127,12 @@ function sessionEventV22(daemonGenerationId, sessionId, position, event, recorde
43575
43127
  var DaemonSessionEventLogV2 = class {
43576
43128
  daemonGenerationId;
43577
43129
  #publisher;
43130
+ #terminal = /* @__PURE__ */ new Map();
43131
+ #publications = /* @__PURE__ */ new Map();
43578
43132
  #queued = /* @__PURE__ */ new Map();
43579
- constructor(publisher, daemonGenerationId = randomUUID9()) {
43133
+ #recordLifecycle;
43134
+ constructor(publisher, recordLifecycle, daemonGenerationId = randomUUID9()) {
43135
+ this.#recordLifecycle = recordLifecycle;
43580
43136
  this.#publisher = publisher;
43581
43137
  this.daemonGenerationId = daemonGenerationId;
43582
43138
  }
@@ -43584,36 +43140,101 @@ var DaemonSessionEventLogV2 = class {
43584
43140
  this.#queued.set(command.commandId, {
43585
43141
  commandId: command.commandId,
43586
43142
  content: promptContent(command),
43143
+ context: {
43144
+ agentId: command.agentId,
43145
+ directoryId: command.directoryId,
43146
+ additionalDirectoryIds: command.additionalDirectoryIds
43147
+ },
43148
+ phase: "queued",
43587
43149
  sessionId: command.sessionId
43588
43150
  });
43589
43151
  };
43590
43152
  started = (sessionId, commandId, attemptId, epoch) => {
43591
43153
  const request = this.#queued.get(commandId);
43592
43154
  if (request?.sessionId === sessionId) {
43593
- this.#queued.delete(commandId);
43594
- return { attemptId, content: request.content, epoch };
43155
+ this.#queued.set(commandId, { ...request, phase: "running" });
43156
+ return { attemptId, content: request.content, epoch, context: request.context };
43595
43157
  }
43596
43158
  throw new Error("The executing prompt was not registered in the V2 queue");
43597
43159
  };
43598
43160
  record = (sessionId, event, position) => {
43599
- this.#publisher.publishV2(this.event(sessionId, position, event, (/* @__PURE__ */ new Date()).toISOString()));
43161
+ const recorded = this.event(sessionId, position, event, (/* @__PURE__ */ new Date()).toISOString());
43162
+ if (event.type === "lifecycle-metadata" && (event.payload.kind === "prompt.completed" || event.payload.kind === "prompt.failed" || event.payload.kind === "prompt.failed-before-start")) {
43163
+ this.#terminal.set(event.payload.commandId, recorded);
43164
+ const pending2 = this.#publications.get(sessionId) ?? [];
43165
+ pending2.push(recorded);
43166
+ this.#publications.set(sessionId, pending2);
43167
+ return;
43168
+ }
43169
+ const pending = this.#publications.get(sessionId);
43170
+ if (pending !== void 0) {
43171
+ pending.push(recorded);
43172
+ } else {
43173
+ this.#publisher.publishV2(recorded);
43174
+ }
43175
+ };
43176
+ publishTerminal = (sessionId, commandId) => {
43177
+ const event = this.#terminal.get(commandId);
43178
+ if (event?.sessionId === sessionId) {
43179
+ this.#terminal.delete(commandId);
43180
+ const pending = this.#publications.get(sessionId) ?? [];
43181
+ while (pending.length > 0) {
43182
+ const next = pending[0];
43183
+ if (next === void 0) {
43184
+ break;
43185
+ }
43186
+ if (next.type === "lifecycle-metadata" && "commandId" in next.payload && this.#terminal.has(next.payload.commandId)) {
43187
+ break;
43188
+ }
43189
+ pending.shift();
43190
+ this.#publisher.publishV2(next);
43191
+ }
43192
+ if (pending.length === 0) {
43193
+ this.#publications.delete(sessionId);
43194
+ }
43195
+ }
43196
+ this.#queued.delete(commandId);
43600
43197
  };
43601
43198
  event = (sessionId, position, event, recordedAt) => sessionEventV22(this.daemonGenerationId, sessionId, position, event, recordedAt);
43602
- queueChanged = (_sessionId) => void 0;
43603
- completed = (sessionId, commandId, _stopReason) => {
43199
+ queueChanged = async (sessionId) => {
43200
+ await this.#recordLifecycle(sessionId, {
43201
+ type: "lifecycle-metadata",
43202
+ payload: { kind: "session.queue.changed" }
43203
+ });
43204
+ };
43205
+ completed = async (sessionId, commandId, stopReason) => {
43604
43206
  const request = this.#queued.get(commandId);
43605
- if (request?.sessionId === sessionId) {
43606
- this.#queued.delete(commandId);
43207
+ if (request?.sessionId !== sessionId || this.#terminal.has(commandId)) {
43208
+ return;
43209
+ }
43210
+ const recorded = await this.#recordLifecycle(sessionId, {
43211
+ type: "lifecycle-metadata",
43212
+ payload: { kind: "prompt.completed", commandId, stopReason }
43213
+ });
43214
+ if (!recorded) {
43215
+ this.#publisher.publishOperationFailure(
43216
+ sessionId,
43217
+ commandId,
43218
+ "cancelled",
43219
+ "The prompt was cancelled before execution"
43220
+ );
43607
43221
  }
43608
43222
  };
43609
- failed = (sessionId, commandId, _code, _message) => {
43223
+ failed = async (sessionId, commandId, code, message) => {
43610
43224
  const request = this.#queued.get(commandId);
43611
- if (request?.sessionId === sessionId) {
43612
- this.#queued.delete(commandId);
43225
+ if (request?.sessionId !== sessionId || this.#terminal.has(commandId)) {
43226
+ return;
43227
+ }
43228
+ const recorded = await this.#recordLifecycle(sessionId, {
43229
+ type: "lifecycle-metadata",
43230
+ payload: { kind: "prompt.failed-before-start", commandId, code, message }
43231
+ });
43232
+ if (!recorded) {
43233
+ this.#publisher.publishOperationFailure(sessionId, commandId, code, message);
43613
43234
  }
43614
43235
  };
43615
43236
  promptRequestRecovery = (sessionId) => ({
43616
- queuedPromptRequests: [...this.#queued.values()].filter((request) => request.sessionId === sessionId).map(({ commandId, content }) => ({ commandId, content }))
43237
+ queuedPromptRequests: [...this.#queued.values()].filter((request) => request.sessionId === sessionId && request.phase === "queued").map(({ commandId, content }) => ({ commandId, content }))
43617
43238
  });
43618
43239
  };
43619
43240
 
@@ -43699,14 +43320,17 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43699
43320
  const sessionStore = new SqliteAcpSessionStore(sessionDatabase, eventsV2);
43700
43321
  await using externalContent = new LocalExternalContentStore(stateDirectory);
43701
43322
  const operations = new DaemonOperationState();
43702
- const publisher = new DaemonSessionEventPublisher();
43703
- const eventLogV2 = new DaemonSessionEventLogV2(publisher, daemonGenerationId);
43323
+ const publisher = new DaemonSessionEventPublisher(timer);
43324
+ const eventLogV2 = new DaemonSessionEventLogV2(
43325
+ publisher,
43326
+ (sessionId, event) => agentRuntime.recordLifecycleEventV2(sessionId, event),
43327
+ daemonGenerationId
43328
+ );
43704
43329
  const activeTurns = new DaemonTurnRegistry(operations);
43705
- const recordSessionEvent = (sessionId, event) => {
43706
- publisher.publish(sessionId, activeTurns.recordEvent(event));
43707
- };
43708
43330
  const agentRuntime = new AgentRuntimeManager(
43709
- new DaemonAcpObserver(recordSessionEvent, eventLogV2.record),
43331
+ new DaemonAcpObserver((_sessionId, event) => {
43332
+ activeTurns.recordEvent(event);
43333
+ }, eventLogV2.record),
43710
43334
  sessionStore,
43711
43335
  {
43712
43336
  read: async (options2, nativeSessionId, nativeTurn) => options2.agent.id === "codex" ? (await readCodexFullHistory(