agents 0.0.0-9688c15 → 0.0.0-96add46

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