agents 0.0.0-2801d35 → 0.0.0-2a6e66e

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 (44) hide show
  1. package/README.md +128 -22
  2. package/dist/ai-chat-agent.d.ts +8 -5
  3. package/dist/ai-chat-agent.js +54 -26
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +13 -9
  6. package/dist/ai-react.js +27 -27
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/{chunk-J6T74FUS.js → chunk-CV3L6FQZ.js} +641 -134
  9. package/dist/chunk-CV3L6FQZ.js.map +1 -0
  10. package/dist/{chunk-Y67CHZBI.js → chunk-HY7ZLHJB.js} +167 -33
  11. package/dist/chunk-HY7ZLHJB.js.map +1 -0
  12. package/dist/{chunk-QSGN3REV.js → chunk-KUH345EY.js} +8 -15
  13. package/dist/chunk-KUH345EY.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-DgyzBU_8.d.ts +4601 -0
  17. package/dist/client.d.ts +8 -2
  18. package/dist/client.js +1 -1
  19. package/dist/index.d.ts +154 -18
  20. package/dist/index.js +10 -4
  21. package/dist/mcp/client.d.ts +9 -781
  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 +38 -10
  25. package/dist/mcp/index.js +237 -61
  26. package/dist/mcp/index.js.map +1 -1
  27. package/dist/observability/index.d.ts +46 -0
  28. package/dist/observability/index.js +10 -0
  29. package/dist/observability/index.js.map +1 -0
  30. package/dist/react.d.ts +54 -36
  31. package/dist/react.js +16 -6
  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/dist/serializable.d.ts +32 -0
  37. package/dist/serializable.js +1 -0
  38. package/dist/serializable.js.map +1 -0
  39. package/package.json +79 -72
  40. package/src/index.ts +846 -176
  41. package/dist/chunk-BZXOAZUX.js.map +0 -1
  42. package/dist/chunk-J6T74FUS.js.map +0 -1
  43. package/dist/chunk-QSGN3REV.js.map +0 -1
  44. package/dist/chunk-Y67CHZBI.js.map +0 -1
@@ -1,22 +1,23 @@
1
+ import {
2
+ MCPClientManager
3
+ } from "./chunk-HY7ZLHJB.js";
1
4
  import {
2
5
  DurableObjectOAuthClientProvider
3
- } from "./chunk-BZXOAZUX.js";
6
+ } from "./chunk-PVQZBKN7.js";
4
7
  import {
5
8
  camelCaseToKebabCase
6
- } from "./chunk-QSGN3REV.js";
7
- import {
8
- MCPClientManager
9
- } from "./chunk-Y67CHZBI.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
- routePartykitRequest,
15
- getServerByName
18
+ getServerByName,
19
+ routePartykitRequest
16
20
  } from "partyserver";
17
- import { parseCronExpression } from "cron-schedule";
18
- import { nanoid } from "nanoid";
19
- import { AsyncLocalStorage } from "node: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,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,19 +186,19 @@ 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);
149
193
  this.broadcast(
150
194
  JSON.stringify({
151
- type: "cf_agent_mcp_servers",
152
- mcp: this.getMcpServers()
195
+ mcp: this.getMcpServers(),
196
+ type: "cf_agent_mcp_servers"
153
197
  })
154
198
  );
155
199
  return new Response("<script>window.close();</script>", {
156
- status: 200,
157
- headers: { "content-type": "text/html" }
200
+ headers: { "content-type": "text/html" },
201
+ status: 200
158
202
  });
159
203
  }
160
204
  return this._tryCatch(() => _onRequest(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));
@@ -172,7 +216,7 @@ var Agent = class extends Server {
172
216
  let parsed;
173
217
  try {
174
218
  parsed = JSON.parse(message);
175
- } catch (e) {
219
+ } catch (_e) {
176
220
  return this._tryCatch(() => _onMessage(connection, message));
177
221
  }
178
222
  if (isStateUpdateMessage(parsed)) {
@@ -196,20 +240,33 @@ 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
- type: "rpc",
257
+ done: true,
201
258
  id,
202
- success: true,
203
259
  result,
204
- done: true
260
+ success: true,
261
+ type: "rpc"
205
262
  };
206
263
  connection.send(JSON.stringify(response));
207
264
  } catch (e) {
208
265
  const response = {
209
- type: "rpc",
266
+ error: e instanceof Error ? e.message : "Unknown error occurred",
210
267
  id: parsed.id,
211
268
  success: false,
212
- error: e instanceof Error ? e.message : "Unknown error occurred"
269
+ type: "rpc"
213
270
  };
214
271
  connection.send(JSON.stringify(response));
215
272
  console.error("RPC error:", e);
@@ -223,23 +280,35 @@ 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) {
230
287
  connection.send(
231
288
  JSON.stringify({
232
- type: "cf_agent_state",
233
- state: this.state
289
+ state: this.state,
290
+ type: "cf_agent_state"
234
291
  })
235
292
  );
236
293
  }
