agents 0.0.0-1eac06e → 0.0.0-1f8c517

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 (50) hide show
  1. package/README.md +32 -7
  2. package/dist/ai-chat-agent.d.ts +9 -8
  3. package/dist/ai-chat-agent.js +142 -59
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration.d.ts +152 -0
  6. package/dist/ai-chat-v5-migration.js +19 -0
  7. package/dist/ai-chat-v5-migration.js.map +1 -0
  8. package/dist/ai-react.d.ts +59 -70
  9. package/dist/ai-react.js +144 -37
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/ai-types.d.ts +36 -19
  12. package/dist/ai-types.js +6 -0
  13. package/dist/chunk-AVYJQSLW.js +17 -0
  14. package/dist/chunk-AVYJQSLW.js.map +1 -0
  15. package/dist/{chunk-PVQZBKN7.js → chunk-LL2AFX7V.js} +5 -2
  16. package/dist/chunk-LL2AFX7V.js.map +1 -0
  17. package/dist/{chunk-XJR75HO7.js → chunk-MH46VMM4.js} +91 -27
  18. package/dist/chunk-MH46VMM4.js.map +1 -0
  19. package/dist/{chunk-KUH345EY.js → chunk-QEVM4BVL.js} +5 -5
  20. package/dist/chunk-QEVM4BVL.js.map +1 -0
  21. package/dist/chunk-UJVEAURM.js +150 -0
  22. package/dist/chunk-UJVEAURM.js.map +1 -0
  23. package/dist/{chunk-2DJ6XAU6.js → chunk-YDUDMOL6.js} +115 -89
  24. package/dist/chunk-YDUDMOL6.js.map +1 -0
  25. package/dist/client-CvaJdLQA.d.ts +5015 -0
  26. package/dist/client.js +2 -1
  27. package/dist/index.d.ts +555 -32
  28. package/dist/index.js +7 -4
  29. package/dist/mcp/client.d.ts +9 -1057
  30. package/dist/mcp/client.js +1 -1
  31. package/dist/mcp/do-oauth-client-provider.d.ts +1 -0
  32. package/dist/mcp/do-oauth-client-provider.js +1 -1
  33. package/dist/mcp/index.d.ts +63 -88
  34. package/dist/mcp/index.js +813 -692
  35. package/dist/mcp/index.js.map +1 -1
  36. package/dist/observability/index.d.ts +46 -14
  37. package/dist/observability/index.js +5 -4
  38. package/dist/react.d.ts +4 -2
  39. package/dist/react.js +7 -5
  40. package/dist/react.js.map +1 -1
  41. package/dist/schedule.d.ts +79 -5
  42. package/dist/schedule.js +15 -2
  43. package/dist/schedule.js.map +1 -1
  44. package/package.json +19 -8
  45. package/src/index.ts +152 -100
  46. package/dist/chunk-2DJ6XAU6.js.map +0 -1
  47. package/dist/chunk-KUH345EY.js.map +0 -1
  48. package/dist/chunk-PVQZBKN7.js.map +0 -1
  49. package/dist/chunk-XJR75HO7.js.map +0 -1
  50. package/dist/index-CLW1aEBr.d.ts +0 -615
package/src/index.ts CHANGED
@@ -26,6 +26,7 @@ import { MCPClientManager } from "./mcp/client";
26
26
  // import type { MCPClientConnection } from "./mcp/client-connection";
27
27
  import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
28
28
  import { genericObservability, type Observability } from "./observability";
29
+ import { MessageType } from "./ai-types";
29
30
 
30
31
  export type { Connection, ConnectionContext, WSMessage } from "partyserver";
31
32
 
