agents 0.0.0-eb6827a → 0.0.0-eeb70e2
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 +49 -3
- package/dist/ai-chat-agent.js +129 -66
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +13 -0
- package/dist/ai-react.js +38 -24
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types.d.ts +5 -0
- package/dist/chunk-BZXOAZUX.js +106 -0
- package/dist/chunk-BZXOAZUX.js.map +1 -0
- package/dist/chunk-OYJXQRRH.js +465 -0
- package/dist/chunk-OYJXQRRH.js.map +1 -0
- package/dist/chunk-P3RZJ72N.js +783 -0
- package/dist/chunk-P3RZJ72N.js.map +1 -0
- package/dist/chunk-VCSB47AK.js +116 -0
- package/dist/chunk-VCSB47AK.js.map +1 -0
- package/dist/client.d.ts +15 -1
- package/dist/client.js +6 -133
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +122 -13
- package/dist/index.js +6 -4
- package/dist/mcp/client.d.ts +783 -0
- package/dist/mcp/client.js +9 -0
- package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
- package/dist/mcp/do-oauth-client-provider.js +7 -0
- package/dist/mcp/do-oauth-client-provider.js.map +1 -0
- package/dist/mcp/index.d.ts +84 -0
- package/dist/mcp/index.js +782 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/react.d.ts +85 -5
- package/dist/react.js +48 -29
- package/dist/react.js.map +1 -1
- package/dist/schedule.js +0 -2
- package/dist/schedule.js.map +1 -1
- package/dist/serializable.d.ts +32 -0
- package/dist/serializable.js +1 -0
- package/dist/serializable.js.map +1 -0
- package/package.json +36 -8
- package/src/index.ts +490 -126
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-X6BBKLSC.js +0 -568
- package/dist/chunk-X6BBKLSC.js.map +0 -1
- package/dist/mcp.d.ts +0 -58
- package/dist/mcp.js +0 -945
- package/dist/mcp.js.map +0 -1
- /package/dist/{chunk-HMLY7DHA.js.map → mcp/client.js.map} +0 -0
|
@@ -0,0 +1,783 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MCPClientManager
|
|
3
|
+
} from "./chunk-OYJXQRRH.js";
|
|
4
|
+
import {
|
|
5
|
+
DurableObjectOAuthClientProvider
|
|
6
|
+
} from "./chunk-BZXOAZUX.js";
|
|
7
|
+
import {
|
|
8
|
+
camelCaseToKebabCase
|
|
9
|
+
} from "./chunk-VCSB47AK.js";
|
|
10
|
+
|
|
11
|
+
// src/index.ts
|
|
12
|
+
import {
|
|
13
|
+
Server,
|
|
14
|
+
getServerByName,
|
|
15
|
+
routePartykitRequest
|
|
16
|
+
} from "partyserver";
|
|
17
|
+
import { parseCronExpression } from "cron-schedule";
|
|
18
|
+
import { nanoid } from "nanoid";
|
|
19
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
20
|
+
function isRPCRequest(msg) {
|
|
21
|
+
return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "rpc" && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
|
|
22
|
+
}
|
|
23
|
+
function isStateUpdateMessage(msg) {
|
|
24
|
+
return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "cf_agent_state" && "state" in msg;
|
|
25
|
+
}
|
|
26
|
+
var callableMetadata = /* @__PURE__ */ new Map();
|
|
27
|
+
function unstable_callable(metadata = {}) {
|
|
28
|
+
return function callableDecorator(target, context) {
|
|
29
|
+
if (!callableMetadata.has(target)) {
|
|
30
|
+
callableMetadata.set(target, metadata);
|
|
31
|
+
}
|
|
32
|
+
return target;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function getNextCronTime(cron) {
|
|
36
|
+
const interval = parseCronExpression(cron);
|
|
37
|
+
return interval.getNextDate();
|
|
38
|
+
}
|
|
39
|
+
var STATE_ROW_ID = "cf_state_row_id";
|
|
40
|
+
var STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
41
|
+
var DEFAULT_STATE = {};
|
|
42
|
+
var agentContext = new AsyncLocalStorage();
|
|
43
|
+
function getCurrentAgent() {
|
|
44
|
+
const store = agentContext.getStore();
|
|
45
|
+
if (!store) {
|
|
46
|
+
return {
|
|
47
|
+
agent: void 0,
|
|
48
|
+
connection: void 0,
|
|
49
|
+
request: void 0
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
return store;
|
|
53
|
+
}
|
|
54
|
+
var Agent = class extends Server {
|
|
55
|
+
constructor(ctx, env) {
|
|
56
|
+
super(ctx, env);
|
|
57
|
+
this._state = DEFAULT_STATE;
|
|
58
|
+
this._ParentClass = Object.getPrototypeOf(this).constructor;
|
|
59
|
+
this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
60
|
+
/**
|
|
61
|
+
* Initial state for the Agent
|
|
62
|
+
* Override to provide default state values
|
|
63
|
+
*/
|
|
64
|
+
this.initialState = DEFAULT_STATE;
|
|
65
|
+
/**
|
|
66
|
+
* Method called when an alarm fires.
|
|
67
|
+
* Executes any scheduled tasks that are due.
|
|
68
|
+
*
|
|
69
|
+
* @remarks
|
|
70
|
+
* To schedule a task, please use the `this.schedule` method instead.
|
|
71
|
+
* See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
|
|
72
|
+
*/
|
|
73
|
+
this.alarm = async () => {
|
|
74
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
75
|
+
const result = this.sql`
|
|
76
|
+
SELECT * FROM cf_agents_schedules WHERE time <= ${now}
|
|
77
|
+
`;
|
|
78
|
+
for (const row of result || []) {
|
|
79
|
+
const callback = this[row.callback];
|
|
80
|
+
if (!callback) {
|
|
81
|
+
console.error(`callback ${row.callback} not found`);
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
await agentContext.run(
|
|
85
|
+
{ agent: this, connection: void 0, request: void 0 },
|
|
86
|
+
async () => {
|
|
87
|
+
try {
|
|
88
|
+
await callback.bind(this)(JSON.parse(row.payload), row);
|
|
89
|
+
} catch (e) {
|
|
90
|
+
console.error(`error executing callback "${row.callback}"`, e);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
);
|
|
94
|
+
if (row.type === "cron") {
|
|
95
|
+
const nextExecutionTime = getNextCronTime(row.cron);
|
|
96
|
+
const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
|
|
97
|
+
this.sql`
|
|
98
|
+
UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
|
|
99
|
+
`;
|
|
100
|
+
} else {
|
|
101
|
+
this.sql`
|
|
102
|
+
DELETE FROM cf_agents_schedules WHERE id = ${row.id}
|
|
103
|
+
`;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
await this._scheduleNextAlarm();
|
|
107
|
+
};
|
|
108
|
+
this.sql`
|
|
109
|
+
CREATE TABLE IF NOT EXISTS cf_agents_state (
|
|
110
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
111
|
+
state TEXT
|
|
112
|
+
)
|
|
113
|
+
`;
|
|
114
|
+
void this.ctx.blockConcurrencyWhile(async () => {
|
|
115
|
+
return this._tryCatch(async () => {
|
|
116
|
+
this.sql`
|
|
117
|
+
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
118
|
+
id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
|
|
119
|
+
callback TEXT,
|
|
120
|
+
payload TEXT,
|
|
121
|
+
type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
|
|
122
|
+
time INTEGER,
|
|
123
|
+
delayInSeconds INTEGER,
|
|
124
|
+
cron TEXT,
|
|
125
|
+
created_at INTEGER DEFAULT (unixepoch())
|
|
126
|
+
)
|
|
127
|
+
`;
|
|
128
|
+
await this.alarm();
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
this.sql`
|
|
132
|
+
CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
|
|
133
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
134
|
+
name TEXT NOT NULL,
|
|
135
|
+
server_url TEXT NOT NULL,
|
|
136
|
+
callback_url TEXT NOT NULL,
|
|
137
|
+
client_id TEXT,
|
|
138
|
+
auth_url TEXT,
|
|
139
|
+
server_options TEXT
|
|
140
|
+
)
|
|
141
|
+
`;
|
|
142
|
+
const _onRequest = this.onRequest.bind(this);
|
|
143
|
+
this.onRequest = (request) => {
|
|
144
|
+
return agentContext.run(
|
|
145
|
+
{ agent: this, connection: void 0, request },
|
|
146
|
+
async () => {
|
|
147
|
+
if (this.mcp.isCallbackRequest(request)) {
|
|
148
|
+
await this.mcp.handleCallbackRequest(request);
|
|
149
|
+
this.broadcast(
|
|
150
|
+
JSON.stringify({
|
|
151
|
+
type: "cf_agent_mcp_servers",
|
|
152
|
+
mcp: this.getMcpServers()
|
|
153
|
+
})
|
|
154
|
+
);
|
|
155
|
+
return new Response("<script>window.close();</script>", {
|
|
156
|
+
status: 200,
|
|
157
|
+
headers: { "content-type": "text/html" }
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
return this._tryCatch(() => _onRequest(request));
|
|
161
|
+
}
|
|
162
|
+
);
|
|
163
|
+
};
|
|
164
|
+
const _onMessage = this.onMessage.bind(this);
|
|
165
|
+
this.onMessage = async (connection, message) => {
|
|
166
|
+
return agentContext.run(
|
|
167
|
+
{ agent: this, connection, request: void 0 },
|
|
168
|
+
async () => {
|
|
169
|
+
if (typeof message !== "string") {
|
|
170
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
171
|
+
}
|
|
172
|
+
let parsed;
|
|
173
|
+
try {
|
|
174
|
+
parsed = JSON.parse(message);
|
|
175
|
+
} catch (e) {
|
|
176
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
177
|
+
}
|
|
178
|
+
if (isStateUpdateMessage(parsed)) {
|
|
179
|
+
this._setStateInternal(parsed.state, connection);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (isRPCRequest(parsed)) {
|
|
183
|
+
try {
|
|
184
|
+
const { id, method, args } = parsed;
|
|
185
|
+
const methodFn = this[method];
|
|
186
|
+
if (typeof methodFn !== "function") {
|
|
187
|
+
throw new Error(`Method ${method} does not exist`);
|
|
188
|
+
}
|
|
189
|
+
if (!this._isCallable(method)) {
|
|
190
|
+
throw new Error(`Method ${method} is not callable`);
|
|
191
|
+
}
|
|
192
|
+
const metadata = callableMetadata.get(methodFn);
|
|
193
|
+
if (metadata?.streaming) {
|
|
194
|
+
const stream = new StreamingResponse(connection, id);
|
|
195
|
+
await methodFn.apply(this, [stream, ...args]);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const result = await methodFn.apply(this, args);
|
|
199
|
+
const response = {
|
|
200
|
+
type: "rpc",
|
|
201
|
+
id,
|
|
202
|
+
success: true,
|
|
203
|
+
result,
|
|
204
|
+
done: true
|
|
205
|
+
};
|
|
206
|
+
connection.send(JSON.stringify(response));
|
|
207
|
+
} catch (e) {
|
|
208
|
+
const response = {
|
|
209
|
+
type: "rpc",
|
|
210
|
+
id: parsed.id,
|
|
211
|
+
success: false,
|
|
212
|
+
error: e instanceof Error ? e.message : "Unknown error occurred"
|
|
213
|
+
};
|
|
214
|
+
connection.send(JSON.stringify(response));
|
|
215
|
+
console.error("RPC error:", e);
|
|
216
|
+
}
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
220
|
+
}
|
|
221
|
+
);
|
|
222
|
+
};
|
|
223
|
+
const _onConnect = this.onConnect.bind(this);
|
|
224
|
+
this.onConnect = (connection, ctx2) => {
|
|
225
|
+
return agentContext.run(
|
|
226
|
+
{ agent: this, connection, request: ctx2.request },
|
|
227
|
+
async () => {
|
|
228
|
+
setTimeout(() => {
|
|
229
|
+
if (this.state) {
|
|
230
|
+
connection.send(
|
|
231
|
+
JSON.stringify({
|
|
232
|
+
type: "cf_agent_state",
|
|
233
|
+
state: this.state
|
|
234
|
+
})
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
connection.send(
|
|
238
|
+
JSON.stringify({
|
|
239
|
+
type: "cf_agent_mcp_servers",
|
|
240
|
+
mcp: this.getMcpServers()
|
|
241
|
+
})
|
|
242
|
+
);
|
|
243
|
+
return this._tryCatch(() => _onConnect(connection, ctx2));
|
|
244
|
+
}, 20);
|
|
245
|
+
}
|
|
246
|
+
);
|
|
247
|
+
};
|
|
248
|
+
const _onStart = this.onStart.bind(this);
|
|
249
|
+
this.onStart = async () => {
|
|
250
|
+
return agentContext.run(
|
|
251
|
+
{ agent: this, connection: void 0, request: void 0 },
|
|
252
|
+
async () => {
|
|
253
|
+
const servers = this.sql`
|
|
254
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
255
|
+
`;
|
|
256
|
+
await Promise.allSettled(
|
|
257
|
+
servers.filter((server) => server.auth_url === null).map((server) => {
|
|
258
|
+
return this._connectToMcpServerInternal(
|
|
259
|
+
server.name,
|
|
260
|
+
server.server_url,
|
|
261
|
+
server.callback_url,
|
|
262
|
+
server.server_options ? JSON.parse(server.server_options) : void 0,
|
|
263
|
+
{
|
|
264
|
+
id: server.id,
|
|
265
|
+
oauthClientId: server.client_id ?? void 0
|
|
266
|
+
}
|
|
267
|
+
);
|
|
268
|
+
})
|
|
269
|
+
);
|
|
270
|
+
this.broadcast(
|
|
271
|
+
JSON.stringify({
|
|
272
|
+
type: "cf_agent_mcp_servers",
|
|
273
|
+
mcp: this.getMcpServers()
|
|
274
|
+
})
|
|
275
|
+
);
|
|
276
|
+
await this._tryCatch(() => _onStart());
|
|
277
|
+
}
|
|
278
|
+
);
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Current state of the Agent
|
|
283
|
+
*/
|
|
284
|
+
get state() {
|
|
285
|
+
if (this._state !== DEFAULT_STATE) {
|
|
286
|
+
return this._state;
|
|
287
|
+
}
|
|
288
|
+
const wasChanged = this.sql`
|
|
289
|
+
SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
|
|
290
|
+
`;
|
|
291
|
+
const result = this.sql`
|
|
292
|
+
SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
|
|
293
|
+
`;
|
|
294
|
+
if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
|
|
295
|
+
result[0]?.state) {
|
|
296
|
+
const state = result[0]?.state;
|
|
297
|
+
this._state = JSON.parse(state);
|
|
298
|
+
return this._state;
|
|
299
|
+
}
|
|
300
|
+
if (this.initialState === DEFAULT_STATE) {
|
|
301
|
+
return void 0;
|
|
302
|
+
}
|
|
303
|
+
this.setState(this.initialState);
|
|
304
|
+
return this.initialState;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Execute SQL queries against the Agent's database
|
|
308
|
+
* @template T Type of the returned rows
|
|
309
|
+
* @param strings SQL query template strings
|
|
310
|
+
* @param values Values to be inserted into the query
|
|
311
|
+
* @returns Array of query results
|
|
312
|
+
*/
|
|
313
|
+
sql(strings, ...values) {
|
|
314
|
+
let query = "";
|
|
315
|
+
try {
|
|
316
|
+
query = strings.reduce(
|
|
317
|
+
(acc, str, i) => acc + str + (i < values.length ? "?" : ""),
|
|
318
|
+
""
|
|
319
|
+
);
|
|
320
|
+
return [...this.ctx.storage.sql.exec(query, ...values)];
|
|
321
|
+
} catch (e) {
|
|
322
|
+
console.error(`failed to execute sql query: ${query}`, e);
|
|
323
|
+
throw this.onError(e);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
_setStateInternal(state, source = "server") {
|
|
327
|
+
this._state = state;
|
|
328
|
+
this.sql`
|
|
329
|
+
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
330
|
+
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
331
|
+
`;
|
|
332
|
+
this.sql`
|
|
333
|
+
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
334
|
+
VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
|
|
335
|
+
`;
|
|
336
|
+
this.broadcast(
|
|
337
|
+
JSON.stringify({
|
|
338
|
+
type: "cf_agent_state",
|
|
339
|
+
state
|
|
340
|
+
}),
|
|
341
|
+
source !== "server" ? [source.id] : []
|
|
342
|
+
);
|
|
343
|
+
return this._tryCatch(() => {
|
|
344
|
+
const { connection, request } = agentContext.getStore() || {};
|
|
345
|
+
return agentContext.run(
|
|
346
|
+
{ agent: this, connection, request },
|
|
347
|
+
async () => {
|
|
348
|
+
return this.onStateUpdate(state, source);
|
|
349
|
+
}
|
|
350
|
+
);
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Update the Agent's state
|
|
355
|
+
* @param state New state to set
|
|
356
|
+
*/
|
|
357
|
+
setState(state) {
|
|
358
|
+
this._setStateInternal(state, "server");
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Called when the Agent's state is updated
|
|
362
|
+
* @param state Updated state
|
|
363
|
+
* @param source Source of the state update ("server" or a client connection)
|
|
364
|
+
*/
|
|
365
|
+
onStateUpdate(state, source) {
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Called when the Agent receives an email
|
|
369
|
+
* @param email Email message to process
|
|
370
|
+
*/
|
|
371
|
+
onEmail(email) {
|
|
372
|
+
return agentContext.run(
|
|
373
|
+
{ agent: this, connection: void 0, request: void 0 },
|
|
374
|
+
async () => {
|
|
375
|
+
console.error("onEmail not implemented");
|
|
376
|
+
}
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
async _tryCatch(fn) {
|
|
380
|
+
try {
|
|
381
|
+
return await fn();
|
|
382
|
+
} catch (e) {
|
|
383
|
+
throw this.onError(e);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
onError(connectionOrError, error) {
|
|
387
|
+
let theError;
|
|
388
|
+
if (connectionOrError && error) {
|
|
389
|
+
theError = error;
|
|
390
|
+
console.error(
|
|
391
|
+
"Error on websocket connection:",
|
|
392
|
+
connectionOrError.id,
|
|
393
|
+
theError
|
|
394
|
+
);
|
|
395
|
+
console.error(
|
|
396
|
+
"Override onError(connection, error) to handle websocket connection errors"
|
|
397
|
+
);
|
|
398
|
+
} else {
|
|
399
|
+
theError = connectionOrError;
|
|
400
|
+
console.error("Error on server:", theError);
|
|
401
|
+
console.error("Override onError(error) to handle server errors");
|
|
402
|
+
}
|
|
403
|
+
throw theError;
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Render content (not implemented in base class)
|
|
407
|
+
*/
|
|
408
|
+
render() {
|
|
409
|
+
throw new Error("Not implemented");
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Schedule a task to be executed in the future
|
|
413
|
+
* @template T Type of the payload data
|
|
414
|
+
* @param when When to execute the task (Date, seconds delay, or cron expression)
|
|
415
|
+
* @param callback Name of the method to call
|
|
416
|
+
* @param payload Data to pass to the callback
|
|
417
|
+
* @returns Schedule object representing the scheduled task
|
|
418
|
+
*/
|
|
419
|
+
async schedule(when, callback, payload) {
|
|
420
|
+
const id = nanoid(9);
|
|
421
|
+
if (typeof callback !== "string") {
|
|
422
|
+
throw new Error("Callback must be a string");
|
|
423
|
+
}
|
|
424
|
+
if (typeof this[callback] !== "function") {
|
|
425
|
+
throw new Error(`this.${callback} is not a function`);
|
|
426
|
+
}
|
|
427
|
+
if (when instanceof Date) {
|
|
428
|
+
const timestamp = Math.floor(when.getTime() / 1e3);
|
|
429
|
+
this.sql`
|
|
430
|
+
INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
|
|
431
|
+
VALUES (${id}, ${callback}, ${JSON.stringify(
|
|
432
|
+
payload
|
|
433
|
+
)}, 'scheduled', ${timestamp})
|
|
434
|
+
`;
|
|
435
|
+
await this._scheduleNextAlarm();
|
|
436
|
+
return {
|
|
437
|
+
id,
|
|
438
|
+
callback,
|
|
439
|
+
payload,
|
|
440
|
+
time: timestamp,
|
|
441
|
+
type: "scheduled"
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
if (typeof when === "number") {
|
|
445
|
+
const time = new Date(Date.now() + when * 1e3);
|
|
446
|
+
const timestamp = Math.floor(time.getTime() / 1e3);
|
|
447
|
+
this.sql`
|
|
448
|
+
INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
|
|
449
|
+
VALUES (${id}, ${callback}, ${JSON.stringify(
|
|
450
|
+
payload
|
|
451
|
+
)}, 'delayed', ${when}, ${timestamp})
|
|
452
|
+
`;
|
|
453
|
+
await this._scheduleNextAlarm();
|
|
454
|
+
return {
|
|
455
|
+
id,
|
|
456
|
+
callback,
|
|
457
|
+
payload,
|
|
458
|
+
delayInSeconds: when,
|
|
459
|
+
time: timestamp,
|
|
460
|
+
type: "delayed"
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
if (typeof when === "string") {
|
|
464
|
+
const nextExecutionTime = getNextCronTime(when);
|
|
465
|
+
const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
|
|
466
|
+
this.sql`
|
|
467
|
+
INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
|
|
468
|
+
VALUES (${id}, ${callback}, ${JSON.stringify(
|
|
469
|
+
payload
|
|
470
|
+
)}, 'cron', ${when}, ${timestamp})
|
|
471
|
+
`;
|
|
472
|
+
await this._scheduleNextAlarm();
|
|
473
|
+
return {
|
|
474
|
+
id,
|
|
475
|
+
callback,
|
|
476
|
+
payload,
|
|
477
|
+
cron: when,
|
|
478
|
+
time: timestamp,
|
|
479
|
+
type: "cron"
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
throw new Error("Invalid schedule type");
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* Get a scheduled task by ID
|
|
486
|
+
* @template T Type of the payload data
|
|
487
|
+
* @param id ID of the scheduled task
|
|
488
|
+
* @returns The Schedule object or undefined if not found
|
|
489
|
+
*/
|
|
490
|
+
async getSchedule(id) {
|
|
491
|
+
const result = this.sql`
|
|
492
|
+
SELECT * FROM cf_agents_schedules WHERE id = ${id}
|
|
493
|
+
`;
|
|
494
|
+
if (!result) {
|
|
495
|
+
console.error(`schedule ${id} not found`);
|
|
496
|
+
return void 0;
|
|
497
|
+
}
|
|
498
|
+
return { ...result[0], payload: JSON.parse(result[0].payload) };
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Get scheduled tasks matching the given criteria
|
|
502
|
+
* @template T Type of the payload data
|
|
503
|
+
* @param criteria Criteria to filter schedules
|
|
504
|
+
* @returns Array of matching Schedule objects
|
|
505
|
+
*/
|
|
506
|
+
getSchedules(criteria = {}) {
|
|
507
|
+
let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
|
|
508
|
+
const params = [];
|
|
509
|
+
if (criteria.id) {
|
|
510
|
+
query += " AND id = ?";
|
|
511
|
+
params.push(criteria.id);
|
|
512
|
+
}
|
|
513
|
+
if (criteria.type) {
|
|
514
|
+
query += " AND type = ?";
|
|
515
|
+
params.push(criteria.type);
|
|
516
|
+
}
|
|
517
|
+
if (criteria.timeRange) {
|
|
518
|
+
query += " AND time >= ? AND time <= ?";
|
|
519
|
+
const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
|
|
520
|
+
const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
|
|
521
|
+
params.push(
|
|
522
|
+
Math.floor(start.getTime() / 1e3),
|
|
523
|
+
Math.floor(end.getTime() / 1e3)
|
|
524
|
+
);
|
|
525
|
+
}
|
|
526
|
+
const result = this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
|
|
527
|
+
...row,
|
|
528
|
+
payload: JSON.parse(row.payload)
|
|
529
|
+
}));
|
|
530
|
+
return result;
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Cancel a scheduled task
|
|
534
|
+
* @param id ID of the task to cancel
|
|
535
|
+
* @returns true if the task was cancelled, false otherwise
|
|
536
|
+
*/
|
|
537
|
+
async cancelSchedule(id) {
|
|
538
|
+
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
539
|
+
await this._scheduleNextAlarm();
|
|
540
|
+
return true;
|
|
541
|
+
}
|
|
542
|
+
async _scheduleNextAlarm() {
|
|
543
|
+
const result = this.sql`
|
|
544
|
+
SELECT time FROM cf_agents_schedules
|
|
545
|
+
WHERE time > ${Math.floor(Date.now() / 1e3)}
|
|
546
|
+
ORDER BY time ASC
|
|
547
|
+
LIMIT 1
|
|
548
|
+
`;
|
|
549
|
+
if (!result) return;
|
|
550
|
+
if (result.length > 0 && "time" in result[0]) {
|
|
551
|
+
const nextTime = result[0].time * 1e3;
|
|
552
|
+
await this.ctx.storage.setAlarm(nextTime);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* Destroy the Agent, removing all state and scheduled tasks
|
|
557
|
+
*/
|
|
558
|
+
async destroy() {
|
|
559
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
560
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
561
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
562
|
+
await this.ctx.storage.deleteAlarm();
|
|
563
|
+
await this.ctx.storage.deleteAll();
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Get all methods marked as callable on this Agent
|
|
567
|
+
* @returns A map of method names to their metadata
|
|
568
|
+
*/
|
|
569
|
+
_isCallable(method) {
|
|
570
|
+
return callableMetadata.has(this[method]);
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Connect to a new MCP Server
|
|
574
|
+
*
|
|
575
|
+
* @param url MCP Server SSE URL
|
|
576
|
+
* @param callbackHost Base host for the agent, used for the redirect URI.
|
|
577
|
+
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
578
|
+
* @param options MCP client and transport (header) options
|
|
579
|
+
* @returns authUrl
|
|
580
|
+
*/
|
|
581
|
+
async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
|
|
582
|
+
const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
583
|
+
const result = await this._connectToMcpServerInternal(
|
|
584
|
+
serverName,
|
|
585
|
+
url,
|
|
586
|
+
callbackUrl,
|
|
587
|
+
options
|
|
588
|
+
);
|
|
589
|
+
this.broadcast(
|
|
590
|
+
JSON.stringify({
|
|
591
|
+
type: "cf_agent_mcp_servers",
|
|
592
|
+
mcp: this.getMcpServers()
|
|
593
|
+
})
|
|
594
|
+
);
|
|
595
|
+
return result;
|
|
596
|
+
}
|
|
597
|
+
async _connectToMcpServerInternal(serverName, url, callbackUrl, options, reconnect) {
|
|
598
|
+
const authProvider = new DurableObjectOAuthClientProvider(
|
|
599
|
+
this.ctx.storage,
|
|
600
|
+
this.name,
|
|
601
|
+
callbackUrl
|
|
602
|
+
);
|
|
603
|
+
if (reconnect) {
|
|
604
|
+
authProvider.serverId = reconnect.id;
|
|
605
|
+
if (reconnect.oauthClientId) {
|
|
606
|
+
authProvider.clientId = reconnect.oauthClientId;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
let headerTransportOpts = {};
|
|
610
|
+
if (options?.transport?.headers) {
|
|
611
|
+
headerTransportOpts = {
|
|
612
|
+
eventSourceInit: {
|
|
613
|
+
fetch: (url2, init) => fetch(url2, {
|
|
614
|
+
...init,
|
|
615
|
+
headers: options?.transport?.headers
|
|
616
|
+
})
|
|
617
|
+
},
|
|
618
|
+
requestInit: {
|
|
619
|
+
headers: options?.transport?.headers
|
|
620
|
+
}
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
const { id, authUrl, clientId } = await this.mcp.connect(url, {
|
|
624
|
+
reconnect,
|
|
625
|
+
transport: {
|
|
626
|
+
...headerTransportOpts,
|
|
627
|
+
authProvider
|
|
628
|
+
},
|
|
629
|
+
client: options?.client
|
|
630
|
+
});
|
|
631
|
+
this.sql`
|
|
632
|
+
INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
633
|
+
VALUES (
|
|
634
|
+
${id},
|
|
635
|
+
${serverName},
|
|
636
|
+
${url},
|
|
637
|
+
${clientId ?? null},
|
|
638
|
+
${authUrl ?? null},
|
|
639
|
+
${callbackUrl},
|
|
640
|
+
${options ? JSON.stringify(options) : null}
|
|
641
|
+
);
|
|
642
|
+
`;
|
|
643
|
+
return {
|
|
644
|
+
id,
|
|
645
|
+
authUrl
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
async removeMcpServer(id) {
|
|
649
|
+
this.mcp.closeConnection(id);
|
|
650
|
+
this.sql`
|
|
651
|
+
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
652
|
+
`;
|
|
653
|
+
this.broadcast(
|
|
654
|
+
JSON.stringify({
|
|
655
|
+
type: "cf_agent_mcp_servers",
|
|
656
|
+
mcp: this.getMcpServers()
|
|
657
|
+
})
|
|
658
|
+
);
|
|
659
|
+
}
|
|
660
|
+
getMcpServers() {
|
|
661
|
+
const mcpState = {
|
|
662
|
+
servers: {},
|
|
663
|
+
tools: this.mcp.listTools(),
|
|
664
|
+
prompts: this.mcp.listPrompts(),
|
|
665
|
+
resources: this.mcp.listResources()
|
|
666
|
+
};
|
|
667
|
+
const servers = this.sql`
|
|
668
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
669
|
+
`;
|
|
670
|
+
for (const server of servers) {
|
|
671
|
+
mcpState.servers[server.id] = {
|
|
672
|
+
name: server.name,
|
|
673
|
+
server_url: server.server_url,
|
|
674
|
+
auth_url: server.auth_url,
|
|
675
|
+
state: this.mcp.mcpConnections[server.id].connectionState,
|
|
676
|
+
instructions: this.mcp.mcpConnections[server.id].instructions ?? null,
|
|
677
|
+
capabilities: this.mcp.mcpConnections[server.id].serverCapabilities ?? null
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
return mcpState;
|
|
681
|
+
}
|
|
682
|
+
};
|
|
683
|
+
/**
|
|
684
|
+
* Agent configuration options
|
|
685
|
+
*/
|
|
686
|
+
Agent.options = {
|
|
687
|
+
/** Whether the Agent should hibernate when inactive */
|
|
688
|
+
hibernate: true
|
|
689
|
+
// default to hibernate
|
|
690
|
+
};
|
|
691
|
+
async function routeAgentRequest(request, env, options) {
|
|
692
|
+
const corsHeaders = options?.cors === true ? {
|
|
693
|
+
"Access-Control-Allow-Origin": "*",
|
|
694
|
+
"Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
|
|
695
|
+
"Access-Control-Allow-Credentials": "true",
|
|
696
|
+
"Access-Control-Max-Age": "86400"
|
|
697
|
+
} : options?.cors;
|
|
698
|
+
if (request.method === "OPTIONS") {
|
|
699
|
+
if (corsHeaders) {
|
|
700
|
+
return new Response(null, {
|
|
701
|
+
headers: corsHeaders
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
console.warn(
|
|
705
|
+
"Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
|
|
706
|
+
);
|
|
707
|
+
}
|
|
708
|
+
let response = await routePartykitRequest(
|
|
709
|
+
request,
|
|
710
|
+
env,
|
|
711
|
+
{
|
|
712
|
+
prefix: "agents",
|
|
713
|
+
...options
|
|
714
|
+
}
|
|
715
|
+
);
|
|
716
|
+
if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
|
|
717
|
+
response = new Response(response.body, {
|
|
718
|
+
headers: {
|
|
719
|
+
...response.headers,
|
|
720
|
+
...corsHeaders
|
|
721
|
+
}
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
return response;
|
|
725
|
+
}
|
|
726
|
+
async function routeAgentEmail(email, env, options) {
|
|
727
|
+
}
|
|
728
|
+
async function getAgentByName(namespace, name, options) {
|
|
729
|
+
return getServerByName(namespace, name, options);
|
|
730
|
+
}
|
|
731
|
+
var StreamingResponse = class {
|
|
732
|
+
constructor(connection, id) {
|
|
733
|
+
this._closed = false;
|
|
734
|
+
this._connection = connection;
|
|
735
|
+
this._id = id;
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* Send a chunk of data to the client
|
|
739
|
+
* @param chunk The data to send
|
|
740
|
+
*/
|
|
741
|
+
send(chunk) {
|
|
742
|
+
if (this._closed) {
|
|
743
|
+
throw new Error("StreamingResponse is already closed");
|
|
744
|
+
}
|
|
745
|
+
const response = {
|
|
746
|
+
type: "rpc",
|
|
747
|
+
id: this._id,
|
|
748
|
+
success: true,
|
|
749
|
+
result: chunk,
|
|
750
|
+
done: false
|
|
751
|
+
};
|
|
752
|
+
this._connection.send(JSON.stringify(response));
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* End the stream and send the final chunk (if any)
|
|
756
|
+
* @param finalChunk Optional final chunk of data to send
|
|
757
|
+
*/
|
|
758
|
+
end(finalChunk) {
|
|
759
|
+
if (this._closed) {
|
|
760
|
+
throw new Error("StreamingResponse is already closed");
|
|
761
|
+
}
|
|
762
|
+
this._closed = true;
|
|
763
|
+
const response = {
|
|
764
|
+
type: "rpc",
|
|
765
|
+
id: this._id,
|
|
766
|
+
success: true,
|
|
767
|
+
result: finalChunk,
|
|
768
|
+
done: true
|
|
769
|
+
};
|
|
770
|
+
this._connection.send(JSON.stringify(response));
|
|
771
|
+
}
|
|
772
|
+
};
|
|
773
|
+
|
|
774
|
+
export {
|
|
775
|
+
unstable_callable,
|
|
776
|
+
getCurrentAgent,
|
|
777
|
+
Agent,
|
|
778
|
+
routeAgentRequest,
|
|
779
|
+
routeAgentEmail,
|
|
780
|
+
getAgentByName,
|
|
781
|
+
StreamingResponse
|
|
782
|
+
};
|
|
783
|
+
//# sourceMappingURL=chunk-P3RZJ72N.js.map
|