agents 0.0.0-07086ea → 0.0.0-0bb74b8

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.
Files changed (47) hide show
  1. package/README.md +22 -22
  2. package/dist/ai-chat-agent.d.ts +32 -6
  3. package/dist/ai-chat-agent.js +149 -115
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +18 -5
  6. package/dist/ai-react.js +28 -29
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/chunk-KUH345EY.js +116 -0
  9. package/dist/chunk-KUH345EY.js.map +1 -0
  10. package/dist/chunk-MGHXAF5T.js +1082 -0
  11. package/dist/chunk-MGHXAF5T.js.map +1 -0
  12. package/dist/{chunk-WNICV3OI.js → chunk-MW5BQ2FW.js} +70 -37
  13. package/dist/chunk-MW5BQ2FW.js.map +1 -0
  14. package/dist/chunk-PVQZBKN7.js +106 -0
  15. package/dist/chunk-PVQZBKN7.js.map +1 -0
  16. package/dist/client.d.ts +16 -2
  17. package/dist/client.js +6 -126
  18. package/dist/client.js.map +1 -1
  19. package/dist/index-CEVsIbwa.d.ts +565 -0
  20. package/dist/index.d.ts +32 -307
  21. package/dist/index.js +14 -7
  22. package/dist/mcp/client.d.ts +310 -23
  23. package/dist/mcp/client.js +1 -2
  24. package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
  25. package/dist/mcp/do-oauth-client-provider.js +3 -103
  26. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  27. package/dist/mcp/index.d.ts +23 -13
  28. package/dist/mcp/index.js +150 -175
  29. package/dist/mcp/index.js.map +1 -1
  30. package/dist/observability/index.d.ts +12 -0
  31. package/dist/observability/index.js +10 -0
  32. package/dist/react.d.ts +85 -5
  33. package/dist/react.js +20 -8
  34. package/dist/react.js.map +1 -1
  35. package/dist/schedule.d.ts +6 -6
  36. package/dist/schedule.js +4 -6
  37. package/dist/schedule.js.map +1 -1
  38. package/dist/serializable.d.ts +32 -0
  39. package/dist/serializable.js +1 -0
  40. package/dist/serializable.js.map +1 -0
  41. package/package.json +76 -68
  42. package/src/index.ts +828 -111
  43. package/dist/chunk-HMLY7DHA.js +0 -16
  44. package/dist/chunk-WNICV3OI.js.map +0 -1
  45. package/dist/chunk-ZRZEISHY.js +0 -597
  46. package/dist/chunk-ZRZEISHY.js.map +0 -1
  47. /package/dist/{chunk-HMLY7DHA.js.map → observability/index.js.map} +0 -0
