@mastra/server 1.86.0-alpha.6 → 1.86.0-alpha.7

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 (75) hide show
  1. package/dist/{a2a-BFN2C8f2.js → a2a-WPGF38fX.js} +1 -1
  2. package/dist/{a2a-DlEIsCZz.cjs → a2a-vSZkdSRE.cjs} +1 -1
  3. package/dist/{agent-builder-Bd6qGrt6.js → agent-builder-C4AIqOxt.js} +1 -1
  4. package/dist/{agent-builder-Bz1beuPE.cjs → agent-builder-dZlRNj1k.cjs} +1 -1
  5. package/dist/{agents-BMdbohgU.js → agents-272TP94y.js} +17 -6
  6. package/dist/{agents-DiQ_L6BU.cjs → agents-mjQZV5tv.cjs} +17 -6
  7. package/dist/{api-schema-manifest-CsefW4Vv.js → api-schema-manifest-BjhiTdNv.js} +1 -1
  8. package/dist/{api-schema-manifest-BuAf53GH.cjs → api-schema-manifest-DVkepK_s.cjs} +1 -1
  9. package/dist/{catalogue-CAIZ08il.cjs → catalogue-BTE9b_mr.cjs} +5 -5
  10. package/dist/{catalogue-BtSLF1p2.js → catalogue-DH64Duv-.js} +5 -5
  11. package/dist/{conversations-6v0VCbif.cjs → conversations-BWA_---j.cjs} +1 -1
  12. package/dist/{conversations-Dzpv_Cgt.js → conversations-CXyaNjLR.js} +1 -1
  13. package/dist/dist-Bn0zFASI.js +1 -0
  14. package/dist/{dist-Czbww9cr.js → dist-Bp1bObAq.js} +290 -25
  15. package/dist/{dist-C0Das1QD.cjs → dist-CSffo32A.cjs} +1 -1
  16. package/dist/{dist-C5rwoPuL.cjs → dist-DGwsCtT4.cjs} +290 -25
  17. package/dist/docs/SKILL.md +1 -1
  18. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  19. package/dist/{editor-builder-Cx9ZiHBw.cjs → editor-builder-BS2xogE_.cjs} +1 -1
  20. package/dist/{editor-builder-DpNB1W4s.js → editor-builder-BayzCprJ.js} +1 -1
  21. package/dist/{plans-DYNE2s8s.cjs → plans-Bes_LVgv.cjs} +1 -1
  22. package/dist/{plans-BoUO4vWD.js → plans-xGwuiZUd.js} +1 -1
  23. package/dist/{probe-image-size-DQsyQSUh.cjs → probe-image-size-BR5MlnnJ.cjs} +1 -1
  24. package/dist/{probe-image-size-C0BvSeqt.js → probe-image-size-DBCcUUw_.js} +1 -1
  25. package/dist/{responses-ByDnfqlJ.cjs → responses-BH567IZf.cjs} +1 -1
  26. package/dist/{responses-CGv4KFQ3.js → responses-CwQO5y2X.js} +1 -1
  27. package/dist/{routes-BLjObOVE.cjs → routes-6p-xrUIq.cjs} +11 -11
  28. package/dist/{routes-C0TLNOPH.js → routes-CrBCJmjc.js} +11 -11
  29. package/dist/{scores-EVbkxGHy.cjs → scores-CXNkN7Bn.cjs} +1 -1
  30. package/dist/{scores-CqNF-thA.js → scores-ksmJiJnJ.js} +1 -1
  31. package/dist/server/handlers/a2a.cjs +1 -1
  32. package/dist/server/handlers/a2a.js +1 -1
  33. package/dist/server/handlers/agent-builder.cjs +1 -1
  34. package/dist/server/handlers/agent-builder.js +1 -1
  35. package/dist/server/handlers/agents.cjs +1 -1
  36. package/dist/server/handlers/agents.js +1 -1
  37. package/dist/server/handlers/conversations.cjs +1 -1
  38. package/dist/server/handlers/conversations.js +1 -1
  39. package/dist/server/handlers/editor-builder.cjs +1 -1
  40. package/dist/server/handlers/editor-builder.js +1 -1
  41. package/dist/server/handlers/favorites-enrichment.cjs +1 -1
  42. package/dist/server/handlers/favorites-enrichment.js +1 -1
  43. package/dist/server/handlers/plans.cjs +1 -1
  44. package/dist/server/handlers/plans.js +1 -1
  45. package/dist/server/handlers/responses.cjs +1 -1
  46. package/dist/server/handlers/responses.js +1 -1
  47. package/dist/server/handlers/scores.cjs +1 -1
  48. package/dist/server/handlers/scores.js +1 -1
  49. package/dist/server/handlers/stored-agent-favorites.cjs +1 -1
  50. package/dist/server/handlers/stored-agent-favorites.js +1 -1
  51. package/dist/server/handlers/stored-agents.cjs +1 -1
  52. package/dist/server/handlers/stored-agents.js +1 -1
  53. package/dist/server/handlers/stored-skill-favorites.cjs +1 -1
  54. package/dist/server/handlers/stored-skill-favorites.js +1 -1
  55. package/dist/server/handlers/stored-skills.cjs +1 -1
  56. package/dist/server/handlers/stored-skills.js +1 -1
  57. package/dist/server/handlers/system.cjs +1 -1
  58. package/dist/server/handlers/system.js +1 -1
  59. package/dist/server/handlers/tools.cjs +1 -1
  60. package/dist/server/handlers/tools.js +1 -1
  61. package/dist/server/handlers/voice.cjs +1 -1
  62. package/dist/server/handlers/voice.js +1 -1
  63. package/dist/server/handlers.cjs +9 -9
  64. package/dist/server/handlers.js +9 -9
  65. package/dist/server/server-adapter/index.cjs +2 -2
  66. package/dist/server/server-adapter/index.js +2 -2
  67. package/dist/server/server-adapter/routes/conversations.d.ts +3 -3
  68. package/dist/{server-adapter-CxMHZZAv.js → server-adapter-BGOi-s7x.js} +1 -1
  69. package/dist/{server-adapter-BkAKl970.cjs → server-adapter-Ceag3til.cjs} +1 -1
  70. package/dist/{tools-CZmeb9MB.js → tools-CY44YtDW.js} +1 -1
  71. package/dist/{tools-D07qyAT0.cjs → tools-DLZ7go-n.cjs} +1 -1
  72. package/dist/{voice-BNwHCtxv.js → voice-DTjrAgqg.js} +1 -1
  73. package/dist/{voice-DN72TM58.cjs → voice-NaerSeVQ.cjs} +1 -1
  74. package/package.json +3 -3
  75. package/dist/dist-C_7xKME1.js +0 -1
