agents 0.0.0-2a6e66e → 0.0.0-2b4c060
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 +7 -6
- package/dist/ai-chat-agent.js +148 -47
- 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-chat-v5-migration.js.map +1 -0
- package/dist/ai-react.d.ts +63 -69
- package/dist/ai-react.js +177 -37
- 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-PVQZBKN7.js → chunk-LL2AFX7V.js} +5 -2
- package/dist/chunk-LL2AFX7V.js.map +1 -0
- package/dist/{chunk-HY7ZLHJB.js → chunk-MH46VMM4.js} +18 -4
- package/dist/chunk-MH46VMM4.js.map +1 -0
- package/dist/{chunk-KUH345EY.js → chunk-QEVM4BVL.js} +5 -5
- 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-CV3L6FQZ.js → chunk-YDUDMOL6.js} +71 -65
- package/dist/chunk-YDUDMOL6.js.map +1 -0
- package/dist/{client-DgyzBU_8.d.ts → client-CvaJdLQA.d.ts} +425 -11
- package/dist/client.js +2 -1
- package/dist/index.d.ts +24 -7
- package/dist/index.js +7 -4
- package/dist/mcp/client.d.ts +1 -1
- package/dist/mcp/client.js +1 -1
- package/dist/mcp/do-oauth-client-provider.d.ts +1 -0
- package/dist/mcp/do-oauth-client-provider.js +1 -1
- package/dist/mcp/index.d.ts +61 -76
- package/dist/mcp/index.js +812 -738
- package/dist/mcp/index.js.map +1 -1
- package/dist/observability/index.js +5 -4
- package/dist/react.d.ts +2 -1
- package/dist/react.js +7 -5
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +76 -2
- package/dist/schedule.js +15 -2
- package/dist/schedule.js.map +1 -1
- package/package.json +13 -6
- package/src/index.ts +102 -75
- package/dist/chunk-CV3L6FQZ.js.map +0 -1
- package/dist/chunk-HY7ZLHJB.js.map +0 -1
- package/dist/chunk-KUH345EY.js.map +0 -1
- package/dist/chunk-PVQZBKN7.js.map +0 -1
|
@@ -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
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/ai-react.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
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";
|
|
@@ -9,7 +8,7 @@ import "cloudflare:workers";
|
|
|
9
8
|
import "@modelcontextprotocol/sdk/client/index.js";
|
|
10
9
|
import "@modelcontextprotocol/sdk/types.js";
|
|
11
10
|
import "partyserver";
|
|
12
|
-
import "./client-
|
|
11
|
+
import "./client-CvaJdLQA.js";
|
|
13
12
|
import "zod";
|
|
14
13
|
import "@modelcontextprotocol/sdk/shared/protocol.js";
|
|
15
14
|
import "@modelcontextprotocol/sdk/client/sse.js";
|
|
@@ -18,87 +17,82 @@ import "./mcp/do-oauth-client-provider.js";
|
|
|
18
17
|
import "@modelcontextprotocol/sdk/client/auth.js";
|
|
19
18
|
import "@modelcontextprotocol/sdk/shared/auth.js";
|
|
20
19
|
import "./observability/index.js";
|
|
20
|
+
import "./ai-types.js";
|
|
21
21
|
import "./client.js";
|
|
22
22
|
import "./serializable.js";
|
|
23
23
|
|
|
24
|
+
type AITool<Input = unknown, Output = unknown> = {
|
|
25
|
+
description?: string;
|
|
26
|
+
inputSchema?: unknown;
|
|
27
|
+
execute?: (input: Input) => Output | Promise<Output>;
|
|
28
|
+
};
|
|
24
29
|
type GetInitialMessagesOptions = {
|
|
25
30
|
agent: string;
|
|
26
31
|
name: string;
|
|
27
32
|
url: string;
|
|
28
33
|
};
|
|
34
|
+
type UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &
|
|
35
|
+
UseChatOptions<M>;
|
|
29
36
|
/**
|
|
30
37
|
* Options for the useAgentChat hook
|
|
31
38
|
*/
|
|
32
|
-
type UseAgentChatOptions<
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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
|
+
/**
|
|
69
|
+
* When true (default), automatically sends the next message only after
|
|
70
|
+
* all pending confirmation-required tool calls have been resolved.
|
|
71
|
+
* @default true
|
|
72
|
+
*/
|
|
73
|
+
autoSendAfterAllConfirmationsResolved?: boolean;
|
|
74
|
+
};
|
|
43
75
|
/**
|
|
44
76
|
* React hook for building AI chat interfaces using an Agent
|
|
45
77
|
* @param options Chat options including the agent connection
|
|
46
78
|
* @returns Chat interface controls and state with added clearHistory method
|
|
47
79
|
*/
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
80
|
+
/**
|
|
81
|
+
* Automatically detects which tools require confirmation based on their configuration.
|
|
82
|
+
* Tools require confirmation if they have no execute function AND are not server-executed.
|
|
83
|
+
* @param tools - Record of tool name to tool definition
|
|
84
|
+
* @returns Array of tool names that require confirmation
|
|
85
|
+
*/
|
|
86
|
+
declare function detectToolsRequiringConfirmation(
|
|
87
|
+
tools?: Record<string, AITool<unknown, unknown>>
|
|
88
|
+
): string[];
|
|
89
|
+
declare function useAgentChat<
|
|
90
|
+
State = unknown,
|
|
91
|
+
ChatMessage extends UIMessage = UIMessage
|
|
92
|
+
>(
|
|
93
|
+
options: UseAgentChatOptions<State, ChatMessage>
|
|
94
|
+
): ReturnType<typeof useChat<ChatMessage>> & {
|
|
54
95
|
clearHistory: () => void;
|
|
55
|
-
/**
|
|
56
|
-
* Set the chat messages and synchronize with the Agent
|
|
57
|
-
* @param messages New messages to set
|
|
58
|
-
*/
|
|
59
|
-
setMessages: (messages: Message[]) => void;
|
|
60
|
-
messages: ai.UIMessage[];
|
|
61
|
-
error: undefined | Error;
|
|
62
|
-
append: (
|
|
63
|
-
message: Message | ai.CreateMessage,
|
|
64
|
-
chatRequestOptions?: ai.ChatRequestOptions
|
|
65
|
-
) => Promise<string | null | undefined>;
|
|
66
|
-
reload: (
|
|
67
|
-
chatRequestOptions?: ai.ChatRequestOptions
|
|
68
|
-
) => Promise<string | null | undefined>;
|
|
69
|
-
stop: () => void;
|
|
70
|
-
experimental_resume: () => void;
|
|
71
|
-
input: string;
|
|
72
|
-
setInput: React.Dispatch<React.SetStateAction<string>>;
|
|
73
|
-
handleInputChange: (
|
|
74
|
-
e:
|
|
75
|
-
| React.ChangeEvent<HTMLInputElement>
|
|
76
|
-
| React.ChangeEvent<HTMLTextAreaElement>
|
|
77
|
-
) => void;
|
|
78
|
-
handleSubmit: (
|
|
79
|
-
event?: {
|
|
80
|
-
preventDefault?: () => void;
|
|
81
|
-
},
|
|
82
|
-
chatRequestOptions?: ai.ChatRequestOptions
|
|
83
|
-
) => void;
|
|
84
|
-
metadata?: Object;
|
|
85
|
-
isLoading: boolean;
|
|
86
|
-
status: "submitted" | "streaming" | "ready" | "error";
|
|
87
|
-
data?: ai.JSONValue[];
|
|
88
|
-
setData: (
|
|
89
|
-
data:
|
|
90
|
-
| ai.JSONValue[]
|
|
91
|
-
| undefined
|
|
92
|
-
| ((data: ai.JSONValue[] | undefined) => ai.JSONValue[] | undefined)
|
|
93
|
-
) => void;
|
|
94
|
-
id: string;
|
|
95
|
-
addToolResult: ({
|
|
96
|
-
toolCallId,
|
|
97
|
-
result
|
|
98
|
-
}: {
|
|
99
|
-
toolCallId: string;
|
|
100
|
-
result: any;
|
|
101
|
-
}) => void;
|
|
102
96
|
};
|
|
103
97
|
|
|
104
|
-
export { useAgentChat };
|
|
98
|
+
export { type AITool, detectToolsRequiringConfirmation, useAgentChat };
|
package/dist/ai-react.js
CHANGED
|
@@ -1,10 +1,28 @@
|
|
|
1
|
+
import "./chunk-AVYJQSLW.js";
|
|
2
|
+
|
|
1
3
|
// src/ai-react.tsx
|
|
2
4
|
import { useChat } from "@ai-sdk/react";
|
|
5
|
+
import { getToolName, isToolUIPart } from "ai";
|
|
6
|
+
import { DefaultChatTransport } from "ai";
|
|
3
7
|
import { nanoid } from "nanoid";
|
|
4
|
-
import { use, useEffect } from "react";
|
|
8
|
+
import { use, useEffect, useRef } from "react";
|
|
5
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
|
+
}
|
|
6
14
|
function useAgentChat(options) {
|
|
7
|
-
const {
|
|
15
|
+
const {
|
|
16
|
+
agent,
|
|
17
|
+
getInitialMessages,
|
|
18
|
+
messages: optionsInitialMessages,
|
|
19
|
+
experimental_automaticToolResolution,
|
|
20
|
+
tools,
|
|
21
|
+
toolsRequiringConfirmation: manualToolsRequiringConfirmation,
|
|
22
|
+
autoSendAfterAllConfirmationsResolved = true,
|
|
23
|
+
...rest
|
|
24
|
+
} = options;
|
|
25
|
+
const toolsRequiringConfirmation = manualToolsRequiringConfirmation ?? detectToolsRequiringConfirmation(tools);
|
|
8
26
|
const agentUrl = new URL(
|
|
9
27
|
`${// @ts-expect-error we're using a protected _url property that includes query params
|
|
10
28
|
(agent._url || agent._pkurl)?.replace("ws://", "http://").replace("wss://", "https://")}`
|
|
@@ -20,7 +38,22 @@ function useAgentChat(options) {
|
|
|
20
38
|
credentials: options.credentials,
|
|
21
39
|
headers: options.headers
|
|
22
40
|
});
|
|
23
|
-
|
|
41
|
+
if (!response.ok) {
|
|
42
|
+
console.warn(
|
|
43
|
+
`Failed to fetch initial messages: ${response.status} ${response.statusText}`
|
|
44
|
+
);
|
|
45
|
+
return [];
|
|
46
|
+
}
|
|
47
|
+
const text = await response.text();
|
|
48
|
+
if (!text.trim()) {
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
try {
|
|
52
|
+
return JSON.parse(text);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
console.warn("Failed to parse initial messages JSON:", error);
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
24
57
|
}
|
|
25
58
|
const getInitialMessagesFetch = getInitialMessages || defaultGetInitialMessagesFetch;
|
|
26
59
|
function doGetInitialMessages(getInitialMessagesOptions) {
|
|
@@ -36,7 +69,7 @@ function useAgentChat(options) {
|
|
|
36
69
|
name: agent.name,
|
|
37
70
|
url: agentUrlString
|
|
38
71
|
});
|
|
39
|
-
const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) :
|
|
72
|
+
const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) : optionsInitialMessages ?? [];
|
|
40
73
|
useEffect(() => {
|
|
41
74
|
if (!initialMessagesPromise) {
|
|
42
75
|
return;
|
|
@@ -62,19 +95,22 @@ function useAgentChat(options) {
|
|
|
62
95
|
referrer,
|
|
63
96
|
referrerPolicy,
|
|
64
97
|
window
|
|
65
|
-
// dispatcher, duplex
|
|
66
98
|
} = options2;
|
|
67
99
|
const id = nanoid(8);
|
|
68
100
|
const abortController = new AbortController();
|
|
101
|
+
let controller;
|
|
102
|
+
let isToolCallInProgress = false;
|
|
69
103
|
signal?.addEventListener("abort", () => {
|
|
70
104
|
agent.send(
|
|
71
105
|
JSON.stringify({
|
|
72
106
|
id,
|
|
73
|
-
type: "cf_agent_chat_request_cancel"
|
|
107
|
+
type: "cf_agent_chat_request_cancel" /* CF_AGENT_CHAT_REQUEST_CANCEL */
|
|
74
108
|
})
|
|
75
109
|
);
|
|
76
110
|
abortController.abort();
|
|
77
|
-
|
|
111
|
+
if (!isToolCallInProgress) {
|
|
112
|
+
controller.close();
|
|
113
|
+
}
|
|
78
114
|
});
|
|
79
115
|
agent.addEventListener(
|
|
80
116
|
"message",
|
|
@@ -85,19 +121,32 @@ function useAgentChat(options) {
|
|
|
85
121
|
} catch (_error) {
|
|
86
122
|
return;
|
|
87
123
|
}
|
|
88
|
-
if (data.type === "cf_agent_use_chat_response") {
|
|
124
|
+
if (data.type === "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */) {
|
|
89
125
|
if (data.id === id) {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
controller.close();
|
|
126
|
+
if (data.error) {
|
|
127
|
+
controller.error(new Error(data.body));
|
|
93
128
|
abortController.abort();
|
|
129
|
+
} else {
|
|
130
|
+
if (data.body?.trim()) {
|
|
131
|
+
if (data.body.includes('"tool_calls"')) {
|
|
132
|
+
isToolCallInProgress = true;
|
|
133
|
+
}
|
|
134
|
+
controller.enqueue(
|
|
135
|
+
new TextEncoder().encode(`data: ${data.body}
|
|
136
|
+
|
|
137
|
+
`)
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
if (data.done && !isToolCallInProgress) {
|
|
141
|
+
controller.close();
|
|
142
|
+
abortController.abort();
|
|
143
|
+
}
|
|
94
144
|
}
|
|
95
145
|
}
|
|
96
146
|
}
|
|
97
147
|
},
|
|
98
148
|
{ signal: abortController.signal }
|
|
99
149
|
);
|
|
100
|
-
let controller;
|
|
101
150
|
const stream = new ReadableStream({
|
|
102
151
|
start(c) {
|
|
103
152
|
controller = c;
|
|
@@ -118,47 +167,123 @@ function useAgentChat(options) {
|
|
|
118
167
|
referrer,
|
|
119
168
|
referrerPolicy,
|
|
120
169
|
window
|
|
121
|
-
// dispatcher,
|
|
122
|
-
// duplex
|
|
123
170
|
},
|
|
124
|
-
type: "cf_agent_use_chat_request"
|
|
171
|
+
type: "cf_agent_use_chat_request" /* CF_AGENT_USE_CHAT_REQUEST */,
|
|
125
172
|
url: request.toString()
|
|
126
173
|
})
|
|
127
174
|
);
|
|
128
175
|
return new Response(stream);
|
|
129
176
|
}
|
|
177
|
+
const customTransport = {
|
|
178
|
+
sendMessages: async (options2) => {
|
|
179
|
+
const transport = new DefaultChatTransport({
|
|
180
|
+
api: agentUrlString,
|
|
181
|
+
fetch: aiFetch
|
|
182
|
+
});
|
|
183
|
+
return transport.sendMessages(options2);
|
|
184
|
+
},
|
|
185
|
+
reconnectToStream: async (options2) => {
|
|
186
|
+
const transport = new DefaultChatTransport({
|
|
187
|
+
api: agentUrlString,
|
|
188
|
+
fetch: aiFetch
|
|
189
|
+
});
|
|
190
|
+
return transport.reconnectToStream(options2);
|
|
191
|
+
}
|
|
192
|
+
};
|
|
130
193
|
const useChatHelpers = useChat({
|
|
131
|
-
|
|
132
|
-
initialMessages,
|
|
133
|
-
|
|
134
|
-
...rest
|
|
194
|
+
...rest,
|
|
195
|
+
messages: initialMessages,
|
|
196
|
+
transport: customTransport
|
|
135
197
|
});
|
|
198
|
+
const processedToolCalls = useRef(/* @__PURE__ */ new Set());
|
|
199
|
+
const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
|
|
200
|
+
const pendingConfirmations = (() => {
|
|
201
|
+
if (!lastMessage || lastMessage.role !== "assistant") {
|
|
202
|
+
return { messageId: void 0, toolCallIds: /* @__PURE__ */ new Set() };
|
|
203
|
+
}
|
|
204
|
+
const pendingIds = /* @__PURE__ */ new Set();
|
|
205
|
+
for (const part of lastMessage.parts ?? []) {
|
|
206
|
+
if (isToolUIPart(part) && part.state === "input-available" && toolsRequiringConfirmation.includes(getToolName(part))) {
|
|
207
|
+
pendingIds.add(part.toolCallId);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return { messageId: lastMessage.id, toolCallIds: pendingIds };
|
|
211
|
+
})();
|
|
212
|
+
const pendingConfirmationsRef = useRef(pendingConfirmations);
|
|
213
|
+
pendingConfirmationsRef.current = pendingConfirmations;
|
|
214
|
+
useEffect(() => {
|
|
215
|
+
if (!experimental_automaticToolResolution) {
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const lastMessage2 = useChatHelpers.messages[useChatHelpers.messages.length - 1];
|
|
219
|
+
if (!lastMessage2 || lastMessage2.role !== "assistant") {
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
const toolCalls = lastMessage2.parts.filter(
|
|
223
|
+
(part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId)
|
|
224
|
+
);
|
|
225
|
+
if (toolCalls.length > 0) {
|
|
226
|
+
(async () => {
|
|
227
|
+
const toolCallsToResolve = toolCalls.filter(
|
|
228
|
+
(part) => isToolUIPart(part) && !toolsRequiringConfirmation.includes(getToolName(part)) && tools?.[getToolName(part)]?.execute
|
|
229
|
+
// Only execute if client has execute function
|
|
230
|
+
);
|
|
231
|
+
if (toolCallsToResolve.length > 0) {
|
|
232
|
+
for (const part of toolCallsToResolve) {
|
|
233
|
+
if (isToolUIPart(part)) {
|
|
234
|
+
processedToolCalls.current.add(part.toolCallId);
|
|
235
|
+
let toolOutput = null;
|
|
236
|
+
const toolName = getToolName(part);
|
|
237
|
+
const tool = tools?.[toolName];
|
|
238
|
+
if (tool?.execute && part.input) {
|
|
239
|
+
try {
|
|
240
|
+
toolOutput = await tool.execute(part.input);
|
|
241
|
+
} catch (error) {
|
|
242
|
+
toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
await useChatHelpers.addToolResult({
|
|
246
|
+
toolCallId: part.toolCallId,
|
|
247
|
+
tool: toolName,
|
|
248
|
+
output: toolOutput
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (pendingConfirmationsRef.current.toolCallIds.size === 0) {
|
|
253
|
+
useChatHelpers.sendMessage();
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
})();
|
|
257
|
+
}
|
|
258
|
+
}, [
|
|
259
|
+
useChatHelpers.messages,
|
|
260
|
+
experimental_automaticToolResolution,
|
|
261
|
+
useChatHelpers.addToolResult,
|
|
262
|
+
useChatHelpers.sendMessage,
|
|
263
|
+
toolsRequiringConfirmation
|
|
264
|
+
]);
|
|
136
265
|
useEffect(() => {
|
|
137
266
|
function onClearHistory(event) {
|
|
138
|
-
if (typeof event.data !== "string")
|
|
139
|
-
return;
|
|
140
|
-
}
|
|
267
|
+
if (typeof event.data !== "string") return;
|
|
141
268
|
let data;
|
|
142
269
|
try {
|
|
143
270
|
data = JSON.parse(event.data);
|
|
144
271
|
} catch (_error) {
|
|
145
272
|
return;
|
|
146
273
|
}
|
|
147
|
-
if (data.type === "cf_agent_chat_clear") {
|
|
274
|
+
if (data.type === "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */) {
|
|
148
275
|
useChatHelpers.setMessages([]);
|
|
149
276
|
}
|
|
150
277
|
}
|
|
151
278
|
function onMessages(event) {
|
|
152
|
-
if (typeof event.data !== "string")
|
|
153
|
-
return;
|
|
154
|
-
}
|
|
279
|
+
if (typeof event.data !== "string") return;
|
|
155
280
|
let data;
|
|
156
281
|
try {
|
|
157
282
|
data = JSON.parse(event.data);
|
|
158
283
|
} catch (_error) {
|
|
159
284
|
return;
|
|
160
285
|
}
|
|
161
|
-
if (data.type === "cf_agent_chat_messages") {
|
|
286
|
+
if (data.type === "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */) {
|
|
162
287
|
useChatHelpers.setMessages(data.messages);
|
|
163
288
|
}
|
|
164
289
|
}
|
|
@@ -169,35 +294,50 @@ function useAgentChat(options) {
|
|
|
169
294
|
agent.removeEventListener("message", onMessages);
|
|
170
295
|
};
|
|
171
296
|
}, [agent, useChatHelpers.setMessages]);
|
|
297
|
+
const addToolResultAndSendMessage = async (args) => {
|
|
298
|
+
const { toolCallId } = args;
|
|
299
|
+
await useChatHelpers.addToolResult(args);
|
|
300
|
+
if (!autoSendAfterAllConfirmationsResolved) {
|
|
301
|
+
useChatHelpers.sendMessage();
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
const pending = pendingConfirmationsRef.current?.toolCallIds;
|
|
305
|
+
if (!pending) {
|
|
306
|
+
useChatHelpers.sendMessage();
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
const wasLast = pending.size === 1 && pending.has(toolCallId);
|
|
310
|
+
if (pending.has(toolCallId)) {
|
|
311
|
+
pending.delete(toolCallId);
|
|
312
|
+
}
|
|
313
|
+
if (wasLast || pending.size === 0) {
|
|
314
|
+
useChatHelpers.sendMessage();
|
|
315
|
+
}
|
|
316
|
+
};
|
|
172
317
|
return {
|
|
173
318
|
...useChatHelpers,
|
|
174
|
-
|
|
175
|
-
* Clear chat history on both client and Agent
|
|
176
|
-
*/
|
|
319
|
+
addToolResult: addToolResultAndSendMessage,
|
|
177
320
|
clearHistory: () => {
|
|
178
321
|
useChatHelpers.setMessages([]);
|
|
179
322
|
agent.send(
|
|
180
323
|
JSON.stringify({
|
|
181
|
-
type: "cf_agent_chat_clear"
|
|
324
|
+
type: "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */
|
|
182
325
|
})
|
|
183
326
|
);
|
|
184
327
|
},
|
|
185
|
-
/**
|
|
186
|
-
* Set the chat messages and synchronize with the Agent
|
|
187
|
-
* @param messages New messages to set
|
|
188
|
-
*/
|
|
189
328
|
setMessages: (messages) => {
|
|
190
329
|
useChatHelpers.setMessages(messages);
|
|
191
330
|
agent.send(
|
|
192
331
|
JSON.stringify({
|
|
193
|
-
messages,
|
|
194
|
-
type: "cf_agent_chat_messages"
|
|
332
|
+
messages: Array.isArray(messages) ? messages : [],
|
|
333
|
+
type: "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */
|
|
195
334
|
})
|
|
196
335
|
);
|
|
197
336
|
}
|
|
198
337
|
};
|
|
199
338
|
}
|
|
200
339
|
export {
|
|
340
|
+
detectToolsRequiringConfirmation,
|
|
201
341
|
useAgentChat
|
|
202
342
|
};
|
|
203
343
|
//# sourceMappingURL=ai-react.js.map
|