agents 0.0.0-cac66b8 → 0.0.0-ccbea72

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 +20 -17
  3. package/dist/ai-chat-agent.js +532 -222
  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 -85
  10. package/dist/ai-react.js +261 -199
  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/client-9Ld2_lnt.js +786 -0
  18. package/dist/client-9Ld2_lnt.js.map +1 -0
  19. package/dist/client-BfiZ3HQd.js +117 -0
  20. package/dist/client-BfiZ3HQd.js.map +1 -0
  21. package/dist/client-BmMRlvlM.d.ts +5313 -0
  22. package/dist/client-CbWe9FBd.d.ts +104 -0
  23. package/dist/client.d.ts +12 -93
  24. package/dist/client.js +4 -11
  25. package/dist/codemode/ai.d.ts +27 -0
  26. package/dist/codemode/ai.js +151 -0
  27. package/dist/codemode/ai.js.map +1 -0
  28. package/dist/do-oauth-client-provider-CswoD5Lu.js +93 -0
  29. package/dist/do-oauth-client-provider-CswoD5Lu.js.map +1 -0
  30. package/dist/do-oauth-client-provider-DGc5pP0l.d.ts +55 -0
  31. package/dist/index-D6iosdF4.d.ts +560 -0
  32. package/dist/index-DhJCaDWd.d.ts +58 -0
  33. package/dist/index.d.ts +61 -402
  34. package/dist/index.js +7 -22
  35. package/dist/mcp/client.d.ts +4 -783
  36. package/dist/mcp/client.js +3 -9
  37. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  38. package/dist/mcp/do-oauth-client-provider.js +3 -7
  39. package/dist/mcp/index.d.ts +126 -81
  40. package/dist/mcp/index.js +1223 -770
  41. package/dist/mcp/index.js.map +1 -1
  42. package/dist/mcp/x402.d.ts +34 -0
  43. package/dist/mcp/x402.js +194 -0
  44. package/dist/mcp/x402.js.map +1 -0
  45. package/dist/mcp-Dw5vDrY8.d.ts +61 -0
  46. package/dist/observability/index.d.ts +3 -0
  47. package/dist/observability/index.js +7 -0
  48. package/dist/react-YzfC33jB.d.ts +115 -0
  49. package/dist/react.d.ts +10 -119
  50. package/dist/react.js +183 -110
  51. package/dist/react.js.map +1 -1
  52. package/dist/schedule.d.ts +89 -12
  53. package/dist/schedule.js +46 -21
  54. package/dist/schedule.js.map +1 -1
  55. package/dist/serializable-CymX8ovI.d.ts +39 -0
  56. package/dist/serializable.d.ts +7 -32
  57. package/dist/serializable.js +1 -1
  58. package/dist/src-Dz0H9hSU.js +1200 -0
  59. package/dist/src-Dz0H9hSU.js.map +1 -0
  60. package/package.json +109 -70
  61. package/dist/ai-types.js.map +0 -1
  62. package/dist/chunk-BZXOAZUX.js +0 -106
  63. package/dist/chunk-BZXOAZUX.js.map +0 -1
  64. package/dist/chunk-DVT5CDUP.js +0 -783
  65. package/dist/chunk-DVT5CDUP.js.map +0 -1
  66. package/dist/chunk-IFXSRTKF.js +0 -465
  67. package/dist/chunk-IFXSRTKF.js.map +0 -1
  68. package/dist/chunk-VCSB47AK.js +0 -116
  69. package/dist/chunk-VCSB47AK.js.map +0 -1
  70. package/dist/client.js.map +0 -1
  71. package/dist/index.js.map +0 -1
  72. package/dist/mcp/client.js.map +0 -1
  73. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  74. package/dist/serializable.js.map +0 -1
  75. package/src/index.ts +0 -1250
