agents 0.0.0-3d0c872 → 0.0.0-4100b67

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 CHANGED
@@ -12,10 +12,23 @@ import { parseCronExpression } from "cron-schedule";
12
12
  import { nanoid } from "nanoid";
13
13
 
14
14
  import { AsyncLocalStorage } from "node:async_hooks";
15
+ import { MCPClientManager } from "./mcp/client";
16
+ import {
17
+ DurableObjectOAuthClientProvider,
18
+ type AgentsOAuthProvider,
19
+ } from "./mcp/do-oauth-client-provider";
20
+ import type {
21
+ Tool,
22
+ Resource,
23
+ Prompt,
24
+ } from "@modelcontextprotocol/sdk/types.js";
15
25
 
16
- export type { Connection, WSMessage, ConnectionContext } from "partyserver";
26
+ import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
27
+ import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
17
28
 
18
- import { WorkflowEntrypoint as CFWorkflowEntrypoint } from "cloudflare:workers";
29
+ import { camelCaseToKebabCase } from "./client";
30
+
31
+ export type { Connection, WSMessage, ConnectionContext } from "partyserver";
19
32
 
20
33
  /**
21
34
  * RPC request message from client
@@ -99,7 +112,6 @@ export type CallableMetadata = {
99
112
  streaming?: boolean;
100
113
  };
101
114
 
102
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
103
115
  const callableMetadata = new Map<Function, CallableMetadata>();
104
116
 
105
117
  /**
@@ -119,11 +131,6 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
119
131
  };
120
132
  }
121
133
 
122
- /**
123
- * A class for creating workflow entry points that can be used with Cloudflare Workers
124
- */
125
- export class WorkflowEntrypoint extends CFWorkflowEntrypoint {}
126
-
127
134
  /**
128
135
  * Represents a scheduled task within an Agent
129
136
  * @template T Type of the payload data
@@ -165,24 +172,90 @@ function getNextCronTime(cron: string) {
165
172
  return interval.getNextDate();
166
173
  }
167
174
 
175
+ /**
176
+ * MCP Server state update message from server -> Client
177
+ */
178
+ export type MCPServerMessage = {
179
+ type: "cf_agent_mcp_servers";
180
+ mcp: MCPServersState;
181
+ };
182
+
183
+ export type MCPServersState = {
184
+ servers: {
185
+ [id: string]: MCPServer;
186
+ };
187
+ tools: Tool[];
188
+ prompts: Prompt[];
189
+ resources: Resource[];
190
+ };
191
+
192
+ export type MCPServer = {
193
+ name: string;
194
+ server_url: string;
195
+ auth_url: string | null;
196
+ state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
197
+ };
198
+
199
+ /**
200
+ * MCP Server data stored in DO SQL for resuming MCP Server connections
201
+ */
202
+ type MCPServerRow = {
203
+ id: string;
204
+ name: string;
205
+ server_url: string;
206
+ client_id: string | null;
207
+ auth_url: string | null;
208
+ callback_url: string;
209
+ server_options: string;
210
+ };
211
+
168
212
  const STATE_ROW_ID = "cf_state_row_id";
169
213
  const STATE_WAS_CHANGED = "cf_state_was_changed";
170
214
 
171
215
  const DEFAULT_STATE = {} as unknown;
172
216
 
