agents 0.0.0-e48e5f9 → 0.0.0-e6dd636

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 (82) hide show
  1. package/README.md +357 -6
  2. package/dist/ai-chat-agent.d.ts +238 -29
  3. package/dist/ai-chat-agent.js +1118 -260
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration.d.ts +155 -0
  6. package/dist/ai-chat-v5-migration.js +155 -0
  7. package/dist/ai-chat-v5-migration.js.map +1 -0
  8. package/dist/ai-react.d.ts +197 -84
  9. package/dist/ai-react.js +574 -199
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/ai-types-0OnT3FHg.d.ts +127 -0
  12. package/dist/ai-types-DEtF_8Km.js +28 -0
  13. package/dist/ai-types-DEtF_8Km.js.map +1 -0
  14. package/dist/ai-types.d.ts +6 -74
  15. package/dist/ai-types.js +3 -1
  16. package/dist/cli/index.d.ts +1 -0
  17. package/dist/cli/index.js +28 -0
  18. package/dist/cli/index.js.map +1 -0
  19. package/dist/client-BINtT7y-.d.ts +834 -0
  20. package/dist/client-CdM5I962.d.ts +104 -0
  21. package/dist/client-DjTPRM8-.js +117 -0
  22. package/dist/client-DjTPRM8-.js.map +1 -0
  23. package/dist/client-QZa2Rq0l.js +1105 -0
  24. package/dist/client-QZa2Rq0l.js.map +1 -0
  25. package/dist/client.d.ts +10 -92
  26. package/dist/client.js +3 -11
  27. package/dist/codemode/ai.d.ts +27 -0
  28. package/dist/codemode/ai.js +151 -0
  29. package/dist/codemode/ai.js.map +1 -0
  30. package/dist/context-BkKbAa1R.js +8 -0
  31. package/dist/context-BkKbAa1R.js.map +1 -0
  32. package/dist/context-DcbQ8o7k.d.ts +24 -0
  33. package/dist/context.d.ts +6 -0
  34. package/dist/context.js +3 -0
  35. package/dist/do-oauth-client-provider--To1Tsjj.d.ts +70 -0
  36. package/dist/do-oauth-client-provider-B1fVIshX.js +155 -0
  37. package/dist/do-oauth-client-provider-B1fVIshX.js.map +1 -0
  38. package/dist/{index-BIJvkfYt.d.ts → index-CxZRDFxS.d.ts} +133 -170
  39. package/dist/index-DLuxm_9W.d.ts +58 -0
  40. package/dist/index.d.ts +66 -38
  41. package/dist/index.js +7 -28
  42. package/dist/mcp/client.d.ts +2 -1055
  43. package/dist/mcp/client.js +4 -9
  44. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  45. package/dist/mcp/do-oauth-client-provider.js +3 -7
  46. package/dist/mcp/index.d.ts +197 -81
  47. package/dist/mcp/index.js +1429 -770
  48. package/dist/mcp/index.js.map +1 -1
  49. package/dist/mcp/x402.d.ts +34 -0
  50. package/dist/mcp/x402.js +198 -0
  51. package/dist/mcp/x402.js.map +1 -0
  52. package/dist/mcp-CPSfGUgd.d.ts +61 -0
  53. package/dist/observability/index.d.ts +2 -12
  54. package/dist/observability/index.js +7 -10
  55. package/dist/react.d.ts +48 -33
  56. package/dist/react.js +183 -110
  57. package/dist/react.js.map +1 -1
  58. package/dist/schedule.d.ts +61 -38
  59. package/dist/schedule.js +46 -21
  60. package/dist/schedule.js.map +1 -1
  61. package/dist/serializable-Crsj26mx.d.ts +39 -0
  62. package/dist/serializable.d.ts +7 -32
  63. package/dist/serializable.js +1 -1
  64. package/dist/src-BZDh910Z.js +1181 -0
  65. package/dist/src-BZDh910Z.js.map +1 -0
  66. package/package.json +93 -29
  67. package/dist/ai-types.js.map +0 -1
  68. package/dist/chunk-5YIRLLUX.js +0 -1264
  69. package/dist/chunk-5YIRLLUX.js.map +0 -1
  70. package/dist/chunk-KUH345EY.js +0 -116
  71. package/dist/chunk-KUH345EY.js.map +0 -1
  72. package/dist/chunk-MW5BQ2FW.js +0 -469
  73. package/dist/chunk-MW5BQ2FW.js.map +0 -1
  74. package/dist/chunk-PVQZBKN7.js +0 -106
  75. package/dist/chunk-PVQZBKN7.js.map +0 -1
  76. package/dist/client.js.map +0 -1
  77. package/dist/index.js.map +0 -1
  78. package/dist/mcp/client.js.map +0 -1
  79. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  80. package/dist/observability/index.js.map +0 -1
  81. package/dist/serializable.js.map +0 -1
  82. package/src/index.ts +0 -1878
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
 
