agents 0.0.0-1232c19 → 0.0.0-14616d3

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 (51) hide show
  1. package/README.md +131 -25
  2. package/dist/ai-chat-agent.d.ts +11 -7
  3. package/dist/ai-chat-agent.js +146 -47
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration.d.ts +152 -0
  6. package/dist/ai-chat-v5-migration.js +19 -0
  7. package/dist/ai-chat-v5-migration.js.map +1 -0
  8. package/dist/ai-react.d.ts +61 -70
  9. package/dist/ai-react.js +144 -37
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/ai-types.d.ts +36 -19
  12. package/dist/ai-types.js +6 -0
  13. package/dist/chunk-AVYJQSLW.js +17 -0
  14. package/dist/chunk-AVYJQSLW.js.map +1 -0
  15. package/dist/{chunk-767EASBA.js → chunk-LL2AFX7V.js} +5 -2
  16. package/dist/chunk-LL2AFX7V.js.map +1 -0
  17. package/dist/{chunk-ZRRXJUAA.js → chunk-O4KIASSE.js} +632 -118
  18. package/dist/chunk-O4KIASSE.js.map +1 -0
  19. package/dist/{chunk-NKZZ66QY.js → chunk-QEVM4BVL.js} +5 -5
  20. package/dist/chunk-QEVM4BVL.js.map +1 -0
  21. package/dist/chunk-UJVEAURM.js +150 -0
  22. package/dist/chunk-UJVEAURM.js.map +1 -0
  23. package/dist/{chunk-E3LCYPCB.js → chunk-VYENMKFS.js} +163 -20
  24. package/dist/chunk-VYENMKFS.js.map +1 -0
  25. package/dist/client-CpU7236R.d.ts +4607 -0
  26. package/dist/client.d.ts +2 -2
  27. package/dist/client.js +2 -1
  28. package/dist/index.d.ts +164 -20
  29. package/dist/index.js +13 -4
  30. package/dist/mcp/client.d.ts +9 -781
  31. package/dist/mcp/client.js +1 -1
  32. package/dist/mcp/do-oauth-client-provider.d.ts +1 -0
  33. package/dist/mcp/do-oauth-client-provider.js +1 -1
  34. package/dist/mcp/index.d.ts +35 -7
  35. package/dist/mcp/index.js +191 -18
  36. package/dist/mcp/index.js.map +1 -1
  37. package/dist/observability/index.d.ts +46 -0
  38. package/dist/observability/index.js +11 -0
  39. package/dist/observability/index.js.map +1 -0
  40. package/dist/react.d.ts +9 -5
  41. package/dist/react.js +7 -5
  42. package/dist/react.js.map +1 -1
  43. package/dist/schedule.d.ts +79 -5
  44. package/dist/schedule.js +15 -2
  45. package/dist/schedule.js.map +1 -1
  46. package/package.json +41 -28
  47. package/src/index.ts +841 -153
  48. package/dist/chunk-767EASBA.js.map +0 -1
  49. package/dist/chunk-E3LCYPCB.js.map +0 -1
  50. package/dist/chunk-NKZZ66QY.js.map +0 -1
  51. package/dist/chunk-ZRRXJUAA.js.map +0 -1
@@ -1,30 +1,31 @@
1
1
  import {
2
2
  MCPClientManager
3
- } from "./chunk-E3LCYPCB.js";
3
+ } from "./chunk-VYENMKFS.js";
4
4
  import {
5
5
  DurableObjectOAuthClientProvider
6
- } from "./chunk-767EASBA.js";
6
+ } from "./chunk-LL2AFX7V.js";
7
7
  import {
8
8
  camelCaseToKebabCase
9
- } from "./chunk-NKZZ66QY.js";
9
+ } from "./chunk-QEVM4BVL.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
- 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
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "rpc" /* RPC */ && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
22
23
  }
23
24
  function isStateUpdateMessage(msg) {
24
- return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "cf_agent_state" && "state" in msg;
25
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "cf_agent_state" /* CF_AGENT_STATE */ && "state" in msg;
25
26
  }
26
27
  var callableMetadata = /* @__PURE__ */ new Map();
