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