agents 0.0.0-d2e8c0e → 0.0.0-d40512c

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 (44) hide show
  1. package/README.md +22 -22
  2. package/dist/ai-chat-agent.d.ts +5 -4
  3. package/dist/ai-chat-agent.js +64 -26
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +10 -9
  6. package/dist/ai-react.js +27 -27
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/{chunk-Y67CHZBI.js → chunk-4RBEYCWK.js} +23 -18
  9. package/dist/chunk-4RBEYCWK.js.map +1 -0
  10. package/dist/{chunk-QSGN3REV.js → chunk-KUH345EY.js} +8 -15
  11. package/dist/chunk-KUH345EY.js.map +1 -0
  12. package/dist/{chunk-J6T74FUS.js → chunk-LU2RSO54.js} +207 -80
  13. package/dist/chunk-LU2RSO54.js.map +1 -0
  14. package/dist/{chunk-BZXOAZUX.js → chunk-PVQZBKN7.js} +5 -5
  15. package/dist/chunk-PVQZBKN7.js.map +1 -0
  16. package/dist/client.d.ts +8 -2
  17. package/dist/client.js +1 -1
  18. package/dist/index-CITGJflw.d.ts +486 -0
  19. package/dist/index.d.ts +25 -405
  20. package/dist/index.js +4 -4
  21. package/dist/mcp/client.d.ts +281 -9
  22. package/dist/mcp/client.js +1 -1
  23. package/dist/mcp/do-oauth-client-provider.js +1 -1
  24. package/dist/mcp/index.d.ts +9 -9
  25. package/dist/mcp/index.js +53 -49
  26. package/dist/mcp/index.js.map +1 -1
  27. package/dist/observability/index.d.ts +12 -0
  28. package/dist/observability/index.js +10 -0
  29. package/dist/observability/index.js.map +1 -0
  30. package/dist/react.d.ts +51 -36
  31. package/dist/react.js +16 -6
  32. package/dist/react.js.map +1 -1
  33. package/dist/schedule.d.ts +6 -6
  34. package/dist/schedule.js +4 -4
  35. package/dist/schedule.js.map +1 -1
  36. package/dist/serializable.d.ts +32 -0
  37. package/dist/serializable.js +1 -0
  38. package/dist/serializable.js.map +1 -0
  39. package/package.json +75 -72
  40. package/src/index.ts +227 -112
  41. package/dist/chunk-BZXOAZUX.js.map +0 -1
  42. package/dist/chunk-J6T74FUS.js.map +0 -1
  43. package/dist/chunk-QSGN3REV.js.map +0 -1
  44. package/dist/chunk-Y67CHZBI.js.map +0 -1
@@ -1,22 +1,22 @@
1
+ import {
2
+ MCPClientManager
3
+ } from "./chunk-4RBEYCWK.js";
1
4
  import {
2
5
  DurableObjectOAuthClientProvider
3
- } from "./chunk-BZXOAZUX.js";
6
+ } from "./chunk-PVQZBKN7.js";
4
7
  import {
5
8
  camelCaseToKebabCase
6
- } from "./chunk-QSGN3REV.js";
7
- import {
8
- MCPClientManager
9
- } from "./chunk-Y67CHZBI.js";
9
+ } from "./chunk-KUH345EY.js";
10
10
 
11
11
  // src/index.ts
12
+ import { AsyncLocalStorage } from "async_hooks";
13
+ import { parseCronExpression } from "cron-schedule";
14
+ import { nanoid } from "nanoid";
12
15
  import {
13
- Server,
16
+ getServerByName,
14
17
  routePartykitRequest,
15
- getServerByName
18
+ Server
16
19
  } from "partyserver";
17
- import { parseCronExpression } from "cron-schedule";
18
- import { nanoid } from "nanoid";
19
- import { AsyncLocalStorage } from "node:async_hooks";
20
20
  function isRPCRequest(msg) {
21
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
22
  }
