agents 0.0.0-c4d53d7 → 0.0.0-c5e3a32

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 +28 -29
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/chunk-EDUDXISR.js +1148 -0
  9. package/dist/chunk-EDUDXISR.js.map +1 -0
  10. package/dist/chunk-KUH345EY.js +116 -0
  11. package/dist/chunk-KUH345EY.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-DukU3sIa.d.ts +571 -0
  20. package/dist/index.d.ts +32 -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 -68
  42. package/src/index.ts +925 -135
  43. package/dist/chunk-HD4VEHBA.js +0 -608
  44. package/dist/chunk-HD4VEHBA.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,1148 @@
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
+ /**
80
+ * Method called when an alarm fires.
81
+ * Executes any scheduled tasks that are due.
82
+ *
83
+ * @remarks
84
+ * To schedule a task, please use the `this.schedule` method instead.
85
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
86
+ */
87
+ this.alarm = async () => {
88
+ const now = Math.floor(Date.now() / 1e3);
89
+ const result = this.sql`
90
+ SELECT * FROM cf_agents_schedules WHERE time <= ${now}
91
+ `;
92
+ if (result && Array.isArray(result)) {
93
+ for (const row of result) {
94
+ const callback = this[row.callback];
95
+ if (!callback) {
96
+ console.error(`callback ${row.callback} not found`);
97
+ continue;
98
+ }
99
+ await agentContext.run(
100
+ {
101
+ agent: this,
102
+ connection: void 0,
103
+ request: void 0,
104
+ email: void 0
105
+ },
106
+ async () => {
107
+ try {
108
+ this.observability?.emit(
109
+ {
110
+ displayMessage: `Schedule ${row.id} executed`,
111
+ id: nanoid(),
112
+ payload: row,
113
+ timestamp: Date.now(),
114
+ type: "schedule:execute"
115
+ },
116
+ this.ctx
117
+ );
118
+ await callback.bind(this)(JSON.parse(row.payload), row);
119
+ } catch (e) {
120
+ console.error(`error executing callback "${row.callback}"`, e);
121
+ }
122
+ }
123
+ );
124
+ if (row.type === "cron") {
125
+ const nextExecutionTime = getNextCronTime(row.cron);
126
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
127
+ this.sql`
128
+ UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
129
+ `;
130
+ } else {
131
+ this.sql`
132
+ DELETE FROM cf_agents_schedules WHERE id = ${row.id}
133
+ `;
134
+ }
135
+ }
136
+ }
137
+ await this._scheduleNextAlarm();
138
+ };
139
+ this.sql`
140
+ CREATE TABLE IF NOT EXISTS cf_agents_state (
141
+ id TEXT PRIMARY KEY NOT NULL,
142
+ state TEXT
143
+ )
144
+ `;
145
+ this._autoWrapCustomMethods();
146
+ void this.ctx.blockConcurrencyWhile(async () => {
147
+ return this._tryCatch(async () => {
148
+ this.sql`
149
+ CREATE TABLE IF NOT EXISTS cf_agents_schedules (
150
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
151
+ callback TEXT,
152
+ payload TEXT,
153
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
154
+ time INTEGER,
155
+ delayInSeconds INTEGER,
156
+ cron TEXT,
157
+ created_at INTEGER DEFAULT (unixepoch())
158
+ )
159
+ `;
160
+ await this.alarm();
161
+ });
162
+ });
163
+ this.sql`
164
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
165
+ id TEXT PRIMARY KEY NOT NULL,
166
+ name TEXT NOT NULL,
167
+ server_url TEXT NOT NULL,
168
+ callback_url TEXT NOT NULL,
169
+ client_id TEXT,
170
+ auth_url TEXT,
171
+ server_options TEXT
172
+ )
173
+ `;
174
+ const _onRequest = this.onRequest.bind(this);
175
+ this.onRequest = (request) => {
176
+ return agentContext.run(
177
+ { agent: this, connection: void 0, request, email: void 0 },
178
+ async () => {
179
+ if (this.mcp.isCallbackRequest(request)) {
180
+ await this.mcp.handleCallbackRequest(request);
181
+ this.broadcast(
182
+ JSON.stringify({
183
+ mcp: this.getMcpServers(),
184
+ type: "cf_agent_mcp_servers"
185
+ })
186
+ );
187
+ return new Response("<script>window.close();</script>", {
188
+ headers: { "content-type": "text/html" },
189
+ status: 200
190
+ });
191
+ }
192
+ return this._tryCatch(() => _onRequest(request));
193
+ }
194
+ );
195
+ };
196
+ const _onMessage = this.onMessage.bind(this);
197
+ this.onMessage = async (connection, message) => {
198
+ return agentContext.run(
199
+ { agent: this, connection, request: void 0, email: void 0 },
200
+ async () => {
201
+ if (typeof message !== "string") {
202
+ return this._tryCatch(() => _onMessage(connection, message));
203
+ }
204
+ let parsed;
205
+ try {
206
+ parsed = JSON.parse(message);
207
+ } catch (_e) {
208
+ return this._tryCatch(() => _onMessage(connection, message));
209
+ }
210
+ if (isStateUpdateMessage(parsed)) {
211
+ this._setStateInternal(parsed.state, connection);
212
+ return;
213
+ }
214
+ if (isRPCRequest(parsed)) {
215
+ try {
216
+ const { id, method, args } = parsed;
217
+ const methodFn = this[method];
218
+ if (typeof methodFn !== "function") {
219
+ throw new Error(`Method ${method} does not exist`);
220
+ }
221
+ if (!this._isCallable(method)) {
222
+ throw new Error(`Method ${method} is not callable`);
223
+ }
224
+ const metadata = callableMetadata.get(methodFn);
225
+ if (metadata?.streaming) {
226
+ const stream = new StreamingResponse(connection, id);
227
+ await methodFn.apply(this, [stream, ...args]);
228
+ return;
229
+ }
230
+ const result = await methodFn.apply(this, args);
231
+ this.observability?.emit(
232
+ {
233
+ displayMessage: `RPC call to ${method}`,
234
+ id: nanoid(),
235
+ payload: {
236
+ args,
237
+ method,
238
+ streaming: metadata?.streaming,
239
+ success: true
240
+ },
241
+ timestamp: Date.now(),
242
+ type: "rpc"
243
+ },
244
+ this.ctx
245
+ );
246
+ const response = {
247
+ done: true,
248
+ id,
249
+ result,
250
+ success: true,
251
+ type: "rpc"
252
+ };
253
+ connection.send(JSON.stringify(response));
254
+ } catch (e) {
255
+ const response = {
256
+ error: e instanceof Error ? e.message : "Unknown error occurred",
257
+ id: parsed.id,
258
+ success: false,
259
+ type: "rpc"
260
+ };
261
+ connection.send(JSON.stringify(response));
262
+ console.error("RPC error:", e);
263
+ }
264
+ return;
265
+ }
266
+ return this._tryCatch(() => _onMessage(connection, message));
267
+ }
268
+ );
269
+ };
270
+ const _onConnect = this.onConnect.bind(this);
271
+ this.onConnect = (connection, ctx2) => {
272
+ return agentContext.run(
273
+ { agent: this, connection, request: ctx2.request, email: void 0 },
274
+ async () => {
275
+ setTimeout(() => {
276
+ if (this.state) {
277
+ connection.send(
278
+ JSON.stringify({
279
+ state: this.state,
280
+ type: "cf_agent_state"
281
+ })
282
+ );
283
+ }
284
+ connection.send(
285
+ JSON.stringify({
286
+ mcp: this.getMcpServers(),
287
+ type: "cf_agent_mcp_servers"
288
+ })
289
+ );
290
+ this.observability?.emit(
291
+ {
292
+ displayMessage: "Connection established",
293
+ id: nanoid(),
294
+ payload: {
295
+ connectionId: connection.id
296
+ },
297
+ timestamp: Date.now(),
298
+ type: "connect"
299
+ },
300
+ this.ctx
301
+ );
302
+ return this._tryCatch(() => _onConnect(connection, ctx2));
303
+ }, 20);
304
+ }
305
+ );
306
+ };
307
+ const _onStart = this.onStart.bind(this);
308
+ this.onStart = async () => {
309
+ return agentContext.run(
310
+ {
311
+ agent: this,
312
+ connection: void 0,
313
+ request: void 0,
314
+ email: void 0
315
+ },
316
+ async () => {
317
+ const servers = this.sql`
318
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
319
+ `;
320
+ if (servers && Array.isArray(servers) && servers.length > 0) {
321
+ Promise.allSettled(
322
+ servers.map((server) => {
323
+ return this._connectToMcpServerInternal(
324
+ server.name,
325
+ server.server_url,
326
+ server.callback_url,
327
+ server.server_options ? JSON.parse(server.server_options) : void 0,
328
+ {
329
+ id: server.id,
330
+ oauthClientId: server.client_id ?? void 0
331
+ }
332
+ );
333
+ })
334
+ ).then((_results) => {
335
+ this.broadcast(
336
+ JSON.stringify({
337
+ mcp: this.getMcpServers(),
338
+ type: "cf_agent_mcp_servers"
339
+ })
340
+ );
341
+ });
342
+ }
343
+ await this._tryCatch(() => _onStart());
344
+ }
345
+ );
346
+ };
347
+ }
348
+ /**
349
+ * Current state of the Agent
350
+ */
351
+ get state() {
352
+ if (this._state !== DEFAULT_STATE) {
353
+ return this._state;
354
+ }
355
+ const wasChanged = this.sql`
356
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
357
+ `;
358
+ const result = this.sql`
359
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
360
+ `;
361
+ if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
362
+ result[0]?.state) {
363
+ const state = result[0]?.state;
364
+ this._state = JSON.parse(state);
365
+ return this._state;
366
+ }
367
+ if (this.initialState === DEFAULT_STATE) {
368
+ return void 0;
369
+ }
370
+ this.setState(this.initialState);
371
+ return this.initialState;
372
+ }
373
+ /**
374
+ * Execute SQL queries against the Agent's database
375
+ * @template T Type of the returned rows
376
+ * @param strings SQL query template strings
377
+ * @param values Values to be inserted into the query
378
+ * @returns Array of query results
379
+ */
380
+ sql(strings, ...values) {
381
+ let query = "";
382
+ try {
383
+ query = strings.reduce(
384
+ (acc, str, i) => acc + str + (i < values.length ? "?" : ""),
385
+ ""
386
+ );
387
+ return [...this.ctx.storage.sql.exec(query, ...values)];
388
+ } catch (e) {
389
+ console.error(`failed to execute sql query: ${query}`, e);
390
+ throw this.onError(e);
391
+ }
392
+ }
393
+ _setStateInternal(state, source = "server") {
394
+ const previousState = this._state;
395
+ this._state = state;
396
+ this.sql`
397
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
398
+ VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
399
+ `;
400
+ this.sql`
401
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
402
+ VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
403
+ `;
404
+ this.broadcast(
405
+ JSON.stringify({
406
+ state,
407
+ type: "cf_agent_state"
408
+ }),
409
+ source !== "server" ? [source.id] : []
410
+ );
411
+ return this._tryCatch(() => {
412
+ const { connection, request, email } = agentContext.getStore() || {};
413
+ return agentContext.run(
414
+ { agent: this, connection, request, email },
415
+ async () => {
416
+ this.observability?.emit(
417
+ {
418
+ displayMessage: "State updated",
419
+ id: nanoid(),
420
+ payload: {
421
+ previousState,
422
+ state
423
+ },
424
+ timestamp: Date.now(),
425
+ type: "state:update"
426
+ },
427
+ this.ctx
428
+ );
429
+ return this.onStateUpdate(state, source);
430
+ }
431
+ );
432
+ });
433
+ }
434
+ /**
435
+ * Update the Agent's state
436
+ * @param state New state to set
437
+ */
438
+ setState(state) {
439
+ this._setStateInternal(state, "server");
440
+ }
441
+ /**
442
+ * Called when the Agent's state is updated
443
+ * @param state Updated state
444
+ * @param source Source of the state update ("server" or a client connection)
445
+ */
446
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
447
+ onStateUpdate(state, source) {
448
+ }
449
+ /**
450
+ * Called when the Agent receives an email via routeAgentEmail()
451
+ * Override this method to handle incoming emails
452
+ * @param email Email message to process
453
+ */
454
+ async _onEmail(email) {
455
+ return agentContext.run(
456
+ { agent: this, connection: void 0, request: void 0, email },
457
+ async () => {
458
+ if ("onEmail" in this && typeof this.onEmail === "function") {
459
+ return this._tryCatch(
460
+ () => this.onEmail(email)
461
+ );
462
+ } else {
463
+ console.log("Received email from:", email.from, "to:", email.to);
464
+ console.log("Subject:", email.headers.get("subject"));
465
+ console.log(
466
+ "Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
467
+ );
468
+ }
469
+ }
470
+ );
471
+ }
472
+ /**
473
+ * Reply to an email
474
+ * @param email The email to reply to
475
+ * @param options Options for the reply
476
+ * @returns void
477
+ */
478
+ async replyToEmail(email, options) {
479
+ return this._tryCatch(async () => {
480
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
481
+ const agentId = this.name;
482
+ const { createMimeMessage } = await import("mimetext");
483
+ const msg = createMimeMessage();
484
+ msg.setSender({ addr: email.to, name: options.fromName });
485
+ msg.setRecipient(email.from);
486
+ msg.setSubject(
487
+ options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
488
+ );
489
+ msg.addMessage({
490
+ contentType: options.contentType || "text/plain",
491
+ data: options.body
492
+ });
493
+ const domain = email.from.split("@")[1];
494
+ const messageId = `<${agentId}@${domain}>`;
495
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID"));
496
+ msg.setHeader("Message-ID", messageId);
497
+ msg.setHeader("X-Agent-Name", agentName);
498
+ msg.setHeader("X-Agent-ID", agentId);
499
+ if (options.headers) {
500
+ for (const [key, value] of Object.entries(options.headers)) {
501
+ msg.setHeader(key, value);
502
+ }
503
+ }
504
+ await email.reply({
505
+ from: email.to,
506
+ raw: msg.asRaw(),
507
+ to: email.from
508
+ });
509
+ });
510
+ }
511
+ async _tryCatch(fn) {
512
+ try {
513
+ return await fn();
514
+ } catch (e) {
515
+ throw this.onError(e);
516
+ }
517
+ }
518
+ /**
519
+ * Automatically wrap custom methods with agent context
520
+ * This ensures getCurrentAgent() works in all custom methods without decorators
521
+ */
522
+ _autoWrapCustomMethods() {
523
+ const basePrototypes = [_Agent.prototype, Server.prototype];
524
+ const baseMethods = /* @__PURE__ */ new Set();
525
+ for (const baseProto of basePrototypes) {
526
+ let proto2 = baseProto;
527
+ while (proto2 && proto2 !== Object.prototype) {
528
+ const methodNames = Object.getOwnPropertyNames(proto2);
529
+ for (const methodName of methodNames) {
530
+ baseMethods.add(methodName);
531
+ }
532
+ proto2 = Object.getPrototypeOf(proto2);
533
+ }
534
+ }
535
+ let proto = Object.getPrototypeOf(this);
536
+ let depth = 0;
537
+ while (proto && proto !== Object.prototype && depth < 10) {
538
+ const methodNames = Object.getOwnPropertyNames(proto);
539
+ for (const methodName of methodNames) {
540
+ if (baseMethods.has(methodName) || methodName.startsWith("_") || typeof this[methodName] !== "function") {
541
+ continue;
542
+ }
543
+ if (!baseMethods.has(methodName)) {
544
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
545
+ if (descriptor && typeof descriptor.value === "function") {
546
+ const wrappedFunction = withAgentContext(
547
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
548
+ this[methodName]
549
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
550
+ );
551
+ if (this._isCallable(methodName)) {
552
+ callableMetadata.set(
553
+ wrappedFunction,
554
+ callableMetadata.get(
555
+ this[methodName]
556
+ )
557
+ );
558
+ }
559
+ this.constructor.prototype[methodName] = wrappedFunction;
560
+ }
561
+ }
562
+ }
563
+ proto = Object.getPrototypeOf(proto);
564
+ depth++;
565
+ }
566
+ }
567
+ onError(connectionOrError, error) {
568
+ let theError;
569
+ if (connectionOrError && error) {
570
+ theError = error;
571
+ console.error(
572
+ "Error on websocket connection:",
573
+ connectionOrError.id,
574
+ theError
575
+ );
576
+ console.error(
577
+ "Override onError(connection, error) to handle websocket connection errors"
578
+ );
579
+ } else {
580
+ theError = connectionOrError;
581
+ console.error("Error on server:", theError);
582
+ console.error("Override onError(error) to handle server errors");
583
+ }
584
+ throw theError;
585
+ }
586
+ /**
587
+ * Render content (not implemented in base class)
588
+ */
589
+ render() {
590
+ throw new Error("Not implemented");
591
+ }
592
+ /**
593
+ * Schedule a task to be executed in the future
594
+ * @template T Type of the payload data
595
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
596
+ * @param callback Name of the method to call
597
+ * @param payload Data to pass to the callback
598
+ * @returns Schedule object representing the scheduled task
599
+ */
600
+ async schedule(when, callback, payload) {
601
+ const id = nanoid(9);
602
+ const emitScheduleCreate = (schedule) => this.observability?.emit(
603
+ {
604
+ displayMessage: `Schedule ${schedule.id} created`,
605
+ id: nanoid(),
606
+ payload: schedule,
607
+ timestamp: Date.now(),
608
+ type: "schedule:create"
609
+ },
610
+ this.ctx
611
+ );
612
+ if (typeof callback !== "string") {
613
+ throw new Error("Callback must be a string");
614
+ }
615
+ if (typeof this[callback] !== "function") {
616
+ throw new Error(`this.${callback} is not a function`);
617
+ }
618
+ if (when instanceof Date) {
619
+ const timestamp = Math.floor(when.getTime() / 1e3);
620
+ this.sql`
621
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
622
+ VALUES (${id}, ${callback}, ${JSON.stringify(
623
+ payload
624
+ )}, 'scheduled', ${timestamp})
625
+ `;
626
+ await this._scheduleNextAlarm();
627
+ const schedule = {
628
+ callback,
629
+ id,
630
+ payload,
631
+ time: timestamp,
632
+ type: "scheduled"
633
+ };
634
+ emitScheduleCreate(schedule);
635
+ return schedule;
636
+ }
637
+ if (typeof when === "number") {
638
+ const time = new Date(Date.now() + when * 1e3);
639
+ const timestamp = Math.floor(time.getTime() / 1e3);
640
+ this.sql`
641
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
642
+ VALUES (${id}, ${callback}, ${JSON.stringify(
643
+ payload
644
+ )}, 'delayed', ${when}, ${timestamp})
645
+ `;
646
+ await this._scheduleNextAlarm();
647
+ const schedule = {
648
+ callback,
649
+ delayInSeconds: when,
650
+ id,
651
+ payload,
652
+ time: timestamp,
653
+ type: "delayed"
654
+ };
655
+ emitScheduleCreate(schedule);
656
+ return schedule;
657
+ }
658
+ if (typeof when === "string") {
659
+ const nextExecutionTime = getNextCronTime(when);
660
+ const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
661
+ this.sql`
662
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
663
+ VALUES (${id}, ${callback}, ${JSON.stringify(
664
+ payload
665
+ )}, 'cron', ${when}, ${timestamp})
666
+ `;
667
+ await this._scheduleNextAlarm();
668
+ const schedule = {
669
+ callback,
670
+ cron: when,
671
+ id,
672
+ payload,
673
+ time: timestamp,
674
+ type: "cron"
675
+ };
676
+ emitScheduleCreate(schedule);
677
+ return schedule;
678
+ }
679
+ throw new Error("Invalid schedule type");
680
+ }
681
+ /**
682
+ * Get a scheduled task by ID
683
+ * @template T Type of the payload data
684
+ * @param id ID of the scheduled task
685
+ * @returns The Schedule object or undefined if not found
686
+ */
687
+ async getSchedule(id) {
688
+ const result = this.sql`
689
+ SELECT * FROM cf_agents_schedules WHERE id = ${id}
690
+ `;
691
+ if (!result) {
692
+ console.error(`schedule ${id} not found`);
693
+ return void 0;
694
+ }
695
+ return { ...result[0], payload: JSON.parse(result[0].payload) };
696
+ }
697
+ /**
698
+ * Get scheduled tasks matching the given criteria
699
+ * @template T Type of the payload data
700
+ * @param criteria Criteria to filter schedules
701
+ * @returns Array of matching Schedule objects
702
+ */
703
+ getSchedules(criteria = {}) {
704
+ let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
705
+ const params = [];
706
+ if (criteria.id) {
707
+ query += " AND id = ?";
708
+ params.push(criteria.id);
709
+ }
710
+ if (criteria.type) {
711
+ query += " AND type = ?";
712
+ params.push(criteria.type);
713
+ }
714
+ if (criteria.timeRange) {
715
+ query += " AND time >= ? AND time <= ?";
716
+ const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
717
+ const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
718
+ params.push(
719
+ Math.floor(start.getTime() / 1e3),
720
+ Math.floor(end.getTime() / 1e3)
721
+ );
722
+ }
723
+ const result = this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
724
+ ...row,
725
+ payload: JSON.parse(row.payload)
726
+ }));
727
+ return result;
728
+ }
729
+ /**
730
+ * Cancel a scheduled task
731
+ * @param id ID of the task to cancel
732
+ * @returns true if the task was cancelled, false otherwise
733
+ */
734
+ async cancelSchedule(id) {
735
+ const schedule = await this.getSchedule(id);
736
+ if (schedule) {
737
+ this.observability?.emit(
738
+ {
739
+ displayMessage: `Schedule ${id} cancelled`,
740
+ id: nanoid(),
741
+ payload: schedule,
742
+ timestamp: Date.now(),
743
+ type: "schedule:cancel"
744
+ },
745
+ this.ctx
746
+ );
747
+ }
748
+ this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
749
+ await this._scheduleNextAlarm();
750
+ return true;
751
+ }
752
+ async _scheduleNextAlarm() {
753
+ const result = this.sql`
754
+ SELECT time FROM cf_agents_schedules
755
+ WHERE time > ${Math.floor(Date.now() / 1e3)}
756
+ ORDER BY time ASC
757
+ LIMIT 1
758
+ `;
759
+ if (!result) return;
760
+ if (result.length > 0 && "time" in result[0]) {
761
+ const nextTime = result[0].time * 1e3;
762
+ await this.ctx.storage.setAlarm(nextTime);
763
+ }
764
+ }
765
+ /**
766
+ * Destroy the Agent, removing all state and scheduled tasks
767
+ */
768
+ async destroy() {
769
+ this.sql`DROP TABLE IF EXISTS cf_agents_state`;
770
+ this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
771
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
772
+ await this.ctx.storage.deleteAlarm();
773
+ await this.ctx.storage.deleteAll();
774
+ this.ctx.abort("destroyed");
775
+ this.observability?.emit(
776
+ {
777
+ displayMessage: "Agent destroyed",
778
+ id: nanoid(),
779
+ payload: {},
780
+ timestamp: Date.now(),
781
+ type: "destroy"
782
+ },
783
+ this.ctx
784
+ );
785
+ }
786
+ /**
787
+ * Get all methods marked as callable on this Agent
788
+ * @returns A map of method names to their metadata
789
+ */
790
+ _isCallable(method) {
791
+ return callableMetadata.has(this[method]);
792
+ }
793
+ /**
794
+ * Connect to a new MCP Server
795
+ *
796
+ * @param url MCP Server SSE URL
797
+ * @param callbackHost Base host for the agent, used for the redirect URI.
798
+ * @param agentsPrefix agents routing prefix if not using `agents`
799
+ * @param options MCP client and transport (header) options
800
+ * @returns authUrl
801
+ */
802
+ async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
803
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
804
+ const result = await this._connectToMcpServerInternal(
805
+ serverName,
806
+ url,
807
+ callbackUrl,
808
+ options
809
+ );
810
+ this.sql`
811
+ INSERT
812
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
813
+ VALUES (
814
+ ${result.id},
815
+ ${serverName},
816
+ ${url},
817
+ ${result.clientId ?? null},
818
+ ${result.authUrl ?? null},
819
+ ${callbackUrl},
820
+ ${options ? JSON.stringify(options) : null}
821
+ );
822
+ `;
823
+ this.broadcast(
824
+ JSON.stringify({
825
+ mcp: this.getMcpServers(),
826
+ type: "cf_agent_mcp_servers"
827
+ })
828
+ );
829
+ return result;
830
+ }
831
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
832
+ const authProvider = new DurableObjectOAuthClientProvider(
833
+ this.ctx.storage,
834
+ this.name,
835
+ callbackUrl
836
+ );
837
+ if (reconnect) {
838
+ authProvider.serverId = reconnect.id;
839
+ if (reconnect.oauthClientId) {
840
+ authProvider.clientId = reconnect.oauthClientId;
841
+ }
842
+ }
843
+ let headerTransportOpts = {};
844
+ if (options?.transport?.headers) {
845
+ headerTransportOpts = {
846
+ eventSourceInit: {
847
+ fetch: (url2, init) => fetch(url2, {
848
+ ...init,
849
+ headers: options?.transport?.headers
850
+ })
851
+ },
852
+ requestInit: {
853
+ headers: options?.transport?.headers
854
+ }
855
+ };
856
+ }
857
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
858
+ client: options?.client,
859
+ reconnect,
860
+ transport: {
861
+ ...headerTransportOpts,
862
+ authProvider
863
+ }
864
+ });
865
+ return {
866
+ authUrl,
867
+ clientId,
868
+ id
869
+ };
870
+ }
871
+ async removeMcpServer(id) {
872
+ this.mcp.closeConnection(id);
873
+ this.sql`
874
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
875
+ `;
876
+ this.broadcast(
877
+ JSON.stringify({
878
+ mcp: this.getMcpServers(),
879
+ type: "cf_agent_mcp_servers"
880
+ })
881
+ );
882
+ }
883
+ getMcpServers() {
884
+ const mcpState = {
885
+ prompts: this.mcp.listPrompts(),
886
+ resources: this.mcp.listResources(),
887
+ servers: {},
888
+ tools: this.mcp.listTools()
889
+ };
890
+ const servers = this.sql`
891
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
892
+ `;
893
+ if (servers && Array.isArray(servers) && servers.length > 0) {
894
+ for (const server of servers) {
895
+ const serverConn = this.mcp.mcpConnections[server.id];
896
+ mcpState.servers[server.id] = {
897
+ auth_url: server.auth_url,
898
+ capabilities: serverConn?.serverCapabilities ?? null,
899
+ instructions: serverConn?.instructions ?? null,
900
+ name: server.name,
901
+ server_url: server.server_url,
902
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
903
+ state: serverConn?.connectionState ?? "authenticating"
904
+ };
905
+ }
906
+ }
907
+ return mcpState;
908
+ }
909
+ };
910
+ /**
911
+ * Agent configuration options
912
+ */
913
+ _Agent.options = {
914
+ /** Whether the Agent should hibernate when inactive */
915
+ hibernate: true
916
+ // default to hibernate
917
+ };
918
+ var Agent = _Agent;
919
+ async function routeAgentRequest(request, env, options) {
920
+ const corsHeaders = options?.cors === true ? {
921
+ "Access-Control-Allow-Credentials": "true",
922
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
923
+ "Access-Control-Allow-Origin": "*",
924
+ "Access-Control-Max-Age": "86400"
925
+ } : options?.cors;
926
+ if (request.method === "OPTIONS") {
927
+ if (corsHeaders) {
928
+ return new Response(null, {
929
+ headers: corsHeaders
930
+ });
931
+ }
932
+ console.warn(
933
+ "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
934
+ );
935
+ }
936
+ let response = await routePartykitRequest(
937
+ request,
938
+ env,
939
+ {
940
+ prefix: "agents",
941
+ ...options
942
+ }
943
+ );
944
+ if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
945
+ response = new Response(response.body, {
946
+ headers: {
947
+ ...response.headers,
948
+ ...corsHeaders
949
+ }
950
+ });
951
+ }
952
+ return response;
953
+ }
954
+ function createHeaderBasedEmailResolver() {
955
+ return async (email, _env) => {
956
+ const messageId = email.headers.get("message-id");
957
+ if (messageId) {
958
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
959
+ if (messageIdMatch) {
960
+ const [, agentId2, domain] = messageIdMatch;
961
+ const agentName2 = domain.split(".")[0];
962
+ return { agentName: agentName2, agentId: agentId2 };
963
+ }
964
+ }
965
+ const references = email.headers.get("references");
966
+ if (references) {
967
+ const referencesMatch = references.match(
968
+ /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
969
+ );
970
+ if (referencesMatch) {
971
+ const [, base64Id, domain] = referencesMatch;
972
+ const agentId2 = Buffer.from(base64Id, "base64").toString("hex");
973
+ const agentName2 = domain.split(".")[0];
974
+ return { agentName: agentName2, agentId: agentId2 };
975
+ }
976
+ }
977
+ const agentName = email.headers.get("x-agent-name");
978
+ const agentId = email.headers.get("x-agent-id");
979
+ if (agentName && agentId) {
980
+ return { agentName, agentId };
981
+ }
982
+ return null;
983
+ };
984
+ }
985
+ function createAddressBasedEmailResolver(defaultAgentName) {
986
+ return async (email, _env) => {
987
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
988
+ if (!emailMatch) {
989
+ return null;
990
+ }
991
+ const [, localPart, subAddress] = emailMatch;
992
+ if (subAddress) {
993
+ return {
994
+ agentName: localPart,
995
+ agentId: subAddress
996
+ };
997
+ }
998
+ return {
999
+ agentName: defaultAgentName,
1000
+ agentId: localPart
1001
+ };
1002
+ };
1003
+ }
1004
+ function createCatchAllEmailResolver(agentName, agentId) {
1005
+ return async () => ({ agentName, agentId });
1006
+ }
1007
+ async function routeAgentEmail(email, env, options) {
1008
+ const routingInfo = await options.resolver(email, env);
1009
+ if (!routingInfo) {
1010
+ console.warn("No routing information found for email, dropping message");
1011
+ return;
1012
+ }
1013
+ const namespaceBinding = env[routingInfo.agentName];
1014
+ if (!namespaceBinding) {
1015
+ throw new Error(
1016
+ `Agent namespace '${routingInfo.agentName}' not found in environment`
1017
+ );
1018
+ }
1019
+ if (typeof namespaceBinding !== "object" || !("idFromName" in namespaceBinding) || typeof namespaceBinding.idFromName !== "function") {
1020
+ throw new Error(
1021
+ `Environment binding '${routingInfo.agentName}' is not an AgentNamespace (found: ${typeof namespaceBinding})`
1022
+ );
1023
+ }
1024
+ const namespace = namespaceBinding;
1025
+ const agent = await getAgentByName(namespace, routingInfo.agentId);
1026
+ const serialisableEmail = {
1027
+ getRaw: async () => {
1028
+ const reader = email.raw.getReader();
1029
+ const chunks = [];
1030
+ let done = false;
1031
+ while (!done) {
1032
+ const { value, done: readerDone } = await reader.read();
1033
+ done = readerDone;
1034
+ if (value) {
1035
+ chunks.push(value);
1036
+ }
1037
+ }
1038
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1039
+ const combined = new Uint8Array(totalLength);
1040
+ let offset = 0;
1041
+ for (const chunk of chunks) {
1042
+ combined.set(chunk, offset);
1043
+ offset += chunk.length;
1044
+ }
1045
+ return combined;
1046
+ },
1047
+ headers: email.headers,
1048
+ rawSize: email.rawSize,
1049
+ setReject: (reason) => {
1050
+ email.setReject(reason);
1051
+ },
1052
+ forward: (rcptTo, headers) => {
1053
+ return email.forward(rcptTo, headers);
1054
+ },
1055
+ reply: (options2) => {
1056
+ return email.reply(
1057
+ new EmailMessage(options2.from, options2.to, options2.raw)
1058
+ );
1059
+ },
1060
+ from: email.from,
1061
+ to: email.to
1062
+ };
1063
+ await agent._onEmail(serialisableEmail);
1064
+ }
1065
+ async function getAgentByName(namespace, name, options) {
1066
+ return getServerByName(namespace, name, options);
1067
+ }
1068
+ var StreamingResponse = class {
1069
+ constructor(connection, id) {
1070
+ this._closed = false;
1071
+ this._connection = connection;
1072
+ this._id = id;
1073
+ }
1074
+ /**
1075
+ * Send a chunk of data to the client
1076
+ * @param chunk The data to send
1077
+ */
1078
+ send(chunk) {
1079
+ if (this._closed) {
1080
+ throw new Error("StreamingResponse is already closed");
1081
+ }
1082
+ const response = {
1083
+ done: false,
1084
+ id: this._id,
1085
+ result: chunk,
1086
+ success: true,
1087
+ type: "rpc"
1088
+ };
1089
+ this._connection.send(JSON.stringify(response));
1090
+ }
1091
+ /**
1092
+ * End the stream and send the final chunk (if any)
1093
+ * @param finalChunk Optional final chunk of data to send
1094
+ */
1095
+ end(finalChunk) {
1096
+ if (this._closed) {
1097
+ throw new Error("StreamingResponse is already closed");
1098
+ }
1099
+ this._closed = true;
1100
+ const response = {
1101
+ done: true,
1102
+ id: this._id,
1103
+ result: finalChunk,
1104
+ success: true,
1105
+ type: "rpc"
1106
+ };
1107
+ this._connection.send(JSON.stringify(response));
1108
+ }
1109
+ };
1110
+
1111
+ // src/observability/index.ts
1112
+ var genericObservability = {
1113
+ emit(event) {
1114
+ if (isLocalMode()) {
1115
+ console.log(event.displayMessage);
1116
+ return;
1117
+ }
1118
+ console.log(event);
1119
+ }
1120
+ };
1121
+ var localMode = false;
1122
+ function isLocalMode() {
1123
+ if (localMode) {
1124
+ return true;
1125
+ }
1126
+ const { request } = getCurrentAgent();
1127
+ if (!request) {
1128
+ return false;
1129
+ }
1130
+ const url = new URL(request.url);
1131
+ localMode = url.hostname === "localhost";
1132
+ return localMode;
1133
+ }
1134
+
1135
+ export {
1136
+ genericObservability,
1137
+ unstable_callable,
1138
+ getCurrentAgent,
1139
+ Agent,
1140
+ routeAgentRequest,
1141
+ createHeaderBasedEmailResolver,
1142
+ createAddressBasedEmailResolver,
1143
+ createCatchAllEmailResolver,
1144
+ routeAgentEmail,
1145
+ getAgentByName,
1146
+ StreamingResponse
1147
+ };
1148
+ //# sourceMappingURL=chunk-EDUDXISR.js.map