agents 0.0.0-de168a2 → 0.0.0-df52d4b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +128 -22
  2. package/dist/ai-chat-agent.d.ts +49 -4
  3. package/dist/ai-chat-agent.js +158 -68
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +21 -5
  6. package/dist/ai-react.js +49 -42
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/ai-types.d.ts +5 -0
  9. package/dist/chunk-DQJFYHG3.js +1290 -0
  10. package/dist/chunk-DQJFYHG3.js.map +1 -0
  11. package/dist/chunk-EM3J4KV7.js +598 -0
  12. package/dist/chunk-EM3J4KV7.js.map +1 -0
  13. package/dist/chunk-KUH345EY.js +116 -0
  14. package/dist/chunk-KUH345EY.js.map +1 -0
  15. package/dist/chunk-PVQZBKN7.js +106 -0
  16. package/dist/chunk-PVQZBKN7.js.map +1 -0
  17. package/dist/client-DgyzBU_8.d.ts +4601 -0
  18. package/dist/client.d.ts +16 -2
  19. package/dist/client.js +6 -126
  20. package/dist/client.js.map +1 -1
  21. package/dist/index.d.ts +263 -18
  22. package/dist/index.js +14 -6
  23. package/dist/mcp/client.d.ts +9 -761
  24. package/dist/mcp/client.js +3 -402
  25. package/dist/mcp/client.js.map +1 -1
  26. package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
  27. package/dist/mcp/do-oauth-client-provider.js +3 -103
  28. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  29. package/dist/mcp/index.d.ts +73 -6
  30. package/dist/mcp/index.js +768 -162
  31. package/dist/mcp/index.js.map +1 -1
  32. package/dist/observability/index.d.ts +46 -0
  33. package/dist/observability/index.js +10 -0
  34. package/dist/react.d.ts +88 -5
  35. package/dist/react.js +20 -8
  36. package/dist/react.js.map +1 -1
  37. package/dist/schedule.d.ts +6 -6
  38. package/dist/schedule.js +4 -6
  39. package/dist/schedule.js.map +1 -1
  40. package/dist/serializable.d.ts +32 -0
  41. package/dist/serializable.js +1 -0
  42. package/dist/serializable.js.map +1 -0
  43. package/package.json +79 -56
  44. package/src/index.ts +1147 -139
  45. package/dist/chunk-HMLY7DHA.js +0 -16
  46. package/dist/chunk-XG52S6YY.js +0 -591
  47. package/dist/chunk-XG52S6YY.js.map +0 -1
  48. /package/dist/{chunk-HMLY7DHA.js.map → observability/index.js.map} +0 -0
package/dist/client.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import {
2
2
  PartySocketOptions,
3
3
  PartyFetchOptions,
4
- PartySocket,
4
+ PartySocket
5
5
  } from "partysocket";
6
+ import { SerializableReturnValue, SerializableValue } from "./serializable.js";
6
7
 
7
8
  /**
8
9
  * Options for creating an AgentClient
@@ -38,17 +39,24 @@ type AgentClientFetchOptions = Omit<PartyFetchOptions, "party" | "room"> & {
38
39
  /** Name of the specific Agent instance */
39
40
  name?: string;
40
41
  };
42
+ /**
43
+ * Convert a camelCase string to a kebab-case string
44
+ * @param str The string to convert
45
+ * @returns The kebab-case string
46
+ */
47
+ declare function camelCaseToKebabCase(str: string): string;
41
48
  /**
42
49
  * WebSocket client for connecting to an Agent
43
50
  */
