agents 0.0.0-fbaa8f7 → 0.0.0-fbf5181
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.
- package/README.md +2 -6
- package/dist/ai-chat-agent.d.ts +6 -5
- package/dist/ai-chat-agent.js +64 -65
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +5 -3
- package/dist/ai-react.js +17 -14
- package/dist/ai-react.js.map +1 -1
- package/dist/{chunk-PDF5WEP4.js → chunk-XG52S6YY.js} +155 -106
- package/dist/chunk-XG52S6YY.js.map +1 -0
- package/dist/client.js +16 -23
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +10 -14
- package/dist/index.js +5 -5
- package/dist/mcp/client.d.ts +763 -0
- package/dist/mcp/client.js +408 -0
- package/dist/mcp/client.js.map +1 -0
- package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
- package/dist/mcp/do-oauth-client-provider.js +107 -0
- package/dist/mcp/do-oauth-client-provider.js.map +1 -0
- package/dist/mcp/index.d.ts +61 -0
- package/dist/mcp/index.js +778 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/react.js +34 -27
- package/dist/react.js.map +1 -1
- package/package.json +35 -5
- package/src/index.ts +167 -107
- package/dist/chunk-PDF5WEP4.js.map +0 -1
package/src/index.ts
CHANGED
|
@@ -11,9 +11,9 @@ import {
|
|
|
11
11
|
import { parseCronExpression } from "cron-schedule";
|
|
12
12
|
import { nanoid } from "nanoid";
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
export type { Connection, WSMessage, ConnectionContext } from "partyserver";
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
19
|
* RPC request message from client
|
|
@@ -117,11 +117,6 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
|
|
|
117
117
|
};
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
-
/**
|
|
121
|
-
* A class for creating workflow entry points that can be used with Cloudflare Workers
|
|
122
|
-
*/
|
|
123
|
-
export class WorkflowEntrypoint extends CFWorkflowEntrypoint {}
|
|
124
|
-
|
|
125
120
|
/**
|
|
126
121
|
* Represents a scheduled task within an Agent
|
|
127
122
|
* @template T Type of the payload data
|
|
@@ -168,6 +163,12 @@ const STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
|
168
163
|
|
|
169
164
|
const DEFAULT_STATE = {} as unknown;
|
|
170
165
|
|
|
166
|
+
export const unstable_context = new AsyncLocalStorage<{
|
|
167
|
+
agent: Agent<unknown>;
|
|
168
|
+
connection: Connection | undefined;
|
|
169
|
+
request: Request | undefined;
|
|
170
|
+
}>();
|
|
171
|
+
|
|
171
172
|
/**
|
|
172
173
|
* Base class for creating Agent implementations
|
|
173
174
|
* @template Env Environment type containing bindings
|
|
@@ -256,7 +257,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
256
257
|
return [...this.ctx.storage.sql.exec(query, ...values)] as T[];
|
|
257
258
|
} catch (e) {
|
|
258
259
|
console.error(`failed to execute sql query: ${query}`, e);
|
|
259
|
-
throw e;
|
|
260
|
+
throw this.onError(e);
|
|
260
261
|
}
|
|
261
262
|
}
|
|
262
263
|
constructor(ctx: AgentContext, env: Env) {
|
|
@@ -270,7 +271,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
270
271
|
`;
|
|
271
272
|
|
|
272
273
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
273
|
-
|
|
274
|
+
return this.#tryCatch(async () => {
|
|
274
275
|
// Create alarms table if it doesn't exist
|
|
275
276
|
this.sql`
|
|
276
277
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
@@ -287,97 +288,105 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
287
288
|
|
|
288
289
|
// execute any pending alarms and schedule the next alarm
|
|
289
290
|
await this.alarm();
|
|
290
|
-
}
|
|
291
|
-
console.error(e);
|
|
292
|
-
throw e;
|
|
293
|
-
}
|
|
291
|
+
});
|
|
294
292
|
});
|
|
295
293
|
|
|
296
294
|
const _onMessage = this.onMessage.bind(this);
|
|
297
295
|
this.onMessage = async (connection: Connection, message: WSMessage) => {
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
try {
|
|
304
|
-
parsed = JSON.parse(message);
|
|
305
|
-
} catch (e) {
|
|
306
|
-
// silently fail and let the onMessage handler handle it
|
|
307
|
-
return _onMessage(connection, message);
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
if (isStateUpdateMessage(parsed)) {
|
|
311
|
-
this.#setStateInternal(parsed.state as State, connection);
|
|
312
|
-
return;
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
if (isRPCRequest(parsed)) {
|
|
316
|
-
try {
|
|
317
|
-
const { id, method, args } = parsed;
|
|
318
|
-
|
|
319
|
-
// Check if method exists and is callable
|
|
320
|
-
const methodFn = this[method as keyof this];
|
|
321
|
-
if (typeof methodFn !== "function") {
|
|
322
|
-
throw new Error(`Method ${method} does not exist`);
|
|
296
|
+
return unstable_context.run(
|
|
297
|
+
{ agent: this, connection, request: undefined },
|
|
298
|
+
async () => {
|
|
299
|
+
if (typeof message !== "string") {
|
|
300
|
+
return this.#tryCatch(() => _onMessage(connection, message));
|
|
323
301
|
}
|
|
324
302
|
|
|
325
|
-
|
|
326
|
-
|
|
303
|
+
let parsed: unknown;
|
|
304
|
+
try {
|
|
305
|
+
parsed = JSON.parse(message);
|
|
306
|
+
} catch (e) {
|
|
307
|
+
// silently fail and let the onMessage handler handle it
|
|
308
|
+
return this.#tryCatch(() => _onMessage(connection, message));
|
|
327
309
|
}
|
|
328
310
|
|
|
329
|
-
|
|
330
|
-
|
|
311
|
+
if (isStateUpdateMessage(parsed)) {
|
|
312
|
+
this.#setStateInternal(parsed.state as State, connection);
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
331
315
|
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
316
|
+
if (isRPCRequest(parsed)) {
|
|
317
|
+
try {
|
|
318
|
+
const { id, method, args } = parsed;
|
|
319
|
+
|
|
320
|
+
// Check if method exists and is callable
|
|
321
|
+
const methodFn = this[method as keyof this];
|
|
322
|
+
if (typeof methodFn !== "function") {
|
|
323
|
+
throw new Error(`Method ${method} does not exist`);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
if (!this.#isCallable(method)) {
|
|
327
|
+
throw new Error(`Method ${method} is not callable`);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
331
|
+
const metadata = callableMetadata.get(methodFn as Function);
|
|
332
|
+
|
|
333
|
+
// For streaming methods, pass a StreamingResponse object
|
|
334
|
+
if (metadata?.streaming) {
|
|
335
|
+
const stream = new StreamingResponse(connection, id);
|
|
336
|
+
await methodFn.apply(this, [stream, ...args]);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// For regular methods, execute and send response
|
|
341
|
+
const result = await methodFn.apply(this, args);
|
|
342
|
+
const response: RPCResponse = {
|
|
343
|
+
type: "rpc",
|
|
344
|
+
id,
|
|
345
|
+
success: true,
|
|
346
|
+
result,
|
|
347
|
+
done: true,
|
|
348
|
+
};
|
|
349
|
+
connection.send(JSON.stringify(response));
|
|
350
|
+
} catch (e) {
|
|
351
|
+
// Send error response
|
|
352
|
+
const response: RPCResponse = {
|
|
353
|
+
type: "rpc",
|
|
354
|
+
id: parsed.id,
|
|
355
|
+
success: false,
|
|
356
|
+
error:
|
|
357
|
+
e instanceof Error ? e.message : "Unknown error occurred",
|
|
358
|
+
};
|
|
359
|
+
connection.send(JSON.stringify(response));
|
|
360
|
+
console.error("RPC error:", e);
|
|
361
|
+
}
|
|
336
362
|
return;
|
|
337
363
|
}
|
|
338
364
|
|
|
339
|
-
|
|
340
|
-
const result = await methodFn.apply(this, args);
|
|
341
|
-
const response: RPCResponse = {
|
|
342
|
-
type: "rpc",
|
|
343
|
-
id,
|
|
344
|
-
success: true,
|
|
345
|
-
result,
|
|
346
|
-
done: true,
|
|
347
|
-
};
|
|
348
|
-
connection.send(JSON.stringify(response));
|
|
349
|
-
} catch (e) {
|
|
350
|
-
// Send error response
|
|
351
|
-
const response: RPCResponse = {
|
|
352
|
-
type: "rpc",
|
|
353
|
-
id: parsed.id,
|
|
354
|
-
success: false,
|
|
355
|
-
error: e instanceof Error ? e.message : "Unknown error occurred",
|
|
356
|
-
};
|
|
357
|
-
connection.send(JSON.stringify(response));
|
|
358
|
-
console.error("RPC error:", e);
|
|
365
|
+
return this.#tryCatch(() => _onMessage(connection, message));
|
|
359
366
|
}
|
|
360
|
-
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
return _onMessage(connection, message);
|
|
367
|
+
);
|
|
364
368
|
};
|
|
365
369
|
|
|
366
370
|
const _onConnect = this.onConnect.bind(this);
|
|
367
371
|
this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
|
|
368
372
|
// TODO: This is a hack to ensure the state is sent after the connection is established
|
|
369
373
|
// must fix this
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
374
|
+
return unstable_context.run(
|
|
375
|
+
{ agent: this, connection, request: ctx.request },
|
|
376
|
+
async () => {
|
|
377
|
+
setTimeout(() => {
|
|
378
|
+
if (this.state) {
|
|
379
|
+
connection.send(
|
|
380
|
+
JSON.stringify({
|
|
381
|
+
type: "cf_agent_state",
|
|
382
|
+
state: this.state,
|
|
383
|
+
})
|
|
384
|
+
);
|
|
385
|
+
}
|
|
386
|
+
return this.#tryCatch(() => _onConnect(connection, ctx));
|
|
387
|
+
}, 20);
|
|
378
388
|
}
|
|
379
|
-
|
|
380
|
-
}, 20);
|
|
389
|
+
);
|
|
381
390
|
};
|
|
382
391
|
}
|
|
383
392
|
|
|
@@ -398,7 +407,15 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
398
407
|
}),
|
|
399
408
|
source !== "server" ? [source.id] : []
|
|
400
409
|
);
|
|
401
|
-
this
|
|
410
|
+
return this.#tryCatch(() => {
|
|
411
|
+
const { connection, request } = unstable_context.getStore() || {};
|
|
412
|
+
return unstable_context.run(
|
|
413
|
+
{ agent: this, connection, request },
|
|
414
|
+
async () => {
|
|
415
|
+
return this.onStateUpdate(state, source);
|
|
416
|
+
}
|
|
417
|
+
);
|
|
418
|
+
});
|
|
402
419
|
}
|
|
403
420
|
|
|
404
421
|
/**
|
|
@@ -423,7 +440,47 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
423
440
|
* @param email Email message to process
|
|
424
441
|
*/
|
|
425
442
|
onEmail(email: ForwardableEmailMessage) {
|
|
426
|
-
|
|
443
|
+
return unstable_context.run(
|
|
444
|
+
{ agent: this, connection: undefined, request: undefined },
|
|
445
|
+
async () => {
|
|
446
|
+
console.error("onEmail not implemented");
|
|
447
|
+
}
|
|
448
|
+
);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
async #tryCatch<T>(fn: () => T | Promise<T>) {
|
|
452
|
+
try {
|
|
453
|
+
return await fn();
|
|
454
|
+
} catch (e) {
|
|
455
|
+
throw this.onError(e);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
override onError(
|
|
460
|
+
connection: Connection,
|
|
461
|
+
error: unknown
|
|
462
|
+
): void | Promise<void>;
|
|
463
|
+
override onError(error: unknown): void | Promise<void>;
|
|
464
|
+
override onError(connectionOrError: Connection | unknown, error?: unknown) {
|
|
465
|
+
let theError: unknown;
|
|
466
|
+
if (connectionOrError && error) {
|
|
467
|
+
theError = error;
|
|
468
|
+
// this is a websocket connection error
|
|
469
|
+
console.error(
|
|
470
|
+
"Error on websocket connection:",
|
|
471
|
+
(connectionOrError as Connection).id,
|
|
472
|
+
theError
|
|
473
|
+
);
|
|
474
|
+
console.error(
|
|
475
|
+
"Override onError(connection, error) to handle websocket connection errors"
|
|
476
|
+
);
|
|
477
|
+
} else {
|
|
478
|
+
theError = connectionOrError;
|
|
479
|
+
// this is a server error
|
|
480
|
+
console.error("Error on server:", theError);
|
|
481
|
+
console.error("Override onError(error) to handle server errors");
|
|
482
|
+
}
|
|
483
|
+
throw theError;
|
|
427
484
|
}
|
|
428
485
|
|
|
429
486
|
/**
|
|
@@ -465,7 +522,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
465
522
|
)}, 'scheduled', ${timestamp})
|
|
466
523
|
`;
|
|
467
524
|
|
|
468
|
-
await this
|
|
525
|
+
await this.#scheduleNextAlarm();
|
|
469
526
|
|
|
470
527
|
return {
|
|
471
528
|
id,
|
|
@@ -486,7 +543,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
486
543
|
)}, 'delayed', ${when}, ${timestamp})
|
|
487
544
|
`;
|
|
488
545
|
|
|
489
|
-
await this
|
|
546
|
+
await this.#scheduleNextAlarm();
|
|
490
547
|
|
|
491
548
|
return {
|
|
492
549
|
id,
|
|
@@ -508,7 +565,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
508
565
|
)}, 'cron', ${when}, ${timestamp})
|
|
509
566
|
`;
|
|
510
567
|
|
|
511
|
-
await this
|
|
568
|
+
await this.#scheduleNextAlarm();
|
|
512
569
|
|
|
513
570
|
return {
|
|
514
571
|
id,
|
|
@@ -532,7 +589,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
532
589
|
const result = this.sql<Schedule<string>>`
|
|
533
590
|
SELECT * FROM cf_agents_schedules WHERE id = ${id}
|
|
534
591
|
`;
|
|
535
|
-
if (!result)
|
|
592
|
+
if (!result) {
|
|
593
|
+
console.error(`schedule ${id} not found`);
|
|
594
|
+
return undefined;
|
|
595
|
+
}
|
|
536
596
|
|
|
537
597
|
return { ...result[0], payload: JSON.parse(result[0].payload) as T };
|
|
538
598
|
}
|
|
@@ -545,7 +605,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
545
605
|
*/
|
|
546
606
|
getSchedules<T = string>(
|
|
547
607
|
criteria: {
|
|
548
|
-
description?: string;
|
|
549
608
|
id?: string;
|
|
550
609
|
type?: "scheduled" | "delayed" | "cron";
|
|
551
610
|
timeRange?: { start?: Date; end?: Date };
|
|
@@ -559,11 +618,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
559
618
|
params.push(criteria.id);
|
|
560
619
|
}
|
|
561
620
|
|
|
562
|
-
if (criteria.description) {
|
|
563
|
-
query += " AND description = ?";
|
|
564
|
-
params.push(criteria.description);
|
|
565
|
-
}
|
|
566
|
-
|
|
567
621
|
if (criteria.type) {
|
|
568
622
|
query += " AND type = ?";
|
|
569
623
|
params.push(criteria.type);
|
|
@@ -598,11 +652,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
598
652
|
async cancelSchedule(id: string): Promise<boolean> {
|
|
599
653
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
600
654
|
|
|
601
|
-
await this
|
|
655
|
+
await this.#scheduleNextAlarm();
|
|
602
656
|
return true;
|
|
603
657
|
}
|
|
604
658
|
|
|
605
|
-
|
|
659
|
+
async #scheduleNextAlarm() {
|
|
606
660
|
// Find the next schedule that needs to be executed
|
|
607
661
|
const result = this.sql`
|
|
608
662
|
SELECT time FROM cf_agents_schedules
|
|
@@ -636,16 +690,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
636
690
|
console.error(`callback ${row.callback} not found`);
|
|
637
691
|
continue;
|
|
638
692
|
}
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
693
|
+
await unstable_context.run(
|
|
694
|
+
{ agent: this, connection: undefined, request: undefined },
|
|
695
|
+
async () => {
|
|
696
|
+
try {
|
|
697
|
+
await (
|
|
698
|
+
callback as (
|
|
699
|
+
payload: unknown,
|
|
700
|
+
schedule: Schedule<unknown>
|
|
701
|
+
) => Promise<void>
|
|
702
|
+
).bind(this)(JSON.parse(row.payload as string), row);
|
|
703
|
+
} catch (e) {
|
|
704
|
+
console.error(`error executing callback "${row.callback}"`, e);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
);
|
|
649
708
|
if (row.type === "cron") {
|
|
650
709
|
// Update next execution time for cron schedules
|
|
651
710
|
const nextExecutionTime = getNextCronTime(row.cron);
|
|
@@ -663,7 +722,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
663
722
|
}
|
|
664
723
|
|
|
665
724
|
// Schedule the next alarm
|
|
666
|
-
await this
|
|
725
|
+
await this.#scheduleNextAlarm();
|
|
667
726
|
}
|
|
668
727
|
|
|
669
728
|
/**
|
|
@@ -683,7 +742,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
683
742
|
* Get all methods marked as callable on this Agent
|
|
684
743
|
* @returns A map of method names to their metadata
|
|
685
744
|
*/
|
|
686
|
-
|
|
745
|
+
#isCallable(method: string): boolean {
|
|
687
746
|
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
688
747
|
return callableMetadata.has(this[method as keyof this] as Function);
|
|
689
748
|
}
|
|
@@ -756,7 +815,8 @@ export async function routeAgentRequest<Env>(
|
|
|
756
815
|
if (
|
|
757
816
|
response &&
|
|
758
817
|
corsHeaders &&
|
|
759
|
-
request.headers.get("upgrade") !== "websocket"
|
|
818
|
+
request.headers.get("upgrade")?.toLowerCase() !== "websocket" &&
|
|
819
|
+
request.headers.get("Upgrade")?.toLowerCase() !== "websocket"
|
|
760
820
|
) {
|
|
761
821
|
response = new Response(response.body, {
|
|
762
822
|
headers: {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n Server,\n routePartykitRequest,\n type PartyServerOptions,\n getServerByName,\n type Connection,\n type ConnectionContext,\n type WSMessage,\n} from \"partyserver\";\n\nimport { parseCronExpression } from \"cron-schedule\";\nimport { nanoid } from \"nanoid\";\n\nexport type { Connection, WSMessage, ConnectionContext } from \"partyserver\";\n\nimport { WorkflowEntrypoint as CFWorkflowEntrypoint } from \"cloudflare:workers\";\n\n/**\n * RPC request message from client\n */\nexport type RPCRequest = {\n type: \"rpc\";\n id: string;\n method: string;\n args: unknown[];\n};\n\n/**\n * State update message from client\n */\nexport type StateUpdateMessage = {\n type: \"cf_agent_state\";\n state: unknown;\n};\n\n/**\n * RPC response message to client\n */\nexport type RPCResponse = {\n type: \"rpc\";\n id: string;\n} & (\n | {\n success: true;\n result: unknown;\n done?: false;\n }\n | {\n success: true;\n result: unknown;\n done: true;\n }\n | {\n success: false;\n error: string;\n }\n);\n\n/**\n * Type guard for RPC request messages\n */\nfunction isRPCRequest(msg: unknown): msg is RPCRequest {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === \"rpc\" &&\n \"id\" in msg &&\n typeof msg.id === \"string\" &&\n \"method\" in msg &&\n typeof msg.method === \"string\" &&\n \"args\" in msg &&\n Array.isArray((msg as RPCRequest).args)\n );\n}\n\n/**\n * Type guard for state update messages\n */\nfunction isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === \"cf_agent_state\" &&\n \"state\" in msg\n );\n}\n\n/**\n * Metadata for a callable method\n */\nexport type CallableMetadata = {\n /** Optional description of what the method does */\n description?: string;\n /** Whether the method supports streaming responses */\n streaming?: boolean;\n};\n\n// biome-ignore lint/complexity/noBannedTypes: <explanation>\nconst callableMetadata = new Map<Function, CallableMetadata>();\n\n/**\n * Decorator that marks a method as callable by clients\n * @param metadata Optional metadata about the callable method\n */\nexport function unstable_callable(metadata: CallableMetadata = {}) {\n return function callableDecorator<This, Args extends unknown[], Return>(\n target: (this: This, ...args: Args) => Return,\n context: ClassMethodDecoratorContext\n ) {\n if (!callableMetadata.has(target)) {\n callableMetadata.set(target, metadata);\n }\n\n return target;\n };\n}\n\n/**\n * A class for creating workflow entry points that can be used with Cloudflare Workers\n */\nexport class WorkflowEntrypoint extends CFWorkflowEntrypoint {}\n\n/**\n * Represents a scheduled task within an Agent\n * @template T Type of the payload data\n */\nexport type Schedule<T = string> = {\n /** Unique identifier for the schedule */\n id: string;\n /** Name of the method to be called */\n callback: string;\n /** Data to be passed to the callback */\n payload: T;\n} & (\n | {\n /** Type of schedule for one-time execution at a specific time */\n type: \"scheduled\";\n /** Timestamp when the task should execute */\n time: number;\n }\n | {\n /** Type of schedule for delayed execution */\n type: \"delayed\";\n /** Timestamp when the task should execute */\n time: number;\n /** Number of seconds to delay execution */\n delayInSeconds: number;\n }\n | {\n /** Type of schedule for recurring execution based on cron expression */\n type: \"cron\";\n /** Timestamp for the next execution */\n time: number;\n /** Cron expression defining the schedule */\n cron: string;\n }\n);\n\nfunction getNextCronTime(cron: string) {\n const interval = parseCronExpression(cron);\n return interval.getNextDate();\n}\n\nconst STATE_ROW_ID = \"cf_state_row_id\";\nconst STATE_WAS_CHANGED = \"cf_state_was_changed\";\n\nconst DEFAULT_STATE = {} as unknown;\n\n/**\n * Base class for creating Agent implementations\n * @template Env Environment type containing bindings\n * @template State State type to store within the Agent\n */\nexport class Agent<Env, State = unknown> extends Server<Env> {\n #state = DEFAULT_STATE as State;\n\n /**\n * Initial state for the Agent\n * Override to provide default state values\n */\n initialState: State = DEFAULT_STATE as State;\n\n /**\n * Current state of the Agent\n */\n get state(): State {\n if (this.#state !== DEFAULT_STATE) {\n // state was previously set, and populated internal state\n return this.#state;\n }\n // looks like this is the first time the state is being accessed\n // check if the state was set in a previous life\n const wasChanged = this.sql<{ state: \"true\" | undefined }>`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}\n `;\n\n // ok, let's pick up the actual state from the db\n const result = this.sql<{ state: State | undefined }>`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}\n `;\n\n if (\n wasChanged[0]?.state === \"true\" ||\n // we do this check for people who updated their code before we shipped wasChanged\n result[0]?.state\n ) {\n const state = result[0]?.state as string; // could be null?\n\n this.#state = JSON.parse(state);\n return this.#state;\n }\n\n // ok, this is the first time the state is being accessed\n // and the state was not set in a previous life\n // so we need to set the initial state (if provided)\n if (this.initialState === DEFAULT_STATE) {\n // no initial state provided, so we return undefined\n return undefined as State;\n }\n // initial state provided, so we set the state,\n // update db and return the initial state\n this.setState(this.initialState);\n return this.initialState;\n }\n\n /**\n * Agent configuration options\n */\n static options = {\n /** Whether the Agent should hibernate when inactive */\n hibernate: true, // default to hibernate\n };\n\n /**\n * Execute SQL queries against the Agent's database\n * @template T Type of the returned rows\n * @param strings SQL query template strings\n * @param values Values to be inserted into the query\n * @returns Array of query results\n */\n sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ) {\n let query = \"\";\n try {\n // Construct the SQL query with placeholders\n query = strings.reduce(\n (acc, str, i) => acc + str + (i < values.length ? \"?\" : \"\"),\n \"\"\n );\n\n // Execute the SQL query with the provided values\n return [...this.ctx.storage.sql.exec(query, ...values)] as T[];\n } catch (e) {\n console.error(`failed to execute sql query: ${query}`, e);\n throw e;\n }\n }\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_state (\n id TEXT PRIMARY KEY NOT NULL,\n state TEXT\n )\n `;\n\n void this.ctx.blockConcurrencyWhile(async () => {\n try {\n // Create alarms table if it doesn't exist\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_schedules (\n id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),\n callback TEXT,\n payload TEXT,\n type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),\n time INTEGER,\n delayInSeconds INTEGER,\n cron TEXT,\n created_at INTEGER DEFAULT (unixepoch())\n )\n `;\n\n // execute any pending alarms and schedule the next alarm\n await this.alarm();\n } catch (e) {\n console.error(e);\n throw e;\n }\n });\n\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n if (typeof message !== \"string\") {\n return _onMessage(connection, message);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(message);\n } catch (e) {\n // silently fail and let the onMessage handler handle it\n return _onMessage(connection, message);\n }\n\n if (isStateUpdateMessage(parsed)) {\n this.#setStateInternal(parsed.state as State, connection);\n return;\n }\n\n if (isRPCRequest(parsed)) {\n try {\n const { id, method, args } = parsed;\n\n // Check if method exists and is callable\n const methodFn = this[method as keyof this];\n if (typeof methodFn !== \"function\") {\n throw new Error(`Method ${method} does not exist`);\n }\n\n if (!this.isCallable(method)) {\n throw new Error(`Method ${method} is not callable`);\n }\n\n // biome-ignore lint/complexity/noBannedTypes: <explanation>\n const metadata = callableMetadata.get(methodFn as Function);\n\n // For streaming methods, pass a StreamingResponse object\n if (metadata?.streaming) {\n const stream = new StreamingResponse(connection, id);\n await methodFn.apply(this, [stream, ...args]);\n return;\n }\n\n // For regular methods, execute and send response\n const result = await methodFn.apply(this, args);\n const response: RPCResponse = {\n type: \"rpc\",\n id,\n success: true,\n result,\n done: true,\n };\n connection.send(JSON.stringify(response));\n } catch (e) {\n // Send error response\n const response: RPCResponse = {\n type: \"rpc\",\n id: parsed.id,\n success: false,\n error: e instanceof Error ? e.message : \"Unknown error occurred\",\n };\n connection.send(JSON.stringify(response));\n console.error(\"RPC error:\", e);\n }\n return;\n }\n\n return _onMessage(connection, message);\n };\n\n const _onConnect = this.onConnect.bind(this);\n this.onConnect = (connection: Connection, ctx: ConnectionContext) => {\n // TODO: This is a hack to ensure the state is sent after the connection is established\n // must fix this\n setTimeout(() => {\n if (this.state) {\n connection.send(\n JSON.stringify({\n type: \"cf_agent_state\",\n state: this.state,\n })\n );\n }\n _onConnect(connection, ctx);\n }, 20);\n };\n }\n\n #setStateInternal(state: State, source: Connection | \"server\" = \"server\") {\n this.#state = state;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})\n `;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})\n `;\n this.broadcast(\n JSON.stringify({\n type: \"cf_agent_state\",\n state: state,\n }),\n source !== \"server\" ? [source.id] : []\n );\n this.onStateUpdate(state, source);\n }\n\n /**\n * Update the Agent's state\n * @param state New state to set\n */\n setState(state: State) {\n this.#setStateInternal(state, \"server\");\n }\n\n /**\n * Called when the Agent's state is updated\n * @param state Updated state\n * @param source Source of the state update (\"server\" or a client connection)\n */\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates\n }\n\n /**\n * Called when the Agent receives an email\n * @param email Email message to process\n */\n onEmail(email: ForwardableEmailMessage) {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Render content (not implemented in base class)\n */\n render() {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Schedule a task to be executed in the future\n * @template T Type of the payload data\n * @param when When to execute the task (Date, seconds delay, or cron expression)\n * @param callback Name of the method to call\n * @param payload Data to pass to the callback\n * @returns Schedule object representing the scheduled task\n */\n async schedule<T = string>(\n when: Date | string | number,\n callback: keyof this,\n payload?: T\n ): Promise<Schedule<T>> {\n const id = nanoid(9);\n\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n\n if (typeof this[callback] !== \"function\") {\n throw new Error(`this.${callback} is not a function`);\n }\n\n if (when instanceof Date) {\n const timestamp = Math.floor(when.getTime() / 1000);\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'scheduled', ${timestamp})\n `;\n\n await this.scheduleNextAlarm();\n\n return {\n id,\n callback: callback,\n payload: payload as T,\n time: timestamp,\n type: \"scheduled\",\n };\n }\n if (typeof when === \"number\") {\n const time = new Date(Date.now() + when * 1000);\n const timestamp = Math.floor(time.getTime() / 1000);\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'delayed', ${when}, ${timestamp})\n `;\n\n await this.scheduleNextAlarm();\n\n return {\n id,\n callback: callback,\n payload: payload as T,\n delayInSeconds: when,\n time: timestamp,\n type: \"delayed\",\n };\n }\n if (typeof when === \"string\") {\n const nextExecutionTime = getNextCronTime(when);\n const timestamp = Math.floor(nextExecutionTime.getTime() / 1000);\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'cron', ${when}, ${timestamp})\n `;\n\n await this.scheduleNextAlarm();\n\n return {\n id,\n callback: callback,\n payload: payload as T,\n cron: when,\n time: timestamp,\n type: \"cron\",\n };\n }\n throw new Error(\"Invalid schedule type\");\n }\n\n /**\n * Get a scheduled task by ID\n * @template T Type of the payload data\n * @param id ID of the scheduled task\n * @returns The Schedule object or undefined if not found\n */\n async getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined> {\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE id = ${id}\n `;\n if (!result) return undefined;\n\n return { ...result[0], payload: JSON.parse(result[0].payload) as T };\n }\n\n /**\n * Get scheduled tasks matching the given criteria\n * @template T Type of the payload data\n * @param criteria Criteria to filter schedules\n * @returns Array of matching Schedule objects\n */\n getSchedules<T = string>(\n criteria: {\n description?: string;\n id?: string;\n type?: \"scheduled\" | \"delayed\" | \"cron\";\n timeRange?: { start?: Date; end?: Date };\n } = {}\n ): Schedule<T>[] {\n let query = \"SELECT * FROM cf_agents_schedules WHERE 1=1\";\n const params = [];\n\n if (criteria.id) {\n query += \" AND id = ?\";\n params.push(criteria.id);\n }\n\n if (criteria.description) {\n query += \" AND description = ?\";\n params.push(criteria.description);\n }\n\n if (criteria.type) {\n query += \" AND type = ?\";\n params.push(criteria.type);\n }\n\n if (criteria.timeRange) {\n query += \" AND time >= ? AND time <= ?\";\n const start = criteria.timeRange.start || new Date(0);\n const end = criteria.timeRange.end || new Date(999999999999999);\n params.push(\n Math.floor(start.getTime() / 1000),\n Math.floor(end.getTime() / 1000)\n );\n }\n\n const result = this.ctx.storage.sql\n .exec(query, ...params)\n .toArray()\n .map((row) => ({\n ...row,\n payload: JSON.parse(row.payload as string) as T,\n })) as Schedule<T>[];\n\n return result;\n }\n\n /**\n * Cancel a scheduled task\n * @param id ID of the task to cancel\n * @returns true if the task was cancelled, false otherwise\n */\n async cancelSchedule(id: string): Promise<boolean> {\n this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;\n\n await this.scheduleNextAlarm();\n return true;\n }\n\n private async scheduleNextAlarm() {\n // Find the next schedule that needs to be executed\n const result = this.sql`\n SELECT time FROM cf_agents_schedules \n WHERE time > ${Math.floor(Date.now() / 1000)}\n ORDER BY time ASC \n LIMIT 1\n `;\n if (!result) return;\n\n if (result.length > 0 && \"time\" in result[0]) {\n const nextTime = (result[0].time as number) * 1000;\n await this.ctx.storage.setAlarm(nextTime);\n }\n }\n\n /**\n * Method called when an alarm fires\n * Executes any scheduled tasks that are due\n */\n async alarm() {\n const now = Math.floor(Date.now() / 1000);\n\n // Get all schedules that should be executed now\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE time <= ${now}\n `;\n\n for (const row of result || []) {\n const callback = this[row.callback as keyof Agent<Env>];\n if (!callback) {\n console.error(`callback ${row.callback} not found`);\n continue;\n }\n try {\n (\n callback as (\n payload: unknown,\n schedule: Schedule<unknown>\n ) => Promise<void>\n ).bind(this)(JSON.parse(row.payload as string), row);\n } catch (e) {\n console.error(`error executing callback ${row.callback}`, e);\n }\n if (row.type === \"cron\") {\n // Update next execution time for cron schedules\n const nextExecutionTime = getNextCronTime(row.cron);\n const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);\n\n this.sql`\n UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}\n `;\n } else {\n // Delete one-time schedules after execution\n this.sql`\n DELETE FROM cf_agents_schedules WHERE id = ${row.id}\n `;\n }\n }\n\n // Schedule the next alarm\n await this.scheduleNextAlarm();\n }\n\n /**\n * Destroy the Agent, removing all state and scheduled tasks\n */\n async destroy() {\n // drop all tables\n this.sql`DROP TABLE IF EXISTS cf_agents_state`;\n this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;\n\n // delete all alarms\n await this.ctx.storage.deleteAlarm();\n await this.ctx.storage.deleteAll();\n }\n\n /**\n * Get all methods marked as callable on this Agent\n * @returns A map of method names to their metadata\n */\n private isCallable(method: string): boolean {\n // biome-ignore lint/complexity/noBannedTypes: <explanation>\n return callableMetadata.has(this[method as keyof this] as Function);\n }\n}\n\n/**\n * Namespace for creating Agent instances\n * @template Agentic Type of the Agent class\n */\nexport type AgentNamespace<Agentic extends Agent<unknown>> =\n DurableObjectNamespace<Agentic>;\n\n/**\n * Agent's durable context\n */\nexport type AgentContext = DurableObjectState;\n\n/**\n * Configuration options for Agent routing\n */\nexport type AgentOptions<Env> = PartyServerOptions<Env> & {\n /**\n * Whether to enable CORS for the Agent\n */\n cors?: boolean | HeadersInit | undefined;\n};\n\n/**\n * Route a request to the appropriate Agent\n * @param request Request to route\n * @param env Environment containing Agent bindings\n * @param options Routing options\n * @returns Response from the Agent or undefined if no route matched\n */\nexport async function routeAgentRequest<Env>(\n request: Request,\n env: Env,\n options?: AgentOptions<Env>\n) {\n const corsHeaders =\n options?.cors === true\n ? {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, POST, HEAD, OPTIONS\",\n \"Access-Control-Allow-Credentials\": \"true\",\n \"Access-Control-Max-Age\": \"86400\",\n }\n : options?.cors;\n\n if (request.method === \"OPTIONS\") {\n if (corsHeaders) {\n return new Response(null, {\n headers: corsHeaders,\n });\n }\n console.warn(\n \"Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.\"\n );\n }\n\n let response = await routePartykitRequest(\n request,\n env as Record<string, unknown>,\n {\n prefix: \"agents\",\n ...(options as PartyServerOptions<Record<string, unknown>>),\n }\n );\n\n if (\n response &&\n corsHeaders &&\n request.headers.get(\"upgrade\") !== \"websocket\"\n ) {\n response = new Response(response.body, {\n headers: {\n ...response.headers,\n ...corsHeaders,\n },\n });\n }\n return response;\n}\n\n/**\n * Route an email to the appropriate Agent\n * @param email Email message to route\n * @param env Environment containing Agent bindings\n * @param options Routing options\n */\nexport async function routeAgentEmail<Env>(\n email: ForwardableEmailMessage,\n env: Env,\n options?: AgentOptions<Env>\n): Promise<void> {}\n\n/**\n * Get or create an Agent by name\n * @template Env Environment type containing bindings\n * @template T Type of the Agent class\n * @param namespace Agent namespace\n * @param name Name of the Agent instance\n * @param options Options for Agent creation\n * @returns Promise resolving to an Agent instance stub\n */\nexport function getAgentByName<Env, T extends Agent<Env>>(\n namespace: AgentNamespace<T>,\n name: string,\n options?: {\n jurisdiction?: DurableObjectJurisdiction;\n locationHint?: DurableObjectLocationHint;\n }\n) {\n return getServerByName<Env, T>(namespace, name, options);\n}\n\n/**\n * A wrapper for streaming responses in callable methods\n */\nexport class StreamingResponse {\n #connection: Connection;\n #id: string;\n #closed = false;\n\n constructor(connection: Connection, id: string) {\n this.#connection = connection;\n this.#id = id;\n }\n\n /**\n * Send a chunk of data to the client\n * @param chunk The data to send\n */\n send(chunk: unknown) {\n if (this.#closed) {\n throw new Error(\"StreamingResponse is already closed\");\n }\n const response: RPCResponse = {\n type: \"rpc\",\n id: this.#id,\n success: true,\n result: chunk,\n done: false,\n };\n this.#connection.send(JSON.stringify(response));\n }\n\n /**\n * End the stream and send the final chunk (if any)\n * @param finalChunk Optional final chunk of data to send\n */\n end(finalChunk?: unknown) {\n if (this.#closed) {\n throw new Error(\"StreamingResponse is already closed\");\n }\n this.#closed = true;\n const response: RPCResponse = {\n type: \"rpc\",\n id: this.#id,\n success: true,\n result: finalChunk,\n done: true,\n };\n this.#connection.send(JSON.stringify(response));\n }\n}\n"],"mappings":";;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,OAIK;AAEP,SAAS,2BAA2B;AACpC,SAAS,cAAc;AAIvB,SAAS,sBAAsB,4BAA4B;AA8C3D,SAAS,aAAa,KAAiC;AACrD,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,IAAI,SAAS,SACb,QAAQ,OACR,OAAO,IAAI,OAAO,YAClB,YAAY,OACZ,OAAO,IAAI,WAAW,YACtB,UAAU,OACV,MAAM,QAAS,IAAmB,IAAI;AAE1C;AAKA,SAAS,qBAAqB,KAAyC;AACrE,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,IAAI,SAAS,oBACb,WAAW;AAEf;AAaA,IAAM,mBAAmB,oBAAI,IAAgC;AAMtD,SAAS,kBAAkB,WAA6B,CAAC,GAAG;AACjE,SAAO,SAAS,kBACd,QACA,SACA;AACA,QAAI,CAAC,iBAAiB,IAAI,MAAM,GAAG;AACjC,uBAAiB,IAAI,QAAQ,QAAQ;AAAA,IACvC;AAEA,WAAO;AAAA,EACT;AACF;AAKO,IAAM,qBAAN,cAAiC,qBAAqB;AAAC;AAsC9D,SAAS,gBAAgB,MAAc;AACrC,QAAM,WAAW,oBAAoB,IAAI;AACzC,SAAO,SAAS,YAAY;AAC9B;AAEA,IAAM,eAAe;AACrB,IAAM,oBAAoB;AAE1B,IAAM,gBAAgB,CAAC;AAxKvB;AA+KO,IAAM,QAAN,cAA0C,OAAY;AAAA,EAsF3D,YAAY,KAAmB,KAAU;AACvC,UAAM,KAAK,GAAG;AAvFX;AACL,+BAAS;AAMT;AAAA;AAAA;AAAA;AAAA,wBAAsB;AAkFpB,SAAK;AAAA;AAAA;AAAA;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