agents 0.0.0-db5b372 → 0.0.0-dc7a99c

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 (46) hide show
  1. package/dist/ai-chat-agent.d.ts +32 -6
  2. package/dist/ai-chat-agent.js +149 -115
  3. package/dist/ai-chat-agent.js.map +1 -1
  4. package/dist/ai-react.d.ts +17 -4
  5. package/dist/ai-react.js +29 -29
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/chunk-767EASBA.js +106 -0
  8. package/dist/chunk-767EASBA.js.map +1 -0
  9. package/dist/{chunk-YZNSS675.js → chunk-E3LCYPCB.js} +71 -37
  10. package/dist/chunk-E3LCYPCB.js.map +1 -0
  11. package/dist/chunk-JFRK72K3.js +910 -0
  12. package/dist/chunk-JFRK72K3.js.map +1 -0
  13. package/dist/chunk-NKZZ66QY.js +116 -0
  14. package/dist/chunk-NKZZ66QY.js.map +1 -0
  15. package/dist/client.d.ts +15 -1
  16. package/dist/client.js +6 -126
  17. package/dist/client.js.map +1 -1
  18. package/dist/index-CITGJflw.d.ts +486 -0
  19. package/dist/index.d.ts +25 -307
  20. package/dist/index.js +8 -7
  21. package/dist/mcp/client.d.ts +310 -23
  22. package/dist/mcp/client.js +1 -2
  23. package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
  24. package/dist/mcp/do-oauth-client-provider.js +3 -103
  25. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  26. package/dist/mcp/index.d.ts +22 -11
  27. package/dist/mcp/index.js +172 -175
  28. package/dist/mcp/index.js.map +1 -1
  29. package/dist/observability/index.d.ts +12 -0
  30. package/dist/observability/index.js +10 -0
  31. package/dist/react.d.ts +85 -5
  32. package/dist/react.js +20 -8
  33. package/dist/react.js.map +1 -1
  34. package/dist/schedule.d.ts +6 -6
  35. package/dist/schedule.js +4 -6
  36. package/dist/schedule.js.map +1 -1
  37. package/dist/serializable.d.ts +32 -0
  38. package/dist/serializable.js +1 -0
  39. package/dist/serializable.js.map +1 -0
  40. package/package.json +75 -68
  41. package/src/index.ts +538 -91
  42. package/dist/chunk-AV3OMRR4.js +0 -597
  43. package/dist/chunk-AV3OMRR4.js.map +0 -1
  44. package/dist/chunk-HMLY7DHA.js +0 -16
  45. package/dist/chunk-YZNSS675.js.map +0 -1
  46. /package/dist/{chunk-HMLY7DHA.js.map → observability/index.js.map} +0 -0
