agents 0.0.0-c552d8b → 0.0.0-c5e3a32

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 (47) hide show
  1. package/README.md +22 -22
  2. package/dist/ai-chat-agent.d.ts +32 -5
  3. package/dist/ai-chat-agent.js +149 -115
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +18 -5
  6. package/dist/ai-react.js +28 -29
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/chunk-EDUDXISR.js +1148 -0
  9. package/dist/chunk-EDUDXISR.js.map +1 -0
  10. package/dist/chunk-KUH345EY.js +116 -0
  11. package/dist/chunk-KUH345EY.js.map +1 -0
  12. package/dist/{chunk-Q5ZBHY4Z.js → chunk-MW5BQ2FW.js} +49 -36
  13. package/dist/chunk-MW5BQ2FW.js.map +1 -0
  14. package/dist/chunk-PVQZBKN7.js +106 -0
  15. package/dist/chunk-PVQZBKN7.js.map +1 -0
  16. package/dist/client.d.ts +16 -2
  17. package/dist/client.js +6 -126
  18. package/dist/client.js.map +1 -1
  19. package/dist/index-DukU3sIa.d.ts +571 -0
  20. package/dist/index.d.ts +32 -308
  21. package/dist/index.js +10 -3
  22. package/dist/mcp/client.d.ts +301 -23
  23. package/dist/mcp/client.js +1 -2
  24. package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
  25. package/dist/mcp/do-oauth-client-provider.js +3 -103
  26. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  27. package/dist/mcp/index.d.ts +23 -13
  28. package/dist/mcp/index.js +150 -175
  29. package/dist/mcp/index.js.map +1 -1
  30. package/dist/observability/index.d.ts +12 -0
  31. package/dist/observability/index.js +10 -0
  32. package/dist/react.d.ts +85 -5
  33. package/dist/react.js +20 -8
  34. package/dist/react.js.map +1 -1
  35. package/dist/schedule.d.ts +6 -6
  36. package/dist/schedule.js +4 -6
  37. package/dist/schedule.js.map +1 -1
  38. package/dist/serializable.d.ts +32 -0
  39. package/dist/serializable.js +1 -0
  40. package/dist/serializable.js.map +1 -0
  41. package/package.json +76 -68
  42. package/src/index.ts +926 -136
  43. package/dist/chunk-HMLY7DHA.js +0 -16
  44. package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
  45. package/dist/chunk-WNIGPPNB.js +0 -608
  46. package/dist/chunk-WNIGPPNB.js.map +0 -1
  47. /package/dist/{chunk-HMLY7DHA.js.map → observability/index.js.map} +0 -0
