agents 0.0.0-fe9e8d3 → 0.0.0-ff431ff

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 +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/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-CbWe9FBd.d.ts +104 -0
  23. package/dist/client-DbS2uI6p.d.ts +5315 -0
  24. package/dist/client-JMskg2fw.js +793 -0
  25. package/dist/client-JMskg2fw.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-CswoD5Lu.js +93 -0
  32. package/dist/do-oauth-client-provider-CswoD5Lu.js.map +1 -0
  33. package/dist/do-oauth-client-provider-DGc5pP0l.d.ts +55 -0
  34. package/dist/index-DhJCaDWd.d.ts +58 -0
  35. package/dist/index-DxXJbYBM.d.ts +560 -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 +3 -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 +151 -71
  43. package/dist/mcp/index.js +1359 -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 +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-BIh615qN.d.ts +115 -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-nFNV3Ttx.js +1216 -0
  62. package/dist/src-nFNV3Ttx.js.map +1 -0
  63. package/package.json +115 -66
  64. package/dist/ai-types.js.map +0 -1
  65. package/dist/chunk-HD4VEHBA.js +0 -608
  66. package/dist/chunk-HD4VEHBA.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 -942
package/src/index.ts DELETED
@@ -1,942 +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 _onMessage = this.onMessage.bind(this);
325
- this.onMessage = async (connection: Connection, message: WSMessage) => {
326
- return agentContext.run(
327
- { agent: this, connection, request: undefined },
328
- async () => {
329
- if (typeof message !== "string") {
330
- return this.#tryCatch(() => _onMessage(connection, message));
331
- }
332
-
333
- let parsed: unknown;
334
- try {
335
- parsed = JSON.parse(message);
336
- } catch (e) {
337
- // silently fail and let the onMessage handler handle it
338
- return this.#tryCatch(() => _onMessage(connection, message));
339
- }
340
-
341
- if (isStateUpdateMessage(parsed)) {
342
- this.#setStateInternal(parsed.state as State, connection);
343
- return;
344
- }
345
-
346
- if (isRPCRequest(parsed)) {
347
- try {
348
- const { id, method, args } = parsed;
349
-
350
- // Check if method exists and is callable
351
- const methodFn = this[method as keyof this];
352
- if (typeof methodFn !== "function") {
353
- throw new Error(`Method ${method} does not exist`);
354
- }
355
-
356
- if (!this.#isCallable(method)) {
357
- throw new Error(`Method ${method} is not callable`);
358
- }
359
-
360
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
361
- const metadata = callableMetadata.get(methodFn as Function);
362
-
363
- // For streaming methods, pass a StreamingResponse object
364
- if (metadata?.streaming) {
365
- const stream = new StreamingResponse(connection, id);
366
- await methodFn.apply(this, [stream, ...args]);
367
- return;
368
- }
369
-
370
- // For regular methods, execute and send response
371
- const result = await methodFn.apply(this, args);
372
- const response: RPCResponse = {
373
- type: "rpc",
374
- id,
375
- success: true,
376
- result,
377
- done: true,
378
- };
379
- connection.send(JSON.stringify(response));
380
- } catch (e) {
381
- // Send error response
382
- const response: RPCResponse = {
383
- type: "rpc",
384
- id: parsed.id,
385
- success: false,
386
- error:
387
- e instanceof Error ? e.message : "Unknown error occurred",
388
- };
389
- connection.send(JSON.stringify(response));
390
- console.error("RPC error:", e);
391
- }
392
- return;
393
- }
394
-
395
- return this.#tryCatch(() => _onMessage(connection, message));
396
- }
397
- );
398
- };
399
-
400
- const _onConnect = this.onConnect.bind(this);
401
- this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
402
- // TODO: This is a hack to ensure the state is sent after the connection is established
403
- // must fix this
404
- return agentContext.run(
405
- { agent: this, connection, request: ctx.request },
406
- async () => {
407
- setTimeout(() => {
408
- if (this.state) {
409
- connection.send(
410
- JSON.stringify({
411
- type: "cf_agent_state",
412
- state: this.state,
413
- })
414
- );
415
- }
416
- return this.#tryCatch(() => _onConnect(connection, ctx));
417
- }, 20);
418
- }
419
- );
420
- };
421
- }
422
-
423
- #setStateInternal(state: State, source: Connection | "server" = "server") {
424
- this.#state = state;
425
- this.sql`
426
- INSERT OR REPLACE INTO cf_agents_state (id, state)
427
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
428
- `;
429
- this.sql`
430
- INSERT OR REPLACE INTO cf_agents_state (id, state)
431
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
432
- `;
433
- this.broadcast(
434
- JSON.stringify({
435
- type: "cf_agent_state",
436
- state: state,
437
- }),
438
- source !== "server" ? [source.id] : []
439
- );
440
- return this.#tryCatch(() => {
441
- const { connection, request } = agentContext.getStore() || {};
442
- return agentContext.run(
443
- { agent: this, connection, request },
444
- async () => {
445
- return this.onStateUpdate(state, source);
446
- }
447
- );
448
- });
449
- }
450
-
451
- /**
452
- * Update the Agent's state
453
- * @param state New state to set
454
- */
455
- setState(state: State) {
456
- this.#setStateInternal(state, "server");
457
- }
458
-
459
- /**
460
- * Called when the Agent's state is updated
461
- * @param state Updated state
462
- * @param source Source of the state update ("server" or a client connection)
463
- */
464
- onStateUpdate(state: State | undefined, source: Connection | "server") {
465
- // override this to handle state updates
466
- }
467
-
468
- /**
469
- * Called when the Agent receives an email
470
- * @param email Email message to process
471
- */
472
- onEmail(email: ForwardableEmailMessage) {
473
- return agentContext.run(
474
- { agent: this, connection: undefined, request: undefined },
475
- async () => {
476
- console.error("onEmail not implemented");
477
- }
478
- );
479
- }
480
-
481
- async #tryCatch<T>(fn: () => T | Promise<T>) {
482
- try {
483
- return await fn();
484
- } catch (e) {
485
- throw this.onError(e);
486
- }
487
- }
488
-
489
- override onError(
490
- connection: Connection,
491
- error: unknown
492
- ): void | Promise<void>;
493
- override onError(error: unknown): void | Promise<void>;
494
- override onError(connectionOrError: Connection | unknown, error?: unknown) {
495
- let theError: unknown;
496
- if (connectionOrError && error) {
497
- theError = error;
498
- // this is a websocket connection error
499
- console.error(
500
- "Error on websocket connection:",
501
- (connectionOrError as Connection).id,
502
- theError
503
- );
504
- console.error(
505
- "Override onError(connection, error) to handle websocket connection errors"
506
- );
507
- } else {
508
- theError = connectionOrError;
509
- // this is a server error
510
- console.error("Error on server:", theError);
511
- console.error("Override onError(error) to handle server errors");
512
- }
513
- throw theError;
514
- }
515
-
516
- /**
517
- * Render content (not implemented in base class)
518
- */
519
- render() {
520
- throw new Error("Not implemented");
521
- }
522
-
523
- /**
524
- * Schedule a task to be executed in the future
525
- * @template T Type of the payload data
526
- * @param when When to execute the task (Date, seconds delay, or cron expression)
527
- * @param callback Name of the method to call
528
- * @param payload Data to pass to the callback
529
- * @returns Schedule object representing the scheduled task
530
- */
531
- async schedule<T = string>(
532
- when: Date | string | number,
533
- callback: keyof this,
534
- payload?: T
535
- ): Promise<Schedule<T>> {
536
- const id = nanoid(9);
537
-
538
- if (typeof callback !== "string") {
539
- throw new Error("Callback must be a string");
540
- }
541
-
542
- if (typeof this[callback] !== "function") {
543
- throw new Error(`this.${callback} is not a function`);
544
- }
545
-
546
- if (when instanceof Date) {
547
- const timestamp = Math.floor(when.getTime() / 1000);
548
- this.sql`
549
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
550
- VALUES (${id}, ${callback}, ${JSON.stringify(
551
- payload
552
- )}, 'scheduled', ${timestamp})
553
- `;
554
-
555
- await this.#scheduleNextAlarm();
556
-
557
- return {
558
- id,
559
- callback: callback,
560
- payload: payload as T,
561
- time: timestamp,
562
- type: "scheduled",
563
- };
564
- }
565
- if (typeof when === "number") {
566
- const time = new Date(Date.now() + when * 1000);
567
- const timestamp = Math.floor(time.getTime() / 1000);
568
-
569
- this.sql`
570
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
571
- VALUES (${id}, ${callback}, ${JSON.stringify(
572
- payload
573
- )}, 'delayed', ${when}, ${timestamp})
574
- `;
575
-
576
- await this.#scheduleNextAlarm();
577
-
578
- return {
579
- id,
580
- callback: callback,
581
- payload: payload as T,
582
- delayInSeconds: when,
583
- time: timestamp,
584
- type: "delayed",
585
- };
586
- }
587
- if (typeof when === "string") {
588
- const nextExecutionTime = getNextCronTime(when);
589
- const timestamp = Math.floor(nextExecutionTime.getTime() / 1000);
590
-
591
- this.sql`
592
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
593
- VALUES (${id}, ${callback}, ${JSON.stringify(
594
- payload
595
- )}, 'cron', ${when}, ${timestamp})
596
- `;
597
-
598
- await this.#scheduleNextAlarm();
599
-
600
- return {
601
- id,
602
- callback: callback,
603
- payload: payload as T,
604
- cron: when,
605
- time: timestamp,
606
- type: "cron",
607
- };
608
- }
609
- throw new Error("Invalid schedule type");
610
- }
611
-
612
- /**
613
- * Get a scheduled task by ID
614
- * @template T Type of the payload data
615
- * @param id ID of the scheduled task
616
- * @returns The Schedule object or undefined if not found
617
- */
618
- async getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined> {
619
- const result = this.sql<Schedule<string>>`
620
- SELECT * FROM cf_agents_schedules WHERE id = ${id}
621
- `;
622
- if (!result) {
623
- console.error(`schedule ${id} not found`);
624
- return undefined;
625
- }
626
-
627
- return { ...result[0], payload: JSON.parse(result[0].payload) as T };
628
- }
629
-
630
- /**
631
- * Get scheduled tasks matching the given criteria
632
- * @template T Type of the payload data
633
- * @param criteria Criteria to filter schedules
634
- * @returns Array of matching Schedule objects
635
- */
636
- getSchedules<T = string>(
637
- criteria: {
638
- id?: string;
639
- type?: "scheduled" | "delayed" | "cron";
640
- timeRange?: { start?: Date; end?: Date };
641
- } = {}
642
- ): Schedule<T>[] {
643
- let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
644
- const params = [];
645
-
646
- if (criteria.id) {
647
- query += " AND id = ?";
648
- params.push(criteria.id);
649
- }
650
-
651
- if (criteria.type) {
652
- query += " AND type = ?";
653
- params.push(criteria.type);
654
- }
655
-
656
- if (criteria.timeRange) {
657
- query += " AND time >= ? AND time <= ?";
658
- const start = criteria.timeRange.start || new Date(0);
659
- const end = criteria.timeRange.end || new Date(999999999999999);
660
- params.push(
661
- Math.floor(start.getTime() / 1000),
662
- Math.floor(end.getTime() / 1000)
663
- );
664
- }
665
-
666
- const result = this.ctx.storage.sql
667
- .exec(query, ...params)
668
- .toArray()
669
- .map((row) => ({
670
- ...row,
671
- payload: JSON.parse(row.payload as string) as T,
672
- })) as Schedule<T>[];
673
-
674
- return result;
675
- }
676
-
677
- /**
678
- * Cancel a scheduled task
679
- * @param id ID of the task to cancel
680
- * @returns true if the task was cancelled, false otherwise
681
- */
682
- async cancelSchedule(id: string): Promise<boolean> {
683
- this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
684
-
685
- await this.#scheduleNextAlarm();
686
- return true;
687
- }
688
-
689
- async #scheduleNextAlarm() {
690
- // Find the next schedule that needs to be executed
691
- const result = this.sql`
692
- SELECT time FROM cf_agents_schedules
693
- WHERE time > ${Math.floor(Date.now() / 1000)}
694
- ORDER BY time ASC
695
- LIMIT 1
696
- `;
697
- if (!result) return;
698
-
699
- if (result.length > 0 && "time" in result[0]) {
700
- const nextTime = (result[0].time as number) * 1000;
701
- await this.ctx.storage.setAlarm(nextTime);
702
- }
703
- }
704
-
705
- /**
706
- * Method called when an alarm fires
707
- * Executes any scheduled tasks that are due
708
- */
709
- async alarm() {
710
- const now = Math.floor(Date.now() / 1000);
711
-
712
- // Get all schedules that should be executed now
713
- const result = this.sql<Schedule<string>>`
714
- SELECT * FROM cf_agents_schedules WHERE time <= ${now}
715
- `;
716
-
717
- for (const row of result || []) {
718
- const callback = this[row.callback as keyof Agent<Env>];
719
- if (!callback) {
720
- console.error(`callback ${row.callback} not found`);
721
- continue;
722
- }
723
- await agentContext.run(
724
- { agent: this, connection: undefined, request: undefined },
725
- async () => {
726
- try {
727
- await (
728
- callback as (
729
- payload: unknown,
730
- schedule: Schedule<unknown>
731
- ) => Promise<void>
732
- ).bind(this)(JSON.parse(row.payload as string), row);
733
- } catch (e) {
734
- console.error(`error executing callback "${row.callback}"`, e);
735
- }
736
- }
737
- );
738
- if (row.type === "cron") {
739
- // Update next execution time for cron schedules
740
- const nextExecutionTime = getNextCronTime(row.cron);
741
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
742
-
743
- this.sql`
744
- UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
745
- `;
746
- } else {
747
- // Delete one-time schedules after execution
748
- this.sql`
749
- DELETE FROM cf_agents_schedules WHERE id = ${row.id}
750
- `;
751
- }
752
- }
753
-
754
- // Schedule the next alarm
755
- await this.#scheduleNextAlarm();
756
- }
757
-
758
- /**
759
- * Destroy the Agent, removing all state and scheduled tasks
760
- */
761
- async destroy() {
762
- // drop all tables
763
- this.sql`DROP TABLE IF EXISTS cf_agents_state`;
764
- this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
765
-
766
- // delete all alarms
767
- await this.ctx.storage.deleteAlarm();
768
- await this.ctx.storage.deleteAll();
769
- }
770
-
771
- /**
772
- * Get all methods marked as callable on this Agent
773
- * @returns A map of method names to their metadata
774
- */
775
- #isCallable(method: string): boolean {
776
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
777
- return callableMetadata.has(this[method as keyof this] as Function);
778
- }
779
- }
780
-
781
- /**
782
- * Namespace for creating Agent instances
783
- * @template Agentic Type of the Agent class
784
- */
785
- export type AgentNamespace<Agentic extends Agent<unknown>> =
786
- DurableObjectNamespace<Agentic>;
787
-
788
- /**
789
- * Agent's durable context
790
- */
791
- export type AgentContext = DurableObjectState;
792
-
793
- /**
794
- * Configuration options for Agent routing
795
- */
796
- export type AgentOptions<Env> = PartyServerOptions<Env> & {
797
- /**
798
- * Whether to enable CORS for the Agent
799
- */
800
- cors?: boolean | HeadersInit | undefined;
801
- };
802
-
803
- /**
804
- * Route a request to the appropriate Agent
805
- * @param request Request to route
806
- * @param env Environment containing Agent bindings
807
- * @param options Routing options
808
- * @returns Response from the Agent or undefined if no route matched
809
- */
810
- export async function routeAgentRequest<Env>(
811
- request: Request,
812
- env: Env,
813
- options?: AgentOptions<Env>
814
- ) {
815
- const corsHeaders =
816
- options?.cors === true
817
- ? {
818
- "Access-Control-Allow-Origin": "*",
819
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
820
- "Access-Control-Allow-Credentials": "true",
821
- "Access-Control-Max-Age": "86400",
822
- }
823
- : options?.cors;
824
-
825
- if (request.method === "OPTIONS") {
826
- if (corsHeaders) {
827
- return new Response(null, {
828
- headers: corsHeaders,
829
- });
830
- }
831
- console.warn(
832
- "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
833
- );
834
- }
835
-
836
- let response = await routePartykitRequest(
837
- request,
838
- env as Record<string, unknown>,
839
- {
840
- prefix: "agents",
841
- ...(options as PartyServerOptions<Record<string, unknown>>),
842
- }
843
- );
844
-
845
- if (
846
- response &&
847
- corsHeaders &&
848
- request.headers.get("upgrade")?.toLowerCase() !== "websocket" &&
849
- request.headers.get("Upgrade")?.toLowerCase() !== "websocket"
850
- ) {
851
- response = new Response(response.body, {
852
- headers: {
853
- ...response.headers,
854
- ...corsHeaders,
855
- },
856
- });
857
- }
858
- return response;
859
- }
860
-
861
- /**
862
- * Route an email to the appropriate Agent
863
- * @param email Email message to route
864
- * @param env Environment containing Agent bindings
865
- * @param options Routing options
866
- */
867
- export async function routeAgentEmail<Env>(
868
- email: ForwardableEmailMessage,
869
- env: Env,
870
- options?: AgentOptions<Env>
871
- ): Promise<void> {}
872
-
873
- /**
874
- * Get or create an Agent by name
875
- * @template Env Environment type containing bindings
876
- * @template T Type of the Agent class
877
- * @param namespace Agent namespace
878
- * @param name Name of the Agent instance
879
- * @param options Options for Agent creation
880
- * @returns Promise resolving to an Agent instance stub
881
- */
882
- export async function getAgentByName<Env, T extends Agent<Env>>(
883
- namespace: AgentNamespace<T>,
884
- name: string,
885
- options?: {
886
- jurisdiction?: DurableObjectJurisdiction;
887
- locationHint?: DurableObjectLocationHint;
888
- }
889
- ) {
890
- return getServerByName<Env, T>(namespace, name, options);
891
- }
892
-
893
- /**
894
- * A wrapper for streaming responses in callable methods
895
- */
896
- export class StreamingResponse {
897
- #connection: Connection;
898
- #id: string;
899
- #closed = false;
900
-
901
- constructor(connection: Connection, id: string) {
902
- this.#connection = connection;
903
- this.#id = id;
904
- }
905
-
906
- /**
907
- * Send a chunk of data to the client
908
- * @param chunk The data to send
909
- */
910
- send(chunk: unknown) {
911
- if (this.#closed) {
912
- throw new Error("StreamingResponse is already closed");
913
- }
914
- const response: RPCResponse = {
915
- type: "rpc",
916
- id: this.#id,
917
- success: true,
918
- result: chunk,
919
- done: false,
920
- };
921
- this.#connection.send(JSON.stringify(response));
922
- }
923
-
924
- /**
925
- * End the stream and send the final chunk (if any)
926
- * @param finalChunk Optional final chunk of data to send
927
- */
928
- end(finalChunk?: unknown) {
929
- if (this.#closed) {
930
- throw new Error("StreamingResponse is already closed");
931
- }
932
- this.#closed = true;
933
- const response: RPCResponse = {
934
- type: "rpc",
935
- id: this.#id,
936
- success: true,
937
- result: finalChunk,
938
- done: true,
939
- };
940
- this.#connection.send(JSON.stringify(response));
941
- }
942
- }