agents 0.0.0-b4ebb44 → 0.0.0-b5aee9f

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 (38) hide show
  1. package/README.md +127 -22
  2. package/dist/ai-chat-agent.d.ts +5 -2
  3. package/dist/ai-chat-agent.js +34 -4
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +5 -3
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/{chunk-ZRRXJUAA.js → chunk-3IQQY2UH.js} +572 -90
  8. package/dist/chunk-3IQQY2UH.js.map +1 -0
  9. package/dist/{chunk-NKZZ66QY.js → chunk-KUH345EY.js} +1 -1
  10. package/dist/chunk-KUH345EY.js.map +1 -0
  11. package/dist/{chunk-767EASBA.js → chunk-PVQZBKN7.js} +1 -1
  12. package/dist/chunk-PVQZBKN7.js.map +1 -0
  13. package/dist/{chunk-E3LCYPCB.js → chunk-UNG3FXYX.js} +58 -2
  14. package/dist/chunk-UNG3FXYX.js.map +1 -0
  15. package/dist/client.d.ts +2 -2
  16. package/dist/client.js +1 -1
  17. package/dist/index-CLW1aEBr.d.ts +615 -0
  18. package/dist/index.d.ts +34 -404
  19. package/dist/index.js +10 -4
  20. package/dist/mcp/client.d.ts +288 -17
  21. package/dist/mcp/client.js +1 -1
  22. package/dist/mcp/do-oauth-client-provider.js +1 -1
  23. package/dist/mcp/index.d.ts +28 -5
  24. package/dist/mcp/index.js +23 -8
  25. package/dist/mcp/index.js.map +1 -1
  26. package/dist/observability/index.d.ts +14 -0
  27. package/dist/observability/index.js +10 -0
  28. package/dist/observability/index.js.map +1 -0
  29. package/dist/react.d.ts +7 -5
  30. package/dist/react.js.map +1 -1
  31. package/dist/schedule.d.ts +4 -4
  32. package/dist/schedule.js.map +1 -1
  33. package/package.json +8 -3
  34. package/src/index.ts +768 -128
  35. package/dist/chunk-767EASBA.js.map +0 -1
  36. package/dist/chunk-E3LCYPCB.js.map +0 -1
  37. package/dist/chunk-NKZZ66QY.js.map +0 -1
  38. package/dist/chunk-ZRRXJUAA.js.map +0 -1
@@ -1,21 +1,22 @@
1
1
  import {
2
2
  MCPClientManager
3
- } from "./chunk-E3LCYPCB.js";
3
+ } from "./chunk-UNG3FXYX.js";
4
4
  import {
5
5
  DurableObjectOAuthClientProvider
6
- } from "./chunk-767EASBA.js";
6
+ } from "./chunk-PVQZBKN7.js";
7
7
  import {
8
8
  camelCaseToKebabCase
9
- } from "./chunk-NKZZ66QY.js";
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
- var Agent = class extends Server {
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
- 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
- }
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
- if (row.type === "cron") {
95
- const nextExecutionTime = getNextCronTime(row.cron);
96
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
97
- this.sql`
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
- } else {
101
- this.sql`
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,31 +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
- { agent: this, connection: void 0, request: void 0 },
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
- await Promise.allSettled(
257
- servers.filter((server) => server.auth_url === null).map((server) => {
258
- return this._connectToMcpServerInternal(
259
- server.name,
260
- server.server_url,
261
- server.callback_url,
262
- server.server_options ? JSON.parse(server.server_options) : void 0,
263
- {
264
- id: server.id,
265
- oauthClientId: server.client_id ?? void 0
266
- }
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
+ );
342
+ })
343
+ ).then((_results) => {
344
+ this.broadcast(
345
+ JSON.stringify({
346
+ mcp: this.getMcpServers(),
347
+ type: "cf_agent_mcp_servers"
348
+ })
267
349
  );
268
- })
269
- );
270
- this.broadcast(
271
- JSON.stringify({
272
- mcp: this.getMcpServers(),
273
- type: "cf_agent_mcp_servers"
274
- })
275
- );
350
+ });
351
+ }
276
352
  await this._tryCatch(() => _onStart());
277
353
  }
278
354
  );
@@ -324,6 +400,7 @@ var Agent = class extends Server {
324
400
  }
325
401
  }
