agents 0.0.0-4f3dfc7 → 0.0.0-54e1986
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 +12 -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-QSGN3REV.js +123 -0
- package/dist/chunk-QSGN3REV.js.map +1 -0
- package/dist/{chunk-X6BBKLSC.js → chunk-RIYR6FR6.js} +382 -173
- package/dist/chunk-RIYR6FR6.js.map +1 -0
- package/dist/chunk-Y67CHZBI.js +464 -0
- package/dist/chunk-Y67CHZBI.js.map +1 -0
- package/dist/client.d.ts +9 -1
- package/dist/client.js +6 -133
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +111 -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 +779 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/react.d.ts +14 -0
- package/dist/react.js +38 -29
- package/dist/react.js.map +1 -1
- package/dist/schedule.js +0 -2
- package/dist/schedule.js.map +1 -1
- package/package.json +36 -8
- package/src/index.ts +481 -126
- package/dist/chunk-HMLY7DHA.js +0 -16
- 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
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
} from "./chunk-
|
|
2
|
+
DurableObjectOAuthClientProvider
|
|
3
|
+
} from "./chunk-BZXOAZUX.js";
|
|
4
|
+
import {
|
|
5
|
+
camelCaseToKebabCase
|
|
6
|
+
} from "./chunk-QSGN3REV.js";
|
|
7
|
+
import {
|
|
8
|
+
MCPClientManager
|
|
9
|
+
} from "./chunk-Y67CHZBI.js";
|
|
7
10
|
|
|
8
11
|
// src/index.ts
|
|
9
12
|
import {
|
|
@@ -13,7 +16,7 @@ import {
|
|
|
13
16
|
} from "partyserver";
|
|
14
17
|
import { parseCronExpression } from "cron-schedule";
|
|
15
18
|
import { nanoid } from "nanoid";
|
|
16
|
-
import {
|
|
19
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
17
20
|
function isRPCRequest(msg) {
|
|
18
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);
|
|
19
22
|
}
|
|
@@ -29,8 +32,6 @@ function unstable_callable(metadata = {}) {
|
|
|
29
32
|
return target;
|
|
30
33
|
};
|
|
31
34
|
}
|
|
32
|
-
var WorkflowEntrypoint = class extends CFWorkflowEntrypoint {
|
|
33
|
-
};
|
|
34
35
|
function getNextCronTime(cron) {
|
|
35
36
|
const interval = parseCronExpression(cron);
|
|
36
37
|
return interval.getNextDate();
|
|
@@ -38,17 +39,72 @@ function getNextCronTime(cron) {
|
|
|
38
39
|
var STATE_ROW_ID = "cf_state_row_id";
|
|
39
40
|
var STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
40
41
|
var DEFAULT_STATE = {};
|
|
41
|
-
var
|
|
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
|
+
}
|
|
42
54
|
var Agent = class extends Server {
|
|
43
55
|
constructor(ctx, env) {
|
|
44
56
|
super(ctx, env);
|
|
45
|
-
|
|
46
|
-
|
|
57
|
+
this._state = DEFAULT_STATE;
|
|
58
|
+
this._ParentClass = Object.getPrototypeOf(this).constructor;
|
|
59
|
+
this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
47
60
|
/**
|
|
48
61
|
* Initial state for the Agent
|
|
49
62
|
* Override to provide default state values
|
|
50
63
|
*/
|
|
51
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
|
+
};
|
|
52
108
|
this.sql`
|
|
53
109
|
CREATE TABLE IF NOT EXISTS cf_agents_state (
|
|
54
110
|
id TEXT PRIMARY KEY NOT NULL,
|
|
@@ -56,7 +112,7 @@ var Agent = class extends Server {
|
|
|
56
112
|
)
|
|
57
113
|
`;
|
|
58
114
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
59
|
-
return
|
|
115
|
+
return this._tryCatch(async () => {
|
|
60
116
|
this.sql`
|
|
61
117
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
62
118
|
id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
|
|
@@ -72,81 +128,162 @@ var Agent = class extends Server {
|
|
|
72
128
|
await this.alarm();
|
|
73
129
|
});
|
|
74
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._getMcpServerStateInternal()
|
|
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
|
+
};
|
|
75
164
|
const _onMessage = this.onMessage.bind(this);
|
|
76
165
|
this.onMessage = async (connection, message) => {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
parsed = JSON.parse(message);
|
|
83
|
-
} catch (e) {
|
|
84
|
-
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
|
|
85
|
-
}
|
|
86
|
-
if (isStateUpdateMessage(parsed)) {
|
|
87
|
-
__privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, parsed.state, connection);
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
if (isRPCRequest(parsed)) {
|
|
91
|
-
try {
|
|
92
|
-
const { id, method, args } = parsed;
|
|
93
|
-
const methodFn = this[method];
|
|
94
|
-
if (typeof methodFn !== "function") {
|
|
95
|
-
throw new Error(`Method ${method} does not exist`);
|
|
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));
|
|
96
171
|
}
|
|
97
|
-
|
|
98
|
-
|
|
172
|
+
let parsed;
|
|
173
|
+
try {
|
|
174
|
+
parsed = JSON.parse(message);
|
|
175
|
+
} catch (e) {
|
|
176
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
99
177
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
const stream = new StreamingResponse(connection, id);
|
|
103
|
-
await methodFn.apply(this, [stream, ...args]);
|
|
178
|
+
if (isStateUpdateMessage(parsed)) {
|
|
179
|
+
this._setStateInternal(parsed.state, connection);
|
|
104
180
|
return;
|
|
105
181
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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));
|
|
124
220
|
}
|
|
125
|
-
|
|
126
|
-
}
|
|
127
|
-
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
|
|
221
|
+
);
|
|
128
222
|
};
|
|
129
223
|
const _onConnect = this.onConnect.bind(this);
|
|
130
224
|
this.onConnect = (connection, ctx2) => {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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._getMcpServerStateInternal()
|
|
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.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(
|
|
134
271
|
JSON.stringify({
|
|
135
|
-
type: "
|
|
136
|
-
|
|
272
|
+
type: "cf_agent_mcp_servers",
|
|
273
|
+
mcp: this._getMcpServerStateInternal()
|
|
137
274
|
})
|
|
138
275
|
);
|
|
276
|
+
await this._tryCatch(() => _onStart());
|
|
139
277
|
}
|
|
140
|
-
|
|
141
|
-
}, 20);
|
|
278
|
+
);
|
|
142
279
|
};
|
|
143
280
|
}
|
|
144
281
|
/**
|
|
145
282
|
* Current state of the Agent
|
|
146
283
|
*/
|
|
147
284
|
get state() {
|
|
148
|
-
if (
|
|
149
|
-
return
|
|
285
|
+
if (this._state !== DEFAULT_STATE) {
|
|
286
|
+
return this._state;
|
|
150
287
|
}
|
|
151
288
|
const wasChanged = this.sql`
|
|
152
289
|
SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
|
|
@@ -157,8 +294,8 @@ var Agent = class extends Server {
|
|
|
157
294
|
if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
|
|
158
295
|
result[0]?.state) {
|
|
159
296
|
const state = result[0]?.state;
|
|
160
|
-
|
|
161
|
-
return
|
|
297
|
+
this._state = JSON.parse(state);
|
|
298
|
+
return this._state;
|
|
162
299
|
}
|
|
163
300
|
if (this.initialState === DEFAULT_STATE) {
|
|
164
301
|
return void 0;
|
|
@@ -186,12 +323,39 @@ var Agent = class extends Server {
|
|
|
186
323
|
throw this.onError(e);
|
|
187
324
|
}
|
|
188
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
|
+
}
|
|
189
353
|
/**
|
|
190
354
|
* Update the Agent's state
|
|
191
355
|
* @param state New state to set
|
|
192
356
|
*/
|
|
193
357
|
setState(state) {
|
|
194
|
-
|
|
358
|
+
this._setStateInternal(state, "server");
|
|
195
359
|
}
|
|
196
360
|
/**
|
|
197
361
|
* Called when the Agent's state is updated
|
|
@@ -205,7 +369,19 @@ var Agent = class extends Server {
|
|
|
205
369
|
* @param email Email message to process
|
|
206
370
|
*/
|
|
207
371
|
onEmail(email) {
|
|
208
|
-
|
|
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
|
+
}
|
|
209
385
|
}
|
|
210
386
|
onError(connectionOrError, error) {
|
|
211
387
|
let theError;
|
|
@@ -256,7 +432,7 @@ var Agent = class extends Server {
|
|
|
256
432
|
payload
|
|
257
433
|
)}, 'scheduled', ${timestamp})
|
|
258
434
|
`;
|
|
259
|
-
await
|
|
435
|
+
await this._scheduleNextAlarm();
|
|
260
436
|
return {
|
|
261
437
|
id,
|
|
262
438
|
callback,
|
|
@@ -274,7 +450,7 @@ var Agent = class extends Server {
|
|
|
274
450
|
payload
|
|
275
451
|
)}, 'delayed', ${when}, ${timestamp})
|
|
276
452
|
`;
|
|
277
|
-
await
|
|
453
|
+
await this._scheduleNextAlarm();
|
|
278
454
|
return {
|
|
279
455
|
id,
|
|
280
456
|
callback,
|
|
@@ -293,7 +469,7 @@ var Agent = class extends Server {
|
|
|
293
469
|
payload
|
|
294
470
|
)}, 'cron', ${when}, ${timestamp})
|
|
295
471
|
`;
|
|
296
|
-
await
|
|
472
|
+
await this._scheduleNextAlarm();
|
|
297
473
|
return {
|
|
298
474
|
id,
|
|
299
475
|
callback,
|
|
@@ -334,10 +510,6 @@ var Agent = class extends Server {
|
|
|
334
510
|
query += " AND id = ?";
|
|
335
511
|
params.push(criteria.id);
|
|
336
512
|
}
|
|
337
|
-
if (criteria.description) {
|
|
338
|
-
query += " AND description = ?";
|
|
339
|
-
params.push(criteria.description);
|
|
340
|
-
}
|
|
341
513
|
if (criteria.type) {
|
|
342
514
|
query += " AND type = ?";
|
|
343
515
|
params.push(criteria.type);
|
|
@@ -364,42 +536,21 @@ var Agent = class extends Server {
|
|
|
364
536
|
*/
|
|
365
537
|
async cancelSchedule(id) {
|
|
366
538
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
367
|
-
await
|
|
539
|
+
await this._scheduleNextAlarm();
|
|
368
540
|
return true;
|
|
369
541
|
}
|
|
370
|
-
|
|
371
|
-
* Method called when an alarm fires
|
|
372
|
-
* Executes any scheduled tasks that are due
|
|
373
|
-
*/
|
|
374
|
-
async alarm() {
|
|
375
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
542
|
+
async _scheduleNextAlarm() {
|
|
376
543
|
const result = this.sql`
|
|
377
|
-
SELECT
|
|
544
|
+
SELECT time FROM cf_agents_schedules
|
|
545
|
+
WHERE time > ${Math.floor(Date.now() / 1e3)}
|
|
546
|
+
ORDER BY time ASC
|
|
547
|
+
LIMIT 1
|
|
378
548
|
`;
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
continue;
|
|
384
|
-
}
|
|
385
|
-
try {
|
|
386
|
-
await callback.bind(this)(JSON.parse(row.payload), row);
|
|
387
|
-
} catch (e) {
|
|
388
|
-
console.error(`error executing callback "${row.callback}"`, e);
|
|
389
|
-
}
|
|
390
|
-
if (row.type === "cron") {
|
|
391
|
-
const nextExecutionTime = getNextCronTime(row.cron);
|
|
392
|
-
const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
|
|
393
|
-
this.sql`
|
|
394
|
-
UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
|
|
395
|
-
`;
|
|
396
|
-
} else {
|
|
397
|
-
this.sql`
|
|
398
|
-
DELETE FROM cf_agents_schedules WHERE id = ${row.id}
|
|
399
|
-
`;
|
|
400
|
-
}
|
|
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);
|
|
401
553
|
}
|
|
402
|
-
await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
|
|
403
554
|
}
|
|
404
555
|
/**
|
|
405
556
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
@@ -407,57 +558,121 @@ var Agent = class extends Server {
|
|
|
407
558
|
async destroy() {
|
|
408
559
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
409
560
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
561
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
410
562
|
await this.ctx.storage.deleteAlarm();
|
|
411
563
|
await this.ctx.storage.deleteAll();
|
|
412
564
|
}
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
_Agent_instances = new WeakSet();
|
|
416
|
-
setStateInternal_fn = function(state, source = "server") {
|
|
417
|
-
__privateSet(this, _state, state);
|
|
418
|
-
this.sql`
|
|
419
|
-
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
420
|
-
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
421
|
-
`;
|
|
422
|
-
this.sql`
|
|
423
|
-
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
424
|
-
VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
|
|
425
|
-
`;
|
|
426
|
-
this.broadcast(
|
|
427
|
-
JSON.stringify({
|
|
428
|
-
type: "cf_agent_state",
|
|
429
|
-
state
|
|
430
|
-
}),
|
|
431
|
-
source !== "server" ? [source.id] : []
|
|
432
|
-
);
|
|
433
|
-
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => this.onStateUpdate(state, source));
|
|
434
|
-
};
|
|
435
|
-
tryCatch_fn = async function(fn) {
|
|
436
|
-
try {
|
|
437
|
-
return await fn();
|
|
438
|
-
} catch (e) {
|
|
439
|
-
throw this.onError(e);
|
|
565
|
+
_isCallable(method) {
|
|
566
|
+
return callableMetadata.has(this[method]);
|
|
440
567
|
}
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
568
|
+
/**
|
|
569
|
+
* Connect to a new MCP Server
|
|
570
|
+
*
|
|
571
|
+
* @param url MCP Server SSE URL
|
|
572
|
+
* @param callbackHost Base host for the agent, used for the redirect URI.
|
|
573
|
+
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
574
|
+
* @param options MCP client and transport (header) options
|
|
575
|
+
* @returns authUrl
|
|
576
|
+
*/
|
|
577
|
+
async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
|
|
578
|
+
const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
579
|
+
const result = await this._connectToMcpServerInternal(
|
|
580
|
+
serverName,
|
|
581
|
+
url,
|
|
582
|
+
callbackUrl,
|
|
583
|
+
options
|
|
584
|
+
);
|
|
585
|
+
this.broadcast(
|
|
586
|
+
JSON.stringify({
|
|
587
|
+
type: "cf_agent_mcp_servers",
|
|
588
|
+
mcp: this._getMcpServerStateInternal()
|
|
589
|
+
})
|
|
590
|
+
);
|
|
591
|
+
return result;
|
|
592
|
+
}
|
|
593
|
+
async _connectToMcpServerInternal(serverName, url, callbackUrl, options, reconnect) {
|
|
594
|
+
const authProvider = new DurableObjectOAuthClientProvider(
|
|
595
|
+
this.ctx.storage,
|
|
596
|
+
this.name,
|
|
597
|
+
callbackUrl
|
|
598
|
+
);
|
|
599
|
+
if (reconnect) {
|
|
600
|
+
authProvider.serverId = reconnect.id;
|
|
601
|
+
if (reconnect.oauthClientId) {
|
|
602
|
+
authProvider.clientId = reconnect.oauthClientId;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
let headerTransportOpts = {};
|
|
606
|
+
if (options?.transport?.headers) {
|
|
607
|
+
headerTransportOpts = {
|
|
608
|
+
eventSourceInit: {
|
|
609
|
+
fetch: (url2, init) => fetch(url2, {
|
|
610
|
+
...init,
|
|
611
|
+
headers: options?.transport?.headers
|
|
612
|
+
})
|
|
613
|
+
},
|
|
614
|
+
requestInit: {
|
|
615
|
+
headers: options?.transport?.headers
|
|
616
|
+
}
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
const { id, authUrl, clientId } = await this.mcp.connect(url, {
|
|
620
|
+
reconnect,
|
|
621
|
+
transport: {
|
|
622
|
+
...headerTransportOpts,
|
|
623
|
+
authProvider
|
|
624
|
+
},
|
|
625
|
+
client: options?.client
|
|
626
|
+
});
|
|
627
|
+
this.sql`
|
|
628
|
+
INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
629
|
+
VALUES (
|
|
630
|
+
${id},
|
|
631
|
+
${serverName},
|
|
632
|
+
${url},
|
|
633
|
+
${clientId ?? null},
|
|
634
|
+
${authUrl ?? null},
|
|
635
|
+
${callbackUrl},
|
|
636
|
+
${options ? JSON.stringify(options) : null}
|
|
637
|
+
);
|
|
448
638
|
`;
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
639
|
+
return {
|
|
640
|
+
id,
|
|
641
|
+
authUrl
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
async removeMcpServer(id) {
|
|
645
|
+
this.mcp.closeConnection(id);
|
|
646
|
+
this.sql`
|
|
647
|
+
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
648
|
+
`;
|
|
649
|
+
this.broadcast(
|
|
650
|
+
JSON.stringify({
|
|
651
|
+
type: "cf_agent_mcp_servers",
|
|
652
|
+
mcp: this._getMcpServerStateInternal()
|
|
653
|
+
})
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
_getMcpServerStateInternal() {
|
|
657
|
+
const mcpState = {
|
|
658
|
+
servers: {},
|
|
659
|
+
tools: this.mcp.listTools(),
|
|
660
|
+
prompts: this.mcp.listPrompts(),
|
|
661
|
+
resources: this.mcp.listResources()
|
|
662
|
+
};
|
|
663
|
+
const servers = this.sql`
|
|
664
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
665
|
+
`;
|
|
666
|
+
for (const server of servers) {
|
|
667
|
+
mcpState.servers[server.id] = {
|
|
668
|
+
name: server.name,
|
|
669
|
+
server_url: server.server_url,
|
|
670
|
+
auth_url: server.auth_url,
|
|
671
|
+
state: this.mcp.mcpConnections[server.id].connectionState
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
return mcpState;
|
|
453
675
|
}
|
|
454
|
-
};
|
|
455
|
-
/**
|
|
456
|
-
* Get all methods marked as callable on this Agent
|
|
457
|
-
* @returns A map of method names to their metadata
|
|
458
|
-
*/
|
|
459
|
-
isCallable_fn = function(method) {
|
|
460
|
-
return callableMetadata.has(this[method]);
|
|
461
676
|
};
|
|
462
677
|
/**
|
|
463
678
|
* Agent configuration options
|
|
@@ -504,65 +719,59 @@ async function routeAgentRequest(request, env, options) {
|
|
|
504
719
|
}
|
|
505
720
|
async function routeAgentEmail(email, env, options) {
|
|
506
721
|
}
|
|
507
|
-
function getAgentByName(namespace, name, options) {
|
|
722
|
+
async function getAgentByName(namespace, name, options) {
|
|
508
723
|
return getServerByName(namespace, name, options);
|
|
509
724
|
}
|
|
510
|
-
var _connection, _id, _closed;
|
|
511
725
|
var StreamingResponse = class {
|
|
512
726
|
constructor(connection, id) {
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
__privateSet(this, _connection, connection);
|
|
517
|
-
__privateSet(this, _id, id);
|
|
727
|
+
this._closed = false;
|
|
728
|
+
this._connection = connection;
|
|
729
|
+
this._id = id;
|
|
518
730
|
}
|
|
519
731
|
/**
|
|
520
732
|
* Send a chunk of data to the client
|
|
521
733
|
* @param chunk The data to send
|
|
522
734
|
*/
|
|
523
735
|
send(chunk) {
|
|
524
|
-
if (
|
|
736
|
+
if (this._closed) {
|
|
525
737
|
throw new Error("StreamingResponse is already closed");
|
|
526
738
|
}
|
|
527
739
|
const response = {
|
|
528
740
|
type: "rpc",
|
|
529
|
-
id:
|
|
741
|
+
id: this._id,
|
|
530
742
|
success: true,
|
|
531
743
|
result: chunk,
|
|
532
744
|
done: false
|
|
533
745
|
};
|
|
534
|
-
|
|
746
|
+
this._connection.send(JSON.stringify(response));
|
|
535
747
|
}
|
|
536
748
|
/**
|
|
537
749
|
* End the stream and send the final chunk (if any)
|
|
538
750
|
* @param finalChunk Optional final chunk of data to send
|
|
539
751
|
*/
|
|
540
752
|
end(finalChunk) {
|
|
541
|
-
if (
|
|
753
|
+
if (this._closed) {
|
|
542
754
|
throw new Error("StreamingResponse is already closed");
|
|
543
755
|
}
|
|
544
|
-
|
|
756
|
+
this._closed = true;
|
|
545
757
|
const response = {
|
|
546
758
|
type: "rpc",
|
|
547
|
-
id:
|
|
759
|
+
id: this._id,
|
|
548
760
|
success: true,
|
|
549
761
|
result: finalChunk,
|
|
550
762
|
done: true
|
|
551
763
|
};
|
|
552
|
-
|
|
764
|
+
this._connection.send(JSON.stringify(response));
|
|
553
765
|
}
|
|
554
766
|
};
|
|
555
|
-
_connection = new WeakMap();
|
|
556
|
-
_id = new WeakMap();
|
|
557
|
-
_closed = new WeakMap();
|
|
558
767
|
|
|
559
768
|
export {
|
|
560
769
|
unstable_callable,
|
|
561
|
-
|
|
770
|
+
getCurrentAgent,
|
|
562
771
|
Agent,
|
|
563
772
|
routeAgentRequest,
|
|
564
773
|
routeAgentEmail,
|
|
565
774
|
getAgentByName,
|
|
566
775
|
StreamingResponse
|
|
567
776
|
};
|
|
568
|
-
//# sourceMappingURL=chunk-
|
|
777
|
+
//# sourceMappingURL=chunk-RIYR6FR6.js.map
|