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