agents 0.0.2 → 0.0.38

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