@@ -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
 
@@ -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
+ // });
334
356
  }
335
357
  }
336
358
  ```
337
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
+ });
400
+ }
401
+ }
402
+ ```
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>
@@ -393,6 +515,235 @@ This creates:
393
515
  - Intuitive input handling
394
516
  - Easy conversation reset
395
517
 
518
+ #### Client-Defined Tools
519
+
520
+ For scenarios where each client needs to register its own tools dynamically (e.g., embeddable chat widgets), use the `tools` option with `execute` functions.
521
+
522
+ Tools with an `execute` function are automatically:
523
+
524
+ 1. Sent to the server as schemas with each request
525
+ 2. Executed on the client when the AI model calls them
526
+
527
+ ##### Client-Side Tool Definition
528
+
529
+ ```tsx
530
+ import { useAgent } from "agents/react";
531
+ import { useAgentChat, type AITool } from "agents/ai-react";
532
+
533
+ // Define tools outside component to avoid recreation on every render
534
+ const tools: Record<string, AITool> = {
535
+ showAlert: {
536
+ description: "Shows an alert dialog to the user",
537
+ parameters: {
538
+ type: "object",
539
+ properties: { message: { type: "string" } },
540
+ required: ["message"]
541
+ },
542
+ execute: async (input) => {
543
+ const { message } = input as { message: string };
544
+ alert(message);
545
+ return { success: true };
546
+ }
547
+ },
548
+ changeBackgroundColor: {
549
+ description: "Changes the page background color",
550
+ parameters: {
551
+ type: "object",
552
+ properties: { color: { type: "string" } }
553
+ },
554
+ execute: async (input) => {
555
+ const { color } = input as { color: string };
556
+ document.body.style.backgroundColor = color;
557
+ return { success: true, color };
558
+ }
559
+ }
560
+ };
561
+
562
+ function EmbeddableChat() {
563
+ const agent = useAgent({ agent: "chat-widget" });
564
+
565
+ const { messages, input, handleInputChange, handleSubmit } = useAgentChat({
566
+ agent,
567
+ tools // Schema + execute in one place
568
+ });
569
+
570
+ return (
571
+ <div className="chat-widget">
572
+ {messages.map((message) => (
573
+ <div key={message.id}>{/* Render message */}</div>
574
+ ))}
575
+ <form onSubmit={handleSubmit}>
576
+ <input value={input} onChange={handleInputChange} />
577
+ </form>
578
+ </div>
579
+ );
580
+ }
581
+ ```
582
+
583
+ ##### Server-Side Tool Handling
584
+
585
+ On the server, use `createToolsFromClientSchemas` to convert client tool schemas to AI SDK format:
586
+
587
+ ```typescript
588
+ import {
589
+ AIChatAgent,
590
+ createToolsFromClientSchemas
591
+ } from "agents/ai-chat-agent";
592
+ import { openai } from "@ai-sdk/openai";
593
+ import { streamText, convertToModelMessages } from "ai";
594
+
595
+ export class ChatWidget extends AIChatAgent {
596
+ async onChatMessage(onFinish, options) {
597
+ const result = streamText({
598
+ model: openai("gpt-4o"),
599
+ messages: convertToModelMessages(this.messages),
600
+ tools: {
601
+ // Server-side tools (execute on server)
602
+ getWeather: tool({
603
+ description: "Get weather for a city",
604
+ parameters: z.object({ city: z.string() }),
605
+ execute: async ({ city }) => fetchWeather(city)
606
+ }),
607
+ // Client-side tools (sent back to client for execution)
608
+ ...createToolsFromClientSchemas(options?.clientTools)
609
+ },
610
+ onFinish
611
+ });
612
+ return result.toUIMessageStreamResponse();
613
+ }
614
+ }
615
+ ```
616
+
617
+ ##### Advanced: Custom Request Data
618
+
619
+ For additional control (custom headers, dynamic context), use `prepareSendMessagesRequest`:
620
+
621
+ ```tsx
622
+ const { messages, handleSubmit } = useAgentChat({
623
+ agent,
624
+ tools, // Tool schemas auto-extracted and sent
625
+ prepareSendMessagesRequest: ({ id, messages }) => ({
626
+ body: {
627
+ // Add dynamic context alongside auto-extracted tool schemas
628
+ currentUrl: window.location.href,
629
+ userTimezone: Intl.DateTimeFormat().resolvedOptions().timeZone
630
+ },
631
+ headers: {
632
+ "X-Widget-Version": "1.0.0",
633
+ "X-Request-ID": crypto.randomUUID()
634
+ }
635
+ })
636
+ });
637
+ ```
638
+
639
+ ### 🔗 MCP (Model Context Protocol) Integration
640
+
641
+ 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).
642
+
643
+ #### Creating an MCP Server
644
+
645
+ ```typescript
646
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
647
+ import { McpAgent } from "agents/mcp";
648
+ import { z } from "zod";
649
+
650
+ type Env = {
651
+ MyMCP: DurableObjectNamespace<MyMCP>;
652
+ };
653
+
654
+ type State = { counter: number };
655
+
656
+ export class MyMCP extends McpAgent<Env, State, {}> {
657
+ server = new McpServer({
658
+ name: "Demo",
659
+ version: "1.0.0"
660
+ });
661
+
662
+ initialState: State = {
663
+ counter: 1
664
+ };
665
+
666
+ async init() {
667
+ this.server.resource("counter", "mcp://resource/counter", (uri) => {
668
+ return {
669
+ contents: [{ text: String(this.state.counter), uri: uri.href }]
670
+ };
671
+ });
672
+
673
+ this.server.registerTool(
674
+ "add",
675
+ {
676
+ description: "Add to the counter, stored in the MCP",
677
+ inputSchema: { a: z.number() }
678
+ },
679
+ async ({ a }) => {
680
+ this.setState({ ...this.state, counter: this.state.counter + a });
681
+
682
+ return {
683
+ content: [
684
+ {
685
+ text: String(`Added ${a}, total is now ${this.state.counter}`),
686
+ type: "text"
687
+ }
688
+ ]
689
+ };
690
+ }
691
+ );
692
+ }
693
+
694
+ onStateUpdate(state: State) {
695
+ console.log({ stateUpdate: state });
696
+ }
697
+ }
698
+
699
+ // HTTP Streamable transport (recommended)
700
+ export default MyMCP.serve("/mcp", {
701
+ binding: "MyMCP"
702
+ });
703
+
704
+ // Or SSE transport for legacy compatibility
705
+ // export default MyMCP.serveSSE("/mcp", { binding: "MyMCP" });
706
+ ```
707
+
708
+ #### Using MCP Tools
709
+
710
+ ```typescript
711
+ import { MCPClientManager } from "agents/mcp";
712
+
713
+ const client = new MCPClientManager("my-app", "1.0.0");
714
+
715
+ // Connect to an MCP server
716
+ await client.connect("https://weather-service.com/mcp", {
717
+ transport: { type: "streamable-http" }
718
+ });
719
+
720
+ // Use tools from the server
721
+ const weather = await client.callTool({
722
+ serverId: "weather-service",
723
+ name: "getWeather",
724
+ arguments: { location: "San Francisco" }
725
+ });
726
+ ```
727
+
728
+ #### AI SDK Integration
729
+
730
+ ```typescript
731
+ import { generateText } from "ai";
732
+
733
+ // Convert MCP tools for AI use
734
+ const result = await generateText({
735
+ model: openai("gpt-4"),
736
+ tools: client.getAITools(),
737
+ prompt: "What's the weather in Tokyo?"
738
+ });
739
+ ```
740
+
741
+ **Transport Options:**
742
+
743
+ - **Auto**: Automatically determine the correct transport
744
+ - **HTTP Streamable**: Best performance, batch requests, session management
745
+ - **SSE**: Simple setup, legacy compatibility
746
+
396
747
  ### 💬 The Path Forward
397
748
 
398
749
  We're developing new dimensions of agent capability:
@@ -418,8 +769,8 @@ Welcome to the future of intelligent agents. Create something meaningful. 🌟
418
769
  Contributions are welcome, but are especially welcome when:
419
770
 
420
771
  - 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.
772
+ - 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.
773
+ - 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
774
 
424
775
  Small fixes, type bugs, and documentation improvements can be raised directly as PRs.
425
776