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