@moxt-ai/mobius 0.0.461 → 0.0.464

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.
@@ -5,7 +5,7 @@ import {
5
5
  __toESM,
6
6
  __using,
7
7
  package_default
8
- } from "./chunk-M25NRHCV.js";
8
+ } from "./chunk-W5MXRFJ5.js";
9
9
 
10
10
  // ../../node_modules/.pnpm/ignore@7.0.9/node_modules/ignore/index.js
11
11
  var require_ignore = __commonJS({
@@ -20779,7 +20779,10 @@ var RUNTIME_HEARTBEAT_ACK_MESSAGE = `{"kind":"${RUNTIME_HEARTBEAT_ACK_KIND}"}`;
20779
20779
  function decodeRuntimeLivenessReadyEvent(encoded) {
20780
20780
  const value = parseJson(encoded);
20781
20781
  assertKind(value, RUNTIME_LIVENESS_READY_KIND);
20782
- return { kind: RUNTIME_LIVENESS_READY_KIND };
20782
+ return {
20783
+ kind: RUNTIME_LIVENESS_READY_KIND,
20784
+ ...Reflect.get(value, "sessionEventAcknowledgement") === true ? { sessionEventAcknowledgement: true } : {}
20785
+ };
20783
20786
  }
20784
20787
  function decodeRuntimeHeartbeatEvent(encoded) {
20785
20788
  const value = parseJson(encoded);
@@ -21800,6 +21803,45 @@ var sessionLiveEventSchema = external_exports.discriminatedUnion("type", [
21800
21803
  type: external_exports.literal("lifecycle-metadata")
21801
21804
  }).readonly()
21802
21805
  ]);
21806
+ var sessionEventDeliverySchema = external_exports.object({ sessionId: identifierStringSchema, after: positionSchema.nullable(), resumed: external_exports.literal(true).optional() }).readonly();
21807
+ var sessionEventDeliveriesSchema = external_exports.array(sessionEventDeliverySchema).min(1).max(SESSION_EVENT_BATCH_MAX_SIZE).readonly();
21808
+ function checkDeliveryOrder(envelope2, context) {
21809
+ if (envelope2.delivery === void 0) {
21810
+ return;
21811
+ }
21812
+ const previous = /* @__PURE__ */ new Map();
21813
+ for (const delivery of envelope2.delivery) {
21814
+ if (previous.has(delivery.sessionId)) {
21815
+ context.addIssue({ code: "custom", message: "A Session's delivery order is stated twice" });
21816
+ return;
21817
+ }
21818
+ previous.set(delivery.sessionId, delivery.after === null ? null : BigInt(delivery.after));
21819
+ }
21820
+ const named = /* @__PURE__ */ new Set();
21821
+ for (const event of envelope2.events) {
21822
+ if (!previous.has(event.sessionId)) {
21823
+ context.addIssue({ code: "custom", message: "An event's Session has no delivery order" });
21824
+ return;
21825
+ }
21826
+ named.add(event.sessionId);
21827
+ const position = BigInt(event.position);
21828
+ const before = previous.get(event.sessionId);
21829
+ if (before !== null && before !== void 0 && position <= before) {
21830
+ context.addIssue({ code: "custom", message: "A Session's events are not in delivery order" });
21831
+ return;
21832
+ }
21833
+ previous.set(event.sessionId, position);
21834
+ }
21835
+ if (named.size !== previous.size) {
21836
+ context.addIssue({ code: "custom", message: "A delivery order names a Session without events" });
21837
+ }
21838
+ }
21839
+ var SESSION_EVENTS_ACKNOWLEDGED_KIND = "session.events.acknowledged";
21840
+ var sessionEventsAcknowledgedSchema = external_exports.object({
21841
+ kind: external_exports.literal(SESSION_EVENTS_ACKNOWLEDGED_KIND),
21842
+ // Each Session's events through this position were recorded or need no Recording; none is sent again.
21843
+ sessions: external_exports.array(external_exports.object({ sessionId: identifierStringSchema, through: positionSchema }).readonly()).min(1).max(SESSION_EVENT_BATCH_MAX_SIZE).readonly()
21844
+ }).readonly();
21803
21845
  var wireLifecyclePayloadSchema = external_exports.object({
21804
21846
  kind: identifierStringSchema,
21805
21847
  commandId: identifierStringSchema.optional(),
@@ -21829,14 +21871,19 @@ var sessionWireEventSchema = external_exports.union([
21829
21871
  ]);
21830
21872
  var sessionWireEnvelopeSchema = external_exports.object({
21831
21873
  kind: external_exports.literal(SESSION_EVENT_KIND),
21832
- events: external_exports.array(sessionWireEventSchema).min(1).max(SESSION_EVENT_BATCH_MAX_SIZE).readonly()
21833
- }).passthrough().readonly();
21874
+ events: external_exports.array(sessionWireEventSchema).min(1).max(SESSION_EVENT_BATCH_MAX_SIZE).readonly(),
21875
+ delivery: sessionEventDeliveriesSchema.optional()
21876
+ }).passthrough().superRefine(checkDeliveryOrder).readonly();
21834
21877
  function isRecord2(value) {
21835
21878
  return typeof value === "object" && value !== null && !Array.isArray(value);
21836
21879
  }
21837
21880
  var sessionEventBatchSchema = external_exports.array(sessionEventSchema).min(1).max(SESSION_EVENT_BATCH_MAX_SIZE).readonly();
21838
21881
  var sessionLiveEventBatchSchema = external_exports.array(sessionLiveEventSchema).min(1).max(SESSION_EVENT_BATCH_MAX_SIZE).readonly();
21839
- var sessionEventEnvelopeSchema = external_exports.object({ events: sessionLiveEventBatchSchema, kind: external_exports.literal(SESSION_EVENT_KIND) }).readonly();
21882
+ var sessionEventEnvelopeSchema = external_exports.object({
21883
+ events: sessionLiveEventBatchSchema,
21884
+ kind: external_exports.literal(SESSION_EVENT_KIND),
21885
+ delivery: sessionEventDeliveriesSchema.optional()
21886
+ }).superRefine(checkDeliveryOrder).readonly();
21840
21887
  var promptMessageOutcomeSchema = external_exports.object({
21841
21888
  payload: external_exports.discriminatedUnion("kind", [promptCompletedSchema, promptFailedSchema]),
21842
21889
  recordedAt: external_exports.iso.datetime({ offset: true })
@@ -21930,6 +21977,8 @@ var decodeKnownSessionEventPayload = (value) => {
21930
21977
  };
21931
21978
  var decodeSessionEventEnvelope = (value) => decode3(value, sessionEventEnvelopeSchema);
21932
21979
  var encodeSessionEventEnvelope = (value) => encode3(value, sessionEventEnvelopeSchema);
21980
+ var decodeSessionEventsAcknowledgedEvent = (value) => decode3(value, sessionEventsAcknowledgedSchema);
21981
+ var encodeSessionEventsAcknowledgedEvent = (value) => encode3(value, sessionEventsAcknowledgedSchema);
21933
21982
  var decodeAcpSessionUpdate = (value) => decode3(value, acpSessionUpdateSchema);
21934
21983
  var decodeKnownNativeSessionEvents = (value) => decode3(sanitizeConsumableNativeSessionEvents(value), nativeSessionEventsSchema);
21935
21984
 
@@ -22948,6 +22997,11 @@ var serviceToDaemonSignatures = {
22948
22997
  encodeRuntimeLivenessReadyEvent,
22949
22998
  decodeRuntimeLivenessReadyEvent
22950
22999
  ),
23000
+ [SESSION_EVENTS_ACKNOWLEDGED_KIND]: defineMessageSignature(
23001
+ SESSION_EVENTS_ACKNOWLEDGED_KIND,
23002
+ encodeSessionEventsAcknowledgedEvent,
23003
+ decodeSessionEventsAcknowledgedEvent
23004
+ ),
22951
23005
  "runtime.diagnostics.read": defineMessageSignature(
22952
23006
  "runtime.diagnostics.read",
22953
23007
  encodeRuntimeDiagnosticsRequest,
@@ -29059,6 +29113,7 @@ var systemTimer = new SystemTimer();
29059
29113
  var TRANSCRIPT_TAIL_BYTES = 65536;
29060
29114
  var TRANSCRIPT_INITIAL_DELAY_MS = 40;
29061
29115
  var TRANSCRIPT_POLL_INTERVAL_MS = 150;
29116
+ var MAX_PARTIAL_SETTLED_TEXT_DEFERRALS = 2;
29062
29117
  var WAKEUP_INACTIVITY_TIMEOUT_MS = 3e5;
29063
29118
  var SESSION_UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
29064
29119
  var SUBAGENT_CONVERSATION_ID_PATTERN = /"conversationId"\s*:\s*"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"/giu;
@@ -29066,6 +29121,8 @@ var SUBAGENT_IDLE_ID_PATTERN = /\bSubagent ([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-
29066
29121
  var AGENT_EXECUTOR_ERROR_PATTERN = /^\s*⚠ agent executor error:\s*(.+?)\s*$/su;
29067
29122
  var TASK_RESULT_SENDER_PATTERN = /\bsender=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/(task-\d+)\b/giu;
29068
29123
  var BACKGROUND_TASK_CREATED_PATTERN = /\bTool is running as a background task with task id:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/(task-\d+)\b/iu;
29124
+ var BACKGROUND_TASK_DESCRIPTION_PATTERN = /\nTask Description:\s*([\s\S]+?)(?:\nTask logs are available at:|\nLog output:|$)/u;
29125
+ var TRANSCRIPT_TRUNCATED_SUFFIX_PATTERN = /\r?\n<truncated \d+ bytes>$/u;
29069
29126
  var SUBAGENT_CREATED_MARKER = "Created the following subagent";
29070
29127
  var MAXIMUM_TOOL_DESCRIPTION_CHARS = 500;
29071
29128
  var MINIMUM_TRUNCATED_MATCH_CHARS = 16;
@@ -29121,7 +29178,7 @@ async function readTranscriptTailState(launchEnvironment, sessionId, baselineSte
29121
29178
  return null;
29122
29179
  }
29123
29180
  if (tail.bytes.byteLength === 0) {
29124
- return { firstStepIndex: -1, maxStepIndex: -1, settledStepIndex: null, steps: [] };
29181
+ return { firstStepIndex: -1, maxStepIndex: -1, settledStep: null, steps: [] };
29125
29182
  }
29126
29183
  const text2 = new TextDecoder().decode(tail.bytes);
29127
29184
  const lines = text2.split("\n");
@@ -29152,10 +29209,20 @@ async function readTranscriptTailState(launchEnvironment, sessionId, baselineSte
29152
29209
  return {
29153
29210
  firstStepIndex,
29154
29211
  maxStepIndex,
29155
- settledStepIndex: settledStep?.step_index ?? null,
29212
+ settledStep: settledStep === void 0 ? null : { content: settledStep.content, stepIndex: settledStep.step_index },
29156
29213
  steps
29157
29214
  };
29158
29215
  }
29216
+ function extractMessageChunkText(updateKind, update) {
29217
+ if (updateKind !== "agent_message_chunk" && updateKind !== "agent_message") {
29218
+ return void 0;
29219
+ }
29220
+ const content = update["content"];
29221
+ if (!isRecord5(content) || content["type"] !== "text") {
29222
+ return void 0;
29223
+ }
29224
+ return readString3(content, "text");
29225
+ }
29159
29226
  function extractUuidMatches(text2, pattern) {
29160
29227
  pattern.lastIndex = 0;
29161
29228
  const matches = [];
@@ -29168,14 +29235,7 @@ function extractUuidMatches(text2, pattern) {
29168
29235
  return matches;
29169
29236
  }
29170
29237
  function extractExecutorError(updateKind, update) {
29171
- if (updateKind !== "agent_message_chunk" && updateKind !== "agent_message") {
29172
- return void 0;
29173
- }
29174
- const content = update["content"];
29175
- if (!isRecord5(content) || content["type"] !== "text") {
29176
- return void 0;
29177
- }
29178
- const text2 = readString3(content, "text");
29238
+ const text2 = extractMessageChunkText(updateKind, update);
29179
29239
  if (text2 === void 0) {
29180
29240
  return void 0;
29181
29241
  }
@@ -29293,6 +29353,34 @@ function decodeTranscriptArg(value) {
29293
29353
  return value;
29294
29354
  }
29295
29355
  }
29356
+ function decodeTruncatedJsonString(raw) {
29357
+ if (!raw.startsWith('"')) {
29358
+ return void 0;
29359
+ }
29360
+ let body = raw.slice(1).replace(TRANSCRIPT_TRUNCATED_SUFFIX_PATTERN, "");
29361
+ const partialUnicode = /\\u[0-9a-fA-F]{0,3}$/u.exec(body);
29362
+ if (partialUnicode !== null) {
29363
+ const precedingBackslashes = /\\*$/u.exec(body.slice(0, partialUnicode.index))?.[0].length ?? 0;
29364
+ if (precedingBackslashes % 2 === 0) {
29365
+ body = body.slice(0, partialUnicode.index);
29366
+ }
29367
+ }
29368
+ const trailingBackslashes = /\\+$/u.exec(body)?.[0].length ?? 0;
29369
+ if (trailingBackslashes % 2 === 1) {
29370
+ body = body.slice(0, -1);
29371
+ }
29372
+ try {
29373
+ const parsed = JSON.parse(`"${body}"`);
29374
+ return typeof parsed === "string" ? parsed : void 0;
29375
+ } catch {
29376
+ return body;
29377
+ }
29378
+ }
29379
+ function extractBackgroundTaskDescription(content) {
29380
+ const match = BACKGROUND_TASK_DESCRIPTION_PATTERN.exec(content);
29381
+ const description = match?.[1]?.trim();
29382
+ return description !== void 0 && description.length > 0 ? description : void 0;
29383
+ }
29296
29384
  function readTranscriptArgString(args, key) {
29297
29385
  const raw = args[key];
29298
29386
  if (raw === void 0) {
@@ -29302,8 +29390,8 @@ function readTranscriptArgString(args, key) {
29302
29390
  if (typeof decoded !== "string") {
29303
29391
  return void 0;
29304
29392
  }
29305
- const stripped = typeof raw === "string" && decoded === raw && decoded.startsWith('"') ? decoded.slice(1) : decoded;
29306
- const trimmed = stripped.trim();
29393
+ const normalized = typeof raw === "string" && decoded === raw && raw.startsWith('"') ? decodeTruncatedJsonString(raw) ?? decoded.slice(1) : decoded;
29394
+ const trimmed = normalized.trim();
29307
29395
  return trimmed.length > 0 ? trimmed : void 0;
29308
29396
  }
29309
29397
  function readTranscriptToolCallInfo(raw) {
@@ -29421,10 +29509,12 @@ var AntigravityBackgroundWakeup = class {
29421
29509
  },
29422
29510
  toolMetadata: /* @__PURE__ */ new Map(),
29423
29511
  wakeupCompletedOpenBgCandidates: /* @__PURE__ */ new Set(),
29512
+ wakeupDeferredSettledStep: null,
29424
29513
  wakeupGeneration: 0,
29425
29514
  wakeupOwedToolCallIds: /* @__PURE__ */ new Set(),
29426
29515
  wakeupSettledStepIndex: null,
29427
- wakeupStageSeq: 0
29516
+ wakeupStageSeq: 0,
29517
+ wakeupStreamedMessageText: ""
29428
29518
  };
29429
29519
  this.#sessions.set(sessionId, created);
29430
29520
  return created;
@@ -29505,6 +29595,8 @@ var AntigravityBackgroundWakeup = class {
29505
29595
  session.backgroundTasks.clear();
29506
29596
  session.wakeupOwedToolCallIds.clear();
29507
29597
  session.wakeupCompletedOpenBgCandidates.clear();
29598
+ session.wakeupDeferredSettledStep = null;
29599
+ session.wakeupStreamedMessageText = "";
29508
29600
  session.backgroundCorrelation.pendingCandidates.length = 0;
29509
29601
  session.backgroundCorrelation.nativeTaskIdByToolCallId.clear();
29510
29602
  session.subagents.conversationIdByToolCallId.clear();
@@ -29550,7 +29642,15 @@ var AntigravityBackgroundWakeup = class {
29550
29642
  candidates.splice(index2, 1);
29551
29643
  }
29552
29644
  };
29553
- #isActiveBackgroundCandidate = (session, toolCallId) => session.backgroundTasks.has(toolCallId) || session.phase.kind === "wakeup" && session.phase.openToolIds.has(toolCallId) || session.wakeupCompletedOpenBgCandidates.has(toolCallId) || session.wakeupOwedToolCallIds.has(toolCallId);
29645
+ #isRunningBackgroundCandidate = (session, toolCallId) => {
29646
+ const tracked = session.backgroundTasks.get(toolCallId);
29647
+ return tracked !== void 0 && tracked.state === "running" || session.phase.kind === "wakeup" && session.phase.openToolIds.has(toolCallId);
29648
+ };
29649
+ #isCompletedBackgroundCandidate = (session, toolCallId) => {
29650
+ const tracked = session.backgroundTasks.get(toolCallId);
29651
+ return tracked !== void 0 && tracked.state === "awaiting-results" || session.wakeupCompletedOpenBgCandidates.has(toolCallId) || session.wakeupOwedToolCallIds.has(toolCallId);
29652
+ };
29653
+ #isActiveBackgroundCandidate = (session, toolCallId) => this.#isRunningBackgroundCandidate(session, toolCallId) || this.#isCompletedBackgroundCandidate(session, toolCallId);
29554
29654
  #pruneInactiveCandidates = (session) => {
29555
29655
  const candidates = session.backgroundCorrelation.pendingCandidates;
29556
29656
  let writeIndex = 0;
@@ -29565,6 +29665,12 @@ var AntigravityBackgroundWakeup = class {
29565
29665
  #syncBackgroundTaskCreations = (sessionId, session, steps) => {
29566
29666
  const correlation = session.backgroundCorrelation;
29567
29667
  const targetSessionId = sessionId.toLowerCase();
29668
+ const deliveredInSteps = extractTaskResultSenderIds(
29669
+ sessionId,
29670
+ steps,
29671
+ session.sessionOpenStepIndex,
29672
+ Number.MAX_SAFE_INTEGER
29673
+ );
29568
29674
  let lastPlanner;
29569
29675
  for (const step of steps) {
29570
29676
  if (step.type === "PLANNER_RESPONSE" && step.tool_calls !== void 0 && step.tool_calls.length > 0) {
@@ -29590,19 +29696,34 @@ var AntigravityBackgroundWakeup = class {
29590
29696
  if (info !== null && info.category === null || step.step_index <= session.sessionOpenStepIndex) {
29591
29697
  continue;
29592
29698
  }
29699
+ const matchText = info?.matchText ?? extractBackgroundTaskDescription(step.content);
29593
29700
  const candidates = correlation.pendingCandidates;
29594
29701
  const categoryMatches = (candidate) => info === null || info.category === null || candidate.category === info.category;
29702
+ const textCompatible = (candidate) => candidate.matchText === void 0 || matchText === void 0 || matchesCandidateText(candidate.matchText, matchText);
29703
+ const alreadyDelivered = correlation.deliveredNativeTaskIds.has(nativeTaskId) || deliveredInSteps.has(nativeTaskId);
29704
+ const primaryMatches = (candidate) => alreadyDelivered ? this.#isCompletedBackgroundCandidate(session, candidate.toolCallId) : this.#isRunningBackgroundCandidate(session, candidate.toolCallId);
29705
+ const secondaryMatches = (candidate) => alreadyDelivered ? this.#isRunningBackgroundCandidate(session, candidate.toolCallId) : this.#isCompletedBackgroundCandidate(session, candidate.toolCallId);
29595
29706
  let matchedIndex = candidates.findIndex(
29596
- (candidate) => this.#isActiveBackgroundCandidate(session, candidate.toolCallId) && categoryMatches(candidate) && matchesCandidateText(candidate.matchText, info?.matchText)
29707
+ (candidate) => primaryMatches(candidate) && categoryMatches(candidate) && matchesCandidateText(candidate.matchText, matchText)
29597
29708
  );
29598
29709
  if (matchedIndex === -1) {
29599
29710
  matchedIndex = candidates.findIndex(
29600
- (candidate) => this.#isActiveBackgroundCandidate(session, candidate.toolCallId) && categoryMatches(candidate)
29711
+ (candidate) => secondaryMatches(candidate) && categoryMatches(candidate) && matchesCandidateText(candidate.matchText, matchText)
29712
+ );
29713
+ }
29714
+ if (matchedIndex === -1) {
29715
+ matchedIndex = candidates.findIndex(
29716
+ (candidate) => primaryMatches(candidate) && categoryMatches(candidate) && textCompatible(candidate)
29601
29717
  );
29602
29718
  }
29603
- if (matchedIndex === -1 && info?.matchText !== void 0) {
29719
+ if (matchedIndex === -1) {
29720
+ matchedIndex = candidates.findIndex(
29721
+ (candidate) => secondaryMatches(candidate) && categoryMatches(candidate) && textCompatible(candidate)
29722
+ );
29723
+ }
29724
+ if (matchedIndex === -1 && matchText !== void 0) {
29604
29725
  matchedIndex = candidates.findIndex(
29605
- (candidate) => categoryMatches(candidate) && matchesCandidateText(candidate.matchText, info.matchText)
29726
+ (candidate) => categoryMatches(candidate) && matchesCandidateText(candidate.matchText, matchText)
29606
29727
  );
29607
29728
  }
29608
29729
  if (matchedIndex !== -1) {
@@ -29812,6 +29933,8 @@ var AntigravityBackgroundWakeup = class {
29812
29933
  const generation = session.wakeupGeneration;
29813
29934
  session.wakeupOwedToolCallIds.clear();
29814
29935
  session.wakeupCompletedOpenBgCandidates.clear();
29936
+ session.wakeupDeferredSettledStep = null;
29937
+ session.wakeupStreamedMessageText = "";
29815
29938
  for (const [toolCallId, task] of session.backgroundTasks) {
29816
29939
  if (task.kind !== "subagent" && task.state === "awaiting-results") {
29817
29940
  session.wakeupOwedToolCallIds.add(toolCallId);
@@ -29836,6 +29959,8 @@ var AntigravityBackgroundWakeup = class {
29836
29959
  session.phase = { cancelRequested, kind: "idle" };
29837
29960
  session.wakeupOwedToolCallIds.clear();
29838
29961
  session.wakeupCompletedOpenBgCandidates.clear();
29962
+ session.wakeupDeferredSettledStep = null;
29963
+ session.wakeupStreamedMessageText = "";
29839
29964
  this.#dropAwaitingResultTasks(session);
29840
29965
  const notifications = [];
29841
29966
  const bgNotification = this.#takeBackgroundTasksUpdate(sessionId, session);
@@ -29858,6 +29983,8 @@ var AntigravityBackgroundWakeup = class {
29858
29983
  session.phase = { cancelRequested: false, kind: "idle" };
29859
29984
  session.wakeupOwedToolCallIds.clear();
29860
29985
  session.wakeupCompletedOpenBgCandidates.clear();
29986
+ session.wakeupDeferredSettledStep = null;
29987
+ session.wakeupStreamedMessageText = "";
29861
29988
  this.#dropAwaitingResultTasks(session);
29862
29989
  const notifications = [];
29863
29990
  const bgNotification = this.#takeBackgroundTasksUpdate(sessionId, session);
@@ -29896,6 +30023,41 @@ var AntigravityBackgroundWakeup = class {
29896
30023
  return;
29897
30024
  }
29898
30025
  };
30026
+ /**
30027
+ * `agy` can flush a settled `PLANNER_RESPONSE` to `transcript.jsonl` slightly before the
30028
+ * matching `agent_message_chunk` notifications finish traversing ACP stdout. Settling early
30029
+ * would close the wakeup turn empty and cause the late chunk to open a second turn.
30030
+ */
30031
+ #shouldDeferSettledReply = (session, settledStep) => {
30032
+ const expectedText = settledStep.content?.trim() ?? "";
30033
+ if (expectedText.length === 0) {
30034
+ return false;
30035
+ }
30036
+ if (session.wakeupStreamedMessageText.trim().length === 0) {
30037
+ return true;
30038
+ }
30039
+ if (session.wakeupStreamedMessageText.includes(expectedText)) {
30040
+ return false;
30041
+ }
30042
+ const nextCount = session.wakeupDeferredSettledStep?.stepIndex === settledStep.stepIndex ? session.wakeupDeferredSettledStep.count + 1 : 1;
30043
+ session.wakeupDeferredSettledStep = { count: nextCount, stepIndex: settledStep.stepIndex };
30044
+ return nextCount <= MAX_PARTIAL_SETTLED_TEXT_DEFERRALS;
30045
+ };
30046
+ #consumeSettledReplyText = (session, settledStep) => {
30047
+ session.wakeupDeferredSettledStep = null;
30048
+ const expectedText = settledStep.content?.trim() ?? "";
30049
+ if (expectedText.length === 0) {
30050
+ return;
30051
+ }
30052
+ const matchIndex = session.wakeupStreamedMessageText.indexOf(expectedText);
30053
+ if (matchIndex !== -1) {
30054
+ session.wakeupStreamedMessageText = session.wakeupStreamedMessageText.slice(
30055
+ matchIndex + expectedText.length
30056
+ );
30057
+ return;
30058
+ }
30059
+ session.wakeupStreamedMessageText = "";
30060
+ };
29899
30061
  #checkWakeupTranscript = async (sessionId, generation, stageEpoch) => {
29900
30062
  if (this.#disposed) {
29901
30063
  return;
@@ -29923,8 +30085,13 @@ var AntigravityBackgroundWakeup = class {
29923
30085
  this.#syncSubagentCreations(current, tail.steps);
29924
30086
  this.#syncBackgroundTaskCreations(sessionId, current, tail.steps);
29925
30087
  }
29926
- if (tail?.settledStepIndex !== null && tail?.settledStepIndex !== void 0) {
29927
- if (this.#settleWakeupReply(sessionId, current, tail, tail.settledStepIndex)) {
30088
+ if (tail?.settledStep !== null && tail?.settledStep !== void 0) {
30089
+ if (this.#shouldDeferSettledReply(current, tail.settledStep)) {
30090
+ this.#rescheduleTranscriptCheck(sessionId, current, generation, stageEpoch, currentStage);
30091
+ return;
30092
+ }
30093
+ this.#consumeSettledReplyText(current, tail.settledStep);
30094
+ if (this.#settleWakeupReply(sessionId, current, tail, tail.settledStep.stepIndex)) {
29928
30095
  this.#emitNotifications(this.#finishWakeup(sessionId, current, "end_turn", false));
29929
30096
  } else {
29930
30097
  const bg2 = this.#takeBackgroundTasksUpdate(sessionId, current);
@@ -30044,8 +30211,9 @@ var AntigravityBackgroundWakeup = class {
30044
30211
  this.#syncSubagentCreations(current, tail.steps);
30045
30212
  this.#syncBackgroundTaskCreations(sessionId, current, tail.steps);
30046
30213
  }
30047
- if (tail?.settledStepIndex !== null && tail?.settledStepIndex !== void 0) {
30048
- this.#settleWakeupReply(sessionId, current, tail, tail.settledStepIndex);
30214
+ if (tail?.settledStep !== null && tail?.settledStep !== void 0) {
30215
+ this.#consumeSettledReplyText(current, tail.settledStep);
30216
+ this.#settleWakeupReply(sessionId, current, tail, tail.settledStep.stepIndex);
30049
30217
  this.#emitNotifications(this.#finishWakeup(sessionId, current, "end_turn", false));
30050
30218
  return;
30051
30219
  }
@@ -30505,6 +30673,11 @@ var AntigravityBackgroundWakeup = class {
30505
30673
  return;
30506
30674
  }
30507
30675
  if (isWakeupChunkUpdateKind(updateKind)) {
30676
+ const messageText = extractMessageChunkText(updateKind, update);
30677
+ if (messageText !== void 0 && messageText.length > 0) {
30678
+ session.wakeupStreamedMessageText += messageText;
30679
+ session.wakeupDeferredSettledStep = null;
30680
+ }
30508
30681
  const executorError = extractExecutorError(updateKind, update);
30509
30682
  this.#promoteOpenWakeupToolsToBackground(session);
30510
30683
  const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
@@ -104879,7 +105052,7 @@ async function runRelayConnection({
104879
105052
  return;
104880
105053
  }
104881
105054
  ready = true;
104882
- publisher.connect(socket);
105055
+ publisher.connect(socket, message.sessionEventAcknowledgement === true);
104883
105056
  connectionLiveness.start();
104884
105057
  onConnected();
104885
105058
  return;
@@ -104889,6 +105062,10 @@ async function runRelayConnection({
104889
105062
  return;
104890
105063
  }
104891
105064
  connectionLiveness.recordInboundActivity();
105065
+ if (kind === SESSION_EVENTS_ACKNOWLEDGED_KIND) {
105066
+ publisher.acknowledge(socket, message);
105067
+ return;
105068
+ }
104892
105069
  commands.dispatch(message);
104893
105070
  } catch (error62) {
104894
105071
  console.error("Mobius daemon rejected a message", error62);
@@ -104917,41 +105094,62 @@ async function runRelayConnection({
104917
105094
  // src/engine/runtime/relay/session-event-publisher.ts
104918
105095
  import { WebSocket as WebSocket11 } from "undici";
104919
105096
  var MAX_BUFFERED_BYTES = 32 * 1024 * 1024;
104920
- var MAX_PENDING_BYTES2 = 32 * 1024 * 1024;
105097
+ var MAX_RETAINED_BYTES = 32 * 1024 * 1024;
104921
105098
  var MAX_EVENT_BATCH_BYTES = 1024 * 1024;
104922
105099
  var MAX_FRAME_BYTES = 8 * 1024 * 1024;
104923
105100
  var LOCAL_BACKPRESSURE_CLOSE_CODE = 4009;
104924
105101
  var EMPTY_ENVELOPE_BYTES = Buffer.byteLength(JSON.stringify({ events: [], kind: SESSION_EVENT_KIND }));
105102
+ var EMPTY_DELIVERY_BYTES = Buffer.byteLength(',"delivery":[]');
104925
105103
  var SESSION_EVENT_BATCH_WINDOW_MILLISECONDS = 100;
105104
+ var SESSION_EVENT_RESEND_INTERVAL_MILLISECONDS = 3e4;
105105
+ var MAX_SESSION_EVENT_RESENDS = 5;
104926
105106
  var RuntimeSessionEventPublisher = class {
104927
- #pending = [];
105107
+ #retained = [];
105108
+ #sessions = /* @__PURE__ */ new Map();
104928
105109
  #awaitingFirstAnswer = /* @__PURE__ */ new Map();
104929
- #pendingBytes = 0;
105110
+ #retainedBytes = 0;
105111
+ #unsentCount = 0;
105112
+ #unsentBytes = 0;
104930
105113
  #overflowReported = false;
104931
105114
  #pendingTask = null;
105115
+ #resendTask = null;
105116
+ #tick = 0;
104932
105117
  #connection = { kind: "disconnected" };
104933
105118
  #timer;
104934
105119
  constructor(timer) {
104935
105120
  this.#timer = timer;
104936
105121
  }
104937
- connect = (socket) => {
105122
+ connect = (socket, acknowledged) => {
104938
105123
  if (this.#connection.kind === "closed") {
104939
105124
  return;
104940
105125
  }
104941
- this.#connection = { kind: "connected", socket };
105126
+ this.#connection = { kind: "connected", socket, acknowledged };
105127
+ for (const retained of this.#retained) {
105128
+ if (retained.handoff.kind === "sent") {
105129
+ this.#markUnsent(retained);
105130
+ }
105131
+ }
105132
+ for (const delivery of this.#sessions.values()) {
105133
+ delivery.lastSent = null;
105134
+ }
104942
105135
  this.flushEvents(socket);
104943
105136
  };
104944
105137
  disconnect = (socket) => {
104945
105138
  if (this.#connection.kind === "connected" && this.#connection.socket === socket) {
104946
105139
  this.#connection = { kind: "disconnected" };
104947
105140
  this.cancelFlush();
105141
+ this.cancelResend();
104948
105142
  }
104949
105143
  };
104950
105144
  close = () => {
104951
105145
  this.#connection = { kind: "closed" };
104952
105146
  this.cancelFlush();
104953
- this.#pending.length = 0;
104954
- this.#pendingBytes = 0;
105147
+ this.cancelResend();
105148
+ this.#retained.length = 0;
105149
+ this.#retainedBytes = 0;
105150
+ this.#unsentCount = 0;
105151
+ this.#unsentBytes = 0;
105152
+ this.#sessions.clear();
104955
105153
  this.#awaitingFirstAnswer.clear();
104956
105154
  };
104957
105155
  flush = () => {
@@ -104959,6 +105157,30 @@ var RuntimeSessionEventPublisher = class {
104959
105157
  this.flushEvents(this.#connection.socket);
104960
105158
  }
104961
105159
  };
105160
+ /** Releases the acknowledged events of each Session, which are never sent again. */
105161
+ acknowledge = (socket, message) => {
105162
+ const connection = this.#connection;
105163
+ if (connection.kind !== "connected" || connection.socket !== socket || !connection.acknowledged) {
105164
+ return;
105165
+ }
105166
+ for (const { sessionId, through } of message.sessions) {
105167
+ const position = Number(through);
105168
+ const delivery = this.#sessions.get(sessionId);
105169
+ const named = this.#retained.some(
105170
+ (retained) => retained.event.sessionId === sessionId && retained.position === position && (retained.handoff.kind === "sent" || retained.handoff.sentBefore)
105171
+ );
105172
+ if (delivery === void 0 || !named) {
105173
+ continue;
105174
+ }
105175
+ this.#release((retained) => retained.event.sessionId === sessionId && retained.position <= position);
105176
+ delivery.acknowledged = position;
105177
+ delivery.resends = 0;
105178
+ if (delivery.lastSent !== null && delivery.lastSent <= position) {
105179
+ delivery.lastSent = null;
105180
+ }
105181
+ this.#forgetSettled(sessionId);
105182
+ }
105183
+ };
104962
105184
  publishOperationFailure = (sessionId, requestId, code, message) => {
104963
105185
  this.#send({ kind: "session.operation.failed", sessionId, requestId, code, message });
104964
105186
  };
@@ -104989,6 +105211,7 @@ var RuntimeSessionEventPublisher = class {
104989
105211
  return;
104990
105212
  }
104991
105213
  const bytes = Buffer.byteLength(JSON.stringify(event), "utf8") + 1;
105214
+ const delivery = this.#delivery(event.sessionId);
104992
105215
  if (bytes + EMPTY_ENVELOPE_BYTES > MAX_FRAME_BYTES) {
104993
105216
  console.warn("Live Session event exceeds the Relay frame limit", {
104994
105217
  code: "live_event_too_large",
@@ -104996,47 +105219,49 @@ var RuntimeSessionEventPublisher = class {
104996
105219
  eventId: event.eventId,
104997
105220
  bytes
104998
105221
  });
105222
+ delivery.lost = true;
104999
105223
  return;
105000
105224
  }
105001
- let batch = this.#pending.at(-1);
105002
- const newBatch = batch === void 0 || batch.events.length >= SESSION_EVENT_BATCH_MAX_SIZE || batch.bytes + bytes > MAX_EVENT_BATCH_BYTES;
105003
- const additionalBytes = bytes + (newBatch ? EMPTY_ENVELOPE_BYTES : 0);
105004
- if (this.#pendingBytes + additionalBytes > MAX_PENDING_BYTES2) {
105225
+ if (this.#retainedBytes + bytes > MAX_RETAINED_BYTES) {
105226
+ this.#evictSent(this.#retainedBytes + bytes - MAX_RETAINED_BYTES);
105227
+ }
105228
+ if (this.#retainedBytes + bytes > MAX_RETAINED_BYTES) {
105005
105229
  if (!this.#overflowReported) {
105006
105230
  this.#overflowReported = true;
105007
105231
  console.warn("Live Session output exceeded the pending buffer limit", {
105008
105232
  code: "live_event_buffer_full",
105009
105233
  sessionId: event.sessionId,
105010
105234
  eventId: event.eventId,
105011
- maximumBytes: MAX_PENDING_BYTES2
105235
+ maximumBytes: MAX_RETAINED_BYTES
105012
105236
  });
105013
105237
  }
105238
+ delivery.lost = true;
105014
105239
  return;
105015
105240
  }
105016
- if (batch === void 0 || newBatch) {
105017
- batch = { events: [], firstAnswers: [], bytes: EMPTY_ENVELOPE_BYTES };
105018
- this.#pending.push(batch);
105019
- }
105020
- batch.events.push(event);
105021
- batch.bytes += bytes;
105022
- this.#pendingBytes += additionalBytes;
105023
105241
  const awaiting = this.#awaitingFirstAnswer.get(event.sessionId);
105024
105242
  const firstAnswer = this.#consumeFirstAnswer(event);
105025
- if (firstAnswer && awaiting !== void 0) {
105026
- batch.firstAnswers.push({
105243
+ this.#retained.push({
105244
+ event,
105245
+ position: Number(event.position),
105246
+ bytes,
105247
+ handoff: { kind: "unsent", sentBefore: false },
105248
+ firstAnswer: firstAnswer && awaiting !== void 0 ? {
105027
105249
  sessionId: event.sessionId,
105028
105250
  commandId: awaiting.commandId,
105029
105251
  eventId: event.eventId,
105030
105252
  observedAt: Date.now(),
105031
105253
  publishedAt: performance.now()
105032
- });
105033
- }
105254
+ } : null
105255
+ });
105256
+ this.#retainedBytes += bytes;
105257
+ this.#unsentCount += 1;
105258
+ this.#unsentBytes += bytes;
105034
105259
  const connection = this.#connection;
105035
105260
  if (connection.kind !== "connected" || connection.socket.readyState !== WebSocket11.OPEN) {
105036
105261
  return;
105037
105262
  }
105038
105263
  const socket = connection.socket;
105039
- if (firstAnswer || this.#pending.length > 1 || batch.events.length >= SESSION_EVENT_BATCH_MAX_SIZE || batch.bytes >= MAX_EVENT_BATCH_BYTES) {
105264
+ if (firstAnswer || this.#unsentCount >= SESSION_EVENT_BATCH_MAX_SIZE || EMPTY_ENVELOPE_BYTES + this.#unsentBytes >= MAX_EVENT_BATCH_BYTES) {
105040
105265
  this.flushEvents(socket);
105041
105266
  return;
105042
105267
  }
@@ -105045,6 +105270,86 @@ var RuntimeSessionEventPublisher = class {
105045
105270
  SESSION_EVENT_BATCH_WINDOW_MILLISECONDS
105046
105271
  );
105047
105272
  };
105273
+ #delivery = (sessionId) => {
105274
+ const existing = this.#sessions.get(sessionId);
105275
+ if (existing !== void 0) {
105276
+ return existing;
105277
+ }
105278
+ const created = { acknowledged: null, lastSent: null, lost: false, resends: 0 };
105279
+ this.#sessions.set(sessionId, created);
105280
+ return created;
105281
+ };
105282
+ /** A Session with nothing retained or owed needs no delivery state; its next events start a new order. */
105283
+ #forgetSettled = (sessionId) => {
105284
+ const delivery = this.#sessions.get(sessionId);
105285
+ if (delivery !== void 0 && !delivery.lost && !this.#retained.some((retained) => retained.event.sessionId === sessionId)) {
105286
+ this.#sessions.delete(sessionId);
105287
+ }
105288
+ };
105289
+ #markUnsent = (retained) => {
105290
+ retained.handoff = { kind: "unsent", sentBefore: true };
105291
+ this.#unsentCount += 1;
105292
+ this.#unsentBytes += retained.bytes;
105293
+ };
105294
+ #release = (released) => {
105295
+ let kept = 0;
105296
+ for (const retained of this.#retained) {
105297
+ if (released(retained)) {
105298
+ this.#retainedBytes -= retained.bytes;
105299
+ if (retained.handoff.kind === "unsent") {
105300
+ this.#unsentCount -= 1;
105301
+ this.#unsentBytes -= retained.bytes;
105302
+ }
105303
+ } else {
105304
+ this.#retained[kept] = retained;
105305
+ kept += 1;
105306
+ }
105307
+ }
105308
+ this.#retained.length = kept;
105309
+ if (this.#retained.length === 0) {
105310
+ this.#overflowReported = false;
105311
+ }
105312
+ };
105313
+ /** Gives up the oldest Sessions' sent events to make room; those Sessions continue with a new, omitted order. */
105314
+ #evictSent = (needed) => {
105315
+ let freed = 0;
105316
+ const sessions = /* @__PURE__ */ new Set();
105317
+ for (const retained of this.#retained) {
105318
+ if (freed >= needed) {
105319
+ break;
105320
+ }
105321
+ if (retained.handoff.kind === "unsent" && !retained.handoff.sentBefore) {
105322
+ continue;
105323
+ }
105324
+ if (!sessions.has(retained.event.sessionId)) {
105325
+ sessions.add(retained.event.sessionId);
105326
+ for (const candidate of this.#retained) {
105327
+ if (candidate.event.sessionId === retained.event.sessionId && (candidate.handoff.kind === "sent" || candidate.handoff.sentBefore)) {
105328
+ freed += candidate.bytes;
105329
+ }
105330
+ }
105331
+ }
105332
+ }
105333
+ if (sessions.size === 0) {
105334
+ return;
105335
+ }
105336
+ this.#giveUp(sessions);
105337
+ console.warn("Unacknowledged live Session output was given up to make room", {
105338
+ code: "live_event_unacknowledged_evicted",
105339
+ sessions: sessions.size
105340
+ });
105341
+ };
105342
+ #giveUp = (sessions) => {
105343
+ this.#release(
105344
+ (retained) => sessions.has(retained.event.sessionId) && (retained.handoff.kind === "sent" || retained.handoff.sentBefore)
105345
+ );
105346
+ for (const sessionId of sessions) {
105347
+ const delivery = this.#delivery(sessionId);
105348
+ delivery.lost = true;
105349
+ delivery.lastSent = null;
105350
+ delivery.resends = 0;
105351
+ }
105352
+ };
105048
105353
  #consumeFirstAnswer = (event) => {
105049
105354
  if (event.type === "lifecycle-metadata") {
105050
105355
  const payload = event.payload;
@@ -105068,24 +105373,100 @@ var RuntimeSessionEventPublisher = class {
105068
105373
  this.#pendingTask?.cancel();
105069
105374
  this.#pendingTask = null;
105070
105375
  };
105376
+ cancelResend = () => {
105377
+ this.#resendTask?.cancel();
105378
+ this.#resendTask = null;
105379
+ };
105380
+ /** Checks for unacknowledged events while this connection holds any it sent. */
105381
+ scheduleResend = (socket) => {
105382
+ if (this.#resendTask !== null || !this.#retained.some((retained) => retained.handoff.kind === "sent")) {
105383
+ return;
105384
+ }
105385
+ this.#resendTask = this.#timer.schedule(() => {
105386
+ this.#resendTask = null;
105387
+ this.resendUnacknowledged(socket);
105388
+ }, SESSION_EVENT_RESEND_INTERVAL_MILLISECONDS);
105389
+ };
105390
+ resendUnacknowledged = (socket) => {
105391
+ const connection = this.#connection;
105392
+ if (connection.kind !== "connected" || connection.socket !== socket || !connection.acknowledged) {
105393
+ return;
105394
+ }
105395
+ this.#tick += 1;
105396
+ const oldest = /* @__PURE__ */ new Map();
105397
+ for (const retained of this.#retained) {
105398
+ if (retained.handoff.kind === "sent" && !oldest.has(retained.event.sessionId)) {
105399
+ oldest.set(retained.event.sessionId, retained.handoff.tick);
105400
+ }
105401
+ }
105402
+ const abandoned = /* @__PURE__ */ new Set();
105403
+ const resent = /* @__PURE__ */ new Set();
105404
+ for (const [sessionId, tick] of oldest) {
105405
+ const delivery = this.#delivery(sessionId);
105406
+ if (this.#tick - tick <= 2 ** delivery.resends) {
105407
+ continue;
105408
+ }
105409
+ if (delivery.resends >= MAX_SESSION_EVENT_RESENDS) {
105410
+ abandoned.add(sessionId);
105411
+ } else {
105412
+ delivery.resends += 1;
105413
+ resent.add(sessionId);
105414
+ }
105415
+ }
105416
+ if (abandoned.size > 0) {
105417
+ this.#giveUp(abandoned);
105418
+ console.warn("Live Session output the Relay never acknowledged was given up", {
105419
+ code: "live_event_unacknowledged_abandoned",
105420
+ sessions: abandoned.size
105421
+ });
105422
+ }
105423
+ for (const retained of this.#retained) {
105424
+ if (resent.has(retained.event.sessionId) && retained.handoff.kind === "sent") {
105425
+ this.#markUnsent(retained);
105426
+ }
105427
+ }
105428
+ for (const sessionId of resent) {
105429
+ const delivery = this.#delivery(sessionId);
105430
+ delivery.lastSent = null;
105431
+ }
105432
+ this.flushEvents(socket);
105433
+ this.scheduleResend(socket);
105434
+ };
105071
105435
  flushEvents = (socket) => {
105072
105436
  this.cancelFlush();
105073
105437
  const connection = this.#connection;
105074
105438
  if (connection.kind !== "connected" || connection.socket !== socket || socket.readyState !== WebSocket11.OPEN) {
105075
105439
  return;
105076
105440
  }
105077
- let sent = 0;
105078
- for (const batch of this.#pending) {
105079
- const encoded = encodeDaemonToServiceMessage({ events: batch.events, kind: SESSION_EVENT_KIND });
105441
+ for (; ; ) {
105442
+ const batch = this.#nextBatch(connection.acknowledged);
105443
+ if (batch.length === 0) {
105444
+ break;
105445
+ }
105446
+ const delivery = connection.acknowledged ? this.#deliveryOrder(batch) : void 0;
105447
+ const encoded = encodeDaemonToServiceMessage({
105448
+ events: batch.map((retained) => retained.event),
105449
+ kind: SESSION_EVENT_KIND,
105450
+ ...delivery === void 0 ? {} : { delivery }
105451
+ });
105080
105452
  if (socket.bufferedAmount + Buffer.byteLength(encoded, "utf8") > MAX_BUFFERED_BYTES) {
105081
105453
  socket.close(LOCAL_BACKPRESSURE_CLOSE_CODE, "Live event transport overloaded");
105082
105454
  break;
105083
105455
  }
105084
105456
  try {
105085
105457
  socket.send(encoded);
105086
- sent += 1;
105087
- this.#pendingBytes -= batch.bytes;
105088
- for (const answer of batch.firstAnswers) {
105458
+ } catch {
105459
+ console.warn("Live Session output could not be sent", { code: "live_event_send_failed" });
105460
+ socket.close(LOCAL_BACKPRESSURE_CLOSE_CODE, "Live event handoff failed");
105461
+ break;
105462
+ }
105463
+ for (const retained of batch) {
105464
+ retained.handoff = { kind: "sent", tick: this.#tick };
105465
+ this.#unsentCount -= 1;
105466
+ this.#unsentBytes -= retained.bytes;
105467
+ const answer = retained.firstAnswer;
105468
+ retained.firstAnswer = null;
105469
+ if (answer !== null) {
105089
105470
  console.info(
105090
105471
  JSON.stringify({
105091
105472
  event: "runtime-first-answer-handoff-timing",
@@ -105098,16 +105479,70 @@ var RuntimeSessionEventPublisher = class {
105098
105479
  })
105099
105480
  );
105100
105481
  }
105101
- } catch {
105102
- console.warn("Live Session output could not be sent", { code: "live_event_send_failed" });
105103
- socket.close(LOCAL_BACKPRESSURE_CLOSE_CODE, "Live event handoff failed");
105104
- break;
105482
+ }
105483
+ if (!connection.acknowledged) {
105484
+ const sent = new Set(batch);
105485
+ this.#release((retained) => sent.has(retained));
105486
+ for (const sessionId of new Set(batch.map((retained) => retained.event.sessionId))) {
105487
+ const delivery2 = this.#sessions.get(sessionId);
105488
+ if (delivery2 !== void 0) {
105489
+ delivery2.lost = false;
105490
+ }
105491
+ this.#forgetSettled(sessionId);
105492
+ }
105105
105493
  }
105106
105494
  }
105107
- this.#pending.splice(0, sent);
105108
- if (this.#pending.length === 0) {
105109
- this.#overflowReported = false;
105495
+ if (connection.acknowledged) {
105496
+ this.scheduleResend(socket);
105497
+ }
105498
+ };
105499
+ /** The oldest unsent events that fit one envelope, in the order they were published. */
105500
+ #nextBatch = (acknowledged) => {
105501
+ const batch = [];
105502
+ const sessions = /* @__PURE__ */ new Set();
105503
+ let bytes = EMPTY_ENVELOPE_BYTES + (acknowledged ? EMPTY_DELIVERY_BYTES : 0);
105504
+ for (const retained of this.#retained) {
105505
+ if (retained.handoff.kind !== "unsent") {
105506
+ continue;
105507
+ }
105508
+ const sessionId = retained.event.sessionId;
105509
+ const orderBytes = acknowledged && !sessions.has(sessionId) ? Buffer.byteLength(
105510
+ `${JSON.stringify({ sessionId, after: String(Number.MAX_SAFE_INTEGER), resumed: true })},`
105511
+ ) : 0;
105512
+ if (batch.length >= SESSION_EVENT_BATCH_MAX_SIZE || batch.length > 0 && bytes + retained.bytes + orderBytes > MAX_EVENT_BATCH_BYTES) {
105513
+ break;
105514
+ }
105515
+ batch.push(retained);
105516
+ sessions.add(sessionId);
105517
+ bytes += retained.bytes + orderBytes;
105518
+ }
105519
+ return batch;
105520
+ };
105521
+ /** States where each Session's events in the batch continue its delivery, and records them as its newest sent. */
105522
+ #deliveryOrder = (batch) => {
105523
+ const order = [];
105524
+ for (const retained of batch) {
105525
+ const sessionId = retained.event.sessionId;
105526
+ const delivery = this.#delivery(sessionId);
105527
+ if (!order.some((entry) => entry.sessionId === sessionId)) {
105528
+ const after = delivery.lost ? null : delivery.lastSent ?? delivery.acknowledged;
105529
+ if (delivery.lost) {
105530
+ retained.event = {
105531
+ ...retained.event,
105532
+ mobiusMetadata: { ...retained.event.mobiusMetadata, omitted: true }
105533
+ };
105534
+ delivery.lost = false;
105535
+ }
105536
+ const resumed = after !== null && delivery.lastSent === null;
105537
+ order.push({
105538
+ sessionId,
105539
+ after: after === null ? null : String(after),
105540
+ ...resumed ? { resumed: true } : {}
105541
+ });
105542
+ }
105543
+ delivery.lastSent = retained.position;
105110
105544
  }
105545
+ return order;
105111
105546
  };
105112
105547
  };
105113
105548
 
@@ -105583,4 +106018,4 @@ export {
105583
106018
  * MIT Licensed
105584
106019
  *)
105585
106020
  */
105586
- //# sourceMappingURL=chunk-FI4KLIFX.js.map
106021
+ //# sourceMappingURL=chunk-YN6SPJT7.js.map