agents 0.0.0-fe9e8d3 → 0.0.0-ff431ff

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 (75) hide show
  1. package/README.md +255 -27
  2. package/dist/ai-chat-agent.d.ts +47 -18
  3. package/dist/ai-chat-agent.js +532 -226
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-DBHGW4Hv.js +155 -0
  6. package/dist/ai-chat-v5-migration-DBHGW4Hv.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +73 -72
  10. package/dist/ai-react.js +261 -200
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-B3aQaFv3.js +20 -0
  13. package/dist/ai-types-B3aQaFv3.js.map +1 -0
  14. package/dist/ai-types-D5YoPrBZ.d.ts +95 -0
  15. package/dist/ai-types.d.ts +6 -74
  16. package/dist/ai-types.js +3 -1
  17. package/dist/cli.d.ts +8 -0
  18. package/dist/cli.js +27 -0
  19. package/dist/cli.js.map +1 -0
  20. package/dist/client-BfiZ3HQd.js +117 -0
  21. package/dist/client-BfiZ3HQd.js.map +1 -0
  22. package/dist/client-CbWe9FBd.d.ts +104 -0
  23. package/dist/client-DbS2uI6p.d.ts +5315 -0
  24. package/dist/client-JMskg2fw.js +793 -0
  25. package/dist/client-JMskg2fw.js.map +1 -0
  26. package/dist/client.d.ts +12 -79
  27. package/dist/client.js +3 -130
  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-CswoD5Lu.js +93 -0
  32. package/dist/do-oauth-client-provider-CswoD5Lu.js.map +1 -0
  33. package/dist/do-oauth-client-provider-DGc5pP0l.d.ts +55 -0
  34. package/dist/index-DhJCaDWd.d.ts +58 -0
  35. package/dist/index-DxXJbYBM.d.ts +560 -0
  36. package/dist/index.d.ts +62 -306
  37. package/dist/index.js +7 -21
  38. package/dist/mcp/client.d.ts +4 -777
  39. package/dist/mcp/client.js +3 -10
  40. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  41. package/dist/mcp/do-oauth-client-provider.js +2 -106
  42. package/dist/mcp/index.d.ts +151 -71
  43. package/dist/mcp/index.js +1359 -797
  44. package/dist/mcp/index.js.map +1 -1
  45. package/dist/mcp/x402.d.ts +34 -0
  46. package/dist/mcp/x402.js +194 -0
  47. package/dist/mcp/x402.js.map +1 -0
  48. package/dist/mcp-Dw5vDrY8.d.ts +61 -0
  49. package/dist/observability/index.d.ts +3 -0
  50. package/dist/observability/index.js +7 -0
  51. package/dist/react-BIh615qN.d.ts +115 -0
  52. package/dist/react.d.ts +10 -39
  53. package/dist/react.js +183 -98
  54. package/dist/react.js.map +1 -1
  55. package/dist/schedule.d.ts +89 -12
  56. package/dist/schedule.js +46 -23
  57. package/dist/schedule.js.map +1 -1
  58. package/dist/serializable-CymX8ovI.d.ts +39 -0
  59. package/dist/serializable.d.ts +7 -0
  60. package/dist/serializable.js +1 -0
  61. package/dist/src-nFNV3Ttx.js +1216 -0
  62. package/dist/src-nFNV3Ttx.js.map +1 -0
  63. package/package.json +115 -66
  64. package/dist/ai-types.js.map +0 -1
  65. package/dist/chunk-HD4VEHBA.js +0 -608
  66. package/dist/chunk-HD4VEHBA.js.map +0 -1
  67. package/dist/chunk-HMLY7DHA.js +0 -16
  68. package/dist/chunk-HMLY7DHA.js.map +0 -1
  69. package/dist/chunk-Q5ZBHY4Z.js +0 -456
  70. package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
  71. package/dist/client.js.map +0 -1
  72. package/dist/index.js.map +0 -1
  73. package/dist/mcp/client.js.map +0 -1
  74. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  75. package/src/index.ts +0 -942
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
 
@@ -66,13 +66,13 @@ export class AIAgent extends Agent {
66
66
  async onRequest(request) {
67
67
  // Connect with AI capabilities
68
68
  const ai = new OpenAI({
69
- apiKey: this.env.OPENAI_API_KEY,
69
+ apiKey: this.env.OPENAI_API_KEY
70
70
  });
71
71
 
72
72
  // Process and understand
73
73
  const response = await ai.chat.completions.create({
74
74
  model: "gpt-4",
75
- messages: [{ role: "user", content: await request.text() }],
75
+ messages: [{ role: "user", content: await request.text() }]
76
76
  });
77
77
 
78
78
  return new Response(response.choices[0].message.content);
@@ -96,17 +96,17 @@ Define your agent's domain:
96
96
  "bindings": [
97
97
  {
98
98
  "name": "AIAgent",
99
- "class_name": "AIAgent",
100
- },
101
- ],
99
+ "class_name": "AIAgent"
100
+ }
101
+ ]
102
102
  },
