agents 0.0.0-b4ebb44 → 0.0.0-b507395

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 (83) hide show
  1. package/README.md +257 -27
  2. package/dist/ai-chat-agent.d.ts +104 -19
  3. package/dist/ai-chat-agent.js +812 -230
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-DguhuLKF.js +155 -0
  6. package/dist/ai-chat-v5-migration-DguhuLKF.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 +79 -85
  10. package/dist/ai-react.js +411 -199
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-CwgHzwUb.js +24 -0
  13. package/dist/ai-types-CwgHzwUb.js.map +1 -0
  14. package/dist/ai-types-D_hTbf25.d.ts +103 -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-CcyhkGfN.js +117 -0
  21. package/dist/client-CcyhkGfN.js.map +1 -0
  22. package/dist/client-ClORm6f0.d.ts +104 -0
  23. package/dist/client-DfIOsabL.d.ts +834 -0
  24. package/dist/client-QZa2Rq0l.js +1105 -0
  25. package/dist/client-QZa2Rq0l.js.map +1 -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 +152 -0
  30. package/dist/codemode/ai.js.map +1 -0
  31. package/dist/context-BkKbAa1R.js +8 -0
  32. package/dist/context-BkKbAa1R.js.map +1 -0
  33. package/dist/context-_sPQqJWv.d.ts +24 -0
  34. package/dist/context.d.ts +6 -0
  35. package/dist/context.js +3 -0
  36. package/dist/do-oauth-client-provider-B-ryFIPr.d.ts +70 -0
  37. package/dist/do-oauth-client-provider-B1fVIshX.js +155 -0
  38. package/dist/do-oauth-client-provider-B1fVIshX.js.map +1 -0
  39. package/dist/index-CyDpAVHZ.d.ts +58 -0
  40. package/dist/index-DPJ32qQn.d.ts +577 -0
  41. package/dist/index.d.ts +61 -402
  42. package/dist/index.js +8 -22
  43. package/dist/mcp/client.d.ts +4 -783
  44. package/dist/mcp/client.js +4 -9
  45. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  46. package/dist/mcp/do-oauth-client-provider.js +3 -7
  47. package/dist/mcp/index.d.ts +191 -81
  48. package/dist/mcp/index.js +1435 -770
  49. package/dist/mcp/index.js.map +1 -1
  50. package/dist/mcp/x402.d.ts +34 -0
  51. package/dist/mcp/x402.js +198 -0
  52. package/dist/mcp/x402.js.map +1 -0
  53. package/dist/mcp-CzbSsLfc.d.ts +61 -0
  54. package/dist/observability/index.d.ts +3 -0
  55. package/dist/observability/index.js +8 -0
  56. package/dist/react-MaOSl7Pr.d.ts +113 -0
  57. package/dist/react.d.ts +11 -119
  58. package/dist/react.js +183 -110
  59. package/dist/react.js.map +1 -1
  60. package/dist/schedule.d.ts +87 -10
  61. package/dist/schedule.js +46 -21
  62. package/dist/schedule.js.map +1 -1
  63. package/dist/serializable-C4GLimgv.d.ts +39 -0
  64. package/dist/serializable.d.ts +7 -32
  65. package/dist/serializable.js +1 -1
  66. package/dist/src-BmbDclOA.js +1181 -0
  67. package/dist/src-BmbDclOA.js.map +1 -0
  68. package/package.json +83 -29
  69. package/dist/ai-types.js.map +0 -1
  70. package/dist/chunk-767EASBA.js +0 -106
  71. package/dist/chunk-767EASBA.js.map +0 -1
  72. package/dist/chunk-E3LCYPCB.js +0 -469
  73. package/dist/chunk-E3LCYPCB.js.map +0 -1
  74. package/dist/chunk-NKZZ66QY.js +0 -116
  75. package/dist/chunk-NKZZ66QY.js.map +0 -1
  76. package/dist/chunk-ZRRXJUAA.js +0 -788
  77. package/dist/chunk-ZRRXJUAA.js.map +0 -1
  78. package/dist/client.js.map +0 -1
  79. package/dist/index.js.map +0 -1
  80. package/dist/mcp/client.js.map +0 -1
  81. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  82. package/dist/serializable.js.map +0 -1
  83. package/src/index.ts +0 -1255
