agents 0.0.0-e03246e → 0.0.0-e173b41

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 (72) hide show
  1. package/README.md +257 -27
  2. package/dist/ai-chat-agent.d.ts +133 -12
  3. package/dist/ai-chat-agent.js +798 -160
  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 -72
  10. package/dist/ai-react.js +411 -192
  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 -69
  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 +12 -79
  27. package/dist/client.js +3 -130
  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-Bx5KK3VJ.d.ts +587 -0
  36. package/dist/index.d.ts +63 -301
  37. package/dist/index.js +7 -22
  38. package/dist/mcp/client.d.ts +4 -675
  39. package/dist/mcp/client.js +3 -267
  40. package/dist/mcp/do-oauth-client-provider.d.ts +2 -0
  41. package/dist/mcp/do-oauth-client-provider.js +3 -0
  42. package/dist/mcp/index.d.ts +191 -43
  43. package/dist/mcp/index.js +1438 -334
  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 -0
  50. package/dist/observability/index.js +7 -0
  51. package/dist/react-CbwD4fBf.d.ts +113 -0
  52. package/dist/react.d.ts +10 -39
  53. package/dist/react.js +183 -98
  54. package/dist/react.js.map +1 -1
  55. package/dist/schedule.d.ts +89 -12
  56. package/dist/schedule.js +46 -23
  57. package/dist/schedule.js.map +1 -1
  58. package/dist/serializable-faDkMCai.d.ts +39 -0
  59. package/dist/serializable.d.ts +7 -0
  60. package/dist/serializable.js +1 -0
  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 +130 -51
  64. package/dist/ai-types.js.map +0 -1
  65. package/dist/chunk-HMLY7DHA.js +0 -16
  66. package/dist/chunk-HMLY7DHA.js.map +0 -1
  67. package/dist/chunk-YMUU7QHV.js +0 -595
  68. package/dist/chunk-YMUU7QHV.js.map +0 -1
  69. package/dist/client.js.map +0 -1
  70. package/dist/index.js.map +0 -1
  71. package/dist/mcp/client.js.map +0 -1
  72. package/src/index.ts +0 -919
