agents 0.0.0-e376805 → 0.0.0-e48e5f9

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 (48) hide show
  1. package/README.md +22 -22
  2. package/dist/ai-chat-agent.d.ts +51 -5
  3. package/dist/ai-chat-agent.js +177 -77
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +18 -5
  6. package/dist/ai-react.js +49 -42
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/ai-types.d.ts +5 -0
  9. package/dist/chunk-5YIRLLUX.js +1264 -0
  10. package/dist/chunk-5YIRLLUX.js.map +1 -0
  11. package/dist/chunk-KUH345EY.js +116 -0
  12. package/dist/chunk-KUH345EY.js.map +1 -0
  13. package/dist/chunk-MW5BQ2FW.js +469 -0
  14. package/dist/chunk-MW5BQ2FW.js.map +1 -0
  15. package/dist/chunk-PVQZBKN7.js +106 -0
  16. package/dist/chunk-PVQZBKN7.js.map +1 -0
  17. package/dist/client.d.ts +16 -2
  18. package/dist/client.js +6 -126
  19. package/dist/client.js.map +1 -1
  20. package/dist/index-BIJvkfYt.d.ts +614 -0
  21. package/dist/index.d.ts +37 -306
  22. package/dist/index.js +14 -8
  23. package/dist/mcp/client.d.ts +417 -37
  24. package/dist/mcp/client.js +3 -262
  25. package/dist/mcp/client.js.map +1 -1
  26. package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
  27. package/dist/mcp/do-oauth-client-provider.js +7 -0
  28. package/dist/mcp/index.d.ts +45 -6
  29. package/dist/mcp/index.js +615 -175
  30. package/dist/mcp/index.js.map +1 -1
  31. package/dist/observability/index.d.ts +12 -0
  32. package/dist/observability/index.js +10 -0
  33. package/dist/observability/index.js.map +1 -0
  34. package/dist/react.d.ts +85 -5
  35. package/dist/react.js +37 -25
  36. package/dist/react.js.map +1 -1
  37. package/dist/schedule.d.ts +6 -6
  38. package/dist/schedule.js +4 -6
  39. package/dist/schedule.js.map +1 -1
  40. package/dist/serializable.d.ts +32 -0
  41. package/dist/serializable.js +1 -0
  42. package/dist/serializable.js.map +1 -0
  43. package/package.json +81 -51
  44. package/src/index.ts +1101 -142
  45. package/dist/chunk-HMLY7DHA.js +0 -16
  46. package/dist/chunk-YMUU7QHV.js +0 -595
  47. package/dist/chunk-YMUU7QHV.js.map +0 -1
  48. /package/dist/{chunk-HMLY7DHA.js.map → mcp/do-oauth-client-provider.js.map} +0 -0