237
294
  connection.send(
238
295
  JSON.stringify({
239
- type: "cf_agent_mcp_servers",
240
- mcp: this.getMcpServers()
296
+ mcp: this.getMcpServers(),
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.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
- type: "cf_agent_mcp_servers",
273
- mcp: this.getMcpServers()
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
  };
@@ -335,16 +429,26 @@ var Agent = class extends Server {
335
429
  `;
336
430
  this.broadcast(
337
431
  JSON.stringify({
338
- type: "cf_agent_state",
339
- state
432
+ state,
433
+ type: "cf_agent_state"
340
434
  }),
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
  );
@@ -362,20 +466,71 @@ var Agent = class extends Server {
362
466
  * @param state Updated state
363
467
  * @param source Source of the state update ("server" or a client connection)
364
468
  */
469
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
365
470
  onStateUpdate(state, source) {
366
471
  }
367
472
  /**
368
- * 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
369
475
  * @param email Email message to process
370
476
  */
371
- onEmail(email) {
477
+ async _onEmail(email) {
372
478
  return agentContext.run(
373
- { agent: this, connection: void 0, request: void 0 },
479
+ { agent: this, connection: void 0, request: void 0, email },
374
480
  async () => {
375
- 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
+ }
376
492
  }
377
493
  );
378
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
+ }
379
534
  async _tryCatch(fn) {
380
535
  try {
381
536
  return await fn();
@@ -383,6 +538,55 @@ var Agent = class extends Server {
383
538
  throw this.onError(e);
384
539
  }
385
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
+ }
386
590
  onError(connectionOrError, error) {
387
591
  let theError;
388
592
  if (connectionOrError && error) {
@@ -408,6 +612,108 @@ var Agent = class extends Server {
408
612
  render() {
409
613
  throw new Error("Not implemented");
410
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
+ }
411
717
  /**
412
718
  * Schedule a task to be executed in the future
413
719
  * @template T Type of the payload data
@@ -418,6 +724,19 @@ var Agent = class extends Server {
418
724
  */
419
725
  async schedule(when, callback, payload) {
420
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
+ );
421
740
  if (typeof callback !== "string") {
422
741
  throw new Error("Callback must be a string");
423
742
  }
@@ -433,13 +752,15 @@ var Agent = class extends Server {
433
752
  )}, 'scheduled', ${timestamp})
434
753
  `;
435
754
  await this._scheduleNextAlarm();
436
- return {
437
- id,
755
+ const schedule = {
438
756
  callback,
757
+ id,
439
758
  payload,
440
759
  time: timestamp,
441
760
  type: "scheduled"
442
761
  };
762
+ emitScheduleCreate(schedule);
763
+ return schedule;
443
764
  }
444
765
  if (typeof when === "number") {
445
766
  const time = new Date(Date.now() + when * 1e3);
@@ -451,14 +772,16 @@ var Agent = class extends Server {
451
772
  )}, 'delayed', ${when}, ${timestamp})
452
773
  `;
453
774
  await this._scheduleNextAlarm();
454
- return {
455
- id,
775
+ const schedule = {
456
776
  callback,
457
- payload,
458
777
  delayInSeconds: when,
778
+ id,
779
+ payload,
459
780
  time: timestamp,
460
781
  type: "delayed"
461
782
  };
783
+ emitScheduleCreate(schedule);
784
+ return schedule;
462
785
  }
463
786
  if (typeof when === "string") {
464
787
  const nextExecutionTime = getNextCronTime(when);
@@ -470,14 +793,16 @@ var Agent = class extends Server {
470
793
  )}, 'cron', ${when}, ${timestamp})
471
794
  `;
472
795
  await this._scheduleNextAlarm();
473
- return {
474
- id,
796
+ const schedule = {
475
797
  callback,
476
- payload,
477
798
  cron: when,
799
+ id,
800
+ payload,
478
801
  time: timestamp,
479
802
  type: "cron"
480
803
  };
804
+ emitScheduleCreate(schedule);
805
+ return schedule;
481
806
  }
482
807
  throw new Error("Invalid schedule type");
483
808
  }
@@ -535,15 +860,31 @@ var Agent = class extends Server {
535
860
  * @returns true if the task was cancelled, false otherwise
536
861
  */
537
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
+ }
538
879
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
539
880
  await this._scheduleNextAlarm();
540
881
  return true;
541
882
  }
542
883
  async _scheduleNextAlarm() {
543
884
  const result = this.sql`
544
- SELECT time FROM cf_agents_schedules
885
+ SELECT time FROM cf_agents_schedules
545
886
  WHERE time > ${Math.floor(Date.now() / 1e3)}
546
- ORDER BY time ASC
887
+ ORDER BY time ASC
547
888
  LIMIT 1
548
889
  `;
549
890
  if (!result) return;
@@ -559,8 +900,20 @@ var Agent = class extends Server {
559
900
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
560
901
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
561
902
  this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
903
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
562
904
  await this.ctx.storage.deleteAlarm();
563
905
  await this.ctx.storage.deleteAll();
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
+ );
564
917
  }
