agents 0.0.0-df41827 → 0.0.0-df52d4b

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 +128 -22
  2. package/dist/ai-chat-agent.d.ts +5 -2
  3. package/dist/ai-chat-agent.js +24 -4
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +6 -3
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/{chunk-ZRRXJUAA.js → chunk-DQJFYHG3.js} +595 -93
  8. package/dist/chunk-DQJFYHG3.js.map +1 -0
  9. package/dist/{chunk-E3LCYPCB.js → chunk-EM3J4KV7.js} +147 -18
  10. package/dist/chunk-EM3J4KV7.js.map +1 -0
  11. package/dist/{chunk-NKZZ66QY.js → chunk-KUH345EY.js} +1 -1
  12. package/dist/chunk-KUH345EY.js.map +1 -0
  13. package/dist/{chunk-767EASBA.js → chunk-PVQZBKN7.js} +1 -1
  14. package/dist/chunk-PVQZBKN7.js.map +1 -0
  15. package/dist/client-DgyzBU_8.d.ts +4601 -0
  16. package/dist/client.d.ts +2 -2
  17. package/dist/client.js +1 -1
  18. package/dist/index.d.ts +152 -16
  19. package/dist/index.js +10 -4
  20. package/dist/mcp/client.d.ts +9 -781
  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 +35 -7
  24. package/dist/mcp/index.js +190 -18
  25. package/dist/mcp/index.js.map +1 -1
  26. package/dist/observability/index.d.ts +46 -0
  27. package/dist/observability/index.js +10 -0
  28. package/dist/observability/index.js.map +1 -0
  29. package/dist/react.d.ts +8 -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 +34 -26
  34. package/src/index.ts +799 -134
  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-EM3J4KV7.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,71 @@ 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: {
114
+ callback: row.callback,
115
+ id: row.id
116
+ },
117
+ timestamp: Date.now(),
118
+ type: "schedule:execute"
119
+ },
120
+ this.ctx
121
+ );
122
+ await callback.bind(this)(JSON.parse(row.payload), row);
123
+ } catch (e) {
124
+ console.error(`error executing callback "${row.callback}"`, e);
125
+ }
126
+ }
127
+ );
128
+ if (row.type === "cron") {
129
+ const nextExecutionTime = getNextCronTime(row.cron);
130
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
131
+ this.sql`
98
132
  UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
99
133
  `;
100
- } else {
101
- this.sql`
134
+ } else {
135
+ this.sql`
102
136
  DELETE FROM cf_agents_schedules WHERE id = ${row.id}
103
137
  `;
138
+ }
104
139
  }
105
140
  }
106
141
  await this._scheduleNextAlarm();
107
142
  };
143
+ this._autoWrapCustomMethods();
108
144
  this.sql`
109
145
  CREATE TABLE IF NOT EXISTS cf_agents_state (
110
146
  id TEXT PRIMARY KEY NOT NULL,
111
147
  state TEXT
112
148
  )
113
149
  `;
150
+ this.sql`
151
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
152
+ id TEXT PRIMARY KEY NOT NULL,
153
+ payload TEXT,
154
+ callback TEXT,
155
+ created_at INTEGER DEFAULT (unixepoch())
156
+ )
157
+ `;
114
158
  void this.ctx.blockConcurrencyWhile(async () => {
115
159
  return this._tryCatch(async () => {
116
160
  this.sql`
