agents 0.0.0-ecf8926 → 0.0.0-ed3f94d

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 (64) hide show
  1. package/README.md +126 -4
  2. package/dist/_esm-LV5FJ3HK.js +3922 -0
  3. package/dist/_esm-LV5FJ3HK.js.map +1 -0
  4. package/dist/ai-chat-agent.d.ts +2 -1
  5. package/dist/ai-chat-agent.js +391 -76
  6. package/dist/ai-chat-agent.js.map +1 -1
  7. package/dist/ai-chat-v5-migration.js +1 -0
  8. package/dist/ai-react.d.ts +8 -1
  9. package/dist/ai-react.js +157 -111
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/ai-types.d.ts +1 -0
  12. package/dist/ai-types.js +2 -1
  13. package/dist/ccip-CMBYN64O.js +15 -0
  14. package/dist/ccip-CMBYN64O.js.map +1 -0
  15. package/dist/{chunk-EGCWEPQL.js → chunk-254F4GDT.js} +151 -98
  16. package/dist/chunk-254F4GDT.js.map +1 -0
  17. package/dist/{chunk-DS7BJNPH.js → chunk-3OT2NNEW.js} +411 -68
  18. package/dist/chunk-3OT2NNEW.js.map +1 -0
  19. package/dist/chunk-5Y6BEZDY.js +276 -0
  20. package/dist/chunk-5Y6BEZDY.js.map +1 -0
  21. package/dist/{chunk-AVYJQSLW.js → chunk-BER7KXUJ.js} +2 -1
  22. package/dist/chunk-BER7KXUJ.js.map +1 -0
  23. package/dist/chunk-JJBFIGUC.js +5202 -0
  24. package/dist/chunk-JJBFIGUC.js.map +1 -0
  25. package/dist/chunk-PR4QN5HX.js +43 -0
  26. package/dist/chunk-PR4QN5HX.js.map +1 -0
  27. package/dist/chunk-TYAY6AU6.js +159 -0
  28. package/dist/chunk-TYAY6AU6.js.map +1 -0
  29. package/dist/{chunk-PVQZBKN7.js → chunk-Z44WASMA.js} +11 -3
  30. package/dist/chunk-Z44WASMA.js.map +1 -0
  31. package/dist/{client-BAqDHqAV.d.ts → client-DVoPb3-C.d.ts} +549 -30
  32. package/dist/client.js +2 -1
  33. package/dist/codemode/ai.d.ts +25 -0
  34. package/dist/codemode/ai.js +5112 -0
  35. package/dist/codemode/ai.js.map +1 -0
  36. package/dist/index.d.ts +44 -35
  37. package/dist/index.js +7 -4
  38. package/dist/mcp/client.d.ts +2 -1
  39. package/dist/mcp/client.js +2 -1
  40. package/dist/mcp/do-oauth-client-provider.d.ts +1 -0
  41. package/dist/mcp/do-oauth-client-provider.js +2 -1
  42. package/dist/mcp/index.d.ts +50 -83
  43. package/dist/mcp/index.js +903 -760
  44. package/dist/mcp/index.js.map +1 -1
  45. package/dist/mcp/x402.d.ts +39 -0
  46. package/dist/mcp/x402.js +3195 -0
  47. package/dist/mcp/x402.js.map +1 -0
  48. package/dist/mcp-BH1fJeiU.d.ts +58 -0
  49. package/dist/observability/index.d.ts +12 -24
  50. package/dist/observability/index.js +5 -4
  51. package/dist/react.d.ts +10 -6
  52. package/dist/react.js +101 -3
  53. package/dist/react.js.map +1 -1
  54. package/dist/schedule.d.ts +76 -2
  55. package/dist/schedule.js +17 -2
  56. package/dist/schedule.js.map +1 -1
  57. package/dist/secp256k1-M22GZP2U.js +2193 -0
  58. package/dist/secp256k1-M22GZP2U.js.map +1 -0
  59. package/package.json +22 -7
  60. package/src/index.ts +226 -116
  61. package/dist/chunk-AVYJQSLW.js.map +0 -1
  62. package/dist/chunk-DS7BJNPH.js.map +0 -1
  63. package/dist/chunk-EGCWEPQL.js.map +0 -1
  64. package/dist/chunk-PVQZBKN7.js.map +0 -1
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Base event structure for all observability events
3
+ */
4
+ type BaseEvent<
5
+ T extends string,
6
+ Payload extends Record<string, unknown> = {}
7
+ > = {
8
+ type: T;
9
+ /**
10
+ * The unique identifier for the event
11
+ */
12
+ id: string;
13
+ /**
14
+ * The message to display in the logs for this event, should the implementation choose to display
15
+ * a human-readable message.
16
+ */
17
+ displayMessage: string;
18
+ /**
19
+ * The payload of the event
20
+ */
21
+ payload: Payload & Record<string, unknown>;
22
+ /**
23
+ * The timestamp of the event in milliseconds since epoch
24
+ */
25
+ timestamp: number;
26
+ };
27
+
28
+ /**
29
+ * MCP-specific observability events
30
+ * These track the lifecycle of MCP connections and operations
31
+ */
32
+ type MCPObservabilityEvent =
33
+ | BaseEvent<
34
+ "mcp:client:preconnect",
35
+ {
36
+ serverId: string;
37
+ }
38
+ >
39
+ | BaseEvent<
40
+ "mcp:client:connect",
41
+ {
42
+ url: string;
43
+ transport: string;
44
+ state: string;
45
+ error?: string;
46
+ }
47
+ >
48
+ | BaseEvent<
49
+ "mcp:client:authorize",
50
+ {
51
+ serverId: string;
52
+ authUrl: string;
53
+ clientId?: string;
54
+ }
55
+ >
56
+ | BaseEvent<"mcp:client:discover", {}>;
57
+
58
+ export type { BaseEvent as B, MCPObservabilityEvent as M };
@@ -1,27 +1,10 @@
1
- type BaseEvent<T extends string, Payload extends Record<string, unknown> = {}> = {
2
- type: T;
3
- /**
4
- * The unique identifier for the event
5
- */
6
- id: string;
7
- /**
8
- * The message to display in the logs for this event, should the implementation choose to display
9
- * a human-readable message.
10
- */
11
- displayMessage: string;
12
- /**
13
- * The payload of the event
14
- */
15
- payload: Payload;
16
- /**
17
- * The timestamp of the event in milliseconds since epoch
18
- */
19
- timestamp: number;
20
- };
1
+ import { B as BaseEvent, M as MCPObservabilityEvent } from '../mcp-BH1fJeiU.js';
2
+
21
3
  /**
22
- * The type of events that can be emitted by an Agent
4
+ * Agent-specific observability events
5
+ * These track the lifecycle and operations of an Agent
23
6
  */
