agents 0.2.14 → 0.2.15

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.
@@ -1,1231 +0,0 @@
1
- import { MessageType } from "./ai-types-UZlfLOYP.js";
2
- import { camelCaseToKebabCase } from "./client-DjR-lC16.js";
3
- import { DisposableStore, MCPClientManager } from "./client-CZBVDDoO.js";
4
- import { DurableObjectOAuthClientProvider } from "./do-oauth-client-provider-B2jr6UNq.js";
5
- import { AsyncLocalStorage } from "node:async_hooks";
6
- import { parseCronExpression } from "cron-schedule";
7
- import { nanoid } from "nanoid";
8
- import { EmailMessage } from "cloudflare:email";
9
- import { Server, getServerByName, routePartykitRequest } from "partyserver";
10
-
11
- //#region src/observability/index.ts
12
- /**
13
- * A generic observability implementation that logs events to the console.
14
- */
15
- const genericObservability = { emit(event) {
16
- if (isLocalMode()) {
17
- console.log(event.displayMessage);
18
- return;
19
- }
20
- console.log(event);
21
- } };
22
- let localMode = false;
23
- function isLocalMode() {
24
- if (localMode) return true;
25
- const { request } = getCurrentAgent();
26
- if (!request) return false;
27
- localMode = new URL(request.url).hostname === "localhost";
28
- return localMode;
29
- }
30
-
31
- //#endregion
32
- //#region src/index.ts
33
- /**
34
- * Type guard for RPC request messages
35
- */
36
- function isRPCRequest(msg) {
37
- return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.RPC && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
38
- }
39
- /**
40
- * Type guard for state update messages
41
- */
42
- function isStateUpdateMessage(msg) {
43
- return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.CF_AGENT_STATE && "state" in msg;
44
- }
45
- const callableMetadata = /* @__PURE__ */ new Map();
46
- /**
47
- * Decorator that marks a method as callable by clients
48
- * @param metadata Optional metadata about the callable method
49
- */
50
- function callable(metadata = {}) {
51
- return function callableDecorator(target, context) {
52
- if (!callableMetadata.has(target)) callableMetadata.set(target, metadata);
53
- return target;
54
- };
55
- }
56
- let didWarnAboutUnstableCallable = false;
57
- /**
58
- * Decorator that marks a method as callable by clients
59
- * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
60
- * @param metadata Optional metadata about the callable method
61
- */
62
- const unstable_callable = (metadata = {}) => {
63
- if (!didWarnAboutUnstableCallable) {
64
- didWarnAboutUnstableCallable = true;
65
- console.warn("unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version.");
66
- }
67
- callable(metadata);
68
- };
69
- function getNextCronTime(cron) {
70
- return parseCronExpression(cron).getNextDate();
71
- }
72
- const STATE_ROW_ID = "cf_state_row_id";
73
- const STATE_WAS_CHANGED = "cf_state_was_changed";
74
- const DEFAULT_STATE = {};
75
- const agentContext = new AsyncLocalStorage();
76
- function getCurrentAgent() {
77
- const store = agentContext.getStore();
78
- if (!store) return {
79
- agent: void 0,
80
- connection: void 0,
81
- request: void 0,
82
- email: void 0
83
- };
84
- return store;
85
- }
86
- /**
87
- * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
88
- * @param agent The agent instance
89
- * @param method The method to wrap
90
- * @returns A wrapped method that runs within the agent context
91
- */
92
- function withAgentContext(method) {
93
- return function(...args) {
94
- const { connection, request, email, agent } = getCurrentAgent();
95
- if (agent === this) return method.apply(this, args);
96
- return agentContext.run({
97
- agent: this,
98
- connection,
99
- request,
100
- email
101
- }, () => {
102
- return method.apply(this, args);
103
- });
104
- };
105
- }
106
- /**
107
- * Base class for creating Agent implementations
108
- * @template Env Environment type containing bindings
109
- * @template State State type to store within the Agent
110
- */
111
- var Agent = class Agent extends Server {
112
- /**
113
- * Current state of the Agent
114
- */
115
- get state() {
116
- if (this._state !== DEFAULT_STATE) return this._state;
117
- const wasChanged = this.sql`
118
- SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
119
- `;
120
- const result = this.sql`
121
- SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
122
- `;
123
- if (wasChanged[0]?.state === "true" || result[0]?.state) {
124
- const state = result[0]?.state;
125
- this._state = JSON.parse(state);
126
- return this._state;
127
- }
128
- if (this.initialState === DEFAULT_STATE) return;
129
- this.setState(this.initialState);
130
- return this.initialState;
131
- }
132
- static {
133
- this.options = { hibernate: true };
134
- }
135
- /**
136
- * Execute SQL queries against the Agent's database
137
- * @template T Type of the returned rows
138
- * @param strings SQL query template strings
139
- * @param values Values to be inserted into the query
140
- * @returns Array of query results
141
- */
142
- sql(strings, ...values) {
143
- let query = "";
144
- try {
145
- query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? "?" : ""), "");
146
- return [...this.ctx.storage.sql.exec(query, ...values)];
147
- } catch (e) {
148
- console.error(`failed to execute sql query: ${query}`, e);
149
- throw this.onError(e);
150
- }
151
- }
152
- constructor(ctx, env) {
153
- super(ctx, env);
154
- this._state = DEFAULT_STATE;
155
- this._disposables = new DisposableStore();
156
- this._ParentClass = Object.getPrototypeOf(this).constructor;
157
- this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
158
- this.initialState = DEFAULT_STATE;
159
- this.observability = genericObservability;
160
- this._flushingQueue = false;
161
- this.alarm = async () => {
162
- const now = Math.floor(Date.now() / 1e3);
163
- const result = this.sql`
164
- SELECT * FROM cf_agents_schedules WHERE time <= ${now}
165
- `;
166
- if (result && Array.isArray(result)) for (const row of result) {
167
- const callback = this[row.callback];
168
- if (!callback) {
169
- console.error(`callback ${row.callback} not found`);
170
- continue;
171
- }
172
- await agentContext.run({
173
- agent: this,
174
- connection: void 0,
175
- request: void 0,
176
- email: void 0
177
- }, async () => {
178
- try {
179
- this.observability?.emit({
180
- displayMessage: `Schedule ${row.id} executed`,
181
- id: nanoid(),
182
- payload: {
183
- callback: row.callback,
184
- id: row.id
185
- },
186
- timestamp: Date.now(),
187
- type: "schedule:execute"
188
- }, this.ctx);
189
- await callback.bind(this)(JSON.parse(row.payload), row);
190
- } catch (e) {
191
- console.error(`error executing callback "${row.callback}"`, e);
192
- }
193
- });
194
- if (row.type === "cron") {
195
- const nextExecutionTime = getNextCronTime(row.cron);
196
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
197
- this.sql`
198
- UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
199
- `;
200
- } else this.sql`
201
- DELETE FROM cf_agents_schedules WHERE id = ${row.id}
202
- `;
203
- }
204
- await this._scheduleNextAlarm();
205
- };
206
- if (!wrappedClasses.has(this.constructor)) {
207
- this._autoWrapCustomMethods();
208
- wrappedClasses.add(this.constructor);
209
- }
210
- this._disposables.add(this.mcp.onConnected(async () => {
211
- this.broadcastMcpServers();
212
- }));
213
- this._disposables.add(this.mcp.onObservabilityEvent((event) => {
214
- this.observability?.emit(event);
215
- }));
216
- this.sql`
217
- CREATE TABLE IF NOT EXISTS cf_agents_state (
218
- id TEXT PRIMARY KEY NOT NULL,
219
- state TEXT
220
- )
221
- `;
222
- this.sql`
223
- CREATE TABLE IF NOT EXISTS cf_agents_queues (
224
- id TEXT PRIMARY KEY NOT NULL,
225
- payload TEXT,
226
- callback TEXT,
227
- created_at INTEGER DEFAULT (unixepoch())
228
- )
229
- `;
230
- this.ctx.blockConcurrencyWhile(async () => {
231
- return this._tryCatch(async () => {
232
- this.sql`
233
- CREATE TABLE IF NOT EXISTS cf_agents_schedules (
234
- id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
235
- callback TEXT,
236
- payload TEXT,
237
- type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
238
- time INTEGER,
239
- delayInSeconds INTEGER,
240
- cron TEXT,
241
- created_at INTEGER DEFAULT (unixepoch())
242
- )
243
- `;
244
- await this.alarm();
245
- });
246
- });
247
- this.sql`
248
- CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
249
- id TEXT PRIMARY KEY NOT NULL,
250
- name TEXT NOT NULL,
251
- server_url TEXT NOT NULL,
252
- callback_url TEXT NOT NULL,
253
- client_id TEXT,
254
- auth_url TEXT,
255
- server_options TEXT
256
- )
257
- `;
258
- const _onRequest = this.onRequest.bind(this);
259
- this.onRequest = (request) => {
260
- return agentContext.run({
261
- agent: this,
262
- connection: void 0,
263
- request,
264
- email: void 0
265
- }, async () => {
266
- const callbackResult = await this._handlePotentialOAuthCallback(request);
267
- if (callbackResult) return callbackResult;
268
- return this._tryCatch(() => _onRequest(request));
269
- });
270
- };
271
- const _onMessage = this.onMessage.bind(this);
272
- this.onMessage = async (connection, message) => {
273
- return agentContext.run({
274
- agent: this,
275
- connection,
276
- request: void 0,
277
- email: void 0
278
- }, async () => {
279
- if (typeof message !== "string") return this._tryCatch(() => _onMessage(connection, message));
280
- let parsed;
281
- try {
282
- parsed = JSON.parse(message);
283
- } catch (_e) {
284
- return this._tryCatch(() => _onMessage(connection, message));
285
- }
286
- if (isStateUpdateMessage(parsed)) {
287
- this._setStateInternal(parsed.state, connection);
288
- return;
289
- }
290
- if (isRPCRequest(parsed)) {
291
- try {
292
- const { id, method, args } = parsed;
293
- const methodFn = this[method];
294
- if (typeof methodFn !== "function") throw new Error(`Method ${method} does not exist`);
295
- if (!this._isCallable(method)) throw new Error(`Method ${method} is not callable`);
296
- const metadata = callableMetadata.get(methodFn);
297
- if (metadata?.streaming) {
298
- const stream = new StreamingResponse(connection, id);
299
- await methodFn.apply(this, [stream, ...args]);
300
- return;
301
- }
302
- const result = await methodFn.apply(this, args);
303
- this.observability?.emit({
304
- displayMessage: `RPC call to ${method}`,
305
- id: nanoid(),
306
- payload: {
307
- method,
308
- streaming: metadata?.streaming
309
- },
310
- timestamp: Date.now(),
311
- type: "rpc"
312
- }, this.ctx);
313
- const response = {
314
- done: true,
315
- id,
316
- result,
317
- success: true,
318
- type: MessageType.RPC
319
- };
320
- connection.send(JSON.stringify(response));
321
- } catch (e) {
322
- const response = {
323
- error: e instanceof Error ? e.message : "Unknown error occurred",
324
- id: parsed.id,
325
- success: false,
326
- type: MessageType.RPC
327
- };
328
- connection.send(JSON.stringify(response));
329
- console.error("RPC error:", e);
330
- }
331
- return;
332
- }
333
- return this._tryCatch(() => _onMessage(connection, message));
334
- });
335
- };
336
- const _onConnect = this.onConnect.bind(this);
337
- this.onConnect = (connection, ctx$1) => {
338
- return agentContext.run({
339
- agent: this,
340
- connection,
341
- request: ctx$1.request,
342
- email: void 0
343
- }, () => {
344
- if (this.state) connection.send(JSON.stringify({
345
- state: this.state,
346
- type: MessageType.CF_AGENT_STATE
347
- }));
348
- connection.send(JSON.stringify({
349
- mcp: this.getMcpServers(),
350
- type: MessageType.CF_AGENT_MCP_SERVERS
351
- }));
352
- this.observability?.emit({
353
- displayMessage: "Connection established",
354
- id: nanoid(),
355
- payload: { connectionId: connection.id },
356
- timestamp: Date.now(),
357
- type: "connect"
358
- }, this.ctx);
359
- return this._tryCatch(() => _onConnect(connection, ctx$1));
360
- });
361
- };
362
- const _onStart = this.onStart.bind(this);
363
- this.onStart = async (props) => {
364
- return agentContext.run({
365
- agent: this,
366
- connection: void 0,
367
- request: void 0,
368
- email: void 0
369
- }, async () => {
370
- await this._tryCatch(() => {
371
- const servers = this.sql`
372
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
373
- `;
374
- this.broadcastMcpServers();
375
- if (servers && Array.isArray(servers) && servers.length > 0) {
376
- servers.forEach((server) => {
377
- if (server.callback_url) this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);
378
- });
379
- servers.forEach((server) => {
380
- this._connectToMcpServerInternal(server.name, server.server_url, server.callback_url, server.server_options ? JSON.parse(server.server_options) : void 0, {
381
- id: server.id,
382
- oauthClientId: server.client_id ?? void 0
383
- }).then(() => {
384
- this.broadcastMcpServers();
385
- }).catch((error) => {
386
- console.error(`Error connecting to MCP server: ${server.name} (${server.server_url})`, error);
387
- this.broadcastMcpServers();
388
- });
389
- });
390
- }
391
- return _onStart(props);
392
- });
393
- });
394
- };
395
- }
396
- _setStateInternal(state, source = "server") {
397
- this._state = state;
398
- this.sql`
399
- INSERT OR REPLACE INTO cf_agents_state (id, state)
400
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
401
- `;
402
- this.sql`
403
- INSERT OR REPLACE INTO cf_agents_state (id, state)
404
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
405
- `;
406
- this.broadcast(JSON.stringify({
407
- state,
408
- type: MessageType.CF_AGENT_STATE
409
- }), source !== "server" ? [source.id] : []);
410
- return this._tryCatch(() => {
411
- const { connection, request, email } = agentContext.getStore() || {};
412
- return agentContext.run({
413
- agent: this,
414
- connection,
415
- request,
416
- email
417
- }, async () => {
418
- this.observability?.emit({
419
- displayMessage: "State updated",
420
- id: nanoid(),
421
- payload: {},
422
- timestamp: Date.now(),
423
- type: "state:update"
424
- }, this.ctx);
425
- return this.onStateUpdate(state, source);
426
- });
427
- });
428
- }
429
- /**
430
- * Update the Agent's state
431
- * @param state New state to set
432
- */
433
- setState(state) {
434
- this._setStateInternal(state, "server");
435
- }
436
- /**
437
- * Called when the Agent's state is updated
438
- * @param state Updated state
439
- * @param source Source of the state update ("server" or a client connection)
440
- */
441
- onStateUpdate(state, source) {}
442
- /**
443
- * Called when the Agent receives an email via routeAgentEmail()
444
- * Override this method to handle incoming emails
445
- * @param email Email message to process
446
- */
447
- async _onEmail(email) {
448
- return agentContext.run({
449
- agent: this,
450
- connection: void 0,
451
- request: void 0,
452
- email
453
- }, async () => {
454
- if ("onEmail" in this && typeof this.onEmail === "function") return this._tryCatch(() => this.onEmail(email));
455
- else {
456
- console.log("Received email from:", email.from, "to:", email.to);
457
- console.log("Subject:", email.headers.get("subject"));
458
- console.log("Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails");
459
- }
460
- });
461
- }
462
- /**
463
- * Reply to an email
464
- * @param email The email to reply to
465
- * @param options Options for the reply
466
- * @returns void
467
- */
468
- async replyToEmail(email, options) {
469
- return this._tryCatch(async () => {
470
- const agentName = camelCaseToKebabCase(this._ParentClass.name);
471
- const agentId = this.name;
472
- const { createMimeMessage } = await import("mimetext");
473
- const msg = createMimeMessage();
474
- msg.setSender({
475
- addr: email.to,
476
- name: options.fromName
477
- });
478
- msg.setRecipient(email.from);
479
- msg.setSubject(options.subject || `Re: ${email.headers.get("subject")}` || "No subject");
480
- msg.addMessage({
481
- contentType: options.contentType || "text/plain",
482
- data: options.body
483
- });
484
- const messageId = `<${agentId}@${email.from.split("@")[1]}>`;
485
- msg.setHeader("In-Reply-To", email.headers.get("Message-ID"));
486
- msg.setHeader("Message-ID", messageId);
487
- msg.setHeader("X-Agent-Name", agentName);
488
- msg.setHeader("X-Agent-ID", agentId);
489
- if (options.headers) for (const [key, value] of Object.entries(options.headers)) msg.setHeader(key, value);
490
- await email.reply({
491
- from: email.to,
492
- raw: msg.asRaw(),
493
- to: email.from
494
- });
495
- });
496
- }
497
- async _tryCatch(fn) {
498
- try {
499
- return await fn();
500
- } catch (e) {
501
- throw this.onError(e);
502
- }
503
- }
504
- /**
505
- * Automatically wrap custom methods with agent context
506
- * This ensures getCurrentAgent() works in all custom methods without decorators
507
- */
508
- _autoWrapCustomMethods() {
509
- const basePrototypes = [Agent.prototype, Server.prototype];
510
- const baseMethods = /* @__PURE__ */ new Set();
511
- for (const baseProto of basePrototypes) {
512
- let proto$1 = baseProto;
513
- while (proto$1 && proto$1 !== Object.prototype) {
514
- const methodNames = Object.getOwnPropertyNames(proto$1);
515
- for (const methodName of methodNames) baseMethods.add(methodName);
516
- proto$1 = Object.getPrototypeOf(proto$1);
517
- }
518
- }
519
- let proto = Object.getPrototypeOf(this);
520
- let depth = 0;
521
- while (proto && proto !== Object.prototype && depth < 10) {
522
- const methodNames = Object.getOwnPropertyNames(proto);
523
- for (const methodName of methodNames) {
524
- const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
525
- if (baseMethods.has(methodName) || methodName.startsWith("_") || !descriptor || !!descriptor.get || typeof descriptor.value !== "function") continue;
526
- const wrappedFunction = withAgentContext(this[methodName]);
527
- if (this._isCallable(methodName)) callableMetadata.set(wrappedFunction, callableMetadata.get(this[methodName]));
528
- this.constructor.prototype[methodName] = wrappedFunction;
529
- }
530
- proto = Object.getPrototypeOf(proto);
531
- depth++;
532
- }
533
- }
534
- onError(connectionOrError, error) {
535
- let theError;
536
- if (connectionOrError && error) {
537
- theError = error;
538
- console.error("Error on websocket connection:", connectionOrError.id, theError);
539
- console.error("Override onError(connection, error) to handle websocket connection errors");
540
- } else {
541
- theError = connectionOrError;
542
- console.error("Error on server:", theError);
543
- console.error("Override onError(error) to handle server errors");
544
- }
545
- throw theError;
546
- }
547
- /**
548
- * Render content (not implemented in base class)
549
- */
550
- render() {
551
- throw new Error("Not implemented");
552
- }
553
- /**
554
- * Queue a task to be executed in the future
555
- * @param payload Payload to pass to the callback
556
- * @param callback Name of the method to call
557
- * @returns The ID of the queued task
558
- */
559
- async queue(callback, payload) {
560
- const id = nanoid(9);
561
- if (typeof callback !== "string") throw new Error("Callback must be a string");
562
- if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
563
- this.sql`
564
- INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
565
- VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
566
- `;
567
- this._flushQueue().catch((e) => {
568
- console.error("Error flushing queue:", e);
569
- });
570
- return id;
571
- }
572
- async _flushQueue() {
573
- if (this._flushingQueue) return;
574
- this._flushingQueue = true;
575
- while (true) {
576
- const result = this.sql`
577
- SELECT * FROM cf_agents_queues
578
- ORDER BY created_at ASC
579
- `;
580
- if (!result || result.length === 0) break;
581
- for (const row of result || []) {
582
- const callback = this[row.callback];
583
- if (!callback) {
584
- console.error(`callback ${row.callback} not found`);
585
- continue;
586
- }
587
- const { connection, request, email } = agentContext.getStore() || {};
588
- await agentContext.run({
589
- agent: this,
590
- connection,
591
- request,
592
- email
593
- }, async () => {
594
- await callback.bind(this)(JSON.parse(row.payload), row);
595
- await this.dequeue(row.id);
596
- });
597
- }
598
- }
599
- this._flushingQueue = false;
600
- }
601
- /**
602
- * Dequeue a task by ID
603
- * @param id ID of the task to dequeue
604
- */
605
- async dequeue(id) {
606
- this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
607
- }
608
- /**
609
- * Dequeue all tasks
610
- */
611
- async dequeueAll() {
612
- this.sql`DELETE FROM cf_agents_queues`;
613
- }
614
- /**
615
- * Dequeue all tasks by callback
616
- * @param callback Name of the callback to dequeue
617
- */
618
- async dequeueAllByCallback(callback) {
619
- this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
620
- }
621
- /**
622
- * Get a queued task by ID
623
- * @param id ID of the task to get
624
- * @returns The task or undefined if not found
625
- */
626
- async getQueue(id) {
627
- const result = this.sql`
628
- SELECT * FROM cf_agents_queues WHERE id = ${id}
629
- `;
630
- return result ? {
631
- ...result[0],
632
- payload: JSON.parse(result[0].payload)
633
- } : void 0;
634
- }
635
- /**
636
- * Get all queues by key and value
637
- * @param key Key to filter by
638
- * @param value Value to filter by
639
- * @returns Array of matching QueueItem objects
640
- */
641
- async getQueues(key, value) {
642
- return this.sql`
643
- SELECT * FROM cf_agents_queues
644
- `.filter((row) => JSON.parse(row.payload)[key] === value);
645
- }
646
- /**
647
- * Schedule a task to be executed in the future
648
- * @template T Type of the payload data
649
- * @param when When to execute the task (Date, seconds delay, or cron expression)
650
- * @param callback Name of the method to call
651
- * @param payload Data to pass to the callback
652
- * @returns Schedule object representing the scheduled task
653
- */
654
- async schedule(when, callback, payload) {
655
- const id = nanoid(9);
656
- const emitScheduleCreate = (schedule) => this.observability?.emit({
657
- displayMessage: `Schedule ${schedule.id} created`,
658
- id: nanoid(),
659
- payload: {
660
- callback,
661
- id
662
- },
663
- timestamp: Date.now(),
664
- type: "schedule:create"
665
- }, this.ctx);
666
- if (typeof callback !== "string") throw new Error("Callback must be a string");
667
- if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
668
- if (when instanceof Date) {
669
- const timestamp = Math.floor(when.getTime() / 1e3);
670
- this.sql`
671
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
672
- VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'scheduled', ${timestamp})
673
- `;
674
- await this._scheduleNextAlarm();
675
- const schedule = {
676
- callback,
677
- id,
678
- payload,
679
- time: timestamp,
680
- type: "scheduled"
681
- };
682
- emitScheduleCreate(schedule);
683
- return schedule;
684
- }
685
- if (typeof when === "number") {
686
- const time = new Date(Date.now() + when * 1e3);
687
- const timestamp = Math.floor(time.getTime() / 1e3);
688
- this.sql`
689
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
690
- VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'delayed', ${when}, ${timestamp})
691
- `;
692
- await this._scheduleNextAlarm();
693
- const schedule = {
694
- callback,
695
- delayInSeconds: when,
696
- id,
697
- payload,
698
- time: timestamp,
699
- type: "delayed"
700
- };
701
- emitScheduleCreate(schedule);
702
- return schedule;
703
- }
704
- if (typeof when === "string") {
705
- const nextExecutionTime = getNextCronTime(when);
706
- const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
707
- this.sql`
708
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
709
- VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'cron', ${when}, ${timestamp})
710
- `;
711
- await this._scheduleNextAlarm();
712
- const schedule = {
713
- callback,
714
- cron: when,
715
- id,
716
- payload,
717
- time: timestamp,
718
- type: "cron"
719
- };
720
- emitScheduleCreate(schedule);
721
- return schedule;
722
- }
723
- throw new Error("Invalid schedule type");
724
- }
725
- /**
726
- * Get a scheduled task by ID
727
- * @template T Type of the payload data
728
- * @param id ID of the scheduled task
729
- * @returns The Schedule object or undefined if not found
730
- */
731
- async getSchedule(id) {
732
- const result = this.sql`
733
- SELECT * FROM cf_agents_schedules WHERE id = ${id}
734
- `;
735
- if (!result) {
736
- console.error(`schedule ${id} not found`);
737
- return;
738
- }
739
- return {
740
- ...result[0],
741
- payload: JSON.parse(result[0].payload)
742
- };
743
- }
744
- /**
745
- * Get scheduled tasks matching the given criteria
746
- * @template T Type of the payload data
747
- * @param criteria Criteria to filter schedules
748
- * @returns Array of matching Schedule objects
749
- */
750
- getSchedules(criteria = {}) {
751
- let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
752
- const params = [];
753
- if (criteria.id) {
754
- query += " AND id = ?";
755
- params.push(criteria.id);
756
- }
757
- if (criteria.type) {
758
- query += " AND type = ?";
759
- params.push(criteria.type);
760
- }
761
- if (criteria.timeRange) {
762
- query += " AND time >= ? AND time <= ?";
763
- const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
764
- const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
765
- params.push(Math.floor(start.getTime() / 1e3), Math.floor(end.getTime() / 1e3));
766
- }
767
- return this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
768
- ...row,
769
- payload: JSON.parse(row.payload)
770
- }));
771
- }
772
- /**
773
- * Cancel a scheduled task
774
- * @param id ID of the task to cancel
775
- * @returns true if the task was cancelled, false otherwise
776
- */
777
- async cancelSchedule(id) {
778
- const schedule = await this.getSchedule(id);
779
- if (schedule) this.observability?.emit({
780
- displayMessage: `Schedule ${id} cancelled`,
781
- id: nanoid(),
782
- payload: {
783
- callback: schedule.callback,
784
- id: schedule.id
785
- },
786
- timestamp: Date.now(),
787
- type: "schedule:cancel"
788
- }, this.ctx);
789
- this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
790
- await this._scheduleNextAlarm();
791
- return true;
792
- }
793
- async _scheduleNextAlarm() {
794
- const result = this.sql`
795
- SELECT time FROM cf_agents_schedules
796
- WHERE time > ${Math.floor(Date.now() / 1e3)}
797
- ORDER BY time ASC
798
- LIMIT 1
799
- `;
800
- if (!result) return;
801
- if (result.length > 0 && "time" in result[0]) {
802
- const nextTime = result[0].time * 1e3;
803
- await this.ctx.storage.setAlarm(nextTime);
804
- }
805
- }
806
- /**
807
- * Destroy the Agent, removing all state and scheduled tasks
808
- */
809
- async destroy() {
810
- this.sql`DROP TABLE IF EXISTS cf_agents_state`;
811
- this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
812
- this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
813
- this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
814
- await this.ctx.storage.deleteAlarm();
815
- await this.ctx.storage.deleteAll();
816
- this._disposables.dispose();
817
- await this.mcp.dispose?.();
818
- this.ctx.abort("destroyed");
819
- this.observability?.emit({
820
- displayMessage: "Agent destroyed",
821
- id: nanoid(),
822
- payload: {},
823
- timestamp: Date.now(),
824
- type: "destroy"
825
- }, this.ctx);
826
- }
827
- /**
828
- * Get all methods marked as callable on this Agent
829
- * @returns A map of method names to their metadata
830
- */
831
- _isCallable(method) {
832
- return callableMetadata.has(this[method]);
833
- }
834
- /**
835
- * Connect to a new MCP Server
836
- *
837
- * @param serverName Name of the MCP server
838
- * @param url MCP Server SSE URL
839
- * @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
840
- * @param agentsPrefix agents routing prefix if not using `agents`
841
- * @param options MCP client and transport options
842
- * @returns authUrl
843
- */
844
- async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
845
- let resolvedCallbackHost = callbackHost;
846
- if (!resolvedCallbackHost) {
847
- const { request } = getCurrentAgent();
848
- if (!request) throw new Error("callbackHost is required when not called within a request context");
849
- const requestUrl = new URL(request.url);
850
- resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
851
- }
852
- const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
853
- const serverId = nanoid(8);
854
- this.sql`
855
- INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
856
- VALUES (
857
- ${serverId},
858
- ${serverName},
859
- ${url},
860
- ${null},
861
- ${null},
862
- ${callbackUrl},
863
- ${options ? JSON.stringify(options) : null}
864
- );
865
- `;
866
- const result = await this._connectToMcpServerInternal(serverName, url, callbackUrl, options, { id: serverId });
867
- if (result.clientId || result.authUrl) this.sql`
868
- UPDATE cf_agents_mcp_servers
869
- SET client_id = ${result.clientId ?? null}, auth_url = ${result.authUrl ?? null}
870
- WHERE id = ${serverId}
871
- `;
872
- this.broadcastMcpServers();
873
- return result;
874
- }
875
- /**
876
- * Handle potential OAuth callback requests after DO hibernation.
877
- * Detects OAuth callbacks, restores state from database, and processes the callback.
878
- * Returns a Response if this was an OAuth callback, otherwise returns undefined.
879
- */
880
- async _handlePotentialOAuthCallback(request) {
881
- if (request.method !== "GET") return;
882
- const url = new URL(request.url);
883
- if (!(url.pathname.includes("/callback/") && url.searchParams.has("code"))) return;
884
- const pathParts = url.pathname.split("/");
885
- const callbackIndex = pathParts.indexOf("callback");
886
- const serverId = callbackIndex !== -1 ? pathParts[callbackIndex + 1] : null;
887
- if (!serverId) return new Response("Invalid callback URL: missing serverId", { status: 400 });
888
- if (this.mcp.isCallbackRequest(request) && this.mcp.mcpConnections[serverId]) return this._processOAuthCallback(request);
889
- try {
890
- const server = this.sql`
891
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options
892
- FROM cf_agents_mcp_servers
893
- WHERE id = ${serverId}
894
- `.find((s) => s.id === serverId);
895
- if (!server) return new Response(`OAuth callback failed: Server ${serverId} not found in database`, { status: 404 });
896
- if (!server.callback_url) return new Response(`OAuth callback failed: No callback URL stored for server ${serverId}`, { status: 500 });
897
- this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);
898
- if (!this.mcp.mcpConnections[serverId]) {
899
- let parsedOptions;
900
- try {
901
- parsedOptions = server.server_options ? JSON.parse(server.server_options) : void 0;
902
- } catch {
903
- return new Response(`OAuth callback failed: Invalid server options in database for ${serverId}`, { status: 500 });
904
- }
905
- await this._connectToMcpServerInternal(server.name, server.server_url, server.callback_url, parsedOptions, {
906
- id: server.id,
907
- oauthClientId: server.client_id ?? void 0
908
- });
909
- }
910
- return this._processOAuthCallback(request);
911
- } catch (error) {
912
- const errorMsg = error instanceof Error ? error.message : "Unknown error";
913
- console.error(`Failed to restore MCP state for ${serverId}:`, error);
914
- return new Response(`OAuth callback failed during state restoration: ${errorMsg}`, { status: 500 });
915
- }
916
- }
917
- /**
918
- * Process an OAuth callback request (assumes state is already restored)
919
- */
920
- async _processOAuthCallback(request) {
921
- const result = await this.mcp.handleCallbackRequest(request);
922
- this.broadcastMcpServers();
923
- if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
924
- console.error("Background connection failed:", error);
925
- }).finally(() => {
926
- this.broadcastMcpServers();
927
- });
928
- return this.handleOAuthCallbackResponse(result, request);
929
- }
930
- async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
931
- const authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);
932
- if (reconnect) {
933
- authProvider.serverId = reconnect.id;
934
- if (reconnect.oauthClientId) authProvider.clientId = reconnect.oauthClientId;
935
- }
936
- const transportType = options?.transport?.type ?? "auto";
937
- let headerTransportOpts = {};
938
- if (options?.transport?.headers) headerTransportOpts = {
939
- eventSourceInit: { fetch: (url$1, init) => fetch(url$1, {
940
- ...init,
941
- headers: options?.transport?.headers
942
- }) },
943
- requestInit: { headers: options?.transport?.headers }
944
- };
945
- const { id, authUrl, clientId } = await this.mcp.connect(url, {
946
- client: options?.client,
947
- reconnect,
948
- transport: {
949
- ...headerTransportOpts,
950
- authProvider,
951
- type: transportType
952
- }
953
- });
954
- return {
955
- authUrl,
956
- clientId,
957
- id
958
- };
959
- }
960
- async removeMcpServer(id) {
961
- this.mcp.closeConnection(id);
962
- this.mcp.unregisterCallbackUrl(id);
963
- this.sql`
964
- DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
965
- `;
966
- this.broadcastMcpServers();
967
- }
968
- getMcpServers() {
969
- const mcpState = {
970
- prompts: this.mcp.listPrompts(),
971
- resources: this.mcp.listResources(),
972
- servers: {},
973
- tools: this.mcp.listTools()
974
- };
975
- const servers = this.sql`
976
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
977
- `;
978
- if (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {
979
- const serverConn = this.mcp.mcpConnections[server.id];
980
- mcpState.servers[server.id] = {
981
- auth_url: server.auth_url,
982
- capabilities: serverConn?.serverCapabilities ?? null,
983
- instructions: serverConn?.instructions ?? null,
984
- name: server.name,
985
- server_url: server.server_url,
986
- state: serverConn?.connectionState ?? "authenticating"
987
- };
988
- }
989
- return mcpState;
990
- }
991
- broadcastMcpServers() {
992
- this.broadcast(JSON.stringify({
993
- mcp: this.getMcpServers(),
994
- type: MessageType.CF_AGENT_MCP_SERVERS
995
- }));
996
- }
997
- /**
998
- * Handle OAuth callback response using MCPClientManager configuration
999
- * @param result OAuth callback result
1000
- * @param request The original request (needed for base URL)
1001
- * @returns Response for the OAuth callback
1002
- */
1003
- handleOAuthCallbackResponse(result, request) {
1004
- const config = this.mcp.getOAuthCallbackConfig();
1005
- if (config?.customHandler) return config.customHandler(result);
1006
- if (config?.successRedirect && result.authSuccess) return Response.redirect(config.successRedirect);
1007
- if (config?.errorRedirect && !result.authSuccess) return Response.redirect(`${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`);
1008
- const baseUrl = new URL(request.url).origin;
1009
- return Response.redirect(baseUrl);
1010
- }
1011
- };
1012
- const wrappedClasses = /* @__PURE__ */ new Set();
1013
- /**
1014
- * Route a request to the appropriate Agent
1015
- * @param request Request to route
1016
- * @param env Environment containing Agent bindings
1017
- * @param options Routing options
1018
- * @returns Response from the Agent or undefined if no route matched
1019
- */
1020
- async function routeAgentRequest(request, env, options) {
1021
- const corsHeaders = options?.cors === true ? {
1022
- "Access-Control-Allow-Credentials": "true",
1023
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1024
- "Access-Control-Allow-Origin": "*",
1025
- "Access-Control-Max-Age": "86400"
1026
- } : options?.cors;
1027
- if (request.method === "OPTIONS") {
1028
- if (corsHeaders) return new Response(null, { headers: corsHeaders });
1029
- console.warn("Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.");
1030
- }
1031
- let response = await routePartykitRequest(request, env, {
1032
- prefix: "agents",
1033
- ...options
1034
- });
1035
- if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") response = new Response(response.body, { headers: {
1036
- ...response.headers,
1037
- ...corsHeaders
1038
- } });
1039
- return response;
1040
- }
1041
- /**
1042
- * Create a resolver that uses the message-id header to determine the agent to route the email to
1043
- * @returns A function that resolves the agent to route the email to
1044
- */
1045
- function createHeaderBasedEmailResolver() {
1046
- return async (email, _env) => {
1047
- const messageId = email.headers.get("message-id");
1048
- if (messageId) {
1049
- const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1050
- if (messageIdMatch) {
1051
- const [, agentId$1, domain] = messageIdMatch;
1052
- return {
1053
- agentName: domain.split(".")[0],
1054
- agentId: agentId$1
1055
- };
1056
- }
1057
- }
1058
- const references = email.headers.get("references");
1059
- if (references) {
1060
- const referencesMatch = references.match(/<([A-Za-z0-9+/]{43}=)@([^>]+)>/);
1061
- if (referencesMatch) {
1062
- const [, base64Id, domain] = referencesMatch;
1063
- const agentId$1 = Buffer.from(base64Id, "base64").toString("hex");
1064
- return {
1065
- agentName: domain.split(".")[0],
1066
- agentId: agentId$1
1067
- };
1068
- }
1069
- }
1070
- const agentName = email.headers.get("x-agent-name");
1071
- const agentId = email.headers.get("x-agent-id");
1072
- if (agentName && agentId) return {
1073
- agentName,
1074
- agentId
1075
- };
1076
- return null;
1077
- };
1078
- }
1079
- /**
1080
- * Create a resolver that uses the email address to determine the agent to route the email to
1081
- * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
1082
- * @returns A function that resolves the agent to route the email to
1083
- */
1084
- function createAddressBasedEmailResolver(defaultAgentName) {
1085
- return async (email, _env) => {
1086
- const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1087
- if (!emailMatch) return null;
1088
- const [, localPart, subAddress] = emailMatch;
1089
- if (subAddress) return {
1090
- agentName: localPart,
1091
- agentId: subAddress
1092
- };
1093
- return {
1094
- agentName: defaultAgentName,
1095
- agentId: localPart
1096
- };
1097
- };
1098
- }
1099
- /**
1100
- * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
1101
- * @param agentName The name of the agent to route the email to
1102
- * @param agentId The id of the agent to route the email to
1103
- * @returns A function that resolves the agent to route the email to
1104
- */
1105
- function createCatchAllEmailResolver(agentName, agentId) {
1106
- return async () => ({
1107
- agentName,
1108
- agentId
1109
- });
1110
- }
1111
- const agentMapCache = /* @__PURE__ */ new WeakMap();
1112
- /**
1113
- * Route an email to the appropriate Agent
1114
- * @param email The email to route
1115
- * @param env The environment containing the Agent bindings
1116
- * @param options The options for routing the email
1117
- * @returns A promise that resolves when the email has been routed
1118
- */
1119
- async function routeAgentEmail(email, env, options) {
1120
- const routingInfo = await options.resolver(email, env);
1121
- if (!routingInfo) {
1122
- console.warn("No routing information found for email, dropping message");
1123
- return;
1124
- }
1125
- if (!agentMapCache.has(env)) {
1126
- const map = {};
1127
- for (const [key, value] of Object.entries(env)) if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
1128
- map[key] = value;
1129
- map[camelCaseToKebabCase(key)] = value;
1130
- }
1131
- agentMapCache.set(env, map);
1132
- }
1133
- const agentMap = agentMapCache.get(env);
1134
- const namespace = agentMap[routingInfo.agentName];
1135
- if (!namespace) {
1136
- const availableAgents = Object.keys(agentMap).filter((key) => !key.includes("-")).join(", ");
1137
- throw new Error(`Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`);
1138
- }
1139
- const agent = await getAgentByName(namespace, routingInfo.agentId);
1140
- const serialisableEmail = {
1141
- getRaw: async () => {
1142
- const reader = email.raw.getReader();
1143
- const chunks = [];
1144
- let done = false;
1145
- while (!done) {
1146
- const { value, done: readerDone } = await reader.read();
1147
- done = readerDone;
1148
- if (value) chunks.push(value);
1149
- }
1150
- const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1151
- const combined = new Uint8Array(totalLength);
1152
- let offset = 0;
1153
- for (const chunk of chunks) {
1154
- combined.set(chunk, offset);
1155
- offset += chunk.length;
1156
- }
1157
- return combined;
1158
- },
1159
- headers: email.headers,
1160
- rawSize: email.rawSize,
1161
- setReject: (reason) => {
1162
- email.setReject(reason);
1163
- },
1164
- forward: (rcptTo, headers) => {
1165
- return email.forward(rcptTo, headers);
1166
- },
1167
- reply: (options$1) => {
1168
- return email.reply(new EmailMessage(options$1.from, options$1.to, options$1.raw));
1169
- },
1170
- from: email.from,
1171
- to: email.to
1172
- };
1173
- await agent._onEmail(serialisableEmail);
1174
- }
1175
- /**
1176
- * Get or create an Agent by name
1177
- * @template Env Environment type containing bindings
1178
- * @template T Type of the Agent class
1179
- * @param namespace Agent namespace
1180
- * @param name Name of the Agent instance
1181
- * @param options Options for Agent creation
1182
- * @returns Promise resolving to an Agent instance stub
1183
- */
1184
- async function getAgentByName(namespace, name, options) {
1185
- return getServerByName(namespace, name, options);
1186
- }
1187
- /**
1188
- * A wrapper for streaming responses in callable methods
1189
- */
1190
- var StreamingResponse = class {
1191
- constructor(connection, id) {
1192
- this._closed = false;
1193
- this._connection = connection;
1194
- this._id = id;
1195
- }
1196
- /**
1197
- * Send a chunk of data to the client
1198
- * @param chunk The data to send
1199
- */
1200
- send(chunk) {
1201
- if (this._closed) throw new Error("StreamingResponse is already closed");
1202
- const response = {
1203
- done: false,
1204
- id: this._id,
1205
- result: chunk,
1206
- success: true,
1207
- type: MessageType.RPC
1208
- };
1209
- this._connection.send(JSON.stringify(response));
1210
- }
1211
- /**
1212
- * End the stream and send the final chunk (if any)
1213
- * @param finalChunk Optional final chunk of data to send
1214
- */
1215
- end(finalChunk) {
1216
- if (this._closed) throw new Error("StreamingResponse is already closed");
1217
- this._closed = true;
1218
- const response = {
1219
- done: true,
1220
- id: this._id,
1221
- result: finalChunk,
1222
- success: true,
1223
- type: MessageType.RPC
1224
- };
1225
- this._connection.send(JSON.stringify(response));
1226
- }
1227
- };
1228
-
1229
- //#endregion
1230
- export { Agent, StreamingResponse, callable, createAddressBasedEmailResolver, createCatchAllEmailResolver, createHeaderBasedEmailResolver, genericObservability, getAgentByName, getCurrentAgent, routeAgentEmail, routeAgentRequest, unstable_callable };
1231
- //# sourceMappingURL=src-L3cHuAag.js.map