@mastra/core
Version:
1 lines • 114 kB
Source Map (JSON)
{"version":3,"file":"output-helpers-JL-HeCbT.cjs","names":["EventEmitter","getSpanErrorOrigin"],"sources":["../src/events/pubsub.ts","../src/events/event-emitter/batch-policy.ts","../src/events/event-emitter/ack-handle-buffer.ts","../src/events/event-emitter/index.ts","../src/events/acking-callback.ts","../src/stream/strip-model-snapshots.ts","../src/events/topics.ts","../src/events/codec/error.ts","../src/events/caching-pubsub.ts","../src/events/publisher-queue-limit-error.ts","../src/stream/aisdk/v5/output-helpers.ts"],"sourcesContent":["import type { Event, EventCallback, SubscribeOptions } from './types';\n\n/**\n * Delivery model for a PubSub implementation.\n *\n * - `pull`: consumers actively read from the broker (e.g. Redis Streams\n * XREADGROUP, GCP Pub/Sub streamingPull, SQS ReceiveMessage). Mastra runs\n * a long-lived `OrchestrationWorker` that owns a subscription loop.\n *\n * - `push`: events arrive without the consumer asking — either in-process\n * (EventEmitter dispatching to a registered listener) or out-of-process\n * (the broker POSTs to an HTTP endpoint, e.g. GCP Pub/Sub push, SNS,\n * EventBridge). Mastra wires the workflow handler directly to the pubsub\n * for in-process push, or relies on `POST /api/workers/events` for\n * broker push delivered over HTTP.\n */\nexport type PubSubDeliveryMode = 'pull' | 'push';\n\nexport abstract class PubSub {\n abstract publish(\n topic: string,\n event: Omit<Event, 'id' | 'createdAt'>,\n options?: { localOnly?: boolean },\n ): Promise<void>;\n abstract subscribe(topic: string, cb: EventCallback, options?: SubscribeOptions): Promise<void>;\n abstract unsubscribe(topic: string, cb: EventCallback): Promise<void>;\n /**\n * Drain any buffered or in-flight deliveries before resolving.\n *\n * Best-effort: a `flush()` that resolves successfully does not guarantee\n * every subscriber callback succeeded — implementations surface per-event\n * delivery errors via their configured logger rather than re-throwing,\n * so a single failed callback does not mask later cleanup work.\n */\n abstract flush(): Promise<void>;\n\n /**\n * Delete all retained state for a topic (cached history, persistent stream\n * entries, consumer groups) once no more events will be published to it.\n *\n * Called by run lifecycles (durable agents, the evented workflow engine)\n * when a run reaches a terminal state, so per-run topics don't accumulate\n * forever on transports that retain messages (e.g. Redis Streams).\n *\n * Default implementation is a no-op: transports that don't retain anything\n * per topic (e.g. plain EventEmitter delivery) have nothing to clear.\n *\n * Best-effort contract: implementations should not throw — callers invoke\n * this fire-and-forget at cleanup boundaries, so failures should be logged\n * by the implementation rather than rejected.\n *\n * @param topic - The topic whose retained state should be deleted\n */\n clearTopic(_topic: string): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Delete a single run's retained entries from a topic: every entry published\n * with `runId`. Used to drop a thread run's entries once storage holds it, so\n * retained transports (e.g. Redis Streams) stay bounded without touching\n * entries of other runs.\n *\n * Default implementation is a no-op: transports that don't retain anything\n * per topic have nothing to trim. Same best-effort contract as `clearTopic`.\n *\n * @param topic - The topic to trim\n * @param options.runId - The run whose entries to delete\n * @param options.producedBefore - Only delete entries whose `data.producedAt`\n * is at or before this epoch ms and that aren't `data.pinned`. Used to drop\n * the parts of a run that storage already holds while the run continues.\n * @param options.retainTerminalEvents - Preserve final run-completed, run-failed,\n * and run-aborted events, plus run-registered authority metadata, so subscribers\n * can recover outcomes without output and reject superseded executions.\n * Completion events with status suspended are not final and may be trimmed.\n */\n trimTopic(\n _topic: string,\n _options: { runId: string; producedBefore?: number; retainTerminalEvents?: boolean },\n ): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Delivery modes this PubSub implementation supports.\n *\n * Defaults to `['pull']` for backward compatibility — third-party\n * implementations that don't override this property are treated as\n * pull-mode, which preserves today's behavior.\n *\n * Implementations that deliver events without an active read loop (e.g.\n * EventEmitter, GCP Pub/Sub push subscriptions) should declare `'push'`.\n * Implementations that support both modes should declare both.\n */\n get supportedModes(): ReadonlyArray<PubSubDeliveryMode> {\n return ['pull'];\n }\n\n /**\n * Whether this implementation honors `options.batch` on `subscribe()`\n * natively. Defaults to `false`.\n *\n * Implementations that integrate batching internally (e.g. against their\n * own broker retention or via an `AckHandleBuffer`) override this getter\n * and return `true`.\n */\n get supportsNativeBatching(): boolean {\n return false;\n }\n\n /**\n * Whether this implementation supports replay from a numeric event offset.\n * Defaults to `false`.\n */\n get supportsOffsets(): boolean {\n return false;\n }\n\n /**\n * Whether a message delivered to a consumer that neither acks nor nacks it\n * (for example because its process died) is delivered again to a consumer of\n * the same group once the broker considers it abandoned. Defaults to `false`.\n *\n * Workflow recovery leaves the evented runs on such a pubsub to the broker:\n * the message of the step a dead worker held is redelivered, so no recovery\n * pass restarts the run. The broker's abandonment threshold must be at least\n * 30 s, the evented step fence a dead worker leaves behind; a redelivery that\n * arrives before the fence expires is dropped as a duplicate.\n */\n get redeliversUnacked(): boolean {\n return false;\n }\n\n /**\n * Whether a subscriber that attaches after events were published on `topic`\n * can still read them (`getHistory`, a replaying subscribe). A publisher that\n * sends changes against its earlier events resends the whole state when it\n * can't. Defaults to {@link supportsOffsets}.\n * @internal\n */\n __replaysTopic(_topic: string): boolean {\n return this.supportsOffsets;\n }\n\n /**\n * Surface attempts to use an unsupported non-zero offset.\n * Implementations may override this hook to use their configured logger.\n */\n protected onUnsupportedOffset(offset: number): void {\n console.warn(`PubSub implementation does not support replay from offset ${offset}; falling back to full replay.`);\n }\n\n /**\n * Get historical events for a topic.\n * Default implementation returns empty array (no history support).\n * Override in implementations that support event caching.\n *\n * @param topic - The topic to get history for\n * @param offset - Starting index (0-based), defaults to 0\n * @returns Array of events from the specified index\n */\n getHistory(_topic: string, _offset?: number): Promise<Event[]> {\n return Promise.resolve([]);\n }\n\n /**\n * Subscribe to a topic with automatic replay of cached events.\n * First replays any cached history, then subscribes to live events.\n * Default implementation falls back to regular subscribe (no replay).\n * Override in implementations that support event caching.\n *\n * @param topic - The topic to subscribe to\n * @param cb - Callback invoked for each event (both cached and live)\n */\n subscribeWithReplay(topic: string, cb: EventCallback): Promise<void> {\n return this.subscribe(topic, cb);\n }\n\n /**\n * Subscribe to a topic with replay starting from a specific index.\n * This is more efficient than full replay when the client knows their last position.\n * Default implementation falls back to subscribeWithReplay (full replay).\n * Override in implementations that support indexed event caching.\n *\n * @param topic - The topic to subscribe to\n * @param offset - Start replaying from this index (0-based)\n * @param cb - Callback invoked for each event\n */\n subscribeFromOffset(topic: string, offset: number, cb: EventCallback): Promise<void> {\n if (offset !== 0 && !this.supportsOffsets) {\n this.onUnsupportedOffset(offset);\n }\n return this.subscribeWithReplay(topic, cb);\n }\n\n /**\n * The underlying delivery transport, unwrapped through decorators.\n *\n * Decorators that delegate delivery (e.g. `CachingPubSub`) override this to\n * return their inner's raw bus. The `mastra.pubsub` proxy forwards the call\n * to its target, so it also unwraps transparently. Used to detect when two\n * PubSub references are backed by the same transport (e.g. an agent's custom\n * pubsub that is also the Mastra-level bus) so a bridge between them doesn't\n * double-deliver.\n * @internal\n */\n __rawBus(): PubSub {\n return this;\n }\n\n /**\n * Identity probe that sees through binding decorators.\n *\n * The `mastra.pubsub` proxy binds every method to its target, so calling\n * `__self()` on the proxy returns the underlying PubSub instance. Used where\n * reference equality must hold across the proxy (e.g. `CachingPubSub`\n * refusing to follow itself). Unlike `__rawBus`, this does NOT unwrap\n * delegating decorators — a `CachingPubSub` returns itself, not its inner.\n * @internal\n */\n __self(): PubSub {\n return this;\n }\n}\n\n/**\n * Distributed leasing capability, separate from event delivery (`PubSub`).\n *\n * Used by the signals layer to elect a single owner across multiple\n * processes (e.g. serverless invocations) for a given resource — most\n * commonly a thread-key, where the owner is the process that will wake\n * and run the agent stream.\n *\n * Leasing is a distinct concern from pub/sub: a backend only implements\n * this when it can genuinely coordinate a lock (Redis via SET-NX, an\n * in-memory map for single-process). Backends that cannot lease simply do\n * not implement `LeaseProvider`; the signals runtime feature-detects and\n * falls back to {@link NoopLeaseProvider} (always-win / no-op), preserving\n * single-process behavior.\n */\nexport interface LeaseProvider {\n /**\n * Atomically try to acquire a lease on a key.\n *\n * Returns `{ acquired: true, owner }` if the caller claimed the lease,\n * or `{ acquired: false, owner }` where `owner` is the current holder\n * (so the caller can route follow-up work to them). `owner` may be\n * `undefined` if the holder could not be read (rare).\n *\n * @param key - The lease key (e.g. thread key)\n * @param owner - Identifier for the owner (e.g. runId) — used so the\n * same owner can call `acquireLease` idempotently and renew/release.\n * @param ttlMs - Time-to-live in milliseconds for the lease\n */\n acquireLease(key: string, owner: string, ttlMs: number): Promise<{ acquired: boolean; owner?: string }>;\n\n /**\n * Read the current owner of a lease, or `undefined` if no lease is held.\n */\n getLeaseOwner(key: string): Promise<string | undefined>;\n\n /**\n * Release a lease. No-op if the caller is not the current owner\n * (implementations should atomically check ownership before releasing\n * to avoid clobbering a renewal that happened concurrently).\n */\n releaseLease(key: string, owner: string): Promise<void>;\n\n /**\n * Renew an existing lease owned by `owner`, extending its TTL.\n *\n * Returns `true` if the renewal succeeded (caller still owns it),\n * `false` if the lease was lost (TTL expired or another owner took it).\n */\n renewLease(key: string, owner: string, ttlMs: number): Promise<boolean>;\n\n /**\n * Atomically hand a held lease from `fromOwner` to `toOwner`, refreshing\n * its TTL, without ever releasing the key in between.\n *\n * This is the gap-free primitive used when one owner finishes but a\n * follow-up owner must take over the *same* lease key immediately (e.g. a\n * thread run completes and a queued follow-up run drains on the same\n * thread). A naive release-then-acquire would briefly leave the key empty,\n * letting a racing process win the freed lease and start a competing run.\n *\n * Returns `true` if `fromOwner` still held the lease and ownership moved to\n * `toOwner`; `false` if the lease was already lost (expired or taken by a\n * third owner), in which case the caller should fall back to a fresh\n * `acquireLease`.\n *\n * Backends that cannot perform this atomically must still implement it —\n * as a best-effort `releaseLease(from)` followed by `acquireLease(to)` — and\n * document that the swap is non-atomic (a racing process can win the key in\n * the gap). Keeping it required means callers have a single code path and the\n * atomicity guarantee is an explicit per-backend decision rather than a\n * silent caller-side fallback.\n */\n transferLease(key: string, fromOwner: string, toOwner: string, ttlMs: number): Promise<boolean>;\n\n /**\n * Optional. Returns `true` when `error`, thrown by one of the methods above,\n * proves the backend is refusing every client, not just this one (e.g. Redis\n * replaying its dataset after a restart answers `LOADING` to everybody). No\n * other owner can be granted a lease meanwhile, so a caller whose lease\n * lapsed may keep waiting for the backend instead of treating it as lost.\n * Any other error, including a connection failure that may affect only this\n * caller, must return `false`.\n */\n isUnavailableToAll?(error: unknown): boolean;\n}\n\n/**\n * Duck-typed check for whether a value implements {@link LeaseProvider}.\n *\n * Uses structural detection rather than `instanceof` so it works across\n * package boundaries (e.g. a separately-published pubsub backend resolving\n * a different copy of `@mastra/core`).\n */\nexport function isLeaseProvider(value: unknown): value is LeaseProvider {\n if (!value || (typeof value !== 'object' && typeof value !== 'function')) return false;\n const candidate = value as Partial<LeaseProvider>;\n return (\n typeof candidate.acquireLease === 'function' &&\n typeof candidate.getLeaseOwner === 'function' &&\n typeof candidate.releaseLease === 'function' &&\n typeof candidate.renewLease === 'function' &&\n typeof candidate.transferLease === 'function'\n );\n}\n\n/**\n * Always-win / no-op {@link LeaseProvider}. Used by the signals runtime\n * when the configured pubsub does not implement `LeaseProvider` — this\n * preserves single-process behavior where every caller \"wins\" its own\n * lease race and release/renew are inert.\n */\nexport const NoopLeaseProvider: LeaseProvider = {\n acquireLease(_key: string, owner: string, _ttlMs: number): Promise<{ acquired: boolean; owner?: string }> {\n return Promise.resolve({ acquired: true, owner });\n },\n getLeaseOwner(_key: string): Promise<string | undefined> {\n return Promise.resolve(undefined);\n },\n releaseLease(_key: string, _owner: string): Promise<void> {\n return Promise.resolve();\n },\n renewLease(_key: string, _owner: string, _ttlMs: number): Promise<boolean> {\n return Promise.resolve(true);\n },\n transferLease(_key: string, _fromOwner: string, _toOwner: string, _ttlMs: number): Promise<boolean> {\n // Single-process: there is no competing holder, so the handoff always\n // \"succeeds\" — the next owner is free to proceed.\n return Promise.resolve(true);\n },\n};\n","import type { Event, SubscribeBatchOptions } from '../types';\n\n/**\n * Opaque timer handle. We don't care whether the runtime returns a number\n * (browser) or a `Timeout` (Node) — we only ever hand it back to\n * `clearTimeout`. Branding it keeps the type honest (you can't pass an\n * arbitrary number) while staying erasure-free at runtime.\n */\ndeclare const batchPolicyTimerHandleBrand: unique symbol;\nexport type BatchPolicyTimerHandle = { readonly [batchPolicyTimerHandleBrand]: true };\n\n/**\n * Injectable dependencies for `BatchPolicy`. Tests pass fake timers /\n * controllable clocks; production uses Node's `Date.now` / `setTimeout` /\n * `clearTimeout`.\n */\nexport interface BatchPolicyDeps {\n now: () => number;\n setTimeout: (cb: () => void, ms: number) => BatchPolicyTimerHandle;\n clearTimeout: (handle: BatchPolicyTimerHandle) => void;\n}\n\nconst defaultDeps: BatchPolicyDeps = {\n now: () => Date.now(),\n setTimeout: (cb, ms) => setTimeout(cb, ms) as unknown as BatchPolicyTimerHandle,\n clearTimeout: handle => clearTimeout(handle as unknown as Parameters<typeof clearTimeout>[0]),\n};\n\nexport type EnqueueDecision = 'flush-now' | 'wait';\n\nexport const DEFAULT_MAX_BUFFER_SIZE = 256;\nexport const DEFAULT_OVERFLOW: NonNullable<SubscribeBatchOptions['overflow']> = 'coalesce-or-drop-oldest';\n\n/**\n * Internal to `EventEmitterPubSub`. Embedded by `AckHandleBuffer` to decide\n * when a batched subscription should flush (size, time, coalesce, overflow).\n *\n * Not part of the public API — users configure batching via\n * `SubscribeBatchOptions` on `subscribe`.\n */\nexport class BatchPolicy {\n private readonly opts: SubscribeBatchOptions;\n private readonly deps: BatchPolicyDeps;\n private readonly maxBufferSize: number;\n private readonly overflow: NonNullable<SubscribeBatchOptions['overflow']>;\n\n private firstQueuedAt: number | null = null;\n private lastDeliveredAt: number = -Infinity;\n private size = 0;\n private timer: BatchPolicyTimerHandle | null = null;\n private flushHandler: (() => void | Promise<void>) | null = null;\n\n constructor(opts: SubscribeBatchOptions, deps: BatchPolicyDeps = defaultDeps) {\n this.opts = opts;\n this.deps = deps;\n this.maxBufferSize = opts.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE;\n this.overflow = opts.overflow ?? DEFAULT_OVERFLOW;\n }\n\n /** Bind the function invoked when the deadline timer fires. */\n bindFlushHandler(fn: () => void | Promise<void>): void {\n this.flushHandler = fn;\n }\n\n /**\n * Called by the integrator each time an event is enqueued.\n * Returns whether the integrator should flush immediately.\n */\n onEnqueue(event: Event): EnqueueDecision {\n this.size += 1;\n if (this.firstQueuedAt === null) {\n this.firstQueuedAt = this.deps.now();\n }\n\n const now = this.deps.now();\n const intervalFloor = this.lastDeliveredAt + (this.opts.minIntervalMs ?? 0);\n\n // Immediate event — bypass maxWait/maxSize gating, but still respect interval floor.\n if (this.opts.isImmediate?.(event)) {\n if (now >= intervalFloor) {\n return 'flush-now';\n }\n // Hold until the floor; reschedule timer there.\n this.scheduleAt(intervalFloor);\n return 'wait';\n }\n\n // Overflow trigger (regardless of interval — overflow is a budget enforcement).\n if (this.size >= this.maxBufferSize) {\n return 'flush-now';\n }\n\n // maxSize trigger — respects interval floor.\n if (this.opts.maxSize !== undefined && this.size >= this.opts.maxSize) {\n if (now >= intervalFloor) {\n return 'flush-now';\n }\n this.scheduleAt(intervalFloor);\n return 'wait';\n }\n\n // No immediate trigger — schedule the deadline if there is one.\n this.scheduleDeadline();\n return 'wait';\n }\n\n /**\n * Called by the integrator after a successful flush has delivered\n * `deliveredCount` events. Resets timer + firstQueuedAt.\n */\n onFlushed(deliveredCount: number): void {\n this.lastDeliveredAt = this.deps.now();\n this.size = Math.max(0, this.size - deliveredCount);\n this.firstQueuedAt = null;\n this.cancelTimer();\n }\n\n /**\n * Pure helper. Given the caller-owned queue contents, applies `coalesce`\n * and `overflow` to decide what to deliver and what to drop.\n * Order-preserving for kept events.\n */\n prepareBatch(events: Event[]): { delivered: Event[]; dropped: Event[] } {\n let working = events;\n\n // 1. Coalesce, if configured.\n if (this.opts.coalesce) {\n const coalesced = this.opts.coalesce(working);\n // Contract: `coalesce` MUST return a subset of `working` by reference\n // identity. Anything else (fresh objects, even with matching ids)\n // breaks ack routing downstream — AckHandleBuffer keys ack/nack by\n // event reference, and there's no way to map a manufactured event\n // back to the original transport handle. Detect the violation here\n // and discard the whole batch (treat all originals as dropped) rather\n // than silently deliver references with no ack/nack wired up.\n const inputRefs = new Set<Event>(working);\n const allInInput = coalesced.every(e => inputRefs.has(e));\n working = allInInput ? coalesced : [];\n }\n\n const keptRefs = new Set<Event>(working);\n const computeDropped = (): Event[] => events.filter(e => !keptRefs.has(e));\n\n // 2. Overflow handling — only if still over `maxBufferSize`.\n if (working.length <= this.maxBufferSize) {\n return { delivered: working, dropped: computeDropped() };\n }\n\n const overBy = working.length - this.maxBufferSize;\n const isImmediate = this.opts.isImmediate;\n\n let kept: Event[];\n let droppedFromOverflow: Event[];\n\n switch (this.overflow) {\n case 'drop-newest': {\n const splitFromEnd = this.takeWithoutDropping(working, overBy, isImmediate, /* fromEnd */ true);\n kept = splitFromEnd.kept;\n droppedFromOverflow = splitFromEnd.dropped;\n break;\n }\n case 'drop-oldest':\n case 'coalesce-or-drop-oldest':\n default: {\n const splitFromStart = this.takeWithoutDropping(working, overBy, isImmediate, /* fromEnd */ false);\n kept = splitFromStart.kept;\n droppedFromOverflow = splitFromStart.dropped;\n break;\n }\n }\n\n return { delivered: kept, dropped: [...computeDropped(), ...droppedFromOverflow] };\n }\n\n /** Stop the timer and clear policy state. */\n dispose(): void {\n this.cancelTimer();\n this.flushHandler = null;\n this.firstQueuedAt = null;\n this.size = 0;\n }\n\n private scheduleDeadline(): void {\n if (this.opts.maxWaitMs === undefined && this.opts.minIntervalMs === undefined) {\n // No time-based trigger — only `maxSize` / `isImmediate` can flush.\n return;\n }\n\n const firstQueuedAt = this.firstQueuedAt ?? this.deps.now();\n const deadline = this.opts.maxWaitMs !== undefined ? firstQueuedAt + this.opts.maxWaitMs : Number.POSITIVE_INFINITY;\n const floor = this.lastDeliveredAt + (this.opts.minIntervalMs ?? 0);\n const at = Math.max(deadline, floor);\n this.scheduleAt(at);\n }\n\n private scheduleAt(at: number): void {\n if (!isFinite(at)) {\n return;\n }\n this.cancelTimer();\n const delay = Math.max(0, at - this.deps.now());\n this.timer = this.deps.setTimeout(() => {\n this.timer = null;\n const handler = this.flushHandler;\n if (handler) {\n void handler();\n }\n }, delay);\n }\n\n private cancelTimer(): void {\n if (this.timer !== null) {\n this.deps.clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n /**\n * Drop `count` non-immediate items from the start (or end) of `items`.\n * Immediate items are never dropped — if every candidate is immediate,\n * fewer than `count` items are dropped.\n */\n private takeWithoutDropping(\n items: Event[],\n count: number,\n isImmediate: ((e: Event) => boolean) | undefined,\n fromEnd: boolean,\n ): { kept: Event[]; dropped: Event[] } {\n const dropped: Event[] = [];\n const result = [...items];\n let remaining = count;\n\n const order = fromEnd ? [...result.keys()].reverse() : [...result.keys()];\n\n for (const idx of order) {\n if (remaining === 0) break;\n const ev = result[idx]!;\n if (isImmediate?.(ev)) continue;\n dropped.push(ev);\n result[idx] = undefined as unknown as Event;\n remaining -= 1;\n }\n\n const kept = result.filter((e): e is Event => e !== undefined);\n return { kept, dropped };\n }\n}\n","import type { Event, EventCallback, SubscribeBatchOptions } from '../types';\nimport type { BatchPolicyDeps } from './batch-policy';\nimport { BatchPolicy } from './batch-policy';\n\ninterface Entry {\n event: Event;\n ack?: () => Promise<void>;\n nack?: () => Promise<void>;\n}\n\n/**\n * In-process queue used by `EventEmitterPubSub` to turn its\n * one-event-per-emit stream into batched callback invocations.\n * Owns a `BatchPolicy` that decides when to flush (size, time,\n * quiet-period) and holds (event, ack, nack) triples in publish\n * order until that decision fires.\n *\n * Extracted from `EventEmitterPubSub` only so the batching state\n * machine can be tested in isolation. Not a public extension point.\n * State is per-process; the queue dies with the process.\n */\nexport class AckHandleBuffer {\n private readonly policy: BatchPolicy;\n private queue: Entry[] = [];\n private flushing = false;\n private reflush = false;\n private disposed = false;\n\n constructor(\n private readonly cb: EventCallback,\n opts: SubscribeBatchOptions,\n deps?: BatchPolicyDeps,\n private readonly onError?: (err: unknown, ctx: { phase: 'cb' | 'ack-dropped' }) => void,\n ) {\n this.policy = new BatchPolicy(opts, deps);\n // The policy's deadline timer fires this handler fire-and-forget (it\n // discards the returned promise), so a rejection from `flush()` — e.g. a\n // user-supplied `coalesce` throwing inside `prepareBatch`, which lands\n // outside the per-event try/catch below — would otherwise escape as an\n // unhandled rejection on the timer path. The inline flush-now, group, and\n // explicit `flush()` paths each catch this already; route the timer path\n // through the same `onError` channel.\n this.policy.bindFlushHandler(() =>\n this.flush().catch(err => {\n this.onError?.(err, { phase: 'cb' });\n }),\n );\n }\n\n /**\n * Called by the adapter for each event arriving from the underlying transport.\n */\n async push(event: Event, ack?: () => Promise<void>, nack?: () => Promise<void>): Promise<void> {\n if (this.disposed) return;\n this.queue.push({ event, ack, nack });\n const decision = this.policy.onEnqueue(event);\n if (decision === 'flush-now') {\n await this.flush();\n }\n }\n\n /**\n * Drain the current queue regardless of policy state. Safe to call from\n * adapter `flush()` or external code that wants to force delivery.\n */\n async flush(): Promise<void> {\n // A flush-now request that lands while we're already draining is not\n // dropped — latch it so the current pass picks up the new events as\n // soon as it finishes its current snapshot, instead of forcing those\n // events to wait until the policy timer fires.\n if (this.flushing) {\n this.reflush = true;\n return;\n }\n // Empty buffer is a true no-op. `policy.onFlushed` bumps `lastDeliveredAt`,\n // which extends the `minIntervalMs` floor — calling it on every empty\n // flush silently corrupts the cadence for callers that flush() defensively.\n if (this.queue.length === 0) return;\n\n this.flushing = true;\n try {\n do {\n this.reflush = false;\n if (this.queue.length === 0) break;\n\n const snapshot = this.queue;\n this.queue = [];\n\n const events = snapshot.map(e => e.event);\n // Build a reverse index once so we don't pay O(n) per event looking up\n // the original Entry below.\n const byEvent = new Map<Event, Entry>();\n for (const e of snapshot) byEvent.set(e.event, e);\n\n const { delivered, dropped } = this.policy.prepareBatch(events);\n\n // Ack events that were coalesced or overflow-dropped — they should\n // not be redelivered. The transport's own ack is the right hook.\n for (const ev of dropped) {\n const entry = byEvent.get(ev);\n if (entry?.ack) {\n try {\n await entry.ack();\n } catch (err) {\n this.onError?.(err, { phase: 'ack-dropped' });\n }\n }\n }\n\n for (const ev of delivered) {\n // A cb may dispose the buffer mid-flush (e.g. subscriber tearing\n // itself down on a fatal event). Honor it immediately — don't keep\n // feeding events into a callback that asked to stop.\n if (this.disposed) break;\n const entry = byEvent.get(ev);\n try {\n await this.cb(ev, entry?.ack, entry?.nack);\n } catch (err) {\n this.onError?.(err, { phase: 'cb' });\n }\n }\n\n // `policy.size` was incremented once per push; decrement it by\n // everything that left the queue (delivered + dropped) so it doesn't\n // drift upward and trip maxSize prematurely.\n this.policy.onFlushed(delivered.length + dropped.length);\n } while (this.reflush && !this.disposed);\n } finally {\n this.flushing = false;\n }\n }\n\n dispose(): void {\n this.disposed = true;\n this.queue = [];\n this.policy.dispose();\n }\n}\n","import EventEmitter from 'node:events';\nimport type { IMastraLogger } from '../../logger';\nimport { PubSub } from '../pubsub';\nimport type { LeaseProvider, PubSubDeliveryMode } from '../pubsub';\nimport type { Event, EventCallback, SubscribeOptions } from '../types';\nimport { AckHandleBuffer } from './ack-handle-buffer';\n\nexport interface EventEmitterPubSubOptions {\n /**\n * Optional logger for surfacing batched-delivery errors. Falls back to\n * `console.error` when not provided.\n */\n logger?: IMastraLogger;\n}\n\n// Reused for the fan-out delivery path where ack/nack are no-ops: the process\n// is the broker, there is no transport-level redelivery to negotiate. Hoisted\n// to module scope so we don't allocate two new closures per emitted event.\nconst NOOP_ACK = async (): Promise<void> => {};\n\n/**\n * The default pubsub: delivers events inside the process that published them.\n *\n * Several Mastra instances that share one storage but each use their own\n * `EventEmitterPubSub` are not supported for evented workflows: every instance\n * treats the others' runs as its own to recover. A multi-instance evented\n * deployment needs a broker such as Redis Streams, Valkey Streams or Google\n * Cloud Pub/Sub.\n */\nexport class EventEmitterPubSub extends PubSub implements LeaseProvider {\n // EventEmitter dispatches synchronously to listeners, so it can serve both\n // a push consumer (no worker) and a pull-style worker that simply calls\n // `subscribe()` to register a listener. Both modes are advertised so the\n // default in-process setup keeps using OrchestrationWorker, while\n // genuinely push-only transports (GCP Pub/Sub push, SNS, EventBridge)\n // declare `['push']` only and skip the worker.\n override get supportedModes(): ReadonlyArray<PubSubDeliveryMode> {\n return ['pull', 'push'];\n }\n\n /**\n * `EventEmitterPubSub` is strictly in-process, so the `AckHandleBuffer`\n * queue it uses for batching shares the same lifetime as everything\n * else here. Nothing more durable is promised, and nothing less is\n * needed.\n */\n override get supportsNativeBatching(): boolean {\n return true;\n }\n\n /**\n * Ack and nack are no-ops here: a message lives only in the process that\n * published it, so nothing redelivers it once that process stops.\n */\n override get redeliversUnacked(): boolean {\n return false;\n }\n\n private emitter: EventEmitter;\n\n // group → topic → callbacks[]\n private groups: Map<string, Map<string, EventCallback[]>> = new Map();\n // \"topic:group\" → round-robin counter\n private groupCounters: Map<string, number> = new Map();\n // \"topic:group\" → the single listener registered on the emitter for this group\n private groupListeners: Map<string, (event: Event) => void> = new Map();\n\n // Track pending nack redeliveries so flush() can wait and close() can cancel them\n private pendingNacks: Set<ReturnType<typeof setTimeout>> = new Set();\n\n // Track delivery attempts per message id\n private deliveryAttempts: Map<string, number> = new Map();\n\n // topic → (original callback → wrapped listener) for fan-out (non-group) subscribers.\n // Nested keying so the same callback registered on multiple topics keeps\n // a distinct wrapper per topic.\n private fanoutWrappers: Map<string, Map<EventCallback, (event: Event) => void>> = new Map();\n\n // topic → (original callback → buffer). Present only for subscribers that\n // opt into batching via `options.batch`. The buffer is the destination of\n // the emitter listener; it invokes the user cb according to its policy.\n private batchBuffers: Map<string, Map<EventCallback, AckHandleBuffer>> = new Map();\n\n private readonly logger?: IMastraLogger;\n\n constructor(existingEmitter?: EventEmitter, options: EventEmitterPubSubOptions = {}) {\n super();\n this.emitter = existingEmitter ?? new EventEmitter();\n this.logger = options.logger;\n }\n\n /**\n * Debug-hostile silent failures are the default for emitter listeners.\n * Surface buffer-side errors on a single channel so they're at least visible.\n */\n /**\n * Subscribers may return a promise now that they can acknowledge deliveries.\n * This transport is push-only and has nothing to redeliver, so a rejection is\n * logged rather than becoming an unhandled rejection.\n */\n private logSubscriberError(topic: string, err: unknown): void {\n const message = `[EventEmitterPubSub] subscriber failed for ${topic}`;\n if (this.logger) {\n this.logger.error(message, err);\n } else {\n console.error(message, err);\n }\n }\n\n private logBufferError(topic: string, err: unknown, ctx: { phase: 'cb' | 'ack-dropped' }): void {\n const message = `[EventEmitterPubSub] batched ${ctx.phase} failed for ${topic}`;\n if (this.logger) {\n this.logger.error(message, err);\n } else {\n console.error(message, err);\n }\n }\n\n async publish(\n topic: string,\n event: Omit<Event, 'id' | 'createdAt'>,\n _options?: { localOnly?: boolean },\n ): Promise<void> {\n const id = crypto.randomUUID();\n const createdAt = new Date();\n this.emitter.emit(topic, {\n ...event,\n id,\n createdAt,\n deliveryAttempt: 1,\n });\n }\n\n async subscribe(topic: string, cb: EventCallback, options?: SubscribeOptions): Promise<void> {\n if (options?.batch) {\n // Batched path: insert an AckHandleBuffer between the emitter and cb.\n // ack/nack are no-ops at this layer — the process is the broker.\n const buffer = new AckHandleBuffer(cb, options.batch, undefined, (err, ctx) => {\n this.logBufferError(topic, err, ctx);\n });\n let byCb = this.batchBuffers.get(topic);\n if (!byCb) {\n byCb = new Map();\n this.batchBuffers.set(topic, byCb);\n }\n byCb.set(cb, buffer);\n\n if (options.group) {\n // Group path: the group's member list keeps the original `cb` so\n // `unsubscribe(topic, cb)` and round-robin tracking work unchanged.\n // `deliverToGroup` checks `batchBuffers` and routes through the\n // buffer when present.\n this.subscribeWithGroup(topic, cb, options.group);\n } else {\n const wrapper = (event: Event) => {\n // Fire-and-forget — buffer.push can reject if the user-supplied\n // `coalesce` throws or any other policy step fails during an\n // inline flush-now. Surface those through the logger rather\n // than letting them become unhandled rejections.\n void buffer.push(event, NOOP_ACK, NOOP_ACK).catch(err => {\n this.logBufferError(topic, err, { phase: 'cb' });\n });\n };\n let byCbFanout = this.fanoutWrappers.get(topic);\n if (!byCbFanout) {\n byCbFanout = new Map();\n this.fanoutWrappers.set(topic, byCbFanout);\n }\n byCbFanout.set(cb, wrapper);\n this.emitter.on(topic, wrapper);\n }\n return;\n }\n\n if (options?.group) {\n this.subscribeWithGroup(topic, cb, options.group);\n } else {\n const wrapper = (event: Event) => {\n try {\n void Promise.resolve(cb(event, NOOP_ACK, NOOP_ACK)).catch(err => {\n this.logSubscriberError(topic, err);\n });\n } catch (err) {\n this.logSubscriberError(topic, err);\n }\n };\n let byCb = this.fanoutWrappers.get(topic);\n if (!byCb) {\n byCb = new Map();\n this.fanoutWrappers.set(topic, byCb);\n }\n byCb.set(cb, wrapper);\n this.emitter.on(topic, wrapper);\n }\n }\n\n async unsubscribe(topic: string, cb: EventCallback): Promise<void> {\n // Tear down a batching buffer for this (topic, cb) pair, if one was set\n // up by `subscribe`. Done first so any in-flight emitter dispatches\n // ignore further events into a disposed buffer.\n const byCbBuffers = this.batchBuffers.get(topic);\n const buffer = byCbBuffers?.get(cb);\n if (buffer && byCbBuffers) {\n buffer.dispose();\n byCbBuffers.delete(cb);\n if (byCbBuffers.size === 0) this.batchBuffers.delete(topic);\n }\n\n // Check if this callback is in any group for this topic\n for (const [group, topicMap] of this.groups) {\n const members = topicMap.get(topic);\n if (members) {\n const idx = members.indexOf(cb);\n if (idx !== -1) {\n members.splice(idx, 1);\n // If group is now empty for this topic, remove the emitter listener\n if (members.length === 0) {\n topicMap.delete(topic);\n const listenerKey = `${topic}:${group}`;\n const listener = this.groupListeners.get(listenerKey);\n if (listener) {\n this.emitter.off(topic, listener);\n this.groupListeners.delete(listenerKey);\n this.groupCounters.delete(listenerKey);\n }\n }\n if (topicMap.size === 0) {\n this.groups.delete(group);\n }\n return;\n }\n }\n }\n\n // Not in a group — remove as fan-out listener\n const byCb = this.fanoutWrappers.get(topic);\n const wrapper = byCb?.get(cb);\n if (wrapper && byCb) {\n this.emitter.off(topic, wrapper);\n byCb.delete(cb);\n if (byCb.size === 0) this.fanoutWrappers.delete(topic);\n } else {\n this.emitter.off(topic, cb);\n }\n }\n\n async flush(): Promise<void> {\n // A batched cb can nack mid-delivery, which schedules a redelivery via\n // setTimeout(0). The redelivered event lands back in `batchBuffers`\n // (the buffer is the group member's destination) and may sit there\n // below maxSize/maxWaitMs thresholds. So we loop: drain buffers, wait\n // for pending nacks to fire, then check whether either side produced\n // more work. Stable-state termination requires both to be empty at the\n // top of a single iteration.\n while (true) {\n const drains: { topic: string; promise: Promise<void> }[] = [];\n for (const [topic, byCb] of this.batchBuffers.entries()) {\n for (const buffer of byCb.values()) {\n drains.push({ topic, promise: buffer.flush() });\n }\n }\n if (drains.length > 0) {\n // allSettled — a single throwing buffer should not block the rest from\n // flushing during shutdown. Rejections that propagate this far skipped\n // the per-event try/catch in AckHandleBuffer (e.g. a throwing coalesce)\n // and must be surfaced or they vanish at shutdown.\n const results = await Promise.allSettled(drains.map(d => d.promise));\n for (let i = 0; i < results.length; i++) {\n const result = results[i]!;\n if (result.status === 'rejected') {\n this.logBufferError(drains[i]!.topic, result.reason, { phase: 'cb' });\n }\n }\n }\n\n if (this.pendingNacks.size === 0) {\n // Nothing scheduled — and the drain above either did nothing or\n // produced no new pending nacks, so we're stable.\n return;\n }\n\n // Wait for the currently-scheduled nacks to fire. Each redelivery\n // may land in a buffer; loop and re-drain.\n await new Promise<void>(resolve => {\n const check = () => {\n if (this.pendingNacks.size === 0) {\n resolve();\n } else {\n setTimeout(check, 10);\n }\n };\n check();\n });\n }\n }\n\n /**\n * Clean up all listeners during graceful shutdown.\n */\n async close(): Promise<void> {\n // Cancel pending nack redeliveries\n for (const handle of this.pendingNacks) {\n clearTimeout(handle);\n }\n this.pendingNacks.clear();\n this.deliveryAttempts.clear();\n\n // Dispose every batching buffer so timers are cleared.\n for (const byCb of this.batchBuffers.values()) {\n for (const buffer of byCb.values()) {\n buffer.dispose();\n }\n }\n this.batchBuffers.clear();\n\n this.emitter.removeAllListeners();\n this.groups.clear();\n this.groupCounters.clear();\n this.groupListeners.clear();\n this.fanoutWrappers.clear();\n }\n\n private subscribeWithGroup(topic: string, cb: EventCallback, group: string): void {\n let topicMap = this.groups.get(group);\n if (!topicMap) {\n topicMap = new Map();\n this.groups.set(group, topicMap);\n }\n\n let members = topicMap.get(topic);\n if (!members) {\n members = [];\n topicMap.set(topic, members);\n }\n\n members.push(cb);\n\n // Register a single emitter listener per topic:group pair\n const listenerKey = `${topic}:${group}`;\n if (!this.groupListeners.has(listenerKey)) {\n const listener = (event: Event) => {\n this.deliverToGroup(topic, group, listenerKey, event);\n };\n\n this.groupListeners.set(listenerKey, listener);\n this.emitter.on(topic, listener);\n }\n }\n\n private deliverToGroup(topic: string, group: string, listenerKey: string, event: Event): void {\n const currentMembers = this.groups.get(group)?.get(topic);\n if (!currentMembers || currentMembers.length === 0) return;\n\n const counter = this.groupCounters.get(listenerKey) ?? 0;\n const idx = counter % currentMembers.length;\n this.groupCounters.set(listenerKey, counter + 1);\n\n // Track delivery attempts scoped per group listener, so ack/nack in one\n // group doesn't disturb another group's attempt counter for the same event.\n const attemptKey = `${listenerKey}:${event.id}`;\n const attempt = this.deliveryAttempts.get(attemptKey) ?? 1;\n const eventWithAttempt = { ...event, deliveryAttempt: attempt };\n\n const ack = async () => {\n // Message successfully processed — clean up attempt tracking\n this.deliveryAttempts.delete(attemptKey);\n };\n\n const nack = async () => {\n // Message processing failed — redeliver to the group after a short delay\n // Increment delivery attempt counter\n this.deliveryAttempts.set(attemptKey, attempt + 1);\n\n const handle = setTimeout(() => {\n this.pendingNacks.delete(handle);\n this.deliverToGroup(topic, group, listenerKey, event);\n }, 0);\n this.pendingNacks.add(handle);\n };\n\n const member = currentMembers[idx]!;\n // If this member opted into batching, route through its buffer.\n const buffer = this.batchBuffers.get(topic)?.get(member);\n if (buffer) {\n // Same rationale as the fan-out push above: surface rejections\n // through the logger so they don't escape as unhandled.\n void buffer.push(eventWithAttempt, ack, nack).catch(err => {\n this.logBufferError(topic, err, { phase: 'cb' });\n });\n } else {\n try {\n void Promise.resolve(member(eventWithAttempt, ack, nack)).catch(err => {\n this.logSubscriberError(topic, err);\n });\n } catch (err) {\n this.logSubscriberError(topic, err);\n }\n }\n }\n\n // key → { owner, expiresAt }. In-process so a single Map is enough;\n // there is no other process to race against. The same owner can renew\n // their own lease; expired entries are reclaimed lazily on the next\n // acquireLease call.\n private leases: Map<string, { owner: string; expiresAt: number }> = new Map();\n\n acquireLease(key: string, owner: string, ttlMs: number): Promise<{ acquired: boolean; owner?: string }> {\n const now = Date.now();\n const existing = this.leases.get(key);\n if (existing && existing.expiresAt > now && existing.owner !== owner) {\n return Promise.resolve({ acquired: false, owner: existing.owner });\n }\n this.leases.set(key, { owner, expiresAt: now + ttlMs });\n return Promise.resolve({ acquired: true, owner });\n }\n\n getLeaseOwner(key: string): Promise<string | undefined> {\n const existing = this.leases.get(key);\n if (!existing) return Promise.resolve(undefined);\n if (existing.expiresAt <= Date.now()) {\n this.leases.delete(key);\n return Promise.resolve(undefined);\n }\n return Promise.resolve(existing.owner);\n }\n\n releaseLease(key: string, owner: string): Promise<void> {\n const existing = this.leases.get(key);\n if (existing && existing.owner === owner) {\n this.leases.delete(key);\n }\n return Promise.resolve();\n }\n\n renewLease(key: string, owner: string, ttlMs: number): Promise<boolean> {\n const existing = this.leases.get(key);\n if (!existing || existing.owner !== owner || existing.expiresAt <= Date.now()) {\n return Promise.resolve(false);\n }\n existing.expiresAt = Date.now() + ttlMs;\n return Promise.resolve(true);\n }\n\n // Atomic owner-guarded handoff: only the current owner can transfer, and the\n // key is never empty during the swap (mirrors the Redis GET==from -> SET to\n // Lua). Lets a finishing run hand the lease to its drain run without a\n // release/acquire gap, even on the in-process backend.\n transferLease(key: string, fromOwner: string, toOwner: string, ttlMs: number): Promise<boolean> {\n const existing = this.leases.get(key);\n if (!existing || existing.owner !== fromOwner || existing.expiresAt <= Date.now()) {\n return Promise.resolve(false);\n }\n this.leases.set(key, { owner: toOwner, expiresAt: Date.now() + ttlMs });\n return Promise.resolve(true);\n }\n}\n","import type { Event, EventCallback } from './types';\n\n/**\n * Adapt an event-only handler into an `EventCallback` that acknowledges every\n * delivery.\n *\n * Handlers that only need the event cannot honour the `EventCallback` contract\n * themselves: on a durable backend (Redis consumer groups, GCP Pub/Sub) every\n * delivery — including the ones a handler inspects and filters out — has to be\n * acked, or it stays in the subscription's pending set and is redelivered.\n * Wrapping is the only way an event-only handler can satisfy that.\n *\n * A throwing handler leaves the delivery unacked and rejects the callback, which\n * a backend that honours redelivery treats as a nack.\n */\nexport function withAck(handler: (event: Event) => void | Promise<void>): EventCallback {\n return async (event, ack) => {\n await handler(event);\n await ack?.();\n };\n}\n","/**\n * Removes the model request/history snapshots that agent `step-start`,\n * `step-finish` and `finish` chunks carry (full prompt, file parts, message\n * history, cumulative steps). Used for copies of chunks that are fanned out to\n * other subscribers, which don't need those fields. Only the given chunk is\n * inspected; callers decide which nested chunks to pass in. Returns the same\n * reference when nothing was removed.\n */\nexport function stripModelSnapshots<T>(chunk: T): T {\n if (!chunk || typeof chunk !== 'object') return chunk;\n const { type, payload } = chunk as { type?: unknown; payload?: unknown };\n if (!payload || typeof payload !== 'object') return chunk;\n const p = payload as Record<string, unknown>;\n\n if (type === 'step-start') {\n if (!('request' in p) && !('inputMessages' in p)) return chunk;\n const { request: _request, inputMessages: _inputMessages, ...rest } = p;\n return { ...chunk, payload: rest };\n }\n\n if (type === 'step-finish' || type === 'finish') {\n let changed = false;\n const next: Record<string, unknown> = { ...p };\n if (p.metadata && typeof p.metadata === 'object' && 'request' in p.metadata) {\n const { request: _request, ...metadata } = p.metadata as Record<string, unknown>;\n next.metadata = metadata;\n changed = true;\n }\n if (p.output && typeof p.output === 'object' && 'steps' in p.output) {\n const { steps: _steps, ...output } = p.output as Record<string, unknown>;\n next.output = output;\n changed = true;\n }\n if ('messages' in p) {\n delete next.messages;\n changed = true;\n }\n return changed ? { ...chunk, payload: next } : chunk;\n }\n\n return chunk;\n}\n\nconst PROGRESS_WRAPPER_TYPES = new Set(['tool-output', 'workflow-step-output']);\n\n/**\n * Removes model request/history snapshots from agent chunks before a progress\n * chunk is published to pubsub. Nested agent chunks arrive wrapped in\n * `tool-output` / `workflow-step-output` payloads, so only those wrappers are\n * unwrapped, and only agent-origin chunks are stripped — data a tool writes\n * itself (`from: 'USER'`) is published as-is.\n */\nexport function slimProgressChunk<T>(chunk: T, depth = 0): T {\n if (!chunk || typeof chunk !== 'object') return chunk;\n const { type, from, payload } = chunk as { type?: unknown; from?: unknown; payload?: unknown };\n\n if (typeof type === 'string' && PROGRESS_WRAPPER_TYPES.has(type) && payload && typeof payload === 'object') {\n const p = payload as Record<string, unknown>;\n const inner = p.output as { type?: unknown; from?: unknown } | undefined;\n const isNestedChunk =\n !!inner &&\n typeof inner === 'object' &&\n typeof inner.type === 'string' &&\n (inner.from === 'AGENT' || PROGRESS_WRAPPER_TYPES.has(inner.type));\n if (!isNestedChunk) return chunk;\n // Past the nesting limit, drop the nested chunk rather than publish it unslimmed.\n if (depth >= 20) {\n const { output: _output, ...rest } = p;\n return { ...chunk, payload: rest };\n }\n const output = slimProgressChunk(inner, depth + 1);\n return output === inner ? chunk : { ...chunk, payload: { ...p, output } };\n }\n\n return from === 'AGENT' ? stripModelSnapshots(chunk) : chunk;\n}\n\n/**\n * Like {@link slimProgressChunk}, but only for the agent chunks nested in a\n * `tool-output` / `workflow-step-output` chunk; any other chunk is returned as-is.\n */\nexport function slimNestedAgentChunks<T>(chunk: T): T {\n const type = chunk && typeof chunk === 'object' ? (chunk as { type?: unknown }).type : undefined;\n return typeof type === 'string' && PROGRESS_WRAPPER_TYPES.has(type) ? slimProgressChunk(chunk) : chunk;\n}\n","import { slimNestedAgentChunks } from '../stream/strip-model-snapshots';\n\n/**\n * Topic prefixes whose events are only ever consumed by the process that\n * published them.\n *\n * `workflow.events.v2.<runId>` carries per-run watch events: the execution\n * engine subscribes per-run, in-process, and nothing replays them. The payloads\n * accumulate step results and routinely run to megabytes.\n */\nexport const RUN_LOCAL_TOPIC_PREFIXES = ['workflow.events.v2.'] as const;\n\n/**\n * Whether a topic is run-local — consumed only by the publishing process.\n *\n * Run-local topics must never be relayed to other instances, nor mirrored into\n * a shared replay cache: no other instance can read them, so caching only grows\n * the store without bound (see issue #20646).\n *\n * This predicate is the single source of truth for that policy. It is consumed\n * both by the `mastra.pubsub` proxy (which tags publishes `localOnly` so the\n * broker skips cross-instance fan-out) and by the durable agent's\n * `CachingPubSub` wiring (which sits *above* that proxy and so cannot observe\n * the `localOnly` flag itself).\n */\nexport function isRunLocalTopic(topic: string): boolean {\n return RUN_LOCAL_TOPIC_PREFIXES.some(prefix => topic.startsWith(prefix));\n}\n\n/**\n * How long a durable run's stream log (`agent.stream.<runId>`) is retained.\n *\n * The log is what `observe({ offset })` replays from, and its counter numbers\n * every frame. A run parked on a tool approval can wait far longer than a\n * cache's default TTL; if the log expired meanwhile, numbering would restart at\n * 0 while an attached observer still held the old cursor. The run's suspension\n * frame is its last append before it parks, so stamping this on every append\n * covers the parked window. Run cleanup deletes the log when the run ends.\n */\nexport const RUN_LOG_TTL_MS = 24 * 60 * 60 * 1000;\n\nconst RUN_LOG_TOPIC_PREFIX = 'agent.stream.';\n\n/** Minimum retention for a topic's cached log, or `undefined` for the cache default. */\nexport function cachedLogTtlMs(topic: string): number | undefined {\n return topic.startsWith(RUN_LOG_TOPIC_PREFIX) ? RUN_LOG_TTL_MS : undefined;\n}\n\n/**\n * The copy of `event` a run's cached log keeps.\n *\n * A delegated sub-agent's chunks are forwarded on the run stream inside\n * `tool-output` / `workflow-step-output`, and each nested step-start,\n * step-finish and finish carries the sub-agent's full prompt, history and\n * steps. Stored as-is, every delegated run grows the log by megabytes. The log\n * keeps them slimmed; live subscribers still receive the event as published,\n * so a caller reading its own run sees the same chunks as a plain Agent's\n * caller (see #29035).\n */\nexport function toCachedLogFrame<E extends { type: string; data?: unknown }>(topic: string, event: E): E {\n if (event.type !== 'chunk' || !topic.startsWith(RUN_LOG_TOPIC_PREFIX)) return event;\n const data = slimNestedAgentChunks(event.data);\n return data === event.data ? event : { ...event, data };\n}\n","import type { SerializedError } from '../../error/utils';\nimport { getSpanErrorOrigin, setSpanErrorOrigin } from '../../observability/error-count';\n\nconst MAX_CAUSE_DEPTH = 5;\n\n/**\n * Serializes an Error instance to a plain SerializedError object without\n * mutating the original. Unlike `getErrorFromUnknown(...).toJSON()`, this does\n * not attach a non-enumerable `toJSON` to the live Error.\n */\nexport function serializeError(err: Error, depth = 0): SerializedError {\n const json: SerializedError = {\n name: err.name || 'Error',\n message: err.message,\n };\n if (err.stack !== undefined) json.stack = err.stack;\n\n if (err.cause !== undefined) {\n if (err.cause instanceof Error && depth < MAX_CAUSE_DEPTH) {\n json.cause = serializeError(err.cause, depth + 1);\n } else {\n json.cause = err.cause;\n }\n }\n\n // Copy enumerable own properties (custom error fields)\n for (const key in err) {\n if (!Object.prototype.hasOwnProperty.call(err, key)) continue;\n if (key === 'message' || key === 'name' || key === 'stack' || key === 'cause' || key === '__mastraSpanErrorOrigin')\n continue;\n json[key] = (err as unknown as Record<string, unknown>)[key];\n }\n\n const origin = getSpanErrorOrigin(err);\n if (origin) json.__mastraSpanErrorOrigin = origin;\n\n return json;\n}\n\n/**\n * Rehydrates a SerializedError into a vanilla Error instance. We never\n * instantiate user-controlled prototypes — name is preserved as a string field.\n */\nexport function rehydrateError(s: SerializedError): Error {\n const cause =\n s.cause !== undefined\n ? s.cause && typeof s.cause === 'object' && 'message' in s.cause && 'name' in s.cause\n ? rehydrateError(s.cause as SerializedError)\n : s.cause\n : undefined;\n\n const err = cause !== undefined ? new Error(s.message, { cause }) : new Error(s.message);\n if (s.name) err.name = s.name;\n if (s.stack !== undefined) err.stack = s.stack;\n\n for (const key in s) {\n if (!Object.prototype.hasOwnProperty.call(s, key)) continue;\n if (key === 'message' || key === 'name' || key === 'stack' || key === 'cause' || key === '__mastraSpanErrorOrigin')\n continue;\n (err as unknown as Record<string, unknown>)[key] = s[key];\n }\n\n const origin = getSpanErrorOrigin(s);\n if (origin) setSpanErrorOrigin(err, origin);\n\n return err;\n}\n","import type { MastraServerCache } from '../cache/base';\nimport type { IMastraLogger } from '../logger';\nimport { isLeaseProvider, PubSub } from './pubsub';\nimport type { LeaseProvider } from './pubsub';\nimport { cachedLogTtlMs, toCachedLogFrame } from './topics';\nimport type { Event, EventCallback, SubscribeOptions } from './types';\n\n/**\n * Options for CachingPubSub\n */\nexport interface CachingPubSubOptions {\n /**\n * Optional prefix for cache keys to namespace events.\n * Defaults to 'pubsub:'.\n */\n keyPrefix?: string;\n /**\n * Optional logger for structured logging.\n * Falls back to console.error if not provided.\n */\n logger?: IMastraLogger;\n /**\n * Use Redis Cluster hash tags for replay keys. Opt in only for new logs or\n * after existing logs have expired; the default preserves legacy keys.\n */\n keyFormat?: 'redis-cluster';\n /**\n * Optional per-topic caching policy. Defaults to caching every topic.\n *\n * Returning `false` takes the same path as a `localOnly` publish: no list\n * entry, no index, no counter allocation — the event is handed straight to\n * the inner PubSub and still delivered live.\n *\n * This exists because `localOnly` is not always visible here. When a caller\n * wraps a PubSub that itself decides `localOnly` (e.g. the `mastra.pubsub`\n * proxy), the cache runs *above* that decision and never sees the flag, so\n * the policy has to be supplied at construction time instead.\n */\n shouldCache?: (topic: string) => boolean;\n /**\n * Only append to topics whose log this cache already holds. A publish to a\n * topic with no log is delivered live and unnumbered, and `onUnlogged` is\n * called with the topic.\n *\n * A process-local cache can only number a topic's frames consistently in the\n * process that started its log. Another process numbering the same topic\n * from 0 in its own cache would produce indices that observers drop as\n * duplicates.\n *\n * @internal\n */\n extendExistingLogsOnly?: boolean;\n /**\n * Called when `extendExistingLogsOnly` leaves a publish unnumbered.\n *\n * @internal\n */\n onUnlogged?: (topic: string) => void;\n /**\n * @deprecated No longer used. Evented steps now cache their frames when they\n * publish, so nothing needs to be copied in from another PubSub. Accepted and\n * ignored for compatibility.\n */\n source?: PubSub;\n}\n\nconst EMPTY_INDICES: ReadonlySet<number> = new Set();\n\n/**\n * A PubSub decorator that adds event caching and replay capabilities.\n *\n * Wraps any PubSub implementation and uses MastraServerCache to:\n * - Cache all published events per topic\n * - Enable replay of cached events for late subscribers\n *\n * This enables resumable streams - clients can disconnect and reconnect\n * without missing events.\n *\n * ## One append path\n *\n * Every cached publish goes through {@link MastraServerCache.listPushIndexed},\n * which allocates the frame's index and appends it. The cache list is\n * therefore the run's log, and the transport only carries the\n * live tail of that log. Subscribers hold a single integer cursor and backfill\n * any gap they observe from the log rather than relying on transport replay.\n *\n * A list position is not necessarily its index: a cache whose append is not\n * atomic can allocate an index and then fail to push the frame, leaving a hole\n * that shifts every later frame to a lower position. Reads go through\n * `readLogFrom`, which uses the counter minus the list length to find where\n * index `from` can start, and returns entries in index order. A frame whose\n * cache write failed is not recoverable.\n *\n * Limitation: a non-atomic append (the default\n * {@link MastraServerCache.listPushIndexed}, or Redis after its CROSSSLOT\n * fallback) can also let concurrent publishes store frames out of order. An\n * entry that lands below the computed start position is then missed, e.g.\n * the log `[0, 2, 1, 3]` read from index 2 loses index 2. Removing that needs\n * an atomic append.\n *\n * If caching a frame fails, it is published without an index and delivered\n * live only.\n *\n * ## Batching\n *\n * `CachingPubSub` is transparent to `options.batch`: `subscribe()` forwards\n * the option to the inner PubSub, and `supportsNativeBatching` mirrors the\n * inner's value. Wrapping a non-native inner with `{ batch: {...} }` results\n * in unbatched delivery — use an inner that returns\n * `supportsNativeBatching === true` (e.g. `EventEmitterPubSub`) if you need\n * batched delivery.\n *\n * @example\n * ```typescript\n * import { EventEmitterPubSub, CachingPubSub } from '@mastra/core/events';\n * import { InMemoryServerCache } from '@mastra/core/cache';\n *\n * const cache = new InMemoryServerCache();\n * const pubsub = new CachingPubSub(new EventEmitterPubSub(), cache);\n *\n * // Subscribe with replay - receives cached events first, then live\n * await pubsub.subscribeWithReplay('my-topic', (event) => {\n * console.log(event);\n * });\n * ```\n */\nexport class CachingPubSub extends PubSub {\n private readonly keyPrefix: string;\n private readonly keyFormat: 'legacy' | 'redis-cluster';\n private readonly logger?: IMastraLogger;\n private readonly shouldCache?: (topic: string) => boolean;\n private readonly extendExistingLogsOnly: boolean;\n private readonly onUnlogged?: (topic: string) => void;\n /** Maps original callbacks to their wrapped versions for proper unsubscribe */\n private callbackMap = new Map<EventCallback, EventCallback>();\n\n /**\n * Log indices per topic that were appended to the cache but whose live\n * publish threw. The frame stays in the log (late subscribers still replay\n * it), but the transport never carried it, so readers must not wait for it\n * to arrive.\n */\n private undeliveredIndices = new Map<string, Set<number>>();\n\n constructor(\n private readonly inner: PubSub,\n private readonly cache: MastraServerCache,\n options: CachingPubSubOptions = {},\n ) {\n super();\n this.keyPrefix = options.keyPrefix ?? 'pubsub:';\n this.keyFormat = options.keyFormat ?? 'legacy';\n this.logger = options.logger;\n this.shouldCache = options.shouldCache;\n this.extendExistingLogsOnly = options.extendExistingLogsOnly ?? false;\n this.onUnlogged = options.onUnlogged;\n }\n\n /**\n * @deprecated No longer used; see {@link CachingPubSubOptions.source}. Kept as\n * a no-op for compatibility.\n */\n __setSource(_source: PubSub | undefined): void {}\n\n /** Unwrap to the inner transport so capability checks see through this decorator. */\n override __rawBus(): PubSub {\n return this.inner.__rawBus();\n }\n\n get supportsNativeBatching(): boolean {\n return this.inner.supportsNativeBatching;\n }\n\n get supportsOffsets(): boolean {\n return true;\n }\n\n get redeliversUnacked(): boolean {\n return this.inner.redeliversUnacked;\n }\n\n /**\n * Topics `shouldCache` leaves out only reach the inner transport. With\n * `extendExistingLogsOnly`, a process that doesn't hold a run's log\n * publishes it live only; that setup is already warned about (`onUnlogged`)\n * and its replays miss those frames whatever they carry, so it still counts\n * as kept.\n */\n override __replaysTopic(topic: string): boolean {\n return this.shouldCache?.(topic) !== false || this.inner.__replaysTopic(topic);\n }\n\n /**\n * Log an error message using the configured logger or console.error.\n */\n private logError(message: string, error: unknown): void {\n if (this.logger) {\n this.logger.error(message, error);\n } else {\n console.error(message, error);\n }\n }\n\n /**\n * Log a warning using the configured logger or console.warn.\n */\n private logWarn(message: string): void {\n if (this.logger) {\n this.logger.warn(message);\n } else {\n console.warn(message);\n }\n }\n\n /** Get the cache key for a topic's event list. */\n private getCacheKey(topic: string): string {\n if (this.keyFormat === 'legacy') return `${this.keyPrefix}${topic}`;\n // Encode braces and percent signs so topics cannot create nested tags or collide with one another.\n const tag = encodeURIComponent(topic) || '%EMPTY';\n return `${this.keyPrefix}{${tag}}`;\n }\n\n /** Get the cache key for a topic's index counter in the same Redis slot. */\n private getCounterKey(topic: string): string {\n return `${this.getCacheKey(topic)}:counter`;\n }\n\n /**\n * Read the log entries for `topic` whose index is `from` or later.\n *\n * Each hole left by an allocated-but-unpushed index moves later entries one\n * position below their index, so slicing at `from` would skip them. The\n * counter minus the list length is the number of holes; start that many\n * positions earlier and filter by index. When either value is unavailable\n * (a failed read, or a cache whose `get` does not return counters), read\n * the whole log instead.\n *\n * Numbered entries are returned in index order, followed by unnumbered\n * ones, because a non-atomic append can store frames out of order.\n */\n private async readLogFrom(topic: string, from: number): Promise<Event[]> {\n const cacheKey = this.getCacheKey(topic);\n let start = 0;\n if (from > 0) {\n // Length before counter: an append landing between the two reads can\n // only overstate the holes, which starts the slice early, never late.\n const length = await this.cache.listLength(cacheKey).catch(() => undefined);\n const counter =\n length === undefined ? undefined : await this.cache.get(this.getCounterKey(topic)).catch(() => undefined);\n if (typeof length === 'number' && typeof counter === 'number') {\n start = Math.max(0, from - Math.max(0, counter - length));\n }\n }\n const entries = (await this.cache.listFromTo(cacheKey, start)) as Event[];\n const numbered: Event[] = [];\n const unnumbered: Event[] = [];\n for (const event of entries) {\n if (typeof event.index !== 'number') unnumbered.push(event);\n else if (event.index >= from) numbered.push(event);\n }\n numbered.sort((a, b) => a.index! - b.index!);\n return [...numbered, ...unnumbered];\n }\n\n async publish(\n topic: string,\n event: Omit<Event, 'id' | 'createdAt' | 'index'>,\n options?: { localOnly?: boolean },\n ): Promise<void> {\n const fullEvent: Event = {\n ...event,\n id: crypto.randomUUID(),\n createdAt: new Date(),\n };\n\n if (options?.localOnly || this.shouldCache?.(topic) === false) {\n await this.inner.publish(topic, fullEvent, options);\n return;\n }\n\n if (this.extendExistingLogsOnly && !(await this.hasLog(topic))) {\n this.onUnlogged?.(topic);\n await this.inner.publish(topic, fullEvent, options);\n return;\n }\n\n // Cache BEFORE live publish so late-joining observers never miss events,\n // and allocate the index as part of that append so the log stays in index\n // order.\n let index: number | undefined;\n try {\n index = await this.cache.listPushIndexed(\n this.getCacheKey(topic),\n this.getCounterKey(topic),\n toCachedLogFrame(topic, fullEvent),\n cachedLogTtlMs(topic),\n );\n } catch (error) {\n this.logError(`[CachingPubSub] Failed to cache event for ${topic}`, error);\n }\n\n // On cache failure leave `index` undefined rather than defaulting to 0:\n // downstream consumers that key off `index` (e.g. replay-from-offset)\n // would otherwise see colliding indices across failed publishes.\n const numbered: Event = index !== undefined ? { ...fullEvent, index } : fullEvent;\n\n // Always publish to inner PubSub — cache failure must not block live delivery.\n try {\n await this.inner.publish(topic, numbered, options);\n } catch (error) {\n if (index !== undefined) {\n let indices = this.undeliveredIndices.get(topic);\n if (!indices) this.undeliveredIndices.set(topic, (indices = new Set()));\n indices.add(index);\n }\n throw error;\n }\n }\n\n private async hasLog(topic: string): Promise<boolean> {\n try {\n return (await this.cache.listLength(this.getCacheKey(topic))) > 0;\n } catch (error) {\n this.logError(`[CachingPubSub] Failed to read cached log length for ${topic}`, error);\n return false;\n }\n }\n\n /**\n * Log indices this instance cached for `topic` but failed to publish to the\n * inner transport. Readers exclude them when waiting for the log to reach\n * them: those frames are replayed to late subscribers, but the live\n * subscription will never deliver them.\n *\n * Only the publishing process knows these indices. A reader in another\n * process sharing the cache still waits out its pending-frame deadline for\n * a frame a remote publisher could not send.\n */\n getUndeliveredIndices(topic: string): ReadonlySet<number> {\n return this.undeliveredIndices.get(topic) ?? EMPTY_INDICES;\n }\n\n /**\n * Subscribe to live events on a topic (no replay).\n */\n async subscribe(topic: string, cb: EventCallback, options?: SubscribeOptions): Promise<void> {\n await this.inner.subscribe(topic, cb, options);\n }\n\n /**\n * Subscribe to a topic with automatic replay of cached events.\n * Delegates to {@link subscribeFromOffset} with offset 0.\n */\n async subscribeWithReplay(topic: string, cb: EventCallback): Promise<void> {\n return this.subscribeFromOffset(topic, 0, cb);\n }\n\n /**\n * Subscribe to a topic with replay starting at a specific index.\n *\n * The subscriber keeps one cursor, `next`, and every frame it receives is\n * reconciled against it:\n * - `index < next` — already delivered (transport replay, retry, or a\n * duplicate) → dropped.\n * - `index === next` — the next frame in the log → delivered.\n * - `index > next` — frames arrived out of order. Because a frame is appended\n * to the log before it is published, the missing frames are already in the\n * log, so they are read back in order and delivered before this one. That\n * holds even when the transport replays nothing at all.\n *\n * One exception to the first rule: a frame numbered `0` whose counter shows\n * the log restarted. That means the retained log expired or was cleared and\n * a new run segment began numbering at 0; the cursor resyncs and the frame is\n * delivered, instead of silently dropping the whole new segment. Nack\n * redeliveries (`deliveryAttempt > 1`) also bypass reconciliation, since a\n * retry of an already-cursor-advanced frame still has to reach the consumer.\n *\n * When the log no longer holds the missing range (no shared cache, or the\n * TTL lapsed) there is nothing to replay; the cursor resynchronises to the\n * frame in hand so live delivery continues.\n *\n * @param topic - The topic to subscribe to\n * @param offset - Start replaying from this index (0-based)\n * @param cb - Callback invoked for each event\n */\n async subscribeFromOffset(topic: string, offset: number, cb: EventCallback): Promise<void> {\n const cacheKey = this.getCacheKey(topic);\n\n let next = offset;\n // The id the log stored for its frame 0 when this subscriber attached. With\n // an offset past the log's end, the cursor sits above the counter, so the\n // counter cannot tell the transport's retained frame 0 from the first frame\n // of a new segment; a new segment writes a new entry 0 with a different id.\n const readFirstId = async () => ((await this.cache.listFromTo(cacheKey, 0, 0)) as Event[])[0]?.id;\n const logLength = offset > 0 ? await this.cache.get(this.getCounterKey(topic)).catch(() => undefined) : undefined;\n // When the attach-time id read fails on an existing log, the counter\n // fallback must compare against the log's end, not a cursor past it, or the\n // intact log's retained frame 0 reads as a restart.\n let attachLogEnd: number | undefined;\n let firstId =\n typeof logLength === 'number'\n ? await readFirstId().catch(() => {\n attachLogEnd = logLength;\n return undefined;\n })\n : undefined;\n let closed = false;\n let warnedUnnumbered = false;\n // Set only while a backfill (or the initial history read) is in flight.\n // Frames delivered meanwhile must wait, or the cursor could advance past a\n // frame that has not been handed to the consumer yet. In the common case\n // (a frame that is next) delivery stays synchronous.\n let pending: Promise<void> | null = null;\n let deferred = false;\n // True until the transport's `subscribe()` resolves (retained replay window).\n let attaching = true;\n\n const emit = (event: Event, ack?: () => Promise<void>, nack?: () => Promise<void>) => {\n if (typeof event.index === 'number') {\n next = event.index + 1;\n }\n return cb(event, ack, nack);\n };\n\n /** Deliver everything the log holds between the cursor and `target`. */\n const backfill = async (target: number) => {\n if (target <= next) return;\n const entries = await this.readLogFrom(topic, next);\n for (const entry of entries) {\n if (closed) return;\n const seq = entry.index;\n if (typeof seq !== 'number' || seq < next) continue;\n if (seq >= target) return;\n await emit(entry);\n }\n };\n\n const reconcile = (event: Event, ack?: () => Promise<void>, nack?: () => Promise<void>): void | Promise<void> => {\n // A nack-redelivery carries the same index but `deliveryAttempt > 1`;\n // the consumer must see it again to retry processing.\n if (event.deliveryAttempt !== undefined && event.deliveryAttempt > 1) {\n return cb(event, ack, nack);\n }\n\n const seq = event.index;\n if (typeof seq !== 'number') {\n // No numbering (the frame failed to cache, or the publisher has no\n // shared log): live-only delivery.\n if (offset > 0 && !warnedUnnumbered) {\n warnedUnnumbered = true;\n this.logWarn(\n `[CachingPubSub] Frames on ${topic} are not numbered, so resuming from offset ${offset} cannot ` +\n `replay or skip them by position. Either the publisher failed to append them to the server cache ` +\n `(check for cache errors), or it does not share a server cache with this process (configure one ` +\n `shared by every process, for example RedisServerCache).`,\n );\n }\n return cb(event, ack, nack);\n }\n\n // Already delivered (a retained transport copy of a frame the log\n // provided). Acknowledge it so it does not stay pending on the backend.\n if (seq < next) {\n if (seq !== 0) return ack?.();\n\n // Index 0 below the cursor can mean the log this subscriber was reading\n // is gone: it expired (or was cleared) and the run resumed, restarting\n // numbering at 0. Dropping it would swallow every frame of the new\n // segment, since all of their indices sit below the stale cursor.\n // Confirm by frame 0's id when one was captured on attach; otherwise by\n // the counter, which restarts with the log and so cannot sit below the\n // cursor in a continuous log.\n deferred = true;\n return (async () => {\n // A cache read failure must not turn a duplicate into a nack loop;\n // fall through to the drop path in that case.\n const allocated = await this.cache.get(this.getCounterKey(topic)).catch(() => undefined);\n // A failed id read is unknown, not unchanged: fall back to the\n // counter, which risks re-sending frames rather than losing them.\n let compareIds = firstId !== undefined;\n let currentFirstId: string | undefined;\n if (compareIds) {\n try {\n currentFirstId = await readFirstId();\n } catch {\n compareIds = false;\n }\n }\n if (closed) return ack?.();\n\n const restarted = compareIds\n ? currentFirstId !== undefined && currentFirstId !== firstId\n : typeof allocated === 'number' && allocated < Math.min(next, attachLogEnd ?? next);\n if (restarted) {\n attachLogEnd = undefined;\n firstId = compareIds ? currentFirstId : await readFirstId().catch(() => undefined);\n this.logWarn(\n `[CachingPubSub] Log for ${topic} restarted at 0 while the subscriber cursor was at ${next}; ` +\n `the retained log expired or was cleared. Resyncing from the start of the new segment.`,\n );\n // The frame in hand may be a delayed copy of the old log's frame 0,\n // so deliver the new segment from the log rather than from it.\n next = 0;\n await backfill(Number.POSITIVE_INFINITY);\n if (closed) return ack?.();\n if (next > 0) return ack?.();\n await emit(event, ack, nack);\n return;\n }\n\n // A late copy of this log's real first frame: nothing to resync.\n await ack?.();\n })();\n }\n\n if (seq > next) {\n // Frames arrived out of order. The log already holds the missing ones,\n // so this has to wait for them; queue later frames behind it.\n deferred = true;\n return (async () => {\n await backfill(seq);\n if (closed) return;\n if (seq < next) {\n // The log supplied this frame; the transport copy is a duplicate.\n await ack?.();\n return;\n }\n // Nothing left in the log for the gap; resume from this frame.\n next = seq;\n await emit(event, ack, nack);\n })();\n }\n\n return emit(event, ack, nack);\n };\n\n const failDelivery = async (error: unknown, nack?: () => Promise<void>) => {\n this.logError(`[CachingPubSub] Subscriber failed for ${topic}`, error);\n await nack?.().catch(() => {});\n };\n\n /**\n * Track a delivery chain so later frames queue behind it.\n *\n * The clear has to be conditional: a newer chain may already have replaced\n * `pending`, and nulling it then would let the next frame reconcile\n * concurrently with the in-flight one (two backfills racing on the same\n * range, delivering the gap twice or out of order).\n */\n const track = (run: Promise<void>, nack?: () => Promise<void>) => {\n const tracked = run.catch(error => failDelivery(error, nack));\n pending = tracked;\n void tracked.then(() => {\n if (pending === tracked) pending = null;\n });\n return tracked;\n };\n\n const wrappedCb: EventCallback = (event, ack, nack) => {\n if (closed) {\n // Nobody will process this delivery; acknowledge so it is not stranded.\n return ack?.();\n }\n\n if (pending) {\n return track(\n pending.then(() => reconcile(event, ack, nack)),\n nack,\n );\n }\n\n deferred = false;\n const result = reconcile(event, ack, nack);\n // While attaching, a direct delivery the transport did not await must\n // also finish before the history read starts delivering later frames.\n if (!deferred && !(attaching && result instanceof Promise)) return result;\n\n // A gap triggered a backfill: hold later frames until it completes.\n return track(result as Promise<void>, nack);\n };\n\n this.callbackMap.set(cb, wrappedCb);\n try {\n // Subscribe before reading history so no frame is missed. Live frames\n // arriving during the read queue behind it.\n await this.inner.subscribe(topic, wrappedCb);\n attaching = false;\n\n // A transport that replays retained frames without awaiting the callback\n // can start a delivery chain (a backfill) before `subscribe()` resolves.\n // Read history only after that chain settles, so the two never deliver\n // at the same time.\n const inFlight = pending;\n let releaseHistory!: () => void;\n const historyGate = new Promise<void>(resolve => {\n releaseHistory = resolve;\n });\n pending = historyGate;\n try {\n await inFlight;\n const entries = await this.readLogFrom(topic, next);\n for (const entry of entries) {\n if (closed) return;\n const seq = entry.index;\n if (typeof seq !== 'number' || seq < next) continue;\n await emit(entry);\n }\n } finally {\n // Only release our own gate: a live frame that arrived during the read\n // may already have queued behind it and replaced `pending`.\n if (pending === historyGate) pending = null;\n releaseHistory();\n }\n } catch (error) {\n // Rollback so the callback isn't stranded on the inner transport.\n closed = true;\n this.callbackMap.delete(cb);\n await this.inner.unsubscribe(topic, wrappedCb).catch(() => {});\n throw error;\n }\n }\n\n /**\n * Unsubscribe from a topic.\n */\n async unsubscribe(topic: string, cb: EventCallback): Promise<void> {\n const wrappedCb = this.callbackMap.get(cb) ?? cb;\n this.callbackMap.delete(cb);\n await this.inner.unsubscribe(topic, wrappedCb);\n }\n\n /**\n * Get historical events for a topic from cache, from index `offset` on.\n */\n async getHistory(topic: string, offset: number = 0): Promise<Event[]> {\n return this.readLogFrom(topic, offset);\n }\n\n /**\n * Flush any pending operations on the inner PubSub.\n */\n async flush(): Promise<void> {\n await this.inner.flush();\n }\n\n /**\n * Expose the inner's {@link LeaseProvider} when it has one, otherwise\n * `undefined`. Leasing is a capability of the underlying backend\n * (e.g. Redis), not of the caching decorator itself — so rather than\n * unconditionally declaring lease methods (which would make\n * {@link isLeaseProvider} report `true` even when the inner can't\n * coordinate a lock), we surface the inner's capability directly. The\n * signals runtime unwraps this so wrapping with caching preserves real\n * distributed lease semantics without faking them.\n */\n getLeaseProvider(): LeaseProvider | undefined {\n return isLeaseProvider(this.inner) ? this.inner : undefined;\n }\n\n /**\n * Clear cached events for a specific topic (and the index counter), and\n * forward the clear to the inner transport.\n *\n * Call this when a stream completes to free memory. The forward matters for\n * persistent inner transports (e.g. Redis Streams): without it, wrapping a\n * pubsub in `CachingPubSub` silently turns `clearTopic` into a cache-only\n * no-op and the inner stream leaks forever.\n */\n override async clearTopic(topic: string): Promise<void> {\n this.undeliveredIndices.delete(topic);\n try {\n await Promise.all([\n this.cache.delete(this.getCacheKey(topic)),\n this.cache.delete(this.getCounterKey(topic)),\n this.inner.clearTopic(topic),\n ]);\n } catch (error) {\n // Honor the base-class contract: clearTopic is best-effort and callers\n // invoke it fire-and-forget, so a cache failure must not become an\n // unhandled rejection. A failed delete means retained state may leak\n // until the transport-level TTL backstop, so make it visible.\n this.logError(`[CachingPubSub] Failed to clear topic ${topic}`, error);\n }\n }\n\n /** Forward run trims to the inner transport; the per-process cache is left to its own bounds. */\n override async trimTopic(\n topic: string,\n options: { runId: string; producedBefore?: number; retainTerminalEvents?: boolean },\n ): Promise<void> {\n try {\n await this.inner.trimTopic(topic, options);\n } catch (error) {\n this.logError(`[CachingPubSub] Failed to trim topic ${topic}`, error);\n }\n }\n\n /**\n * Get the inner PubSub instance.\n * Useful for accessing implementation-specific methods like close().\n */\n getInner(): PubSub {\n return this.inner;\n }\n\n /** The cache holding this bus's retained frames. */\n getCache(): MastraServerCache {\n return this.cache;\n }\n}\n\n/**\n * Factory function to wrap a PubSub with caching capabilities.\n *\n * @example\n * ```typescript\n * import { withCaching, EventEmitterPubSub } from '@mastra/core/events';\n * import { InMemoryServerCache } from '@mastra/core/cache';\n *\n * const cache = new InMemoryServerCache();\n * const pubsub = withCaching(new EventEmitterPubSub(), cache);\n * ```\n */\nexport function withCaching(pubsub: PubSub, cache: MastraServerCache, options?: CachingPubSubOptions): CachingPubSub {\n return new CachingPubSub(pubsub, cache, options);\n}\n","export class PublisherQueueLimitError extends Error {\n constructor(\n message = 'UnixSocketPubSub publisher queue limit exceeded',\n readonly waitForCapacity?: () => Promise<void>,\n ) {\n super(message);\n }\n}\n","import type {\n StepResult,\n ToolSet,\n StaticToolCall,\n StaticToolResult,\n DynamicToolCall,\n DynamicToolResult,\n} from '@internal/ai-sdk-v5';\nimport type { StepTripwireData } from '../../types';\n\n// ContentPart is not exported from ai, so we derive it from StepResult\ntype ContentPart<TOOLS extends ToolSet> = StepResult<TOOLS>['content'][number];\nexport class DefaultStepResult<TOOLS extends ToolSet> implements StepResult<TOOLS> {\n readonly content: StepResult<TOOLS>['content'];\n readonly finishReason: StepResult<TOOLS>['finishReason'];\n readonly usage: StepResult<TOOLS>['usage'];\n readonly warnings: StepResult<TOOLS>['warnings'];\n readonly request: StepResult<TOOLS>['request'];\n readonly response: StepResult<TOOLS>['response'];\n readonly providerMetadata: StepResult<TOOLS>['providerMetadata'];\n /** Tripwire data if this step was rejected by a processor */\n readonly tripwire?: StepTripwireData;\n\n constructor({\n content,\n finishReason,\n usage,\n warnings,\n request,\n response,\n providerMetadata,\n tripwire,\n }: {\n content: StepResult<TOOLS>['content'];\n finishReason: StepResult<TOOLS>['finishReason'];\n usage: StepResult<TOOLS>['usage'];\n warnings: StepResult<TOOLS>['warnings'];\n request: StepResult<TOOLS>['request'];\n response: StepResult<TOOLS>['response'];\n providerMetadata: StepResult<TOOLS>['providerMetadata'];\n tripwire?: StepTripwireData;\n }) {\n this.content = content;\n this.finishReason = finishReason;\n this.usage = usage;\n this.warnings = warnings;\n this.request = request;\n this.response = response;\n this.providerMetadata = providerMetadata;\n this.tripwire = tripwire;\n }\n\n get text() {\n // Return empty string if this step was rejected by a tripwire\n if (this.tripwire) {\n return '';\n }\n return this.content\n .filter(part => part.type === 'text')\n .map(part => part.text)\n .join('');\n }\n\n get reasoning() {\n return this.content.filter(part => part.type === 'reasoning');\n }\n\n get reasoningText() {\n return this.reasoning.length === 0 ? undefined : this.reasoning.map(part => part.text).join('');\n }\n\n get files() {\n return this.content.filter(part => part.type === 'file').map(part => part.file);\n }\n\n get sources(): Extract<ContentPart<TOOLS>, { type: 'source' }>[] {\n return this.content.filter(part => part.type === 'source');\n }\n\n get toolCalls() {\n return this.content.filter(part => part.type === 'tool-call');\n }\n\n get staticToolCalls() {\n return this.toolCalls.filter((toolCall): toolCall is StaticToolCall<TOOLS> => toolCall.dynamic === false);\n }\n\n get dynamicToolCalls() {\n return this.toolCalls.filter((toolCall): toolCall is DynamicToolCall => toolCall.dynamic === true);\n }\n\n get toolResults() {\n return this.content.filter(part => part.type === 'tool-result');\n }\n\n get staticToolResults() {\n return this.toolResults.filter((toolResult): toolResult is StaticToolResult<TOOLS> => toolResult.dynamic === false);\n }\n\n get dynamicToolResults() {\n return this.toolResults.filter((toolResult): toolResult is DynamicToolResult => toolResult.dynamic === true);\n }\n}\n"],"mappings":";;;;;AAkBA,IAAsB,SAAtB,MAA6B;;;;;;;;;;;;;;;;;;CAmC3B,WAAW,QAA+B;EACxC,OAAO,QAAQ,QAAQ;CACzB;;;;;;;;;;;;;;;;;;;;CAqBA,UACE,QACA,UACe;EACf,OAAO,QAAQ,QAAQ;CACzB;;;;;;;;;;;;CAaA,IAAI,iBAAoD;EACtD,OAAO,CAAC,MAAM;CAChB;;;;;;;;;CAUA,IAAI,yBAAkC;EACpC,OAAO;CACT;;;;;CAMA,IAAI,kBAA2B;EAC7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