44
51
  declare class AgentClient<State = unknown> extends PartySocket {
45
- #private;
46
52
  /**
47
53
  * @deprecated Use agentFetch instead
48
54
  */
49
55
  static fetch(_opts: PartyFetchOptions): Promise<Response>;
50
56
  agent: string;
51
57
  name: string;
58
+ private options;
59
+ private _pendingCalls;
52
60
  constructor(options: AgentClientOptions<State>);
53
61
  setState(state: State): void;
54
62
  /**
@@ -58,6 +66,11 @@ declare class AgentClient<State = unknown> extends PartySocket {
58
66
  * @param streamOptions Options for handling streaming responses
59
67
  * @returns Promise that resolves with the method's return value
60
68
  */
69
+ call<T extends SerializableReturnValue>(
70
+ method: string,
71
+ args?: SerializableValue[],
72
+ streamOptions?: StreamOptions
73
+ ): Promise<T>;
61
74
  call<T = unknown>(
62
75
  method: string,
63
76
  args?: unknown[],
@@ -81,4 +94,5 @@ export {
81
94
  type AgentClientOptions,
82
95
  type StreamOptions,
83
96
  agentFetch,
97
+ camelCaseToKebabCase
84
98
  };
package/dist/client.js CHANGED
@@ -1,131 +1,11 @@
1
1
  import {
2
- __privateAdd,
3
- __privateGet,
4
- __privateSet
5
- } from "./chunk-HMLY7DHA.js";
6
-
7
- // src/client.ts
8
- import {
9
- PartySocket
10
- } from "partysocket";
11
- function camelCaseToKebabCase(str) {
12
- if (str === str.toUpperCase() && str !== str.toLowerCase()) {
13
- return str.toLowerCase().replace(/_/g, "-");
14
- }
15
- let kebabified = str.replace(
16
- /[A-Z]/g,
17
- (letter) => `-${letter.toLowerCase()}`
18
- );
19
- kebabified = kebabified.startsWith("-") ? kebabified.slice(1) : kebabified;
20
- return kebabified.replace(/_/g, "-").replace(/-$/, "");
21
- }
22
- var _options, _pendingCalls;
23
- var AgentClient = class extends PartySocket {
24
- constructor(options) {
25
- const agentNamespace = camelCaseToKebabCase(options.agent);
26
- super({
27
- prefix: "agents",
28
- party: agentNamespace,
29
- room: options.name || "default",
30
- ...options
31
- });
32
- __privateAdd(this, _options);
33
- __privateAdd(this, _pendingCalls, /* @__PURE__ */ new Map());
34
- this.agent = agentNamespace;
35
- this.name = options.name || "default";
36
- __privateSet(this, _options, options);
37
- this.addEventListener("message", (event) => {
38
- if (typeof event.data === "string") {
39
- let parsedMessage;
40
- try {
41
- parsedMessage = JSON.parse(event.data);
42
- } catch (error) {
43
- return;
44
- }
45
- if (parsedMessage.type === "cf_agent_state") {
46
- __privateGet(this, _options).onStateUpdate?.(parsedMessage.state, "server");
47
- return;
48
- }
49
- if (parsedMessage.type === "rpc") {
50
- const response = parsedMessage;
51
- const pending = __privateGet(this, _pendingCalls).get(response.id);
52
- if (!pending) return;
53
- if (!response.success) {
54
- pending.reject(new Error(response.error));
55
- __privateGet(this, _pendingCalls).delete(response.id);
56
- pending.stream?.onError?.(response.error);
57
- return;
58
- }
59
- if ("done" in response) {
60
- if (response.done) {
61
- pending.resolve(response.result);
62
- __privateGet(this, _pendingCalls).delete(response.id);
63
- pending.stream?.onDone?.(response.result);
64
- } else {
65
- pending.stream?.onChunk?.(response.result);
66
- }
67
- } else {
68
- pending.resolve(response.result);
69
- __privateGet(this, _pendingCalls).delete(response.id);
70
- }
71
- }
72
- }
73
- });
74
- }
75
- /**
76
- * @deprecated Use agentFetch instead
77
- */
78
- static fetch(_opts) {
79
- throw new Error(
80
- "AgentClient.fetch is not implemented, use agentFetch instead"
81
- );
82
- }
83
- setState(state) {
84
- this.send(JSON.stringify({ type: "cf_agent_state", state }));
85
- __privateGet(this, _options).onStateUpdate?.(state, "client");
86
- }
87
- /**
88
- * Call a method on the Agent
89
- * @param method Name of the method to call
90
- * @param args Arguments to pass to the method
91
- * @param streamOptions Options for handling streaming responses
92
- * @returns Promise that resolves with the method's return value
93
- */
94
- async call(method, args = [], streamOptions) {
95
- return new Promise((resolve, reject) => {
96
- const id = Math.random().toString(36).slice(2);
97
- __privateGet(this, _pendingCalls).set(id, {
98
- resolve: (value) => resolve(value),
99
- reject,
100
- stream: streamOptions,
101
- type: null
102
- });
103
- const request = {
104
- type: "rpc",
105
- id,
106
- method,
107
- args
108
- };
109
- this.send(JSON.stringify(request));
110
- });
111
- }
112
- };
113
- _options = new WeakMap();
114
- _pendingCalls = new WeakMap();
115
- function agentFetch(opts, init) {
116
- const agentNamespace = camelCaseToKebabCase(opts.agent);
117
- return PartySocket.fetch(
118
- {
119
- prefix: "agents",
120
- party: agentNamespace,
121
- room: opts.name || "default",
122
- ...opts
123
- },
124
- init
125
- );
126
- }
2
+ AgentClient,
3
+ agentFetch,
4
+ camelCaseToKebabCase
5
+ } from "./chunk-KUH345EY.js";
127
6
  export {
128
7
  AgentClient,
129
- agentFetch
8
+ agentFetch,
9
+ camelCaseToKebabCase
130
10
  };
131
11
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts"],"sourcesContent":["import {\n PartySocket,\n type PartySocketOptions,\n type PartyFetchOptions,\n} from \"partysocket\";\nimport type { RPCRequest, RPCResponse } from \"./\";\n\n/**\n * Options for creating an AgentClient\n */\nexport type AgentClientOptions<State = unknown> = Omit<\n PartySocketOptions,\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n /** Called when the Agent's state is updated */\n onStateUpdate?: (state: State, source: \"server\" | \"client\") => void;\n};\n\n/**\n * Options for streaming RPC calls\n */\nexport type StreamOptions = {\n /** Called when a chunk of data is received */\n onChunk?: (chunk: unknown) => void;\n /** Called when the stream ends */\n onDone?: (finalChunk: unknown) => void;\n /** Called when an error occurs */\n onError?: (error: string) => void;\n};\n\n/**\n * Options for the agentFetch function\n */\nexport type AgentClientFetchOptions = Omit<\n PartyFetchOptions,\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n};\n\n/**\n * Convert a camelCase string to a kebab-case string\n * @param str The string to convert\n * @returns The kebab-case string\n */\nfunction camelCaseToKebabCase(str: string): string {\n // If string is all uppercase, convert to lowercase\n if (str === str.toUpperCase() && str !== str.toLowerCase()) {\n return str.toLowerCase().replace(/_/g, \"-\");\n }\n\n // Otherwise handle camelCase to kebab-case\n let kebabified = str.replace(\n /[A-Z]/g,\n (letter) => `-${letter.toLowerCase()}`\n );\n kebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n // Convert any remaining underscores to hyphens and remove trailing -'s\n return kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n\n/**\n * WebSocket client for connecting to an Agent\n */\nexport class AgentClient<State = unknown> extends PartySocket {\n /**\n * @deprecated Use agentFetch instead\n */\n static fetch(_opts: PartyFetchOptions): Promise<Response> {\n throw new Error(\n \"AgentClient.fetch is not implemented, use agentFetch instead\"\n );\n }\n agent: string;\n name: string;\n #options: AgentClientOptions<State>;\n #pendingCalls = new Map<\n string,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n stream?: StreamOptions;\n type?: unknown;\n }\n >();\n\n constructor(options: AgentClientOptions<State>) {\n const agentNamespace = camelCaseToKebabCase(options.agent);\n super({\n prefix: \"agents\",\n party: agentNamespace,\n room: options.name || \"default\",\n ...options,\n });\n this.agent = agentNamespace;\n this.name = options.name || \"default\";\n this.#options = options;\n\n this.addEventListener(\"message\", (event) => {\n if (typeof event.data === \"string\") {\n let parsedMessage: Record<string, unknown>;\n try {\n parsedMessage = JSON.parse(event.data);\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (parsedMessage.type === \"cf_agent_state\") {\n this.#options.onStateUpdate?.(parsedMessage.state as State, \"server\");\n return;\n }\n if (parsedMessage.type === \"rpc\") {\n const response = parsedMessage as RPCResponse;\n const pending = this.#pendingCalls.get(response.id);\n if (!pending) return;\n\n if (!response.success) {\n pending.reject(new Error(response.error));\n this.#pendingCalls.delete(response.id);\n pending.stream?.onError?.(response.error);\n return;\n }\n\n // Handle streaming responses\n if (\"done\" in response) {\n if (response.done) {\n pending.resolve(response.result);\n this.#pendingCalls.delete(response.id);\n pending.stream?.onDone?.(response.result);\n } else {\n pending.stream?.onChunk?.(response.result);\n }\n } else {\n // Non-streaming response\n pending.resolve(response.result);\n this.#pendingCalls.delete(response.id);\n }\n }\n }\n });\n }\n\n setState(state: State) {\n this.send(JSON.stringify({ type: \"cf_agent_state\", state }));\n this.#options.onStateUpdate?.(state, \"client\");\n }\n\n /**\n * Call a method on the Agent\n * @param method Name of the method to call\n * @param args Arguments to pass to the method\n * @param streamOptions Options for handling streaming responses\n * @returns Promise that resolves with the method's return value\n */\n async call<T = unknown>(\n method: string,\n args: unknown[] = [],\n streamOptions?: StreamOptions\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const id = Math.random().toString(36).slice(2);\n this.#pendingCalls.set(id, {\n resolve: (value: unknown) => resolve(value as T),\n reject,\n stream: streamOptions,\n type: null as T,\n });\n\n const request: RPCRequest = {\n type: \"rpc\",\n id,\n method,\n args,\n };\n\n this.send(JSON.stringify(request));\n });\n }\n}\n\n/**\n * Make an HTTP request to an Agent\n * @param opts Connection options\n * @param init Request initialization options\n * @returns Promise resolving to a Response\n */\nexport function agentFetch(opts: AgentClientFetchOptions, init?: RequestInit) {\n const agentNamespace = camelCaseToKebabCase(opts.agent);\n\n return PartySocket.fetch(\n {\n prefix: \"agents\",\n party: agentNamespace,\n room: opts.name || \"default\",\n ...opts,\n },\n init\n );\n}\n"],"mappings":"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","names":[]}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,23 @@
1
+ import { env } from "cloudflare:workers";
2
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
+ import {
4
+ ServerCapabilities,
5
+ Tool,
6
+ Prompt,
7
+ Resource
8
+ } from "@modelcontextprotocol/sdk/types.js";
1
9
  import { Server, Connection, PartyServerOptions } from "partyserver";