103
103
  "migrations": [
104
104
  {
105
105
  "tag": "v1",
106
106
  // Mandatory for the Agent to store state
107
- "new_sqlite_classes": ["AIAgent"],
108
- },
109
- ],
107
+ "new_sqlite_classes": ["AIAgent"]
108
+ }
109
+ ]
110
110
  }
111
111
  ```
112
112
 
@@ -123,7 +123,7 @@ const agent = env.AIAgent.get(id);
123
123
  await agent.processTask({
124
124
  type: "analysis",
125
125
  context: "incoming_data",
126
- parameters: initialConfig,
126
+ parameters: initialConfig
127
127
  });
128
128
 
129
129
  // Or reconnect with an existing one
@@ -143,7 +143,7 @@ export class APIAgent extends Agent {
143
143
 
144
144
  return Response.json({
145
145
  insight: await this.process(data),
146
- moment: Date.now(),
146
+ moment: Date.now()
147
147
  });
148
148
  }
149
149
  }
@@ -166,7 +166,7 @@ export class DialogueAgent extends Agent {
166
166
  }
167
167
  ```
168
168
 
169
- #### Client Communion
169
+ #### Client Communication
170
170
 
171
171
  For direct connection to your agent:
172
172
 
@@ -175,7 +175,7 @@ import { AgentClient } from "agents/client";
175
175
 
176
176
  const connection = new AgentClient({
177
177
  agent: "dialogue-agent",
178
- name: "insight-seeker",
178
+ name: "insight-seeker"
179
179
  });
180
180
 