24
- type ObservabilityEvent = BaseEvent<"state:update", {}> | BaseEvent<"rpc", {
7
+ type AgentObservabilityEvent = BaseEvent<"state:update", {}> | BaseEvent<"rpc", {
25
8
  method: string;
26
9
  streaming?: boolean;
27
10
  }> | BaseEvent<"message:request" | "message:response", {}> | BaseEvent<"message:clear"> | BaseEvent<"schedule:create" | "schedule:execute" | "schedule:cancel", {
@@ -30,13 +13,18 @@ type ObservabilityEvent = BaseEvent<"state:update", {}> | BaseEvent<"rpc", {
30
13
  }> | BaseEvent<"destroy"> | BaseEvent<"connect", {
31
14
  connectionId: string;
32
15
  }>;
16
+
17
+ /**
18
+ * Union of all observability event types from different domains
19
+ */
20
+ type ObservabilityEvent = AgentObservabilityEvent | MCPObservabilityEvent;
33
21
  interface Observability {
34
22
  /**
35
23
  * Emit an event for the Agent's observability implementation to handle.
36
24
  * @param event - The event to emit
37
- * @param ctx - The execution context of the invocation
25
+ * @param ctx - The execution context of the invocation (optional)
38
26
  */
39
- emit(event: ObservabilityEvent, ctx: DurableObjectState): void;
27
+ emit(event: ObservabilityEvent, ctx?: DurableObjectState): void;
40
28
  }
41
29
  /**
42
30
  * A generic observability implementation that logs events to the console.
@@ -1,10 +1,11 @@
1
1
  import {
2
2
  genericObservability
3
- } from "../chunk-EGCWEPQL.js";
4
- import "../chunk-DS7BJNPH.js";
5
- import "../chunk-PVQZBKN7.js";
3
+ } from "../chunk-254F4GDT.js";
4
+ import "../chunk-3OT2NNEW.js";
5
+ import "../chunk-Z44WASMA.js";
6
6
  import "../chunk-QEVM4BVL.js";
7
- import "../chunk-AVYJQSLW.js";
7
+ import "../chunk-BER7KXUJ.js";
8
+ import "../chunk-PR4QN5HX.js";
8
9
  export {
9
10
  genericObservability
10
11
  };
package/dist/react.d.ts CHANGED
@@ -7,10 +7,11 @@ import "cloudflare:workers";
7
7
  import "@modelcontextprotocol/sdk/client/index.js";
8
8
  import "@modelcontextprotocol/sdk/types.js";
9
9
  import "partyserver";
10
- import "./client-BAqDHqAV.js";
10
+ import "./client-DVoPb3-C.js";
11
11
  import "zod";
12
12
  import "@modelcontextprotocol/sdk/shared/protocol.js";
13
13
  import "ai";
14
+ import "./mcp-BH1fJeiU.js";
14
15
  import "@modelcontextprotocol/sdk/client/sse.js";
15
16
  import "@modelcontextprotocol/sdk/client/streamableHttp.js";
16
17
  import "./mcp/do-oauth-client-provider.js";
@@ -19,18 +20,25 @@ import "@modelcontextprotocol/sdk/shared/auth.js";
19
20
  import "./observability/index.js";
20
21
  import "./ai-types.js";
21
22
 
23
+ type QueryObject = Record<string, string | null>;
22
24
  /**
23
25
  * Options for the useAgent hook
24
26
  * @template State Type of the Agent's state
25
27
  */
26
28
  type UseAgentOptions<State = unknown> = Omit<
27
29
  Parameters<typeof usePartySocket>[0],
28
- "party" | "room"
30
+ "party" | "room" | "query"
29
31
  > & {
30
32
  /** Name of the agent to connect to */
31
33
  agent: string;
32
34
  /** Name of the specific Agent instance */
33
35
  name?: string;
36
+ /** Query parameters - can be static object or async function */
37
+ query?: QueryObject | (() => Promise<QueryObject>);
38
+ /** Dependencies for async query caching */
39
+ queryDeps?: unknown[];
40
+ /** Cache TTL in milliseconds for auth tokens/time-sensitive data */
41
+ cacheTtl?: number;
34
42
  /** Called when the Agent's state is updated */
35
43
  onStateUpdate?: (state: State, source: "server" | "client") => void;
36
44
  /** Called when MCP server state is updated */
@@ -91,10 +99,6 @@ type AgentStub<T> = {
91
99
  type UntypedAgentStub = Record<string, Method>;
92
100
  /**
93
101
  * React hook for connecting to an Agent
94
- * @template State Type of the Agent's state
95
- * @template Agent Type of the Agent
96
- * @param options Connection options
97
- * @returns WebSocket connection with setState and call methods
98
102
  */
99
103
  declare function useAgent<State = unknown>(
100
104
  options: UseAgentOptions<State>
package/dist/react.js CHANGED
@@ -1,8 +1,9 @@
1
- import "./chunk-AVYJQSLW.js";
1
+ import "./chunk-BER7KXUJ.js";
2
+ import "./chunk-PR4QN5HX.js";
2
3
 
3
4
  // src/react.tsx
4
5
  import { usePartySocket } from "partysocket/react";
5
- import { useCallback, useRef } from "react";
6
+ import { useCallback, useRef, use, useMemo, useEffect } from "react";
6
7
  function camelCaseToKebabCase(str) {
7
8
  if (str === str.toUpperCase() && str !== str.toLowerCase()) {
8
9
  return str.toLowerCase().replace(/_/g, "-");
@@ -14,16 +15,113 @@ function camelCaseToKebabCase(str) {
14
15
  kebabified = kebabified.startsWith("-") ? kebabified.slice(1) : kebabified;
15
16
  return kebabified.replace(/_/g, "-").replace(/-$/, "");
16
17
  }
18
+ var queryCache = /* @__PURE__ */ new Map();
19
+ function arraysEqual(a, b) {
20
+ if (a === b) return true;
21
+ if (a.length !== b.length) return false;
22
+ for (let i = 0; i < a.length; i++) {
23
+ if (!Object.is(a[i], b[i])) return false;
24
+ }
25
+ return true;
26
+ }
27
+ function findCacheEntry(targetKey) {
28
+ for (const [existingKey, entry] of queryCache.entries()) {
29
+ if (arraysEqual(existingKey, targetKey)) {
30
+ if (Date.now() > entry.expiresAt) {
31
+ queryCache.delete(existingKey);
32
+ return void 0;
33
+ }
34
+ entry.refCount++;
35
+ return entry.promise;
36
+ }
37
+ }
38
+ return void 0;
39
+ }
40
+ function setCacheEntry(key, value, cacheTtl) {
41
+ for (const [existingKey] of queryCache.entries()) {
42
+ if (arraysEqual(existingKey, key)) {
43
+ queryCache.delete(existingKey);
44
+ break;
45
+ }
46
+ }
47
+ const expiresAt = cacheTtl ? Date.now() + cacheTtl : Date.now() + 5 * 60 * 1e3;
48
+ queryCache.set(key, { promise: value, refCount: 1, expiresAt, cacheTtl });
49
+ }
50
+ function decrementCacheEntry(targetKey) {
51
+ for (const [existingKey, entry] of queryCache.entries()) {
52
+ if (arraysEqual(existingKey, targetKey)) {
53
+ entry.refCount--;
54
+ if (entry.refCount <= 0) {
55
+ queryCache.delete(existingKey);
56
+ }
57
+ return true;
58
+ }
59
+ }
60
+ return false;
61
+ }
62
+ function createCacheKey(agentNamespace, name, deps) {
63
+ return [agentNamespace, name || "default", ...deps];
64
+ }
17
65
  function useAgent(options) {
18
66
  const agentNamespace = camelCaseToKebabCase(options.agent);
67
+ const { query, queryDeps, cacheTtl, ...restOptions } = options;
19
68
  const pendingCallsRef = useRef(
20
69
  /* @__PURE__ */ new Map()
21
70
  );
71
+ const cacheKey = useMemo(() => {
72
+ const deps = queryDeps || [];
73
+ return createCacheKey(agentNamespace, options.name, deps);
74
+ }, [agentNamespace, options.name, queryDeps]);
75
+ const queryPromise = useMemo(() => {
76
+ if (!query || typeof query !== "function") {
77
+ return null;
78
+ }
79
+ const existingPromise = findCacheEntry(cacheKey);
80
+ if (existingPromise) {
81
+ return existingPromise;
82
+ }
83
+ const promise = query().catch((error) => {
84
+ console.error(
85
+ `[useAgent] Query failed for agent "${options.agent}":`,
86
+ error
87
+ );
88
+ decrementCacheEntry(cacheKey);
89
+ throw error;
90
+ });
91
+ setCacheEntry(cacheKey, promise, cacheTtl);
92
+ return promise;
93
+ }, [cacheKey, query, options.agent, cacheTtl]);
94
+ let resolvedQuery;
95
+ if (query) {
96
+ if (typeof query === "function") {
97
+ const queryResult = use(queryPromise);
98
+ if (queryResult) {
99
+ for (const [key, value] of Object.entries(queryResult)) {
100
+ if (value !== null && value !== void 0 && typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
101
+ console.warn(
102
+ `[useAgent] Query parameter "${key}" is an object and will be converted to "[object Object]". Query parameters should be string, number, boolean, or null.`
103
+ );
104
+ }
105
+ }
106
+ resolvedQuery = queryResult;
107
+ }
108
+ } else {
109
+ resolvedQuery = query;
110
+ }
111
+ }
112
+ useEffect(() => {
113
+ return () => {
114
+ if (queryPromise) {
115
+ decrementCacheEntry(cacheKey);
116
+ }
117
+ };
118
+ }, [cacheKey, queryPromise]);
22
119
  const agent = usePartySocket({
23
120
  party: agentNamespace,
24
121
  prefix: "agents",
25
122
  room: options.name || "default",
26
- ...options,
123
+ query: resolvedQuery,
124
+ ...restOptions,
27
125
  onMessage: (message) => {
28
126
  if (typeof message.data === "string") {
29
127
  let parsedMessage;
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/react.tsx"],"sourcesContent":["import type { PartySocket } from \"partysocket\";\nimport { usePartySocket } from \"partysocket/react\";\nimport { useCallback, useRef } from \"react\";\nimport type { Agent, MCPServersState, RPCRequest, RPCResponse } from \"./\";\nimport type { StreamOptions } from \"./client\";\nimport type { Method, RPCMethod } from \"./serializable\";\nimport { MessageType } from \"./ai-types\";\n\n/**\n * Convert a camelCase string to a kebab-case string\n * @param str The string to convert\n * @returns The kebab-case string\n */\nfunction camelCaseToKebabCase(str: string): string {\n // If string is all uppercase, convert to lowercase\n if (str === str.toUpperCase() && str !== str.toLowerCase()) {\n return str.toLowerCase().replace(/_/g, \"-\");\n }\n\n // Otherwise handle camelCase to kebab-case\n let kebabified = str.replace(\n /[A-Z]/g,\n (letter) => `-${letter.toLowerCase()}`\n );\n kebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n // Convert any remaining underscores to hyphens and remove trailing -'s\n return kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n\n/**\n * Options for the useAgent hook\n * @template State Type of the Agent's state\n */\nexport type UseAgentOptions<State = unknown> = Omit<\n Parameters<typeof usePartySocket>[0],\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n /** Called when the Agent's state is updated */\n onStateUpdate?: (state: State, source: \"server\" | \"client\") => void;\n /** Called when MCP server state is updated */\n onMcpUpdate?: (mcpServers: MCPServersState) => void;\n};\n\ntype AllOptional<T> = T extends [infer A, ...infer R]\n ? undefined extends A\n ? AllOptional<R>\n : false\n : true; // no params means optional by default\n\ntype RPCMethods<T> = {\n [K in keyof T as T[K] extends RPCMethod<T[K]> ? K : never]: RPCMethod<T[K]>;\n};\n\ntype OptionalParametersMethod<T extends RPCMethod> =\n AllOptional<Parameters<T>> extends true ? T : never;\n\n// all methods of the Agent, excluding the ones that are declared in the base Agent class\n// biome-ignore lint: suppressions/parse\ntype AgentMethods<T> = Omit<RPCMethods<T>, keyof Agent<any, any>>;\n\ntype OptionalAgentMethods<T> = {\n [K in keyof AgentMethods<T> as AgentMethods<T>[K] extends OptionalParametersMethod<\n AgentMethods<T>[K]\n >\n ? K\n : never]: OptionalParametersMethod<AgentMethods<T>[K]>;\n};\n\ntype RequiredAgentMethods<T> = Omit<\n AgentMethods<T>,\n keyof OptionalAgentMethods<T>\n>;\n\ntype AgentPromiseReturnType<T, K extends keyof AgentMethods<T>> =\n // biome-ignore lint: suppressions/parse\n ReturnType<AgentMethods<T>[K]> extends Promise<any>\n ? ReturnType<AgentMethods<T>[K]>\n : Promise<ReturnType<AgentMethods<T>[K]>>;\n\ntype OptionalArgsAgentMethodCall<AgentT> = <\n K extends keyof OptionalAgentMethods<AgentT>\n>(\n method: K,\n args?: Parameters<OptionalAgentMethods<AgentT>[K]>,\n streamOptions?: StreamOptions\n) => AgentPromiseReturnType<AgentT, K>;\n\ntype RequiredArgsAgentMethodCall<AgentT> = <\n K extends keyof RequiredAgentMethods<AgentT>\n>(\n method: K,\n args: Parameters<RequiredAgentMethods<AgentT>[K]>,\n streamOptions?: StreamOptions\n) => AgentPromiseReturnType<AgentT, K>;\n\ntype AgentMethodCall<AgentT> = OptionalArgsAgentMethodCall<AgentT> &\n RequiredArgsAgentMethodCall<AgentT>;\n\ntype UntypedAgentMethodCall = <T = unknown>(\n method: string,\n args?: unknown[],\n streamOptions?: StreamOptions\n) => Promise<T>;\n\ntype AgentStub<T> = {\n [K in keyof AgentMethods<T>]: (\n ...args: Parameters<AgentMethods<T>[K]>\n ) => AgentPromiseReturnType<AgentMethods<T>, K>;\n};\n\n// we neet to use Method instead of RPCMethod here for retro-compatibility\ntype UntypedAgentStub = Record<string, Method>;\n\n/**\n * React hook for connecting to an Agent\n * @template State Type of the Agent's state\n * @template Agent Type of the Agent\n * @param options Connection options\n * @returns WebSocket connection with setState and call methods\n */\nexport function useAgent<State = unknown>(\n options: UseAgentOptions<State>\n): PartySocket & {\n agent: string;\n name: string;\n setState: (state: State) => void;\n call: UntypedAgentMethodCall;\n stub: UntypedAgentStub;\n};\nexport function useAgent<\n AgentT extends {\n get state(): State;\n },\n State\n>(\n options: UseAgentOptions<State>\n): PartySocket & {\n agent: string;\n name: string;\n setState: (state: State) => void;\n call: AgentMethodCall<AgentT>;\n stub: AgentStub<AgentT>;\n};\nexport function useAgent<State>(\n options: UseAgentOptions<unknown>\n): PartySocket & {\n agent: string;\n name: string;\n setState: (state: State) => void;\n call: UntypedAgentMethodCall | AgentMethodCall<unknown>;\n stub: UntypedAgentStub;\n} {\n const agentNamespace = camelCaseToKebabCase(options.agent);\n // Keep track of pending RPC calls\n const pendingCallsRef = useRef(\n new Map<\n string,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n stream?: StreamOptions;\n }\n >()\n );\n\n // TODO: if options.query is a function, then use\n // \"use()\" to get the value and pass it\n // as a query parameter to usePartySocket\n const agent = usePartySocket({\n party: agentNamespace,\n prefix: \"agents\",\n room: options.name || \"default\",\n ...options,\n onMessage: (message) => {\n if (typeof message.data === \"string\") {\n let parsedMessage: Record<string, unknown>;\n try {\n parsedMessage = JSON.parse(message.data);\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return options.onMessage?.(message);\n }\n if (parsedMessage.type === MessageType.CF_AGENT_STATE) {\n options.onStateUpdate?.(parsedMessage.state as State, \"server\");\n return;\n }\n if (parsedMessage.type === MessageType.CF_AGENT_MCP_SERVERS) {\n options.onMcpUpdate?.(parsedMessage.mcp as MCPServersState);\n return;\n }\n if (parsedMessage.type === MessageType.RPC) {\n const response = parsedMessage as RPCResponse;\n const pending = pendingCallsRef.current.get(response.id);\n if (!pending) return;\n\n if (!response.success) {\n pending.reject(new Error(response.error));\n pendingCallsRef.current.delete(response.id);\n pending.stream?.onError?.(response.error);\n return;\n }\n\n // Handle streaming responses\n if (\"done\" in response) {\n if (response.done) {\n pending.resolve(response.result);\n pendingCallsRef.current.delete(response.id);\n pending.stream?.onDone?.(response.result);\n } else {\n pending.stream?.onChunk?.(response.result);\n }\n } else {\n // Non-streaming response\n pending.resolve(response.result);\n pendingCallsRef.current.delete(response.id);\n }\n return;\n }\n }\n options.onMessage?.(message);\n }\n }) as PartySocket & {\n agent: string;\n name: string;\n setState: (state: State) => void;\n call: UntypedAgentMethodCall;\n stub: UntypedAgentStub;\n };\n // Create the call method\n const call = useCallback(\n <T = unknown,>(\n method: string,\n args: unknown[] = [],\n streamOptions?: StreamOptions\n ): Promise<T> => {\n return new Promise((resolve, reject) => {\n const id = Math.random().toString(36).slice(2);\n pendingCallsRef.current.set(id, {\n reject,\n resolve: resolve as (value: unknown) => void,\n stream: streamOptions\n });\n\n const request: RPCRequest = {\n args,\n id,\n method,\n type: MessageType.RPC\n };\n\n agent.send(JSON.stringify(request));\n });\n },\n [agent]\n );\n\n agent.setState = (state: State) => {\n agent.send(JSON.stringify({ state, type: MessageType.CF_AGENT_STATE }));\n options.onStateUpdate?.(state, \"client\");\n };\n\n agent.call = call;\n agent.agent = agentNamespace;\n agent.name = options.name || \"default\";\n // biome-ignore lint: suppressions/parse\n agent.stub = new Proxy<any>(\n {},\n {\n get: (_target, method) => {\n return (...args: unknown[]) => {\n return call(method as string, args);\n };\n }\n }\n );\n\n // warn if agent isn't in lowercase\n if (agent.agent !== agent.agent.toLowerCase()) {\n console.warn(\n `Agent name: ${agent.agent} should probably be in lowercase. Received: ${agent.agent}`\n );\n }\n\n return agent;\n}\n"],"mappings":";;;AACA,SAAS,sBAAsB;AAC/B,SAAS,aAAa,cAAc;AAWpC,SAAS,qBAAqB,KAAqB;AAEjD,MAAI,QAAQ,IAAI,YAAY,KAAK,QAAQ,IAAI,YAAY,GAAG;AAC1D,WAAO,IAAI,YAAY,EAAE,QAAQ,MAAM,GAAG;AAAA,EAC5C;AAGA,MAAI,aAAa,IAAI;AAAA,IACnB;AAAA,IACA,CAAC,WAAW,IAAI,OAAO,YAAY,CAAC;AAAA,EACtC;AACA,eAAa,WAAW,WAAW,GAAG,IAAI,WAAW,MAAM,CAAC,IAAI;AAEhE,SAAO,WAAW,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,EAAE;AACvD;AAwHO,SAAS,SACd,SAOA;AACA,QAAM,iBAAiB,qBAAqB,QAAQ,KAAK;AAEzD,QAAM,kBAAkB;AAAA,IACtB,oBAAI,IAOF;AAAA,EACJ;AAKA,QAAM,QA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C,GACnB,kBACe;AACf,aAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,cAAM,KAAK,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC;AAC7C,wBAAgB,QAAQ,IAAI,IAAI;AAAA,UAC9B;AAAA,UACA;AAAA,UACA,QAAQ;AAAA,QACV,CAAC;AAED,cAAM,UAAsB;AAAA,UAC1B;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAEA,cAAM,KAAK,KAAK,UAAU,OAAO,CAAC;AAAA,MACpC,CAAC;AAAA,IACH;AAAA,IACA,CAAC,KAAK;AAAA,EACR;AAEA,QAAM,WAAW,CAAC,UAAiB;AACjC,UAAM,KAAK,KAAK,UAAU,EAAE,OAAO,4CAAiC,CAAC,CAAC;AACtE,YAAQ,gBAAgB,OAAO,QAAQ;AAAA,EACzC;AAEA,QAAM,OAAO;AACb,QAAM,QAAQ;AACd,QAAM,OAAO,QAAQ,QAAQ;AAE7B,QAAM,OAAO,IAAI;AAAA,IACf,CAAC;AAAA,IACD;AAAA,MACE,KAAK,CAAC,SAAS,WAAW;AACxB,eAAO,IAAI,SAAoB;AAC7B,iBAAO,KAAK,QAAkB,IAAI;AAAA,QACpC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAGA,MAAI,MAAM,UAAU,MAAM,MAAM,YAAY,GAAG;AAC7C,YAAQ;AAAA,MACN,eAAe,MAAM,KAAK,+CAA+C,MAAM,KAAK;AAAA,IACtF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/react.tsx"],"sourcesContent":["import type { PartySocket } from \"partysocket\";\nimport { usePartySocket } from \"partysocket/react\";\nimport { useCallback, useRef, use, useMemo, useEffect } from \"react\";\nimport type { Agent, MCPServersState, RPCRequest, RPCResponse } from \"./\";\nimport type { StreamOptions } from \"./client\";\nimport type { Method, RPCMethod } from \"./serializable\";\nimport { MessageType } from \"./ai-types\";\n\n/**\n * Convert a camelCase string to a kebab-case string\n * @param str The string to convert\n * @returns The kebab-case string\n */\nfunction camelCaseToKebabCase(str: string): string {\n // If string is all uppercase, convert to lowercase\n if (str === str.toUpperCase() && str !== str.toLowerCase()) {\n return str.toLowerCase().replace(/_/g, \"-\");\n }\n\n // Otherwise handle camelCase to kebab-case\n let kebabified = str.replace(\n /[A-Z]/g,\n (letter) => `-${letter.toLowerCase()}`\n );\n kebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n // Convert any remaining underscores to hyphens and remove trailing -'s\n return kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n\ntype QueryObject = Record<string, string | null>;\n\nconst queryCache = new Map<\n unknown[],\n {\n promise: Promise<QueryObject>;\n refCount: number;\n expiresAt: number;\n cacheTtl?: number;\n }\n>();\n\nfunction arraysEqual(a: unknown[], b: unknown[]): boolean {\n if (a === b) return true;\n if (a.length !== b.length) return false;\n\n for (let i = 0; i < a.length; i++) {\n if (!Object.is(a[i], b[i])) return false;\n }\n return true;\n}\n\nfunction findCacheEntry(\n targetKey: unknown[]\n): Promise<QueryObject> | undefined {\n for (const [existingKey, entry] of queryCache.entries()) {\n if (arraysEqual(existingKey, targetKey)) {\n // Check if entry has expired\n if (Date.now() > entry.expiresAt) {\n queryCache.delete(existingKey);\n return undefined;\n }\n entry.refCount++;\n return entry.promise;\n }\n }\n return undefined;\n}\n\nfunction setCacheEntry(\n key: unknown[],\n value: Promise<QueryObject>,\n cacheTtl?: number\n): void {\n // Remove any existing entry with matching members\n for (const [existingKey] of queryCache.entries()) {\n if (arraysEqual(existingKey, key)) {\n queryCache.delete(existingKey);\n break;\n }\n }\n\n const expiresAt = cacheTtl\n ? Date.now() + cacheTtl\n : Date.now() + 5 * 60 * 1000; // Default 5 minutes\n queryCache.set(key, { promise: value, refCount: 1, expiresAt, cacheTtl });\n}\n\nfunction decrementCacheEntry(targetKey: unknown[]): boolean {\n for (const [existingKey, entry] of queryCache.entries()) {\n if (arraysEqual(existingKey, targetKey)) {\n entry.refCount--;\n if (entry.refCount <= 0) {\n queryCache.delete(existingKey);\n }\n return true;\n }\n }\n return false;\n}\n\nfunction createCacheKey(\n agentNamespace: string,\n name: string | undefined,\n deps: unknown[]\n): unknown[] {\n return [agentNamespace, name || \"default\", ...deps];\n}\n\n/**\n * Options for the useAgent hook\n * @template State Type of the Agent's state\n */\nexport type UseAgentOptions<State = unknown> = Omit<\n Parameters<typeof usePartySocket>[0],\n \"party\" | \"room\" | \"query\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n /** Query parameters - can be static object or async function */\n query?: QueryObject | (() => Promise<QueryObject>);\n /** Dependencies for async query caching */\n queryDeps?: unknown[];\n /** Cache TTL in milliseconds for auth tokens/time-sensitive data */\n cacheTtl?: number;\n /** Called when the Agent's state is updated */\n onStateUpdate?: (state: State, source: \"server\" | \"client\") => void;\n /** Called when MCP server state is updated */\n onMcpUpdate?: (mcpServers: MCPServersState) => void;\n};\n\ntype AllOptional<T> = T extends [infer A, ...infer R]\n ? undefined extends A\n ? AllOptional<R>\n : false\n : true; // no params means optional by default\n\ntype RPCMethods<T> = {\n [K in keyof T as T[K] extends RPCMethod<T[K]> ? K : never]: RPCMethod<T[K]>;\n};\n\ntype OptionalParametersMethod<T extends RPCMethod> =\n AllOptional<Parameters<T>> extends true ? T : never;\n\n// all methods of the Agent, excluding the ones that are declared in the base Agent class\n// biome-ignore lint: suppressions/parse\ntype AgentMethods<T> = Omit<RPCMethods<T>, keyof Agent<any, any>>;\n\ntype OptionalAgentMethods<T> = {\n [K in keyof AgentMethods<T> as AgentMethods<T>[K] extends OptionalParametersMethod<\n AgentMethods<T>[K]\n >\n ? K\n : never]: OptionalParametersMethod<AgentMethods<T>[K]>;\n};\n\ntype RequiredAgentMethods<T> = Omit<\n AgentMethods<T>,\n keyof OptionalAgentMethods<T>\n>;\n\ntype AgentPromiseReturnType<T, K extends keyof AgentMethods<T>> =\n // biome-ignore lint: suppressions/parse\n ReturnType<AgentMethods<T>[K]> extends Promise<any>\n ? ReturnType<AgentMethods<T>[K]>\n : Promise<ReturnType<AgentMethods<T>[K]>>;\n\ntype OptionalArgsAgentMethodCall<AgentT> = <\n K extends keyof OptionalAgentMethods<AgentT>\n>(\n method: K,\n args?: Parameters<OptionalAgentMethods<AgentT>[K]>,\n streamOptions?: StreamOptions\n) => AgentPromiseReturnType<AgentT, K>;\n\ntype RequiredArgsAgentMethodCall<AgentT> = <\n K extends keyof RequiredAgentMethods<AgentT>\n>(\n method: K,\n args: Parameters<RequiredAgentMethods<AgentT>[K]>,\n streamOptions?: StreamOptions\n) => AgentPromiseReturnType<AgentT, K>;\n\ntype AgentMethodCall<AgentT> = OptionalArgsAgentMethodCall<AgentT> &\n RequiredArgsAgentMethodCall<AgentT>;\n\ntype UntypedAgentMethodCall = <T = unknown>(\n method: string,\n args?: unknown[],\n streamOptions?: StreamOptions\n) => Promise<T>;\n\ntype AgentStub<T> = {\n [K in keyof AgentMethods<T>]: (\n ...args: Parameters<AgentMethods<T>[K]>\n ) => AgentPromiseReturnType<AgentMethods<T>, K>;\n};\n\n// we neet to use Method instead of RPCMethod here for retro-compatibility\ntype UntypedAgentStub = Record<string, Method>;\n\n/**\n * React hook for connecting to an Agent\n */\nexport function useAgent<State = unknown>(\n options: UseAgentOptions<State>\n): PartySocket & {\n agent: string;\n name: string;\n setState: (state: State) => void;\n call: UntypedAgentMethodCall;\n stub: UntypedAgentStub;\n};\nexport function useAgent<\n AgentT extends {\n get state(): State;\n },\n State\n>(\n options: UseAgentOptions<State>\n): PartySocket & {\n agent: string;\n name: string;\n setState: (state: State) => void;\n call: AgentMethodCall<AgentT>;\n stub: AgentStub<AgentT>;\n};\nexport function useAgent<State>(\n options: UseAgentOptions<unknown>\n): PartySocket & {\n agent: string;\n name: string;\n setState: (state: State) => void;\n call: UntypedAgentMethodCall | AgentMethodCall<unknown>;\n stub: UntypedAgentStub;\n} {\n const agentNamespace = camelCaseToKebabCase(options.agent);\n const { query, queryDeps, cacheTtl, ...restOptions } = options;\n\n // Keep track of pending RPC calls\n const pendingCallsRef = useRef(\n new Map<\n string,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n stream?: StreamOptions;\n }\n >()\n );\n\n // Handle both sync and async query patterns\n const cacheKey = useMemo(() => {\n const deps = queryDeps || [];\n return createCacheKey(agentNamespace, options.name, deps);\n }, [agentNamespace, options.name, queryDeps]);\n\n const queryPromise = useMemo(() => {\n if (!query || typeof query !== \"function\") {\n return null;\n }\n\n const existingPromise = findCacheEntry(cacheKey);\n if (existingPromise) {\n return existingPromise;\n }\n\n const promise = query().catch((error) => {\n console.error(\n `[useAgent] Query failed for agent \"${options.agent}\":`,\n error\n );\n decrementCacheEntry(cacheKey); // Remove failed promise from cache\n throw error; // Re-throw for Suspense error boundary\n });\n\n setCacheEntry(cacheKey, promise, cacheTtl);\n\n return promise;\n }, [cacheKey, query, options.agent, cacheTtl]);\n\n let resolvedQuery: QueryObject | undefined;\n\n if (query) {\n if (typeof query === \"function\") {\n // Use React's use() to resolve the promise\n const queryResult = use(queryPromise!);\n\n // Check for non-primitive values and warn\n if (queryResult) {\n for (const [key, value] of Object.entries(queryResult)) {\n if (\n value !== null &&\n value !== undefined &&\n typeof value !== \"string\" &&\n typeof value !== \"number\" &&\n typeof value !== \"boolean\"\n ) {\n console.warn(\n `[useAgent] Query parameter \"${key}\" is an object and will be converted to \"[object Object]\". ` +\n \"Query parameters should be string, number, boolean, or null.\"\n );\n }\n }\n resolvedQuery = queryResult;\n }\n } else {\n // Sync query - use directly\n resolvedQuery = query;\n }\n }\n\n // Cleanup cache on unmount\n useEffect(() => {\n return () => {\n if (queryPromise) {\n decrementCacheEntry(cacheKey);\n }\n };\n }, [cacheKey, queryPromise]);\n\n const agent = usePartySocket({\n party: agentNamespace,\n prefix: \"agents\",\n room: options.name || \"default\",\n query: resolvedQuery,\n ...restOptions,\n onMessage: (message) => {\n if (typeof message.data === \"string\") {\n let parsedMessage: Record<string, unknown>;\n try {\n parsedMessage = JSON.parse(message.data);\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return options.onMessage?.(message);\n }\n if (parsedMessage.type === MessageType.CF_AGENT_STATE) {\n options.onStateUpdate?.(parsedMessage.state as State, \"server\");\n return;\n }\n if (parsedMessage.type === MessageType.CF_AGENT_MCP_SERVERS) {\n options.onMcpUpdate?.(parsedMessage.mcp as MCPServersState);\n return;\n }\n if (parsedMessage.type === MessageType.RPC) {\n const response = parsedMessage as RPCResponse;\n const pending = pendingCallsRef.current.get(response.id);\n if (!pending) return;\n\n if (!response.success) {\n pending.reject(new Error(response.error));\n pendingCallsRef.current.delete(response.id);\n pending.stream?.onError?.(response.error);\n return;\n }\n\n // Handle streaming responses\n if (\"done\" in response) {\n if (response.done) {\n pending.resolve(response.result);\n pendingCallsRef.current.delete(response.id);\n pending.stream?.onDone?.(response.result);\n } else {\n pending.stream?.onChunk?.(response.result);\n }\n } else {\n // Non-streaming response\n pending.resolve(response.result);\n pendingCallsRef.current.delete(response.id);\n }\n return;\n }\n }\n options.onMessage?.(message);\n }\n }) as PartySocket & {\n agent: string;\n name: string;\n setState: (state: State) => void;\n call: UntypedAgentMethodCall;\n stub: UntypedAgentStub;\n };\n // Create the call method\n const call = useCallback(\n <T = unknown,>(\n method: string,\n args: unknown[] = [],\n streamOptions?: StreamOptions\n ): Promise<T> => {\n return new Promise((resolve, reject) => {\n const id = Math.random().toString(36).slice(2);\n pendingCallsRef.current.set(id, {\n reject,\n resolve: resolve as (value: unknown) => void,\n stream: streamOptions\n });\n\n const request: RPCRequest = {\n args,\n id,\n method,\n type: MessageType.RPC\n };\n\n agent.send(JSON.stringify(request));\n });\n },\n [agent]\n );\n\n agent.setState = (state: State) => {\n agent.send(JSON.stringify({ state, type: MessageType.CF_AGENT_STATE }));\n options.onStateUpdate?.(state, \"client\");\n };\n\n agent.call = call;\n agent.agent = agentNamespace;\n agent.name = options.name || \"default\";\n // biome-ignore lint: suppressions/parse\n agent.stub = new Proxy<any>(\n {},\n {\n get: (_target, method) => {\n return (...args: unknown[]) => {\n return call(method as string, args);\n };\n }\n }\n );\n\n // warn if agent isn't in lowercase\n if (agent.agent !== agent.agent.toLowerCase()) {\n console.warn(\n `Agent name: ${agent.agent} should probably be in lowercase. Received: ${agent.agent}`\n );\n }\n\n return agent;\n}\n"],"mappings":";;;;AACA,SAAS,sBAAsB;AAC/B,SAAS,aAAa,QAAQ,KAAK,SAAS,iBAAiB;AAW7D,SAAS,qBAAqB,KAAqB;AAEjD,MAAI,QAAQ,IAAI,YAAY,KAAK,QAAQ,IAAI,YAAY,GAAG;AAC1D,WAAO,IAAI,YAAY,EAAE,QAAQ,MAAM,GAAG;AAAA,EAC5C;AAGA,MAAI,aAAa,IAAI;AAAA,IACnB;AAAA,IACA,CAAC,WAAW,IAAI,OAAO,YAAY,CAAC;AAAA,EACtC;AACA,eAAa,WAAW,WAAW,GAAG,IAAI,WAAW,MAAM,CAAC,IAAI;AAEhE,SAAO,WAAW,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,EAAE;AACvD;AAIA,IAAM,aAAa,oBAAI,IAQrB;AAEF,SAAS,YAAY,GAAc,GAAuB;AACxD,MAAI,MAAM,EAAG,QAAO;AACpB,MAAI,EAAE,WAAW,EAAE,OAAQ,QAAO;AAElC,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;AACjC,QAAI,CAAC,OAAO,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,EAAG,QAAO;AAAA,EACrC;AACA,SAAO;AACT;AAEA,SAAS,eACP,WACkC;AAClC,aAAW,CAAC,aAAa,KAAK,KAAK,WAAW,QAAQ,GAAG;AACvD,QAAI,YAAY,aAAa,SAAS,GAAG;AAEvC,UAAI,KAAK,IAAI,IAAI,MAAM,WAAW;AAChC,mBAAW,OAAO,WAAW;AAC7B,eAAO;AAAA,MACT;AACA,YAAM;AACN,aAAO,MAAM;AAAA,IACf;AAAA,EACF;A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,WAAW,CAAC,UAAiB;AACjC,UAAM,KAAK,KAAK,UAAU,EAAE,OAAO,4CAAiC,CAAC,CAAC;AACtE,YAAQ,gBAAgB,OAAO,QAAQ;AAAA,EACzC;AAEA,QAAM,OAAO;AACb,QAAM,QAAQ;AACd,QAAM,OAAO,QAAQ,QAAQ;AAE7B,QAAM,OAAO,IAAI;AAAA,IACf,CAAC;AAAA,IACD;AAAA,MACE,KAAK,CAAC,SAAS,WAAW;AACxB,eAAO,IAAI,SAAoB;AAC7B,iBAAO,KAAK,QAAkB,IAAI;AAAA,QACpC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAGA,MAAI,MAAM,UAAU,MAAM,MAAM,YAAY,GAAG;AAC7C,YAAQ;AAAA,MACN,eAAe,MAAM,KAAK,+CAA+C,MAAM,KAAK;AAAA,IACtF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1,7 +1,75 @@
1
1
  import { z } from "zod";
2
2
 
3
- type Schedule = z.infer<typeof unstable_scheduleSchema>;
3
+ /**
4
+ * Get the schedule prompt for a given event
5
+ * @param event - The event to get the schedule prompt for
6
+ * @returns The schedule prompt
7
+ */
8
+ declare function getSchedulePrompt(event: { date: Date }): string;
9
+ /**
10
+ * @deprecated this has been renamed to getSchedulePrompt, and unstable_getSchedulePrompt will be removed in the next major version
11
+ * @param event - The event to get the schedule prompt for
12
+ * @returns The schedule prompt
13
+ */
4
14
  declare function unstable_getSchedulePrompt(event: { date: Date }): string;
15
+ /**
16
+ * The schema for the schedule prompt
17
+ */
18
+ declare const scheduleSchema: z.ZodObject<
19
+ {
20
+ description: z.ZodString;
21
+ when: z.ZodObject<
22
+ {
23
+ cron: z.ZodOptional<z.ZodString>;
24
+ date: z.ZodOptional<z.ZodDate>;
25
+ delayInSeconds: z.ZodOptional<z.ZodNumber>;
26
+ type: z.ZodEnum<["scheduled", "delayed", "cron", "no-schedule"]>;
27
+ },
28
+ "strip",
29
+ z.ZodTypeAny,
30
+ {
31
+ type: "scheduled" | "delayed" | "cron" | "no-schedule";
32
+ date?: Date | undefined;
33
+ cron?: string | undefined;
34
+ delayInSeconds?: number | undefined;
35
+ },
36
+ {
37
+ type: "scheduled" | "delayed" | "cron" | "no-schedule";
38
+ date?: Date | undefined;
39
+ cron?: string | undefined;
40
+ delayInSeconds?: number | undefined;
41
+ }
42
+ >;
43
+ },
44
+ "strip",
45
+ z.ZodTypeAny,
46
+ {
47
+ description: string;
48
+ when: {
49
+ type: "scheduled" | "delayed" | "cron" | "no-schedule";
50
+ date?: Date | undefined;
51
+ cron?: string | undefined;
52
+ delayInSeconds?: number | undefined;
53
+ };
54
+ },
55
+ {
56
+ description: string;
57
+ when: {
58
+ type: "scheduled" | "delayed" | "cron" | "no-schedule";
59
+ date?: Date | undefined;
60
+ cron?: string | undefined;
61
+ delayInSeconds?: number | undefined;
62
+ };
63
+ }
64
+ >;
65
+ /**
66
+ * The type for the schedule prompt
67
+ */
68
+ type Schedule = z.infer<typeof scheduleSchema>;
69
+ /**
70
+ * @deprecated this has been renamed to scheduleSchema, and unstable_scheduleSchema will be removed in the next major version
71
+ * @returns The schedule schema
72
+ */
5
73
  declare const unstable_scheduleSchema: z.ZodObject<
6
74
  {
7
75
  description: z.ZodString;
@@ -50,4 +118,10 @@ declare const unstable_scheduleSchema: z.ZodObject<
50
118
  }
51
119
  >;
52
120
 
53
- export { type Schedule, unstable_getSchedulePrompt, unstable_scheduleSchema };
121
+ export {
122
+ type Schedule,
123
+ getSchedulePrompt,
124
+ scheduleSchema,
125
+ unstable_getSchedulePrompt,
126
+ unstable_scheduleSchema
127
+ };
package/dist/schedule.js CHANGED
@@ -1,6 +1,8 @@
1
+ import "./chunk-PR4QN5HX.js";
2
+
1
3
  // src/schedule.ts
2
4
  import { z } from "zod";
3
- function unstable_getSchedulePrompt(event) {
5
+ function getSchedulePrompt(event) {
4
6
  return `
5
7
  [Schedule Parser Component]
6
8
 
@@ -49,7 +51,17 @@ Example outputs:
49
51
  [End Schedule Parser Component]
50
52
  `;
51
53
  }
52
- var unstable_scheduleSchema = z.object({
54
+ var didWarnAboutUnstableGetSchedulePrompt = false;
55
+ function unstable_getSchedulePrompt(event) {
56
+ if (!didWarnAboutUnstableGetSchedulePrompt) {
57
+ didWarnAboutUnstableGetSchedulePrompt = true;
58
+ console.warn(
59
+ "unstable_getSchedulePrompt is deprecated, use getSchedulePrompt instead. unstable_getSchedulePrompt will be removed in the next major version."
60
+ );
61
+ }
62
+ return getSchedulePrompt(event);
63
+ }
64
+ var scheduleSchema = z.object({
53
65
  description: z.string().describe("A description of the task"),
54
66
  when: z.object({
55
67
  cron: z.string().optional().describe(
@@ -64,7 +76,10 @@ var unstable_scheduleSchema = z.object({
64
76
  type: z.enum(["scheduled", "delayed", "cron", "no-schedule"]).describe("The type of scheduling details")
65
77
  })
66
78
  });
79
+ var unstable_scheduleSchema = scheduleSchema;
67
80
  export {
81
+ getSchedulePrompt,
82
+ scheduleSchema,
68
83
  unstable_getSchedulePrompt,
69
84
  unstable_scheduleSchema
70
85
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schedule.ts"],"sourcesContent":["import { z } from \"zod\";\n\nexport type Schedule = z.infer<typeof unstable_scheduleSchema>;\n\nexport function unstable_getSchedulePrompt(event: { date: Date }) {\n return `\n[Schedule Parser Component]\n\nCurrent time: ${event.date.toUTCString()}\n\nThis component parses natural language scheduling requests into a structured format. It extracts:\n1. A clean task description (without timing information)\n2. Scheduling details in one of these formats:\n - scheduled: Specific date/time events\n - delayed: Relative time delays (in seconds)\n - cron: Recurring patterns\n - no-schedule: Tasks without timing\n\nRules:\n- Task descriptions should be clean and focused on the action\n- Use numbers (0-6) for days in cron patterns (0=Sunday)\n- For recurring tasks, use standard cron syntax\n- For relative times, convert to seconds\n- For specific dates, use the current time as reference\n\nExample outputs:\n{\n \"description\": \"meeting with team\",\n \"when\": {\n \"type\": \"scheduled\",\n \"date\": \"tomorrow at 14:00\"\n }\n}\n\n{\n \"description\": \"backup database\",\n \"when\": {\n \"type\": \"cron\",\n \"cron\": \"0 0 * * *\"\n }\n}\n\n{\n \"description\": \"send report\",\n \"when\": {\n \"type\": \"delayed\",\n \"delayInSeconds\": 1800\n }\n}\n\n[End Schedule Parser Component]\n`;\n}\n\nexport const unstable_scheduleSchema = z.object({\n description: z.string().describe(\"A description of the task\"),\n when: z.object({\n cron: z\n .string()\n .optional()\n .describe(\n \"execute task on a recurring interval specified as cron syntax (only use if the type is cron)\"\n ),\n date: z.coerce\n .date()\n .optional()\n .describe(\n \"execute task at the specified date and time (only use if the type is scheduled)\"\n ),\n delayInSeconds: z\n .number()\n .optional()\n .describe(\n \"execute task after a delay in seconds (only use if the type is delayed)\"\n ),\n type: z\n .enum([\"scheduled\", \"delayed\", \"cron\", \"no-schedule\"])\n .describe(\"The type of scheduling details\")\n })\n});\n"],"mappings":";AAAA,SAAS,SAAS;AAIX,SAAS,2BAA2B,OAAuB;AAChE,SAAO;AAAA;AAAA;AAAA,gBAGO,MAAM,KAAK,YAAY,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4CxC;AAEO,IAAM,0BAA0B,EAAE,OAAO;AAAA,EAC9C,aAAa,EAAE,OAAO,EAAE,SAAS,2BAA2B;AAAA,EAC5D,MAAM,EAAE,OAAO;AAAA,IACb,MAAM,EACH,OAAO,EACP,SAAS,EACT;AAAA,MACC;AAAA,IACF;AAAA,IACF,MAAM,EAAE,OACL,KAAK,EACL,SAAS,EACT;AAAA,MACC;AAAA,IACF;AAAA,IACF,gBAAgB,EACb,OAAO,EACP,SAAS,EACT;AAAA,MACC;AAAA,IACF;AAAA,IACF,MAAM,EACH,KAAK,CAAC,aAAa,WAAW,QAAQ,aAAa,CAAC,EACpD,SAAS,gCAAgC;AAAA,EAC9C,CAAC;AACH,CAAC;","names":[]}
1
+ {"version":3,"sources":["../src/schedule.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * Get the schedule prompt for a given event\n * @param event - The event to get the schedule prompt for\n * @returns The schedule prompt\n */\nexport function getSchedulePrompt(event: { date: Date }) {\n return `\n[Schedule Parser Component]\n\nCurrent time: ${event.date.toUTCString()}\n\nThis component parses natural language scheduling requests into a structured format. It extracts:\n1. A clean task description (without timing information)\n2. Scheduling details in one of these formats:\n - scheduled: Specific date/time events\n - delayed: Relative time delays (in seconds)\n - cron: Recurring patterns\n - no-schedule: Tasks without timing\n\nRules:\n- Task descriptions should be clean and focused on the action\n- Use numbers (0-6) for days in cron patterns (0=Sunday)\n- For recurring tasks, use standard cron syntax\n- For relative times, convert to seconds\n- For specific dates, use the current time as reference\n\nExample outputs:\n{\n \"description\": \"meeting with team\",\n \"when\": {\n \"type\": \"scheduled\",\n \"date\": \"tomorrow at 14:00\"\n }\n}\n\n{\n \"description\": \"backup database\",\n \"when\": {\n \"type\": \"cron\",\n \"cron\": \"0 0 * * *\"\n }\n}\n\n{\n \"description\": \"send report\",\n \"when\": {\n \"type\": \"delayed\",\n \"delayInSeconds\": 1800\n }\n}\n\n[End Schedule Parser Component]\n`;\n}\n\nlet didWarnAboutUnstableGetSchedulePrompt = false;\n\n/**\n * @deprecated this has been renamed to getSchedulePrompt, and unstable_getSchedulePrompt will be removed in the next major version\n * @param event - The event to get the schedule prompt for\n * @returns The schedule prompt\n */\nexport function unstable_getSchedulePrompt(event: { date: Date }) {\n if (!didWarnAboutUnstableGetSchedulePrompt) {\n didWarnAboutUnstableGetSchedulePrompt = true;\n console.warn(\n \"unstable_getSchedulePrompt is deprecated, use getSchedulePrompt instead. unstable_getSchedulePrompt will be removed in the next major version.\"\n );\n }\n return getSchedulePrompt(event);\n}\n\n/**\n * The schema for the schedule prompt\n */\nexport const scheduleSchema = z.object({\n description: z.string().describe(\"A description of the task\"),\n when: z.object({\n cron: z\n .string()\n .optional()\n .describe(\n \"execute task on a recurring interval specified as cron syntax (only use if the type is cron)\"\n ),\n date: z.coerce\n .date()\n .optional()\n .describe(\n \"execute task at the specified date and time (only use if the type is scheduled)\"\n ),\n delayInSeconds: z\n .number()\n .optional()\n .describe(\n \"execute task after a delay in seconds (only use if the type is delayed)\"\n ),\n type: z\n .enum([\"scheduled\", \"delayed\", \"cron\", \"no-schedule\"])\n .describe(\"The type of scheduling details\")\n })\n});\n\n/**\n * The type for the schedule prompt\n */\nexport type Schedule = z.infer<typeof scheduleSchema>;\n\n/**\n * @deprecated this has been renamed to scheduleSchema, and unstable_scheduleSchema will be removed in the next major version\n * @returns The schedule schema\n */\nexport const unstable_scheduleSchema = scheduleSchema;\n"],"mappings":";;;AAAA,SAAS,SAAS;AAOX,SAAS,kBAAkB,OAAuB;AACvD,SAAO;AAAA;AAAA;AAAA,gBAGO,MAAM,KAAK,YAAY,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4CxC;AAEA,IAAI,wCAAwC;AAOrC,SAAS,2BAA2B,OAAuB;AAChE,MAAI,CAAC,uCAAuC;AAC1C,4CAAwC;AACxC,YAAQ;AAAA,MACN;AAAA,IACF;AAAA,EACF;AACA,SAAO,kBAAkB,KAAK;AAChC;AAKO,IAAM,iBAAiB,EAAE,OAAO;AAAA,EACrC,aAAa,EAAE,OAAO,EAAE,SAAS,2BAA2B;AAAA,EAC5D,MAAM,EAAE,OAAO;AAAA,IACb,MAAM,EACH,OAAO,EACP,SAAS,EACT;AAAA,MACC;AAAA,IACF;AAAA,IACF,MAAM,EAAE,OACL,KAAK,EACL,SAAS,EACT;AAAA,MACC;AAAA,IACF;AAAA,IACF,gBAAgB,EACb,OAAO,EACP,SAAS,EACT;AAAA,MACC;AAAA,IACF;AAAA,IACF,MAAM,EACH,KAAK,CAAC,aAAa,WAAW,QAAQ,aAAa,CAAC,EACpD,SAAS,gCAAgC;AAAA,EAC9C,CAAC;AACH,CAAC;AAWM,IAAM,0BAA0B;","names":[]}