@mastra/client-js 1.15.2-alpha.0 → 1.15.2-alpha.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,113 @@
1
1
  # @mastra/client-js
2
2
 
3
+ ## 1.15.2-alpha.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Add durable agents with resumable streams ([#12557](https://github.com/mastra-ai/mastra/pull/12557))
8
+
9
+ Durable agents make agent execution resilient to disconnections, crashes, and long-running operations.
10
+
11
+ ### The Problem
12
+
13
+ Standard agent streaming has two fragility points:
14
+ 1. **Connection drops** - If a client disconnects mid-stream (network blip, browser refresh, mobile app backgrounded), all subsequent events are lost. The client has no way to "catch up" on what they missed.
15
+ 2. **Long-running operations** - Agent loops with tool calls can take minutes. Holding an HTTP connection open that long is unreliable. If the server restarts or the connection times out, the work is lost.
16
+
17
+ ### The Solution
18
+
19
+ **Resumable streams** solve connection drops. Every event is cached with a sequential index. If a client disconnects at event 5, they can reconnect and request events starting from index 6. They receive cached events immediately, then continue with live events as they arrive.
20
+
21
+ **Durable execution** solves long-running operations. Instead of executing the agent loop directly in the HTTP request, execution happens in a workflow engine (built-in evented engine or Inngest). The HTTP request just subscribes to events. If the connection drops, execution continues. The client can reconnect anytime to observe progress.
22
+
23
+ ### Usage
24
+
25
+ Wrap any existing `Agent` with durability using factory functions:
26
+
27
+ ```typescript
28
+ import { Agent } from '@mastra/core/agent';
29
+ import { createDurableAgent } from '@mastra/core/agent/durable';
30
+
31
+ const agent = new Agent({
32
+ id: 'my-agent',
33
+ model: openai('gpt-4'),
34
+ instructions: 'You are helpful',
35
+ });
36
+
37
+ const durableAgent = createDurableAgent({ agent });
38
+ ```
39
+
40
+ **Factory functions for different execution strategies:**
41
+
42
+ | Factory | Execution | Use Case |
43
+ | ---------------------------------------- | ----------------------------------- | ------------------------------- |
44
+ | `createDurableAgent({ agent })` | Local, synchronous | Development, simple deployments |
45
+ | `createEventedAgent({ agent })` | Fire-and-forget via workflow engine | Long-running operations |
46
+ | `createInngestAgent({ agent, inngest })` | Inngest-powered | Production, distributed systems |
47
+
48
+ ### Resumable Streams
49
+
50
+ ```typescript
51
+ // Start streaming
52
+ const { runId, output } = await durableAgent.stream('Analyze this data...');
53
+
54
+ // Client disconnects at event 5...
55
+
56
+ // Reconnect and resume from where we left off
57
+ const { output: resumed } = await durableAgent.observe(runId, { offset: 6 });
58
+ // Receives events 6, 7, 8... from cache, then continues with live events
59
+ ```
60
+
61
+ ### PubSub and Cache
62
+
63
+ Durable agents use two infrastructure components:
64
+
65
+ | Component | Purpose | Default |
66
+ | ---------- | ----------------------------------------- | --------------------- |
67
+ | **PubSub** | Real-time event delivery during streaming | `EventEmitterPubSub` |
68
+ | **Cache** | Stores events for replay on reconnection | `InMemoryServerCache` |
69
+
70
+ When `stream()` is called, events flow through pubsub in real-time. The cache stores each event with a sequential index. When `observe()` is called, missed events replay from cache before continuing with live events.
71
+
72
+ **Configure via Mastra instance (recommended):**
73
+
74
+ ```typescript
75
+ const mastra = new Mastra({
76
+ cache: new RedisServerCache({ url: 'redis://...' }),
77
+ pubsub: new RedisPubSub({ url: 'redis://...' }),
78
+ agents: {
79
+ // Inherits cache and pubsub from Mastra
80
+ myAgent: createDurableAgent({ agent }),
81
+ },
82
+ });
83
+ ```
84
+
85
+ **Configure per-agent (overrides Mastra):**
86
+
87
+ ```typescript
88
+ const durableAgent = createDurableAgent({
89
+ agent,
90
+ cache: new RedisServerCache({ url: 'redis://...' }),
91
+ pubsub: new RedisPubSub({ url: 'redis://...' }),
92
+ });
93
+ ```
94
+
95
+ **Disable caching (streams won't be resumable):**
96
+
97
+ ```typescript
98
+ const durableAgent = createDurableAgent({ agent, cache: false });
99
+ ```
100
+
101
+ For single-instance deployments, the defaults work fine. For multi-instance deployments (load balancer, horizontal scaling), use Redis-backed implementations so any instance can serve reconnection requests.
102
+
103
+ ### Class Hierarchy
104
+ - `DurableAgent` extends `Agent` - base class with resumable streams
105
+ - `EventedAgent` extends `DurableAgent` - fire-and-forget execution
106
+ - `InngestAgent` extends `DurableAgent` - Inngest-powered execution
107
+
108
+ - Updated dependencies [[`920c757`](https://github.com/mastra-ai/mastra/commit/920c75799c6bd71787d86deaf654a35af4c839ca), [`1fe2533`](https://github.com/mastra-ai/mastra/commit/1fe2533c4382ca6858aac7c4b63e888c2eac6541), [`f8694b6`](https://github.com/mastra-ai/mastra/commit/f8694b6fa0b7a5cde71d794c3bbef4957c55bcb8)]:
109
+ - @mastra/core@1.30.0-alpha.1
110
+
3
111
  ## 1.15.2-alpha.0
4
112
 
5
113
  ### Patch Changes
@@ -3,7 +3,7 @@ name: mastra-client-js
3
3
  description: Documentation for @mastra/client-js. Use when working with @mastra/client-js APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/client-js"
6
- version: "1.15.2-alpha.0"
6
+ version: "1.15.2-alpha.1"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.15.2-alpha.0",
2
+ "version": "1.15.2-alpha.1",
3
3
  "package": "@mastra/client-js",
4
4
  "exports": {
5
5
  "RequestContext": {
package/dist/index.cjs CHANGED
@@ -1558,6 +1558,51 @@ var Agent = class extends BaseResource {
1558
1558
  };
1559
1559
  return streamResponse;
1560
1560
  }
1561
+ /**
1562
+ * Observe (reconnect to) an existing agent stream.
1563
+ * Use this to resume receiving events after a disconnection.
1564
+ *
1565
+ * @param params.runId - The run ID to observe
1566
+ * @param params.offset - Optional position to resume from (0-based). If omitted, replays all events.
1567
+ * @returns Promise containing a streaming Response
1568
+ *
1569
+ * @example
1570
+ * ```typescript
1571
+ * // Reconnect to a stream from a specific position
1572
+ * const response = await client.agents('my-agent').observe({
1573
+ * runId: 'run-123',
1574
+ * offset: 42, // Resume from event 42
1575
+ * });
1576
+ *
1577
+ * await response.processDataStream({
1578
+ * onChunk: (chunk) => console.log('Received:', chunk),
1579
+ * });
1580
+ * ```
1581
+ */
1582
+ async observe(params) {
1583
+ const response = await this.request(`/agents/${this.agentId}/observe`, {
1584
+ method: "POST",
1585
+ body: params,
1586
+ stream: true
1587
+ });
1588
+ if (!response.body) {
1589
+ throw new Error("No response body");
1590
+ }
1591
+ const streamResponse = new Response(response.body, {
1592
+ status: response.status,
1593
+ statusText: response.statusText,
1594
+ headers: response.headers
1595
+ });
1596
+ streamResponse.processDataStream = async ({
1597
+ onChunk
1598
+ }) => {
1599
+ await processMastraStream({
1600
+ stream: streamResponse.body,
1601
+ onChunk
1602
+ });
1603
+ };
1604
+ return streamResponse;
1605
+ }
1561
1606
  /**
1562
1607
  * Resumes a suspended agent stream with custom resume data.
1563
1608
  * Used to continue execution after a suspension point (e.g., workflow suspend within an agent).
@@ -2311,19 +2356,32 @@ var Run = class extends BaseResource {
2311
2356
  return response.body.pipeThrough(this.createChunkTransformStream());
2312
2357
  }
2313
2358
  /**
2314
- * Observes workflow stream for a workflow run
2315
- * @returns Promise containing the workflow execution results
2359
+ * Observe (reconnect to) an existing workflow stream.
2360
+ * Use this to resume receiving events after a disconnection.
2361
+ *
2362
+ * @param params.offset - Optional position to resume from (0-based). If omitted, replays all events.
2363
+ * @returns Promise containing a ReadableStream of workflow events
2364
+ *
2365
+ * @example
2366
+ * ```typescript
2367
+ * // Reconnect to a workflow stream from a specific position
2368
+ * const stream = await run.observe({ offset: 42 });
2369
+ *
2370
+ * for await (const event of stream) {
2371
+ * console.log('Received:', event);
2372
+ * }
2373
+ * ```
2316
2374
  */
2317
- async observeStream() {
2375
+ async observe(params) {
2318
2376
  const searchParams = new URLSearchParams();
2319
2377
  searchParams.set("runId", this.runId);
2320
- const response = await this.request(
2321
- `/workflows/${this.workflowId}/observe-stream?${searchParams.toString()}`,
2322
- {
2323
- method: "POST",
2324
- stream: true
2325
- }
2326
- );
2378
+ if (params?.offset !== void 0) {
2379
+ searchParams.set("offset", String(params.offset));
2380
+ }
2381
+ const response = await this.request(`/workflows/${this.workflowId}/observe?${searchParams.toString()}`, {
2382
+ method: "POST",
2383
+ stream: true
2384
+ });
2327
2385
  if (!response.ok) {
2328
2386
  throw new Error(`Failed to observe workflow stream: ${response.statusText}`);
2329
2387
  }
@@ -2332,6 +2390,14 @@ var Run = class extends BaseResource {
2332
2390
  }
2333
2391
  return response.body.pipeThrough(this.createChunkTransformStream());
2334
2392
  }
2393
+ /**
2394
+ * Observes workflow stream for a workflow run
2395
+ * @deprecated Use `observe()` instead for better control over replay position
2396
+ * @returns Promise containing the workflow execution results
2397
+ */
2398
+ async observeStream() {
2399
+ return this.observe();
2400
+ }
2335
2401
  /**
2336
2402
  * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
2337
2403
  * @param params - Object containing the step, resumeData and requestContext