173
- export const unstable_context = new AsyncLocalStorage<{
217
+ const agentContext = new AsyncLocalStorage<{
174
218
  agent: Agent<unknown>;
175
219
  connection: Connection | undefined;
176
220
  request: Request | undefined;
177
221
  }>();
178
222
 
223
+ export function getCurrentAgent<
224
+ T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
225
+ >(): {
226
+ agent: T | undefined;
227
+ connection: Connection | undefined;
228
+ request: Request<unknown, CfProperties<unknown>> | undefined;
229
+ } {
230
+ const store = agentContext.getStore() as
231
+ | {
232
+ agent: T;
233
+ connection: Connection | undefined;
234
+ request: Request<unknown, CfProperties<unknown>> | undefined;
235
+ }
236
+ | undefined;
237
+ if (!store) {
238
+ return {
239
+ agent: undefined,
240
+ connection: undefined,
241
+ request: undefined,
242
+ };
243
+ }
244
+ return store;
245
+ }
246
+
179
247
  /**
180
248
  * Base class for creating Agent implementations
181
249
  * @template Env Environment type containing bindings
182
250
  * @template State State type to store within the Agent
183
251
  */
184
252
  export class Agent<Env, State = unknown> extends Server<Env> {
185
- #state = DEFAULT_STATE as State;
253
+ private _state = DEFAULT_STATE as State;
254
+
255
+ private _ParentClass: typeof Agent<Env, State> =
256
+ Object.getPrototypeOf(this).constructor;
257
+
258
+ mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
186
259
 
187
260
  /**
188
261
  * Initial state for the Agent
@@ -194,9 +267,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
194
267
  * Current state of the Agent
195
268
  */
196
269
  get state(): State {
197
- if (this.#state !== DEFAULT_STATE) {
270
+ if (this._state !== DEFAULT_STATE) {
198
271
  // state was previously set, and populated internal state
199
- return this.#state;
272
+ return this._state;
200
273
  }
201
274
  // looks like this is the first time the state is being accessed
202
275
  // check if the state was set in a previous life
@@ -216,8 +289,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
216
289
  ) {
217
290
  const state = result[0]?.state as string; // could be null?
218
291
 
219
- this.#state = JSON.parse(state);
220
- return this.#state;
292
+ this._state = JSON.parse(state);
293
+ return this._state;
221
294
  }
222
295
 
223
296
  // ok, this is the first time the state is being accessed
@@ -278,7 +351,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
278
351
  `;
279
352
 
280
353
  void this.ctx.blockConcurrencyWhile(async () => {
281
- return this.#tryCatch(async () => {
354
+ return this._tryCatch(async () => {
282
355
  // Create alarms table if it doesn't exist
283
356
  this.sql`
284
357
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
@@ -298,13 +371,53 @@ export class Agent<Env, State = unknown> extends Server<Env> {
298
371
  });
299
372
  });
300
373
 
374
+ this.sql`
375
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
376
+ id TEXT PRIMARY KEY NOT NULL,
377
+ name TEXT NOT NULL,
378
+ server_url TEXT NOT NULL,
379
+ callback_url TEXT NOT NULL,
380
+ client_id TEXT,
381
+ auth_url TEXT,
382
+ server_options TEXT
383
+ )
384
+ `;
385
+
386
+ const _onRequest = this.onRequest.bind(this);
387
+ this.onRequest = (request: Request) => {
388
+ return agentContext.run(
389
+ { agent: this, connection: undefined, request },
390
+ async () => {
391
+ if (this.mcp.isCallbackRequest(request)) {
392
+ await this.mcp.handleCallbackRequest(request);
393
+
394
+ // after the MCP connection handshake, we can send updated mcp state
395
+ this.broadcast(
396
+ JSON.stringify({
397
+ type: "cf_agent_mcp_servers",
398
+ mcp: this._getMcpServerStateInternal(),
399
+ })
400
+ );
401
+
402
+ // We probably should let the user configure this response/redirect, but this is fine for now.
403
+ return new Response("<script>window.close();</script>", {
404
+ status: 200,
405
+ headers: { "content-type": "text/html" },
406
+ });
407
+ }
408
+
409
+ return this._tryCatch(() => _onRequest(request));
410
+ }
411
+ );
412
+ };
413
+
301
414
  const _onMessage = this.onMessage.bind(this);
