agents 0.0.0-94d9a2e → 0.0.0-9688c15

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.
@@ -1,12 +1,18 @@
1
1
  import {
2
2
  DurableObjectOAuthClientProvider
3
- } from "./chunk-BZXOAZUX.js";
3
+ } from "./chunk-D6UOOELW.js";
4
4
  import {
5
5
  camelCaseToKebabCase
6
- } from "./chunk-QSGN3REV.js";
6
+ } from "./chunk-RN4SNE73.js";
7
7
  import {
8
8
  MCPClientManager
9
- } from "./chunk-Y67CHZBI.js";
9
+ } from "./chunk-25YDMV4H.js";
10
+ import {
11
+ __privateAdd,
12
+ __privateGet,
13
+ __privateMethod,
14
+ __privateSet
15
+ } from "./chunk-HMLY7DHA.js";
10
16
 
11
17
  // src/index.ts
12
18
  import {
@@ -51,12 +57,14 @@ function getCurrentAgent() {
51
57
  }
52
58
  return store;
53
59
  }
60
+ var _state, _ParentClass, _Agent_instances, setStateInternal_fn, tryCatch_fn, scheduleNextAlarm_fn, isCallable_fn, connectToMcpServerInternal_fn, getMcpServerStateInternal_fn;
54
61
  var Agent = class extends Server {
55
62
  constructor(ctx, env) {
56
63
  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");
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");
60
68
  /**
61
69
  * Initial state for the Agent
62
70
  * Override to provide default state values
@@ -103,7 +111,7 @@ var Agent = class extends Server {
103
111
  `;
104
112
  }
105
113
  }
106
- await this._scheduleNextAlarm();
114
+ await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
107
115
  };
108
116
  this.sql`
109
117
  CREATE TABLE IF NOT EXISTS cf_agents_state (
@@ -112,7 +120,7 @@ var Agent = class extends Server {
112
120
  )
113
121
  `;
114
122
  void this.ctx.blockConcurrencyWhile(async () => {
115
- return this._tryCatch(async () => {
123
+ return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, async () => {
116
124
  this.sql`
117
125
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
118
126
  id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
@@ -149,7 +157,7 @@ var Agent = class extends Server {
149
157
  this.broadcast(
150
158
  JSON.stringify({
151
159
  type: "cf_agent_mcp_servers",
152
- mcp: this.getMcpServers()
160
+ mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
153
161
  })
154
162
  );
155
163
  return new Response("<script>window.close();</script>", {
@@ -157,7 +165,7 @@ var Agent = class extends Server {
157
165
  headers: { "content-type": "text/html" }
158
166
  });
159
167
  }
160
- return this._tryCatch(() => _onRequest(request));
168
+ return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onRequest(request));
161
169
  }
162
170
  );
163
171
  };
@@ -167,16 +175,16 @@ var Agent = class extends Server {
167
175
  { agent: this, connection, request: void 0 },
168
176
  async () => {
169
177
  if (typeof message !== "string") {
170
- return this._tryCatch(() => _onMessage(connection, message));
178
+ return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
171
179
  }
172
180
  let parsed;
173
181
  try {
174
182
  parsed = JSON.parse(message);
175
183
  } catch (e) {
176
- return this._tryCatch(() => _onMessage(connection, message));
184
+ return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
177
185
  }
178
186
  if (isStateUpdateMessage(parsed)) {
179
- this._setStateInternal(parsed.state, connection);
187
+ __privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, parsed.state, connection);
180
188
  return;
181
189
  }
182
190
  if (isRPCRequest(parsed)) {
@@ -186,7 +194,7 @@ var Agent = class extends Server {
186
194
  if (typeof methodFn !== "function") {
187
195
  throw new Error(`Method ${method} does not exist`);
188
196
  }
189
- if (!this._isCallable(method)) {
197
+ if (!__privateMethod(this, _Agent_instances, isCallable_fn).call(this, method)) {
190
198
  throw new Error(`Method ${method} is not callable`);
191
199
  }
192
200
  const metadata = callableMetadata.get(methodFn);
@@ -216,7 +224,7 @@ var Agent = class extends Server {
216
224
  }
217
225
  return;
218
226
  }
219
- return this._tryCatch(() => _onMessage(connection, message));
227
+ return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
220
228
  }
221
229
  );
222
230
  };
@@ -237,10 +245,10 @@ var Agent = class extends Server {
237
245
  connection.send(
238
246
  JSON.stringify({
239
247
  type: "cf_agent_mcp_servers",
240
- mcp: this.getMcpServers()
248
+ mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
241
249
  })
242
250
  );
243
- return this._tryCatch(() => _onConnect(connection, ctx2));
251
+ return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onConnect(connection, ctx2));
244
252
  }, 20);
245
253
  }
246
254
  );
@@ -255,25 +263,19 @@ var Agent = class extends Server {
255
263
  `;
256
264
  await Promise.allSettled(
257
265
  servers.map((server) => {
258
- return this._connectToMcpServerInternal(
259
- server.name,
260
- server.server_url,
261
- server.callback_url,
262
- server.server_options ? JSON.parse(server.server_options) : void 0,
263
- {
264
- id: server.id,
265
- oauthClientId: server.client_id ?? void 0
266
- }
267
- );
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
+ });
268
270
  })
269
271
  );
270
272
  this.broadcast(
271
273
  JSON.stringify({
272
274
  type: "cf_agent_mcp_servers",
273
- mcp: this.getMcpServers()
275
+ mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
274
276
  })
275
277
  );
276
- await this._tryCatch(() => _onStart());
278
+ await __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onStart());
277
279
  }
278
280
  );
279
281
  };
@@ -282,8 +284,8 @@ var Agent = class extends Server {
282
284
  * Current state of the Agent
283
285
  */
284
286
  get state() {
285
- if (this._state !== DEFAULT_STATE) {
286
- return this._state;
287
+ if (__privateGet(this, _state) !== DEFAULT_STATE) {
288
+ return __privateGet(this, _state);
287
289
  }
288
290
  const wasChanged = this.sql`
289
291
  SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
@@ -294,8 +296,8 @@ var Agent = class extends Server {
294
296
  if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
295
297
  result[0]?.state) {
296
298
  const state = result[0]?.state;
297
- this._state = JSON.parse(state);
298
- return this._state;
299
+ __privateSet(this, _state, JSON.parse(state));
300
+ return __privateGet(this, _state);
299
301
  }
300
302
  if (this.initialState === DEFAULT_STATE) {
301
303
  return void 0;
@@ -323,39 +325,12 @@ var Agent = class extends Server {
323
325
  throw this.onError(e);
324
326
  }
325
327
  }
326
- _setStateInternal(state, source = "server") {
327
- this._state = state;
328
- this.sql`
329
- INSERT OR REPLACE INTO cf_agents_state (id, state)
330
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
331
- `;
332
- this.sql`
333
- INSERT OR REPLACE INTO cf_agents_state (id, state)
334
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
335
- `;
336
- this.broadcast(
337
- JSON.stringify({
338
- type: "cf_agent_state",
339
- state
340
- }),
341
- source !== "server" ? [source.id] : []
342
- );
343
- return this._tryCatch(() => {
344
- const { connection, request } = agentContext.getStore() || {};
345
- return agentContext.run(
346
- { agent: this, connection, request },
347
- async () => {
348
- return this.onStateUpdate(state, source);
349
- }
350
- );
351
- });
352
- }
353
328
  /**
354
329
  * Update the Agent's state
355
330
  * @param state New state to set
356
331
  */
357
332
  setState(state) {
358
- this._setStateInternal(state, "server");
333
+ __privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, state, "server");
359
334
  }
360
335
  /**
361
336
  * Called when the Agent's state is updated
@@ -376,13 +351,6 @@ var Agent = class extends Server {
376
351
  }
377
352
  );
378
353
  }
379
- async _tryCatch(fn) {
380
- try {
381
- return await fn();
382
- } catch (e) {
383
- throw this.onError(e);
384
- }
385
- }
386
354
  onError(connectionOrError, error) {
387
355
  let theError;
388
356
  if (connectionOrError && error) {
@@ -432,7 +400,7 @@ var Agent = class extends Server {
432
400
  payload
433
401
  )}, 'scheduled', ${timestamp})
434
402
  `;
435
- await this._scheduleNextAlarm();
403
+ await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
436
404
  return {
437
405
  id,
438
406
  callback,
@@ -450,7 +418,7 @@ var Agent = class extends Server {
450
418
  payload
451
419
  )}, 'delayed', ${when}, ${timestamp})
452
420
  `;
453
- await this._scheduleNextAlarm();
421
+ await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
454
422
  return {
455
423
  id,
456
424
  callback,
@@ -469,7 +437,7 @@ var Agent = class extends Server {
469
437
  payload
470
438
  )}, 'cron', ${when}, ${timestamp})
471
439
  `;
472
- await this._scheduleNextAlarm();
440
+ await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
473
441
  return {
474
442
  id,
475
443
  callback,
@@ -536,22 +504,9 @@ var Agent = class extends Server {
536
504
  */
537
505
  async cancelSchedule(id) {
538
506
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
539
- await this._scheduleNextAlarm();
507
+ await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
540
508
  return true;
541
509
  }
542
- async _scheduleNextAlarm() {
543
- const result = this.sql`
544
- SELECT time FROM cf_agents_schedules
545
- WHERE time > ${Math.floor(Date.now() / 1e3)}
546
- ORDER BY time ASC
547
- LIMIT 1
548
- `;
549
- if (!result) return;
550
- if (result.length > 0 && "time" in result[0]) {
551
- const nextTime = result[0].time * 1e3;
552
- await this.ctx.storage.setAlarm(nextTime);
553
- }
554
- }
555
510
  /**
556
511
  * Destroy the Agent, removing all state and scheduled tasks
557
512
  */
@@ -562,13 +517,6 @@ var Agent = class extends Server {
562
517
  await this.ctx.storage.deleteAlarm();
563
518
  await this.ctx.storage.deleteAll();
564
519
  }
565
- /**
566
- * Get all methods marked as callable on this Agent
567
- * @returns A map of method names to their metadata
568
- */
569
- _isCallable(method) {
570
- return callableMetadata.has(this[method]);
571
- }
572
520
  /**
573
521
  * Connect to a new MCP Server
574
522
  *
@@ -579,56 +527,121 @@ var Agent = class extends Server {
579
527
  * @returns authUrl
580
528
  */
581
529
  async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
582
- const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
583
- const result = await this._connectToMcpServerInternal(
584
- serverName,
585
- url,
586
- callbackUrl,
587
- options
588
- );
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);
589
532
  this.broadcast(
590
533
  JSON.stringify({
591
534
  type: "cf_agent_mcp_servers",
592
- mcp: this.getMcpServers()
535
+ mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
593
536
  })
594
537
  );
595
538
  return result;
596
539
  }
597
- async _connectToMcpServerInternal(serverName, url, callbackUrl, options, reconnect) {
598
- const authProvider = new DurableObjectOAuthClientProvider(
599
- this.ctx.storage,
600
- this.name,
601
- callbackUrl
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
+ })
602
550
  );
603
- if (reconnect) {
604
- authProvider.serverId = reconnect.id;
605
- if (reconnect.oauthClientId) {
606
- authProvider.clientId = reconnect.oauthClientId;
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);
607
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;
608
620
  }
609
- let headerTransportOpts = {};
610
- if (options?.transport?.headers) {
611
- headerTransportOpts = {
612
- eventSourceInit: {
613
- fetch: (url2, init) => fetch(url2, {
614
- ...init,
615
- headers: options?.transport?.headers
616
- })
617
- },
618
- requestInit: {
621
+ }
622
+ let headerTransportOpts = {};
623
+ if (options?.transport?.headers) {
624
+ headerTransportOpts = {
625
+ eventSourceInit: {
626
+ fetch: (url2, init) => fetch(url2, {
627
+ ...init,
619
628
  headers: options?.transport?.headers
620
- }
621
- };
622
- }
623
- const { id, authUrl, clientId } = await this.mcp.connect(url, {
624
- reconnect,
625
- transport: {
626
- ...headerTransportOpts,
627
- authProvider
629
+ })
628
630
  },
629
- client: options?.client
630
- });
631
- this.sql`
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`
632
645
  INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
633
646
  VALUES (
634
647
  ${id},
@@ -640,45 +653,30 @@ var Agent = class extends Server {
640
653
  ${options ? JSON.stringify(options) : null}
641
654
  );
642
655
  `;
643
- return {
644
- id,
645
- authUrl
646
- };
647
- }
648
- async removeMcpServer(id) {
649
- this.mcp.closeConnection(id);
650
- this.sql`
651
- DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
652
- `;
653
- this.broadcast(
654
- JSON.stringify({
655
- type: "cf_agent_mcp_servers",
656
- mcp: this.getMcpServers()
657
- })
658
- );
659
- }
660
- getMcpServers() {
661
- const mcpState = {
662
- servers: {},
663
- tools: this.mcp.listTools(),
664
- prompts: this.mcp.listPrompts(),
665
- resources: this.mcp.listResources()
666
- };
667
- const servers = this.sql`
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`
668
669
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
669
670
  `;
670
- for (const server of servers) {
671
- mcpState.servers[server.id] = {
672
- name: server.name,
673
- server_url: server.server_url,
674
- auth_url: server.auth_url,
675
- state: this.mcp.mcpConnections[server.id].connectionState,
676
- instructions: this.mcp.mcpConnections[server.id].instructions ?? null,
677
- capabilities: this.mcp.mcpConnections[server.id].serverCapabilities ?? null
678
- };
679
- }
680
- return mcpState;
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
+ };
681
678
  }
679
+ return mcpState;
682
680
  };
683
681
  /**
684
682
  * Agent configuration options
@@ -728,48 +726,54 @@ async function routeAgentEmail(email, env, options) {
728
726
  async function getAgentByName(namespace, name, options) {
729
727
  return getServerByName(namespace, name, options);
730
728
  }
729
+ var _connection, _id, _closed;
731
730
  var StreamingResponse = class {
732
731
  constructor(connection, id) {
733
- this._closed = false;
734
- this._connection = connection;
735
- this._id = id;
732
+ __privateAdd(this, _connection);
733
+ __privateAdd(this, _id);
734
+ __privateAdd(this, _closed, false);
735
+ __privateSet(this, _connection, connection);
736
+ __privateSet(this, _id, id);
736
737
  }
737
738
  /**
738
739
  * Send a chunk of data to the client
739
740
  * @param chunk The data to send
740
741
  */
741
742
  send(chunk) {
742
- if (this._closed) {
743
+ if (__privateGet(this, _closed)) {
743
744
  throw new Error("StreamingResponse is already closed");
744
745
  }
745
746
  const response = {
746
747
  type: "rpc",
747
- id: this._id,
748
+ id: __privateGet(this, _id),
748
749
  success: true,
749
750
  result: chunk,
750
751
  done: false
751
752
  };
752
- this._connection.send(JSON.stringify(response));
753
+ __privateGet(this, _connection).send(JSON.stringify(response));
753
754
  }
754
755
  /**
755
756
  * End the stream and send the final chunk (if any)
756
757
  * @param finalChunk Optional final chunk of data to send
757
758
  */
758
759
  end(finalChunk) {
759
- if (this._closed) {
760
+ if (__privateGet(this, _closed)) {
760
761
  throw new Error("StreamingResponse is already closed");
761
762
  }
762
- this._closed = true;
763
+ __privateSet(this, _closed, true);
763
764
  const response = {
764
765
  type: "rpc",
765
- id: this._id,
766
+ id: __privateGet(this, _id),
766
767
  success: true,
767
768
  result: finalChunk,
768
769
  done: true
769
770
  };
770
- this._connection.send(JSON.stringify(response));
771
+ __privateGet(this, _connection).send(JSON.stringify(response));
771
772
  }
772
773
  };
774
+ _connection = new WeakMap();
775
+ _id = new WeakMap();
776
+ _closed = new WeakMap();
773
777
 
774
778
  export {
775
779
  unstable_callable,
@@ -780,4 +784,4 @@ export {
780
784
  getAgentByName,
781
785
  StreamingResponse
782
786
  };
783
- //# sourceMappingURL=chunk-J6T74FUS.js.map
787
+ //# sourceMappingURL=chunk-YFPCCSZO.js.map