agents 0.0.2 → 0.0.37

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