2
10
  export { Connection, ConnectionContext, WSMessage } from "partyserver";
3
- import { AsyncLocalStorage } from "node:async_hooks";
11
+ import { M as MCPClientManager } from "./client-DgyzBU_8.js";
12
+ import { Observability } from "./observability/index.js";
13
+ import "zod";
14
+ import "@modelcontextprotocol/sdk/shared/protocol.js";
15
+ import "ai";
16
+ import "@modelcontextprotocol/sdk/client/sse.js";
17
+ import "@modelcontextprotocol/sdk/client/streamableHttp.js";
18
+ import "./mcp/do-oauth-client-provider.js";
19
+ import "@modelcontextprotocol/sdk/client/auth.js";
20
+ import "@modelcontextprotocol/sdk/shared/auth.js";
4
21
 
5
22
  /**
6
23
  * RPC request message from client
@@ -59,6 +76,12 @@ declare function unstable_callable(
59
76
  target: (this: This, ...args: Args) => Return,
60
77
  context: ClassMethodDecoratorContext
61
78
  ) => (this: This, ...args: Args) => Return;
79
+ type QueueItem<T = string> = {
80
+ id: string;
81
+ payload: T;
82
+ callback: keyof Agent<unknown>;
83
+ created_at: number;
84
+ };
62
85
  /**
63
86
  * Represents a scheduled task within an Agent
64
87
  * @template T Type of the payload data
@@ -94,18 +117,46 @@ type Schedule<T = string> = {
94
117
  cron: string;
95
118
  }
96
119
  );
97
- declare const unstable_context: AsyncLocalStorage<{
98
- agent: Agent<unknown>;
120
+ /**
121
+ * MCP Server state update message from server -> Client
122
+ */
123
+ type MCPServerMessage = {
124
+ type: "cf_agent_mcp_servers";
125
+ mcp: MCPServersState;
126
+ };
127
+ type MCPServersState = {
128
+ servers: {
129
+ [id: string]: MCPServer;
130
+ };
131
+ tools: Tool[];
132
+ prompts: Prompt[];
133
+ resources: Resource[];
134
+ };
135
+ type MCPServer = {
136
+ name: string;
137
+ server_url: string;
138
+ auth_url: string | null;
139
+ state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
140
+ instructions: string | null;
141
+ capabilities: ServerCapabilities | null;
142
+ };
143
+ declare function getCurrentAgent<
144
+ T extends Agent<unknown, unknown> = Agent<unknown, unknown>
145
+ >(): {
146
+ agent: T | undefined;
99
147
  connection: Connection | undefined;
100
148
  request: Request | undefined;
101
- }>;
149
+ email: AgentEmail | undefined;
150
+ };
102
151
  /**
103
152
  * Base class for creating Agent implementations
104
153
  * @template Env Environment type containing bindings
105
154
  * @template State State type to store within the Agent
106
155
  */
