@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/runtime.js CHANGED
@@ -20342,8 +20342,6 @@ function decodeValue(value, schema) {
20342
20342
  }
20343
20343
  return result.data;
20344
20344
  }
20345
- var decodeAgentDisplayContentValue = (value) => decodeValue(value, displayContentSchema);
20346
- var decodeRecordedAgentContentValue = (value) => decodeValue(value, recordedDisplayContentSchema);
20347
20345
  var decodePromptImagesValue = (value) => decodeValue(value, external_exports.array(promptImageSchema).max(8).readonly());
20348
20346
  var decodePromptResourcesValue = (value) => decodeValue(value, external_exports.array(promptResourceSchema).max(16).readonly());
20349
20347
  var decodeSessionConfigurationSelections = (value) => decodeValue(value, sessionConfigurationSelectionsSchema);
@@ -20385,20 +20383,13 @@ var encodeSessionReadyEvent = (message) => encode3(message, sessionReadyEventSch
20385
20383
  var decodeSessionConfigureCommand = (encoded) => decode3(encoded, sessionConfigureCommandSchema);
20386
20384
  var encodeSessionConfigureCommand = (message) => encode3(message, sessionConfigureCommandSchema);
20387
20385
  var decodeSessionConfigUpdatedEvent = (encoded) => decode3(encoded, sessionConfigUpdatedEventSchema);
20388
- var decodeSessionUsageUpdatedEvent = (encoded) => decode3(encoded, sessionUsageUpdatedEventSchema);
20389
- var decodeSessionCommandsUpdatedEvent = (encoded) => decode3(encoded, sessionCommandsUpdatedEventSchema);
20390
- var decodeSessionInfoUpdatedEvent = (encoded) => decode3(encoded, sessionInfoUpdatedEventSchema);
20391
- var decodeSessionPermissionRequestedEvent = (encoded) => decode3(encoded, sessionPermissionRequestedEventSchema);
20386
+ var encodeSessionConfigUpdatedEvent = (message) => encode3(message, sessionConfigUpdatedEventSchema);
20392
20387
  var decodeSessionPermissionRespondCommand = (encoded) => decode3(encoded, sessionPermissionRespondCommandSchema);
20393
20388
  var encodeSessionPermissionRespondCommand = (message) => encode3(message, sessionPermissionRespondCommandSchema);
20394
- var decodeSessionPermissionResolvedEvent = (encoded) => decode3(encoded, sessionPermissionResolvedEventSchema);
20395
- var decodeSessionElicitationRequestedEvent = (encoded) => decode3(encoded, sessionElicitationRequestedEventSchema);
20396
20389
  var decodeSessionElicitationRespondCommand = (encoded) => decode3(encoded, sessionElicitationRespondCommandSchema);
20397
20390
  var encodeSessionElicitationRespondCommand = (message) => encode3(message, sessionElicitationRespondCommandSchema);
20398
- var decodeSessionElicitationResolvedEvent = (encoded) => decode3(encoded, sessionElicitationResolvedEventSchema);
20399
20391
  var decodeSessionOperationFailedEvent = (encoded) => decode3(encoded, sessionOperationFailedEventSchema);
20400
20392
  var encodeSessionOperationFailedEvent = (message) => encode3(message, sessionOperationFailedEventSchema);
20401
- var decodeAgentContentEvent = (encoded) => decode3(encoded, agentContentEventSchema);
20402
20393
  var decodeAgentInstallRequestCommand = (encoded) => decode3(encoded, agentInstallRequestCommandSchema);
20403
20394
  var encodeAgentInstallRequestCommand = (message) => encode3(message, agentInstallRequestCommandSchema);
20404
20395
  var decodeAgentInstallCancelCommand = (encoded) => decode3(encoded, agentInstallCancelCommandSchema);
@@ -20424,7 +20415,6 @@ var RUNTIME_HEARTBEAT_KIND = "runtime.heartbeat";
20424
20415
  var RUNTIME_HEARTBEAT_ACK_KIND = "runtime.heartbeat.ack";
20425
20416
  var RUNTIME_PING_KIND = "runtime.ping";
20426
20417
  var RUNTIME_PONG_KIND = "runtime.pong";
20427
- var SESSION_STARTED_KIND = "session.started";
20428
20418
  var SESSION_QUEUED_KIND = "session.queued";
20429
20419
  var AGENT_MESSAGE_DELTA_KIND = "agent.message.delta";
20430
20420
  var AGENT_ACTIVITY_KIND = "agent.activity";
@@ -20434,8 +20424,6 @@ var AGENT_ACTIVITY_RECORDED_FIELD_LIMIT = 4e6;
20434
20424
  var AGENT_ACTIVITY_RECORDED_DETAIL_LIMIT = 6e6;
20435
20425
  var AGENT_ACTIVITY_LOCATION_LIMIT = 12;
20436
20426
  var AGENT_ACTIVITY_LOCATION_LENGTH_LIMIT = 1024;
20437
- var SESSION_COMPLETED_KIND = "session.completed";
20438
- var SESSION_FAILED_KIND = "session.failed";
20439
20427
  var SessionPromptDisposition = Object.freeze({
20440
20428
  Queue: "queue",
20441
20429
  Reject: "reject",
@@ -20446,23 +20434,6 @@ var SessionPromptDisposition = Object.freeze({
20446
20434
  var DIRECTORY_IDENTIFIER_PATTERN2 = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/;
20447
20435
  var MAX_PROMPT_LENGTH = 1e4;
20448
20436
  var MAX_PROMPT_ATTACHMENT_LENGTH = 6e6;
20449
- var MAX_EVENT_TEXT_LENGTH = 1e5;
20450
- var ACTIVITY_TYPES = /* @__PURE__ */ new Set(["notice", "plan", "progress", "reasoning", "tool"]);
20451
- var NARRATION_ACTIVITY_TYPES = /* @__PURE__ */ new Set(["progress", "reasoning"]);
20452
- var ACTIVITY_STATUSES = /* @__PURE__ */ new Set(["pending", "running", "completed", "failed"]);
20453
- var TOOL_KINDS = /* @__PURE__ */ new Set([
20454
- "",
20455
- "delete",
20456
- "edit",
20457
- "execute",
20458
- "fetch",
20459
- "move",
20460
- "other",
20461
- "read",
20462
- "search",
20463
- "switch_mode",
20464
- "think"
20465
- ]);
20466
20437
  var ProtocolMessageError = class extends Error {
20467
20438
  code = "invalid_protocol_message";
20468
20439
  constructor(message, options = {}) {
@@ -20512,13 +20483,6 @@ function readText(value, key, maximumLength) {
20512
20483
  }
20513
20484
  return field;
20514
20485
  }
20515
- function readAllowedString(value, key, allowedValues) {
20516
- const field = readText(value, key, 64);
20517
- if (!allowedValues.has(field)) {
20518
- throw new ProtocolMessageError(`Invalid value field: ${key}`);
20519
- }
20520
- return field;
20521
- }
20522
20486
  function readPromptDisposition(value) {
20523
20487
  const field = value["disposition"];
20524
20488
  if (field === void 0 || field === SessionPromptDisposition.Reject) {
@@ -20532,32 +20496,6 @@ function readPromptDisposition(value) {
20532
20496
  }
20533
20497
  throw new ProtocolMessageError("Invalid value field: disposition");
20534
20498
  }
20535
- function readSequence(value, key) {
20536
- const field = value[key];
20537
- if (typeof field !== "number" || !Number.isSafeInteger(field) || field < 0) {
20538
- throw new ProtocolMessageError(`Invalid integer field: ${key}`);
20539
- }
20540
- return field;
20541
- }
20542
- function readLocations(value) {
20543
- const field = value["locations"];
20544
- if (!Array.isArray(field) || field.length > AGENT_ACTIVITY_LOCATION_LIMIT) {
20545
- throw new ProtocolMessageError("Invalid locations field");
20546
- }
20547
- const locations = [];
20548
- const unique = /* @__PURE__ */ new Set();
20549
- for (const location of field) {
20550
- if (typeof location !== "string" || location.length === 0 || location.length > AGENT_ACTIVITY_LOCATION_LENGTH_LIMIT) {
20551
- throw new ProtocolMessageError("Invalid activity location");
20552
- }
20553
- if (unique.has(location)) {
20554
- throw new ProtocolMessageError("Duplicate activity location");
20555
- }
20556
- unique.add(location);
20557
- locations.push(location);
20558
- }
20559
- return locations;
20560
- }
20561
20499
  function readDirectoryIdentifiers(value, key, maximumCount) {
20562
20500
  const field = value[key];
20563
20501
  if (!Array.isArray(field) || field.length > maximumCount) {
@@ -20574,54 +20512,6 @@ function readDirectoryIdentifiers(value, key, maximumCount) {
20574
20512
  }
20575
20513
  return identifiers;
20576
20514
  }
20577
- function readActivityContent(value) {
20578
- const field = value["content"];
20579
- if (!Array.isArray(field) || field.length > 100) {
20580
- throw new ProtocolMessageError("Invalid activity content field");
20581
- }
20582
- return field.map((entry) => decodeAgentDisplayContentValue(entry));
20583
- }
20584
- function readActivityDetail(value) {
20585
- const field = value["detail"];
20586
- if (!isRecord(field)) {
20587
- throw new ProtocolMessageError("Invalid activity detail field");
20588
- }
20589
- const kind = readString(field, "kind", 32);
20590
- if (kind === "available") {
20591
- return {
20592
- artifactId: readIdentifier(field, "artifactId"),
20593
- kind
20594
- };
20595
- }
20596
- if (kind === "unrecorded") {
20597
- return { kind };
20598
- }
20599
- if (kind === "truncated") {
20600
- const capturedBytes = readSequence(field, "capturedBytes");
20601
- const originalBytes = readSequence(field, "originalBytes");
20602
- if (capturedBytes > originalBytes) {
20603
- throw new ProtocolMessageError("Invalid truncated activity detail size");
20604
- }
20605
- return { capturedBytes, kind, originalBytes };
20606
- }
20607
- if (kind === "recorded") {
20608
- const contentValue = field["content"];
20609
- if (!Array.isArray(contentValue) || contentValue.length > 100) {
20610
- throw new ProtocolMessageError("Invalid recorded activity content");
20611
- }
20612
- const detail = {
20613
- content: contentValue.map((entry) => decodeRecordedAgentContentValue(entry)),
20614
- input: readText(field, "input", AGENT_ACTIVITY_RECORDED_FIELD_LIMIT),
20615
- kind,
20616
- output: readText(field, "output", AGENT_ACTIVITY_RECORDED_FIELD_LIMIT)
20617
- };
20618
- if (JSON.stringify(detail).length > AGENT_ACTIVITY_RECORDED_DETAIL_LIMIT) {
20619
- throw new ProtocolMessageError("Recorded activity detail is too large");
20620
- }
20621
- return detail;
20622
- }
20623
- throw new ProtocolMessageError("Invalid activity detail availability");
20624
- }
20625
20515
  function readIdentifier(value, key) {
20626
20516
  try {
20627
20517
  return decodeIdentifier(value[key]);
@@ -20746,82 +20636,6 @@ function decodeRuntimePongEvent(encoded) {
20746
20636
  assertKind(value, RUNTIME_PONG_KIND);
20747
20637
  return { kind: RUNTIME_PONG_KIND, requestId: readIdentifier(value, "requestId") };
20748
20638
  }
20749
- function decodeSessionStartedEvent(encoded) {
20750
- const value = parseJson2(encoded);
20751
- assertKind(value, SESSION_STARTED_KIND);
20752
- const sequence = readSequence(value, "sequence");
20753
- if (sequence !== 0) {
20754
- throw new ProtocolMessageError("Invalid live start sequence");
20755
- }
20756
- return {
20757
- commandId: readIdentifier(value, "commandId"),
20758
- epoch: readIdentifier(value, "epoch"),
20759
- kind: SESSION_STARTED_KIND,
20760
- attemptId: readIdentifier(value, "attemptId"),
20761
- prompt: readText(value, "prompt", MAX_PROMPT_LENGTH),
20762
- sequence,
20763
- sessionId: readIdentifier(value, "sessionId")
20764
- };
20765
- }
20766
- function decodeAgentMessageDeltaEvent(encoded) {
20767
- const value = parseJson2(encoded);
20768
- assertKind(value, AGENT_MESSAGE_DELTA_KIND);
20769
- const sequence = readSequence(value, "sequence");
20770
- if (sequence === 0) {
20771
- throw new ProtocolMessageError("Invalid live sequence");
20772
- }
20773
- return {
20774
- commandId: readIdentifier(value, "commandId"),
20775
- epoch: readIdentifier(value, "epoch"),
20776
- kind: AGENT_MESSAGE_DELTA_KIND,
20777
- messageId: value["messageId"] === void 0 ? "" : readText(value, "messageId", 255),
20778
- sequence,
20779
- sessionId: readIdentifier(value, "sessionId"),
20780
- text: readString(value, "text", MAX_EVENT_TEXT_LENGTH)
20781
- };
20782
- }
20783
- function decodeAgentActivityEvent(encoded) {
20784
- const value = parseJson2(encoded);
20785
- assertKind(value, AGENT_ACTIVITY_KIND);
20786
- return {
20787
- activityId: readIdentifier(value, "activityId"),
20788
- activityType: readAllowedString(value, "activityType", ACTIVITY_TYPES),
20789
- commandId: readIdentifier(value, "commandId"),
20790
- content: readActivityContent(value),
20791
- detail: readActivityDetail(value),
20792
- input: readText(value, "input", AGENT_ACTIVITY_DETAIL_LIMIT),
20793
- kind: AGENT_ACTIVITY_KIND,
20794
- locations: readLocations(value),
20795
- name: readText(value, "name", 128),
20796
- output: readText(value, "output", AGENT_ACTIVITY_DETAIL_LIMIT),
20797
- sequence: readSequence(value, "sequence"),
20798
- sessionId: readIdentifier(value, "sessionId"),
20799
- status: readAllowedString(value, "status", ACTIVITY_STATUSES),
20800
- title: readString(value, "title", 500),
20801
- toolKind: readAllowedString(value, "toolKind", TOOL_KINDS)
20802
- };
20803
- }
20804
- function decodeSessionCompletedEvent(encoded) {
20805
- const value = parseJson2(encoded);
20806
- assertKind(value, SESSION_COMPLETED_KIND);
20807
- return {
20808
- commandId: readIdentifier(value, "commandId"),
20809
- kind: SESSION_COMPLETED_KIND,
20810
- sessionId: readIdentifier(value, "sessionId"),
20811
- stopReason: readString(value, "stopReason", 64)
20812
- };
20813
- }
20814
- function decodeSessionFailedEvent(encoded) {
20815
- const value = parseJson2(encoded);
20816
- assertKind(value, SESSION_FAILED_KIND);
20817
- return {
20818
- code: readIdentifier(value, "code"),
20819
- commandId: readIdentifier(value, "commandId"),
20820
- kind: SESSION_FAILED_KIND,
20821
- message: readString(value, "message", 500),
20822
- sessionId: readIdentifier(value, "sessionId")
20823
- };
20824
- }
20825
20639
  function encodeSessionPromptCommand(message) {
20826
20640
  return JSON.stringify(decodeSessionPromptCommand(JSON.stringify(message)));
20827
20641
  }
@@ -20849,19 +20663,6 @@ function encodeRuntimePingCommand(message) {
20849
20663
  function encodeRuntimePongEvent(message) {
20850
20664
  return JSON.stringify(decodeRuntimePongEvent(JSON.stringify(message)));
20851
20665
  }
20852
- function decodeAgentActivityNarrationEvent(encoded) {
20853
- const value = parseJson2(encoded);
20854
- assertKind(value, AGENT_ACTIVITY_NARRATION_KIND);
20855
- return {
20856
- activityId: readIdentifier(value, "activityId"),
20857
- activityType: readAllowedString(value, "activityType", NARRATION_ACTIVITY_TYPES),
20858
- commandId: readIdentifier(value, "commandId"),
20859
- kind: AGENT_ACTIVITY_NARRATION_KIND,
20860
- sequence: readSequence(value, "sequence"),
20861
- sessionId: readIdentifier(value, "sessionId"),
20862
- text: readText(value, "text", MAX_EVENT_TEXT_LENGTH)
20863
- };
20864
- }
20865
20666
 
20866
20667
  // ../protocol/src/session-history.ts
20867
20668
  var SESSION_HISTORY_CHARACTER_LIMIT = 256e3;
@@ -21127,6 +20928,7 @@ var MAX_CONTENT_LENGTH = 1e6;
21127
20928
  var MAX_JSON_DEPTH = 16;
21128
20929
  var MAX_JSON_KEYS = 1e3;
21129
20930
  var SESSION_EVENT_V2_KIND = "session.event.v2";
20931
+ var SESSION_EVENT_V2_BATCH_MAX_SIZE = 1e3;
21130
20932
  var boundedString = external_exports.string().max(MAX_CONTENT_LENGTH);
21131
20933
  var shortString = external_exports.string().max(2048);
21132
20934
  var externalContentKeySchema = external_exports.string().regex(/^[a-f0-9]{64}$/u);
@@ -21430,6 +21232,11 @@ var acpSessionUpdateV2Schema = external_exports.discriminatedUnion("sessionUpdat
21430
21232
  }).readonly()
21431
21233
  ]);
21432
21234
  var lifecycleBase = { commandId: identifierStringSchema };
21235
+ var promptExecutionContextV2Schema = external_exports.object({
21236
+ agentId: identifierStringSchema,
21237
+ directoryId: shortString,
21238
+ additionalDirectoryIds: external_exports.array(identifierStringSchema).max(16).readonly()
21239
+ }).readonly();
21433
21240
  var lifecycleMetadataV2Schema = external_exports.discriminatedUnion("kind", [
21434
21241
  external_exports.object({ kind: external_exports.literal("session.queue.changed") }).readonly(),
21435
21242
  external_exports.object({ event: sessionPermissionRequestedEventSchema, kind: external_exports.literal("session.permission.requested") }).readonly(),
@@ -21439,7 +21246,8 @@ var lifecycleMetadataV2Schema = external_exports.discriminatedUnion("kind", [
21439
21246
  external_exports.object({
21440
21247
  ...lifecycleBase,
21441
21248
  content: external_exports.array(contentBlockV2Schema).min(1).max(100).readonly(),
21442
- kind: external_exports.literal("prompt.requested")
21249
+ kind: external_exports.literal("prompt.requested"),
21250
+ context: promptExecutionContextV2Schema.optional()
21443
21251
  }).readonly(),
21444
21252
  external_exports.object({ ...lifecycleBase, attemptId: identifierStringSchema, epoch: identifierStringSchema, kind: external_exports.literal("prompt.started") }).readonly(),
21445
21253
  external_exports.object({ ...lifecycleBase, kind: external_exports.literal("prompt.completed"), stopReason: shortString }).readonly(),
@@ -21492,6 +21300,7 @@ var sessionEventV2Schema = external_exports.discriminatedUnion("type", [
21492
21300
  type: external_exports.literal("lifecycle-metadata")
21493
21301
  }).readonly()
21494
21302
  ]);
21303
+ var sessionEventBatchV2Schema = external_exports.array(sessionEventV2Schema).min(1).max(SESSION_EVENT_V2_BATCH_MAX_SIZE).readonly();
21495
21304
  var sessionExportV2Schema = external_exports.object({
21496
21305
  binding: external_exports.object({
21497
21306
  bindingId: identifierStringSchema,
@@ -21534,7 +21343,7 @@ var mobiusSessionExportV2Schema = external_exports.object({
21534
21343
  formatVersion: external_exports.literal("2"),
21535
21344
  session: sessionExportV2Schema
21536
21345
  }).readonly();
21537
- var sessionEventEnvelopeV2Schema = external_exports.object({ event: sessionEventV2Schema, kind: external_exports.literal(SESSION_EVENT_V2_KIND) }).readonly();
21346
+ var sessionEventEnvelopeV2Schema = external_exports.object({ events: sessionEventBatchV2Schema, kind: external_exports.literal(SESSION_EVENT_V2_KIND) }).readonly();
21538
21347
  var sessionEventLogPageV2Schema = external_exports.object({
21539
21348
  daemonGenerationId: identifierStringSchema,
21540
21349
  events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
@@ -21579,94 +21388,6 @@ var decodeSessionEventEnvelopeV2 = (value) => decode5(value, sessionEventEnvelop
21579
21388
  var encodeSessionEventEnvelopeV2 = (value) => encode4(value, sessionEventEnvelopeV2Schema);
21580
21389
  var decodeAcpSessionUpdateV2 = (value) => decode5(value, acpSessionUpdateV2Schema);
21581
21390
 
21582
- // ../protocol/src/session-events.ts
21583
- var SESSION_EVENT_KIND = "session.event";
21584
- var SESSION_FORKED_KIND = "session.forked";
21585
- var MAX_RECORDED_EVENT_LENGTH = 8 * 1024 * 1024;
21586
- var sessionEventEnvelopeSchema = external_exports.object({
21587
- kind: external_exports.literal(SESSION_EVENT_KIND),
21588
- payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
21589
- sessionId: identifierStringSchema
21590
- }).readonly();
21591
- var SESSION_QUEUE_CHANGED_KIND = "session.queue.changed";
21592
- var sessionQueueChangedSchema = external_exports.object({ kind: external_exports.literal(SESSION_QUEUE_CHANGED_KIND), sessionId: identifierStringSchema }).readonly();
21593
- var sessionForkedSchema = external_exports.object({
21594
- kind: external_exports.literal(SESSION_FORKED_KIND),
21595
- sessionId: identifierStringSchema,
21596
- sourceSessionId: identifierStringSchema,
21597
- throughCommandId: identifierStringSchema
21598
- }).readonly();
21599
- function decode6(encoded, schema) {
21600
- let value;
21601
- try {
21602
- value = JSON.parse(encoded);
21603
- } catch (cause) {
21604
- throw new ProtocolMessageError("Message is not valid JSON", { cause });
21605
- }
21606
- const decoded = schema.safeParse(value);
21607
- if (!decoded.success) {
21608
- throw new ProtocolMessageError("Message does not match its schema", {
21609
- cause: decoded.error
21610
- });
21611
- }
21612
- return decoded.data;
21613
- }
21614
- var encode5 = (message, schema) => {
21615
- const decoded = schema.safeParse(message);
21616
- if (!decoded.success) {
21617
- throw new ProtocolMessageError("Message does not match its schema", {
21618
- cause: decoded.error
21619
- });
21620
- }
21621
- return JSON.stringify(decoded.data);
21622
- };
21623
- var decodeSessionEventEnvelope = (encoded) => decode6(encoded, sessionEventEnvelopeSchema);
21624
- var encodeSessionEventEnvelope = (message) => encode5(message, sessionEventEnvelopeSchema);
21625
- function decodeRecordedSessionEvent(encoded) {
21626
- const kind = decodeMessageKind(encoded);
21627
- switch (kind) {
21628
- case SESSION_QUEUE_CHANGED_KIND:
21629
- return decode6(encoded, sessionQueueChangedSchema);
21630
- case SESSION_FORKED_KIND:
21631
- return decode6(encoded, sessionForkedSchema);
21632
- case AGENT_ACTIVITY_KIND:
21633
- return decodeAgentActivityEvent(encoded);
21634
- case AGENT_ACTIVITY_NARRATION_KIND:
21635
- return decodeAgentActivityNarrationEvent(encoded);
21636
- case AGENT_CONTENT_KIND:
21637
- return decodeAgentContentEvent(encoded);
21638
- case AGENT_MESSAGE_DELTA_KIND:
21639
- return decodeAgentMessageDeltaEvent(encoded);
21640
- case SESSION_COMMANDS_UPDATED_KIND:
21641
- return decodeSessionCommandsUpdatedEvent(encoded);
21642
- case SESSION_COMPLETED_KIND:
21643
- return decodeSessionCompletedEvent(encoded);
21644
- case SESSION_CONFIG_UPDATED_KIND:
21645
- return decodeSessionConfigUpdatedEvent(encoded);
21646
- case SESSION_ELICITATION_REQUESTED_KIND:
21647
- return decodeSessionElicitationRequestedEvent(encoded);
21648
- case SESSION_ELICITATION_RESOLVED_KIND:
21649
- return decodeSessionElicitationResolvedEvent(encoded);
21650
- case SESSION_FAILED_KIND:
21651
- return decodeSessionFailedEvent(encoded);
21652
- case SESSION_INFO_UPDATED_KIND:
21653
- return decodeSessionInfoUpdatedEvent(encoded);
21654
- case SESSION_PERMISSION_REQUESTED_KIND:
21655
- return decodeSessionPermissionRequestedEvent(encoded);
21656
- case SESSION_PERMISSION_RESOLVED_KIND:
21657
- return decodeSessionPermissionResolvedEvent(encoded);
21658
- case SESSION_READY_KIND:
21659
- return decodeSessionReadyEvent(encoded);
21660
- case SESSION_STARTED_KIND:
21661
- return decodeSessionStartedEvent(encoded);
21662
- case SESSION_USAGE_UPDATED_KIND:
21663
- return decodeSessionUsageUpdatedEvent(encoded);
21664
- default:
21665
- throw new UnsupportedProtocolMessageKindError("daemon-to-service", kind);
21666
- }
21667
- }
21668
- var encodeRecordedSessionEvent = (event) => JSON.stringify(decodeRecordedSessionEvent(JSON.stringify(event)));
21669
-
21670
21391
  // ../protocol/src/session-live-history.ts
21671
21392
  var SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND = "session.live-history.v2.page.load";
21672
21393
  var SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND = "session.live-history.v2.page.loaded";
@@ -21688,7 +21409,7 @@ var sessionLiveHistoryV2PageLoadedSchema = external_exports.object({
21688
21409
  requestId: identifierStringSchema,
21689
21410
  sessionId: identifierStringSchema
21690
21411
  }).readonly();
21691
- function decode7(schema, encoded) {
21412
+ function decode6(schema, encoded) {
21692
21413
  try {
21693
21414
  const value = JSON.parse(encoded);
21694
21415
  return schema.parse(value);
@@ -21696,8 +21417,8 @@ function decode7(schema, encoded) {
21696
21417
  throw new ProtocolMessageError("Invalid live Session history message", { cause });
21697
21418
  }
21698
21419
  }
21699
- var decodeSessionLiveHistoryV2PageLoad = (encoded) => decode7(sessionLiveHistoryV2PageLoadSchema, encoded);
21700
- var decodeSessionLiveHistoryV2PageLoaded = (encoded) => decode7(sessionLiveHistoryV2PageLoadedSchema, encoded);
21420
+ var decodeSessionLiveHistoryV2PageLoad = (encoded) => decode6(sessionLiveHistoryV2PageLoadSchema, encoded);
21421
+ var decodeSessionLiveHistoryV2PageLoaded = (encoded) => decode6(sessionLiveHistoryV2PageLoadedSchema, encoded);
21701
21422
  var encodeSessionLiveHistoryV2PageLoad = (value) => JSON.stringify(sessionLiveHistoryV2PageLoadSchema.parse(value));
21702
21423
  var encodeSessionLiveHistoryV2PageLoaded = (value) => JSON.stringify(sessionLiveHistoryV2PageLoadedSchema.parse(value));
21703
21424
 
@@ -21811,6 +21532,11 @@ function decodeServiceToDaemonMessage(encoded) {
21811
21532
  return signature.decoder(encoded);
21812
21533
  }
21813
21534
  var daemonToServiceSignatures = {
21535
+ [SESSION_CONFIG_UPDATED_KIND]: defineMessageSignature(
21536
+ SESSION_CONFIG_UPDATED_KIND,
21537
+ encodeSessionConfigUpdatedEvent,
21538
+ decodeSessionConfigUpdatedEvent
21539
+ ),
21814
21540
  [AGENT_INSTALL_CANCELLED_KIND]: defineMessageSignature(
21815
21541
  AGENT_INSTALL_CANCELLED_KIND,
21816
21542
  encodeAgentInstallCancelledEvent,
@@ -21881,11 +21607,6 @@ var daemonToServiceSignatures = {
21881
21607
  decodeRuntimeHeartbeatEvent
21882
21608
  ),
21883
21609
  [RUNTIME_PONG_KIND]: defineMessageSignature(RUNTIME_PONG_KIND, encodeRuntimePongEvent, decodeRuntimePongEvent),
21884
- [SESSION_EVENT_KIND]: defineMessageSignature(
21885
- SESSION_EVENT_KIND,
21886
- encodeSessionEventEnvelope,
21887
- decodeSessionEventEnvelope
21888
- ),
21889
21610
  [SESSION_EVENT_V2_KIND]: defineMessageSignature(
21890
21611
  SESSION_EVENT_V2_KIND,
21891
21612
  encodeSessionEventEnvelopeV2,
@@ -24626,14 +24347,6 @@ var CodexAcpAgent = class {
24626
24347
  if (isCompactPrompt(context.params.prompt)) {
24627
24348
  return await this.#compact(context.signal);
24628
24349
  }
24629
- const messageId = crypto.randomUUID();
24630
- for (const content of context.params.prompt) {
24631
- await this.#emit({
24632
- content,
24633
- messageId,
24634
- sessionUpdate: "user_message_chunk"
24635
- });
24636
- }
24637
24350
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
24638
24351
  }).onRequest(
24639
24352
  "_session/steering",
@@ -25119,10 +24832,6 @@ var CodexAcpAgent = class {
25119
24832
  if (steering.length === 0) {
25120
24833
  throw new AcpExecutionError("Codex received an empty steering request", {}, "invalid_request");
25121
24834
  }
25122
- const messageId = crypto.randomUUID();
25123
- for (const block of steering) {
25124
- await this.#emit({ content: block.content, messageId, sessionUpdate: "user_message_chunk" });
25125
- }
25126
24835
  const response = turnSteerResponseSchema.parse(
25127
24836
  await this.#appServer.request(
25128
24837
  "turn/steer",
@@ -25159,7 +24868,7 @@ var CodexAcpAgent = class {
25159
24868
  };
25160
24869
  #completeTurn = async (turn) => {
25161
24870
  const active = this.#turn;
25162
- if (active === null) {
24871
+ if (active === null || active.turn.id !== turn.id) {
25163
24872
  return;
25164
24873
  }
25165
24874
  await this.#updateTail;
@@ -27881,14 +27590,13 @@ var AgentConnection = class {
27881
27590
  get inProcessAgent() {
27882
27591
  return this.#process.kind === "in-process" ? this.#process.endpoint : null;
27883
27592
  }
27884
- captureProcessTree = async () => this.#process.kind === "child" ? await captureProcessTree(this.#process.child) : [];
27885
- closeProcess = async (capturedProcesses = []) => {
27593
+ closeProcess = async () => {
27886
27594
  try {
27887
27595
  if (this.#process.kind === "in-process") {
27888
27596
  await this.#process.endpoint.close();
27889
27597
  return;
27890
27598
  }
27891
- await stopProcessTree(this.#process.child, capturedProcesses);
27599
+ await stopProcessTree(this.#process.child);
27892
27600
  } finally {
27893
27601
  this.connection.close();
27894
27602
  }
@@ -34641,7 +34349,7 @@ var AgentSession = class _AgentSession {
34641
34349
  commandId: () => this.#turn.commandId,
34642
34350
  assertNativeSession: (sessionId) => this.assertNativeSession(sessionId),
34643
34351
  observer: getObserver,
34644
- recordSessionEventV2: this.#recordLifecycleEventV2
34352
+ recordSessionEventV2: this.recordLifecycleEventV2
34645
34353
  });
34646
34354
  this.#connection = new AgentConnection(agent, cwd, this);
34647
34355
  this.#contentExternalizer = contentExternalizer;
@@ -35224,7 +34932,14 @@ var AgentSession = class _AgentSession {
35224
34932
  if (this.#turn.running) {
35225
34933
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
35226
34934
  }
35227
- const completedHistory = this.#capabilities.loadSession ? await this.#completedHistory(options.signal, "ACP agent exited while loading history before a prompt") : null;
34935
+ if (!this.#capabilities.loadSession && this.#sessionLoad.kind === "not-requested") {
34936
+ this.#sessionLoad = {
34937
+ kind: "loaded",
34938
+ history: new AcpHistoryReplay(this.#store.eventsV2, this.#mobiusSessionId),
34939
+ response: {}
34940
+ };
34941
+ }
34942
+ 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;
35228
34943
  const prompt = this.buildPrompt(options);
35229
34944
  if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
35230
34945
  this.#sessionTitle = truncate(options.prompt, 500);
@@ -35253,11 +34968,16 @@ var AgentSession = class _AgentSession {
35253
34968
  this.#turnHistory = completedHistory === null ? null : new AcpHistoryReplay(this.#store.eventsV2, this.#mobiusSessionId);
35254
34969
  const lifecycleV2 = options.lifecycleV2;
35255
34970
  if (lifecycleV2 !== void 0) {
35256
- await this.#recordLifecycleEventV2({
35257
- payload: { commandId: options.commandId, content: lifecycleV2.content, kind: "prompt.requested" },
34971
+ await this.recordLifecycleEventV2({
34972
+ payload: {
34973
+ commandId: options.commandId,
34974
+ content: lifecycleV2.content,
34975
+ kind: "prompt.requested",
34976
+ ...lifecycleV2.context === void 0 ? {} : { context: lifecycleV2.context }
34977
+ },
35258
34978
  type: "lifecycle-metadata"
35259
34979
  });
35260
- await this.#recordLifecycleEventV2({
34980
+ await this.recordLifecycleEventV2({
35261
34981
  payload: {
35262
34982
  attemptId: lifecycleV2.attemptId,
35263
34983
  commandId: options.commandId,
@@ -35320,7 +35040,7 @@ var AgentSession = class _AgentSession {
35320
35040
  )
35321
35041
  );
35322
35042
  if (lifecycleV2 !== void 0) {
35323
- await this.#recordLifecycleEventV2({
35043
+ await this.recordLifecycleEventV2({
35324
35044
  payload: { commandId: options.commandId, kind: "prompt.completed", stopReason: result.stopReason },
35325
35045
  type: "lifecycle-metadata"
35326
35046
  });
@@ -35330,8 +35050,8 @@ var AgentSession = class _AgentSession {
35330
35050
  await running.activities.finish();
35331
35051
  const failure2 = error62 instanceof AcpExecutionError ? error62 : new AcpExecutionError("ACP agent execution failed", { cause: error62 });
35332
35052
  if (lifecycleV2 !== void 0) {
35333
- await this.#recordLifecycleEventV2({
35334
- payload: {
35053
+ await this.recordLifecycleEventV2({
35054
+ payload: options.cancellationRequested?.() === true ? { commandId: options.commandId, kind: "prompt.completed", stopReason: "cancelled" } : {
35335
35055
  attemptId: lifecycleV2.attemptId,
35336
35056
  code: failure2.code,
35337
35057
  commandId: options.commandId,
@@ -35367,11 +35087,16 @@ var AgentSession = class _AgentSession {
35367
35087
  const prompt = this.buildPrompt(options);
35368
35088
  const lifecycleV2 = options.lifecycleV2;
35369
35089
  if (lifecycleV2 !== void 0) {
35370
- await this.#recordLifecycleEventV2({
35371
- payload: { commandId: options.commandId, content: lifecycleV2.content, kind: "prompt.requested" },
35090
+ await this.recordLifecycleEventV2({
35091
+ payload: {
35092
+ commandId: options.commandId,
35093
+ content: lifecycleV2.content,
35094
+ kind: "prompt.requested",
35095
+ ...lifecycleV2.context === void 0 ? {} : { context: lifecycleV2.context }
35096
+ },
35372
35097
  type: "lifecycle-metadata"
35373
35098
  });
35374
- await this.#recordLifecycleEventV2({
35099
+ await this.recordLifecycleEventV2({
35375
35100
  payload: {
35376
35101
  attemptId: lifecycleV2.attemptId,
35377
35102
  commandId: options.commandId,
@@ -35401,7 +35126,7 @@ var AgentSession = class _AgentSession {
35401
35126
  const outcome = response["outcome"];
35402
35127
  if (outcome === "injected" || outcome === "startedNewTurn") {
35403
35128
  if (lifecycleV2 !== void 0) {
35404
- await this.#recordLifecycleEventV2({
35129
+ await this.recordLifecycleEventV2({
35405
35130
  payload: { commandId: options.commandId, kind: "prompt.completed", stopReason: "steered" },
35406
35131
  type: "lifecycle-metadata"
35407
35132
  });
@@ -35426,7 +35151,7 @@ var AgentSession = class _AgentSession {
35426
35151
  } catch (error62) {
35427
35152
  const failure2 = error62 instanceof AcpExecutionError ? error62 : new AcpExecutionError("ACP agent execution failed", { cause: error62 });
35428
35153
  if (lifecycleV2 !== void 0) {
35429
- await this.#recordLifecycleEventV2({
35154
+ await this.recordLifecycleEventV2({
35430
35155
  payload: {
35431
35156
  attemptId: lifecycleV2.attemptId,
35432
35157
  code: failure2.code,
@@ -35441,16 +35166,11 @@ var AgentSession = class _AgentSession {
35441
35166
  }
35442
35167
  };
35443
35168
  cancel = async () => {
35444
- const capturedProcesses = await this.#connection.captureProcessTree();
35445
- try {
35446
- await this.#interactions.cancelPendingInteractions();
35447
- if (this.#turn.running) {
35448
- await this.#connection.connection.agent.notify(methods8.agent.session.cancel, {
35449
- sessionId: this.#updates.sessionId()
35450
- });
35451
- }
35452
- } finally {
35453
- await this.closeProcess(capturedProcesses);
35169
+ await this.#interactions.cancelPendingInteractions();
35170
+ if (this.#turn.running) {
35171
+ await this.#connection.connection.agent.notify(methods8.agent.session.cancel, {
35172
+ sessionId: this.#updates.sessionId()
35173
+ });
35454
35174
  }
35455
35175
  };
35456
35176
  respondPermission = (options) => this.#interactions.respondPermission(options);
@@ -35459,7 +35179,14 @@ var AgentSession = class _AgentSession {
35459
35179
  onElicitation = (request, signal) => this.#interactions.onElicitation(request, signal);
35460
35180
  onElicitationComplete = (notification) => this.#interactions.onElicitationComplete(notification);
35461
35181
  onUpdate = (notification) => this.#updates.receive(notification);
35462
- #recordLifecycleEventV2 = async (event) => {
35182
+ recordControlEventV2 = async (event) => {
35183
+ if (this.#sessionLoad.kind !== "loaded") {
35184
+ return false;
35185
+ }
35186
+ await this.recordLifecycleEventV2(event);
35187
+ return true;
35188
+ };
35189
+ recordLifecycleEventV2 = async (event) => {
35463
35190
  if (event.type !== "lifecycle-metadata" || this.#sessionLoad.kind !== "loaded") {
35464
35191
  return;
35465
35192
  }
@@ -35643,7 +35370,7 @@ var AgentSession = class _AgentSession {
35643
35370
  await this.closeProcess();
35644
35371
  }
35645
35372
  };
35646
- closeProcess = (capturedProcesses = []) => this.#connection.closeProcess(capturedProcesses);
35373
+ closeProcess = () => this.#connection.closeProcess();
35647
35374
  race = (operation, exitMessage, signal) => this.#connection.race(operation, exitMessage, signal);
35648
35375
  assertNativeSession = (sessionId) => {
35649
35376
  if (sessionId !== this.#updates.sessionId()) {
@@ -36522,6 +36249,13 @@ var AgentRuntimeManager = class {
36522
36249
  this.#contentExternalizer = contentExternalizer;
36523
36250
  this.#queryProcesses = new AgentQueryProcesses(this.#processes, contentExternalizer);
36524
36251
  }
36252
+ recordLifecycleEventV2 = async (sessionId, event) => {
36253
+ const runtime = this.#executionProcesses.get(sessionId);
36254
+ if (runtime === void 0) {
36255
+ return false;
36256
+ }
36257
+ return await runtime.recordControlEventV2(event);
36258
+ };
36525
36259
  setObserver = (observer) => {
36526
36260
  this.#observer = observer;
36527
36261
  };
@@ -36777,13 +36511,7 @@ var AgentRuntimeManager = class {
36777
36511
  await this.#executions.cancel(sessionId, async () => {
36778
36512
  const runtime = this.#executionProcesses.get(sessionId);
36779
36513
  if (runtime !== void 0) {
36780
- try {
36781
- await runtime.cancel();
36782
- } finally {
36783
- if (this.#executionProcesses.detach(sessionId, runtime)) {
36784
- this.#processes.releaseClosed(runtime);
36785
- }
36786
- }
36514
+ await runtime.cancel();
36787
36515
  }
36788
36516
  });
36789
36517
  };
@@ -36851,7 +36579,10 @@ var AgentRuntimeManager = class {
36851
36579
  return { stopReason: "cancelled" };
36852
36580
  }
36853
36581
  try {
36854
- const result = await runtime.prompt(options2);
36582
+ const result = await runtime.prompt({
36583
+ ...options2,
36584
+ cancellationRequested: () => this.#executions.cancellation(options2.sessionId) !== void 0
36585
+ });
36855
36586
  return this.#executions.cancellation(options2.sessionId) !== void 0 ? { stopReason: "cancelled" } : result;
36856
36587
  } catch (error62) {
36857
36588
  if (this.#executions.cancellation(options2.sessionId) !== void 0) {
@@ -38149,16 +37880,7 @@ function send(socket, message) {
38149
37880
  }
38150
37881
  socket.send(encodeDaemonToServiceMessage(message));
38151
37882
  }
38152
- function reportFailure(publisher, command, code, message) {
38153
- publisher.publish(command.sessionId, {
38154
- code,
38155
- commandId: command.commandId,
38156
- kind: SESSION_FAILED_KIND,
38157
- message,
38158
- sessionId: command.sessionId
38159
- });
38160
- }
38161
- function settleAbandonedTurn(publisher, operations, audit, cancellation) {
37883
+ async function settleAbandonedTurn(eventLog, operations, audit, cancellation) {
38162
37884
  const attemptId = operations.findUnsettledAttemptId(cancellation.commandId, cancellation.sessionId);
38163
37885
  if (attemptId === null) {
38164
37886
  console.warn("Mobius daemon ignored cancellation for an inactive turn");
@@ -38169,13 +37891,14 @@ function settleAbandonedTurn(publisher, operations, audit, cancellation) {
38169
37891
  event: "session_abandoned_turn_settled",
38170
37892
  sessionId: cancellation.sessionId
38171
37893
  });
38172
- reportFailure(
38173
- publisher,
38174
- cancellation,
37894
+ await eventLog.failed(
37895
+ cancellation.sessionId,
37896
+ cancellation.commandId,
38175
37897
  "agent_execution_abandoned",
38176
37898
  "The local Agent execution was abandoned before it completed"
38177
37899
  );
38178
37900
  operations.transitionExecution(cancellation.commandId, "failed");
37901
+ eventLog.publishTerminal(cancellation.sessionId, cancellation.commandId);
38179
37902
  }
38180
37903
  function operationErrorCode(error62) {
38181
37904
  if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof PromptArtifactError) {
@@ -41264,112 +40987,6 @@ function warnIgnoredSetting(audit, event, commandId, sessionId, agentId, selecti
41264
40987
  `);
41265
40988
  }
41266
40989
 
41267
- // src/relay-connection/coalescing-agent-event-publisher.ts
41268
- var AGENT_EVENT_COALESCING_MILLISECONDS = 100;
41269
- var AGENT_EVENT_TEXT_MAXIMUM_LENGTH = 1e5;
41270
- var CoalescingAgentEventPublisher = class {
41271
- #entries = [];
41272
- #publish;
41273
- #publishedActivityIds = /* @__PURE__ */ new Set();
41274
- #scheduled = null;
41275
- #timer;
41276
- constructor(timer, publish) {
41277
- this.#publish = publish;
41278
- this.#timer = timer;
41279
- }
41280
- flush = () => {
41281
- this.#scheduled?.cancel();
41282
- this.#scheduled = null;
41283
- const entries = this.#entries;
41284
- this.#entries = [];
41285
- for (const entry of entries) {
41286
- this.#publish(entry);
41287
- }
41288
- };
41289
- recordActivity = (activity2) => {
41290
- const latest = this.#entries.at(-1);
41291
- 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" }];
41292
- const first = !this.#publishedActivityIds.has(activity2.activityId);
41293
- this.#publishedActivityIds.add(activity2.activityId);
41294
- if (first || activity2.status !== "pending" && activity2.status !== "running") {
41295
- this.flush();
41296
- } else {
41297
- this.schedule();
41298
- }
41299
- return Promise.resolve();
41300
- };
41301
- recordNarration = (increment) => {
41302
- if (increment.text.length === 0) {
41303
- return Promise.resolve();
41304
- }
41305
- let remaining = increment.text;
41306
- while (remaining.length > 0) {
41307
- const latest = this.#entries.at(-1);
41308
- if (latest?.kind === "narration" && latest.increment.activityId === increment.activityId) {
41309
- const available = AGENT_EVENT_TEXT_MAXIMUM_LENGTH - latest.increment.text.length;
41310
- if (available > 0) {
41311
- this.#entries = [
41312
- ...this.#entries.slice(0, -1),
41313
- {
41314
- increment: {
41315
- ...increment,
41316
- text: `${latest.increment.text}${remaining.slice(0, available)}`
41317
- },
41318
- kind: "narration"
41319
- }
41320
- ];
41321
- remaining = remaining.slice(available);
41322
- continue;
41323
- }
41324
- }
41325
- this.#entries = [
41326
- ...this.#entries,
41327
- {
41328
- increment: { ...increment, text: remaining.slice(0, AGENT_EVENT_TEXT_MAXIMUM_LENGTH) },
41329
- kind: "narration"
41330
- }
41331
- ];
41332
- remaining = remaining.slice(AGENT_EVENT_TEXT_MAXIMUM_LENGTH);
41333
- }
41334
- this.schedule();
41335
- return Promise.resolve();
41336
- };
41337
- recordText = (text2, messageId) => {
41338
- if (text2.length === 0) {
41339
- return Promise.resolve();
41340
- }
41341
- let remaining = text2;
41342
- while (remaining.length > 0) {
41343
- const latest = this.#entries.at(-1);
41344
- if (latest?.kind === "text" && latest.messageId === messageId) {
41345
- const available = AGENT_EVENT_TEXT_MAXIMUM_LENGTH - latest.text.length;
41346
- if (available > 0) {
41347
- this.#entries = [
41348
- ...this.#entries.slice(0, -1),
41349
- { ...latest, text: `${latest.text}${remaining.slice(0, available)}` }
41350
- ];
41351
- remaining = remaining.slice(available);
41352
- continue;
41353
- }
41354
- }
41355
- this.#entries = [
41356
- ...this.#entries,
41357
- {
41358
- kind: "text",
41359
- messageId,
41360
- text: remaining.slice(0, AGENT_EVENT_TEXT_MAXIMUM_LENGTH)
41361
- }
41362
- ];
41363
- remaining = remaining.slice(AGENT_EVENT_TEXT_MAXIMUM_LENGTH);
41364
- }
41365
- this.schedule();
41366
- return Promise.resolve();
41367
- };
41368
- schedule() {
41369
- this.#scheduled ??= this.#timer.schedule(this.flush, AGENT_EVENT_COALESCING_MILLISECONDS);
41370
- }
41371
- };
41372
-
41373
40990
  // src/daemon-prompt-executor.ts
41374
40991
  function daemonActivity(command, activity2) {
41375
40992
  return {
@@ -41392,7 +41009,6 @@ function daemonActivity(command, activity2) {
41392
41009
  }
41393
41010
  async function executePrompt({
41394
41011
  operations,
41395
- publisher,
41396
41012
  eventLogV2,
41397
41013
  command,
41398
41014
  config: config2,
@@ -41402,36 +41018,11 @@ async function executePrompt({
41402
41018
  attemptId,
41403
41019
  activateAttempt,
41404
41020
  waitForSessionAvailability,
41405
- timer,
41406
41021
  signal,
41407
- recordLiveEvent,
41022
+ recordTurnEvent,
41408
41023
  recordSteeringPrompt,
41409
41024
  cancellationRequested
41410
41025
  }) {
41411
- const events = new CoalescingAgentEventPublisher(timer, (event) => {
41412
- if (event.kind === "text") {
41413
- publisher.publish(
41414
- command.sessionId,
41415
- recordLiveEvent({ kind: AGENT_MESSAGE_DELTA_KIND, messageId: event.messageId, text: event.text })
41416
- );
41417
- return;
41418
- }
41419
- if (event.kind === "narration") {
41420
- const recorded = {
41421
- activityId: event.increment.activityId,
41422
- activityType: event.increment.activityType,
41423
- commandId: command.commandId,
41424
- kind: AGENT_ACTIVITY_NARRATION_KIND,
41425
- sequence: event.increment.sequence,
41426
- sessionId: command.sessionId,
41427
- text: event.increment.text
41428
- };
41429
- publisher.publish(command.sessionId, recordLiveEvent(recorded));
41430
- return;
41431
- }
41432
- const activity2 = daemonActivity(command, event.activity);
41433
- publisher.publish(command.sessionId, recordLiveEvent(activity2));
41434
- });
41435
41026
  try {
41436
41027
  const resolved = await resolveSessionDirectories(
41437
41028
  directories,
@@ -41499,33 +41090,6 @@ async function executePrompt({
41499
41090
  }
41500
41091
  const stream = activateAttempt();
41501
41092
  const lifecycleV2 = eventLogV2.started(command.sessionId, command.commandId, attemptId, stream.epoch);
41502
- if (!prepared.prompted) {
41503
- const listing = await directories.list(config2.bindingId, command.directoryId, signal);
41504
- publisher.publish(command.sessionId, {
41505
- additionalDirectories: resolved.additionalDirectoryEntries,
41506
- agentId: command.agentId,
41507
- agentName: prepared.agentName,
41508
- agentVersion: prepared.agentVersion,
41509
- capabilities: prepared.capabilities,
41510
- commands: prepared.commands,
41511
- configOptions: prepared.configOptions,
41512
- directoryId: command.directoryId,
41513
- directoryLabel: listing.directoryLabel,
41514
- kind: SESSION_READY_KIND,
41515
- requestId: command.commandId,
41516
- restored: prepared.restored,
41517
- sessionId: command.sessionId
41518
- });
41519
- }
41520
- publisher.publish(command.sessionId, {
41521
- commandId: command.commandId,
41522
- epoch: stream.epoch,
41523
- kind: SESSION_STARTED_KIND,
41524
- attemptId,
41525
- prompt: command.prompt,
41526
- sequence: stream.sequence,
41527
- sessionId: command.sessionId
41528
- });
41529
41093
  const attachments = await resolvePromptArtifacts(config2, command, signal);
41530
41094
  let stopReason;
41531
41095
  if (availability.disposition === SessionPromptDisposition.Steer) {
@@ -41552,9 +41116,20 @@ async function executePrompt({
41552
41116
  disposition: availability.disposition,
41553
41117
  images: attachments.images,
41554
41118
  lifecycleV2,
41555
- onActivity: events.recordActivity,
41556
- onNarration: events.recordNarration,
41557
- onText: events.recordText,
41119
+ onActivity: async (activity2) => {
41120
+ recordTurnEvent(daemonActivity(command, activity2));
41121
+ },
41122
+ onNarration: async (increment) => {
41123
+ recordTurnEvent({
41124
+ ...increment,
41125
+ commandId: command.commandId,
41126
+ sessionId: command.sessionId,
41127
+ kind: AGENT_ACTIVITY_NARRATION_KIND
41128
+ });
41129
+ },
41130
+ onText: async (text2, messageId) => {
41131
+ recordTurnEvent({ kind: AGENT_MESSAGE_DELTA_KIND, text: text2, messageId });
41132
+ },
41558
41133
  prompt: command.prompt,
41559
41134
  resources: attachments.resources,
41560
41135
  sessionId: command.sessionId,
@@ -41563,14 +41138,7 @@ async function executePrompt({
41563
41138
  });
41564
41139
  stopReason = result.stopReason;
41565
41140
  }
41566
- events.flush();
41567
- publisher.publish(command.sessionId, {
41568
- commandId: command.commandId,
41569
- kind: SESSION_COMPLETED_KIND,
41570
- sessionId: command.sessionId,
41571
- stopReason
41572
- });
41573
- eventLogV2.completed(command.sessionId, command.commandId, stopReason);
41141
+ await eventLogV2.completed(command.sessionId, command.commandId, stopReason);
41574
41142
  operations.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
41575
41143
  audit.record({
41576
41144
  commandId: command.commandId,
@@ -41578,15 +41146,8 @@ async function executePrompt({
41578
41146
  sessionId: command.sessionId
41579
41147
  });
41580
41148
  } catch (error62) {
41581
- events.flush();
41582
41149
  if (signal.aborted && cancellationRequested()) {
41583
- publisher.publish(command.sessionId, {
41584
- commandId: command.commandId,
41585
- kind: SESSION_COMPLETED_KIND,
41586
- sessionId: command.sessionId,
41587
- stopReason: "cancelled"
41588
- });
41589
- eventLogV2.completed(command.sessionId, command.commandId, "cancelled");
41150
+ await eventLogV2.completed(command.sessionId, command.commandId, "cancelled");
41590
41151
  operations.transitionExecution(command.commandId, "cancelled");
41591
41152
  audit.record({
41592
41153
  commandId: command.commandId,
@@ -41603,8 +41164,7 @@ async function executePrompt({
41603
41164
  const code = operationErrorCode(error62);
41604
41165
  const failureCode = code === "session_operation_failed" ? "agent_execution_failed" : code;
41605
41166
  const failureMessage = code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62);
41606
- eventLogV2.failed(command.sessionId, command.commandId, failureCode, failureMessage);
41607
- reportFailure(publisher, command, failureCode, failureMessage);
41167
+ await eventLogV2.failed(command.sessionId, command.commandId, failureCode, failureMessage);
41608
41168
  operations.transitionExecution(command.commandId, "failed");
41609
41169
  console.error("Mobius daemon command failed", error62);
41610
41170
  }
@@ -41632,7 +41192,7 @@ async function executeWorkspaceList(socket, command, directories, audit, signal)
41632
41192
  reportOperationFailure(socket, command.requestId, "", error62);
41633
41193
  }
41634
41194
  }
41635
- async function executeSessionPrepare(publisher, socket, command, config2, directories, audit, sessions, diagnostics, signal) {
41195
+ async function executeSessionPrepare(socket, command, config2, directories, audit, sessions, diagnostics, signal) {
41636
41196
  const metrics = new AccumulatingOperationMetrics();
41637
41197
  try {
41638
41198
  const readyEvent = await metrics.measure("prepare-total", async () => {
@@ -41682,12 +41242,6 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
41682
41242
  event: "session_configured",
41683
41243
  sessionId: command.sessionId
41684
41244
  });
41685
- publisher.publish(command.sessionId, {
41686
- configOptions,
41687
- kind: "session.config.updated",
41688
- requestId: command.requestId,
41689
- sessionId: command.sessionId
41690
- });
41691
41245
  }
41692
41246
  const event = {
41693
41247
  additionalDirectories: resolved.additionalDirectoryEntries,
@@ -41705,11 +41259,6 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
41705
41259
  sessionId: command.sessionId,
41706
41260
  runtimeTimings: metrics.snapshot()
41707
41261
  };
41708
- if (command.transient !== true) {
41709
- metrics.measureSync("readiness-commit", () => {
41710
- publisher.publish(command.sessionId, event);
41711
- });
41712
- }
41713
41262
  return event;
41714
41263
  });
41715
41264
  send(socket, {
@@ -41739,7 +41288,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
41739
41288
  reportOperationFailure(socket, command.requestId, command.sessionId, error62, metrics.snapshot());
41740
41289
  }
41741
41290
  }
41742
- async function executeSessionConfigure(publisher, socket, command, config2, directories, audit, sessions, signal) {
41291
+ async function executeSessionConfigure(socket, command, config2, directories, audit, sessions, signal) {
41743
41292
  try {
41744
41293
  const resolved = await resolveSessionDirectories(
41745
41294
  directories,
@@ -41765,7 +41314,7 @@ async function executeSessionConfigure(publisher, socket, command, config2, dire
41765
41314
  event: "session_configured",
41766
41315
  sessionId: command.sessionId
41767
41316
  });
41768
- publisher.publish(command.sessionId, {
41317
+ send(socket, {
41769
41318
  configOptions,
41770
41319
  kind: "session.config.updated",
41771
41320
  requestId: command.requestId,
@@ -41885,7 +41434,6 @@ function createDaemonCommandHandler({
41885
41434
  installations,
41886
41435
  nativeSessions,
41887
41436
  operations,
41888
- publisher,
41889
41437
  eventLogV2,
41890
41438
  externalContent,
41891
41439
  activeTurns,
@@ -41906,8 +41454,9 @@ function createDaemonCommandHandler({
41906
41454
  timer
41907
41455
  });
41908
41456
  const queueChanged = (sessionId) => {
41909
- publisher.publish(sessionId, { kind: "session.queue.changed", sessionId });
41910
- eventLogV2.queueChanged(sessionId);
41457
+ void eventLogV2.queueChanged(sessionId).catch((error62) => {
41458
+ console.error("Could not record queue change", error62);
41459
+ });
41911
41460
  };
41912
41461
  const nativeRequestHandler = createNativeSessionRequestHandler({
41913
41462
  audit,
@@ -41976,7 +41525,9 @@ function createDaemonCommandHandler({
41976
41525
  const cancellation = message;
41977
41526
  const turn2 = activeTurns.get(cancellation.commandId);
41978
41527
  if (turn2 === void 0 || !turn2.matches(cancellation)) {
41979
- settleAbandonedTurn(publisher, operations, audit, cancellation);
41528
+ void settleAbandonedTurn(eventLogV2, operations, audit, cancellation).catch((error62) => {
41529
+ console.error("Could not settle abandoned turn", error62);
41530
+ });
41980
41531
  return;
41981
41532
  }
41982
41533
  const cancellationState = turn2.requestCancellation();
@@ -42016,22 +41567,12 @@ function createDaemonCommandHandler({
42016
41567
  }
42017
41568
  if (kind === SESSION_PREPARE_KIND) {
42018
41569
  const command2 = message;
42019
- void executeSessionPrepare(
42020
- publisher,
42021
- socket,
42022
- command2,
42023
- config2,
42024
- directories,
42025
- audit,
42026
- sessions,
42027
- diagnostics,
42028
- signal
42029
- );
41570
+ void executeSessionPrepare(socket, command2, config2, directories, audit, sessions, diagnostics, signal);
42030
41571
  return;
42031
41572
  }
42032
41573
  if (kind === SESSION_CONFIGURE_KIND) {
42033
41574
  const command2 = message;
42034
- void executeSessionConfigure(publisher, socket, command2, config2, directories, audit, sessions, signal);
41575
+ void executeSessionConfigure(socket, command2, config2, directories, audit, sessions, signal);
42035
41576
  return;
42036
41577
  }
42037
41578
  if (kind === SESSION_LIST_KIND) {
@@ -42133,7 +41674,6 @@ function createDaemonCommandHandler({
42133
41674
  eventLogV2.requested(command);
42134
41675
  void executePrompt({
42135
41676
  operations,
42136
- publisher,
42137
41677
  eventLogV2,
42138
41678
  command,
42139
41679
  config: config2,
@@ -42150,15 +41690,15 @@ function createDaemonCommandHandler({
42150
41690
  sessionId: command.sessionId
42151
41691
  });
42152
41692
  }),
42153
- timer,
42154
41693
  signal: turn.signal,
42155
- recordLiveEvent: turn.recordEvent,
41694
+ recordTurnEvent: turn.recordEvent,
42156
41695
  recordSteeringPrompt: () => activeTurns.recordSteeringPrompt(command),
42157
41696
  cancellationRequested: turn.cancellationRequested
42158
41697
  }).catch((error62) => {
42159
41698
  console.error("Mobius daemon turn failed", error62);
42160
41699
  }).finally(() => {
42161
41700
  activeTurns.finish(turn);
41701
+ eventLogV2.publishTerminal(command.sessionId, command.commandId);
42162
41702
  if (command.disposition === SessionPromptDisposition.Queue) {
42163
41703
  queueChanged(command.sessionId);
42164
41704
  }
@@ -42442,7 +41982,6 @@ async function runRelayConnection({
42442
41982
  installations,
42443
41983
  nativeSessions,
42444
41984
  operations,
42445
- publisher,
42446
41985
  eventLogV2,
42447
41986
  externalContent,
42448
41987
  activeTurns,
@@ -42594,29 +42133,39 @@ async function runRelayConnection({
42594
42133
  // src/relay-connection/session-event-publisher.ts
42595
42134
  import { WebSocket as WebSocket8 } from "undici";
42596
42135
  var MAX_BUFFERED_BYTES = 32 * 1024 * 1024;
42136
+ var SESSION_EVENT_V2_BATCH_WINDOW_MILLISECONDS = 200;
42597
42137
  var DaemonSessionEventPublisher = class {
42138
+ #pendingV2Events = [];
42139
+ #pendingV2Task = null;
42598
42140
  #socket = null;
42141
+ #timer;
42142
+ constructor(timer) {
42143
+ this.#timer = timer;
42144
+ }
42599
42145
  connect = (socket) => {
42146
+ this.dropPendingV2Events();
42600
42147
  this.#socket = socket;
42601
42148
  };
42602
42149
  disconnect = (socket) => {
42603
42150
  if (this.#socket === socket) {
42604
42151
  this.#socket = null;
42152
+ this.dropPendingV2Events();
42605
42153
  }
42606
42154
  };
42607
42155
  close = () => {
42608
42156
  this.#socket = null;
42157
+ this.dropPendingV2Events();
42609
42158
  };
42610
- publish = (sessionId, event) => {
42159
+ publishOperationFailure = (sessionId, requestId, code, message) => {
42160
+ this.#send({ kind: "session.operation.failed", sessionId, requestId, code, message });
42161
+ };
42162
+ publishStatus = (event) => this.#send(event);
42163
+ #send = (message) => {
42611
42164
  const socket = this.#socket;
42612
42165
  if (socket === null || socket.readyState !== WebSocket8.OPEN) {
42613
42166
  return;
42614
42167
  }
42615
- const encoded = encodeDaemonToServiceMessage({
42616
- kind: SESSION_EVENT_KIND,
42617
- payload: encodeRecordedSessionEvent(event),
42618
- sessionId
42619
- });
42168
+ const encoded = encodeDaemonToServiceMessage(message);
42620
42169
  if (socket.bufferedAmount + Buffer.byteLength(encoded, "utf8") > MAX_BUFFERED_BYTES) {
42621
42170
  socket.close(1013, "Live event transport overloaded");
42622
42171
  return;
@@ -42626,32 +42175,35 @@ var DaemonSessionEventPublisher = class {
42626
42175
  } catch {
42627
42176
  }
42628
42177
  };
42629
- publishBatch = (sessionId, events) => {
42630
- for (const event of events) {
42631
- this.publish(sessionId, event);
42632
- }
42633
- };
42634
- publishStatus = (event) => {
42178
+ publishV2 = (event) => {
42635
42179
  const socket = this.#socket;
42636
42180
  if (socket === null || socket.readyState !== WebSocket8.OPEN) {
42637
42181
  return;
42638
42182
  }
42639
- const encoded = encodeDaemonToServiceMessage(event);
42640
- if (socket.bufferedAmount + Buffer.byteLength(encoded, "utf8") > MAX_BUFFERED_BYTES) {
42641
- socket.close(1013, "Live event transport overloaded");
42183
+ this.#pendingV2Events.push(event);
42184
+ if (this.#pendingV2Events.length >= SESSION_EVENT_V2_BATCH_MAX_SIZE) {
42185
+ this.flushV2Events(socket);
42642
42186
  return;
42643
42187
  }
42644
- try {
42645
- socket.send(encoded);
42646
- } catch {
42647
- }
42188
+ this.#pendingV2Task ??= this.#timer.schedule(
42189
+ () => this.flushV2Events(socket),
42190
+ SESSION_EVENT_V2_BATCH_WINDOW_MILLISECONDS
42191
+ );
42648
42192
  };
42649
- publishV2 = (event) => {
42650
- const socket = this.#socket;
42651
- if (socket === null || socket.readyState !== WebSocket8.OPEN) {
42193
+ dropPendingV2Events = () => {
42194
+ this.#pendingV2Task?.cancel();
42195
+ this.#pendingV2Task = null;
42196
+ this.#pendingV2Events = [];
42197
+ };
42198
+ flushV2Events = (socket) => {
42199
+ this.#pendingV2Task?.cancel();
42200
+ this.#pendingV2Task = null;
42201
+ const events = this.#pendingV2Events;
42202
+ this.#pendingV2Events = [];
42203
+ if (events.length === 0 || this.#socket !== socket || socket.readyState !== WebSocket8.OPEN) {
42652
42204
  return;
42653
42205
  }
42654
- const encoded = encodeDaemonToServiceMessage({ event, kind: SESSION_EVENT_V2_KIND });
42206
+ const encoded = encodeDaemonToServiceMessage({ events, kind: SESSION_EVENT_V2_KIND });
42655
42207
  if (socket.bufferedAmount + Buffer.byteLength(encoded, "utf8") > MAX_BUFFERED_BYTES) {
42656
42208
  socket.close(1013, "Live event transport overloaded");
42657
42209
  return;
@@ -42711,8 +42263,12 @@ function sessionEventV22(daemonGenerationId, sessionId, position, event, recorde
42711
42263
  var DaemonSessionEventLogV2 = class {
42712
42264
  daemonGenerationId;
42713
42265
  #publisher;
42266
+ #terminal = /* @__PURE__ */ new Map();
42267
+ #publications = /* @__PURE__ */ new Map();
42714
42268
  #queued = /* @__PURE__ */ new Map();
42715
- constructor(publisher, daemonGenerationId = randomUUID8()) {
42269
+ #recordLifecycle;
42270
+ constructor(publisher, recordLifecycle, daemonGenerationId = randomUUID8()) {
42271
+ this.#recordLifecycle = recordLifecycle;
42716
42272
  this.#publisher = publisher;
42717
42273
  this.daemonGenerationId = daemonGenerationId;
42718
42274
  }
@@ -42720,36 +42276,101 @@ var DaemonSessionEventLogV2 = class {
42720
42276
  this.#queued.set(command.commandId, {
42721
42277
  commandId: command.commandId,
42722
42278
  content: promptContent(command),
42279
+ context: {
42280
+ agentId: command.agentId,
42281
+ directoryId: command.directoryId,
42282
+ additionalDirectoryIds: command.additionalDirectoryIds
42283
+ },
42284
+ phase: "queued",
42723
42285
  sessionId: command.sessionId
42724
42286
  });
42725
42287
  };
42726
42288
  started = (sessionId, commandId, attemptId, epoch) => {
42727
42289
  const request = this.#queued.get(commandId);
42728
42290
  if (request?.sessionId === sessionId) {
42729
- this.#queued.delete(commandId);
42730
- return { attemptId, content: request.content, epoch };
42291
+ this.#queued.set(commandId, { ...request, phase: "running" });
42292
+ return { attemptId, content: request.content, epoch, context: request.context };
42731
42293
  }
42732
42294
  throw new Error("The executing prompt was not registered in the V2 queue");
42733
42295
  };
42734
42296
  record = (sessionId, event, position) => {
42735
- this.#publisher.publishV2(this.event(sessionId, position, event, (/* @__PURE__ */ new Date()).toISOString()));
42297
+ const recorded = this.event(sessionId, position, event, (/* @__PURE__ */ new Date()).toISOString());
42298
+ if (event.type === "lifecycle-metadata" && (event.payload.kind === "prompt.completed" || event.payload.kind === "prompt.failed" || event.payload.kind === "prompt.failed-before-start")) {
42299
+ this.#terminal.set(event.payload.commandId, recorded);
42300
+ const pending2 = this.#publications.get(sessionId) ?? [];
42301
+ pending2.push(recorded);
42302
+ this.#publications.set(sessionId, pending2);
42303
+ return;
42304
+ }
42305
+ const pending = this.#publications.get(sessionId);
42306
+ if (pending !== void 0) {
42307
+ pending.push(recorded);
42308
+ } else {
42309
+ this.#publisher.publishV2(recorded);
42310
+ }
42311
+ };
42312
+ publishTerminal = (sessionId, commandId) => {
42313
+ const event = this.#terminal.get(commandId);
42314
+ if (event?.sessionId === sessionId) {
42315
+ this.#terminal.delete(commandId);
42316
+ const pending = this.#publications.get(sessionId) ?? [];
42317
+ while (pending.length > 0) {
42318
+ const next = pending[0];
42319
+ if (next === void 0) {
42320
+ break;
42321
+ }
42322
+ if (next.type === "lifecycle-metadata" && "commandId" in next.payload && this.#terminal.has(next.payload.commandId)) {
42323
+ break;
42324
+ }
42325
+ pending.shift();
42326
+ this.#publisher.publishV2(next);
42327
+ }
42328
+ if (pending.length === 0) {
42329
+ this.#publications.delete(sessionId);
42330
+ }
42331
+ }
42332
+ this.#queued.delete(commandId);
42736
42333
  };
42737
42334
  event = (sessionId, position, event, recordedAt) => sessionEventV22(this.daemonGenerationId, sessionId, position, event, recordedAt);
42738
- queueChanged = (_sessionId) => void 0;
42739
- completed = (sessionId, commandId, _stopReason) => {
42335
+ queueChanged = async (sessionId) => {
42336
+ await this.#recordLifecycle(sessionId, {
42337
+ type: "lifecycle-metadata",
42338
+ payload: { kind: "session.queue.changed" }
42339
+ });
42340
+ };
42341
+ completed = async (sessionId, commandId, stopReason) => {
42740
42342
  const request = this.#queued.get(commandId);
42741
- if (request?.sessionId === sessionId) {
42742
- this.#queued.delete(commandId);
42343
+ if (request?.sessionId !== sessionId || this.#terminal.has(commandId)) {
42344
+ return;
42345
+ }
42346
+ const recorded = await this.#recordLifecycle(sessionId, {
42347
+ type: "lifecycle-metadata",
42348
+ payload: { kind: "prompt.completed", commandId, stopReason }
42349
+ });
42350
+ if (!recorded) {
42351
+ this.#publisher.publishOperationFailure(
42352
+ sessionId,
42353
+ commandId,
42354
+ "cancelled",
42355
+ "The prompt was cancelled before execution"
42356
+ );
42743
42357
  }
42744
42358
  };
42745
- failed = (sessionId, commandId, _code, _message) => {
42359
+ failed = async (sessionId, commandId, code, message) => {
42746
42360
  const request = this.#queued.get(commandId);
42747
- if (request?.sessionId === sessionId) {
42748
- this.#queued.delete(commandId);
42361
+ if (request?.sessionId !== sessionId || this.#terminal.has(commandId)) {
42362
+ return;
42363
+ }
42364
+ const recorded = await this.#recordLifecycle(sessionId, {
42365
+ type: "lifecycle-metadata",
42366
+ payload: { kind: "prompt.failed-before-start", commandId, code, message }
42367
+ });
42368
+ if (!recorded) {
42369
+ this.#publisher.publishOperationFailure(sessionId, commandId, code, message);
42749
42370
  }
42750
42371
  };
42751
42372
  promptRequestRecovery = (sessionId) => ({
42752
- queuedPromptRequests: [...this.#queued.values()].filter((request) => request.sessionId === sessionId).map(({ commandId, content }) => ({ commandId, content }))
42373
+ queuedPromptRequests: [...this.#queued.values()].filter((request) => request.sessionId === sessionId && request.phase === "queued").map(({ commandId, content }) => ({ commandId, content }))
42753
42374
  });
42754
42375
  };
42755
42376
 
@@ -42835,14 +42456,17 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
42835
42456
  const sessionStore = new SqliteAcpSessionStore(sessionDatabase, eventsV2);
42836
42457
  await using externalContent = new LocalExternalContentStore(stateDirectory);
42837
42458
  const operations = new DaemonOperationState();
42838
- const publisher = new DaemonSessionEventPublisher();
42839
- const eventLogV2 = new DaemonSessionEventLogV2(publisher, daemonGenerationId);
42459
+ const publisher = new DaemonSessionEventPublisher(timer);
42460
+ const eventLogV2 = new DaemonSessionEventLogV2(
42461
+ publisher,
42462
+ (sessionId, event) => agentRuntime.recordLifecycleEventV2(sessionId, event),
42463
+ daemonGenerationId
42464
+ );
42840
42465
  const activeTurns = new DaemonTurnRegistry(operations);
42841
- const recordSessionEvent = (sessionId, event) => {
42842
- publisher.publish(sessionId, activeTurns.recordEvent(event));
42843
- };
42844
42466
  const agentRuntime = new AgentRuntimeManager(
42845
- new DaemonAcpObserver(recordSessionEvent, eventLogV2.record),
42467
+ new DaemonAcpObserver((_sessionId, event) => {
42468
+ activeTurns.recordEvent(event);
42469
+ }, eventLogV2.record),
42846
42470
  sessionStore,
42847
42471
  {
42848
42472
  read: async (options2, nativeSessionId, nativeTurn) => options2.agent.id === "codex" ? (await readCodexFullHistory(