302
415
  this.onMessage = async (connection: Connection, message: WSMessage) => {
303
- return unstable_context.run(
416
+ return agentContext.run(
304
417
  { agent: this, connection, request: undefined },
305
418
  async () => {
306
419
  if (typeof message !== "string") {
307
- return this.#tryCatch(() => _onMessage(connection, message));
420
+ return this._tryCatch(() => _onMessage(connection, message));
308
421
  }
309
422
 
310
423
  let parsed: unknown;
@@ -312,11 +425,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
312
425
  parsed = JSON.parse(message);
313
426
  } catch (e) {
314
427
  // silently fail and let the onMessage handler handle it
315
- return this.#tryCatch(() => _onMessage(connection, message));
428
+ return this._tryCatch(() => _onMessage(connection, message));
316
429
  }
317
430
 
318
431
  if (isStateUpdateMessage(parsed)) {
319
- this.#setStateInternal(parsed.state as State, connection);
432
+ this._setStateInternal(parsed.state as State, connection);
320
433
  return;
321
434
  }
322
435
 
@@ -330,11 +443,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
330
443
  throw new Error(`Method ${method} does not exist`);
331
444
  }
332
445
 
333
- if (!this.#isCallable(method)) {
446
+ if (!this._isCallable(method)) {
334
447
  throw new Error(`Method ${method} is not callable`);
335
448
  }
336
449
 
337
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
338
450
  const metadata = callableMetadata.get(methodFn as Function);
339
451
 
340
452
  // For streaming methods, pass a StreamingResponse object
@@ -369,7 +481,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
369
481
  return;
370
482
  }
371
483
 
372
- return this.#tryCatch(() => _onMessage(connection, message));
484
+ return this._tryCatch(() => _onMessage(connection, message));
373
485
  }
374
486
  );
375
487
  };
@@ -378,7 +490,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
378
490
  this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
379
491
  // TODO: This is a hack to ensure the state is sent after the connection is established
380
492
  // must fix this
381
- return unstable_context.run(
493
+ return agentContext.run(
382
494
  { agent: this, connection, request: ctx.request },
383
495
  async () => {
384
496
  setTimeout(() => {
@@ -390,15 +502,65 @@ export class Agent<Env, State = unknown> extends Server<Env> {
390
502
  })
391
503
  );
392
504
  }
393
- return this.#tryCatch(() => _onConnect(connection, ctx));
505
+
506
+ connection.send(
507
+ JSON.stringify({
508
+ type: "cf_agent_mcp_servers",
509
+ mcp: this._getMcpServerStateInternal(),
510
+ })
511
+ );
512
+
513
+ return this._tryCatch(() => _onConnect(connection, ctx));
394
514
  }, 20);
395
515
  }
396
516
  );
397
517
  };
518
+
519
+ const _onStart = this.onStart.bind(this);
520
+ this.onStart = async () => {
521
+ return agentContext.run(
522
+ { agent: this, connection: undefined, request: undefined },
523
+ async () => {
524
+ const servers = this.sql<MCPServerRow>`
525
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
526
+ `;
527
+
528
+ // from DO storage, reconnect to all servers using our saved auth information
529
+ await Promise.allSettled(
530
+ servers.map((server) => {
531
+ return this._connectToMcpServerInternal(
532
+ server.name,
533
+ server.server_url,
534
+ server.callback_url,
535
+ server.server_options
536
+ ? JSON.parse(server.server_options)
537
+ : undefined,
538
+ {
539
+ id: server.id,
540
+ oauthClientId: server.client_id ?? undefined,
541
+ }
542
+ );
543
+ })
544
+ );
545
+
546
+ this.broadcast(
547
+ JSON.stringify({
548
+ type: "cf_agent_mcp_servers",
549
+ mcp: this._getMcpServerStateInternal(),
550
+ })
551
+ );
552
+
553
+ await this._tryCatch(() => _onStart());
554
+ }
555
+ );
556
+ };
398
557
  }
399
558
 
