agents 0.0.0-eeb70e2 → 0.0.0-f31397c

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 (41) hide show
  1. package/README.md +22 -22
  2. package/dist/ai-chat-agent.d.ts +4 -3
  3. package/dist/ai-chat-agent.js +64 -26
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +9 -9
  6. package/dist/ai-react.js +27 -27
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/{chunk-VCSB47AK.js → chunk-KUH345EY.js} +8 -8
  9. package/dist/chunk-KUH345EY.js.map +1 -0
  10. package/dist/{chunk-P3RZJ72N.js → chunk-MFNGQLFL.js} +602 -125
  11. package/dist/chunk-MFNGQLFL.js.map +1 -0
  12. package/dist/{chunk-OYJXQRRH.js → chunk-MW5BQ2FW.js} +22 -18
  13. package/dist/chunk-MW5BQ2FW.js.map +1 -0
  14. package/dist/{chunk-BZXOAZUX.js → chunk-PVQZBKN7.js} +5 -5
  15. package/dist/chunk-PVQZBKN7.js.map +1 -0
  16. package/dist/client.d.ts +2 -2
  17. package/dist/client.js +1 -1
  18. package/dist/index-BIJvkfYt.d.ts +614 -0
  19. package/dist/index.d.ts +33 -405
  20. package/dist/index.js +10 -4
  21. package/dist/mcp/client.d.ts +281 -9
  22. package/dist/mcp/client.js +1 -1
  23. package/dist/mcp/do-oauth-client-provider.js +1 -1
  24. package/dist/mcp/index.d.ts +9 -9
  25. package/dist/mcp/index.js +50 -49
  26. package/dist/mcp/index.js.map +1 -1
  27. package/dist/observability/index.d.ts +12 -0
  28. package/dist/observability/index.js +10 -0
  29. package/dist/observability/index.js.map +1 -0
  30. package/dist/react.d.ts +8 -8
  31. package/dist/react.js +7 -7
  32. package/dist/react.js.map +1 -1
  33. package/dist/schedule.d.ts +6 -6
  34. package/dist/schedule.js +4 -4
  35. package/dist/schedule.js.map +1 -1
  36. package/package.json +76 -71
  37. package/src/index.ts +777 -155
  38. package/dist/chunk-BZXOAZUX.js.map +0 -1
  39. package/dist/chunk-OYJXQRRH.js.map +0 -1
  40. package/dist/chunk-P3RZJ72N.js.map +0 -1
  41. package/dist/chunk-VCSB47AK.js.map +0 -1
@@ -1,22 +1,23 @@
1
1
  import {
2
2
  MCPClientManager
3
- } from "./chunk-OYJXQRRH.js";
3
+ } from "./chunk-MW5BQ2FW.js";
4
4
  import {
5
5
  DurableObjectOAuthClientProvider
6
- } from "./chunk-BZXOAZUX.js";
6
+ } from "./chunk-PVQZBKN7.js";
7
7
  import {
8
8
  camelCaseToKebabCase
9
- } from "./chunk-VCSB47AK.js";
9
+ } from "./chunk-KUH345EY.js";
10
10
 
11
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";
12
16
  import {
13
17
  Server,
14
18
  getServerByName,
15
19
  routePartykitRequest
16
20
  } from "partyserver";
17
- import { parseCronExpression } from "cron-schedule";
18
- import { nanoid } from "nanoid";
19
- import { AsyncLocalStorage } from "async_hooks";
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);
22
23
  }
@@ -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,19 +183,19 @@ 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);
149
190
  this.broadcast(
150
191
  JSON.stringify({
151
- type: "cf_agent_mcp_servers",
152
- mcp: this.getMcpServers()
192
+ mcp: this.getMcpServers(),
193
+ type: "cf_agent_mcp_servers"
153
194
  })
154
195
  );
155
196
  return new Response("<script>window.close();</script>", {
156
- status: 200,
157
- headers: { "content-type": "text/html" }
197
+ headers: { "content-type": "text/html" },
198
+ status: 200
158
199
  });
159
200
  }
160
201
  return this._tryCatch(() => _onRequest(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));