107
- declare class Agent<Env, State = unknown> extends Server<Env> {
108
- #private;
156
+ declare class Agent<Env = typeof env, State = unknown> extends Server<Env> {
157
+ private _state;
158
+ private _ParentClass;
159
+ mcp: MCPClientManager;
109
160
  /**
110
161
  * Initial state for the Agent
111
162
  * Override to provide default state values
@@ -122,6 +173,10 @@ declare class Agent<Env, State = unknown> extends Server<Env> {
122
173
  /** Whether the Agent should hibernate when inactive */
123
174
  hibernate: boolean;
124
175
  };
176
+ /**
177
+ * The observability implementation to use for the Agent
178
+ */
179
+ observability?: Observability;
125
180
  /**
126
181
  * Execute SQL queries against the Agent's database
127
182
  * @template T Type of the returned rows
@@ -134,6 +189,7 @@ declare class Agent<Env, State = unknown> extends Server<Env> {
134
189
  ...values: (string | number | boolean | null)[]
135
190
  ): T[];
136
191
  constructor(ctx: AgentContext, env: Env);
192
+ private _setStateInternal;
137
193
  /**
138
194
  * Update the Agent's state
139
195
  * @param state New state to set
@@ -146,16 +202,75 @@ declare class Agent<Env, State = unknown> extends Server<Env> {
146
202
  */
147
203
  onStateUpdate(state: State | undefined, source: Connection | "server"): void;
148
204
  /**
149
- * Called when the Agent receives an email
205
+ * Called when the Agent receives an email via routeAgentEmail()
206
+ * Override this method to handle incoming emails
150
207
  * @param email Email message to process
151
208
  */
152
- onEmail(email: ForwardableEmailMessage): Promise<void>;
209
+ _onEmail(email: AgentEmail): Promise<void>;
210
+ /**
211
+ * Reply to an email
212
+ * @param email The email to reply to
213
+ * @param options Options for the reply
214
+ * @returns void
215
+ */
216
+ replyToEmail(
217
+ email: AgentEmail,
218
+ options: {
219
+ fromName: string;
220
+ subject?: string | undefined;
221
+ body: string;
222
+ contentType?: string;
223
+ headers?: Record<string, string>;
224
+ }
225
+ ): Promise<void>;
226
+ private _tryCatch;
227
+ /**
228
+ * Automatically wrap custom methods with agent context
229
+ * This ensures getCurrentAgent() works in all custom methods without decorators
230
+ */
231
+ private _autoWrapCustomMethods;
153
232
  onError(connection: Connection, error: unknown): void | Promise<void>;
154
233
  onError(error: unknown): void | Promise<void>;
155
234
  /**
156
235
  * Render content (not implemented in base class)
157
236
  */
158
237
  render(): void;
238
+ /**
239
+ * Queue a task to be executed in the future
240
+ * @param payload Payload to pass to the callback
241
+ * @param callback Name of the method to call
242
+ * @returns The ID of the queued task
243
+ */
244
+ queue<T = unknown>(callback: keyof this, payload: T): Promise<string>;
245
+ private _flushingQueue;
246
+ private _flushQueue;
247
+ /**
248
+ * Dequeue a task by ID
249
+ * @param id ID of the task to dequeue
250
+ */
251
+ dequeue(id: string): Promise<void>;
252
+ /**
253
+ * Dequeue all tasks
254
+ */
255
+ dequeueAll(): Promise<void>;
256
+ /**
257
+ * Dequeue all tasks by callback
258
+ * @param callback Name of the callback to dequeue
259
+ */
260
+ dequeueAllByCallback(callback: string): Promise<void>;
261
+ /**
262
+ * Get a queued task by ID
263
+ * @param id ID of the task to get
264
+ * @returns The task or undefined if not found
265
+ */
266
+ getQueue(id: string): Promise<QueueItem<string> | undefined>;
267
+ /**
268
+ * Get all queues by key and value
269
+ * @param key Key to filter by
270
+ * @param value Value to filter by
271
+ * @returns Array of matching QueueItem objects
272
+ */
273
+ getQueues(key: string, value: string): Promise<QueueItem<string>[]>;
159
274
  /**
160
275
  * Schedule a task to be executed in the future
161
276
  * @template T Type of the payload data
@@ -196,15 +311,77 @@ declare class Agent<Env, State = unknown> extends Server<Env> {
196
311
  * @returns true if the task was cancelled, false otherwise
197
312
  */
198
313
  cancelSchedule(id: string): Promise<boolean>;
314
+ private _scheduleNextAlarm;
199
315
  /**
200
- * Method called when an alarm fires
201
- * Executes any scheduled tasks that are due
316
+ * Method called when an alarm fires.
317
+ * Executes any scheduled tasks that are due.
318
+ *
319
+ * @remarks
320
+ * To schedule a task, please use the `this.schedule` method instead.
321
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
202
322
  */
203
- alarm(): Promise<void>;
323
+ readonly alarm: () => Promise<void>;
204
324
  /**
205
325
  * Destroy the Agent, removing all state and scheduled tasks
206
326
  */
207
327
  destroy(): Promise<void>;
328
+ /**
329
+ * Get all methods marked as callable on this Agent
330
+ * @returns A map of method names to their metadata
331
+ */
332
+ private _isCallable;
333
+ /**
334
+ * Connect to a new MCP Server
335
+ *
336
+ * @param url MCP Server SSE URL
337
+ * @param callbackHost Base host for the agent, used for the redirect URI.
338
+ * @param agentsPrefix agents routing prefix if not using `agents`
339
+ * @param options MCP client and transport (header) options
340
+ * @returns authUrl
341
+ */
342
+ addMcpServer(
343
+ serverName: string,
344
+ url: string,
345
+ callbackHost: string,
346
+ agentsPrefix?: string,
347
+ options?: {
348
+ client?: ConstructorParameters<typeof Client>[1];
349
+ transport?: {
350
+ headers: HeadersInit;
351
+ };
352
+ }
353
+ ): Promise<{
354
+ id: string;
355
+ authUrl: string | undefined;
356
+ }>;
357
+ _connectToMcpServerInternal(
358
+ _serverName: string,
359
+ url: string,
360
+ callbackUrl: string,
361
+ options?: {
362
+ client?: ConstructorParameters<typeof Client>[1];
363
+ /**
364
+ * We don't expose the normal set of transport options because:
365
+ * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
366
+ * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
367
+ *
368
+ * 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).
369
+ */
370
+ transport?: {
371
+ headers?: HeadersInit;
372
+ };
373
+ },
374
+ reconnect?: {
375
+ id: string;
376
+ oauthClientId?: string;
377
+ }
378
+ ): Promise<{
379
+ id: string;
380
+ authUrl: string | undefined;
381
+ clientId: string | undefined;
382
+ }>;
383
+ removeMcpServer(id: string): Promise<void>;
384
+ getMcpServers(): MCPServersState;
208
385
  }