326
402
  _setStateInternal(state, source = "server") {
403
+ const previousState = this._state;
327
404
  this._state = state;
328
405
  this.sql`
329
406
  INSERT OR REPLACE INTO cf_agents_state (id, state)
@@ -341,10 +418,23 @@ var Agent = class extends Server {
341
418
  source !== "server" ? [source.id] : []
342
419
  );
343
420
  return this._tryCatch(() => {
344
- const { connection, request } = agentContext.getStore() || {};
421
+ const { connection, request, email } = agentContext.getStore() || {};
345
422
  return agentContext.run(
346
- { agent: this, connection, request },
423
+ { agent: this, connection, request, email },
347
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
+ );
348
438
  return this.onStateUpdate(state, source);
349
439
  }
350
440
  );
@@ -366,18 +456,67 @@ var Agent = class extends Server {
366
456
  onStateUpdate(state, source) {
367
457
  }
368
458
  /**
369
- * 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
370
461
  * @param email Email message to process
371
462
  */
372
- // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
373
- onEmail(email) {
463
+ async _onEmail(email) {
374
464
  return agentContext.run(
375
- { agent: this, connection: void 0, request: void 0 },
465
+ { agent: this, connection: void 0, request: void 0, email },
376
466
  async () => {
377
- console.error("onEmail not implemented");
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
+ }
378
478
  }
379
479
  );
380
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
+ }
381
520
  async _tryCatch(fn) {
382
521
  try {
383
522
  return await fn();
@@ -385,6 +524,55 @@ var Agent = class extends Server {
385
524
  throw this.onError(e);
386
525
  }
387
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
+ }
388
576
  onError(connectionOrError, error) {
389
577
  let theError;
390
578
  if (connectionOrError && error) {
@@ -410,6 +598,108 @@ var Agent = class extends Server {
410
598
  render() {
411
599
  throw new Error("Not implemented");
412
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
+ }
413
703
  /**
414
704
  * Schedule a task to be executed in the future
415
705
  * @template T Type of the payload data
@@ -420,6 +710,16 @@ var Agent = class extends Server {
420
710
  */
421
711
  async schedule(when, callback, payload) {
422
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
+ );
423
723
  if (typeof callback !== "string") {
424
724
  throw new Error("Callback must be a string");
425
725
  }
@@ -435,13 +735,15 @@ var Agent = class extends Server {
435
735
  )}, 'scheduled', ${timestamp})
436
736
  `;
437
737
  await this._scheduleNextAlarm();
438
- return {
738
+ const schedule = {
439
739
  callback,
440
740
  id,
441
741
  payload,
442
742
  time: timestamp,
443
743
  type: "scheduled"
444
744
  };
745
+ emitScheduleCreate(schedule);
746
+ return schedule;
445
747
  }
446
748
  if (typeof when === "number") {
447
749
  const time = new Date(Date.now() + when * 1e3);
@@ -453,7 +755,7 @@ var Agent = class extends Server {
453
755
  )}, 'delayed', ${when}, ${timestamp})
454
756
  `;
455
757
  await this._scheduleNextAlarm();
456
- return {
758
+ const schedule = {
457
759
  callback,
458
760
  delayInSeconds: when,
459
761
  id,
@@ -461,6 +763,8 @@ var Agent = class extends Server {
461
763
  time: timestamp,
462
764
  type: "delayed"
463
765
  };
766
+ emitScheduleCreate(schedule);
767
+ return schedule;
464
768
  }
465
769
  if (typeof when === "string") {
466
770
  const nextExecutionTime = getNextCronTime(when);
@@ -472,7 +776,7 @@ var Agent = class extends Server {
472
776
  )}, 'cron', ${when}, ${timestamp})
473
777
  `;
474
778
  await this._scheduleNextAlarm();
475
- return {
779
+ const schedule = {
476
780
  callback,
477
781
  cron: when,
478
782
  id,
@@ -480,6 +784,8 @@ var Agent = class extends Server {
480
784
  time: timestamp,
481
785
  type: "cron"
482
786
  };
787
+ emitScheduleCreate(schedule);
788
+ return schedule;
483
789
  }
484
790
  throw new Error("Invalid schedule type");
485
791
  }
@@ -537,15 +843,28 @@ var Agent = class extends Server {
537
843
  * @returns true if the task was cancelled, false otherwise
538
844
  */
539
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
+ }
540
859
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
541
860
  await this._scheduleNextAlarm();
542
861
  return true;
543
862
  }
