agents 0.0.0-f59e6a2 → 0.0.0-f5ccde3

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