@mastra/client-js 0.0.0-error-handler-fix-20251020202607 → 0.0.0-esbuild-bundle-worker-20260807182016

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +9405 -3
  2. package/LICENSE.md +15 -0
  3. package/README.md +11 -13
  4. package/dist/_types/@ai-sdk_provider/dist/index.d.ts +1587 -0
  5. package/dist/_types/@ai-sdk_provider-utils/dist/index.d.ts +379 -0
  6. package/dist/_types/@ai-sdk_ui-utils/dist/index.d.ts +820 -0
  7. package/dist/agent-learning.d.ts +182 -0
  8. package/dist/agent-learning.d.ts.map +1 -0
  9. package/dist/client.d.ts +767 -80
  10. package/dist/client.d.ts.map +1 -1
  11. package/dist/docs/SKILL.md +52 -0
  12. package/dist/docs/assets/SOURCE_MAP.json +6 -0
  13. package/dist/docs/references/docs-agents-a2a.md +340 -0
  14. package/dist/docs/references/docs-editor-overview.md +349 -0
  15. package/dist/docs/references/docs-long-running-agents-schedules.md +201 -0
  16. package/dist/docs/references/docs-long-running-agents-signals.md +426 -0
  17. package/dist/docs/references/docs-server-auth-auth0.md +262 -0
  18. package/dist/docs/references/docs-server-auth-clerk.md +154 -0
  19. package/dist/docs/references/docs-server-auth-firebase.md +294 -0
  20. package/dist/docs/references/docs-server-auth-jwt.md +116 -0
  21. package/dist/docs/references/docs-server-auth-supabase.md +139 -0
  22. package/dist/docs/references/docs-server-auth-workos.md +271 -0
  23. package/dist/docs/references/docs-server-mastra-client.md +323 -0
  24. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-messages.md +97 -0
  25. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-stream.md +282 -0
  26. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v4-messages.md +81 -0
  27. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v5-messages.md +78 -0
  28. package/dist/docs/references/reference-client-js-agents.md +959 -0
  29. package/dist/docs/references/reference-client-js-conversations.md +137 -0
  30. package/dist/docs/references/reference-client-js-error-handling.md +18 -0
  31. package/dist/docs/references/reference-client-js-logs.md +26 -0
  32. package/dist/docs/references/reference-client-js-mastra-client.md +96 -0
  33. package/dist/docs/references/reference-client-js-memory.md +237 -0
  34. package/dist/docs/references/reference-client-js-observability.md +183 -0
  35. package/dist/docs/references/reference-client-js-responses.md +219 -0
  36. package/dist/docs/references/reference-client-js-telemetry.md +22 -0
  37. package/dist/docs/references/reference-client-js-tools.md +46 -0
  38. package/dist/docs/references/reference-client-js-vectors.md +81 -0
  39. package/dist/docs/references/reference-client-js-workflows.md +393 -0
  40. package/dist/docs/references/reference-editor-versioning.md +130 -0
  41. package/dist/index.cjs +7638 -3257
  42. package/dist/index.cjs.map +1 -1
  43. package/dist/index.d.ts +9 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +7606 -3252
  46. package/dist/index.js.map +1 -1
  47. package/dist/observability/collector.d.ts +45 -0
  48. package/dist/observability/collector.d.ts.map +1 -0
  49. package/dist/observability/index.d.ts +14 -0
  50. package/dist/observability/index.d.ts.map +1 -0
  51. package/dist/observability/types.d.ts +27 -0
  52. package/dist/observability/types.d.ts.map +1 -0
  53. package/dist/resources/a2a.d.ts +80 -11
  54. package/dist/resources/a2a.d.ts.map +1 -1
  55. package/dist/resources/agent-builder.d.ts +57 -72
  56. package/dist/resources/agent-builder.d.ts.map +1 -1
  57. package/dist/resources/agent-controller.d.ts +589 -0
  58. package/dist/resources/agent-controller.d.ts.map +1 -0
  59. package/dist/resources/agent.d.ts +368 -59
  60. package/dist/resources/agent.d.ts.map +1 -1
  61. package/dist/resources/base.d.ts +2 -1
  62. package/dist/resources/base.d.ts.map +1 -1
  63. package/dist/resources/channels.d.ts +63 -0
  64. package/dist/resources/channels.d.ts.map +1 -0
  65. package/dist/resources/conversations.d.ts +15 -0
  66. package/dist/resources/conversations.d.ts.map +1 -0
  67. package/dist/resources/index.d.ts +14 -0
  68. package/dist/resources/index.d.ts.map +1 -1
  69. package/dist/resources/mcp-tool.d.ts +5 -5
  70. package/dist/resources/mcp-tool.d.ts.map +1 -1
  71. package/dist/resources/memory-thread.d.ts +51 -16
  72. package/dist/resources/memory-thread.d.ts.map +1 -1
  73. package/dist/resources/observability.d.ts +222 -19
  74. package/dist/resources/observability.d.ts.map +1 -1
  75. package/dist/resources/processor-provider.d.ts +15 -0
  76. package/dist/resources/processor-provider.d.ts.map +1 -0
  77. package/dist/resources/processor.d.ts +20 -0
  78. package/dist/resources/processor.d.ts.map +1 -0
  79. package/dist/resources/responses.d.ts +22 -0
  80. package/dist/resources/responses.d.ts.map +1 -0
  81. package/dist/resources/run.d.ts +256 -0
  82. package/dist/resources/run.d.ts.map +1 -0
  83. package/dist/resources/stored-agent.d.ts +112 -0
  84. package/dist/resources/stored-agent.d.ts.map +1 -0
  85. package/dist/resources/stored-mcp-client.d.ts +30 -0
  86. package/dist/resources/stored-mcp-client.d.ts.map +1 -0
  87. package/dist/resources/stored-prompt-block.d.ts +83 -0
  88. package/dist/resources/stored-prompt-block.d.ts.map +1 -0
  89. package/dist/resources/stored-scorer.d.ts +83 -0
  90. package/dist/resources/stored-scorer.d.ts.map +1 -0
  91. package/dist/resources/stored-skill.d.ts +40 -0
  92. package/dist/resources/stored-skill.d.ts.map +1 -0
  93. package/dist/resources/stored-workflow.d.ts +18 -0
  94. package/dist/resources/stored-workflow.d.ts.map +1 -0
  95. package/dist/resources/tool-provider.d.ts +80 -0
  96. package/dist/resources/tool-provider.d.ts.map +1 -0
  97. package/dist/resources/tool.d.ts +4 -4
  98. package/dist/resources/vector.d.ts +9 -9
  99. package/dist/resources/vector.d.ts.map +1 -1
  100. package/dist/resources/workflow.d.ts +32 -231
  101. package/dist/resources/workflow.d.ts.map +1 -1
  102. package/dist/resources/workspace.d.ts +129 -0
  103. package/dist/resources/workspace.d.ts.map +1 -0
  104. package/dist/route-types.generated.d.ts +18087 -0
  105. package/dist/route-types.generated.d.ts.map +1 -0
  106. package/dist/tools.d.ts +3 -6
  107. package/dist/tools.d.ts.map +1 -1
  108. package/dist/types.d.ts +2740 -197
  109. package/dist/types.d.ts.map +1 -1
  110. package/dist/utils/client-tool-model-output.d.ts +16 -0
  111. package/dist/utils/client-tool-model-output.d.ts.map +1 -0
  112. package/dist/utils/index.d.ts +65 -4
  113. package/dist/utils/index.d.ts.map +1 -1
  114. package/dist/utils/process-a2a-stream.d.ts +4 -0
  115. package/dist/utils/process-a2a-stream.d.ts.map +1 -0
  116. package/dist/utils/process-client-tools.d.ts.map +1 -1
  117. package/dist/utils/process-mastra-stream.d.ts +8 -7
  118. package/dist/utils/process-mastra-stream.d.ts.map +1 -1
  119. package/dist/utils/stream-transforms.d.ts +9 -0
  120. package/dist/utils/stream-transforms.d.ts.map +1 -0
  121. package/dist/utils/verify-agent-card-signature.d.ts +21 -0
  122. package/dist/utils/verify-agent-card-signature.d.ts.map +1 -0
  123. package/dist/utils/zod-to-json-schema.d.ts +11 -2
  124. package/dist/utils/zod-to-json-schema.d.ts.map +1 -1
  125. package/package.json +26 -19
  126. package/dist/resources/network-memory-thread.d.ts +0 -47
  127. package/dist/resources/network-memory-thread.d.ts.map +0 -1
