agents 0.0.0-bcae0ba → 0.0.0-d127c8f
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 +2 -6
- package/dist/ai-chat-agent.d.ts +1 -4
- package/dist/ai-chat-agent.js +73 -75
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +5 -3
- package/dist/ai-react.js.map +1 -1
- package/dist/{chunk-PDF5WEP4.js → chunk-X6BBKLSC.js} +69 -43
- package/dist/chunk-X6BBKLSC.js.map +1 -0
- package/dist/index.d.ts +2 -6
- package/dist/index.js +1 -1
- package/dist/mcp.d.ts +58 -0
- package/dist/mcp.js +945 -0
- package/dist/mcp.js.map +1 -0
- package/package.json +12 -4
- package/src/index.ts +59 -23
- package/dist/chunk-PDF5WEP4.js.map +0 -1
package/README.md
CHANGED
|
@@ -316,18 +316,14 @@ Create meaningful conversations with intelligence:
|
|
|
316
316
|
|
|
317
317
|
```ts
|
|
318
318
|
import { AIChatAgent } from "agents/ai-chat-agent";
|
|
319
|
-
import {
|
|
319
|
+
import { openai } from "@ai-sdk/openai";
|
|
320
320
|
|
|
321
321
|
export class DialogueAgent extends AIChatAgent {
|
|
322
322
|
async onChatMessage(onFinish) {
|
|
323
323
|
return createDataStreamResponse({
|
|
324
324
|
execute: async (dataStream) => {
|
|
325
|
-
const ai = createOpenAI({
|
|
326
|
-
apiKey: this.env.OPENAI_API_KEY,
|
|
327
|
-
});
|
|
328
|
-
|
|
329
325
|
const stream = streamText({
|
|
330
|
-
model:
|
|
326
|
+
model: openai("gpt-4o"),
|
|
331
327
|
messages: this.messages,
|
|
332
328
|
onFinish, // call onFinish so that messages get saved
|
|
333
329
|
});
|
package/dist/ai-chat-agent.d.ts
CHANGED
|
@@ -11,11 +11,10 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
|
|
|
11
11
|
Env,
|
|
12
12
|
State
|
|
13
13
|
> {
|
|
14
|
+
#private;
|
|
14
15
|
/** Array of chat messages for the current conversation */
|
|
15
16
|
messages: Message[];
|
|
16
17
|
constructor(ctx: AgentContext, env: Env);
|
|
17
|
-
private sendChatMessage;
|
|
18
|
-
private broadcastChatMessage;
|
|
19
18
|
onMessage(connection: Connection, message: WSMessage): Promise<void>;
|
|
20
19
|
onRequest(request: Request): Promise<Response>;
|
|
21
20
|
/**
|
|
@@ -31,8 +30,6 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
|
|
|
31
30
|
* @param messages Chat messages to save
|
|
32
31
|
*/
|
|
33
32
|
saveMessages(messages: Message[]): Promise<void>;
|
|
34
|
-
private persistMessages;
|
|
35
|
-
private reply;
|
|
36
33
|
}
|
|
37
34
|
|
|
38
35
|
export { AIChatAgent };
|
package/dist/ai-chat-agent.js
CHANGED
|
@@ -1,14 +1,19 @@
|
|
|
1
1
|
import {
|
|
2
2
|
Agent
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import
|
|
3
|
+
} from "./chunk-X6BBKLSC.js";
|
|
4
|
+
import {
|
|
5
|
+
__privateAdd,
|
|
6
|
+
__privateMethod
|
|
7
|
+
} from "./chunk-HMLY7DHA.js";
|
|
5
8
|
|
|
6
9
|
// src/ai-chat-agent.ts
|
|
7
10
|
import { appendResponseMessages } from "ai";
|
|
8
11
|
var decoder = new TextDecoder();
|
|
12
|
+
var _AIChatAgent_instances, broadcastChatMessage_fn, tryCatch_fn, persistMessages_fn, reply_fn;
|
|
9
13
|
var AIChatAgent = class extends Agent {
|
|
10
14
|
constructor(ctx, env) {
|
|
11
15
|
super(ctx, env);
|
|
16
|
+
__privateAdd(this, _AIChatAgent_instances);
|
|
12
17
|
this.sql`create table if not exists cf_ai_chat_agent_messages (
|
|
13
18
|
id text primary key,
|
|
14
19
|
message text not null,
|
|
@@ -18,18 +23,6 @@ var AIChatAgent = class extends Agent {
|
|
|
18
23
|
return JSON.parse(row.message);
|
|
19
24
|
});
|
|
20
25
|
}
|
|
21
|
-
sendChatMessage(connection, message) {
|
|
22
|
-
try {
|
|
23
|
-
connection.send(JSON.stringify(message));
|
|
24
|
-
} catch (e) {
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
broadcastChatMessage(message, exclude) {
|
|
28
|
-
try {
|
|
29
|
-
this.broadcast(JSON.stringify(message), exclude);
|
|
30
|
-
} catch (e) {
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
26
|
async onMessage(connection, message) {
|
|
34
27
|
if (typeof message === "string") {
|
|
35
28
|
let data;
|
|
@@ -56,46 +49,45 @@ var AIChatAgent = class extends Agent {
|
|
|
56
49
|
// duplex
|
|
57
50
|
} = data.init;
|
|
58
51
|
const { messages } = JSON.parse(body);
|
|
59
|
-
this.
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
52
|
+
__privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
|
|
53
|
+
type: "cf_agent_chat_messages",
|
|
54
|
+
messages
|
|
55
|
+
}, [connection.id]);
|
|
56
|
+
await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, messages, [connection.id]);
|
|
57
|
+
return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, async () => {
|
|
58
|
+
const response = await this.onChatMessage(async ({ response: response2 }) => {
|
|
59
|
+
const finalMessages = appendResponseMessages({
|
|
60
|
+
messages,
|
|
61
|
+
responseMessages: response2.messages
|
|
62
|
+
});
|
|
63
|
+
await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, finalMessages, [connection.id]);
|
|
71
64
|
});
|
|
72
|
-
|
|
65
|
+
if (response) {
|
|
66
|
+
await __privateMethod(this, _AIChatAgent_instances, reply_fn).call(this, data.id, response);
|
|
67
|
+
}
|
|
73
68
|
});
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
}
|
|
77
|
-
} else if (data.type === "cf_agent_chat_clear") {
|
|
69
|
+
}
|
|
70
|
+
if (data.type === "cf_agent_chat_clear") {
|
|
78
71
|
this.sql`delete from cf_ai_chat_agent_messages`;
|
|
79
72
|
this.messages = [];
|
|
80
|
-
this.
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
},
|
|
84
|
-
[connection.id]
|
|
85
|
-
);
|
|
73
|
+
__privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
|
|
74
|
+
type: "cf_agent_chat_clear"
|
|
75
|
+
}, [connection.id]);
|
|
86
76
|
} else if (data.type === "cf_agent_chat_messages") {
|
|
87
|
-
await this.
|
|
77
|
+
await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, data.messages, [connection.id]);
|
|
88
78
|
}
|
|
89
79
|
}
|
|
90
80
|
}
|
|
91
81
|
async onRequest(request) {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
82
|
+
return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, () => {
|
|
83
|
+
if (request.url.endsWith("/get-messages")) {
|
|
84
|
+
const messages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
|
|
85
|
+
return JSON.parse(row.message);
|
|
86
|
+
});
|
|
87
|
+
return Response.json(messages);
|
|
88
|
+
}
|
|
89
|
+
return super.onRequest(request);
|
|
90
|
+
});
|
|
99
91
|
}
|
|
100
92
|
/**
|
|
101
93
|
* Handle incoming chat messages and generate a response
|
|
@@ -112,13 +104,13 @@ var AIChatAgent = class extends Agent {
|
|
|
112
104
|
* @param messages Chat messages to save
|
|
113
105
|
*/
|
|
114
106
|
async saveMessages(messages) {
|
|
115
|
-
await this.
|
|
107
|
+
await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, messages);
|
|
116
108
|
const response = await this.onChatMessage(async ({ response: response2 }) => {
|
|
117
109
|
const finalMessages = appendResponseMessages({
|
|
118
110
|
messages,
|
|
119
111
|
responseMessages: response2.messages
|
|
120
112
|
});
|
|
121
|
-
await this.
|
|
113
|
+
await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, finalMessages, []);
|
|
122
114
|
});
|
|
123
115
|
if (response) {
|
|
124
116
|
for await (const chunk of response.body) {
|
|
@@ -127,41 +119,47 @@ var AIChatAgent = class extends Agent {
|
|
|
127
119
|
response.body?.cancel();
|
|
128
120
|
}
|
|
129
121
|
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
},
|
|
141
|
-
excludeBroadcastIds
|
|
142
|
-
);
|
|
122
|
+
};
|
|
123
|
+
_AIChatAgent_instances = new WeakSet();
|
|
124
|
+
broadcastChatMessage_fn = function(message, exclude) {
|
|
125
|
+
this.broadcast(JSON.stringify(message), exclude);
|
|
126
|
+
};
|
|
127
|
+
tryCatch_fn = async function(fn) {
|
|
128
|
+
try {
|
|
129
|
+
return await fn();
|
|
130
|
+
} catch (e) {
|
|
131
|
+
throw this.onError(e);
|
|
143
132
|
}
|
|
144
|
-
|
|
133
|
+
};
|
|
134
|
+
persistMessages_fn = async function(messages, excludeBroadcastIds = []) {
|
|
135
|
+
this.sql`delete from cf_ai_chat_agent_messages`;
|
|
136
|
+
for (const message of messages) {
|
|
137
|
+
this.sql`insert into cf_ai_chat_agent_messages (id, message) values (${message.id},${JSON.stringify(message)})`;
|
|
138
|
+
}
|
|
139
|
+
this.messages = messages;
|
|
140
|
+
__privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
|
|
141
|
+
type: "cf_agent_chat_messages",
|
|
142
|
+
messages
|
|
143
|
+
}, excludeBroadcastIds);
|
|
144
|
+
};
|
|
145
|
+
reply_fn = async function(id, response) {
|
|
146
|
+
return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, async () => {
|
|
145
147
|
for await (const chunk of response.body) {
|
|
146
148
|
const body = decoder.decode(chunk);
|
|
147
|
-
|
|
148
|
-
this.sendChatMessage(conn, {
|
|
149
|
-
id,
|
|
150
|
-
type: "cf_agent_use_chat_response",
|
|
151
|
-
body,
|
|
152
|
-
done: false
|
|
153
|
-
});
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
for (const conn of this.getConnections()) {
|
|
157
|
-
this.sendChatMessage(conn, {
|
|
149
|
+
__privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
|
|
158
150
|
id,
|
|
159
151
|
type: "cf_agent_use_chat_response",
|
|
160
|
-
body
|
|
161
|
-
done:
|
|
152
|
+
body,
|
|
153
|
+
done: false
|
|
162
154
|
});
|
|
163
155
|
}
|
|
164
|
-
|
|
156
|
+
__privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
|
|
157
|
+
id,
|
|
158
|
+
type: "cf_agent_use_chat_response",
|
|
159
|
+
body: "",
|
|
160
|
+
done: true
|
|
161
|
+
});
|
|
162
|
+
});
|
|
165
163
|
};
|
|
166
164
|
export {
|
|
167
165
|
AIChatAgent
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ai-chat-agent.ts"],"sourcesContent":["import { Agent, type AgentContext, type Connection, type WSMessage } from \"./\";\nimport type {\n Message as ChatMessage,\n StreamTextOnFinishCallback,\n ToolSet,\n} from \"ai\";\nimport { appendResponseMessages } from \"ai\";\nimport type { OutgoingMessage, IncomingMessage } from \"./ai-types\";\nconst decoder = new TextDecoder();\n\n/**\n * Extension of Agent with built-in chat capabilities\n * @template Env Environment type containing bindings\n */\nexport class AIChatAgent<Env = unknown, State = unknown> extends Agent<\n Env,\n State\n> {\n /** Array of chat messages for the current conversation */\n messages: ChatMessage[];\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n this.sql`create table if not exists cf_ai_chat_agent_messages (\n id text primary key,\n message text not null,\n created_at datetime default current_timestamp\n )`;\n this.messages = (\n this.sql`select * from cf_ai_chat_agent_messages` || []\n ).map((row) => {\n return JSON.parse(row.message as string);\n });\n }\n\n
|
|
1
|
+
{"version":3,"sources":["../src/ai-chat-agent.ts"],"sourcesContent":["import { Agent, type AgentContext, type Connection, type WSMessage } from \"./\";\nimport type {\n Message as ChatMessage,\n StreamTextOnFinishCallback,\n ToolSet,\n} from \"ai\";\nimport { appendResponseMessages } from \"ai\";\nimport type { OutgoingMessage, IncomingMessage } from \"./ai-types\";\nconst decoder = new TextDecoder();\n\n/**\n * Extension of Agent with built-in chat capabilities\n * @template Env Environment type containing bindings\n */\nexport class AIChatAgent<Env = unknown, State = unknown> extends Agent<\n Env,\n State\n> {\n /** Array of chat messages for the current conversation */\n messages: ChatMessage[];\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n this.sql`create table if not exists cf_ai_chat_agent_messages (\n id text primary key,\n message text not null,\n created_at datetime default current_timestamp\n )`;\n this.messages = (\n this.sql`select * from cf_ai_chat_agent_messages` || []\n ).map((row) => {\n return JSON.parse(row.message as string);\n });\n }\n\n #broadcastChatMessage(message: OutgoingMessage, exclude?: string[]) {\n this.broadcast(JSON.stringify(message), exclude);\n }\n\n override async onMessage(connection: Connection, message: WSMessage) {\n if (typeof message === \"string\") {\n let data: IncomingMessage;\n try {\n data = JSON.parse(message) as IncomingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (\n data.type === \"cf_agent_use_chat_request\" &&\n data.init.method === \"POST\"\n ) {\n const {\n method,\n keepalive,\n headers,\n body, // we're reading this\n redirect,\n integrity,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window,\n // dispatcher,\n // duplex\n } = data.init;\n const { messages } = JSON.parse(body as string);\n this.#broadcastChatMessage(\n {\n type: \"cf_agent_chat_messages\",\n messages,\n },\n [connection.id]\n );\n await this.#persistMessages(messages, [connection.id]);\n return this.#tryCatch(async () => {\n const response = await this.onChatMessage(async ({ response }) => {\n const finalMessages = appendResponseMessages({\n messages,\n responseMessages: response.messages,\n });\n\n await this.#persistMessages(finalMessages, [connection.id]);\n });\n if (response) {\n await this.#reply(data.id, response);\n }\n });\n }\n if (data.type === \"cf_agent_chat_clear\") {\n this.sql`delete from cf_ai_chat_agent_messages`;\n this.messages = [];\n this.#broadcastChatMessage(\n {\n type: \"cf_agent_chat_clear\",\n },\n [connection.id]\n );\n } else if (data.type === \"cf_agent_chat_messages\") {\n // replace the messages with the new ones\n await this.#persistMessages(data.messages, [connection.id]);\n }\n }\n }\n\n override async onRequest(request: Request): Promise<Response> {\n return this.#tryCatch(() => {\n if (request.url.endsWith(\"/get-messages\")) {\n const messages = (\n this.sql`select * from cf_ai_chat_agent_messages` || []\n ).map((row) => {\n return JSON.parse(row.message as string);\n });\n return Response.json(messages);\n }\n return super.onRequest(request);\n });\n }\n\n async #tryCatch<T>(fn: () => T | Promise<T>) {\n try {\n return await fn();\n } catch (e) {\n throw this.onError(e);\n }\n }\n\n /**\n * Handle incoming chat messages and generate a response\n * @param onFinish Callback to be called when the response is finished\n * @returns Response to send to the client or undefined\n */\n async onChatMessage(\n onFinish: StreamTextOnFinishCallback<ToolSet>\n ): Promise<Response | undefined> {\n throw new Error(\n \"recieved a chat message, override onChatMessage and return a Response to send to the client\"\n );\n }\n\n /**\n * Save messages on the server side and trigger AI response\n * @param messages Chat messages to save\n */\n async saveMessages(messages: ChatMessage[]) {\n await this.#persistMessages(messages);\n const response = await this.onChatMessage(async ({ response }) => {\n const finalMessages = appendResponseMessages({\n messages,\n responseMessages: response.messages,\n });\n\n await this.#persistMessages(finalMessages, []);\n });\n if (response) {\n // we're just going to drain the body\n // @ts-ignore TODO: fix this type error\n for await (const chunk of response.body!) {\n decoder.decode(chunk);\n }\n response.body?.cancel();\n }\n }\n\n async #persistMessages(\n messages: ChatMessage[],\n excludeBroadcastIds: string[] = []\n ) {\n this.sql`delete from cf_ai_chat_agent_messages`;\n for (const message of messages) {\n this.sql`insert into cf_ai_chat_agent_messages (id, message) values (${\n message.id\n },${JSON.stringify(message)})`;\n }\n this.messages = messages;\n this.#broadcastChatMessage(\n {\n type: \"cf_agent_chat_messages\",\n messages: messages,\n },\n excludeBroadcastIds\n );\n }\n\n async #reply(id: string, response: Response) {\n // now take chunks out from dataStreamResponse and send them to the client\n return this.#tryCatch(async () => {\n // @ts-expect-error TODO: fix this type error\n for await (const chunk of response.body!) {\n const body = decoder.decode(chunk);\n\n this.#broadcastChatMessage({\n id,\n type: \"cf_agent_use_chat_response\",\n body,\n done: false,\n });\n }\n\n this.#broadcastChatMessage({\n id,\n type: \"cf_agent_use_chat_response\",\n body: \"\",\n done: true,\n });\n });\n }\n}\n"],"mappings":";;;;;;;;;AAMA,SAAS,8BAA8B;AAEvC,IAAM,UAAU,IAAI,YAAY;AARhC;AAcO,IAAM,cAAN,cAA0D,MAG/D;AAAA,EAGA,YAAY,KAAmB,KAAU;AACvC,UAAM,KAAK,GAAG;AAPX;AAQH,SAAK;AAAA;AAAA;AAAA;AAAA;AAKL,SAAK,YACH,KAAK,gDAAgD,CAAC,GACtD,IAAI,CAAC,QAAQ;AACb,aAAO,KAAK,MAAM,IAAI,OAAiB;AAAA,IACzC,CAAC;AAAA,EACH;AAAA,EAMA,MAAe,UAAU,YAAwB,SAAoB;AACnE,QAAI,OAAO,YAAY,UAAU;AAC/B,UAAI;AACJ,UAAI;AACF,eAAO,KAAK,MAAM,OAAO;AAAA,MAC3B,SAAS,OAAO;AAGd;AAAA,MACF;AACA,UACE,KAAK,SAAS,+BACd,KAAK,KAAK,WAAW,QACrB;AACA,cAAM;AAAA,UACJ;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA;AAAA;AAAA,QAGF,IAAI,KAAK;AACT,cAAM,EAAE,SAAS,IAAI,KAAK,MAAM,IAAc;AAC9C,8BAAK,iDAAL,WACE;AAAA,U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A,MACN,MAAM;AAAA,IACR;AAAA,EACF;AACF;","names":["response"]}
|
package/dist/ai-react.d.ts
CHANGED
|
@@ -14,10 +14,10 @@ type GetInitialMessagesOptions = {
|
|
|
14
14
|
/**
|
|
15
15
|
* Options for the useAgentChat hook
|
|
16
16
|
*/
|
|
17
|
-
type UseAgentChatOptions = Omit<
|
|
17
|
+
type UseAgentChatOptions<State> = Omit<
|
|
18
18
|
Parameters<typeof useChat>[0] & {
|
|
19
19
|
/** Agent connection from useAgent */
|
|
20
|
-
agent: ReturnType<typeof useAgent
|
|
20
|
+
agent: ReturnType<typeof useAgent<State>>;
|
|
21
21
|
getInitialMessages?:
|
|
22
22
|
| undefined
|
|
23
23
|
| null
|
|
@@ -30,7 +30,9 @@ type UseAgentChatOptions = Omit<
|
|
|
30
30
|
* @param options Chat options including the agent connection
|
|
31
31
|
* @returns Chat interface controls and state with added clearHistory method
|
|
32
32
|
*/
|
|
33
|
-
declare function useAgentChat
|
|
33
|
+
declare function useAgentChat<State = unknown>(
|
|
34
|
+
options: UseAgentChatOptions<State>
|
|
35
|
+
): {
|
|
34
36
|
/**
|
|
35
37
|
* Set the chat messages and synchronize with the Agent
|
|
36
38
|
* @param messages New messages to set
|
package/dist/ai-react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ai-react.tsx"],"sourcesContent":["import { useChat } from \"@ai-sdk/react\";\nimport type { Message } from \"ai\";\nimport type { useAgent } from \"./react\";\nimport { useEffect, use } from \"react\";\nimport type { OutgoingMessage } from \"./ai-types\";\n\ntype GetInitialMessagesOptions = {\n agent: string;\n name: string;\n url: string;\n};\n\n/**\n * Options for the useAgentChat hook\n */\ntype UseAgentChatOptions = Omit<\n Parameters<typeof useChat>[0] & {\n /** Agent connection from useAgent */\n agent: ReturnType<typeof useAgent
|
|
1
|
+
{"version":3,"sources":["../src/ai-react.tsx"],"sourcesContent":["import { useChat } from \"@ai-sdk/react\";\nimport type { Message } from \"ai\";\nimport type { useAgent } from \"./react\";\nimport { useEffect, use } from \"react\";\nimport type { OutgoingMessage } from \"./ai-types\";\n\ntype GetInitialMessagesOptions = {\n agent: string;\n name: string;\n url: string;\n};\n\n/**\n * Options for the useAgentChat hook\n */\ntype UseAgentChatOptions<State> = Omit<\n Parameters<typeof useChat>[0] & {\n /** Agent connection from useAgent */\n agent: ReturnType<typeof useAgent<State>>;\n getInitialMessages?:\n | undefined\n | null\n // | (() => Message[])\n | ((options: GetInitialMessagesOptions) => Promise<Message[]>);\n },\n \"fetch\"\n>;\n\n// TODO: clear cache when the agent is unmounted?\nconst requestCache = new Map<string, Promise<Message[]>>();\n\n/**\n * React hook for building AI chat interfaces using an Agent\n * @param options Chat options including the agent connection\n * @returns Chat interface controls and state with added clearHistory method\n */\nexport function useAgentChat<State = unknown>(\n options: UseAgentChatOptions<State>\n) {\n const { agent, getInitialMessages, ...rest } = options;\n const url = `${agent._pkurl\n .replace(\"ws://\", \"http://\")\n .replace(\"wss://\", \"https://\")}`;\n\n async function defaultGetInitialMessagesFetch({\n url,\n }: GetInitialMessagesOptions) {\n const response = await fetch(new Request(`${url}/get-messages`), {\n headers: options.headers,\n credentials: options.credentials,\n });\n return response.json<Message[]>();\n }\n\n const getInitialMessagesFetch =\n getInitialMessages || defaultGetInitialMessagesFetch;\n\n function doGetInitialMessages(\n getInitialMessagesOptions: GetInitialMessagesOptions\n ) {\n if (requestCache.has(url)) {\n return requestCache.get(url)!;\n }\n const promise = getInitialMessagesFetch(getInitialMessagesOptions);\n requestCache.set(url, promise);\n return promise;\n }\n\n const initialMessages =\n getInitialMessages !== null\n ? use(\n doGetInitialMessages({\n agent: agent.agent,\n name: agent.name,\n url,\n })\n )\n : rest.initialMessages;\n\n useEffect(() => {\n return () => {\n requestCache.delete(url);\n };\n }, [url]);\n\n async function aiFetch(\n request: RequestInfo | URL,\n options: RequestInit = {}\n ) {\n // we're going to use a websocket to do the actual \"fetching\"\n // but still satisfy the type signature of the fetch function\n // so we'll return a promise that resolves to a response\n\n const {\n method,\n keepalive,\n headers,\n body,\n redirect,\n integrity,\n signal,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window,\n // dispatcher, duplex\n } = options;\n const id = crypto.randomUUID();\n const abortController = new AbortController();\n\n signal?.addEventListener(\"abort\", () => {\n abortController.abort();\n });\n\n agent.addEventListener(\n \"message\",\n (event) => {\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_use_chat_response\") {\n if (data.id === id) {\n controller.enqueue(new TextEncoder().encode(data.body));\n if (data.done) {\n controller.close();\n abortController.abort();\n }\n }\n }\n },\n { signal: abortController.signal }\n );\n\n let controller: ReadableStreamDefaultController;\n\n const stream = new ReadableStream({\n start(c) {\n controller = c;\n },\n });\n\n agent.send(\n JSON.stringify({\n type: \"cf_agent_use_chat_request\",\n id,\n url: request.toString(),\n init: {\n method,\n keepalive,\n headers,\n body,\n redirect,\n integrity,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window,\n // dispatcher,\n // duplex\n },\n })\n );\n\n return new Response(stream);\n }\n const useChatHelpers = useChat({\n initialMessages,\n sendExtraMessageFields: true,\n fetch: aiFetch,\n ...rest,\n });\n\n useEffect(() => {\n function onClearHistory(event: MessageEvent) {\n if (typeof event.data !== \"string\") {\n return;\n }\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_chat_clear\") {\n useChatHelpers.setMessages([]);\n }\n }\n\n function onMessages(event: MessageEvent) {\n if (typeof event.data !== \"string\") {\n return;\n }\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_chat_messages\") {\n useChatHelpers.setMessages(data.messages);\n }\n }\n\n agent.addEventListener(\"message\", onClearHistory);\n agent.addEventListener(\"message\", onMessages);\n\n return () => {\n agent.removeEventListener(\"message\", onClearHistory);\n agent.removeEventListener(\"message\", onMessages);\n };\n }, [\n agent.addEventListener,\n agent.removeEventListener,\n useChatHelpers.setMessages,\n ]);\n\n return {\n ...useChatHelpers,\n /**\n * Set the chat messages and synchronize with the Agent\n * @param messages New messages to set\n */\n setMessages: (messages: Message[]) => {\n useChatHelpers.setMessages(messages);\n agent.send(\n JSON.stringify({\n type: \"cf_agent_chat_messages\",\n messages,\n })\n );\n },\n /**\n * Clear chat history on both client and Agent\n */\n clearHistory: () => {\n useChatHelpers.setMessages([]);\n agent.send(\n JSON.stringify({\n type: \"cf_agent_chat_clear\",\n })\n );\n },\n };\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AAGxB,SAAS,WAAW,WAAW;AA0B/B,IAAM,eAAe,oBAAI,IAAgC;AAOlD,SAAS,aACd,SACA;AACA,QAAM,EAAE,OAAO,oBAAoB,GAAG,KAAK,IAAI;AAC/C,QAAM,MAAM,GAAG,MAAM,OAClB,QAAQ,SAAS,SAAS,EAC1B,QAAQ,UAAU,UAAU,CAAC;AAEhC,iBAAe,+BAA+B;AAAA,IAC5C,KAAAA;AAAA,EACF,GAA8B;AAC5B,UAAM,WAAW,MAAM,MAAM,IAAI,QAAQ,GAAGA,IAAG,eAAe,GAAG;AAAA,MAC/D,SAAS,QAAQ;AAAA,MACjB,aAAa,QAAQ;AAAA,IACvB,CAAC;AACD,WAAO,SAAS,KAAgB;AAAA,EAClC;AAEA,QAAM,0BACJ,sBAAsB;AAExB,WAAS,qBACP,2BACA;AACA,QAAI,aAAa,IAAI,GAAG,GAAG;AACzB,aAAO,aAAa,IAAI,GAAG;AAAA,IAC7B;AACA,UAAM,UAAU,wBAAwB,yBAAyB;AACjE,iBAAa,IAAI,KAAK,OAAO;AAC7B,WAAO;AAAA,EACT;AAEA,QAAM,kBACJ,uBA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nC,YAAM;AAAA,QACJ,KAAK,UAAU;AAAA,UACb,MAAM;AAAA,UACN;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA;AAAA;AAAA;AAAA,IAIA,cAAc,MAAM;AAClB,qBAAe,YAAY,CAAC,CAAC;AAC7B,YAAM;AAAA,QACJ,KAAK,UAAU;AAAA,UACb,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;","names":["url","options"]}
|
|
@@ -38,7 +38,7 @@ function getNextCronTime(cron) {
|
|
|
38
38
|
var STATE_ROW_ID = "cf_state_row_id";
|
|
39
39
|
var STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
40
40
|
var DEFAULT_STATE = {};
|
|
41
|
-
var _state, _Agent_instances, setStateInternal_fn;
|
|
41
|
+
var _state, _Agent_instances, setStateInternal_fn, tryCatch_fn, scheduleNextAlarm_fn, isCallable_fn;
|
|
42
42
|
var Agent = class extends Server {
|
|
43
43
|
constructor(ctx, env) {
|
|
44
44
|
super(ctx, env);
|
|
@@ -56,7 +56,7 @@ var Agent = class extends Server {
|
|
|
56
56
|
)
|
|
57
57
|
`;
|
|
58
58
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
59
|
-
|
|
59
|
+
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, async () => {
|
|
60
60
|
this.sql`
|
|
61
61
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
62
62
|
id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
|
|
@@ -70,21 +70,18 @@ var Agent = class extends Server {
|
|
|
70
70
|
)
|
|
71
71
|
`;
|
|
72
72
|
await this.alarm();
|
|
73
|
-
}
|
|
74
|
-
console.error(e);
|
|
75
|
-
throw e;
|
|
76
|
-
}
|
|
73
|
+
});
|
|
77
74
|
});
|
|
78
75
|
const _onMessage = this.onMessage.bind(this);
|
|
79
76
|
this.onMessage = async (connection, message) => {
|
|
80
77
|
if (typeof message !== "string") {
|
|
81
|
-
return _onMessage(connection, message);
|
|
78
|
+
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
|
|
82
79
|
}
|
|
83
80
|
let parsed;
|
|
84
81
|
try {
|
|
85
82
|
parsed = JSON.parse(message);
|
|
86
83
|
} catch (e) {
|
|
87
|
-
return _onMessage(connection, message);
|
|
84
|
+
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
|
|
88
85
|
}
|
|
89
86
|
if (isStateUpdateMessage(parsed)) {
|
|
90
87
|
__privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, parsed.state, connection);
|
|
@@ -97,7 +94,7 @@ var Agent = class extends Server {
|
|
|
97
94
|
if (typeof methodFn !== "function") {
|
|
98
95
|
throw new Error(`Method ${method} does not exist`);
|
|
99
96
|
}
|
|
100
|
-
if (!this.
|
|
97
|
+
if (!__privateMethod(this, _Agent_instances, isCallable_fn).call(this, method)) {
|
|
101
98
|
throw new Error(`Method ${method} is not callable`);
|
|
102
99
|
}
|
|
103
100
|
const metadata = callableMetadata.get(methodFn);
|
|
@@ -127,7 +124,7 @@ var Agent = class extends Server {
|
|
|
127
124
|
}
|
|
128
125
|
return;
|
|
129
126
|
}
|
|
130
|
-
return _onMessage(connection, message);
|
|
127
|
+
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
|
|
131
128
|
};
|
|
132
129
|
const _onConnect = this.onConnect.bind(this);
|
|
133
130
|
this.onConnect = (connection, ctx2) => {
|
|
@@ -140,7 +137,7 @@ var Agent = class extends Server {
|
|
|
140
137
|
})
|
|
141
138
|
);
|
|
142
139
|
}
|
|
143
|
-
_onConnect(connection, ctx2);
|
|
140
|
+
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onConnect(connection, ctx2));
|
|
144
141
|
}, 20);
|
|
145
142
|
};
|
|
146
143
|
}
|
|
@@ -186,7 +183,7 @@ var Agent = class extends Server {
|
|
|
186
183
|
return [...this.ctx.storage.sql.exec(query, ...values)];
|
|
187
184
|
} catch (e) {
|
|
188
185
|
console.error(`failed to execute sql query: ${query}`, e);
|
|
189
|
-
throw e;
|
|
186
|
+
throw this.onError(e);
|
|
190
187
|
}
|
|
191
188
|
}
|
|
192
189
|
/**
|
|
@@ -210,6 +207,25 @@ var Agent = class extends Server {
|
|
|
210
207
|
onEmail(email) {
|
|
211
208
|
throw new Error("Not implemented");
|
|
212
209
|
}
|
|
210
|
+
onError(connectionOrError, error) {
|
|
211
|
+
let theError;
|
|
212
|
+
if (connectionOrError && error) {
|
|
213
|
+
theError = error;
|
|
214
|
+
console.error(
|
|
215
|
+
"Error on websocket connection:",
|
|
216
|
+
connectionOrError.id,
|
|
217
|
+
theError
|
|
218
|
+
);
|
|
219
|
+
console.error(
|
|
220
|
+
"Override onError(connection, error) to handle websocket connection errors"
|
|
221
|
+
);
|
|
222
|
+
} else {
|
|
223
|
+
theError = connectionOrError;
|
|
224
|
+
console.error("Error on server:", theError);
|
|
225
|
+
console.error("Override onError(error) to handle server errors");
|
|
226
|
+
}
|
|
227
|
+
throw theError;
|
|
228
|
+
}
|
|
213
229
|
/**
|
|
214
230
|
* Render content (not implemented in base class)
|
|
215
231
|
*/
|
|
@@ -240,7 +256,7 @@ var Agent = class extends Server {
|
|
|
240
256
|
payload
|
|
241
257
|
)}, 'scheduled', ${timestamp})
|
|
242
258
|
`;
|
|
243
|
-
await this.
|
|
259
|
+
await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
|
|
244
260
|
return {
|
|
245
261
|
id,
|
|
246
262
|
callback,
|
|
@@ -258,7 +274,7 @@ var Agent = class extends Server {
|
|
|
258
274
|
payload
|
|
259
275
|
)}, 'delayed', ${when}, ${timestamp})
|
|
260
276
|
`;
|
|
261
|
-
await this.
|
|
277
|
+
await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
|
|
262
278
|
return {
|
|
263
279
|
id,
|
|
264
280
|
callback,
|
|
@@ -277,7 +293,7 @@ var Agent = class extends Server {
|
|
|
277
293
|
payload
|
|
278
294
|
)}, 'cron', ${when}, ${timestamp})
|
|
279
295
|
`;
|
|
280
|
-
await this.
|
|
296
|
+
await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
|
|
281
297
|
return {
|
|
282
298
|
id,
|
|
283
299
|
callback,
|
|
@@ -299,7 +315,10 @@ var Agent = class extends Server {
|
|
|
299
315
|
const result = this.sql`
|
|
300
316
|
SELECT * FROM cf_agents_schedules WHERE id = ${id}
|
|
301
317
|
`;
|
|
302
|
-
if (!result)
|
|
318
|
+
if (!result) {
|
|
319
|
+
console.error(`schedule ${id} not found`);
|
|
320
|
+
return void 0;
|
|
321
|
+
}
|
|
303
322
|
return { ...result[0], payload: JSON.parse(result[0].payload) };
|
|
304
323
|
}
|
|
305
324
|
/**
|
|
@@ -345,22 +364,9 @@ var Agent = class extends Server {
|
|
|
345
364
|
*/
|
|
346
365
|
async cancelSchedule(id) {
|
|
347
366
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
348
|
-
await this.
|
|
367
|
+
await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
|
|
349
368
|
return true;
|
|
350
369
|
}
|
|
351
|
-
async scheduleNextAlarm() {
|
|
352
|
-
const result = this.sql`
|
|
353
|
-
SELECT time FROM cf_agents_schedules
|
|
354
|
-
WHERE time > ${Math.floor(Date.now() / 1e3)}
|
|
355
|
-
ORDER BY time ASC
|
|
356
|
-
LIMIT 1
|
|
357
|
-
`;
|
|
358
|
-
if (!result) return;
|
|
359
|
-
if (result.length > 0 && "time" in result[0]) {
|
|
360
|
-
const nextTime = result[0].time * 1e3;
|
|
361
|
-
await this.ctx.storage.setAlarm(nextTime);
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
370
|
/**
|
|
365
371
|
* Method called when an alarm fires
|
|
366
372
|
* Executes any scheduled tasks that are due
|
|
@@ -377,9 +383,9 @@ var Agent = class extends Server {
|
|
|
377
383
|
continue;
|
|
378
384
|
}
|
|
379
385
|
try {
|
|
380
|
-
callback.bind(this)(JSON.parse(row.payload), row);
|
|
386
|
+
await callback.bind(this)(JSON.parse(row.payload), row);
|
|
381
387
|
} catch (e) {
|
|
382
|
-
console.error(`error executing callback ${row.callback}`, e);
|
|
388
|
+
console.error(`error executing callback "${row.callback}"`, e);
|
|
383
389
|
}
|
|
384
390
|
if (row.type === "cron") {
|
|
385
391
|
const nextExecutionTime = getNextCronTime(row.cron);
|
|
@@ -393,7 +399,7 @@ var Agent = class extends Server {
|
|
|
393
399
|
`;
|
|
394
400
|
}
|
|
395
401
|
}
|
|
396
|
-
await this.
|
|
402
|
+
await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
|
|
397
403
|
}
|
|
398
404
|
/**
|
|
399
405
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
@@ -404,13 +410,6 @@ var Agent = class extends Server {
|
|
|
404
410
|
await this.ctx.storage.deleteAlarm();
|
|
405
411
|
await this.ctx.storage.deleteAll();
|
|
406
412
|
}
|
|
407
|
-
/**
|
|
408
|
-
* Get all methods marked as callable on this Agent
|
|
409
|
-
* @returns A map of method names to their metadata
|
|
410
|
-
*/
|
|
411
|
-
isCallable(method) {
|
|
412
|
-
return callableMetadata.has(this[method]);
|
|
413
|
-
}
|
|
414
413
|
};
|
|
415
414
|
_state = new WeakMap();
|
|
416
415
|
_Agent_instances = new WeakSet();
|
|
@@ -431,7 +430,34 @@ setStateInternal_fn = function(state, source = "server") {
|
|
|
431
430
|
}),
|
|
432
431
|
source !== "server" ? [source.id] : []
|
|
433
432
|
);
|
|
434
|
-
this.onStateUpdate(state, source);
|
|
433
|
+
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => this.onStateUpdate(state, source));
|
|
434
|
+
};
|
|
435
|
+
tryCatch_fn = async function(fn) {
|
|
436
|
+
try {
|
|
437
|
+
return await fn();
|
|
438
|
+
} catch (e) {
|
|
439
|
+
throw this.onError(e);
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
scheduleNextAlarm_fn = async function() {
|
|
443
|
+
const result = this.sql`
|
|
444
|
+
SELECT time FROM cf_agents_schedules
|
|
445
|
+
WHERE time > ${Math.floor(Date.now() / 1e3)}
|
|
446
|
+
ORDER BY time ASC
|
|
447
|
+
LIMIT 1
|
|
448
|
+
`;
|
|
449
|
+
if (!result) return;
|
|
450
|
+
if (result.length > 0 && "time" in result[0]) {
|
|
451
|
+
const nextTime = result[0].time * 1e3;
|
|
452
|
+
await this.ctx.storage.setAlarm(nextTime);
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
/**
|
|
456
|
+
* Get all methods marked as callable on this Agent
|
|
457
|
+
* @returns A map of method names to their metadata
|
|
458
|
+
*/
|
|
459
|
+
isCallable_fn = function(method) {
|
|
460
|
+
return callableMetadata.has(this[method]);
|
|
435
461
|
};
|
|
436
462
|
/**
|
|
437
463
|
* Agent configuration options
|
|
@@ -466,7 +492,7 @@ async function routeAgentRequest(request, env, options) {
|
|
|
466
492
|
...options
|
|
467
493
|
}
|
|
468
494
|
);
|
|
469
|
-
if (response && corsHeaders && request.headers.get("upgrade") !== "websocket") {
|
|
495
|
+
if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
|
|
470
496
|
response = new Response(response.body, {
|
|
471
497
|
headers: {
|
|
472
498
|
...response.headers,
|
|
@@ -539,4 +565,4 @@ export {
|
|
|
539
565
|
getAgentByName,
|
|
540
566
|
StreamingResponse
|
|
541
567
|
};
|
|
542
|
-
//# sourceMappingURL=chunk-
|
|
568
|
+
//# sourceMappingURL=chunk-X6BBKLSC.js.map
|