agents 0.0.0-de168a2 → 0.0.0-de1d9aa

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