@redplanethq/sdk 0.1.16 → 1.2.1

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 (84) hide show
  1. package/CHANGELOG.md +1657 -0
  2. package/LICENSE.md +30 -0
  3. package/README.md +159 -183
  4. package/dist/__tests__/__fixtures__/network.stream.d.ts +2329 -0
  5. package/dist/__tests__/__fixtures__/network.stream.d.ts.map +1 -0
  6. package/dist/_types/@ai-sdk_provider/dist/index.d.ts +1725 -0
  7. package/dist/_types/@internal_ai-sdk-v5/dist/index.d.ts +10332 -0
  8. package/dist/_types/@internal_ai-v6/dist/index.d.ts +13493 -0
  9. package/dist/chat-route.d.ts +117 -0
  10. package/dist/chat-route.d.ts.map +1 -0
  11. package/dist/chunk-3YJ25IUJ.js +79 -0
  12. package/dist/chunk-3YJ25IUJ.js.map +1 -0
  13. package/dist/chunk-DGUM43GV.js +10 -0
  14. package/dist/chunk-DGUM43GV.js.map +1 -0
  15. package/dist/chunk-HDI4ZP7N.js +79 -0
  16. package/dist/chunk-HDI4ZP7N.js.map +1 -0
  17. package/dist/chunk-HMOX24BQ.js +439 -0
  18. package/dist/chunk-HMOX24BQ.js.map +1 -0
  19. package/dist/chunk-IV3RKEE4.js +439 -0
  20. package/dist/chunk-IV3RKEE4.js.map +1 -0
  21. package/dist/chunk-JEQ2X3Z6.cjs +12 -0
  22. package/dist/chunk-JEQ2X3Z6.cjs.map +1 -0
  23. package/dist/chunk-PEZAMDZJ.cjs +84 -0
  24. package/dist/chunk-PEZAMDZJ.cjs.map +1 -0
  25. package/dist/chunk-VJW66KXQ.cjs +441 -0
  26. package/dist/chunk-VJW66KXQ.cjs.map +1 -0
  27. package/dist/chunk-WFARZCDO.cjs +84 -0
  28. package/dist/chunk-WFARZCDO.cjs.map +1 -0
  29. package/dist/chunk-X72VW7EY.cjs +441 -0
  30. package/dist/chunk-X72VW7EY.cjs.map +1 -0
  31. package/dist/convert-messages.d.ts +90 -0
  32. package/dist/convert-messages.d.ts.map +1 -0
  33. package/dist/convert-streams.d.ts +59 -0
  34. package/dist/convert-streams.d.ts.map +1 -0
  35. package/dist/helpers.d.ts +59 -0
  36. package/dist/helpers.d.ts.map +1 -0
  37. package/dist/index.cjs +14385 -0
  38. package/dist/index.cjs.map +1 -0
  39. package/dist/index.d.ts +14 -1243
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +14289 -804
  42. package/dist/index.js.map +1 -1
  43. package/dist/middleware.d.ts +159 -0
  44. package/dist/middleware.d.ts.map +1 -0
  45. package/dist/network-route.d.ts +84 -0
  46. package/dist/network-route.d.ts.map +1 -0
  47. package/dist/public-types.d.ts +9 -0
  48. package/dist/public-types.d.ts.map +1 -0
  49. package/dist/to-ai-sdk-format.d.ts +16 -0
  50. package/dist/to-ai-sdk-format.d.ts.map +1 -0
  51. package/dist/token-APYSY3BW-CBIBV5F2.js +61 -0
  52. package/dist/token-APYSY3BW-CBIBV5F2.js.map +1 -0
  53. package/dist/token-APYSY3BW-INR55PKP.js +61 -0
  54. package/dist/token-APYSY3BW-INR55PKP.js.map +1 -0
  55. package/dist/token-APYSY3BW-M2K6HVOG.cjs +63 -0
  56. package/dist/token-APYSY3BW-M2K6HVOG.cjs.map +1 -0
  57. package/dist/token-APYSY3BW-Y5VD4L7Z.cjs +63 -0
  58. package/dist/token-APYSY3BW-Y5VD4L7Z.cjs.map +1 -0
  59. package/dist/token-util-RMHT2CPJ-3LCBPXJ6.cjs +10 -0
  60. package/dist/token-util-RMHT2CPJ-3LCBPXJ6.cjs.map +1 -0
  61. package/dist/token-util-RMHT2CPJ-4YTBAZ23.cjs +10 -0
  62. package/dist/token-util-RMHT2CPJ-4YTBAZ23.cjs.map +1 -0
  63. package/dist/token-util-RMHT2CPJ-HCMQIDTV.js +8 -0
  64. package/dist/token-util-RMHT2CPJ-HCMQIDTV.js.map +1 -0
  65. package/dist/token-util-RMHT2CPJ-IOKQM5O3.js +8 -0
  66. package/dist/token-util-RMHT2CPJ-IOKQM5O3.js.map +1 -0
  67. package/dist/transformers.d.ts +315 -0
  68. package/dist/transformers.d.ts.map +1 -0
  69. package/dist/ui.cjs +15 -0
  70. package/dist/ui.cjs.map +1 -0
  71. package/dist/ui.d.ts +2 -0
  72. package/dist/ui.d.ts.map +1 -0
  73. package/dist/ui.js +12 -0
  74. package/dist/ui.js.map +1 -0
  75. package/dist/utils.d.ts +11 -0
  76. package/dist/utils.d.ts.map +1 -0
  77. package/dist/workflow-route.d.ts +93 -0
  78. package/dist/workflow-route.d.ts.map +1 -0
  79. package/package.json +65 -31
  80. package/ui.d.ts +1 -0
  81. package/LICENSE +0 -44
  82. package/dist/index.d.mts +0 -1243
  83. package/dist/index.mjs +0 -822
  84. package/dist/index.mjs.map +0 -1
