agents 0.0.0-eede2bd → 0.0.0-f31397c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +22 -22
  2. package/dist/ai-chat-agent.d.ts +32 -5
  3. package/dist/ai-chat-agent.js +149 -115
  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 +27 -29
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/chunk-KUH345EY.js +116 -0
  9. package/dist/chunk-KUH345EY.js.map +1 -0
  10. package/dist/chunk-MFNGQLFL.js +1260 -0
  11. package/dist/chunk-MFNGQLFL.js.map +1 -0
  12. package/dist/{chunk-Q5ZBHY4Z.js → chunk-MW5BQ2FW.js} +49 -36
  13. package/dist/chunk-MW5BQ2FW.js.map +1 -0
  14. package/dist/chunk-PVQZBKN7.js +106 -0
  15. package/dist/chunk-PVQZBKN7.js.map +1 -0
  16. package/dist/client.d.ts +16 -2
  17. package/dist/client.js +6 -126
  18. package/dist/client.js.map +1 -1
  19. package/dist/index-BIJvkfYt.d.ts +614 -0
  20. package/dist/index.d.ts +33 -308
  21. package/dist/index.js +10 -3
  22. package/dist/mcp/client.d.ts +301 -23
  23. package/dist/mcp/client.js +1 -2
  24. package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
  25. package/dist/mcp/do-oauth-client-provider.js +3 -103
  26. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  27. package/dist/mcp/index.d.ts +20 -10
  28. package/dist/mcp/index.js +148 -175
  29. package/dist/mcp/index.js.map +1 -1
  30. package/dist/observability/index.d.ts +12 -0
  31. package/dist/observability/index.js +10 -0
  32. package/dist/react.d.ts +85 -5
  33. package/dist/react.js +20 -8
  34. package/dist/react.js.map +1 -1
  35. package/dist/schedule.d.ts +6 -6
  36. package/dist/schedule.js +4 -6
  37. package/dist/schedule.js.map +1 -1
  38. package/dist/serializable.d.ts +32 -0
  39. package/dist/serializable.js +1 -0
  40. package/dist/serializable.js.map +1 -0
  41. package/package.json +76 -69
  42. package/src/index.ts +1059 -137
  43. package/dist/chunk-5W7ZWKOP.js +0 -617
  44. package/dist/chunk-5W7ZWKOP.js.map +0 -1
  45. package/dist/chunk-HMLY7DHA.js +0 -16
  46. package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
  47. /package/dist/{chunk-HMLY7DHA.js.map → observability/index.js.map} +0 -0
