agents 0.0.0-d6a4eda → 0.0.0-d6d6d60

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 (77) hide show
  1. package/README.md +255 -27
  2. package/dist/ai-chat-agent.d.ts +20 -17
  3. package/dist/ai-chat-agent.js +532 -222
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-DBHGW4Hv.js +155 -0
  6. package/dist/ai-chat-v5-migration-DBHGW4Hv.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +73 -84
  10. package/dist/ai-react.js +266 -199
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-B3aQaFv3.js +20 -0
  13. package/dist/ai-types-B3aQaFv3.js.map +1 -0
  14. package/dist/ai-types-D5YoPrBZ.d.ts +95 -0
  15. package/dist/ai-types.d.ts +6 -74
  16. package/dist/ai-types.js +3 -1
  17. package/dist/cli.d.ts +8 -0
  18. package/dist/cli.js +27 -0
  19. package/dist/cli.js.map +1 -0
  20. package/dist/client-BfiZ3HQd.js +117 -0
  21. package/dist/client-BfiZ3HQd.js.map +1 -0
  22. package/dist/client-Bws9q38u.d.ts +5427 -0
  23. package/dist/client-CbWe9FBd.d.ts +104 -0
  24. package/dist/client-DvK0u9vD.js +898 -0
  25. package/dist/client-DvK0u9vD.js.map +1 -0
  26. package/dist/client.d.ts +12 -87
  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-CcTno-25.d.ts +142 -0
  32. package/dist/do-oauth-client-provider-D2P1lSft.js +93 -0
  33. package/dist/do-oauth-client-provider-D2P1lSft.js.map +1 -0
  34. package/dist/index-Bdzb2feZ.d.ts +572 -0
  35. package/dist/index-DhJCaDWd.d.ts +58 -0
  36. package/dist/index.d.ts +62 -392
  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 +1428 -767
  44. package/dist/mcp/index.js.map +1 -1
  45. package/dist/mcp/x402.d.ts +34 -0
  46. package/dist/mcp/x402.js +194 -0
  47. package/dist/mcp/x402.js.map +1 -0
  48. package/dist/mcp-Dw5vDrY8.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-DFNXTQzy.d.ts +113 -0
  52. package/dist/react.d.ts +10 -53
  53. package/dist/react.js +183 -100
  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-CymX8ovI.d.ts +39 -0
  59. package/dist/serializable.d.ts +7 -0
  60. package/dist/serializable.js +1 -0
  61. package/dist/src-C1WWpbRo.js +1247 -0
  62. package/dist/src-C1WWpbRo.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-QSGN3REV.js +0 -123
  68. package/dist/chunk-QSGN3REV.js.map +0 -1
  69. package/dist/chunk-RIYR6FR6.js +0 -777
  70. package/dist/chunk-RIYR6FR6.js.map +0 -1
  71. package/dist/chunk-Y67CHZBI.js +0 -464
  72. package/dist/chunk-Y67CHZBI.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/src/index.ts +0 -1243