package/LICENSE.md ADDED
@@ -0,0 +1,30 @@
1
+ Portions of this software are licensed as follows:
2
+
3
+ - All content that resides under any directory named "ee/" within this
4
+ repository, including but not limited to:
5
+ - `packages/core/src/auth/ee/`
6
+ - `packages/server/src/server/auth/ee/`
7
+ is licensed under the license defined in `ee/LICENSE`.
8
+
9
+ - All third-party components incorporated into the Mastra Software are
10
+ licensed under the original license provided by the owner of the
11
+ applicable component.
12
+
13
+ - Content outside of the above-mentioned directories or restrictions is
14
+ available under the "Apache License 2.0" as defined below.
15
+
16
+ # Apache License 2.0
17
+
18
+ Copyright (c) 2025 Kepler Software, Inc.
19
+
20
+ Licensed under the Apache License, Version 2.0 (the "License");
21
+ you may not use this file except in compliance with the License.
22
+ You may obtain a copy of the License at
23
+
24
+ http://www.apache.org/licenses/LICENSE-2.0
25
+
26
+ Unless required by applicable law or agreed to in writing, software
27
+ distributed under the License is distributed on an "AS IS" BASIS,
28
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29
+ See the License for the specific language governing permissions and
30
+ limitations under the License.
package/README.md CHANGED
@@ -1,228 +1,204 @@
1
- # Core SDK
1
+ # @mastra/ai-sdk
2
2
 
3
- The Core SDK provides tools and utilities for building integrations with the Core platform.
3
+ The recommended way of using Mastra and AI SDK together is by installing the `@mastra/ai-sdk` package. `@mastra/ai-sdk` provides custom API routes and utilities for streaming Mastra agents in AI SDK-compatible formats. Including chat, workflow, and network route handlers, along with utilities and exported types for UI integrations.
4
4
 
5
- ## Integration System
6
-
7
- The Core integration system uses a CLI-based approach where each integration is a command-line tool that responds to specific events. This makes integrations portable, testable, and easy to debug.
8
-
9
- ### Integration Event Types
10
-
11
- Each integration CLI handles 5 core event types:
12
-
13
- #### 1. `spec`
14
-
15
- Returns the integration's metadata and configuration.
16
-
17
- **Usage:**
5
+ ## Installation
18
6
 
19
7
  ```bash
20
- my-integration spec
8
+ npm install @mastra/ai-sdk
21
9
  ```
22
10
 
23
- **Returns:** Integration specification including name, description, auth config, etc.
11
+ ## Usage
24
12
 
25
- #### 2. `setup`
13
+ If you want to use dynamic agents you can use a path with `:agentId`.
26
14
 