209
386
  /**
210
387
  * Namespace for creating Agent instances
@@ -237,17 +414,72 @@ declare function routeAgentRequest<Env>(
237
414
  env: Env,
238
415
  options?: AgentOptions<Env>
239
416
  ): Promise<Response | null>;
417
+ type EmailResolver<Env> = (
418
+ email: ForwardableEmailMessage,
419
+ env: Env
420
+ ) => Promise<{
421
+ agentName: string;
422
+ agentId: string;
423
+ } | null>;
424
+ /**
425
+ * Create a resolver that uses the message-id header to determine the agent to route the email to
426
+ * @returns A function that resolves the agent to route the email to
427
+ */
428
+ declare function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env>;
429
+ /**
430
+ * Create a resolver that uses the email address to determine the agent to route the email to
431
+ * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
432
+ * @returns A function that resolves the agent to route the email to
433
+ */
434
+ declare function createAddressBasedEmailResolver<Env>(
435
+ defaultAgentName: string
436
+ ): EmailResolver<Env>;
437
+ /**
438
+ * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
439
+ * @param agentName The name of the agent to route the email to
440
+ * @param agentId The id of the agent to route the email to
441
+ * @returns A function that resolves the agent to route the email to
442
+ */
443
+ declare function createCatchAllEmailResolver<Env>(
444
+ agentName: string,
445
+ agentId: string
446
+ ): EmailResolver<Env>;
447
+ type EmailRoutingOptions<Env> = AgentOptions<Env> & {
448
+ resolver: EmailResolver<Env>;
449
+ };
240
450
  /**
241
451
  * Route an email to the appropriate Agent
242
- * @param email Email message to route
243
- * @param env Environment containing Agent bindings
244
- * @param options Routing options
452
+ * @param email The email to route
453
+ * @param env The environment containing the Agent bindings
454
+ * @param options The options for routing the email
455
+ * @returns A promise that resolves when the email has been routed
245
456
  */
