agents 0.0.0-d045755 → 0.0.0-d08612f

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