@@ -0,0 +1,1082 @@
1
+ import {
2
+ MCPClientManager
3
+ } from "./chunk-MW5BQ2FW.js";
4
+ import {
5
+ DurableObjectOAuthClientProvider
6
+ } from "./chunk-PVQZBKN7.js";
7
+ import {
8
+ camelCaseToKebabCase
9
+ } from "./chunk-KUH345EY.js";
10
+
11
+ // src/index.ts
12
+ import { AsyncLocalStorage } from "async_hooks";
13
+ import { parseCronExpression } from "cron-schedule";
14
+ import { nanoid } from "nanoid";
15
+ import { EmailMessage } from "cloudflare:email";
16
+ import {
17
+ Server,
18
+ getServerByName,
19
+ routePartykitRequest
20
+ } from "partyserver";
21
+ function isRPCRequest(msg) {
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);
23
+ }
24
+ function isStateUpdateMessage(msg) {
25
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "cf_agent_state" && "state" in msg;
26
+ }
27
+ var callableMetadata = /* @__PURE__ */ new Map();
28
+ function unstable_callable(metadata = {}) {
29
+ return function callableDecorator(target, context) {
30
+ if (!callableMetadata.has(target)) {
31
+ callableMetadata.set(target, metadata);
32
+ }
33
+ return target;
34
+ };
35
+ }
36
+ function getNextCronTime(cron) {
37
+ const interval = parseCronExpression(cron);
38
+ return interval.getNextDate();
39
+ }
40
+ var STATE_ROW_ID = "cf_state_row_id";
41
+ var STATE_WAS_CHANGED = "cf_state_was_changed";
42
+ var DEFAULT_STATE = {};
43
+ var agentContext = new AsyncLocalStorage();
44
+ function getCurrentAgent() {
45
+ const store = agentContext.getStore();
46
+ if (!store) {
47
+ return {
48
+ agent: void 0,
49
+ connection: void 0,
50
+ request: void 0
51
+ };
52
+ }
53
+ return store;
54
+ }
55
+ var Agent = class extends Server {
56
+ constructor(ctx, env) {
57
+ super(ctx, env);
58
+ this._state = DEFAULT_STATE;
59
+ this._ParentClass = Object.getPrototypeOf(this).constructor;
60
+ this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
61
+ /**
62
+ * Initial state for the Agent
63
+ * Override to provide default state values
64
+ */
65
+ this.initialState = DEFAULT_STATE;
66
+ /**
67
+ * The observability implementation to use for the Agent
68
+ */
69
+ this.observability = genericObservability;
70
+ /**
71
+ * Method called when an alarm fires.
72
+ * Executes any scheduled tasks that are due.
73
+ *
74
+ * @remarks
75
+ * To schedule a task, please use the `this.schedule` method instead.
76
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
77
+ */
78
+ this.alarm = async () => {
79
+ const now = Math.floor(Date.now() / 1e3);
80
+ const result = this.sql`
81
+ SELECT * FROM cf_agents_schedules WHERE time <= ${now}
82
+ `;
83
+ for (const row of result || []) {
84
+ const callback = this[row.callback];
85
+ if (!callback) {
86
+ console.error(`callback ${row.callback} not found`);
87
+ continue;
88
+ }
89
+ await agentContext.run(
90
+ {
91
+ agent: this,
92
+ connection: void 0,
93
+ request: void 0,
94
+ email: void 0
95
+ },
96
+ async () => {
97
+ try {
98
+ this.observability?.emit(
99
+ {
100
+ displayMessage: `Schedule ${row.id} executed`,
101
+ id: nanoid(),
102
+ payload: row,
103
+ timestamp: Date.now(),
104
+ type: "schedule:execute"
105
+ },
106
+ this.ctx
107
+ );
108
+ await callback.bind(this)(JSON.parse(row.payload), row);
109
+ } catch (e) {
110
+ console.error(`error executing callback "${row.callback}"`, e);
111
+ }
112
+ }
113
+ );
114
+ if (row.type === "cron") {
115
+ const nextExecutionTime = getNextCronTime(row.cron);
116
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
117
+ this.sql`
118
+ UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
119
+ `;
120
+ } else {
121
+ this.sql`
122
+ DELETE FROM cf_agents_schedules WHERE id = ${row.id}
123
+ `;
124
+ }
125
+ }
126
+ await this._scheduleNextAlarm();
127
+ };
128
+ this.sql`
129
+ CREATE TABLE IF NOT EXISTS cf_agents_state (
130
+ id TEXT PRIMARY KEY NOT NULL,
131
+ state TEXT
132
+ )
133
+ `;
134
+ void this.ctx.blockConcurrencyWhile(async () => {
135
+ return this._tryCatch(async () => {
136
+ this.sql`
137
+ CREATE TABLE IF NOT EXISTS cf_agents_schedules (
138
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
139
+ callback TEXT,
140
+ payload TEXT,
141
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
142
+ time INTEGER,
143
+ delayInSeconds INTEGER,
144
+ cron TEXT,
145
+ created_at INTEGER DEFAULT (unixepoch())
146
+ )
147
+ `;
148
+ await this.alarm();
149
+ });
150
+ });
151
+ this.sql`
152
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
153
+ id TEXT PRIMARY KEY NOT NULL,
154
+ name TEXT NOT NULL,
155
+ server_url TEXT NOT NULL,
156
+ callback_url TEXT NOT NULL,
157
+ client_id TEXT,
158
+ auth_url TEXT,
159
+ server_options TEXT
160
+ )
161
+ `;
162
+ const _onRequest = this.onRequest.bind(this);
163
+ this.onRequest = (request) => {
164
+ return agentContext.run(
165
+ { agent: this, connection: void 0, request, email: void 0 },
166
+ async () => {
167
+ if (this.mcp.isCallbackRequest(request)) {
168
+ await this.mcp.handleCallbackRequest(request);
169
+ this.broadcast(
170
+ JSON.stringify({
171
+ mcp: this.getMcpServers(),
172
+ type: "cf_agent_mcp_servers"
173
+ })
174
+ );
175
+ return new Response("<script>window.close();</script>", {
176
+ headers: { "content-type": "text/html" },
177
+ status: 200
178
+ });
179
+ }
180
+ return this._tryCatch(() => _onRequest(request));
181
+ }
182
+ );
183
+ };
184
+ const _onMessage = this.onMessage.bind(this);
185
+ this.onMessage = async (connection, message) => {
186
+ return agentContext.run(
187
+ { agent: this, connection, request: void 0, email: void 0 },
188
+ async () => {
189
+ if (typeof message !== "string") {
190
+ return this._tryCatch(() => _onMessage(connection, message));
191
+ }
192
+ let parsed;
193
+ try {
194
+ parsed = JSON.parse(message);
195
+ } catch (_e) {
196
+ return this._tryCatch(() => _onMessage(connection, message));
197
+ }
198
+ if (isStateUpdateMessage(parsed)) {
199
+ this._setStateInternal(parsed.state, connection);
200
+ return;
201
+ }
202
+ if (isRPCRequest(parsed)) {
203
+ try {
204
+ const { id, method, args } = parsed;
205
+ const methodFn = this[method];
206
+ if (typeof methodFn !== "function") {
207
+ throw new Error(`Method ${method} does not exist`);
208
+ }
209
+ if (!this._isCallable(method)) {
210
+ throw new Error(`Method ${method} is not callable`);
211
+ }
212
+ const metadata = callableMetadata.get(methodFn);
213
+ if (metadata?.streaming) {
214
+ const stream = new StreamingResponse(connection, id);
215
+ await methodFn.apply(this, [stream, ...args]);
216
+ return;
217
+ }
218
+ const result = await methodFn.apply(this, args);
219
+ this.observability?.emit(
220
+ {
221
+ displayMessage: `RPC call to ${method}`,
222
+ id: nanoid(),
223
+ payload: {
224
+ args,
225
+ method,
226
+ streaming: metadata?.streaming,
227
+ success: true
228
+ },
229
+ timestamp: Date.now(),
230
+ type: "rpc"
231
+ },
232
+ this.ctx
233
+ );
234
+ const response = {
235
+ done: true,
236
+ id,
237
+ result,
238
+ success: true,
239
+ type: "rpc"
240
+ };
241
+ connection.send(JSON.stringify(response));
242
+ } catch (e) {
243
+ const response = {
244
+ error: e instanceof Error ? e.message : "Unknown error occurred",
245
+ id: parsed.id,
246
+ success: false,
247
+ type: "rpc"
248
+ };
249
+ connection.send(JSON.stringify(response));
250
+ console.error("RPC error:", e);
251
+ }
252
+ return;
253
+ }
254
+ return this._tryCatch(() => _onMessage(connection, message));
255
+ }
256
+ );
257
+ };
258
+ const _onConnect = this.onConnect.bind(this);
259
+ this.onConnect = (connection, ctx2) => {
260
+ return agentContext.run(
261
+ { agent: this, connection, request: ctx2.request, email: void 0 },
262
+ async () => {
263
+ setTimeout(() => {
264
+ if (this.state) {
265
+ connection.send(
266
+ JSON.stringify({
267
+ state: this.state,
268
+ type: "cf_agent_state"
269
+ })
270
+ );
271
+ }
272
+ connection.send(
273
+ JSON.stringify({
274
+ mcp: this.getMcpServers(),
275
+ type: "cf_agent_mcp_servers"
276
+ })
277
+ );
278
+ this.observability?.emit(
279
+ {
280
+ displayMessage: "Connection established",
281
+ id: nanoid(),
282
+ payload: {
283
+ connectionId: connection.id
284
+ },
285
+ timestamp: Date.now(),
286
+ type: "connect"
287
+ },
288
+ this.ctx
289
+ );
290
+ return this._tryCatch(() => _onConnect(connection, ctx2));
291
+ }, 20);
292
+ }
293
+ );
294
+ };
295
+ const _onStart = this.onStart.bind(this);
296
+ this.onStart = async () => {
297
+ return agentContext.run(
298
+ {
299
+ agent: this,
300
+ connection: void 0,
301
+ request: void 0,
302
+ email: void 0
303
+ },
304
+ async () => {
305
+ const servers = this.sql`
306
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
307
+ `;
308
+ Promise.allSettled(
309
+ servers.map((server) => {
310
+ return this._connectToMcpServerInternal(
311
+ server.name,
312
+ server.server_url,
313
+ server.callback_url,
314
+ server.server_options ? JSON.parse(server.server_options) : void 0,
315
+ {
316
+ id: server.id,
317
+ oauthClientId: server.client_id ?? void 0
318
+ }
319
+ );
320
+ })
321
+ ).then((_results) => {
322
+ this.broadcast(
323
+ JSON.stringify({
324
+ mcp: this.getMcpServers(),
325
+ type: "cf_agent_mcp_servers"
326
+ })
327
+ );
328
+ });
329
+ await this._tryCatch(() => _onStart());
330
+ }
331
+ );
332
+ };
333
+ }
334
+ /**
335
+ * Current state of the Agent
336
+ */
337
+ get state() {
338
+ if (this._state !== DEFAULT_STATE) {
339
+ return this._state;
340
+ }
341
+ const wasChanged = this.sql`
342
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
343
+ `;
344
+ const result = this.sql`
345
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
346
+ `;
347
+ if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
348
+ result[0]?.state) {
349
+ const state = result[0]?.state;
350
+ this._state = JSON.parse(state);
351
+ return this._state;
352
+ }
353
+ if (this.initialState === DEFAULT_STATE) {
354
+ return void 0;
355
+ }
356
+ this.setState(this.initialState);
357
+ return this.initialState;
358
+ }
359
+ /**
360
+ * Execute SQL queries against the Agent's database
361
+ * @template T Type of the returned rows
362
+ * @param strings SQL query template strings
363
+ * @param values Values to be inserted into the query
364
+ * @returns Array of query results
365
+ */
366
+ sql(strings, ...values) {
367
+ let query = "";
368
+ try {
369
+ query = strings.reduce(
370
+ (acc, str, i) => acc + str + (i < values.length ? "?" : ""),
371
+ ""
372
+ );
373
+ return [...this.ctx.storage.sql.exec(query, ...values)];
374
+ } catch (e) {
375
+ console.error(`failed to execute sql query: ${query}`, e);
376
+ throw this.onError(e);
377
+ }
378
+ }
379
+ _setStateInternal(state, source = "server") {
380
+ const previousState = this._state;
381
+ this._state = state;
382
+ this.sql`
383
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
384
+ VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
385
+ `;
386
+ this.sql`
387
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
388
+ VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
389
+ `;
390
+ this.broadcast(
391
+ JSON.stringify({
392
+ state,
393
+ type: "cf_agent_state"
394
+ }),
395
+ source !== "server" ? [source.id] : []
396
+ );
397
+ return this._tryCatch(() => {
398
+ const { connection, request, email } = agentContext.getStore() || {};
399
+ return agentContext.run(
400
+ { agent: this, connection, request, email },
401
+ async () => {
402
+ this.observability?.emit(
403
+ {
404
+ displayMessage: "State updated",
405
+ id: nanoid(),
406
+ payload: {
407
+ previousState,
408
+ state
409
+ },
410
+ timestamp: Date.now(),
411
+ type: "state:update"
412
+ },
413
+ this.ctx
414
+ );
415
+ return this.onStateUpdate(state, source);
416
+ }
417
+ );
418
+ });
419
+ }
420
+ /**
421
+ * Update the Agent's state
422
+ * @param state New state to set
423
+ */
424
+ setState(state) {
425
+ this._setStateInternal(state, "server");
426
+ }
427
+ /**
428
+ * Called when the Agent's state is updated
429
+ * @param state Updated state
430
+ * @param source Source of the state update ("server" or a client connection)
431
+ */
432
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
433
+ onStateUpdate(state, source) {
434
+ }
435
+ /**
436
+ * Called when the Agent receives an email via routeAgentEmail()
437
+ * Override this method to handle incoming emails
438
+ * @param email Email message to process
439
+ */
440
+ async _onEmail(email) {
441
+ return agentContext.run(
442
+ { agent: this, connection: void 0, request: void 0, email },
443
+ async () => {
444
+ if ("onEmail" in this && typeof this.onEmail === "function") {
445
+ return this._tryCatch(
446
+ () => this.onEmail(email)
447
+ );
448
+ } else {
449
+ console.log("Received email from:", email.from, "to:", email.to);
450
+ console.log("Subject:", email.headers.get("subject"));
451
+ console.log(
452
+ "Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
453
+ );
454
+ }
455
+ }
456
+ );
457
+ }
458
+ /**
459
+ * Reply to an email
460
+ * @param email The email to reply to
461
+ * @param options Options for the reply
462
+ * @returns void
463
+ */
464
+ async replyToEmail(email, options) {
465
+ return this._tryCatch(async () => {
466
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
467
+ const agentId = this.name;
468
+ const { createMimeMessage } = await import("mimetext");
469
+ const msg = createMimeMessage();
470
+ msg.setSender({ addr: email.to, name: options.fromName });
471
+ msg.setRecipient(email.from);
472
+ msg.setSubject(
473
+ options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
474
+ );
475
+ msg.addMessage({
476
+ contentType: options.contentType || "text/plain",
477
+ data: options.body
478
+ });
479
+ const domain = email.from.split("@")[1];
480
+ const messageId = `<${agentId}@${domain}>`;
481
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID"));
482
+ msg.setHeader("Message-ID", messageId);
483
+ msg.setHeader("X-Agent-Name", agentName);
484
+ msg.setHeader("X-Agent-ID", agentId);
485
+ if (options.headers) {
486
+ for (const [key, value] of Object.entries(options.headers)) {
487
+ msg.setHeader(key, value);
488
+ }
489
+ }
490
+ await email.reply({
491
+ from: email.to,
492
+ raw: msg.asRaw(),
493
+ to: email.from
494
+ });
495
+ });
496
+ }
497
+ async _tryCatch(fn) {
498
+ try {
499
+ return await fn();
500
+ } catch (e) {
501
+ throw this.onError(e);
502
+ }
503
+ }
504
+ onError(connectionOrError, error) {
505
+ let theError;
506
+ if (connectionOrError && error) {
507
+ theError = error;
508
+ console.error(
509
+ "Error on websocket connection:",
510
+ connectionOrError.id,
511
+ theError
512
+ );
513
+ console.error(
514
+ "Override onError(connection, error) to handle websocket connection errors"
515
+ );
516
+ } else {
517
+ theError = connectionOrError;
518
+ console.error("Error on server:", theError);
519
+ console.error("Override onError(error) to handle server errors");
520
+ }
521
+ throw theError;
522
+ }
523
+ /**
524
+ * Render content (not implemented in base class)
525
+ */
526
+ render() {
527
+ throw new Error("Not implemented");
528
+ }
529
+ /**
530
+ * Schedule a task to be executed in the future
531
+ * @template T Type of the payload data
532
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
533
+ * @param callback Name of the method to call
534
+ * @param payload Data to pass to the callback
535
+ * @returns Schedule object representing the scheduled task
536
+ */
537
+ async schedule(when, callback, payload) {
538
+ const id = nanoid(9);
539
+ const emitScheduleCreate = (schedule) => this.observability?.emit(
540
+ {
541
+ displayMessage: `Schedule ${schedule.id} created`,
542
+ id: nanoid(),
543
+ payload: schedule,
544
+ timestamp: Date.now(),
545
+ type: "schedule:create"
546
+ },
547
+ this.ctx
548
+ );
549
+ if (typeof callback !== "string") {
550
+ throw new Error("Callback must be a string");
551
+ }
552
+ if (typeof this[callback] !== "function") {
553
+ throw new Error(`this.${callback} is not a function`);
554
+ }
555
+ if (when instanceof Date) {
556
+ const timestamp = Math.floor(when.getTime() / 1e3);
557
+ this.sql`
558
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
559
+ VALUES (${id}, ${callback}, ${JSON.stringify(
560
+ payload
561
+ )}, 'scheduled', ${timestamp})
562
+ `;
563
+ await this._scheduleNextAlarm();
564
+ const schedule = {
565
+ callback,
566
+ id,
567
+ payload,
568
+ time: timestamp,
569
+ type: "scheduled"
570
+ };
571
+ emitScheduleCreate(schedule);
572
+ return schedule;
573
+ }
574
+ if (typeof when === "number") {
575
+ const time = new Date(Date.now() + when * 1e3);
576
+ const timestamp = Math.floor(time.getTime() / 1e3);
577
+ this.sql`
578
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
579
+ VALUES (${id}, ${callback}, ${JSON.stringify(
580
+ payload
581
+ )}, 'delayed', ${when}, ${timestamp})
582
+ `;
583
+ await this._scheduleNextAlarm();
584
+ const schedule = {
585
+ callback,
586
+ delayInSeconds: when,
587
+ id,
588
+ payload,
589
+ time: timestamp,
590
+ type: "delayed"
591
+ };
592
+ emitScheduleCreate(schedule);
593
+ return schedule;
594
+ }
595
+ if (typeof when === "string") {
596
+ const nextExecutionTime = getNextCronTime(when);
597
+ const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
598
+ this.sql`
599
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
600
+ VALUES (${id}, ${callback}, ${JSON.stringify(
601
+ payload
602
+ )}, 'cron', ${when}, ${timestamp})
603
+ `;
604
+ await this._scheduleNextAlarm();
605
+ const schedule = {
606
+ callback,
607
+ cron: when,
608
+ id,
609
+ payload,
610
+ time: timestamp,
611
+ type: "cron"
612
+ };
613
+ emitScheduleCreate(schedule);
614
+ return schedule;
615
+ }
616
+ throw new Error("Invalid schedule type");
617
+ }
618
+ /**
619
+ * Get a scheduled task by ID
620
+ * @template T Type of the payload data
621
+ * @param id ID of the scheduled task
622
+ * @returns The Schedule object or undefined if not found
623
+ */
624
+ async getSchedule(id) {
625
+ const result = this.sql`
626
+ SELECT * FROM cf_agents_schedules WHERE id = ${id}
627
+ `;
628
+ if (!result) {
629
+ console.error(`schedule ${id} not found`);
630
+ return void 0;
631
+ }
632
+ return { ...result[0], payload: JSON.parse(result[0].payload) };
633
+ }
634
+ /**
635
+ * Get scheduled tasks matching the given criteria
636
+ * @template T Type of the payload data
637
+ * @param criteria Criteria to filter schedules
638
+ * @returns Array of matching Schedule objects
639
+ */
640
+ getSchedules(criteria = {}) {
641
+ let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
642
+ const params = [];
643
+ if (criteria.id) {
644
+ query += " AND id = ?";
645
+ params.push(criteria.id);
646
+ }
647
+ if (criteria.type) {
648
+ query += " AND type = ?";
649
+ params.push(criteria.type);
650
+ }
651
+ if (criteria.timeRange) {
652
+ query += " AND time >= ? AND time <= ?";
653
+ const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
654
+ const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
655
+ params.push(
656
+ Math.floor(start.getTime() / 1e3),
657
+ Math.floor(end.getTime() / 1e3)
658
+ );
659
+ }
660
+ const result = this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
661
+ ...row,
662
+ payload: JSON.parse(row.payload)
663
+ }));
664
+ return result;
665
+ }
666
+ /**
667
+ * Cancel a scheduled task
668
+ * @param id ID of the task to cancel
669
+ * @returns true if the task was cancelled, false otherwise
670
+ */
671
+ async cancelSchedule(id) {
672
+ const schedule = await this.getSchedule(id);
673
+ if (schedule) {
674
+ this.observability?.emit(
675
+ {
676
+ displayMessage: `Schedule ${id} cancelled`,
677
+ id: nanoid(),
678
+ payload: schedule,
679
+ timestamp: Date.now(),
680
+ type: "schedule:cancel"
681
+ },
682
+ this.ctx
683
+ );
684
+ }
685
+ this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
686
+ await this._scheduleNextAlarm();
687
+ return true;
688
+ }
689
+ async _scheduleNextAlarm() {
690
+ const result = this.sql`
691
+ SELECT time FROM cf_agents_schedules
692
+ WHERE time > ${Math.floor(Date.now() / 1e3)}
693
+ ORDER BY time ASC
694
+ LIMIT 1
695
+ `;
696
+ if (!result) return;
697
+ if (result.length > 0 && "time" in result[0]) {
698
+ const nextTime = result[0].time * 1e3;
699
+ await this.ctx.storage.setAlarm(nextTime);
700
+ }
701
+ }
702
+ /**
703
+ * Destroy the Agent, removing all state and scheduled tasks
704
+ */
705
+ async destroy() {
706
+ this.sql`DROP TABLE IF EXISTS cf_agents_state`;
707
+ this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
708
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
709
+ await this.ctx.storage.deleteAlarm();
710
+ await this.ctx.storage.deleteAll();
711
+ this.ctx.abort("destroyed");
712
+ this.observability?.emit(
713
+ {
714
+ displayMessage: "Agent destroyed",
715
+ id: nanoid(),
716
+ payload: {},
717
+ timestamp: Date.now(),
718
+ type: "destroy"
719
+ },
720
+ this.ctx
721
+ );
722
+ }
723
+ /**
724
+ * Get all methods marked as callable on this Agent
725
+ * @returns A map of method names to their metadata
726
+ */
727
+ _isCallable(method) {
728
+ return callableMetadata.has(this[method]);
729
+ }
730
+ /**
731
+ * Connect to a new MCP Server
732
+ *
733
+ * @param url MCP Server SSE URL
734
+ * @param callbackHost Base host for the agent, used for the redirect URI.
735
+ * @param agentsPrefix agents routing prefix if not using `agents`
736
+ * @param options MCP client and transport (header) options
737
+ * @returns authUrl
738
+ */
739
+ async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
740
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
741
+ const result = await this._connectToMcpServerInternal(
742
+ serverName,
743
+ url,
744
+ callbackUrl,
745
+ options
746
+ );
747
+ this.sql`
748
+ INSERT
749
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
750
+ VALUES (
751
+ ${result.id},
752
+ ${serverName},
753
+ ${url},
754
+ ${result.clientId ?? null},
755
+ ${result.authUrl ?? null},
756
+ ${callbackUrl},
757
+ ${options ? JSON.stringify(options) : null}
758
+ );
759
+ `;
760
+ this.broadcast(
761
+ JSON.stringify({
762
+ mcp: this.getMcpServers(),
763
+ type: "cf_agent_mcp_servers"
764
+ })
765
+ );
766
+ return result;
767
+ }
768
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
769
+ const authProvider = new DurableObjectOAuthClientProvider(
770
+ this.ctx.storage,
771
+ this.name,
772
+ callbackUrl
773
+ );
774
+ if (reconnect) {
775
+ authProvider.serverId = reconnect.id;
776
+ if (reconnect.oauthClientId) {
777
+ authProvider.clientId = reconnect.oauthClientId;
778
+ }
779
+ }
780
+ let headerTransportOpts = {};
781
+ if (options?.transport?.headers) {
782
+ headerTransportOpts = {
783
+ eventSourceInit: {
784
+ fetch: (url2, init) => fetch(url2, {
785
+ ...init,
786
+ headers: options?.transport?.headers
787
+ })
788
+ },
789
+ requestInit: {
790
+ headers: options?.transport?.headers
791
+ }
792
+ };
793
+ }
794
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
795
+ client: options?.client,
796
+ reconnect,
797
+ transport: {
798
+ ...headerTransportOpts,
799
+ authProvider
800
+ }
801
+ });
802
+ return {
803
+ authUrl,
804
+ clientId,
805
+ id
806
+ };
807
+ }
808
+ async removeMcpServer(id) {
809
+ this.mcp.closeConnection(id);
810
+ this.sql`
811
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
812
+ `;
813
+ this.broadcast(
814
+ JSON.stringify({
815
+ mcp: this.getMcpServers(),
816
+ type: "cf_agent_mcp_servers"
817
+ })
818
+ );
819
+ }
820
+ getMcpServers() {
821
+ const mcpState = {
822
+ prompts: this.mcp.listPrompts(),
823
+ resources: this.mcp.listResources(),
824
+ servers: {},
825
+ tools: this.mcp.listTools()
826
+ };
827
+ const servers = this.sql`
828
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
829
+ `;
830
+ for (const server of servers) {
831
+ const serverConn = this.mcp.mcpConnections[server.id];
832
+ mcpState.servers[server.id] = {
833
+ auth_url: server.auth_url,
834
+ capabilities: serverConn?.serverCapabilities ?? null,
835
+ instructions: serverConn?.instructions ?? null,
836
+ name: server.name,
837
+ server_url: server.server_url,
838
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
839
+ state: serverConn?.connectionState ?? "authenticating"
840
+ };
841
+ }
842
+ return mcpState;
843
+ }
844
+ };
845
+ /**
846
+ * Agent configuration options
847
+ */
848
+ Agent.options = {
849
+ /** Whether the Agent should hibernate when inactive */
850
+ hibernate: true
851
+ // default to hibernate
852
+ };
853
+ async function routeAgentRequest(request, env, options) {
854
+ const corsHeaders = options?.cors === true ? {
855
+ "Access-Control-Allow-Credentials": "true",
856
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
857
+ "Access-Control-Allow-Origin": "*",
858
+ "Access-Control-Max-Age": "86400"
859
+ } : options?.cors;
860
+ if (request.method === "OPTIONS") {
861
+ if (corsHeaders) {
862
+ return new Response(null, {
863
+ headers: corsHeaders
864
+ });
865
+ }
866
+ console.warn(
867
+ "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
868
+ );
869
+ }
870
+ let response = await routePartykitRequest(
871
+ request,
872
+ env,
873
+ {
874
+ prefix: "agents",
875
+ ...options
876
+ }
877
+ );
878
+ if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
879
+ response = new Response(response.body, {
880
+ headers: {
881
+ ...response.headers,
882
+ ...corsHeaders
883
+ }
884
+ });
885
+ }
886
+ return response;
887
+ }
888
+ function createHeaderBasedEmailResolver() {
889
+ return async (email, _env) => {
890
+ const messageId = email.headers.get("message-id");
891
+ if (messageId) {
892
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
893
+ if (messageIdMatch) {
894
+ const [, agentId2, domain] = messageIdMatch;
895
+ const agentName2 = domain.split(".")[0];
896
+ return { agentName: agentName2, agentId: agentId2 };
897
+ }
898
+ }
899
+ const references = email.headers.get("references");
900
+ if (references) {
901
+ const referencesMatch = references.match(
902
+ /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
903
+ );
904
+ if (referencesMatch) {
905
+ const [, base64Id, domain] = referencesMatch;
906
+ const agentId2 = Buffer.from(base64Id, "base64").toString("hex");
907
+ const agentName2 = domain.split(".")[0];
908
+ return { agentName: agentName2, agentId: agentId2 };
909
+ }
910
+ }
911
+ const agentName = email.headers.get("x-agent-name");
912
+ const agentId = email.headers.get("x-agent-id");
913
+ if (agentName && agentId) {
914
+ return { agentName, agentId };
915
+ }
916
+ return null;
917
+ };
918
+ }
919
+ function createAddressBasedEmailResolver(defaultAgentName) {
920
+ return async (email, _env) => {
921
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
922
+ if (!emailMatch) {
923
+ return null;
924
+ }
925
+ const [, localPart, subAddress] = emailMatch;
926
+ if (subAddress) {
927
+ return {
928
+ agentName: localPart,
929
+ agentId: subAddress
930
+ };
931
+ }
932
+ return {
933
+ agentName: defaultAgentName,
934
+ agentId: localPart
935
+ };
936
+ };
937
+ }
938
+ function createCatchAllEmailResolver(agentName, agentId) {
939
+ return async () => ({ agentName, agentId });
940
+ }
941
+ async function routeAgentEmail(email, env, options) {
942
+ const routingInfo = await options.resolver(email, env);
943
+ if (!routingInfo) {
944
+ console.warn("No routing information found for email, dropping message");
945
+ return;
946
+ }
947
+ const namespaceBinding = env[routingInfo.agentName];
948
+ if (!namespaceBinding) {
949
+ throw new Error(
950
+ `Agent namespace '${routingInfo.agentName}' not found in environment`
951
+ );
952
+ }
953
+ if (typeof namespaceBinding !== "object" || !("idFromName" in namespaceBinding) || typeof namespaceBinding.idFromName !== "function") {
954
+ throw new Error(
955
+ `Environment binding '${routingInfo.agentName}' is not an AgentNamespace (found: ${typeof namespaceBinding})`
956
+ );
957
+ }
958
+ const namespace = namespaceBinding;
959
+ const agent = await getAgentByName(namespace, routingInfo.agentId);
960
+ const serialisableEmail = {
961
+ getRaw: async () => {
962
+ const reader = email.raw.getReader();
963
+ const chunks = [];
964
+ let done = false;
965
+ while (!done) {
966
+ const { value, done: readerDone } = await reader.read();
967
+ done = readerDone;
968
+ if (value) {
969
+ chunks.push(value);
970
+ }
971
+ }
972
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
973
+ const combined = new Uint8Array(totalLength);
974
+ let offset = 0;
975
+ for (const chunk of chunks) {
976
+ combined.set(chunk, offset);
977
+ offset += chunk.length;
978
+ }
979
+ return combined;
980
+ },
981
+ headers: email.headers,
982
+ rawSize: email.rawSize,
983
+ setReject: (reason) => {
984
+ email.setReject(reason);
985
+ },
986
+ forward: (rcptTo, headers) => {
987
+ return email.forward(rcptTo, headers);
988
+ },
989
+ reply: (options2) => {
990
+ return email.reply(
991
+ new EmailMessage(options2.from, options2.to, options2.raw)
992
+ );
993
+ },
994
+ from: email.from,
995
+ to: email.to
996
+ };
997
+ await agent._onEmail(serialisableEmail);
998
+ }
999
+ async function getAgentByName(namespace, name, options) {
1000
+ return getServerByName(namespace, name, options);
1001
+ }
1002
+ var StreamingResponse = class {
1003
+ constructor(connection, id) {
1004
+ this._closed = false;
1005
+ this._connection = connection;
1006
+ this._id = id;
1007
+ }
1008
+ /**
1009
+ * Send a chunk of data to the client
1010
+ * @param chunk The data to send
1011
+ */
1012
+ send(chunk) {
1013
+ if (this._closed) {
1014
+ throw new Error("StreamingResponse is already closed");
1015
+ }
1016
+ const response = {
1017
+ done: false,
1018
+ id: this._id,
1019
+ result: chunk,
1020
+ success: true,
1021
+ type: "rpc"
1022
+ };
1023
+ this._connection.send(JSON.stringify(response));
1024
+ }
1025
+ /**
1026
+ * End the stream and send the final chunk (if any)
1027
+ * @param finalChunk Optional final chunk of data to send
1028
+ */
1029
+ end(finalChunk) {
1030
+ if (this._closed) {
1031
+ throw new Error("StreamingResponse is already closed");
1032
+ }
1033
+ this._closed = true;
1034
+ const response = {
1035
+ done: true,
1036
+ id: this._id,
1037
+ result: finalChunk,
1038
+ success: true,
1039
+ type: "rpc"
1040
+ };
1041
+ this._connection.send(JSON.stringify(response));
1042
+ }
1043
+ };
1044
+
1045
+ // src/observability/index.ts
1046
+ var genericObservability = {
1047
+ emit(event) {
1048
+ if (isLocalMode()) {
1049
+ console.log(event.displayMessage);
1050
+ return;
1051
+ }
1052
+ console.log(event);
1053
+ }
1054
+ };
1055
+ var localMode = false;
1056
+ function isLocalMode() {
1057
+ if (localMode) {
1058
+ return true;
1059
+ }
1060
+ const { request } = getCurrentAgent();
1061
+ if (!request) {
1062
+ return false;
1063
+ }
1064
+ const url = new URL(request.url);
1065
+ localMode = url.hostname === "localhost";
1066
+ return localMode;
1067
+ }
1068
+
1069
+ export {
1070
+ genericObservability,
1071
+ unstable_callable,
1072
+ getCurrentAgent,
1073
+ Agent,
1074
+ routeAgentRequest,
1075
+ createHeaderBasedEmailResolver,
1076
+ createAddressBasedEmailResolver,
1077
+ createCatchAllEmailResolver,
1078
+ routeAgentEmail,
1079
+ getAgentByName,
1080
+ StreamingResponse
1081
+ };
1082
+ //# sourceMappingURL=chunk-MGHXAF5T.js.map