246
457
  declare function routeAgentEmail<Env>(
247
458
  email: ForwardableEmailMessage,
248
459
  env: Env,
249
- options?: AgentOptions<Env>
460
+ options: EmailRoutingOptions<Env>
250
461
  ): Promise<void>;
462
+ type AgentEmail = {
463
+ from: string;
464
+ to: string;
465
+ getRaw: () => Promise<Uint8Array>;
466
+ headers: Headers;
467
+ rawSize: number;
468
+ setReject: (reason: string) => void;
469
+ forward: (rcptTo: string, headers?: Headers) => Promise<void>;
470
+ reply: (options: { from: string; to: string; raw: string }) => Promise<void>;
471
+ };
472
+ type EmailSendOptions = {
473
+ to: string;
474
+ subject: string;
475
+ body: string;
476
+ contentType?: string;
477
+ headers?: Record<string, string>;
478
+ includeRoutingHeaders?: boolean;
479
+ agentName?: string;
480
+ agentId?: string;
481
+ domain?: string;
482
+ };
251
483
  /**
252
484
  * Get or create an Agent by name
253
485
  * @template Env Environment type containing bindings
@@ -269,7 +501,9 @@ declare function getAgentByName<Env, T extends Agent<Env>>(
269
501
  * A wrapper for streaming responses in callable methods
270
502
  */