@@ -172,7 +213,7 @@ var Agent = class extends Server {
172
213
  let parsed;
173
214
  try {
174
215
  parsed = JSON.parse(message);
175
- } catch (e) {
216
+ } catch (_e) {
176
217
  return this._tryCatch(() => _onMessage(connection, message));
177
218
  }
178
219
  if (isStateUpdateMessage(parsed)) {
@@ -196,20 +237,35 @@ 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
- type: "rpc",
256
+ done: true,
201
257
  id,
202
- success: true,
203
258
  result,
204
- done: true
259
+ success: true,
260
+ type: "rpc"
205
261
  };
206
262
  connection.send(JSON.stringify(response));
207
263
  } catch (e) {
208
264
  const response = {
209
- type: "rpc",
265
+ error: e instanceof Error ? e.message : "Unknown error occurred",
210
266
  id: parsed.id,
211
267
  success: false,
212
- error: e instanceof Error ? e.message : "Unknown error occurred"
268
+ type: "rpc"
213
269
  };
214
270
  connection.send(JSON.stringify(response));
215
271
  console.error("RPC error:", e);
@@ -223,23 +279,35 @@ 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) {
230
286
  connection.send(
231
287
  JSON.stringify({
232
- type: "cf_agent_state",
233
- state: this.state
288
+ state: this.state,
289
+ type: "cf_agent_state"
234
290
  })
235
291
  );
236
292
  }
237
293
  connection.send(
238
294
  JSON.stringify({
239
- type: "cf_agent_mcp_servers",
240
- mcp: this.getMcpServers()
295
+ mcp: this.getMcpServers(),
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
- type: "cf_agent_mcp_servers",
273
- mcp: this.getMcpServers()
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)
@@ -335,16 +412,29 @@ var Agent = class extends Server {
335
412
  `;
336
413
  this.broadcast(
337
414
  JSON.stringify({
338
- type: "cf_agent_state",
339
- state
415
+ state,
416
+ type: "cf_agent_state"
340
417
  }),
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
  );
@@ -362,20 +452,71 @@ var Agent = class extends Server {
362
452
  * @param state Updated state
363
453
  * @param source Source of the state update ("server" or a client connection)
364
454
  */
455
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
365
456
  onStateUpdate(state, source) {
366
457
  }
367
458
  /**
368
- * 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
369
461
  * @param email Email message to process
370
462
  */
371
- onEmail(email) {
463
+ async _onEmail(email) {
372
464
  return agentContext.run(
373
- { agent: this, connection: void 0, request: void 0 },
465
+ { agent: this, connection: void 0, request: void 0, email },
374
466
  async () => {
375
- 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
+ }
376
478
  }
377
479
  );
378
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
+ }
379
520
  async _tryCatch(fn) {
380
521
  try {
381
522
  return await fn();
@@ -383,6 +524,55 @@ var Agent = class extends Server {
383
524
  throw this.onError(e);
384
525
  }
385
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
+ }
386
576
  onError(connectionOrError, error) {
387
577
  let theError;
388
578
  if (connectionOrError && error) {
@@ -408,6 +598,108 @@ var Agent = class extends Server {
408
598
  render() {
409
599
  throw new Error("Not implemented");
410
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
+ }
411
703
  /**
412
704
  * Schedule a task to be executed in the future
413
705
  * @template T Type of the payload data
@@ -418,6 +710,16 @@ var Agent = class extends Server {
418
710
  */
419
711
  async schedule(when, callback, payload) {
420
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
+ );
421
723
  if (typeof callback !== "string") {
422
724
  throw new Error("Callback must be a string");
423
725
  }
@@ -433,13 +735,15 @@ var Agent = class extends Server {
433
735
  )}, 'scheduled', ${timestamp})
434
736
  `;
435
737
  await this._scheduleNextAlarm();
436
- return {
437
- id,
738
+ const schedule = {
438
739
  callback,
740
+ id,
439
741
  payload,
440
742
  time: timestamp,
441
743
  type: "scheduled"
442
744
  };
745
+ emitScheduleCreate(schedule);
746
+ return schedule;
443
747
  }
444
748
  if (typeof when === "number") {
445
749
  const time = new Date(Date.now() + when * 1e3);
@@ -451,14 +755,16 @@ var Agent = class extends Server {
451
755
  )}, 'delayed', ${when}, ${timestamp})
452
756
  `;
453
757
  await this._scheduleNextAlarm();
454
- return {
455
- id,
758
+ const schedule = {
456
759
  callback,
457
- payload,
458
760
  delayInSeconds: when,
761
+ id,
762
+ payload,
459
763
  time: timestamp,
460
764
  type: "delayed"
461
765
  };
766
+ emitScheduleCreate(schedule);
767
+ return schedule;
462
768
  }
463
769
  if (typeof when === "string") {
464
770
  const nextExecutionTime = getNextCronTime(when);
@@ -470,14 +776,16 @@ var Agent = class extends Server {
470
776
  )}, 'cron', ${when}, ${timestamp})
471
777
  `;
472
778
  await this._scheduleNextAlarm();
473
- return {
474
- id,
779
+ const schedule = {
475
780
  callback,
476
- payload,
477
781
  cron: when,
782
+ id,
783
+ payload,
478
784
  time: timestamp,
479
785
  type: "cron"
480
786
  };
787
+ emitScheduleCreate(schedule);
788
+ return schedule;
481
789
  }
482
790
  throw new Error("Invalid schedule type");
483
791
  }
@@ -535,6 +843,19 @@ var Agent = class extends Server {
535
843
  * @returns true if the task was cancelled, false otherwise
536
844
  */
537
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
+ }
538
859
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
539
860
  await this._scheduleNextAlarm();
540
861
  return true;
@@ -559,8 +880,20 @@ var Agent = class extends Server {
559
880
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
560
881
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
561
882
  this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
883
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
562
884
  await this.ctx.storage.deleteAlarm();
563
885
  await this.ctx.storage.deleteAll();
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
+ );
564
897
  }