@@ -62,6 +62,10 @@ var Agent = class extends Server {
62
62
  * Override to provide default state values
63
63
  */
64
64
  this.initialState = DEFAULT_STATE;
65
+ /**
66
+ * The observability implementation to use for the Agent
67
+ */
68
+ this.observability = genericObservability;
65
69
  /**
66
70
  * Method called when an alarm fires.
67
71
  * Executes any scheduled tasks that are due.
@@ -85,6 +89,16 @@ var Agent = class extends Server {
85
89
  { agent: this, connection: void 0, request: void 0 },
86
90
  async () => {
87
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
+ );
88
102
  await callback.bind(this)(JSON.parse(row.payload), row);
89
103
  } catch (e) {
90
104
  console.error(`error executing callback "${row.callback}"`, e);
@@ -148,13 +162,13 @@ var Agent = class extends Server {
148
162
  await this.mcp.handleCallbackRequest(request);
149
163
  this.broadcast(
150
164
  JSON.stringify({
151
- type: "cf_agent_mcp_servers",
152
- mcp: this.getMcpServers()
165
+ mcp: this.getMcpServers(),
166
+ type: "cf_agent_mcp_servers"
153
167
  })
154
168
  );
155
169
  return new Response("<script>window.close();</script>", {
156
- status: 200,
157
- headers: { "content-type": "text/html" }
170
+ headers: { "content-type": "text/html" },
171
+ status: 200
158
172
  });
159
173
  }
160
174
  return this._tryCatch(() => _onRequest(request));
@@ -172,7 +186,7 @@ var Agent = class extends Server {
172
186
  let parsed;
173
187
  try {
174
188
  parsed = JSON.parse(message);
175
- } catch (e) {
189
+ } catch (_e) {
176
190
  return this._tryCatch(() => _onMessage(connection, message));
177
191
  }
178
192
  if (isStateUpdateMessage(parsed)) {
@@ -196,20 +210,35 @@ var Agent = class extends Server {
196
210
  return;
197
211
  }
198
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
+ );
199
228
  const response = {
200
- type: "rpc",
229
+ done: true,
201
230
  id,
202
- success: true,
203
231
  result,
204
- done: true
232
+ success: true,
233
+ type: "rpc"
205
234
  };
206
235
  connection.send(JSON.stringify(response));
207
236
  } catch (e) {
208
237
  const response = {
209
- type: "rpc",
238
+ error: e instanceof Error ? e.message : "Unknown error occurred",
210
239
  id: parsed.id,
211
240
  success: false,
212
- error: e instanceof Error ? e.message : "Unknown error occurred"
241
+ type: "rpc"
213
242
  };
214
243
  connection.send(JSON.stringify(response));
215
244
  console.error("RPC error:", e);
@@ -229,17 +258,29 @@ var Agent = class extends Server {
229
258
  if (this.state) {
230
259
  connection.send(
231
260
  JSON.stringify({
232
- type: "cf_agent_state",
233
- state: this.state
261
+ state: this.state,
262
+ type: "cf_agent_state"
234
263
  })
235
264
  );
236
265
  }
237
266
  connection.send(
238
267
  JSON.stringify({
239
- type: "cf_agent_mcp_servers",
240
- mcp: this.getMcpServers()
268
+ mcp: this.getMcpServers(),
269
+ type: "cf_agent_mcp_servers"
241
270
  })
242
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
+ );
243
284
  return this._tryCatch(() => _onConnect(connection, ctx2));
244
285
  }, 20);
245
286
  }
@@ -253,7 +294,7 @@ var Agent = class extends Server {
253
294
  const servers = this.sql`
254
295
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
255
296
  `;
256
- await Promise.allSettled(
297
+ Promise.allSettled(
257
298
  servers.map((server) => {
258
299
  return this._connectToMcpServerInternal(
259
300
  server.name,
@@ -266,13 +307,14 @@ var Agent = class extends Server {
266
307
  }
267
308
  );
268
309
  })
269
- );
270
- this.broadcast(
271
- JSON.stringify({
272
- type: "cf_agent_mcp_servers",
273
- mcp: this.getMcpServers()
274
- })
275
- );
310
+ ).then((_results) => {
311
+ this.broadcast(
312
+ JSON.stringify({
313
+ mcp: this.getMcpServers(),
314
+ type: "cf_agent_mcp_servers"
315
+ })
316
+ );
317
+ });
276
318
  await this._tryCatch(() => _onStart());
277
319
  }
278
320
  );
@@ -324,6 +366,7 @@ var Agent = class extends Server {
324
366
  }
325
367
  }
326
368
  _setStateInternal(state, source = "server") {
369
+ const previousState = this._state;
327
370
  this._state = state;
328
371
  this.sql`
329
372
  INSERT OR REPLACE INTO cf_agents_state (id, state)
@@ -335,8 +378,8 @@ var Agent = class extends Server {
335
378
  `;
336
379
  this.broadcast(
337
380
  JSON.stringify({
338
- type: "cf_agent_state",
339
- state
381
+ state,
382
+ type: "cf_agent_state"
340
383
  }),
341
384
  source !== "server" ? [source.id] : []
342
385
  );
@@ -345,6 +388,19 @@ var Agent = class extends Server {
345
388
  return agentContext.run(
346
389
  { agent: this, connection, request },
347
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
+ );
348
404
  return this.onStateUpdate(state, source);
349
405
  }
350
406
  );
@@ -362,12 +418,14 @@ var Agent = class extends Server {
362
418
  * @param state Updated state
363
419
  * @param source Source of the state update ("server" or a client connection)
364
420
  */
421
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
365
422
  onStateUpdate(state, source) {
366
423
  }
367
424
  /**
368
425
  * Called when the Agent receives an email
369
426
  * @param email Email message to process
370
427
  */
428
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
371
429
  onEmail(email) {
372
430
  return agentContext.run(
373
431
  { agent: this, connection: void 0, request: void 0 },
@@ -418,6 +476,16 @@ var Agent = class extends Server {
418
476
  */
419
477
  async schedule(when, callback, payload) {
420
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
+ );
421
489
  if (typeof callback !== "string") {
422
490
  throw new Error("Callback must be a string");
423
491
  }
@@ -433,13 +501,15 @@ var Agent = class extends Server {
433
501
  )}, 'scheduled', ${timestamp})
434
502
  `;
435
503
  await this._scheduleNextAlarm();
436
- return {
437
- id,
504
+ const schedule = {
438
505
  callback,
506
+ id,
439
507
  payload,
440
508
  time: timestamp,
441
509
  type: "scheduled"
442
510
  };
511
+ emitScheduleCreate(schedule);
512
+ return schedule;
443
513
  }
444
514
  if (typeof when === "number") {
445
515
  const time = new Date(Date.now() + when * 1e3);
@@ -451,14 +521,16 @@ var Agent = class extends Server {
451
521
  )}, 'delayed', ${when}, ${timestamp})
452
522
  `;
453
523
  await this._scheduleNextAlarm();
454
- return {
455
- id,
524
+ const schedule = {
456
525
  callback,
457
- payload,
458
526
  delayInSeconds: when,
527
+ id,
528
+ payload,
459
529
  time: timestamp,
460
530
  type: "delayed"
461
531
  };
532
+ emitScheduleCreate(schedule);
533
+ return schedule;
462
534
  }
463
535
  if (typeof when === "string") {
464
536
  const nextExecutionTime = getNextCronTime(when);
@@ -470,14 +542,16 @@ var Agent = class extends Server {
470
542
  )}, 'cron', ${when}, ${timestamp})
471
543
  `;
472
544
  await this._scheduleNextAlarm();
473
- return {
474
- id,
545
+ const schedule = {
475
546
  callback,
476
- payload,
477
547
  cron: when,
548
+ id,
549
+ payload,
478
550
  time: timestamp,
479
551
  type: "cron"
480
552
  };
553
+ emitScheduleCreate(schedule);
554
+ return schedule;
481
555
  }
482
556
  throw new Error("Invalid schedule type");
483
557
  }
@@ -535,6 +609,19 @@ var Agent = class extends Server {
535
609
  * @returns true if the task was cancelled, false otherwise
536
610
  */
537
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
+ }
538
625
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
539
626
  await this._scheduleNextAlarm();
540
627
  return true;
@@ -561,6 +648,17 @@ var Agent = class extends Server {
561
648
  this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
562
649
  await this.ctx.storage.deleteAlarm();
563
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
+ );
564
662
  }
565
663
  /**
566
664
  * Get all methods marked as callable on this Agent
@@ -586,15 +684,28 @@ var Agent = class extends Server {
586
684
  callbackUrl,
587
685
  options
588
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
+ `;
589
700
  this.broadcast(
590
701
  JSON.stringify({
591
- type: "cf_agent_mcp_servers",
592
- mcp: this.getMcpServers()
702
+ mcp: this.getMcpServers(),
703
+ type: "cf_agent_mcp_servers"
593
704
  })
594
705
  );
595
706
  return result;
596
707
  }