@@ -0,0 +1,571 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ import {
3
+ ServerCapabilities,
4
+ Tool,
5
+ Prompt,
6
+ Resource
7
+ } from "@modelcontextprotocol/sdk/types.js";
8
+ import { Server, Connection, PartyServerOptions } from "partyserver";
9
+ import { MCPClientManager } from "./mcp/client.js";
10
+ import { Message } from "ai";
11
+
12
+ type BaseEvent<
13
+ T extends string,
14
+ Payload extends Record<string, unknown> = {}
15
+ > = {
16
+ type: T;
17
+ /**
18
+ * The unique identifier for the event
19
+ */
20
+ id: string;
21
+ /**
22
+ * The message to display in the logs for this event, should the implementation choose to display
23
+ * a human-readable message.
24
+ */
25
+ displayMessage: string;
26
+ /**
27
+ * The payload of the event
28
+ */
29
+ payload: Payload;
30
+ /**
31
+ * The timestamp of the event in milliseconds since epoch
32
+ */
33
+ timestamp: number;
34
+ };
35
+ /**
36
+ * The type of events that can be emitted by an Agent
37
+ */
38
+ type ObservabilityEvent =
39
+ | BaseEvent<
40
+ "state:update",
41
+ {
42
+ state: unknown;
43
+ previousState: unknown;
44
+ }
45
+ >
46
+ | BaseEvent<
47
+ "rpc",
48
+ {
49
+ method: string;
50
+ args: unknown[];
51
+ streaming?: boolean;
52
+ success: boolean;
53
+ }
54
+ >
55
+ | BaseEvent<
56
+ "message:request" | "message:response",
57
+ {
58
+ message: Message[];
59
+ }
60
+ >
61
+ | BaseEvent<"message:clear">
62
+ | BaseEvent<
63
+ "schedule:create" | "schedule:execute" | "schedule:cancel",
64
+ Schedule<unknown>
65
+ >
66
+ | BaseEvent<"destroy">
67
+ | BaseEvent<
68
+ "connect",
69
+ {
70
+ connectionId: string;
71
+ }
72
+ >;
73
+ interface Observability {
74
+ /**
75
+ * Emit an event for the Agent's observability implementation to handle.
76
+ * @param event - The event to emit
77
+ * @param ctx - The execution context of the invocation
78
+ */
79
+ emit(event: ObservabilityEvent, ctx: DurableObjectState): void;
80
+ }
81
+ /**
82
+ * A generic observability implementation that logs events to the console.
83
+ */
84
+ declare const genericObservability: Observability;
85
+
86
+ /**
87
+ * RPC request message from client
88
+ */
89
+ type RPCRequest = {
90
+ type: "rpc";
91
+ id: string;
92
+ method: string;
93
+ args: unknown[];
94
+ };
95
+ /**
96
+ * State update message from client
97
+ */
98
+ type StateUpdateMessage = {
99
+ type: "cf_agent_state";
100
+ state: unknown;
101
+ };
102
+ /**
103
+ * RPC response message to client
104
+ */
105
+ type RPCResponse = {
106
+ type: "rpc";
107
+ id: string;
108
+ } & (
109
+ | {
110
+ success: true;
111
+ result: unknown;
112
+ done?: false;
113
+ }
114
+ | {
115
+ success: true;
116
+ result: unknown;
117
+ done: true;
118
+ }
119
+ | {
120
+ success: false;
121
+ error: string;
122
+ }
123
+ );
124
+ /**
125
+ * Metadata for a callable method
126
+ */
127
+ type CallableMetadata = {
128
+ /** Optional description of what the method does */
129
+ description?: string;
130
+ /** Whether the method supports streaming responses */
131
+ streaming?: boolean;
132
+ };
133
+ /**
134
+ * Decorator that marks a method as callable by clients
135
+ * @param metadata Optional metadata about the callable method
136
+ */
137
+ declare function unstable_callable(
138
+ metadata?: CallableMetadata
139
+ ): <This, Args extends unknown[], Return>(
140
+ target: (this: This, ...args: Args) => Return,
141
+ context: ClassMethodDecoratorContext
142
+ ) => (this: This, ...args: Args) => Return;
143
+ /**
144
+ * Represents a scheduled task within an Agent
145
+ * @template T Type of the payload data
146
+ */
147
+ type Schedule<T = string> = {
148
+ /** Unique identifier for the schedule */
149
+ id: string;
150
+ /** Name of the method to be called */
151
+ callback: string;
152
+ /** Data to be passed to the callback */
153
+ payload: T;
154
+ } & (
155
+ | {
156
+ /** Type of schedule for one-time execution at a specific time */
157
+ type: "scheduled";
158
+ /** Timestamp when the task should execute */
159
+ time: number;
160
+ }
161
+ | {
162
+ /** Type of schedule for delayed execution */
163
+ type: "delayed";
164
+ /** Timestamp when the task should execute */
165
+ time: number;
166
+ /** Number of seconds to delay execution */
167
+ delayInSeconds: number;
168
+ }
169
+ | {
170
+ /** Type of schedule for recurring execution based on cron expression */
171
+ type: "cron";
172
+ /** Timestamp for the next execution */
173
+ time: number;
174
+ /** Cron expression defining the schedule */
175
+ cron: string;
176
+ }
177
+ );
178
+ /**
179
+ * MCP Server state update message from server -> Client
180
+ */
181
+ type MCPServerMessage = {
182
+ type: "cf_agent_mcp_servers";
183
+ mcp: MCPServersState;
184
+ };
185
+ type MCPServersState = {
186
+ servers: {
187
+ [id: string]: MCPServer;
188
+ };
189
+ tools: Tool[];
190
+ prompts: Prompt[];
191
+ resources: Resource[];
192
+ };
193
+ type MCPServer = {
194
+ name: string;
195
+ server_url: string;
196
+ auth_url: string | null;
197
+ state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
198
+ instructions: string | null;
199
+ capabilities: ServerCapabilities | null;
200
+ };
201
+ declare function getCurrentAgent<
202
+ T extends Agent<unknown, unknown> = Agent<unknown, unknown>
203
+ >(): {
204
+ agent: T | undefined;
205
+ connection: Connection | undefined;
206
+ request: Request | undefined;
207
+ email: AgentEmail | undefined;
208
+ };
209
+ /**
210
+ * Base class for creating Agent implementations
211
+ * @template Env Environment type containing bindings
212
+ * @template State State type to store within the Agent
213
+ */
214
+ declare class Agent<Env, State = unknown> extends Server<Env> {
215
+ private _state;
216
+ private _ParentClass;
217
+ mcp: MCPClientManager;
218
+ /**
219
+ * Initial state for the Agent
220
+ * Override to provide default state values
221
+ */
222
+ initialState: State;
223
+ /**
224
+ * Current state of the Agent
225
+ */
226
+ get state(): State;
227
+ /**
228
+ * Agent configuration options
229
+ */
230
+ static options: {
231
+ /** Whether the Agent should hibernate when inactive */
232
+ hibernate: boolean;
233
+ };
234
+ /**
235
+ * The observability implementation to use for the Agent
236
+ */
237
+ observability?: Observability;
238
+ /**
239
+ * Execute SQL queries against the Agent's database
240
+ * @template T Type of the returned rows
241
+ * @param strings SQL query template strings
242
+ * @param values Values to be inserted into the query
243
+ * @returns Array of query results
244
+ */
245
+ sql<T = Record<string, string | number | boolean | null>>(
246
+ strings: TemplateStringsArray,
247
+ ...values: (string | number | boolean | null)[]
248
+ ): T[];
249
+ constructor(ctx: AgentContext, env: Env);
250
+ private _setStateInternal;
251
+ /**
252
+ * Update the Agent's state
253
+ * @param state New state to set
254
+ */
255
+ setState(state: State): void;
256
+ /**
257
+ * Called when the Agent's state is updated
258
+ * @param state Updated state
259
+ * @param source Source of the state update ("server" or a client connection)
260
+ */
261
+ onStateUpdate(state: State | undefined, source: Connection | "server"): void;
262
+ /**
263
+ * Called when the Agent receives an email via routeAgentEmail()
264
+ * Override this method to handle incoming emails
265
+ * @param email Email message to process
266
+ */
267
+ _onEmail(email: AgentEmail): Promise<void>;
268
+ /**
269
+ * Reply to an email
270
+ * @param email The email to reply to
271
+ * @param options Options for the reply
272
+ * @returns void
273
+ */
274
+ replyToEmail(
275
+ email: AgentEmail,
276
+ options: {
277
+ fromName: string;
278
+ subject?: string | undefined;
279
+ body: string;
280
+ contentType?: string;
281
+ headers?: Record<string, string>;
282
+ }
283
+ ): Promise<void>;
284
+ private _tryCatch;
285
+ /**
286
+ * Automatically wrap custom methods with agent context
287
+ * This ensures getCurrentAgent() works in all custom methods without decorators
288
+ */
289
+ private _autoWrapCustomMethods;
290
+ onError(connection: Connection, error: unknown): void | Promise<void>;
291
+ onError(error: unknown): void | Promise<void>;
292
+ /**
293
+ * Render content (not implemented in base class)
294
+ */
295
+ render(): void;
296
+ /**
297
+ * Schedule a task to be executed in the future
298
+ * @template T Type of the payload data
299
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
300
+ * @param callback Name of the method to call
301
+ * @param payload Data to pass to the callback
302
+ * @returns Schedule object representing the scheduled task
303
+ */
304
+ schedule<T = string>(
305
+ when: Date | string | number,
306
+ callback: keyof this,
307
+ payload?: T
308
+ ): Promise<Schedule<T>>;
309
+ /**
310
+ * Get a scheduled task by ID
311
+ * @template T Type of the payload data
312
+ * @param id ID of the scheduled task
313
+ * @returns The Schedule object or undefined if not found
314
+ */
315
+ getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined>;
316
+ /**
317
+ * Get scheduled tasks matching the given criteria
318
+ * @template T Type of the payload data
319
+ * @param criteria Criteria to filter schedules
320
+ * @returns Array of matching Schedule objects
321
+ */
322
+ getSchedules<T = string>(criteria?: {
323
+ id?: string;
324
+ type?: "scheduled" | "delayed" | "cron";
325
+ timeRange?: {
326
+ start?: Date;
327
+ end?: Date;
328
+ };
329
+ }): Schedule<T>[];
330
+ /**
331
+ * Cancel a scheduled task
332
+ * @param id ID of the task to cancel
333
+ * @returns true if the task was cancelled, false otherwise
334
+ */
335
+ cancelSchedule(id: string): Promise<boolean>;
336
+ private _scheduleNextAlarm;
337
+ /**
338
+ * Method called when an alarm fires.
339
+ * Executes any scheduled tasks that are due.
340
+ *
341
+ * @remarks
342
+ * To schedule a task, please use the `this.schedule` method instead.
343
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
344
+ */
345
+ readonly alarm: () => Promise<void>;
346
+ /**
347
+ * Destroy the Agent, removing all state and scheduled tasks
348
+ */
349
+ destroy(): Promise<void>;
350
+ /**
351
+ * Get all methods marked as callable on this Agent
352
+ * @returns A map of method names to their metadata
353
+ */
354
+ private _isCallable;
355
+ /**
356
+ * Connect to a new MCP Server
357
+ *
358
+ * @param url MCP Server SSE URL
359
+ * @param callbackHost Base host for the agent, used for the redirect URI.
360
+ * @param agentsPrefix agents routing prefix if not using `agents`
361
+ * @param options MCP client and transport (header) options
362
+ * @returns authUrl
363
+ */
364
+ addMcpServer(
365
+ serverName: string,
366
+ url: string,
367
+ callbackHost: string,
368
+ agentsPrefix?: string,
369
+ options?: {
370
+ client?: ConstructorParameters<typeof Client>[1];
371
+ transport?: {
372
+ headers: HeadersInit;
373
+ };
374
+ }
375
+ ): Promise<{
376
+ id: string;
377
+ authUrl: string | undefined;
378
+ }>;
379
+ _connectToMcpServerInternal(
380
+ _serverName: string,
381
+ url: string,
382
+ callbackUrl: string,
383
+ options?: {
384
+ client?: ConstructorParameters<typeof Client>[1];
385
+ /**
386
+ * We don't expose the normal set of transport options because:
387
+ * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
388
+ * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
389
+ *
390
+ * This has the limitation that you can't override fetch, but I think headers should handle nearly all cases needed (i.e. non-standard bearer auth).
391
+ */
392
+ transport?: {
393
+ headers?: HeadersInit;
394
+ };
395
+ },
396
+ reconnect?: {
397
+ id: string;
398
+ oauthClientId?: string;
399
+ }
400
+ ): Promise<{
401
+ id: string;
402
+ authUrl: string | undefined;
403
+ clientId: string | undefined;
404
+ }>;
405
+ removeMcpServer(id: string): Promise<void>;
406
+ getMcpServers(): MCPServersState;
407
+ }
408
+ /**
409
+ * Namespace for creating Agent instances
410
+ * @template Agentic Type of the Agent class
411
+ */
412
+ type AgentNamespace<Agentic extends Agent<unknown>> =
413
+ DurableObjectNamespace<Agentic>;
414
+ /**
415
+ * Agent's durable context
416
+ */
417
+ type AgentContext = DurableObjectState;
418
+ /**
419
+ * Configuration options for Agent routing
420
+ */
421
+ type AgentOptions<Env> = PartyServerOptions<Env> & {
422
+ /**
423
+ * Whether to enable CORS for the Agent
424
+ */
425
+ cors?: boolean | HeadersInit | undefined;
426
+ };
427
+ /**
428
+ * Route a request to the appropriate Agent
429
+ * @param request Request to route
430
+ * @param env Environment containing Agent bindings
431
+ * @param options Routing options
432
+ * @returns Response from the Agent or undefined if no route matched
433
+ */
434
+ declare function routeAgentRequest<Env>(
435
+ request: Request,
436
+ env: Env,
437
+ options?: AgentOptions<Env>
438
+ ): Promise<Response | null>;
439
+ type EmailResolver<Env> = (
440
+ email: ForwardableEmailMessage,
441
+ env: Env
442
+ ) => Promise<{
443
+ agentName: string;
444
+ agentId: string;
445
+ } | null>;
446
+ /**
447
+ * Create a resolver that uses the message-id header to determine the agent to route the email to
448
+ * @returns A function that resolves the agent to route the email to
449
+ */
450
+ declare function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env>;
451
+ /**
452
+ * Create a resolver that uses the email address to determine the agent to route the email to
453
+ * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
454
+ * @returns A function that resolves the agent to route the email to
455
+ */
456
+ declare function createAddressBasedEmailResolver<Env>(
457
+ defaultAgentName: string
458
+ ): EmailResolver<Env>;
459
+ /**
460
+ * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
461
+ * @param agentName The name of the agent to route the email to
462
+ * @param agentId The id of the agent to route the email to
463
+ * @returns A function that resolves the agent to route the email to
464
+ */
465
+ declare function createCatchAllEmailResolver<Env>(
466
+ agentName: string,
467
+ agentId: string
468
+ ): EmailResolver<Env>;
469
+ type EmailRoutingOptions<Env> = AgentOptions<Env> & {
470
+ resolver: EmailResolver<Env>;
471
+ };
472
+ /**
473
+ * Route an email to the appropriate Agent
474
+ * @param email The email to route
475
+ * @param env The environment containing the Agent bindings
476
+ * @param options The options for routing the email
477
+ * @returns A promise that resolves when the email has been routed
478
+ */
479
+ declare function routeAgentEmail<Env>(
480
+ email: ForwardableEmailMessage,
481
+ env: Env,
482
+ options: EmailRoutingOptions<Env>
483
+ ): Promise<void>;
484
+ type AgentEmail = {
485
+ from: string;
486
+ to: string;
487
+ getRaw: () => Promise<Uint8Array>;
488
+ headers: Headers;
489
+ rawSize: number;
490
+ setReject: (reason: string) => void;
491
+ forward: (rcptTo: string, headers?: Headers) => Promise<void>;
492
+ reply: (options: { from: string; to: string; raw: string }) => Promise<void>;
493
+ };
494
+ type EmailSendOptions = {
495
+ to: string;
496
+ subject: string;
497
+ body: string;
498
+ contentType?: string;
499
+ headers?: Record<string, string>;
500
+ includeRoutingHeaders?: boolean;
501
+ agentName?: string;
502
+ agentId?: string;
503
+ domain?: string;
504
+ };
505
+ /**
506
+ * Get or create an Agent by name
507
+ * @template Env Environment type containing bindings
508
+ * @template T Type of the Agent class
509
+ * @param namespace Agent namespace
510
+ * @param name Name of the Agent instance
511
+ * @param options Options for Agent creation
512
+ * @returns Promise resolving to an Agent instance stub
513
+ */
514
+ declare function getAgentByName<Env, T extends Agent<Env>>(
515
+ namespace: AgentNamespace<T>,
516
+ name: string,
517
+ options?: {
518
+ jurisdiction?: DurableObjectJurisdiction;
519
+ locationHint?: DurableObjectLocationHint;
520
+ }
521
+ ): Promise<DurableObjectStub<T>>;
522
+ /**
523
+ * A wrapper for streaming responses in callable methods
524
+ */
525
+ declare class StreamingResponse {
526
+ private _connection;
527
+ private _id;
528
+ private _closed;
529
+ constructor(connection: Connection, id: string);
530
+ /**
531
+ * Send a chunk of data to the client
532
+ * @param chunk The data to send
533
+ */
534
+ send(chunk: unknown): void;
535
+ /**
536
+ * End the stream and send the final chunk (if any)
537
+ * @param finalChunk Optional final chunk of data to send
538
+ */
539
+ end(finalChunk?: unknown): void;
540
+ }
541
+
542
+ export {
543
+ Agent as A,
544
+ type CallableMetadata as C,
545
+ type EmailResolver as E,
546
+ type MCPServersState as M,
547
+ type ObservabilityEvent as O,
548
+ type RPCRequest as R,
549
+ type StateUpdateMessage as S,
550
+ type AgentContext as a,
551
+ type Observability as b,
552
+ type RPCResponse as c,
553
+ type Schedule as d,
554
+ type MCPServerMessage as e,
555
+ type MCPServer as f,
556
+ genericObservability as g,
557
+ getCurrentAgent as h,
558
+ type AgentNamespace as i,
559
+ type AgentOptions as j,
560
+ createHeaderBasedEmailResolver as k,
561
+ createAddressBasedEmailResolver as l,
562
+ createCatchAllEmailResolver as m,
563
+ type EmailRoutingOptions as n,
564
+ routeAgentEmail as o,
565
+ type AgentEmail as p,
566
+ type EmailSendOptions as q,
567
+ routeAgentRequest as r,
568
+ getAgentByName as s,
569
+ StreamingResponse as t,
570
+ unstable_callable as u
571
+ };