agents 0.0.0-4100b67 → 0.0.0-412321b

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