agents 0.0.0-feef082 → 0.0.0-ff45307

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 (85) hide show
  1. package/README.md +130 -6
  2. package/dist/ai-chat-agent.d.ts +99 -19
  3. package/dist/ai-chat-agent.js +804 -329
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-BSiGZmYU.js +155 -0
  6. package/dist/ai-chat-v5-migration-BSiGZmYU.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +7 -4
  8. package/dist/ai-chat-v5-migration.js +3 -19
  9. package/dist/ai-react.d.ts +25 -23
  10. package/dist/ai-react.js +409 -304
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-81H_-Uxh.d.ts +103 -0
  13. package/dist/ai-types-CrMqkwc_.js +24 -0
  14. package/dist/ai-types-CrMqkwc_.js.map +1 -0
  15. package/dist/ai-types.d.ts +6 -91
  16. package/dist/ai-types.js +3 -7
  17. package/dist/cli/index.d.ts +1 -0
  18. package/dist/cli/index.js +28 -0
  19. package/dist/cli/index.js.map +1 -0
  20. package/dist/client-B3SR12TQ.js +117 -0
  21. package/dist/client-B3SR12TQ.js.map +1 -0
  22. package/dist/client-BAQA84dr.d.ts +104 -0
  23. package/dist/client-CFhjXCiO.js +1093 -0
  24. package/dist/client-CFhjXCiO.js.map +1 -0
  25. package/dist/client-CwqTTb-B.d.ts +833 -0
  26. package/dist/client.d.ts +11 -92
  27. package/dist/client.js +4 -12
  28. package/dist/codemode/ai.d.ts +27 -0
  29. package/dist/codemode/ai.js +151 -0
  30. package/dist/codemode/ai.js.map +1 -0
  31. package/dist/do-oauth-client-provider-C2CHH5x-.d.ts +55 -0
  32. package/dist/do-oauth-client-provider-CwqK5SXm.js +94 -0
  33. package/dist/do-oauth-client-provider-CwqK5SXm.js.map +1 -0
  34. package/dist/index-BUle9RiP.d.ts +58 -0
  35. package/dist/index-DJ4vV2-x.d.ts +587 -0
  36. package/dist/index.d.ts +56 -541
  37. package/dist/index.js +7 -31
  38. package/dist/mcp/client.d.ts +4 -11
  39. package/dist/mcp/client.js +4 -9
  40. package/dist/mcp/do-oauth-client-provider.d.ts +2 -42
  41. package/dist/mcp/do-oauth-client-provider.js +3 -7
  42. package/dist/mcp/index.d.ts +190 -109
  43. package/dist/mcp/index.js +1434 -943
  44. package/dist/mcp/index.js.map +1 -1
  45. package/dist/mcp/x402.d.ts +34 -0
  46. package/dist/mcp/x402.js +198 -0
  47. package/dist/mcp/x402.js.map +1 -0
  48. package/dist/mcp-BwPscEiF.d.ts +61 -0
  49. package/dist/observability/index.d.ts +3 -46
  50. package/dist/observability/index.js +7 -11
  51. package/dist/react-w4GT20p4.d.ts +113 -0
  52. package/dist/react.d.ts +10 -123
  53. package/dist/react.js +183 -112
  54. package/dist/react.js.map +1 -1
  55. package/dist/schedule.d.ts +13 -10
  56. package/dist/schedule.js +43 -31
  57. package/dist/schedule.js.map +1 -1
  58. package/dist/serializable-faDkMCai.d.ts +39 -0
  59. package/dist/serializable.d.ts +7 -32
  60. package/dist/serializable.js +1 -1
  61. package/dist/src-tXpYCgas.js +1184 -0
  62. package/dist/src-tXpYCgas.js.map +1 -0
  63. package/package.json +72 -31
  64. package/dist/ai-chat-v5-migration.js.map +0 -1
  65. package/dist/ai-types.js.map +0 -1
  66. package/dist/chunk-AVYJQSLW.js +0 -17
  67. package/dist/chunk-AVYJQSLW.js.map +0 -1
  68. package/dist/chunk-LL2AFX7V.js +0 -109
  69. package/dist/chunk-LL2AFX7V.js.map +0 -1
  70. package/dist/chunk-PNF6ZMUA.js +0 -1296
  71. package/dist/chunk-PNF6ZMUA.js.map +0 -1
  72. package/dist/chunk-QEVM4BVL.js +0 -116
  73. package/dist/chunk-QEVM4BVL.js.map +0 -1
  74. package/dist/chunk-UJVEAURM.js +0 -150
  75. package/dist/chunk-UJVEAURM.js.map +0 -1
  76. package/dist/chunk-VYENMKFS.js +0 -612
  77. package/dist/chunk-VYENMKFS.js.map +0 -1
  78. package/dist/client-B9tFv5gX.d.ts +0 -4607
  79. package/dist/client.js.map +0 -1
  80. package/dist/index.js.map +0 -1
  81. package/dist/mcp/client.js.map +0 -1
  82. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  83. package/dist/observability/index.js.map +0 -1
  84. package/dist/serializable.js.map +0 -1
  85. package/src/index.ts +0 -1938
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ### 🧠 `agents` - A Framework for Digital Intelligence
2
2
 