27
- Processes authentication data and returns tokens/credentials to be saved.
28
-
29
- **Usage:**
30
-
31
- ```bash
32
- my-integration setup --event-body '{"code":"oauth_code","state":"state"}' --integration-definition '{}'
15
+ ```typescript
16
+ import { chatRoute } from '@mastra/ai-sdk';
17
+
18
+ export const mastra = new Mastra({
19
+ server: {
20
+ apiRoutes: [
21
+ chatRoute({
22
+ path: '/chat/:agentId',
23
+ }),
24
+ ],
25
+ },
26
+ });
33
27
  ```
34
28
 
35
- **Returns:** Configuration data (tokens, credentials) to be stored for the account.
36
-
37
- #### 3. `identify`
29
+ Or you can create a fixed route (i.e. `/chat`):
38
30
 
39
- Extracts accountId from webhook data to route webhooks to the correct account.
40
-
41
- **Usage:**
42
-
43
- ```bash
44
- my-integration identify --webhook-data '{"team_id":"T123","event":{}}'
31
+ ```typescript
32
+ import { chatRoute } from '@mastra/ai-sdk';
33
+
34
+ export const mastra = new Mastra({
35
+ server: {
36
+ apiRoutes: [
37
+ chatRoute({
38
+ path: '/chat',
39
+ agent: 'weatherAgent',
40
+ }),
41
+ ],
42
+ },
43
+ });
45
44
  ```
46
45
 
47
- **Returns:** Account identifier for webhook routing.
48
-
49
- #### 4. `process`
50
-
51
- Handles webhook events and returns activity data.
46
+ After defining a dynamic route with `:agentId` you can use the `useChat()` hook like so:
52
47
 
53
- **Usage:**
48
+ ```typescript
49
+ type MyMessage = {};
54
50
 
55
- ```bash
56
- my-integration process --event-data '{"type":"reaction_added","reaction":"=M"}' --config '{"access_token":"token"}'
51
+ const { error, status, sendMessage, messages, regenerate, stop } = useChat<MyMessage>({
52
+ transport: new DefaultChatTransport({
53
+ api: 'http://localhost:4111/chat/weatherAgent',
54
+ }),
55
+ });
57
56
  ```
58
57
 
59
- **Returns:** Activity messages representing user actions.
60
-
61
- #### 5. `sync`
58
+ `chatRoute()` forwards the incoming request `AbortSignal` to `agent.stream()`. If the client disconnects, Mastra aborts the in-flight generation. If you need generation to continue and persist server-side after disconnect, build a custom route around `agent.stream()`, avoid passing the request signal, and call `consumeStream()` on the returned `MastraModelOutput`.
62
59
 
63
- Performs scheduled data synchronization for integrations that don't support webhooks.
60
+ ### Workflow route
64
61
 
65
- **Usage:**
62
+ Stream a workflow in AI SDK-compatible format.
66
63
 
67
- ```bash
68
- my-integration sync --config '{"access_token":"token","last_sync":"2023-01-01T00:00:00Z"}'
64
+ ```typescript
65
+ import { workflowRoute } from '@mastra/ai-sdk';
66
+
67
+ export const mastra = new Mastra({
68
+ server: {
69
+ apiRoutes: [
70
+ workflowRoute({
71
+ path: '/workflow',
72
+ agent: 'weatherAgent',
73
+ }),
74
+ ],
75
+ },
76
+ });
69
77
  ```
70
78
 
71
- **Returns:** Activity messages and updated state for next sync.
79
+ ### Network route
72
80
 
73
- ### Message Types
81
+ Stream agent networks (routing + nested agent/workflow/tool executions) in AI SDK-compatible format.
74
82
 
75
- All integration responses are wrapped in a `Message` object with a `type` field:
76
-
77
- - **`spec`** - Integration metadata and configuration
78
- - **`activity`** - User actions/events from the integration
79
- - **`state`** - Sync state for polling integrations
80
- - **`identifier`** - Account identification for webhook routing
81
-
82
- ### Building an Integration
83
+ ```typescript
84
+ import { networkRoute } from '@mastra/ai-sdk';
85
+
86
+ export const mastra = new Mastra({
87
+ server: {
88
+ apiRoutes: [
89
+ networkRoute({
90
+ path: '/network',
91
+ agent: 'weatherAgent',
92
+ }),
93
+ ],
94
+ },
95
+ });
96
+ ```
83
97
 
