agents 0.0.0-8ebc079 → 0.0.0-8f03865

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 (80) hide show
  1. package/README.md +257 -27
  2. package/dist/ai-chat-agent.d.ts +131 -20
  3. package/dist/ai-chat-agent.js +812 -226
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-DguhuLKF.js +155 -0
  6. package/dist/ai-chat-v5-migration-DguhuLKF.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +79 -72
  10. package/dist/ai-react.js +411 -201
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-CwgHzwUb.js +24 -0
  13. package/dist/ai-types-CwgHzwUb.js.map +1 -0
  14. package/dist/ai-types-D_hTbf25.d.ts +103 -0
  15. package/dist/ai-types.d.ts +6 -74
  16. package/dist/ai-types.js +3 -1
  17. package/dist/cli/index.d.ts +1 -0
  18. package/dist/cli/index.js +28 -0
  19. package/dist/cli/index.js.map +1 -0
  20. package/dist/client-C_M5uPrn.d.ts +834 -0
  21. package/dist/client-CcyhkGfN.js +117 -0
  22. package/dist/client-CcyhkGfN.js.map +1 -0
  23. package/dist/client-ClORm6f0.d.ts +104 -0
  24. package/dist/client-QZa2Rq0l.js +1105 -0
  25. package/dist/client-QZa2Rq0l.js.map +1 -0
  26. package/dist/client.d.ts +12 -79
  27. package/dist/client.js +3 -130
  28. package/dist/codemode/ai.d.ts +27 -0
  29. package/dist/codemode/ai.js +152 -0
  30. package/dist/codemode/ai.js.map +1 -0
  31. package/dist/context-BkKbAa1R.js +8 -0
  32. package/dist/context-BkKbAa1R.js.map +1 -0
  33. package/dist/context-_sPQqJWv.d.ts +24 -0
  34. package/dist/context.d.ts +6 -0
  35. package/dist/context.js +3 -0
  36. package/dist/do-oauth-client-provider-B-ryFIPr.d.ts +70 -0
  37. package/dist/do-oauth-client-provider-B1fVIshX.js +155 -0
  38. package/dist/do-oauth-client-provider-B1fVIshX.js.map +1 -0
  39. package/dist/index-CyDpAVHZ.d.ts +58 -0
  40. package/dist/index-DUnsVDnf.d.ts +577 -0
  41. package/dist/index.d.ts +62 -310
  42. package/dist/index.js +8 -21
  43. package/dist/mcp/client.d.ts +4 -777
  44. package/dist/mcp/client.js +4 -10
  45. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  46. package/dist/mcp/do-oauth-client-provider.js +2 -106
  47. package/dist/mcp/index.d.ts +191 -71
  48. package/dist/mcp/index.js +1437 -799
  49. package/dist/mcp/index.js.map +1 -1
  50. package/dist/mcp/x402.d.ts +34 -0
  51. package/dist/mcp/x402.js +198 -0
  52. package/dist/mcp/x402.js.map +1 -0
  53. package/dist/mcp-CzbSsLfc.d.ts +61 -0
  54. package/dist/observability/index.d.ts +3 -0
  55. package/dist/observability/index.js +8 -0
  56. package/dist/react-DIGWa87z.d.ts +137 -0
  57. package/dist/react.d.ts +15 -39
  58. package/dist/react.js +190 -98
  59. package/dist/react.js.map +1 -1
  60. package/dist/schedule.d.ts +89 -12
  61. package/dist/schedule.js +46 -23
  62. package/dist/schedule.js.map +1 -1
  63. package/dist/serializable-C4GLimgv.d.ts +39 -0
  64. package/dist/serializable.d.ts +7 -0
  65. package/dist/serializable.js +1 -0
  66. package/dist/src-BmbDclOA.js +1181 -0
  67. package/dist/src-BmbDclOA.js.map +1 -0
  68. package/package.json +125 -69
  69. package/dist/ai-types.js.map +0 -1
  70. package/dist/chunk-7VFQNJFK.js +0 -462
  71. package/dist/chunk-7VFQNJFK.js.map +0 -1
  72. package/dist/chunk-HMLY7DHA.js +0 -16
  73. package/dist/chunk-HMLY7DHA.js.map +0 -1
  74. package/dist/chunk-JR3NW4A7.js +0 -621
  75. package/dist/chunk-JR3NW4A7.js.map +0 -1
  76. package/dist/client.js.map +0 -1
  77. package/dist/index.js.map +0 -1
  78. package/dist/mcp/client.js.map +0 -1
  79. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  80. package/src/index.ts +0 -956
