agents 0.0.0-d40512c → 0.0.0-d520fe8

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