@@ -8655,7 +8655,7 @@ function splitLines(text) {
8655
8655
  else result.push(result.pop().slice(0, -1));
8656
8656
  return result;
8657
8657
  }
8658
- // ../memory/dist/src-CRmfe-8x.js
8658
+ // ../memory/dist/src-CDv__4kY.js
8659
8659
  var __defProp$3 = Object.defineProperty;
8660
8660
  var __exportAll = (all, no_symbols) => {
8661
8661
  let target = {};
@@ -37277,7 +37277,7 @@ async function resolveImageDimensionsAsync(part) {
37277
37277
  const url = resolveHttpAssetUrl(getObjectValue(part, "image") ?? getObjectValue(part, "data"));
37278
37278
  if (!url) return existing;
37279
37279
  try {
37280
- const probeImageSize = (await import("./probe-image-size-C0BvSeqt.js").then((m) => /* @__PURE__ */ __toESM$1(m.default, 1))).default;
37280
+ const probeImageSize = (await import("./probe-image-size-DBCcUUw_.js").then((m) => /* @__PURE__ */ __toESM$1(m.default, 1))).default;
37281
37281
  const probed = await probeImageSize(url, {
37282
37282
  open_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
37283
37283
  response_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
@@ -41497,6 +41497,79 @@ var BufferingCoordinator = class BufferingCoordinator {
41497
41497
  * Key format: "refl:{lockKey}"
41498
41498
  */
41499
41499
  static reflectionBufferCycleIds = /* @__PURE__ */ new Map();
41500
+ /**
41501
+ * The buffered-reflection op that set the reflection boundary and cycle, and the generation
41502
+ * it buffers for. Key format: "refl:{lockKey}"
41503
+ */
41504
+ static reflectionBufferOwners = /* @__PURE__ */ new Map();
41505
+ /** Set the reflection boundary for a new buffered-reflection op on generation `recordId`. */
41506
+ static startReflectionBuffer(bufferKey, tokens, recordId) {
41507
+ const owner = {
41508
+ recordId,
41509
+ retired: false
41510
+ };
41511
+ BufferingCoordinator.lastBufferedBoundary.set(bufferKey, tokens);
41512
+ BufferingCoordinator.reflectionBufferOwners.set(bufferKey, owner);
41513
+ return owner;
41514
+ }
41515
+ /** Drop this process's reflection boundary, cycle, and owner. */
41516
+ static clearReflectionBuffer(bufferKey) {
41517
+ BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
41518
+ BufferingCoordinator.reflectionBufferCycleIds.delete(bufferKey);
41519
+ BufferingCoordinator.reflectionBufferOwners.delete(bufferKey);
41520
+ }
41521
+ /**
41522
+ * Another writer retired generation `recordId`, so a buffer this process prepared for it can
41523
+ * never activate. Its boundary and cycle are dropped now, or, while the op that set them is
41524
+ * still running (it may be awaiting its `onReflectionEnd` hook), when that op finishes. State
41525
+ * owned by a newer generation is kept.
41526
+ */
41527
+ static retireReflectionBuffer(bufferKey, recordId) {
41528
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
41529
+ if (owner && owner.recordId !== recordId) return;
41530
+ if (owner && BufferingCoordinator.asyncBufferingOps.has(bufferKey)) {
41531
+ owner.retired = true;
41532
+ return;
41533
+ }
41534
+ BufferingCoordinator.clearReflectionBuffer(bufferKey);
41535
+ }
41536
+ /**
41537
+ * Reconcile this process's reflection buffer state against an observed head record.
41538
+ * Whenever `head.id` differs from `owner.recordId`, confirm against a fresh storage read started
41539
+ * after `owner` existed (never trusting `generationCount`, which resets to 0 after `clear()`):
41540
+ * only retire/clear when storage's live head is no longer `owner.recordId`.
41541
+ */
41542
+ static async reconcileReflectionBufferHead(bufferKey, headId, readLiveHead) {
41543
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
41544
+ if (!owner || owner.recordId === headId) return;
41545
+ const ownerRecordId = owner.recordId;
41546
+ const live = await readLiveHead();
41547
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner || owner.recordId !== ownerRecordId) return;
41548
+ if (live?.id === ownerRecordId) return;
41549
+ if (BufferingCoordinator.asyncBufferingOps.has(bufferKey)) {
41550
+ owner.retired = true;
41551
+ return;
41552
+ }
41553
+ BufferingCoordinator.clearReflectionBuffer(bufferKey);
41554
+ }
41555
+ /**
41556
+ * Take the buffered-reflection cycle id for generation `recordId` and release its
41557
+ * coordinator state after its buffer activates. State owned by another generation
41558
+ * is left untouched.
41559
+ */
41560
+ static consumeReflectionBuffer(bufferKey, recordId) {
41561
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
41562
+ if (owner && owner.recordId !== recordId) return void 0;
41563
+ const cycleId = BufferingCoordinator.reflectionBufferCycleIds.get(bufferKey);
41564
+ if (owner && BufferingCoordinator.asyncBufferingOps.has(bufferKey)) owner.retired = true;
41565
+ else BufferingCoordinator.clearReflectionBuffer(bufferKey);
41566
+ return cycleId;
41567
+ }
41568
+ /** Called when the op that started as `owner` finishes; completes a deferred retirement. */
41569
+ static finishReflectionBuffer(bufferKey, owner) {
41570
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) return;
41571
+ if (owner.retired) BufferingCoordinator.clearReflectionBuffer(bufferKey);
41572
+ }
41500
41573
  constructor(opts) {
41501
41574
  this.observationConfig = opts.observationConfig;
41502
41575
  this.reflectionConfig = opts.reflectionConfig;
@@ -41552,6 +41625,7 @@ var BufferingCoordinator = class BufferingCoordinator {
41552
41625
  BufferingCoordinator.asyncBufferingOps.delete(obsBufKey);
41553
41626
  BufferingCoordinator.asyncBufferingOps.delete(reflBufKey);
41554
41627
  BufferingCoordinator.reflectionBufferCycleIds.delete(reflBufKey);
41628
+ BufferingCoordinator.reflectionBufferOwners.delete(reflBufKey);
41555
41629
  }
41556
41630
  }
41557
41631
  /**
@@ -44404,6 +44478,79 @@ var ObservationTurn = class {
44404
44478
  };
44405
44479
  }
44406
44480
  };
44481
+ const pendingValuesBaseSchema = z$2.object({
44482
+ recordId: z$2.string(),
44483
+ reflectedObservationLineCount: z$2.number(),
44484
+ values: z$2.record(z$2.string(), z$2.unknown())
44485
+ });
44486
+ const pendingValuesSchema = z$2.union([pendingValuesBaseSchema.extend({
44487
+ reflectionDigest: z$2.string().regex(/^[a-f0-9]{64}$/),
44488
+ reflection: z$2.never().optional()
44489
+ }), pendingValuesBaseSchema.extend({
44490
+ reflection: z$2.string(),
44491
+ reflectionDigest: z$2.never().optional()
44492
+ })]);
44493
+ const metadataSchema = z$2.record(z$2.string(), z$2.unknown());
44494
+ function reflectionDigest(reflection) {
44495
+ return createHash("sha256").update(reflection).digest("hex");
44496
+ }
44497
+ function getMastraMetadata(metadata) {
44498
+ const parsed = metadataSchema.safeParse(metadata?.mastra);
44499
+ return parsed.success ? parsed.data : {};
44500
+ }
44501
+ /** Keep prepared values outside active OM metadata, durable across Memory instances. */
44502
+ async function stageBufferedReflectionValues(storage, record, values) {
44503
+ if (!record.threadId || !record.bufferedReflection) return;
44504
+ const digest = reflectionDigest(record.bufferedReflection);
44505
+ await storage.updateThreadMetadata({
44506
+ id: record.threadId,
44507
+ update: (thread) => ({
44508
+ ...thread.metadata,
44509
+ mastra: {
44510
+ ...getMastraMetadata(thread.metadata),
44511
+ omBufferedReflection: {
44512
+ recordId: record.id,
44513
+ reflectionDigest: digest,
44514
+ reflectedObservationLineCount: record.reflectedObservationLineCount ?? 0,
44515
+ values: values ?? {}
44516
+ }
44517
+ }
44518
+ })
44519
+ });
44520
+ }
44521
+ /** Called under the OM commit lock, only after this exact buffer was activated. */
44522
+ async function publishBufferedReflectionValues(storage, extractors, record) {
44523
+ if (!record.threadId || !record.bufferedReflection) return;
44524
+ const digest = reflectionDigest(record.bufferedReflection);
44525
+ await storage.updateThreadMetadata({
44526
+ id: record.threadId,
44527
+ update: (thread) => {
44528
+ const mastra = getMastraMetadata(thread.metadata);
44529
+ const parsed = pendingValuesSchema.safeParse(mastra.omBufferedReflection);
44530
+ if (!parsed.success) return;
44531
+ const pending = parsed.data;
44532
+ if (pending.recordId !== record.id || (pending.reflectionDigest !== void 0 ? pending.reflectionDigest !== digest : pending.reflection !== record.bufferedReflection) || pending.reflectedObservationLineCount !== (record.reflectedObservationLineCount ?? 0)) return;
44533
+ const update = buildThreadMetadataFromExtractedValues(extractors, pending.values);
44534
+ const previous = getThreadOMMetadata(thread.metadata);
44535
+ const metadata = setThreadOMMetadata(thread.metadata, {
44536
+ currentTask: update.currentTask ?? previous?.currentTask,
44537
+ suggestedResponse: update.suggestedResponse ?? previous?.suggestedResponse,
44538
+ threadTitle: update.threadTitle ?? previous?.threadTitle,
44539
+ extracted: {
44540
+ ...previous?.extracted,
44541
+ ...update.extracted
44542
+ }
44543
+ });
44544
+ return {
44545
+ ...metadata,
44546
+ mastra: {
44547
+ ...getMastraMetadata(metadata),
44548
+ omBufferedReflection: null
44549
+ }
44550
+ };
44551
+ }
44552
+ });
44553
+ }
44407
44554
  /**
44408
44555
  * Build the Reflector's system prompt.
44409
44556
  *
@@ -44761,6 +44908,15 @@ function isReflectionApplied(returned, newRecordId, reflectedRecordId) {
44761
44908
  return returned.supersededBy === void 0 && returned.id !== reflectedRecordId;
44762
44909
  }
44763
44910
  /**
44911
+ * The active observations a buffered-reflection swap writes: the buffered reflection replaces the
44912
+ * first `reflectedLineCount` lines, and the trimmed remainder follows after a blank line. Mirrors
44913
+ * `swapBufferedReflectionToActive` in the storage adapters.
44914
+ */
44915
+ function bufferedActivationText({ bufferedReflection, observations, reflectedLineCount }) {
44916
+ const unreflected = observations.split("\n").slice(reflectedLineCount).join("\n").trim();
44917
+ return unreflected ? `${bufferedReflection}\n\n${unreflected}` : bufferedReflection;
44918
+ }
44919
+ /**
44764
44920
  * Runs the Reflector agent for compressing observations.
44765
44921
  * Handles synchronous reflection, async buffered reflection, and activation.
44766
44922
  */
@@ -45069,18 +45225,18 @@ var ReflectorRunner = class {
45069
45225
  startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
45070
45226
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
45071
45227
  if (this.buffering.isAsyncBufferingInProgress(bufferKey)) return;
45072
- BufferingCoordinator.lastBufferedBoundary.set(bufferKey, observationTokens);
45228
+ const owner = BufferingCoordinator.startReflectionBuffer(bufferKey, observationTokens, record.id);
45073
45229
  registerOp(record.id, "bufferingReflection");
45074
45230
  const flagSet = this.storage.setBufferingReflectionFlag(record.id, true).catch((err) => {
45075
45231
  omError("[OM] Failed to set buffering reflection flag", err);
45076
45232
  });
45077
- const asyncOp = (async () => {
45233
+ const run = async () => {
45078
45234
  await flagSet;
45079
45235
  let outcome;
45080
45236
  let reflectionError;
45081
45237
  try {
45082
45238
  await reflectionHooks?.onReflectionStart?.();
45083
- outcome = await this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
45239
+ outcome = await this.doAsyncBufferedReflection(record, bufferKey, owner, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
45084
45240
  } catch (error) {
45085
45241
  reflectionError = error instanceof Error ? error : new Error(String(error));
45086
45242
  if (writer) try {
@@ -45103,7 +45259,7 @@ var ReflectorRunner = class {
45103
45259
  omError("[OM] Failed to persist buffering-failed marker after async buffered reflection failure", markerError);
45104
45260
  }
45105
45261
  omError("[OM] Async buffered reflection failed", error);
45106
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
45262
+ owner.retired = true;
45107
45263
  } finally {
45108
45264
  try {
45109
45265
  await reflectionHooks?.onReflectionEnd?.({
@@ -45114,13 +45270,15 @@ var ReflectorRunner = class {
45114
45270
  } catch (hookError) {
45115
45271
  omError("[OM] onReflectionEnd hook failed after async buffered reflection", hookError);
45116
45272
  }
45117
- BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
45273
+ BufferingCoordinator.finishReflectionBuffer(bufferKey, owner);
45274
+ if (BufferingCoordinator.asyncBufferingOps.get(bufferKey) === asyncOp) BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
45118
45275
  unregisterOp(record.id, "bufferingReflection");
45119
45276
  await this.storage.setBufferingReflectionFlag(record.id, false).catch((err) => {
45120
45277
  omError("[OM] Failed to clear buffering reflection flag", err);
45121
45278
  });
45122
45279
  }
45123
- })();
45280
+ };
45281
+ const asyncOp = run();
45124
45282
  BufferingCoordinator.asyncBufferingOps.set(bufferKey, asyncOp);
45125
45283
  this.trackBackgroundWork?.(asyncOp, lockKey);
45126
45284
  }
@@ -45128,13 +45286,27 @@ var ReflectorRunner = class {
45128
45286
  * Perform async buffered reflection — reflects observations and stores to bufferedReflection.
45129
45287
  * Does NOT create a new generation or update activeObservations.
45130
45288
  */
45131
- async doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
45132
- const currentRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId) ?? record;
45289
+ async doAsyncBufferedReflection(record, bufferKey, owner, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
45290
+ const freshRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45291
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) {
45292
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: ${bufferKey} was cleared while the op waited; stopping`);
45293
+ return;
45294
+ }
45295
+ const currentRecord = freshRecord ?? record;
45296
+ if (freshRecord?.bufferedReflection) {
45297
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: live head ${freshRecord.id} already has a buffered reflection; skipping duplicate run`);
45298
+ owner.retired = true;
45299
+ return;
45300
+ }
45133
45301
  const observationTokens = currentRecord.observationTokenCount ?? 0;
45134
45302
  const reflectThreshold = getMaxThreshold(this.getEffectiveReflectionTokens(currentRecord));
45135
45303
  const bufferActivation = this.reflectionConfig.bufferActivation ?? .5;
45136
45304
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
45137
45305
  const cycleId = `reflect-buf-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
45306
+ if (owner.recordId !== currentRecord.id) {
45307
+ owner.recordId = currentRecord.id;
45308
+ owner.retired = false;
45309
+ }
45138
45310
  BufferingCoordinator.reflectionBufferCycleIds.set(bufferKey, cycleId);
45139
45311
  const allLines = (currentRecord.activeObservations ?? "").split("\n");
45140
45312
  const totalLines = allLines.length;
@@ -45171,10 +45343,18 @@ var ReflectorRunner = class {
45171
45343
  const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
45172
45344
  const reflectResult = await this.call(activeObservations, void 0, void 0, compressionTarget, void 0, true, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal, currentModel);
45173
45345
  reflectResult.observations = await applyTextTransform(this.hooks, "afterReflection", reflectResult.observations, hookContext);
45346
+ if (!reflectResult.observations.trim()) {
45347
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: reflection for ${currentRecord.id} is empty after afterReflection; discarding it`);
45348
+ owner.retired = true;
45349
+ return {
45350
+ usage: reflectResult.usage,
45351
+ providerMetadata: reflectResult.providerMetadata
45352
+ };
45353
+ }
45174
45354
  const reflectionTokenCount = this.tokenCounter.countObservations(reflectResult.observations);
45175
45355
  omDebug(`[OM:reflect] doAsyncBufferedReflection: reflector returned ${reflectionTokenCount} tokens (${reflectResult.observations?.length} chars), saving to recordId=${currentRecord.id}`);
45176
45356
  if (!await runOMCommit(this.buffering.getLockKey(currentRecord.threadId, currentRecord.resourceId), async () => {
45177
- if ((await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId))?.id !== currentRecord.id) return false;
45357
+ if ((await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId))?.id !== currentRecord.id || BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) return false;
45178
45358
  await this.storage.updateBufferedReflection({
45179
45359
  id: currentRecord.id,
45180
45360
  reflection: reflectResult.observations,
@@ -45182,17 +45362,18 @@ var ReflectorRunner = class {
45182
45362
  inputTokenCount: sliceTokenEstimate,
45183
45363
  reflectedObservationLineCount
45184
45364
  });
45365
+ const buffered = await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId);
45366
+ if (buffered?.id === currentRecord.id && buffered.bufferedReflection === reflectResult.observations) await stageBufferedReflectionValues(this.storage, buffered, reflectResult.extractedValues);
45185
45367
  return true;
45186
45368
  })) {
45187
45369
  omDebug(`[OM:reflect] doAsyncBufferedReflection: record ${currentRecord.id} is no longer the head; discarding the buffered reflection`);
45188
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
45370
+ owner.retired = true;
45189
45371
  return {
45190
45372
  usage: reflectResult.usage,
45191
45373
  providerMetadata: reflectResult.providerMetadata
45192
45374
  };
45193
45375
  }
45194
45376
  omDebug(`[OM:reflect] doAsyncBufferedReflection: bufferedReflection saved with lineCount=${reflectedObservationLineCount}`);
45195
- await persistThreadExtractedValues(this.storage, this.reflectionConfig.extractors, currentRecord.threadId ?? void 0, reflectResult.extractedValues);
45196
45377
  if (writer) {
45197
45378
  const endMarker = createBufferingEndMarker({
45198
45379
  cycleId,
@@ -45218,6 +45399,57 @@ var ReflectorRunner = class {
45218
45399
  };
45219
45400
  }
45220
45401
  /**
45402
+ * Decide what a buffered-reflection swap did. Built-in adapters only swap the buffer and line
45403
+ * count in the snapshot, return the stored record (no new generation) when another writer
45404
+ * extended them after the head check, and mark a generation they created after that check with
45405
+ * `bufferedReflectionVerified`. Adapters without that check build the new generation from
45406
+ * whatever is stored. Either way the swap must also produce what the snapshot's buffer and line
45407
+ * count give from the text the swap retired (retired records are never written again, so that
45408
+ * text is exactly what the swap read).
45409
+ *
45410
+ * Staged values are published only with the adapter's proof. Without it an extension that
45411
+ * repeats the unreflected tail produces the same text as the snapshot's buffer, so the values
45412
+ * fail closed: the activation still applies, but the staged values stay unpublished.
45413
+ */
45414
+ async classifyBufferedReflectionSwap({ result, newRecordId, snapshot, bufferedReflection, reflectedLineCount }) {
45415
+ if (result.id === snapshot.id) return {
45416
+ kind: "not-applied",
45417
+ headId: result.id
45418
+ };
45419
+ const createdByThisSwap = result.id === newRecordId;
45420
+ if (!createdByThisSwap && result.supersededBy !== void 0) return {
45421
+ kind: "not-applied",
45422
+ headId: result.id
45423
+ };
45424
+ const swapActiveObservations = result.activeObservations;
45425
+ const bufferedReflectionVerified = result.bufferedReflectionVerified === true;
45426
+ let matchesSnapshotBuffer = false;
45427
+ try {
45428
+ const retired = (await this.storage.getObservationalMemoryHistory(snapshot.threadId, snapshot.resourceId, 5, { recordId: snapshot.id })).find((candidate) => candidate.id === snapshot.id);
45429
+ matchesSnapshotBuffer = retired !== void 0 && swapActiveObservations === bufferedActivationText({
45430
+ bufferedReflection,
45431
+ observations: retired.activeObservations,
45432
+ reflectedLineCount
45433
+ });
45434
+ } catch (error) {
45435
+ omError("[OM] Failed to read the generation retired by buffered reflection activation", error);
45436
+ }
45437
+ const snapshotBufferActivated = matchesSnapshotBuffer && bufferedReflectionVerified;
45438
+ if (createdByThisSwap) return {
45439
+ kind: "applied",
45440
+ record: result,
45441
+ snapshotBufferActivated
45442
+ };
45443
+ return matchesSnapshotBuffer ? {
45444
+ kind: "applied",
45445
+ record: result,
45446
+ snapshotBufferActivated
45447
+ } : {
45448
+ kind: "not-applied",
45449
+ headId: result.id
45450
+ };
45451
+ }
45452
+ /**
45221
45453
  * Try to activate buffered reflection when threshold is reached.
45222
45454
  * Returns a discriminated result so the caller can distinguish between
45223
45455
  * "activated", "no buffer present", and "suppressed by overshoot guard"
@@ -45237,18 +45469,26 @@ var ReflectorRunner = class {
45237
45469
  }
45238
45470
  }
45239
45471
  }
45240
- const freshRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45472
+ const storedRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45473
+ const freshRecord = storedRecord ? { ...storedRecord } : void 0;
45241
45474
  omDebug(`[OM:reflect] tryActivateBufferedReflection: recordId=${record.id}, hasBufferedReflection=${!!freshRecord?.bufferedReflection}, bufferedReflectionLen=${freshRecord?.bufferedReflection?.length ?? 0}`);
45242
45475
  omDebug(`[OM:reflect] tryActivateBufferedReflection: freshRecord.id=${freshRecord?.id}, freshBufferedReflection=${freshRecord?.bufferedReflection ? "present (" + freshRecord.bufferedReflection.length + " chars)" : "empty"}, freshObsTokens=${freshRecord?.observationTokenCount}`);
45476
+ if (freshRecord) await BufferingCoordinator.reconcileReflectionBufferHead(bufferKey, freshRecord.id, () => this.storage.getObservationalMemory(record.threadId, record.resourceId));
45243
45477
  if (!freshRecord?.bufferedReflection) {
45244
45478
  omDebug(`[OM:reflect] tryActivateBufferedReflection: no buffered reflection after re-fetch`);
45245
45479
  return { status: "no-buffer" };
45246
45480
  }
45247
45481
  const beforeTokens = freshRecord.observationTokenCount ?? 0;
45248
45482
  const reflectedLineCount = freshRecord.reflectedObservationLineCount ?? 0;
45249
- const unreflectedLines = (freshRecord.activeObservations ?? "").split("\n").slice(reflectedLineCount);
45483
+ const currentObservations = freshRecord.activeObservations ?? "";
45484
+ const unreflectedLines = currentObservations.split("\n").slice(reflectedLineCount);
45250
45485
  const unreflectedContent = unreflectedLines.join("\n").trim();
45251
- const combinedObservations = unreflectedContent ? `${freshRecord.bufferedReflection}\n\n${unreflectedContent}` : freshRecord.bufferedReflection;
45486
+ const bufferedReflection = freshRecord.bufferedReflection;
45487
+ const combinedObservations = bufferedActivationText({
45488
+ bufferedReflection,
45489
+ observations: currentObservations,
45490
+ reflectedLineCount
45491
+ });
45252
45492
  const combinedTokenCount = this.tokenCounter.countObservations(combinedObservations);
45253
45493
  if (activationMetadata?.triggeredBy === "ttl" || activationMetadata?.triggeredBy === "provider_change") {
45254
45494
  const unreflectedTailTokens = unreflectedContent ? this.tokenCounter.countObservations(unreflectedContent) : 0;
@@ -45274,28 +45514,48 @@ var ReflectorRunner = class {
45274
45514
  }
45275
45515
  omDebug(`[OM:reflect] tryActivateBufferedReflection: activating, beforeTokens=${beforeTokens}, combinedTokenCount=${combinedTokenCount}, reflectedLineCount=${reflectedLineCount}, unreflectedLines=${unreflectedLines.length}`);
45276
45516
  const newRecordId = crypto.randomUUID();
45277
- const swapped = await runOMCommit(lockKey, () => {
45517
+ const commit = await runOMCommit(lockKey, async () => {
45278
45518
  abortSignal?.throwIfAborted();
45279
- return this.storage.swapBufferedReflectionToActive({
45519
+ const head = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45520
+ if (head && (head.id !== freshRecord.id || head.bufferedReflection !== freshRecord.bufferedReflection || head.reflectedObservationLineCount !== freshRecord.reflectedObservationLineCount)) return {
45521
+ kind: "not-applied",
45522
+ headId: head.id
45523
+ };
45524
+ const result = await this.storage.swapBufferedReflectionToActive({
45280
45525
  currentRecord: freshRecord,
45281
45526
  tokenCount: combinedTokenCount,
45282
45527
  newRecordId
45283
45528
  });
45529
+ const outcome = await this.classifyBufferedReflectionSwap({
45530
+ result,
45531
+ newRecordId,
45532
+ snapshot: freshRecord,
45533
+ bufferedReflection,
45534
+ reflectedLineCount
45535
+ });
45536
+ if (outcome.kind === "applied" && outcome.snapshotBufferActivated) try {
45537
+ await publishBufferedReflectionValues(this.storage, this.reflectionConfig.extractors, freshRecord);
45538
+ } catch (error) {
45539
+ omError("[OM] Failed to publish buffered reflection values after activation", error);
45540
+ }
45541
+ return outcome;
45284
45542
  }, {
45285
45543
  priority: "reflection",
45286
45544
  abortSignal
45287
45545
  });
45288
- if (!isReflectionApplied(swapped, newRecordId, freshRecord.id)) {
45289
- omDebug(`[OM:reflect] tryActivateBufferedReflection: buffered reflection on ${freshRecord.id} not applied (head is ${swapped.id})`);
45546
+ if (commit.kind === "not-applied") {
45547
+ omDebug(`[OM:reflect] tryActivateBufferedReflection: buffered reflection on ${freshRecord.id} not applied (head is ${commit.headId})`);
45548
+ if (commit.headId !== freshRecord.id) BufferingCoordinator.retireReflectionBuffer(bufferKey, freshRecord.id);
45290
45549
  return { status: "not-applied" };
45291
45550
  }
45292
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
45551
+ if (!commit.snapshotBufferActivated) omDebug(`[OM:reflect] tryActivateBufferedReflection: ${commit.record.id} does not hold exactly the snapshot's buffered reflection (extended by another writer, or unverifiable); staged values stay unpublished`);
45552
+ const originalCycleId = BufferingCoordinator.consumeReflectionBuffer(bufferKey, freshRecord.id);
45293
45553
  const afterRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
45294
45554
  const afterTokens = afterRecord?.observationTokenCount ?? 0;
45295
45555
  omDebug(`[OM:reflect] tryActivateBufferedReflection: activation complete! beforeTokens=${beforeTokens}, afterTokens=${afterTokens}, newRecordId=${afterRecord?.id}, newGenCount=${afterRecord?.generationCount}`);
45296
45556
  if (writer) {
45297
45557
  const activationMarker = createActivationMarker({
45298
- cycleId: BufferingCoordinator.reflectionBufferCycleIds.get(bufferKey) ?? `reflect-act-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
45558
+ cycleId: originalCycleId ?? `reflect-act-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
45299
45559
  operationType: "reflection",
45300
45560
  chunksActivated: 1,
45301
45561
  tokensActivated: beforeTokens,
@@ -45321,7 +45581,6 @@ var ReflectorRunner = class {
45321
45581
  }).catch(() => {});
45322
45582
  await this.persistMarkerToMessage(activationMarker, messageList, freshRecord.threadId ?? "", freshRecord.resourceId ?? void 0, abortSignal);
45323
45583
  }
45324
- BufferingCoordinator.reflectionBufferCycleIds.delete(bufferKey);
45325
45584
  return { status: "activated" };
45326
45585
  }
45327
45586
  /**
@@ -45338,7 +45597,7 @@ var ReflectorRunner = class {
45338
45597
  const priorExtractedValues = await getThreadExtractedValues(this.storage, this.reflectionConfig.extractors, requestedThreadId ?? record.threadId);
45339
45598
  abortSignal?.throwIfAborted();
45340
45599
  if (this.buffering.isAsyncReflectionEnabled() && observationTokens < reflectThreshold) {
45341
- if ((() => {
45600
+ if (await (async () => {
45342
45601
  if (!this.buffering.isAsyncReflectionEnabled()) return false;
45343
45602
  if (record.isBufferingReflection) {
45344
45603
  if (isOpActiveInProcess(record.id, "bufferingReflection")) return false;
@@ -45346,6 +45605,7 @@ var ReflectorRunner = class {
45346
45605
  this.storage.setBufferingReflectionFlag(record.id, false).catch(() => {});
45347
45606
  }
45348
45607
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
45608
+ await BufferingCoordinator.reconcileReflectionBufferHead(bufferKey, record.id, () => this.storage.getObservationalMemory(record.threadId, record.resourceId));
45349
45609
  if (this.buffering.isAsyncBufferingInProgress(bufferKey)) return false;
45350
45610
  if (BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) return false;
45351
45611
  if (record.bufferedReflection) return false;
@@ -45391,6 +45651,11 @@ var ReflectorRunner = class {
45391
45651
  omDebug(`[OM:reflect] skipping async reflection — observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
45392
45652
  return;
45393
45653
  }
45654
+ const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
45655
+ if (this.buffering.isAsyncBufferingInProgress(bufferKey) || BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) {
45656
+ omDebug(`[OM:reflect] skipping async reflection — reflection buffer already active or present for ${bufferKey}`);
45657
+ return;
45658
+ }
45394
45659
  omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) — starting background reflection`);
45395
45660
  this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
45396
45661
  return;
@@ -52793,7 +53058,7 @@ const createModelInstance = async (provider, modelId, version = "v2") => {
52793
53058
  try {
52794
53059
  const providerFn = version === `v1` ? { v1: {
52795
53060
  openai: async () => {
52796
- const { openai } = await import("./dist-C_7xKME1.js");
53061
+ const { openai } = await import("./dist-Bn0zFASI.js");
52797
53062
  return openai(modelId);
52798
53063
  },
52799
53064
  anthropic: async () => {
@@ -1,3 +1,3 @@
1
1
  require("./rolldown-runtime-10nMEhjP.cjs");
2
- const require_dist = require("./dist-C5rwoPuL.cjs");
2
+ const require_dist = require("./dist-DGwsCtT4.cjs");
3
3
  exports.openai = require_dist.openai;