package/src/index.ts DELETED
@@ -1,956 +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
-
17
- export type { Connection, WSMessage, ConnectionContext } from "partyserver";
18
-
19
- /**
20
- * RPC request message from client
21
- */
22
- export type RPCRequest = {
23
- type: "rpc";
24
- id: string;
25
- method: string;
26
- args: unknown[];
27
- };
28
-
29
- /**
30
- * State update message from client
31
- */
32
- export type StateUpdateMessage = {
33
- type: "cf_agent_state";
34
- state: unknown;
35
- };
36
-
37
- /**
38
- * RPC response message to client
39
- */
40
- export type RPCResponse = {
41
- type: "rpc";
42
- id: string;
43
- } & (
44
- | {
45
- success: true;
46
- result: unknown;
47
- done?: false;
48
- }
49
- | {
50
- success: true;
51
- result: unknown;
52
- done: true;
53
- }
54
- | {
55
- success: false;
56
- error: string;
57
- }
58
- );
59
-
60
- /**
61
- * Type guard for RPC request messages
62
- */
63
- function isRPCRequest(msg: unknown): msg is RPCRequest {
64
- return (
65
- typeof msg === "object" &&
66
- msg !== null &&
67
- "type" in msg &&
68
- msg.type === "rpc" &&
69
- "id" in msg &&
70
- typeof msg.id === "string" &&
71
- "method" in msg &&
72
- typeof msg.method === "string" &&
73
- "args" in msg &&
74
- Array.isArray((msg as RPCRequest).args)
75
- );
76
- }
77
-
78
- /**
79
- * Type guard for state update messages
80
- */
81
- function isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {
82
- return (
83
- typeof msg === "object" &&
84
- msg !== null &&
85
- "type" in msg &&
86
- msg.type === "cf_agent_state" &&
87
- "state" in msg
88
- );
89
- }
90
-
91
- /**
92
- * Metadata for a callable method
93
- */
94
- export type CallableMetadata = {
95
- /** Optional description of what the method does */
96
- description?: string;
97
- /** Whether the method supports streaming responses */
98
- streaming?: boolean;
99
- };
100
-
101
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
102
- const callableMetadata = new Map<Function, CallableMetadata>();
103
-
104
- /**
105
- * Decorator that marks a method as callable by clients
106
- * @param metadata Optional metadata about the callable method
107
- */
108
- export function unstable_callable(metadata: CallableMetadata = {}) {
109
- return function callableDecorator<This, Args extends unknown[], Return>(
110
- target: (this: This, ...args: Args) => Return,
111
- context: ClassMethodDecoratorContext
112
- ) {
113
- if (!callableMetadata.has(target)) {
114
- callableMetadata.set(target, metadata);
115
- }
116
-
117
- return target;
118
- };
119
- }
120
-
121
- /**
122
- * Represents a scheduled task within an Agent
123
- * @template T Type of the payload data
124
- */
125
- export type Schedule<T = string> = {
126
- /** Unique identifier for the schedule */
127
- id: string;
128
- /** Name of the method to be called */
129
- callback: string;
130
- /** Data to be passed to the callback */
131
- payload: T;
132
- } & (
133
- | {
134
- /** Type of schedule for one-time execution at a specific time */
135
- type: "scheduled";
136
- /** Timestamp when the task should execute */
137
- time: number;
138
- }
139
- | {
140
- /** Type of schedule for delayed execution */
141
- type: "delayed";
142
- /** Timestamp when the task should execute */
143
- time: number;
144
- /** Number of seconds to delay execution */
145
- delayInSeconds: number;
146
- }
147
- | {
148
- /** Type of schedule for recurring execution based on cron expression */
149
- type: "cron";
150
- /** Timestamp for the next execution */
151
- time: number;
152
- /** Cron expression defining the schedule */
153
- cron: string;
154
- }
155
- );
156
-
157
- function getNextCronTime(cron: string) {
158
- const interval = parseCronExpression(cron);
159
- return interval.getNextDate();
160
- }
161
-
162
- const STATE_ROW_ID = "cf_state_row_id";
163
- const STATE_WAS_CHANGED = "cf_state_was_changed";
164
-
165
- const DEFAULT_STATE = {} as unknown;
166
-
167
- const agentContext = new AsyncLocalStorage<{
168
- agent: Agent<unknown>;
169
- connection: Connection | undefined;
170
- request: Request | undefined;
171
- }>();
172
-
173
- export function getCurrentAgent<
174
- T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
175
- >(): {
176
- agent: T | undefined;
177
- connection: Connection | undefined;
178
- request: Request<unknown, CfProperties<unknown>> | undefined;
179
- } {
180
- const store = agentContext.getStore() as
181
- | {
182
- agent: T;
183
- connection: Connection | undefined;
184
- request: Request<unknown, CfProperties<unknown>> | undefined;
185
- }
186
- | undefined;
187
- if (!store) {
188
- return {
189
- agent: undefined,
190
- connection: undefined,
191
- request: undefined,
192
- };
193
- }
194
- return store;
195
- }
196
-
197
- /**
198
- * Base class for creating Agent implementations
199
- * @template Env Environment type containing bindings
200
- * @template State State type to store within the Agent
201
- */
202
- export class Agent<Env, State = unknown> extends Server<Env> {
203
- #state = DEFAULT_STATE as State;
204
-
205
- #ParentClass: typeof Agent<Env, State> =
206
- Object.getPrototypeOf(this).constructor;
207
-
208
- mcp: MCPClientManager = new MCPClientManager(this.#ParentClass.name, "0.0.1");
209
-
210
- /**
211
- * Initial state for the Agent
212
- * Override to provide default state values
213
- */
214
- initialState: State = DEFAULT_STATE as State;
215
-
216
- /**
217
- * Current state of the Agent
218
- */
219
- get state(): State {
220
- if (this.#state !== DEFAULT_STATE) {
221
- // state was previously set, and populated internal state
222
- return this.#state;
223
- }
224
- // looks like this is the first time the state is being accessed
225
- // check if the state was set in a previous life
226
- const wasChanged = this.sql<{ state: "true" | undefined }>`
227
- SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
228
- `;
229
-
230
- // ok, let's pick up the actual state from the db
231
- const result = this.sql<{ state: State | undefined }>`
232
- SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
233
- `;
234
-
235
- if (
236
- wasChanged[0]?.state === "true" ||
237
- // we do this check for people who updated their code before we shipped wasChanged
238
- result[0]?.state
239
- ) {
240
- const state = result[0]?.state as string; // could be null?
241
-
242
- this.#state = JSON.parse(state);
243
- return this.#state;
244
- }
245
-
246
- // ok, this is the first time the state is being accessed
247
- // and the state was not set in a previous life
248
- // so we need to set the initial state (if provided)
249
- if (this.initialState === DEFAULT_STATE) {
250
- // no initial state provided, so we return undefined
251
- return undefined as State;
252
- }
253
- // initial state provided, so we set the state,
254
- // update db and return the initial state
255
- this.setState(this.initialState);
256
- return this.initialState;
257
- }
258
-
259
- /**
260
- * Agent configuration options
261
- */
262
- static options = {
263
- /** Whether the Agent should hibernate when inactive */
264
- hibernate: true, // default to hibernate
265
- };
266
-
267
- /**
268
- * Execute SQL queries against the Agent's database
269
- * @template T Type of the returned rows
270
- * @param strings SQL query template strings
271
- * @param values Values to be inserted into the query
272
- * @returns Array of query results
273
- */
274
- sql<T = Record<string, string | number | boolean | null>>(
275
- strings: TemplateStringsArray,
276
- ...values: (string | number | boolean | null)[]
277
- ) {
278
- let query = "";
279
- try {
280
- // Construct the SQL query with placeholders
281
- query = strings.reduce(
282
- (acc, str, i) => acc + str + (i < values.length ? "?" : ""),
283
- ""
284
- );
285
-
286
- // Execute the SQL query with the provided values
287
- return [...this.ctx.storage.sql.exec(query, ...values)] as T[];
288
- } catch (e) {
289
- console.error(`failed to execute sql query: ${query}`, e);
290
- throw this.onError(e);
291
- }
292
- }
293
- constructor(ctx: AgentContext, env: Env) {
294
- super(ctx, env);
295
-
296
- this.sql`
297
- CREATE TABLE IF NOT EXISTS cf_agents_state (
298
- id TEXT PRIMARY KEY NOT NULL,
299
- state TEXT
300
- )
301
- `;
302
-
303
- void this.ctx.blockConcurrencyWhile(async () => {
304
- return this.#tryCatch(async () => {
305
- // Create alarms table if it doesn't exist
306
- this.sql`
307
- CREATE TABLE IF NOT EXISTS cf_agents_schedules (
308
- id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
309
- callback TEXT,
310
- payload TEXT,
311
- type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
312
- time INTEGER,
313
- delayInSeconds INTEGER,
314
- cron TEXT,
315
- created_at INTEGER DEFAULT (unixepoch())
316
- )
317
- `;
318
-
319
- // execute any pending alarms and schedule the next alarm
320
- await this.alarm();
321
- });
322
- });
323
-
324
- const _onRequest = this.onRequest.bind(this);
325
- this.onRequest = (request: Request) => {
326
- return agentContext.run(
327
- { agent: this, connection: undefined, request },
328
- async () => {
329
- return this.#tryCatch(() => _onRequest(request));
330
- }
331
- );
332
- };
333
-
334
- const _onMessage = this.onMessage.bind(this);
335
- this.onMessage = async (connection: Connection, message: WSMessage) => {
336
- return agentContext.run(
337
- { agent: this, connection, request: undefined },
338
- async () => {
339
- if (typeof message !== "string") {
340
- return this.#tryCatch(() => _onMessage(connection, message));
341
- }
342
-
343
- let parsed: unknown;
344
- try {
345
- parsed = JSON.parse(message);
346
- } catch (e) {
347
- // silently fail and let the onMessage handler handle it
348
- return this.#tryCatch(() => _onMessage(connection, message));
349
- }
350
-
351
- if (isStateUpdateMessage(parsed)) {
352
- this.#setStateInternal(parsed.state as State, connection);
353
- return;
354
- }
355
-
356
- if (isRPCRequest(parsed)) {
357
- try {
358
- const { id, method, args } = parsed;
359
-
360
- // Check if method exists and is callable
361
- const methodFn = this[method as keyof this];
362
- if (typeof methodFn !== "function") {
363
- throw new Error(`Method ${method} does not exist`);
364
- }
365
-
366
- if (!this.#isCallable(method)) {
367
- throw new Error(`Method ${method} is not callable`);
368
- }
369
-
370
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
371
- const metadata = callableMetadata.get(methodFn as Function);
372
-
373
- // For streaming methods, pass a StreamingResponse object
374
- if (metadata?.streaming) {
375
- const stream = new StreamingResponse(connection, id);
376
- await methodFn.apply(this, [stream, ...args]);
377
- return;
378
- }
379
-
380
- // For regular methods, execute and send response
381
- const result = await methodFn.apply(this, args);
382
- const response: RPCResponse = {
383
- type: "rpc",
384
- id,
385
- success: true,
386
- result,
387
- done: true,
388
- };
389
- connection.send(JSON.stringify(response));
390
- } catch (e) {
391
- // Send error response
392
- const response: RPCResponse = {
393
- type: "rpc",
394
- id: parsed.id,
395
- success: false,
396
- error:
397
- e instanceof Error ? e.message : "Unknown error occurred",
398
- };
399
- connection.send(JSON.stringify(response));
400
- console.error("RPC error:", e);
401
- }
402
- return;
403
- }
404
-
405
- return this.#tryCatch(() => _onMessage(connection, message));
406
- }
407
- );
408
- };
409
-
410
- const _onConnect = this.onConnect.bind(this);
411
- this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
412
- // TODO: This is a hack to ensure the state is sent after the connection is established
413
- // must fix this
414
- return agentContext.run(
415
- { agent: this, connection, request: ctx.request },
416
- async () => {
417
- setTimeout(() => {
418
- if (this.state) {
419
- connection.send(
420
- JSON.stringify({
421
- type: "cf_agent_state",
422
- state: this.state,
423
- })
424
- );
425
- }
426
- return this.#tryCatch(() => _onConnect(connection, ctx));
427
- }, 20);
428
- }
429
- );
430
- };
431
- }
432
-
433
- #setStateInternal(state: State, source: Connection | "server" = "server") {
434
- this.#state = state;
435
- this.sql`
436
- INSERT OR REPLACE INTO cf_agents_state (id, state)
437
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
438
- `;
439
- this.sql`
440
- INSERT OR REPLACE INTO cf_agents_state (id, state)
441
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
442
- `;
443
- this.broadcast(
444
- JSON.stringify({
445
- type: "cf_agent_state",
446
- state: state,
447
- }),
448
- source !== "server" ? [source.id] : []
449
- );
450
- return this.#tryCatch(() => {
451
- const { connection, request } = agentContext.getStore() || {};
452
- return agentContext.run(
453
- { agent: this, connection, request },
454
- async () => {
455
- return this.onStateUpdate(state, source);
456
- }
457
- );
458
- });
459
- }
460
-
461
- /**
462
- * Update the Agent's state
463
- * @param state New state to set
464
- */
465
- setState(state: State) {
466
- this.#setStateInternal(state, "server");
467
- }
468
-
469
- /**
470
- * Called when the Agent's state is updated
471
- * @param state Updated state
472
- * @param source Source of the state update ("server" or a client connection)
473
- */
474
- onStateUpdate(state: State | undefined, source: Connection | "server") {
475
- // override this to handle state updates
476
- }
477
-
478
- /**
479
- * Called when the Agent receives an email
480
- * @param email Email message to process
481
- */
482
- onEmail(email: ForwardableEmailMessage) {
483
- return agentContext.run(
484
- { agent: this, connection: undefined, request: undefined },
485
- async () => {
486
- console.error("onEmail not implemented");
487
- }
488
- );
489
- }
490
-
491
- async #tryCatch<T>(fn: () => T | Promise<T>) {
492
- try {
493
- return await fn();
494
- } catch (e) {
495
- throw this.onError(e);
496
- }
497
- }
498
-
499
- override onError(
500
- connection: Connection,
501
- error: unknown
502
- ): void | Promise<void>;
503
- override onError(error: unknown): void | Promise<void>;
504
- override onError(connectionOrError: Connection | unknown, error?: unknown) {
505
- let theError: unknown;
506
- if (connectionOrError && error) {
507
- theError = error;
508
- // this is a websocket connection error
509
- console.error(
510
- "Error on websocket connection:",
511
- (connectionOrError as Connection).id,
512
- theError
513
- );
514
- console.error(
515
- "Override onError(connection, error) to handle websocket connection errors"
516
- );
517
- } else {
518
- theError = connectionOrError;
519
- // this is a server error
520
- console.error("Error on server:", theError);
521
- console.error("Override onError(error) to handle server errors");
522
- }
523
- throw theError;
524
- }
525
-
526
- /**
527
- * Render content (not implemented in base class)
528
- */
529
- render() {
530
- throw new Error("Not implemented");
531
- }
532
-
533
- /**
534
- * Schedule a task to be executed in the future
535
- * @template T Type of the payload data
536
- * @param when When to execute the task (Date, seconds delay, or cron expression)
537
- * @param callback Name of the method to call
538
- * @param payload Data to pass to the callback
539
- * @returns Schedule object representing the scheduled task
540
- */
541
- async schedule<T = string>(
542
- when: Date | string | number,
543
- callback: keyof this,
544
- payload?: T
545
- ): Promise<Schedule<T>> {
546
- const id = nanoid(9);
547
-
548
- if (typeof callback !== "string") {
549
- throw new Error("Callback must be a string");
550
- }
551
-
552
- if (typeof this[callback] !== "function") {
553
- throw new Error(`this.${callback} is not a function`);
554
- }
555
-
556
- if (when instanceof Date) {
557
- const timestamp = Math.floor(when.getTime() / 1000);
558
- this.sql`
559
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
560
- VALUES (${id}, ${callback}, ${JSON.stringify(
561
- payload
562
- )}, 'scheduled', ${timestamp})
563
- `;
564
-
565
- await this.#scheduleNextAlarm();
566
-
567
- return {
568
- id,
569
- callback: callback,
570
- payload: payload as T,
571
- time: timestamp,
572
- type: "scheduled",
573
- };
574
- }
575
- if (typeof when === "number") {
576
- const time = new Date(Date.now() + when * 1000);
577
- const timestamp = Math.floor(time.getTime() / 1000);
578
-
579
- this.sql`
580
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
581
- VALUES (${id}, ${callback}, ${JSON.stringify(
582
- payload
583
- )}, 'delayed', ${when}, ${timestamp})
584
- `;
585
-
586
- await this.#scheduleNextAlarm();
587
-
588
- return {
589
- id,
590
- callback: callback,
591
- payload: payload as T,
592
- delayInSeconds: when,
593
- time: timestamp,
594
- type: "delayed",
595
- };
596
- }
597
- if (typeof when === "string") {
598
- const nextExecutionTime = getNextCronTime(when);
599
- const timestamp = Math.floor(nextExecutionTime.getTime() / 1000);
600
-
601
- this.sql`
602
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
603
- VALUES (${id}, ${callback}, ${JSON.stringify(
604
- payload
605
- )}, 'cron', ${when}, ${timestamp})
606
- `;
607
-
608
- await this.#scheduleNextAlarm();
609
-
610
- return {
611
- id,
612
- callback: callback,
613
- payload: payload as T,
614
- cron: when,
615
- time: timestamp,
616
- type: "cron",
617
- };
618
- }
619
- throw new Error("Invalid schedule type");
620
- }
621
-
622
- /**
623
- * Get a scheduled task by ID
624
- * @template T Type of the payload data
625
- * @param id ID of the scheduled task
626
- * @returns The Schedule object or undefined if not found
627
- */
628
- async getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined> {
629
- const result = this.sql<Schedule<string>>`
630
- SELECT * FROM cf_agents_schedules WHERE id = ${id}
631
- `;
632
- if (!result) {
633
- console.error(`schedule ${id} not found`);
634
- return undefined;
635
- }
636
-
637
- return { ...result[0], payload: JSON.parse(result[0].payload) as T };
638
- }
639
-
640
- /**
641
- * Get scheduled tasks matching the given criteria
642
- * @template T Type of the payload data
643
- * @param criteria Criteria to filter schedules
644
- * @returns Array of matching Schedule objects
645
- */
646
- getSchedules<T = string>(
647
- criteria: {
648
- id?: string;
649
- type?: "scheduled" | "delayed" | "cron";
650
- timeRange?: { start?: Date; end?: Date };
651
- } = {}
652
- ): Schedule<T>[] {
653
- let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
654
- const params = [];
655
-
656
- if (criteria.id) {
657
- query += " AND id = ?";
658
- params.push(criteria.id);
659
- }
660
-
661
- if (criteria.type) {
662
- query += " AND type = ?";
663
- params.push(criteria.type);
664
- }
665
-
666
- if (criteria.timeRange) {
667
- query += " AND time >= ? AND time <= ?";
668
- const start = criteria.timeRange.start || new Date(0);
669
- const end = criteria.timeRange.end || new Date(999999999999999);
670
- params.push(
671
- Math.floor(start.getTime() / 1000),
672
- Math.floor(end.getTime() / 1000)
673
- );
674
- }
675
-
676
- const result = this.ctx.storage.sql
677
- .exec(query, ...params)
678
- .toArray()
679
- .map((row) => ({
680
- ...row,
681
- payload: JSON.parse(row.payload as string) as T,
682
- })) as Schedule<T>[];
683
-
684
- return result;
685
- }
686
-
687
- /**
688
- * Cancel a scheduled task
689
- * @param id ID of the task to cancel
690
- * @returns true if the task was cancelled, false otherwise
691
- */
692
- async cancelSchedule(id: string): Promise<boolean> {
693
- this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
694
-
695
- await this.#scheduleNextAlarm();
696
- return true;
697
- }
698
-
699
- async #scheduleNextAlarm() {
700
- // Find the next schedule that needs to be executed
701
- const result = this.sql`
702
- SELECT time FROM cf_agents_schedules
703
- WHERE time > ${Math.floor(Date.now() / 1000)}
704
- ORDER BY time ASC
705
- LIMIT 1
706
- `;
707
- if (!result) return;
708
-
709
- if (result.length > 0 && "time" in result[0]) {
710
- const nextTime = (result[0].time as number) * 1000;
711
- await this.ctx.storage.setAlarm(nextTime);
712
- }
713
- }
714
-
715
- /**
716
- * Method called when an alarm fires.
717
- * Executes any scheduled tasks that are due.
718
- *
719
- * @remarks
720
- * To schedule a task, please use the `this.schedule` method instead.
721
- * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
722
- */
723
- public readonly alarm = async () => {
724
- const now = Math.floor(Date.now() / 1000);
725
-
726
- // Get all schedules that should be executed now
727
- const result = this.sql<Schedule<string>>`
728
- SELECT * FROM cf_agents_schedules WHERE time <= ${now}
729
- `;
730
-
731
- for (const row of result || []) {
732
- const callback = this[row.callback as keyof Agent<Env>];
733
- if (!callback) {
734
- console.error(`callback ${row.callback} not found`);
735
- continue;
736
- }
737
- await agentContext.run(
738
- { agent: this, connection: undefined, request: undefined },
739
- async () => {
740
- try {
741
- await (
742
- callback as (
743
- payload: unknown,
744
- schedule: Schedule<unknown>
745
- ) => Promise<void>
746
- ).bind(this)(JSON.parse(row.payload as string), row);
747
- } catch (e) {
748
- console.error(`error executing callback "${row.callback}"`, e);
749
- }
750
- }
751
- );
752
- if (row.type === "cron") {
753
- // Update next execution time for cron schedules
754
- const nextExecutionTime = getNextCronTime(row.cron);
755
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
756
-
757
- this.sql`
758
- UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
759
- `;
760
- } else {
761
- // Delete one-time schedules after execution
762
- this.sql`
763
- DELETE FROM cf_agents_schedules WHERE id = ${row.id}
764
- `;
765
- }
766
- }
767
-
768
- // Schedule the next alarm
769
- await this.#scheduleNextAlarm();
770
- };
771
-
772
- /**
773
- * Destroy the Agent, removing all state and scheduled tasks
774
- */
775
- async destroy() {
776
- // drop all tables
777
- this.sql`DROP TABLE IF EXISTS cf_agents_state`;
778
- this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
779
-
780
- // delete all alarms
781
- await this.ctx.storage.deleteAlarm();
782
- await this.ctx.storage.deleteAll();
783
- }
784
-
785
- /**
786
- * Get all methods marked as callable on this Agent
787
- * @returns A map of method names to their metadata
788
- */
789
- #isCallable(method: string): boolean {
790
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
791
- return callableMetadata.has(this[method as keyof this] as Function);
792
- }
793
- }
794
-
795
- /**
796
- * Namespace for creating Agent instances
797
- * @template Agentic Type of the Agent class
798
- */
799
- export type AgentNamespace<Agentic extends Agent<unknown>> =
800
- DurableObjectNamespace<Agentic>;
801
-
802
- /**
803
- * Agent's durable context
804
- */
805
- export type AgentContext = DurableObjectState;
806
-
807
- /**
808
- * Configuration options for Agent routing
809
- */
810
- export type AgentOptions<Env> = PartyServerOptions<Env> & {
811
- /**
812
- * Whether to enable CORS for the Agent
813
- */
814
- cors?: boolean | HeadersInit | undefined;
815
- };
816
-
817
- /**
818
- * Route a request to the appropriate Agent
819
- * @param request Request to route
820
- * @param env Environment containing Agent bindings
821
- * @param options Routing options
822
- * @returns Response from the Agent or undefined if no route matched
823
- */
824
- export async function routeAgentRequest<Env>(
825
- request: Request,
826
- env: Env,
827
- options?: AgentOptions<Env>
828
- ) {
829
- const corsHeaders =
830
- options?.cors === true
831
- ? {
832
- "Access-Control-Allow-Origin": "*",
833
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
834
- "Access-Control-Allow-Credentials": "true",
835
- "Access-Control-Max-Age": "86400",
836
- }
837
- : options?.cors;
838
-
839
- if (request.method === "OPTIONS") {
840
- if (corsHeaders) {
841
- return new Response(null, {
842
- headers: corsHeaders,
843
- });
844
- }
845
- console.warn(
846
- "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
847
- );
848
- }
849
-
850
- let response = await routePartykitRequest(
851
- request,
852
- env as Record<string, unknown>,
853
- {
854
- prefix: "agents",
855
- ...(options as PartyServerOptions<Record<string, unknown>>),
856
- }
857
- );
858
-
859
- if (
860
- response &&
861
- corsHeaders &&
862
- request.headers.get("upgrade")?.toLowerCase() !== "websocket" &&
863
- request.headers.get("Upgrade")?.toLowerCase() !== "websocket"
864
- ) {
865
- response = new Response(response.body, {
866
- headers: {
867
- ...response.headers,
868
- ...corsHeaders,
869
- },
870
- });
871
- }
872
- return response;
873
- }
874
-
875
- /**
876
- * Route an email to the appropriate Agent
877
- * @param email Email message to route
878
- * @param env Environment containing Agent bindings
879
- * @param options Routing options
880
- */
881
- export async function routeAgentEmail<Env>(
882
- email: ForwardableEmailMessage,
883
- env: Env,
884
- options?: AgentOptions<Env>
885
- ): Promise<void> {}
886
-
887
- /**
888
- * Get or create an Agent by name
889
- * @template Env Environment type containing bindings
890
- * @template T Type of the Agent class
891
- * @param namespace Agent namespace
892
- * @param name Name of the Agent instance
893
- * @param options Options for Agent creation
894
- * @returns Promise resolving to an Agent instance stub
895
- */
896
- export async function getAgentByName<Env, T extends Agent<Env>>(
897
- namespace: AgentNamespace<T>,
898
- name: string,
899
- options?: {
900
- jurisdiction?: DurableObjectJurisdiction;
901
- locationHint?: DurableObjectLocationHint;
902
- }
903
- ) {
904
- return getServerByName<Env, T>(namespace, name, options);
905
- }
906
-
907
- /**
908
- * A wrapper for streaming responses in callable methods
909
- */
910
- export class StreamingResponse {
911
- #connection: Connection;
912
- #id: string;
913
- #closed = false;
914
-
915
- constructor(connection: Connection, id: string) {
916
- this.#connection = connection;
917
- this.#id = id;
918
- }
919
-
920
- /**
921
- * Send a chunk of data to the client
922
- * @param chunk The data to send
923
- */
924
- send(chunk: unknown) {
925
- if (this.#closed) {
926
- throw new Error("StreamingResponse is already closed");
927
- }
928
- const response: RPCResponse = {
929
- type: "rpc",
930
- id: this.#id,
931
- success: true,
932
- result: chunk,
933
- done: false,
934
- };
935
- this.#connection.send(JSON.stringify(response));
936
- }
937
-
938
- /**
939
- * End the stream and send the final chunk (if any)
940
- * @param finalChunk Optional final chunk of data to send
941
- */
942
- end(finalChunk?: unknown) {
943
- if (this.#closed) {
944
- throw new Error("StreamingResponse is already closed");
945
- }
946
- this.#closed = true;
947
- const response: RPCResponse = {
948
- type: "rpc",
949
- id: this.#id,
950
- success: true,
951
- result: finalChunk,
952
- done: true,
953
- };
954
- this.#connection.send(JSON.stringify(response));
955
- }
956
- }