@@ -43,7 +44,7 @@ export type RPCRequest = {
43
44
  * State update message from client
44
45
  */
45
46
  export type StateUpdateMessage = {
46
- type: "cf_agent_state";
47
+ type: MessageType.CF_AGENT_STATE;
47
48
  state: unknown;
48
49
  };
49
50
 
@@ -51,7 +52,7 @@ export type StateUpdateMessage = {
51
52
  * RPC response message to client
52
53
  */
53
54
  export type RPCResponse = {
54
- type: "rpc";
55
+ type: MessageType.RPC;
55
56
  id: string;
56
57
  } & (
57
58
  | {
@@ -78,7 +79,7 @@ function isRPCRequest(msg: unknown): msg is RPCRequest {
78
79
  typeof msg === "object" &&
79
80
  msg !== null &&
80
81
  "type" in msg &&
81
- msg.type === "rpc" &&
82
+ msg.type === MessageType.RPC &&
82
83
  "id" in msg &&
83
84
  typeof msg.id === "string" &&
84
85
  "method" in msg &&
@@ -96,7 +97,7 @@ function isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {
96
97
  typeof msg === "object" &&
97
98
  msg !== null &&
98
99
  "type" in msg &&
99
- msg.type === "cf_agent_state" &&
100
+ msg.type === MessageType.CF_AGENT_STATE &&
100
101
  "state" in msg
101
102
  );
102
103
  }
@@ -117,7 +118,7 @@ const callableMetadata = new Map<Function, CallableMetadata>();
117
118
  * Decorator that marks a method as callable by clients
118
119
  * @param metadata Optional metadata about the callable method
119
120
  */
120
- export function unstable_callable(metadata: CallableMetadata = {}) {
121
+ export function callable(metadata: CallableMetadata = {}) {
121
122
  return function callableDecorator<This, Args extends unknown[], Return>(
122
123
  target: (this: This, ...args: Args) => Return,
123
124
  // biome-ignore lint/correctness/noUnusedFunctionParameters: later
@@ -131,6 +132,23 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
131
132
  };
132
133
  }
133
134
 
135
+ let didWarnAboutUnstableCallable = false;
136
+
137
+ /**
138
+ * Decorator that marks a method as callable by clients
139
+ * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
140
+ * @param metadata Optional metadata about the callable method
141
+ */
142
+ export const unstable_callable = (metadata: CallableMetadata = {}) => {
143
+ if (!didWarnAboutUnstableCallable) {
144
+ didWarnAboutUnstableCallable = true;
145
+ console.warn(
146
+ "unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version."
147
+ );
148
+ }
149
+ callable(metadata);
150
+ };
151
+
134
152
  export type QueueItem<T = string> = {
135
153
  id: string;
136
154
  payload: T;
@@ -183,7 +201,7 @@ function getNextCronTime(cron: string) {
183
201
  * MCP Server state update message from server -> Client
184
202
  */
185
203
  export type MCPServerMessage = {
186
- type: "cf_agent_mcp_servers";
204
+ type: MessageType.CF_AGENT_MCP_SERVERS;
187
205
  mcp: MCPServersState;
188
206
  };
189
207
 
@@ -272,7 +290,13 @@ function withAgentContext<T extends (...args: any[]) => any>(
272
290
  method: T
273
291
  ): (this: Agent<unknown, unknown>, ...args: Parameters<T>) => ReturnType<T> {
274
292
  return function (...args: Parameters<T>): ReturnType<T> {
275
- const { connection, request, email } = getCurrentAgent();
293
+ const { connection, request, email, agent } = getCurrentAgent();
294
+
295
+ if (agent === this) {
296
+ // already wrapped, so we can just call the method
297
+ return method.apply(this, args);
298
+ }
299
+ // not wrapped, so we need to wrap it
276
300
  return agentContext.run({ agent: this, connection, request, email }, () => {
277
301
  return method.apply(this, args);
278
302
  });
@@ -284,7 +308,11 @@ function withAgentContext<T extends (...args: any[]) => any>(
284
308
  * @template Env Environment type containing bindings
285
309
  * @template State State type to store within the Agent
286
310
  */
287
- export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
311
+ export class Agent<
312
+ Env = typeof env,
313
+ State = unknown,
314
+ Props extends Record<string, unknown> = Record<string, unknown>
315
+ > extends Server<Env, Props> {
288
316
  private _state = DEFAULT_STATE as State;
289
317
 
290
318
  private _ParentClass: typeof Agent<Env, State> =
@@ -447,7 +475,7 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
447
475
  this.broadcast(
448
476
  JSON.stringify({
449
477
  mcp: this.getMcpServers(),
450
- type: "cf_agent_mcp_servers"
478
+ type: MessageType.CF_AGENT_MCP_SERVERS
451
479
  })
452
480
  );
453
481
 
@@ -516,10 +544,8 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
516
544
  displayMessage: `RPC call to ${method}`,
517
545
  id: nanoid(),
518
546
  payload: {
519
- args,
520
547
  method,
521
- streaming: metadata?.streaming,
522
- success: true
548
+ streaming: metadata?.streaming
523
549
  },
524
550
  timestamp: Date.now(),
525
551
  type: "rpc"
@@ -532,7 +558,7 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
532
558
  id,
533
559
  result,
534
560
  success: true,
535
- type: "rpc"
561
+ type: MessageType.RPC
536
562
  };
537
563
  connection.send(JSON.stringify(response));
538
564
  } catch (e) {
@@ -542,7 +568,7 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
542
568
  e instanceof Error ? e.message : "Unknown error occurred",
543
569
  id: parsed.id,
544
570
  success: false,
545
- type: "rpc"
571
+ type: MessageType.RPC
546
572
  };
547
573
  connection.send(JSON.stringify(response));
548
574
  console.error("RPC error:", e);
@@ -561,44 +587,42 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
561
587
  // must fix this
562
588
  return agentContext.run(
563
589
  { agent: this, connection, request: ctx.request, email: undefined },
564
- async () => {
565
- setTimeout(() => {
566
- if (this.state) {
567
- connection.send(
568
- JSON.stringify({
569
- state: this.state,
570
- type: "cf_agent_state"
571
- })
572
- );
573
- }
574
-
590
+ () => {
591
+ if (this.state) {
575
592
  connection.send(
576
593
  JSON.stringify({
577
- mcp: this.getMcpServers(),
578
- type: "cf_agent_mcp_servers"
594
+ state: this.state,
595
+ type: MessageType.CF_AGENT_STATE
579
596
  })
580
597
  );
598
+ }
581
599
 
582
- this.observability?.emit(
583
- {
584
- displayMessage: "Connection established",
585
- id: nanoid(),
586
- payload: {
587
- connectionId: connection.id
588
- },
589
- timestamp: Date.now(),
590
- type: "connect"
600
+ connection.send(
601
+ JSON.stringify({
602
+ mcp: this.getMcpServers(),
603
+ type: MessageType.CF_AGENT_MCP_SERVERS
604
+ })
605
+ );
606
+
607
+ this.observability?.emit(
608
+ {
609
+ displayMessage: "Connection established",
610
+ id: nanoid(),
611
+ payload: {
612
+ connectionId: connection.id
591
613
  },
592
- this.ctx
593
- );
594
- return this._tryCatch(() => _onConnect(connection, ctx));
595
- }, 20);
614
+ timestamp: Date.now(),
615
+ type: "connect"
616
+ },
617
+ this.ctx
618
+ );
619
+ return this._tryCatch(() => _onConnect(connection, ctx));
596
620
  }
597
621
  );
598
622
  };
599
623
 
600
624
  const _onStart = this.onStart.bind(this);
601
- this.onStart = async () => {
625
+ this.onStart = async (props?: Props) => {
602
626
  return agentContext.run(
603
627
  {
604
628
  agent: this,
@@ -607,15 +631,22 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
607
631
  email: undefined
608
632
  },
609
633
  async () => {
610
- const servers = this.sql<MCPServerRow>`
634
+ await this._tryCatch(() => {
635
+ const servers = this.sql<MCPServerRow>`
611
636
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
612
637
  `;
613
638
 
614
- // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
615
- if (servers && Array.isArray(servers) && servers.length > 0) {
616
- Promise.allSettled(
617
- servers.map((server) => {
618
- return this._connectToMcpServerInternal(
639
+ this.broadcast(
640
+ JSON.stringify({
641
+ mcp: this.getMcpServers(),
642
+ type: MessageType.CF_AGENT_MCP_SERVERS
643
+ })
644
+ );
645
+
646
+ // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
647
+ if (servers && Array.isArray(servers) && servers.length > 0) {
648
+ servers.forEach((server) => {
649
+ this._connectToMcpServerInternal(
619
650
  server.name,
620
651
  server.server_url,
621
652
  server.callback_url,
@@ -626,18 +657,33 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
626
657
  id: server.id,
627
658
  oauthClientId: server.client_id ?? undefined
628
659
  }
629
- );
630
- })
631
- ).then((_results) => {
632
- this.broadcast(
633
- JSON.stringify({
634
- mcp: this.getMcpServers(),
635
- type: "cf_agent_mcp_servers"
636
- })
637
- );
638
- });
639
- }
640
- await this._tryCatch(() => _onStart());
660
+ )
661
+ .then(() => {
662
+ // Broadcast updated MCP servers state after each server connects
663
+ this.broadcast(
664
+ JSON.stringify({
665
+ mcp: this.getMcpServers(),
666
+ type: MessageType.CF_AGENT_MCP_SERVERS
667
+ })
668
+ );
669
+ })
670
+ .catch((error) => {
671
+ console.error(
672
+ `Error connecting to MCP server: ${server.name} (${server.server_url})`,
673
+ error
674
+ );
675
+ // Still broadcast even if connection fails, so clients know about the failure
676
+ this.broadcast(
677
+ JSON.stringify({
678
+ mcp: this.getMcpServers(),
679
+ type: MessageType.CF_AGENT_MCP_SERVERS
680
+ })
681
+ );
682
+ });
683
+ });
684
+ }
685
+ return _onStart(props);
686
+ });
641
687
  }
642
688
  );
643
689
  };
@@ -647,7 +693,6 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
647
693
  state: State,
648
694
  source: Connection | "server" = "server"
649
695
  ) {
650
- const previousState = this._state;
651
696
  this._state = state;
652
697
  this.sql`
653
698
  INSERT OR REPLACE INTO cf_agents_state (id, state)
@@ -660,7 +705,7 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
660
705
  this.broadcast(
661
706
  JSON.stringify({
662
707
  state: state,
663
- type: "cf_agent_state"
708
+ type: MessageType.CF_AGENT_STATE
664
709
  }),
665
710
  source !== "server" ? [source.id] : []
666
711
  );
@@ -673,10 +718,7 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
673
718
  {
674
719
  displayMessage: "State updated",
675
720
  id: nanoid(),
676
- payload: {
677
- previousState,
678
- state
679
- },
721
+ payload: {},
680
722
  timestamp: Date.now(),
681
723
  type: "state:update"
682
724
  },
@@ -816,41 +858,37 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
816
858
  while (proto && proto !== Object.prototype && depth < 10) {
817
859
  const methodNames = Object.getOwnPropertyNames(proto);
818
860
  for (const methodName of methodNames) {
819
- // Skip if it's a private method or not a function
861
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
862
+
863
+ // Skip if it's a private method, a base method, a getter, or not a function,
820
864
  if (
821
865
  baseMethods.has(methodName) ||
822
866
  methodName.startsWith("_") ||
823
- typeof this[methodName as keyof this] !== "function"
867
+ !descriptor ||
868
+ !!descriptor.get ||
869
+ typeof descriptor.value !== "function"
824
870
  ) {
825
871
  continue;
826
872
  }
827
- // If the method doesn't exist in base prototypes, it's a custom method
828
- if (!baseMethods.has(methodName)) {
829
- const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
830
- if (descriptor && typeof descriptor.value === "function") {
831
- // Wrap the custom method with context
832
-
833
- const wrappedFunction = withAgentContext(
834
- // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
835
- this[methodName as keyof this] as (...args: any[]) => any
836
- // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
837
- ) as any;
838
-
839
- // if the method is callable, copy the metadata from the original method
840
- if (this._isCallable(methodName)) {
841
- callableMetadata.set(
842
- wrappedFunction,
843
- callableMetadata.get(
844
- this[methodName as keyof this] as Function
845
- )!
846
- );
847
- }
848
873
 
849
- // set the wrapped function on the prototype
850
- this.constructor.prototype[methodName as keyof this] =
851
- wrappedFunction;
852
- }
874
+ // Now, methodName is confirmed to be a custom method/function
875
+ // Wrap the custom method with context
876
+ const wrappedFunction = withAgentContext(
877
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
878
+ this[methodName as keyof this] as (...args: any[]) => any
879
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
880
+ ) as any;
881
+
882
+ // if the method is callable, copy the metadata from the original method
883
+ if (this._isCallable(methodName)) {
884
+ callableMetadata.set(
885
+ wrappedFunction,
886
+ callableMetadata.get(this[methodName as keyof this] as Function)!
887
+ );
853
888
  }
889
+
890
+ // set the wrapped function on the prototype
891
+ this.constructor.prototype[methodName as keyof this] = wrappedFunction;
854
892
  }
855
893
 
856
894
  proto = Object.getPrototypeOf(proto);
@@ -1037,7 +1075,10 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
1037
1075
  {
1038
1076
  displayMessage: `Schedule ${schedule.id} created`,
1039
1077
  id: nanoid(),
1040
- payload: schedule,
1078
+ payload: {
1079
+ callback: callback as string,
1080
+ id: id
1081
+ },
1041
1082
  timestamp: Date.now(),
1042
1083
  type: "schedule:create"
1043
1084
  },
@@ -1207,7 +1248,10 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
1207
1248
  {
1208
1249
  displayMessage: `Schedule ${id} cancelled`,
1209
1250
  id: nanoid(),
1210
- payload: schedule,
1251
+ payload: {
1252
+ callback: schedule.callback,
1253
+ id: schedule.id
1254
+ },
1211
1255
  timestamp: Date.now(),
1212
1256
  type: "schedule:cancel"
1213
1257
  },
@@ -1272,7 +1316,10 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
1272
1316
  {
1273
1317
  displayMessage: `Schedule ${row.id} executed`,
1274
1318
  id: nanoid(),
1275
- payload: row,
1319
+ payload: {
1320
+ callback: row.callback,
1321
+ id: row.id
1322
+ },
1276
1323
  timestamp: Date.now(),
1277
1324
  type: "schedule:execute"
1278
1325
  },
@@ -1392,7 +1439,7 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
1392
1439
  this.broadcast(
1393
1440
  JSON.stringify({
1394
1441
  mcp: this.getMcpServers(),
1395
- type: "cf_agent_mcp_servers"
1442
+ type: MessageType.CF_AGENT_MCP_SERVERS
1396
1443
  })
1397
1444
  );
1398
1445
 
@@ -1481,7 +1528,7 @@ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
1481
1528
  this.broadcast(
1482
1529
  JSON.stringify({
1483
1530
  mcp: this.getMcpServers(),
1484
- type: "cf_agent_mcp_servers"
1531
+ type: MessageType.CF_AGENT_MCP_SERVERS
1485
1532
  })
1486
1533
  );
1487
1534
  }
@@ -1832,12 +1879,17 @@ export type EmailSendOptions = {
1832
1879
  * @param options Options for Agent creation
1833
1880
  * @returns Promise resolving to an Agent instance stub
1834
1881
  */
1835
- export async function getAgentByName<Env, T extends Agent<Env>>(
1882
+ export async function getAgentByName<
1883
+ Env,
1884
+ T extends Agent<Env>,
1885
+ Props extends Record<string, unknown> = Record<string, unknown>
1886
+ >(
1836
1887
  namespace: AgentNamespace<T>,
1837
1888
  name: string,
1838
1889
  options?: {
1839
1890
  jurisdiction?: DurableObjectJurisdiction;
1840
1891
  locationHint?: DurableObjectLocationHint;
1892
+ props?: Props;
1841
1893
  }
1842
1894
  ) {
1843
1895
  return getServerByName<Env, T>(namespace, name, options);
@@ -1869,7 +1921,7 @@ export class StreamingResponse {
1869
1921
  id: this._id,
1870
1922
  result: chunk,
1871
1923
  success: true,
1872
- type: "rpc"
1924
+ type: MessageType.RPC
1873
1925
  };
1874
1926
  this._connection.send(JSON.stringify(response));
1875
1927
  }
@@ -1888,7 +1940,7 @@ export class StreamingResponse {
1888
1940
  id: this._id,
1889
1941
  result: finalChunk,
1890
1942
  success: true,
1891
- type: "rpc"
1943
+ type: MessageType.RPC
1892
1944
  };
1893
1945
  this._connection.send(JSON.stringify(response));
1894
1946
  }