27
- function unstable_callable(metadata = {}) {
28
+ function callable(metadata = {}) {
28
29
  return function callableDecorator(target, context) {
29
30
  if (!callableMetadata.has(target)) {
30
31
  callableMetadata.set(target, metadata);
@@ -32,6 +33,16 @@ function unstable_callable(metadata = {}) {
32
33
  return target;
33
34
  };
34
35
  }
36
+ var didWarnAboutUnstableCallable = false;
37
+ var unstable_callable = (metadata = {}) => {
38
+ if (!didWarnAboutUnstableCallable) {
39
+ didWarnAboutUnstableCallable = true;
40
+ console.warn(
41
+ "unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version."
42
+ );
43
+ }
44
+ callable(metadata);
45
+ };
35
46
  function getNextCronTime(cron) {
36
47
  const interval = parseCronExpression(cron);
37
48
  return interval.getNextDate();
@@ -46,12 +57,24 @@ function getCurrentAgent() {
46
57
  return {
47
58
  agent: void 0,
48
59
  connection: void 0,
49
- request: void 0
60
+ request: void 0,
61
+ email: void 0
50
62
  };
51
63
  }
52
64
  return store;
53
65
  }
54
- var Agent = class extends Server {
66
+ function withAgentContext(method) {
67
+ return function(...args) {
68
+ const { connection, request, email, agent } = getCurrentAgent();
69
+ if (agent === this) {
70
+ return method.apply(this, args);
71
+ }
72
+ return agentContext.run({ agent: this, connection, request, email }, () => {
73
+ return method.apply(this, args);
74
+ });
75
+ };
76
+ }
77
+ var _Agent = class _Agent extends Server {
55
78
  constructor(ctx, env) {
56
79
  super(ctx, env);
57
80
  this._state = DEFAULT_STATE;
@@ -62,6 +85,11 @@ var Agent = class extends Server {
62
85
  * Override to provide default state values
63
86
  */
64
87
  this.initialState = DEFAULT_STATE;
88
+ /**
89
+ * The observability implementation to use for the Agent
90
+ */
91
+ this.observability = genericObservability;
92
+ this._flushingQueue = false;
65
93
  /**
66
94
  * Method called when an alarm fires.
67
95
  * Executes any scheduled tasks that are due.
@@ -75,42 +103,71 @@ var Agent = class extends Server {
75
103
  const result = this.sql`
76
104
  SELECT * FROM cf_agents_schedules WHERE time <= ${now}
77
105
  `;
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
- }
106
+ if (result && Array.isArray(result)) {
107
+ for (const row of result) {
108
+ const callback = this[row.callback];
109
+ if (!callback) {
110
+ console.error(`callback ${row.callback} not found`);
111
+ continue;
92
112
  }
93
- );
94
- if (row.type === "cron") {
95
- const nextExecutionTime = getNextCronTime(row.cron);
96
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
97
- this.sql`
113
+ await agentContext.run(
114
+ {
115
+ agent: this,
116
+ connection: void 0,
117
+ request: void 0,
118
+ email: void 0
119
+ },
120
+ async () => {
121
+ try {
122
+ this.observability?.emit(
123
+ {
124
+ displayMessage: `Schedule ${row.id} executed`,
125
+ id: nanoid(),
126
+ payload: {
127
+ callback: row.callback,
128
+ id: row.id
129
+ },
130
+ timestamp: Date.now(),
131
+ type: "schedule:execute"
132
+ },
133
+ this.ctx
134
+ );
135
+ await callback.bind(this)(JSON.parse(row.payload), row);
136
+ } catch (e) {
137
+ console.error(`error executing callback "${row.callback}"`, e);
138
+ }
139
+ }
140
+ );
141
+ if (row.type === "cron") {
142
+ const nextExecutionTime = getNextCronTime(row.cron);
143
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
144
+ this.sql`
98
145
  UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
99
146
  `;
100
- } else {
101
- this.sql`
147
+ } else {
148
+ this.sql`
102
149
  DELETE FROM cf_agents_schedules WHERE id = ${row.id}
103
150
  `;
151
+ }
104
152
  }
105
153
  }
106
154
  await this._scheduleNextAlarm();
107
155
  };
156
+ this._autoWrapCustomMethods();
108
157
  this.sql`
109
158
  CREATE TABLE IF NOT EXISTS cf_agents_state (
110
159
  id TEXT PRIMARY KEY NOT NULL,
111
160
  state TEXT
112
161
  )
113
162
  `;
163
+ this.sql`
164
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
165
+ id TEXT PRIMARY KEY NOT NULL,
166
+ payload TEXT,
167
+ callback TEXT,
168
+ created_at INTEGER DEFAULT (unixepoch())
169
+ )
170
+ `;
114
171
  void this.ctx.blockConcurrencyWhile(async () => {
115
172
  return this._tryCatch(async () => {
116
173
  this.sql`
@@ -142,14 +199,14 @@ var Agent = class extends Server {
142
199
  const _onRequest = this.onRequest.bind(this);
143
200
  this.onRequest = (request) => {
144
201
  return agentContext.run(
145
- { agent: this, connection: void 0, request },
202
+ { agent: this, connection: void 0, request, email: void 0 },
146
203
  async () => {
147
204
  if (this.mcp.isCallbackRequest(request)) {
148
205
  await this.mcp.handleCallbackRequest(request);
149
206
  this.broadcast(
150
207
  JSON.stringify({
151
208
  mcp: this.getMcpServers(),
152
- type: "cf_agent_mcp_servers"
209
+ type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
153
210
  })
154
211
  );
155
212
  return new Response("<script>window.close();</script>", {
@@ -164,7 +221,7 @@ var Agent = class extends Server {
164
221
  const _onMessage = this.onMessage.bind(this);
165
222
  this.onMessage = async (connection, message) => {
166
223
  return agentContext.run(
167
- { agent: this, connection, request: void 0 },
224
+ { agent: this, connection, request: void 0, email: void 0 },
168
225
  async () => {
169
226
  if (typeof message !== "string") {
170
227
  return this._tryCatch(() => _onMessage(connection, message));
@@ -196,12 +253,25 @@ var Agent = class extends Server {
196
253
  return;
197
254
  }
198
255
  const result = await methodFn.apply(this, args);
256
+ this.observability?.emit(
257
+ {
258
+ displayMessage: `RPC call to ${method}`,
259
+ id: nanoid(),
260
+ payload: {
261
+ method,
262
+ streaming: metadata?.streaming
263
+ },
264
+ timestamp: Date.now(),
265
+ type: "rpc"
266
+ },
267
+ this.ctx
268
+ );
199
269
  const response = {
200
270
  done: true,
201
271
  id,
202
272
  result,
203
273
  success: true,
204
- type: "rpc"
274
+ type: "rpc" /* RPC */
205
275
  };
206
276
  connection.send(JSON.stringify(response));
207
277
  } catch (e) {
@@ -209,7 +279,7 @@ var Agent = class extends Server {
209
279
  error: e instanceof Error ? e.message : "Unknown error occurred",
210
280
  id: parsed.id,
211
281
  success: false,
212
- type: "rpc"
282
+ type: "rpc" /* RPC */
213
283
  };
214
284
  connection.send(JSON.stringify(response));
215
285
  console.error("RPC error:", e);
@@ -223,57 +293,92 @@ var Agent = class extends Server {
223
293
  const _onConnect = this.onConnect.bind(this);
224
294
  this.onConnect = (connection, ctx2) => {
225
295
  return agentContext.run(
226
- { agent: this, connection, request: ctx2.request },
227
- async () => {
228
- setTimeout(() => {
229
- if (this.state) {
230
- connection.send(
231
- JSON.stringify({
232
- state: this.state,
233
- type: "cf_agent_state"
234
- })
235
- );
236
- }
296
+ { agent: this, connection, request: ctx2.request, email: void 0 },
297
+ () => {
298
+ if (this.state) {
237
299
  connection.send(
238
300
  JSON.stringify({
239
- mcp: this.getMcpServers(),
240
- type: "cf_agent_mcp_servers"
301
+ state: this.state,
302
+ type: "cf_agent_state" /* CF_AGENT_STATE */
241
303
  })
242
304
  );
243
- return this._tryCatch(() => _onConnect(connection, ctx2));
244
- }, 20);
305
+ }
306
+ connection.send(
307
+ JSON.stringify({
308
+ mcp: this.getMcpServers(),
309
+ type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
310
+ })
311
+ );
312
+ this.observability?.emit(
313
+ {
314
+ displayMessage: "Connection established",
315
+ id: nanoid(),
316
+ payload: {
317
+ connectionId: connection.id
318
+ },
319
+ timestamp: Date.now(),
320
+ type: "connect"
321
+ },
322
+ this.ctx
323
+ );
324
+ return this._tryCatch(() => _onConnect(connection, ctx2));
245
325
  }
246
326
  );
247
327
  };
248
328
  const _onStart = this.onStart.bind(this);
249
329
  this.onStart = async () => {
250
330
  return agentContext.run(
251
- { agent: this, connection: void 0, request: void 0 },
331
+ {
332
+ agent: this,
333
+ connection: void 0,
334
+ request: void 0,
335
+ email: void 0
336
+ },
252
337
  async () => {
253
- const servers = this.sql`
338
+ await this._tryCatch(() => {
339
+ const servers = this.sql`
254
340
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
255
341
  `;
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());
342
+ this.broadcast(
343
+ JSON.stringify({
344
+ mcp: this.getMcpServers(),
345
+ type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
346
+ })
347
+ );
348
+ if (servers && Array.isArray(servers) && servers.length > 0) {
349
+ servers.forEach((server) => {
350
+ this._connectToMcpServerInternal(
351
+ server.name,
352
+ server.server_url,
353
+ server.callback_url,
354
+ server.server_options ? JSON.parse(server.server_options) : void 0,
355
+ {
356
+ id: server.id,
357
+ oauthClientId: server.client_id ?? void 0
358
+ }
359
+ ).then(() => {
360
+ this.broadcast(
361
+ JSON.stringify({
362
+ mcp: this.getMcpServers(),
363
+ type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
364
+ })
365
+ );
366
+ }).catch((error) => {
367
+ console.error(
368
+ `Error connecting to MCP server: ${server.name} (${server.server_url})`,
369
+ error
370
+ );
371
+ this.broadcast(
372
+ JSON.stringify({
373
+ mcp: this.getMcpServers(),
374
+ type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
375
+ })
376
+ );
377
+ });
378
+ });
379
+ }
380
+ return _onStart();
381
+ });
277
382
  }
278
383
  );
279
384
  };
@@ -336,15 +441,25 @@ var Agent = class extends Server {
336
441
  this.broadcast(
337
442
  JSON.stringify({
338
443
  state,
339
- type: "cf_agent_state"
444
+ type: "cf_agent_state" /* CF_AGENT_STATE */
340
445
  }),
341
446
  source !== "server" ? [source.id] : []
342
447
  );
343
448
  return this._tryCatch(() => {
344
- const { connection, request } = agentContext.getStore() || {};
449
+ const { connection, request, email } = agentContext.getStore() || {};
345
450
  return agentContext.run(
346
- { agent: this, connection, request },
451
+ { agent: this, connection, request, email },
347
452
  async () => {
453
+ this.observability?.emit(
454
+ {
455
+ displayMessage: "State updated",
456
+ id: nanoid(),
457
+ payload: {},
458
+ timestamp: Date.now(),
459
+ type: "state:update"
460
+ },
461
+ this.ctx
462
+ );
348
463
  return this.onStateUpdate(state, source);
349
464
  }
350
465
  );
@@ -366,18 +481,67 @@ var Agent = class extends Server {
366
481
  onStateUpdate(state, source) {
367
482
  }
368
483
  /**
369
- * Called when the Agent receives an email
484
+ * Called when the Agent receives an email via routeAgentEmail()
485
+ * Override this method to handle incoming emails
370
486
  * @param email Email message to process
371
487
  */
372
- // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
373
- onEmail(email) {
488
+ async _onEmail(email) {
374
489
  return agentContext.run(
375
- { agent: this, connection: void 0, request: void 0 },
490
+ { agent: this, connection: void 0, request: void 0, email },
376
491
  async () => {
377
- console.error("onEmail not implemented");
492
+ if ("onEmail" in this && typeof this.onEmail === "function") {
493
+ return this._tryCatch(
494
+ () => this.onEmail(email)
495
+ );
496
+ } else {
497
+ console.log("Received email from:", email.from, "to:", email.to);
498
+ console.log("Subject:", email.headers.get("subject"));
499
+ console.log(
500
+ "Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
501
+ );
502
+ }
378
503
  }
379
504
  );
380
505
  }
506
+ /**
507
+ * Reply to an email
508
+ * @param email The email to reply to
509
+ * @param options Options for the reply
510
+ * @returns void
511
+ */
512
+ async replyToEmail(email, options) {
513
+ return this._tryCatch(async () => {
514
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
515
+ const agentId = this.name;
516
+ const { createMimeMessage } = await import("mimetext");
517
+ const msg = createMimeMessage();
518
+ msg.setSender({ addr: email.to, name: options.fromName });
519
+ msg.setRecipient(email.from);
520
+ msg.setSubject(
521
+ options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
522
+ );
523
+ msg.addMessage({
524
+ contentType: options.contentType || "text/plain",
525
+ data: options.body
526
+ });
527
+ const domain = email.from.split("@")[1];
528
+ const messageId = `<${agentId}@${domain}>`;
529
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID"));
530
+ msg.setHeader("Message-ID", messageId);
531
+ msg.setHeader("X-Agent-Name", agentName);
532
+ msg.setHeader("X-Agent-ID", agentId);
533
+ if (options.headers) {
534
+ for (const [key, value] of Object.entries(options.headers)) {
535
+ msg.setHeader(key, value);
536
+ }
537
+ }
538
+ await email.reply({
539
+ from: email.to,
540
+ raw: msg.asRaw(),
541
+ to: email.from
542
+ });
543
+ });
544
+ }
381
545
  async _tryCatch(fn) {
382
546
  try {
383
547
  return await fn();
@@ -385,6 +549,55 @@ var Agent = class extends Server {
385
549
  throw this.onError(e);
386
550
  }
387
551
  }
552
+ /**
553
+ * Automatically wrap custom methods with agent context
554
+ * This ensures getCurrentAgent() works in all custom methods without decorators
555
+ */
556
+ _autoWrapCustomMethods() {
557
+ const basePrototypes = [_Agent.prototype, Server.prototype];
558
+ const baseMethods = /* @__PURE__ */ new Set();
559
+ for (const baseProto of basePrototypes) {
560
+ let proto2 = baseProto;
561
+ while (proto2 && proto2 !== Object.prototype) {
562
+ const methodNames = Object.getOwnPropertyNames(proto2);
563
+ for (const methodName of methodNames) {
564
+ baseMethods.add(methodName);
565
+ }
566
+ proto2 = Object.getPrototypeOf(proto2);
567
+ }
568
+ }
569
+ let proto = Object.getPrototypeOf(this);
570
+ let depth = 0;
571
+ while (proto && proto !== Object.prototype && depth < 10) {
572
+ const methodNames = Object.getOwnPropertyNames(proto);
573
+ for (const methodName of methodNames) {
574
+ if (baseMethods.has(methodName) || methodName.startsWith("_") || typeof this[methodName] !== "function" || !!Object.getOwnPropertyDescriptor(proto, methodName)?.get) {
575
+ continue;
576
+ }
577
+ if (!baseMethods.has(methodName)) {
578
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
579
+ if (descriptor && typeof descriptor.value === "function") {
580
+ const wrappedFunction = withAgentContext(
581
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
582
+ this[methodName]
583
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
584
+ );
585
+ if (this._isCallable(methodName)) {
586
+ callableMetadata.set(
587
+ wrappedFunction,
588
+ callableMetadata.get(
589
+ this[methodName]
590
+ )
591
+ );
592
+ }
593
+ this.constructor.prototype[methodName] = wrappedFunction;
594
+ }
595
+ }
596
+ }
597
+ proto = Object.getPrototypeOf(proto);
598
+ depth++;
599
+ }
600
+ }
388
601
  onError(connectionOrError, error) {
389
602
  let theError;
390
603
  if (connectionOrError && error) {
@@ -410,6 +623,108 @@ var Agent = class extends Server {
410
623
  render() {
411
624
  throw new Error("Not implemented");
412
625
  }
626
+ /**
627
+ * Queue a task to be executed in the future
628
+ * @param payload Payload to pass to the callback
629
+ * @param callback Name of the method to call
630
+ * @returns The ID of the queued task
631
+ */
632
+ async queue(callback, payload) {
633
+ const id = nanoid(9);
634
+ if (typeof callback !== "string") {
635
+ throw new Error("Callback must be a string");
636
+ }
637
+ if (typeof this[callback] !== "function") {
638
+ throw new Error(`this.${callback} is not a function`);
639
+ }
640
+ this.sql`
641
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
642
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
643
+ `;
644
+ void this._flushQueue().catch((e) => {
645
+ console.error("Error flushing queue:", e);
646
+ });
647
+ return id;
648
+ }
649
+ async _flushQueue() {
650
+ if (this._flushingQueue) {
651
+ return;
652
+ }
653
+ this._flushingQueue = true;
654
+ while (true) {
655
+ const result = this.sql`
656
+ SELECT * FROM cf_agents_queues
657
+ ORDER BY created_at ASC
658
+ `;
659
+ if (!result || result.length === 0) {
660
+ break;
661
+ }
662
+ for (const row of result || []) {
663
+ const callback = this[row.callback];
664
+ if (!callback) {
665
+ console.error(`callback ${row.callback} not found`);
666
+ continue;
667
+ }
668
+ const { connection, request, email } = agentContext.getStore() || {};
669
+ await agentContext.run(
670
+ {
671
+ agent: this,
672
+ connection,
673
+ request,
674
+ email
675
+ },
676
+ async () => {
677
+ await callback.bind(this)(JSON.parse(row.payload), row);
678
+ await this.dequeue(row.id);
679
+ }
680
+ );
681
+ }
682
+ }
683
+ this._flushingQueue = false;
684
+ }
685
+ /**
686
+ * Dequeue a task by ID
687
+ * @param id ID of the task to dequeue
688
+ */
689
+ async dequeue(id) {
690
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
691
+ }
692
+ /**
693
+ * Dequeue all tasks
694
+ */
695
+ async dequeueAll() {
696
+ this.sql`DELETE FROM cf_agents_queues`;
697
+ }
698
+ /**
699
+ * Dequeue all tasks by callback
700
+ * @param callback Name of the callback to dequeue
701
+ */
702
+ async dequeueAllByCallback(callback) {
703
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
704
+ }
705
+ /**
706
+ * Get a queued task by ID
707
+ * @param id ID of the task to get
708
+ * @returns The task or undefined if not found
709
+ */
710
+ async getQueue(id) {
711
+ const result = this.sql`
712
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
713
+ `;
714
+ return result ? { ...result[0], payload: JSON.parse(result[0].payload) } : void 0;
715
+ }
716
+ /**
717
+ * Get all queues by key and value
718
+ * @param key Key to filter by
719
+ * @param value Value to filter by
720
+ * @returns Array of matching QueueItem objects
721
+ */
722
+ async getQueues(key, value) {
723
+ const result = this.sql`
724
+ SELECT * FROM cf_agents_queues
725
+ `;
726
+ return result.filter((row) => JSON.parse(row.payload)[key] === value);
727
+ }
413
728
  /**
414
729
  * Schedule a task to be executed in the future
415
730
  * @template T Type of the payload data
@@ -420,6 +735,19 @@ var Agent = class extends Server {
420
735
  */
421
736
  async schedule(when, callback, payload) {
422
737
  const id = nanoid(9);
738
+ const emitScheduleCreate = (schedule) => this.observability?.emit(
739
+ {
740
+ displayMessage: `Schedule ${schedule.id} created`,
741
+ id: nanoid(),
742
+ payload: {
743
+ callback,
744
+ id
745
+ },
746
+ timestamp: Date.now(),
747
+ type: "schedule:create"
748
+ },
749
+ this.ctx
750
+ );
423
751
  if (typeof callback !== "string") {
424
752
  throw new Error("Callback must be a string");
425
753
  }
@@ -435,13 +763,15 @@ var Agent = class extends Server {
435
763
  )}, 'scheduled', ${timestamp})
436
764
  `;
437
765
  await this._scheduleNextAlarm();
438
- return {
766
+ const schedule = {
439
767
  callback,
440
768
  id,
441
769
  payload,
442
770
  time: timestamp,
443
771
  type: "scheduled"
444
772
  };
773
+ emitScheduleCreate(schedule);
774
+ return schedule;
445
775
  }
446
776
  if (typeof when === "number") {
447
777
  const time = new Date(Date.now() + when * 1e3);
@@ -453,7 +783,7 @@ var Agent = class extends Server {
453
783
  )}, 'delayed', ${when}, ${timestamp})
454
784
  `;
455
785
  await this._scheduleNextAlarm();
456
- return {
786
+ const schedule = {
457
787
  callback,
458
788
  delayInSeconds: when,
459
789
  id,
@@ -461,6 +791,8 @@ var Agent = class extends Server {
461
791
  time: timestamp,
462
792
  type: "delayed"
463
793
  };
794
+ emitScheduleCreate(schedule);
795
+ return schedule;
464
796
  }
465
797
  if (typeof when === "string") {
466
798
  const nextExecutionTime = getNextCronTime(when);
@@ -472,7 +804,7 @@ var Agent = class extends Server {
472
804
  )}, 'cron', ${when}, ${timestamp})
473
805
  `;
474
806
  await this._scheduleNextAlarm();
475
- return {
807
+ const schedule = {
476
808
  callback,
477
809
  cron: when,
478
810
  id,
@@ -480,6 +812,8 @@ var Agent = class extends Server {
480
812
  time: timestamp,
481
813
  type: "cron"
482
814
  };
815
+ emitScheduleCreate(schedule);
816
+ return schedule;
483
817
  }
484
818
  throw new Error("Invalid schedule type");
485
819
  }
@@ -537,15 +871,31 @@ var Agent = class extends Server {
537
871
  * @returns true if the task was cancelled, false otherwise
538
872
  */
539
873
  async cancelSchedule(id) {
874
+ const schedule = await this.getSchedule(id);
875
+ if (schedule) {
876
+ this.observability?.emit(
877
+ {
878
+ displayMessage: `Schedule ${id} cancelled`,
879
+ id: nanoid(),
880
+ payload: {
881
+ callback: schedule.callback,
882
+ id: schedule.id
883
+ },
884
+ timestamp: Date.now(),
885
+ type: "schedule:cancel"
886
+ },
887
+ this.ctx
888
+ );
889
+ }
540
890
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
541
891
  await this._scheduleNextAlarm();
542
892
  return true;
543
893
  }
544
894
  async _scheduleNextAlarm() {
545
895
  const result = this.sql`
546
- SELECT time FROM cf_agents_schedules
896
+ SELECT time FROM cf_agents_schedules
547
897
  WHERE time > ${Math.floor(Date.now() / 1e3)}
548
- ORDER BY time ASC
898
+ ORDER BY time ASC
549
899
  LIMIT 1
550
900
  `;
551
901
  if (!result) return;
@@ -561,9 +911,20 @@ var Agent = class extends Server {
561
911
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
562
912
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
563
913
  this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
914
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
564
915
  await this.ctx.storage.deleteAlarm();
565
916
  await this.ctx.storage.deleteAll();
566
917
  this.ctx.abort("destroyed");
918
+ this.observability?.emit(
919
+ {
920
+ displayMessage: "Agent destroyed",
921
+ id: nanoid(),
922
+ payload: {},
923
+ timestamp: Date.now(),
924
+ type: "destroy"
925
+ },
926
+ this.ctx
927
+ );
567
928
  }
568
929
  /**
569
930
  * Get all methods marked as callable on this Agent
@@ -589,15 +950,28 @@ var Agent = class extends Server {
589
950
  callbackUrl,
590
951
  options
591
952
  );
953
+ this.sql`
954
+ INSERT
955
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
956
+ VALUES (
957
+ ${result.id},
958
+ ${serverName},
959
+ ${url},
960
+ ${result.clientId ?? null},
961
+ ${result.authUrl ?? null},
962
+ ${callbackUrl},
963
+ ${options ? JSON.stringify(options) : null}
964
+ );
965
+ `;
592
966
  this.broadcast(
593
967
  JSON.stringify({
594
968
  mcp: this.getMcpServers(),
595
- type: "cf_agent_mcp_servers"
969
+ type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
596
970
  })
597
971
  );
598
972
  return result;
599
973
  }
600
- async _connectToMcpServerInternal(serverName, url, callbackUrl, options, reconnect) {
974
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
601
975
  const authProvider = new DurableObjectOAuthClientProvider(
602
976
  this.ctx.storage,
603
977
  this.name,
@@ -631,20 +1005,9 @@ var Agent = class extends Server {
631
1005
  authProvider
632
1006
  }
633
1007
  });
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
1008
  return {
647
1009
  authUrl,
1010
+ clientId,
648
1011
  id
649
1012
  };
650
1013
  }
@@ -656,7 +1019,7 @@ var Agent = class extends Server {
656
1019
  this.broadcast(
657
1020
  JSON.stringify({
658
1021
  mcp: this.getMcpServers(),
659
- type: "cf_agent_mcp_servers"
1022
+ type: "cf_agent_mcp_servers" /* CF_AGENT_MCP_SERVERS */
660
1023
  })
661
1024
  );
662
1025
  }
@@ -670,17 +1033,19 @@ var Agent = class extends Server {
670
1033
  const servers = this.sql`
671
1034
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
672
1035
  `;
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
- };
1036
+ if (servers && Array.isArray(servers) && servers.length > 0) {
1037
+ for (const server of servers) {
1038
+ const serverConn = this.mcp.mcpConnections[server.id];
1039
+ mcpState.servers[server.id] = {
1040
+ auth_url: server.auth_url,
1041
+ capabilities: serverConn?.serverCapabilities ?? null,
1042
+ instructions: serverConn?.instructions ?? null,
1043
+ name: server.name,
1044
+ server_url: server.server_url,
1045
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1046
+ state: serverConn?.connectionState ?? "authenticating"
1047
+ };
1048
+ }
684
1049
  }
685
1050
  return mcpState;
686
1051
  }
@@ -688,11 +1053,12 @@ var Agent = class extends Server {
688
1053
  /**
689
1054
  * Agent configuration options
690
1055
  */
691
- Agent.options = {
1056
+ _Agent.options = {
692
1057
  /** Whether the Agent should hibernate when inactive */
693
1058
  hibernate: true
694
1059
  // default to hibernate
695
1060
  };
1061
+ var Agent = _Agent;
696
1062
  async function routeAgentRequest(request, env, options) {
697
1063
  const corsHeaders = options?.cors === true ? {
698
1064
  "Access-Control-Allow-Credentials": "true",
@@ -728,7 +1094,126 @@ async function routeAgentRequest(request, env, options) {
728
1094
  }
729
1095
  return response;
730
1096
  }
731
- async function routeAgentEmail(_email, _env, _options) {
1097
+ function createHeaderBasedEmailResolver() {
1098
+ return async (email, _env) => {
1099
+ const messageId = email.headers.get("message-id");
1100
+ if (messageId) {
1101
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1102
+ if (messageIdMatch) {
1103
+ const [, agentId2, domain] = messageIdMatch;
1104
+ const agentName2 = domain.split(".")[0];
1105
+ return { agentName: agentName2, agentId: agentId2 };
1106
+ }
1107
+ }
1108
+ const references = email.headers.get("references");
1109
+ if (references) {
1110
+ const referencesMatch = references.match(
1111
+ /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
1112
+ );
1113
+ if (referencesMatch) {
1114
+ const [, base64Id, domain] = referencesMatch;
1115
+ const agentId2 = Buffer.from(base64Id, "base64").toString("hex");
1116
+ const agentName2 = domain.split(".")[0];
1117
+ return { agentName: agentName2, agentId: agentId2 };
1118
+ }
1119
+ }
1120
+ const agentName = email.headers.get("x-agent-name");
1121
+ const agentId = email.headers.get("x-agent-id");
1122
+ if (agentName && agentId) {
1123
+ return { agentName, agentId };
1124
+ }
1125
+ return null;
1126
+ };
1127
+ }
1128
+ function createAddressBasedEmailResolver(defaultAgentName) {
1129
+ return async (email, _env) => {
1130
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1131
+ if (!emailMatch) {
1132
+ return null;
1133
+ }
1134
+ const [, localPart, subAddress] = emailMatch;
1135
+ if (subAddress) {
1136
+ return {
1137
+ agentName: localPart,
1138
+ agentId: subAddress
1139
+ };
1140
+ }
1141
+ return {
1142
+ agentName: defaultAgentName,
1143
+ agentId: localPart
1144
+ };
1145
+ };
1146
+ }
1147
+ function createCatchAllEmailResolver(agentName, agentId) {
1148
+ return async () => ({ agentName, agentId });
1149
+ }
1150
+ var agentMapCache = /* @__PURE__ */ new WeakMap();
1151
+ async function routeAgentEmail(email, env, options) {
1152
+ const routingInfo = await options.resolver(email, env);
1153
+ if (!routingInfo) {
1154
+ console.warn("No routing information found for email, dropping message");
1155
+ return;
1156
+ }
1157
+ if (!agentMapCache.has(env)) {
1158
+ const map = {};
1159
+ for (const [key, value] of Object.entries(env)) {
1160
+ if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
1161
+ map[key] = value;
1162
+ map[camelCaseToKebabCase(key)] = value;
1163
+ }
1164
+ }
1165
+ agentMapCache.set(env, map);
1166
+ }
1167
+ const agentMap = agentMapCache.get(env);
1168
+ const namespace = agentMap[routingInfo.agentName];
1169
+ if (!namespace) {
1170
+ const availableAgents = Object.keys(agentMap).filter((key) => !key.includes("-")).join(", ");
1171
+ throw new Error(
1172
+ `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`
1173
+ );
1174
+ }
1175
+ const agent = await getAgentByName(
1176
+ namespace,
1177
+ routingInfo.agentId
1178
+ );
1179
+ const serialisableEmail = {
1180
+ getRaw: async () => {
1181
+ const reader = email.raw.getReader();
1182
+ const chunks = [];
1183
+ let done = false;
1184
+ while (!done) {
1185
+ const { value, done: readerDone } = await reader.read();
1186
+ done = readerDone;
1187
+ if (value) {
1188
+ chunks.push(value);
1189
+ }
1190
+ }
1191
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1192
+ const combined = new Uint8Array(totalLength);
1193
+ let offset = 0;
1194
+ for (const chunk of chunks) {
1195
+ combined.set(chunk, offset);
1196
+ offset += chunk.length;
1197
+ }
1198
+ return combined;
1199
+ },
1200
+ headers: email.headers,
1201
+ rawSize: email.rawSize,
1202
+ setReject: (reason) => {
1203
+ email.setReject(reason);
1204
+ },
1205
+ forward: (rcptTo, headers) => {
1206
+ return email.forward(rcptTo, headers);
1207
+ },
1208
+ reply: (options2) => {
1209
+ return email.reply(
1210
+ new EmailMessage(options2.from, options2.to, options2.raw)
1211
+ );
1212
+ },
1213
+ from: email.from,
1214
+ to: email.to
1215
+ };
1216
+ await agent._onEmail(serialisableEmail);
732
1217
  }
733
1218
  async function getAgentByName(namespace, name, options) {
734
1219
  return getServerByName(namespace, name, options);
@@ -752,7 +1237,7 @@ var StreamingResponse = class {
752
1237
  id: this._id,
753
1238
  result: chunk,
754
1239
  success: true,
755
- type: "rpc"
1240
+ type: "rpc" /* RPC */
756
1241
  };
757
1242
  this._connection.send(JSON.stringify(response));
758
1243
  }
@@ -770,19 +1255,48 @@ var StreamingResponse = class {
770
1255
  id: this._id,
771
1256
  result: finalChunk,
772
1257
  success: true,
773
- type: "rpc"
1258
+ type: "rpc" /* RPC */
774
1259
  };
775
1260
  this._connection.send(JSON.stringify(response));
776
1261
  }
777
1262
  };
778
1263
 
1264
+ // src/observability/index.ts
1265
+ var genericObservability = {
1266
+ emit(event) {
1267
+ if (isLocalMode()) {
1268
+ console.log(event.displayMessage);
1269
+ return;
1270
+ }
1271
+ console.log(event);
1272
+ }
1273
+ };
1274
+ var localMode = false;
1275
+ function isLocalMode() {
1276
+ if (localMode) {
1277
+ return true;
1278
+ }
1279
+ const { request } = getCurrentAgent();
1280
+ if (!request) {
1281
+ return false;
1282
+ }
1283
+ const url = new URL(request.url);
1284
+ localMode = url.hostname === "localhost";
1285
+ return localMode;
1286
+ }
1287
+
779
1288
  export {
1289
+ genericObservability,
1290
+ callable,
780
1291
  unstable_callable,
781
1292
  getCurrentAgent,
782
1293
  Agent,
783
1294
  routeAgentRequest,
1295
+ createHeaderBasedEmailResolver,
1296
+ createAddressBasedEmailResolver,
1297
+ createCatchAllEmailResolver,
784
1298
  routeAgentEmail,
785
1299
  getAgentByName,
786
1300
  StreamingResponse
787
1301
  };
788
- //# sourceMappingURL=chunk-ZRRXJUAA.js.map
1302
+ //# sourceMappingURL=chunk-O4KIASSE.js.map