agents 0.0.0-9688c15 → 0.0.0-96add46

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