271
503
  declare class StreamingResponse {
272
- #private;
504
+ private _connection;
505
+ private _id;
506
+ private _closed;
273
507
  constructor(connection: Connection, id: string);
274
508
  /**
275
509
  * Send a chunk of data to the client
@@ -286,17 +520,28 @@ declare class StreamingResponse {
286
520
  export {
287
521
  Agent,
288
522
  type AgentContext,
523
+ type AgentEmail,
289
524
  type AgentNamespace,
290
525
  type AgentOptions,
291
526
  type CallableMetadata,
527
+ type EmailResolver,
528
+ type EmailRoutingOptions,
529
+ type EmailSendOptions,
530
+ type MCPServer,
531
+ type MCPServerMessage,
532
+ type MCPServersState,
533
+ type QueueItem,
292
534
  type RPCRequest,
293
535
  type RPCResponse,
294
536
  type Schedule,
295
537
  type StateUpdateMessage,
296
538
  StreamingResponse,
539
+ createAddressBasedEmailResolver,
540
+ createCatchAllEmailResolver,
541
+ createHeaderBasedEmailResolver,
297
542
  getAgentByName,
543
+ getCurrentAgent,
298
544
  routeAgentEmail,
299
545
  routeAgentRequest,
300
- unstable_callable,
301
- unstable_context,
546
+ unstable_callable
302
547
  };
package/dist/index.js CHANGED
@@ -1,20 +1,28 @@
1
1
  import {
2
2
  Agent,
3
3
  StreamingResponse,
4
+ createAddressBasedEmailResolver,
5
+ createCatchAllEmailResolver,
6
+ createHeaderBasedEmailResolver,
4
7
  getAgentByName,
8
+ getCurrentAgent,
5
9
  routeAgentEmail,
6
10
  routeAgentRequest,
7
- unstable_callable,
8
- unstable_context
9
- } from "./chunk-XG52S6YY.js";
10
- import "./chunk-HMLY7DHA.js";
11
+ unstable_callable
12
+ } from "./chunk-DQJFYHG3.js";
13
+ import "./chunk-EM3J4KV7.js";
14
+ import "./chunk-PVQZBKN7.js";
15
+ import "./chunk-KUH345EY.js";
11
16
  export {
12
17
  Agent,
13
18
  StreamingResponse,
19
+ createAddressBasedEmailResolver,
20
+ createCatchAllEmailResolver,
21
+ createHeaderBasedEmailResolver,
14
22
  getAgentByName,
23
+ getCurrentAgent,
15
24
  routeAgentEmail,
16
25
  routeAgentRequest,
17
- unstable_callable,
18
- unstable_context
26
+ unstable_callable
19
27
  };
20
28
  //# sourceMappingURL=index.js.map