@mastra/client-js 0.0.0-share-agent-metadata-with-cloud-20250718123411 → 0.0.0-stream-vnext-usage-20250908171242

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 (81) hide show
  1. package/CHANGELOG.md +781 -2
  2. package/README.md +6 -3
  3. package/dist/client.d.ts +280 -0
  4. package/dist/client.d.ts.map +1 -0
  5. package/dist/example.d.ts +2 -0
  6. package/dist/example.d.ts.map +1 -0
  7. package/dist/index.cjs +1688 -707
  8. package/dist/index.cjs.map +1 -0
  9. package/dist/index.d.ts +4 -1194
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +1688 -707
  12. package/dist/index.js.map +1 -0
  13. package/dist/resources/a2a.d.ts +41 -0
  14. package/dist/resources/a2a.d.ts.map +1 -0
  15. package/dist/resources/agent-builder.d.ts +161 -0
  16. package/dist/resources/agent-builder.d.ts.map +1 -0
  17. package/dist/resources/agent.d.ts +155 -0
  18. package/dist/resources/agent.d.ts.map +1 -0
  19. package/dist/resources/base.d.ts +13 -0
  20. package/dist/resources/base.d.ts.map +1 -0
  21. package/dist/resources/index.d.ts +13 -0
  22. package/dist/resources/index.d.ts.map +1 -0
  23. package/dist/resources/legacy-workflow.d.ts +87 -0
  24. package/dist/resources/legacy-workflow.d.ts.map +1 -0
  25. package/dist/resources/mcp-tool.d.ts +27 -0
  26. package/dist/resources/mcp-tool.d.ts.map +1 -0
  27. package/dist/resources/memory-thread.d.ts +53 -0
  28. package/dist/resources/memory-thread.d.ts.map +1 -0
  29. package/dist/resources/network-memory-thread.d.ts +47 -0
  30. package/dist/resources/network-memory-thread.d.ts.map +1 -0
  31. package/dist/resources/network.d.ts +30 -0
  32. package/dist/resources/network.d.ts.map +1 -0
  33. package/dist/resources/observability.d.ts +19 -0
  34. package/dist/resources/observability.d.ts.map +1 -0
  35. package/dist/resources/tool.d.ts +23 -0
  36. package/dist/resources/tool.d.ts.map +1 -0
  37. package/dist/resources/vNextNetwork.d.ts +42 -0
  38. package/dist/resources/vNextNetwork.d.ts.map +1 -0
  39. package/dist/resources/vector.d.ts +48 -0
  40. package/dist/resources/vector.d.ts.map +1 -0
  41. package/dist/resources/workflow.d.ts +169 -0
  42. package/dist/resources/workflow.d.ts.map +1 -0
  43. package/dist/types.d.ts +461 -0
  44. package/dist/types.d.ts.map +1 -0
  45. package/dist/utils/index.d.ts +3 -0
  46. package/dist/utils/index.d.ts.map +1 -0
  47. package/dist/utils/process-client-tools.d.ts +3 -0
  48. package/dist/utils/process-client-tools.d.ts.map +1 -0
  49. package/dist/utils/process-mastra-stream.d.ts +7 -0
  50. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  51. package/dist/utils/zod-to-json-schema.d.ts +3 -0
  52. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  53. package/package.json +26 -14
  54. package/.turbo/turbo-build.log +0 -19
  55. package/dist/index.d.cts +0 -1194
  56. package/eslint.config.js +0 -6
  57. package/src/adapters/agui.test.ts +0 -180
  58. package/src/adapters/agui.ts +0 -239
  59. package/src/client.ts +0 -526
  60. package/src/example.ts +0 -95
  61. package/src/index.test.ts +0 -836
  62. package/src/index.ts +0 -2
  63. package/src/resources/a2a.ts +0 -88
  64. package/src/resources/agent.ts +0 -800
  65. package/src/resources/base.ts +0 -72
  66. package/src/resources/index.ts +0 -10
  67. package/src/resources/legacy-workflow.ts +0 -242
  68. package/src/resources/mcp-tool.ts +0 -48
  69. package/src/resources/memory-thread.ts +0 -63
  70. package/src/resources/network-memory-thread.ts +0 -63
  71. package/src/resources/network.ts +0 -85
  72. package/src/resources/tool.ts +0 -45
  73. package/src/resources/vNextNetwork.ts +0 -194
  74. package/src/resources/vector.ts +0 -83
  75. package/src/resources/workflow.ts +0 -401
  76. package/src/types.ts +0 -428
  77. package/src/utils/index.ts +0 -11
  78. package/src/utils/process-client-tools.ts +0 -32
  79. package/src/utils/zod-to-json-schema.ts +0 -10
  80. package/tsconfig.json +0 -5
  81. package/vitest.config.js +0 -8
