const require_rolldown_runtime = require("./rolldown-runtime-BrhgMLW6.cjs");
const require_error_count = require("./error-count-DeDpeWU2.cjs");
let events = require("events");
events = require_rolldown_runtime.__toESM(events, 1);
// src/events/pubsub.ts
var PubSub = class {
/**
* Delete all retained state for a topic (cached history, persistent stream
* entries, consumer groups) once no more events will be published to it.
*
* Called by run lifecycles (durable agents, the evented workflow engine)
* when a run reaches a terminal state, so per-run topics don't accumulate
* forever on transports that retain messages (e.g. Redis Streams).
*
* Default implementation is a no-op: transports that don't retain anything
* per topic (e.g. plain EventEmitter delivery) have nothing to clear.
*
* Best-effort contract: implementations should not throw — callers invoke
* this fire-and-forget at cleanup boundaries, so failures should be logged
* by the implementation rather than rejected.
*
* @param topic - The topic whose retained state should be deleted
*/
clearTopic(_topic) {
return Promise.resolve();
}
/**
* Delete a single run's retained entries from a topic: every entry published
* with `runId`. Used to drop a thread run's entries once storage holds it, so
* retained transports (e.g. Redis Streams) stay bounded without touching
* entries of other runs.
*
* Default implementation is a no-op: transports that don't retain anything
* per topic have nothing to trim. Same best-effort contract as `clearTopic`.
*
* @param topic - The topic to trim
* @param options.runId - The run whose entries to delete
* @param options.producedBefore - Only delete entries whose `data.producedAt`
* is at or before this epoch ms and that aren't `data.pinned`. Used to drop
* the parts of a run that storage already holds while the run continues.
* @param options.retainTerminalEvents - Preserve final run-completed, run-failed,
* and run-aborted events, plus run-registered authority metadata, so subscribers
* can recover outcomes without output and reject superseded executions.
* Completion events with status suspended are not final and may be trimmed.
*/
trimTopic(_topic, _options) {
return Promise.resolve();
}
/**
* Delivery modes this PubSub implementation supports.
*
* Defaults to `['pull']` for backward compatibility — third-party
* implementations that don't override this property are treated as
* pull-mode, which preserves today's behavior.
*
* Implementations that deliver events without an active read loop (e.g.
* EventEmitter, GCP Pub/Sub push subscriptions) should declare `'push'`.
* Implementations that support both modes should declare both.
*/
get supportedModes() {
return ["pull"];
}
/**
* Whether this implementation honors `options.batch` on `subscribe()`
* natively. Defaults to `false`.
*
* Implementations that integrate batching internally (e.g. against their
* own broker retention or via an `AckHandleBuffer`) override this getter
* and return `true`.
*/
get supportsNativeBatching() {
return false;
}
/**
* Whether this implementation supports replay from a numeric event offset.
* Defaults to `false`.
*/
get supportsOffsets() {
return false;
}
/**
* Whether a message delivered to a consumer that neither acks nor nacks it
* (for example because its process died) is delivered again to a consumer of
* the same group once the broker considers it abandoned. Defaults to `false`.
*
* Workflow recovery leaves the evented runs on such a pubsub to the broker:
* the message of the step a dead worker held is redelivered, so no recovery
* pass restarts the run. The broker's abandonment threshold must be at least
* 30 s, the evented step fence a dead worker leaves behind; a redelivery that
* arrives before the fence expires is dropped as a duplicate.
*/
get redeliversUnacked() {
return false;
}
/**
* Whether a subscriber that attaches after events were published on `topic`
* can still read them (`getHistory`, a replaying subscribe). A publisher that
* sends changes against its earlier events resends the whole state when it
* can't. Defaults to {@link supportsOffsets}.
* @internal
*/
__replaysTopic(_topic) {
return this.supportsOffsets;
}
/**
* Surface attempts to use an unsupported non-zero offset.
* Implementations may override this hook to use their configured logger.
*/
onUnsupportedOffset(offset) {
console.warn(`PubSub implementation does not support replay from offset ${offset}; falling back to full replay.`);
}
/**
* Get historical events for a topic.
* Default implementation returns empty array (no history support).
* Override in implementations that support event caching.
*
* @param topic - The topic to get history for
* @param offset - Starting index (0-based), defaults to 0
* @returns Array of events from the specified index
*/
getHistory(_topic, _offset) {
return Promise.resolve([]);
}
/**
* Subscribe to a topic with automatic replay of cached events.
* First replays any cached history, then subscribes to live events.
* Default implementation falls back to regular subscribe (no replay).
* Override in implementations that support event caching.
*
* @param topic - The topic to subscribe to
* @param cb - Callback invoked for each event (both cached and live)
*/
subscribeWithReplay(topic, cb) {
return this.subscribe(topic, cb);
}
/**
* Subscribe to a topic with replay starting from a specific index.
* This is more efficient than full replay when the client knows their last position.
* Default implementation falls back to subscribeWithReplay (full replay).
* Override in implementations that support indexed event caching.
*
* @param topic - The topic to subscribe to
* @param offset - Start replaying from this index (0-based)
* @param cb - Callback invoked for each event
*/
subscribeFromOffset(topic, offset, cb) {
if (offset !== 0 && !this.supportsOffsets) this.onUnsupportedOffset(offset);
return this.subscribeWithReplay(topic, cb);
}
/**
* The underlying delivery transport, unwrapped through decorators.
*
* Decorators that delegate delivery (e.g. `CachingPubSub`) override this to
* return their inner's raw bus. The `mastra.pubsub` proxy forwards the call
* to its target, so it also unwraps transparently. Used to detect when two
* PubSub references are backed by the same transport (e.g. an agent's custom
* pubsub that is also the Mastra-level bus) so a bridge between them doesn't
* double-deliver.
* @internal
*/
__rawBus() {
return this;
}
/**
* Identity probe that sees through binding decorators.
*
* The `mastra.pubsub` proxy binds every method to its target, so calling
* `__self()` on the proxy returns the underlying PubSub instance. Used where
* reference equality must hold across the proxy (e.g. `CachingPubSub`
* refusing to follow itself). Unlike `__rawBus`, this does NOT unwrap
* delegating decorators — a `CachingPubSub` returns itself, not its inner.
* @internal
*/
__self() {
return this;
}
};
/**
* Duck-typed check for whether a value implements {@link LeaseProvider}.
*
* Uses structural detection rather than `instanceof` so it works across
* package boundaries (e.g. a separately-published pubsub backend resolving
* a different copy of `@mastra/core`).
*/
function isLeaseProvider(value) {
if (!value || typeof value !== "object" && typeof value !== "function") return false;
const candidate = value;
return typeof candidate.acquireLease === "function" && typeof candidate.getLeaseOwner === "function" && typeof candidate.releaseLease === "function" && typeof candidate.renewLease === "function" && typeof candidate.transferLease === "function";
}
/**
* Always-win / no-op {@link LeaseProvider}. Used by the signals runtime
* when the configured pubsub does not implement `LeaseProvider` — this
* preserves single-process behavior where every caller "wins" its own
* lease race and release/renew are inert.
*/
const NoopLeaseProvider = {
acquireLease(_key, owner, _ttlMs) {
return Promise.resolve({
acquired: true,
owner
});
},
getLeaseOwner(_key) {
return Promise.resolve(void 0);
},
releaseLease(_key, _owner) {
return Promise.resolve();
},
renewLease(_key, _owner, _ttlMs) {
return Promise.resolve(true);
},
transferLease(_key, _fromOwner, _toOwner, _ttlMs) {
return Promise.resolve(true);
}
};
// src/events/event-emitter/batch-policy.ts
const defaultDeps = {
now: () => Date.now(),
setTimeout: (cb, ms) => setTimeout(cb, ms),
clearTimeout: (handle) => clearTimeout(handle)
};
/**
* Internal to `EventEmitterPubSub`. Embedded by `AckHandleBuffer` to decide
* when a batched subscription should flush (size, time, coalesce, overflow).
*
* Not part of the public API — users configure batching via
* `SubscribeBatchOptions` on `subscribe`.
*/
var BatchPolicy = class {
opts;
deps;
maxBufferSize;
overflow;
firstQueuedAt = null;
lastDeliveredAt = -Infinity;
size = 0;
timer = null;
flushHandler = null;
constructor(opts, deps = defaultDeps) {
this.opts = opts;
this.deps = deps;
this.maxBufferSize = opts.maxBufferSize ?? 256;
this.overflow = opts.overflow ?? "coalesce-or-drop-oldest";
}
/** Bind the function invoked when the deadline timer fires. */
bindFlushHandler(fn) {
this.flushHandler = fn;
}
/**
* Called by the integrator each time an event is enqueued.
* Returns whether the integrator should flush immediately.
*/
onEnqueue(event) {
this.size += 1;
if (this.firstQueuedAt === null) this.firstQueuedAt = this.deps.now();
const now = this.deps.now();
const intervalFloor = this.lastDeliveredAt + (this.opts.minIntervalMs ?? 0);
if (this.opts.isImmediate?.(event)) {
if (now >= intervalFloor) return "flush-now";
this.scheduleAt(intervalFloor);
return "wait";
}
if (this.size >= this.maxBufferSize) return "flush-now";
if (this.opts.maxSize !== void 0 && this.size >= this.opts.maxSize) {
if (now >= intervalFloor) return "flush-now";
this.scheduleAt(intervalFloor);
return "wait";
}
this.scheduleDeadline();
return "wait";
}
/**
* Called by the integrator after a successful flush has delivered
* `deliveredCount` events. Resets timer + firstQueuedAt.
*/
onFlushed(deliveredCount) {
this.lastDeliveredAt = this.deps.now();
this.size = Math.max(0, this.size - deliveredCount);
this.firstQueuedAt = null;
this.cancelTimer();
}
/**
* Pure helper. Given the caller-owned queue contents, applies `coalesce`
* and `overflow` to decide what to deliver and what to drop.
* Order-preserving for kept events.
*/
prepareBatch(events) {
let working = events;
if (this.opts.coalesce) {
const coalesced = this.opts.coalesce(working);
const inputRefs = new Set(working);
working = coalesced.every((e) => inputRefs.has(e)) ? coalesced : [];
}
const keptRefs = new Set(working);
const computeDropped = () => events.filter((e) => !keptRefs.has(e));
if (working.length <= this.maxBufferSize) return {
delivered: working,
dropped: computeDropped()
};
const overBy = working.length - this.maxBufferSize;
const isImmediate = this.opts.isImmediate;
let kept;
let droppedFromOverflow;
switch (this.overflow) {
case "drop-newest": {
const splitFromEnd = this.takeWithoutDropping(working, overBy, isImmediate, true);
kept = splitFromEnd.kept;
droppedFromOverflow = splitFromEnd.dropped;
break;
}
default: {
const splitFromStart = this.takeWithoutDropping(working, overBy, isImmediate, false);
kept = splitFromStart.kept;
droppedFromOverflow = splitFromStart.dropped;
break;
}
}
return {
delivered: kept,
dropped: [...computeDropped(), ...droppedFromOverflow]
};
}
/** Stop the timer and clear policy state. */
dispose() {
this.cancelTimer();
this.flushHandler = null;
this.firstQueuedAt = null;
this.size = 0;
}
scheduleDeadline() {
if (this.opts.maxWaitMs === void 0 && this.opts.minIntervalMs === void 0) return;
const firstQueuedAt = this.firstQueuedAt ?? this.deps.now();
const deadline = this.opts.maxWaitMs !== void 0 ? firstQueuedAt + this.opts.maxWaitMs : Number.POSITIVE_INFINITY;
const floor = this.lastDeliveredAt + (this.opts.minIntervalMs ?? 0);
const at = Math.max(deadline, floor);
this.scheduleAt(at);
}
scheduleAt(at) {
if (!isFinite(at)) return;
this.cancelTimer();
const delay = Math.max(0, at - this.deps.now());
this.timer = this.deps.setTimeout(() => {
this.timer = null;
const handler = this.flushHandler;
if (handler) handler();
}, delay);
}
cancelTimer() {
if (this.timer !== null) {
this.deps.clearTimeout(this.timer);
this.timer = null;
}
}
/**
* Drop `count` non-immediate items from the start (or end) of `items`.
* Immediate items are never dropped — if every candidate is immediate,
* fewer than `count` items are dropped.
*/
takeWithoutDropping(items, count, isImmediate, fromEnd) {
const dropped = [];
const result = [...items];
let remaining = count;
const order = fromEnd ? [...result.keys()].reverse() : [...result.keys()];
for (const idx of order) {
if (remaining === 0) break;
const ev = result[idx];
if (isImmediate?.(ev)) continue;
dropped.push(ev);
result[idx] = void 0;
remaining -= 1;
}
return {
kept: result.filter((e) => e !== void 0),
dropped
};
}
};
// src/events/event-emitter/ack-handle-buffer.ts
/**
* In-process queue used by `EventEmitterPubSub` to turn its
* one-event-per-emit stream into batched callback invocations.
* Owns a `BatchPolicy` that decides when to flush (size, time,
* quiet-period) and holds (event, ack, nack) triples in publish
* order until that decision fires.
*
* Extracted from `EventEmitterPubSub` only so the batching state
* machine can be tested in isolation. Not a public extension point.
* State is per-process; the queue dies with the process.
*/
var AckHandleBuffer = class {
cb;
onError;
policy;
queue = [];
flushing = false;
reflush = false;
disposed = false;
constructor(cb, opts, deps, onError) {
this.cb = cb;
this.onError = onError;
this.policy = new BatchPolicy(opts, deps);
this.policy.bindFlushHandler(() => this.flush().catch((err) => {
this.onError?.(err, { phase: "cb" });
}));
}
/**
* Called by the adapter for each event arriving from the underlying transport.
*/
async push(event, ack, nack) {
if (this.disposed) return;
this.queue.push({
event,
ack,
nack
});
if (this.policy.onEnqueue(event) === "flush-now") await this.flush();
}
/**
* Drain the current queue regardless of policy state. Safe to call from
* adapter `flush()` or external code that wants to force delivery.
*/
async flush() {
if (this.flushing) {
this.reflush = true;
return;
}
if (this.queue.length === 0) return;
this.flushing = true;
try {
do {
this.reflush = false;
if (this.queue.length === 0) break;
const snapshot = this.queue;
this.queue = [];
const events = snapshot.map((e) => e.event);
const byEvent = /* @__PURE__ */ new Map();
for (const e of snapshot) byEvent.set(e.event, e);
const { delivered, dropped } = this.policy.prepareBatch(events);
for (const ev of dropped) {
const entry = byEvent.get(ev);
if (entry?.ack) try {
await entry.ack();
} catch (err) {
this.onError?.(err, { phase: "ack-dropped" });
}
}
for (const ev of delivered) {
if (this.disposed) break;
const entry = byEvent.get(ev);
try {
await this.cb(ev, entry?.ack, entry?.nack);
} catch (err) {
this.onError?.(err, { phase: "cb" });
}
}
this.policy.onFlushed(delivered.length + dropped.length);
} while (this.reflush && !this.disposed);
} finally {
this.flushing = false;
}
}
dispose() {
this.disposed = true;
this.queue = [];
this.policy.dispose();
}
};
// src/events/event-emitter/index.ts
const NOOP_ACK = async () => {};
/**
* The default pubsub: delivers events inside the process that published them.
*
* Several Mastra instances that share one storage but each use their own
* `EventEmitterPubSub` are not supported for evented workflows: every instance
* treats the others' runs as its own to recover. A multi-instance evented
* deployment needs a broker such as Redis Streams, Valkey Streams or Google
* Cloud Pub/Sub.
*/
var EventEmitterPubSub = class extends PubSub {
get supportedModes() {
return ["pull", "push"];
}
/**
* `EventEmitterPubSub` is strictly in-process, so the `AckHandleBuffer`
* queue it uses for batching shares the same lifetime as everything
* else here. Nothing more durable is promised, and nothing less is
* needed.
*/
get supportsNativeBatching() {
return true;
}
/**
* Ack and nack are no-ops here: a message lives only in the process that
* published it, so nothing redelivers it once that process stops.
*/
get redeliversUnacked() {
return false;
}
emitter;
groups = /* @__PURE__ */ new Map();
groupCounters = /* @__PURE__ */ new Map();
groupListeners = /* @__PURE__ */ new Map();
pendingNacks = /* @__PURE__ */ new Set();
deliveryAttempts = /* @__PURE__ */ new Map();
fanoutWrappers = /* @__PURE__ */ new Map();
batchBuffers = /* @__PURE__ */ new Map();
logger;
constructor(existingEmitter, options = {}) {
super();
this.emitter = existingEmitter ?? new events.default();
this.logger = options.logger;
}
/**
* Debug-hostile silent failures are the default for emitter listeners.
* Surface buffer-side errors on a single channel so they're at least visible.
*/
/**
* Subscribers may return a promise now that they can acknowledge deliveries.
* This transport is push-only and has nothing to redeliver, so a rejection is
* logged rather than becoming an unhandled rejection.
*/
logSubscriberError(topic, err) {
const message = `[EventEmitterPubSub] subscriber failed for ${topic}`;
if (this.logger) this.logger.error(message, err);
else console.error(message, err);
}
logBufferError(topic, err, ctx) {
const message = `[EventEmitterPubSub] batched ${ctx.phase} failed for ${topic}`;
if (this.logger) this.logger.error(message, err);
else console.error(message, err);
}
async publish(topic, event, _options) {
const id = crypto.randomUUID();
const createdAt = /* @__PURE__ */ new Date();
this.emitter.emit(topic, {
...event,
id,
createdAt,
deliveryAttempt: 1
});
}
async subscribe(topic, cb, options) {
if (options?.batch) {
const buffer = new AckHandleBuffer(cb, options.batch, void 0, (err, ctx) => {
this.logBufferError(topic, err, ctx);
});
let byCb = this.batchBuffers.get(topic);
if (!byCb) {
byCb = /* @__PURE__ */ new Map();
this.batchBuffers.set(topic, byCb);
}
byCb.set(cb, buffer);
if (options.group) this.subscribeWithGroup(topic, cb, options.group);
else {
const wrapper = (event) => {
buffer.push(event, NOOP_ACK, NOOP_ACK).catch((err) => {
this.logBufferError(topic, err, { phase: "cb" });
});
};
let byCbFanout = this.fanoutWrappers.get(topic);
if (!byCbFanout) {
byCbFanout = /* @__PURE__ */ new Map();
this.fanoutWrappers.set(topic, byCbFanout);
}
byCbFanout.set(cb, wrapper);
this.emitter.on(topic, wrapper);
}
return;
}
if (options?.group) this.subscribeWithGroup(topic, cb, options.group);
else {
const wrapper = (event) => {
try {
Promise.resolve(cb(event, NOOP_ACK, NOOP_ACK)).catch((err) => {
this.logSubscriberError(topic, err);
});
} catch (err) {
this.logSubscriberError(topic, err);
}
};
let byCb = this.fanoutWrappers.get(topic);
if (!byCb) {
byCb = /* @__PURE__ */ new Map();
this.fanoutWrappers.set(topic, byCb);
}
byCb.set(cb, wrapper);
this.emitter.on(topic, wrapper);
}
}
async unsubscribe(topic, cb) {
const byCbBuffers = this.batchBuffers.get(topic);
const buffer = byCbBuffers?.get(cb);
if (buffer && byCbBuffers) {
buffer.dispose();
byCbBuffers.delete(cb);
if (byCbBuffers.size === 0) this.batchBuffers.delete(topic);
}
for (const [group, topicMap] of this.groups) {
const members = topicMap.get(topic);
if (members) {
const idx = members.indexOf(cb);
if (idx !== -1) {
members.splice(idx, 1);
if (members.length === 0) {
topicMap.delete(topic);
const listenerKey = `${topic}:${group}`;
const listener = this.groupListeners.get(listenerKey);
if (listener) {
this.emitter.off(topic, listener);
this.groupListeners.delete(listenerKey);
this.groupCounters.delete(listenerKey);
}
}
if (topicMap.size === 0) this.groups.delete(group);
return;
}
}
}
const byCb = this.fanoutWrappers.get(topic);
const wrapper = byCb?.get(cb);
if (wrapper && byCb) {
this.emitter.off(topic, wrapper);
byCb.delete(cb);
if (byCb.size === 0) this.fanoutWrappers.delete(topic);
} else this.emitter.off(topic, cb);
}
async flush() {
while (true) {
const drains = [];
for (const [topic, byCb] of this.batchBuffers.entries()) for (const buffer of byCb.values()) drains.push({
topic,
promise: buffer.flush()
});
if (drains.length > 0) {
const results = await Promise.allSettled(drains.map((d) => d.promise));
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (result.status === "rejected") this.logBufferError(drains[i].topic, result.reason, { phase: "cb" });
}
}
if (this.pendingNacks.size === 0) return;
await new Promise((resolve) => {
const check = () => {
if (this.pendingNacks.size === 0) resolve();
else setTimeout(check, 10);
};
check();
});
}
}
/**
* Clean up all listeners during graceful shutdown.
*/
async close() {
for (const handle of this.pendingNacks) clearTimeout(handle);
this.pendingNacks.clear();
this.deliveryAttempts.clear();
for (const byCb of this.batchBuffers.values()) for (const buffer of byCb.values()) buffer.dispose();
this.batchBuffers.clear();
this.emitter.removeAllListeners();
this.groups.clear();
this.groupCounters.clear();
this.groupListeners.clear();
this.fanoutWrappers.clear();
}
subscribeWithGroup(topic, cb, group) {
let topicMap = this.groups.get(group);
if (!topicMap) {
topicMap = /* @__PURE__ */ new Map();
this.groups.set(group, topicMap);
}
let members = topicMap.get(topic);
if (!members) {
members = [];
topicMap.set(topic, members);
}
members.push(cb);
const listenerKey = `${topic}:${group}`;
if (!this.groupListeners.has(listenerKey)) {
const listener = (event) => {
this.deliverToGroup(topic, group, listenerKey, event);
};
this.groupListeners.set(listenerKey, listener);
this.emitter.on(topic, listener);
}
}
deliverToGroup(topic, group, listenerKey, event) {
const currentMembers = this.groups.get(group)?.get(topic);
if (!currentMembers || currentMembers.length === 0) return;
const counter = this.groupCounters.get(listenerKey) ?? 0;
const idx = counter % currentMembers.length;
this.groupCounters.set(listenerKey, counter + 1);
const attemptKey = `${listenerKey}:${event.id}`;
const attempt = this.deliveryAttempts.get(attemptKey) ?? 1;
const eventWithAttempt = {
...event,
deliveryAttempt: attempt
};
const ack = async () => {
this.deliveryAttempts.delete(attemptKey);
};
const nack = async () => {
this.deliveryAttempts.set(attemptKey, attempt + 1);
const handle = setTimeout(() => {
this.pendingNacks.delete(handle);
this.deliverToGroup(topic, group, listenerKey, event);
}, 0);
this.pendingNacks.add(handle);
};
const member = currentMembers[idx];
const buffer = this.batchBuffers.get(topic)?.get(member);
if (buffer) buffer.push(eventWithAttempt, ack, nack).catch((err) => {
this.logBufferError(topic, err, { phase: "cb" });
});
else try {
Promise.resolve(member(eventWithAttempt, ack, nack)).catch((err) => {
this.logSubscriberError(topic, err);
});
} catch (err) {
this.logSubscriberError(topic, err);
}
}
leases = /* @__PURE__ */ new Map();
acquireLease(key, owner, ttlMs) {
const now = Date.now();
const existing = this.leases.get(key);
if (existing && existing.expiresAt > now && existing.owner !== owner) return Promise.resolve({
acquired: false,
owner: existing.owner
});
this.leases.set(key, {
owner,
expiresAt: now + ttlMs
});
return Promise.resolve({
acquired: true,
owner
});
}
getLeaseOwner(key) {
const existing = this.leases.get(key);
if (!existing) return Promise.resolve(void 0);
if (existing.expiresAt <= Date.now()) {
this.leases.delete(key);
return Promise.resolve(void 0);
}
return Promise.resolve(existing.owner);
}
releaseLease(key, owner) {
const existing = this.leases.get(key);
if (existing && existing.owner === owner) this.leases.delete(key);
return Promise.resolve();
}
renewLease(key, owner, ttlMs) {
const existing = this.leases.get(key);
if (!existing || existing.owner !== owner || existing.expiresAt <= Date.now()) return Promise.resolve(false);
existing.expiresAt = Date.now() + ttlMs;
return Promise.resolve(true);
}
transferLease(key, fromOwner, toOwner, ttlMs) {
const existing = this.leases.get(key);
if (!existing || existing.owner !== fromOwner || existing.expiresAt <= Date.now()) return Promise.resolve(false);
this.leases.set(key, {
owner: toOwner,
expiresAt: Date.now() + ttlMs
});
return Promise.resolve(true);
}
};
// src/events/acking-callback.ts
/**
* Adapt an event-only handler into an `EventCallback` that acknowledges every
* delivery.
*
* Handlers that only need the event cannot honour the `EventCallback` contract
* themselves: on a durable backend (Redis consumer groups, GCP Pub/Sub) every
* delivery — including the ones a handler inspects and filters out — has to be
* acked, or it stays in the subscription's pending set and is redelivered.
* Wrapping is the only way an event-only handler can satisfy that.
*
* A throwing handler leaves the delivery unacked and rejects the callback, which
* a backend that honours redelivery treats as a nack.
*/
function withAck(handler) {
return async (event, ack) => {
await handler(event);
await ack?.();
};
}
// src/stream/strip-model-snapshots.ts
/**
* Removes the model request/history snapshots that agent `step-start`,
* `step-finish` and `finish` chunks carry (full prompt, file parts, message
* history, cumulative steps). Used for copies of chunks that are fanned out to
* other subscribers, which don't need those fields. Only the given chunk is
* inspected; callers decide which nested chunks to pass in. Returns the same
* reference when nothing was removed.
*/
function stripModelSnapshots(chunk) {
if (!chunk || typeof chunk !== "object") return chunk;
const { type, payload } = chunk;
if (!payload || typeof payload !== "object") return chunk;
const p = payload;
if (type === "step-start") {
if (!("request" in p) && !("inputMessages" in p)) return chunk;
const { request: _request, inputMessages: _inputMessages, ...rest } = p;
return {
...chunk,
payload: rest
};
}
if (type === "step-finish" || type === "finish") {
let changed = false;
const next = { ...p };
if (p.metadata && typeof p.metadata === "object" && "request" in p.metadata) {
const { request: _request, ...metadata } = p.metadata;
next.metadata = metadata;
changed = true;
}
if (p.output && typeof p.output === "object" && "steps" in p.output) {
const { steps: _steps, ...output } = p.output;
next.output = output;
changed = true;
}
if ("messages" in p) {
delete next.messages;
changed = true;
}
return changed ? {
...chunk,
payload: next
} : chunk;
}
return chunk;
}
const PROGRESS_WRAPPER_TYPES = /* @__PURE__ */ new Set(["tool-output", "workflow-step-output"]);
/**
* Removes model request/history snapshots from agent chunks before a progress
* chunk is published to pubsub. Nested agent chunks arrive wrapped in
* `tool-output` / `workflow-step-output` payloads, so only those wrappers are
* unwrapped, and only agent-origin chunks are stripped — data a tool writes
* itself (`from: 'USER'`) is published as-is.
*/
function slimProgressChunk(chunk, depth = 0) {
if (!chunk || typeof chunk !== "object") return chunk;
const { type, from, payload } = chunk;
if (typeof type === "string" && PROGRESS_WRAPPER_TYPES.has(type) && payload && typeof payload === "object") {
const p = payload;
const inner = p.output;
if (!(!!inner && typeof inner === "object" && typeof inner.type === "string" && (inner.from === "AGENT" || PROGRESS_WRAPPER_TYPES.has(inner.type)))) return chunk;
if (depth >= 20) {
const { output: _output, ...rest } = p;
return {
...chunk,
payload: rest
};
}
const output = slimProgressChunk(inner, depth + 1);
return output === inner ? chunk : {
...chunk,
payload: {
...p,
output
}
};
}
return from === "AGENT" ? stripModelSnapshots(chunk) : chunk;
}
/**
* Like {@link slimProgressChunk}, but only for the agent chunks nested in a
* `tool-output` / `workflow-step-output` chunk; any other chunk is returned as-is.
*/
function slimNestedAgentChunks(chunk) {
const type = chunk && typeof chunk === "object" ? chunk.type : void 0;
return typeof type === "string" && PROGRESS_WRAPPER_TYPES.has(type) ? slimProgressChunk(chunk) : chunk;
}
// src/events/topics.ts
/**
* Topic prefixes whose events are only ever consumed by the process that
* published them.
*
* `workflow.events.v2.<runId>` carries per-run watch events: the execution
* engine subscribes per-run, in-process, and nothing replays them. The payloads
* accumulate step results and routinely run to megabytes.
*/
const RUN_LOCAL_TOPIC_PREFIXES = ["workflow.events.v2."];
/**
* Whether a topic is run-local — consumed only by the publishing process.
*
* Run-local topics must never be relayed to other instances, nor mirrored into
* a shared replay cache: no other instance can read them, so caching only grows
* the store without bound (see issue #20646).
*
* This predicate is the single source of truth for that policy. It is consumed
* both by the `mastra.pubsub` proxy (which tags publishes `localOnly` so the
* broker skips cross-instance fan-out) and by the durable agent's
* `CachingPubSub` wiring (which sits *above* that proxy and so cannot observe
* the `localOnly` flag itself).
*/
function isRunLocalTopic(topic) {
return RUN_LOCAL_TOPIC_PREFIXES.some((prefix) => topic.startsWith(prefix));
}
/**
* How long a durable run's stream log (`agent.stream.<runId>`) is retained.
*
* The log is what `observe({ offset })` replays from, and its counter numbers
* every frame. A run parked on a tool approval can wait far longer than a
* cache's default TTL; if the log expired meanwhile, numbering would restart at
* 0 while an attached observer still held the old cursor. The run's suspension
* frame is its last append before it parks, so stamping this on every append
* covers the parked window. Run cleanup deletes the log when the run ends.
*/
const RUN_LOG_TTL_MS = 864e5;
const RUN_LOG_TOPIC_PREFIX = "agent.stream.";
/** Minimum retention for a topic's cached log, or `undefined` for the cache default. */
function cachedLogTtlMs(topic) {
return topic.startsWith(RUN_LOG_TOPIC_PREFIX) ? RUN_LOG_TTL_MS : void 0;
}
/**
* The copy of `event` a run's cached log keeps.
*
* A delegated sub-agent's chunks are forwarded on the run stream inside
* `tool-output` / `workflow-step-output`, and each nested step-start,
* step-finish and finish carries the sub-agent's full prompt, history and
* steps. Stored as-is, every delegated run grows the log by megabytes. The log
* keeps them slimmed; live subscribers still receive the event as published,
* so a caller reading its own run sees the same chunks as a plain Agent's
* caller (see #29035).
*/
function toCachedLogFrame(topic, event) {
if (event.type !== "chunk" || !topic.startsWith(RUN_LOG_TOPIC_PREFIX)) return event;
const data = slimNestedAgentChunks(event.data);
return data === event.data ? event : {
...event,
data
};
}
// src/events/codec/error.ts
const MAX_CAUSE_DEPTH = 5;
/**
* Serializes an Error instance to a plain SerializedError object without
* mutating the original. Unlike `getErrorFromUnknown(...).toJSON()`, this does
* not attach a non-enumerable `toJSON` to the live Error.
*/
function serializeError(err, depth = 0) {
const json = {
name: err.name || "Error",
message: err.message
};
if (err.stack !== void 0) json.stack = err.stack;
if (err.cause !== void 0) {
if (err.cause instanceof Error && depth < MAX_CAUSE_DEPTH) json.cause = serializeError(err.cause, depth + 1);
else json.cause = err.cause;
}
for (const key in err) {
if (!Object.prototype.hasOwnProperty.call(err, key)) continue;
if (key === "message" || key === "name" || key === "stack" || key === "cause" || key === "__mastraSpanErrorOrigin") continue;
json[key] = err[key];
}
const origin = require_error_count.getSpanErrorOrigin(err);
if (origin) json.__mastraSpanErrorOrigin = origin;
return json;
}
/**
* Rehydrates a SerializedError into a vanilla Error instance. We never
* instantiate user-controlled prototypes — name is preserved as a string field.
*/
function rehydrateError(s) {
const cause = s.cause !== void 0 ? s.cause && typeof s.cause === "object" && "message" in s.cause && "name" in s.cause ? rehydrateError(s.cause) : s.cause : void 0;
const err = cause !== void 0 ? new Error(s.message, { cause }) : new Error(s.message);
if (s.name) err.name = s.name;
if (s.stack !== void 0) err.stack = s.stack;
for (const key in s) {
if (!Object.prototype.hasOwnProperty.call(s, key)) continue;
if (key === "message" || key === "name" || key === "stack" || key === "cause" || key === "__mastraSpanErrorOrigin") continue;
err[key] = s[key];
}
const origin = require_error_count.getSpanErrorOrigin(s);
if (origin) require_error_count.setSpanErrorOrigin(err, origin);
return err;
}
// src/events/caching-pubsub.ts
const EMPTY_INDICES = /* @__PURE__ */ new Set();
/**
* A PubSub decorator that adds event caching and replay capabilities.
*
* Wraps any PubSub implementation and uses MastraServerCache to:
* - Cache all published events per topic
* - Enable replay of cached events for late subscribers
*
* This enables resumable streams - clients can disconnect and reconnect
* without missing events.
*
* ## One append path
*
* Every cached publish goes through {@link MastraServerCache.listPushIndexed},
* which allocates the frame's index and appends it. The cache list is
* therefore the run's log, and the transport only carries the
* live tail of that log. Subscribers hold a single integer cursor and backfill
* any gap they observe from the log rather than relying on transport replay.
*
* A list position is not necessarily its index: a cache whose append is not
* atomic can allocate an index and then fail to push the frame, leaving a hole
* that shifts every later frame to a lower position. Reads go through
* `readLogFrom`, which uses the counter minus the list length to find where
* index `from` can start, and returns entries in index order. A frame whose
* cache write failed is not recoverable.
*
* Limitation: a non-atomic append (the default
* {@link MastraServerCache.listPushIndexed}, or Redis after its CROSSSLOT
* fallback) can also let concurrent publishes store frames out of order. An
* entry that lands below the computed start position is then missed, e.g.
* the log `[0, 2, 1, 3]` read from index 2 loses index 2. Removing that needs
* an atomic append.
*
* If caching a frame fails, it is published without an index and delivered
* live only.
*
* ## Batching
*
* `CachingPubSub` is transparent to `options.batch`: `subscribe()` forwards
* the option to the inner PubSub, and `supportsNativeBatching` mirrors the
* inner's value. Wrapping a non-native inner with `{ batch: {...} }` results
* in unbatched delivery — use an inner that returns
* `supportsNativeBatching === true` (e.g. `EventEmitterPubSub`) if you need
* batched delivery.
*
* @example
* ```typescript
* import { EventEmitterPubSub, CachingPubSub } from '@mastra/core/events';
* import { InMemoryServerCache } from '@mastra/core/cache';
*
* const cache = new InMemoryServerCache();
* const pubsub = new CachingPubSub(new EventEmitterPubSub(), cache);
*
* // Subscribe with replay - receives cached events first, then live
* await pubsub.subscribeWithReplay('my-topic', (event) => {
* console.log(event);
* });
* ```
*/
var CachingPubSub = class extends PubSub {
inner;
cache;
keyPrefix;
keyFormat;
logger;
shouldCache;
extendExistingLogsOnly;
onUnlogged;
/** Maps original callbacks to their wrapped versions for proper unsubscribe */
callbackMap = /* @__PURE__ */ new Map();
/**
* Log indices per topic that were appended to the cache but whose live
* publish threw. The frame stays in the log (late subscribers still replay
* it), but the transport never carried it, so readers must not wait for it
* to arrive.
*/
undeliveredIndices = /* @__PURE__ */ new Map();
constructor(inner, cache, options = {}) {
super();
this.inner = inner;
this.cache = cache;
this.keyPrefix = options.keyPrefix ?? "pubsub:";
this.keyFormat = options.keyFormat ?? "legacy";
this.logger = options.logger;
this.shouldCache = options.shouldCache;
this.extendExistingLogsOnly = options.extendExistingLogsOnly ?? false;
this.onUnlogged = options.onUnlogged;
}
/**
* @deprecated No longer used; see {@link CachingPubSubOptions.source}. Kept as
* a no-op for compatibility.
*/
__setSource(_source) {}
/** Unwrap to the inner transport so capability checks see through this decorator. */
__rawBus() {
return this.inner.__rawBus();
}
get supportsNativeBatching() {
return this.inner.supportsNativeBatching;
}
get supportsOffsets() {
return true;
}
get redeliversUnacked() {
return this.inner.redeliversUnacked;
}
/**
* Topics `shouldCache` leaves out only reach the inner transport. With
* `extendExistingLogsOnly`, a process that doesn't hold a run's log
* publishes it live only; that setup is already warned about (`onUnlogged`)
* and its replays miss those frames whatever they carry, so it still counts
* as kept.
*/
__replaysTopic(topic) {
return this.shouldCache?.(topic) !== false || this.inner.__replaysTopic(topic);
}
/**
* Log an error message using the configured logger or console.error.
*/
logError(message, error) {
if (this.logger) this.logger.error(message, error);
else console.error(message, error);
}
/**
* Log a warning using the configured logger or console.warn.
*/
logWarn(message) {
if (this.logger) this.logger.warn(message);
else console.warn(message);
}
/** Get the cache key for a topic's event list. */
getCacheKey(topic) {
if (this.keyFormat === "legacy") return `${this.keyPrefix}${topic}`;
const tag = encodeURIComponent(topic) || "%EMPTY";
return `${this.keyPrefix}{${tag}}`;
}
/** Get the cache key for a topic's index counter in the same Redis slot. */
getCounterKey(topic) {
return `${this.getCacheKey(topic)}:counter`;
}
/**
* Read the log entries for `topic` whose index is `from` or later.
*
* Each hole left by an allocated-but-unpushed index moves later entries one
* position below their index, so slicing at `from` would skip them. The
* counter minus the list length is the number of holes; start that many
* positions earlier and filter by index. When either value is unavailable
* (a failed read, or a cache whose `get` does not return counters), read
* the whole log instead.
*
* Numbered entries are returned in index order, followed by unnumbered
* ones, because a non-atomic append can store frames out of order.
*/
async readLogFrom(topic, from) {
const cacheKey = this.getCacheKey(topic);
let start = 0;
if (from > 0) {
const length = await this.cache.listLength(cacheKey).catch(() => void 0);
const counter = length === void 0 ? void 0 : await this.cache.get(this.getCounterKey(topic)).catch(() => void 0);
if (typeof length === "number" && typeof counter === "number") start = Math.max(0, from - Math.max(0, counter - length));
}
const entries = await this.cache.listFromTo(cacheKey, start);
const numbered = [];
const unnumbered = [];
for (const event of entries) if (typeof event.index !== "number") unnumbered.push(event);
else if (event.index >= from) numbered.push(event);
numbered.sort((a, b) => a.index - b.index);
return [...numbered, ...unnumbered];
}
async publish(topic, event, options) {
const fullEvent = {
...event,
id: crypto.randomUUID(),
createdAt: /* @__PURE__ */ new Date()
};
if (options?.localOnly || this.shouldCache?.(topic) === false) {
await this.inner.publish(topic, fullEvent, options);
return;
}
if (this.extendExistingLogsOnly && !await this.hasLog(topic)) {
this.onUnlogged?.(topic);
await this.inner.publish(topic, fullEvent, options);
return;
}
let index;
try {
index = await this.cache.listPushIndexed(this.getCacheKey(topic), this.getCounterKey(topic), toCachedLogFrame(topic, fullEvent), cachedLogTtlMs(topic));
} catch (error) {
this.logError(`[CachingPubSub] Failed to cache event for ${topic}`, error);
}
const numbered = index !== void 0 ? {
...fullEvent,
index
} : fullEvent;
try {
await this.inner.publish(topic, numbered, options);
} catch (error) {
if (index !== void 0) {
let indices = this.undeliveredIndices.get(topic);
if (!indices) this.undeliveredIndices.set(topic, indices = /* @__PURE__ */ new Set());
indices.add(index);
}
throw error;
}
}
async hasLog(topic) {
try {
return await this.cache.listLength(this.getCacheKey(topic)) > 0;
} catch (error) {
this.logError(`[CachingPubSub] Failed to read cached log length for ${topic}`, error);
return false;
}
}
/**
* Log indices this instance cached for `topic` but failed to publish to the
* inner transport. Readers exclude them when waiting for the log to reach
* them: those frames are replayed to late subscribers, but the live
* subscription will never deliver them.
*
* Only the publishing process knows these indices. A reader in another
* process sharing the cache still waits out its pending-frame deadline for
* a frame a remote publisher could not send.
*/
getUndeliveredIndices(topic) {
return this.undeliveredIndices.get(topic) ?? EMPTY_INDICES;
}
/**
* Subscribe to live events on a topic (no replay).
*/
async subscribe(topic, cb, options) {
await this.inner.subscribe(topic, cb, options);
}
/**
* Subscribe to a topic with automatic replay of cached events.
* Delegates to {@link subscribeFromOffset} with offset 0.
*/
async subscribeWithReplay(topic, cb) {
return this.subscribeFromOffset(topic, 0, cb);
}
/**
* Subscribe to a topic with replay starting at a specific index.
*
* The subscriber keeps one cursor, `next`, and every frame it receives is
* reconciled against it:
* - `index < next` — already delivered (transport replay, retry, or a
* duplicate) → dropped.
* - `index === next` — the next frame in the log → delivered.
* - `index > next` — frames arrived out of order. Because a frame is appended
* to the log before it is published, the missing frames are already in the
* log, so they are read back in order and delivered before this one. That
* holds even when the transport replays nothing at all.
*
* One exception to the first rule: a frame numbered `0` whose counter shows
* the log restarted. That means the retained log expired or was cleared and
* a new run segment began numbering at 0; the cursor resyncs and the frame is
* delivered, instead of silently dropping the whole new segment. Nack
* redeliveries (`deliveryAttempt > 1`) also bypass reconciliation, since a
* retry of an already-cursor-advanced frame still has to reach the consumer.
*
* When the log no longer holds the missing range (no shared cache, or the
* TTL lapsed) there is nothing to replay; the cursor resynchronises to the
* frame in hand so live delivery continues.
*
* @param topic - The topic to subscribe to
* @param offset - Start replaying from this index (0-based)
* @param cb - Callback invoked for each event
*/
async subscribeFromOffset(topic, offset, cb) {
const cacheKey = this.getCacheKey(topic);
let next = offset;
const readFirstId = async () => (await this.cache.listFromTo(cacheKey, 0, 0))[0]?.id;
const logLength = offset > 0 ? await this.cache.get(this.getCounterKey(topic)).catch(() => void 0) : void 0;
let attachLogEnd;
let firstId = typeof logLength === "number" ? await readFirstId().catch(() => {
attachLogEnd = logLength;
}) : void 0;
let closed = false;
let warnedUnnumbered = false;
let pending = null;
let deferred = false;
let attaching = true;
const emit = (event, ack, nack) => {
if (typeof event.index === "number") next = event.index + 1;
return cb(event, ack, nack);
};
/** Deliver everything the log holds between the cursor and `target`. */
const backfill = async (target) => {
if (target <= next) return;
const entries = await this.readLogFrom(topic, next);
for (const entry of entries) {
if (closed) return;
const seq = entry.index;
if (typeof seq !== "number" || seq < next) continue;
if (seq >= target) return;
await emit(entry);
}
};
const reconcile = (event, ack, nack) => {
if (event.deliveryAttempt !== void 0 && event.deliveryAttempt > 1) return cb(event, ack, nack);
const seq = event.index;
if (typeof seq !== "number") {
if (offset > 0 && !warnedUnnumbered) {
warnedUnnumbered = true;
this.logWarn(`[CachingPubSub] Frames on ${topic} are not numbered, so resuming from offset ${offset} cannot replay or skip them by position. Either the publisher failed to append them to the server cache (check for cache errors), or it does not share a server cache with this process (configure one shared by every process, for example RedisServerCache).`);
}
return cb(event, ack, nack);
}
if (seq < next) {
if (seq !== 0) return ack?.();
deferred = true;
return (async () => {
const allocated = await this.cache.get(this.getCounterKey(topic)).catch(() => void 0);
let compareIds = firstId !== void 0;
let currentFirstId;
if (compareIds) try {
currentFirstId = await readFirstId();
} catch {
compareIds = false;
}
if (closed) return ack?.();
if (compareIds ? currentFirstId !== void 0 && currentFirstId !== firstId : typeof allocated === "number" && allocated < Math.min(next, attachLogEnd ?? next)) {
attachLogEnd = void 0;
firstId = compareIds ? currentFirstId : await readFirstId().catch(() => void 0);
this.logWarn(`[CachingPubSub] Log for ${topic} restarted at 0 while the subscriber cursor was at ${next}; the retained log expired or was cleared. Resyncing from the start of the new segment.`);
next = 0;
await backfill(Number.POSITIVE_INFINITY);
if (closed) return ack?.();
if (next > 0) return ack?.();
await emit(event, ack, nack);
return;
}
await ack?.();
})();
}
if (seq > next) {
deferred = true;
return (async () => {
await backfill(seq);
if (closed) return;
if (seq < next) {
await ack?.();
return;
}
next = seq;
await emit(event, ack, nack);
})();
}
return emit(event, ack, nack);
};
const failDelivery = async (error, nack) => {
this.logError(`[CachingPubSub] Subscriber failed for ${topic}`, error);
await nack?.().catch(() => {});
};
/**
* Track a delivery chain so later frames queue behind it.
*
* The clear has to be conditional: a newer chain may already have replaced
* `pending`, and nulling it then would let the next frame reconcile
* concurrently with the in-flight one (two backfills racing on the same
* range, delivering the gap twice or out of order).
*/
const track = (run, nack) => {
const tracked = run.catch((error) => failDelivery(error, nack));
pending = tracked;
tracked.then(() => {
if (pending === tracked) pending = null;
});
return tracked;
};
const wrappedCb = (event, ack, nack) => {
if (closed) return ack?.();
if (pending) return track(pending.then(() => reconcile(event, ack, nack)), nack);
deferred = false;
const result = reconcile(event, ack, nack);
if (!deferred && !(attaching && result instanceof Promise)) return result;
return track(result, nack);
};
this.callbackMap.set(cb, wrappedCb);
try {
await this.inner.subscribe(topic, wrappedCb);
attaching = false;
const inFlight = pending;
let releaseHistory;
const historyGate = new Promise((resolve) => {
releaseHistory = resolve;
});
pending = historyGate;
try {
await inFlight;
const entries = await this.readLogFrom(topic, next);
for (const entry of entries) {
if (closed) return;
const seq = entry.index;
if (typeof seq !== "number" || seq < next) continue;
await emit(entry);
}
} finally {
if (pending === historyGate) pending = null;
releaseHistory();
}
} catch (error) {
closed = true;
this.callbackMap.delete(cb);
await this.inner.unsubscribe(topic, wrappedCb).catch(() => {});
throw error;
}
}
/**
* Unsubscribe from a topic.
*/
async unsubscribe(topic, cb) {
const wrappedCb = this.callbackMap.get(cb) ?? cb;
this.callbackMap.delete(cb);
await this.inner.unsubscribe(topic, wrappedCb);
}
/**
* Get historical events for a topic from cache, from index `offset` on.
*/
async getHistory(topic, offset = 0) {
return this.readLogFrom(topic, offset);
}
/**
* Flush any pending operations on the inner PubSub.
*/
async flush() {
await this.inner.flush();
}
/**
* Expose the inner's {@link LeaseProvider} when it has one, otherwise
* `undefined`. Leasing is a capability of the underlying backend
* (e.g. Redis), not of the caching decorator itself — so rather than
* unconditionally declaring lease methods (which would make
* {@link isLeaseProvider} report `true` even when the inner can't
* coordinate a lock), we surface the inner's capability directly. The
* signals runtime unwraps this so wrapping with caching preserves real
* distributed lease semantics without faking them.
*/
getLeaseProvider() {
return isLeaseProvider(this.inner) ? this.inner : void 0;
}
/**
* Clear cached events for a specific topic (and the index counter), and
* forward the clear to the inner transport.
*
* Call this when a stream completes to free memory. The forward matters for
* persistent inner transports (e.g. Redis Streams): without it, wrapping a
* pubsub in `CachingPubSub` silently turns `clearTopic` into a cache-only
* no-op and the inner stream leaks forever.
*/
async clearTopic(topic) {
this.undeliveredIndices.delete(topic);
try {
await Promise.all([
this.cache.delete(this.getCacheKey(topic)),
this.cache.delete(this.getCounterKey(topic)),
this.inner.clearTopic(topic)
]);
} catch (error) {
this.logError(`[CachingPubSub] Failed to clear topic ${topic}`, error);
}
}
/** Forward run trims to the inner transport; the per-process cache is left to its own bounds. */
async trimTopic(topic, options) {
try {
await this.inner.trimTopic(topic, options);
} catch (error) {
this.logError(`[CachingPubSub] Failed to trim topic ${topic}`, error);
}
}
/**
* Get the inner PubSub instance.
* Useful for accessing implementation-specific methods like close().
*/
getInner() {
return this.inner;
}
/** The cache holding this bus's retained frames. */
getCache() {
return this.cache;
}
};
/**
* Factory function to wrap a PubSub with caching capabilities.
*
* @example
* ```typescript
* import { withCaching, EventEmitterPubSub } from '@mastra/core/events';
* import { InMemoryServerCache } from '@mastra/core/cache';
*
* const cache = new InMemoryServerCache();
* const pubsub = withCaching(new EventEmitterPubSub(), cache);
* ```
*/
function withCaching(pubsub, cache, options) {
return new CachingPubSub(pubsub, cache, options);
}
// src/events/publisher-queue-limit-error.ts
var PublisherQueueLimitError = class extends Error {
waitForCapacity;
constructor(message = "UnixSocketPubSub publisher queue limit exceeded", waitForCapacity) {
super(message);
this.waitForCapacity = waitForCapacity;
}
};
// src/stream/aisdk/v5/output-helpers.ts
var DefaultStepResult = class {
content;
finishReason;
usage;
warnings;
request;
response;
providerMetadata;
/** Tripwire data if this step was rejected by a processor */
tripwire;
constructor({ content, finishReason, usage, warnings, request, response, providerMetadata, tripwire }) {
this.content = content;
this.finishReason = finishReason;
this.usage = usage;
this.warnings = warnings;
this.request = request;
this.response = response;
this.providerMetadata = providerMetadata;
this.tripwire = tripwire;
}
get text() {
if (this.tripwire) return "";
return this.content.filter((part) => part.type === "text").map((part) => part.text).join("");
}
get reasoning() {
return this.content.filter((part) => part.type === "reasoning");
}
get reasoningText() {
return this.reasoning.length === 0 ? void 0 : this.reasoning.map((part) => part.text).join("");
}
get files() {
return this.content.filter((part) => part.type === "file").map((part) => part.file);
}
get sources() {
return this.content.filter((part) => part.type === "source");
}
get toolCalls() {
return this.content.filter((part) => part.type === "tool-call");
}
get staticToolCalls() {
return this.toolCalls.filter((toolCall) => toolCall.dynamic === false);
}
get dynamicToolCalls() {
return this.toolCalls.filter((toolCall) => toolCall.dynamic === true);
}
get toolResults() {
return this.content.filter((part) => part.type === "tool-result");
}
get staticToolResults() {
return this.toolResults.filter((toolResult) => toolResult.dynamic === false);
}
get dynamicToolResults() {
return this.toolResults.filter((toolResult) => toolResult.dynamic === true);
}
};
Object.defineProperty(exports, "CachingPubSub", {
enumerable: true,
get: function() {
return CachingPubSub;
}
});
Object.defineProperty(exports, "DefaultStepResult", {
enumerable: true,
get: function() {
return DefaultStepResult;
}
});
Object.defineProperty(exports, "EventEmitterPubSub", {
enumerable: true,
get: function() {
return EventEmitterPubSub;
}
});
Object.defineProperty(exports, "NoopLeaseProvider", {
enumerable: true,
get: function() {
return NoopLeaseProvider;
}
});
Object.defineProperty(exports, "PubSub", {
enumerable: true,
get: function() {
return PubSub;
}
});
Object.defineProperty(exports, "PublisherQueueLimitError", {
enumerable: true,
get: function() {
return PublisherQueueLimitError;
}
});
Object.defineProperty(exports, "RUN_LOCAL_TOPIC_PREFIXES", {
enumerable: true,
get: function() {
return RUN_LOCAL_TOPIC_PREFIXES;
}
});
Object.defineProperty(exports, "RUN_LOG_TTL_MS", {
enumerable: true,
get: function() {
return RUN_LOG_TTL_MS;
}
});
Object.defineProperty(exports, "cachedLogTtlMs", {
enumerable: true,
get: function() {
return cachedLogTtlMs;
}
});
Object.defineProperty(exports, "isLeaseProvider", {
enumerable: true,
get: function() {
return isLeaseProvider;
}
});
Object.defineProperty(exports, "isRunLocalTopic", {
enumerable: true,
get: function() {
return isRunLocalTopic;
}
});
Object.defineProperty(exports, "rehydrateError", {
enumerable: true,
get: function() {
return rehydrateError;
}
});
Object.defineProperty(exports, "serializeError", {
enumerable: true,
get: function() {
return serializeError;
}
});
Object.defineProperty(exports, "slimNestedAgentChunks", {
enumerable: true,
get: function() {
return slimNestedAgentChunks;
}
});
Object.defineProperty(exports, "slimProgressChunk", {
enumerable: true,
get: function() {
return slimProgressChunk;
}
});
Object.defineProperty(exports, "stripModelSnapshots", {
enumerable: true,
get: function() {
return stripModelSnapshots;
}
});
Object.defineProperty(exports, "toCachedLogFrame", {
enumerable: true,
get: function() {
return toCachedLogFrame;
}
});
Object.defineProperty(exports, "withAck", {
enumerable: true,
get: function() {
return withAck;
}
});
Object.defineProperty(exports, "withCaching", {
enumerable: true,
get: function() {
return withCaching;
}
});
//# sourceMappingURL=output-helpers-JL-HeCbT.cjs.map