agents 0.0.111 → 0.0.113

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