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