565
898
  /**
566
899
  * Get all methods marked as callable on this Agent
@@ -586,15 +919,28 @@ var Agent = class extends Server {
586
919
  callbackUrl,
587
920
  options
588
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
+ `;
589
935
  this.broadcast(
590
936
  JSON.stringify({
591
- type: "cf_agent_mcp_servers",
592
- mcp: this.getMcpServers()
937
+ mcp: this.getMcpServers(),
938
+ type: "cf_agent_mcp_servers"
593
939
  })
594
940
  );
595
941
  return result;
596
942
  }
597
- async _connectToMcpServerInternal(serverName, url, callbackUrl, options, reconnect) {
943
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
598
944
  const authProvider = new DurableObjectOAuthClientProvider(
599
945
  this.ctx.storage,
600
946
  this.name,
@@ -621,28 +967,17 @@ var Agent = class extends Server {
621
967
  };
622
968
  }
623
969
  const { id, authUrl, clientId } = await this.mcp.connect(url, {
970
+ client: options?.client,
624
971
  reconnect,
625
972
  transport: {
626
973
  ...headerTransportOpts,
627
974
  authProvider
628
- },
629
- client: options?.client
975
+ }
630
976
  });
631
- this.sql`
632
- INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
633
- VALUES (
634
- ${id},
635
- ${serverName},
636
- ${url},
637
- ${clientId ?? null},
638
- ${authUrl ?? null},
639
- ${callbackUrl},
640
- ${options ? JSON.stringify(options) : null}
641
- );
642
- `;
643
977
  return {
644
- id,
645
- authUrl
978
+ authUrl,
979
+ clientId,
980
+ id
646
981
  };
647
982
  }
648
983
  async removeMcpServer(id) {
@@ -652,30 +987,34 @@ var Agent = class extends Server {
652
987
  `;
653
988
  this.broadcast(
654
989
  JSON.stringify({
655
- type: "cf_agent_mcp_servers",
656
- mcp: this.getMcpServers()
990
+ mcp: this.getMcpServers(),
991
+ type: "cf_agent_mcp_servers"
657
992
  })
658
993
  );
659
994
  }
660
995
  getMcpServers() {
661
996
  const mcpState = {
662
- servers: {},
663
- tools: this.mcp.listTools(),
664
997
  prompts: this.mcp.listPrompts(),
665
- resources: this.mcp.listResources()
998
+ resources: this.mcp.listResources(),
999
+ servers: {},
1000
+ tools: this.mcp.listTools()
666
1001
  };
667
1002
  const servers = this.sql`
668
1003
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
669
1004
  `;
670
- for (const server of servers) {
671
- mcpState.servers[server.id] = {
672
- name: server.name,
673
- server_url: server.server_url,
674
- auth_url: server.auth_url,
675
- state: this.mcp.mcpConnections[server.id].connectionState,
676
- instructions: this.mcp.mcpConnections[server.id].instructions ?? null,
677
- capabilities: this.mcp.mcpConnections[server.id].serverCapabilities ?? null
678
- };
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
+ }
679
1018
  }
680
1019
  return mcpState;
681
1020
  }
@@ -683,16 +1022,17 @@ var Agent = class extends Server {
683
1022
  /**
684
1023
  * Agent configuration options
685
1024
  */