597
- async _connectToMcpServerInternal(serverName, url, callbackUrl, options, reconnect) {
708
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
598
709
  const authProvider = new DurableObjectOAuthClientProvider(
599
710
  this.ctx.storage,
600
711
  this.name,
@@ -621,28 +732,17 @@ var Agent = class extends Server {
621
732
  };
622
733
  }
623
734
  const { id, authUrl, clientId } = await this.mcp.connect(url, {
735
+ client: options?.client,
624
736
  reconnect,
625
737
  transport: {
626
738
  ...headerTransportOpts,
627
739
  authProvider
628
- },
629
- client: options?.client
740
+ }
630
741
  });
631
- this.sql`
632
- INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
633
- VALUES (
634
- ${id},
635
- ${serverName},
636
- ${url},
637
- ${clientId ?? null},
638
- ${authUrl ?? null},
639
- ${callbackUrl},
640
- ${options ? JSON.stringify(options) : null}
641
- );
642
- `;
643
742
  return {
644
- id,
645
- authUrl
743
+ authUrl,
744
+ clientId,
745
+ id
646
746
  };
647
747
  }
648
748
  async removeMcpServer(id) {
@@ -652,29 +752,31 @@ var Agent = class extends Server {
652
752
  `;
653
753
  this.broadcast(
654
754
  JSON.stringify({
655
- type: "cf_agent_mcp_servers",
656
- mcp: this.getMcpServers()
755
+ mcp: this.getMcpServers(),
756
+ type: "cf_agent_mcp_servers"
657
757
  })
658
758
  );
659
759
  }
660
760
  getMcpServers() {
661
761
  const mcpState = {
662
- servers: {},
663
- tools: this.mcp.listTools(),
664
762
  prompts: this.mcp.listPrompts(),
665
- resources: this.mcp.listResources()
763
+ resources: this.mcp.listResources(),
764
+ servers: {},
765
+ tools: this.mcp.listTools()
666
766
  };
667
767
  const servers = this.sql`
668
768
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
669
769
  `;
670
770
  for (const server of servers) {
771
+ const serverConn = this.mcp.mcpConnections[server.id];
671
772
  mcpState.servers[server.id] = {
773
+ auth_url: server.auth_url,
774
+ capabilities: serverConn?.serverCapabilities ?? null,
775
+ instructions: serverConn?.instructions ?? null,
672
776
  name: server.name,
673
777
  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
778
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
779
+ state: serverConn?.connectionState ?? "authenticating"
678
780
  };
679
781
  }
680
782
  return mcpState;
@@ -690,9 +792,9 @@ Agent.options = {
690
792
  };
691
793
  async function routeAgentRequest(request, env, options) {
692
794
  const corsHeaders = options?.cors === true ? {
693
- "Access-Control-Allow-Origin": "*",
694
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
695
795
  "Access-Control-Allow-Credentials": "true",
796
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
797
+ "Access-Control-Allow-Origin": "*",
696
798
  "Access-Control-Max-Age": "86400"
697
799
  } : options?.cors;
698
800
  if (request.method === "OPTIONS") {
@@ -723,7 +825,7 @@ async function routeAgentRequest(request, env, options) {
723
825
  }
724
826
  return response;
725
827
  }
726
- async function routeAgentEmail(email, env, options) {
828
+ async function routeAgentEmail(_email, _env, _options) {
727
829
  }
728
830
  async function getAgentByName(namespace, name, options) {
729
831
  return getServerByName(namespace, name, options);
@@ -743,11 +845,11 @@ var StreamingResponse = class {
743
845
  throw new Error("StreamingResponse is already closed");
744
846
  }
745
847
  const response = {
746
- type: "rpc",
848
+ done: false,
747
849
  id: this._id,
748
- success: true,
749
850
  result: chunk,
750
- done: false
851
+ success: true,
852
+ type: "rpc"
751
853
  };
752
854
  this._connection.send(JSON.stringify(response));
753
855
  }
@@ -761,17 +863,42 @@ var StreamingResponse = class {
761
863
  }
762
864
  this._closed = true;
763
865
  const response = {
764
- type: "rpc",
866
+ done: true,
765
867
  id: this._id,
766
- success: true,
767
868
  result: finalChunk,
768
- done: true
869
+ success: true,
870
+ type: "rpc"
769
871
  };
770
872
  this._connection.send(JSON.stringify(response));
771
873
  }
772
874
  };
773
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
+
774
900
  export {
901
+ genericObservability,
775
902
  unstable_callable,
776
903
  getCurrentAgent,
777
904
  Agent,
@@ -780,4 +907,4 @@ export {
780
907
  getAgentByName,
781
908
  StreamingResponse
782
909
  };
783
- //# sourceMappingURL=chunk-J6T74FUS.js.map
910
+ //# sourceMappingURL=chunk-LU2RSO54.js.map