@@ -0,0 +1,1264 @@
1
+ import {
2
+ MCPClientManager
3
+ } from "./chunk-MW5BQ2FW.js";
4
+ import {
5
+ DurableObjectOAuthClientProvider
6
+ } from "./chunk-PVQZBKN7.js";
7
+ import {
8
+ camelCaseToKebabCase
9
+ } from "./chunk-KUH345EY.js";
10
+
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";
16
+ import {
17
+ Server,
18
+ getServerByName,
19
+ routePartykitRequest
20
+ } from "partyserver";
21
+ function isRPCRequest(msg) {
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);
23
+ }
24
+ function isStateUpdateMessage(msg) {
25
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "cf_agent_state" && "state" in msg;
26
+ }
27
+ var callableMetadata = /* @__PURE__ */ new Map();
28
+ function unstable_callable(metadata = {}) {
29
+ return function callableDecorator(target, context) {
30
+ if (!callableMetadata.has(target)) {
31
+ callableMetadata.set(target, metadata);
32
+ }
33
+ return target;
34
+ };
35
+ }
36
+ function getNextCronTime(cron) {
37
+ const interval = parseCronExpression(cron);
38
+ return interval.getNextDate();
39
+ }
40
+ var STATE_ROW_ID = "cf_state_row_id";
41
+ var STATE_WAS_CHANGED = "cf_state_was_changed";
42
+ var DEFAULT_STATE = {};
43
+ var agentContext = new AsyncLocalStorage();
44
+ function getCurrentAgent() {
45
+ const store = agentContext.getStore();
46
+ if (!store) {
47
+ return {
48
+ agent: void 0,
49
+ connection: void 0,
50
+ request: void 0,
51
+ email: void 0
52
+ };
53
+ }
54
+ return store;
55
+ }
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 {
65
+ constructor(ctx, env) {
66
+ super(ctx, env);
67
+ this._state = DEFAULT_STATE;
68
+ this._ParentClass = Object.getPrototypeOf(this).constructor;
69
+ this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
70
+ /**
71
+ * Initial state for the Agent
72
+ * Override to provide default state values
73
+ */
74
+ this.initialState = DEFAULT_STATE;
75
+ /**
76
+ * The observability implementation to use for the Agent
77
+ */
78
+ this.observability = genericObservability;
79
+ this._flushingQueue = false;
80
+ /**
81
+ * Method called when an alarm fires.
82
+ * Executes any scheduled tasks that are due.
83
+ *
84
+ * @remarks
85
+ * To schedule a task, please use the `this.schedule` method instead.
86
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
87
+ */
88
+ this.alarm = async () => {
89
+ const now = Math.floor(Date.now() / 1e3);
90
+ const result = this.sql`
91
+ SELECT * FROM cf_agents_schedules WHERE time <= ${now}
92
+ `;
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;
99
+ }
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`
129
+ UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
130
+ `;
131
+ } else {
132
+ this.sql`
133
+ DELETE FROM cf_agents_schedules WHERE id = ${row.id}
134
+ `;
135
+ }
136
+ }
137
+ }
138
+ await this._scheduleNextAlarm();
139
+ };
140
+ this._autoWrapCustomMethods();
141
+ this.sql`
142
+ CREATE TABLE IF NOT EXISTS cf_agents_state (
143
+ id TEXT PRIMARY KEY NOT NULL,
144
+ state TEXT
145
+ )
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
+ `;
155
+ void this.ctx.blockConcurrencyWhile(async () => {
156
+ return this._tryCatch(async () => {
157
+ this.sql`
158
+ CREATE TABLE IF NOT EXISTS cf_agents_schedules (
159
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
160
+ callback TEXT,
161
+ payload TEXT,
162
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
163
+ time INTEGER,
164
+ delayInSeconds INTEGER,
165
+ cron TEXT,
166
+ created_at INTEGER DEFAULT (unixepoch())
167
+ )
168
+ `;
169
+ await this.alarm();
170
+ });
171
+ });
172
+ this.sql`
173
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
174
+ id TEXT PRIMARY KEY NOT NULL,
175
+ name TEXT NOT NULL,
176
+ server_url TEXT NOT NULL,
177
+ callback_url TEXT NOT NULL,
178
+ client_id TEXT,
179
+ auth_url TEXT,
180
+ server_options TEXT
181
+ )
182
+ `;
183
+ const _onRequest = this.onRequest.bind(this);
184
+ this.onRequest = (request) => {
185
+ return agentContext.run(
186
+ { agent: this, connection: void 0, request, email: void 0 },
187
+ async () => {
188
+ if (this.mcp.isCallbackRequest(request)) {
189
+ await this.mcp.handleCallbackRequest(request);
190
+ this.broadcast(
191
+ JSON.stringify({
192
+ mcp: this.getMcpServers(),
193
+ type: "cf_agent_mcp_servers"
194
+ })
195
+ );
196
+ return new Response("<script>window.close();</script>", {
197
+ headers: { "content-type": "text/html" },
198
+ status: 200
199
+ });
200
+ }
201
+ return this._tryCatch(() => _onRequest(request));
202
+ }
203
+ );
204
+ };
205
+ const _onMessage = this.onMessage.bind(this);
206
+ this.onMessage = async (connection, message) => {
207
+ return agentContext.run(
208
+ { agent: this, connection, request: void 0, email: void 0 },
209
+ async () => {
210
+ if (typeof message !== "string") {
211
+ return this._tryCatch(() => _onMessage(connection, message));
212
+ }
213
+ let parsed;
214
+ try {
215
+ parsed = JSON.parse(message);
216
+ } catch (_e) {
217
+ return this._tryCatch(() => _onMessage(connection, message));
218
+ }
219
+ if (isStateUpdateMessage(parsed)) {
220
+ this._setStateInternal(parsed.state, connection);
221
+ return;
222
+ }
223
+ if (isRPCRequest(parsed)) {
224
+ try {
225
+ const { id, method, args } = parsed;
226
+ const methodFn = this[method];
227
+ if (typeof methodFn !== "function") {
228
+ throw new Error(`Method ${method} does not exist`);
229
+ }
230
+ if (!this._isCallable(method)) {
231
+ throw new Error(`Method ${method} is not callable`);
232
+ }
233
+ const metadata = callableMetadata.get(methodFn);
234
+ if (metadata?.streaming) {
235
+ const stream = new StreamingResponse(connection, id);
236
+ await methodFn.apply(this, [stream, ...args]);
237
+ return;
238
+ }
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
+ );
255
+ const response = {
256
+ done: true,
257
+ id,
258
+ result,
259
+ success: true,
260
+ type: "rpc"
261
+ };
262
+ connection.send(JSON.stringify(response));
263
+ } catch (e) {
264
+ const response = {
265
+ error: e instanceof Error ? e.message : "Unknown error occurred",
266
+ id: parsed.id,
267
+ success: false,
268
+ type: "rpc"
269
+ };
270
+ connection.send(JSON.stringify(response));
271
+ console.error("RPC error:", e);
272
+ }
273
+ return;
274
+ }
275
+ return this._tryCatch(() => _onMessage(connection, message));
276
+ }
277
+ );
278
+ };
279
+ const _onConnect = this.onConnect.bind(this);
280
+ this.onConnect = (connection, ctx2) => {
281
+ return agentContext.run(
282
+ { agent: this, connection, request: ctx2.request, email: void 0 },
283
+ async () => {
284
+ setTimeout(() => {
285
+ if (this.state) {
286
+ connection.send(
287
+ JSON.stringify({
288
+ state: this.state,
289
+ type: "cf_agent_state"
290
+ })
291
+ );
292
+ }
293
+ connection.send(
294
+ JSON.stringify({
295
+ mcp: this.getMcpServers(),
296
+ type: "cf_agent_mcp_servers"
297
+ })
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
+ );
311
+ return this._tryCatch(() => _onConnect(connection, ctx2));
312
+ }, 20);
313
+ }
314
+ );
315
+ };
316
+ const _onStart = this.onStart.bind(this);
317
+ this.onStart = async () => {
318
+ return agentContext.run(
319
+ {
320
+ agent: this,
321
+ connection: void 0,
322
+ request: void 0,
323
+ email: void 0
324
+ },
325
+ async () => {
326
+ const servers = this.sql`
327
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
328
+ `;
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
+ })
349
+ );
350
+ });
351
+ }
352
+ await this._tryCatch(() => _onStart());
353
+ }
354
+ );
355
+ };
356
+ }
357
+ /**
358
+ * Current state of the Agent
359
+ */
360
+ get state() {
361
+ if (this._state !== DEFAULT_STATE) {
362
+ return this._state;
363
+ }
364
+ const wasChanged = this.sql`
365
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
366
+ `;
367
+ const result = this.sql`
368
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
369
+ `;
370
+ if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
371
+ result[0]?.state) {
372
+ const state = result[0]?.state;
373
+ this._state = JSON.parse(state);
374
+ return this._state;
375
+ }
376
+ if (this.initialState === DEFAULT_STATE) {
377
+ return void 0;
378
+ }
379
+ this.setState(this.initialState);
380
+ return this.initialState;
381
+ }
382
+ /**
383
+ * Execute SQL queries against the Agent's database
384
+ * @template T Type of the returned rows
385
+ * @param strings SQL query template strings
386
+ * @param values Values to be inserted into the query
387
+ * @returns Array of query results
388
+ */
389
+ sql(strings, ...values) {
390
+ let query = "";
391
+ try {
392
+ query = strings.reduce(
393
+ (acc, str, i) => acc + str + (i < values.length ? "?" : ""),
394
+ ""
395
+ );
396
+ return [...this.ctx.storage.sql.exec(query, ...values)];
397
+ } catch (e) {
398
+ console.error(`failed to execute sql query: ${query}`, e);
399
+ throw this.onError(e);
400
+ }
401
+ }
402
+ _setStateInternal(state, source = "server") {
403
+ const previousState = this._state;
404
+ this._state = state;
405
+ this.sql`
406
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
407
+ VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
408
+ `;
409
+ this.sql`
410
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
411
+ VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
412
+ `;
413
+ this.broadcast(
414
+ JSON.stringify({
415
+ state,
416
+ type: "cf_agent_state"
417
+ }),
418
+ source !== "server" ? [source.id] : []
419
+ );
420
+ return this._tryCatch(() => {
421
+ const { connection, request, email } = agentContext.getStore() || {};
422
+ return agentContext.run(
423
+ { agent: this, connection, request, email },
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
+ );
438
+ return this.onStateUpdate(state, source);
439
+ }
440
+ );
441
+ });
442
+ }
443
+ /**
444
+ * Update the Agent's state
445
+ * @param state New state to set
446
+ */
447
+ setState(state) {
448
+ this._setStateInternal(state, "server");
449
+ }
450
+ /**
451
+ * Called when the Agent's state is updated
452
+ * @param state Updated state
453
+ * @param source Source of the state update ("server" or a client connection)
454
+ */
455
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
456
+ onStateUpdate(state, source) {
457
+ }
458
+ /**
459
+ * Called when the Agent receives an email via routeAgentEmail()
460
+ * Override this method to handle incoming emails
461
+ * @param email Email message to process
462
+ */
463
+ async _onEmail(email) {
464
+ return agentContext.run(
465
+ { agent: this, connection: void 0, request: void 0, email },
466
+ async () => {
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
+ }
478
+ }
479
+ );
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
+ }
520
+ async _tryCatch(fn) {
521
+ try {
522
+ return await fn();
523
+ } catch (e) {
524
+ throw this.onError(e);
525
+ }
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
+ }
576
+ onError(connectionOrError, error) {
577
+ let theError;
578
+ if (connectionOrError && error) {
579
+ theError = error;
580
+ console.error(
581
+ "Error on websocket connection:",
582
+ connectionOrError.id,
583
+ theError
584
+ );
585
+ console.error(
586
+ "Override onError(connection, error) to handle websocket connection errors"
587
+ );
588
+ } else {
589
+ theError = connectionOrError;
590
+ console.error("Error on server:", theError);
591
+ console.error("Override onError(error) to handle server errors");
592
+ }
593
+ throw theError;
594
+ }
595
+ /**
596
+ * Render content (not implemented in base class)
597
+ */
598
+ render() {
599
+ throw new Error("Not implemented");
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 executed = [];
631
+ const result = this.sql`
632
+ SELECT * FROM cf_agents_queues
633
+ ORDER BY created_at ASC
634
+ `;
635
+ if (!result || result.length === 0) {
636
+ break;
637
+ }
638
+ for (const row of result || []) {
639
+ const callback = this[row.callback];
640
+ if (!callback) {
641
+ console.error(`callback ${row.callback} not found`);
642
+ continue;
643
+ }
644
+ const { connection, request, email } = agentContext.getStore() || {};
645
+ await agentContext.run(
646
+ {
647
+ agent: this,
648
+ connection,
649
+ request,
650
+ email
651
+ },
652
+ async () => {
653
+ await callback.bind(this)(JSON.parse(row.payload), row);
654
+ executed.push(row.id);
655
+ }
656
+ );
657
+ }
658
+ for (const id of executed) {
659
+ await this.dequeue(id);
660
+ }
661
+ }
662
+ this._flushingQueue = false;
663
+ }
664
+ /**
665
+ * Dequeue a task by ID
666
+ * @param id ID of the task to dequeue
667
+ */
668
+ async dequeue(id) {
669
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
670
+ }
671
+ /**
672
+ * Dequeue all tasks
673
+ */
674
+ async dequeueAll() {
675
+ this.sql`DELETE FROM cf_agents_queues`;
676
+ }
677
+ /**
678
+ * Dequeue all tasks by callback
679
+ * @param callback Name of the callback to dequeue
680
+ */
681
+ async dequeueAllByCallback(callback) {
682
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
683
+ }
684
+ /**
685
+ * Get a queued task by ID
686
+ * @param id ID of the task to get
687
+ * @returns The task or undefined if not found
688
+ */
689
+ async getQueue(id) {
690
+ const result = this.sql`
691
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
692
+ `;
693
+ return result ? { ...result[0], payload: JSON.parse(result[0].payload) } : void 0;
694
+ }
695
+ /**
696
+ * Get all queues by key and value
697
+ * @param key Key to filter by
698
+ * @param value Value to filter by
699
+ * @returns Array of matching QueueItem objects
700
+ */
701
+ async getQueues(key, value) {
702
+ const result = this.sql`
703
+ SELECT * FROM cf_agents_queues
704
+ `;
705
+ return result.filter((row) => JSON.parse(row.payload)[key] === value);
706
+ }
707
+ /**
708
+ * Schedule a task to be executed in the future
709
+ * @template T Type of the payload data
710
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
711
+ * @param callback Name of the method to call
712
+ * @param payload Data to pass to the callback
713
+ * @returns Schedule object representing the scheduled task
714
+ */
715
+ async schedule(when, callback, payload) {
716
+ const id = nanoid(9);
717
+ const emitScheduleCreate = (schedule) => this.observability?.emit(
718
+ {
719
+ displayMessage: `Schedule ${schedule.id} created`,
720
+ id: nanoid(),
721
+ payload: schedule,
722
+ timestamp: Date.now(),
723
+ type: "schedule:create"
724
+ },
725
+ this.ctx
726
+ );
727
+ if (typeof callback !== "string") {
728
+ throw new Error("Callback must be a string");
729
+ }
730
+ if (typeof this[callback] !== "function") {
731
+ throw new Error(`this.${callback} is not a function`);
732
+ }
733
+ if (when instanceof Date) {
734
+ const timestamp = Math.floor(when.getTime() / 1e3);
735
+ this.sql`
736
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
737
+ VALUES (${id}, ${callback}, ${JSON.stringify(
738
+ payload
739
+ )}, 'scheduled', ${timestamp})
740
+ `;
741
+ await this._scheduleNextAlarm();
742
+ const schedule = {
743
+ callback,
744
+ id,
745
+ payload,
746
+ time: timestamp,
747
+ type: "scheduled"
748
+ };
749
+ emitScheduleCreate(schedule);
750
+ return schedule;
751
+ }
752
+ if (typeof when === "number") {
753
+ const time = new Date(Date.now() + when * 1e3);
754
+ const timestamp = Math.floor(time.getTime() / 1e3);
755
+ this.sql`
756
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
757
+ VALUES (${id}, ${callback}, ${JSON.stringify(
758
+ payload
759
+ )}, 'delayed', ${when}, ${timestamp})
760
+ `;
761
+ await this._scheduleNextAlarm();
762
+ const schedule = {
763
+ callback,
764
+ delayInSeconds: when,
765
+ id,
766
+ payload,
767
+ time: timestamp,
768
+ type: "delayed"
769
+ };
770
+ emitScheduleCreate(schedule);
771
+ return schedule;
772
+ }
773
+ if (typeof when === "string") {
774
+ const nextExecutionTime = getNextCronTime(when);
775
+ const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
776
+ this.sql`
777
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
778
+ VALUES (${id}, ${callback}, ${JSON.stringify(
779
+ payload
780
+ )}, 'cron', ${when}, ${timestamp})
781
+ `;
782
+ await this._scheduleNextAlarm();
783
+ const schedule = {
784
+ callback,
785
+ cron: when,
786
+ id,
787
+ payload,
788
+ time: timestamp,
789
+ type: "cron"
790
+ };
791
+ emitScheduleCreate(schedule);
792
+ return schedule;
793
+ }
794
+ throw new Error("Invalid schedule type");
795
+ }
796
+ /**
797
+ * Get a scheduled task by ID
798
+ * @template T Type of the payload data
799
+ * @param id ID of the scheduled task
800
+ * @returns The Schedule object or undefined if not found
801
+ */
802
+ async getSchedule(id) {
803
+ const result = this.sql`
804
+ SELECT * FROM cf_agents_schedules WHERE id = ${id}
805
+ `;
806
+ if (!result) {
807
+ console.error(`schedule ${id} not found`);
808
+ return void 0;
809
+ }
810
+ return { ...result[0], payload: JSON.parse(result[0].payload) };
811
+ }
812
+ /**
813
+ * Get scheduled tasks matching the given criteria
814
+ * @template T Type of the payload data
815
+ * @param criteria Criteria to filter schedules
816
+ * @returns Array of matching Schedule objects
817
+ */
818
+ getSchedules(criteria = {}) {
819
+ let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
820
+ const params = [];
821
+ if (criteria.id) {
822
+ query += " AND id = ?";
823
+ params.push(criteria.id);
824
+ }
825
+ if (criteria.type) {
826
+ query += " AND type = ?";
827
+ params.push(criteria.type);
828
+ }
829
+ if (criteria.timeRange) {
830
+ query += " AND time >= ? AND time <= ?";
831
+ const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
832
+ const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
833
+ params.push(
834
+ Math.floor(start.getTime() / 1e3),
835
+ Math.floor(end.getTime() / 1e3)
836
+ );
837
+ }
838
+ const result = this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
839
+ ...row,
840
+ payload: JSON.parse(row.payload)
841
+ }));
842
+ return result;
843
+ }
844
+ /**
845
+ * Cancel a scheduled task
846
+ * @param id ID of the task to cancel
847
+ * @returns true if the task was cancelled, false otherwise
848
+ */
849
+ async cancelSchedule(id) {
850
+ const schedule = await this.getSchedule(id);
851
+ if (schedule) {
852
+ this.observability?.emit(
853
+ {
854
+ displayMessage: `Schedule ${id} cancelled`,
855
+ id: nanoid(),
856
+ payload: schedule,
857
+ timestamp: Date.now(),
858
+ type: "schedule:cancel"
859
+ },
860
+ this.ctx
861
+ );
862
+ }
863
+ this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
864
+ await this._scheduleNextAlarm();
865
+ return true;
866
+ }
867
+ async _scheduleNextAlarm() {
868
+ const result = this.sql`
869
+ SELECT time FROM cf_agents_schedules
870
+ WHERE time > ${Math.floor(Date.now() / 1e3)}
871
+ ORDER BY time ASC
872
+ LIMIT 1
873
+ `;
874
+ if (!result) return;
875
+ if (result.length > 0 && "time" in result[0]) {
876
+ const nextTime = result[0].time * 1e3;
877
+ await this.ctx.storage.setAlarm(nextTime);
878
+ }
879
+ }
880
+ /**
881
+ * Destroy the Agent, removing all state and scheduled tasks
882
+ */
883
+ async destroy() {
884
+ this.sql`DROP TABLE IF EXISTS cf_agents_state`;
885
+ this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
886
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
887
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
888
+ await this.ctx.storage.deleteAlarm();
889
+ await this.ctx.storage.deleteAll();
890
+ this.ctx.abort("destroyed");
891
+ this.observability?.emit(
892
+ {
893
+ displayMessage: "Agent destroyed",
894
+ id: nanoid(),
895
+ payload: {},
896
+ timestamp: Date.now(),
897
+ type: "destroy"
898
+ },
899
+ this.ctx
900
+ );
901
+ }
902
+ /**
903
+ * Get all methods marked as callable on this Agent
904
+ * @returns A map of method names to their metadata
905
+ */
906
+ _isCallable(method) {
907
+ return callableMetadata.has(this[method]);
908
+ }
909
+ /**
910
+ * Connect to a new MCP Server
911
+ *
912
+ * @param url MCP Server SSE URL
913
+ * @param callbackHost Base host for the agent, used for the redirect URI.
914
+ * @param agentsPrefix agents routing prefix if not using `agents`
915
+ * @param options MCP client and transport (header) options
916
+ * @returns authUrl
917
+ */
918
+ async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
919
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
920
+ const result = await this._connectToMcpServerInternal(
921
+ serverName,
922
+ url,
923
+ callbackUrl,
924
+ options
925
+ );
926
+ this.sql`
927
+ INSERT
928
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
929
+ VALUES (
930
+ ${result.id},
931
+ ${serverName},
932
+ ${url},
933
+ ${result.clientId ?? null},
934
+ ${result.authUrl ?? null},
935
+ ${callbackUrl},
936
+ ${options ? JSON.stringify(options) : null}
937
+ );
938
+ `;
939
+ this.broadcast(
940
+ JSON.stringify({
941
+ mcp: this.getMcpServers(),
942
+ type: "cf_agent_mcp_servers"
943
+ })
944
+ );
945
+ return result;
946
+ }
947
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
948
+ const authProvider = new DurableObjectOAuthClientProvider(
949
+ this.ctx.storage,
950
+ this.name,
951
+ callbackUrl
952
+ );
953
+ if (reconnect) {
954
+ authProvider.serverId = reconnect.id;
955
+ if (reconnect.oauthClientId) {
956
+ authProvider.clientId = reconnect.oauthClientId;
957
+ }
958
+ }
959
+ let headerTransportOpts = {};
960
+ if (options?.transport?.headers) {
961
+ headerTransportOpts = {
962
+ eventSourceInit: {
963
+ fetch: (url2, init) => fetch(url2, {
964
+ ...init,
965
+ headers: options?.transport?.headers
966
+ })
967
+ },
968
+ requestInit: {
969
+ headers: options?.transport?.headers
970
+ }
971
+ };
972
+ }
973
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
974
+ client: options?.client,
975
+ reconnect,
976
+ transport: {
977
+ ...headerTransportOpts,
978
+ authProvider
979
+ }
980
+ });
981
+ return {
982
+ authUrl,
983
+ clientId,
984
+ id
985
+ };
986
+ }
987
+ async removeMcpServer(id) {
988
+ this.mcp.closeConnection(id);
989
+ this.sql`
990
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
991
+ `;
992
+ this.broadcast(
993
+ JSON.stringify({
994
+ mcp: this.getMcpServers(),
995
+ type: "cf_agent_mcp_servers"
996
+ })
997
+ );
998
+ }
999
+ getMcpServers() {
1000
+ const mcpState = {
1001
+ prompts: this.mcp.listPrompts(),
1002
+ resources: this.mcp.listResources(),
1003
+ servers: {},
1004
+ tools: this.mcp.listTools()
1005
+ };
1006
+ const servers = this.sql`
1007
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1008
+ `;
1009
+ if (servers && Array.isArray(servers) && servers.length > 0) {
1010
+ for (const server of servers) {
1011
+ const serverConn = this.mcp.mcpConnections[server.id];
1012
+ mcpState.servers[server.id] = {
1013
+ auth_url: server.auth_url,
1014
+ capabilities: serverConn?.serverCapabilities ?? null,
1015
+ instructions: serverConn?.instructions ?? null,
1016
+ name: server.name,
1017
+ server_url: server.server_url,
1018
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1019
+ state: serverConn?.connectionState ?? "authenticating"
1020
+ };
1021
+ }
1022
+ }
1023
+ return mcpState;
1024
+ }
1025
+ };
1026
+ /**
1027
+ * Agent configuration options
1028
+ */
1029
+ _Agent.options = {
1030
+ /** Whether the Agent should hibernate when inactive */
1031
+ hibernate: true
1032
+ // default to hibernate
1033
+ };
1034
+ var Agent = _Agent;
1035
+ async function routeAgentRequest(request, env, options) {
1036
+ const corsHeaders = options?.cors === true ? {
1037
+ "Access-Control-Allow-Credentials": "true",
1038
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1039
+ "Access-Control-Allow-Origin": "*",
1040
+ "Access-Control-Max-Age": "86400"
1041
+ } : options?.cors;
1042
+ if (request.method === "OPTIONS") {
1043
+ if (corsHeaders) {
1044
+ return new Response(null, {
1045
+ headers: corsHeaders
1046
+ });
1047
+ }
1048
+ console.warn(
1049
+ "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
1050
+ );
1051
+ }
1052
+ let response = await routePartykitRequest(
1053
+ request,
1054
+ env,
1055
+ {
1056
+ prefix: "agents",
1057
+ ...options
1058
+ }
1059
+ );
1060
+ if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
1061
+ response = new Response(response.body, {
1062
+ headers: {
1063
+ ...response.headers,
1064
+ ...corsHeaders
1065
+ }
1066
+ });
1067
+ }
1068
+ return response;
1069
+ }
1070
+ function createHeaderBasedEmailResolver() {
1071
+ return async (email, _env) => {
1072
+ const messageId = email.headers.get("message-id");
1073
+ if (messageId) {
1074
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1075
+ if (messageIdMatch) {
1076
+ const [, agentId2, domain] = messageIdMatch;
1077
+ const agentName2 = domain.split(".")[0];
1078
+ return { agentName: agentName2, agentId: agentId2 };
1079
+ }
1080
+ }
1081
+ const references = email.headers.get("references");
1082
+ if (references) {
1083
+ const referencesMatch = references.match(
1084
+ /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
1085
+ );
1086
+ if (referencesMatch) {
1087
+ const [, base64Id, domain] = referencesMatch;
1088
+ const agentId2 = Buffer.from(base64Id, "base64").toString("hex");
1089
+ const agentName2 = domain.split(".")[0];
1090
+ return { agentName: agentName2, agentId: agentId2 };
1091
+ }
1092
+ }
1093
+ const agentName = email.headers.get("x-agent-name");
1094
+ const agentId = email.headers.get("x-agent-id");
1095
+ if (agentName && agentId) {
1096
+ return { agentName, agentId };
1097
+ }
1098
+ return null;
1099
+ };
1100
+ }
1101
+ function createAddressBasedEmailResolver(defaultAgentName) {
1102
+ return async (email, _env) => {
1103
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1104
+ if (!emailMatch) {
1105
+ return null;
1106
+ }
1107
+ const [, localPart, subAddress] = emailMatch;
1108
+ if (subAddress) {
1109
+ return {
1110
+ agentName: localPart,
1111
+ agentId: subAddress
1112
+ };
1113
+ }
1114
+ return {
1115
+ agentName: defaultAgentName,
1116
+ agentId: localPart
1117
+ };
1118
+ };
1119
+ }
1120
+ function createCatchAllEmailResolver(agentName, agentId) {
1121
+ return async () => ({ agentName, agentId });
1122
+ }
1123
+ async function routeAgentEmail(email, env, options) {
1124
+ const routingInfo = await options.resolver(email, env);
1125
+ if (!routingInfo) {
1126
+ console.warn("No routing information found for email, dropping message");
1127
+ return;
1128
+ }
1129
+ const namespaceBinding = env[routingInfo.agentName];
1130
+ if (!namespaceBinding) {
1131
+ throw new Error(
1132
+ `Agent namespace '${routingInfo.agentName}' not found in environment`
1133
+ );
1134
+ }
1135
+ if (typeof namespaceBinding !== "object" || !("idFromName" in namespaceBinding) || typeof namespaceBinding.idFromName !== "function") {
1136
+ throw new Error(
1137
+ `Environment binding '${routingInfo.agentName}' is not an AgentNamespace (found: ${typeof namespaceBinding})`
1138
+ );
1139
+ }
1140
+ const namespace = namespaceBinding;
1141
+ const agent = await getAgentByName(namespace, routingInfo.agentId);
1142
+ const serialisableEmail = {
1143
+ getRaw: async () => {
1144
+ const reader = email.raw.getReader();
1145
+ const chunks = [];
1146
+ let done = false;
1147
+ while (!done) {
1148
+ const { value, done: readerDone } = await reader.read();
1149
+ done = readerDone;
1150
+ if (value) {
1151
+ chunks.push(value);
1152
+ }
1153
+ }
1154
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1155
+ const combined = new Uint8Array(totalLength);
1156
+ let offset = 0;
1157
+ for (const chunk of chunks) {
1158
+ combined.set(chunk, offset);
1159
+ offset += chunk.length;
1160
+ }
1161
+ return combined;
1162
+ },
1163
+ headers: email.headers,
1164
+ rawSize: email.rawSize,
1165
+ setReject: (reason) => {
1166
+ email.setReject(reason);
1167
+ },
1168
+ forward: (rcptTo, headers) => {
1169
+ return email.forward(rcptTo, headers);
1170
+ },
1171
+ reply: (options2) => {
1172
+ return email.reply(
1173
+ new EmailMessage(options2.from, options2.to, options2.raw)
1174
+ );
1175
+ },
1176
+ from: email.from,
1177
+ to: email.to
1178
+ };
1179
+ await agent._onEmail(serialisableEmail);
1180
+ }
1181
+ async function getAgentByName(namespace, name, options) {
1182
+ return getServerByName(namespace, name, options);
1183
+ }
1184
+ var StreamingResponse = class {
1185
+ constructor(connection, id) {
1186
+ this._closed = false;
1187
+ this._connection = connection;
1188
+ this._id = id;
1189
+ }
1190
+ /**
1191
+ * Send a chunk of data to the client
1192
+ * @param chunk The data to send
1193
+ */
1194
+ send(chunk) {
1195
+ if (this._closed) {
1196
+ throw new Error("StreamingResponse is already closed");
1197
+ }
1198
+ const response = {
1199
+ done: false,
1200
+ id: this._id,
1201
+ result: chunk,
1202
+ success: true,
1203
+ type: "rpc"
1204
+ };
1205
+ this._connection.send(JSON.stringify(response));
1206
+ }
1207
+ /**
1208
+ * End the stream and send the final chunk (if any)
1209
+ * @param finalChunk Optional final chunk of data to send
1210
+ */
1211
+ end(finalChunk) {
1212
+ if (this._closed) {
1213
+ throw new Error("StreamingResponse is already closed");
1214
+ }
1215
+ this._closed = true;
1216
+ const response = {
1217
+ done: true,
1218
+ id: this._id,
1219
+ result: finalChunk,
1220
+ success: true,
1221
+ type: "rpc"
1222
+ };
1223
+ this._connection.send(JSON.stringify(response));
1224
+ }
1225
+ };
1226
+
1227
+ // src/observability/index.ts
1228
+ var genericObservability = {
1229
+ emit(event) {
1230
+ if (isLocalMode()) {
1231
+ console.log(event.displayMessage);
1232
+ return;
1233
+ }
1234
+ console.log(event);
1235
+ }
1236
+ };
1237
+ var localMode = false;
1238
+ function isLocalMode() {
1239
+ if (localMode) {
1240
+ return true;
1241
+ }
1242
+ const { request } = getCurrentAgent();
1243
+ if (!request) {
1244
+ return false;
1245
+ }
1246
+ const url = new URL(request.url);
1247
+ localMode = url.hostname === "localhost";
1248
+ return localMode;
1249
+ }
1250
+
1251
+ export {
1252
+ genericObservability,
1253
+ unstable_callable,
1254
+ getCurrentAgent,
1255
+ Agent,
1256
+ routeAgentRequest,
1257
+ createHeaderBasedEmailResolver,
1258
+ createAddressBasedEmailResolver,
1259
+ createCatchAllEmailResolver,
1260
+ routeAgentEmail,
1261
+ getAgentByName,
1262
+ StreamingResponse
1263
+ };
1264
+ //# sourceMappingURL=chunk-5YIRLLUX.js.map