400
- #setStateInternal(state: State, source: Connection | "server" = "server") {
401
- this.#state = state;
559
+ private _setStateInternal(
560
+ state: State,
561
+ source: Connection | "server" = "server"
562
+ ) {
563
+ this._state = state;
402
564
  this.sql`
403
565
  INSERT OR REPLACE INTO cf_agents_state (id, state)
404
566
  VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
@@ -414,9 +576,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
414
576
  }),
415
577
  source !== "server" ? [source.id] : []
416
578
  );
417
- return this.#tryCatch(() => {
418
- const { connection, request } = unstable_context.getStore() || {};
419
- return unstable_context.run(
579
+ return this._tryCatch(() => {
580
+ const { connection, request } = agentContext.getStore() || {};
581
+ return agentContext.run(
420
582
  { agent: this, connection, request },
421
583
  async () => {
422
584
  return this.onStateUpdate(state, source);
@@ -430,7 +592,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
430
592
  * @param state New state to set
431
593
  */
432
594
  setState(state: State) {
433
- this.#setStateInternal(state, "server");
595
+ this._setStateInternal(state, "server");
434
596
  }
435
597
 
436
598
  /**
@@ -447,7 +609,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
447
609
  * @param email Email message to process
448
610
  */
449
611
  onEmail(email: ForwardableEmailMessage) {
450
- return unstable_context.run(
612
+ return agentContext.run(
451
613
  { agent: this, connection: undefined, request: undefined },
452
614
  async () => {
453
615
  console.error("onEmail not implemented");
@@ -455,7 +617,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
455
617
  );
456
618
  }
457
619
 
458
- async #tryCatch<T>(fn: () => T | Promise<T>) {
620
+ private async _tryCatch<T>(fn: () => T | Promise<T>) {
459
621
  try {
460
622
  return await fn();
461
623
  } catch (e) {
@@ -529,7 +691,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
529
691
  )}, 'scheduled', ${timestamp})
530
692
  `;
531
693
 
532
- await this.#scheduleNextAlarm();
694
+ await this._scheduleNextAlarm();
533
695
 
534
696
  return {
535
697
  id,
@@ -550,7 +712,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
550
712
  )}, 'delayed', ${when}, ${timestamp})
551
713
  `;
552
714
 
553
- await this.#scheduleNextAlarm();
715
+ await this._scheduleNextAlarm();
554
716
 
555
717
  return {
556
718
  id,
@@ -572,7 +734,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
572
734
  )}, 'cron', ${when}, ${timestamp})
573
735
  `;
574
736
 
575
- await this.#scheduleNextAlarm();
737
+ await this._scheduleNextAlarm();
576
738
 
