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