agents 0.0.0-fe9e8d3 → 0.0.0-feef082
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 +131 -25
- package/dist/ai-chat-agent.d.ts +40 -10
- package/dist/ai-chat-agent.js +246 -143
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-chat-v5-migration.d.ts +152 -0
- package/dist/ai-chat-v5-migration.js +19 -0
- package/dist/ai-react.d.ts +71 -67
- package/dist/ai-react.js +160 -54
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types.d.ts +36 -19
- package/dist/ai-types.js +6 -0
- package/dist/chunk-AVYJQSLW.js +17 -0
- package/dist/chunk-AVYJQSLW.js.map +1 -0
- package/dist/chunk-LL2AFX7V.js +109 -0
- package/dist/chunk-LL2AFX7V.js.map +1 -0
- package/dist/chunk-PNF6ZMUA.js +1296 -0
- package/dist/chunk-PNF6ZMUA.js.map +1 -0
- package/dist/chunk-QEVM4BVL.js +116 -0
- package/dist/chunk-QEVM4BVL.js.map +1 -0
- package/dist/chunk-UJVEAURM.js +150 -0
- package/dist/chunk-UJVEAURM.js.map +1 -0
- package/dist/{chunk-Q5ZBHY4Z.js → chunk-VYENMKFS.js} +209 -53
- package/dist/chunk-VYENMKFS.js.map +1 -0
- package/dist/client-B9tFv5gX.d.ts +4607 -0
- package/dist/client.d.ts +16 -2
- package/dist/client.js +7 -126
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +264 -23
- package/dist/index.js +13 -3
- package/dist/mcp/client.d.ts +9 -775
- package/dist/mcp/client.js +1 -2
- package/dist/mcp/do-oauth-client-provider.d.ts +4 -3
- package/dist/mcp/do-oauth-client-provider.js +3 -103
- package/dist/mcp/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/index.d.ts +52 -14
- package/dist/mcp/index.js +331 -183
- package/dist/mcp/index.js.map +1 -1
- package/dist/observability/index.d.ts +46 -0
- package/dist/observability/index.js +11 -0
- package/dist/observability/index.js.map +1 -0
- package/dist/react.d.ts +89 -5
- package/dist/react.js +23 -9
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +81 -7
- package/dist/schedule.js +19 -8
- package/dist/schedule.js.map +1 -1
- package/dist/serializable.d.ts +32 -0
- package/dist/serializable.js +1 -0
- package/dist/serializable.js.map +1 -0
- package/package.json +83 -67
- package/src/index.ts +1147 -151
- package/dist/chunk-HD4VEHBA.js +0 -608
- package/dist/chunk-HD4VEHBA.js.map +0 -1
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
- /package/dist/{chunk-HMLY7DHA.js.map → ai-chat-v5-migration.js.map} +0 -0
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { UIMessage } from "ai";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* AI SDK v5 Migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages
|
|
5
|
+
* Using exact types from the official AI SDK documentation
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* AI SDK v5 Message Part types reference (from official AI SDK documentation)
|
|
9
|
+
*
|
|
10
|
+
* The migration logic below transforms legacy messages to match these official AI SDK v5 formats:
|
|
11
|
+
* - TextUIPart: { type: "text", text: string, state?: "streaming" | "done" }
|
|
12
|
+
* - ReasoningUIPart: { type: "reasoning", text: string, state?: "streaming" | "done", providerMetadata?: Record<string, unknown> }
|
|
13
|
+
* - FileUIPart: { type: "file", mediaType: string, filename?: string, url: string }
|
|
14
|
+
* - ToolUIPart: { type: `tool-${string}`, toolCallId: string, state: "input-streaming" | "input-available" | "output-available" | "output-error", input?: Record<string, unknown>, output?: unknown, errorText?: string, providerExecuted?: boolean }
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Tool invocation from v4 format
|
|
18
|
+
*/
|
|
19
|
+
type ToolInvocation = {
|
|
20
|
+
toolCallId: string;
|
|
21
|
+
toolName: string;
|
|
22
|
+
args: Record<string, unknown>;
|
|
23
|
+
result?: unknown;
|
|
24
|
+
state: "partial-call" | "call" | "result" | "error";
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Legacy part from v4 format
|
|
28
|
+
*/
|
|
29
|
+
type LegacyPart = {
|
|
30
|
+
type: string;
|
|
31
|
+
text?: string;
|
|
32
|
+
url?: string;
|
|
33
|
+
data?: string;
|
|
34
|
+
mimeType?: string;
|
|
35
|
+
mediaType?: string;
|
|
36
|
+
filename?: string;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Legacy message format from AI SDK v4
|
|
40
|
+
*/
|
|
41
|
+
type LegacyMessage = {
|
|
42
|
+
id?: string;
|
|
43
|
+
role: string;
|
|
44
|
+
content: string;
|
|
45
|
+
reasoning?: string;
|
|
46
|
+
toolInvocations?: ToolInvocation[];
|
|
47
|
+
parts?: LegacyPart[];
|
|
48
|
+
[key: string]: unknown;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Corrupt content item
|
|
52
|
+
*/
|
|
53
|
+
type CorruptContentItem = {
|
|
54
|
+
type: string;
|
|
55
|
+
text: string;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Corrupted message format - has content as array instead of parts
|
|
59
|
+
*/
|
|
60
|
+
type CorruptArrayMessage = {
|
|
61
|
+
id?: string;
|
|
62
|
+
role: string;
|
|
63
|
+
content: CorruptContentItem[];
|
|
64
|
+
reasoning?: string;
|
|
65
|
+
toolInvocations?: ToolInvocation[];
|
|
66
|
+
[key: string]: unknown;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Union type for messages that could be in any format
|
|
70
|
+
*/
|
|
71
|
+
type MigratableMessage = LegacyMessage | CorruptArrayMessage | UIMessage;
|
|
72
|
+
/**
|
|
73
|
+
* Checks if a message is already in the UIMessage format (has parts array)
|
|
74
|
+
*/
|
|
75
|
+
declare function isUIMessage(message: unknown): message is UIMessage;
|
|
76
|
+
/**
|
|
77
|
+
* Input message that could be in any format - using unknown for flexibility
|
|
78
|
+
*/
|
|
79
|
+
type InputMessage = {
|
|
80
|
+
id?: string;
|
|
81
|
+
role?: string;
|
|
82
|
+
content?: unknown;
|
|
83
|
+
reasoning?: string;
|
|
84
|
+
toolInvocations?: unknown[];
|
|
85
|
+
parts?: unknown[];
|
|
86
|
+
[key: string]: unknown;
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Automatic message transformer following the blog post pattern
|
|
90
|
+
* Handles comprehensive migration from AI SDK v4 to v5 format
|
|
91
|
+
* @param message - Message in any legacy format
|
|
92
|
+
* @param index - Index for ID generation fallback
|
|
93
|
+
* @returns UIMessage in v5 format
|
|
94
|
+
*/
|
|
95
|
+
declare function autoTransformMessage(
|
|
96
|
+
message: InputMessage,
|
|
97
|
+
index?: number
|
|
98
|
+
): UIMessage;
|
|
99
|
+
/**
|
|
100
|
+
* Legacy single message migration for backward compatibility
|
|
101
|
+
*/
|
|
102
|
+
declare function migrateToUIMessage(message: MigratableMessage): UIMessage;
|
|
103
|
+
/**
|
|
104
|
+
* Automatic message transformer for arrays following the blog post pattern
|
|
105
|
+
* @param messages - Array of messages in any format
|
|
106
|
+
* @returns Array of UIMessages in v5 format
|
|
107
|
+
*/
|
|
108
|
+
declare function autoTransformMessages(messages: unknown[]): UIMessage[];
|
|
109
|
+
/**
|
|
110
|
+
* Migrates an array of messages to UIMessage format (legacy compatibility)
|
|
111
|
+
* @param messages - Array of messages in old or new format
|
|
112
|
+
* @returns Array of UIMessages in the new format
|
|
113
|
+
*/
|
|
114
|
+
declare function migrateMessagesToUIFormat(
|
|
115
|
+
messages: MigratableMessage[]
|
|
116
|
+
): UIMessage[];
|
|
117
|
+
/**
|
|
118
|
+
* Checks if any messages in an array need migration
|
|
119
|
+
* @param messages - Array of messages to check
|
|
120
|
+
* @returns true if any messages are not in proper UIMessage format
|
|
121
|
+
*/
|
|
122
|
+
declare function needsMigration(messages: unknown[]): boolean;
|
|
123
|
+
/**
|
|
124
|
+
* Analyzes the corruption types in a message array for debugging
|
|
125
|
+
* @param messages - Array of messages to analyze
|
|
126
|
+
* @returns Statistics about corruption types found
|
|
127
|
+
*/
|
|
128
|
+
declare function analyzeCorruption(messages: unknown[]): {
|
|
129
|
+
total: number;
|
|
130
|
+
clean: number;
|
|
131
|
+
legacyString: number;
|
|
132
|
+
corruptArray: number;
|
|
133
|
+
unknown: number;
|
|
134
|
+
examples: {
|
|
135
|
+
legacyString?: unknown;
|
|
136
|
+
corruptArray?: unknown;
|
|
137
|
+
unknown?: unknown;
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
export {
|
|
142
|
+
type CorruptArrayMessage,
|
|
143
|
+
type LegacyMessage,
|
|
144
|
+
type MigratableMessage,
|
|
145
|
+
analyzeCorruption,
|
|
146
|
+
autoTransformMessage,
|
|
147
|
+
autoTransformMessages,
|
|
148
|
+
isUIMessage,
|
|
149
|
+
migrateMessagesToUIFormat,
|
|
150
|
+
migrateToUIMessage,
|
|
151
|
+
needsMigration
|
|
152
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import {
|
|
2
|
+
analyzeCorruption,
|
|
3
|
+
autoTransformMessage,
|
|
4
|
+
autoTransformMessages,
|
|
5
|
+
isUIMessage,
|
|
6
|
+
migrateMessagesToUIFormat,
|
|
7
|
+
migrateToUIMessage,
|
|
8
|
+
needsMigration
|
|
9
|
+
} from "./chunk-UJVEAURM.js";
|
|
10
|
+
export {
|
|
11
|
+
analyzeCorruption,
|
|
12
|
+
autoTransformMessage,
|
|
13
|
+
autoTransformMessages,
|
|
14
|
+
isUIMessage,
|
|
15
|
+
migrateMessagesToUIFormat,
|
|
16
|
+
migrateToUIMessage,
|
|
17
|
+
needsMigration
|
|
18
|
+
};
|
|
19
|
+
//# sourceMappingURL=ai-chat-v5-migration.js.map
|
package/dist/ai-react.d.ts
CHANGED
|
@@ -1,88 +1,92 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
import { useChat } from "@ai-sdk/react";
|
|
1
|
+
import { UseChatOptions, useChat } from "@ai-sdk/react";
|
|
2
|
+
import { UIMessage, ChatInit } from "ai";
|
|
4
3
|
import { useAgent } from "./react.js";
|
|
5
4
|
import "partysocket";
|
|
6
5
|
import "partysocket/react";
|
|
6
|
+
import "./index.js";
|
|
7
|
+
import "cloudflare:workers";
|
|
8
|
+
import "@modelcontextprotocol/sdk/client/index.js";
|
|
9
|
+
import "@modelcontextprotocol/sdk/types.js";
|
|
10
|
+
import "partyserver";
|
|
11
|
+
import "./client-B9tFv5gX.js";
|
|
12
|
+
import "zod";
|
|
13
|
+
import "@modelcontextprotocol/sdk/shared/protocol.js";
|
|
14
|
+
import "@modelcontextprotocol/sdk/client/sse.js";
|
|
15
|
+
import "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
16
|
+
import "./mcp/do-oauth-client-provider.js";
|
|
17
|
+
import "@modelcontextprotocol/sdk/client/auth.js";
|
|
18
|
+
import "@modelcontextprotocol/sdk/shared/auth.js";
|
|
19
|
+
import "./observability/index.js";
|
|
20
|
+
import "./ai-types.js";
|
|
7
21
|
import "./client.js";
|
|
22
|
+
import "./serializable.js";
|
|
8
23
|
|
|
24
|
+
type AITool<Input = unknown, Output = unknown> = {
|
|
25
|
+
description?: string;
|
|
26
|
+
inputSchema?: unknown;
|
|
27
|
+
execute?: (input: Input) => Output | Promise<Output>;
|
|
28
|
+
};
|
|
9
29
|
type GetInitialMessagesOptions = {
|
|
10
30
|
agent: string;
|
|
11
31
|
name: string;
|
|
12
32
|
url: string;
|
|
13
33
|
};
|
|
34
|
+
type UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &
|
|
35
|
+
UseChatOptions<M>;
|
|
14
36
|
/**
|
|
15
37
|
* Options for the useAgentChat hook
|
|
16
38
|
*/
|
|
17
|
-
type UseAgentChatOptions<
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
39
|
+
type UseAgentChatOptions<
|
|
40
|
+
State,
|
|
41
|
+
ChatMessage extends UIMessage = UIMessage
|
|
42
|
+
> = Omit<UseChatParams<ChatMessage>, "fetch"> & {
|
|
43
|
+
/** Agent connection from useAgent */
|
|
44
|
+
agent: ReturnType<typeof useAgent<State>>;
|
|
45
|
+
getInitialMessages?:
|
|
46
|
+
| undefined
|
|
47
|
+
| null
|
|
48
|
+
| ((options: GetInitialMessagesOptions) => Promise<ChatMessage[]>);
|
|
49
|
+
/** Request credentials */
|
|
50
|
+
credentials?: RequestCredentials;
|
|
51
|
+
/** Request headers */
|
|
52
|
+
headers?: HeadersInit;
|
|
53
|
+
/**
|
|
54
|
+
* @description Whether to automatically resolve tool calls that do not require human interaction.
|
|
55
|
+
* @experimental
|
|
56
|
+
*/
|
|
57
|
+
experimental_automaticToolResolution?: boolean;
|
|
58
|
+
/**
|
|
59
|
+
* @description Tools object for automatic detection of confirmation requirements.
|
|
60
|
+
* Tools without execute function will require confirmation.
|
|
61
|
+
*/
|
|
62
|
+
tools?: Record<string, AITool<unknown, unknown>>;
|
|
63
|
+
/**
|
|
64
|
+
* @description Manual override for tools requiring confirmation.
|
|
65
|
+
* If not provided, will auto-detect from tools object.
|
|
66
|
+
*/
|
|
67
|
+
toolsRequiringConfirmation?: string[];
|
|
68
|
+
};
|
|
28
69
|
/**
|
|
29
70
|
* React hook for building AI chat interfaces using an Agent
|
|
30
71
|
* @param options Chat options including the agent connection
|
|
31
72
|
* @returns Chat interface controls and state with added clearHistory method
|
|
32
73
|
*/
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
74
|
+
/**
|
|
75
|
+
* Automatically detects which tools require confirmation based on their configuration.
|
|
76
|
+
* Tools require confirmation if they have no execute function AND are not server-executed.
|
|
77
|
+
* @param tools - Record of tool name to tool definition
|
|
78
|
+
* @returns Array of tool names that require confirmation
|
|
79
|
+
*/
|
|
80
|
+
declare function detectToolsRequiringConfirmation(
|
|
81
|
+
tools?: Record<string, AITool<unknown, unknown>>
|
|
82
|
+
): string[];
|
|
83
|
+
declare function useAgentChat<
|
|
84
|
+
State = unknown,
|
|
85
|
+
ChatMessage extends UIMessage = UIMessage
|
|
86
|
+
>(
|
|
87
|
+
options: UseAgentChatOptions<State, ChatMessage>
|
|
88
|
+
): ReturnType<typeof useChat<ChatMessage>> & {
|
|
44
89
|
clearHistory: () => void;
|
|
45
|
-
messages: ai.UIMessage[];
|
|
46
|
-
error: undefined | Error;
|
|
47
|
-
append: (
|
|
48
|
-
message: Message | ai.CreateMessage,
|
|
49
|
-
chatRequestOptions?: ai.ChatRequestOptions
|
|
50
|
-
) => Promise<string | null | undefined>;
|
|
51
|
-
reload: (
|
|
52
|
-
chatRequestOptions?: ai.ChatRequestOptions
|
|
53
|
-
) => Promise<string | null | undefined>;
|
|
54
|
-
stop: () => void;
|
|
55
|
-
input: string;
|
|
56
|
-
setInput: React.Dispatch<React.SetStateAction<string>>;
|
|
57
|
-
handleInputChange: (
|
|
58
|
-
e:
|
|
59
|
-
| React.ChangeEvent<HTMLInputElement>
|
|
60
|
-
| React.ChangeEvent<HTMLTextAreaElement>
|
|
61
|
-
) => void;
|
|
62
|
-
handleSubmit: (
|
|
63
|
-
event?: {
|
|
64
|
-
preventDefault?: () => void;
|
|
65
|
-
},
|
|
66
|
-
chatRequestOptions?: ai.ChatRequestOptions
|
|
67
|
-
) => void;
|
|
68
|
-
metadata?: Object;
|
|
69
|
-
isLoading: boolean;
|
|
70
|
-
status: "submitted" | "streaming" | "ready" | "error";
|
|
71
|
-
data?: ai.JSONValue[];
|
|
72
|
-
setData: (
|
|
73
|
-
data:
|
|
74
|
-
| ai.JSONValue[]
|
|
75
|
-
| undefined
|
|
76
|
-
| ((data: ai.JSONValue[] | undefined) => ai.JSONValue[] | undefined)
|
|
77
|
-
) => void;
|
|
78
|
-
id: string;
|
|
79
|
-
addToolResult: ({
|
|
80
|
-
toolCallId,
|
|
81
|
-
result,
|
|
82
|
-
}: {
|
|
83
|
-
toolCallId: string;
|
|
84
|
-
result: any;
|
|
85
|
-
}) => void;
|
|
86
90
|
};
|
|
87
91
|
|
|
88
|
-
export { useAgentChat };
|
|
92
|
+
export { type AITool, detectToolsRequiringConfirmation, useAgentChat };
|
package/dist/ai-react.js
CHANGED
|
@@ -1,12 +1,27 @@
|
|
|
1
|
-
import "./chunk-
|
|
1
|
+
import "./chunk-AVYJQSLW.js";
|
|
2
2
|
|
|
3
3
|
// src/ai-react.tsx
|
|
4
4
|
import { useChat } from "@ai-sdk/react";
|
|
5
|
-
import {
|
|
5
|
+
import { getToolName, isToolUIPart } from "ai";
|
|
6
|
+
import { DefaultChatTransport } from "ai";
|
|
6
7
|
import { nanoid } from "nanoid";
|
|
8
|
+
import { use, useEffect, useRef } from "react";
|
|
7
9
|
var requestCache = /* @__PURE__ */ new Map();
|
|
10
|
+
function detectToolsRequiringConfirmation(tools) {
|
|
11
|
+
if (!tools) return [];
|
|
12
|
+
return Object.entries(tools).filter(([_name, tool]) => !tool.execute).map(([name]) => name);
|
|
13
|
+
}
|
|
8
14
|
function useAgentChat(options) {
|
|
9
|
-
const {
|
|
15
|
+
const {
|
|
16
|
+
agent,
|
|
17
|
+
getInitialMessages,
|
|
18
|
+
messages: optionsInitialMessages,
|
|
19
|
+
experimental_automaticToolResolution,
|
|
20
|
+
tools,
|
|
21
|
+
toolsRequiringConfirmation: manualToolsRequiringConfirmation,
|
|
22
|
+
...rest
|
|
23
|
+
} = options;
|
|
24
|
+
const toolsRequiringConfirmation = manualToolsRequiringConfirmation ?? detectToolsRequiringConfirmation(tools);
|
|
10
25
|
const agentUrl = new URL(
|
|
11
26
|
`${// @ts-expect-error we're using a protected _url property that includes query params
|
|
12
27
|
(agent._url || agent._pkurl)?.replace("ws://", "http://").replace("wss://", "https://")}`
|
|
@@ -19,10 +34,25 @@ function useAgentChat(options) {
|
|
|
19
34
|
const getMessagesUrl = new URL(url);
|
|
20
35
|
getMessagesUrl.pathname += "/get-messages";
|
|
21
36
|
const response = await fetch(getMessagesUrl.toString(), {
|
|
22
|
-
|
|
23
|
-
|
|
37
|
+
credentials: options.credentials,
|
|
38
|
+
headers: options.headers
|
|
24
39
|
});
|
|
25
|
-
|
|
40
|
+
if (!response.ok) {
|
|
41
|
+
console.warn(
|
|
42
|
+
`Failed to fetch initial messages: ${response.status} ${response.statusText}`
|
|
43
|
+
);
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
46
|
+
const text = await response.text();
|
|
47
|
+
if (!text.trim()) {
|
|
48
|
+
return [];
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
return JSON.parse(text);
|
|
52
|
+
} catch (error) {
|
|
53
|
+
console.warn("Failed to parse initial messages JSON:", error);
|
|
54
|
+
return [];
|
|
55
|
+
}
|
|
26
56
|
}
|
|
27
57
|
const getInitialMessagesFetch = getInitialMessages || defaultGetInitialMessagesFetch;
|
|
28
58
|
function doGetInitialMessages(getInitialMessagesOptions) {
|
|
@@ -38,7 +68,7 @@ function useAgentChat(options) {
|
|
|
38
68
|
name: agent.name,
|
|
39
69
|
url: agentUrlString
|
|
40
70
|
});
|
|
41
|
-
const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) :
|
|
71
|
+
const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) : optionsInitialMessages ?? [];
|
|
42
72
|
useEffect(() => {
|
|
43
73
|
if (!initialMessagesPromise) {
|
|
44
74
|
return;
|
|
@@ -64,18 +94,22 @@ function useAgentChat(options) {
|
|
|
64
94
|
referrer,
|
|
65
95
|
referrerPolicy,
|
|
66
96
|
window
|
|
67
|
-
// dispatcher, duplex
|
|
68
97
|
} = options2;
|
|
69
98
|
const id = nanoid(8);
|
|
70
99
|
const abortController = new AbortController();
|
|
100
|
+
let controller;
|
|
101
|
+
let isToolCallInProgress = false;
|
|
71
102
|
signal?.addEventListener("abort", () => {
|
|
72
103
|
agent.send(
|
|
73
104
|
JSON.stringify({
|
|
74
|
-
|
|
75
|
-
|
|
105
|
+
id,
|
|
106
|
+
type: "cf_agent_chat_request_cancel" /* CF_AGENT_CHAT_REQUEST_CANCEL */
|
|
76
107
|
})
|
|
77
108
|
);
|
|
78
109
|
abortController.abort();
|
|
110
|
+
if (!isToolCallInProgress) {
|
|
111
|
+
controller.close();
|
|
112
|
+
}
|
|
79
113
|
});
|
|
80
114
|
agent.addEventListener(
|
|
81
115
|
"message",
|
|
@@ -83,22 +117,35 @@ function useAgentChat(options) {
|
|
|
83
117
|
let data;
|
|
84
118
|
try {
|
|
85
119
|
data = JSON.parse(event.data);
|
|
86
|
-
} catch (
|
|
120
|
+
} catch (_error) {
|
|
87
121
|
return;
|
|
88
122
|
}
|
|
89
|
-
if (data.type === "cf_agent_use_chat_response") {
|
|
123
|
+
if (data.type === "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */) {
|
|
90
124
|
if (data.id === id) {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
controller.close();
|
|
125
|
+
if (data.error) {
|
|
126
|
+
controller.error(new Error(data.body));
|
|
94
127
|
abortController.abort();
|
|
128
|
+
} else {
|
|
129
|
+
if (data.body?.trim()) {
|
|
130
|
+
if (data.body.includes('"tool_calls"')) {
|
|
131
|
+
isToolCallInProgress = true;
|
|
132
|
+
}
|
|
133
|
+
controller.enqueue(
|
|
134
|
+
new TextEncoder().encode(`data: ${data.body}
|
|
135
|
+
|
|
136
|
+
`)
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
if (data.done && !isToolCallInProgress) {
|
|
140
|
+
controller.close();
|
|
141
|
+
abortController.abort();
|
|
142
|
+
}
|
|
95
143
|
}
|
|
96
144
|
}
|
|
97
145
|
}
|
|
98
146
|
},
|
|
99
147
|
{ signal: abortController.signal }
|
|
100
148
|
);
|
|
101
|
-
let controller;
|
|
102
149
|
const stream = new ReadableStream({
|
|
103
150
|
start(c) {
|
|
104
151
|
controller = c;
|
|
@@ -106,60 +153,119 @@ function useAgentChat(options) {
|
|
|
106
153
|
});
|
|
107
154
|
agent.send(
|
|
108
155
|
JSON.stringify({
|
|
109
|
-
type: "cf_agent_use_chat_request",
|
|
110
156
|
id,
|
|
111
|
-
url: request.toString(),
|
|
112
157
|
init: {
|
|
113
|
-
method,
|
|
114
|
-
keepalive,
|
|
115
|
-
headers,
|
|
116
158
|
body,
|
|
117
|
-
redirect,
|
|
118
|
-
integrity,
|
|
119
159
|
credentials,
|
|
160
|
+
headers,
|
|
161
|
+
integrity,
|
|
162
|
+
keepalive,
|
|
163
|
+
method,
|
|
120
164
|
mode,
|
|
165
|
+
redirect,
|
|
121
166
|
referrer,
|
|
122
167
|
referrerPolicy,
|
|
123
168
|
window
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
169
|
+
},
|
|
170
|
+
type: "cf_agent_use_chat_request" /* CF_AGENT_USE_CHAT_REQUEST */,
|
|
171
|
+
url: request.toString()
|
|
127
172
|
})
|
|
128
173
|
);
|
|
129
174
|
return new Response(stream);
|
|
130
175
|
}
|
|
176
|
+
const customTransport = {
|
|
177
|
+
sendMessages: async (options2) => {
|
|
178
|
+
const transport = new DefaultChatTransport({
|
|
179
|
+
api: agentUrlString,
|
|
180
|
+
fetch: aiFetch
|
|
181
|
+
});
|
|
182
|
+
return transport.sendMessages(options2);
|
|
183
|
+
},
|
|
184
|
+
reconnectToStream: async (options2) => {
|
|
185
|
+
const transport = new DefaultChatTransport({
|
|
186
|
+
api: agentUrlString,
|
|
187
|
+
fetch: aiFetch
|
|
188
|
+
});
|
|
189
|
+
return transport.reconnectToStream(options2);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
131
192
|
const useChatHelpers = useChat({
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
...rest
|
|
193
|
+
...rest,
|
|
194
|
+
messages: initialMessages,
|
|
195
|
+
transport: customTransport
|
|
136
196
|
});
|
|
197
|
+
const processedToolCalls = useRef(/* @__PURE__ */ new Set());
|
|
198
|
+
useEffect(() => {
|
|
199
|
+
if (!experimental_automaticToolResolution) {
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
|
|
203
|
+
if (!lastMessage || lastMessage.role !== "assistant") {
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
const toolCalls = lastMessage.parts.filter(
|
|
207
|
+
(part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId)
|
|
208
|
+
);
|
|
209
|
+
if (toolCalls.length > 0) {
|
|
210
|
+
(async () => {
|
|
211
|
+
const toolCallsToResolve = toolCalls.filter(
|
|
212
|
+
(part) => isToolUIPart(part) && !toolsRequiringConfirmation.includes(getToolName(part)) && tools?.[getToolName(part)]?.execute
|
|
213
|
+
// Only execute if client has execute function
|
|
214
|
+
);
|
|
215
|
+
if (toolCallsToResolve.length > 0) {
|
|
216
|
+
for (const part of toolCallsToResolve) {
|
|
217
|
+
if (isToolUIPart(part)) {
|
|
218
|
+
processedToolCalls.current.add(part.toolCallId);
|
|
219
|
+
let toolOutput = null;
|
|
220
|
+
const toolName = getToolName(part);
|
|
221
|
+
const tool = tools?.[toolName];
|
|
222
|
+
if (tool?.execute && part.input) {
|
|
223
|
+
try {
|
|
224
|
+
toolOutput = await tool.execute(part.input);
|
|
225
|
+
} catch (error) {
|
|
226
|
+
toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
await useChatHelpers.addToolResult({
|
|
230
|
+
toolCallId: part.toolCallId,
|
|
231
|
+
tool: toolName,
|
|
232
|
+
output: toolOutput
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
useChatHelpers.sendMessage();
|
|
237
|
+
}
|
|
238
|
+
})();
|
|
239
|
+
}
|
|
240
|
+
}, [
|
|
241
|
+
useChatHelpers.messages,
|
|
242
|
+
experimental_automaticToolResolution,
|
|
243
|
+
useChatHelpers.addToolResult,
|
|
244
|
+
useChatHelpers.sendMessage,
|
|
245
|
+
toolsRequiringConfirmation
|
|
246
|
+
]);
|
|
137
247
|
useEffect(() => {
|
|
138
248
|
function onClearHistory(event) {
|
|
139
|
-
if (typeof event.data !== "string")
|
|
140
|
-
return;
|
|
141
|
-
}
|
|
249
|
+
if (typeof event.data !== "string") return;
|
|
142
250
|
let data;
|
|
143
251
|
try {
|
|
144
252
|
data = JSON.parse(event.data);
|
|
145
|
-
} catch (
|
|
253
|
+
} catch (_error) {
|
|
146
254
|
return;
|
|
147
255
|
}
|
|
148
|
-
if (data.type === "cf_agent_chat_clear") {
|
|
256
|
+
if (data.type === "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */) {
|
|
149
257
|
useChatHelpers.setMessages([]);
|
|
150
258
|
}
|
|
151
259
|
}
|
|
152
260
|
function onMessages(event) {
|
|
153
|
-
if (typeof event.data !== "string")
|
|
154
|
-
return;
|
|
155
|
-
}
|
|
261
|
+
if (typeof event.data !== "string") return;
|
|
156
262
|
let data;
|
|
157
263
|
try {
|
|
158
264
|
data = JSON.parse(event.data);
|
|
159
|
-
} catch (
|
|
265
|
+
} catch (_error) {
|
|
160
266
|
return;
|
|
161
267
|
}
|
|
162
|
-
if (data.type === "cf_agent_chat_messages") {
|
|
268
|
+
if (data.type === "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */) {
|
|
163
269
|
useChatHelpers.setMessages(data.messages);
|
|
164
270
|
}
|
|
165
271
|
}
|
|
@@ -170,35 +276,35 @@ function useAgentChat(options) {
|
|
|
170
276
|
agent.removeEventListener("message", onMessages);
|
|
171
277
|
};
|
|
172
278
|
}, [agent, useChatHelpers.setMessages]);
|
|
279
|
+
const { addToolResult } = useChatHelpers;
|
|
280
|
+
const addToolResultAndSendMessage = async (...args) => {
|
|
281
|
+
await addToolResult(...args);
|
|
282
|
+
useChatHelpers.sendMessage();
|
|
283
|
+
};
|
|
173
284
|
return {
|
|
174
285
|
...useChatHelpers,
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
*/
|
|
179
|
-
setMessages: (messages) => {
|
|
180
|
-
useChatHelpers.setMessages(messages);
|
|
286
|
+
addToolResult: addToolResultAndSendMessage,
|
|
287
|
+
clearHistory: () => {
|
|
288
|
+
useChatHelpers.setMessages([]);
|
|
181
289
|
agent.send(
|
|
182
290
|
JSON.stringify({
|
|
183
|
-
type: "
|
|
184
|
-
messages
|
|
291
|
+
type: "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */
|
|
185
292
|
})
|
|
186
293
|
);
|
|
187
294
|
},
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
*/
|
|
191
|
-
clearHistory: () => {
|
|
192
|
-
useChatHelpers.setMessages([]);
|
|
295
|
+
setMessages: (messages) => {
|
|
296
|
+
useChatHelpers.setMessages(messages);
|
|
193
297
|
agent.send(
|
|
194
298
|
JSON.stringify({
|
|
195
|
-
|
|
299
|
+
messages: Array.isArray(messages) ? messages : [],
|
|
300
|
+
type: "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */
|
|
196
301
|
})
|
|
197
302
|
);
|
|
198
303
|
}
|
|
199
304
|
};
|
|
200
305
|
}
|
|
201
306
|
export {
|
|
307
|
+
detectToolsRequiringConfirmation,
|
|
202
308
|
useAgentChat
|
|
203
309
|
};
|
|
204
310
|
//# sourceMappingURL=ai-react.js.map
|