package/src/index.ts DELETED
@@ -1,1243 +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
- private _state = DEFAULT_STATE as State;
255
-
256
- private _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
- private _setStateInternal(
562
- state: State,
563
- source: Connection | "server" = "server"
564
- ) {
565
- this._state = state;
566
- this.sql`
567
- INSERT OR REPLACE INTO cf_agents_state (id, state)
568
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
569
- `;
570
- this.sql`
571
- INSERT OR REPLACE INTO cf_agents_state (id, state)
572
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
573
- `;
574
- this.broadcast(
575
- JSON.stringify({
576
- type: "cf_agent_state",
577
- state: state,
578
- }),
579
- source !== "server" ? [source.id] : []
580
- );
581
- return this._tryCatch(() => {
582
- const { connection, request } = agentContext.getStore() || {};
583
- return agentContext.run(
584
- { agent: this, connection, request },
585
- async () => {
586
- return this.onStateUpdate(state, source);
587
- }
588
- );
589
- });
590
- }
591
-
592
- /**
593
- * Update the Agent's state
594
- * @param state New state to set
595
- */
596
- setState(state: State) {
597
- this._setStateInternal(state, "server");
598
- }
599
-
600
- /**
601
- * Called when the Agent's state is updated
602
- * @param state Updated state
603
- * @param source Source of the state update ("server" or a client connection)
604
- */
605
- onStateUpdate(state: State | undefined, source: Connection | "server") {
606
- // override this to handle state updates
607
- }
608
-
609
- /**
610
- * Called when the Agent receives an email
611
- * @param email Email message to process
612
- */
613
- onEmail(email: ForwardableEmailMessage) {
614
- return agentContext.run(
615
- { agent: this, connection: undefined, request: undefined },
616
- async () => {
617
- console.error("onEmail not implemented");
618
- }
619
- );
620
- }
621
-
622
- private async _tryCatch<T>(fn: () => T | Promise<T>) {
623
- try {
624
- return await fn();
625
- } catch (e) {
626
- throw this.onError(e);
627
- }
628
- }
629
-
630
- override onError(
631
- connection: Connection,
632
- error: unknown
633
- ): void | Promise<void>;
634
- override onError(error: unknown): void | Promise<void>;
635
- override onError(connectionOrError: Connection | unknown, error?: unknown) {
636
- let theError: unknown;
637
- if (connectionOrError && error) {
638
- theError = error;
639
- // this is a websocket connection error
640
- console.error(
641
- "Error on websocket connection:",
642
- (connectionOrError as Connection).id,
643
- theError
644
- );
645
- console.error(
646
- "Override onError(connection, error) to handle websocket connection errors"
647
- );
648
- } else {
649
- theError = connectionOrError;
650
- // this is a server error
651
- console.error("Error on server:", theError);
652
- console.error("Override onError(error) to handle server errors");
653
- }
654
- throw theError;
655
- }
656
-
657
- /**
658
- * Render content (not implemented in base class)
659
- */
660
- render() {
661
- throw new Error("Not implemented");
662
- }
663
-
664
- /**
665
- * Schedule a task to be executed in the future
666
- * @template T Type of the payload data
667
- * @param when When to execute the task (Date, seconds delay, or cron expression)
668
- * @param callback Name of the method to call
669
- * @param payload Data to pass to the callback
670
- * @returns Schedule object representing the scheduled task
671
- */
672
- async schedule<T = string>(
673
- when: Date | string | number,
674
- callback: keyof this,
675
- payload?: T
676
- ): Promise<Schedule<T>> {
677
- const id = nanoid(9);
678
-
679
- if (typeof callback !== "string") {
680
- throw new Error("Callback must be a string");
681
- }
682
-
683
- if (typeof this[callback] !== "function") {
684
- throw new Error(`this.${callback} is not a function`);
685
- }
686
-
687
- if (when instanceof Date) {
688
- const timestamp = Math.floor(when.getTime() / 1000);
689
- this.sql`
690
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
691
- VALUES (${id}, ${callback}, ${JSON.stringify(
692
- payload
693
- )}, 'scheduled', ${timestamp})
694
- `;
695
-
696
- await this._scheduleNextAlarm();
697
-
698
- return {
699
- id,
700
- callback: callback,
701
- payload: payload as T,
702
- time: timestamp,
703
- type: "scheduled",
704
- };
705
- }
706
- if (typeof when === "number") {
707
- const time = new Date(Date.now() + when * 1000);
708
- const timestamp = Math.floor(time.getTime() / 1000);
709
-
710
- this.sql`
711
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
712
- VALUES (${id}, ${callback}, ${JSON.stringify(
713
- payload
714
- )}, 'delayed', ${when}, ${timestamp})
715
- `;
716
-
717
- await this._scheduleNextAlarm();
718
-
719
- return {
720
- id,
721
- callback: callback,
722
- payload: payload as T,
723
- delayInSeconds: when,
724
- time: timestamp,
725
- type: "delayed",
726
- };
727
- }
728
- if (typeof when === "string") {
729
- const nextExecutionTime = getNextCronTime(when);
730
- const timestamp = Math.floor(nextExecutionTime.getTime() / 1000);
731
-
732
- this.sql`
733
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
734
- VALUES (${id}, ${callback}, ${JSON.stringify(
735
- payload
736
- )}, 'cron', ${when}, ${timestamp})
737
- `;
738
-
739
- await this._scheduleNextAlarm();
740
-
741
- return {
742
- id,
743
- callback: callback,
744
- payload: payload as T,
745
- cron: when,
746
- time: timestamp,
747
- type: "cron",
748
- };
749
- }
750
- throw new Error("Invalid schedule type");
751
- }
752
-
753
- /**
754
- * Get a scheduled task by ID
755
- * @template T Type of the payload data
756
- * @param id ID of the scheduled task
757
- * @returns The Schedule object or undefined if not found
758
- */
759
- async getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined> {
760
- const result = this.sql<Schedule<string>>`
761
- SELECT * FROM cf_agents_schedules WHERE id = ${id}
762
- `;
763
- if (!result) {
764
- console.error(`schedule ${id} not found`);
765
- return undefined;
766
- }
767
-
768
- return { ...result[0], payload: JSON.parse(result[0].payload) as T };
769
- }
770
-
771
- /**
772
- * Get scheduled tasks matching the given criteria
773
- * @template T Type of the payload data
774
- * @param criteria Criteria to filter schedules
775
- * @returns Array of matching Schedule objects
776
- */
777
- getSchedules<T = string>(
778
- criteria: {
779
- id?: string;
780
- type?: "scheduled" | "delayed" | "cron";
781
- timeRange?: { start?: Date; end?: Date };
782
- } = {}
783
- ): Schedule<T>[] {
784
- let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
785
- const params = [];
786
-
787
- if (criteria.id) {
788
- query += " AND id = ?";
789
- params.push(criteria.id);
790
- }
791
-
792
- if (criteria.type) {
793
- query += " AND type = ?";
794
- params.push(criteria.type);
795
- }
796
-
797
- if (criteria.timeRange) {
798
- query += " AND time >= ? AND time <= ?";
799
- const start = criteria.timeRange.start || new Date(0);
800
- const end = criteria.timeRange.end || new Date(999999999999999);
801
- params.push(
802
- Math.floor(start.getTime() / 1000),
803
- Math.floor(end.getTime() / 1000)
804
- );
805
- }
806
-
807
- const result = this.ctx.storage.sql
808
- .exec(query, ...params)
809
- .toArray()
810
- .map((row) => ({
811
- ...row,
812
- payload: JSON.parse(row.payload as string) as T,
813
- })) as Schedule<T>[];
814
-
815
- return result;
816
- }
817
-
818
- /**
819
- * Cancel a scheduled task
820
- * @param id ID of the task to cancel
821
- * @returns true if the task was cancelled, false otherwise
822
- */
823
- async cancelSchedule(id: string): Promise<boolean> {
824
- this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
825
-
826
- await this._scheduleNextAlarm();
827
- return true;
828
- }
829
-
830
- private async _scheduleNextAlarm() {
831
- // Find the next schedule that needs to be executed
832
- const result = this.sql`
833
- SELECT time FROM cf_agents_schedules
834
- WHERE time > ${Math.floor(Date.now() / 1000)}
835
- ORDER BY time ASC
836
- LIMIT 1
837
- `;
838
- if (!result) return;
839
-
840
- if (result.length > 0 && "time" in result[0]) {
841
- const nextTime = (result[0].time as number) * 1000;
842
- await this.ctx.storage.setAlarm(nextTime);
843
- }
844
- }
845
-
846
- /**
847
- * Method called when an alarm fires.
848
- * Executes any scheduled tasks that are due.
849
- *
850
- * @remarks
851
- * To schedule a task, please use the `this.schedule` method instead.
852
- * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
853
- */
854
- public readonly alarm = async () => {
855
- const now = Math.floor(Date.now() / 1000);
856
-
857
- // Get all schedules that should be executed now
858
- const result = this.sql<Schedule<string>>`
859
- SELECT * FROM cf_agents_schedules WHERE time <= ${now}
860
- `;
861
-
862
- for (const row of result || []) {
863
- const callback = this[row.callback as keyof Agent<Env>];
864
- if (!callback) {
865
- console.error(`callback ${row.callback} not found`);
866
- continue;
867
- }
868
- await agentContext.run(
869
- { agent: this, connection: undefined, request: undefined },
870
- async () => {
871
- try {
872
- await (
873
- callback as (
874
- payload: unknown,
875
- schedule: Schedule<unknown>
876
- ) => Promise<void>
877
- ).bind(this)(JSON.parse(row.payload as string), row);
878
- } catch (e) {
879
- console.error(`error executing callback "${row.callback}"`, e);
880
- }
881
- }
882
- );
883
- if (row.type === "cron") {
884
- // Update next execution time for cron schedules
885
- const nextExecutionTime = getNextCronTime(row.cron);
886
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
887
-
888
- this.sql`
889
- UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
890
- `;
891
- } else {
892
- // Delete one-time schedules after execution
893
- this.sql`
894
- DELETE FROM cf_agents_schedules WHERE id = ${row.id}
895
- `;
896
- }
897
- }
898
-
899
- // Schedule the next alarm
900
- await this._scheduleNextAlarm();
901
- };
902
-
903
- /**
904
- * Destroy the Agent, removing all state and scheduled tasks
905
- */
906
- async destroy() {
907
- // drop all tables
908
- this.sql`DROP TABLE IF EXISTS cf_agents_state`;
909
- this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
910
- this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
911
-
912
- // delete all alarms
913
- await this.ctx.storage.deleteAlarm();
914
- await this.ctx.storage.deleteAll();
915
- }
916
-
917
- private _isCallable(method: string): boolean {
918
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
919
- return callableMetadata.has(this[method as keyof this] as Function);
920
- }
921
-
922
- /**
923
- * Connect to a new MCP Server
924
- *
925
- * @param url MCP Server SSE URL
926
- * @param callbackHost Base host for the agent, used for the redirect URI.
927
- * @param agentsPrefix agents routing prefix if not using `agents`
928
- * @param options MCP client and transport (header) options
929
- * @returns authUrl
930
- */
931
- async addMcpServer(
932
- serverName: string,
933
- url: string,
934
- callbackHost: string,
935
- agentsPrefix = "agents",
936
- options?: {
937
- client?: ConstructorParameters<typeof Client>[1];
938
- transport?: {
939
- headers: HeadersInit;
940
- };
941
- }
942
- ): Promise<{ id: string; authUrl: string | undefined }> {
943
- const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
944
-
945
- const result = await this._connectToMcpServerInternal(
946
- serverName,
947
- url,
948
- callbackUrl,
949
- options
950
- );
951
-
952
- this.broadcast(
953
- JSON.stringify({
954
- type: "cf_agent_mcp_servers",
955
- mcp: this._getMcpServerStateInternal(),
956
- })
957
- );
958
-
959
- return result;
960
- }
961
-
962
- async _connectToMcpServerInternal(
963
- serverName: string,
964
- url: string,
965
- callbackUrl: string,
966
- // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
967
- options?: {
968
- client?: ConstructorParameters<typeof Client>[1];
969
- /**
970
- * We don't expose the normal set of transport options because:
971
- * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
972
- * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
973
- *
974
- * 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).
975
- */
976
- transport?: {
977
- headers?: HeadersInit;
978
- };
979
- },
980
- reconnect?: {
981
- id: string;
982
- oauthClientId?: string;
983
- }
984
- ): Promise<{ id: string; authUrl: string | undefined }> {
985
- const authProvider = new DurableObjectOAuthClientProvider(
986
- this.ctx.storage,
987
- this.name,
988
- callbackUrl
989
- );
990
-
991
- if (reconnect) {
992
- authProvider.serverId = reconnect.id;
993
- if (reconnect.oauthClientId) {
994
- authProvider.clientId = reconnect.oauthClientId;
995
- }
996
- }
997
-
998
- // allows passing through transport headers if necessary
999
- // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
1000
- let headerTransportOpts: SSEClientTransportOptions = {};
1001
- if (options?.transport?.headers) {
1002
- headerTransportOpts = {
1003
- eventSourceInit: {
1004
- fetch: (url, init) =>
1005
- fetch(url, {
1006
- ...init,
1007
- headers: options?.transport?.headers,
1008
- }),
1009
- },
1010
- requestInit: {
1011
- headers: options?.transport?.headers,
1012
- },
1013
- };
1014
- }
1015
-
1016
- const { id, authUrl, clientId } = await this.mcp.connect(url, {
1017
- reconnect,
1018
- transport: {
1019
- ...headerTransportOpts,
1020
- authProvider,
1021
- },
1022
- client: options?.client,
1023
- });
1024
-
1025
- this.sql`
1026
- INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1027
- VALUES (
1028
- ${id},
1029
- ${serverName},
1030
- ${url},
1031
- ${clientId ?? null},
1032
- ${authUrl ?? null},
1033
- ${callbackUrl},
1034
- ${options ? JSON.stringify(options) : null}
1035
- );
1036
- `;
1037
-
1038
- return {
1039
- id,
1040
- authUrl,
1041
- };
1042
- }
1043
-
1044
- async removeMcpServer(id: string) {
1045
- this.mcp.closeConnection(id);
1046
- this.sql`
1047
- DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1048
- `;
1049
- this.broadcast(
1050
- JSON.stringify({
1051
- type: "cf_agent_mcp_servers",
1052
- mcp: this._getMcpServerStateInternal(),
1053
- })
1054
- );
1055
- }
1056
-
1057
- private _getMcpServerStateInternal(): MCPServersState {
1058
- const mcpState: MCPServersState = {
1059
- servers: {},
1060
- tools: this.mcp.listTools(),
1061
- prompts: this.mcp.listPrompts(),
1062
- resources: this.mcp.listResources(),
1063
- };
1064
-
1065
- const servers = this.sql<MCPServerRow>`
1066
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1067
- `;
1068
-
1069
- for (const server of servers) {
1070
- mcpState.servers[server.id] = {
1071
- name: server.name,
1072
- server_url: server.server_url,
1073
- auth_url: server.auth_url,
1074
- state: this.mcp.mcpConnections[server.id].connectionState,
1075
- };
1076
- }
1077
-
1078
- return mcpState;
1079
- }
1080
- }
1081
-
1082
- /**
1083
- * Namespace for creating Agent instances
1084
- * @template Agentic Type of the Agent class
1085
- */
1086
- export type AgentNamespace<Agentic extends Agent<unknown>> =
1087
- DurableObjectNamespace<Agentic>;
1088
-
1089
- /**
1090
- * Agent's durable context
1091
- */
1092
- export type AgentContext = DurableObjectState;
1093
-
1094
- /**
1095
- * Configuration options for Agent routing
1096
- */
1097
- export type AgentOptions<Env> = PartyServerOptions<Env> & {
1098
- /**
1099
- * Whether to enable CORS for the Agent
1100
- */
1101
- cors?: boolean | HeadersInit | undefined;
1102
- };
1103
-
1104
- /**
1105
- * Route a request to the appropriate Agent
1106
- * @param request Request to route
1107
- * @param env Environment containing Agent bindings
1108
- * @param options Routing options
1109
- * @returns Response from the Agent or undefined if no route matched
1110
- */
1111
- export async function routeAgentRequest<Env>(
1112
- request: Request,
1113
- env: Env,
1114
- options?: AgentOptions<Env>
1115
- ) {
1116
- const corsHeaders =
1117
- options?.cors === true
1118
- ? {
1119
- "Access-Control-Allow-Origin": "*",
1120
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1121
- "Access-Control-Allow-Credentials": "true",
1122
- "Access-Control-Max-Age": "86400",
1123
- }
1124
- : options?.cors;
1125
-
1126
- if (request.method === "OPTIONS") {
1127
- if (corsHeaders) {
1128
- return new Response(null, {
1129
- headers: corsHeaders,
1130
- });
1131
- }
1132
- console.warn(
1133
- "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
1134
- );
1135
- }
1136
-
1137
- let response = await routePartykitRequest(
1138
- request,
1139
- env as Record<string, unknown>,
1140
- {
1141
- prefix: "agents",
1142
- ...(options as PartyServerOptions<Record<string, unknown>>),
1143
- }
1144
- );
1145
-
1146
- if (
1147
- response &&
1148
- corsHeaders &&
1149
- request.headers.get("upgrade")?.toLowerCase() !== "websocket" &&
1150
- request.headers.get("Upgrade")?.toLowerCase() !== "websocket"
1151
- ) {
1152
- response = new Response(response.body, {
1153
- headers: {
1154
- ...response.headers,
1155
- ...corsHeaders,
1156
- },
1157
- });
1158
- }
1159
- return response;
1160
- }
1161
-
1162
- /**
1163
- * Route an email to the appropriate Agent
1164
- * @param email Email message to route
1165
- * @param env Environment containing Agent bindings
1166
- * @param options Routing options
1167
- */
1168
- export async function routeAgentEmail<Env>(
1169
- email: ForwardableEmailMessage,
1170
- env: Env,
1171
- options?: AgentOptions<Env>
1172
- ): Promise<void> {}
1173
-
1174
- /**
1175
- * Get or create an Agent by name
1176
- * @template Env Environment type containing bindings
1177
- * @template T Type of the Agent class
1178
- * @param namespace Agent namespace
1179
- * @param name Name of the Agent instance
1180
- * @param options Options for Agent creation
1181
- * @returns Promise resolving to an Agent instance stub
1182
- */
1183
- export async function getAgentByName<Env, T extends Agent<Env>>(
1184
- namespace: AgentNamespace<T>,
1185
- name: string,
1186
- options?: {
1187
- jurisdiction?: DurableObjectJurisdiction;
1188
- locationHint?: DurableObjectLocationHint;
1189
- }
1190
- ) {
1191
- return getServerByName<Env, T>(namespace, name, options);
1192
- }
1193
-
1194
- /**
1195
- * A wrapper for streaming responses in callable methods
1196
- */
1197
- export class StreamingResponse {
1198
- private _connection: Connection;
1199
- private _id: string;
1200
- private _closed = false;
1201
-
1202
- constructor(connection: Connection, id: string) {
1203
- this._connection = connection;
1204
- this._id = id;
1205
- }
1206
-
1207
- /**
1208
- * Send a chunk of data to the client
1209
- * @param chunk The data to send
1210
- */
1211
- send(chunk: unknown) {
1212
- if (this._closed) {
1213
- throw new Error("StreamingResponse is already closed");
1214
- }
1215
- const response: RPCResponse = {
1216
- type: "rpc",
1217
- id: this._id,
1218
- success: true,
1219
- result: chunk,
1220
- done: false,
1221
- };
1222
- this._connection.send(JSON.stringify(response));
1223
- }
1224
-
1225
- /**
1226
- * End the stream and send the final chunk (if any)
1227
- * @param finalChunk Optional final chunk of data to send
1228
- */
1229
- end(finalChunk?: unknown) {
1230
- if (this._closed) {
1231
- throw new Error("StreamingResponse is already closed");
1232
- }
1233
- this._closed = true;
1234
- const response: RPCResponse = {
1235
- type: "rpc",
1236
- id: this._id,
1237
- success: true,
1238
- result: finalChunk,
1239
- done: true,
1240
- };
1241
- this._connection.send(JSON.stringify(response));
1242
- }
1243
- }