agents 0.0.0-75614c2 → 0.0.0-77368ff
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +127 -22
- package/dist/ai-chat-agent.d.ts +4 -2
- package/dist/ai-chat-agent.js +34 -4
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +4 -3
- package/dist/ai-react.js.map +1 -1
- package/dist/{chunk-NKZZ66QY.js → chunk-KUH345EY.js} +1 -1
- package/dist/chunk-KUH345EY.js.map +1 -0
- package/dist/{chunk-767EASBA.js → chunk-PVQZBKN7.js} +1 -1
- package/dist/chunk-PVQZBKN7.js.map +1 -0
- package/dist/{chunk-E3LCYPCB.js → chunk-UNG3FXYX.js} +58 -2
- package/dist/chunk-UNG3FXYX.js.map +1 -0
- package/dist/{chunk-CGWTDCBQ.js → chunk-Z2OUUKK4.js} +557 -78
- package/dist/chunk-Z2OUUKK4.js.map +1 -0
- package/dist/client.d.ts +2 -2
- package/dist/client.js +1 -1
- package/dist/index-BIJvkfYt.d.ts +614 -0
- package/dist/index.d.ts +33 -405
- package/dist/index.js +10 -4
- package/dist/mcp/client.d.ts +288 -17
- package/dist/mcp/client.js +1 -1
- package/dist/mcp/do-oauth-client-provider.js +1 -1
- package/dist/mcp/index.d.ts +28 -5
- package/dist/mcp/index.js +13 -8
- package/dist/mcp/index.js.map +1 -1
- package/dist/observability/index.d.ts +13 -0
- package/dist/observability/index.js +10 -0
- package/dist/observability/index.js.map +1 -0
- package/dist/react.d.ts +6 -5
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +4 -4
- package/dist/schedule.js.map +1 -1
- package/package.json +8 -3
- package/src/index.ts +757 -120
- package/dist/chunk-767EASBA.js.map +0 -1
- package/dist/chunk-CGWTDCBQ.js.map +0 -1
- package/dist/chunk-E3LCYPCB.js.map +0 -1
- package/dist/chunk-NKZZ66QY.js.map +0 -1
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
import {
|
|
2
2
|
MCPClientManager
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-UNG3FXYX.js";
|
|
4
4
|
import {
|
|
5
5
|
DurableObjectOAuthClientProvider
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-PVQZBKN7.js";
|
|
7
7
|
import {
|
|
8
8
|
camelCaseToKebabCase
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-KUH345EY.js";
|
|
10
10
|
|
|
11
11
|
// src/index.ts
|
|
12
12
|
import { AsyncLocalStorage } from "async_hooks";
|
|
13
13
|
import { parseCronExpression } from "cron-schedule";
|
|
14
14
|
import { nanoid } from "nanoid";
|
|
15
|
+
import { EmailMessage } from "cloudflare:email";
|
|
15
16
|
import {
|
|
17
|
+
Server,
|
|
16
18
|
getServerByName,
|
|
17
|
-
routePartykitRequest
|
|
18
|
-
Server
|
|
19
|
+
routePartykitRequest
|
|
19
20
|
} from "partyserver";
|
|
20
21
|
function isRPCRequest(msg) {
|
|
21
22
|
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);
|
|
@@ -46,12 +47,21 @@ function getCurrentAgent() {
|
|
|
46
47
|
return {
|
|
47
48
|
agent: void 0,
|
|
48
49
|
connection: void 0,
|
|
49
|
-
request: void 0
|
|
50
|
+
request: void 0,
|
|
51
|
+
email: void 0
|
|
50
52
|
};
|
|
51
53
|
}
|
|
52
54
|
return store;
|
|
53
55
|
}
|
|
54
|
-
|
|
56
|
+
function withAgentContext(method) {
|
|
57
|
+
return function(...args) {
|
|
58
|
+
const { connection, request, email } = getCurrentAgent();
|
|
59
|
+
return agentContext.run({ agent: this, connection, request, email }, () => {
|
|
60
|
+
return method.apply(this, args);
|
|
61
|
+
});
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
var _Agent = class _Agent extends Server {
|
|
55
65
|
constructor(ctx, env) {
|
|
56
66
|
super(ctx, env);
|
|
57
67
|
this._state = DEFAULT_STATE;
|
|
@@ -62,6 +72,11 @@ var Agent = class extends Server {
|
|
|
62
72
|
* Override to provide default state values
|
|
63
73
|
*/
|
|
64
74
|
this.initialState = DEFAULT_STATE;
|
|
75
|
+
/**
|
|
76
|
+
* The observability implementation to use for the Agent
|
|
77
|
+
*/
|
|
78
|
+
this.observability = genericObservability;
|
|
79
|
+
this._flushingQueue = false;
|
|
65
80
|
/**
|
|
66
81
|
* Method called when an alarm fires.
|
|
67
82
|
* Executes any scheduled tasks that are due.
|
|
@@ -75,42 +90,68 @@ var Agent = class extends Server {
|
|
|
75
90
|
const result = this.sql`
|
|
76
91
|
SELECT * FROM cf_agents_schedules WHERE time <= ${now}
|
|
77
92
|
`;
|
|
78
|
-
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
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
|
-
}
|
|
93
|
+
if (result && Array.isArray(result)) {
|
|
94
|
+
for (const row of result) {
|
|
95
|
+
const callback = this[row.callback];
|
|
96
|
+
if (!callback) {
|
|
97
|
+
console.error(`callback ${row.callback} not found`);
|
|
98
|
+
continue;
|
|
92
99
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
100
|
+
await agentContext.run(
|
|
101
|
+
{
|
|
102
|
+
agent: this,
|
|
103
|
+
connection: void 0,
|
|
104
|
+
request: void 0,
|
|
105
|
+
email: void 0
|
|
106
|
+
},
|
|
107
|
+
async () => {
|
|
108
|
+
try {
|
|
109
|
+
this.observability?.emit(
|
|
110
|
+
{
|
|
111
|
+
displayMessage: `Schedule ${row.id} executed`,
|
|
112
|
+
id: nanoid(),
|
|
113
|
+
payload: row,
|
|
114
|
+
timestamp: Date.now(),
|
|
115
|
+
type: "schedule:execute"
|
|
116
|
+
},
|
|
117
|
+
this.ctx
|
|
118
|
+
);
|
|
119
|
+
await callback.bind(this)(JSON.parse(row.payload), row);
|
|
120
|
+
} catch (e) {
|
|
121
|
+
console.error(`error executing callback "${row.callback}"`, e);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
);
|
|
125
|
+
if (row.type === "cron") {
|
|
126
|
+
const nextExecutionTime = getNextCronTime(row.cron);
|
|
127
|
+
const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
|
|
128
|
+
this.sql`
|
|
98
129
|
UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
|
|
99
130
|
`;
|
|
100
|
-
|
|
101
|
-
|
|
131
|
+
} else {
|
|
132
|
+
this.sql`
|
|
102
133
|
DELETE FROM cf_agents_schedules WHERE id = ${row.id}
|
|
103
134
|
`;
|
|
135
|
+
}
|
|
104
136
|
}
|
|
105
137
|
}
|
|
106
138
|
await this._scheduleNextAlarm();
|
|
107
139
|
};
|
|
140
|
+
this._autoWrapCustomMethods();
|
|
108
141
|
this.sql`
|
|
109
142
|
CREATE TABLE IF NOT EXISTS cf_agents_state (
|
|
110
143
|
id TEXT PRIMARY KEY NOT NULL,
|
|
111
144
|
state TEXT
|
|
112
145
|
)
|
|
113
146
|
`;
|
|
147
|
+
this.sql`
|
|
148
|
+
CREATE TABLE IF NOT EXISTS cf_agents_queues (
|
|
149
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
150
|
+
payload TEXT,
|
|
151
|
+
callback TEXT,
|
|
152
|
+
created_at INTEGER DEFAULT (unixepoch())
|
|
153
|
+
)
|
|
154
|
+
`;
|
|
114
155
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
115
156
|
return this._tryCatch(async () => {
|
|
116
157
|
this.sql`
|
|
@@ -142,7 +183,7 @@ var Agent = class extends Server {
|
|
|
142
183
|
const _onRequest = this.onRequest.bind(this);
|
|
143
184
|
this.onRequest = (request) => {
|
|
144
185
|
return agentContext.run(
|
|
145
|
-
{ agent: this, connection: void 0, request },
|
|
186
|
+
{ agent: this, connection: void 0, request, email: void 0 },
|
|
146
187
|
async () => {
|
|
147
188
|
if (this.mcp.isCallbackRequest(request)) {
|
|
148
189
|
await this.mcp.handleCallbackRequest(request);
|
|
@@ -164,7 +205,7 @@ var Agent = class extends Server {
|
|
|
164
205
|
const _onMessage = this.onMessage.bind(this);
|
|
165
206
|
this.onMessage = async (connection, message) => {
|
|
166
207
|
return agentContext.run(
|
|
167
|
-
{ agent: this, connection, request: void 0 },
|
|
208
|
+
{ agent: this, connection, request: void 0, email: void 0 },
|
|
168
209
|
async () => {
|
|
169
210
|
if (typeof message !== "string") {
|
|
170
211
|
return this._tryCatch(() => _onMessage(connection, message));
|
|
@@ -196,6 +237,21 @@ var Agent = class extends Server {
|
|
|
196
237
|
return;
|
|
197
238
|
}
|
|
198
239
|
const result = await methodFn.apply(this, args);
|
|
240
|
+
this.observability?.emit(
|
|
241
|
+
{
|
|
242
|
+
displayMessage: `RPC call to ${method}`,
|
|
243
|
+
id: nanoid(),
|
|
244
|
+
payload: {
|
|
245
|
+
args,
|
|
246
|
+
method,
|
|
247
|
+
streaming: metadata?.streaming,
|
|
248
|
+
success: true
|
|
249
|
+
},
|
|
250
|
+
timestamp: Date.now(),
|
|
251
|
+
type: "rpc"
|
|
252
|
+
},
|
|
253
|
+
this.ctx
|
|
254
|
+
);
|
|
199
255
|
const response = {
|
|
200
256
|
done: true,
|
|
201
257
|
id,
|
|
@@ -223,7 +279,7 @@ var Agent = class extends Server {
|
|
|
223
279
|
const _onConnect = this.onConnect.bind(this);
|
|
224
280
|
this.onConnect = (connection, ctx2) => {
|
|
225
281
|
return agentContext.run(
|
|
226
|
-
{ agent: this, connection, request: ctx2.request },
|
|
282
|
+
{ agent: this, connection, request: ctx2.request, email: void 0 },
|
|
227
283
|
async () => {
|
|
228
284
|
setTimeout(() => {
|
|
229
285
|
if (this.state) {
|
|
@@ -240,6 +296,18 @@ var Agent = class extends Server {
|
|
|
240
296
|
type: "cf_agent_mcp_servers"
|
|
241
297
|
})
|
|
242
298
|
);
|
|
299
|
+
this.observability?.emit(
|
|
300
|
+
{
|
|
301
|
+
displayMessage: "Connection established",
|
|
302
|
+
id: nanoid(),
|
|
303
|
+
payload: {
|
|
304
|
+
connectionId: connection.id
|
|
305
|
+
},
|
|
306
|
+
timestamp: Date.now(),
|
|
307
|
+
type: "connect"
|
|
308
|
+
},
|
|
309
|
+
this.ctx
|
|
310
|
+
);
|
|
243
311
|
return this._tryCatch(() => _onConnect(connection, ctx2));
|
|
244
312
|
}, 20);
|
|
245
313
|
}
|
|
@@ -248,32 +316,39 @@ var Agent = class extends Server {
|
|
|
248
316
|
const _onStart = this.onStart.bind(this);
|
|
249
317
|
this.onStart = async () => {
|
|
250
318
|
return agentContext.run(
|
|
251
|
-
{
|
|
319
|
+
{
|
|
320
|
+
agent: this,
|
|
321
|
+
connection: void 0,
|
|
322
|
+
request: void 0,
|
|
323
|
+
email: void 0
|
|
324
|
+
},
|
|
252
325
|
async () => {
|
|
253
326
|
const servers = this.sql`
|
|
254
327
|
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
255
328
|
`;
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
).then((_results) => {
|
|
270
|
-
this.broadcast(
|
|
271
|
-
JSON.stringify({
|
|
272
|
-
type: "cf_agent_mcp_servers",
|
|
273
|
-
mcp: this.getMcpServers()
|
|
329
|
+
if (servers && Array.isArray(servers) && servers.length > 0) {
|
|
330
|
+
Promise.allSettled(
|
|
331
|
+
servers.map((server) => {
|
|
332
|
+
return this._connectToMcpServerInternal(
|
|
333
|
+
server.name,
|
|
334
|
+
server.server_url,
|
|
335
|
+
server.callback_url,
|
|
336
|
+
server.server_options ? JSON.parse(server.server_options) : void 0,
|
|
337
|
+
{
|
|
338
|
+
id: server.id,
|
|
339
|
+
oauthClientId: server.client_id ?? void 0
|
|
340
|
+
}
|
|
341
|
+
);
|
|
274
342
|
})
|
|
275
|
-
)
|
|
276
|
-
|
|
343
|
+
).then((_results) => {
|
|
344
|
+
this.broadcast(
|
|
345
|
+
JSON.stringify({
|
|
346
|
+
mcp: this.getMcpServers(),
|
|
347
|
+
type: "cf_agent_mcp_servers"
|
|
348
|
+
})
|
|
349
|
+
);
|
|
350
|
+
});
|
|
351
|
+
}
|
|
277
352
|
await this._tryCatch(() => _onStart());
|
|
278
353
|
}
|
|
279
354
|
);
|
|
@@ -325,6 +400,7 @@ var Agent = class extends Server {
|
|
|
325
400
|
}
|
|
326
401
|
}
|
|
327
402
|
_setStateInternal(state, source = "server") {
|
|
403
|
+
const previousState = this._state;
|
|
328
404
|
this._state = state;
|
|
329
405
|
this.sql`
|
|
330
406
|
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
@@ -342,10 +418,23 @@ var Agent = class extends Server {
|
|
|
342
418
|
source !== "server" ? [source.id] : []
|
|
343
419
|
);
|
|
344
420
|
return this._tryCatch(() => {
|
|
345
|
-
const { connection, request } = agentContext.getStore() || {};
|
|
421
|
+
const { connection, request, email } = agentContext.getStore() || {};
|
|
346
422
|
return agentContext.run(
|
|
347
|
-
{ agent: this, connection, request },
|
|
423
|
+
{ agent: this, connection, request, email },
|
|
348
424
|
async () => {
|
|
425
|
+
this.observability?.emit(
|
|
426
|
+
{
|
|
427
|
+
displayMessage: "State updated",
|
|
428
|
+
id: nanoid(),
|
|
429
|
+
payload: {
|
|
430
|
+
previousState,
|
|
431
|
+
state
|
|
432
|
+
},
|
|
433
|
+
timestamp: Date.now(),
|
|
434
|
+
type: "state:update"
|
|
435
|
+
},
|
|
436
|
+
this.ctx
|
|
437
|
+
);
|
|
349
438
|
return this.onStateUpdate(state, source);
|
|
350
439
|
}
|
|
351
440
|
);
|
|
@@ -367,18 +456,67 @@ var Agent = class extends Server {
|
|
|
367
456
|
onStateUpdate(state, source) {
|
|
368
457
|
}
|
|
369
458
|
/**
|
|
370
|
-
* Called when the Agent receives an email
|
|
459
|
+
* Called when the Agent receives an email via routeAgentEmail()
|
|
460
|
+
* Override this method to handle incoming emails
|
|
371
461
|
* @param email Email message to process
|
|
372
462
|
*/
|
|
373
|
-
|
|
374
|
-
onEmail(email) {
|
|
463
|
+
async _onEmail(email) {
|
|
375
464
|
return agentContext.run(
|
|
376
|
-
{ agent: this, connection: void 0, request: void 0 },
|
|
465
|
+
{ agent: this, connection: void 0, request: void 0, email },
|
|
377
466
|
async () => {
|
|
378
|
-
|
|
467
|
+
if ("onEmail" in this && typeof this.onEmail === "function") {
|
|
468
|
+
return this._tryCatch(
|
|
469
|
+
() => this.onEmail(email)
|
|
470
|
+
);
|
|
471
|
+
} else {
|
|
472
|
+
console.log("Received email from:", email.from, "to:", email.to);
|
|
473
|
+
console.log("Subject:", email.headers.get("subject"));
|
|
474
|
+
console.log(
|
|
475
|
+
"Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
|
|
476
|
+
);
|
|
477
|
+
}
|
|
379
478
|
}
|
|
380
479
|
);
|
|
381
480
|
}
|
|
481
|
+
/**
|
|
482
|
+
* Reply to an email
|
|
483
|
+
* @param email The email to reply to
|
|
484
|
+
* @param options Options for the reply
|
|
485
|
+
* @returns void
|
|
486
|
+
*/
|
|
487
|
+
async replyToEmail(email, options) {
|
|
488
|
+
return this._tryCatch(async () => {
|
|
489
|
+
const agentName = camelCaseToKebabCase(this._ParentClass.name);
|
|
490
|
+
const agentId = this.name;
|
|
491
|
+
const { createMimeMessage } = await import("mimetext");
|
|
492
|
+
const msg = createMimeMessage();
|
|
493
|
+
msg.setSender({ addr: email.to, name: options.fromName });
|
|
494
|
+
msg.setRecipient(email.from);
|
|
495
|
+
msg.setSubject(
|
|
496
|
+
options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
|
|
497
|
+
);
|
|
498
|
+
msg.addMessage({
|
|
499
|
+
contentType: options.contentType || "text/plain",
|
|
500
|
+
data: options.body
|
|
501
|
+
});
|
|
502
|
+
const domain = email.from.split("@")[1];
|
|
503
|
+
const messageId = `<${agentId}@${domain}>`;
|
|
504
|
+
msg.setHeader("In-Reply-To", email.headers.get("Message-ID"));
|
|
505
|
+
msg.setHeader("Message-ID", messageId);
|
|
506
|
+
msg.setHeader("X-Agent-Name", agentName);
|
|
507
|
+
msg.setHeader("X-Agent-ID", agentId);
|
|
508
|
+
if (options.headers) {
|
|
509
|
+
for (const [key, value] of Object.entries(options.headers)) {
|
|
510
|
+
msg.setHeader(key, value);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
await email.reply({
|
|
514
|
+
from: email.to,
|
|
515
|
+
raw: msg.asRaw(),
|
|
516
|
+
to: email.from
|
|
517
|
+
});
|
|
518
|
+
});
|
|
519
|
+
}
|
|
382
520
|
async _tryCatch(fn) {
|
|
383
521
|
try {
|
|
384
522
|
return await fn();
|
|
@@ -386,6 +524,55 @@ var Agent = class extends Server {
|
|
|
386
524
|
throw this.onError(e);
|
|
387
525
|
}
|
|
388
526
|
}
|
|
527
|
+
/**
|
|
528
|
+
* Automatically wrap custom methods with agent context
|
|
529
|
+
* This ensures getCurrentAgent() works in all custom methods without decorators
|
|
530
|
+
*/
|
|
531
|
+
_autoWrapCustomMethods() {
|
|
532
|
+
const basePrototypes = [_Agent.prototype, Server.prototype];
|
|
533
|
+
const baseMethods = /* @__PURE__ */ new Set();
|
|
534
|
+
for (const baseProto of basePrototypes) {
|
|
535
|
+
let proto2 = baseProto;
|
|
536
|
+
while (proto2 && proto2 !== Object.prototype) {
|
|
537
|
+
const methodNames = Object.getOwnPropertyNames(proto2);
|
|
538
|
+
for (const methodName of methodNames) {
|
|
539
|
+
baseMethods.add(methodName);
|
|
540
|
+
}
|
|
541
|
+
proto2 = Object.getPrototypeOf(proto2);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
let proto = Object.getPrototypeOf(this);
|
|
545
|
+
let depth = 0;
|
|
546
|
+
while (proto && proto !== Object.prototype && depth < 10) {
|
|
547
|
+
const methodNames = Object.getOwnPropertyNames(proto);
|
|
548
|
+
for (const methodName of methodNames) {
|
|
549
|
+
if (baseMethods.has(methodName) || methodName.startsWith("_") || typeof this[methodName] !== "function") {
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
if (!baseMethods.has(methodName)) {
|
|
553
|
+
const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
|
|
554
|
+
if (descriptor && typeof descriptor.value === "function") {
|
|
555
|
+
const wrappedFunction = withAgentContext(
|
|
556
|
+
// biome-ignore lint/suspicious/noExplicitAny: I can't typescript
|
|
557
|
+
this[methodName]
|
|
558
|
+
// biome-ignore lint/suspicious/noExplicitAny: I can't typescript
|
|
559
|
+
);
|
|
560
|
+
if (this._isCallable(methodName)) {
|
|
561
|
+
callableMetadata.set(
|
|
562
|
+
wrappedFunction,
|
|
563
|
+
callableMetadata.get(
|
|
564
|
+
this[methodName]
|
|
565
|
+
)
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
this.constructor.prototype[methodName] = wrappedFunction;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
proto = Object.getPrototypeOf(proto);
|
|
573
|
+
depth++;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
389
576
|
onError(connectionOrError, error) {
|
|
390
577
|
let theError;
|
|
391
578
|
if (connectionOrError && error) {
|
|
@@ -411,6 +598,108 @@ var Agent = class extends Server {
|
|
|
411
598
|
render() {
|
|
412
599
|
throw new Error("Not implemented");
|
|
413
600
|
}
|
|
601
|
+
/**
|
|
602
|
+
* Queue a task to be executed in the future
|
|
603
|
+
* @param payload Payload to pass to the callback
|
|
604
|
+
* @param callback Name of the method to call
|
|
605
|
+
* @returns The ID of the queued task
|
|
606
|
+
*/
|
|
607
|
+
async queue(callback, payload) {
|
|
608
|
+
const id = nanoid(9);
|
|
609
|
+
if (typeof callback !== "string") {
|
|
610
|
+
throw new Error("Callback must be a string");
|
|
611
|
+
}
|
|
612
|
+
if (typeof this[callback] !== "function") {
|
|
613
|
+
throw new Error(`this.${callback} is not a function`);
|
|
614
|
+
}
|
|
615
|
+
this.sql`
|
|
616
|
+
INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
|
|
617
|
+
VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
|
|
618
|
+
`;
|
|
619
|
+
void this._flushQueue().catch((e) => {
|
|
620
|
+
console.error("Error flushing queue:", e);
|
|
621
|
+
});
|
|
622
|
+
return id;
|
|
623
|
+
}
|
|
624
|
+
async _flushQueue() {
|
|
625
|
+
if (this._flushingQueue) {
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
this._flushingQueue = true;
|
|
629
|
+
while (true) {
|
|
630
|
+
const result = this.sql`
|
|
631
|
+
SELECT * FROM cf_agents_queues
|
|
632
|
+
ORDER BY created_at ASC
|
|
633
|
+
`;
|
|
634
|
+
if (!result || result.length === 0) {
|
|
635
|
+
break;
|
|
636
|
+
}
|
|
637
|
+
for (const row of result || []) {
|
|
638
|
+
const callback = this[row.callback];
|
|
639
|
+
if (!callback) {
|
|
640
|
+
console.error(`callback ${row.callback} not found`);
|
|
641
|
+
continue;
|
|
642
|
+
}
|
|
643
|
+
const { connection, request, email } = agentContext.getStore() || {};
|
|
644
|
+
await agentContext.run(
|
|
645
|
+
{
|
|
646
|
+
agent: this,
|
|
647
|
+
connection,
|
|
648
|
+
request,
|
|
649
|
+
email
|
|
650
|
+
},
|
|
651
|
+
async () => {
|
|
652
|
+
await callback.bind(this)(JSON.parse(row.payload), row);
|
|
653
|
+
await this.dequeue(row.id);
|
|
654
|
+
}
|
|
655
|
+
);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
this._flushingQueue = false;
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* Dequeue a task by ID
|
|
662
|
+
* @param id ID of the task to dequeue
|
|
663
|
+
*/
|
|
664
|
+
async dequeue(id) {
|
|
665
|
+
this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
|
|
666
|
+
}
|
|
667
|
+
/**
|
|
668
|
+
* Dequeue all tasks
|
|
669
|
+
*/
|
|
670
|
+
async dequeueAll() {
|
|
671
|
+
this.sql`DELETE FROM cf_agents_queues`;
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* Dequeue all tasks by callback
|
|
675
|
+
* @param callback Name of the callback to dequeue
|
|
676
|
+
*/
|
|
677
|
+
async dequeueAllByCallback(callback) {
|
|
678
|
+
this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* Get a queued task by ID
|
|
682
|
+
* @param id ID of the task to get
|
|
683
|
+
* @returns The task or undefined if not found
|
|
684
|
+
*/
|
|
685
|
+
async getQueue(id) {
|
|
686
|
+
const result = this.sql`
|
|
687
|
+
SELECT * FROM cf_agents_queues WHERE id = ${id}
|
|
688
|
+
`;
|
|
689
|
+
return result ? { ...result[0], payload: JSON.parse(result[0].payload) } : void 0;
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* Get all queues by key and value
|
|
693
|
+
* @param key Key to filter by
|
|
694
|
+
* @param value Value to filter by
|
|
695
|
+
* @returns Array of matching QueueItem objects
|
|
696
|
+
*/
|
|
697
|
+
async getQueues(key, value) {
|
|
698
|
+
const result = this.sql`
|
|
699
|
+
SELECT * FROM cf_agents_queues
|
|
700
|
+
`;
|
|
701
|
+
return result.filter((row) => JSON.parse(row.payload)[key] === value);
|
|
702
|
+
}
|
|
414
703
|
/**
|
|
415
704
|
* Schedule a task to be executed in the future
|
|
416
705
|
* @template T Type of the payload data
|
|
@@ -421,6 +710,16 @@ var Agent = class extends Server {
|
|
|
421
710
|
*/
|
|
422
711
|
async schedule(when, callback, payload) {
|
|
423
712
|
const id = nanoid(9);
|
|
713
|
+
const emitScheduleCreate = (schedule) => this.observability?.emit(
|
|
714
|
+
{
|
|
715
|
+
displayMessage: `Schedule ${schedule.id} created`,
|
|
716
|
+
id: nanoid(),
|
|
717
|
+
payload: schedule,
|
|
718
|
+
timestamp: Date.now(),
|
|
719
|
+
type: "schedule:create"
|
|
720
|
+
},
|
|
721
|
+
this.ctx
|
|
722
|
+
);
|
|
424
723
|
if (typeof callback !== "string") {
|
|
425
724
|
throw new Error("Callback must be a string");
|
|
426
725
|
}
|
|
@@ -436,13 +735,15 @@ var Agent = class extends Server {
|
|
|
436
735
|
)}, 'scheduled', ${timestamp})
|
|
437
736
|
`;
|
|
438
737
|
await this._scheduleNextAlarm();
|
|
439
|
-
|
|
738
|
+
const schedule = {
|
|
440
739
|
callback,
|
|
441
740
|
id,
|
|
442
741
|
payload,
|
|
443
742
|
time: timestamp,
|
|
444
743
|
type: "scheduled"
|
|
445
744
|
};
|
|
745
|
+
emitScheduleCreate(schedule);
|
|
746
|
+
return schedule;
|
|
446
747
|
}
|
|
447
748
|
if (typeof when === "number") {
|
|
448
749
|
const time = new Date(Date.now() + when * 1e3);
|
|
@@ -454,7 +755,7 @@ var Agent = class extends Server {
|
|
|
454
755
|
)}, 'delayed', ${when}, ${timestamp})
|
|
455
756
|
`;
|
|
456
757
|
await this._scheduleNextAlarm();
|
|
457
|
-
|
|
758
|
+
const schedule = {
|
|
458
759
|
callback,
|
|
459
760
|
delayInSeconds: when,
|
|
460
761
|
id,
|
|
@@ -462,6 +763,8 @@ var Agent = class extends Server {
|
|
|
462
763
|
time: timestamp,
|
|
463
764
|
type: "delayed"
|
|
464
765
|
};
|
|
766
|
+
emitScheduleCreate(schedule);
|
|
767
|
+
return schedule;
|
|
465
768
|
}
|
|
466
769
|
if (typeof when === "string") {
|
|
467
770
|
const nextExecutionTime = getNextCronTime(when);
|
|
@@ -473,7 +776,7 @@ var Agent = class extends Server {
|
|
|
473
776
|
)}, 'cron', ${when}, ${timestamp})
|
|
474
777
|
`;
|
|
475
778
|
await this._scheduleNextAlarm();
|
|
476
|
-
|
|
779
|
+
const schedule = {
|
|
477
780
|
callback,
|
|
478
781
|
cron: when,
|
|
479
782
|
id,
|
|
@@ -481,6 +784,8 @@ var Agent = class extends Server {
|
|
|
481
784
|
time: timestamp,
|
|
482
785
|
type: "cron"
|
|
483
786
|
};
|
|
787
|
+
emitScheduleCreate(schedule);
|
|
788
|
+
return schedule;
|
|
484
789
|
}
|
|
485
790
|
throw new Error("Invalid schedule type");
|
|
486
791
|
}
|
|
@@ -538,15 +843,28 @@ var Agent = class extends Server {
|
|
|
538
843
|
* @returns true if the task was cancelled, false otherwise
|
|
539
844
|
*/
|
|
540
845
|
async cancelSchedule(id) {
|
|
846
|
+
const schedule = await this.getSchedule(id);
|
|
847
|
+
if (schedule) {
|
|
848
|
+
this.observability?.emit(
|
|
849
|
+
{
|
|
850
|
+
displayMessage: `Schedule ${id} cancelled`,
|
|
851
|
+
id: nanoid(),
|
|
852
|
+
payload: schedule,
|
|
853
|
+
timestamp: Date.now(),
|
|
854
|
+
type: "schedule:cancel"
|
|
855
|
+
},
|
|
856
|
+
this.ctx
|
|
857
|
+
);
|
|
858
|
+
}
|
|
541
859
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
542
860
|
await this._scheduleNextAlarm();
|
|
543
861
|
return true;
|
|
544
862
|
}
|
|
545
863
|
async _scheduleNextAlarm() {
|
|
546
864
|
const result = this.sql`
|
|
547
|
-
SELECT time FROM cf_agents_schedules
|
|
865
|
+
SELECT time FROM cf_agents_schedules
|
|
548
866
|
WHERE time > ${Math.floor(Date.now() / 1e3)}
|
|
549
|
-
ORDER BY time ASC
|
|
867
|
+
ORDER BY time ASC
|
|
550
868
|
LIMIT 1
|
|
551
869
|
`;
|
|
552
870
|
if (!result) return;
|
|
@@ -562,9 +880,20 @@ var Agent = class extends Server {
|
|
|
562
880
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
563
881
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
564
882
|
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
883
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
|
|
565
884
|
await this.ctx.storage.deleteAlarm();
|
|
566
885
|
await this.ctx.storage.deleteAll();
|
|
567
886
|
this.ctx.abort("destroyed");
|
|
887
|
+
this.observability?.emit(
|
|
888
|
+
{
|
|
889
|
+
displayMessage: "Agent destroyed",
|
|
890
|
+
id: nanoid(),
|
|
891
|
+
payload: {},
|
|
892
|
+
timestamp: Date.now(),
|
|
893
|
+
type: "destroy"
|
|
894
|
+
},
|
|
895
|
+
this.ctx
|
|
896
|
+
);
|
|
568
897
|
}
|
|
569
898
|
/**
|
|
570
899
|
* Get all methods marked as callable on this Agent
|
|
@@ -673,17 +1002,19 @@ var Agent = class extends Server {
|
|
|
673
1002
|
const servers = this.sql`
|
|
674
1003
|
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
675
1004
|
`;
|
|
676
|
-
|
|
677
|
-
const
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
1005
|
+
if (servers && Array.isArray(servers) && servers.length > 0) {
|
|
1006
|
+
for (const server of servers) {
|
|
1007
|
+
const serverConn = this.mcp.mcpConnections[server.id];
|
|
1008
|
+
mcpState.servers[server.id] = {
|
|
1009
|
+
auth_url: server.auth_url,
|
|
1010
|
+
capabilities: serverConn?.serverCapabilities ?? null,
|
|
1011
|
+
instructions: serverConn?.instructions ?? null,
|
|
1012
|
+
name: server.name,
|
|
1013
|
+
server_url: server.server_url,
|
|
1014
|
+
// mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
|
|
1015
|
+
state: serverConn?.connectionState ?? "authenticating"
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
687
1018
|
}
|
|
688
1019
|
return mcpState;
|
|
689
1020
|
}
|
|
@@ -691,11 +1022,12 @@ var Agent = class extends Server {
|
|
|
691
1022
|
/**
|
|
692
1023
|
* Agent configuration options
|
|
693
1024
|
*/
|
|
694
|
-
|
|
1025
|
+
_Agent.options = {
|
|
695
1026
|
/** Whether the Agent should hibernate when inactive */
|
|
696
1027
|
hibernate: true
|
|
697
1028
|
// default to hibernate
|
|
698
1029
|
};
|
|
1030
|
+
var Agent = _Agent;
|
|
699
1031
|
async function routeAgentRequest(request, env, options) {
|
|
700
1032
|
const corsHeaders = options?.cors === true ? {
|
|
701
1033
|
"Access-Control-Allow-Credentials": "true",
|
|
@@ -731,7 +1063,126 @@ async function routeAgentRequest(request, env, options) {
|
|
|
731
1063
|
}
|
|
732
1064
|
return response;
|
|
733
1065
|
}
|
|
734
|
-
|
|
1066
|
+
function createHeaderBasedEmailResolver() {
|
|
1067
|
+
return async (email, _env) => {
|
|
1068
|
+
const messageId = email.headers.get("message-id");
|
|
1069
|
+
if (messageId) {
|
|
1070
|
+
const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
|
|
1071
|
+
if (messageIdMatch) {
|
|
1072
|
+
const [, agentId2, domain] = messageIdMatch;
|
|
1073
|
+
const agentName2 = domain.split(".")[0];
|
|
1074
|
+
return { agentName: agentName2, agentId: agentId2 };
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
const references = email.headers.get("references");
|
|
1078
|
+
if (references) {
|
|
1079
|
+
const referencesMatch = references.match(
|
|
1080
|
+
/<([A-Za-z0-9+/]{43}=)@([^>]+)>/
|
|
1081
|
+
);
|
|
1082
|
+
if (referencesMatch) {
|
|
1083
|
+
const [, base64Id, domain] = referencesMatch;
|
|
1084
|
+
const agentId2 = Buffer.from(base64Id, "base64").toString("hex");
|
|
1085
|
+
const agentName2 = domain.split(".")[0];
|
|
1086
|
+
return { agentName: agentName2, agentId: agentId2 };
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
const agentName = email.headers.get("x-agent-name");
|
|
1090
|
+
const agentId = email.headers.get("x-agent-id");
|
|
1091
|
+
if (agentName && agentId) {
|
|
1092
|
+
return { agentName, agentId };
|
|
1093
|
+
}
|
|
1094
|
+
return null;
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
function createAddressBasedEmailResolver(defaultAgentName) {
|
|
1098
|
+
return async (email, _env) => {
|
|
1099
|
+
const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
|
|
1100
|
+
if (!emailMatch) {
|
|
1101
|
+
return null;
|
|
1102
|
+
}
|
|
1103
|
+
const [, localPart, subAddress] = emailMatch;
|
|
1104
|
+
if (subAddress) {
|
|
1105
|
+
return {
|
|
1106
|
+
agentName: localPart,
|
|
1107
|
+
agentId: subAddress
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
return {
|
|
1111
|
+
agentName: defaultAgentName,
|
|
1112
|
+
agentId: localPart
|
|
1113
|
+
};
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
function createCatchAllEmailResolver(agentName, agentId) {
|
|
1117
|
+
return async () => ({ agentName, agentId });
|
|
1118
|
+
}
|
|
1119
|
+
var agentMapCache = /* @__PURE__ */ new WeakMap();
|
|
1120
|
+
async function routeAgentEmail(email, env, options) {
|
|
1121
|
+
const routingInfo = await options.resolver(email, env);
|
|
1122
|
+
if (!routingInfo) {
|
|
1123
|
+
console.warn("No routing information found for email, dropping message");
|
|
1124
|
+
return;
|
|
1125
|
+
}
|
|
1126
|
+
if (!agentMapCache.has(env)) {
|
|
1127
|
+
const map = {};
|
|
1128
|
+
for (const [key, value] of Object.entries(env)) {
|
|
1129
|
+
if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
|
|
1130
|
+
map[key] = value;
|
|
1131
|
+
map[camelCaseToKebabCase(key)] = value;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
agentMapCache.set(env, map);
|
|
1135
|
+
}
|
|
1136
|
+
const agentMap = agentMapCache.get(env);
|
|
1137
|
+
const namespace = agentMap[routingInfo.agentName];
|
|
1138
|
+
if (!namespace) {
|
|
1139
|
+
const availableAgents = Object.keys(agentMap).filter((key) => !key.includes("-")).join(", ");
|
|
1140
|
+
throw new Error(
|
|
1141
|
+
`Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`
|
|
1142
|
+
);
|
|
1143
|
+
}
|
|
1144
|
+
const agent = await getAgentByName(
|
|
1145
|
+
namespace,
|
|
1146
|
+
routingInfo.agentId
|
|
1147
|
+
);
|
|
1148
|
+
const serialisableEmail = {
|
|
1149
|
+
getRaw: async () => {
|
|
1150
|
+
const reader = email.raw.getReader();
|
|
1151
|
+
const chunks = [];
|
|
1152
|
+
let done = false;
|
|
1153
|
+
while (!done) {
|
|
1154
|
+
const { value, done: readerDone } = await reader.read();
|
|
1155
|
+
done = readerDone;
|
|
1156
|
+
if (value) {
|
|
1157
|
+
chunks.push(value);
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
|
|
1161
|
+
const combined = new Uint8Array(totalLength);
|
|
1162
|
+
let offset = 0;
|
|
1163
|
+
for (const chunk of chunks) {
|
|
1164
|
+
combined.set(chunk, offset);
|
|
1165
|
+
offset += chunk.length;
|
|
1166
|
+
}
|
|
1167
|
+
return combined;
|
|
1168
|
+
},
|
|
1169
|
+
headers: email.headers,
|
|
1170
|
+
rawSize: email.rawSize,
|
|
1171
|
+
setReject: (reason) => {
|
|
1172
|
+
email.setReject(reason);
|
|
1173
|
+
},
|
|
1174
|
+
forward: (rcptTo, headers) => {
|
|
1175
|
+
return email.forward(rcptTo, headers);
|
|
1176
|
+
},
|
|
1177
|
+
reply: (options2) => {
|
|
1178
|
+
return email.reply(
|
|
1179
|
+
new EmailMessage(options2.from, options2.to, options2.raw)
|
|
1180
|
+
);
|
|
1181
|
+
},
|
|
1182
|
+
from: email.from,
|
|
1183
|
+
to: email.to
|
|
1184
|
+
};
|
|
1185
|
+
await agent._onEmail(serialisableEmail);
|
|
735
1186
|
}
|
|
736
1187
|
async function getAgentByName(namespace, name, options) {
|
|
737
1188
|
return getServerByName(namespace, name, options);
|
|
@@ -779,13 +1230,41 @@ var StreamingResponse = class {
|
|
|
779
1230
|
}
|
|
780
1231
|
};
|
|
781
1232
|
|
|
1233
|
+
// src/observability/index.ts
|
|
1234
|
+
var genericObservability = {
|
|
1235
|
+
emit(event) {
|
|
1236
|
+
if (isLocalMode()) {
|
|
1237
|
+
console.log(event.displayMessage);
|
|
1238
|
+
return;
|
|
1239
|
+
}
|
|
1240
|
+
console.log(event);
|
|
1241
|
+
}
|
|
1242
|
+
};
|
|
1243
|
+
var localMode = false;
|
|
1244
|
+
function isLocalMode() {
|
|
1245
|
+
if (localMode) {
|
|
1246
|
+
return true;
|
|
1247
|
+
}
|
|
1248
|
+
const { request } = getCurrentAgent();
|
|
1249
|
+
if (!request) {
|
|
1250
|
+
return false;
|
|
1251
|
+
}
|
|
1252
|
+
const url = new URL(request.url);
|
|
1253
|
+
localMode = url.hostname === "localhost";
|
|
1254
|
+
return localMode;
|
|
1255
|
+
}
|
|
1256
|
+
|
|
782
1257
|
export {
|
|
1258
|
+
genericObservability,
|
|
783
1259
|
unstable_callable,
|
|
784
1260
|
getCurrentAgent,
|
|
785
1261
|
Agent,
|
|
786
1262
|
routeAgentRequest,
|
|
1263
|
+
createHeaderBasedEmailResolver,
|
|
1264
|
+
createAddressBasedEmailResolver,
|
|
1265
|
+
createCatchAllEmailResolver,
|
|
787
1266
|
routeAgentEmail,
|
|
788
1267
|
getAgentByName,
|
|
789
1268
|
StreamingResponse
|
|
790
1269
|
};
|
|
791
|
-
//# sourceMappingURL=chunk-
|
|
1270
|
+
//# sourceMappingURL=chunk-Z2OUUKK4.js.map
|