package/src/index.ts DELETED
@@ -1,919 +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 unstable_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 unstable_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 unstable_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 } = unstable_context.getStore() || {};
419
- return unstable_context.run(
420
- { agent: this, connection, request },
421
- async () => {
422
- return this.onStateUpdate(state, source);
423
- }
424
- );
425
- });
426
- }
427
-
428
- /**
429
- * Update the Agent's state
430
- * @param state New state to set
431
- */
432
- setState(state: State) {
433
- this.#setStateInternal(state, "server");
434
- }
435
-
436
- /**
437
- * Called when the Agent's state is updated
438
- * @param state Updated state
439
- * @param source Source of the state update ("server" or a client connection)
440
- */
441
- onStateUpdate(state: State | undefined, source: Connection | "server") {
442
- // override this to handle state updates
443
- }
444
-
445
- /**
446
- * Called when the Agent receives an email
447
- * @param email Email message to process
448
- */
449
- onEmail(email: ForwardableEmailMessage) {
450
- return unstable_context.run(
451
- { agent: this, connection: undefined, request: undefined },
452
- async () => {
453
- console.error("onEmail not implemented");
454
- }
455
- );
456
- }
457
-
458
- async #tryCatch<T>(fn: () => T | Promise<T>) {
459
- try {
460
- return await fn();
461
- } catch (e) {
462
- throw this.onError(e);
463
- }
464
- }
465
-
466
- override onError(
467
- connection: Connection,
468
- error: unknown
469
- ): void | Promise<void>;
470
- override onError(error: unknown): void | Promise<void>;
471
- override onError(connectionOrError: Connection | unknown, error?: unknown) {
472
- let theError: unknown;
473
- if (connectionOrError && error) {
474
- theError = error;
475
- // this is a websocket connection error
476
- console.error(
477
- "Error on websocket connection:",
478
- (connectionOrError as Connection).id,
479
- theError
480
- );
481
- console.error(
482
- "Override onError(connection, error) to handle websocket connection errors"
483
- );
484
- } else {
485
- theError = connectionOrError;
486
- // this is a server error
487
- console.error("Error on server:", theError);
488
- console.error("Override onError(error) to handle server errors");
489
- }
490
- throw theError;
491
- }
492
-
493
- /**
494
- * Render content (not implemented in base class)
495
- */
496
- render() {
497
- throw new Error("Not implemented");
498
- }
499
-
500
- /**
501
- * Schedule a task to be executed in the future
502
- * @template T Type of the payload data
503
- * @param when When to execute the task (Date, seconds delay, or cron expression)
504
- * @param callback Name of the method to call
505
- * @param payload Data to pass to the callback
506
- * @returns Schedule object representing the scheduled task
507
- */
508
- async schedule<T = string>(
509
- when: Date | string | number,
510
- callback: keyof this,
511
- payload?: T
512
- ): Promise<Schedule<T>> {
513
- const id = nanoid(9);
514
-
515
- if (typeof callback !== "string") {
516
- throw new Error("Callback must be a string");
517
- }
518
-
519
- if (typeof this[callback] !== "function") {
520
- throw new Error(`this.${callback} is not a function`);
521
- }
522
-
523
- if (when instanceof Date) {
524
- const timestamp = Math.floor(when.getTime() / 1000);
525
- this.sql`
526
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
527
- VALUES (${id}, ${callback}, ${JSON.stringify(
528
- payload
529
- )}, 'scheduled', ${timestamp})
530
- `;
531
-
532
- await this.#scheduleNextAlarm();
533
-
534
- return {
535
- id,
536
- callback: callback,
537
- payload: payload as T,
538
- time: timestamp,
539
- type: "scheduled",
540
- };
541
- }
542
- if (typeof when === "number") {
543
- const time = new Date(Date.now() + when * 1000);
544
- const timestamp = Math.floor(time.getTime() / 1000);
545
-
546
- this.sql`
547
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
548
- VALUES (${id}, ${callback}, ${JSON.stringify(
549
- payload
550
- )}, 'delayed', ${when}, ${timestamp})
551
- `;
552
-
553
- await this.#scheduleNextAlarm();
554
-
555
- return {
556
- id,
557
- callback: callback,
558
- payload: payload as T,
559
- delayInSeconds: when,
560
- time: timestamp,
561
- type: "delayed",
562
- };
563
- }
564
- if (typeof when === "string") {
565
- const nextExecutionTime = getNextCronTime(when);
566
- const timestamp = Math.floor(nextExecutionTime.getTime() / 1000);
567
-
568
- this.sql`
569
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
570
- VALUES (${id}, ${callback}, ${JSON.stringify(
571
- payload
572
- )}, 'cron', ${when}, ${timestamp})
573
- `;
574
-
575
- await this.#scheduleNextAlarm();
576
-
577
- return {
578
- id,
579
- callback: callback,
580
- payload: payload as T,
581
- cron: when,
582
- time: timestamp,
583
- type: "cron",
584
- };
585
- }
586
- throw new Error("Invalid schedule type");
587
- }
588
-
589
- /**
590
- * Get a scheduled task by ID
591
- * @template T Type of the payload data
592
- * @param id ID of the scheduled task
593
- * @returns The Schedule object or undefined if not found
594
- */
595
- async getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined> {
596
- const result = this.sql<Schedule<string>>`
597
- SELECT * FROM cf_agents_schedules WHERE id = ${id}
598
- `;
599
- if (!result) {
600
- console.error(`schedule ${id} not found`);
601
- return undefined;
602
- }
603
-
604
- return { ...result[0], payload: JSON.parse(result[0].payload) as T };
605
- }
606
-
607
- /**
608
- * Get scheduled tasks matching the given criteria
609
- * @template T Type of the payload data
610
- * @param criteria Criteria to filter schedules
611
- * @returns Array of matching Schedule objects
612
- */
613
- getSchedules<T = string>(
614
- criteria: {
615
- id?: string;
616
- type?: "scheduled" | "delayed" | "cron";
617
- timeRange?: { start?: Date; end?: Date };
618
- } = {}
619
- ): Schedule<T>[] {
620
- let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
621
- const params = [];
622
-
623
- if (criteria.id) {
624
- query += " AND id = ?";
625
- params.push(criteria.id);
626
- }
627
-
628
- if (criteria.type) {
629
- query += " AND type = ?";
630
- params.push(criteria.type);
631
- }
632
-
633
- if (criteria.timeRange) {
634
- query += " AND time >= ? AND time <= ?";
635
- const start = criteria.timeRange.start || new Date(0);
636
- const end = criteria.timeRange.end || new Date(999999999999999);
637
- params.push(
638
- Math.floor(start.getTime() / 1000),
639
- Math.floor(end.getTime() / 1000)
640
- );
641
- }
642
-
643
- const result = this.ctx.storage.sql
644
- .exec(query, ...params)
645
- .toArray()
646
- .map((row) => ({
647
- ...row,
648
- payload: JSON.parse(row.payload as string) as T,
649
- })) as Schedule<T>[];
650
-
651
- return result;
652
- }
653
-
654
- /**
655
- * Cancel a scheduled task
656
- * @param id ID of the task to cancel
657
- * @returns true if the task was cancelled, false otherwise
658
- */
659
- async cancelSchedule(id: string): Promise<boolean> {
660
- this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
661
-
662
- await this.#scheduleNextAlarm();
663
- return true;
664
- }
665
-
666
- async #scheduleNextAlarm() {
667
- // Find the next schedule that needs to be executed
668
- const result = this.sql`
669
- SELECT time FROM cf_agents_schedules
670
- WHERE time > ${Math.floor(Date.now() / 1000)}
671
- ORDER BY time ASC
672
- LIMIT 1
673
- `;
674
- if (!result) return;
675
-
676
- if (result.length > 0 && "time" in result[0]) {
677
- const nextTime = (result[0].time as number) * 1000;
678
- await this.ctx.storage.setAlarm(nextTime);
679
- }
680
- }
681
-
682
- /**
683
- * Method called when an alarm fires
684
- * Executes any scheduled tasks that are due
685
- */
686
- async alarm() {
687
- const now = Math.floor(Date.now() / 1000);
688
-
689
- // Get all schedules that should be executed now
690
- const result = this.sql<Schedule<string>>`
691
- SELECT * FROM cf_agents_schedules WHERE time <= ${now}
692
- `;
693
-
694
- for (const row of result || []) {
695
- const callback = this[row.callback as keyof Agent<Env>];
696
- if (!callback) {
697
- console.error(`callback ${row.callback} not found`);
698
- continue;
699
- }
700
- await unstable_context.run(
701
- { agent: this, connection: undefined, request: undefined },
702
- async () => {
703
- try {
704
- await (
705
- callback as (
706
- payload: unknown,
707
- schedule: Schedule<unknown>
708
- ) => Promise<void>
709
- ).bind(this)(JSON.parse(row.payload as string), row);
710
- } catch (e) {
711
- console.error(`error executing callback "${row.callback}"`, e);
712
- }
713
- }
714
- );
715
- if (row.type === "cron") {
716
- // Update next execution time for cron schedules
717
- const nextExecutionTime = getNextCronTime(row.cron);
718
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
719
-
720
- this.sql`
721
- UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
722
- `;
723
- } else {
724
- // Delete one-time schedules after execution
725
- this.sql`
726
- DELETE FROM cf_agents_schedules WHERE id = ${row.id}
727
- `;
728
- }
729
- }
730
-
731
- // Schedule the next alarm
732
- await this.#scheduleNextAlarm();
733
- }
734
-
735
- /**
736
- * Destroy the Agent, removing all state and scheduled tasks
737
- */
738
- async destroy() {
739
- // drop all tables
740
- this.sql`DROP TABLE IF EXISTS cf_agents_state`;
741
- this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
742
-
743
- // delete all alarms
744
- await this.ctx.storage.deleteAlarm();
745
- await this.ctx.storage.deleteAll();
746
- }
747
-
748
- /**
749
- * Get all methods marked as callable on this Agent
750
- * @returns A map of method names to their metadata
751
- */
752
- #isCallable(method: string): boolean {
753
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
754
- return callableMetadata.has(this[method as keyof this] as Function);
755
- }
756
- }
757
-
758
- /**
759
- * Namespace for creating Agent instances
760
- * @template Agentic Type of the Agent class
761
- */
762
- export type AgentNamespace<Agentic extends Agent<unknown>> =
763
- DurableObjectNamespace<Agentic>;
764
-
765
- /**
766
- * Agent's durable context
767
- */
768
- export type AgentContext = DurableObjectState;
769
-
770
- /**
771
- * Configuration options for Agent routing
772
- */
773
- export type AgentOptions<Env> = PartyServerOptions<Env> & {
774
- /**
775
- * Whether to enable CORS for the Agent
776
- */
777
- cors?: boolean | HeadersInit | undefined;
778
- };
779
-
780
- /**
781
- * Route a request to the appropriate Agent
782
- * @param request Request to route
783
- * @param env Environment containing Agent bindings
784
- * @param options Routing options
785
- * @returns Response from the Agent or undefined if no route matched
786
- */
787
- export async function routeAgentRequest<Env>(
788
- request: Request,
789
- env: Env,
790
- options?: AgentOptions<Env>
791
- ) {
792
- const corsHeaders =
793
- options?.cors === true
794
- ? {
795
- "Access-Control-Allow-Origin": "*",
796
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
797
- "Access-Control-Allow-Credentials": "true",
798
- "Access-Control-Max-Age": "86400",
799
- }
800
- : options?.cors;
801
-
802
- if (request.method === "OPTIONS") {
803
- if (corsHeaders) {
804
- return new Response(null, {
805
- headers: corsHeaders,
806
- });
807
- }
808
- console.warn(
809
- "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
810
- );
811
- }
812
-
813
- let response = await routePartykitRequest(
814
- request,
815
- env as Record<string, unknown>,
816
- {
817
- prefix: "agents",
818
- ...(options as PartyServerOptions<Record<string, unknown>>),
819
- }
820
- );
821
-
822
- if (
823
- response &&
824
- corsHeaders &&
825
- request.headers.get("upgrade")?.toLowerCase() !== "websocket" &&
826
- request.headers.get("Upgrade")?.toLowerCase() !== "websocket"
827
- ) {
828
- response = new Response(response.body, {
829
- headers: {
830
- ...response.headers,
831
- ...corsHeaders,
832
- },
833
- });
834
- }
835
- return response;
836
- }
837
-
838
- /**
839
- * Route an email to the appropriate Agent
840
- * @param email Email message to route
841
- * @param env Environment containing Agent bindings
842
- * @param options Routing options
843
- */
844
- export async function routeAgentEmail<Env>(
845
- email: ForwardableEmailMessage,
846
- env: Env,
847
- options?: AgentOptions<Env>
848
- ): Promise<void> {}
849
-
850
- /**
851
- * Get or create an Agent by name
852
- * @template Env Environment type containing bindings
853
- * @template T Type of the Agent class
854
- * @param namespace Agent namespace
855
- * @param name Name of the Agent instance
856
- * @param options Options for Agent creation
857
- * @returns Promise resolving to an Agent instance stub
858
- */
859
- export function getAgentByName<Env, T extends Agent<Env>>(
860
- namespace: AgentNamespace<T>,
861
- name: string,
862
- options?: {
863
- jurisdiction?: DurableObjectJurisdiction;
864
- locationHint?: DurableObjectLocationHint;
865
- }
866
- ) {
867
- return getServerByName<Env, T>(namespace, name, options);
868
- }
869
-
870
- /**
871
- * A wrapper for streaming responses in callable methods
872
- */
873
- export class StreamingResponse {
874
- #connection: Connection;
875
- #id: string;
876
- #closed = false;
877
-
878
- constructor(connection: Connection, id: string) {
879
- this.#connection = connection;
880
- this.#id = id;
881
- }
882
-
883
- /**
884
- * Send a chunk of data to the client
885
- * @param chunk The data to send
886
- */
887
- send(chunk: unknown) {
888
- if (this.#closed) {
889
- throw new Error("StreamingResponse is already closed");
890
- }
891
- const response: RPCResponse = {
892
- type: "rpc",
893
- id: this.#id,
894
- success: true,
895
- result: chunk,
896
- done: false,
897
- };
898
- this.#connection.send(JSON.stringify(response));
899
- }
900
-
901
- /**
902
- * End the stream and send the final chunk (if any)
903
- * @param finalChunk Optional final chunk of data to send
904
- */
905
- end(finalChunk?: unknown) {
906
- if (this.#closed) {
907
- throw new Error("StreamingResponse is already closed");
908
- }
909
- this.#closed = true;
910
- const response: RPCResponse = {
911
- type: "rpc",
912
- id: this.#id,
913
- success: true,
914
- result: finalChunk,
915
- done: true,
916
- };
917
- this.#connection.send(JSON.stringify(response));
918
- }
919
- }