package/src/index.ts DELETED
@@ -1,1250 +0,0 @@
1
- import {
2
- Server,
3
- routePartykitRequest,
4
- type PartyServerOptions,
5
- getServerByName,
6
- type Connection,
7
- type ConnectionContext,
8
- type WSMessage,
9
- } from "partyserver";
10
-
11
- import { parseCronExpression } from "cron-schedule";
12
- import { nanoid } from "nanoid";
13
-
14
- import { AsyncLocalStorage } from "node:async_hooks";
15
- import { MCPClientManager } from "./mcp/client";
16
- import {
17
- DurableObjectOAuthClientProvider,
18
- type AgentsOAuthProvider,
19
- } from "./mcp/do-oauth-client-provider";
20
- import type {
21
- Tool,
22
- Resource,
23
- Prompt,
24
- ServerCapabilities,
25
- } from "@modelcontextprotocol/sdk/types.js";
26
-
27
- import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
28
- import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
29
-
30
- import { camelCaseToKebabCase } from "./client";
31
-
32
- export type { Connection, WSMessage, ConnectionContext } from "partyserver";
33
-
34
- /**
35
- * RPC request message from client
36
- */
37
- export type RPCRequest = {
38
- type: "rpc";
39
- id: string;
40
- method: string;
41
- args: unknown[];
42
- };
43
-
44
- /**
45
- * State update message from client
46
- */
47
- export type StateUpdateMessage = {
48
- type: "cf_agent_state";
49
- state: unknown;
50
- };
51
-
52
- /**
53
- * RPC response message to client
54
- */
55
- export type RPCResponse = {
56
- type: "rpc";
57
- id: string;
58
- } & (
59
- | {
60
- success: true;
61
- result: unknown;
62
- done?: false;
63
- }
64
- | {
65
- success: true;
66
- result: unknown;
67
- done: true;
68
- }
69
- | {
70
- success: false;
71
- error: string;
72
- }
73
- );
74
-
75
- /**
76
- * Type guard for RPC request messages
77
- */
78
- function isRPCRequest(msg: unknown): msg is RPCRequest {
79
- return (
80
- typeof msg === "object" &&
81
- msg !== null &&
82
- "type" in msg &&
83
- msg.type === "rpc" &&
84
- "id" in msg &&
85
- typeof msg.id === "string" &&
86
- "method" in msg &&
87
- typeof msg.method === "string" &&
88
- "args" in msg &&
89
- Array.isArray((msg as RPCRequest).args)
90
- );
91
- }
92
-
93
- /**
94
- * Type guard for state update messages
95
- */
96
- function isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {
97
- return (
98
- typeof msg === "object" &&
99
- msg !== null &&
100
- "type" in msg &&
101
- msg.type === "cf_agent_state" &&
102
- "state" in msg
103
- );
104
- }
105
-
106
- /**
107
- * Metadata for a callable method
108
- */
109
- export type CallableMetadata = {
110
- /** Optional description of what the method does */
111
- description?: string;
112
- /** Whether the method supports streaming responses */
113
- streaming?: boolean;
114
- };
115
-
116
- const callableMetadata = new Map<Function, CallableMetadata>();
117
-
118
- /**
119
- * Decorator that marks a method as callable by clients
120
- * @param metadata Optional metadata about the callable method
121
- */
122
- export function unstable_callable(metadata: CallableMetadata = {}) {
123
- return function callableDecorator<This, Args extends unknown[], Return>(
124
- target: (this: This, ...args: Args) => Return,
125
- context: ClassMethodDecoratorContext
126
- ) {
127
- if (!callableMetadata.has(target)) {
128
- callableMetadata.set(target, metadata);
129
- }
130
-
131
- return target;
132
- };
133
- }
134
-
135
- /**
136
- * Represents a scheduled task within an Agent
137
- * @template T Type of the payload data
138
- */
139
- export type Schedule<T = string> = {
140
- /** Unique identifier for the schedule */
141
- id: string;
142
- /** Name of the method to be called */
143
- callback: string;
144
- /** Data to be passed to the callback */
145
- payload: T;
146
- } & (
147
- | {
148
- /** Type of schedule for one-time execution at a specific time */
149
- type: "scheduled";
150
- /** Timestamp when the task should execute */
151
- time: number;
152
- }
153
- | {
154
- /** Type of schedule for delayed execution */
155
- type: "delayed";
156
- /** Timestamp when the task should execute */
157
- time: number;
158
- /** Number of seconds to delay execution */
159
- delayInSeconds: number;
160
- }
161
- | {
162
- /** Type of schedule for recurring execution based on cron expression */
163
- type: "cron";
164
- /** Timestamp for the next execution */
165
- time: number;
166
- /** Cron expression defining the schedule */
167
- cron: string;
168
- }
169
- );
170
-
171
- function getNextCronTime(cron: string) {
172
- const interval = parseCronExpression(cron);
173
- return interval.getNextDate();
174
- }
175
-
176
- /**
177
- * MCP Server state update message from server -> Client
178
- */
179
- export type MCPServerMessage = {
180
- type: "cf_agent_mcp_servers";
181
- mcp: MCPServersState;
182
- };
183
-
184
- export type MCPServersState = {
185
- servers: {
186
- [id: string]: MCPServer;
187
- };
188
- tools: Tool[];
189
- prompts: Prompt[];
190
- resources: Resource[];
191
- };
192
-
193
- export 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
-
202
- /**
203
- * MCP Server data stored in DO SQL for resuming MCP Server connections
204
- */
205
- type MCPServerRow = {
206
- id: string;
207
- name: string;
208
- server_url: string;
209
- client_id: string | null;
210
- auth_url: string | null;
211
- callback_url: string;
212
- server_options: string;
213
- };
214
-
215
- const STATE_ROW_ID = "cf_state_row_id";
216
- const STATE_WAS_CHANGED = "cf_state_was_changed";
217
-
218
- const DEFAULT_STATE = {} as unknown;
219
-
220
- const agentContext = new AsyncLocalStorage<{
221
- agent: Agent<unknown>;
222
- connection: Connection | undefined;
223
- request: Request | undefined;
224
- }>();
225
-
226
- export function getCurrentAgent<
227
- T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
228
- >(): {
229
- agent: T | undefined;
230
- connection: Connection | undefined;
231
- request: Request<unknown, CfProperties<unknown>> | undefined;
232
- } {
233
- const store = agentContext.getStore() as
234
- | {
235
- agent: T;
236
- connection: Connection | undefined;
237
- request: Request<unknown, CfProperties<unknown>> | undefined;
238
- }
239
- | undefined;
240
- if (!store) {
241
- return {
242
- agent: undefined,
243
- connection: undefined,
244
- request: undefined,
245
- };
246
- }
247
- return store;
248
- }
249
-
250
- /**
251
- * Base class for creating Agent implementations
252
- * @template Env Environment type containing bindings
253
- * @template State State type to store within the Agent
254
- */
255
- export class Agent<Env, State = unknown> extends Server<Env> {
256
- private _state = DEFAULT_STATE as State;
257
-
258
- private _ParentClass: typeof Agent<Env, State> =
259
- Object.getPrototypeOf(this).constructor;
260
-
261
- mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
262
-
263
- /**
264
- * Initial state for the Agent
265
- * Override to provide default state values
266
- */
267
- initialState: State = DEFAULT_STATE as State;
268
-
269
- /**
270
- * Current state of the Agent
271
- */
272
- get state(): State {
273
- if (this._state !== DEFAULT_STATE) {
274
- // state was previously set, and populated internal state
275
- return this._state;
276
- }
277
- // looks like this is the first time the state is being accessed
278
- // check if the state was set in a previous life
279
- const wasChanged = this.sql<{ state: "true" | undefined }>`
280
- SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
281
- `;
282
-
283
- // ok, let's pick up the actual state from the db
284
- const result = this.sql<{ state: State | undefined }>`
285
- SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
286
- `;
287
-
288
- if (
289
- wasChanged[0]?.state === "true" ||
290
- // we do this check for people who updated their code before we shipped wasChanged
291
- result[0]?.state
292
- ) {
293
- const state = result[0]?.state as string; // could be null?
294
-
295
- this._state = JSON.parse(state);
296
- return this._state;
297
- }
298
-
299
- // ok, this is the first time the state is being accessed
300
- // and the state was not set in a previous life
301
- // so we need to set the initial state (if provided)
302
- if (this.initialState === DEFAULT_STATE) {
303
- // no initial state provided, so we return undefined
304
- return undefined as State;
305
- }
306
- // initial state provided, so we set the state,
307
- // update db and return the initial state
308
- this.setState(this.initialState);
309
- return this.initialState;
310
- }
311
-
312
- /**
313
- * Agent configuration options
314
- */
315
- static options = {
316
- /** Whether the Agent should hibernate when inactive */
317
- hibernate: true, // default to hibernate
318
- };
319
-
320
- /**
321
- * Execute SQL queries against the Agent's database
322
- * @template T Type of the returned rows
323
- * @param strings SQL query template strings
324
- * @param values Values to be inserted into the query
325
- * @returns Array of query results
326
- */
327
- sql<T = Record<string, string | number | boolean | null>>(
328
- strings: TemplateStringsArray,
329
- ...values: (string | number | boolean | null)[]
330
- ) {
331
- let query = "";
332
- try {
333
- // Construct the SQL query with placeholders
334
- query = strings.reduce(
335
- (acc, str, i) => acc + str + (i < values.length ? "?" : ""),
336
- ""
337
- );
338
-
339
- // Execute the SQL query with the provided values
340
- return [...this.ctx.storage.sql.exec(query, ...values)] as T[];
341
- } catch (e) {
342
- console.error(`failed to execute sql query: ${query}`, e);
343
- throw this.onError(e);
344
- }
345
- }
346
- constructor(ctx: AgentContext, env: Env) {
347
- super(ctx, env);
348
-
349
- this.sql`
350
- CREATE TABLE IF NOT EXISTS cf_agents_state (
351
- id TEXT PRIMARY KEY NOT NULL,
352
- state TEXT
353
- )
354
- `;
355
-
356
- void this.ctx.blockConcurrencyWhile(async () => {
357
- return this._tryCatch(async () => {
358
- // Create alarms table if it doesn't exist
359
- this.sql`
360
- CREATE TABLE IF NOT EXISTS cf_agents_schedules (
361
- id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
362
- callback TEXT,
363
- payload TEXT,
364
- type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
365
- time INTEGER,
366
- delayInSeconds INTEGER,
367
- cron TEXT,
368
- created_at INTEGER DEFAULT (unixepoch())
369
- )
370
- `;
371
-
372
- // execute any pending alarms and schedule the next alarm
373
- await this.alarm();
374
- });
375
- });
376
-
377
- this.sql`
378
- CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
379
- id TEXT PRIMARY KEY NOT NULL,
380
- name TEXT NOT NULL,
381
- server_url TEXT NOT NULL,
382
- callback_url TEXT NOT NULL,
383
- client_id TEXT,
384
- auth_url TEXT,
385
- server_options TEXT
386
- )
387
- `;
388
-
389
- const _onRequest = this.onRequest.bind(this);
390
- this.onRequest = (request: Request) => {
391
- return agentContext.run(
392
- { agent: this, connection: undefined, request },
393
- async () => {
394
- if (this.mcp.isCallbackRequest(request)) {
395
- await this.mcp.handleCallbackRequest(request);
396
-
397
- // after the MCP connection handshake, we can send updated mcp state
398
- this.broadcast(
399
- JSON.stringify({
400
- type: "cf_agent_mcp_servers",
401
- mcp: this.getMcpServers(),
402
- })
403
- );
404
-
405
- // We probably should let the user configure this response/redirect, but this is fine for now.
406
- return new Response("<script>window.close();</script>", {
407
- status: 200,
408
- headers: { "content-type": "text/html" },
409
- });
410
- }
411
-
412
- return this._tryCatch(() => _onRequest(request));
413
- }
414
- );
415
- };
416
-
417
- const _onMessage = this.onMessage.bind(this);
418
- this.onMessage = async (connection: Connection, message: WSMessage) => {
419
- return agentContext.run(
420
- { agent: this, connection, request: undefined },
421
- async () => {
422
- if (typeof message !== "string") {
423
- return this._tryCatch(() => _onMessage(connection, message));
424
- }
425
-
426
- let parsed: unknown;
427
- try {
428
- parsed = JSON.parse(message);
429
- } catch (e) {
430
- // silently fail and let the onMessage handler handle it
431
- return this._tryCatch(() => _onMessage(connection, message));
432
- }
433
-
434
- if (isStateUpdateMessage(parsed)) {
435
- this._setStateInternal(parsed.state as State, connection);
436
- return;
437
- }
438
-
439
- if (isRPCRequest(parsed)) {
440
- try {
441
- const { id, method, args } = parsed;
442
-
443
- // Check if method exists and is callable
444
- const methodFn = this[method as keyof this];
445
- if (typeof methodFn !== "function") {
446
- throw new Error(`Method ${method} does not exist`);
447
- }
448
-
449
- if (!this._isCallable(method)) {
450
- throw new Error(`Method ${method} is not callable`);
451
- }
452
-
453
- const metadata = callableMetadata.get(methodFn as Function);
454
-
455
- // For streaming methods, pass a StreamingResponse object
456
- if (metadata?.streaming) {
457
- const stream = new StreamingResponse(connection, id);
458
- await methodFn.apply(this, [stream, ...args]);
459
- return;
460
- }
461
-
462
- // For regular methods, execute and send response
463
- const result = await methodFn.apply(this, args);
464
- const response: RPCResponse = {
465
- type: "rpc",
466
- id,
467
- success: true,
468
- result,
469
- done: true,
470
- };
471
- connection.send(JSON.stringify(response));
472
- } catch (e) {
473
- // Send error response
474
- const response: RPCResponse = {
475
- type: "rpc",
476
- id: parsed.id,
477
- success: false,
478
- error:
479
- e instanceof Error ? e.message : "Unknown error occurred",
480
- };
481
- connection.send(JSON.stringify(response));
482
- console.error("RPC error:", e);
483
- }
484
- return;
485
- }
486
-
487
- return this._tryCatch(() => _onMessage(connection, message));
488
- }
489
- );
490
- };
491
-
492
- const _onConnect = this.onConnect.bind(this);
493
- this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
494
- // TODO: This is a hack to ensure the state is sent after the connection is established
495
- // must fix this
496
- return agentContext.run(
497
- { agent: this, connection, request: ctx.request },
498
- async () => {
499
- setTimeout(() => {
500
- if (this.state) {
501
- connection.send(
502
- JSON.stringify({
503
- type: "cf_agent_state",
504
- state: this.state,
505
- })
506
- );
507
- }
508
-
509
- connection.send(
510
- JSON.stringify({
511
- type: "cf_agent_mcp_servers",
512
- mcp: this.getMcpServers(),
513
- })
514
- );
515
-
516
- return this._tryCatch(() => _onConnect(connection, ctx));
517
- }, 20);
518
- }
519
- );
520
- };
521
-
522
- const _onStart = this.onStart.bind(this);
523
- this.onStart = async () => {
524
- return agentContext.run(
525
- { agent: this, connection: undefined, request: undefined },
526
- async () => {
527
- const servers = this.sql<MCPServerRow>`
528
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
529
- `;
530
-
531
- // from DO storage, reconnect to all servers using our saved auth information
532
- await Promise.allSettled(
533
- servers.map((server) => {
534
- return this._connectToMcpServerInternal(
535
- server.name,
536
- server.server_url,
537
- server.callback_url,
538
- server.server_options
539
- ? JSON.parse(server.server_options)
540
- : undefined,
541
- {
542
- id: server.id,
543
- oauthClientId: server.client_id ?? undefined,
544
- }
545
- );
546
- })
547
- );
548
-
549
- this.broadcast(
550
- JSON.stringify({
551
- type: "cf_agent_mcp_servers",
552
- mcp: this.getMcpServers(),
553
- })
554
- );
555
-
556
- await this._tryCatch(() => _onStart());
557
- }
558
- );
559
- };
560
- }
561
-
562
- private _setStateInternal(
563
- state: State,
564
- source: Connection | "server" = "server"
565
- ) {
566
- this._state = state;
567
- this.sql`
568
- INSERT OR REPLACE INTO cf_agents_state (id, state)
569
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
570
- `;
571
- this.sql`
572
- INSERT OR REPLACE INTO cf_agents_state (id, state)
573
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
574
- `;
575
- this.broadcast(
576
- JSON.stringify({
577
- type: "cf_agent_state",
578
- state: state,
579
- }),
580
- source !== "server" ? [source.id] : []
581
- );
582
- return this._tryCatch(() => {
583
- const { connection, request } = agentContext.getStore() || {};
584
- return agentContext.run(
585
- { agent: this, connection, request },
586
- async () => {
587
- return this.onStateUpdate(state, source);
588
- }
589
- );
590
- });
591
- }
592
-
593
- /**
594
- * Update the Agent's state
595
- * @param state New state to set
596
- */
597
- setState(state: State) {
598
- this._setStateInternal(state, "server");
599
- }
600
-
601
- /**
602
- * Called when the Agent's state is updated
603
- * @param state Updated state
604
- * @param source Source of the state update ("server" or a client connection)
605
- */
606
- onStateUpdate(state: State | undefined, source: Connection | "server") {
607
- // override this to handle state updates
608
- }
609
-
610
- /**
611
- * Called when the Agent receives an email
612
- * @param email Email message to process
613
- */
614
- onEmail(email: ForwardableEmailMessage) {
615
- return agentContext.run(
616
- { agent: this, connection: undefined, request: undefined },
617
- async () => {
618
- console.error("onEmail not implemented");
619
- }
620
- );
621
- }
622
-
623
- private async _tryCatch<T>(fn: () => T | Promise<T>) {
624
- try {
625
- return await fn();
626
- } catch (e) {
627
- throw this.onError(e);
628
- }
629
- }
630
-
631
- override onError(
632
- connection: Connection,
633
- error: unknown
634
- ): void | Promise<void>;
635
- override onError(error: unknown): void | Promise<void>;
636
- override onError(connectionOrError: Connection | unknown, error?: unknown) {
637
- let theError: unknown;
638
- if (connectionOrError && error) {
639
- theError = error;
640
- // this is a websocket connection error
641
- console.error(
642
- "Error on websocket connection:",
643
- (connectionOrError as Connection).id,
644
- theError
645
- );
646
- console.error(
647
- "Override onError(connection, error) to handle websocket connection errors"
648
- );
649
- } else {
650
- theError = connectionOrError;
651
- // this is a server error
652
- console.error("Error on server:", theError);
653
- console.error("Override onError(error) to handle server errors");
654
- }
655
- throw theError;
656
- }
657
-
658
- /**
659
- * Render content (not implemented in base class)
660
- */
661
- render() {
662
- throw new Error("Not implemented");
663
- }
664
-
665
- /**
666
- * Schedule a task to be executed in the future
667
- * @template T Type of the payload data
668
- * @param when When to execute the task (Date, seconds delay, or cron expression)
669
- * @param callback Name of the method to call
670
- * @param payload Data to pass to the callback
671
- * @returns Schedule object representing the scheduled task
672
- */
673
- async schedule<T = string>(
674
- when: Date | string | number,
675
- callback: keyof this,
676
- payload?: T
677
- ): Promise<Schedule<T>> {
678
- const id = nanoid(9);
679
-
680
- if (typeof callback !== "string") {
681
- throw new Error("Callback must be a string");
682
- }
683
-
684
- if (typeof this[callback] !== "function") {
685
- throw new Error(`this.${callback} is not a function`);
686
- }
687
-
688
- if (when instanceof Date) {
689
- const timestamp = Math.floor(when.getTime() / 1000);
690
- this.sql`
691
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
692
- VALUES (${id}, ${callback}, ${JSON.stringify(
693
- payload
694
- )}, 'scheduled', ${timestamp})
695
- `;
696
-
697
- await this._scheduleNextAlarm();
698
-
699
- return {
700
- id,
701
- callback: callback,
702
- payload: payload as T,
703
- time: timestamp,
704
- type: "scheduled",
705
- };
706
- }
707
- if (typeof when === "number") {
708
- const time = new Date(Date.now() + when * 1000);
709
- const timestamp = Math.floor(time.getTime() / 1000);
710
-
711
- this.sql`
712
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
713
- VALUES (${id}, ${callback}, ${JSON.stringify(
714
- payload
715
- )}, 'delayed', ${when}, ${timestamp})
716
- `;
717
-
718
- await this._scheduleNextAlarm();
719
-
720
- return {
721
- id,
722
- callback: callback,
723
- payload: payload as T,
724
- delayInSeconds: when,
725
- time: timestamp,
726
- type: "delayed",
727
- };
728
- }
729
- if (typeof when === "string") {
730
- const nextExecutionTime = getNextCronTime(when);
731
- const timestamp = Math.floor(nextExecutionTime.getTime() / 1000);
732
-
733
- this.sql`
734
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
735
- VALUES (${id}, ${callback}, ${JSON.stringify(
736
- payload
737
- )}, 'cron', ${when}, ${timestamp})
738
- `;
739
-
740
- await this._scheduleNextAlarm();
741
-
742
- return {
743
- id,
744
- callback: callback,
745
- payload: payload as T,
746
- cron: when,
747
- time: timestamp,
748
- type: "cron",
749
- };
750
- }
751
- throw new Error("Invalid schedule type");
752
- }
753
-
754
- /**
755
- * Get a scheduled task by ID
756
- * @template T Type of the payload data
757
- * @param id ID of the scheduled task
758
- * @returns The Schedule object or undefined if not found
759
- */
760
- async getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined> {
761
- const result = this.sql<Schedule<string>>`
762
- SELECT * FROM cf_agents_schedules WHERE id = ${id}
763
- `;
764
- if (!result) {
765
- console.error(`schedule ${id} not found`);
766
- return undefined;
767
- }
768
-
769
- return { ...result[0], payload: JSON.parse(result[0].payload) as T };
770
- }
771
-
772
- /**
773
- * Get scheduled tasks matching the given criteria
774
- * @template T Type of the payload data
775
- * @param criteria Criteria to filter schedules
776
- * @returns Array of matching Schedule objects
777
- */
778
- getSchedules<T = string>(
779
- criteria: {
780
- id?: string;
781
- type?: "scheduled" | "delayed" | "cron";
782
- timeRange?: { start?: Date; end?: Date };
783
- } = {}
784
- ): Schedule<T>[] {
785
- let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
786
- const params = [];
787
-
788
- if (criteria.id) {
789
- query += " AND id = ?";
790
- params.push(criteria.id);
791
- }
792
-
793
- if (criteria.type) {
794
- query += " AND type = ?";
795
- params.push(criteria.type);
796
- }
797
-
798
- if (criteria.timeRange) {
799
- query += " AND time >= ? AND time <= ?";
800
- const start = criteria.timeRange.start || new Date(0);
801
- const end = criteria.timeRange.end || new Date(999999999999999);
802
- params.push(
803
- Math.floor(start.getTime() / 1000),
804
- Math.floor(end.getTime() / 1000)
805
- );
806
- }
807
-
808
- const result = this.ctx.storage.sql
809
- .exec(query, ...params)
810
- .toArray()
811
- .map((row) => ({
812
- ...row,
813
- payload: JSON.parse(row.payload as string) as T,
814
- })) as Schedule<T>[];
815
-
816
- return result;
817
- }
818
-
819
- /**
820
- * Cancel a scheduled task
821
- * @param id ID of the task to cancel
822
- * @returns true if the task was cancelled, false otherwise
823
- */
824
- async cancelSchedule(id: string): Promise<boolean> {
825
- this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
826
-
827
- await this._scheduleNextAlarm();
828
- return true;
829
- }
830
-
831
- private async _scheduleNextAlarm() {
832
- // Find the next schedule that needs to be executed
833
- const result = this.sql`
834
- SELECT time FROM cf_agents_schedules
835
- WHERE time > ${Math.floor(Date.now() / 1000)}
836
- ORDER BY time ASC
837
- LIMIT 1
838
- `;
839
- if (!result) return;
840
-
841
- if (result.length > 0 && "time" in result[0]) {
842
- const nextTime = (result[0].time as number) * 1000;
843
- await this.ctx.storage.setAlarm(nextTime);
844
- }
845
- }
846
-
847
- /**
848
- * Method called when an alarm fires.
849
- * Executes any scheduled tasks that are due.
850
- *
851
- * @remarks
852
- * To schedule a task, please use the `this.schedule` method instead.
853
- * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
854
- */
855
- public readonly alarm = async () => {
856
- const now = Math.floor(Date.now() / 1000);
857
-
858
- // Get all schedules that should be executed now
859
- const result = this.sql<Schedule<string>>`
860
- SELECT * FROM cf_agents_schedules WHERE time <= ${now}
861
- `;
862
-
863
- for (const row of result || []) {
864
- const callback = this[row.callback as keyof Agent<Env>];
865
- if (!callback) {
866
- console.error(`callback ${row.callback} not found`);
867
- continue;
868
- }
869
- await agentContext.run(
870
- { agent: this, connection: undefined, request: undefined },
871
- async () => {
872
- try {
873
- await (
874
- callback as (
875
- payload: unknown,
876
- schedule: Schedule<unknown>
877
- ) => Promise<void>
878
- ).bind(this)(JSON.parse(row.payload as string), row);
879
- } catch (e) {
880
- console.error(`error executing callback "${row.callback}"`, e);
881
- }
882
- }
883
- );
884
- if (row.type === "cron") {
885
- // Update next execution time for cron schedules
886
- const nextExecutionTime = getNextCronTime(row.cron);
887
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
888
-
889
- this.sql`
890
- UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
891
- `;
892
- } else {
893
- // Delete one-time schedules after execution
894
- this.sql`
895
- DELETE FROM cf_agents_schedules WHERE id = ${row.id}
896
- `;
897
- }
898
- }
899
-
900
- // Schedule the next alarm
901
- await this._scheduleNextAlarm();
902
- };
903
-
904
- /**
905
- * Destroy the Agent, removing all state and scheduled tasks
906
- */
907
- async destroy() {
908
- // drop all tables
909
- this.sql`DROP TABLE IF EXISTS cf_agents_state`;
910
- this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
911
- this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
912
-
913
- // delete all alarms
914
- await this.ctx.storage.deleteAlarm();
915
- await this.ctx.storage.deleteAll();
916
- }
917
-
918
- /**
919
- * Get all methods marked as callable on this Agent
920
- * @returns A map of method names to their metadata
921
- */
922
- private _isCallable(method: string): boolean {
923
- return callableMetadata.has(this[method as keyof this] as Function);
924
- }
925
-
926
- /**
927
- * Connect to a new MCP Server
928
- *
929
- * @param url MCP Server SSE URL
930
- * @param callbackHost Base host for the agent, used for the redirect URI.
931
- * @param agentsPrefix agents routing prefix if not using `agents`
932
- * @param options MCP client and transport (header) options
933
- * @returns authUrl
934
- */
935
- async addMcpServer(
936
- serverName: string,
937
- url: string,
938
- callbackHost: string,
939
- agentsPrefix = "agents",
940
- options?: {
941
- client?: ConstructorParameters<typeof Client>[1];
942
- transport?: {
943
- headers: HeadersInit;
944
- };
945
- }
946
- ): Promise<{ id: string; authUrl: string | undefined }> {
947
- const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
948
-
949
- const result = await this._connectToMcpServerInternal(
950
- serverName,
951
- url,
952
- callbackUrl,
953
- options
954
- );
955
-
956
- this.broadcast(
957
- JSON.stringify({
958
- type: "cf_agent_mcp_servers",
959
- mcp: this.getMcpServers(),
960
- })
961
- );
962
-
963
- return result;
964
- }
965
-
966
- async _connectToMcpServerInternal(
967
- serverName: string,
968
- url: string,
969
- callbackUrl: string,
970
- // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
971
- options?: {
972
- client?: ConstructorParameters<typeof Client>[1];
973
- /**
974
- * We don't expose the normal set of transport options because:
975
- * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
976
- * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
977
- *
978
- * 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).
979
- */
980
- transport?: {
981
- headers?: HeadersInit;
982
- };
983
- },
984
- reconnect?: {
985
- id: string;
986
- oauthClientId?: string;
987
- }
988
- ): Promise<{ id: string; authUrl: string | undefined }> {
989
- const authProvider = new DurableObjectOAuthClientProvider(
990
- this.ctx.storage,
991
- this.name,
992
- callbackUrl
993
- );
994
-
995
- if (reconnect) {
996
- authProvider.serverId = reconnect.id;
997
- if (reconnect.oauthClientId) {
998
- authProvider.clientId = reconnect.oauthClientId;
999
- }
1000
- }
1001
-
1002
- // allows passing through transport headers if necessary
1003
- // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
1004
- let headerTransportOpts: SSEClientTransportOptions = {};
1005
- if (options?.transport?.headers) {
1006
- headerTransportOpts = {
1007
- eventSourceInit: {
1008
- fetch: (url, init) =>
1009
- fetch(url, {
1010
- ...init,
1011
- headers: options?.transport?.headers,
1012
- }),
1013
- },
1014
- requestInit: {
1015
- headers: options?.transport?.headers,
1016
- },
1017
- };
1018
- }
1019
-
1020
- const { id, authUrl, clientId } = await this.mcp.connect(url, {
1021
- reconnect,
1022
- transport: {
1023
- ...headerTransportOpts,
1024
- authProvider,
1025
- },
1026
- client: options?.client,
1027
- });
1028
-
1029
- this.sql`
1030
- INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1031
- VALUES (
1032
- ${id},
1033
- ${serverName},
1034
- ${url},
1035
- ${clientId ?? null},
1036
- ${authUrl ?? null},
1037
- ${callbackUrl},
1038
- ${options ? JSON.stringify(options) : null}
1039
- );
1040
- `;
1041
-
1042
- return {
1043
- id,
1044
- authUrl,
1045
- };
1046
- }
1047
-
1048
- async removeMcpServer(id: string) {
1049
- this.mcp.closeConnection(id);
1050
- this.sql`
1051
- DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1052
- `;
1053
- this.broadcast(
1054
- JSON.stringify({
1055
- type: "cf_agent_mcp_servers",
1056
- mcp: this.getMcpServers(),
1057
- })
1058
- );
1059
- }
1060
-
1061
- getMcpServers(): MCPServersState {
1062
- const mcpState: MCPServersState = {
1063
- servers: {},
1064
- tools: this.mcp.listTools(),
1065
- prompts: this.mcp.listPrompts(),
1066
- resources: this.mcp.listResources(),
1067
- };
1068
-
1069
- const servers = this.sql<MCPServerRow>`
1070
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1071
- `;
1072
-
1073
- for (const server of servers) {
1074
- mcpState.servers[server.id] = {
1075
- name: server.name,
1076
- server_url: server.server_url,
1077
- auth_url: server.auth_url,
1078
- state: this.mcp.mcpConnections[server.id].connectionState,
1079
- instructions: this.mcp.mcpConnections[server.id].instructions ?? null,
1080
- capabilities:
1081
- this.mcp.mcpConnections[server.id].serverCapabilities ?? null,
1082
- };
1083
- }
1084
-
1085
- return mcpState;
1086
- }
1087
- }
1088
-
1089
- /**
1090
- * Namespace for creating Agent instances
1091
- * @template Agentic Type of the Agent class
1092
- */
1093
- export type AgentNamespace<Agentic extends Agent<unknown>> =
1094
- DurableObjectNamespace<Agentic>;
1095
-
1096
- /**
1097
- * Agent's durable context
1098
- */
1099
- export type AgentContext = DurableObjectState;
1100
-
1101
- /**
1102
- * Configuration options for Agent routing
1103
- */
1104
- export type AgentOptions<Env> = PartyServerOptions<Env> & {
1105
- /**
1106
- * Whether to enable CORS for the Agent
1107
- */
1108
- cors?: boolean | HeadersInit | undefined;
1109
- };
1110
-
1111
- /**
1112
- * Route a request to the appropriate Agent
1113
- * @param request Request to route
1114
- * @param env Environment containing Agent bindings
1115
- * @param options Routing options
1116
- * @returns Response from the Agent or undefined if no route matched
1117
- */
1118
- export async function routeAgentRequest<Env>(
1119
- request: Request,
1120
- env: Env,
1121
- options?: AgentOptions<Env>
1122
- ) {
1123
- const corsHeaders =
1124
- options?.cors === true
1125
- ? {
1126
- "Access-Control-Allow-Origin": "*",
1127
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1128
- "Access-Control-Allow-Credentials": "true",
1129
- "Access-Control-Max-Age": "86400",
1130
- }
1131
- : options?.cors;
1132
-
1133
- if (request.method === "OPTIONS") {
1134
- if (corsHeaders) {
1135
- return new Response(null, {
1136
- headers: corsHeaders,
1137
- });
1138
- }
1139
- console.warn(
1140
- "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
1141
- );
1142
- }
1143
-
1144
- let response = await routePartykitRequest(
1145
- request,
1146
- env as Record<string, unknown>,
1147
- {
1148
- prefix: "agents",
1149
- ...(options as PartyServerOptions<Record<string, unknown>>),
1150
- }
1151
- );
1152
-
1153
- if (
1154
- response &&
1155
- corsHeaders &&
1156
- request.headers.get("upgrade")?.toLowerCase() !== "websocket" &&
1157
- request.headers.get("Upgrade")?.toLowerCase() !== "websocket"
1158
- ) {
1159
- response = new Response(response.body, {
1160
- headers: {
1161
- ...response.headers,
1162
- ...corsHeaders,
1163
- },
1164
- });
1165
- }
1166
- return response;
1167
- }
1168
-
1169
- /**
1170
- * Route an email to the appropriate Agent
1171
- * @param email Email message to route
1172
- * @param env Environment containing Agent bindings
1173
- * @param options Routing options
1174
- */
1175
- export async function routeAgentEmail<Env>(
1176
- email: ForwardableEmailMessage,
1177
- env: Env,
1178
- options?: AgentOptions<Env>
1179
- ): Promise<void> {}
1180
-
1181
- /**
1182
- * Get or create an Agent by name
1183
- * @template Env Environment type containing bindings
1184
- * @template T Type of the Agent class
1185
- * @param namespace Agent namespace
1186
- * @param name Name of the Agent instance
1187
- * @param options Options for Agent creation
1188
- * @returns Promise resolving to an Agent instance stub
1189
- */
1190
- export async function getAgentByName<Env, T extends Agent<Env>>(
1191
- namespace: AgentNamespace<T>,
1192
- name: string,
1193
- options?: {
1194
- jurisdiction?: DurableObjectJurisdiction;
1195
- locationHint?: DurableObjectLocationHint;
1196
- }
1197
- ) {
1198
- return getServerByName<Env, T>(namespace, name, options);
1199
- }
1200
-
1201
- /**
1202
- * A wrapper for streaming responses in callable methods
1203
- */
1204
- export class StreamingResponse {
1205
- private _connection: Connection;
1206
- private _id: string;
1207
- private _closed = false;
1208
-
1209
- constructor(connection: Connection, id: string) {
1210
- this._connection = connection;
1211
- this._id = id;
1212
- }
1213
-
1214
- /**
1215
- * Send a chunk of data to the client
1216
- * @param chunk The data to send
1217
- */
1218
- send(chunk: unknown) {
1219
- if (this._closed) {
1220
- throw new Error("StreamingResponse is already closed");
1221
- }
1222
- const response: RPCResponse = {
1223
- type: "rpc",
1224
- id: this._id,
1225
- success: true,
1226
- result: chunk,
1227
- done: false,
1228
- };
1229
- this._connection.send(JSON.stringify(response));
1230
- }
1231
-
1232
- /**
1233
- * End the stream and send the final chunk (if any)
1234
- * @param finalChunk Optional final chunk of data to send
1235
- */
1236
- end(finalChunk?: unknown) {
1237
- if (this._closed) {
1238
- throw new Error("StreamingResponse is already closed");
1239
- }
1240
- this._closed = true;
1241
- const response: RPCResponse = {
1242
- type: "rpc",
1243
- id: this._id,
1244
- success: true,
1245
- result: finalChunk,
1246
- done: true,
1247
- };
1248
- this._connection.send(JSON.stringify(response));
1249
- }
1250
- }