@@ -0,0 +1,910 @@
1
+ import {
2
+ MCPClientManager
3
+ } from "./chunk-E3LCYPCB.js";
4
+ import {
5
+ DurableObjectOAuthClientProvider
6
+ } from "./chunk-767EASBA.js";
7
+ import {
8
+ camelCaseToKebabCase
9
+ } from "./chunk-NKZZ66QY.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 {
16
+ getServerByName,
17
+ routePartykitRequest,
18
+ Server
19
+ } from "partyserver";
20
+ function isRPCRequest(msg) {
21
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "rpc" && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
22
+ }
23
+ function isStateUpdateMessage(msg) {
24
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "cf_agent_state" && "state" in msg;
25
+ }
26
+ var callableMetadata = /* @__PURE__ */ new Map();
27
+ function unstable_callable(metadata = {}) {
28
+ return function callableDecorator(target, context) {
29
+ if (!callableMetadata.has(target)) {
30
+ callableMetadata.set(target, metadata);
31
+ }
32
+ return target;
33
+ };
34
+ }
35
+ function getNextCronTime(cron) {
36
+ const interval = parseCronExpression(cron);
37
+ return interval.getNextDate();
38
+ }
39
+ var STATE_ROW_ID = "cf_state_row_id";
40
+ var STATE_WAS_CHANGED = "cf_state_was_changed";
41
+ var DEFAULT_STATE = {};
42
+ var agentContext = new AsyncLocalStorage();
43
+ function getCurrentAgent() {
44
+ const store = agentContext.getStore();
45
+ if (!store) {
46
+ return {
47
+ agent: void 0,
48
+ connection: void 0,
49
+ request: void 0
50
+ };
51
+ }
52
+ return store;
53
+ }
54
+ var Agent = class extends Server {
55
+ constructor(ctx, env) {
56
+ super(ctx, env);
57
+ this._state = DEFAULT_STATE;
58
+ this._ParentClass = Object.getPrototypeOf(this).constructor;
59
+ this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
60
+ /**
61
+ * Initial state for the Agent
62
+ * Override to provide default state values
63
+ */
64
+ this.initialState = DEFAULT_STATE;
65
+ /**
66
+ * The observability implementation to use for the Agent
67
+ */
68
+ this.observability = genericObservability;
69
+ /**
70
+ * Method called when an alarm fires.
71
+ * Executes any scheduled tasks that are due.
72
+ *
73
+ * @remarks
74
+ * To schedule a task, please use the `this.schedule` method instead.
75
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
76
+ */
77
+ this.alarm = async () => {
78
+ const now = Math.floor(Date.now() / 1e3);
79
+ const result = this.sql`
80
+ SELECT * FROM cf_agents_schedules WHERE time <= ${now}
81
+ `;
82
+ for (const row of result || []) {
83
+ const callback = this[row.callback];
84
+ if (!callback) {
85
+ console.error(`callback ${row.callback} not found`);
86
+ continue;
87
+ }
88
+ await agentContext.run(
89
+ { agent: this, connection: void 0, request: void 0 },
90
+ async () => {
91
+ try {
92
+ this.observability?.emit(
93
+ {
94
+ displayMessage: `Schedule ${row.id} executed`,
95
+ id: nanoid(),
96
+ payload: row,
97
+ timestamp: Date.now(),
98
+ type: "schedule:execute"
99
+ },
100
+ this.ctx
101
+ );
102
+ await callback.bind(this)(JSON.parse(row.payload), row);
103
+ } catch (e) {
104
+ console.error(`error executing callback "${row.callback}"`, e);
105
+ }
106
+ }
107
+ );
108
+ if (row.type === "cron") {
109
+ const nextExecutionTime = getNextCronTime(row.cron);
110
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
111
+ this.sql`
112
+ UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
113
+ `;
114
+ } else {
115
+ this.sql`
116
+ DELETE FROM cf_agents_schedules WHERE id = ${row.id}
117
+ `;
118
+ }
119
+ }
120
+ await this._scheduleNextAlarm();
121
+ };
122
+ this.sql`
123
+ CREATE TABLE IF NOT EXISTS cf_agents_state (
124
+ id TEXT PRIMARY KEY NOT NULL,
125
+ state TEXT
126
+ )
127
+ `;
128
+ void this.ctx.blockConcurrencyWhile(async () => {
129
+ return this._tryCatch(async () => {
130
+ this.sql`
131
+ CREATE TABLE IF NOT EXISTS cf_agents_schedules (
132
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
133
+ callback TEXT,
134
+ payload TEXT,
135
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
136
+ time INTEGER,
137
+ delayInSeconds INTEGER,
138
+ cron TEXT,
139
+ created_at INTEGER DEFAULT (unixepoch())
140
+ )
141
+ `;
142
+ await this.alarm();
143
+ });
144
+ });
145
+ this.sql`
146
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
147
+ id TEXT PRIMARY KEY NOT NULL,
148
+ name TEXT NOT NULL,
149
+ server_url TEXT NOT NULL,
150
+ callback_url TEXT NOT NULL,
151
+ client_id TEXT,
152
+ auth_url TEXT,
153
+ server_options TEXT
154
+ )
155
+ `;
156
+ const _onRequest = this.onRequest.bind(this);
157
+ this.onRequest = (request) => {
158
+ return agentContext.run(
159
+ { agent: this, connection: void 0, request },
160
+ async () => {
161
+ if (this.mcp.isCallbackRequest(request)) {
162
+ await this.mcp.handleCallbackRequest(request);
163
+ this.broadcast(
164
+ JSON.stringify({
165
+ mcp: this.getMcpServers(),
166
+ type: "cf_agent_mcp_servers"
167
+ })
168
+ );
169
+ return new Response("<script>window.close();</script>", {
170
+ headers: { "content-type": "text/html" },
171
+ status: 200
172
+ });
173
+ }
174
+ return this._tryCatch(() => _onRequest(request));
175
+ }
176
+ );
177
+ };
178
+ const _onMessage = this.onMessage.bind(this);
179
+ this.onMessage = async (connection, message) => {
180
+ return agentContext.run(
181
+ { agent: this, connection, request: void 0 },
182
+ async () => {
183
+ if (typeof message !== "string") {
184
+ return this._tryCatch(() => _onMessage(connection, message));
185
+ }
186
+ let parsed;
187
+ try {
188
+ parsed = JSON.parse(message);
189
+ } catch (_e) {
190
+ return this._tryCatch(() => _onMessage(connection, message));
191
+ }
192
+ if (isStateUpdateMessage(parsed)) {
193
+ this._setStateInternal(parsed.state, connection);
194
+ return;
195
+ }
196
+ if (isRPCRequest(parsed)) {
197
+ try {
198
+ const { id, method, args } = parsed;
199
+ const methodFn = this[method];
200
+ if (typeof methodFn !== "function") {
201
+ throw new Error(`Method ${method} does not exist`);
202
+ }
203
+ if (!this._isCallable(method)) {
204
+ throw new Error(`Method ${method} is not callable`);
205
+ }
206
+ const metadata = callableMetadata.get(methodFn);
207
+ if (metadata?.streaming) {
208
+ const stream = new StreamingResponse(connection, id);
209
+ await methodFn.apply(this, [stream, ...args]);
210
+ return;
211
+ }
212
+ const result = await methodFn.apply(this, args);
213
+ this.observability?.emit(
214
+ {
215
+ displayMessage: `RPC call to ${method}`,
216
+ id: nanoid(),
217
+ payload: {
218
+ args,
219
+ method,
220
+ streaming: metadata?.streaming,
221
+ success: true
222
+ },
223
+ timestamp: Date.now(),
224
+ type: "rpc"
225
+ },
226
+ this.ctx
227
+ );
228
+ const response = {
229
+ done: true,
230
+ id,
231
+ result,
232
+ success: true,
233
+ type: "rpc"
234
+ };
235
+ connection.send(JSON.stringify(response));
236
+ } catch (e) {
237
+ const response = {
238
+ error: e instanceof Error ? e.message : "Unknown error occurred",
239
+ id: parsed.id,
240
+ success: false,
241
+ type: "rpc"
242
+ };
243
+ connection.send(JSON.stringify(response));
244
+ console.error("RPC error:", e);
245
+ }
246
+ return;
247
+ }
248
+ return this._tryCatch(() => _onMessage(connection, message));
249
+ }
250
+ );
251
+ };
252
+ const _onConnect = this.onConnect.bind(this);
253
+ this.onConnect = (connection, ctx2) => {
254
+ return agentContext.run(
255
+ { agent: this, connection, request: ctx2.request },
256
+ async () => {
257
+ setTimeout(() => {
258
+ if (this.state) {
259
+ connection.send(
260
+ JSON.stringify({
261
+ state: this.state,
262
+ type: "cf_agent_state"
263
+ })
264
+ );
265
+ }
266
+ connection.send(
267
+ JSON.stringify({
268
+ mcp: this.getMcpServers(),
269
+ type: "cf_agent_mcp_servers"
270
+ })
271
+ );
272
+ this.observability?.emit(
273
+ {
274
+ displayMessage: "Connection established",
275
+ id: nanoid(),
276
+ payload: {
277
+ connectionId: connection.id
278
+ },
279
+ timestamp: Date.now(),
280
+ type: "connect"
281
+ },
282
+ this.ctx
283
+ );
284
+ return this._tryCatch(() => _onConnect(connection, ctx2));
285
+ }, 20);
286
+ }
287
+ );
288
+ };
289
+ const _onStart = this.onStart.bind(this);
290
+ this.onStart = async () => {
291
+ return agentContext.run(
292
+ { agent: this, connection: void 0, request: void 0 },
293
+ async () => {
294
+ const servers = this.sql`
295
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
296
+ `;
297
+ Promise.allSettled(
298
+ servers.map((server) => {
299
+ return this._connectToMcpServerInternal(
300
+ server.name,
301
+ server.server_url,
302
+ server.callback_url,
303
+ server.server_options ? JSON.parse(server.server_options) : void 0,
304
+ {
305
+ id: server.id,
306
+ oauthClientId: server.client_id ?? void 0
307
+ }
308
+ );
309
+ })
310
+ ).then((_results) => {
311
+ this.broadcast(
312
+ JSON.stringify({
313
+ mcp: this.getMcpServers(),
314
+ type: "cf_agent_mcp_servers"
315
+ })
316
+ );
317
+ });
318
+ await this._tryCatch(() => _onStart());
319
+ }
320
+ );
321
+ };
322
+ }
323
+ /**
324
+ * Current state of the Agent
325
+ */
326
+ get state() {
327
+ if (this._state !== DEFAULT_STATE) {
328
+ return this._state;
329
+ }
330
+ const wasChanged = this.sql`
331
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
332
+ `;
333
+ const result = this.sql`
334
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
335
+ `;
336
+ if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
337
+ result[0]?.state) {
338
+ const state = result[0]?.state;
339
+ this._state = JSON.parse(state);
340
+ return this._state;
341
+ }
342
+ if (this.initialState === DEFAULT_STATE) {
343
+ return void 0;
344
+ }
345
+ this.setState(this.initialState);
346
+ return this.initialState;
347
+ }
348
+ /**
349
+ * Execute SQL queries against the Agent's database
350
+ * @template T Type of the returned rows
351
+ * @param strings SQL query template strings
352
+ * @param values Values to be inserted into the query
353
+ * @returns Array of query results
354
+ */
355
+ sql(strings, ...values) {
356
+ let query = "";
357
+ try {
358
+ query = strings.reduce(
359
+ (acc, str, i) => acc + str + (i < values.length ? "?" : ""),
360
+ ""
361
+ );
362
+ return [...this.ctx.storage.sql.exec(query, ...values)];
363
+ } catch (e) {
364
+ console.error(`failed to execute sql query: ${query}`, e);
365
+ throw this.onError(e);
366
+ }
367
+ }
368
+ _setStateInternal(state, source = "server") {
369
+ const previousState = this._state;
370
+ this._state = state;
371
+ this.sql`
372
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
373
+ VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
374
+ `;
375
+ this.sql`
376
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
377
+ VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
378
+ `;
379
+ this.broadcast(
380
+ JSON.stringify({
381
+ state,
382
+ type: "cf_agent_state"
383
+ }),
384
+ source !== "server" ? [source.id] : []
385
+ );
386
+ return this._tryCatch(() => {
387
+ const { connection, request } = agentContext.getStore() || {};
388
+ return agentContext.run(
389
+ { agent: this, connection, request },
390
+ async () => {
391
+ this.observability?.emit(
392
+ {
393
+ displayMessage: "State updated",
394
+ id: nanoid(),
395
+ payload: {
396
+ previousState,
397
+ state
398
+ },
399
+ timestamp: Date.now(),
400
+ type: "state:update"
401
+ },
402
+ this.ctx
403
+ );
404
+ return this.onStateUpdate(state, source);
405
+ }
406
+ );
407
+ });
408
+ }
409
+ /**
410
+ * Update the Agent's state
411
+ * @param state New state to set
412
+ */
413
+ setState(state) {
414
+ this._setStateInternal(state, "server");
415
+ }
416
+ /**
417
+ * Called when the Agent's state is updated
418
+ * @param state Updated state
419
+ * @param source Source of the state update ("server" or a client connection)
420
+ */
421
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
422
+ onStateUpdate(state, source) {
423
+ }
424
+ /**
425
+ * Called when the Agent receives an email
426
+ * @param email Email message to process
427
+ */
428
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
429
+ onEmail(email) {
430
+ return agentContext.run(
431
+ { agent: this, connection: void 0, request: void 0 },
432
+ async () => {
433
+ console.error("onEmail not implemented");
434
+ }
435
+ );
436
+ }
437
+ async _tryCatch(fn) {
438
+ try {
439
+ return await fn();
440
+ } catch (e) {
441
+ throw this.onError(e);
442
+ }
443
+ }
444
+ onError(connectionOrError, error) {
445
+ let theError;
446
+ if (connectionOrError && error) {
447
+ theError = error;
448
+ console.error(
449
+ "Error on websocket connection:",
450
+ connectionOrError.id,
451
+ theError
452
+ );
453
+ console.error(
454
+ "Override onError(connection, error) to handle websocket connection errors"
455
+ );
456
+ } else {
457
+ theError = connectionOrError;
458
+ console.error("Error on server:", theError);
459
+ console.error("Override onError(error) to handle server errors");
460
+ }
461
+ throw theError;
462
+ }
463
+ /**
464
+ * Render content (not implemented in base class)
465
+ */
466
+ render() {
467
+ throw new Error("Not implemented");
468
+ }
469
+ /**
470
+ * Schedule a task to be executed in the future
471
+ * @template T Type of the payload data
472
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
473
+ * @param callback Name of the method to call
474
+ * @param payload Data to pass to the callback
475
+ * @returns Schedule object representing the scheduled task
476
+ */
477
+ async schedule(when, callback, payload) {
478
+ const id = nanoid(9);
479
+ const emitScheduleCreate = (schedule) => this.observability?.emit(
480
+ {
481
+ displayMessage: `Schedule ${schedule.id} created`,
482
+ id: nanoid(),
483
+ payload: schedule,
484
+ timestamp: Date.now(),
485
+ type: "schedule:create"
486
+ },
487
+ this.ctx
488
+ );
489
+ if (typeof callback !== "string") {
490
+ throw new Error("Callback must be a string");
491
+ }
492
+ if (typeof this[callback] !== "function") {
493
+ throw new Error(`this.${callback} is not a function`);
494
+ }
495
+ if (when instanceof Date) {
496
+ const timestamp = Math.floor(when.getTime() / 1e3);
497
+ this.sql`
498
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
499
+ VALUES (${id}, ${callback}, ${JSON.stringify(
500
+ payload
501
+ )}, 'scheduled', ${timestamp})
502
+ `;
503
+ await this._scheduleNextAlarm();
504
+ const schedule = {
505
+ callback,
506
+ id,
507
+ payload,
508
+ time: timestamp,
509
+ type: "scheduled"
510
+ };
511
+ emitScheduleCreate(schedule);
512
+ return schedule;
513
+ }
514
+ if (typeof when === "number") {
515
+ const time = new Date(Date.now() + when * 1e3);
516
+ const timestamp = Math.floor(time.getTime() / 1e3);
517
+ this.sql`
518
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
519
+ VALUES (${id}, ${callback}, ${JSON.stringify(
520
+ payload
521
+ )}, 'delayed', ${when}, ${timestamp})
522
+ `;
523
+ await this._scheduleNextAlarm();
524
+ const schedule = {
525
+ callback,
526
+ delayInSeconds: when,
527
+ id,
528
+ payload,
529
+ time: timestamp,
530
+ type: "delayed"
531
+ };
532
+ emitScheduleCreate(schedule);
533
+ return schedule;
534
+ }
535
+ if (typeof when === "string") {
536
+ const nextExecutionTime = getNextCronTime(when);
537
+ const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
538
+ this.sql`
539
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
540
+ VALUES (${id}, ${callback}, ${JSON.stringify(
541
+ payload
542
+ )}, 'cron', ${when}, ${timestamp})
543
+ `;
544
+ await this._scheduleNextAlarm();
545
+ const schedule = {
546
+ callback,
547
+ cron: when,
548
+ id,
549
+ payload,
550
+ time: timestamp,
551
+ type: "cron"
552
+ };
553
+ emitScheduleCreate(schedule);
554
+ return schedule;
555
+ }
556
+ throw new Error("Invalid schedule type");
557
+ }
558
+ /**
559
+ * Get a scheduled task by ID
560
+ * @template T Type of the payload data
561
+ * @param id ID of the scheduled task
562
+ * @returns The Schedule object or undefined if not found
563
+ */
564
+ async getSchedule(id) {
565
+ const result = this.sql`
566
+ SELECT * FROM cf_agents_schedules WHERE id = ${id}
567
+ `;
568
+ if (!result) {
569
+ console.error(`schedule ${id} not found`);
570
+ return void 0;
571
+ }
572
+ return { ...result[0], payload: JSON.parse(result[0].payload) };
573
+ }
574
+ /**
575
+ * Get scheduled tasks matching the given criteria
576
+ * @template T Type of the payload data
577
+ * @param criteria Criteria to filter schedules
578
+ * @returns Array of matching Schedule objects
579
+ */
580
+ getSchedules(criteria = {}) {
581
+ let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
582
+ const params = [];
583
+ if (criteria.id) {
584
+ query += " AND id = ?";
585
+ params.push(criteria.id);
586
+ }
587
+ if (criteria.type) {
588
+ query += " AND type = ?";
589
+ params.push(criteria.type);
590
+ }
591
+ if (criteria.timeRange) {
592
+ query += " AND time >= ? AND time <= ?";
593
+ const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
594
+ const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
595
+ params.push(
596
+ Math.floor(start.getTime() / 1e3),
597
+ Math.floor(end.getTime() / 1e3)
598
+ );
599
+ }
600
+ const result = this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
601
+ ...row,
602
+ payload: JSON.parse(row.payload)
603
+ }));
604
+ return result;
605
+ }
606
+ /**
607
+ * Cancel a scheduled task
608
+ * @param id ID of the task to cancel
609
+ * @returns true if the task was cancelled, false otherwise
610
+ */
611
+ async cancelSchedule(id) {
612
+ const schedule = await this.getSchedule(id);
613
+ if (schedule) {
614
+ this.observability?.emit(
615
+ {
616
+ displayMessage: `Schedule ${id} cancelled`,
617
+ id: nanoid(),
618
+ payload: schedule,
619
+ timestamp: Date.now(),
620
+ type: "schedule:cancel"
621
+ },
622
+ this.ctx
623
+ );
624
+ }
625
+ this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
626
+ await this._scheduleNextAlarm();
627
+ return true;
628
+ }
629
+ async _scheduleNextAlarm() {
630
+ const result = this.sql`
631
+ SELECT time FROM cf_agents_schedules
632
+ WHERE time > ${Math.floor(Date.now() / 1e3)}
633
+ ORDER BY time ASC
634
+ LIMIT 1
635
+ `;
636
+ if (!result) return;
637
+ if (result.length > 0 && "time" in result[0]) {
638
+ const nextTime = result[0].time * 1e3;
639
+ await this.ctx.storage.setAlarm(nextTime);
640
+ }
641
+ }
642
+ /**
643
+ * Destroy the Agent, removing all state and scheduled tasks
644
+ */
645
+ async destroy() {
646
+ this.sql`DROP TABLE IF EXISTS cf_agents_state`;
647
+ this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
648
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
649
+ await this.ctx.storage.deleteAlarm();
650
+ await this.ctx.storage.deleteAll();
651
+ this.ctx.abort("destroyed");
652
+ this.observability?.emit(
653
+ {
654
+ displayMessage: "Agent destroyed",
655
+ id: nanoid(),
656
+ payload: {},
657
+ timestamp: Date.now(),
658
+ type: "destroy"
659
+ },
660
+ this.ctx
661
+ );
662
+ }
663
+ /**
664
+ * Get all methods marked as callable on this Agent
665
+ * @returns A map of method names to their metadata
666
+ */
667
+ _isCallable(method) {
668
+ return callableMetadata.has(this[method]);
669
+ }
670
+ /**
671
+ * Connect to a new MCP Server
672
+ *
673
+ * @param url MCP Server SSE URL
674
+ * @param callbackHost Base host for the agent, used for the redirect URI.
675
+ * @param agentsPrefix agents routing prefix if not using `agents`
676
+ * @param options MCP client and transport (header) options
677
+ * @returns authUrl
678
+ */
679
+ async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
680
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
681
+ const result = await this._connectToMcpServerInternal(
682
+ serverName,
683
+ url,
684
+ callbackUrl,
685
+ options
686
+ );
687
+ this.sql`
688
+ INSERT
689
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
690
+ VALUES (
691
+ ${result.id},
692
+ ${serverName},
693
+ ${url},
694
+ ${result.clientId ?? null},
695
+ ${result.authUrl ?? null},
696
+ ${callbackUrl},
697
+ ${options ? JSON.stringify(options) : null}
698
+ );
699
+ `;
700
+ this.broadcast(
701
+ JSON.stringify({
702
+ mcp: this.getMcpServers(),
703
+ type: "cf_agent_mcp_servers"
704
+ })
705
+ );
706
+ return result;
707
+ }
708
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
709
+ const authProvider = new DurableObjectOAuthClientProvider(
710
+ this.ctx.storage,
711
+ this.name,
712
+ callbackUrl
713
+ );
714
+ if (reconnect) {
715
+ authProvider.serverId = reconnect.id;
716
+ if (reconnect.oauthClientId) {
717
+ authProvider.clientId = reconnect.oauthClientId;
718
+ }
719
+ }
720
+ let headerTransportOpts = {};
721
+ if (options?.transport?.headers) {
722
+ headerTransportOpts = {
723
+ eventSourceInit: {
724
+ fetch: (url2, init) => fetch(url2, {
725
+ ...init,
726
+ headers: options?.transport?.headers
727
+ })
728
+ },
729
+ requestInit: {
730
+ headers: options?.transport?.headers
731
+ }
732
+ };
733
+ }
734
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
735
+ client: options?.client,
736
+ reconnect,
737
+ transport: {
738
+ ...headerTransportOpts,
739
+ authProvider
740
+ }
741
+ });
742
+ return {
743
+ authUrl,
744
+ clientId,
745
+ id
746
+ };
747
+ }
748
+ async removeMcpServer(id) {
749
+ this.mcp.closeConnection(id);
750
+ this.sql`
751
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
752
+ `;
753
+ this.broadcast(
754
+ JSON.stringify({
755
+ mcp: this.getMcpServers(),
756
+ type: "cf_agent_mcp_servers"
757
+ })
758
+ );
759
+ }
760
+ getMcpServers() {
761
+ const mcpState = {
762
+ prompts: this.mcp.listPrompts(),
763
+ resources: this.mcp.listResources(),
764
+ servers: {},
765
+ tools: this.mcp.listTools()
766
+ };
767
+ const servers = this.sql`
768
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
769
+ `;
770
+ for (const server of servers) {
771
+ const serverConn = this.mcp.mcpConnections[server.id];
772
+ mcpState.servers[server.id] = {
773
+ auth_url: server.auth_url,
774
+ capabilities: serverConn?.serverCapabilities ?? null,
775
+ instructions: serverConn?.instructions ?? null,
776
+ name: server.name,
777
+ server_url: server.server_url,
778
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
779
+ state: serverConn?.connectionState ?? "authenticating"
780
+ };
781
+ }
782
+ return mcpState;
783
+ }
784
+ };
785
+ /**
786
+ * Agent configuration options
787
+ */
788
+ Agent.options = {
789
+ /** Whether the Agent should hibernate when inactive */
790
+ hibernate: true
791
+ // default to hibernate
792
+ };
793
+ async function routeAgentRequest(request, env, options) {
794
+ const corsHeaders = options?.cors === true ? {
795
+ "Access-Control-Allow-Credentials": "true",
796
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
797
+ "Access-Control-Allow-Origin": "*",
798
+ "Access-Control-Max-Age": "86400"
799
+ } : options?.cors;
800
+ if (request.method === "OPTIONS") {
801
+ if (corsHeaders) {
802
+ return new Response(null, {
803
+ headers: corsHeaders
804
+ });
805
+ }
806
+ console.warn(
807
+ "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
808
+ );
809
+ }
810
+ let response = await routePartykitRequest(
811
+ request,
812
+ env,
813
+ {
814
+ prefix: "agents",
815
+ ...options
816
+ }
817
+ );
818
+ if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
819
+ response = new Response(response.body, {
820
+ headers: {
821
+ ...response.headers,
822
+ ...corsHeaders
823
+ }
824
+ });
825
+ }
826
+ return response;
827
+ }
828
+ async function routeAgentEmail(_email, _env, _options) {
829
+ }
830
+ async function getAgentByName(namespace, name, options) {
831
+ return getServerByName(namespace, name, options);
832
+ }
833
+ var StreamingResponse = class {
834
+ constructor(connection, id) {
835
+ this._closed = false;
836
+ this._connection = connection;
837
+ this._id = id;
838
+ }
839
+ /**
840
+ * Send a chunk of data to the client
841
+ * @param chunk The data to send
842
+ */
843
+ send(chunk) {
844
+ if (this._closed) {
845
+ throw new Error("StreamingResponse is already closed");
846
+ }
847
+ const response = {
848
+ done: false,
849
+ id: this._id,
850
+ result: chunk,
851
+ success: true,
852
+ type: "rpc"
853
+ };
854
+ this._connection.send(JSON.stringify(response));
855
+ }
856
+ /**
857
+ * End the stream and send the final chunk (if any)
858
+ * @param finalChunk Optional final chunk of data to send
859
+ */
860
+ end(finalChunk) {
861
+ if (this._closed) {
862
+ throw new Error("StreamingResponse is already closed");
863
+ }
864
+ this._closed = true;
865
+ const response = {
866
+ done: true,
867
+ id: this._id,
868
+ result: finalChunk,
869
+ success: true,
870
+ type: "rpc"
871
+ };
872
+ this._connection.send(JSON.stringify(response));
873
+ }
874
+ };
875
+
876
+ // src/observability/index.ts
877
+ var genericObservability = {
878
+ emit(event) {
879
+ if (isLocalMode()) {
880
+ console.log(event.displayMessage);
881
+ return;
882
+ }
883
+ console.log(event);
884
+ }
885
+ };
886
+ var localMode = false;
887
+ function isLocalMode() {
888
+ if (localMode) {
889
+ return true;
890
+ }
891
+ const { request } = getCurrentAgent();
892
+ if (!request) {
893
+ return false;
894
+ }
895
+ const url = new URL(request.url);
896
+ localMode = url.hostname === "localhost";
897
+ return localMode;
898
+ }
899
+
900
+ export {
901
+ genericObservability,
902
+ unstable_callable,
903
+ getCurrentAgent,
904
+ Agent,
905
+ routeAgentRequest,
906
+ routeAgentEmail,
907
+ getAgentByName,
908
+ StreamingResponse
909
+ };
910
+ //# sourceMappingURL=chunk-JFRK72K3.js.map