577
739
  return {
578
740
  id,
@@ -659,11 +821,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
659
821
  async cancelSchedule(id: string): Promise<boolean> {
660
822
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
661
823
 
662
- await this.#scheduleNextAlarm();
824
+ await this._scheduleNextAlarm();
663
825
  return true;
664
826
  }
665
827
 
666
- async #scheduleNextAlarm() {
828
+ private async _scheduleNextAlarm() {
667
829
  // Find the next schedule that needs to be executed
668
830
  const result = this.sql`
669
831
  SELECT time FROM cf_agents_schedules
@@ -680,10 +842,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
680
842
  }
681
843
 
682
844
  /**
683
- * Method called when an alarm fires
684
- * Executes any scheduled tasks that are due
845
+ * Method called when an alarm fires.
846
+ * Executes any scheduled tasks that are due.
847
+ *
848
+ * @remarks
849
+ * To schedule a task, please use the `this.schedule` method instead.
850
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
685
851
  */
686
- async alarm() {
852
+ public readonly alarm = async () => {
687
853
  const now = Math.floor(Date.now() / 1000);
688
854
 
689
855
  // Get all schedules that should be executed now
@@ -697,7 +863,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
697
863
  console.error(`callback ${row.callback} not found`);
698
864
  continue;
699
865
  }
700
- await unstable_context.run(
866
+ await agentContext.run(
701
867
  { agent: this, connection: undefined, request: undefined },
702
868
  async () => {
703
869
  try {
@@ -729,8 +895,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
729
895
  }
730
896
 
731
897
  // Schedule the next alarm
732
- await this.#scheduleNextAlarm();
733
- }
898
+ await this._scheduleNextAlarm();
899
+ };
734
900
 
735
901
  /**
736
902
  * Destroy the Agent, removing all state and scheduled tasks
@@ -739,6 +905,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
739
905
  // drop all tables
740
906
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
741
907
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
908
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
742
909
 
743
910
  // delete all alarms
744
911
  await this.ctx.storage.deleteAlarm();
@@ -749,10 +916,168 @@ export class Agent<Env, State = unknown> extends Server<Env> {
749
916
  * Get all methods marked as callable on this Agent
750
917
  * @returns A map of method names to their metadata
751
918
  */
752
- #isCallable(method: string): boolean {
753
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
919
+ private _isCallable(method: string): boolean {
754
920
  return callableMetadata.has(this[method as keyof this] as Function);
755
921
  }
922
+
923
+ /**
924
+ * Connect to a new MCP Server
925
+ *
926
+ * @param url MCP Server SSE URL
927
+ * @param callbackHost Base host for the agent, used for the redirect URI.
928
+ * @param agentsPrefix agents routing prefix if not using `agents`
929
+ * @param options MCP client and transport (header) options
930
+ * @returns authUrl
931
+ */
932
+ async addMcpServer(
933
+ serverName: string,
934
+ url: string,
935
+ callbackHost: string,
936
+ agentsPrefix = "agents",
937
+ options?: {
938
+ client?: ConstructorParameters<typeof Client>[1];
939
+ transport?: {
940
+ headers: HeadersInit;
941
+ };
942
+ }
943
+ ): Promise<{ id: string; authUrl: string | undefined }> {
944
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
945
+
946
+ const result = await this._connectToMcpServerInternal(
947
+ serverName,
948
+ url,
949
+ callbackUrl,
950
+ options
951
+ );
952
+
953
+ this.broadcast(
954
+ JSON.stringify({
955
+ type: "cf_agent_mcp_servers",
956
+ mcp: this._getMcpServerStateInternal(),
957
+ })
958
+ );
959
+
960
+ return result;
961
+ }
962
+
963
+ async _connectToMcpServerInternal(
964
+ serverName: string,
965
+ url: string,
966
+ callbackUrl: string,
967
+ // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
968
+ options?: {
969
+ client?: ConstructorParameters<typeof Client>[1];
970
+ /**
971
+ * We don't expose the normal set of transport options because:
972
+ * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
973
+ * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
974
+ *
975
+ * This has the limitation that you can't override fetch, but I think headers should handle nearly all cases needed (i.e. non-standard bearer auth).
976
+ */
977
+ transport?: {
978
+ headers?: HeadersInit;
979
+ };
980
+ },
981
+ reconnect?: {
982
+ id: string;
983
+ oauthClientId?: string;
984
+ }
985
+ ): Promise<{ id: string; authUrl: string | undefined }> {
986
+ const authProvider = new DurableObjectOAuthClientProvider(
987
+ this.ctx.storage,
988
+ this.name,
989
+ callbackUrl
990
+ );
991
+
992
+ if (reconnect) {
993
+ authProvider.serverId = reconnect.id;
994
+ if (reconnect.oauthClientId) {
995
+ authProvider.clientId = reconnect.oauthClientId;
996
+ }
997
+ }
998
+
999
+ // allows passing through transport headers if necessary
1000
+ // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
1001
+ let headerTransportOpts: SSEClientTransportOptions = {};
1002
+ if (options?.transport?.headers) {
1003
+ headerTransportOpts = {
1004
+ eventSourceInit: {
1005
+ fetch: (url, init) =>
1006
+ fetch(url, {
1007
+ ...init,
1008
+ headers: options?.transport?.headers,
1009
+ }),
1010
+ },
1011
+ requestInit: {
1012
+ headers: options?.transport?.headers,
1013
+ },
1014
+ };
1015
+ }
1016
+
1017
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
1018
+ reconnect,
1019
+ transport: {
1020
+ ...headerTransportOpts,
1021
+ authProvider,
1022
+ },
1023
+ client: options?.client,
1024
+ });
1025
+
1026
+ this.sql`
1027
+ INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1028
+ VALUES (
1029
+ ${id},
1030
+ ${serverName},
1031
+ ${url},
1032
+ ${clientId ?? null},
1033
+ ${authUrl ?? null},
1034
+ ${callbackUrl},
1035
+ ${options ? JSON.stringify(options) : null}
1036
+ );
1037
+ `;
1038
+
1039
+ return {
1040
+ id,
1041
+ authUrl,
1042
+ };
1043
+ }
1044
+
1045
+ async removeMcpServer(id: string) {
1046
+ this.mcp.closeConnection(id);
1047
+ this.sql`
1048
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1049
+ `;
1050
+ this.broadcast(
1051
+ JSON.stringify({
1052
+ type: "cf_agent_mcp_servers",
1053
+ mcp: this._getMcpServerStateInternal(),
1054
+ })
1055
+ );
1056
+ }
1057
+
1058
+ private _getMcpServerStateInternal(): MCPServersState {
1059
+ const mcpState: MCPServersState = {
1060
+ servers: {},
1061
+ tools: this.mcp.listTools(),
1062
+ prompts: this.mcp.listPrompts(),
1063
+ resources: this.mcp.listResources(),
1064
+ };
1065
+
1066
+ const servers = this.sql<MCPServerRow>`
1067
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1068
+ `;
1069
+
1070
+ for (const server of servers) {
1071
+ mcpState.servers[server.id] = {
1072
+ name: server.name,
1073
+ server_url: server.server_url,
1074
+ auth_url: server.auth_url,
1075
+ state: this.mcp.mcpConnections[server.id].connectionState,
1076
+ };
1077
+ }
1078
+
1079
+ return mcpState;
1080
+ }
756
1081
  }
757
1082
 
758
1083
  /**
@@ -856,7 +1181,7 @@ export async function routeAgentEmail<Env>(
856
1181
  * @param options Options for Agent creation
857
1182
  * @returns Promise resolving to an Agent instance stub
858
1183
  */
859
- export function getAgentByName<Env, T extends Agent<Env>>(
1184
+ export async function getAgentByName<Env, T extends Agent<Env>>(
860
1185
  namespace: AgentNamespace<T>,
861
1186
  name: string,
862
1187
  options?: {
@@ -871,13 +1196,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
871
1196
  * A wrapper for streaming responses in callable methods
872
1197
  */
873
1198
  export class StreamingResponse {
874
- #connection: Connection;
875
- #id: string;
876
- #closed = false;
1199
+ private _connection: Connection;
1200
+ private _id: string;
1201
+ private _closed = false;
877
1202
 
878
1203
  constructor(connection: Connection, id: string) {
879
- this.#connection = connection;
880
- this.#id = id;
1204
+ this._connection = connection;
1205
+ this._id = id;
881
1206
  }
882
1207
 
883
1208
  /**
@@ -885,17 +1210,17 @@ export class StreamingResponse {
885
1210
  * @param chunk The data to send
886
1211
  */
887
1212
  send(chunk: unknown) {
888
- if (this.#closed) {
1213
+ if (this._closed) {
889
1214
  throw new Error("StreamingResponse is already closed");
890
1215
  }
891
1216
  const response: RPCResponse = {
892
1217
  type: "rpc",
893
- id: this.#id,
1218
+ id: this._id,
894
1219
  success: true,
895
1220
  result: chunk,
896
1221
  done: false,
897
1222
  };
898
- this.#connection.send(JSON.stringify(response));
1223
+ this._connection.send(JSON.stringify(response));
899
1224
  }
900
1225
 
901
1226
  /**
@@ -903,17 +1228,17 @@ export class StreamingResponse {
903
1228
  * @param finalChunk Optional final chunk of data to send
904
1229
  */
905
1230
  end(finalChunk?: unknown) {
906
- if (this.#closed) {
1231
+ if (this._closed) {
907
1232
  throw new Error("StreamingResponse is already closed");
908
1233
  }
909
- this.#closed = true;
1234
+ this._closed = true;
910
1235
  const response: RPCResponse = {
911
1236
  type: "rpc",
912
- id: this.#id,
1237
+ id: this._id,
913
1238
  success: true,
914
1239
  result: finalChunk,
915
1240
  done: true,
916
1241
  };
917
- this.#connection.send(JSON.stringify(response));
1242
+ this._connection.send(JSON.stringify(response));
918
1243
  }
919
1244
  }