@@ -142,7 +186,7 @@ var Agent = class extends Server {
142
186
  const _onRequest = this.onRequest.bind(this);
143
187
  this.onRequest = (request) => {
144
188
  return agentContext.run(
145
- { agent: this, connection: void 0, request },
189
+ { agent: this, connection: void 0, request, email: void 0 },
146
190
  async () => {
147
191
  if (this.mcp.isCallbackRequest(request)) {
148
192
  await this.mcp.handleCallbackRequest(request);
@@ -164,7 +208,7 @@ var Agent = class extends Server {
164
208
  const _onMessage = this.onMessage.bind(this);
165
209
  this.onMessage = async (connection, message) => {
166
210
  return agentContext.run(
167
- { agent: this, connection, request: void 0 },
211
+ { agent: this, connection, request: void 0, email: void 0 },
168
212
  async () => {
169
213
  if (typeof message !== "string") {
170
214
  return this._tryCatch(() => _onMessage(connection, message));
@@ -196,6 +240,19 @@ var Agent = class extends Server {
196
240
  return;
197
241
  }
198
242
  const result = await methodFn.apply(this, args);
243
+ this.observability?.emit(
244
+ {
245
+ displayMessage: `RPC call to ${method}`,
246
+ id: nanoid(),
247
+ payload: {
248
+ method,
249
+ streaming: metadata?.streaming
250
+ },
251
+ timestamp: Date.now(),
252
+ type: "rpc"
253
+ },
254
+ this.ctx
255
+ );
199
256
  const response = {
200
257
  done: true,
201
258
  id,
@@ -223,7 +280,7 @@ var Agent = class extends Server {
223
280
  const _onConnect = this.onConnect.bind(this);
224
281
  this.onConnect = (connection, ctx2) => {
225
282
  return agentContext.run(
226
- { agent: this, connection, request: ctx2.request },
283
+ { agent: this, connection, request: ctx2.request, email: void 0 },
227
284
  async () => {
228
285
  setTimeout(() => {
229
286
  if (this.state) {
@@ -240,6 +297,18 @@ var Agent = class extends Server {
240
297
  type: "cf_agent_mcp_servers"
241
298
  })
242
299
  );
300
+ this.observability?.emit(
301
+ {
302
+ displayMessage: "Connection established",
303
+ id: nanoid(),
304
+ payload: {
305
+ connectionId: connection.id
306
+ },
307
+ timestamp: Date.now(),
308
+ type: "connect"
309
+ },
310
+ this.ctx
311
+ );
243
312
  return this._tryCatch(() => _onConnect(connection, ctx2));
244
313
  }, 20);
245
314
  }
@@ -248,32 +317,57 @@ var Agent = class extends Server {
248
317
  const _onStart = this.onStart.bind(this);
249
318
  this.onStart = async () => {
250
319
  return agentContext.run(
251
- { agent: this, connection: void 0, request: void 0 },
320
+ {
321
+ agent: this,
322
+ connection: void 0,
323
+ request: void 0,
324
+ email: void 0
325
+ },
252
326
  async () => {
253
- const servers = this.sql`
327
+ await this._tryCatch(() => {
328
+ const servers = this.sql`
254
329
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
255
330
  `;
256
- await Promise.allSettled(
257
- servers.filter((server) => server.auth_url === null).map((server) => {
258
- return this._connectToMcpServerInternal(
259
- server.name,
260
- server.server_url,
261
- server.callback_url,
262
- server.server_options ? JSON.parse(server.server_options) : void 0,
263
- {
264
- id: server.id,
265
- oauthClientId: server.client_id ?? void 0
266
- }
267
- );
268
- })
269
- );
270
- this.broadcast(
271
- JSON.stringify({
272
- mcp: this.getMcpServers(),
273
- type: "cf_agent_mcp_servers"
274
- })
275
- );
276
- await this._tryCatch(() => _onStart());
331
+ this.broadcast(
332
+ JSON.stringify({
333
+ mcp: this.getMcpServers(),
334
+ type: "cf_agent_mcp_servers"
335
+ })
336
+ );
337
+ if (servers && Array.isArray(servers) && servers.length > 0) {
338
+ servers.forEach((server) => {
339
+ this._connectToMcpServerInternal(
340
+ server.name,
341
+ server.server_url,
342
+ server.callback_url,
343
+ server.server_options ? JSON.parse(server.server_options) : void 0,
344
+ {
345
+ id: server.id,
346
+ oauthClientId: server.client_id ?? void 0
347
+ }
348
+ ).then(() => {
349
+ this.broadcast(
350
+ JSON.stringify({
351
+ mcp: this.getMcpServers(),
352
+ type: "cf_agent_mcp_servers"
353
+ })
354
+ );
355
+ }).catch((error) => {
356
+ console.error(
357
+ `Error connecting to MCP server: ${server.name} (${server.server_url})`,
358
+ error
359
+ );
360
+ this.broadcast(
361
+ JSON.stringify({
362
+ mcp: this.getMcpServers(),
363
+ type: "cf_agent_mcp_servers"
364
+ })
365
+ );
366
+ });
367
+ });
368
+ }
369
+ return _onStart();
370
+ });
277
371
  }
278
372
  );
279
373
  };
@@ -341,10 +435,20 @@ var Agent = class extends Server {
341
435
  source !== "server" ? [source.id] : []
342
436
  );
343
437
  return this._tryCatch(() => {
344
- const { connection, request } = agentContext.getStore() || {};
438
+ const { connection, request, email } = agentContext.getStore() || {};
345
439
  return agentContext.run(
346
- { agent: this, connection, request },
440
+ { agent: this, connection, request, email },
347
441
  async () => {
442
+ this.observability?.emit(
443
+ {
444
+ displayMessage: "State updated",
445
+ id: nanoid(),
446
+ payload: {},
447
+ timestamp: Date.now(),
448
+ type: "state:update"
449
+ },
450
+ this.ctx
451
+ );
348
452
  return this.onStateUpdate(state, source);
349
453
  }
350
454
  );
@@ -366,18 +470,67 @@ var Agent = class extends Server {
366
470
  onStateUpdate(state, source) {
367
471
  }
368
472
  /**
369
- * Called when the Agent receives an email
473
+ * Called when the Agent receives an email via routeAgentEmail()
474
+ * Override this method to handle incoming emails
370
475
  * @param email Email message to process
371
476
  */
372
- // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
373
- onEmail(email) {
477
+ async _onEmail(email) {
374
478
  return agentContext.run(
375
- { agent: this, connection: void 0, request: void 0 },
479
+ { agent: this, connection: void 0, request: void 0, email },
376
480
  async () => {
377
- console.error("onEmail not implemented");
481
+ if ("onEmail" in this && typeof this.onEmail === "function") {
482
+ return this._tryCatch(
483
+ () => this.onEmail(email)
484
+ );
485
+ } else {
486
+ console.log("Received email from:", email.from, "to:", email.to);
487
+ console.log("Subject:", email.headers.get("subject"));
488
+ console.log(
489
+ "Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
490
+ );
491
+ }
378
492
  }
379
493
  );
380
494
  }
495
+ /**
496
+ * Reply to an email
497
+ * @param email The email to reply to
498
+ * @param options Options for the reply
499
+ * @returns void
500
+ */
501
+ async replyToEmail(email, options) {
502
+ return this._tryCatch(async () => {
503
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
504
+ const agentId = this.name;
505
+ const { createMimeMessage } = await import("mimetext");
506
+ const msg = createMimeMessage();
507
+ msg.setSender({ addr: email.to, name: options.fromName });
508
+ msg.setRecipient(email.from);
509
+ msg.setSubject(
510
+ options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
511
+ );
512
+ msg.addMessage({
513
+ contentType: options.contentType || "text/plain",
514
+ data: options.body
515
+ });
516
+ const domain = email.from.split("@")[1];
517
+ const messageId = `<${agentId}@${domain}>`;
518
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID"));
519
+ msg.setHeader("Message-ID", messageId);
520
+ msg.setHeader("X-Agent-Name", agentName);
521
+ msg.setHeader("X-Agent-ID", agentId);
522
+ if (options.headers) {
523
+ for (const [key, value] of Object.entries(options.headers)) {
524
+ msg.setHeader(key, value);
525
+ }
526
+ }
527
+ await email.reply({
528
+ from: email.to,
529
+ raw: msg.asRaw(),
530
+ to: email.from
531
+ });
532
+ });
533
+ }
381
534
  async _tryCatch(fn) {
382
535
  try {
383
536
  return await fn();
@@ -385,6 +538,55 @@ var Agent = class extends Server {
385
538
  throw this.onError(e);
386
539
  }
387
540
  }
541
+ /**
542
+ * Automatically wrap custom methods with agent context
543
+ * This ensures getCurrentAgent() works in all custom methods without decorators
544
+ */
545
+ _autoWrapCustomMethods() {
546
+ const basePrototypes = [_Agent.prototype, Server.prototype];
547
+ const baseMethods = /* @__PURE__ */ new Set();
548
+ for (const baseProto of basePrototypes) {
549
+ let proto2 = baseProto;
550
+ while (proto2 && proto2 !== Object.prototype) {
551
+ const methodNames = Object.getOwnPropertyNames(proto2);
552
+ for (const methodName of methodNames) {
553
+ baseMethods.add(methodName);
554
+ }
555
+ proto2 = Object.getPrototypeOf(proto2);
556
+ }
557
+ }
558
+ let proto = Object.getPrototypeOf(this);
559
+ let depth = 0;
560
+ while (proto && proto !== Object.prototype && depth < 10) {
561
+ const methodNames = Object.getOwnPropertyNames(proto);
562
+ for (const methodName of methodNames) {
563
+ if (baseMethods.has(methodName) || methodName.startsWith("_") || typeof this[methodName] !== "function") {
564
+ continue;
565
+ }
566
+ if (!baseMethods.has(methodName)) {
567
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
568
+ if (descriptor && typeof descriptor.value === "function") {
569
+ const wrappedFunction = withAgentContext(
570
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
571
+ this[methodName]
572
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
573
+ );
574
+ if (this._isCallable(methodName)) {
575
+ callableMetadata.set(
576
+ wrappedFunction,
577
+ callableMetadata.get(
578
+ this[methodName]
579
+ )
580
+ );
581
+ }
582
+ this.constructor.prototype[methodName] = wrappedFunction;
583
+ }
584
+ }
585
+ }
586
+ proto = Object.getPrototypeOf(proto);
587
+ depth++;
588
+ }
589
+ }
388
590
  onError(connectionOrError, error) {
389
591
  let theError;
390
592
  if (connectionOrError && error) {
@@ -410,6 +612,108 @@ var Agent = class extends Server {
410
612
  render() {
411
613
  throw new Error("Not implemented");
412
614
  }
615
+ /**
616
+ * Queue a task to be executed in the future
617
+ * @param payload Payload to pass to the callback
618
+ * @param callback Name of the method to call
619
+ * @returns The ID of the queued task
620
+ */
621
+ async queue(callback, payload) {
622
+ const id = nanoid(9);
623
+ if (typeof callback !== "string") {
624
+ throw new Error("Callback must be a string");
625
+ }
626
+ if (typeof this[callback] !== "function") {
627
+ throw new Error(`this.${callback} is not a function`);
628
+ }
629
+ this.sql`
630
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
631
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
632
+ `;
633
+ void this._flushQueue().catch((e) => {
634
+ console.error("Error flushing queue:", e);
635
+ });
636
+ return id;
637
+ }
638
+ async _flushQueue() {
639
+ if (this._flushingQueue) {
640
+ return;
641
+ }
642
+ this._flushingQueue = true;
643
+ while (true) {
644
+ const result = this.sql`
645
+ SELECT * FROM cf_agents_queues
646
+ ORDER BY created_at ASC
647
+ `;
648
+ if (!result || result.length === 0) {
649
+ break;
650
+ }
651
+ for (const row of result || []) {
652
+ const callback = this[row.callback];
653
+ if (!callback) {
654
+ console.error(`callback ${row.callback} not found`);
655
+ continue;
656
+ }
657
+ const { connection, request, email } = agentContext.getStore() || {};
658
+ await agentContext.run(
659
+ {
660
+ agent: this,
661
+ connection,
662
+ request,
663
+ email
664
+ },
665
+ async () => {
666
+ await callback.bind(this)(JSON.parse(row.payload), row);
667
+ await this.dequeue(row.id);
668
+ }
669
+ );
670
+ }
671
+ }
672
+ this._flushingQueue = false;
673
+ }
674
+ /**
675
+ * Dequeue a task by ID
676
+ * @param id ID of the task to dequeue
677
+ */
678
+ async dequeue(id) {
679
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
680
+ }
681
+ /**
682
+ * Dequeue all tasks
683
+ */
684
+ async dequeueAll() {
685
+ this.sql`DELETE FROM cf_agents_queues`;
686
+ }
687
+ /**
688
+ * Dequeue all tasks by callback
689
+ * @param callback Name of the callback to dequeue
690
+ */
691
+ async dequeueAllByCallback(callback) {
692
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
693
+ }
694
+ /**
695
+ * Get a queued task by ID
696
+ * @param id ID of the task to get
697
+ * @returns The task or undefined if not found
698
+ */
699
+ async getQueue(id) {
700
+ const result = this.sql`
701
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
702
+ `;
703
+ return result ? { ...result[0], payload: JSON.parse(result[0].payload) } : void 0;
704
+ }
705
+ /**
706
+ * Get all queues by key and value
707
+ * @param key Key to filter by
708
+ * @param value Value to filter by
709
+ * @returns Array of matching QueueItem objects
710
+ */
711
+ async getQueues(key, value) {
712
+ const result = this.sql`
713
+ SELECT * FROM cf_agents_queues
714
+ `;
715
+ return result.filter((row) => JSON.parse(row.payload)[key] === value);
716
+ }
413
717
  /**
414
718
  * Schedule a task to be executed in the future
415
719
  * @template T Type of the payload data
@@ -420,6 +724,19 @@ var Agent = class extends Server {
420
724
  */
421
725
  async schedule(when, callback, payload) {
422
726
  const id = nanoid(9);
727
+ const emitScheduleCreate = (schedule) => this.observability?.emit(
728
+ {
729
+ displayMessage: `Schedule ${schedule.id} created`,
730
+ id: nanoid(),
731
+ payload: {
732
+ callback,
733
+ id
734
+ },
735
+ timestamp: Date.now(),
736
+ type: "schedule:create"
737
+ },
738
+ this.ctx
739
+ );
423
740
  if (typeof callback !== "string") {
424
741
  throw new Error("Callback must be a string");
425
742
  }
@@ -435,13 +752,15 @@ var Agent = class extends Server {
435
752
  )}, 'scheduled', ${timestamp})
436
753
  `;
437
754
  await this._scheduleNextAlarm();
438
- return {
755
+ const schedule = {
439
756
  callback,
440
757
  id,
441
758
  payload,
442
759
  time: timestamp,
443
760
  type: "scheduled"
444
761
  };
762
+ emitScheduleCreate(schedule);
763
+ return schedule;
445
764
  }
446
765
  if (typeof when === "number") {
447
766
  const time = new Date(Date.now() + when * 1e3);
@@ -453,7 +772,7 @@ var Agent = class extends Server {
453
772
  )}, 'delayed', ${when}, ${timestamp})
454
773
  `;
455
774
  await this._scheduleNextAlarm();
456
- return {
775
+ const schedule = {
457
776
  callback,
458
777
  delayInSeconds: when,
459
778
  id,
@@ -461,6 +780,8 @@ var Agent = class extends Server {
461
780
  time: timestamp,
462
781
  type: "delayed"
463
782
  };
783
+ emitScheduleCreate(schedule);
784
+ return schedule;
464
785
  }
465
786
  if (typeof when === "string") {
466
787
  const nextExecutionTime = getNextCronTime(when);
@@ -472,7 +793,7 @@ var Agent = class extends Server {
472
793
  )}, 'cron', ${when}, ${timestamp})
473
794
  `;
474
795
  await this._scheduleNextAlarm();
475
- return {
796
+ const schedule = {
476
797
  callback,
477
798
  cron: when,
478
799
  id,
@@ -480,6 +801,8 @@ var Agent = class extends Server {
480
801
  time: timestamp,
481
802
  type: "cron"
482
803
  };
804
+ emitScheduleCreate(schedule);
805
+ return schedule;
483
806
  }
484
807
  throw new Error("Invalid schedule type");
485
808
  }
@@ -537,15 +860,31 @@ var Agent = class extends Server {
537
860
  * @returns true if the task was cancelled, false otherwise
538
861
  */
539
862
  async cancelSchedule(id) {
863
+ const schedule = await this.getSchedule(id);
864
+ if (schedule) {
865
+ this.observability?.emit(
866
+ {
867
+ displayMessage: `Schedule ${id} cancelled`,
868
+ id: nanoid(),
869
+ payload: {
870
+ callback: schedule.callback,
871
+ id: schedule.id
872
+ },
873
+ timestamp: Date.now(),
874
+ type: "schedule:cancel"
875
+ },
876
+ this.ctx
877
+ );
878
+ }
540
879
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
541
880
  await this._scheduleNextAlarm();
542
881
  return true;
543
882
  }
544
883
  async _scheduleNextAlarm() {
545
884
  const result = this.sql`
546
- SELECT time FROM cf_agents_schedules
885
+ SELECT time FROM cf_agents_schedules
547
886
  WHERE time > ${Math.floor(Date.now() / 1e3)}
548
- ORDER BY time ASC
887
+ ORDER BY time ASC
549
888
  LIMIT 1
550
889
  `;
551
890
  if (!result) return;
@@ -561,9 +900,20 @@ var Agent = class extends Server {
561
900
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
562
901
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
563
902
  this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
903
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
564
904
  await this.ctx.storage.deleteAlarm();
565
905
  await this.ctx.storage.deleteAll();
566
906
  this.ctx.abort("destroyed");
907
+ this.observability?.emit(
908
+ {
909
+ displayMessage: "Agent destroyed",
910
+ id: nanoid(),
911
+ payload: {},
912
+ timestamp: Date.now(),
913
+ type: "destroy"
914
+ },
915
+ this.ctx
916
+ );
567
917
  }
568
918
  /**
569
919
  * Get all methods marked as callable on this Agent
@@ -589,6 +939,19 @@ var Agent = class extends Server {
589
939
  callbackUrl,
590
940
  options
591
941
  );
942
+ this.sql`
943
+ INSERT
944
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
945
+ VALUES (
946
+ ${result.id},
947
+ ${serverName},
948
+ ${url},
949
+ ${result.clientId ?? null},
950
+ ${result.authUrl ?? null},
951
+ ${callbackUrl},
952
+ ${options ? JSON.stringify(options) : null}
953
+ );
954
+ `;
592
955
  this.broadcast(
593
956
  JSON.stringify({
594
957
  mcp: this.getMcpServers(),
@@ -597,7 +960,7 @@ var Agent = class extends Server {
597
960
  );
598
961
  return result;
599
962
  }
600
- async _connectToMcpServerInternal(serverName, url, callbackUrl, options, reconnect) {
963
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
601
964
  const authProvider = new DurableObjectOAuthClientProvider(
602
965
  this.ctx.storage,
603
966
  this.name,
@@ -631,20 +994,9 @@ var Agent = class extends Server {
631
994
  authProvider
632
995
  }
633
996
  });
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
997
  return {
647
998
  authUrl,
999
+ clientId,
648
1000
  id
649
1001
  };
650
1002
  }
@@ -670,17 +1022,19 @@ var Agent = class extends Server {
670
1022
  const servers = this.sql`
671
1023
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
672
1024
  `;
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
- };
1025
+ if (servers && Array.isArray(servers) && servers.length > 0) {
1026
+ for (const server of servers) {
1027
+ const serverConn = this.mcp.mcpConnections[server.id];
1028
+ mcpState.servers[server.id] = {
1029
+ auth_url: server.auth_url,
1030
+ capabilities: serverConn?.serverCapabilities ?? null,
1031
+ instructions: serverConn?.instructions ?? null,
1032
+ name: server.name,
1033
+ server_url: server.server_url,
1034
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1035
+ state: serverConn?.connectionState ?? "authenticating"
1036
+ };
1037
+ }
684
1038
  }
685
1039
  return mcpState;
686
1040
  }
@@ -688,11 +1042,12 @@ var Agent = class extends Server {
688
1042
  /**
689
1043
  * Agent configuration options
690
1044
  */
691
- Agent.options = {
1045
+ _Agent.options = {
692
1046
  /** Whether the Agent should hibernate when inactive */
693
1047
  hibernate: true
694
1048
  // default to hibernate
695
1049
  };
1050
+ var Agent = _Agent;
696
1051
  async function routeAgentRequest(request, env, options) {
697
1052
  const corsHeaders = options?.cors === true ? {
698
1053
  "Access-Control-Allow-Credentials": "true",
@@ -728,7 +1083,126 @@ async function routeAgentRequest(request, env, options) {
728
1083
  }
729
1084
  return response;
730
1085
  }
731
- async function routeAgentEmail(_email, _env, _options) {
1086
+ function createHeaderBasedEmailResolver() {
1087
+ return async (email, _env) => {
1088
+ const messageId = email.headers.get("message-id");
1089
+ if (messageId) {
1090
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1091
+ if (messageIdMatch) {
1092
+ const [, agentId2, domain] = messageIdMatch;
1093
+ const agentName2 = domain.split(".")[0];
1094
+ return { agentName: agentName2, agentId: agentId2 };
1095
+ }
1096
+ }
1097
+ const references = email.headers.get("references");
1098
+ if (references) {
1099
+ const referencesMatch = references.match(
1100
+ /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
1101
+ );
1102
+ if (referencesMatch) {
1103
+ const [, base64Id, domain] = referencesMatch;
1104
+ const agentId2 = Buffer.from(base64Id, "base64").toString("hex");
1105
+ const agentName2 = domain.split(".")[0];
1106
+ return { agentName: agentName2, agentId: agentId2 };
1107
+ }
1108
+ }
1109
+ const agentName = email.headers.get("x-agent-name");
1110
+ const agentId = email.headers.get("x-agent-id");
1111
+ if (agentName && agentId) {
1112
+ return { agentName, agentId };
1113
+ }
1114
+ return null;
1115
+ };
1116
+ }
1117
+ function createAddressBasedEmailResolver(defaultAgentName) {
1118
+ return async (email, _env) => {
1119
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1120
+ if (!emailMatch) {
1121
+ return null;
1122
+ }
1123
+ const [, localPart, subAddress] = emailMatch;
1124
+ if (subAddress) {
1125
+ return {
1126
+ agentName: localPart,
1127
+ agentId: subAddress
1128
+ };
1129
+ }
1130
+ return {
1131
+ agentName: defaultAgentName,
1132
+ agentId: localPart
1133
+ };
1134
+ };
1135
+ }
1136
+ function createCatchAllEmailResolver(agentName, agentId) {
1137
+ return async () => ({ agentName, agentId });
1138
+ }
1139
+ var agentMapCache = /* @__PURE__ */ new WeakMap();
1140
+ async function routeAgentEmail(email, env, options) {
1141
+ const routingInfo = await options.resolver(email, env);
1142
+ if (!routingInfo) {
1143
+ console.warn("No routing information found for email, dropping message");
1144
+ return;
1145
+ }
1146
+ if (!agentMapCache.has(env)) {
1147
+ const map = {};
1148
+ for (const [key, value] of Object.entries(env)) {
1149
+ if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
1150
+ map[key] = value;
1151
+ map[camelCaseToKebabCase(key)] = value;
1152
+ }
1153
+ }
1154
+ agentMapCache.set(env, map);
1155
+ }
1156
+ const agentMap = agentMapCache.get(env);
1157
+ const namespace = agentMap[routingInfo.agentName];
1158
+ if (!namespace) {
1159
+ const availableAgents = Object.keys(agentMap).filter((key) => !key.includes("-")).join(", ");
1160
+ throw new Error(
1161
+ `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`
1162
+ );
1163
+ }
1164
+ const agent = await getAgentByName(
1165
+ namespace,
1166
+ routingInfo.agentId
1167
+ );
1168
+ const serialisableEmail = {
1169
+ getRaw: async () => {
1170
+ const reader = email.raw.getReader();
1171
+ const chunks = [];
1172
+ let done = false;
1173
+ while (!done) {
1174
+ const { value, done: readerDone } = await reader.read();
1175
+ done = readerDone;
1176
+ if (value) {
1177
+ chunks.push(value);
1178
+ }
1179
+ }
1180
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1181
+ const combined = new Uint8Array(totalLength);
1182
+ let offset = 0;
1183
+ for (const chunk of chunks) {
1184
+ combined.set(chunk, offset);
1185
+ offset += chunk.length;
1186
+ }
1187
+ return combined;
1188
+ },
1189
+ headers: email.headers,
1190
+ rawSize: email.rawSize,
1191
+ setReject: (reason) => {
1192
+ email.setReject(reason);
1193
+ },
1194
+ forward: (rcptTo, headers) => {
1195
+ return email.forward(rcptTo, headers);
1196
+ },
1197
+ reply: (options2) => {
1198
+ return email.reply(
1199
+ new EmailMessage(options2.from, options2.to, options2.raw)
1200
+ );
1201
+ },
1202
+ from: email.from,
1203
+ to: email.to
1204
+ };
1205
+ await agent._onEmail(serialisableEmail);
732
1206
  }
733
1207
  async function getAgentByName(namespace, name, options) {
734
1208
  return getServerByName(namespace, name, options);
@@ -776,13 +1250,41 @@ var StreamingResponse = class {
776
1250
  }
777
1251
  };
778
1252
 
1253
+ // src/observability/index.ts
1254
+ var genericObservability = {
1255
+ emit(event) {
1256
+ if (isLocalMode()) {
1257
+ console.log(event.displayMessage);
1258
+ return;
1259
+ }
1260
+ console.log(event);
1261
+ }
1262
+ };
1263
+ var localMode = false;
1264
+ function isLocalMode() {
1265
+ if (localMode) {
1266
+ return true;
1267
+ }
1268
+ const { request } = getCurrentAgent();
1269
+ if (!request) {
1270
+ return false;
1271
+ }
1272
+ const url = new URL(request.url);
1273
+ localMode = url.hostname === "localhost";
1274
+ return localMode;
1275
+ }
1276
+
779
1277
  export {
1278
+ genericObservability,
780
1279
  unstable_callable,
781
1280
  getCurrentAgent,
782
1281
  Agent,
783
1282
  routeAgentRequest,
1283
+ createHeaderBasedEmailResolver,
1284
+ createAddressBasedEmailResolver,
1285
+ createCatchAllEmailResolver,
784
1286
  routeAgentEmail,
785
1287
  getAgentByName,
786
1288
  StreamingResponse
787
1289
  };
788
- //# sourceMappingURL=chunk-ZRRXJUAA.js.map
1290
+ //# sourceMappingURL=chunk-DQJFYHG3.js.map