agents 0.0.0-f5b5854 → 0.0.0-f6c26e4

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