84
- 1. **Install the SDK:**
98
+ ## Framework-agnostic handlers
85
99
 
86
- ```bash
87
- npm install @Core/core-sdk
88
- ```
100
+ For use outside the Mastra server (e.g., Next.js App Router, Express), you can use the standalone handler functions directly. These handlers return a compatibility `ReadableStream` that can be passed to AI SDK response helpers like `createUIMessageStreamResponse` and `pipeUIMessageStreamToResponse`:
89
101
 
90
- 2. **Create your integration class:**
102
+ ### handleChatStream
91
103
 
92
104
  ```typescript
93
- import { IntegrationCLI } from '@Core/core-sdk';
94
-
95
- class MyIntegration extends IntegrationCLI {
96
- constructor() {
97
- super('my-integration', '1.0.0');
98
- }
99
-
100
- protected async handleEvent(
101
- eventPayload: IntegrationEventPayload,
102
- ): Promise<any> {
103
- switch (eventPayload.event) {
104
- case 'SETUP':
105
- return this.handleSetup(eventPayload);
106
- case 'PROCESS':
107
- return this.handleProcess(eventPayload);
108
- case 'IDENTIFY':
109
- return this.handleIdentify(eventPayload);
110
- case 'SYNC':
111
- return this.handleSync(eventPayload);
112
- default:
113
- throw new Error(`Unknown event type: ${eventPayload.event}`);
114
- }
115
- }
116
-
117
- protected async getSpec(): Promise<Spec> {
118
- return {
119
- name: 'My Integration',
120
- key: 'my-integration',
121
- description: 'Integration with My Service',
122
- icon: 'https://example.com/icon.png',
123
- auth: {
124
- OAuth2: {
125
- token_url: 'https://api.example.com/oauth/token',
126
- authorization_url: 'https://api.example.com/oauth/authorize',
127
- scopes: ['read', 'write'],
128
- },
129
- },
130
- };
131
- }
132
-
133
- private async handleSetup(
134
- eventPayload: IntegrationEventPayload,
135
- ): Promise<any> {
136
- // Process OAuth response and return tokens to save
137
- const { code } = eventPayload.eventBody;
138
- // Exchange code for tokens...
139
- return {
140
- access_token: 'token',
141
- refresh_token: 'refresh_token',
142
- expires_at: Date.now() + 3600000,
143
- };
144
- }
145
-
146
- private async handleProcess(
147
- eventPayload: IntegrationEventPayload,
148
- ): Promise<any> {
149
- // Handle webhook events
150
- const { eventData } = eventPayload.eventBody;
151
- // Process event and return activity...
152
- return {
153
- type: 'message',
154
- user: 'user123',
155
- content: 'Hello world',
156
- timestamp: new Date(),
157
- };
158
- }
159
-
160
- private async handleIdentify(
161
- eventPayload: IntegrationEventPayload,
162
- ): Promise<any> {
163
- // Extract account ID from webhook
164
- const { team_id } = eventPayload.eventBody;
165
- return { id: team_id };
166
- }
167
-
168
- private async handleSync(
169
- eventPayload: IntegrationEventPayload,
170
- ): Promise<any> {
171
- // Perform scheduled sync
172
- const { config } = eventPayload;
173
- // Fetch data since last sync...
174
- return {
175
- activities: [
176
- /* activity data */
177
- ],
178
- state: { last_sync: new Date().toISOString() },
179
- };
180
- }
105
+ import { handleChatStream } from '@mastra/ai-sdk';
106
+ import { createUIMessageStreamResponse } from 'ai';
107
+ import { mastra } from '@/src/mastra';
108
+
109
+ export async function POST(req: Request) {
110
+ const params = await req.json();
111
+ const stream = await handleChatStream({
112
+ mastra,
113
+ agentId: 'weatherAgent',
114
+ params,
115
+ });
116
+ return createUIMessageStreamResponse({ stream });
181
117
  }
182
-
183
- // CLI entry point
184
- const integration = new MyIntegration();
185
- integration.parse();
186
118
  ```
187
119
 
188
- 3. **Build and package your integration:**
120
+ ### handleWorkflowStream
189
121
 