3
- ![agents-header](https://github.com/user-attachments/assets/f6d99eeb-1803-4495-9c5e-3cf07a37b402)
3
+ ![npm install agents](../../assets/npm-install-agents.svg)
4
4
 
5
5
  Welcome to a new chapter in software development, where AI agents persist, think, and act with purpose. The `agents` framework creates an environment where artificial intelligence can flourish - maintaining state, engaging in meaningful interactions, and evolving over time.
6
6
 
@@ -317,24 +317,139 @@ Create meaningful conversations with intelligence:
317
317
  ```ts
318
318
  import { AIChatAgent } from "agents/ai-chat-agent";
319
319
  import { openai } from "@ai-sdk/openai";
320
+ import { streamText, generateText, createDataStreamResponse } from "ai";
320
321
 
321
322
  export class DialogueAgent extends AIChatAgent {
322
323
  async onChatMessage(onFinish) {
324
+ // Option 1: Streaming responses (recommended for real-time interaction)
323
325
  return createDataStreamResponse({
324
326
  execute: async (dataStream) => {
325
327
  const stream = streamText({
326
328
  model: openai("gpt-4o"),
327
329
  messages: this.messages,
328
- onFinish // call onFinish so that messages get saved
330
+ // Optional: onFinish is invoked by the AI SDK when generation completes.
331
+ // Persistence is handled automatically by AIChatAgent after streaming completes.
332
+ onFinish
329
333
  });
330
334
 
331
335
  stream.mergeIntoDataStream(dataStream);
332
336
  }
333
337
  });
338
+
339
+ // Option 2: Non-streaming responses (simpler, but no real-time updates)
340
+ // const result = await generateText({
341
+ // model: openai("gpt-4o"),
342
+ // messages: this.messages,
343
+ // });
344
+ //
345
+ // // For non-streaming with metadata, use toUIMessage:
346
+ // const message = result.toUIMessage({
347
+ // metadata: {
348
+ // model: 'gpt-4o',
349
+ // totalTokens: result.usage?.totalTokens,
350
+ // }
351
+ // });
352
+ //
353
+ // return new Response(JSON.stringify(message), {
354
+ // headers: { 'Content-Type': 'application/json' }
355
+ // });
356
+ }
357
+ }
358
+ ```
359
+
360
+ #### Metadata Support
361
+
362
+ The AI SDK provides native support for message metadata through the `messageMetadata` callback. This allows you to attach custom information to messages at the message level.
363
+
364
+ ##### AIChatAgent Integration
365
+
366
+ In the context of `AIChatAgent`, you can use metadata like this:
367
+
368
+ ```typescript
369
+ import { AIChatAgent } from "agents/ai-chat-agent";
370
+ import { streamText } from "ai";
371
+ import { openai } from "@ai-sdk/openai";
372
+
373
+ export class MyAgent extends AIChatAgent<Env> {
374
+ async onChatMessage(onFinish) {
375
+ const startTime = Date.now();
376
+
377
+ const result = streamText({
378
+ model: openai("gpt-4o"),
379
+ messages: this.messages,
380
+ onFinish
381
+ });
382
+
383
+ return result.toUIMessageStreamResponse({
384
+ messageMetadata: ({ part }) => {
385
+ if (part.type === "start") {
386
+ return {
387
+ model: "gpt-4o",
388
+ createdAt: Date.now(),
389
+ messageCount: this.messages.length
390
+ };
391
+ }
392
+ if (part.type === "finish") {
393
+ return {
394
+ responseTime: Date.now() - startTime,
395
+ totalTokens: part.totalUsage?.totalTokens
396
+ };
397
+ }
398
+ }
399
+ });
334
400
  }
335
401
  }
336
402
  ```
337
403
 
404
+ ##### Accessing Metadata on the Client
405
+
406
+ Access metadata through the `message.metadata` property:
407
+
408
+ ```typescript
409
+ 'use client';
410
+
411
+ import { useChat } from '@ai-sdk/react';
412
+ import { DefaultChatTransport } from 'ai';
413
+ import type { MyUIMessage } from '@/types';
414
+
415
+ export default function Chat() {
416
+ const { messages } = useChat<MyUIMessage>({
417
+ transport: new DefaultChatTransport({
418
+ api: '/api/chat',
419
+ }),
420
+ });
421
+
422
+ return (
423
+ <div>
424
+ {messages.map(message => (
425
+ <div key={message.id}>
426
+ <div>
427
+ {message.role === 'user' ? 'User: ' : 'AI: '}
428
+ {message.metadata?.createdAt && (
429
+ <span className="text-sm text-gray-500">
430
+ {new Date(message.metadata.createdAt).toLocaleTimeString()}
431
+ </span>
432
+ )}
433
+ </div>
434
+ {/* Render message content */}
435
+ {message.parts.map((part, index) =>
436
+ part.type === 'text' ? <div key={index}>{part.text}</div> : null,
437
+ )}
438
+ {/* Display additional metadata */}
439
+ {message.metadata?.totalTokens && (
440
+ <div className="text-xs text-gray-400">
441
+ {message.metadata.totalTokens} tokens
442
+ </div>
443
+ )}
444
+ </div>
445
+ ))}
446
+ </div>
447
+ );
448
+ }
449
+ ```
450
+
451
+ For more details, see the [AI SDK Message Metadata documentation](https://ai-sdk.dev/docs/ai-sdk-ui/message-metadata).
452
+
338
453
  #### Creating the Interface
339
454
 
340
455
  Connect with your agent through a React interface:
@@ -363,7 +478,14 @@ function ChatInterface() {
363
478
  {messages.map((message) => (
364
479
  <div key={message.id} className="message">
365
480
  <div className="role">{message.role}</div>
366
- <div className="content">{message.content}</div>
481
+ <div className="content">
482
+ {message.parts.map((part, i) => {
483
+ if (part.type === "text")
484
+ return <span key={i}>{part.text}</span>;
485
+ // Render other part types (e.g., files, tool calls) as desired
486
+ return null;
487
+ })}
488
+ </div>
367
489
  </div>
368
490
  ))}
369
491
  </div>
@@ -427,10 +549,12 @@ export class MyMCP extends McpAgent<Env, State, {}> {
427
549
  };
428
550
  });
429
551
 
430
- this.server.tool(
552
+ this.server.registerTool(
431
553
  "add",
432
- "Add to the counter, stored in the MCP",
433
- { a: z.number() },
554
+ {
555
+ description: "Add to the counter, stored in the MCP",
556
+ inputSchema: { a: z.number() }
557
+ },
434
558
  async ({ a }) => {
435
559
  this.setState({ ...this.state, counter: this.state.counter + a });
436
560
 
@@ -1,20 +1,12 @@
1
- import { UIMessage, StreamTextOnFinishCallback, ToolSet } from "ai";
2
- import { Agent, AgentContext } from "./index.js";
3
- import { Connection, WSMessage } from "partyserver";
4
- import "cloudflare:workers";
5
- import "@modelcontextprotocol/sdk/client/index.js";
6
- import "@modelcontextprotocol/sdk/types.js";
7
- import "./client-B9tFv5gX.js";
8
- import "zod";
9
- import "@modelcontextprotocol/sdk/shared/protocol.js";
10
- import "@modelcontextprotocol/sdk/client/sse.js";
11
- import "@modelcontextprotocol/sdk/client/streamableHttp.js";
12
- import "./mcp/do-oauth-client-provider.js";
13
- import "@modelcontextprotocol/sdk/client/auth.js";
14
- import "@modelcontextprotocol/sdk/shared/auth.js";
15
- import "./observability/index.js";
16
- import "./ai-types.js";
1
+ import "./client-CwqTTb-B.js";
2
+ import "./mcp-BwPscEiF.js";
3
+ import "./do-oauth-client-provider-C2CHH5x-.js";
4
+ import "./index-BUle9RiP.js";
5
+ import "./ai-types-81H_-Uxh.js";
6
+ import { n as AgentContext, t as Agent } from "./index-DJ4vV2-x.js";
7
+ import { StreamTextOnFinishCallback, ToolSet, UIMessage } from "ai";
17
8
 
9
+ //#region src/ai-chat-agent.d.ts
18
10
  /**
19
11
  * Extension of Agent with built-in chat capabilities
20
12
  * @template Env Environment type containing bindings
@@ -28,11 +20,92 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
28
20
  * useful to propagate request cancellation signals for any external calls made by the agent
29
21
  */
30
22
  private _chatMessageAbortControllers;
23
+ /**
24
+ * Currently active stream ID for resumable streaming.
25
+ * Stored in memory for quick access; persisted in stream_metadata table.
26
+ * @internal Protected for testing purposes.
27
+ */
28
+ protected _activeStreamId: string | null;
29
+ /**
30
+ * Request ID associated with the active stream.
31
+ * @internal Protected for testing purposes.
32
+ */
33
+ protected _activeRequestId: string | null;
34
+ /**
35
+ * Current chunk index for the active stream
36
+ */
37
+ private _streamChunkIndex;
38
+ /**
39
+ * Buffer for stream chunks pending write to SQLite.
40
+ * Chunks are batched and flushed when buffer reaches CHUNK_BUFFER_SIZE.
41
+ */
42
+ private _chunkBuffer;
43
+ /**
44
+ * Lock to prevent concurrent flush operations
45
+ */
46
+ private _isFlushingChunks;
47
+ /**
48
+ * Timestamp of the last cleanup operation for old streams
49
+ */
50
+ private _lastCleanupTime;
31
51
  /** Array of chat messages for the current conversation */
32
52
  messages: UIMessage[];
33
53
  constructor(ctx: AgentContext, env: Env);
54
+ /**
55
+ * Restore active stream state if the agent was restarted during streaming.
56
+ * Called during construction to recover any interrupted streams.
57
+ * Validates stream freshness to avoid sending stale resume notifications.
58
+ * @internal Protected for testing purposes.
59
+ */
60
+ protected _restoreActiveStream(): void;
61
+ /**
62
+ * Notify a connection about an active stream that can be resumed.
63
+ * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
64
+ * Uses in-memory state for request ID - no extra DB lookup needed.
65
+ * @param connection - The WebSocket connection to notify
66
+ */
67
+ private _notifyStreamResuming;
68
+ /**
69
+ * Send stream chunks to a connection after receiving ACK.
70
+ * @param connection - The WebSocket connection
71
+ * @param streamId - The stream to replay
72
+ * @param requestId - The original request ID
73
+ */
74
+ private _sendStreamChunks;
75
+ /**
76
+ * Buffer a stream chunk for batch write to SQLite.
77
+ * @param streamId - The stream this chunk belongs to
78
+ * @param body - The serialized chunk body
79
+ * @internal Protected for testing purposes.
80
+ */
81
+ protected _storeStreamChunk(streamId: string, body: string): void;
82
+ /**
83
+ * Flush buffered chunks to SQLite in a single batch.
84
+ * Uses a lock to prevent concurrent flush operations.
85
+ * @internal Protected for testing purposes.
86
+ */
87
+ protected _flushChunkBuffer(): void;
88
+ /**
89
+ * Start tracking a new stream for resumable streaming.
90
+ * Creates metadata entry in SQLite and sets up tracking state.
91
+ * @param requestId - The unique ID of the chat request
92
+ * @returns The generated stream ID
93
+ * @internal Protected for testing purposes.
94
+ */
95
+ protected _startStream(requestId: string): string;
96
+ /**
97
+ * Mark a stream as completed and flush any pending chunks.
98
+ * @param streamId - The stream to mark as completed
99
+ * @internal Protected for testing purposes.
100
+ */
101
+ protected _completeStream(streamId: string): void;
102
+ /**
103
+ * Clean up old completed streams if enough time has passed since last cleanup.
104
+ * This prevents database growth while avoiding cleanup overhead on every stream completion.
105
+ */
106
+ private _maybeCleanupOldStreams;
34
107
  private _broadcastChatMessage;
35
- onMessage(connection: Connection, message: WSMessage): Promise<void>;
108
+ private _loadMessagesFromDb;
36
109
  onRequest(request: Request): Promise<Response>;
37
110
  private _tryCatchChat;
38
111
  /**
@@ -57,6 +130,12 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
57
130
  excludeBroadcastIds?: string[]
58
131
  ): Promise<void>;
59
132
  private _reply;
133
+ /**
134
+ * Mark a stream as errored and clean up state.
135
+ * @param streamId - The stream to mark as errored
136
+ * @internal Protected for testing purposes.
137
+ */
138
+ protected _markStreamError(streamId: string): void;
60
139
  /**
61
140
  * For the given message id, look up its associated AbortController
62
141
  * If the AbortController does not exist, create and store one in memory
@@ -77,9 +156,10 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
77
156
  */
78
157
  private _destroyAbortControllers;
79
158
  /**
80
- * When the DO is destroyed, cancel all pending requests
159
+ * When the DO is destroyed, cancel all pending requests and clean up resources
81
160
  */
82
161
  destroy(): Promise<void>;
83
162
  }
84
-
163
+ //#endregion
85
164
  export { AIChatAgent };
165
+ //# sourceMappingURL=ai-chat-agent.d.ts.map