686
- Agent.options = {
1025
+ _Agent.options = {
687
1026
  /** Whether the Agent should hibernate when inactive */
688
1027
  hibernate: true
689
1028
  // default to hibernate
690
1029
  };
1030
+ var Agent = _Agent;
691
1031
  async function routeAgentRequest(request, env, options) {
692
1032
  const corsHeaders = options?.cors === true ? {
693
- "Access-Control-Allow-Origin": "*",
694
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
695
1033
  "Access-Control-Allow-Credentials": "true",
1034
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1035
+ "Access-Control-Allow-Origin": "*",
696
1036
  "Access-Control-Max-Age": "86400"
697
1037
  } : options?.cors;
698
1038
  if (request.method === "OPTIONS") {
@@ -723,7 +1063,116 @@ async function routeAgentRequest(request, env, options) {
723
1063
  }
724
1064
  return response;
725
1065
  }
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
+ }
726
1119
  async function routeAgentEmail(email, env, options) {
1120
+ const routingInfo = await options.resolver(email, env);
1121
+ if (!routingInfo) {
1122
+ console.warn("No routing information found for email, dropping message");
1123
+ return;
1124
+ }
1125
+ const namespaceBinding = env[routingInfo.agentName];
1126
+ if (!namespaceBinding) {
1127
+ throw new Error(
1128
+ `Agent namespace '${routingInfo.agentName}' not found in environment`
1129
+ );
1130
+ }
1131
+ if (typeof namespaceBinding !== "object" || !("idFromName" in namespaceBinding) || typeof namespaceBinding.idFromName !== "function") {
1132
+ throw new Error(
1133
+ `Environment binding '${routingInfo.agentName}' is not an AgentNamespace (found: ${typeof namespaceBinding})`
1134
+ );
1135
+ }
1136
+ const namespace = namespaceBinding;
1137
+ const agent = await getAgentByName(namespace, routingInfo.agentId);
1138
+ const serialisableEmail = {
1139
+ getRaw: async () => {
1140
+ const reader = email.raw.getReader();
1141
+ const chunks = [];
1142
+ let done = false;
1143
+ while (!done) {
1144
+ const { value, done: readerDone } = await reader.read();
1145
+ done = readerDone;
1146
+ if (value) {
1147
+ chunks.push(value);
1148
+ }
1149
+ }
1150
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1151
+ const combined = new Uint8Array(totalLength);
1152
+ let offset = 0;
1153
+ for (const chunk of chunks) {
1154
+ combined.set(chunk, offset);
1155
+ offset += chunk.length;
1156
+ }
1157
+ return combined;
1158
+ },
1159
+ headers: email.headers,
1160
+ rawSize: email.rawSize,
1161
+ setReject: (reason) => {
1162
+ email.setReject(reason);
1163
+ },
1164
+ forward: (rcptTo, headers) => {
1165
+ return email.forward(rcptTo, headers);
1166
+ },
1167
+ reply: (options2) => {
1168
+ return email.reply(
1169
+ new EmailMessage(options2.from, options2.to, options2.raw)
1170
+ );
1171
+ },
1172
+ from: email.from,
1173
+ to: email.to
1174
+ };
1175
+ await agent._onEmail(serialisableEmail);
727
1176
  }
728
1177
  async function getAgentByName(namespace, name, options) {
729
1178
  return getServerByName(namespace, name, options);
@@ -743,11 +1192,11 @@ var StreamingResponse = class {
743
1192
  throw new Error("StreamingResponse is already closed");
744
1193
  }
745
1194
  const response = {
746
- type: "rpc",
1195
+ done: false,
747
1196
  id: this._id,
748
- success: true,
749
1197
  result: chunk,
750
- done: false
1198
+ success: true,
1199
+ type: "rpc"
751
1200
  };
752
1201
  this._connection.send(JSON.stringify(response));
753
1202
  }
@@ -761,23 +1210,51 @@ var StreamingResponse = class {
761
1210
  }
762
1211
  this._closed = true;
763
1212
  const response = {
764
- type: "rpc",
1213
+ done: true,
765
1214
  id: this._id,
766
- success: true,
767
1215
  result: finalChunk,
768
- done: true
1216
+ success: true,
1217
+ type: "rpc"
769
1218
  };
770
1219
  this._connection.send(JSON.stringify(response));
771
1220
  }
772
1221
  };
773
1222
 
1223
+ // src/observability/index.ts
1224
+ var genericObservability = {
1225
+ emit(event) {
1226
+ if (isLocalMode()) {
1227
+ console.log(event.displayMessage);
1228
+ return;
1229
+ }
1230
+ console.log(event);
1231
+ }
1232
+ };
1233
+ var localMode = false;
1234
+ function isLocalMode() {
1235
+ if (localMode) {
1236
+ return true;
1237
+ }
1238
+ const { request } = getCurrentAgent();
1239
+ if (!request) {
1240
+ return false;
1241
+ }
1242
+ const url = new URL(request.url);
1243
+ localMode = url.hostname === "localhost";
1244
+ return localMode;
1245
+ }
1246
+
774
1247
  export {
1248
+ genericObservability,
775
1249
  unstable_callable,
776
1250
  getCurrentAgent,
777
1251
  Agent,
778
1252
  routeAgentRequest,
1253
+ createHeaderBasedEmailResolver,
1254
+ createAddressBasedEmailResolver,
1255
+ createCatchAllEmailResolver,
779
1256
  routeAgentEmail,
780
1257
  getAgentByName,
781
1258
  StreamingResponse
782
1259
  };
783
- //# sourceMappingURL=chunk-P3RZJ72N.js.map
1260
+ //# sourceMappingURL=chunk-MFNGQLFL.js.map