544
863
  async _scheduleNextAlarm() {
545
864
  const result = this.sql`
546
- SELECT time FROM cf_agents_schedules
865
+ SELECT time FROM cf_agents_schedules
547
866
  WHERE time > ${Math.floor(Date.now() / 1e3)}
548
- ORDER BY time ASC
867
+ ORDER BY time ASC
549
868
  LIMIT 1
550
869
  `;
551
870
  if (!result) return;
@@ -561,9 +880,20 @@ var Agent = class extends Server {
561
880
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
562
881
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
563
882
  this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
883
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
564
884
  await this.ctx.storage.deleteAlarm();
565
885
  await this.ctx.storage.deleteAll();
566
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
+ );
567
897
  }
568
898
  /**
569
899
  * Get all methods marked as callable on this Agent
@@ -589,6 +919,19 @@ var Agent = class extends Server {
589
919
  callbackUrl,
590
920
  options
591
921
  );
922
+ this.sql`
923
+ INSERT
924
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
925
+ VALUES (
926
+ ${result.id},
927
+ ${serverName},
928
+ ${url},
929
+ ${result.clientId ?? null},
930
+ ${result.authUrl ?? null},
931
+ ${callbackUrl},
932
+ ${options ? JSON.stringify(options) : null}
933
+ );
934
+ `;
592
935
  this.broadcast(
593
936
  JSON.stringify({
594
937
  mcp: this.getMcpServers(),
@@ -597,7 +940,7 @@ var Agent = class extends Server {
597
940
  );
598
941
  return result;
599
942
  }
600
- async _connectToMcpServerInternal(serverName, url, callbackUrl, options, reconnect) {
943
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
601
944
  const authProvider = new DurableObjectOAuthClientProvider(
602
945
  this.ctx.storage,
603
946
  this.name,
@@ -631,20 +974,9 @@ var Agent = class extends Server {
631
974
  authProvider
632
975
  }
633
976
  });
634
- this.sql`
635
- INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
636
- VALUES (
637
- ${id},
638
- ${serverName},
639
- ${url},
640
- ${clientId ?? null},
641
- ${authUrl ?? null},
642
- ${callbackUrl},
643
- ${options ? JSON.stringify(options) : null}
644
- );
645
- `;
646
977
  return {
647
978
  authUrl,
979
+ clientId,
648
980
  id
649
981
  };
650
982
  }
@@ -670,17 +1002,19 @@ var Agent = class extends Server {
670
1002
  const servers = this.sql`
671
1003
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
672
1004
  `;
673
- for (const server of servers) {
674
- const serverConn = this.mcp.mcpConnections[server.id];
675
- mcpState.servers[server.id] = {
676
- auth_url: server.auth_url,
677
- capabilities: serverConn?.serverCapabilities ?? null,
678
- instructions: serverConn?.instructions ?? null,
679
- name: server.name,
680
- server_url: server.server_url,
681
- // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
682
- state: serverConn?.connectionState ?? "authenticating"
683
- };
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
+ }
684
1018
  }
685
1019
  return mcpState;
686
1020
  }
@@ -688,11 +1022,12 @@ var Agent = class extends Server {
688
1022
  /**
689
1023
  * Agent configuration options
690
1024
  */
691
- Agent.options = {
1025
+ _Agent.options = {
692
1026
  /** Whether the Agent should hibernate when inactive */
693
1027
  hibernate: true
694
1028
  // default to hibernate
695
1029
  };
1030
+ var Agent = _Agent;
696
1031
  async function routeAgentRequest(request, env, options) {
697
1032
  const corsHeaders = options?.cors === true ? {
698
1033
  "Access-Control-Allow-Credentials": "true",
@@ -728,7 +1063,126 @@ async function routeAgentRequest(request, env, options) {
728
1063
  }
729
1064
  return response;
730
1065
  }
731
- async function routeAgentEmail(_email, _env, _options) {
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);
732
1186
  }
733
1187
  async function getAgentByName(namespace, name, options) {
734
1188
  return getServerByName(namespace, name, options);
@@ -776,13 +1230,41 @@ var StreamingResponse = class {
776
1230
  }
777
1231
  };
778
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
+
779
1257
  export {
1258
+ genericObservability,
780
1259
  unstable_callable,
781
1260
  getCurrentAgent,
782
1261
  Agent,
783
1262
  routeAgentRequest,
1263
+ createHeaderBasedEmailResolver,
1264
+ createAddressBasedEmailResolver,
1265
+ createCatchAllEmailResolver,
784
1266
  routeAgentEmail,
785
1267
  getAgentByName,
786
1268
  StreamingResponse
787
1269
  };
788
- //# sourceMappingURL=chunk-ZRRXJUAA.js.map
1270
+ //# sourceMappingURL=chunk-3IQQY2UH.js.map