agents 0.0.0-9c6b2d7 → 0.0.0-9d21dd8

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