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