package/src/index.ts DELETED
@@ -1,1255 +0,0 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
2
- import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
- import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
4
-
5
- import type {
6
- Prompt,
7
- Resource,
8
- ServerCapabilities,
9
- Tool,
10
- } from "@modelcontextprotocol/sdk/types.js";
11
- import { parseCronExpression } from "cron-schedule";
12
- import { nanoid } from "nanoid";
13
- import {
14
- type Connection,
15
- type ConnectionContext,
16
- getServerByName,
17
- type PartyServerOptions,
18
- routePartykitRequest,
19
- Server,
20
- type WSMessage,
21
- } from "partyserver";
22
- import { camelCaseToKebabCase } from "./client";
23
- import { MCPClientManager } from "./mcp/client";
24
- // import type { MCPClientConnection } from "./mcp/client-connection";
25
- import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
26
-
27
- export type { Connection, ConnectionContext, WSMessage } from "partyserver";
28
-
29
- /**
30
- * RPC request message from client
31
- */
32
- export type RPCRequest = {
33
- type: "rpc";
34
- id: string;
35
- method: string;
36
- args: unknown[];
37
- };
38
-
39
- /**
40
- * State update message from client
41
- */
42
- export type StateUpdateMessage = {
43
- type: "cf_agent_state";
44
- state: unknown;
45
- };
46
-
47
- /**
48
- * RPC response message to client
49
- */
50
- export type RPCResponse = {
51
- type: "rpc";
52
- id: string;
53
- } & (
54
- | {
55
- success: true;
56
- result: unknown;
57
- done?: false;
58
- }
59
- | {
60
- success: true;
61
- result: unknown;
62
- done: true;
63
- }
64
- | {
65
- success: false;
66
- error: string;
67
- }
68
- );
69
-
70
- /**
71
- * Type guard for RPC request messages
72
- */
73
- function isRPCRequest(msg: unknown): msg is RPCRequest {
74
- return (
75
- typeof msg === "object" &&
76
- msg !== null &&
77
- "type" in msg &&
78
- msg.type === "rpc" &&
79
- "id" in msg &&
80
- typeof msg.id === "string" &&
81
- "method" in msg &&
82
- typeof msg.method === "string" &&
83
- "args" in msg &&
84
- Array.isArray((msg as RPCRequest).args)
85
- );
86
- }
87
-
88
- /**
89
- * Type guard for state update messages
90
- */
91
- function isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {
92
- return (
93
- typeof msg === "object" &&
94
- msg !== null &&
95
- "type" in msg &&
96
- msg.type === "cf_agent_state" &&
97
- "state" in msg
98
- );
99
- }
100
-
101
- /**
102
- * Metadata for a callable method
103
- */
104
- export type CallableMetadata = {
105
- /** Optional description of what the method does */
106
- description?: string;
107
- /** Whether the method supports streaming responses */
108
- streaming?: boolean;
109
- };
110
-
111
- const callableMetadata = new Map<Function, CallableMetadata>();
112
-
113
- /**
114
- * Decorator that marks a method as callable by clients
115
- * @param metadata Optional metadata about the callable method
116
- */
117
- export function unstable_callable(metadata: CallableMetadata = {}) {
118
- return function callableDecorator<This, Args extends unknown[], Return>(
119
- target: (this: This, ...args: Args) => Return,
120
- // biome-ignore lint/correctness/noUnusedFunctionParameters: later
121
- context: ClassMethodDecoratorContext
122
- ) {
123
- if (!callableMetadata.has(target)) {
124
- callableMetadata.set(target, metadata);
125
- }
126
-
127
- return target;
128
- };
129
- }
130
-
131
- /**
132
- * Represents a scheduled task within an Agent
133
- * @template T Type of the payload data
134
- */
135
- export type Schedule<T = string> = {
136
- /** Unique identifier for the schedule */
137
- id: string;
138
- /** Name of the method to be called */
139
- callback: string;
140
- /** Data to be passed to the callback */
141
- payload: T;
142
- } & (
143
- | {
144
- /** Type of schedule for one-time execution at a specific time */
145
- type: "scheduled";
146
- /** Timestamp when the task should execute */
147
- time: number;
148
- }
149
- | {
150
- /** Type of schedule for delayed execution */
151
- type: "delayed";
152
- /** Timestamp when the task should execute */
153
- time: number;
154
- /** Number of seconds to delay execution */
155
- delayInSeconds: number;
156
- }
157
- | {
158
- /** Type of schedule for recurring execution based on cron expression */
159
- type: "cron";
160
- /** Timestamp for the next execution */
161
- time: number;
162
- /** Cron expression defining the schedule */
163
- cron: string;
164
- }
165
- );
166
-
167
- function getNextCronTime(cron: string) {
168
- const interval = parseCronExpression(cron);
169
- return interval.getNextDate();
170
- }
171
-
172
- /**
173
- * MCP Server state update message from server -> Client
174
- */
175
- export type MCPServerMessage = {
176
- type: "cf_agent_mcp_servers";
177
- mcp: MCPServersState;
178
- };
179
-
180
- export type MCPServersState = {
181
- servers: {
182
- [id: string]: MCPServer;
183
- };
184
- tools: Tool[];
185
- prompts: Prompt[];
186
- resources: Resource[];
187
- };
188
-
189
- export type MCPServer = {
190
- name: string;
191
- server_url: string;
192
- auth_url: string | null;
193
- // This state is specifically about the temporary process of getting a token (if needed).
194
- // Scope outside of that can't be relied upon because when the DO sleeps, there's no way
195
- // to communicate a change to a non-ready state.
196
- state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
197
- instructions: string | null;
198
- capabilities: ServerCapabilities | null;
199
- };
200
-
201
- /**
202
- * MCP Server data stored in DO SQL for resuming MCP Server connections
203
- */
204
- type MCPServerRow = {
205
- id: string;
206
- name: string;
207
- server_url: string;
208
- client_id: string | null;
209
- auth_url: string | null;
210
- callback_url: string;
211
- server_options: string;
212
- };
213
-
214
- const STATE_ROW_ID = "cf_state_row_id";
215
- const STATE_WAS_CHANGED = "cf_state_was_changed";
216
-
217
- const DEFAULT_STATE = {} as unknown;
218
-
219
- const agentContext = new AsyncLocalStorage<{
220
- agent: Agent<unknown>;
221
- connection: Connection | undefined;
222
- request: Request | undefined;
223
- }>();
224
-
225
- export function getCurrentAgent<
226
- T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
227
- >(): {
228
- agent: T | undefined;
229
- connection: Connection | undefined;
230
- request: Request<unknown, CfProperties<unknown>> | undefined;
231
- } {
232
- const store = agentContext.getStore() as
233
- | {
234
- agent: T;
235
- connection: Connection | undefined;
236
- request: Request<unknown, CfProperties<unknown>> | undefined;
237
- }
238
- | undefined;
239
- if (!store) {
240
- return {
241
- agent: undefined,
242
- connection: undefined,
243
- request: undefined,
244
- };
245
- }
246
- return store;
247
- }
248
-
249
- /**
250
- * Base class for creating Agent implementations
251
- * @template Env Environment type containing bindings
252
- * @template State State type to store within the Agent
253
- */
254
- export class Agent<Env, State = unknown> extends Server<Env> {
255
- private _state = DEFAULT_STATE as State;
256
-
257
- private _ParentClass: typeof Agent<Env, State> =
258
- Object.getPrototypeOf(this).constructor;
259
-
260
- mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
261
-
262
- /**
263
- * Initial state for the Agent
264
- * Override to provide default state values
265
- */
266
- initialState: State = DEFAULT_STATE as State;
267
-
268
- /**
269
- * Current state of the Agent
270
- */
271
- get state(): State {
272
- if (this._state !== DEFAULT_STATE) {
273
- // state was previously set, and populated internal state
274
- return this._state;
275
- }
276
- // looks like this is the first time the state is being accessed
277
- // check if the state was set in a previous life
278
- const wasChanged = this.sql<{ state: "true" | undefined }>`
279
- SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
280
- `;
281
-
282
- // ok, let's pick up the actual state from the db
283
- const result = this.sql<{ state: State | undefined }>`
284
- SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
285
- `;
286
-
287
- if (
288
- wasChanged[0]?.state === "true" ||
289
- // we do this check for people who updated their code before we shipped wasChanged
290
- result[0]?.state
291
- ) {
292
- const state = result[0]?.state as string; // could be null?
293
-
294
- this._state = JSON.parse(state);
295
- return this._state;
296
- }
297
-
298
- // ok, this is the first time the state is being accessed
299
- // and the state was not set in a previous life
300
- // so we need to set the initial state (if provided)
301
- if (this.initialState === DEFAULT_STATE) {
302
- // no initial state provided, so we return undefined
303
- return undefined as State;
304
- }
305
- // initial state provided, so we set the state,
306
- // update db and return the initial state
307
- this.setState(this.initialState);
308
- return this.initialState;
309
- }
310
-
311
- /**
312
- * Agent configuration options
313
- */
314
- static options = {
315
- /** Whether the Agent should hibernate when inactive */
316
- hibernate: true, // default to hibernate
317
- };
318
-
319
- /**
320
- * Execute SQL queries against the Agent's database
321
- * @template T Type of the returned rows
322
- * @param strings SQL query template strings
323
- * @param values Values to be inserted into the query
324
- * @returns Array of query results
325
- */
326
- sql<T = Record<string, string | number | boolean | null>>(
327
- strings: TemplateStringsArray,
328
- ...values: (string | number | boolean | null)[]
329
- ) {
330
- let query = "";
331
- try {
332
- // Construct the SQL query with placeholders
333
- query = strings.reduce(
334
- (acc, str, i) => acc + str + (i < values.length ? "?" : ""),
335
- ""
336
- );
337
-
338
- // Execute the SQL query with the provided values
339
- return [...this.ctx.storage.sql.exec(query, ...values)] as T[];
340
- } catch (e) {
341
- console.error(`failed to execute sql query: ${query}`, e);
342
- throw this.onError(e);
343
- }
344
- }
345
- constructor(ctx: AgentContext, env: Env) {
346
- super(ctx, env);
347
-
348
- this.sql`
349
- CREATE TABLE IF NOT EXISTS cf_agents_state (
350
- id TEXT PRIMARY KEY NOT NULL,
351
- state TEXT
352
- )
353
- `;
354
-
355
- void this.ctx.blockConcurrencyWhile(async () => {
356
- return this._tryCatch(async () => {
357
- // Create alarms table if it doesn't exist
358
- this.sql`
359
- CREATE TABLE IF NOT EXISTS cf_agents_schedules (
360
- id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
361
- callback TEXT,
362
- payload TEXT,
363
- type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
364
- time INTEGER,
365
- delayInSeconds INTEGER,
366
- cron TEXT,
367
- created_at INTEGER DEFAULT (unixepoch())
368
- )
369
- `;
370
-
371
- // execute any pending alarms and schedule the next alarm
372
- await this.alarm();
373
- });
374
- });
375
-
376
- this.sql`
377
- CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
378
- id TEXT PRIMARY KEY NOT NULL,
379
- name TEXT NOT NULL,
380
- server_url TEXT NOT NULL,
381
- callback_url TEXT NOT NULL,
382
- client_id TEXT,
383
- auth_url TEXT,
384
- server_options TEXT
385
- )
386
- `;
387
-
388
- const _onRequest = this.onRequest.bind(this);
389
- this.onRequest = (request: Request) => {
390
- return agentContext.run(
391
- { agent: this, connection: undefined, request },
392
- async () => {
393
- if (this.mcp.isCallbackRequest(request)) {
394
- await this.mcp.handleCallbackRequest(request);
395
-
396
- // after the MCP connection handshake, we can send updated mcp state
397
- this.broadcast(
398
- JSON.stringify({
399
- mcp: this.getMcpServers(),
400
- type: "cf_agent_mcp_servers",
401
- })
402
- );
403
-
404
- // We probably should let the user configure this response/redirect, but this is fine for now.
405
- return new Response("<script>window.close();</script>", {
406
- headers: { "content-type": "text/html" },
407
- status: 200,
408
- });
409
- }
410
-
411
- return this._tryCatch(() => _onRequest(request));
412
- }
413
- );
414
- };
415
-
416
- const _onMessage = this.onMessage.bind(this);
417
- this.onMessage = async (connection: Connection, message: WSMessage) => {
418
- return agentContext.run(
419
- { agent: this, connection, request: undefined },
420
- async () => {
421
- if (typeof message !== "string") {
422
- return this._tryCatch(() => _onMessage(connection, message));
423
- }
424
-
425
- let parsed: unknown;
426
- try {
427
- parsed = JSON.parse(message);
428
- } catch (_e) {
429
- // silently fail and let the onMessage handler handle it
430
- return this._tryCatch(() => _onMessage(connection, message));
431
- }
432
-
433
- if (isStateUpdateMessage(parsed)) {
434
- this._setStateInternal(parsed.state as State, connection);
435
- return;
436
- }
437
-
438
- if (isRPCRequest(parsed)) {
439
- try {
440
- const { id, method, args } = parsed;
441
-
442
- // Check if method exists and is callable
443
- const methodFn = this[method as keyof this];
444
- if (typeof methodFn !== "function") {
445
- throw new Error(`Method ${method} does not exist`);
446
- }
447
-
448
- if (!this._isCallable(method)) {
449
- throw new Error(`Method ${method} is not callable`);
450
- }
451
-
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
- done: true,
465
- id,
466
- result,
467
- success: true,
468
- type: "rpc",
469
- };
470
- connection.send(JSON.stringify(response));
471
- } catch (e) {
472
- // Send error response
473
- const response: RPCResponse = {
474
- error:
475
- e instanceof Error ? e.message : "Unknown error occurred",
476
- id: parsed.id,
477
- success: false,
478
- type: "rpc",
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
- state: this.state,
503
- type: "cf_agent_state",
504
- })
505
- );
506
- }
507
-
508
- connection.send(
509
- JSON.stringify({
510
- mcp: this.getMcpServers(),
511
- type: "cf_agent_mcp_servers",
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 not currently in the oauth flow using our saved auth information
531
- await Promise.allSettled(
532
- servers
533
- .filter((server) => server.auth_url === null)
534
- .map((server) => {
535
- return this._connectToMcpServerInternal(
536
- server.name,
537
- server.server_url,
538
- server.callback_url,
539
- server.server_options
540
- ? JSON.parse(server.server_options)
541
- : undefined,
542
- {
543
- id: server.id,
544
- oauthClientId: server.client_id ?? undefined,
545
- }
546
- );
547
- })
548
- );
549
-
550
- this.broadcast(
551
- JSON.stringify({
552
- mcp: this.getMcpServers(),
553
- type: "cf_agent_mcp_servers",
554
- })
555
- );
556
-
557
- await this._tryCatch(() => _onStart());
558
- }
559
- );
560
- };
561
- }
562
-
563
- private _setStateInternal(
564
- state: State,
565
- source: Connection | "server" = "server"
566
- ) {
567
- this._state = state;
568
- this.sql`
569
- INSERT OR REPLACE INTO cf_agents_state (id, state)
570
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
571
- `;
572
- this.sql`
573
- INSERT OR REPLACE INTO cf_agents_state (id, state)
574
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
575
- `;
576
- this.broadcast(
577
- JSON.stringify({
578
- state: state,
579
- type: "cf_agent_state",
580
- }),
581
- source !== "server" ? [source.id] : []
582
- );
583
- return this._tryCatch(() => {
584
- const { connection, request } = agentContext.getStore() || {};
585
- return agentContext.run(
586
- { agent: this, connection, request },
587
- async () => {
588
- return this.onStateUpdate(state, source);
589
- }
590
- );
591
- });
592
- }
593
-
594
- /**
595
- * Update the Agent's state
596
- * @param state New state to set
597
- */
598
- setState(state: State) {
599
- this._setStateInternal(state, "server");
600
- }
601
-
602
- /**
603
- * Called when the Agent's state is updated
604
- * @param state Updated state
605
- * @param source Source of the state update ("server" or a client connection)
606
- */
607
- // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
608
- onStateUpdate(state: State | undefined, source: Connection | "server") {
609
- // override this to handle state updates
610
- }
611
-
612
- /**
613
- * Called when the Agent receives an email
614
- * @param email Email message to process
615
- */
616
- // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
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
- callback: callback,
704
- id,
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
- callback: callback,
725
- delayInSeconds: when,
726
- id,
727
- payload: payload as T,
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
- callback: callback,
747
- cron: when,
748
- id,
749
- payload: payload as T,
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
- this.ctx.abort("destroyed"); // enforce that the agent is evicted
920
- }
921
-
922
- /**
923
- * Get all methods marked as callable on this Agent
924
- * @returns A map of method names to their metadata
925
- */
926
- private _isCallable(method: string): boolean {
927
- return callableMetadata.has(this[method as keyof this] as Function);
928
- }
929
-
930
- /**
931
- * Connect to a new MCP Server
932
- *
933
- * @param url MCP Server SSE URL
934
- * @param callbackHost Base host for the agent, used for the redirect URI.
935
- * @param agentsPrefix agents routing prefix if not using `agents`
936
- * @param options MCP client and transport (header) options
937
- * @returns authUrl
938
- */
939
- async addMcpServer(
940
- serverName: string,
941
- url: string,
942
- callbackHost: string,
943
- agentsPrefix = "agents",
944
- options?: {
945
- client?: ConstructorParameters<typeof Client>[1];
946
- transport?: {
947
- headers: HeadersInit;
948
- };
949
- }
950
- ): Promise<{ id: string; authUrl: string | undefined }> {
951
- const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
952
-
953
- const result = await this._connectToMcpServerInternal(
954
- serverName,
955
- url,
956
- callbackUrl,
957
- options
958
- );
959
-
960
- this.broadcast(
961
- JSON.stringify({
962
- mcp: this.getMcpServers(),
963
- type: "cf_agent_mcp_servers",
964
- })
965
- );
966
-
967
- return result;
968
- }
969
-
970
- async _connectToMcpServerInternal(
971
- serverName: string,
972
- url: string,
973
- callbackUrl: string,
974
- // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
975
- options?: {
976
- client?: ConstructorParameters<typeof Client>[1];
977
- /**
978
- * We don't expose the normal set of transport options because:
979
- * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
980
- * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
981
- *
982
- * 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).
983
- */
984
- transport?: {
985
- headers?: HeadersInit;
986
- };
987
- },
988
- reconnect?: {
989
- id: string;
990
- oauthClientId?: string;
991
- }
992
- ): Promise<{ id: string; authUrl: string | undefined }> {
993
- const authProvider = new DurableObjectOAuthClientProvider(
994
- this.ctx.storage,
995
- this.name,
996
- callbackUrl
997
- );
998
-
999
- if (reconnect) {
1000
- authProvider.serverId = reconnect.id;
1001
- if (reconnect.oauthClientId) {
1002
- authProvider.clientId = reconnect.oauthClientId;
1003
- }
1004
- }
1005
-
1006
- // allows passing through transport headers if necessary
1007
- // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
1008
- let headerTransportOpts: SSEClientTransportOptions = {};
1009
- if (options?.transport?.headers) {
1010
- headerTransportOpts = {
1011
- eventSourceInit: {
1012
- fetch: (url, init) =>
1013
- fetch(url, {
1014
- ...init,
1015
- headers: options?.transport?.headers,
1016
- }),
1017
- },
1018
- requestInit: {
1019
- headers: options?.transport?.headers,
1020
- },
1021
- };
1022
- }
1023
-
1024
- const { id, authUrl, clientId } = await this.mcp.connect(url, {
1025
- client: options?.client,
1026
- reconnect,
1027
- transport: {
1028
- ...headerTransportOpts,
1029
- authProvider,
1030
- },
1031
- });
1032
-
1033
- this.sql`
1034
- INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1035
- VALUES (
1036
- ${id},
1037
- ${serverName},
1038
- ${url},
1039
- ${clientId ?? null},
1040
- ${authUrl ?? null},
1041
- ${callbackUrl},
1042
- ${options ? JSON.stringify(options) : null}
1043
- );
1044
- `;
1045
-
1046
- return {
1047
- authUrl,
1048
- id,
1049
- };
1050
- }
1051
-
1052
- async removeMcpServer(id: string) {
1053
- this.mcp.closeConnection(id);
1054
- this.sql`
1055
- DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1056
- `;
1057
- this.broadcast(
1058
- JSON.stringify({
1059
- mcp: this.getMcpServers(),
1060
- type: "cf_agent_mcp_servers",
1061
- })
1062
- );
1063
- }
1064
-
1065
- getMcpServers(): MCPServersState {
1066
- const mcpState: MCPServersState = {
1067
- prompts: this.mcp.listPrompts(),
1068
- resources: this.mcp.listResources(),
1069
- servers: {},
1070
- tools: this.mcp.listTools(),
1071
- };
1072
-
1073
- const servers = this.sql<MCPServerRow>`
1074
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1075
- `;
1076
-
1077
- for (const server of servers) {
1078
- const serverConn = this.mcp.mcpConnections[server.id];
1079
- mcpState.servers[server.id] = {
1080
- auth_url: server.auth_url,
1081
- capabilities: serverConn?.serverCapabilities ?? null,
1082
- instructions: serverConn?.instructions ?? null,
1083
- name: server.name,
1084
- server_url: server.server_url,
1085
- // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1086
- state: serverConn?.connectionState ?? "authenticating",
1087
- };
1088
- }
1089
-
1090
- return mcpState;
1091
- }
1092
- }
1093
-
1094
- /**
1095
- * Namespace for creating Agent instances
1096
- * @template Agentic Type of the Agent class
1097
- */
1098
- export type AgentNamespace<Agentic extends Agent<unknown>> =
1099
- DurableObjectNamespace<Agentic>;
1100
-
1101
- /**
1102
- * Agent's durable context
1103
- */
1104
- export type AgentContext = DurableObjectState;
1105
-
1106
- /**
1107
- * Configuration options for Agent routing
1108
- */
1109
- export type AgentOptions<Env> = PartyServerOptions<Env> & {
1110
- /**
1111
- * Whether to enable CORS for the Agent
1112
- */
1113
- cors?: boolean | HeadersInit | undefined;
1114
- };
1115
-
1116
- /**
1117
- * Route a request to the appropriate Agent
1118
- * @param request Request to route
1119
- * @param env Environment containing Agent bindings
1120
- * @param options Routing options
1121
- * @returns Response from the Agent or undefined if no route matched
1122
- */
1123
- export async function routeAgentRequest<Env>(
1124
- request: Request,
1125
- env: Env,
1126
- options?: AgentOptions<Env>
1127
- ) {
1128
- const corsHeaders =
1129
- options?.cors === true
1130
- ? {
1131
- "Access-Control-Allow-Credentials": "true",
1132
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1133
- "Access-Control-Allow-Origin": "*",
1134
- "Access-Control-Max-Age": "86400",
1135
- }
1136
- : options?.cors;
1137
-
1138
- if (request.method === "OPTIONS") {
1139
- if (corsHeaders) {
1140
- return new Response(null, {
1141
- headers: corsHeaders,
1142
- });
1143
- }
1144
- console.warn(
1145
- "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
1146
- );
1147
- }
1148
-
1149
- let response = await routePartykitRequest(
1150
- request,
1151
- env as Record<string, unknown>,
1152
- {
1153
- prefix: "agents",
1154
- ...(options as PartyServerOptions<Record<string, unknown>>),
1155
- }
1156
- );
1157
-
1158
- if (
1159
- response &&
1160
- corsHeaders &&
1161
- request.headers.get("upgrade")?.toLowerCase() !== "websocket" &&
1162
- request.headers.get("Upgrade")?.toLowerCase() !== "websocket"
1163
- ) {
1164
- response = new Response(response.body, {
1165
- headers: {
1166
- ...response.headers,
1167
- ...corsHeaders,
1168
- },
1169
- });
1170
- }
1171
- return response;
1172
- }
1173
-
1174
- /**
1175
- * Route an email to the appropriate Agent
1176
- * @param email Email message to route
1177
- * @param env Environment containing Agent bindings
1178
- * @param options Routing options
1179
- */
1180
- export async function routeAgentEmail<Env>(
1181
- _email: ForwardableEmailMessage,
1182
- _env: Env,
1183
- _options?: AgentOptions<Env>
1184
- ): Promise<void> {}
1185
-
1186
- /**
1187
- * Get or create an Agent by name
1188
- * @template Env Environment type containing bindings
1189
- * @template T Type of the Agent class
1190
- * @param namespace Agent namespace
1191
- * @param name Name of the Agent instance
1192
- * @param options Options for Agent creation
1193
- * @returns Promise resolving to an Agent instance stub
1194
- */
1195
- export async function getAgentByName<Env, T extends Agent<Env>>(
1196
- namespace: AgentNamespace<T>,
1197
- name: string,
1198
- options?: {
1199
- jurisdiction?: DurableObjectJurisdiction;
1200
- locationHint?: DurableObjectLocationHint;
1201
- }
1202
- ) {
1203
- return getServerByName<Env, T>(namespace, name, options);
1204
- }
1205
-
1206
- /**
1207
- * A wrapper for streaming responses in callable methods
1208
- */
1209
- export class StreamingResponse {
1210
- private _connection: Connection;
1211
- private _id: string;
1212
- private _closed = false;
1213
-
1214
- constructor(connection: Connection, id: string) {
1215
- this._connection = connection;
1216
- this._id = id;
1217
- }
1218
-
1219
- /**
1220
- * Send a chunk of data to the client
1221
- * @param chunk The data to send
1222
- */
1223
- send(chunk: unknown) {
1224
- if (this._closed) {
1225
- throw new Error("StreamingResponse is already closed");
1226
- }
1227
- const response: RPCResponse = {
1228
- done: false,
1229
- id: this._id,
1230
- result: chunk,
1231
- success: true,
1232
- type: "rpc",
1233
- };
1234
- this._connection.send(JSON.stringify(response));
1235
- }
1236
-
1237
- /**
1238
- * End the stream and send the final chunk (if any)
1239
- * @param finalChunk Optional final chunk of data to send
1240
- */
1241
- end(finalChunk?: unknown) {
1242
- if (this._closed) {
1243
- throw new Error("StreamingResponse is already closed");
1244
- }
1245
- this._closed = true;
1246
- const response: RPCResponse = {
1247
- done: true,
1248
- id: this._id,
1249
- result: finalChunk,
1250
- success: true,
1251
- type: "rpc",
1252
- };
1253
- this._connection.send(JSON.stringify(response));
1254
- }
1255
- }