@@ -0,0 +1,426 @@
1
+ > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
2
+
3
+ # Signals
4
+
5
+ **Added in:** `@mastra/core@1.39.0`
6
+
7
+ > **Beta:** This feature is in beta. Breaking changes may occur without a major version bump until the API is stable.
8
+
9
+ Signals are a way to interact with an agent through a thread. Instead of starting every interaction with `agent.stream()`, subscribe to a thread and send messages or signals. Mastra either wakes the agent when the thread is idle or drops input into the running agent loop, or alternatively queues input for the next turn.
10
+
11
+ Use message APIs for user-authored input. Use `sendSignal()` for lower-level system context, such as background task notifications, policy reminders, or processor-generated context.
12
+
13
+ > **📹 Watch:** Watch [Mastra signals overview](https://www.youtube.com/watch?v=7It2y89TVP4) to see how signals wake and steer long-running agents.
14
+
15
+ ## When to use signals
16
+
17
+ Use signals when an agent thread needs new input or context outside the original `stream()` call. Signals are useful when users send follow-up messages while a run is active, when background systems need to add context to a thread, or when external events should wake, update, or notify the agent.
18
+
19
+ Use `sendMessage()` and `queueMessage()` for user-authored input. Use `sendSignal()` for lower-level system context. Use `sendStateSignal()` for durable state lanes, and use `sendNotificationSignal()` when an external event should create a durable notification inbox record.
20
+
21
+ ## Quickstart
22
+
23
+ Create an agent, subscribe to a thread, then send a message to that thread. The subscription receives the active stream when the message wakes the agent or enters a running loop.
24
+
25
+ ```typescript
26
+ import { Agent } from '@mastra/core/agent'
27
+
28
+ const agent = new Agent({
29
+ id: 'support-agent',
30
+ name: 'Support Agent',
31
+ instructions: 'Help the user compare options.',
32
+ model: 'openai/gpt-5.6-sol',
33
+ })
34
+
35
+ const thread = {
36
+ resourceId: 'user_123',
37
+ threadId: 'thread_456',
38
+ }
39
+
40
+ const subscription = await agent.subscribeToThread(thread)
41
+
42
+ await agent.sendMessage('Compare that with the previous option.', thread)
43
+
44
+ for await (const chunk of subscription.stream) {
45
+ console.log(chunk)
46
+ }
47
+ ```
48
+
49
+ When the thread has a running agent stream, `sendMessage()` becomes new input inside that agent loop. When the thread is idle, Mastra starts a stream with the message as the first input.
50
+
51
+ ## Message input
52
+
53
+ ### Send a message now
54
+
55
+ Use `sendMessage()` when the user expects the active agent to see the message immediately.
56
+
57
+ ```typescript
58
+ agent.sendMessage(
59
+ {
60
+ contents: 'Use the latest customer note too.',
61
+ attributes: { name: 'Jane', sentFrom: 'slack' },
62
+ },
63
+ {
64
+ resourceId: 'user_123',
65
+ threadId: 'thread_456',
66
+ },
67
+ )
68
+ ```
69
+
70
+ The model receives attributed messages as XML-wrapped user input:
71
+
72
+ ```xml
73
+ <user name="Jane" sentFrom="slack">Use the latest customer note too.</user>
74
+ ```
75
+
76
+ Messages without attributes are sent as plain user input.
77
+
78
+ ### Queue a message for the next turn
79
+
80
+ Use `queueMessage()` when a user sends a follow-up but the active model call should finish first. Mastra waits for the active run to complete, then starts a new run on the same thread.
81
+
82
+ ```typescript
83
+ agent.queueMessage('Also check whether the tests need updates.', {
84
+ resourceId: 'user_123',
85
+ threadId: 'thread_456',
86
+ })
87
+ ```
88
+
89
+ When the thread is idle, `queueMessage()` starts a run immediately. When the thread is active, it preserves turn order by starting a new run after the active run completes.
90
+
91
+ ## Signal context
92
+
93
+ ### Control low-level signal behavior
94
+
95
+ Use `sendSignal()` when you need to send system-generated context instead of user-authored input. For external events, use `type: 'notification'`. By default, Mastra delivers signals to active runs and wakes idle threads. Use `ifActive.behavior` and `ifIdle.behavior` to change that behavior.
96
+
97
+ ```typescript
98
+ const result = agent.sendSignal(
99
+ {
100
+ type: 'notification',
101
+ contents: 'GitHub CI failed on PR #123: 3 tests failed.',
102
+ },
103
+ {
104
+ resourceId: 'user_123',
105
+ threadId: 'thread_456',
106
+ ifIdle: {
107
+ behavior: 'persist',
108
+ },
109
+ },
110
+ )
111
+
112
+ await result.persisted
113
+ ```
114
+
115
+ Pass `ifIdle.streamOptions` when the idle wake-up stream needs options such as model settings, tools, or runtime context. Visit [`Agent.sendSignal()` reference](https://mastra.ai/reference/agents/agent) for `ifActive`, `ifIdle`, branch attributes, and `streamOptions`.
116
+
117
+ ### Send notification context
118
+
119
+ Signals have a semantic `type` and an LLM-facing `tagName`. Use `type` to describe the signal category. Use `tagName` to control the XML tag the model sees.
120
+
121
+ For external events, use `type: 'notification'`. Reactive signals are reserved for processor- or runtime-generated context, such as policy guidance, background task results, and auto-loaded instructions.
122
+
123
+ ```typescript
124
+ agent.sendSignal(
125
+ {
126
+ type: 'notification',
127
+ contents: 'PR #123 has a new review comment from User X about the API surface.',
128
+ attributes: {
129
+ source: 'github',
130
+ pr: '123',
131
+ },
132
+ },
133
+ {
134
+ resourceId: 'user_123',
135
+ threadId: 'thread_456',
136
+ },
137
+ )
138
+ ```
139
+
140
+ The model receives the signal as context like this:
141
+
142
+ ```xml
143
+ <notification source="github" pr="123">PR #123 has a new review comment from User X about the API surface.</notification>
144
+ ```
145
+
146
+ Use XML-safe `tagName` and attribute names. They can contain letters, numbers, shows, periods, and hyphens. They must start with a letter or underscore.
147
+
148
+ #### Storage support
149
+
150
+ Notification inbox storage is available in the storage adapters that support richer memory and signal workflows: [libSQL](https://mastra.ai/reference/storage/libsql), [PostgreSQL](https://mastra.ai/reference/storage/postgresql), and [MongoDB](https://mastra.ai/reference/storage/mongodb). These adapters expose notification records through `getStore('notifications')`.
151
+
152
+ ### Send processor context
153
+
154
+ Processors can send reactive signals during a run. A processor should inspect the chat history, react to a specific trigger, and avoid sending the same context more than once.
155
+
156
+ The following example demonstrates a processor that injects `AGENTS.md` instructions after a tool call reads an `AGENTS.md` file.
157
+
158
+ ```typescript
159
+ import type { Processor, ProcessInputStepArgs } from '@mastra/core/processors'
160
+
161
+ export const agentsMdReminderProcessor: Processor = {
162
+ id: 'agents-md-reminder',
163
+ async processInputStep({ messageList, sendSignal }: ProcessInputStepArgs) {
164
+ const messages = messageList.get.all.db()
165
+ const agentsMdPath = findAgentsMdPathFromToolCalls(messages)
166
+
167
+ if (!agentsMdPath || hasAlreadySentAgentsMdReminder(messages, agentsMdPath)) {
168
+ return messageList
169
+ }
170
+
171
+ await sendSignal?.({
172
+ type: 'reactive',
173
+ contents: readAgentsMdInstructions(agentsMdPath),
174
+ attributes: {
175
+ type: 'dynamic-agents-md',
176
+ path: agentsMdPath,
177
+ },
178
+ metadata: {
179
+ path: agentsMdPath,
180
+ },
181
+ })
182
+
183
+ return messageList
184
+ },
185
+ }
186
+ ```
187
+
188
+ Reactive signals default to `tagName: 'system-reminder'`, so the model receives this context as
189
+
190
+ ```xml
191
+ <system-reminder type="dynamic-agents-md" path="packages/ui/AGENTS.md">
192
+ $agentsMdFileContents
193
+ </system-reminder>
194
+ ```
195
+
196
+ Awaiting `sendSignal()` preserves stream echo ordering when a subscribed thread is active.
197
+
198
+ ### Conditional attributes
199
+
200
+ Use `ifActive.attributes` and `ifIdle.attributes` to tag input with context that depends on whether the agent is active or idle at delivery time. Top-level `attributes` always apply, and Mastra merges the selected branch's `attributes` into them when the input is accepted. Visit [`Agent.sendMessage()` reference](https://mastra.ai/reference/agents/agent) and [`Agent.sendSignal()` reference](https://mastra.ai/reference/agents/agent) for branch-specific attributes.
201
+
202
+ ## State and notification signals
203
+
204
+ ### State signals
205
+
206
+ State signals expose named, thread-scoped context lanes. Use them for durable context that changes over time, such as browser state, editor state, or a background watcher result.
207
+
208
+ Use `sendStateSignal()` when an external producer detects a state change. Each state signal identifies a state lane, a producer-owned cache key, and whether the update is a snapshot or delta.
209
+
210
+ ```typescript
211
+ await agent.sendStateSignal(
212
+ {
213
+ id: 'browser',
214
+ mode: 'snapshot',
215
+ cacheKey: 'browser:https://example.com:3-tabs',
216
+ contents: 'Browser is open. Active tab URL: https://example.com. 3 open tabs.',
217
+ value: {
218
+ activeUrl: 'https://example.com',
219
+ tabCount: 3,
220
+ open: true,
221
+ },
222
+ },
223
+ {
224
+ resourceId: 'user_123',
225
+ threadId: 'thread_456',
226
+ },
227
+ )
228
+ ```
229
+
230
+ When Mastra accepts a state signal, it stores compact tracking metadata on the thread. If a producer sends the same `cacheKey` and mode again while that state is still current, Mastra skips the duplicate.
231
+
232
+ Use `computeStateSignal()` when a processor owns a state lane. Mastra calls it once per model input step after `processInputStep()`. Visit [`Agent.sendStateSignal()` reference](https://mastra.ai/reference/agents/agent) for state signal fields and return values.
233
+
234
+ ```typescript
235
+ import type { ComputeStateSignalArgs, Processor } from '@mastra/core/processors'
236
+
237
+ export const browserStateProcessor: Processor = {
238
+ id: 'browser-state',
239
+ stateId: 'browser',
240
+ computeStateSignal(args: ComputeStateSignalArgs) {
241
+ const browser = readCurrentBrowserState()
242
+ const previous = readMostRecentBrowserState(args.activeStateSignals)
243
+ const changed = previous ? diffBrowserState(previous, browser) : browser
244
+ const shouldRefreshSnapshot = Boolean(args.lastSnapshot && !args.contextWindow.hasSnapshot)
245
+
246
+ if (previous && Object.keys(changed).length === 0 && !shouldRefreshSnapshot) {
247
+ return
248
+ }
249
+
250
+ const isDelta = Boolean(previous && !shouldRefreshSnapshot)
251
+
252
+ return {
253
+ mode: isDelta ? 'delta' : 'snapshot',
254
+ cacheKey: stableBrowserStateCacheKey(browser),
255
+ contents: isDelta ? describeBrowserDelta(changed) : describeBrowserSnapshot(browser),
256
+ value: browser,
257
+ ...(isDelta ? { delta: changed } : {}),
258
+ }
259
+ },
260
+ }
261
+ ```
262
+
263
+ Mastra passes `lastSnapshot` and `deltasSinceSnapshot` into `computeStateSignal()`. It resolves them from message history when the current message list doesn't contain the latest snapshot. The processor still owns merge and diff logic.
264
+
265
+ `contextWindow.hasSnapshot` tells the processor whether the active message window already contains a snapshot for this state lane. If it's `false`, return a fresh `snapshot` so the model sees the current state even after older state messages are trimmed from the context window.
266
+
267
+ The built-in browser context processor emits state under the `browser` id with snapshot and delta modes.
268
+
269
+ ### Notification signals
270
+
271
+ Notification signals represent external events such as GitHub activity, email, Slack mentions, CI status, incidents, recordings, or direct messages. Use `agent.sendNotificationSignal()` when the event should create a durable inbox record.
272
+
273
+ Notification delivery has two phases. During ingress, `agent.sendNotificationSignal()` stores a notification record and resolves the agent's delivery policy. During dispatch, Mastra consumes due records and emits full notification or summary signals.
274
+
275
+ The default delivery policy is priority-aware. Urgent notifications deliver immediately, while lower-priority notifications may be batched into summaries or wait until the thread is idle. Visit [`Agent.sendNotificationSignal()` reference](https://mastra.ai/reference/agents/agent) for notification fields, [`Agent` constructor reference](https://mastra.ai/reference/agents/agent) for `notifications.deliveryPolicy` configuration, and [`createNotificationInboxTool()` reference](https://mastra.ai/reference/signals/create-notification-inbox-tool) for inbox tool actions.
276
+
277
+ ```typescript
278
+ await agent.sendNotificationSignal(
279
+ {
280
+ source: 'github',
281
+ kind: 'ci-status',
282
+ priority: 'high',
283
+ summary: 'CI failed on main: 3 tests failed.',
284
+ payload: {
285
+ repository: 'acme/app',
286
+ branch: 'main',
287
+ },
288
+ dedupeKey: 'github:acme/app:main:ci',
289
+ },
290
+ {
291
+ resourceId: 'user_123',
292
+ threadId: 'thread_456',
293
+ },
294
+ )
295
+ ```
296
+
297
+ The model receives full notifications as context:
298
+
299
+ ```xml
300
+ <notification source="github" type="ci-status" priority="high" status="delivered">CI failed on main: 3 tests failed.</notification>
301
+ ```
302
+
303
+ Notification summaries tell the model that inbox records are waiting:
304
+
305
+ ```xml
306
+ <notification-summary pending="10">github: 3, email: 5, slack: 2</notification-summary>
307
+ ```
308
+
309
+ When Mastra emits a summary, it clears `summaryAt` and sets `summarySignalId` on each summarized record. The records stay pending and readable. When Mastra emits a full notification, it sets `deliveredSignalId` and marks the record `delivered`. If the inbox tool reads a notification first, it can inject the full notification signal and mark the record `seen`, which prevents duplicate full delivery.
310
+
311
+ Configure a delivery policy on the agent when some notifications should wait for a different dispatch window or summary rollup. Enable scheduled dispatch at the Mastra level when deferred notifications and summary rollups should be delivered automatically. Visit [`Agent` constructor reference](https://mastra.ai/reference/agents/agent) for `notifications.deliveryPolicy` and [`Mastra` class reference](https://mastra.ai/reference/core/mastra-class) for runtime notification dispatch configuration.
312
+
313
+ #### Notification inbox tool
314
+
315
+ Use `createNotificationInboxTool()` to give agents one tool for inbox actions instead of many CRUD tools. Use `read` after a `<notification-summary>` signal when the agent needs the full records behind the summary. The notification contents are delivered as signals, not as normal tool output. Visit [`createNotificationInboxTool()` reference](https://mastra.ai/reference/signals/create-notification-inbox-tool) for the setup example, input schema, and action behavior.
316
+
317
+ `sendNotificationSignal()` requires a storage domain with `notifications` support. Use `sendSignal({ type: 'notification' })` only for lower-level notification-shaped context that should bypass inbox storage.
318
+
319
+ ## Distributed and serverless deployments
320
+
321
+ Signals coordinate runs through a pub/sub backend. When a signal arrives on a backend that implements `LeaseProvider`, Mastra acquires a lease on the target thread so a single process owns the conversation at a time, then either wakes the agent or routes the input into the running loop. Backends without leasing fall back to a no-op that always grants ownership, which is fine in a single process but not across instances.
322
+
323
+ The default in-memory pub/sub can't cross instance boundaries. On serverless platforms like Vercel, or any multi-instance deployment, a follow-up signal can be routed to a different instance than the one running the agent.
324
+
325
+ Without a shared pub/sub, that instance can't reach the active run and starts its own, leaving the original run untouched and the thread processed twice.
326
+
327
+ Configure a shared pub/sub backed by Redis Streams on the `Mastra` instance so leases and signals coordinate across instances:
328
+
329
+ ```typescript
330
+ import { Mastra } from '@mastra/core'
331
+ import { RedisStreamsPubSub } from '@mastra/redis-streams'
332
+
333
+ export const mastra = new Mastra({
334
+ agents: { agent },
335
+ pubsub: new RedisStreamsPubSub({
336
+ url: process.env.REDIS_URL,
337
+ keyPrefix: 'mastra:my-app',
338
+ }),
339
+ })
340
+ ```
341
+
342
+ `RedisStreamsPubSub` implements both the event delivery contract and distributed leasing, so a single backend handles cross-instance signal delivery and lease ownership. Vercel's managed Redis integration and Upstash Redis both work well. For more on when a distributed pub/sub is needed, see the [PubSub guide](https://mastra.ai/docs/server/pubsub) and the [`RedisStreamsPubSub` reference](https://mastra.ai/reference/pubsub/redis-streams).
343
+
344
+ ## Compatibility and APIs
345
+
346
+ ### Compatibility
347
+
348
+ Mastra still accepts legacy signal payloads such as `type: 'user-message'` and `type: 'system-reminder'`. It normalizes them internally to the new category and tag shape:
349
+
350
+ - `type: 'user-message'`: Normalizes to `type: 'user'` and `tagName: 'user'`
351
+ - `type: 'system-reminder'`: Normalizes to `type: 'reactive'` and `tagName: 'system-reminder'`
352
+
353
+ Existing stored signal rows and older clients continue to load through the compatibility layer. New clients call the message routes when the server supports them; React's thread signal path falls back to the legacy `/signals` route when it detects an older server. Visit [Agent signals reference](https://mastra.ai/reference/agents/agent) for the full message, signal, and subscription types.
354
+
355
+ ### Approve tool calls
356
+
357
+ When a subscribed run pauses for tool approval, approve or decline the tool call with the subscription-native methods. The resumed chunks arrive through the existing thread subscription. Visit [`client.getAgent().sendToolApproval()` reference](https://mastra.ai/reference/client-js/agents) and [server agent routes](https://mastra.ai/reference/server/routes) for request and response shapes.
358
+
359
+ ### Use HTTP routes
360
+
361
+ If you call Mastra over HTTP directly, use `POST /api/agents/:agentId/send-message` for immediate messages and `POST /api/agents/:agentId/queue-message` for next-turn messages. For subscription-native tool approval, use `POST /api/agents/:agentId/send-tool-approval`. See [Server routes reference](https://mastra.ai/reference/server/routes) for request and response schemas.
362
+
363
+ ### Use the client SDK
364
+
365
+ The JavaScript client exposes thread signal APIs.
366
+
367
+ Use `subscribeToThread()` before sending thread input so the client can render the stream that receives the input or wakes in response to it.
368
+
369
+ ```typescript
370
+ const agent = client.getAgent('supportAgent')
371
+
372
+ const subscription = await agent.subscribeToThread({
373
+ resourceId: 'user_123',
374
+ threadId: 'thread_456',
375
+ })
376
+
377
+ await agent.sendMessage({
378
+ message: 'Show the shorter version.',
379
+ resourceId: 'user_123',
380
+ threadId: 'thread_456',
381
+ })
382
+
383
+ await subscription.processDataStream({
384
+ onChunk: chunk => {
385
+ console.log(chunk)
386
+ },
387
+ reconnect: true,
388
+ })
389
+ ```
390
+
391
+ Use `reconnect: true` for long-lived subscriptions. Visit [`client.getAgent().subscribeToThread()` reference](https://mastra.ai/reference/client-js/agents) for reconnect options.
392
+
393
+ ### Keep custom SSE subscriptions alive
394
+
395
+ If you expose your own Server-Sent Events (SSE) endpoint for thread subscriptions, send periodic heartbeat frames while the stream is idle. This keeps browsers, proxies, and load balancers from closing the connection before the next signal or model chunk arrives.
396
+
397
+ The following example sends an SSE comment every 25 seconds:
398
+
399
+ ```typescript
400
+ const heartbeat = setInterval(() => {
401
+ controller.enqueue(encoder.encode(': keep-alive\n\n'))
402
+ }, 25_000)
403
+
404
+ request.signal.addEventListener('abort', () => {
405
+ clearInterval(heartbeat)
406
+ })
407
+ ```
408
+
409
+ Use heartbeats together with client-side reconnect logic. Heartbeats reduce idle disconnects, while reconnects recover when the network or runtime still closes the stream.
410
+
411
+ ## Related
412
+
413
+ - [`Agent.sendMessage()`](https://mastra.ai/reference/agents/agent)
414
+ - [`Agent.queueMessage()`](https://mastra.ai/reference/agents/agent)
415
+ - [`Agent.sendSignal()`](https://mastra.ai/reference/agents/agent)
416
+ - [`Agent.sendStateSignal()`](https://mastra.ai/reference/agents/agent)
417
+ - [`Agent.subscribeToThread()`](https://mastra.ai/reference/agents/agent)
418
+ - [`createNotificationInboxTool()`](https://mastra.ai/reference/signals/create-notification-inbox-tool)
419
+ - [`client.getAgent().sendMessage()`](https://mastra.ai/reference/client-js/agents)
420
+ - [`client.getAgent().queueMessage()`](https://mastra.ai/reference/client-js/agents)
421
+ - [`client.getAgent().sendSignal()`](https://mastra.ai/reference/client-js/agents)
422
+ - [Server agent routes](https://mastra.ai/reference/server/routes)
423
+ - [`client.getAgent().subscribeToThread()`](https://mastra.ai/reference/client-js/agents)
424
+ - [`client.getAgent().sendToolApproval()`](https://mastra.ai/reference/client-js/agents)
425
+ - [`RedisStreamsPubSub`](https://mastra.ai/reference/pubsub/redis-streams)
426
+ - 📹 [Mastra signals workshop](https://www.youtube.com/watch?v=KLg6uFKz9aw\&t=3020s)
@@ -0,0 +1,262 @@
1
+ > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
2
+
3
+ # Auth0
4
+
5
+ The `@mastra/auth-auth0` package provides authentication for Mastra using Auth0. It verifies incoming requests using Auth0-issued JWT tokens and integrates with the Mastra server using the `auth` option.
6
+
7
+ ## Prerequisites
8
+
9
+ This example uses Auth0 authentication. Make sure to:
10
+
11
+ 1. Create an Auth0 account at [auth0.com](https://auth0.com/)
12
+ 2. Set up an Application in your Auth0 Dashboard
13
+ 3. Configure an API in your Auth0 Dashboard with an identifier (audience)
14
+ 4. Configure your application's allowed callback URLs, web origins, and logout URLs
15
+
16
+ ```env
17
+ AUTH0_DOMAIN=your-tenant.auth0.com
18
+ AUTH0_AUDIENCE=your-api-identifier
19
+ ```
20
+
21
+ > **Note:** You can find your domain in the Auth0 Dashboard under Applications > Settings. The audience is the identifier of your API configured in Auth0 Dashboard > APIs.
22
+ >
23
+ > For detailed setup instructions, refer to the [Auth0 quickstarts](https://auth0.com/docs/quickstarts) for your specific platform.
24
+
25
+ ## Installation
26
+
27
+ Before you can use the `MastraAuthAuth0` class you have to install the `@mastra/auth-auth0` package.
28
+
29
+ **npm**:
30
+
31
+ ```bash
32
+ npm install @mastra/auth-auth0@latest
33
+ ```
34
+
35
+ **pnpm**:
36
+
37
+ ```bash
38
+ pnpm add @mastra/auth-auth0@latest
39
+ ```
40
+
41
+ **Yarn**:
42
+
43
+ ```bash
44
+ yarn add @mastra/auth-auth0@latest
45
+ ```
46
+
47
+ **Bun**:
48
+
49
+ ```bash
50
+ bun add @mastra/auth-auth0@latest
51
+ ```
52
+
53
+ ## Usage examples
54
+
55
+ ### Basic usage with environment variables
56
+
57
+ ```typescript
58
+ import { Mastra } from '@mastra/core'
59
+ import { MastraAuthAuth0 } from '@mastra/auth-auth0'
60
+
61
+ export const mastra = new Mastra({
62
+ server: {
63
+ auth: new MastraAuthAuth0(),
64
+ },
65
+ })
66
+ ```
67
+
68
+ ### Custom configuration
69
+
70
+ ```typescript
71
+ import { Mastra } from '@mastra/core'
72
+ import { MastraAuthAuth0 } from '@mastra/auth-auth0'
73
+
74
+ export const mastra = new Mastra({
75
+ server: {
76
+ auth: new MastraAuthAuth0({
77
+ domain: process.env.AUTH0_DOMAIN,
78
+ audience: process.env.AUTH0_AUDIENCE,
79
+ }),
80
+ },
81
+ })
82
+ ```
83
+
84
+ ## Configuration
85
+
86
+ ### User Authorization
87
+
88
+ By default, `MastraAuthAuth0` allows all authenticated users who have valid Auth0 tokens for the specified audience. The token verification ensures that:
89
+
90
+ 1. The token is properly signed by Auth0
91
+ 2. The token isn't expired
92
+ 3. The token audience matches your configured audience
93
+ 4. The token issuer matches your Auth0 domain
94
+
95
+ To customize user authorization, provide a custom `authorizeUser` function:
96
+
97
+ ```typescript
98
+ import { MastraAuthAuth0 } from '@mastra/auth-auth0'
99
+
100
+ const auth0Provider = new MastraAuthAuth0({
101
+ authorizeUser: async user => {
102
+ // Custom authorization logic
103
+ return user.email?.endsWith('@yourcompany.com') || false
104
+ },
105
+ })
106
+ ```
107
+
108
+ Visit [MastraAuthAuth0](https://mastra.ai/reference/auth/auth0) for all available configuration options.
109
+
110
+ ## Client-side setup
111
+
112
+ When using Auth0 auth, you'll need to set up the Auth0 React SDK, authenticate users, and retrieve their access tokens to pass to your Mastra requests.
113
+
114
+ ### Setting up Auth0 React SDK
115
+
116
+ First, install and configure the Auth0 React SDK in your application:
117
+
118
+ **npm**:
119
+
120
+ ```bash
121
+ npm install @auth0/auth0-react
122
+ ```
123
+
124
+ **pnpm**:
125
+
126
+ ```bash
127
+ pnpm add @auth0/auth0-react
128
+ ```
129
+
130
+ **Yarn**:
131
+
132
+ ```bash
133
+ yarn add @auth0/auth0-react
134
+ ```
135
+
136
+ **Bun**:
137
+
138
+ ```bash
139
+ bun add @auth0/auth0-react
140
+ ```
141
+
142
+ ```typescript
143
+ import React from 'react'
144
+ import { Auth0Provider } from '@auth0/auth0-react'
145
+
146
+ const Auth0ProviderWithHistory = ({ children }) => {
147
+ return (
148
+ <Auth0Provider
149
+ domain={process.env.REACT_APP_AUTH0_DOMAIN}
150
+ clientId={process.env.REACT_APP_AUTH0_CLIENT_ID}
151
+ authorizationParams={{
152
+ redirect_uri: window.location.origin,
153
+ audience: process.env.REACT_APP_AUTH0_AUDIENCE,
154
+ scope: 'read:current_user update:current_user_metadata',
155
+ }}
156
+ >
157
+ {children}
158
+ </Auth0Provider>
159
+ )
160
+ }
161
+
162
+ export default Auth0ProviderWithHistory
163
+ ```
164
+
165
+ ### Retrieving access tokens
166
+
167
+ Use the Auth0 React SDK to authenticate users and retrieve their access tokens:
168
+
169
+ ```typescript
170
+ import { useAuth0 } from '@auth0/auth0-react'
171
+
172
+ export const useAuth0Token = () => {
173
+ const { getAccessTokenSilently } = useAuth0()
174
+
175
+ const getAccessToken = async () => {
176
+ const token = await getAccessTokenSilently()
177
+ return token
178
+ }
179
+
180
+ return { getAccessToken }
181
+ }
182
+ ```
183
+
184
+ > **Note:** Refer to the [Auth0 React SDK documentation](https://auth0.com/docs/libraries/auth0-react) for more authentication methods and configuration options.
185
+
186
+ ## Configuring `MastraClient`
187
+
188
+ When `auth` is enabled, all requests made with `MastraClient` must include a valid Auth0 access token in the `Authorization` header:
189
+
190
+ ```typescript
191
+ import { MastraClient } from '@mastra/client-js'
192
+
193
+ export const createMastraClient = (accessToken: string) => {
194
+ return new MastraClient({
195
+ baseUrl: 'https://<mastra-api-url>',
196
+ headers: {
197
+ Authorization: `Bearer ${accessToken}`,
198
+ },
199
+ })
200
+ }
201
+ ```
202
+
203
+ > **Info:** The access token must be prefixed with `Bearer` in the Authorization header.
204
+ >
205
+ > Visit [Mastra Client SDK](https://mastra.ai/docs/server/mastra-client) for more configuration options.
206
+
207
+ ### Making authenticated requests
208
+
209
+ Once `MastraClient` is configured with the Auth0 access token, you can send authenticated requests:
210
+
211
+ **React**:
212
+
213
+ ```tsx
214
+ import React, { useState } from 'react'
215
+ import { useAuth0 } from '@auth0/auth0-react'
216
+ import { MastraClient } from '@mastra/client-js'
217
+
218
+ export const MastraApiTest = () => {
219
+ const { getAccessTokenSilently } = useAuth0()
220
+ const [result, setResult] = useState(null)
221
+
222
+ const callMastraApi = async () => {
223
+ const token = await getAccessTokenSilently()
224
+
225
+ const mastra = new MastraClient({
226
+ baseUrl: 'http://localhost:4111',
227
+ headers: {
228
+ Authorization: `Bearer ${token}`,
229
+ },
230
+ })
231
+
232
+ const weatherAgent = mastra.getAgent('weatherAgent')
233
+ const response = await weatherAgent.generate("What's the weather like in New York")
234
+
235
+ setResult(response.text)
236
+ }
237
+
238
+ return (
239
+ <div>
240
+ <button onClick={callMastraApi}>Test Mastra API</button>
241
+
242
+ {result && (
243
+ <div className="result">
244
+ <h6>Result:</h6>
245
+ <pre>{result}</pre>
246
+ </div>
247
+ )}
248
+ </div>
249
+ )
250
+ }
251
+ ```
252
+
253
+ **cURL**:
254
+
255
+ ```bash
256
+ curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
257
+ -H "Content-Type: application/json" \
258
+ -H "Authorization: Bearer <your-auth0-access-token>" \
259
+ -d '{
260
+ "messages": "Weather in London"
261
+ }'
262
+ ```