@@ -1,194 +0,0 @@
1
- import type { WatchEvent } from '@mastra/core/workflows';
2
-
3
- import type {
4
- ClientOptions,
5
- GetVNextNetworkResponse,
6
- GenerateVNextNetworkResponse,
7
- LoopVNextNetworkResponse,
8
- GenerateOrStreamVNextNetworkParams,
9
- LoopStreamVNextNetworkParams,
10
- } from '../types';
11
-
12
- import { BaseResource } from './base';
13
- import { parseClientRuntimeContext } from '../utils';
14
- import type { RuntimeContext } from '@mastra/core/runtime-context';
15
-
16
- const RECORD_SEPARATOR = '\x1E';
17
-
18
- export class VNextNetwork extends BaseResource {
19
- constructor(
20
- options: ClientOptions,
21
- private networkId: string,
22
- ) {
23
- super(options);
24
- }
25
-
26
- /**
27
- * Retrieves details about the network
28
- * @returns Promise containing vNext network details
29
- */
30
- details(): Promise<GetVNextNetworkResponse> {
31
- return this.request(`/api/networks/v-next/${this.networkId}`);
32
- }
33
-
34
- /**
35
- * Generates a response from the v-next network
36
- * @param params - Generation parameters including message
37
- * @returns Promise containing the generated response
38
- */
39
- generate(params: GenerateOrStreamVNextNetworkParams): Promise<GenerateVNextNetworkResponse> {
40
- return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
41
- method: 'POST',
42
- body: {
43
- ...params,
44
- runtimeContext: parseClientRuntimeContext(params.runtimeContext),
45
- },
46
- });
47
- }
48
-
49
- /**
50
- * Generates a response from the v-next network using multiple primitives
51
- * @param params - Generation parameters including message
52
- * @returns Promise containing the generated response
53
- */
54
- loop(params: {
55
- message: string;
56
- runtimeContext?: RuntimeContext | Record<string, any>;
57
- }): Promise<LoopVNextNetworkResponse> {
58
- return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
59
- method: 'POST',
60
- body: {
61
- ...params,
62
- runtimeContext: parseClientRuntimeContext(params.runtimeContext),
63
- },
64
- });
65
- }
66
-
67
- private async *streamProcessor(stream: ReadableStream): AsyncGenerator<WatchEvent, void, unknown> {
68
- const reader = stream.getReader();
69
-
70
- // Track if we've finished reading from the stream
71
- let doneReading = false;
72
- // Buffer to accumulate partial chunks
73
- let buffer = '';
74
-
75
- try {
76
- while (!doneReading) {
77
- // Read the next chunk from the stream
78
- const { done, value } = await reader.read();
79
- doneReading = done;
80
-
81
- // Skip processing if we're done and there's no value
82
- if (done && !value) continue;
83
-
84
- try {
85
- // Decode binary data to text
86
- const decoded = value ? new TextDecoder().decode(value) : '';
87
-
88
- // Split the combined buffer and new data by record separator
89
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
90
-
91
- // The last chunk might be incomplete, so save it for the next iteration
92
- buffer = chunks.pop() || '';
93
-
94
- // Process complete chunks
95
- for (const chunk of chunks) {
96
- if (chunk) {
97
- // Only process non-empty chunks
98
- if (typeof chunk === 'string') {
99
- try {
100
- const parsedChunk = JSON.parse(chunk);
101
- yield parsedChunk;
102
- } catch {
103
- // Silently ignore parsing errors to maintain stream processing
104
- // This allows the stream to continue even if one record is malformed
105
- }
106
- }
107
- }
108
- }
109
- } catch {
110
- // Silently ignore parsing errors to maintain stream processing
111
- // This allows the stream to continue even if one record is malformed
112
- }
113
- }
114
-
115
- // Process any remaining data in the buffer after stream is done
116
- if (buffer) {
117
- try {
118
- yield JSON.parse(buffer);
119
- } catch {
120
- // Ignore parsing error for final chunk
121
- }
122
- }
123
- } finally {
124
- // Always ensure we clean up the reader
125
- reader.cancel().catch(() => {
126
- // Ignore cancel errors
127
- });
128
- }
129
- }
130
-
131
- /**
132
- * Streams a response from the v-next network
133
- * @param params - Stream parameters including message
134
- * @returns Promise containing the results
135
- */
136
- async stream(params: GenerateOrStreamVNextNetworkParams, onRecord: (record: WatchEvent) => void) {
137
- const response: Response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
138
- method: 'POST',
139
- body: {
140
- ...params,
141
- runtimeContext: parseClientRuntimeContext(params.runtimeContext),
142
- },
143
- stream: true,
144
- });
145
-
146
- if (!response.ok) {
147
- throw new Error(`Failed to stream vNext network: ${response.statusText}`);
148
- }
149
-
150
- if (!response.body) {
151
- throw new Error('Response body is null');
152
- }
153
-
154
- for await (const record of this.streamProcessor(response.body)) {
155
- if (typeof record === 'string') {
156
- onRecord(JSON.parse(record));
157
- } else {
158
- onRecord(record);
159
- }
160
- }
161
- }
162
-
163
- /**
164
- * Streams a response from the v-next network loop
165
- * @param params - Stream parameters including message
166
- * @returns Promise containing the results
167
- */
168
- async loopStream(params: LoopStreamVNextNetworkParams, onRecord: (record: WatchEvent) => void) {
169
- const response: Response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
170
- method: 'POST',
171
- body: {
172
- ...params,
173
- runtimeContext: parseClientRuntimeContext(params.runtimeContext),
174
- },
175
- stream: true,
176
- });
177
-
178
- if (!response.ok) {
179
- throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
180
- }
181
-
182
- if (!response.body) {
183
- throw new Error('Response body is null');
184
- }
185
-
186
- for await (const record of this.streamProcessor(response.body)) {
187
- if (typeof record === 'string') {
188
- onRecord(JSON.parse(record));
189
- } else {
190
- onRecord(record);
191
- }
192
- }
193
- }
194
- }
@@ -1,83 +0,0 @@
1
- import type {
2
- CreateIndexParams,
3
- GetVectorIndexResponse,
4
- QueryVectorParams,
5
- QueryVectorResponse,
6
- ClientOptions,
7
- UpsertVectorParams,
8
- } from '../types';
9
-
10
- import { BaseResource } from './base';
11
-
12
- export class Vector extends BaseResource {
13
- constructor(
14
- options: ClientOptions,
15
- private vectorName: string,
16
- ) {
17
- super(options);
18
- }
19
-
20
- /**
21
- * Retrieves details about a specific vector index
22
- * @param indexName - Name of the index to get details for
23
- * @returns Promise containing vector index details
24
- */
25
- details(indexName: string): Promise<GetVectorIndexResponse> {
26
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
27
- }
28
-
29
- /**
30
- * Deletes a vector index
31
- * @param indexName - Name of the index to delete
32
- * @returns Promise indicating deletion success
33
- */
34
- delete(indexName: string): Promise<{ success: boolean }> {
35
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`, {
36
- method: 'DELETE',
37
- });
38
- }
39
-
40
- /**
41
- * Retrieves a list of all available indexes
42
- * @returns Promise containing array of index names
43
- */
44
- getIndexes(): Promise<{ indexes: string[] }> {
45
- return this.request(`/api/vector/${this.vectorName}/indexes`);
46
- }
47
-
48
- /**
49
- * Creates a new vector index
50
- * @param params - Parameters for index creation including dimension and metric
51
- * @returns Promise indicating creation success
52
- */
53
- createIndex(params: CreateIndexParams): Promise<{ success: boolean }> {
54
- return this.request(`/api/vector/${this.vectorName}/create-index`, {
55
- method: 'POST',
56
- body: params,
57
- });
58
- }
59
-
60
- /**
61
- * Upserts vectors into an index
62
- * @param params - Parameters containing vectors, metadata, and optional IDs
63
- * @returns Promise containing array of vector IDs
64
- */
65
- upsert(params: UpsertVectorParams): Promise<string[]> {
66
- return this.request(`/api/vector/${this.vectorName}/upsert`, {
67
- method: 'POST',
68
- body: params,
69
- });
70
- }
71
-
72
- /**
73
- * Queries vectors in an index
74
- * @param params - Query parameters including query vector and search options
75
- * @returns Promise containing query results
76
- */
77
- query(params: QueryVectorParams): Promise<QueryVectorResponse> {
78
- return this.request(`/api/vector/${this.vectorName}/query`, {
79
- method: 'POST',
80
- body: params,
81
- });
82
- }
83
- }
@@ -1,401 +0,0 @@
1
- import type { RuntimeContext } from '@mastra/core/runtime-context';
2
- import type {
3
- ClientOptions,
4
- GetWorkflowResponse,
5
- GetWorkflowRunsResponse,
6
- GetWorkflowRunsParams,
7
- WorkflowRunResult,
8
- WorkflowWatchResult,
9
- GetWorkflowRunByIdResponse,
10
- GetWorkflowRunExecutionResultResponse,
11
- } from '../types';
12
-
13
- import { parseClientRuntimeContext } from '../utils';
14
- import { BaseResource } from './base';
15
-
16
- const RECORD_SEPARATOR = '\x1E';
17
-
18
- export class Workflow extends BaseResource {
19
- constructor(
20
- options: ClientOptions,
21
- private workflowId: string,
22
- ) {
23
- super(options);
24
- }
25
-
26
- /**
27
- * Creates an async generator that processes a readable stream and yields workflow records
28
- * separated by the Record Separator character (\x1E)
29
- *
30
- * @param stream - The readable stream to process
31
- * @returns An async generator that yields parsed records
32
- */
33
- private async *streamProcessor(stream: ReadableStream): AsyncGenerator<WorkflowWatchResult, void, unknown> {
34
- const reader = stream.getReader();
35
-
36
- // Track if we've finished reading from the stream
37
- let doneReading = false;
38
- // Buffer to accumulate partial chunks
39
- let buffer = '';
40
-
41
- try {
42
- while (!doneReading) {
43
- // Read the next chunk from the stream
44
- const { done, value } = await reader.read();
45
- doneReading = done;
46
-
47
- // Skip processing if we're done and there's no value
48
- if (done && !value) continue;
49
-
50
- try {
51
- // Decode binary data to text
52
- const decoded = value ? new TextDecoder().decode(value) : '';
53
-
54
- // Split the combined buffer and new data by record separator
55
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
56
-
57
- // The last chunk might be incomplete, so save it for the next iteration
58
- buffer = chunks.pop() || '';
59
-
60
- // Process complete chunks
61
- for (const chunk of chunks) {
62
- if (chunk) {
63
- // Only process non-empty chunks
64
- if (typeof chunk === 'string') {
65
- try {
66
- const parsedChunk = JSON.parse(chunk);
67
- yield parsedChunk;
68
- } catch {
69
- // Silently ignore parsing errors to maintain stream processing
70
- // This allows the stream to continue even if one record is malformed
71
- }
72
- }
73
- }
74
- }
75
- } catch {
76
- // Silently ignore parsing errors to maintain stream processing
77
- // This allows the stream to continue even if one record is malformed
78
- }
79
- }
80
-
81
- // Process any remaining data in the buffer after stream is done
82
- if (buffer) {
83
- try {
84
- yield JSON.parse(buffer);
85
- } catch {
86
- // Ignore parsing error for final chunk
87
- }
88
- }
89
- } finally {
90
- // Always ensure we clean up the reader
91
- reader.cancel().catch(() => {
92
- // Ignore cancel errors
93
- });
94
- }
95
- }
96
-
97
- /**
98
- * Retrieves details about the workflow
99
- * @returns Promise containing workflow details including steps and graphs
100
- */
101
- details(): Promise<GetWorkflowResponse> {
102
- return this.request(`/api/workflows/${this.workflowId}`);
103
- }
104
-
105
- /**
106
- * Retrieves all runs for a workflow
107
- * @param params - Parameters for filtering runs
108
- * @returns Promise containing workflow runs array
109
- */
110
- runs(params?: GetWorkflowRunsParams): Promise<GetWorkflowRunsResponse> {
111
- const searchParams = new URLSearchParams();
112
- if (params?.fromDate) {
113
- searchParams.set('fromDate', params.fromDate.toISOString());
114
- }
115
- if (params?.toDate) {
116
- searchParams.set('toDate', params.toDate.toISOString());
117
- }
118
- if (params?.limit !== null && params?.limit !== undefined && !isNaN(Number(params?.limit))) {
119
- searchParams.set('limit', String(params.limit));
120
- }
121
- if (params?.offset !== null && params?.offset !== undefined && !isNaN(Number(params?.offset))) {
122
- searchParams.set('offset', String(params.offset));
123
- }
124
- if (params?.resourceId) {
125
- searchParams.set('resourceId', params.resourceId);
126
- }
127
-
128
- if (searchParams.size) {
129
- return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
130
- } else {
131
- return this.request(`/api/workflows/${this.workflowId}/runs`);
132
- }
133
- }
134
-
135
- /**
136
- * Retrieves a specific workflow run by its ID
137
- * @param runId - The ID of the workflow run to retrieve
138
- * @returns Promise containing the workflow run details
139
- */
140
- runById(runId: string): Promise<GetWorkflowRunByIdResponse> {
141
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
142
- }
143
-
144
- /**
145
- * Retrieves the execution result for a specific workflow run by its ID
146
- * @param runId - The ID of the workflow run to retrieve the execution result for
147
- * @returns Promise containing the workflow run execution result
148
- */
149
- runExecutionResult(runId: string): Promise<GetWorkflowRunExecutionResultResponse> {
150
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
151
- }
152
-
153
- /**
154
- * Cancels a specific workflow run by its ID
155
- * @param runId - The ID of the workflow run to cancel
156
- * @returns Promise containing a success message
157
- */
158
- cancelRun(runId: string): Promise<{ message: string }> {
159
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
160
- method: 'POST',
161
- });
162
- }
163
-
164
- /**
165
- * Sends an event to a specific workflow run by its ID
166
- * @param params - Object containing the runId, event and data
167
- * @returns Promise containing a success message
168
- */
169
- sendRunEvent(params: { runId: string; event: string; data: unknown }): Promise<{ message: string }> {
170
- return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
171
- method: 'POST',
172
- body: { event: params.event, data: params.data },
173
- });
174
- }
175
-
176
- /**
177
- * Creates a new workflow run
178
- * @param params - Optional object containing the optional runId
179
- * @returns Promise containing the runId of the created run
180
- */
181
- createRun(params?: { runId?: string }): Promise<{ runId: string }> {
182
- const searchParams = new URLSearchParams();
183
-
184
- if (!!params?.runId) {
185
- searchParams.set('runId', params.runId);
186
- }
187
-
188
- return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
189
- method: 'POST',
190
- });
191
- }
192
-
193
- /**
194
- * Starts a workflow run synchronously without waiting for the workflow to complete
195
- * @param params - Object containing the runId, inputData and runtimeContext
196
- * @returns Promise containing success message
197
- */
198
- start(params: {
199
- runId: string;
200
- inputData: Record<string, any>;
201
- runtimeContext?: RuntimeContext | Record<string, any>;
202
- }): Promise<{ message: string }> {
203
- const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
204
- return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
205
- method: 'POST',
206
- body: { inputData: params?.inputData, runtimeContext },
207
- });
208
- }
209
-
210
- /**
211
- * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
212
- * @param params - Object containing the runId, step, resumeData and runtimeContext
213
- * @returns Promise containing success message
214
- */
215
- resume({
216
- step,
217
- runId,
218
- resumeData,
219
- ...rest
220
- }: {
221
- step: string | string[];
222
- runId: string;
223
- resumeData?: Record<string, any>;
224
- runtimeContext?: RuntimeContext | Record<string, any>;
225
- }): Promise<{ message: string }> {
226
- const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
227
- return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
228
- method: 'POST',
229
- stream: true,
230
- body: {
231
- step,
232
- resumeData,
233
- runtimeContext,
234
- },
235
- });
236
- }
237
-
238
- /**
239
- * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
240
- * @param params - Object containing the optional runId, inputData and runtimeContext
241
- * @returns Promise containing the workflow execution results
242
- */
243
- startAsync(params: {
244
- runId?: string;
245
- inputData: Record<string, any>;
246
- runtimeContext?: RuntimeContext | Record<string, any>;
247
- }): Promise<WorkflowRunResult> {
248
- const searchParams = new URLSearchParams();
249
-
250
- if (!!params?.runId) {
251
- searchParams.set('runId', params.runId);
252
- }
253
-
254
- const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
255
-
256
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
257
- method: 'POST',
258
- body: { inputData: params.inputData, runtimeContext },
259
- });
260
- }
261
-
262
- /**
263
- * Starts a workflow run and returns a stream
264
- * @param params - Object containing the optional runId, inputData and runtimeContext
265
- * @returns Promise containing the workflow execution results
266
- */
267
- async stream(params: { runId?: string; inputData: Record<string, any>; runtimeContext?: RuntimeContext }) {
268
- const searchParams = new URLSearchParams();
269
-
270
- if (!!params?.runId) {
271
- searchParams.set('runId', params.runId);
272
- }
273
-
274
- const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
275
- const response: Response = await this.request(
276
- `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
277
- {
278
- method: 'POST',
279
- body: { inputData: params.inputData, runtimeContext },
280
- stream: true,
281
- },
282
- );
283
-
284
- if (!response.ok) {
285
- throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
286
- }
287
-
288
- if (!response.body) {
289
- throw new Error('Response body is null');
290
- }
291
-
292
- //using undefined instead of empty string to avoid parsing errors
293
- let failedChunk: string | undefined = undefined;
294
-
295
- // Create a transform stream that processes the response body
296
- const transformStream = new TransformStream<ArrayBuffer, { type: string; payload: any }>({
297
- start() {},
298
- async transform(chunk, controller) {
299
- try {
300
- // Decode binary data to text
301
- const decoded = new TextDecoder().decode(chunk);
302
-
303
- // Split by record separator
304
- const chunks = decoded.split(RECORD_SEPARATOR);
305
-
306
- // Process each chunk
307
- for (const chunk of chunks) {
308
- if (chunk) {
309
- const newChunk: string = failedChunk ? failedChunk + chunk : chunk;
310
- try {
311
- const parsedChunk = JSON.parse(newChunk);
312
- controller.enqueue(parsedChunk);
313
- failedChunk = undefined;
314
- } catch (error) {
315
- failedChunk = newChunk;
316
- }
317
- }
318
- }
319
- } catch {
320
- // Silently ignore processing errors
321
- }
322
- },
323
- });
324
-
325
- // Pipe the response body through the transform stream
326
- return response.body.pipeThrough(transformStream);
327
- }
328
-
329
- /**
330
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
331
- * @param params - Object containing the runId, step, resumeData and runtimeContext
332
- * @returns Promise containing the workflow resume results
333
- */
334
- resumeAsync(params: {
335
- runId: string;
336
- step: string | string[];
337
- resumeData?: Record<string, any>;
338
- runtimeContext?: RuntimeContext | Record<string, any>;
339
- }): Promise<WorkflowRunResult> {
340
- const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
341
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
342
- method: 'POST',
343
- body: {
344
- step: params.step,
345
- resumeData: params.resumeData,
346
- runtimeContext,
347
- },
348
- });
349
- }
350
-
351
- /**
352
- * Watches workflow transitions in real-time
353
- * @param runId - Optional run ID to filter the watch stream
354
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
355
- */
356
- async watch({ runId }: { runId?: string }, onRecord: (record: WorkflowWatchResult) => void) {
357
- const response: Response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
358
- stream: true,
359
- });
360
-
361
- if (!response.ok) {
362
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
363
- }
364
-
365
- if (!response.body) {
366
- throw new Error('Response body is null');
367
- }
368
-
369
- for await (const record of this.streamProcessor(response.body)) {
370
- if (typeof record === 'string') {
371
- onRecord(JSON.parse(record));
372
- } else {
373
- onRecord(record);
374
- }
375
- }
376
- }
377
-
378
- /**
379
- * Creates a new ReadableStream from an iterable or async iterable of objects,
380
- * serializing each as JSON and separating them with the record separator (\x1E).
381
- *
382
- * @param records - An iterable or async iterable of objects to stream
383
- * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
384
- */
385
- static createRecordStream(records: Iterable<any> | AsyncIterable<any>): ReadableStream {
386
- const encoder = new TextEncoder();
387
- return new ReadableStream({
388
- async start(controller) {
389
- try {
390
- for await (const record of records as AsyncIterable<any>) {
391
- const json = JSON.stringify(record) + RECORD_SEPARATOR;
392
- controller.enqueue(encoder.encode(json));
393
- }
394
- controller.close();
395
- } catch (err) {
396
- controller.error(err);
397
- }
398
- },
399
- });
400
- }
401
- }