agents 0.0.0-e4a2352 → 0.0.0-e75ec71
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.
- package/README.md +129 -7
- package/dist/ai-chat-agent.d.ts +20 -20
- package/dist/ai-chat-agent.js +532 -260
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-chat-v5-migration-DBHGW4Hv.js +155 -0
- package/dist/ai-chat-v5-migration-DBHGW4Hv.js.map +1 -0
- package/dist/ai-chat-v5-migration.d.ts +155 -0
- package/dist/ai-chat-v5-migration.js +3 -0
- package/dist/ai-react.d.ts +73 -87
- package/dist/ai-react.js +261 -199
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types-B3aQaFv3.js +20 -0
- package/dist/ai-types-B3aQaFv3.js.map +1 -0
- package/dist/ai-types-D5YoPrBZ.d.ts +95 -0
- package/dist/ai-types.d.ts +6 -74
- package/dist/ai-types.js +3 -1
- package/dist/client-9Ld2_lnt.js +786 -0
- package/dist/client-9Ld2_lnt.js.map +1 -0
- package/dist/client-BfiZ3HQd.js +117 -0
- package/dist/client-BfiZ3HQd.js.map +1 -0
- package/dist/client-CbWe9FBd.d.ts +104 -0
- package/dist/client-CtM-Lpn3.d.ts +5314 -0
- package/dist/client.d.ts +11 -92
- package/dist/client.js +4 -11
- package/dist/codemode/ai.d.ts +27 -0
- package/dist/codemode/ai.js +151 -0
- package/dist/codemode/ai.js.map +1 -0
- package/dist/do-oauth-client-provider-CswoD5Lu.js +93 -0
- package/dist/do-oauth-client-provider-CswoD5Lu.js.map +1 -0
- package/dist/do-oauth-client-provider-DGc5pP0l.d.ts +55 -0
- package/dist/{index-BCJclX6q.d.ts → index-DgMq4s2H.d.ts} +100 -155
- package/dist/index-DhJCaDWd.d.ts +58 -0
- package/dist/index.d.ts +69 -40
- package/dist/index.js +7 -28
- package/dist/mcp/client.d.ts +4 -11
- package/dist/mcp/client.js +3 -9
- package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
- package/dist/mcp/do-oauth-client-provider.js +3 -7
- package/dist/mcp/index.d.ts +150 -99
- package/dist/mcp/index.js +1338 -901
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/x402.d.ts +34 -0
- package/dist/mcp/x402.js +194 -0
- package/dist/mcp/x402.js.map +1 -0
- package/dist/mcp-Dw5vDrY8.d.ts +61 -0
- package/dist/observability/index.d.ts +3 -14
- package/dist/observability/index.js +7 -10
- package/dist/react-Cr4RjXOP.d.ts +115 -0
- package/dist/react.d.ts +10 -121
- package/dist/react.js +183 -110
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +87 -10
- package/dist/schedule.js +46 -21
- package/dist/schedule.js.map +1 -1
- package/dist/serializable-CymX8ovI.d.ts +39 -0
- package/dist/serializable.d.ts +7 -32
- package/dist/serializable.js +1 -1
- package/dist/src-Dz0H9hSU.js +1200 -0
- package/dist/src-Dz0H9hSU.js.map +1 -0
- package/package.json +45 -11
- package/dist/ai-types.js.map +0 -1
- package/dist/chunk-HY7ZLHJB.js +0 -598
- package/dist/chunk-HY7ZLHJB.js.map +0 -1
- package/dist/chunk-JXN5WZFQ.js +0 -1287
- package/dist/chunk-JXN5WZFQ.js.map +0 -1
- package/dist/chunk-KUH345EY.js +0 -116
- package/dist/chunk-KUH345EY.js.map +0 -1
- package/dist/chunk-PVQZBKN7.js +0 -106
- package/dist/chunk-PVQZBKN7.js.map +0 -1
- package/dist/client-DgyzBU_8.d.ts +0 -4601
- package/dist/client.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/mcp/client.js.map +0 -1
- package/dist/mcp/do-oauth-client-provider.js.map +0 -1
- package/dist/observability/index.js.map +0 -1
- package/dist/serializable.js.map +0 -1
- package/src/index.ts +0 -1917
package/dist/react.js
CHANGED
|
@@ -1,116 +1,189 @@
|
|
|
1
|
-
|
|
1
|
+
import { t as MessageType } from "./ai-types-B3aQaFv3.js";
|
|
2
|
+
import { use, useCallback, useEffect, useMemo, useRef } from "react";
|
|
2
3
|
import { usePartySocket } from "partysocket/react";
|
|
3
|
-
|
|
4
|
+
|
|
5
|
+
//#region src/react.tsx
|
|
6
|
+
/**
|
|
7
|
+
* Convert a camelCase string to a kebab-case string
|
|
8
|
+
* @param str The string to convert
|
|
9
|
+
* @returns The kebab-case string
|
|
10
|
+
*/
|
|
4
11
|
function camelCaseToKebabCase(str) {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
if (str === str.toUpperCase() && str !== str.toLowerCase()) return str.toLowerCase().replace(/_/g, "-");
|
|
13
|
+
let kebabified = str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
14
|
+
kebabified = kebabified.startsWith("-") ? kebabified.slice(1) : kebabified;
|
|
15
|
+
return kebabified.replace(/_/g, "-").replace(/-$/, "");
|
|
16
|
+
}
|
|
17
|
+
const queryCache = /* @__PURE__ */ new Map();
|
|
18
|
+
function arraysEqual(a, b) {
|
|
19
|
+
if (a === b) return true;
|
|
20
|
+
if (a.length !== b.length) return false;
|
|
21
|
+
for (let i = 0; i < a.length; i++) if (!Object.is(a[i], b[i])) return false;
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
24
|
+
function findCacheEntry(targetKey) {
|
|
25
|
+
for (const [existingKey, entry] of queryCache.entries()) if (arraysEqual(existingKey, targetKey)) {
|
|
26
|
+
if (Date.now() > entry.expiresAt) {
|
|
27
|
+
queryCache.delete(existingKey);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
entry.refCount++;
|
|
31
|
+
return entry.promise;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function setCacheEntry(key, value, cacheTtl) {
|
|
35
|
+
for (const [existingKey] of queryCache.entries()) if (arraysEqual(existingKey, key)) {
|
|
36
|
+
queryCache.delete(existingKey);
|
|
37
|
+
break;
|
|
38
|
+
}
|
|
39
|
+
const expiresAt = cacheTtl ? Date.now() + cacheTtl : Date.now() + 300 * 1e3;
|
|
40
|
+
queryCache.set(key, {
|
|
41
|
+
promise: value,
|
|
42
|
+
refCount: 1,
|
|
43
|
+
expiresAt,
|
|
44
|
+
cacheTtl
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
function decrementCacheEntry(targetKey) {
|
|
48
|
+
for (const [existingKey, entry] of queryCache.entries()) if (arraysEqual(existingKey, targetKey)) {
|
|
49
|
+
entry.refCount--;
|
|
50
|
+
if (entry.refCount <= 0) queryCache.delete(existingKey);
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
function createCacheKey(agentNamespace, name, deps) {
|
|
56
|
+
return [
|
|
57
|
+
agentNamespace,
|
|
58
|
+
name || "default",
|
|
59
|
+
...deps
|
|
60
|
+
];
|
|
14
61
|
}
|
|
15
62
|
function useAgent(options) {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
63
|
+
const agentNamespace = camelCaseToKebabCase(options.agent);
|
|
64
|
+
const { query, queryDeps, cacheTtl,...restOptions } = options;
|
|
65
|
+
const pendingCallsRef = useRef(/* @__PURE__ */ new Map());
|
|
66
|
+
const cacheKey = useMemo(() => {
|
|
67
|
+
const deps = queryDeps || [];
|
|
68
|
+
return createCacheKey(agentNamespace, options.name, deps);
|
|
69
|
+
}, [
|
|
70
|
+
agentNamespace,
|
|
71
|
+
options.name,
|
|
72
|
+
queryDeps
|
|
73
|
+
]);
|
|
74
|
+
const queryPromise = useMemo(() => {
|
|
75
|
+
if (!query || typeof query !== "function") return null;
|
|
76
|
+
const existingPromise = findCacheEntry(cacheKey);
|
|
77
|
+
if (existingPromise) return existingPromise;
|
|
78
|
+
const promise = query().catch((error) => {
|
|
79
|
+
console.error(`[useAgent] Query failed for agent "${options.agent}":`, error);
|
|
80
|
+
decrementCacheEntry(cacheKey);
|
|
81
|
+
throw error;
|
|
82
|
+
});
|
|
83
|
+
setCacheEntry(cacheKey, promise, cacheTtl);
|
|
84
|
+
return promise;
|
|
85
|
+
}, [
|
|
86
|
+
cacheKey,
|
|
87
|
+
query,
|
|
88
|
+
options.agent,
|
|
89
|
+
cacheTtl
|
|
90
|
+
]);
|
|
91
|
+
let resolvedQuery;
|
|
92
|
+
if (query) if (typeof query === "function") {
|
|
93
|
+
const queryResult = use(queryPromise);
|
|
94
|
+
if (queryResult) {
|
|
95
|
+
for (const [key, value] of Object.entries(queryResult)) if (value !== null && value !== void 0 && typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") console.warn(`[useAgent] Query parameter "${key}" is an object and will be converted to "[object Object]". Query parameters should be string, number, boolean, or null.`);
|
|
96
|
+
resolvedQuery = queryResult;
|
|
97
|
+
}
|
|
98
|
+
} else resolvedQuery = query;
|
|
99
|
+
useEffect(() => {
|
|
100
|
+
return () => {
|
|
101
|
+
if (queryPromise) decrementCacheEntry(cacheKey);
|
|
102
|
+
};
|
|
103
|
+
}, [cacheKey, queryPromise]);
|
|
104
|
+
const agent = usePartySocket({
|
|
105
|
+
party: agentNamespace,
|
|
106
|
+
prefix: "agents",
|
|
107
|
+
room: options.name || "default",
|
|
108
|
+
query: resolvedQuery,
|
|
109
|
+
...restOptions,
|
|
110
|
+
onMessage: (message) => {
|
|
111
|
+
if (typeof message.data === "string") {
|
|
112
|
+
let parsedMessage;
|
|
113
|
+
try {
|
|
114
|
+
parsedMessage = JSON.parse(message.data);
|
|
115
|
+
} catch (_error) {
|
|
116
|
+
return options.onMessage?.(message);
|
|
117
|
+
}
|
|
118
|
+
if (parsedMessage.type === MessageType.CF_AGENT_STATE) {
|
|
119
|
+
options.onStateUpdate?.(parsedMessage.state, "server");
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (parsedMessage.type === MessageType.CF_AGENT_MCP_SERVERS) {
|
|
123
|
+
options.onMcpUpdate?.(parsedMessage.mcp);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (parsedMessage.type === MessageType.RPC) {
|
|
127
|
+
const response = parsedMessage;
|
|
128
|
+
const pending = pendingCallsRef.current.get(response.id);
|
|
129
|
+
if (!pending) return;
|
|
130
|
+
if (!response.success) {
|
|
131
|
+
pending.reject(new Error(response.error));
|
|
132
|
+
pendingCallsRef.current.delete(response.id);
|
|
133
|
+
pending.stream?.onError?.(response.error);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if ("done" in response) if (response.done) {
|
|
137
|
+
pending.resolve(response.result);
|
|
138
|
+
pendingCallsRef.current.delete(response.id);
|
|
139
|
+
pending.stream?.onDone?.(response.result);
|
|
140
|
+
} else pending.stream?.onChunk?.(response.result);
|
|
141
|
+
else {
|
|
142
|
+
pending.resolve(response.result);
|
|
143
|
+
pendingCallsRef.current.delete(response.id);
|
|
144
|
+
}
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
options.onMessage?.(message);
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
const call = useCallback((method, args = [], streamOptions) => {
|
|
152
|
+
return new Promise((resolve, reject) => {
|
|
153
|
+
const id = Math.random().toString(36).slice(2);
|
|
154
|
+
pendingCallsRef.current.set(id, {
|
|
155
|
+
reject,
|
|
156
|
+
resolve,
|
|
157
|
+
stream: streamOptions
|
|
158
|
+
});
|
|
159
|
+
const request = {
|
|
160
|
+
args,
|
|
161
|
+
id,
|
|
162
|
+
method,
|
|
163
|
+
type: MessageType.RPC
|
|
164
|
+
};
|
|
165
|
+
agent.send(JSON.stringify(request));
|
|
166
|
+
});
|
|
167
|
+
}, [agent]);
|
|
168
|
+
agent.setState = (state) => {
|
|
169
|
+
agent.send(JSON.stringify({
|
|
170
|
+
state,
|
|
171
|
+
type: MessageType.CF_AGENT_STATE
|
|
172
|
+
}));
|
|
173
|
+
options.onStateUpdate?.(state, "client");
|
|
174
|
+
};
|
|
175
|
+
agent.call = call;
|
|
176
|
+
agent.agent = agentNamespace;
|
|
177
|
+
agent.name = options.name || "default";
|
|
178
|
+
agent.stub = new Proxy({}, { get: (_target, method) => {
|
|
179
|
+
return (...args) => {
|
|
180
|
+
return call(method, args);
|
|
181
|
+
};
|
|
182
|
+
} });
|
|
183
|
+
if (agent.agent !== agent.agent.toLowerCase()) console.warn(`Agent name: ${agent.agent} should probably be in lowercase. Received: ${agent.agent}`);
|
|
184
|
+
return agent;
|
|
112
185
|
}
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
};
|
|
186
|
+
|
|
187
|
+
//#endregion
|
|
188
|
+
export { useAgent };
|
|
116
189
|
//# sourceMappingURL=react.js.map
|
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\";\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 === \"cf_agent_state\") {\n options.onStateUpdate?.(parsedMessage.state as State, \"server\");\n return;\n }\n if (parsedMessage.type === \"cf_agent_mcp_servers\") {\n options.onMcpUpdate?.(parsedMessage.mcp as MCPServersState);\n return;\n }\n if (parsedMessage.type === \"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: \"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: \"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;AAUpC,SAAS,qB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O,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,"file":"react.js","names":["resolvedQuery: QueryObject | undefined","parsedMessage: Record<string, unknown>","request: RPCRequest"],"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":";;;;;;;;;;AAaA,SAAS,qBAAqB,KAAqB;AAEjD,KAAI,QAAQ,IAAI,aAAa,IAAI,QAAQ,IAAI,aAAa,CACxD,QAAO,IAAI,aAAa,CAAC,QAAQ,MAAM,IAAI;CAI7C,IAAI,aAAa,IAAI,QACnB,WACC,WAAW,IAAI,OAAO,aAAa,GACrC;AACD,cAAa,WAAW,WAAW,IAAI,GAAG,WAAW,MAAM,EAAE,GAAG;AAEhE,QAAO,WAAW,QAAQ,MAAM,IAAI,CAAC,QAAQ,MAAM,GAAG;;AAKxD,MAAM,6BAAa,IAAI,KAQpB;AAEH,SAAS,YAAY,GAAc,G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M,OAAO,IAAI,MACf,EAAE,EACF,EACE,MAAM,SAAS,WAAW;AACxB,UAAQ,GAAG,SAAoB;AAC7B,UAAO,KAAK,QAAkB,KAAK;;IAGxC,CACF;AAGD,KAAI,MAAM,UAAU,MAAM,MAAM,aAAa,CAC3C,SAAQ,KACN,eAAe,MAAM,MAAM,8CAA8C,MAAM,QAChF;AAGH,QAAO"}
|
package/dist/schedule.d.ts
CHANGED
|
@@ -1,8 +1,23 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
//#region src/schedule.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Get the schedule prompt for a given event
|
|
7
|
+
* @param event - The event to get the schedule prompt for
|
|
8
|
+
* @returns The schedule prompt
|
|
9
|
+
*/
|
|
10
|
+
declare function getSchedulePrompt(event: { date: Date }): string;
|
|
11
|
+
/**
|
|
12
|
+
* @deprecated this has been renamed to getSchedulePrompt, and unstable_getSchedulePrompt will be removed in the next major version
|
|
13
|
+
* @param event - The event to get the schedule prompt for
|
|
14
|
+
* @returns The schedule prompt
|
|
15
|
+
*/
|
|
4
16
|
declare function unstable_getSchedulePrompt(event: { date: Date }): string;
|
|
5
|
-
|
|
17
|
+
/**
|
|
18
|
+
* The schema for the schedule prompt
|
|
19
|
+
*/
|
|
20
|
+
declare const scheduleSchema: z.ZodObject<
|
|
6
21
|
{
|
|
7
22
|
description: z.ZodString;
|
|
8
23
|
when: z.ZodObject<
|
|
@@ -15,16 +30,16 @@ declare const unstable_scheduleSchema: z.ZodObject<
|
|
|
15
30
|
"strip",
|
|
16
31
|
z.ZodTypeAny,
|
|
17
32
|
{
|
|
18
|
-
type: "
|
|
33
|
+
type: "cron" | "scheduled" | "delayed" | "no-schedule";
|
|
19
34
|
date?: Date | undefined;
|
|
20
|
-
delayInSeconds?: number | undefined;
|
|
21
35
|
cron?: string | undefined;
|
|
36
|
+
delayInSeconds?: number | undefined;
|
|
22
37
|
},
|
|
23
38
|
{
|
|
24
|
-
type: "
|
|
39
|
+
type: "cron" | "scheduled" | "delayed" | "no-schedule";
|
|
25
40
|
date?: Date | undefined;
|
|
26
|
-
delayInSeconds?: number | undefined;
|
|
27
41
|
cron?: string | undefined;
|
|
42
|
+
delayInSeconds?: number | undefined;
|
|
28
43
|
}
|
|
29
44
|
>;
|
|
30
45
|
},
|
|
@@ -33,21 +48,83 @@ declare const unstable_scheduleSchema: z.ZodObject<
|
|
|
33
48
|
{
|
|
34
49
|
description: string;
|
|
35
50
|
when: {
|
|
36
|
-
type: "
|
|
51
|
+
type: "cron" | "scheduled" | "delayed" | "no-schedule";
|
|
37
52
|
date?: Date | undefined;
|
|
53
|
+
cron?: string | undefined;
|
|
38
54
|
delayInSeconds?: number | undefined;
|
|
55
|
+
};
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
description: string;
|
|
59
|
+
when: {
|
|
60
|
+
type: "cron" | "scheduled" | "delayed" | "no-schedule";
|
|
61
|
+
date?: Date | undefined;
|
|
39
62
|
cron?: string | undefined;
|
|
63
|
+
delayInSeconds?: number | undefined;
|
|
40
64
|
};
|
|
65
|
+
}
|
|
66
|
+
>;
|
|
67
|
+
/**
|
|
68
|
+
* The type for the schedule prompt
|
|
69
|
+
*/
|
|
70
|
+
type Schedule = z.infer<typeof scheduleSchema>;
|
|
71
|
+
/**
|
|
72
|
+
* @deprecated this has been renamed to scheduleSchema, and unstable_scheduleSchema will be removed in the next major version
|
|
73
|
+
* @returns The schedule schema
|
|
74
|
+
*/
|
|
75
|
+
declare const unstable_scheduleSchema: z.ZodObject<
|
|
76
|
+
{
|
|
77
|
+
description: z.ZodString;
|
|
78
|
+
when: z.ZodObject<
|
|
79
|
+
{
|
|
80
|
+
cron: z.ZodOptional<z.ZodString>;
|
|
81
|
+
date: z.ZodOptional<z.ZodDate>;
|
|
82
|
+
delayInSeconds: z.ZodOptional<z.ZodNumber>;
|
|
83
|
+
type: z.ZodEnum<["scheduled", "delayed", "cron", "no-schedule"]>;
|
|
84
|
+
},
|
|
85
|
+
"strip",
|
|
86
|
+
z.ZodTypeAny,
|
|
87
|
+
{
|
|
88
|
+
type: "cron" | "scheduled" | "delayed" | "no-schedule";
|
|
89
|
+
date?: Date | undefined;
|
|
90
|
+
cron?: string | undefined;
|
|
91
|
+
delayInSeconds?: number | undefined;
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
type: "cron" | "scheduled" | "delayed" | "no-schedule";
|
|
95
|
+
date?: Date | undefined;
|
|
96
|
+
cron?: string | undefined;
|
|
97
|
+
delayInSeconds?: number | undefined;
|
|
98
|
+
}
|
|
99
|
+
>;
|
|
41
100
|
},
|
|
101
|
+
"strip",
|
|
102
|
+
z.ZodTypeAny,
|
|
42
103
|
{
|
|
43
104
|
description: string;
|
|
44
105
|
when: {
|
|
45
|
-
type: "
|
|
106
|
+
type: "cron" | "scheduled" | "delayed" | "no-schedule";
|
|
46
107
|
date?: Date | undefined;
|
|
108
|
+
cron?: string | undefined;
|
|
47
109
|
delayInSeconds?: number | undefined;
|
|
110
|
+
};
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
description: string;
|
|
114
|
+
when: {
|
|
115
|
+
type: "cron" | "scheduled" | "delayed" | "no-schedule";
|
|
116
|
+
date?: Date | undefined;
|
|
48
117
|
cron?: string | undefined;
|
|
118
|
+
delayInSeconds?: number | undefined;
|
|
49
119
|
};
|
|
50
120
|
}
|
|
51
121
|
>;
|
|
52
|
-
|
|
53
|
-
export {
|
|
122
|
+
//#endregion
|
|
123
|
+
export {
|
|
124
|
+
Schedule,
|
|
125
|
+
getSchedulePrompt,
|
|
126
|
+
scheduleSchema,
|
|
127
|
+
unstable_getSchedulePrompt,
|
|
128
|
+
unstable_scheduleSchema
|
|
129
|
+
};
|
|
130
|
+
//# sourceMappingURL=schedule.d.ts.map
|
package/dist/schedule.js
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
|
-
// src/schedule.ts
|
|
2
1
|
import { z } from "zod";
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
|
|
3
|
+
//#region src/schedule.ts
|
|
4
|
+
/**
|
|
5
|
+
* Get the schedule prompt for a given event
|
|
6
|
+
* @param event - The event to get the schedule prompt for
|
|
7
|
+
* @returns The schedule prompt
|
|
8
|
+
*/
|
|
9
|
+
function getSchedulePrompt(event) {
|
|
10
|
+
return `
|
|
5
11
|
[Schedule Parser Component]
|
|
6
12
|
|
|
7
13
|
Current time: ${event.date.toUTCString()}
|
|
@@ -49,23 +55,42 @@ Example outputs:
|
|
|
49
55
|
[End Schedule Parser Component]
|
|
50
56
|
`;
|
|
51
57
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
58
|
+
let didWarnAboutUnstableGetSchedulePrompt = false;
|
|
59
|
+
/**
|
|
60
|
+
* @deprecated this has been renamed to getSchedulePrompt, and unstable_getSchedulePrompt will be removed in the next major version
|
|
61
|
+
* @param event - The event to get the schedule prompt for
|
|
62
|
+
* @returns The schedule prompt
|
|
63
|
+
*/
|
|
64
|
+
function unstable_getSchedulePrompt(event) {
|
|
65
|
+
if (!didWarnAboutUnstableGetSchedulePrompt) {
|
|
66
|
+
didWarnAboutUnstableGetSchedulePrompt = true;
|
|
67
|
+
console.warn("unstable_getSchedulePrompt is deprecated, use getSchedulePrompt instead. unstable_getSchedulePrompt will be removed in the next major version.");
|
|
68
|
+
}
|
|
69
|
+
return getSchedulePrompt(event);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The schema for the schedule prompt
|
|
73
|
+
*/
|
|
74
|
+
const scheduleSchema = z.object({
|
|
75
|
+
description: z.string().describe("A description of the task"),
|
|
76
|
+
when: z.object({
|
|
77
|
+
cron: z.string().optional().describe("execute task on a recurring interval specified as cron syntax (only use if the type is cron)"),
|
|
78
|
+
date: z.coerce.date().optional().describe("execute task at the specified date and time (only use if the type is scheduled)"),
|
|
79
|
+
delayInSeconds: z.number().optional().describe("execute task after a delay in seconds (only use if the type is delayed)"),
|
|
80
|
+
type: z.enum([
|
|
81
|
+
"scheduled",
|
|
82
|
+
"delayed",
|
|
83
|
+
"cron",
|
|
84
|
+
"no-schedule"
|
|
85
|
+
]).describe("The type of scheduling details")
|
|
86
|
+
})
|
|
66
87
|
});
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
88
|
+
/**
|
|
89
|
+
* @deprecated this has been renamed to scheduleSchema, and unstable_scheduleSchema will be removed in the next major version
|
|
90
|
+
* @returns The schedule schema
|
|
91
|
+
*/
|
|
92
|
+
const unstable_scheduleSchema = scheduleSchema;
|
|
93
|
+
|
|
94
|
+
//#endregion
|
|
95
|
+
export { getSchedulePrompt, scheduleSchema, unstable_getSchedulePrompt, unstable_scheduleSchema };
|
|
71
96
|
//# sourceMappingURL=schedule.js.map
|
package/dist/schedule.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schedule.ts"],"sourcesContent":["import { z } from \"zod\";\n\
|
|
1
|
+
{"version":3,"file":"schedule.js","names":[],"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":";;;;;;;;AAOA,SAAgB,kBAAkB,OAAuB;AACvD,QAAO;;;gBAGO,MAAM,KAAK,aAAa,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CzC,IAAI,wCAAwC;;;;;;AAO5C,SAAgB,2BAA2B,OAAuB;AAChE,KAAI,CAAC,uCAAuC;AAC1C,0CAAwC;AACxC,UAAQ,KACN,iJACD;;AAEH,QAAO,kBAAkB,MAAM;;;;;AAMjC,MAAa,iBAAiB,EAAE,OAAO;CACrC,aAAa,EAAE,QAAQ,CAAC,SAAS,4BAA4B;CAC7D,MAAM,EAAE,OAAO;EACb,MAAM,EACH,QAAQ,CACR,UAAU,CACV,SACC,+FACD;EACH,MAAM,EAAE,OACL,MAAM,CACN,UAAU,CACV,SACC,kFACD;EACH,gBAAgB,EACb,QAAQ,CACR,UAAU,CACV,SACC,0EACD;EACH,MAAM,EACH,KAAK;GAAC;GAAa;GAAW;GAAQ;GAAc,CAAC,CACrD,SAAS,iCAAiC;EAC9C,CAAC;CACH,CAAC;;;;;AAWF,MAAa,0BAA0B"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
//#region src/serializable.d.ts
|
|
2
|
+
type SerializableValue =
|
|
3
|
+
| undefined
|
|
4
|
+
| null
|
|
5
|
+
| string
|
|
6
|
+
| number
|
|
7
|
+
| boolean
|
|
8
|
+
| {
|
|
9
|
+
[key: string]: SerializableValue;
|
|
10
|
+
}
|
|
11
|
+
| SerializableValue[];
|
|
12
|
+
type SerializableReturnValue =
|
|
13
|
+
| SerializableValue
|
|
14
|
+
| void
|
|
15
|
+
| Promise<SerializableValue>
|
|
16
|
+
| Promise<void>;
|
|
17
|
+
type AllSerializableValues<A$1> = A$1 extends [infer First, ...infer Rest]
|
|
18
|
+
? First extends SerializableValue
|
|
19
|
+
? AllSerializableValues<Rest>
|
|
20
|
+
: false
|
|
21
|
+
: true;
|
|
22
|
+
type Method = (...args: any[]) => any;
|
|
23
|
+
type RPCMethod<T = Method> = T extends Method
|
|
24
|
+
? T extends (...arg: infer A) => infer R
|
|
25
|
+
? AllSerializableValues<A> extends true
|
|
26
|
+
? R extends SerializableReturnValue
|
|
27
|
+
? T
|
|
28
|
+
: never
|
|
29
|
+
: never
|
|
30
|
+
: never
|
|
31
|
+
: never;
|
|
32
|
+
//#endregion
|
|
33
|
+
export {
|
|
34
|
+
SerializableValue as i,
|
|
35
|
+
RPCMethod as n,
|
|
36
|
+
SerializableReturnValue as r,
|
|
37
|
+
Method as t
|
|
38
|
+
};
|
|
39
|
+
//# sourceMappingURL=serializable-CymX8ovI.d.ts.map
|