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.
- package/README.md +128 -22
- package/dist/ai-chat-agent.d.ts +49 -4
- package/dist/ai-chat-agent.js +158 -68
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +21 -5
- package/dist/ai-react.js +49 -42
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types.d.ts +5 -0
- package/dist/chunk-DQJFYHG3.js +1290 -0
- package/dist/chunk-DQJFYHG3.js.map +1 -0
- package/dist/chunk-EM3J4KV7.js +598 -0
- package/dist/chunk-EM3J4KV7.js.map +1 -0
- package/dist/chunk-KUH345EY.js +116 -0
- package/dist/chunk-KUH345EY.js.map +1 -0
- package/dist/chunk-PVQZBKN7.js +106 -0
- package/dist/chunk-PVQZBKN7.js.map +1 -0
- package/dist/client-DgyzBU_8.d.ts +4601 -0
- package/dist/client.d.ts +16 -2
- package/dist/client.js +6 -126
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +263 -18
- package/dist/index.js +14 -6
- package/dist/mcp/client.d.ts +9 -761
- package/dist/mcp/client.js +3 -402
- package/dist/mcp/client.js.map +1 -1
- package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
- package/dist/mcp/do-oauth-client-provider.js +3 -103
- package/dist/mcp/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/index.d.ts +73 -6
- package/dist/mcp/index.js +768 -162
- package/dist/mcp/index.js.map +1 -1
- package/dist/observability/index.d.ts +46 -0
- package/dist/observability/index.js +10 -0
- package/dist/react.d.ts +88 -5
- package/dist/react.js +20 -8
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +6 -6
- package/dist/schedule.js +4 -6
- package/dist/schedule.js.map +1 -1
- package/dist/serializable.d.ts +32 -0
- package/dist/serializable.js +1 -0
- package/dist/serializable.js.map +1 -0
- package/package.json +79 -56
- package/src/index.ts +1147 -139
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-XG52S6YY.js +0 -591
- package/dist/chunk-XG52S6YY.js.map +0 -1
- /package/dist/{chunk-HMLY7DHA.js.map → observability/index.js.map} +0 -0
package/src/index.ts
CHANGED
|
@@ -1,19 +1,33 @@
|
|
|
1
|
+
import type { env } from "cloudflare:workers";
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
4
|
+
import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
5
|
+
|
|
6
|
+
import type {
|
|
7
|
+
Prompt,
|
|
8
|
+
Resource,
|
|
9
|
+
ServerCapabilities,
|
|
10
|
+
Tool
|
|
11
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
12
|
+
import { parseCronExpression } from "cron-schedule";
|
|
13
|
+
import { nanoid } from "nanoid";
|
|
14
|
+
import { EmailMessage } from "cloudflare:email";
|
|
1
15
|
import {
|
|
2
|
-
Server,
|
|
3
|
-
routePartykitRequest,
|
|
4
|
-
type PartyServerOptions,
|
|
5
|
-
getServerByName,
|
|
6
16
|
type Connection,
|
|
7
17
|
type ConnectionContext,
|
|
18
|
+
type PartyServerOptions,
|
|
19
|
+
Server,
|
|
8
20
|
type WSMessage,
|
|
21
|
+
getServerByName,
|
|
22
|
+
routePartykitRequest
|
|
9
23
|
} from "partyserver";
|
|
24
|
+
import { camelCaseToKebabCase } from "./client";
|
|
25
|
+
import { MCPClientManager } from "./mcp/client";
|
|
26
|
+
// import type { MCPClientConnection } from "./mcp/client-connection";
|
|
27
|
+
import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
|
|
28
|
+
import { genericObservability, type Observability } from "./observability";
|
|
10
29
|
|
|
11
|
-
|
|
12
|
-
import { nanoid } from "nanoid";
|
|
13
|
-
|
|
14
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
15
|
-
|
|
16
|
-
export type { Connection, WSMessage, ConnectionContext } from "partyserver";
|
|
30
|
+
export type { Connection, ConnectionContext, WSMessage } from "partyserver";
|
|
17
31
|
|
|
18
32
|
/**
|
|
19
33
|
* RPC request message from client
|
|
@@ -97,7 +111,6 @@ export type CallableMetadata = {
|
|
|
97
111
|
streaming?: boolean;
|
|
98
112
|
};
|
|
99
113
|
|
|
100
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
101
114
|
const callableMetadata = new Map<Function, CallableMetadata>();
|
|
102
115
|
|
|
103
116
|
/**
|
|
@@ -107,6 +120,7 @@ const callableMetadata = new Map<Function, CallableMetadata>();
|
|
|
107
120
|
export function unstable_callable(metadata: CallableMetadata = {}) {
|
|
108
121
|
return function callableDecorator<This, Args extends unknown[], Return>(
|
|
109
122
|
target: (this: This, ...args: Args) => Return,
|
|
123
|
+
// biome-ignore lint/correctness/noUnusedFunctionParameters: later
|
|
110
124
|
context: ClassMethodDecoratorContext
|
|
111
125
|
) {
|
|
112
126
|
if (!callableMetadata.has(target)) {
|
|
@@ -117,6 +131,13 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
|
|
|
117
131
|
};
|
|
118
132
|
}
|
|
119
133
|
|
|
134
|
+
export type QueueItem<T = string> = {
|
|
135
|
+
id: string;
|
|
136
|
+
payload: T;
|
|
137
|
+
callback: keyof Agent<unknown>;
|
|
138
|
+
created_at: number;
|
|
139
|
+
};
|
|
140
|
+
|
|
120
141
|
/**
|
|
121
142
|
* Represents a scheduled task within an Agent
|
|
122
143
|
* @template T Type of the payload data
|
|
@@ -158,24 +179,118 @@ function getNextCronTime(cron: string) {
|
|
|
158
179
|
return interval.getNextDate();
|
|
159
180
|
}
|
|
160
181
|
|
|
182
|
+
/**
|
|
183
|
+
* MCP Server state update message from server -> Client
|
|
184
|
+
*/
|
|
185
|
+
export type MCPServerMessage = {
|
|
186
|
+
type: "cf_agent_mcp_servers";
|
|
187
|
+
mcp: MCPServersState;
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
export type MCPServersState = {
|
|
191
|
+
servers: {
|
|
192
|
+
[id: string]: MCPServer;
|
|
193
|
+
};
|
|
194
|
+
tools: Tool[];
|
|
195
|
+
prompts: Prompt[];
|
|
196
|
+
resources: Resource[];
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
export type MCPServer = {
|
|
200
|
+
name: string;
|
|
201
|
+
server_url: string;
|
|
202
|
+
auth_url: string | null;
|
|
203
|
+
// This state is specifically about the temporary process of getting a token (if needed).
|
|
204
|
+
// Scope outside of that can't be relied upon because when the DO sleeps, there's no way
|
|
205
|
+
// to communicate a change to a non-ready state.
|
|
206
|
+
state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
|
|
207
|
+
instructions: string | null;
|
|
208
|
+
capabilities: ServerCapabilities | null;
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* MCP Server data stored in DO SQL for resuming MCP Server connections
|
|
213
|
+
*/
|
|
214
|
+
type MCPServerRow = {
|
|
215
|
+
id: string;
|
|
216
|
+
name: string;
|
|
217
|
+
server_url: string;
|
|
218
|
+
client_id: string | null;
|
|
219
|
+
auth_url: string | null;
|
|
220
|
+
callback_url: string;
|
|
221
|
+
server_options: string;
|
|
222
|
+
};
|
|
223
|
+
|
|
161
224
|
const STATE_ROW_ID = "cf_state_row_id";
|
|
162
225
|
const STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
163
226
|
|
|
164
227
|
const DEFAULT_STATE = {} as unknown;
|
|
165
228
|
|
|
166
|
-
|
|
167
|
-
agent: Agent<unknown>;
|
|
229
|
+
const agentContext = new AsyncLocalStorage<{
|
|
230
|
+
agent: Agent<unknown, unknown>;
|
|
168
231
|
connection: Connection | undefined;
|
|
169
232
|
request: Request | undefined;
|
|
233
|
+
email: AgentEmail | undefined;
|
|
170
234
|
}>();
|
|
171
235
|
|
|
236
|
+
export function getCurrentAgent<
|
|
237
|
+
T extends Agent<unknown, unknown> = Agent<unknown, unknown>
|
|
238
|
+
>(): {
|
|
239
|
+
agent: T | undefined;
|
|
240
|
+
connection: Connection | undefined;
|
|
241
|
+
request: Request | undefined;
|
|
242
|
+
email: AgentEmail | undefined;
|
|
243
|
+
} {
|
|
244
|
+
const store = agentContext.getStore() as
|
|
245
|
+
| {
|
|
246
|
+
agent: T;
|
|
247
|
+
connection: Connection | undefined;
|
|
248
|
+
request: Request | undefined;
|
|
249
|
+
email: AgentEmail | undefined;
|
|
250
|
+
}
|
|
251
|
+
| undefined;
|
|
252
|
+
if (!store) {
|
|
253
|
+
return {
|
|
254
|
+
agent: undefined,
|
|
255
|
+
connection: undefined,
|
|
256
|
+
request: undefined,
|
|
257
|
+
email: undefined
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
return store;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
|
|
265
|
+
* @param agent The agent instance
|
|
266
|
+
* @param method The method to wrap
|
|
267
|
+
* @returns A wrapped method that runs within the agent context
|
|
268
|
+
*/
|
|
269
|
+
|
|
270
|
+
// biome-ignore lint/suspicious/noExplicitAny: I can't typescript
|
|
271
|
+
function withAgentContext<T extends (...args: any[]) => any>(
|
|
272
|
+
method: T
|
|
273
|
+
): (this: Agent<unknown, unknown>, ...args: Parameters<T>) => ReturnType<T> {
|
|
274
|
+
return function (...args: Parameters<T>): ReturnType<T> {
|
|
275
|
+
const { connection, request, email } = getCurrentAgent();
|
|
276
|
+
return agentContext.run({ agent: this, connection, request, email }, () => {
|
|
277
|
+
return method.apply(this, args);
|
|
278
|
+
});
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
172
282
|
/**
|
|
173
283
|
* Base class for creating Agent implementations
|
|
174
284
|
* @template Env Environment type containing bindings
|
|
175
285
|
* @template State State type to store within the Agent
|
|
176
286
|
*/
|
|
177
|
-
export class Agent<Env, State = unknown> extends Server<Env> {
|
|
178
|
-
|
|
287
|
+
export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
|
|
288
|
+
private _state = DEFAULT_STATE as State;
|
|
289
|
+
|
|
290
|
+
private _ParentClass: typeof Agent<Env, State> =
|
|
291
|
+
Object.getPrototypeOf(this).constructor;
|
|
292
|
+
|
|
293
|
+
mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
179
294
|
|
|
180
295
|
/**
|
|
181
296
|
* Initial state for the Agent
|
|
@@ -187,9 +302,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
187
302
|
* Current state of the Agent
|
|
188
303
|
*/
|
|
189
304
|
get state(): State {
|
|
190
|
-
if (this
|
|
305
|
+
if (this._state !== DEFAULT_STATE) {
|
|
191
306
|
// state was previously set, and populated internal state
|
|
192
|
-
return this
|
|
307
|
+
return this._state;
|
|
193
308
|
}
|
|
194
309
|
// looks like this is the first time the state is being accessed
|
|
195
310
|
// check if the state was set in a previous life
|
|
@@ -209,8 +324,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
209
324
|
) {
|
|
210
325
|
const state = result[0]?.state as string; // could be null?
|
|
211
326
|
|
|
212
|
-
this
|
|
213
|
-
return this
|
|
327
|
+
this._state = JSON.parse(state);
|
|
328
|
+
return this._state;
|
|
214
329
|
}
|
|
215
330
|
|
|
216
331
|
// ok, this is the first time the state is being accessed
|
|
@@ -231,9 +346,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
231
346
|
*/
|
|
232
347
|
static options = {
|
|
233
348
|
/** Whether the Agent should hibernate when inactive */
|
|
234
|
-
hibernate: true
|
|
349
|
+
hibernate: true // default to hibernate
|
|
235
350
|
};
|
|
236
351
|
|
|
352
|
+
/**
|
|
353
|
+
* The observability implementation to use for the Agent
|
|
354
|
+
*/
|
|
355
|
+
observability?: Observability = genericObservability;
|
|
356
|
+
|
|
237
357
|
/**
|
|
238
358
|
* Execute SQL queries against the Agent's database
|
|
239
359
|
* @template T Type of the returned rows
|
|
@@ -263,6 +383,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
263
383
|
constructor(ctx: AgentContext, env: Env) {
|
|
264
384
|
super(ctx, env);
|
|
265
385
|
|
|
386
|
+
// Auto-wrap custom methods with agent context
|
|
387
|
+
this._autoWrapCustomMethods();
|
|
388
|
+
|
|
266
389
|
this.sql`
|
|
267
390
|
CREATE TABLE IF NOT EXISTS cf_agents_state (
|
|
268
391
|
id TEXT PRIMARY KEY NOT NULL,
|
|
@@ -270,8 +393,17 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
270
393
|
)
|
|
271
394
|
`;
|
|
272
395
|
|
|
396
|
+
this.sql`
|
|
397
|
+
CREATE TABLE IF NOT EXISTS cf_agents_queues (
|
|
398
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
399
|
+
payload TEXT,
|
|
400
|
+
callback TEXT,
|
|
401
|
+
created_at INTEGER DEFAULT (unixepoch())
|
|
402
|
+
)
|
|
403
|
+
`;
|
|
404
|
+
|
|
273
405
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
274
|
-
return this
|
|
406
|
+
return this._tryCatch(async () => {
|
|
275
407
|
// Create alarms table if it doesn't exist
|
|
276
408
|
this.sql`
|
|
277
409
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
@@ -291,25 +423,65 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
291
423
|
});
|
|
292
424
|
});
|
|
293
425
|
|
|
426
|
+
this.sql`
|
|
427
|
+
CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
|
|
428
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
429
|
+
name TEXT NOT NULL,
|
|
430
|
+
server_url TEXT NOT NULL,
|
|
431
|
+
callback_url TEXT NOT NULL,
|
|
432
|
+
client_id TEXT,
|
|
433
|
+
auth_url TEXT,
|
|
434
|
+
server_options TEXT
|
|
435
|
+
)
|
|
436
|
+
`;
|
|
437
|
+
|
|
438
|
+
const _onRequest = this.onRequest.bind(this);
|
|
439
|
+
this.onRequest = (request: Request) => {
|
|
440
|
+
return agentContext.run(
|
|
441
|
+
{ agent: this, connection: undefined, request, email: undefined },
|
|
442
|
+
async () => {
|
|
443
|
+
if (this.mcp.isCallbackRequest(request)) {
|
|
444
|
+
await this.mcp.handleCallbackRequest(request);
|
|
445
|
+
|
|
446
|
+
// after the MCP connection handshake, we can send updated mcp state
|
|
447
|
+
this.broadcast(
|
|
448
|
+
JSON.stringify({
|
|
449
|
+
mcp: this.getMcpServers(),
|
|
450
|
+
type: "cf_agent_mcp_servers"
|
|
451
|
+
})
|
|
452
|
+
);
|
|
453
|
+
|
|
454
|
+
// We probably should let the user configure this response/redirect, but this is fine for now.
|
|
455
|
+
return new Response("<script>window.close();</script>", {
|
|
456
|
+
headers: { "content-type": "text/html" },
|
|
457
|
+
status: 200
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
return this._tryCatch(() => _onRequest(request));
|
|
462
|
+
}
|
|
463
|
+
);
|
|
464
|
+
};
|
|
465
|
+
|
|
294
466
|
const _onMessage = this.onMessage.bind(this);
|
|
295
467
|
this.onMessage = async (connection: Connection, message: WSMessage) => {
|
|
296
|
-
return
|
|
297
|
-
{ agent: this, connection, request: undefined },
|
|
468
|
+
return agentContext.run(
|
|
469
|
+
{ agent: this, connection, request: undefined, email: undefined },
|
|
298
470
|
async () => {
|
|
299
471
|
if (typeof message !== "string") {
|
|
300
|
-
return this
|
|
472
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
301
473
|
}
|
|
302
474
|
|
|
303
475
|
let parsed: unknown;
|
|
304
476
|
try {
|
|
305
477
|
parsed = JSON.parse(message);
|
|
306
|
-
} catch (
|
|
478
|
+
} catch (_e) {
|
|
307
479
|
// silently fail and let the onMessage handler handle it
|
|
308
|
-
return this
|
|
480
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
309
481
|
}
|
|
310
482
|
|
|
311
483
|
if (isStateUpdateMessage(parsed)) {
|
|
312
|
-
this
|
|
484
|
+
this._setStateInternal(parsed.state as State, connection);
|
|
313
485
|
return;
|
|
314
486
|
}
|
|
315
487
|
|
|
@@ -323,11 +495,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
323
495
|
throw new Error(`Method ${method} does not exist`);
|
|
324
496
|
}
|
|
325
497
|
|
|
326
|
-
if (!this
|
|
498
|
+
if (!this._isCallable(method)) {
|
|
327
499
|
throw new Error(`Method ${method} is not callable`);
|
|
328
500
|
}
|
|
329
501
|
|
|
330
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
331
502
|
const metadata = callableMetadata.get(methodFn as Function);
|
|
332
503
|
|
|
333
504
|
// For streaming methods, pass a StreamingResponse object
|
|
@@ -339,22 +510,37 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
339
510
|
|
|
340
511
|
// For regular methods, execute and send response
|
|
341
512
|
const result = await methodFn.apply(this, args);
|
|
513
|
+
|
|
514
|
+
this.observability?.emit(
|
|
515
|
+
{
|
|
516
|
+
displayMessage: `RPC call to ${method}`,
|
|
517
|
+
id: nanoid(),
|
|
518
|
+
payload: {
|
|
519
|
+
method,
|
|
520
|
+
streaming: metadata?.streaming
|
|
521
|
+
},
|
|
522
|
+
timestamp: Date.now(),
|
|
523
|
+
type: "rpc"
|
|
524
|
+
},
|
|
525
|
+
this.ctx
|
|
526
|
+
);
|
|
527
|
+
|
|
342
528
|
const response: RPCResponse = {
|
|
343
|
-
|
|
529
|
+
done: true,
|
|
344
530
|
id,
|
|
345
|
-
success: true,
|
|
346
531
|
result,
|
|
347
|
-
|
|
532
|
+
success: true,
|
|
533
|
+
type: "rpc"
|
|
348
534
|
};
|
|
349
535
|
connection.send(JSON.stringify(response));
|
|
350
536
|
} catch (e) {
|
|
351
537
|
// Send error response
|
|
352
538
|
const response: RPCResponse = {
|
|
353
|
-
type: "rpc",
|
|
354
|
-
id: parsed.id,
|
|
355
|
-
success: false,
|
|
356
539
|
error:
|
|
357
540
|
e instanceof Error ? e.message : "Unknown error occurred",
|
|
541
|
+
id: parsed.id,
|
|
542
|
+
success: false,
|
|
543
|
+
type: "rpc"
|
|
358
544
|
};
|
|
359
545
|
connection.send(JSON.stringify(response));
|
|
360
546
|
console.error("RPC error:", e);
|
|
@@ -362,7 +548,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
362
548
|
return;
|
|
363
549
|
}
|
|
364
550
|
|
|
365
|
-
return this
|
|
551
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
366
552
|
}
|
|
367
553
|
);
|
|
368
554
|
};
|
|
@@ -371,27 +557,117 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
371
557
|
this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
|
|
372
558
|
// TODO: This is a hack to ensure the state is sent after the connection is established
|
|
373
559
|
// must fix this
|
|
374
|
-
return
|
|
375
|
-
{ agent: this, connection, request: ctx.request },
|
|
560
|
+
return agentContext.run(
|
|
561
|
+
{ agent: this, connection, request: ctx.request, email: undefined },
|
|
376
562
|
async () => {
|
|
377
563
|
setTimeout(() => {
|
|
378
564
|
if (this.state) {
|
|
379
565
|
connection.send(
|
|
380
566
|
JSON.stringify({
|
|
381
|
-
type: "cf_agent_state",
|
|
382
567
|
state: this.state,
|
|
568
|
+
type: "cf_agent_state"
|
|
383
569
|
})
|
|
384
570
|
);
|
|
385
571
|
}
|
|
386
|
-
|
|
572
|
+
|
|
573
|
+
connection.send(
|
|
574
|
+
JSON.stringify({
|
|
575
|
+
mcp: this.getMcpServers(),
|
|
576
|
+
type: "cf_agent_mcp_servers"
|
|
577
|
+
})
|
|
578
|
+
);
|
|
579
|
+
|
|
580
|
+
this.observability?.emit(
|
|
581
|
+
{
|
|
582
|
+
displayMessage: "Connection established",
|
|
583
|
+
id: nanoid(),
|
|
584
|
+
payload: {
|
|
585
|
+
connectionId: connection.id
|
|
586
|
+
},
|
|
587
|
+
timestamp: Date.now(),
|
|
588
|
+
type: "connect"
|
|
589
|
+
},
|
|
590
|
+
this.ctx
|
|
591
|
+
);
|
|
592
|
+
return this._tryCatch(() => _onConnect(connection, ctx));
|
|
387
593
|
}, 20);
|
|
388
594
|
}
|
|
389
595
|
);
|
|
390
596
|
};
|
|
597
|
+
|
|
598
|
+
const _onStart = this.onStart.bind(this);
|
|
599
|
+
this.onStart = async () => {
|
|
600
|
+
return agentContext.run(
|
|
601
|
+
{
|
|
602
|
+
agent: this,
|
|
603
|
+
connection: undefined,
|
|
604
|
+
request: undefined,
|
|
605
|
+
email: undefined
|
|
606
|
+
},
|
|
607
|
+
async () => {
|
|
608
|
+
await this._tryCatch(() => {
|
|
609
|
+
const servers = this.sql<MCPServerRow>`
|
|
610
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
611
|
+
`;
|
|
612
|
+
|
|
613
|
+
this.broadcast(
|
|
614
|
+
JSON.stringify({
|
|
615
|
+
mcp: this.getMcpServers(),
|
|
616
|
+
type: "cf_agent_mcp_servers"
|
|
617
|
+
})
|
|
618
|
+
);
|
|
619
|
+
|
|
620
|
+
// from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
|
|
621
|
+
if (servers && Array.isArray(servers) && servers.length > 0) {
|
|
622
|
+
servers.forEach((server) => {
|
|
623
|
+
this._connectToMcpServerInternal(
|
|
624
|
+
server.name,
|
|
625
|
+
server.server_url,
|
|
626
|
+
server.callback_url,
|
|
627
|
+
server.server_options
|
|
628
|
+
? JSON.parse(server.server_options)
|
|
629
|
+
: undefined,
|
|
630
|
+
{
|
|
631
|
+
id: server.id,
|
|
632
|
+
oauthClientId: server.client_id ?? undefined
|
|
633
|
+
}
|
|
634
|
+
)
|
|
635
|
+
.then(() => {
|
|
636
|
+
// Broadcast updated MCP servers state after each server connects
|
|
637
|
+
this.broadcast(
|
|
638
|
+
JSON.stringify({
|
|
639
|
+
mcp: this.getMcpServers(),
|
|
640
|
+
type: "cf_agent_mcp_servers"
|
|
641
|
+
})
|
|
642
|
+
);
|
|
643
|
+
})
|
|
644
|
+
.catch((error) => {
|
|
645
|
+
console.error(
|
|
646
|
+
`Error connecting to MCP server: ${server.name} (${server.server_url})`,
|
|
647
|
+
error
|
|
648
|
+
);
|
|
649
|
+
// Still broadcast even if connection fails, so clients know about the failure
|
|
650
|
+
this.broadcast(
|
|
651
|
+
JSON.stringify({
|
|
652
|
+
mcp: this.getMcpServers(),
|
|
653
|
+
type: "cf_agent_mcp_servers"
|
|
654
|
+
})
|
|
655
|
+
);
|
|
656
|
+
});
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
return _onStart();
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
);
|
|
663
|
+
};
|
|
391
664
|
}
|
|
392
665
|
|
|
393
|
-
|
|
394
|
-
|
|
666
|
+
private _setStateInternal(
|
|
667
|
+
state: State,
|
|
668
|
+
source: Connection | "server" = "server"
|
|
669
|
+
) {
|
|
670
|
+
this._state = state;
|
|
395
671
|
this.sql`
|
|
396
672
|
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
397
673
|
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
@@ -402,16 +678,26 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
402
678
|
`;
|
|
403
679
|
this.broadcast(
|
|
404
680
|
JSON.stringify({
|
|
405
|
-
type: "cf_agent_state",
|
|
406
681
|
state: state,
|
|
682
|
+
type: "cf_agent_state"
|
|
407
683
|
}),
|
|
408
684
|
source !== "server" ? [source.id] : []
|
|
409
685
|
);
|
|
410
|
-
return this
|
|
411
|
-
const { connection, request } =
|
|
412
|
-
return
|
|
413
|
-
{ agent: this, connection, request },
|
|
686
|
+
return this._tryCatch(() => {
|
|
687
|
+
const { connection, request, email } = agentContext.getStore() || {};
|
|
688
|
+
return agentContext.run(
|
|
689
|
+
{ agent: this, connection, request, email },
|
|
414
690
|
async () => {
|
|
691
|
+
this.observability?.emit(
|
|
692
|
+
{
|
|
693
|
+
displayMessage: "State updated",
|
|
694
|
+
id: nanoid(),
|
|
695
|
+
payload: {},
|
|
696
|
+
timestamp: Date.now(),
|
|
697
|
+
type: "state:update"
|
|
698
|
+
},
|
|
699
|
+
this.ctx
|
|
700
|
+
);
|
|
415
701
|
return this.onStateUpdate(state, source);
|
|
416
702
|
}
|
|
417
703
|
);
|
|
@@ -423,7 +709,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
423
709
|
* @param state New state to set
|
|
424
710
|
*/
|
|
425
711
|
setState(state: State) {
|
|
426
|
-
this
|
|
712
|
+
this._setStateInternal(state, "server");
|
|
427
713
|
}
|
|
428
714
|
|
|
429
715
|
/**
|
|
@@ -431,24 +717,90 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
431
717
|
* @param state Updated state
|
|
432
718
|
* @param source Source of the state update ("server" or a client connection)
|
|
433
719
|
*/
|
|
720
|
+
// biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
|
|
434
721
|
onStateUpdate(state: State | undefined, source: Connection | "server") {
|
|
435
722
|
// override this to handle state updates
|
|
436
723
|
}
|
|
437
724
|
|
|
438
725
|
/**
|
|
439
|
-
* Called when the Agent receives an email
|
|
726
|
+
* Called when the Agent receives an email via routeAgentEmail()
|
|
727
|
+
* Override this method to handle incoming emails
|
|
440
728
|
* @param email Email message to process
|
|
441
729
|
*/
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
730
|
+
async _onEmail(email: AgentEmail) {
|
|
731
|
+
// nb: we use this roundabout way of getting to onEmail
|
|
732
|
+
// because of https://github.com/cloudflare/workerd/issues/4499
|
|
733
|
+
return agentContext.run(
|
|
734
|
+
{ agent: this, connection: undefined, request: undefined, email: email },
|
|
445
735
|
async () => {
|
|
446
|
-
|
|
736
|
+
if ("onEmail" in this && typeof this.onEmail === "function") {
|
|
737
|
+
return this._tryCatch(() =>
|
|
738
|
+
(this.onEmail as (email: AgentEmail) => Promise<void>)(email)
|
|
739
|
+
);
|
|
740
|
+
} else {
|
|
741
|
+
console.log("Received email from:", email.from, "to:", email.to);
|
|
742
|
+
console.log("Subject:", email.headers.get("subject"));
|
|
743
|
+
console.log(
|
|
744
|
+
"Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
|
|
745
|
+
);
|
|
746
|
+
}
|
|
447
747
|
}
|
|
448
748
|
);
|
|
449
749
|
}
|
|
450
750
|
|
|
451
|
-
|
|
751
|
+
/**
|
|
752
|
+
* Reply to an email
|
|
753
|
+
* @param email The email to reply to
|
|
754
|
+
* @param options Options for the reply
|
|
755
|
+
* @returns void
|
|
756
|
+
*/
|
|
757
|
+
async replyToEmail(
|
|
758
|
+
email: AgentEmail,
|
|
759
|
+
options: {
|
|
760
|
+
fromName: string;
|
|
761
|
+
subject?: string | undefined;
|
|
762
|
+
body: string;
|
|
763
|
+
contentType?: string;
|
|
764
|
+
headers?: Record<string, string>;
|
|
765
|
+
}
|
|
766
|
+
): Promise<void> {
|
|
767
|
+
return this._tryCatch(async () => {
|
|
768
|
+
const agentName = camelCaseToKebabCase(this._ParentClass.name);
|
|
769
|
+
const agentId = this.name;
|
|
770
|
+
|
|
771
|
+
const { createMimeMessage } = await import("mimetext");
|
|
772
|
+
const msg = createMimeMessage();
|
|
773
|
+
msg.setSender({ addr: email.to, name: options.fromName });
|
|
774
|
+
msg.setRecipient(email.from);
|
|
775
|
+
msg.setSubject(
|
|
776
|
+
options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
|
|
777
|
+
);
|
|
778
|
+
msg.addMessage({
|
|
779
|
+
contentType: options.contentType || "text/plain",
|
|
780
|
+
data: options.body
|
|
781
|
+
});
|
|
782
|
+
|
|
783
|
+
const domain = email.from.split("@")[1];
|
|
784
|
+
const messageId = `<${agentId}@${domain}>`;
|
|
785
|
+
msg.setHeader("In-Reply-To", email.headers.get("Message-ID")!);
|
|
786
|
+
msg.setHeader("Message-ID", messageId);
|
|
787
|
+
msg.setHeader("X-Agent-Name", agentName);
|
|
788
|
+
msg.setHeader("X-Agent-ID", agentId);
|
|
789
|
+
|
|
790
|
+
if (options.headers) {
|
|
791
|
+
for (const [key, value] of Object.entries(options.headers)) {
|
|
792
|
+
msg.setHeader(key, value);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
await email.reply({
|
|
796
|
+
from: email.to,
|
|
797
|
+
raw: msg.asRaw(),
|
|
798
|
+
to: email.from
|
|
799
|
+
});
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
private async _tryCatch<T>(fn: () => T | Promise<T>) {
|
|
452
804
|
try {
|
|
453
805
|
return await fn();
|
|
454
806
|
} catch (e) {
|
|
@@ -456,6 +808,72 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
456
808
|
}
|
|
457
809
|
}
|
|
458
810
|
|
|
811
|
+
/**
|
|
812
|
+
* Automatically wrap custom methods with agent context
|
|
813
|
+
* This ensures getCurrentAgent() works in all custom methods without decorators
|
|
814
|
+
*/
|
|
815
|
+
private _autoWrapCustomMethods() {
|
|
816
|
+
// Collect all methods from base prototypes (Agent and Server)
|
|
817
|
+
const basePrototypes = [Agent.prototype, Server.prototype];
|
|
818
|
+
const baseMethods = new Set<string>();
|
|
819
|
+
for (const baseProto of basePrototypes) {
|
|
820
|
+
let proto = baseProto;
|
|
821
|
+
while (proto && proto !== Object.prototype) {
|
|
822
|
+
const methodNames = Object.getOwnPropertyNames(proto);
|
|
823
|
+
for (const methodName of methodNames) {
|
|
824
|
+
baseMethods.add(methodName);
|
|
825
|
+
}
|
|
826
|
+
proto = Object.getPrototypeOf(proto);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
// Get all methods from the current instance's prototype chain
|
|
830
|
+
let proto = Object.getPrototypeOf(this);
|
|
831
|
+
let depth = 0;
|
|
832
|
+
while (proto && proto !== Object.prototype && depth < 10) {
|
|
833
|
+
const methodNames = Object.getOwnPropertyNames(proto);
|
|
834
|
+
for (const methodName of methodNames) {
|
|
835
|
+
// Skip if it's a private method or not a function
|
|
836
|
+
if (
|
|
837
|
+
baseMethods.has(methodName) ||
|
|
838
|
+
methodName.startsWith("_") ||
|
|
839
|
+
typeof this[methodName as keyof this] !== "function"
|
|
840
|
+
) {
|
|
841
|
+
continue;
|
|
842
|
+
}
|
|
843
|
+
// If the method doesn't exist in base prototypes, it's a custom method
|
|
844
|
+
if (!baseMethods.has(methodName)) {
|
|
845
|
+
const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
|
|
846
|
+
if (descriptor && typeof descriptor.value === "function") {
|
|
847
|
+
// Wrap the custom method with context
|
|
848
|
+
|
|
849
|
+
const wrappedFunction = withAgentContext(
|
|
850
|
+
// biome-ignore lint/suspicious/noExplicitAny: I can't typescript
|
|
851
|
+
this[methodName as keyof this] as (...args: any[]) => any
|
|
852
|
+
// biome-ignore lint/suspicious/noExplicitAny: I can't typescript
|
|
853
|
+
) as any;
|
|
854
|
+
|
|
855
|
+
// if the method is callable, copy the metadata from the original method
|
|
856
|
+
if (this._isCallable(methodName)) {
|
|
857
|
+
callableMetadata.set(
|
|
858
|
+
wrappedFunction,
|
|
859
|
+
callableMetadata.get(
|
|
860
|
+
this[methodName as keyof this] as Function
|
|
861
|
+
)!
|
|
862
|
+
);
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
// set the wrapped function on the prototype
|
|
866
|
+
this.constructor.prototype[methodName as keyof this] =
|
|
867
|
+
wrappedFunction;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
proto = Object.getPrototypeOf(proto);
|
|
873
|
+
depth++;
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
|
|
459
877
|
override onError(
|
|
460
878
|
connection: Connection,
|
|
461
879
|
error: unknown
|
|
@@ -490,6 +908,131 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
490
908
|
throw new Error("Not implemented");
|
|
491
909
|
}
|
|
492
910
|
|
|
911
|
+
/**
|
|
912
|
+
* Queue a task to be executed in the future
|
|
913
|
+
* @param payload Payload to pass to the callback
|
|
914
|
+
* @param callback Name of the method to call
|
|
915
|
+
* @returns The ID of the queued task
|
|
916
|
+
*/
|
|
917
|
+
async queue<T = unknown>(callback: keyof this, payload: T): Promise<string> {
|
|
918
|
+
const id = nanoid(9);
|
|
919
|
+
if (typeof callback !== "string") {
|
|
920
|
+
throw new Error("Callback must be a string");
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
if (typeof this[callback] !== "function") {
|
|
924
|
+
throw new Error(`this.${callback} is not a function`);
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
this.sql`
|
|
928
|
+
INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
|
|
929
|
+
VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
|
|
930
|
+
`;
|
|
931
|
+
|
|
932
|
+
void this._flushQueue().catch((e) => {
|
|
933
|
+
console.error("Error flushing queue:", e);
|
|
934
|
+
});
|
|
935
|
+
|
|
936
|
+
return id;
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
private _flushingQueue = false;
|
|
940
|
+
|
|
941
|
+
private async _flushQueue() {
|
|
942
|
+
if (this._flushingQueue) {
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
this._flushingQueue = true;
|
|
946
|
+
while (true) {
|
|
947
|
+
const result = this.sql<QueueItem<string>>`
|
|
948
|
+
SELECT * FROM cf_agents_queues
|
|
949
|
+
ORDER BY created_at ASC
|
|
950
|
+
`;
|
|
951
|
+
|
|
952
|
+
if (!result || result.length === 0) {
|
|
953
|
+
break;
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
for (const row of result || []) {
|
|
957
|
+
const callback = this[row.callback as keyof Agent<Env>];
|
|
958
|
+
if (!callback) {
|
|
959
|
+
console.error(`callback ${row.callback} not found`);
|
|
960
|
+
continue;
|
|
961
|
+
}
|
|
962
|
+
const { connection, request, email } = agentContext.getStore() || {};
|
|
963
|
+
await agentContext.run(
|
|
964
|
+
{
|
|
965
|
+
agent: this,
|
|
966
|
+
connection,
|
|
967
|
+
request,
|
|
968
|
+
email
|
|
969
|
+
},
|
|
970
|
+
async () => {
|
|
971
|
+
// TODO: add retries and backoff
|
|
972
|
+
await (
|
|
973
|
+
callback as (
|
|
974
|
+
payload: unknown,
|
|
975
|
+
queueItem: QueueItem<string>
|
|
976
|
+
) => Promise<void>
|
|
977
|
+
).bind(this)(JSON.parse(row.payload as string), row);
|
|
978
|
+
await this.dequeue(row.id);
|
|
979
|
+
}
|
|
980
|
+
);
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
this._flushingQueue = false;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
/**
|
|
987
|
+
* Dequeue a task by ID
|
|
988
|
+
* @param id ID of the task to dequeue
|
|
989
|
+
*/
|
|
990
|
+
async dequeue(id: string) {
|
|
991
|
+
this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
/**
|
|
995
|
+
* Dequeue all tasks
|
|
996
|
+
*/
|
|
997
|
+
async dequeueAll() {
|
|
998
|
+
this.sql`DELETE FROM cf_agents_queues`;
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
/**
|
|
1002
|
+
* Dequeue all tasks by callback
|
|
1003
|
+
* @param callback Name of the callback to dequeue
|
|
1004
|
+
*/
|
|
1005
|
+
async dequeueAllByCallback(callback: string) {
|
|
1006
|
+
this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/**
|
|
1010
|
+
* Get a queued task by ID
|
|
1011
|
+
* @param id ID of the task to get
|
|
1012
|
+
* @returns The task or undefined if not found
|
|
1013
|
+
*/
|
|
1014
|
+
async getQueue(id: string): Promise<QueueItem<string> | undefined> {
|
|
1015
|
+
const result = this.sql<QueueItem<string>>`
|
|
1016
|
+
SELECT * FROM cf_agents_queues WHERE id = ${id}
|
|
1017
|
+
`;
|
|
1018
|
+
return result
|
|
1019
|
+
? { ...result[0], payload: JSON.parse(result[0].payload) }
|
|
1020
|
+
: undefined;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
/**
|
|
1024
|
+
* Get all queues by key and value
|
|
1025
|
+
* @param key Key to filter by
|
|
1026
|
+
* @param value Value to filter by
|
|
1027
|
+
* @returns Array of matching QueueItem objects
|
|
1028
|
+
*/
|
|
1029
|
+
async getQueues(key: string, value: string): Promise<QueueItem<string>[]> {
|
|
1030
|
+
const result = this.sql<QueueItem<string>>`
|
|
1031
|
+
SELECT * FROM cf_agents_queues
|
|
1032
|
+
`;
|
|
1033
|
+
return result.filter((row) => JSON.parse(row.payload)[key] === value);
|
|
1034
|
+
}
|
|
1035
|
+
|
|
493
1036
|
/**
|
|
494
1037
|
* Schedule a task to be executed in the future
|
|
495
1038
|
* @template T Type of the payload data
|
|
@@ -505,6 +1048,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
505
1048
|
): Promise<Schedule<T>> {
|
|
506
1049
|
const id = nanoid(9);
|
|
507
1050
|
|
|
1051
|
+
const emitScheduleCreate = (schedule: Schedule<T>) =>
|
|
1052
|
+
this.observability?.emit(
|
|
1053
|
+
{
|
|
1054
|
+
displayMessage: `Schedule ${schedule.id} created`,
|
|
1055
|
+
id: nanoid(),
|
|
1056
|
+
payload: {
|
|
1057
|
+
callback: callback as string,
|
|
1058
|
+
id: id
|
|
1059
|
+
},
|
|
1060
|
+
timestamp: Date.now(),
|
|
1061
|
+
type: "schedule:create"
|
|
1062
|
+
},
|
|
1063
|
+
this.ctx
|
|
1064
|
+
);
|
|
1065
|
+
|
|
508
1066
|
if (typeof callback !== "string") {
|
|
509
1067
|
throw new Error("Callback must be a string");
|
|
510
1068
|
}
|
|
@@ -522,15 +1080,19 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
522
1080
|
)}, 'scheduled', ${timestamp})
|
|
523
1081
|
`;
|
|
524
1082
|
|
|
525
|
-
await this
|
|
1083
|
+
await this._scheduleNextAlarm();
|
|
526
1084
|
|
|
527
|
-
|
|
528
|
-
id,
|
|
1085
|
+
const schedule: Schedule<T> = {
|
|
529
1086
|
callback: callback,
|
|
1087
|
+
id,
|
|
530
1088
|
payload: payload as T,
|
|
531
1089
|
time: timestamp,
|
|
532
|
-
type: "scheduled"
|
|
1090
|
+
type: "scheduled"
|
|
533
1091
|
};
|
|
1092
|
+
|
|
1093
|
+
emitScheduleCreate(schedule);
|
|
1094
|
+
|
|
1095
|
+
return schedule;
|
|
534
1096
|
}
|
|
535
1097
|
if (typeof when === "number") {
|
|
536
1098
|
const time = new Date(Date.now() + when * 1000);
|
|
@@ -543,16 +1105,20 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
543
1105
|
)}, 'delayed', ${when}, ${timestamp})
|
|
544
1106
|
`;
|
|
545
1107
|
|
|
546
|
-
await this
|
|
1108
|
+
await this._scheduleNextAlarm();
|
|
547
1109
|
|
|
548
|
-
|
|
549
|
-
id,
|
|
1110
|
+
const schedule: Schedule<T> = {
|
|
550
1111
|
callback: callback,
|
|
551
|
-
payload: payload as T,
|
|
552
1112
|
delayInSeconds: when,
|
|
1113
|
+
id,
|
|
1114
|
+
payload: payload as T,
|
|
553
1115
|
time: timestamp,
|
|
554
|
-
type: "delayed"
|
|
1116
|
+
type: "delayed"
|
|
555
1117
|
};
|
|
1118
|
+
|
|
1119
|
+
emitScheduleCreate(schedule);
|
|
1120
|
+
|
|
1121
|
+
return schedule;
|
|
556
1122
|
}
|
|
557
1123
|
if (typeof when === "string") {
|
|
558
1124
|
const nextExecutionTime = getNextCronTime(when);
|
|
@@ -565,16 +1131,20 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
565
1131
|
)}, 'cron', ${when}, ${timestamp})
|
|
566
1132
|
`;
|
|
567
1133
|
|
|
568
|
-
await this
|
|
1134
|
+
await this._scheduleNextAlarm();
|
|
569
1135
|
|
|
570
|
-
|
|
571
|
-
id,
|
|
1136
|
+
const schedule: Schedule<T> = {
|
|
572
1137
|
callback: callback,
|
|
573
|
-
payload: payload as T,
|
|
574
1138
|
cron: when,
|
|
1139
|
+
id,
|
|
1140
|
+
payload: payload as T,
|
|
575
1141
|
time: timestamp,
|
|
576
|
-
type: "cron"
|
|
1142
|
+
type: "cron"
|
|
577
1143
|
};
|
|
1144
|
+
|
|
1145
|
+
emitScheduleCreate(schedule);
|
|
1146
|
+
|
|
1147
|
+
return schedule;
|
|
578
1148
|
}
|
|
579
1149
|
throw new Error("Invalid schedule type");
|
|
580
1150
|
}
|
|
@@ -638,7 +1208,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
638
1208
|
.toArray()
|
|
639
1209
|
.map((row) => ({
|
|
640
1210
|
...row,
|
|
641
|
-
payload: JSON.parse(row.payload as string) as T
|
|
1211
|
+
payload: JSON.parse(row.payload as string) as T
|
|
642
1212
|
})) as Schedule<T>[];
|
|
643
1213
|
|
|
644
1214
|
return result;
|
|
@@ -650,18 +1220,34 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
650
1220
|
* @returns true if the task was cancelled, false otherwise
|
|
651
1221
|
*/
|
|
652
1222
|
async cancelSchedule(id: string): Promise<boolean> {
|
|
1223
|
+
const schedule = await this.getSchedule(id);
|
|
1224
|
+
if (schedule) {
|
|
1225
|
+
this.observability?.emit(
|
|
1226
|
+
{
|
|
1227
|
+
displayMessage: `Schedule ${id} cancelled`,
|
|
1228
|
+
id: nanoid(),
|
|
1229
|
+
payload: {
|
|
1230
|
+
callback: schedule.callback,
|
|
1231
|
+
id: schedule.id
|
|
1232
|
+
},
|
|
1233
|
+
timestamp: Date.now(),
|
|
1234
|
+
type: "schedule:cancel"
|
|
1235
|
+
},
|
|
1236
|
+
this.ctx
|
|
1237
|
+
);
|
|
1238
|
+
}
|
|
653
1239
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
654
1240
|
|
|
655
|
-
await this
|
|
1241
|
+
await this._scheduleNextAlarm();
|
|
656
1242
|
return true;
|
|
657
1243
|
}
|
|
658
1244
|
|
|
659
|
-
async
|
|
1245
|
+
private async _scheduleNextAlarm() {
|
|
660
1246
|
// Find the next schedule that needs to be executed
|
|
661
1247
|
const result = this.sql`
|
|
662
|
-
SELECT time FROM cf_agents_schedules
|
|
1248
|
+
SELECT time FROM cf_agents_schedules
|
|
663
1249
|
WHERE time > ${Math.floor(Date.now() / 1000)}
|
|
664
|
-
ORDER BY time ASC
|
|
1250
|
+
ORDER BY time ASC
|
|
665
1251
|
LIMIT 1
|
|
666
1252
|
`;
|
|
667
1253
|
if (!result) return;
|
|
@@ -673,10 +1259,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
673
1259
|
}
|
|
674
1260
|
|
|
675
1261
|
/**
|
|
676
|
-
* Method called when an alarm fires
|
|
677
|
-
* Executes any scheduled tasks that are due
|
|
1262
|
+
* Method called when an alarm fires.
|
|
1263
|
+
* Executes any scheduled tasks that are due.
|
|
1264
|
+
*
|
|
1265
|
+
* @remarks
|
|
1266
|
+
* To schedule a task, please use the `this.schedule` method instead.
|
|
1267
|
+
* See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
|
|
678
1268
|
*/
|
|
679
|
-
async
|
|
1269
|
+
public readonly alarm = async () => {
|
|
680
1270
|
const now = Math.floor(Date.now() / 1000);
|
|
681
1271
|
|
|
682
1272
|
// Get all schedules that should be executed now
|
|
@@ -684,46 +1274,67 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
684
1274
|
SELECT * FROM cf_agents_schedules WHERE time <= ${now}
|
|
685
1275
|
`;
|
|
686
1276
|
|
|
687
|
-
|
|
688
|
-
const
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
await unstable_context.run(
|
|
694
|
-
{ agent: this, connection: undefined, request: undefined },
|
|
695
|
-
async () => {
|
|
696
|
-
try {
|
|
697
|
-
await (
|
|
698
|
-
callback as (
|
|
699
|
-
payload: unknown,
|
|
700
|
-
schedule: Schedule<unknown>
|
|
701
|
-
) => Promise<void>
|
|
702
|
-
).bind(this)(JSON.parse(row.payload as string), row);
|
|
703
|
-
} catch (e) {
|
|
704
|
-
console.error(`error executing callback "${row.callback}"`, e);
|
|
705
|
-
}
|
|
1277
|
+
if (result && Array.isArray(result)) {
|
|
1278
|
+
for (const row of result) {
|
|
1279
|
+
const callback = this[row.callback as keyof Agent<Env>];
|
|
1280
|
+
if (!callback) {
|
|
1281
|
+
console.error(`callback ${row.callback} not found`);
|
|
1282
|
+
continue;
|
|
706
1283
|
}
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
1284
|
+
await agentContext.run(
|
|
1285
|
+
{
|
|
1286
|
+
agent: this,
|
|
1287
|
+
connection: undefined,
|
|
1288
|
+
request: undefined,
|
|
1289
|
+
email: undefined
|
|
1290
|
+
},
|
|
1291
|
+
async () => {
|
|
1292
|
+
try {
|
|
1293
|
+
this.observability?.emit(
|
|
1294
|
+
{
|
|
1295
|
+
displayMessage: `Schedule ${row.id} executed`,
|
|
1296
|
+
id: nanoid(),
|
|
1297
|
+
payload: {
|
|
1298
|
+
callback: row.callback,
|
|
1299
|
+
id: row.id
|
|
1300
|
+
},
|
|
1301
|
+
timestamp: Date.now(),
|
|
1302
|
+
type: "schedule:execute"
|
|
1303
|
+
},
|
|
1304
|
+
this.ctx
|
|
1305
|
+
);
|
|
712
1306
|
|
|
713
|
-
|
|
1307
|
+
await (
|
|
1308
|
+
callback as (
|
|
1309
|
+
payload: unknown,
|
|
1310
|
+
schedule: Schedule<unknown>
|
|
1311
|
+
) => Promise<void>
|
|
1312
|
+
).bind(this)(JSON.parse(row.payload as string), row);
|
|
1313
|
+
} catch (e) {
|
|
1314
|
+
console.error(`error executing callback "${row.callback}"`, e);
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
);
|
|
1318
|
+
if (row.type === "cron") {
|
|
1319
|
+
// Update next execution time for cron schedules
|
|
1320
|
+
const nextExecutionTime = getNextCronTime(row.cron);
|
|
1321
|
+
const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
|
|
1322
|
+
|
|
1323
|
+
this.sql`
|
|
714
1324
|
UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
|
|
715
1325
|
`;
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
1326
|
+
} else {
|
|
1327
|
+
// Delete one-time schedules after execution
|
|
1328
|
+
this.sql`
|
|
719
1329
|
DELETE FROM cf_agents_schedules WHERE id = ${row.id}
|
|
720
1330
|
`;
|
|
1331
|
+
}
|
|
721
1332
|
}
|
|
722
1333
|
}
|
|
723
1334
|
|
|
724
1335
|
// Schedule the next alarm
|
|
725
|
-
await this
|
|
726
|
-
}
|
|
1336
|
+
await this._scheduleNextAlarm();
|
|
1337
|
+
};
|
|
727
1338
|
|
|
728
1339
|
/**
|
|
729
1340
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
@@ -732,20 +1343,203 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
732
1343
|
// drop all tables
|
|
733
1344
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
734
1345
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
1346
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
1347
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
|
|
735
1348
|
|
|
736
1349
|
// delete all alarms
|
|
737
1350
|
await this.ctx.storage.deleteAlarm();
|
|
738
1351
|
await this.ctx.storage.deleteAll();
|
|
1352
|
+
this.ctx.abort("destroyed"); // enforce that the agent is evicted
|
|
1353
|
+
|
|
1354
|
+
this.observability?.emit(
|
|
1355
|
+
{
|
|
1356
|
+
displayMessage: "Agent destroyed",
|
|
1357
|
+
id: nanoid(),
|
|
1358
|
+
payload: {},
|
|
1359
|
+
timestamp: Date.now(),
|
|
1360
|
+
type: "destroy"
|
|
1361
|
+
},
|
|
1362
|
+
this.ctx
|
|
1363
|
+
);
|
|
739
1364
|
}
|
|
740
1365
|
|
|
741
1366
|
/**
|
|
742
1367
|
* Get all methods marked as callable on this Agent
|
|
743
1368
|
* @returns A map of method names to their metadata
|
|
744
1369
|
*/
|
|
745
|
-
|
|
746
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
1370
|
+
private _isCallable(method: string): boolean {
|
|
747
1371
|
return callableMetadata.has(this[method as keyof this] as Function);
|
|
748
1372
|
}
|
|
1373
|
+
|
|
1374
|
+
/**
|
|
1375
|
+
* Connect to a new MCP Server
|
|
1376
|
+
*
|
|
1377
|
+
* @param url MCP Server SSE URL
|
|
1378
|
+
* @param callbackHost Base host for the agent, used for the redirect URI.
|
|
1379
|
+
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
1380
|
+
* @param options MCP client and transport (header) options
|
|
1381
|
+
* @returns authUrl
|
|
1382
|
+
*/
|
|
1383
|
+
async addMcpServer(
|
|
1384
|
+
serverName: string,
|
|
1385
|
+
url: string,
|
|
1386
|
+
callbackHost: string,
|
|
1387
|
+
agentsPrefix = "agents",
|
|
1388
|
+
options?: {
|
|
1389
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
1390
|
+
transport?: {
|
|
1391
|
+
headers: HeadersInit;
|
|
1392
|
+
};
|
|
1393
|
+
}
|
|
1394
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
1395
|
+
const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
1396
|
+
|
|
1397
|
+
const result = await this._connectToMcpServerInternal(
|
|
1398
|
+
serverName,
|
|
1399
|
+
url,
|
|
1400
|
+
callbackUrl,
|
|
1401
|
+
options
|
|
1402
|
+
);
|
|
1403
|
+
this.sql`
|
|
1404
|
+
INSERT
|
|
1405
|
+
OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
1406
|
+
VALUES (
|
|
1407
|
+
${result.id},
|
|
1408
|
+
${serverName},
|
|
1409
|
+
${url},
|
|
1410
|
+
${result.clientId ?? null},
|
|
1411
|
+
${result.authUrl ?? null},
|
|
1412
|
+
${callbackUrl},
|
|
1413
|
+
${options ? JSON.stringify(options) : null}
|
|
1414
|
+
);
|
|
1415
|
+
`;
|
|
1416
|
+
|
|
1417
|
+
this.broadcast(
|
|
1418
|
+
JSON.stringify({
|
|
1419
|
+
mcp: this.getMcpServers(),
|
|
1420
|
+
type: "cf_agent_mcp_servers"
|
|
1421
|
+
})
|
|
1422
|
+
);
|
|
1423
|
+
|
|
1424
|
+
return result;
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
async _connectToMcpServerInternal(
|
|
1428
|
+
_serverName: string,
|
|
1429
|
+
url: string,
|
|
1430
|
+
callbackUrl: string,
|
|
1431
|
+
// it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
|
|
1432
|
+
options?: {
|
|
1433
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
1434
|
+
/**
|
|
1435
|
+
* We don't expose the normal set of transport options because:
|
|
1436
|
+
* 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
|
|
1437
|
+
* 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
|
|
1438
|
+
*
|
|
1439
|
+
* 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).
|
|
1440
|
+
*/
|
|
1441
|
+
transport?: {
|
|
1442
|
+
headers?: HeadersInit;
|
|
1443
|
+
};
|
|
1444
|
+
},
|
|
1445
|
+
reconnect?: {
|
|
1446
|
+
id: string;
|
|
1447
|
+
oauthClientId?: string;
|
|
1448
|
+
}
|
|
1449
|
+
): Promise<{
|
|
1450
|
+
id: string;
|
|
1451
|
+
authUrl: string | undefined;
|
|
1452
|
+
clientId: string | undefined;
|
|
1453
|
+
}> {
|
|
1454
|
+
const authProvider = new DurableObjectOAuthClientProvider(
|
|
1455
|
+
this.ctx.storage,
|
|
1456
|
+
this.name,
|
|
1457
|
+
callbackUrl
|
|
1458
|
+
);
|
|
1459
|
+
|
|
1460
|
+
if (reconnect) {
|
|
1461
|
+
authProvider.serverId = reconnect.id;
|
|
1462
|
+
if (reconnect.oauthClientId) {
|
|
1463
|
+
authProvider.clientId = reconnect.oauthClientId;
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
// allows passing through transport headers if necessary
|
|
1468
|
+
// this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
|
|
1469
|
+
let headerTransportOpts: SSEClientTransportOptions = {};
|
|
1470
|
+
if (options?.transport?.headers) {
|
|
1471
|
+
headerTransportOpts = {
|
|
1472
|
+
eventSourceInit: {
|
|
1473
|
+
fetch: (url, init) =>
|
|
1474
|
+
fetch(url, {
|
|
1475
|
+
...init,
|
|
1476
|
+
headers: options?.transport?.headers
|
|
1477
|
+
})
|
|
1478
|
+
},
|
|
1479
|
+
requestInit: {
|
|
1480
|
+
headers: options?.transport?.headers
|
|
1481
|
+
}
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
const { id, authUrl, clientId } = await this.mcp.connect(url, {
|
|
1486
|
+
client: options?.client,
|
|
1487
|
+
reconnect,
|
|
1488
|
+
transport: {
|
|
1489
|
+
...headerTransportOpts,
|
|
1490
|
+
authProvider
|
|
1491
|
+
}
|
|
1492
|
+
});
|
|
1493
|
+
|
|
1494
|
+
return {
|
|
1495
|
+
authUrl,
|
|
1496
|
+
clientId,
|
|
1497
|
+
id
|
|
1498
|
+
};
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
async removeMcpServer(id: string) {
|
|
1502
|
+
this.mcp.closeConnection(id);
|
|
1503
|
+
this.sql`
|
|
1504
|
+
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
1505
|
+
`;
|
|
1506
|
+
this.broadcast(
|
|
1507
|
+
JSON.stringify({
|
|
1508
|
+
mcp: this.getMcpServers(),
|
|
1509
|
+
type: "cf_agent_mcp_servers"
|
|
1510
|
+
})
|
|
1511
|
+
);
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
getMcpServers(): MCPServersState {
|
|
1515
|
+
const mcpState: MCPServersState = {
|
|
1516
|
+
prompts: this.mcp.listPrompts(),
|
|
1517
|
+
resources: this.mcp.listResources(),
|
|
1518
|
+
servers: {},
|
|
1519
|
+
tools: this.mcp.listTools()
|
|
1520
|
+
};
|
|
1521
|
+
|
|
1522
|
+
const servers = this.sql<MCPServerRow>`
|
|
1523
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
1524
|
+
`;
|
|
1525
|
+
|
|
1526
|
+
if (servers && Array.isArray(servers) && servers.length > 0) {
|
|
1527
|
+
for (const server of servers) {
|
|
1528
|
+
const serverConn = this.mcp.mcpConnections[server.id];
|
|
1529
|
+
mcpState.servers[server.id] = {
|
|
1530
|
+
auth_url: server.auth_url,
|
|
1531
|
+
capabilities: serverConn?.serverCapabilities ?? null,
|
|
1532
|
+
instructions: serverConn?.instructions ?? null,
|
|
1533
|
+
name: server.name,
|
|
1534
|
+
server_url: server.server_url,
|
|
1535
|
+
// mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
|
|
1536
|
+
state: serverConn?.connectionState ?? "authenticating"
|
|
1537
|
+
};
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
return mcpState;
|
|
1542
|
+
}
|
|
749
1543
|
}
|
|
750
1544
|
|
|
751
1545
|
/**
|
|
@@ -785,17 +1579,17 @@ export async function routeAgentRequest<Env>(
|
|
|
785
1579
|
const corsHeaders =
|
|
786
1580
|
options?.cors === true
|
|
787
1581
|
? {
|
|
788
|
-
"Access-Control-Allow-Origin": "*",
|
|
789
|
-
"Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
|
|
790
1582
|
"Access-Control-Allow-Credentials": "true",
|
|
791
|
-
"Access-Control-
|
|
1583
|
+
"Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
|
|
1584
|
+
"Access-Control-Allow-Origin": "*",
|
|
1585
|
+
"Access-Control-Max-Age": "86400"
|
|
792
1586
|
}
|
|
793
1587
|
: options?.cors;
|
|
794
1588
|
|
|
795
1589
|
if (request.method === "OPTIONS") {
|
|
796
1590
|
if (corsHeaders) {
|
|
797
1591
|
return new Response(null, {
|
|
798
|
-
headers: corsHeaders
|
|
1592
|
+
headers: corsHeaders
|
|
799
1593
|
});
|
|
800
1594
|
}
|
|
801
1595
|
console.warn(
|
|
@@ -808,7 +1602,7 @@ export async function routeAgentRequest<Env>(
|
|
|
808
1602
|
env as Record<string, unknown>,
|
|
809
1603
|
{
|
|
810
1604
|
prefix: "agents",
|
|
811
|
-
...(options as PartyServerOptions<Record<string, unknown>>)
|
|
1605
|
+
...(options as PartyServerOptions<Record<string, unknown>>)
|
|
812
1606
|
}
|
|
813
1607
|
);
|
|
814
1608
|
|
|
@@ -821,24 +1615,238 @@ export async function routeAgentRequest<Env>(
|
|
|
821
1615
|
response = new Response(response.body, {
|
|
822
1616
|
headers: {
|
|
823
1617
|
...response.headers,
|
|
824
|
-
...corsHeaders
|
|
825
|
-
}
|
|
1618
|
+
...corsHeaders
|
|
1619
|
+
}
|
|
826
1620
|
});
|
|
827
1621
|
}
|
|
828
1622
|
return response;
|
|
829
1623
|
}
|
|
830
1624
|
|
|
1625
|
+
export type EmailResolver<Env> = (
|
|
1626
|
+
email: ForwardableEmailMessage,
|
|
1627
|
+
env: Env
|
|
1628
|
+
) => Promise<{
|
|
1629
|
+
agentName: string;
|
|
1630
|
+
agentId: string;
|
|
1631
|
+
} | null>;
|
|
1632
|
+
|
|
1633
|
+
/**
|
|
1634
|
+
* Create a resolver that uses the message-id header to determine the agent to route the email to
|
|
1635
|
+
* @returns A function that resolves the agent to route the email to
|
|
1636
|
+
*/
|
|
1637
|
+
export function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env> {
|
|
1638
|
+
return async (email: ForwardableEmailMessage, _env: Env) => {
|
|
1639
|
+
const messageId = email.headers.get("message-id");
|
|
1640
|
+
if (messageId) {
|
|
1641
|
+
const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
|
|
1642
|
+
if (messageIdMatch) {
|
|
1643
|
+
const [, agentId, domain] = messageIdMatch;
|
|
1644
|
+
const agentName = domain.split(".")[0];
|
|
1645
|
+
return { agentName, agentId };
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
const references = email.headers.get("references");
|
|
1650
|
+
if (references) {
|
|
1651
|
+
const referencesMatch = references.match(
|
|
1652
|
+
/<([A-Za-z0-9+/]{43}=)@([^>]+)>/
|
|
1653
|
+
);
|
|
1654
|
+
if (referencesMatch) {
|
|
1655
|
+
const [, base64Id, domain] = referencesMatch;
|
|
1656
|
+
const agentId = Buffer.from(base64Id, "base64").toString("hex");
|
|
1657
|
+
const agentName = domain.split(".")[0];
|
|
1658
|
+
return { agentName, agentId };
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
|
|
1662
|
+
const agentName = email.headers.get("x-agent-name");
|
|
1663
|
+
const agentId = email.headers.get("x-agent-id");
|
|
1664
|
+
if (agentName && agentId) {
|
|
1665
|
+
return { agentName, agentId };
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
return null;
|
|
1669
|
+
};
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
/**
|
|
1673
|
+
* Create a resolver that uses the email address to determine the agent to route the email to
|
|
1674
|
+
* @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
|
|
1675
|
+
* @returns A function that resolves the agent to route the email to
|
|
1676
|
+
*/
|
|
1677
|
+
export function createAddressBasedEmailResolver<Env>(
|
|
1678
|
+
defaultAgentName: string
|
|
1679
|
+
): EmailResolver<Env> {
|
|
1680
|
+
return async (email: ForwardableEmailMessage, _env: Env) => {
|
|
1681
|
+
const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
|
|
1682
|
+
if (!emailMatch) {
|
|
1683
|
+
return null;
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
const [, localPart, subAddress] = emailMatch;
|
|
1687
|
+
|
|
1688
|
+
if (subAddress) {
|
|
1689
|
+
return {
|
|
1690
|
+
agentName: localPart,
|
|
1691
|
+
agentId: subAddress
|
|
1692
|
+
};
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
// Option 2: Use defaultAgentName namespace, localPart as agentId
|
|
1696
|
+
// Common for catch-all email routing to a single EmailAgent namespace
|
|
1697
|
+
return {
|
|
1698
|
+
agentName: defaultAgentName,
|
|
1699
|
+
agentId: localPart
|
|
1700
|
+
};
|
|
1701
|
+
};
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
/**
|
|
1705
|
+
* Create a resolver that uses the agentName and agentId to determine the agent to route the email to
|
|
1706
|
+
* @param agentName The name of the agent to route the email to
|
|
1707
|
+
* @param agentId The id of the agent to route the email to
|
|
1708
|
+
* @returns A function that resolves the agent to route the email to
|
|
1709
|
+
*/
|
|
1710
|
+
export function createCatchAllEmailResolver<Env>(
|
|
1711
|
+
agentName: string,
|
|
1712
|
+
agentId: string
|
|
1713
|
+
): EmailResolver<Env> {
|
|
1714
|
+
return async () => ({ agentName, agentId });
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1717
|
+
export type EmailRoutingOptions<Env> = AgentOptions<Env> & {
|
|
1718
|
+
resolver: EmailResolver<Env>;
|
|
1719
|
+
};
|
|
1720
|
+
|
|
1721
|
+
// Cache the agent namespace map for email routing
|
|
1722
|
+
// This maps both kebab-case and original names to namespaces
|
|
1723
|
+
const agentMapCache = new WeakMap<
|
|
1724
|
+
Record<string, unknown>,
|
|
1725
|
+
Record<string, unknown>
|
|
1726
|
+
>();
|
|
1727
|
+
|
|
831
1728
|
/**
|
|
832
1729
|
* Route an email to the appropriate Agent
|
|
833
|
-
* @param email
|
|
834
|
-
* @param env
|
|
835
|
-
* @param options
|
|
1730
|
+
* @param email The email to route
|
|
1731
|
+
* @param env The environment containing the Agent bindings
|
|
1732
|
+
* @param options The options for routing the email
|
|
1733
|
+
* @returns A promise that resolves when the email has been routed
|
|
836
1734
|
*/
|
|
837
1735
|
export async function routeAgentEmail<Env>(
|
|
838
1736
|
email: ForwardableEmailMessage,
|
|
839
1737
|
env: Env,
|
|
840
|
-
options
|
|
841
|
-
): Promise<void> {
|
|
1738
|
+
options: EmailRoutingOptions<Env>
|
|
1739
|
+
): Promise<void> {
|
|
1740
|
+
const routingInfo = await options.resolver(email, env);
|
|
1741
|
+
|
|
1742
|
+
if (!routingInfo) {
|
|
1743
|
+
console.warn("No routing information found for email, dropping message");
|
|
1744
|
+
return;
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
// Build a map that includes both original names and kebab-case versions
|
|
1748
|
+
if (!agentMapCache.has(env as Record<string, unknown>)) {
|
|
1749
|
+
const map: Record<string, unknown> = {};
|
|
1750
|
+
for (const [key, value] of Object.entries(env as Record<string, unknown>)) {
|
|
1751
|
+
if (
|
|
1752
|
+
value &&
|
|
1753
|
+
typeof value === "object" &&
|
|
1754
|
+
"idFromName" in value &&
|
|
1755
|
+
typeof value.idFromName === "function"
|
|
1756
|
+
) {
|
|
1757
|
+
// Add both the original name and kebab-case version
|
|
1758
|
+
map[key] = value;
|
|
1759
|
+
map[camelCaseToKebabCase(key)] = value;
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
agentMapCache.set(env as Record<string, unknown>, map);
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
const agentMap = agentMapCache.get(env as Record<string, unknown>)!;
|
|
1766
|
+
const namespace = agentMap[routingInfo.agentName];
|
|
1767
|
+
|
|
1768
|
+
if (!namespace) {
|
|
1769
|
+
// Provide helpful error message listing available agents
|
|
1770
|
+
const availableAgents = Object.keys(agentMap)
|
|
1771
|
+
.filter((key) => !key.includes("-")) // Show only original names, not kebab-case duplicates
|
|
1772
|
+
.join(", ");
|
|
1773
|
+
throw new Error(
|
|
1774
|
+
`Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`
|
|
1775
|
+
);
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
const agent = await getAgentByName(
|
|
1779
|
+
namespace as unknown as AgentNamespace<Agent<Env>>,
|
|
1780
|
+
routingInfo.agentId
|
|
1781
|
+
);
|
|
1782
|
+
|
|
1783
|
+
// let's make a serialisable version of the email
|
|
1784
|
+
const serialisableEmail: AgentEmail = {
|
|
1785
|
+
getRaw: async () => {
|
|
1786
|
+
const reader = email.raw.getReader();
|
|
1787
|
+
const chunks: Uint8Array[] = [];
|
|
1788
|
+
|
|
1789
|
+
let done = false;
|
|
1790
|
+
while (!done) {
|
|
1791
|
+
const { value, done: readerDone } = await reader.read();
|
|
1792
|
+
done = readerDone;
|
|
1793
|
+
if (value) {
|
|
1794
|
+
chunks.push(value);
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
|
|
1799
|
+
const combined = new Uint8Array(totalLength);
|
|
1800
|
+
let offset = 0;
|
|
1801
|
+
for (const chunk of chunks) {
|
|
1802
|
+
combined.set(chunk, offset);
|
|
1803
|
+
offset += chunk.length;
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
return combined;
|
|
1807
|
+
},
|
|
1808
|
+
headers: email.headers,
|
|
1809
|
+
rawSize: email.rawSize,
|
|
1810
|
+
setReject: (reason: string) => {
|
|
1811
|
+
email.setReject(reason);
|
|
1812
|
+
},
|
|
1813
|
+
forward: (rcptTo: string, headers?: Headers) => {
|
|
1814
|
+
return email.forward(rcptTo, headers);
|
|
1815
|
+
},
|
|
1816
|
+
reply: (options: { from: string; to: string; raw: string }) => {
|
|
1817
|
+
return email.reply(
|
|
1818
|
+
new EmailMessage(options.from, options.to, options.raw)
|
|
1819
|
+
);
|
|
1820
|
+
},
|
|
1821
|
+
from: email.from,
|
|
1822
|
+
to: email.to
|
|
1823
|
+
};
|
|
1824
|
+
|
|
1825
|
+
await agent._onEmail(serialisableEmail);
|
|
1826
|
+
}
|
|
1827
|
+
|
|
1828
|
+
export type AgentEmail = {
|
|
1829
|
+
from: string;
|
|
1830
|
+
to: string;
|
|
1831
|
+
getRaw: () => Promise<Uint8Array>;
|
|
1832
|
+
headers: Headers;
|
|
1833
|
+
rawSize: number;
|
|
1834
|
+
setReject: (reason: string) => void;
|
|
1835
|
+
forward: (rcptTo: string, headers?: Headers) => Promise<void>;
|
|
1836
|
+
reply: (options: { from: string; to: string; raw: string }) => Promise<void>;
|
|
1837
|
+
};
|
|
1838
|
+
|
|
1839
|
+
export type EmailSendOptions = {
|
|
1840
|
+
to: string;
|
|
1841
|
+
subject: string;
|
|
1842
|
+
body: string;
|
|
1843
|
+
contentType?: string;
|
|
1844
|
+
headers?: Record<string, string>;
|
|
1845
|
+
includeRoutingHeaders?: boolean;
|
|
1846
|
+
agentName?: string;
|
|
1847
|
+
agentId?: string;
|
|
1848
|
+
domain?: string;
|
|
1849
|
+
};
|
|
842
1850
|
|
|
843
1851
|
/**
|
|
844
1852
|
* Get or create an Agent by name
|
|
@@ -849,7 +1857,7 @@ export async function routeAgentEmail<Env>(
|
|
|
849
1857
|
* @param options Options for Agent creation
|
|
850
1858
|
* @returns Promise resolving to an Agent instance stub
|
|
851
1859
|
*/
|
|
852
|
-
export function getAgentByName<Env, T extends Agent<Env>>(
|
|
1860
|
+
export async function getAgentByName<Env, T extends Agent<Env>>(
|
|
853
1861
|
namespace: AgentNamespace<T>,
|
|
854
1862
|
name: string,
|
|
855
1863
|
options?: {
|
|
@@ -864,13 +1872,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
|
|
|
864
1872
|
* A wrapper for streaming responses in callable methods
|
|
865
1873
|
*/
|
|
866
1874
|
export class StreamingResponse {
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
1875
|
+
private _connection: Connection;
|
|
1876
|
+
private _id: string;
|
|
1877
|
+
private _closed = false;
|
|
870
1878
|
|
|
871
1879
|
constructor(connection: Connection, id: string) {
|
|
872
|
-
this
|
|
873
|
-
this
|
|
1880
|
+
this._connection = connection;
|
|
1881
|
+
this._id = id;
|
|
874
1882
|
}
|
|
875
1883
|
|
|
876
1884
|
/**
|
|
@@ -878,17 +1886,17 @@ export class StreamingResponse {
|
|
|
878
1886
|
* @param chunk The data to send
|
|
879
1887
|
*/
|
|
880
1888
|
send(chunk: unknown) {
|
|
881
|
-
if (this
|
|
1889
|
+
if (this._closed) {
|
|
882
1890
|
throw new Error("StreamingResponse is already closed");
|
|
883
1891
|
}
|
|
884
1892
|
const response: RPCResponse = {
|
|
885
|
-
type: "rpc",
|
|
886
|
-
id: this.#id,
|
|
887
|
-
success: true,
|
|
888
|
-
result: chunk,
|
|
889
1893
|
done: false,
|
|
1894
|
+
id: this._id,
|
|
1895
|
+
result: chunk,
|
|
1896
|
+
success: true,
|
|
1897
|
+
type: "rpc"
|
|
890
1898
|
};
|
|
891
|
-
this
|
|
1899
|
+
this._connection.send(JSON.stringify(response));
|
|
892
1900
|
}
|
|
893
1901
|
|
|
894
1902
|
/**
|
|
@@ -896,17 +1904,17 @@ export class StreamingResponse {
|
|
|
896
1904
|
* @param finalChunk Optional final chunk of data to send
|
|
897
1905
|
*/
|
|
898
1906
|
end(finalChunk?: unknown) {
|
|
899
|
-
if (this
|
|
1907
|
+
if (this._closed) {
|
|
900
1908
|
throw new Error("StreamingResponse is already closed");
|
|
901
1909
|
}
|
|
902
|
-
this
|
|
1910
|
+
this._closed = true;
|
|
903
1911
|
const response: RPCResponse = {
|
|
904
|
-
type: "rpc",
|
|
905
|
-
id: this.#id,
|
|
906
|
-
success: true,
|
|
907
|
-
result: finalChunk,
|
|
908
1912
|
done: true,
|
|
1913
|
+
id: this._id,
|
|
1914
|
+
result: finalChunk,
|
|
1915
|
+
success: true,
|
|
1916
|
+
type: "rpc"
|
|
909
1917
|
};
|
|
910
|
-
this
|
|
1918
|
+
this._connection.send(JSON.stringify(response));
|
|
911
1919
|
}
|
|
912
1920
|
}
|