@@ -0,0 +1,1260 @@
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 result = this.sql`
631
+ SELECT * FROM cf_agents_queues
632
+ ORDER BY created_at ASC
633
+ `;
634
+ if (!result || result.length === 0) {
635
+ break;
636
+ }
637
+ for (const row of result || []) {
638
+ const callback = this[row.callback];
639
+ if (!callback) {
640
+ console.error(`callback ${row.callback} not found`);
641
+ continue;
642
+ }
643
+ const { connection, request, email } = agentContext.getStore() || {};
644
+ await agentContext.run(
645
+ {
646
+ agent: this,
647
+ connection,
648
+ request,
649
+ email
650
+ },
651
+ async () => {
652
+ await callback.bind(this)(JSON.parse(row.payload), row);
653
+ await this.dequeue(row.id);
654
+ }
655
+ );
656
+ }
657
+ }
658
+ this._flushingQueue = false;
659
+ }
660
+ /**
661
+ * Dequeue a task by ID
662
+ * @param id ID of the task to dequeue
663
+ */
664
+ async dequeue(id) {
665
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
666
+ }
667
+ /**
668
+ * Dequeue all tasks
669
+ */
670
+ async dequeueAll() {
671
+ this.sql`DELETE FROM cf_agents_queues`;
672
+ }
673
+ /**
674
+ * Dequeue all tasks by callback
675
+ * @param callback Name of the callback to dequeue
676
+ */
677
+ async dequeueAllByCallback(callback) {
678
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
679
+ }
680
+ /**
681
+ * Get a queued task by ID
682
+ * @param id ID of the task to get
683
+ * @returns The task or undefined if not found
684
+ */
685
+ async getQueue(id) {
686
+ const result = this.sql`
687
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
688
+ `;
689
+ return result ? { ...result[0], payload: JSON.parse(result[0].payload) } : void 0;
690
+ }
691
+ /**
692
+ * Get all queues by key and value
693
+ * @param key Key to filter by
694
+ * @param value Value to filter by
695
+ * @returns Array of matching QueueItem objects
696
+ */
697
+ async getQueues(key, value) {
698
+ const result = this.sql`
699
+ SELECT * FROM cf_agents_queues
700
+ `;
701
+ return result.filter((row) => JSON.parse(row.payload)[key] === value);
702
+ }
703
+ /**
704
+ * Schedule a task to be executed in the future
705
+ * @template T Type of the payload data
706
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
707
+ * @param callback Name of the method to call
708
+ * @param payload Data to pass to the callback
709
+ * @returns Schedule object representing the scheduled task
710
+ */
711
+ async schedule(when, callback, payload) {
712
+ const id = nanoid(9);
713
+ const emitScheduleCreate = (schedule) => this.observability?.emit(
714
+ {
715
+ displayMessage: `Schedule ${schedule.id} created`,
716
+ id: nanoid(),
717
+ payload: schedule,
718
+ timestamp: Date.now(),
719
+ type: "schedule:create"
720
+ },
721
+ this.ctx
722
+ );
723
+ if (typeof callback !== "string") {
724
+ throw new Error("Callback must be a string");
725
+ }
726
+ if (typeof this[callback] !== "function") {
727
+ throw new Error(`this.${callback} is not a function`);
728
+ }
729
+ if (when instanceof Date) {
730
+ const timestamp = Math.floor(when.getTime() / 1e3);
731
+ this.sql`
732
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
733
+ VALUES (${id}, ${callback}, ${JSON.stringify(
734
+ payload
735
+ )}, 'scheduled', ${timestamp})
736
+ `;
737
+ await this._scheduleNextAlarm();
738
+ const schedule = {
739
+ callback,
740
+ id,
741
+ payload,
742
+ time: timestamp,
743
+ type: "scheduled"
744
+ };
745
+ emitScheduleCreate(schedule);
746
+ return schedule;
747
+ }
748
+ if (typeof when === "number") {
749
+ const time = new Date(Date.now() + when * 1e3);
750
+ const timestamp = Math.floor(time.getTime() / 1e3);
751
+ this.sql`
752
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
753
+ VALUES (${id}, ${callback}, ${JSON.stringify(
754
+ payload
755
+ )}, 'delayed', ${when}, ${timestamp})
756
+ `;
757
+ await this._scheduleNextAlarm();
758
+ const schedule = {
759
+ callback,
760
+ delayInSeconds: when,
761
+ id,
762
+ payload,
763
+ time: timestamp,
764
+ type: "delayed"
765
+ };
766
+ emitScheduleCreate(schedule);
767
+ return schedule;
768
+ }
769
+ if (typeof when === "string") {
770
+ const nextExecutionTime = getNextCronTime(when);
771
+ const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
772
+ this.sql`
773
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
774
+ VALUES (${id}, ${callback}, ${JSON.stringify(
775
+ payload
776
+ )}, 'cron', ${when}, ${timestamp})
777
+ `;
778
+ await this._scheduleNextAlarm();
779
+ const schedule = {
780
+ callback,
781
+ cron: when,
782
+ id,
783
+ payload,
784
+ time: timestamp,
785
+ type: "cron"
786
+ };
787
+ emitScheduleCreate(schedule);
788
+ return schedule;
789
+ }
790
+ throw new Error("Invalid schedule type");
791
+ }
792
+ /**
793
+ * Get a scheduled task by ID
794
+ * @template T Type of the payload data
795
+ * @param id ID of the scheduled task
796
+ * @returns The Schedule object or undefined if not found
797
+ */
798
+ async getSchedule(id) {
799
+ const result = this.sql`
800
+ SELECT * FROM cf_agents_schedules WHERE id = ${id}
801
+ `;
802
+ if (!result) {
803
+ console.error(`schedule ${id} not found`);
804
+ return void 0;
805
+ }
806
+ return { ...result[0], payload: JSON.parse(result[0].payload) };
807
+ }
808
+ /**
809
+ * Get scheduled tasks matching the given criteria
810
+ * @template T Type of the payload data
811
+ * @param criteria Criteria to filter schedules
812
+ * @returns Array of matching Schedule objects
813
+ */
814
+ getSchedules(criteria = {}) {
815
+ let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
816
+ const params = [];
817
+ if (criteria.id) {
818
+ query += " AND id = ?";
819
+ params.push(criteria.id);
820
+ }
821
+ if (criteria.type) {
822
+ query += " AND type = ?";
823
+ params.push(criteria.type);
824
+ }
825
+ if (criteria.timeRange) {
826
+ query += " AND time >= ? AND time <= ?";
827
+ const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
828
+ const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
829
+ params.push(
830
+ Math.floor(start.getTime() / 1e3),
831
+ Math.floor(end.getTime() / 1e3)
832
+ );
833
+ }
834
+ const result = this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
835
+ ...row,
836
+ payload: JSON.parse(row.payload)
837
+ }));
838
+ return result;
839
+ }
840
+ /**
841
+ * Cancel a scheduled task
842
+ * @param id ID of the task to cancel
843
+ * @returns true if the task was cancelled, false otherwise
844
+ */
845
+ async cancelSchedule(id) {
846
+ const schedule = await this.getSchedule(id);
847
+ if (schedule) {
848
+ this.observability?.emit(
849
+ {
850
+ displayMessage: `Schedule ${id} cancelled`,
851
+ id: nanoid(),
852
+ payload: schedule,
853
+ timestamp: Date.now(),
854
+ type: "schedule:cancel"
855
+ },
856
+ this.ctx
857
+ );
858
+ }
859
+ this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
860
+ await this._scheduleNextAlarm();
861
+ return true;
862
+ }
863
+ async _scheduleNextAlarm() {
864
+ const result = this.sql`
865
+ SELECT time FROM cf_agents_schedules
866
+ WHERE time > ${Math.floor(Date.now() / 1e3)}
867
+ ORDER BY time ASC
868
+ LIMIT 1
869
+ `;
870
+ if (!result) return;
871
+ if (result.length > 0 && "time" in result[0]) {
872
+ const nextTime = result[0].time * 1e3;
873
+ await this.ctx.storage.setAlarm(nextTime);
874
+ }
875
+ }
876
+ /**
877
+ * Destroy the Agent, removing all state and scheduled tasks
878
+ */
879
+ async destroy() {
880
+ this.sql`DROP TABLE IF EXISTS cf_agents_state`;
881
+ this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
882
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
883
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
884
+ await this.ctx.storage.deleteAlarm();
885
+ await this.ctx.storage.deleteAll();
886
+ this.ctx.abort("destroyed");
887
+ this.observability?.emit(
888
+ {
889
+ displayMessage: "Agent destroyed",
890
+ id: nanoid(),
891
+ payload: {},
892
+ timestamp: Date.now(),
893
+ type: "destroy"
894
+ },
895
+ this.ctx
896
+ );
897
+ }
898
+ /**
899
+ * Get all methods marked as callable on this Agent
900
+ * @returns A map of method names to their metadata
901
+ */
902
+ _isCallable(method) {
903
+ return callableMetadata.has(this[method]);
904
+ }
905
+ /**
906
+ * Connect to a new MCP Server
907
+ *
908
+ * @param url MCP Server SSE URL
909
+ * @param callbackHost Base host for the agent, used for the redirect URI.
910
+ * @param agentsPrefix agents routing prefix if not using `agents`
911
+ * @param options MCP client and transport (header) options
912
+ * @returns authUrl
913
+ */
914
+ async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
915
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
916
+ const result = await this._connectToMcpServerInternal(
917
+ serverName,
918
+ url,
919
+ callbackUrl,
920
+ options
921
+ );
922
+ this.sql`
923
+ INSERT
924
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
925
+ VALUES (
926
+ ${result.id},
927
+ ${serverName},
928
+ ${url},
929
+ ${result.clientId ?? null},
930
+ ${result.authUrl ?? null},
931
+ ${callbackUrl},
932
+ ${options ? JSON.stringify(options) : null}
933
+ );
934
+ `;
935
+ this.broadcast(
936
+ JSON.stringify({
937
+ mcp: this.getMcpServers(),
938
+ type: "cf_agent_mcp_servers"
939
+ })
940
+ );
941
+ return result;
942
+ }
943
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
944
+ const authProvider = new DurableObjectOAuthClientProvider(
945
+ this.ctx.storage,
946
+ this.name,
947
+ callbackUrl
948
+ );
949
+ if (reconnect) {
950
+ authProvider.serverId = reconnect.id;
951
+ if (reconnect.oauthClientId) {
952
+ authProvider.clientId = reconnect.oauthClientId;
953
+ }
954
+ }
955
+ let headerTransportOpts = {};
956
+ if (options?.transport?.headers) {
957
+ headerTransportOpts = {
958
+ eventSourceInit: {
959
+ fetch: (url2, init) => fetch(url2, {
960
+ ...init,
961
+ headers: options?.transport?.headers
962
+ })
963
+ },
964
+ requestInit: {
965
+ headers: options?.transport?.headers
966
+ }
967
+ };
968
+ }
969
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
970
+ client: options?.client,
971
+ reconnect,
972
+ transport: {
973
+ ...headerTransportOpts,
974
+ authProvider
975
+ }
976
+ });
977
+ return {
978
+ authUrl,
979
+ clientId,
980
+ id
981
+ };
982
+ }
983
+ async removeMcpServer(id) {
984
+ this.mcp.closeConnection(id);
985
+ this.sql`
986
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
987
+ `;
988
+ this.broadcast(
989
+ JSON.stringify({
990
+ mcp: this.getMcpServers(),
991
+ type: "cf_agent_mcp_servers"
992
+ })
993
+ );
994
+ }
995
+ getMcpServers() {
996
+ const mcpState = {
997
+ prompts: this.mcp.listPrompts(),
998
+ resources: this.mcp.listResources(),
999
+ servers: {},
1000
+ tools: this.mcp.listTools()
1001
+ };
1002
+ const servers = this.sql`
1003
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1004
+ `;
1005
+ if (servers && Array.isArray(servers) && servers.length > 0) {
1006
+ for (const server of servers) {
1007
+ const serverConn = this.mcp.mcpConnections[server.id];
1008
+ mcpState.servers[server.id] = {
1009
+ auth_url: server.auth_url,
1010
+ capabilities: serverConn?.serverCapabilities ?? null,
1011
+ instructions: serverConn?.instructions ?? null,
1012
+ name: server.name,
1013
+ server_url: server.server_url,
1014
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1015
+ state: serverConn?.connectionState ?? "authenticating"
1016
+ };
1017
+ }
1018
+ }
1019
+ return mcpState;
1020
+ }
1021
+ };
1022
+ /**
1023
+ * Agent configuration options
1024
+ */
1025
+ _Agent.options = {
1026
+ /** Whether the Agent should hibernate when inactive */
1027
+ hibernate: true
1028
+ // default to hibernate
1029
+ };
1030
+ var Agent = _Agent;
1031
+ async function routeAgentRequest(request, env, options) {
1032
+ const corsHeaders = options?.cors === true ? {
1033
+ "Access-Control-Allow-Credentials": "true",
1034
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1035
+ "Access-Control-Allow-Origin": "*",
1036
+ "Access-Control-Max-Age": "86400"
1037
+ } : options?.cors;
1038
+ if (request.method === "OPTIONS") {
1039
+ if (corsHeaders) {
1040
+ return new Response(null, {
1041
+ headers: corsHeaders
1042
+ });
1043
+ }
1044
+ console.warn(
1045
+ "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
1046
+ );
1047
+ }
1048
+ let response = await routePartykitRequest(
1049
+ request,
1050
+ env,
1051
+ {
1052
+ prefix: "agents",
1053
+ ...options
1054
+ }
1055
+ );
1056
+ if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
1057
+ response = new Response(response.body, {
1058
+ headers: {
1059
+ ...response.headers,
1060
+ ...corsHeaders
1061
+ }
1062
+ });
1063
+ }
1064
+ return response;
1065
+ }
1066
+ function createHeaderBasedEmailResolver() {
1067
+ return async (email, _env) => {
1068
+ const messageId = email.headers.get("message-id");
1069
+ if (messageId) {
1070
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1071
+ if (messageIdMatch) {
1072
+ const [, agentId2, domain] = messageIdMatch;
1073
+ const agentName2 = domain.split(".")[0];
1074
+ return { agentName: agentName2, agentId: agentId2 };
1075
+ }
1076
+ }
1077
+ const references = email.headers.get("references");
1078
+ if (references) {
1079
+ const referencesMatch = references.match(
1080
+ /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
1081
+ );
1082
+ if (referencesMatch) {
1083
+ const [, base64Id, domain] = referencesMatch;
1084
+ const agentId2 = Buffer.from(base64Id, "base64").toString("hex");
1085
+ const agentName2 = domain.split(".")[0];
1086
+ return { agentName: agentName2, agentId: agentId2 };
1087
+ }
1088
+ }
1089
+ const agentName = email.headers.get("x-agent-name");
1090
+ const agentId = email.headers.get("x-agent-id");
1091
+ if (agentName && agentId) {
1092
+ return { agentName, agentId };
1093
+ }
1094
+ return null;
1095
+ };
1096
+ }
1097
+ function createAddressBasedEmailResolver(defaultAgentName) {
1098
+ return async (email, _env) => {
1099
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1100
+ if (!emailMatch) {
1101
+ return null;
1102
+ }
1103
+ const [, localPart, subAddress] = emailMatch;
1104
+ if (subAddress) {
1105
+ return {
1106
+ agentName: localPart,
1107
+ agentId: subAddress
1108
+ };
1109
+ }
1110
+ return {
1111
+ agentName: defaultAgentName,
1112
+ agentId: localPart
1113
+ };
1114
+ };
1115
+ }
1116
+ function createCatchAllEmailResolver(agentName, agentId) {
1117
+ return async () => ({ agentName, agentId });
1118
+ }
1119
+ async function routeAgentEmail(email, env, options) {
1120
+ const routingInfo = await options.resolver(email, env);
1121
+ if (!routingInfo) {
1122
+ console.warn("No routing information found for email, dropping message");
1123
+ return;
1124
+ }
1125
+ const namespaceBinding = env[routingInfo.agentName];
1126
+ if (!namespaceBinding) {
1127
+ throw new Error(
1128
+ `Agent namespace '${routingInfo.agentName}' not found in environment`
1129
+ );
1130
+ }
1131
+ if (typeof namespaceBinding !== "object" || !("idFromName" in namespaceBinding) || typeof namespaceBinding.idFromName !== "function") {
1132
+ throw new Error(
1133
+ `Environment binding '${routingInfo.agentName}' is not an AgentNamespace (found: ${typeof namespaceBinding})`
1134
+ );
1135
+ }
1136
+ const namespace = namespaceBinding;
1137
+ const agent = await getAgentByName(namespace, routingInfo.agentId);
1138
+ const serialisableEmail = {
1139
+ getRaw: async () => {
1140
+ const reader = email.raw.getReader();
1141
+ const chunks = [];
1142
+ let done = false;
1143
+ while (!done) {
1144
+ const { value, done: readerDone } = await reader.read();
1145
+ done = readerDone;
1146
+ if (value) {
1147
+ chunks.push(value);
1148
+ }
1149
+ }
1150
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1151
+ const combined = new Uint8Array(totalLength);
1152
+ let offset = 0;
1153
+ for (const chunk of chunks) {
1154
+ combined.set(chunk, offset);
1155
+ offset += chunk.length;
1156
+ }
1157
+ return combined;
1158
+ },
1159
+ headers: email.headers,
1160
+ rawSize: email.rawSize,
1161
+ setReject: (reason) => {
1162
+ email.setReject(reason);
1163
+ },
1164
+ forward: (rcptTo, headers) => {
1165
+ return email.forward(rcptTo, headers);
1166
+ },
1167
+ reply: (options2) => {
1168
+ return email.reply(
1169
+ new EmailMessage(options2.from, options2.to, options2.raw)
1170
+ );
1171
+ },
1172
+ from: email.from,
1173
+ to: email.to
1174
+ };
1175
+ await agent._onEmail(serialisableEmail);
1176
+ }
1177
+ async function getAgentByName(namespace, name, options) {
1178
+ return getServerByName(namespace, name, options);
1179
+ }
1180
+ var StreamingResponse = class {
1181
+ constructor(connection, id) {
1182
+ this._closed = false;
1183
+ this._connection = connection;
1184
+ this._id = id;
1185
+ }
1186
+ /**
1187
+ * Send a chunk of data to the client
1188
+ * @param chunk The data to send
1189
+ */
1190
+ send(chunk) {
1191
+ if (this._closed) {
1192
+ throw new Error("StreamingResponse is already closed");
1193
+ }
1194
+ const response = {
1195
+ done: false,
1196
+ id: this._id,
1197
+ result: chunk,
1198
+ success: true,
1199
+ type: "rpc"
1200
+ };
1201
+ this._connection.send(JSON.stringify(response));
1202
+ }
1203
+ /**
1204
+ * End the stream and send the final chunk (if any)
1205
+ * @param finalChunk Optional final chunk of data to send
1206
+ */
1207
+ end(finalChunk) {
1208
+ if (this._closed) {
1209
+ throw new Error("StreamingResponse is already closed");
1210
+ }
1211
+ this._closed = true;
1212
+ const response = {
1213
+ done: true,
1214
+ id: this._id,
1215
+ result: finalChunk,
1216
+ success: true,
1217
+ type: "rpc"
1218
+ };
1219
+ this._connection.send(JSON.stringify(response));
1220
+ }
1221
+ };
1222
+
1223
+ // src/observability/index.ts
1224
+ var genericObservability = {
1225
+ emit(event) {
1226
+ if (isLocalMode()) {
1227
+ console.log(event.displayMessage);
1228
+ return;
1229
+ }
1230
+ console.log(event);
1231
+ }
1232
+ };
1233
+ var localMode = false;
1234
+ function isLocalMode() {
1235
+ if (localMode) {
1236
+ return true;
1237
+ }
1238
+ const { request } = getCurrentAgent();
1239
+ if (!request) {
1240
+ return false;
1241
+ }
1242
+ const url = new URL(request.url);
1243
+ localMode = url.hostname === "localhost";
1244
+ return localMode;
1245
+ }
1246
+
1247
+ export {
1248
+ genericObservability,
1249
+ unstable_callable,
1250
+ getCurrentAgent,
1251
+ Agent,
1252
+ routeAgentRequest,
1253
+ createHeaderBasedEmailResolver,
1254
+ createAddressBasedEmailResolver,
1255
+ createCatchAllEmailResolver,
1256
+ routeAgentEmail,
1257
+ getAgentByName,
1258
+ StreamingResponse
1259
+ };
1260
+ //# sourceMappingURL=chunk-MFNGQLFL.js.map