565
918
  /**
566
919
  * Get all methods marked as callable on this Agent
@@ -586,15 +939,28 @@ var Agent = class extends Server {
586
939
  callbackUrl,
587
940
  options
588
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
+ `;
589
955
  this.broadcast(
590
956
  JSON.stringify({
591
- type: "cf_agent_mcp_servers",
592
- mcp: this.getMcpServers()
957
+ mcp: this.getMcpServers(),
958
+ type: "cf_agent_mcp_servers"
593
959
  })
594
960
  );
595
961
  return result;
596
962
  }
597
- async _connectToMcpServerInternal(serverName, url, callbackUrl, options, reconnect) {
963
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
598
964
  const authProvider = new DurableObjectOAuthClientProvider(
599
965
  this.ctx.storage,
600
966
  this.name,
@@ -621,28 +987,17 @@ var Agent = class extends Server {
621
987
  };
622
988
  }
623
989
  const { id, authUrl, clientId } = await this.mcp.connect(url, {
990
+ client: options?.client,
624
991
  reconnect,
625
992
  transport: {
626
993
  ...headerTransportOpts,
627
994
  authProvider
628
- },
629
- client: options?.client
995
+ }
630
996
  });
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
997
  return {
644
- id,
645
- authUrl
998
+ authUrl,
999
+ clientId,
1000
+ id
646
1001
  };
647
1002
  }
648
1003
  async removeMcpServer(id) {
@@ -652,30 +1007,34 @@ var Agent = class extends Server {
652
1007
  `;
653
1008
  this.broadcast(
654
1009
  JSON.stringify({
655
- type: "cf_agent_mcp_servers",
656
- mcp: this.getMcpServers()
1010
+ mcp: this.getMcpServers(),
1011
+ type: "cf_agent_mcp_servers"
657
1012
  })
658
1013
  );
659
1014
  }
660
1015
  getMcpServers() {
661
1016
  const mcpState = {
662
- servers: {},
663
- tools: this.mcp.listTools(),
664
1017
  prompts: this.mcp.listPrompts(),
665
- resources: this.mcp.listResources()
1018
+ resources: this.mcp.listResources(),
1019
+ servers: {},
1020
+ tools: this.mcp.listTools()
666
1021
  };
667
1022
  const servers = this.sql`
668
1023
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
669
1024
  `;
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
- };
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
+ }
679
1038
  }
680
1039
  return mcpState;
681
1040
  }
@@ -683,16 +1042,17 @@ var Agent = class extends Server {
683
1042
  /**
684
1043
  * Agent configuration options
685
1044
  */
686
- Agent.options = {
1045
+ _Agent.options = {
687
1046
  /** Whether the Agent should hibernate when inactive */
688
1047
  hibernate: true
689
1048
  // default to hibernate
690
1049
  };
1050
+ var Agent = _Agent;
691
1051
  async function routeAgentRequest(request, env, options) {
692
1052
  const corsHeaders = options?.cors === true ? {
693
- "Access-Control-Allow-Origin": "*",
694
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
695
1053
  "Access-Control-Allow-Credentials": "true",
1054
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1055
+ "Access-Control-Allow-Origin": "*",
696
1056
  "Access-Control-Max-Age": "86400"
697
1057
  } : options?.cors;
698
1058
  if (request.method === "OPTIONS") {
@@ -723,7 +1083,126 @@ async function routeAgentRequest(request, env, options) {
723
1083
  }
724
1084
  return response;
725
1085
  }
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();
726
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);
727
1206
  }
728
1207
  async function getAgentByName(namespace, name, options) {
729
1208
  return getServerByName(namespace, name, options);
@@ -743,11 +1222,11 @@ var StreamingResponse = class {
743
1222
  throw new Error("StreamingResponse is already closed");
744
1223
  }
745
1224
  const response = {
746
- type: "rpc",
1225
+ done: false,
747
1226
  id: this._id,
748
- success: true,
749
1227
  result: chunk,
750
- done: false
1228
+ success: true,
1229
+ type: "rpc"
751
1230
  };
752
1231
  this._connection.send(JSON.stringify(response));
753
1232
  }
@@ -761,23 +1240,51 @@ var StreamingResponse = class {
761
1240
  }
762
1241
  this._closed = true;
763
1242
  const response = {
764
- type: "rpc",
1243
+ done: true,
765
1244
  id: this._id,
766
- success: true,
767
1245
  result: finalChunk,
768
- done: true
1246
+ success: true,
1247
+ type: "rpc"
769
1248
  };
770
1249
  this._connection.send(JSON.stringify(response));
771
1250
  }
772
1251
  };
773
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
+
774
1277
  export {
1278
+ genericObservability,
775
1279
  unstable_callable,
776
1280
  getCurrentAgent,
777
1281
  Agent,
778
1282
  routeAgentRequest,
1283
+ createHeaderBasedEmailResolver,
1284
+ createAddressBasedEmailResolver,
1285
+ createCatchAllEmailResolver,
779
1286
  routeAgentEmail,
780
1287
  getAgentByName,
781
1288
  StreamingResponse
782
1289
  };
783
- //# sourceMappingURL=chunk-J6T74FUS.js.map
1290
+ //# sourceMappingURL=chunk-CV3L6FQZ.js.map