agents 0.0.0-b342dcf → 0.0.0-b3c7e5e

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