181
181
  connection.addEventListener("message", (event) => {
@@ -185,7 +185,7 @@ connection.addEventListener("message", (event) => {
185
185
  connection.send(
186
186
  JSON.stringify({
187
187
  type: "inquiry",
188
- content: "What patterns do you see?",
188
+ content: "What patterns do you see?"
189
189
  })
190
190
  );
191
191
  ```
@@ -205,14 +205,14 @@ function AgentInterface() {
205
205
  console.log("Understanding received:", message.data);
206
206
  },
207
207
  onOpen: () => console.log("Connection established"),
208
- onClose: () => console.log("Connection closed"),
208
+ onClose: () => console.log("Connection closed")
209
209
  });
210
210
 
211
211
  const inquire = () => {
212
212
  connection.send(
213
213
  JSON.stringify({
214
214
  type: "inquiry",
215
- content: "What insights have you gathered?",
215
+ content: "What insights have you gathered?"
216
216
  })
217
217
  );
218
218
  };
@@ -235,14 +235,14 @@ export class ThinkingAgent extends Agent {
235
235
  this.setState({
236
236
  ...this.state,
237
237
  insights: [...(this.state.insights || []), newInsight],
238
- understanding: this.state.understanding + 1,
238
+ understanding: this.state.understanding + 1
239
239
  });
240
240
  }
241
241
 
242
242
  onStateUpdate(state, source) {
243
243
  console.log("Understanding deepened:", {
244
244
  newState: state,
245
- origin: source,
245
+ origin: source
246
246
  });
247
247
  }
248
248
  }
@@ -259,7 +259,7 @@ function StateInterface() {
259
259
 
260
260
  const agent = useAgent({
261
261
  agent: "thinking-agent",
262
- onStateUpdate: (newState) => setState(newState),
262
+ onStateUpdate: (newState) => setState(newState)
263
263
  });
264
264
 
265
265
  const increment = () => {
@@ -289,7 +289,7 @@ export class TimeAwareAgent extends Agent {
289
289
 
290
290
  // Daily synthesis
291
291
  this.schedule("0 0 * * *", "dailySynthesis", {
292
- depth: "comprehensive",
292
+ depth: "comprehensive"
293
293
  });
294
294
 
295
295
  // Milestone review
@@ -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
+ }
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
+ }
333
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:
@@ -346,14 +461,14 @@ import { useAgentChat } from "agents/ai-react";
346
461
  function ChatInterface() {
347
462
  // Connect to the agent
348
463
  const agent = useAgent({
349
- agent: "dialogue-agent",
464
+ agent: "dialogue-agent"
350
465
  });
351
466
 
352
467
  // Set up the chat interaction
353
468
  const { messages, input, handleInputChange, handleSubmit, clearHistory } =
354
469
  useAgentChat({
355
470
  agent,
356
- maxSteps: 5,
471
+ maxSteps: 5
357
472
  });
358
473
 
359
474
  return (
@@ -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>
@@ -393,6 +515,112 @@ This creates:
393
515
  - Intuitive input handling
394
516
  - Easy conversation reset
395
517
 
518
+ ### 🔗 MCP (Model Context Protocol) Integration
519
+
520
+ Agents can seamlessly integrate with the Model Context Protocol, allowing them to act as both MCP servers (providing tools to AI assistants) and MCP clients (using tools from other services).
521
+
522
+ #### Creating an MCP Server
523
+
524
+ ```typescript
525
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
526
+ import { McpAgent } from "agents/mcp";
527
+ import { z } from "zod";
528
+
529
+ type Env = {
530
+ MyMCP: DurableObjectNamespace<MyMCP>;
531
+ };
532
+
533
+ type State = { counter: number };
534
+
535
+ export class MyMCP extends McpAgent<Env, State, {}> {
536
+ server = new McpServer({
537
+ name: "Demo",
538
+ version: "1.0.0"
539
+ });
540
+
541
+ initialState: State = {
542
+ counter: 1
543
+ };
544
+
545
+ async init() {
546
+ this.server.resource("counter", "mcp://resource/counter", (uri) => {
547
+ return {
548
+ contents: [{ text: String(this.state.counter), uri: uri.href }]
549
+ };
550
+ });
551
+
552
+ this.server.tool(
553
+ "add",
554
+ "Add to the counter, stored in the MCP",
555
+ { a: z.number() },
556
+ async ({ a }) => {
557
+ this.setState({ ...this.state, counter: this.state.counter + a });
558
+
559
+ return {
560
+ content: [
561
+ {
562
+ text: String(`Added ${a}, total is now ${this.state.counter}`),
563
+ type: "text"
564
+ }
565
+ ]
566
+ };
567
+ }
568
+ );
569
+ }
570
+
571
+ onStateUpdate(state: State) {
572
+ console.log({ stateUpdate: state });
573
+ }
574
+ }
575
+
576
+ // HTTP Streamable transport (recommended)
577
+ export default MyMCP.serve("/mcp", {
578
+ binding: "MyMCP"
579
+ });
580
+
581
+ // Or SSE transport for legacy compatibility
582
+ // export default MyMCP.serveSSE("/mcp", { binding: "MyMCP" });
583
+ ```
584
+
585
+ #### Using MCP Tools
586
+
587
+ ```typescript
588
+ import { MCPClientManager } from "agents/mcp";
589
+
590
+ const client = new MCPClientManager("my-app", "1.0.0");
591
+
592
+ // Connect to an MCP server
593
+ await client.connect("https://weather-service.com/mcp", {
594
+ transport: { type: "streamable-http" }
595
+ });
596
+
597
+ // Use tools from the server
598
+ const weather = await client.callTool({
599
+ serverId: "weather-service",
600
+ name: "getWeather",
601
+ arguments: { location: "San Francisco" }
602
+ });
603
+ ```
604
+
605
+ #### AI SDK Integration
606
+
607
+ ```typescript
608
+ import { generateText } from "ai";
609
+
610
+ // Convert MCP tools for AI use
611
+ const result = await generateText({
612
+ model: openai("gpt-4"),
613
+ tools: client.getAITools(),
614
+ prompt: "What's the weather in Tokyo?"
615
+ });
616
+ ```
617
+
618
+ **Transport Options:**
619
+
620
+ - **Auto**: Automatically determine the correct transport
621
+ - **HTTP Streamable**: Best performance, batch requests, session management
622
+ - **SSE**: Simple setup, legacy compatibility
623
+
396
624
  ### 💬 The Path Forward
397
625
 
398
626
  We're developing new dimensions of agent capability:
@@ -418,8 +646,8 @@ Welcome to the future of intelligent agents. Create something meaningful. 🌟
418
646
  Contributions are welcome, but are especially welcome when:
419
647
 
420
648
  - You have opened an issue as a Request for Comment (RFC) to discuss your proposal, show your thinking, and iterate together.
421
- - Is not "AI slop": LLMs are powerful tools, but contributions entirely authored by vibe coding are unlikely to meet the quality bar, and will be rejected.
422
- - You're willing to accept feedback and make sure the changes fit the goals of the `agents` sdk. Not everything will, and that's OK.
649
+ - Not "AI slop": LLMs are powerful tools, but contributions entirely authored by vibe coding are unlikely to meet the quality bar, and will be rejected.
650
+ - You're willing to accept feedback and make sure the changes fit the goals of the `agents` SDK. Not everything will, and that's OK.
423
651
 
424
652
  Small fixes, type bugs, and documentation improvements can be raised directly as PRs.
425
653
 
@@ -1,16 +1,17 @@
1
- import { Agent, AgentContext } from "./index.js";
2
- import { Message, StreamTextOnFinishCallback, ToolSet } from "ai";
3
- import { Connection, WSMessage } from "partyserver";
4
- import "./mcp/client.js";
5
- import "zod";
6
- import "@modelcontextprotocol/sdk/types.js";
7
- import "@modelcontextprotocol/sdk/client/index.js";
8
- import "@modelcontextprotocol/sdk/client/sse.js";
9
- import "./mcp/do-oauth-client-provider.js";
10
- import "@modelcontextprotocol/sdk/client/auth.js";
11
- import "@modelcontextprotocol/sdk/shared/auth.js";
12
- import "@modelcontextprotocol/sdk/shared/protocol.js";
1
+ import "./client-DbS2uI6p.js";
2
+ import "./mcp-Dw5vDrY8.js";
3
+ import "./do-oauth-client-provider-DGc5pP0l.js";
4
+ import "./index-DhJCaDWd.js";
5
+ import "./ai-types-D5YoPrBZ.js";
6
+ import {
7
+ n as AgentContext,
8
+ s as Connection,
9
+ t as Agent,
10
+ x as WSMessage
11
+ } from "./index-DxXJbYBM.js";
12
+ import { StreamTextOnFinishCallback, ToolSet, UIMessage } from "ai";
13
13
 
14
+ //#region src/ai-chat-agent.d.ts
14
15
  /**
15
16
  * Extension of Agent with built-in chat capabilities
16
17
  * @template Env Environment type containing bindings
@@ -19,12 +20,19 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
19
20
  Env,
20
21
  State
21
22
  > {
22
- #private;
23
+ /**
24
+ * Map of message `id`s to `AbortController`s
25
+ * useful to propagate request cancellation signals for any external calls made by the agent
26
+ */
27
+ private _chatMessageAbortControllers;
23
28
  /** Array of chat messages for the current conversation */
24
- messages: Message[];
29
+ messages: UIMessage[];
25
30
  constructor(ctx: AgentContext, env: Env);
31
+ private _broadcastChatMessage;
32
+ private _loadMessagesFromDb;
26
33
  onMessage(connection: Connection, message: WSMessage): Promise<void>;
27
34
  onRequest(request: Request): Promise<Response>;
35
+ private _tryCatchChat;
28
36
  /**
29
37
  * Handle incoming chat messages and generate a response
30
38
  * @param onFinish Callback to be called when the response is finished
@@ -38,18 +46,39 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
38
46
  }
39
47
  ): Promise<Response | undefined>;
40
48
  /**
41
- * Save messages on the server side and trigger AI response
49
+ * Save messages on the server side
42
50
  * @param messages Chat messages to save
43
51
  */
44
- saveMessages(messages: Message[]): Promise<void>;
52
+ saveMessages(messages: UIMessage[]): Promise<void>;
45
53
  persistMessages(
46
- messages: Message[],
54
+ messages: UIMessage[],
47
55
  excludeBroadcastIds?: string[]
48
56
  ): Promise<void>;
57
+ private _reply;
58
+ /**
59
+ * For the given message id, look up its associated AbortController
60
+ * If the AbortController does not exist, create and store one in memory
61
+ *
62
+ * returns the AbortSignal associated with the AbortController
63
+ */
64
+ private _getAbortSignal;
65
+ /**
66
+ * Remove an abort controller from the cache of pending message responses
67
+ */
68
+ private _removeAbortController;
69
+ /**
70
+ * Propagate an abort signal for any requests associated with the given message id
71
+ */
72
+ private _cancelChatRequest;
73
+ /**
74
+ * Abort all pending requests and clear the cache of AbortControllers
75
+ */
76
+ private _destroyAbortControllers;
49
77
  /**
50
78
  * When the DO is destroyed, cancel all pending requests
51
79
  */
52
80
  destroy(): Promise<void>;
53
81
  }
54
-
82
+ //#endregion
55
83
  export { AIChatAgent };
84
+ //# sourceMappingURL=ai-chat-agent.d.ts.map