190
- ```bash
191
- npm run build
192
- npm pack
122
+ ```typescript
123
+ import { handleWorkflowStream } from '@mastra/ai-sdk';
124
+ import { createUIMessageStreamResponse } from 'ai';
125
+ import { mastra } from '@/src/mastra';
126
+
127
+ export async function POST(req: Request) {
128
+ const params = await req.json();
129
+ const stream = await handleWorkflowStream({
130
+ mastra,
131
+ workflowId: 'myWorkflow',
132
+ params,
133
+ });
134
+ return createUIMessageStreamResponse({ stream });
135
+ }
193
136
  ```
194
137
 
195
- ### Integration Development
138
+ ### handleNetworkStream
196
139
 
197
- The `IntegrationCLI` base class provides:
140
+ Pass AI SDK `UIMessage[]` from your installed `ai` version so TypeScript can infer the correct stream overload.
198
141
 
199
- - **Automatic CLI setup** with all required commands
200
- - **JSON input/output handling** for all event types
201
- - **Error handling** with proper exit codes
202
- - **Consistent message formatting** for all responses
142
+ Handlers keep the existing v5/default behavior. If your app is typed against `ai@6`, pass `version: 'v6'`.
203
143
 
204
- ### Testing
144
+ ```typescript
145
+ import { handleNetworkStream } from '@mastra/ai-sdk';
146
+ import { createUIMessageStreamResponse, type UIMessage } from 'ai';
147
+ import { mastra } from '@/src/mastra';
148
+
149
+ export async function POST(req: Request) {
150
+ const params = (await req.json()) as { messages: UIMessage[] };
151
+ const stream = await handleNetworkStream({
152
+ mastra,
153
+ agentId: 'routingAgent',
154
+ version: 'v6',
155
+ params,
156
+ });
157
+ return createUIMessageStreamResponse({ stream });
158
+ }
159
+ ```
205
160
 
206
- Test your integration by running commands directly:
161
+ ## Manual transformation
207
162
 
208
- ```bash
209
- # Test spec
210
- node dist/index.js spec
163
+ If you have a raw Mastra `stream`, you can manually transform it to AI SDK UI message parts:
211
164
 
212
- # Test setup
213
- node dist/index.js setup --event-body '{"code":"test"}' --integration-definition '{}'
165
+ Use `toAISdkStream` for both versions. If your app is typed against `ai@6`, pass `version: 'v6'`.
214
166
 
215
- # Test webhook processing
216
- node dist/index.js process --event-data '{"type":"test"}' --config '{"token":"test"}'
167
+ ```typescript
168
+ import { toAISdkStream } from '@mastra/ai-sdk';
169
+ import { createUIMessageStream, createUIMessageStreamResponse } from 'ai';
170
+
171
+ export async function POST(req: Request) {
172
+ const { messages } = await req.json();
173
+ const agent = mastra.getAgent('weatherAgent');
174
+ const stream = await agent.stream(messages);
175
+
176
+ // deduplicate messages https://ai-sdk.dev/docs/troubleshooting/repeated-assistant-messages
177
+ const uiMessageStream = createUIMessageStream({
178
+ originalMessages: messages,
179
+ execute: async ({ writer }) => {
180
+ for await (const part of toAISdkStream(stream, { from: 'agent' })) {
181
+ writer.write(part);
182
+ }
183
+ },
184
+ });
185
+
186
+ return createUIMessageStreamResponse({ stream: uiMessageStream });
187
+ }
217
188
  ```
218
189
 
219
- ### Best Practices
220
-
221
- 1. **Always validate input data** before processing
222
- 2. **Handle errors gracefully** with meaningful error messages
223
- 3. **Use consistent data structures** for activities
224
- 4. **Include proper timestamps** in all activity data
225
- 5. **Store minimal state** for sync operations
226
- 6. **Test all event types** thoroughly
190
+ For AI SDK v6, select the v6 stream contract explicitly:
227
191
 
228
- For more examples, see the integrations in the `integrations/` directory.
192
+ ```typescript
193
+ const uiMessageStream = createUIMessageStream({
194
+ originalMessages: messages,
195
+ execute: async ({ writer }) => {
196
+ for await (const part of toAISdkStream(stream, {
197
+ from: 'agent',
198
+ version: 'v6',
199
+ })) {
200
+ writer.write(part);
201
+ }
202
+ },
203
+ });
204
+ ```