agents 0.0.0-eede2bd → 0.0.0-ef38e84

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