@4djs/assistant 0.0.0 → 0.0.1
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/dist/core/chat-activity.d.ts +19 -0
- package/dist/core/chat-activity.d.ts.map +1 -0
- package/dist/core/chat-commands.d.ts +33 -0
- package/dist/core/chat-commands.d.ts.map +1 -0
- package/dist/core/chat-history.d.ts +14 -0
- package/dist/core/chat-history.d.ts.map +1 -0
- package/dist/core/chat-reply-suggestions-parse.d.ts +20 -0
- package/dist/core/chat-reply-suggestions-parse.d.ts.map +1 -0
- package/dist/core/code-highlight.d.ts +3 -0
- package/dist/core/code-highlight.d.ts.map +1 -0
- package/dist/core/create-assistant-store.d.ts +33 -0
- package/dist/core/create-assistant-store.d.ts.map +1 -0
- package/dist/core/fetch-suggested-prompts.d.ts +11 -0
- package/dist/core/fetch-suggested-prompts.d.ts.map +1 -0
- package/dist/core/index.d.ts +19 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +2876 -0
- package/dist/core/interactive-tools/choices.d.ts +22 -0
- package/dist/core/interactive-tools/choices.d.ts.map +1 -0
- package/dist/core/interactive-tools/confirmation.d.ts +15 -0
- package/dist/core/interactive-tools/confirmation.d.ts.map +1 -0
- package/dist/core/interactive-tools/constants.d.ts +6 -0
- package/dist/core/interactive-tools/constants.d.ts.map +1 -0
- package/dist/core/interactive-tools/execute.d.ts +11 -0
- package/dist/core/interactive-tools/execute.d.ts.map +1 -0
- package/dist/core/interactive-tools/index.d.ts +7 -0
- package/dist/core/interactive-tools/index.d.ts.map +1 -0
- package/dist/core/interactive-tools/suggestions.d.ts +13 -0
- package/dist/core/interactive-tools/suggestions.d.ts.map +1 -0
- package/dist/core/interactive-tools/waiters.d.ts +4 -0
- package/dist/core/interactive-tools/waiters.d.ts.map +1 -0
- package/dist/core/llm-chat.d.ts +96 -0
- package/dist/core/llm-chat.d.ts.map +1 -0
- package/dist/core/llm-config.d.ts +24 -0
- package/dist/core/llm-config.d.ts.map +1 -0
- package/dist/core/llm-models.d.ts +14 -0
- package/dist/core/llm-models.d.ts.map +1 -0
- package/dist/core/llm-provider.d.ts +13 -0
- package/dist/core/llm-provider.d.ts.map +1 -0
- package/dist/core/llm-settings-storage.d.ts +47 -0
- package/dist/core/llm-settings-storage.d.ts.map +1 -0
- package/dist/core/llm-sse.d.ts +13 -0
- package/dist/core/llm-sse.d.ts.map +1 -0
- package/dist/core/llm-types.d.ts +49 -0
- package/dist/core/llm-types.d.ts.map +1 -0
- package/dist/core/markdown-utils.d.ts +3 -0
- package/dist/core/markdown-utils.d.ts.map +1 -0
- package/dist/core/prepare-markdown.d.ts +7 -0
- package/dist/core/prepare-markdown.d.ts.map +1 -0
- package/dist/core/types.d.ts +74 -0
- package/dist/core/types.d.ts.map +1 -0
- package/dist/index.css +1195 -0
- package/dist/index.js +184948 -0
- package/dist/react/Assistant.d.ts +10 -0
- package/dist/react/Assistant.d.ts.map +1 -0
- package/dist/react/components/HighlightedJsonCode.d.ts +6 -0
- package/dist/react/components/HighlightedJsonCode.d.ts.map +1 -0
- package/dist/react/components/MarkdownContent.d.ts +10 -0
- package/dist/react/components/MarkdownContent.d.ts.map +1 -0
- package/dist/react/components/MarkdownEditor.d.ts +11 -0
- package/dist/react/components/MarkdownEditor.d.ts.map +1 -0
- package/dist/react/components/MermaidDiagram.d.ts +8 -0
- package/dist/react/components/MermaidDiagram.d.ts.map +1 -0
- package/dist/react/components/ModelSelector.d.ts +8 -0
- package/dist/react/components/ModelSelector.d.ts.map +1 -0
- package/dist/react/components/chat/AssistantErrorCallout.d.ts +11 -0
- package/dist/react/components/chat/AssistantErrorCallout.d.ts.map +1 -0
- package/dist/react/components/chat/ChatActivity.d.ts +8 -0
- package/dist/react/components/chat/ChatActivity.d.ts.map +1 -0
- package/dist/react/components/chat/ChatComposer.d.ts +36 -0
- package/dist/react/components/chat/ChatComposer.d.ts.map +1 -0
- package/dist/react/components/chat/ChatEmptyState.d.ts +10 -0
- package/dist/react/components/chat/ChatEmptyState.d.ts.map +1 -0
- package/dist/react/components/chat/ChatInteractivePrompt/choices-prompt.d.ts +7 -0
- package/dist/react/components/chat/ChatInteractivePrompt/choices-prompt.d.ts.map +1 -0
- package/dist/react/components/chat/ChatInteractivePrompt/confirmation-prompt.d.ts +7 -0
- package/dist/react/components/chat/ChatInteractivePrompt/confirmation-prompt.d.ts.map +1 -0
- package/dist/react/components/chat/ChatInteractivePrompt/index.d.ts +7 -0
- package/dist/react/components/chat/ChatInteractivePrompt/index.d.ts.map +1 -0
- package/dist/react/components/chat/ChatInteractivePrompt/shell.d.ts +13 -0
- package/dist/react/components/chat/ChatInteractivePrompt/shell.d.ts.map +1 -0
- package/dist/react/components/chat/ChatInteractivePrompt/utils.d.ts +4 -0
- package/dist/react/components/chat/ChatInteractivePrompt/utils.d.ts.map +1 -0
- package/dist/react/components/chat/ChatMessage.d.ts +11 -0
- package/dist/react/components/chat/ChatMessage.d.ts.map +1 -0
- package/dist/react/components/chat/ChatMessageScroll.d.ts +8 -0
- package/dist/react/components/chat/ChatMessageScroll.d.ts.map +1 -0
- package/dist/react/components/chat/ChatReplySuggestions.d.ts +9 -0
- package/dist/react/components/chat/ChatReplySuggestions.d.ts.map +1 -0
- package/dist/react/components/chat/ComposerCommandMenu.d.ts +10 -0
- package/dist/react/components/chat/ComposerCommandMenu.d.ts.map +1 -0
- package/dist/react/components/chat/LlmSettingsStrip.d.ts +7 -0
- package/dist/react/components/chat/LlmSettingsStrip.d.ts.map +1 -0
- package/dist/react/components/chat/LlmSetupPrompt.d.ts +7 -0
- package/dist/react/components/chat/LlmSetupPrompt.d.ts.map +1 -0
- package/dist/react/components/chat/LlmUnavailableBanner.d.ts +6 -0
- package/dist/react/components/chat/LlmUnavailableBanner.d.ts.map +1 -0
- package/dist/react/components/chat/SuggestedPromptsList.d.ts +14 -0
- package/dist/react/components/chat/SuggestedPromptsList.d.ts.map +1 -0
- package/dist/react/components/chat/SuggestedPromptsStrip.d.ts +11 -0
- package/dist/react/components/chat/SuggestedPromptsStrip.d.ts.map +1 -0
- package/dist/react/components/chat/SystemPromptField.d.ts +10 -0
- package/dist/react/components/chat/SystemPromptField.d.ts.map +1 -0
- package/dist/react/components/highlighted-code.d.ts +8 -0
- package/dist/react/components/highlighted-code.d.ts.map +1 -0
- package/dist/react/context.d.ts +11 -0
- package/dist/react/context.d.ts.map +1 -0
- package/dist/react/hooks/use-composer-commands.d.ts +21 -0
- package/dist/react/hooks/use-composer-commands.d.ts.map +1 -0
- package/dist/react/hooks/use-suggested-prompts.d.ts +29 -0
- package/dist/react/hooks/use-suggested-prompts.d.ts.map +1 -0
- package/dist/react/index.d.ts +17 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/lib/parse-assistant-error.d.ts +9 -0
- package/dist/react/lib/parse-assistant-error.d.ts.map +1 -0
- package/dist/react/lib/prompt-icons.d.ts +5 -0
- package/dist/react/lib/prompt-icons.d.ts.map +1 -0
- package/dist/react/types.d.ts +69 -0
- package/dist/react/types.d.ts.map +1 -0
- package/dist/react/utils/cn.d.ts +2 -0
- package/dist/react/utils/cn.d.ts.map +1 -0
- package/package.json +16 -5
- package/src/core/chat-activity.ts +0 -107
- package/src/core/chat-commands.ts +0 -173
- package/src/core/chat-history.ts +0 -113
- package/src/core/chat-reply-suggestions-parse.ts +0 -119
- package/src/core/code-highlight.ts +0 -20
- package/src/core/create-assistant-store.ts +0 -639
- package/src/core/fetch-suggested-prompts.ts +0 -53
- package/src/core/index.ts +0 -125
- package/src/core/interactive-tools/choices.ts +0 -155
- package/src/core/interactive-tools/confirmation.ts +0 -63
- package/src/core/interactive-tools/constants.ts +0 -22
- package/src/core/interactive-tools/execute.ts +0 -70
- package/src/core/interactive-tools/index.ts +0 -41
- package/src/core/interactive-tools/suggestions.ts +0 -87
- package/src/core/interactive-tools/waiters.ts +0 -55
- package/src/core/llm-chat.ts +0 -686
- package/src/core/llm-config.ts +0 -101
- package/src/core/llm-models.ts +0 -96
- package/src/core/llm-provider.ts +0 -99
- package/src/core/llm-settings-storage.ts +0 -331
- package/src/core/llm-sse.ts +0 -166
- package/src/core/llm-types.ts +0 -52
- package/src/core/markdown-utils.ts +0 -11
- package/src/core/prepare-markdown.ts +0 -38
- package/src/core/types.ts +0 -86
- package/src/css.d.ts +0 -1
- package/src/react/Assistant.tsx +0 -358
- package/src/react/components/HighlightedJsonCode.tsx +0 -24
- package/src/react/components/MarkdownContent.tsx +0 -98
- package/src/react/components/MarkdownEditor.tsx +0 -60
- package/src/react/components/MermaidDiagram.tsx +0 -139
- package/src/react/components/ModelSelector.tsx +0 -243
- package/src/react/components/chat/AssistantErrorCallout.tsx +0 -79
- package/src/react/components/chat/ChatActivity.tsx +0 -274
- package/src/react/components/chat/ChatComposer.tsx +0 -189
- package/src/react/components/chat/ChatEmptyState.tsx +0 -145
- package/src/react/components/chat/ChatInteractivePrompt/choices-prompt.tsx +0 -262
- package/src/react/components/chat/ChatInteractivePrompt/confirmation-prompt.tsx +0 -97
- package/src/react/components/chat/ChatInteractivePrompt/index.tsx +0 -60
- package/src/react/components/chat/ChatInteractivePrompt/shell.tsx +0 -60
- package/src/react/components/chat/ChatInteractivePrompt/utils.ts +0 -14
- package/src/react/components/chat/ChatMessage.tsx +0 -150
- package/src/react/components/chat/ChatMessageScroll.tsx +0 -116
- package/src/react/components/chat/ChatReplySuggestions.tsx +0 -231
- package/src/react/components/chat/ComposerCommandMenu.tsx +0 -69
- package/src/react/components/chat/LlmSettingsStrip.tsx +0 -348
- package/src/react/components/chat/LlmSetupPrompt.tsx +0 -58
- package/src/react/components/chat/LlmUnavailableBanner.tsx +0 -11
- package/src/react/components/chat/SuggestedPromptsList.tsx +0 -121
- package/src/react/components/chat/SuggestedPromptsStrip.tsx +0 -72
- package/src/react/components/chat/SystemPromptField.tsx +0 -107
- package/src/react/components/highlighted-code.tsx +0 -107
- package/src/react/context.tsx +0 -72
- package/src/react/hooks/use-composer-commands.ts +0 -129
- package/src/react/hooks/use-suggested-prompts.ts +0 -128
- package/src/react/index.ts +0 -39
- package/src/react/lib/parse-assistant-error.ts +0 -96
- package/src/react/lib/prompt-icons.ts +0 -40
- package/src/react/types.ts +0 -83
- package/src/react/utils/cn.ts +0 -5
- package/test/buildLlmHistory.test.ts +0 -95
- package/test/llm-config.test.ts +0 -72
- package/test/llmSettingsStorage.test.ts +0 -121
- package/test/parse-assistant-error.test.ts +0 -24
- package/tsconfig.json +0 -8
- /package/{src/styles/assistant.css → dist/styles.css} +0 -0
|
@@ -0,0 +1,2876 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __toESM = (mod, isNodeMode, target) => {
|
|
7
|
+
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
8
|
+
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
9
|
+
for (let key of __getOwnPropNames(mod))
|
|
10
|
+
if (!__hasOwnProp.call(to, key))
|
|
11
|
+
__defProp(to, key, {
|
|
12
|
+
get: () => mod[key],
|
|
13
|
+
enumerable: true
|
|
14
|
+
});
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
18
|
+
|
|
19
|
+
// ../../node_modules/.bun/react@19.2.7/node_modules/react/cjs/react.development.js
|
|
20
|
+
var require_react_development = __commonJS((exports, module) => {
|
|
21
|
+
(function() {
|
|
22
|
+
function defineDeprecationWarning(methodName, info) {
|
|
23
|
+
Object.defineProperty(Component.prototype, methodName, {
|
|
24
|
+
get: function() {
|
|
25
|
+
console.warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]);
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
function getIteratorFn(maybeIterable) {
|
|
30
|
+
if (maybeIterable === null || typeof maybeIterable !== "object")
|
|
31
|
+
return null;
|
|
32
|
+
maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
|
|
33
|
+
return typeof maybeIterable === "function" ? maybeIterable : null;
|
|
34
|
+
}
|
|
35
|
+
function warnNoop(publicInstance, callerName) {
|
|
36
|
+
publicInstance = (publicInstance = publicInstance.constructor) && (publicInstance.displayName || publicInstance.name) || "ReactClass";
|
|
37
|
+
var warningKey = publicInstance + "." + callerName;
|
|
38
|
+
didWarnStateUpdateForUnmountedComponent[warningKey] || (console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, publicInstance), didWarnStateUpdateForUnmountedComponent[warningKey] = true);
|
|
39
|
+
}
|
|
40
|
+
function Component(props, context, updater) {
|
|
41
|
+
this.props = props;
|
|
42
|
+
this.context = context;
|
|
43
|
+
this.refs = emptyObject;
|
|
44
|
+
this.updater = updater || ReactNoopUpdateQueue;
|
|
45
|
+
}
|
|
46
|
+
function ComponentDummy() {}
|
|
47
|
+
function PureComponent(props, context, updater) {
|
|
48
|
+
this.props = props;
|
|
49
|
+
this.context = context;
|
|
50
|
+
this.refs = emptyObject;
|
|
51
|
+
this.updater = updater || ReactNoopUpdateQueue;
|
|
52
|
+
}
|
|
53
|
+
function noop() {}
|
|
54
|
+
function testStringCoercion(value) {
|
|
55
|
+
return "" + value;
|
|
56
|
+
}
|
|
57
|
+
function checkKeyStringCoercion(value) {
|
|
58
|
+
try {
|
|
59
|
+
testStringCoercion(value);
|
|
60
|
+
var JSCompiler_inline_result = false;
|
|
61
|
+
} catch (e) {
|
|
62
|
+
JSCompiler_inline_result = true;
|
|
63
|
+
}
|
|
64
|
+
if (JSCompiler_inline_result) {
|
|
65
|
+
JSCompiler_inline_result = console;
|
|
66
|
+
var JSCompiler_temp_const = JSCompiler_inline_result.error;
|
|
67
|
+
var JSCompiler_inline_result$jscomp$0 = typeof Symbol === "function" && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
|
|
68
|
+
JSCompiler_temp_const.call(JSCompiler_inline_result, "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", JSCompiler_inline_result$jscomp$0);
|
|
69
|
+
return testStringCoercion(value);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function getComponentNameFromType(type) {
|
|
73
|
+
if (type == null)
|
|
74
|
+
return null;
|
|
75
|
+
if (typeof type === "function")
|
|
76
|
+
return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
|
|
77
|
+
if (typeof type === "string")
|
|
78
|
+
return type;
|
|
79
|
+
switch (type) {
|
|
80
|
+
case REACT_FRAGMENT_TYPE:
|
|
81
|
+
return "Fragment";
|
|
82
|
+
case REACT_PROFILER_TYPE:
|
|
83
|
+
return "Profiler";
|
|
84
|
+
case REACT_STRICT_MODE_TYPE:
|
|
85
|
+
return "StrictMode";
|
|
86
|
+
case REACT_SUSPENSE_TYPE:
|
|
87
|
+
return "Suspense";
|
|
88
|
+
case REACT_SUSPENSE_LIST_TYPE:
|
|
89
|
+
return "SuspenseList";
|
|
90
|
+
case REACT_ACTIVITY_TYPE:
|
|
91
|
+
return "Activity";
|
|
92
|
+
}
|
|
93
|
+
if (typeof type === "object")
|
|
94
|
+
switch (typeof type.tag === "number" && console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."), type.$$typeof) {
|
|
95
|
+
case REACT_PORTAL_TYPE:
|
|
96
|
+
return "Portal";
|
|
97
|
+
case REACT_CONTEXT_TYPE:
|
|
98
|
+
return type.displayName || "Context";
|
|
99
|
+
case REACT_CONSUMER_TYPE:
|
|
100
|
+
return (type._context.displayName || "Context") + ".Consumer";
|
|
101
|
+
case REACT_FORWARD_REF_TYPE:
|
|
102
|
+
var innerType = type.render;
|
|
103
|
+
type = type.displayName;
|
|
104
|
+
type || (type = innerType.displayName || innerType.name || "", type = type !== "" ? "ForwardRef(" + type + ")" : "ForwardRef");
|
|
105
|
+
return type;
|
|
106
|
+
case REACT_MEMO_TYPE:
|
|
107
|
+
return innerType = type.displayName || null, innerType !== null ? innerType : getComponentNameFromType(type.type) || "Memo";
|
|
108
|
+
case REACT_LAZY_TYPE:
|
|
109
|
+
innerType = type._payload;
|
|
110
|
+
type = type._init;
|
|
111
|
+
try {
|
|
112
|
+
return getComponentNameFromType(type(innerType));
|
|
113
|
+
} catch (x) {}
|
|
114
|
+
}
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
function getTaskName(type) {
|
|
118
|
+
if (type === REACT_FRAGMENT_TYPE)
|
|
119
|
+
return "<>";
|
|
120
|
+
if (typeof type === "object" && type !== null && type.$$typeof === REACT_LAZY_TYPE)
|
|
121
|
+
return "<...>";
|
|
122
|
+
try {
|
|
123
|
+
var name = getComponentNameFromType(type);
|
|
124
|
+
return name ? "<" + name + ">" : "<...>";
|
|
125
|
+
} catch (x) {
|
|
126
|
+
return "<...>";
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
function getOwner() {
|
|
130
|
+
var dispatcher = ReactSharedInternals.A;
|
|
131
|
+
return dispatcher === null ? null : dispatcher.getOwner();
|
|
132
|
+
}
|
|
133
|
+
function UnknownOwner() {
|
|
134
|
+
return Error("react-stack-top-frame");
|
|
135
|
+
}
|
|
136
|
+
function hasValidKey(config) {
|
|
137
|
+
if (hasOwnProperty.call(config, "key")) {
|
|
138
|
+
var getter = Object.getOwnPropertyDescriptor(config, "key").get;
|
|
139
|
+
if (getter && getter.isReactWarning)
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
return config.key !== undefined;
|
|
143
|
+
}
|
|
144
|
+
function defineKeyPropWarningGetter(props, displayName) {
|
|
145
|
+
function warnAboutAccessingKey() {
|
|
146
|
+
specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", displayName));
|
|
147
|
+
}
|
|
148
|
+
warnAboutAccessingKey.isReactWarning = true;
|
|
149
|
+
Object.defineProperty(props, "key", {
|
|
150
|
+
get: warnAboutAccessingKey,
|
|
151
|
+
configurable: true
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
function elementRefGetterWithDeprecationWarning() {
|
|
155
|
+
var componentName = getComponentNameFromType(this.type);
|
|
156
|
+
didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."));
|
|
157
|
+
componentName = this.props.ref;
|
|
158
|
+
return componentName !== undefined ? componentName : null;
|
|
159
|
+
}
|
|
160
|
+
function ReactElement(type, key, props, owner, debugStack, debugTask) {
|
|
161
|
+
var refProp = props.ref;
|
|
162
|
+
type = {
|
|
163
|
+
$$typeof: REACT_ELEMENT_TYPE,
|
|
164
|
+
type,
|
|
165
|
+
key,
|
|
166
|
+
props,
|
|
167
|
+
_owner: owner
|
|
168
|
+
};
|
|
169
|
+
(refProp !== undefined ? refProp : null) !== null ? Object.defineProperty(type, "ref", {
|
|
170
|
+
enumerable: false,
|
|
171
|
+
get: elementRefGetterWithDeprecationWarning
|
|
172
|
+
}) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
|
|
173
|
+
type._store = {};
|
|
174
|
+
Object.defineProperty(type._store, "validated", {
|
|
175
|
+
configurable: false,
|
|
176
|
+
enumerable: false,
|
|
177
|
+
writable: true,
|
|
178
|
+
value: 0
|
|
179
|
+
});
|
|
180
|
+
Object.defineProperty(type, "_debugInfo", {
|
|
181
|
+
configurable: false,
|
|
182
|
+
enumerable: false,
|
|
183
|
+
writable: true,
|
|
184
|
+
value: null
|
|
185
|
+
});
|
|
186
|
+
Object.defineProperty(type, "_debugStack", {
|
|
187
|
+
configurable: false,
|
|
188
|
+
enumerable: false,
|
|
189
|
+
writable: true,
|
|
190
|
+
value: debugStack
|
|
191
|
+
});
|
|
192
|
+
Object.defineProperty(type, "_debugTask", {
|
|
193
|
+
configurable: false,
|
|
194
|
+
enumerable: false,
|
|
195
|
+
writable: true,
|
|
196
|
+
value: debugTask
|
|
197
|
+
});
|
|
198
|
+
Object.freeze && (Object.freeze(type.props), Object.freeze(type));
|
|
199
|
+
return type;
|
|
200
|
+
}
|
|
201
|
+
function cloneAndReplaceKey(oldElement, newKey) {
|
|
202
|
+
newKey = ReactElement(oldElement.type, newKey, oldElement.props, oldElement._owner, oldElement._debugStack, oldElement._debugTask);
|
|
203
|
+
oldElement._store && (newKey._store.validated = oldElement._store.validated);
|
|
204
|
+
return newKey;
|
|
205
|
+
}
|
|
206
|
+
function validateChildKeys(node) {
|
|
207
|
+
isValidElement(node) ? node._store && (node._store.validated = 1) : typeof node === "object" && node !== null && node.$$typeof === REACT_LAZY_TYPE && (node._payload.status === "fulfilled" ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
|
|
208
|
+
}
|
|
209
|
+
function isValidElement(object) {
|
|
210
|
+
return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
|
|
211
|
+
}
|
|
212
|
+
function escape(key) {
|
|
213
|
+
var escaperLookup = { "=": "=0", ":": "=2" };
|
|
214
|
+
return "$" + key.replace(/[=:]/g, function(match) {
|
|
215
|
+
return escaperLookup[match];
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
function getElementKey(element, index) {
|
|
219
|
+
return typeof element === "object" && element !== null && element.key != null ? (checkKeyStringCoercion(element.key), escape("" + element.key)) : index.toString(36);
|
|
220
|
+
}
|
|
221
|
+
function resolveThenable(thenable) {
|
|
222
|
+
switch (thenable.status) {
|
|
223
|
+
case "fulfilled":
|
|
224
|
+
return thenable.value;
|
|
225
|
+
case "rejected":
|
|
226
|
+
throw thenable.reason;
|
|
227
|
+
default:
|
|
228
|
+
switch (typeof thenable.status === "string" ? thenable.then(noop, noop) : (thenable.status = "pending", thenable.then(function(fulfilledValue) {
|
|
229
|
+
thenable.status === "pending" && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
|
|
230
|
+
}, function(error) {
|
|
231
|
+
thenable.status === "pending" && (thenable.status = "rejected", thenable.reason = error);
|
|
232
|
+
})), thenable.status) {
|
|
233
|
+
case "fulfilled":
|
|
234
|
+
return thenable.value;
|
|
235
|
+
case "rejected":
|
|
236
|
+
throw thenable.reason;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
throw thenable;
|
|
240
|
+
}
|
|
241
|
+
function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
|
|
242
|
+
var type = typeof children;
|
|
243
|
+
if (type === "undefined" || type === "boolean")
|
|
244
|
+
children = null;
|
|
245
|
+
var invokeCallback = false;
|
|
246
|
+
if (children === null)
|
|
247
|
+
invokeCallback = true;
|
|
248
|
+
else
|
|
249
|
+
switch (type) {
|
|
250
|
+
case "bigint":
|
|
251
|
+
case "string":
|
|
252
|
+
case "number":
|
|
253
|
+
invokeCallback = true;
|
|
254
|
+
break;
|
|
255
|
+
case "object":
|
|
256
|
+
switch (children.$$typeof) {
|
|
257
|
+
case REACT_ELEMENT_TYPE:
|
|
258
|
+
case REACT_PORTAL_TYPE:
|
|
259
|
+
invokeCallback = true;
|
|
260
|
+
break;
|
|
261
|
+
case REACT_LAZY_TYPE:
|
|
262
|
+
return invokeCallback = children._init, mapIntoArray(invokeCallback(children._payload), array, escapedPrefix, nameSoFar, callback);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (invokeCallback) {
|
|
266
|
+
invokeCallback = children;
|
|
267
|
+
callback = callback(invokeCallback);
|
|
268
|
+
var childKey = nameSoFar === "" ? "." + getElementKey(invokeCallback, 0) : nameSoFar;
|
|
269
|
+
isArrayImpl(callback) ? (escapedPrefix = "", childKey != null && (escapedPrefix = childKey.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c) {
|
|
270
|
+
return c;
|
|
271
|
+
})) : callback != null && (isValidElement(callback) && (callback.key != null && (invokeCallback && invokeCallback.key === callback.key || checkKeyStringCoercion(callback.key)), escapedPrefix = cloneAndReplaceKey(callback, escapedPrefix + (callback.key == null || invokeCallback && invokeCallback.key === callback.key ? "" : ("" + callback.key).replace(userProvidedKeyEscapeRegex, "$&/") + "/") + childKey), nameSoFar !== "" && invokeCallback != null && isValidElement(invokeCallback) && invokeCallback.key == null && invokeCallback._store && !invokeCallback._store.validated && (escapedPrefix._store.validated = 2), callback = escapedPrefix), array.push(callback));
|
|
272
|
+
return 1;
|
|
273
|
+
}
|
|
274
|
+
invokeCallback = 0;
|
|
275
|
+
childKey = nameSoFar === "" ? "." : nameSoFar + ":";
|
|
276
|
+
if (isArrayImpl(children))
|
|
277
|
+
for (var i = 0;i < children.length; i++)
|
|
278
|
+
nameSoFar = children[i], type = childKey + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray(nameSoFar, array, escapedPrefix, type, callback);
|
|
279
|
+
else if (i = getIteratorFn(children), typeof i === "function")
|
|
280
|
+
for (i === children.entries && (didWarnAboutMaps || console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."), didWarnAboutMaps = true), children = i.call(children), i = 0;!(nameSoFar = children.next()).done; )
|
|
281
|
+
nameSoFar = nameSoFar.value, type = childKey + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray(nameSoFar, array, escapedPrefix, type, callback);
|
|
282
|
+
else if (type === "object") {
|
|
283
|
+
if (typeof children.then === "function")
|
|
284
|
+
return mapIntoArray(resolveThenable(children), array, escapedPrefix, nameSoFar, callback);
|
|
285
|
+
array = String(children);
|
|
286
|
+
throw Error("Objects are not valid as a React child (found: " + (array === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead.");
|
|
287
|
+
}
|
|
288
|
+
return invokeCallback;
|
|
289
|
+
}
|
|
290
|
+
function mapChildren(children, func, context) {
|
|
291
|
+
if (children == null)
|
|
292
|
+
return children;
|
|
293
|
+
var result = [], count = 0;
|
|
294
|
+
mapIntoArray(children, result, "", "", function(child) {
|
|
295
|
+
return func.call(context, child, count++);
|
|
296
|
+
});
|
|
297
|
+
return result;
|
|
298
|
+
}
|
|
299
|
+
function lazyInitializer(payload) {
|
|
300
|
+
if (payload._status === -1) {
|
|
301
|
+
var ioInfo = payload._ioInfo;
|
|
302
|
+
ioInfo != null && (ioInfo.start = ioInfo.end = performance.now());
|
|
303
|
+
ioInfo = payload._result;
|
|
304
|
+
var thenable = ioInfo();
|
|
305
|
+
thenable.then(function(moduleObject) {
|
|
306
|
+
if (payload._status === 0 || payload._status === -1) {
|
|
307
|
+
payload._status = 1;
|
|
308
|
+
payload._result = moduleObject;
|
|
309
|
+
var _ioInfo = payload._ioInfo;
|
|
310
|
+
_ioInfo != null && (_ioInfo.end = performance.now());
|
|
311
|
+
thenable.status === undefined && (thenable.status = "fulfilled", thenable.value = moduleObject);
|
|
312
|
+
}
|
|
313
|
+
}, function(error) {
|
|
314
|
+
if (payload._status === 0 || payload._status === -1) {
|
|
315
|
+
payload._status = 2;
|
|
316
|
+
payload._result = error;
|
|
317
|
+
var _ioInfo2 = payload._ioInfo;
|
|
318
|
+
_ioInfo2 != null && (_ioInfo2.end = performance.now());
|
|
319
|
+
thenable.status === undefined && (thenable.status = "rejected", thenable.reason = error);
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
ioInfo = payload._ioInfo;
|
|
323
|
+
if (ioInfo != null) {
|
|
324
|
+
ioInfo.value = thenable;
|
|
325
|
+
var displayName = thenable.displayName;
|
|
326
|
+
typeof displayName === "string" && (ioInfo.name = displayName);
|
|
327
|
+
}
|
|
328
|
+
payload._status === -1 && (payload._status = 0, payload._result = thenable);
|
|
329
|
+
}
|
|
330
|
+
if (payload._status === 1)
|
|
331
|
+
return ioInfo = payload._result, ioInfo === undefined && console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
332
|
+
|
|
333
|
+
Your code should look like:
|
|
334
|
+
const MyComponent = lazy(() => import('./MyComponent'))
|
|
335
|
+
|
|
336
|
+
Did you accidentally put curly braces around the import?`, ioInfo), "default" in ioInfo || console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
337
|
+
|
|
338
|
+
Your code should look like:
|
|
339
|
+
const MyComponent = lazy(() => import('./MyComponent'))`, ioInfo), ioInfo.default;
|
|
340
|
+
throw payload._result;
|
|
341
|
+
}
|
|
342
|
+
function resolveDispatcher() {
|
|
343
|
+
var dispatcher = ReactSharedInternals.H;
|
|
344
|
+
dispatcher === null && console.error(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
|
|
345
|
+
1. You might have mismatching versions of React and the renderer (such as React DOM)
|
|
346
|
+
2. You might be breaking the Rules of Hooks
|
|
347
|
+
3. You might have more than one copy of React in the same app
|
|
348
|
+
See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`);
|
|
349
|
+
return dispatcher;
|
|
350
|
+
}
|
|
351
|
+
function releaseAsyncTransition() {
|
|
352
|
+
ReactSharedInternals.asyncTransitions--;
|
|
353
|
+
}
|
|
354
|
+
function enqueueTask(task) {
|
|
355
|
+
if (enqueueTaskImpl === null)
|
|
356
|
+
try {
|
|
357
|
+
var requireString = ("require" + Math.random()).slice(0, 7);
|
|
358
|
+
enqueueTaskImpl = (module && module[requireString]).call(module, "timers").setImmediate;
|
|
359
|
+
} catch (_err) {
|
|
360
|
+
enqueueTaskImpl = function(callback) {
|
|
361
|
+
didWarnAboutMessageChannel === false && (didWarnAboutMessageChannel = true, typeof MessageChannel === "undefined" && console.error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));
|
|
362
|
+
var channel = new MessageChannel;
|
|
363
|
+
channel.port1.onmessage = callback;
|
|
364
|
+
channel.port2.postMessage(undefined);
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
return enqueueTaskImpl(task);
|
|
368
|
+
}
|
|
369
|
+
function aggregateErrors(errors) {
|
|
370
|
+
return 1 < errors.length && typeof AggregateError === "function" ? new AggregateError(errors) : errors[0];
|
|
371
|
+
}
|
|
372
|
+
function popActScope(prevActQueue, prevActScopeDepth) {
|
|
373
|
+
prevActScopeDepth !== actScopeDepth - 1 && console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. ");
|
|
374
|
+
actScopeDepth = prevActScopeDepth;
|
|
375
|
+
}
|
|
376
|
+
function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
|
|
377
|
+
var queue = ReactSharedInternals.actQueue;
|
|
378
|
+
if (queue !== null)
|
|
379
|
+
if (queue.length !== 0)
|
|
380
|
+
try {
|
|
381
|
+
flushActQueue(queue);
|
|
382
|
+
enqueueTask(function() {
|
|
383
|
+
return recursivelyFlushAsyncActWork(returnValue, resolve, reject);
|
|
384
|
+
});
|
|
385
|
+
return;
|
|
386
|
+
} catch (error) {
|
|
387
|
+
ReactSharedInternals.thrownErrors.push(error);
|
|
388
|
+
}
|
|
389
|
+
else
|
|
390
|
+
ReactSharedInternals.actQueue = null;
|
|
391
|
+
0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve(returnValue);
|
|
392
|
+
}
|
|
393
|
+
function flushActQueue(queue) {
|
|
394
|
+
if (!isFlushing) {
|
|
395
|
+
isFlushing = true;
|
|
396
|
+
var i = 0;
|
|
397
|
+
try {
|
|
398
|
+
for (;i < queue.length; i++) {
|
|
399
|
+
var callback = queue[i];
|
|
400
|
+
do {
|
|
401
|
+
ReactSharedInternals.didUsePromise = false;
|
|
402
|
+
var continuation = callback(false);
|
|
403
|
+
if (continuation !== null) {
|
|
404
|
+
if (ReactSharedInternals.didUsePromise) {
|
|
405
|
+
queue[i] = callback;
|
|
406
|
+
queue.splice(0, i);
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
callback = continuation;
|
|
410
|
+
} else
|
|
411
|
+
break;
|
|
412
|
+
} while (1);
|
|
413
|
+
}
|
|
414
|
+
queue.length = 0;
|
|
415
|
+
} catch (error) {
|
|
416
|
+
queue.splice(0, i + 1), ReactSharedInternals.thrownErrors.push(error);
|
|
417
|
+
} finally {
|
|
418
|
+
isFlushing = false;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
|
|
423
|
+
var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, didWarnStateUpdateForUnmountedComponent = {}, ReactNoopUpdateQueue = {
|
|
424
|
+
isMounted: function() {
|
|
425
|
+
return false;
|
|
426
|
+
},
|
|
427
|
+
enqueueForceUpdate: function(publicInstance) {
|
|
428
|
+
warnNoop(publicInstance, "forceUpdate");
|
|
429
|
+
},
|
|
430
|
+
enqueueReplaceState: function(publicInstance) {
|
|
431
|
+
warnNoop(publicInstance, "replaceState");
|
|
432
|
+
},
|
|
433
|
+
enqueueSetState: function(publicInstance) {
|
|
434
|
+
warnNoop(publicInstance, "setState");
|
|
435
|
+
}
|
|
436
|
+
}, assign = Object.assign, emptyObject = {};
|
|
437
|
+
Object.freeze(emptyObject);
|
|
438
|
+
Component.prototype.isReactComponent = {};
|
|
439
|
+
Component.prototype.setState = function(partialState, callback) {
|
|
440
|
+
if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null)
|
|
441
|
+
throw Error("takes an object of state variables to update or a function which returns an object of state variables.");
|
|
442
|
+
this.updater.enqueueSetState(this, partialState, callback, "setState");
|
|
443
|
+
};
|
|
444
|
+
Component.prototype.forceUpdate = function(callback) {
|
|
445
|
+
this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
|
|
446
|
+
};
|
|
447
|
+
var deprecatedAPIs = {
|
|
448
|
+
isMounted: [
|
|
449
|
+
"isMounted",
|
|
450
|
+
"Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
|
|
451
|
+
],
|
|
452
|
+
replaceState: [
|
|
453
|
+
"replaceState",
|
|
454
|
+
"Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
|
|
455
|
+
]
|
|
456
|
+
};
|
|
457
|
+
for (fnName in deprecatedAPIs)
|
|
458
|
+
deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
|
|
459
|
+
ComponentDummy.prototype = Component.prototype;
|
|
460
|
+
deprecatedAPIs = PureComponent.prototype = new ComponentDummy;
|
|
461
|
+
deprecatedAPIs.constructor = PureComponent;
|
|
462
|
+
assign(deprecatedAPIs, Component.prototype);
|
|
463
|
+
deprecatedAPIs.isPureReactComponent = true;
|
|
464
|
+
var isArrayImpl = Array.isArray, REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = {
|
|
465
|
+
H: null,
|
|
466
|
+
A: null,
|
|
467
|
+
T: null,
|
|
468
|
+
S: null,
|
|
469
|
+
actQueue: null,
|
|
470
|
+
asyncTransitions: 0,
|
|
471
|
+
isBatchingLegacy: false,
|
|
472
|
+
didScheduleLegacyUpdate: false,
|
|
473
|
+
didUsePromise: false,
|
|
474
|
+
thrownErrors: [],
|
|
475
|
+
getCurrentStack: null,
|
|
476
|
+
recentlyCreatedOwnerStacks: 0
|
|
477
|
+
}, hasOwnProperty = Object.prototype.hasOwnProperty, createTask = console.createTask ? console.createTask : function() {
|
|
478
|
+
return null;
|
|
479
|
+
};
|
|
480
|
+
deprecatedAPIs = {
|
|
481
|
+
react_stack_bottom_frame: function(callStackForError) {
|
|
482
|
+
return callStackForError();
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime;
|
|
486
|
+
var didWarnAboutElementRef = {};
|
|
487
|
+
var unknownOwnerDebugStack = deprecatedAPIs.react_stack_bottom_frame.bind(deprecatedAPIs, UnknownOwner)();
|
|
488
|
+
var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
|
|
489
|
+
var didWarnAboutMaps = false, userProvidedKeyEscapeRegex = /\/+/g, reportGlobalError = typeof reportError === "function" ? reportError : function(error) {
|
|
490
|
+
if (typeof window === "object" && typeof window.ErrorEvent === "function") {
|
|
491
|
+
var event = new window.ErrorEvent("error", {
|
|
492
|
+
bubbles: true,
|
|
493
|
+
cancelable: true,
|
|
494
|
+
message: typeof error === "object" && error !== null && typeof error.message === "string" ? String(error.message) : String(error),
|
|
495
|
+
error
|
|
496
|
+
});
|
|
497
|
+
if (!window.dispatchEvent(event))
|
|
498
|
+
return;
|
|
499
|
+
} else if (typeof process === "object" && typeof process.emit === "function") {
|
|
500
|
+
process.emit("uncaughtException", error);
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
console.error(error);
|
|
504
|
+
}, didWarnAboutMessageChannel = false, enqueueTaskImpl = null, actScopeDepth = 0, didWarnNoAwaitAct = false, isFlushing = false, queueSeveralMicrotasks = typeof queueMicrotask === "function" ? function(callback) {
|
|
505
|
+
queueMicrotask(function() {
|
|
506
|
+
return queueMicrotask(callback);
|
|
507
|
+
});
|
|
508
|
+
} : enqueueTask;
|
|
509
|
+
deprecatedAPIs = Object.freeze({
|
|
510
|
+
__proto__: null,
|
|
511
|
+
c: function(size) {
|
|
512
|
+
return resolveDispatcher().useMemoCache(size);
|
|
513
|
+
}
|
|
514
|
+
});
|
|
515
|
+
var fnName = {
|
|
516
|
+
map: mapChildren,
|
|
517
|
+
forEach: function(children, forEachFunc, forEachContext) {
|
|
518
|
+
mapChildren(children, function() {
|
|
519
|
+
forEachFunc.apply(this, arguments);
|
|
520
|
+
}, forEachContext);
|
|
521
|
+
},
|
|
522
|
+
count: function(children) {
|
|
523
|
+
var n = 0;
|
|
524
|
+
mapChildren(children, function() {
|
|
525
|
+
n++;
|
|
526
|
+
});
|
|
527
|
+
return n;
|
|
528
|
+
},
|
|
529
|
+
toArray: function(children) {
|
|
530
|
+
return mapChildren(children, function(child) {
|
|
531
|
+
return child;
|
|
532
|
+
}) || [];
|
|
533
|
+
},
|
|
534
|
+
only: function(children) {
|
|
535
|
+
if (!isValidElement(children))
|
|
536
|
+
throw Error("React.Children.only expected to receive a single React element child.");
|
|
537
|
+
return children;
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
exports.Activity = REACT_ACTIVITY_TYPE;
|
|
541
|
+
exports.Children = fnName;
|
|
542
|
+
exports.Component = Component;
|
|
543
|
+
exports.Fragment = REACT_FRAGMENT_TYPE;
|
|
544
|
+
exports.Profiler = REACT_PROFILER_TYPE;
|
|
545
|
+
exports.PureComponent = PureComponent;
|
|
546
|
+
exports.StrictMode = REACT_STRICT_MODE_TYPE;
|
|
547
|
+
exports.Suspense = REACT_SUSPENSE_TYPE;
|
|
548
|
+
exports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
|
|
549
|
+
exports.__COMPILER_RUNTIME = deprecatedAPIs;
|
|
550
|
+
exports.act = function(callback) {
|
|
551
|
+
var prevActQueue = ReactSharedInternals.actQueue, prevActScopeDepth = actScopeDepth;
|
|
552
|
+
actScopeDepth++;
|
|
553
|
+
var queue = ReactSharedInternals.actQueue = prevActQueue !== null ? prevActQueue : [], didAwaitActCall = false;
|
|
554
|
+
try {
|
|
555
|
+
var result = callback();
|
|
556
|
+
} catch (error) {
|
|
557
|
+
ReactSharedInternals.thrownErrors.push(error);
|
|
558
|
+
}
|
|
559
|
+
if (0 < ReactSharedInternals.thrownErrors.length)
|
|
560
|
+
throw popActScope(prevActQueue, prevActScopeDepth), callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
|
|
561
|
+
if (result !== null && typeof result === "object" && typeof result.then === "function") {
|
|
562
|
+
var thenable = result;
|
|
563
|
+
queueSeveralMicrotasks(function() {
|
|
564
|
+
didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"));
|
|
565
|
+
});
|
|
566
|
+
return {
|
|
567
|
+
then: function(resolve, reject) {
|
|
568
|
+
didAwaitActCall = true;
|
|
569
|
+
thenable.then(function(returnValue) {
|
|
570
|
+
popActScope(prevActQueue, prevActScopeDepth);
|
|
571
|
+
if (prevActScopeDepth === 0) {
|
|
572
|
+
try {
|
|
573
|
+
flushActQueue(queue), enqueueTask(function() {
|
|
574
|
+
return recursivelyFlushAsyncActWork(returnValue, resolve, reject);
|
|
575
|
+
});
|
|
576
|
+
} catch (error$0) {
|
|
577
|
+
ReactSharedInternals.thrownErrors.push(error$0);
|
|
578
|
+
}
|
|
579
|
+
if (0 < ReactSharedInternals.thrownErrors.length) {
|
|
580
|
+
var _thrownError = aggregateErrors(ReactSharedInternals.thrownErrors);
|
|
581
|
+
ReactSharedInternals.thrownErrors.length = 0;
|
|
582
|
+
reject(_thrownError);
|
|
583
|
+
}
|
|
584
|
+
} else
|
|
585
|
+
resolve(returnValue);
|
|
586
|
+
}, function(error) {
|
|
587
|
+
popActScope(prevActQueue, prevActScopeDepth);
|
|
588
|
+
0 < ReactSharedInternals.thrownErrors.length ? (error = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(error)) : reject(error);
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
var returnValue$jscomp$0 = result;
|
|
594
|
+
popActScope(prevActQueue, prevActScopeDepth);
|
|
595
|
+
prevActScopeDepth === 0 && (flushActQueue(queue), queue.length !== 0 && queueSeveralMicrotasks(function() {
|
|
596
|
+
didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error("A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"));
|
|
597
|
+
}), ReactSharedInternals.actQueue = null);
|
|
598
|
+
if (0 < ReactSharedInternals.thrownErrors.length)
|
|
599
|
+
throw callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
|
|
600
|
+
return {
|
|
601
|
+
then: function(resolve, reject) {
|
|
602
|
+
didAwaitActCall = true;
|
|
603
|
+
prevActScopeDepth === 0 ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() {
|
|
604
|
+
return recursivelyFlushAsyncActWork(returnValue$jscomp$0, resolve, reject);
|
|
605
|
+
})) : resolve(returnValue$jscomp$0);
|
|
606
|
+
}
|
|
607
|
+
};
|
|
608
|
+
};
|
|
609
|
+
exports.cache = function(fn) {
|
|
610
|
+
return function() {
|
|
611
|
+
return fn.apply(null, arguments);
|
|
612
|
+
};
|
|
613
|
+
};
|
|
614
|
+
exports.cacheSignal = function() {
|
|
615
|
+
return null;
|
|
616
|
+
};
|
|
617
|
+
exports.captureOwnerStack = function() {
|
|
618
|
+
var getCurrentStack = ReactSharedInternals.getCurrentStack;
|
|
619
|
+
return getCurrentStack === null ? null : getCurrentStack();
|
|
620
|
+
};
|
|
621
|
+
exports.cloneElement = function(element, config, children) {
|
|
622
|
+
if (element === null || element === undefined)
|
|
623
|
+
throw Error("The argument must be a React element, but you passed " + element + ".");
|
|
624
|
+
var props = assign({}, element.props), key = element.key, owner = element._owner;
|
|
625
|
+
if (config != null) {
|
|
626
|
+
var JSCompiler_inline_result;
|
|
627
|
+
a: {
|
|
628
|
+
if (hasOwnProperty.call(config, "ref") && (JSCompiler_inline_result = Object.getOwnPropertyDescriptor(config, "ref").get) && JSCompiler_inline_result.isReactWarning) {
|
|
629
|
+
JSCompiler_inline_result = false;
|
|
630
|
+
break a;
|
|
631
|
+
}
|
|
632
|
+
JSCompiler_inline_result = config.ref !== undefined;
|
|
633
|
+
}
|
|
634
|
+
JSCompiler_inline_result && (owner = getOwner());
|
|
635
|
+
hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key);
|
|
636
|
+
for (propName in config)
|
|
637
|
+
!hasOwnProperty.call(config, propName) || propName === "key" || propName === "__self" || propName === "__source" || propName === "ref" && config.ref === undefined || (props[propName] = config[propName]);
|
|
638
|
+
}
|
|
639
|
+
var propName = arguments.length - 2;
|
|
640
|
+
if (propName === 1)
|
|
641
|
+
props.children = children;
|
|
642
|
+
else if (1 < propName) {
|
|
643
|
+
JSCompiler_inline_result = Array(propName);
|
|
644
|
+
for (var i = 0;i < propName; i++)
|
|
645
|
+
JSCompiler_inline_result[i] = arguments[i + 2];
|
|
646
|
+
props.children = JSCompiler_inline_result;
|
|
647
|
+
}
|
|
648
|
+
props = ReactElement(element.type, key, props, owner, element._debugStack, element._debugTask);
|
|
649
|
+
for (key = 2;key < arguments.length; key++)
|
|
650
|
+
validateChildKeys(arguments[key]);
|
|
651
|
+
return props;
|
|
652
|
+
};
|
|
653
|
+
exports.createContext = function(defaultValue) {
|
|
654
|
+
defaultValue = {
|
|
655
|
+
$$typeof: REACT_CONTEXT_TYPE,
|
|
656
|
+
_currentValue: defaultValue,
|
|
657
|
+
_currentValue2: defaultValue,
|
|
658
|
+
_threadCount: 0,
|
|
659
|
+
Provider: null,
|
|
660
|
+
Consumer: null
|
|
661
|
+
};
|
|
662
|
+
defaultValue.Provider = defaultValue;
|
|
663
|
+
defaultValue.Consumer = {
|
|
664
|
+
$$typeof: REACT_CONSUMER_TYPE,
|
|
665
|
+
_context: defaultValue
|
|
666
|
+
};
|
|
667
|
+
defaultValue._currentRenderer = null;
|
|
668
|
+
defaultValue._currentRenderer2 = null;
|
|
669
|
+
return defaultValue;
|
|
670
|
+
};
|
|
671
|
+
exports.createElement = function(type, config, children) {
|
|
672
|
+
for (var i = 2;i < arguments.length; i++)
|
|
673
|
+
validateChildKeys(arguments[i]);
|
|
674
|
+
i = {};
|
|
675
|
+
var key = null;
|
|
676
|
+
if (config != null)
|
|
677
|
+
for (propName in didWarnAboutOldJSXRuntime || !("__self" in config) || "key" in config || (didWarnAboutOldJSXRuntime = true, console.warn("Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform")), hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key), config)
|
|
678
|
+
hasOwnProperty.call(config, propName) && propName !== "key" && propName !== "__self" && propName !== "__source" && (i[propName] = config[propName]);
|
|
679
|
+
var childrenLength = arguments.length - 2;
|
|
680
|
+
if (childrenLength === 1)
|
|
681
|
+
i.children = children;
|
|
682
|
+
else if (1 < childrenLength) {
|
|
683
|
+
for (var childArray = Array(childrenLength), _i = 0;_i < childrenLength; _i++)
|
|
684
|
+
childArray[_i] = arguments[_i + 2];
|
|
685
|
+
Object.freeze && Object.freeze(childArray);
|
|
686
|
+
i.children = childArray;
|
|
687
|
+
}
|
|
688
|
+
if (type && type.defaultProps)
|
|
689
|
+
for (propName in childrenLength = type.defaultProps, childrenLength)
|
|
690
|
+
i[propName] === undefined && (i[propName] = childrenLength[propName]);
|
|
691
|
+
key && defineKeyPropWarningGetter(i, typeof type === "function" ? type.displayName || type.name || "Unknown" : type);
|
|
692
|
+
var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
|
|
693
|
+
return ReactElement(type, key, i, getOwner(), propName ? Error("react-stack-top-frame") : unknownOwnerDebugStack, propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask);
|
|
694
|
+
};
|
|
695
|
+
exports.createRef = function() {
|
|
696
|
+
var refObject = { current: null };
|
|
697
|
+
Object.seal(refObject);
|
|
698
|
+
return refObject;
|
|
699
|
+
};
|
|
700
|
+
exports.forwardRef = function(render) {
|
|
701
|
+
render != null && render.$$typeof === REACT_MEMO_TYPE ? console.error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...)).") : typeof render !== "function" ? console.error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render) : render.length !== 0 && render.length !== 2 && console.error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined.");
|
|
702
|
+
render != null && render.defaultProps != null && console.error("forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?");
|
|
703
|
+
var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render }, ownName;
|
|
704
|
+
Object.defineProperty(elementType, "displayName", {
|
|
705
|
+
enumerable: false,
|
|
706
|
+
configurable: true,
|
|
707
|
+
get: function() {
|
|
708
|
+
return ownName;
|
|
709
|
+
},
|
|
710
|
+
set: function(name) {
|
|
711
|
+
ownName = name;
|
|
712
|
+
render.name || render.displayName || (Object.defineProperty(render, "name", { value: name }), render.displayName = name);
|
|
713
|
+
}
|
|
714
|
+
});
|
|
715
|
+
return elementType;
|
|
716
|
+
};
|
|
717
|
+
exports.isValidElement = isValidElement;
|
|
718
|
+
exports.lazy = function(ctor) {
|
|
719
|
+
ctor = { _status: -1, _result: ctor };
|
|
720
|
+
var lazyType = {
|
|
721
|
+
$$typeof: REACT_LAZY_TYPE,
|
|
722
|
+
_payload: ctor,
|
|
723
|
+
_init: lazyInitializer
|
|
724
|
+
}, ioInfo = {
|
|
725
|
+
name: "lazy",
|
|
726
|
+
start: -1,
|
|
727
|
+
end: -1,
|
|
728
|
+
value: null,
|
|
729
|
+
owner: null,
|
|
730
|
+
debugStack: Error("react-stack-top-frame"),
|
|
731
|
+
debugTask: console.createTask ? console.createTask("lazy()") : null
|
|
732
|
+
};
|
|
733
|
+
ctor._ioInfo = ioInfo;
|
|
734
|
+
lazyType._debugInfo = [{ awaited: ioInfo }];
|
|
735
|
+
return lazyType;
|
|
736
|
+
};
|
|
737
|
+
exports.memo = function(type, compare) {
|
|
738
|
+
type == null && console.error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type);
|
|
739
|
+
compare = {
|
|
740
|
+
$$typeof: REACT_MEMO_TYPE,
|
|
741
|
+
type,
|
|
742
|
+
compare: compare === undefined ? null : compare
|
|
743
|
+
};
|
|
744
|
+
var ownName;
|
|
745
|
+
Object.defineProperty(compare, "displayName", {
|
|
746
|
+
enumerable: false,
|
|
747
|
+
configurable: true,
|
|
748
|
+
get: function() {
|
|
749
|
+
return ownName;
|
|
750
|
+
},
|
|
751
|
+
set: function(name) {
|
|
752
|
+
ownName = name;
|
|
753
|
+
type.name || type.displayName || (Object.defineProperty(type, "name", { value: name }), type.displayName = name);
|
|
754
|
+
}
|
|
755
|
+
});
|
|
756
|
+
return compare;
|
|
757
|
+
};
|
|
758
|
+
exports.startTransition = function(scope) {
|
|
759
|
+
var prevTransition = ReactSharedInternals.T, currentTransition = {};
|
|
760
|
+
currentTransition._updatedFibers = new Set;
|
|
761
|
+
ReactSharedInternals.T = currentTransition;
|
|
762
|
+
try {
|
|
763
|
+
var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
|
|
764
|
+
onStartTransitionFinish !== null && onStartTransitionFinish(currentTransition, returnValue);
|
|
765
|
+
typeof returnValue === "object" && returnValue !== null && typeof returnValue.then === "function" && (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(noop, reportGlobalError));
|
|
766
|
+
} catch (error) {
|
|
767
|
+
reportGlobalError(error);
|
|
768
|
+
} finally {
|
|
769
|
+
prevTransition === null && currentTransition._updatedFibers && (scope = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < scope && console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.")), prevTransition !== null && currentTransition.types !== null && (prevTransition.types !== null && prevTransition.types !== currentTransition.types && console.error("We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
|
|
770
|
+
}
|
|
771
|
+
};
|
|
772
|
+
exports.unstable_useCacheRefresh = function() {
|
|
773
|
+
return resolveDispatcher().useCacheRefresh();
|
|
774
|
+
};
|
|
775
|
+
exports.use = function(usable) {
|
|
776
|
+
return resolveDispatcher().use(usable);
|
|
777
|
+
};
|
|
778
|
+
exports.useActionState = function(action, initialState, permalink) {
|
|
779
|
+
return resolveDispatcher().useActionState(action, initialState, permalink);
|
|
780
|
+
};
|
|
781
|
+
exports.useCallback = function(callback, deps) {
|
|
782
|
+
return resolveDispatcher().useCallback(callback, deps);
|
|
783
|
+
};
|
|
784
|
+
exports.useContext = function(Context) {
|
|
785
|
+
var dispatcher = resolveDispatcher();
|
|
786
|
+
Context.$$typeof === REACT_CONSUMER_TYPE && console.error("Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?");
|
|
787
|
+
return dispatcher.useContext(Context);
|
|
788
|
+
};
|
|
789
|
+
exports.useDebugValue = function(value, formatterFn) {
|
|
790
|
+
return resolveDispatcher().useDebugValue(value, formatterFn);
|
|
791
|
+
};
|
|
792
|
+
exports.useDeferredValue = function(value, initialValue) {
|
|
793
|
+
return resolveDispatcher().useDeferredValue(value, initialValue);
|
|
794
|
+
};
|
|
795
|
+
exports.useEffect = function(create, deps) {
|
|
796
|
+
create == null && console.warn("React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?");
|
|
797
|
+
return resolveDispatcher().useEffect(create, deps);
|
|
798
|
+
};
|
|
799
|
+
exports.useEffectEvent = function(callback) {
|
|
800
|
+
return resolveDispatcher().useEffectEvent(callback);
|
|
801
|
+
};
|
|
802
|
+
exports.useId = function() {
|
|
803
|
+
return resolveDispatcher().useId();
|
|
804
|
+
};
|
|
805
|
+
exports.useImperativeHandle = function(ref, create, deps) {
|
|
806
|
+
return resolveDispatcher().useImperativeHandle(ref, create, deps);
|
|
807
|
+
};
|
|
808
|
+
exports.useInsertionEffect = function(create, deps) {
|
|
809
|
+
create == null && console.warn("React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?");
|
|
810
|
+
return resolveDispatcher().useInsertionEffect(create, deps);
|
|
811
|
+
};
|
|
812
|
+
exports.useLayoutEffect = function(create, deps) {
|
|
813
|
+
create == null && console.warn("React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?");
|
|
814
|
+
return resolveDispatcher().useLayoutEffect(create, deps);
|
|
815
|
+
};
|
|
816
|
+
exports.useMemo = function(create, deps) {
|
|
817
|
+
return resolveDispatcher().useMemo(create, deps);
|
|
818
|
+
};
|
|
819
|
+
exports.useOptimistic = function(passthrough, reducer) {
|
|
820
|
+
return resolveDispatcher().useOptimistic(passthrough, reducer);
|
|
821
|
+
};
|
|
822
|
+
exports.useReducer = function(reducer, initialArg, init) {
|
|
823
|
+
return resolveDispatcher().useReducer(reducer, initialArg, init);
|
|
824
|
+
};
|
|
825
|
+
exports.useRef = function(initialValue) {
|
|
826
|
+
return resolveDispatcher().useRef(initialValue);
|
|
827
|
+
};
|
|
828
|
+
exports.useState = function(initialState) {
|
|
829
|
+
return resolveDispatcher().useState(initialState);
|
|
830
|
+
};
|
|
831
|
+
exports.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) {
|
|
832
|
+
return resolveDispatcher().useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
|
833
|
+
};
|
|
834
|
+
exports.useTransition = function() {
|
|
835
|
+
return resolveDispatcher().useTransition();
|
|
836
|
+
};
|
|
837
|
+
exports.version = "19.2.7";
|
|
838
|
+
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
|
|
839
|
+
})();
|
|
840
|
+
});
|
|
841
|
+
|
|
842
|
+
// ../../node_modules/.bun/react@19.2.7/node_modules/react/index.js
|
|
843
|
+
var require_react = __commonJS((exports, module) => {
|
|
844
|
+
var react_development = __toESM(require_react_development());
|
|
845
|
+
if (false) {} else {
|
|
846
|
+
module.exports = react_development;
|
|
847
|
+
}
|
|
848
|
+
});
|
|
849
|
+
|
|
850
|
+
// src/core/chat-activity.ts
|
|
851
|
+
function summarizeActivityResult(result) {
|
|
852
|
+
if (result === undefined || result === null)
|
|
853
|
+
return result;
|
|
854
|
+
if (typeof result !== "object")
|
|
855
|
+
return result;
|
|
856
|
+
const value = result;
|
|
857
|
+
if ("structuredContent" in value) {
|
|
858
|
+
return value.structuredContent ?? value;
|
|
859
|
+
}
|
|
860
|
+
if ("content" in value && Array.isArray(value.content)) {
|
|
861
|
+
return value.content;
|
|
862
|
+
}
|
|
863
|
+
return result;
|
|
864
|
+
}
|
|
865
|
+
function chatActivityStepLabel(step) {
|
|
866
|
+
if (step.status === "active") {
|
|
867
|
+
if (step.name === "request_confirmation")
|
|
868
|
+
return "Waiting for confirmation…";
|
|
869
|
+
if (step.name === "request_choices")
|
|
870
|
+
return "Waiting for your choice…";
|
|
871
|
+
if (step.name === "suggest_replies")
|
|
872
|
+
return "Suggesting replies…";
|
|
873
|
+
return `Running ${step.name}…`;
|
|
874
|
+
}
|
|
875
|
+
if (step.status === "error")
|
|
876
|
+
return `${step.name} failed`;
|
|
877
|
+
if (step.name === "request_confirmation")
|
|
878
|
+
return "Confirmation answered";
|
|
879
|
+
if (step.name === "request_choices")
|
|
880
|
+
return "Choice submitted";
|
|
881
|
+
if (step.name === "suggest_replies")
|
|
882
|
+
return "Reply suggestions shown";
|
|
883
|
+
return `Ran ${step.name}`;
|
|
884
|
+
}
|
|
885
|
+
function formatJsonIfLarge(raw) {
|
|
886
|
+
const trimmed = raw.trim();
|
|
887
|
+
const JSON_PRETTY_MIN_LENGTH = 80;
|
|
888
|
+
if (trimmed.length < JSON_PRETTY_MIN_LENGTH) {
|
|
889
|
+
return trimmed;
|
|
890
|
+
}
|
|
891
|
+
try {
|
|
892
|
+
return JSON.stringify(JSON.parse(trimmed), null, 2);
|
|
893
|
+
} catch {
|
|
894
|
+
return trimmed;
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
// src/core/chat-commands.ts
|
|
898
|
+
var CHAT_COMMANDS = [
|
|
899
|
+
{
|
|
900
|
+
name: "clear",
|
|
901
|
+
description: "Clear the current conversation",
|
|
902
|
+
surfaces: ["assistant"],
|
|
903
|
+
run: async (args, deps) => {
|
|
904
|
+
if (args) {
|
|
905
|
+
throw new Error("The /clear command does not accept arguments.");
|
|
906
|
+
}
|
|
907
|
+
if (deps.streaming) {
|
|
908
|
+
throw new Error("Wait for the assistant to finish before clearing.");
|
|
909
|
+
}
|
|
910
|
+
deps.clearMessages();
|
|
911
|
+
deps.setError(null);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
];
|
|
915
|
+
function getChatCommandSuggestions(surface) {
|
|
916
|
+
return CHAT_COMMANDS.filter((command) => command.surfaces.includes(surface)).map(({ name, description }) => ({
|
|
917
|
+
name,
|
|
918
|
+
description,
|
|
919
|
+
usage: `/${name}`
|
|
920
|
+
}));
|
|
921
|
+
}
|
|
922
|
+
function isChatCommandInput(value) {
|
|
923
|
+
return value.trimStart().startsWith("/");
|
|
924
|
+
}
|
|
925
|
+
function filterChatCommands(value, surface) {
|
|
926
|
+
if (!isChatCommandInput(value)) {
|
|
927
|
+
return [];
|
|
928
|
+
}
|
|
929
|
+
const query = value.trimStart().slice(1).toLowerCase();
|
|
930
|
+
const commands = getChatCommandSuggestions(surface);
|
|
931
|
+
if (!query) {
|
|
932
|
+
return commands;
|
|
933
|
+
}
|
|
934
|
+
return commands.filter((command) => command.name.startsWith(query) || command.usage.toLowerCase().startsWith(`/${query}`));
|
|
935
|
+
}
|
|
936
|
+
function shouldShowChatCommandMenu(value, surface) {
|
|
937
|
+
if (!isChatCommandInput(value) || value.includes(`
|
|
938
|
+
`)) {
|
|
939
|
+
return false;
|
|
940
|
+
}
|
|
941
|
+
const trimmed = value.trimStart();
|
|
942
|
+
if (trimmed.includes(" ")) {
|
|
943
|
+
return false;
|
|
944
|
+
}
|
|
945
|
+
return filterChatCommands(value, surface).length > 0;
|
|
946
|
+
}
|
|
947
|
+
function listChatCommands(surface) {
|
|
948
|
+
return CHAT_COMMANDS.filter((command) => !surface || command.surfaces.includes(surface)).map(({ name, description }) => ({ name, description }));
|
|
949
|
+
}
|
|
950
|
+
function parseChatCommand(input) {
|
|
951
|
+
const trimmed = input.trim();
|
|
952
|
+
const match = /^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/i.exec(trimmed);
|
|
953
|
+
if (!match) {
|
|
954
|
+
return null;
|
|
955
|
+
}
|
|
956
|
+
const name = match[1];
|
|
957
|
+
if (!name) {
|
|
958
|
+
return null;
|
|
959
|
+
}
|
|
960
|
+
return {
|
|
961
|
+
name: name.toLowerCase(),
|
|
962
|
+
args: (match[2] ?? "").trim()
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
async function executeCommand(parsed, deps) {
|
|
966
|
+
const command = CHAT_COMMANDS.find((entry) => entry.name === parsed.name);
|
|
967
|
+
if (!command?.surfaces.includes("assistant")) {
|
|
968
|
+
return {
|
|
969
|
+
handled: true,
|
|
970
|
+
clearInput: true,
|
|
971
|
+
error: `Unknown command: /${parsed.name}`
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
try {
|
|
975
|
+
await command.run(parsed.args, deps);
|
|
976
|
+
return { handled: true, clearInput: true };
|
|
977
|
+
} catch (error) {
|
|
978
|
+
return {
|
|
979
|
+
handled: true,
|
|
980
|
+
clearInput: true,
|
|
981
|
+
error: error instanceof Error ? error.message : "Command failed"
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
async function runAssistantChatCommand(input, deps) {
|
|
986
|
+
const parsed = parseChatCommand(input);
|
|
987
|
+
if (!parsed) {
|
|
988
|
+
return { handled: false };
|
|
989
|
+
}
|
|
990
|
+
return executeCommand(parsed, deps);
|
|
991
|
+
}
|
|
992
|
+
// src/core/interactive-tools/choices.ts
|
|
993
|
+
var REQUEST_CHOICES_TOOL = "request_choices";
|
|
994
|
+
var CHOICES_TOOL = {
|
|
995
|
+
name: REQUEST_CHOICES_TOOL,
|
|
996
|
+
description: "Present options when multiple valid paths exist and you need the user to choose before continuing. Supports single-select and multi-select.",
|
|
997
|
+
inputSchema: {
|
|
998
|
+
type: "object",
|
|
999
|
+
properties: {
|
|
1000
|
+
message: {
|
|
1001
|
+
type: "string",
|
|
1002
|
+
description: "Prompt explaining what the user should choose."
|
|
1003
|
+
},
|
|
1004
|
+
options: {
|
|
1005
|
+
type: "array",
|
|
1006
|
+
minItems: 2,
|
|
1007
|
+
items: {
|
|
1008
|
+
type: "object",
|
|
1009
|
+
properties: {
|
|
1010
|
+
id: {
|
|
1011
|
+
type: "string",
|
|
1012
|
+
description: "Stable option id returned in the tool result."
|
|
1013
|
+
},
|
|
1014
|
+
label: {
|
|
1015
|
+
type: "string",
|
|
1016
|
+
description: "User-visible option label."
|
|
1017
|
+
},
|
|
1018
|
+
description: {
|
|
1019
|
+
type: "string",
|
|
1020
|
+
description: "Optional longer description for the option."
|
|
1021
|
+
}
|
|
1022
|
+
},
|
|
1023
|
+
required: ["id", "label"],
|
|
1024
|
+
additionalProperties: false
|
|
1025
|
+
}
|
|
1026
|
+
},
|
|
1027
|
+
allowMultiple: {
|
|
1028
|
+
type: "boolean",
|
|
1029
|
+
description: "If true, the user may select multiple options."
|
|
1030
|
+
},
|
|
1031
|
+
minSelections: {
|
|
1032
|
+
type: "integer",
|
|
1033
|
+
description: "Minimum number of selections when allowMultiple is true. Default: 1."
|
|
1034
|
+
},
|
|
1035
|
+
maxSelections: {
|
|
1036
|
+
type: "integer",
|
|
1037
|
+
description: "Maximum number of selections when allowMultiple is true."
|
|
1038
|
+
},
|
|
1039
|
+
submitLabel: {
|
|
1040
|
+
type: "string",
|
|
1041
|
+
description: "Submit button label. Default: Continue."
|
|
1042
|
+
}
|
|
1043
|
+
},
|
|
1044
|
+
required: ["message", "options"],
|
|
1045
|
+
additionalProperties: false
|
|
1046
|
+
}
|
|
1047
|
+
};
|
|
1048
|
+
function parseChoicesArgs(args) {
|
|
1049
|
+
const message = String(args.message ?? "").trim();
|
|
1050
|
+
if (!message) {
|
|
1051
|
+
throw new Error("request_choices requires a non-empty message");
|
|
1052
|
+
}
|
|
1053
|
+
if (!Array.isArray(args.options) || args.options.length < 2) {
|
|
1054
|
+
throw new Error("request_choices requires at least two options");
|
|
1055
|
+
}
|
|
1056
|
+
const options = [];
|
|
1057
|
+
const seenIds = new Set;
|
|
1058
|
+
for (const entry of args.options) {
|
|
1059
|
+
if (!entry || typeof entry !== "object") {
|
|
1060
|
+
throw new Error("Each choice option must be an object with id and label");
|
|
1061
|
+
}
|
|
1062
|
+
const option = entry;
|
|
1063
|
+
const id = String(option.id ?? "").trim();
|
|
1064
|
+
const label = String(option.label ?? "").trim();
|
|
1065
|
+
if (!id || !label) {
|
|
1066
|
+
throw new Error("Each choice option requires a non-empty id and label");
|
|
1067
|
+
}
|
|
1068
|
+
if (seenIds.has(id)) {
|
|
1069
|
+
throw new Error(`Duplicate choice option id: ${id}`);
|
|
1070
|
+
}
|
|
1071
|
+
seenIds.add(id);
|
|
1072
|
+
options.push({
|
|
1073
|
+
id,
|
|
1074
|
+
label,
|
|
1075
|
+
description: option.description !== undefined ? String(option.description).trim() : undefined
|
|
1076
|
+
});
|
|
1077
|
+
}
|
|
1078
|
+
const allowMultiple = Boolean(args.allowMultiple);
|
|
1079
|
+
const minSelections = typeof args.minSelections === "number" && args.minSelections > 0 ? Math.floor(args.minSelections) : 1;
|
|
1080
|
+
const maxSelections = typeof args.maxSelections === "number" && args.maxSelections > 0 ? Math.floor(args.maxSelections) : undefined;
|
|
1081
|
+
if (allowMultiple && maxSelections !== undefined && maxSelections < minSelections) {
|
|
1082
|
+
throw new Error("maxSelections must be greater than or equal to minSelections");
|
|
1083
|
+
}
|
|
1084
|
+
return {
|
|
1085
|
+
message,
|
|
1086
|
+
options,
|
|
1087
|
+
allowMultiple,
|
|
1088
|
+
minSelections: allowMultiple ? minSelections : 1,
|
|
1089
|
+
maxSelections: allowMultiple ? maxSelections : 1,
|
|
1090
|
+
submitLabel: args.submitLabel ? String(args.submitLabel).trim() : "Continue"
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
// src/core/interactive-tools/confirmation.ts
|
|
1094
|
+
var REQUEST_CONFIRMATION_TOOL = "request_confirmation";
|
|
1095
|
+
var CONFIRMATION_TOOL = {
|
|
1096
|
+
name: REQUEST_CONFIRMATION_TOOL,
|
|
1097
|
+
description: "Ask the user to confirm before proceeding with an important or irreversible action. Execution pauses until the user confirms or cancels.",
|
|
1098
|
+
inputSchema: {
|
|
1099
|
+
type: "object",
|
|
1100
|
+
properties: {
|
|
1101
|
+
message: {
|
|
1102
|
+
type: "string",
|
|
1103
|
+
description: "Explanation or question shown to the user."
|
|
1104
|
+
},
|
|
1105
|
+
action: {
|
|
1106
|
+
type: "string",
|
|
1107
|
+
description: "Short summary of what happens if confirmed, e.g. 'Delete 3 User records'."
|
|
1108
|
+
},
|
|
1109
|
+
confirmLabel: {
|
|
1110
|
+
type: "string",
|
|
1111
|
+
description: "Confirm button label. Default: Proceed."
|
|
1112
|
+
},
|
|
1113
|
+
cancelLabel: {
|
|
1114
|
+
type: "string",
|
|
1115
|
+
description: "Cancel button label. Default: Cancel."
|
|
1116
|
+
}
|
|
1117
|
+
},
|
|
1118
|
+
required: ["message"],
|
|
1119
|
+
additionalProperties: false
|
|
1120
|
+
}
|
|
1121
|
+
};
|
|
1122
|
+
function parseConfirmationArgs(args) {
|
|
1123
|
+
const message = String(args.message ?? "").trim();
|
|
1124
|
+
if (!message) {
|
|
1125
|
+
throw new Error("request_confirmation requires a non-empty message");
|
|
1126
|
+
}
|
|
1127
|
+
return {
|
|
1128
|
+
message,
|
|
1129
|
+
action: args.action !== undefined ? String(args.action).trim() : undefined,
|
|
1130
|
+
confirmLabel: args.confirmLabel ? String(args.confirmLabel).trim() : "Proceed",
|
|
1131
|
+
cancelLabel: args.cancelLabel ? String(args.cancelLabel).trim() : "Cancel"
|
|
1132
|
+
};
|
|
1133
|
+
}
|
|
1134
|
+
// src/core/interactive-tools/suggestions.ts
|
|
1135
|
+
var SUGGEST_REPLIES_TOOL = "suggest_replies";
|
|
1136
|
+
var SUGGEST_REPLIES_TOOL_DEFINITION = {
|
|
1137
|
+
name: SUGGEST_REPLIES_TOOL,
|
|
1138
|
+
description: "Required when your message asks the user a question and you can suggest 2–6 short example answers. Call as the ONLY tool in the turn, after writing the question in your message. Use for yes/no, dataclass picks, filter examples, or next-step options. The user can tap a suggestion or type their own reply.",
|
|
1139
|
+
inputSchema: {
|
|
1140
|
+
type: "object",
|
|
1141
|
+
properties: {
|
|
1142
|
+
question: {
|
|
1143
|
+
type: "string",
|
|
1144
|
+
description: "The question from your message, e.g. Which dataclass should I query?"
|
|
1145
|
+
},
|
|
1146
|
+
suggestions: {
|
|
1147
|
+
type: "array",
|
|
1148
|
+
minItems: 2,
|
|
1149
|
+
maxItems: 8,
|
|
1150
|
+
items: {
|
|
1151
|
+
type: "string",
|
|
1152
|
+
description: "A short tap-to-send answer."
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
},
|
|
1156
|
+
required: ["question", "suggestions"],
|
|
1157
|
+
additionalProperties: false
|
|
1158
|
+
}
|
|
1159
|
+
};
|
|
1160
|
+
function parseSuggestRepliesArgs(args) {
|
|
1161
|
+
const question = String(args.question ?? "").trim();
|
|
1162
|
+
if (!question) {
|
|
1163
|
+
throw new Error("suggest_replies requires a non-empty question");
|
|
1164
|
+
}
|
|
1165
|
+
if (!Array.isArray(args.suggestions) || args.suggestions.length < 2) {
|
|
1166
|
+
throw new Error("suggest_replies requires at least two suggestions");
|
|
1167
|
+
}
|
|
1168
|
+
const suggestions = args.suggestions.map((entry) => String(entry ?? "").trim()).filter((entry) => entry.length > 0);
|
|
1169
|
+
if (suggestions.length < 2) {
|
|
1170
|
+
throw new Error("suggest_replies requires at least two non-empty suggestions");
|
|
1171
|
+
}
|
|
1172
|
+
if (suggestions.length > 8) {
|
|
1173
|
+
throw new Error("suggest_replies allows at most 8 suggestions");
|
|
1174
|
+
}
|
|
1175
|
+
return { question, suggestions };
|
|
1176
|
+
}
|
|
1177
|
+
function isValidReplySuggestions(value) {
|
|
1178
|
+
if (!value || typeof value !== "object")
|
|
1179
|
+
return false;
|
|
1180
|
+
const entry = value;
|
|
1181
|
+
if (typeof entry.question !== "string" || !entry.question.trim()) {
|
|
1182
|
+
return false;
|
|
1183
|
+
}
|
|
1184
|
+
if (!Array.isArray(entry.suggestions) || entry.suggestions.length < 2) {
|
|
1185
|
+
return false;
|
|
1186
|
+
}
|
|
1187
|
+
return entry.suggestions.every((suggestion) => typeof suggestion === "string" && suggestion.trim());
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
// src/core/interactive-tools/constants.ts
|
|
1191
|
+
var INTERACTIVE_CHAT_TOOL_NAMES = new Set([
|
|
1192
|
+
REQUEST_CONFIRMATION_TOOL,
|
|
1193
|
+
REQUEST_CHOICES_TOOL
|
|
1194
|
+
]);
|
|
1195
|
+
var POST_RESPONSE_CHAT_TOOL_NAMES = new Set([SUGGEST_REPLIES_TOOL]);
|
|
1196
|
+
function isInteractiveChatTool(name) {
|
|
1197
|
+
return INTERACTIVE_CHAT_TOOL_NAMES.has(name);
|
|
1198
|
+
}
|
|
1199
|
+
function isPostResponseChatTool(name) {
|
|
1200
|
+
return POST_RESPONSE_CHAT_TOOL_NAMES.has(name);
|
|
1201
|
+
}
|
|
1202
|
+
function isChatUiTool(name) {
|
|
1203
|
+
return isInteractiveChatTool(name) || isPostResponseChatTool(name);
|
|
1204
|
+
}
|
|
1205
|
+
// src/core/interactive-tools/waiters.ts
|
|
1206
|
+
var waiters = new Map;
|
|
1207
|
+
function waitForInteractiveToolResult(callId, signal) {
|
|
1208
|
+
return new Promise((resolve, reject) => {
|
|
1209
|
+
if (signal?.aborted) {
|
|
1210
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
1211
|
+
return;
|
|
1212
|
+
}
|
|
1213
|
+
const onAbort = () => {
|
|
1214
|
+
waiters.delete(callId);
|
|
1215
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
1216
|
+
};
|
|
1217
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1218
|
+
waiters.set(callId, {
|
|
1219
|
+
resolve: (value) => {
|
|
1220
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1221
|
+
resolve(value);
|
|
1222
|
+
},
|
|
1223
|
+
reject: (error) => {
|
|
1224
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1225
|
+
reject(error);
|
|
1226
|
+
}
|
|
1227
|
+
});
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
function resolveInteractiveToolResult(callId, value) {
|
|
1231
|
+
const waiter = waiters.get(callId);
|
|
1232
|
+
if (!waiter)
|
|
1233
|
+
return false;
|
|
1234
|
+
waiter.resolve(value);
|
|
1235
|
+
waiters.delete(callId);
|
|
1236
|
+
return true;
|
|
1237
|
+
}
|
|
1238
|
+
function rejectAllInteractiveToolWaiters(error) {
|
|
1239
|
+
for (const [callId, waiter] of waiters.entries()) {
|
|
1240
|
+
waiter.reject(error);
|
|
1241
|
+
waiters.delete(callId);
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
// src/core/interactive-tools/execute.ts
|
|
1246
|
+
function getChatInteractiveTools() {
|
|
1247
|
+
return [CONFIRMATION_TOOL, CHOICES_TOOL, SUGGEST_REPLIES_TOOL_DEFINITION];
|
|
1248
|
+
}
|
|
1249
|
+
async function executeChatInteractiveTool(name, args, callId, signal) {
|
|
1250
|
+
if (name === REQUEST_CONFIRMATION_TOOL) {
|
|
1251
|
+
parseConfirmationArgs(args);
|
|
1252
|
+
const result = await waitForInteractiveToolResult(callId, signal);
|
|
1253
|
+
return { content: JSON.stringify(result) };
|
|
1254
|
+
}
|
|
1255
|
+
if (name === REQUEST_CHOICES_TOOL) {
|
|
1256
|
+
parseChoicesArgs(args);
|
|
1257
|
+
const result = await waitForInteractiveToolResult(callId, signal);
|
|
1258
|
+
return { content: JSON.stringify(result) };
|
|
1259
|
+
}
|
|
1260
|
+
if (name === SUGGEST_REPLIES_TOOL) {
|
|
1261
|
+
const suggestions = parseSuggestRepliesArgs(args);
|
|
1262
|
+
return {
|
|
1263
|
+
content: JSON.stringify({ displayed: true }),
|
|
1264
|
+
postResponse: suggestions
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
throw new Error(`Unknown chat UI tool: ${name}`);
|
|
1268
|
+
}
|
|
1269
|
+
function shouldTerminateTurnAfterTool(name) {
|
|
1270
|
+
return isPostResponseChatTool(name);
|
|
1271
|
+
}
|
|
1272
|
+
// src/core/chat-history.ts
|
|
1273
|
+
var DEFAULT_HISTORY_KEY = "assistant-chat-history";
|
|
1274
|
+
var DEFAULT_MAX_STORED = 100;
|
|
1275
|
+
function toStored(message) {
|
|
1276
|
+
return {
|
|
1277
|
+
id: message.id,
|
|
1278
|
+
role: message.role,
|
|
1279
|
+
content: message.content,
|
|
1280
|
+
activity: message.activity,
|
|
1281
|
+
toolCall: message.toolCall,
|
|
1282
|
+
replySuggestions: message.replySuggestions,
|
|
1283
|
+
isError: message.isError,
|
|
1284
|
+
llmSetupRequired: message.llmSetupRequired,
|
|
1285
|
+
timestamp: message.timestamp
|
|
1286
|
+
};
|
|
1287
|
+
}
|
|
1288
|
+
function fromStored(message) {
|
|
1289
|
+
return {
|
|
1290
|
+
id: message.id,
|
|
1291
|
+
role: message.role,
|
|
1292
|
+
content: message.content,
|
|
1293
|
+
activity: message.activity,
|
|
1294
|
+
toolCall: message.toolCall,
|
|
1295
|
+
replySuggestions: isValidReplySuggestions(message.replySuggestions) ? message.replySuggestions : undefined,
|
|
1296
|
+
isError: message.isError,
|
|
1297
|
+
llmSetupRequired: message.llmSetupRequired,
|
|
1298
|
+
timestamp: message.timestamp
|
|
1299
|
+
};
|
|
1300
|
+
}
|
|
1301
|
+
function isStoredChatMessage(value) {
|
|
1302
|
+
if (!value || typeof value !== "object")
|
|
1303
|
+
return false;
|
|
1304
|
+
const message = value;
|
|
1305
|
+
return typeof message.id === "string" && (message.role === "user" || message.role === "assistant" || message.role === "system") && typeof message.content === "string" && typeof message.timestamp === "number";
|
|
1306
|
+
}
|
|
1307
|
+
function createChatHistoryHelpers(options) {
|
|
1308
|
+
const storageKey = options.storageKey ?? DEFAULT_HISTORY_KEY;
|
|
1309
|
+
const maxStored = options.maxStored ?? DEFAULT_MAX_STORED;
|
|
1310
|
+
function getStored() {
|
|
1311
|
+
try {
|
|
1312
|
+
const raw = localStorage.getItem(storageKey);
|
|
1313
|
+
if (!raw)
|
|
1314
|
+
return null;
|
|
1315
|
+
const parsed = JSON.parse(raw);
|
|
1316
|
+
if (!Array.isArray(parsed))
|
|
1317
|
+
return null;
|
|
1318
|
+
const messages = parsed.filter(isStoredChatMessage).map(fromStored);
|
|
1319
|
+
return messages.length > 0 ? messages : null;
|
|
1320
|
+
} catch {
|
|
1321
|
+
return null;
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
function persist(messages) {
|
|
1325
|
+
const storable = messages.filter((message) => !message.streaming).slice(-maxStored).map(toStored);
|
|
1326
|
+
localStorage.setItem(storageKey, JSON.stringify(storable));
|
|
1327
|
+
}
|
|
1328
|
+
function clear() {
|
|
1329
|
+
localStorage.removeItem(storageKey);
|
|
1330
|
+
}
|
|
1331
|
+
function loadInitial(ctx) {
|
|
1332
|
+
const stored = getStored();
|
|
1333
|
+
const welcome = options.welcomeMessage(ctx);
|
|
1334
|
+
if (stored) {
|
|
1335
|
+
const hasWelcome = stored.some((message) => message.id === "welcome");
|
|
1336
|
+
if (hasWelcome)
|
|
1337
|
+
return stored;
|
|
1338
|
+
return [welcome, ...stored];
|
|
1339
|
+
}
|
|
1340
|
+
return [welcome];
|
|
1341
|
+
}
|
|
1342
|
+
return { getStored, persist, clear, loadInitial };
|
|
1343
|
+
}
|
|
1344
|
+
// ../../node_modules/.bun/zustand@5.0.14+93dbe784b8baa420/node_modules/zustand/esm/vanilla.mjs
|
|
1345
|
+
var createStoreImpl = (createState) => {
|
|
1346
|
+
let state;
|
|
1347
|
+
const listeners = /* @__PURE__ */ new Set;
|
|
1348
|
+
const setState = (partial, replace) => {
|
|
1349
|
+
const nextState = typeof partial === "function" ? partial(state) : partial;
|
|
1350
|
+
if (!Object.is(nextState, state)) {
|
|
1351
|
+
const previousState = state;
|
|
1352
|
+
state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
|
|
1353
|
+
listeners.forEach((listener) => listener(state, previousState));
|
|
1354
|
+
}
|
|
1355
|
+
};
|
|
1356
|
+
const getState = () => state;
|
|
1357
|
+
const getInitialState = () => initialState;
|
|
1358
|
+
const subscribe = (listener) => {
|
|
1359
|
+
listeners.add(listener);
|
|
1360
|
+
return () => listeners.delete(listener);
|
|
1361
|
+
};
|
|
1362
|
+
const api = { setState, getState, getInitialState, subscribe };
|
|
1363
|
+
const initialState = state = createState(setState, getState, api);
|
|
1364
|
+
return api;
|
|
1365
|
+
};
|
|
1366
|
+
var createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl;
|
|
1367
|
+
|
|
1368
|
+
// ../../node_modules/.bun/zustand@5.0.14+93dbe784b8baa420/node_modules/zustand/esm/react.mjs
|
|
1369
|
+
var import_react = __toESM(require_react(), 1);
|
|
1370
|
+
var identity = (arg) => arg;
|
|
1371
|
+
function useStore(api, selector = identity) {
|
|
1372
|
+
const slice = import_react.default.useSyncExternalStore(api.subscribe, import_react.default.useCallback(() => selector(api.getState()), [api, selector]), import_react.default.useCallback(() => selector(api.getInitialState()), [api, selector]));
|
|
1373
|
+
import_react.default.useDebugValue(slice);
|
|
1374
|
+
return slice;
|
|
1375
|
+
}
|
|
1376
|
+
var createImpl = (createState) => {
|
|
1377
|
+
const api = createStore(createState);
|
|
1378
|
+
const useBoundStore = (selector) => useStore(api, selector);
|
|
1379
|
+
Object.assign(useBoundStore, api);
|
|
1380
|
+
return useBoundStore;
|
|
1381
|
+
};
|
|
1382
|
+
var create = (createState) => createState ? createImpl(createState) : createImpl;
|
|
1383
|
+
|
|
1384
|
+
// src/core/llm-config.ts
|
|
1385
|
+
var DEFAULT_LLM_BASE_URL = "https://api.openai.com/v1";
|
|
1386
|
+
var DEFAULT_LLM_MODEL = "gpt-4o-mini";
|
|
1387
|
+
var DEFAULT_ASSISTANT_SYSTEM_PROMPT = "You are a helpful assistant with access to tools. Use tools when they help answer the user.";
|
|
1388
|
+
var FALLBACK_MODEL_OPTIONS = [
|
|
1389
|
+
DEFAULT_LLM_MODEL,
|
|
1390
|
+
"gpt-4o",
|
|
1391
|
+
"gpt-4.1",
|
|
1392
|
+
"gpt-4.1-mini",
|
|
1393
|
+
"gpt-4.1-nano",
|
|
1394
|
+
"o3-mini"
|
|
1395
|
+
];
|
|
1396
|
+
function getFallbackModels(defaultModel) {
|
|
1397
|
+
return [...new Set([defaultModel, ...FALLBACK_MODEL_OPTIONS])];
|
|
1398
|
+
}
|
|
1399
|
+
function resolveRequestModel(requested, config) {
|
|
1400
|
+
const candidate = requested?.trim();
|
|
1401
|
+
if (candidate)
|
|
1402
|
+
return candidate;
|
|
1403
|
+
return config.model;
|
|
1404
|
+
}
|
|
1405
|
+
function buildCompletionsUrl(baseUrl) {
|
|
1406
|
+
const base = baseUrl.replace(/\/+$/, "");
|
|
1407
|
+
if (base.endsWith("/v1"))
|
|
1408
|
+
return `${base}/chat/completions`;
|
|
1409
|
+
return `${base}/v1/chat/completions`;
|
|
1410
|
+
}
|
|
1411
|
+
function buildModelsUrl(baseUrl) {
|
|
1412
|
+
const base = baseUrl.replace(/\/+$/, "");
|
|
1413
|
+
if (base.endsWith("/v1"))
|
|
1414
|
+
return `${base}/models`;
|
|
1415
|
+
return `${base}/v1/models`;
|
|
1416
|
+
}
|
|
1417
|
+
function isLocalLlmBaseUrl(baseUrl) {
|
|
1418
|
+
try {
|
|
1419
|
+
const normalized = baseUrl.includes("://") ? baseUrl : `http://${baseUrl}`;
|
|
1420
|
+
const hostname = new URL(normalized).hostname.toLowerCase();
|
|
1421
|
+
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "0.0.0.0" || hostname === "[::1]" || hostname.endsWith(".local");
|
|
1422
|
+
} catch {
|
|
1423
|
+
return false;
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
function isLlmConfigured(settings) {
|
|
1427
|
+
if (settings.enabled === false)
|
|
1428
|
+
return false;
|
|
1429
|
+
if (!settings.baseUrl?.trim() || !settings.model?.trim())
|
|
1430
|
+
return false;
|
|
1431
|
+
if (settings.apiKey?.trim())
|
|
1432
|
+
return true;
|
|
1433
|
+
return isLocalLlmBaseUrl(settings.baseUrl);
|
|
1434
|
+
}
|
|
1435
|
+
var LLM_UNAVAILABLE_MESSAGE = "Chat requires an LLM. Open LLM settings to add your provider base URL, model, and API key (optional for local servers).";
|
|
1436
|
+
function isLlmUnavailableMessage(message) {
|
|
1437
|
+
return message.llmSetupRequired === true || message.content.trim() === LLM_UNAVAILABLE_MESSAGE;
|
|
1438
|
+
}
|
|
1439
|
+
function buildLlmRequestHeaders(apiKey) {
|
|
1440
|
+
const headers = {
|
|
1441
|
+
"Content-Type": "application/json"
|
|
1442
|
+
};
|
|
1443
|
+
const token = apiKey?.trim();
|
|
1444
|
+
if (token) {
|
|
1445
|
+
headers.Authorization = `Bearer ${token}`;
|
|
1446
|
+
}
|
|
1447
|
+
return headers;
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
// src/core/llm-models.ts
|
|
1451
|
+
var CACHE_TTL_MS = 5 * 60 * 1000;
|
|
1452
|
+
var EXCLUDED_MODEL_PATTERNS = [
|
|
1453
|
+
/embed/i,
|
|
1454
|
+
/whisper/i,
|
|
1455
|
+
/tts/i,
|
|
1456
|
+
/dall-e/i,
|
|
1457
|
+
/moderation/i,
|
|
1458
|
+
/transcribe/i,
|
|
1459
|
+
/realtime/i,
|
|
1460
|
+
/audio/i,
|
|
1461
|
+
/speech/i,
|
|
1462
|
+
/image/i,
|
|
1463
|
+
/completion$/i
|
|
1464
|
+
];
|
|
1465
|
+
var modelCache = null;
|
|
1466
|
+
async function fetchProviderModels(config) {
|
|
1467
|
+
const cacheKey = `${config.baseUrl}:${config.apiKey?.slice(-6) ?? "local"}`;
|
|
1468
|
+
if (modelCache && modelCache.key === cacheKey && Date.now() - modelCache.fetchedAt < CACHE_TTL_MS) {
|
|
1469
|
+
return modelCache.models;
|
|
1470
|
+
}
|
|
1471
|
+
if (!config.apiKey?.trim()) {
|
|
1472
|
+
if (!isLlmConfigured({ enabled: true, ...config })) {
|
|
1473
|
+
return getFallbackModels(config.model);
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
try {
|
|
1477
|
+
const response = await fetch(buildModelsUrl(config.baseUrl), {
|
|
1478
|
+
headers: buildLlmRequestHeaders(config.apiKey)
|
|
1479
|
+
});
|
|
1480
|
+
if (!response.ok) {
|
|
1481
|
+
return getFallbackModels(config.model);
|
|
1482
|
+
}
|
|
1483
|
+
const body = await response.json();
|
|
1484
|
+
const models = normalizeProviderModels(body, config.model);
|
|
1485
|
+
modelCache = { key: cacheKey, models, fetchedAt: Date.now() };
|
|
1486
|
+
return models;
|
|
1487
|
+
} catch {
|
|
1488
|
+
return getFallbackModels(config.model);
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
function normalizeProviderModels(body, defaultModel) {
|
|
1492
|
+
const ids = (body.data ?? []).map((entry) => entry.id?.trim()).filter((id) => Boolean(id)).filter(isChatModel);
|
|
1493
|
+
return mergeModels(defaultModel, ids);
|
|
1494
|
+
}
|
|
1495
|
+
function isChatModel(modelId) {
|
|
1496
|
+
return !EXCLUDED_MODEL_PATTERNS.some((pattern) => pattern.test(modelId));
|
|
1497
|
+
}
|
|
1498
|
+
function mergeModels(defaultModel, models) {
|
|
1499
|
+
return [...new Set([defaultModel, ...models])].sort((a, b) => a.localeCompare(b));
|
|
1500
|
+
}
|
|
1501
|
+
function clearProviderModelCache() {
|
|
1502
|
+
modelCache = null;
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
// src/core/llm-provider.ts
|
|
1506
|
+
var DISABLED_SETTINGS = {
|
|
1507
|
+
enabled: false,
|
|
1508
|
+
baseUrl: DEFAULT_LLM_BASE_URL,
|
|
1509
|
+
apiKey: null,
|
|
1510
|
+
model: DEFAULT_LLM_MODEL
|
|
1511
|
+
};
|
|
1512
|
+
var resolveSettings = null;
|
|
1513
|
+
function normalizeSettings(input) {
|
|
1514
|
+
return {
|
|
1515
|
+
enabled: input.enabled,
|
|
1516
|
+
baseUrl: input.baseUrl?.trim() || DEFAULT_LLM_BASE_URL,
|
|
1517
|
+
apiKey: input.apiKey?.trim() || null,
|
|
1518
|
+
model: input.model?.trim() || DEFAULT_LLM_MODEL,
|
|
1519
|
+
models: input.models?.length ? [...input.models] : undefined,
|
|
1520
|
+
systemPrompt: input.systemPrompt?.trim() || undefined
|
|
1521
|
+
};
|
|
1522
|
+
}
|
|
1523
|
+
function configureAssistantLlm(config) {
|
|
1524
|
+
if (typeof config === "function") {
|
|
1525
|
+
resolveSettings = async () => normalizeSettings(await config());
|
|
1526
|
+
return;
|
|
1527
|
+
}
|
|
1528
|
+
const settings = normalizeSettings(config);
|
|
1529
|
+
resolveSettings = async () => settings;
|
|
1530
|
+
}
|
|
1531
|
+
async function resolveAssistantLlmSettings() {
|
|
1532
|
+
if (!resolveSettings)
|
|
1533
|
+
return DISABLED_SETTINGS;
|
|
1534
|
+
return resolveSettings();
|
|
1535
|
+
}
|
|
1536
|
+
function resetAssistantLlm() {
|
|
1537
|
+
resolveSettings = null;
|
|
1538
|
+
}
|
|
1539
|
+
async function testLlmConnection(settings) {
|
|
1540
|
+
if (!settings.apiKey?.trim() && !isLocalLlmBaseUrl(settings.baseUrl)) {
|
|
1541
|
+
return {
|
|
1542
|
+
ok: false,
|
|
1543
|
+
error: "API key is required for remote LLM providers."
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
try {
|
|
1547
|
+
const response = await fetch(buildCompletionsUrl(settings.baseUrl), {
|
|
1548
|
+
method: "POST",
|
|
1549
|
+
headers: buildLlmRequestHeaders(settings.apiKey),
|
|
1550
|
+
body: JSON.stringify({
|
|
1551
|
+
model: settings.model,
|
|
1552
|
+
messages: [{ role: "user", content: "ping" }],
|
|
1553
|
+
max_tokens: 1
|
|
1554
|
+
})
|
|
1555
|
+
});
|
|
1556
|
+
if (!response.ok) {
|
|
1557
|
+
const raw = await response.text();
|
|
1558
|
+
let message = `Connection failed (${response.status})`;
|
|
1559
|
+
try {
|
|
1560
|
+
const body2 = JSON.parse(raw);
|
|
1561
|
+
if (typeof body2.error === "string")
|
|
1562
|
+
message = body2.error;
|
|
1563
|
+
else if (typeof body2.error?.message === "string") {
|
|
1564
|
+
message = body2.error.message;
|
|
1565
|
+
} else if (typeof body2.message === "string") {
|
|
1566
|
+
message = body2.message;
|
|
1567
|
+
}
|
|
1568
|
+
} catch {
|
|
1569
|
+
if (raw.trim())
|
|
1570
|
+
message = raw.trim();
|
|
1571
|
+
}
|
|
1572
|
+
return { ok: false, error: message };
|
|
1573
|
+
}
|
|
1574
|
+
const body = await response.json();
|
|
1575
|
+
return { ok: true, model: body.model ?? settings.model };
|
|
1576
|
+
} catch (error) {
|
|
1577
|
+
return {
|
|
1578
|
+
ok: false,
|
|
1579
|
+
error: error instanceof Error ? error.message : "Connection failed"
|
|
1580
|
+
};
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
// src/core/llm-sse.ts
|
|
1585
|
+
function createStreamParser() {
|
|
1586
|
+
let content = "";
|
|
1587
|
+
let model = null;
|
|
1588
|
+
const toolAcc = new Map;
|
|
1589
|
+
function toolCallAt(index) {
|
|
1590
|
+
const existing = toolAcc.get(index);
|
|
1591
|
+
if (existing)
|
|
1592
|
+
return existing;
|
|
1593
|
+
const created = {
|
|
1594
|
+
id: "",
|
|
1595
|
+
type: "function",
|
|
1596
|
+
function: { name: "", arguments: "" }
|
|
1597
|
+
};
|
|
1598
|
+
toolAcc.set(index, created);
|
|
1599
|
+
return created;
|
|
1600
|
+
}
|
|
1601
|
+
function ingestLine(line) {
|
|
1602
|
+
const trimmed = line.trim();
|
|
1603
|
+
if (!trimmed.startsWith("data:"))
|
|
1604
|
+
return null;
|
|
1605
|
+
const data = trimmed.slice(5).trim();
|
|
1606
|
+
if (data === "[DONE]") {
|
|
1607
|
+
return {
|
|
1608
|
+
contentDelta: "",
|
|
1609
|
+
content,
|
|
1610
|
+
toolCalls: finalizeToolCalls(),
|
|
1611
|
+
model,
|
|
1612
|
+
done: true
|
|
1613
|
+
};
|
|
1614
|
+
}
|
|
1615
|
+
let json;
|
|
1616
|
+
try {
|
|
1617
|
+
json = JSON.parse(data);
|
|
1618
|
+
} catch {
|
|
1619
|
+
return null;
|
|
1620
|
+
}
|
|
1621
|
+
if (typeof json.model === "string")
|
|
1622
|
+
model = json.model;
|
|
1623
|
+
const choice = json.choices?.[0];
|
|
1624
|
+
const delta = choice?.delta;
|
|
1625
|
+
if (!delta)
|
|
1626
|
+
return null;
|
|
1627
|
+
let contentDelta = "";
|
|
1628
|
+
if (typeof delta.content === "string" && delta.content.length > 0) {
|
|
1629
|
+
contentDelta = delta.content;
|
|
1630
|
+
content += contentDelta;
|
|
1631
|
+
}
|
|
1632
|
+
const toolDeltas = delta.tool_calls;
|
|
1633
|
+
if (toolDeltas) {
|
|
1634
|
+
for (const toolDelta of toolDeltas) {
|
|
1635
|
+
const index = toolDelta.index ?? 0;
|
|
1636
|
+
const current = toolCallAt(index);
|
|
1637
|
+
if (typeof toolDelta.id === "string")
|
|
1638
|
+
current.id = toolDelta.id;
|
|
1639
|
+
const fn = toolDelta.function;
|
|
1640
|
+
if (fn && typeof fn.name === "string")
|
|
1641
|
+
current.function.name = fn.name;
|
|
1642
|
+
if (fn && typeof fn.arguments === "string") {
|
|
1643
|
+
current.function.arguments += fn.arguments;
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
return {
|
|
1648
|
+
contentDelta,
|
|
1649
|
+
content,
|
|
1650
|
+
toolCalls: finalizeToolCalls(),
|
|
1651
|
+
model,
|
|
1652
|
+
done: false
|
|
1653
|
+
};
|
|
1654
|
+
}
|
|
1655
|
+
function finalizeToolCalls() {
|
|
1656
|
+
return [...toolAcc.entries()].sort(([a], [b]) => a - b).map(([, value]) => value).filter((value) => Boolean(value.id && value.function.name));
|
|
1657
|
+
}
|
|
1658
|
+
return { ingestLine };
|
|
1659
|
+
}
|
|
1660
|
+
async function readSseStream(body, onChunk, signal) {
|
|
1661
|
+
const reader = body.getReader();
|
|
1662
|
+
const decoder = new TextDecoder;
|
|
1663
|
+
const parser = createStreamParser();
|
|
1664
|
+
let buffer = "";
|
|
1665
|
+
let last = {
|
|
1666
|
+
contentDelta: "",
|
|
1667
|
+
content: "",
|
|
1668
|
+
toolCalls: [],
|
|
1669
|
+
model: null,
|
|
1670
|
+
done: false
|
|
1671
|
+
};
|
|
1672
|
+
const abort = () => {
|
|
1673
|
+
reader.cancel();
|
|
1674
|
+
};
|
|
1675
|
+
if (signal?.aborted) {
|
|
1676
|
+
abort();
|
|
1677
|
+
throw new DOMException("Aborted", "AbortError");
|
|
1678
|
+
}
|
|
1679
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
1680
|
+
try {
|
|
1681
|
+
while (true) {
|
|
1682
|
+
if (signal?.aborted) {
|
|
1683
|
+
throw new DOMException("Aborted", "AbortError");
|
|
1684
|
+
}
|
|
1685
|
+
const { done, value } = await reader.read();
|
|
1686
|
+
if (done)
|
|
1687
|
+
break;
|
|
1688
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1689
|
+
const lines = buffer.split(`
|
|
1690
|
+
`);
|
|
1691
|
+
buffer = lines.pop() ?? "";
|
|
1692
|
+
for (const line of lines) {
|
|
1693
|
+
const chunk = parser.ingestLine(line);
|
|
1694
|
+
if (!chunk)
|
|
1695
|
+
continue;
|
|
1696
|
+
last = chunk;
|
|
1697
|
+
onChunk(chunk);
|
|
1698
|
+
if (chunk.done)
|
|
1699
|
+
return chunk;
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
} finally {
|
|
1703
|
+
signal?.removeEventListener("abort", abort);
|
|
1704
|
+
}
|
|
1705
|
+
if (buffer.trim()) {
|
|
1706
|
+
const chunk = parser.ingestLine(buffer);
|
|
1707
|
+
if (chunk) {
|
|
1708
|
+
last = { ...chunk, done: true };
|
|
1709
|
+
onChunk(last);
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
return { ...last, done: true };
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
// src/core/llm-chat.ts
|
|
1716
|
+
var MAX_AGENT_STEPS = 8;
|
|
1717
|
+
var DEFAULT_SYSTEM_PROMPT = "You are a helpful assistant with access to tools. Use tools when they help answer the user.";
|
|
1718
|
+
|
|
1719
|
+
class LlmNotConfiguredError extends Error {
|
|
1720
|
+
code = "LLM_DISABLED";
|
|
1721
|
+
constructor(message = "LLM is not configured. Provide llm settings with a valid apiKey.") {
|
|
1722
|
+
super(message);
|
|
1723
|
+
this.name = "LlmNotConfiguredError";
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
class LlmUpstreamError extends Error {
|
|
1728
|
+
status;
|
|
1729
|
+
code;
|
|
1730
|
+
constructor(message, status, code = "LLM_UPSTREAM_ERROR") {
|
|
1731
|
+
super(message);
|
|
1732
|
+
this.name = "LlmUpstreamError";
|
|
1733
|
+
this.status = status;
|
|
1734
|
+
this.code = code;
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
class ChatAbortedError extends Error {
|
|
1739
|
+
constructor() {
|
|
1740
|
+
super("Chat aborted");
|
|
1741
|
+
this.name = "ChatAbortedError";
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
async function fetchLlmStatus() {
|
|
1745
|
+
try {
|
|
1746
|
+
const config = await resolveAssistantLlmSettings();
|
|
1747
|
+
if (!isLlmConfigured(config)) {
|
|
1748
|
+
return { enabled: false, model: null, models: [] };
|
|
1749
|
+
}
|
|
1750
|
+
const models = config.models?.length ? config.models : await fetchProviderModels(config);
|
|
1751
|
+
return {
|
|
1752
|
+
enabled: true,
|
|
1753
|
+
model: config.model,
|
|
1754
|
+
models
|
|
1755
|
+
};
|
|
1756
|
+
} catch {
|
|
1757
|
+
return { enabled: false, model: null, models: [] };
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
async function requestLlmCompletion(input) {
|
|
1761
|
+
if (input.stream) {
|
|
1762
|
+
return requestLlmCompletionStream(input, input.stream);
|
|
1763
|
+
}
|
|
1764
|
+
const settings = await requireLlmSettings();
|
|
1765
|
+
const payload = buildChatPayload(input, settings);
|
|
1766
|
+
const res = await fetch(buildCompletionsUrl(settings.baseUrl), {
|
|
1767
|
+
method: "POST",
|
|
1768
|
+
headers: buildLlmRequestHeaders(settings.apiKey),
|
|
1769
|
+
body: JSON.stringify(payload),
|
|
1770
|
+
signal: input.signal
|
|
1771
|
+
});
|
|
1772
|
+
const raw = await res.text();
|
|
1773
|
+
let data = {};
|
|
1774
|
+
try {
|
|
1775
|
+
data = raw ? JSON.parse(raw) : {};
|
|
1776
|
+
} catch {
|
|
1777
|
+
throw new LlmUpstreamError(`LLM returned non-JSON response (${res.status})`, 502, "LLM_BAD_RESPONSE");
|
|
1778
|
+
}
|
|
1779
|
+
if (!res.ok) {
|
|
1780
|
+
throw upstreamError(data, res.status);
|
|
1781
|
+
}
|
|
1782
|
+
const choice = data.choices?.[0];
|
|
1783
|
+
const message = choice?.message;
|
|
1784
|
+
if (!message) {
|
|
1785
|
+
throw new LlmUpstreamError("LLM response missing message", 502, "LLM_BAD_RESPONSE");
|
|
1786
|
+
}
|
|
1787
|
+
return {
|
|
1788
|
+
content: message.content ?? null,
|
|
1789
|
+
toolCalls: message.tool_calls ?? [],
|
|
1790
|
+
model: typeof data.model === "string" ? data.model : settings.model
|
|
1791
|
+
};
|
|
1792
|
+
}
|
|
1793
|
+
async function requestLlmCompletionStream(input, handlers) {
|
|
1794
|
+
const settings = await requireLlmSettings();
|
|
1795
|
+
const payload = buildChatPayload(input, settings);
|
|
1796
|
+
try {
|
|
1797
|
+
const res = await fetch(buildCompletionsUrl(settings.baseUrl), {
|
|
1798
|
+
method: "POST",
|
|
1799
|
+
headers: buildLlmRequestHeaders(settings.apiKey),
|
|
1800
|
+
body: JSON.stringify({ ...payload, stream: true }),
|
|
1801
|
+
signal: input.signal
|
|
1802
|
+
});
|
|
1803
|
+
if (!res.ok) {
|
|
1804
|
+
const raw = await res.text();
|
|
1805
|
+
let data = {};
|
|
1806
|
+
try {
|
|
1807
|
+
data = raw ? JSON.parse(raw) : {};
|
|
1808
|
+
} catch {}
|
|
1809
|
+
throw upstreamError(data, res.status);
|
|
1810
|
+
}
|
|
1811
|
+
if (!res.body) {
|
|
1812
|
+
throw new LlmUpstreamError("LLM stream missing body", 502, "LLM_BAD_RESPONSE");
|
|
1813
|
+
}
|
|
1814
|
+
const final = await readSseStream(res.body, (chunk) => {
|
|
1815
|
+
if (chunk.contentDelta) {
|
|
1816
|
+
handlers.onUpdate(chunk.content);
|
|
1817
|
+
}
|
|
1818
|
+
}, input.signal);
|
|
1819
|
+
return {
|
|
1820
|
+
content: final.content || null,
|
|
1821
|
+
toolCalls: final.toolCalls,
|
|
1822
|
+
model: final.model ?? settings.model
|
|
1823
|
+
};
|
|
1824
|
+
} catch (error) {
|
|
1825
|
+
if (input.signal?.aborted || error instanceof DOMException && error.name === "AbortError") {
|
|
1826
|
+
throw new ChatAbortedError;
|
|
1827
|
+
}
|
|
1828
|
+
throw error;
|
|
1829
|
+
}
|
|
1830
|
+
}
|
|
1831
|
+
async function runLlmAgent(input) {
|
|
1832
|
+
const apiMessages = [
|
|
1833
|
+
...input.history,
|
|
1834
|
+
{ role: "user", content: input.userMessage }
|
|
1835
|
+
];
|
|
1836
|
+
let lastToolResult;
|
|
1837
|
+
const clientTools = [
|
|
1838
|
+
...input.tools.map(toClientTool),
|
|
1839
|
+
...getChatInteractiveTools()
|
|
1840
|
+
];
|
|
1841
|
+
let finalContent = "";
|
|
1842
|
+
let endedWithPostResponseTool = false;
|
|
1843
|
+
for (let step = 0;step < MAX_AGENT_STEPS; step++) {
|
|
1844
|
+
if (input.signal?.aborted) {
|
|
1845
|
+
throw new ChatAbortedError;
|
|
1846
|
+
}
|
|
1847
|
+
const completion = await requestLlmCompletion({
|
|
1848
|
+
messages: apiMessages,
|
|
1849
|
+
tools: clientTools,
|
|
1850
|
+
model: input.model,
|
|
1851
|
+
signal: input.signal,
|
|
1852
|
+
stream: input.stream ? {
|
|
1853
|
+
turnId: input.stream.turnId,
|
|
1854
|
+
onUpdate: (content) => {
|
|
1855
|
+
finalContent = content;
|
|
1856
|
+
input.stream?.onUpdate(content);
|
|
1857
|
+
}
|
|
1858
|
+
} : undefined
|
|
1859
|
+
});
|
|
1860
|
+
if (completion.toolCalls.length === 0) {
|
|
1861
|
+
finalContent = completion.content?.trim() || "I couldn't produce a response. Try rephrasing your request.";
|
|
1862
|
+
input.stream?.onUpdate(finalContent);
|
|
1863
|
+
apiMessages.push({
|
|
1864
|
+
role: "assistant",
|
|
1865
|
+
content: completion.content
|
|
1866
|
+
});
|
|
1867
|
+
break;
|
|
1868
|
+
}
|
|
1869
|
+
apiMessages.push({
|
|
1870
|
+
role: "assistant",
|
|
1871
|
+
content: completion.content,
|
|
1872
|
+
tool_calls: completion.toolCalls
|
|
1873
|
+
});
|
|
1874
|
+
let terminatesTurn = false;
|
|
1875
|
+
for (const call of completion.toolCalls) {
|
|
1876
|
+
const args = parseToolArguments(call.function.arguments);
|
|
1877
|
+
const stepId = crypto.randomUUID();
|
|
1878
|
+
input.toolHandlers?.onStart({
|
|
1879
|
+
id: stepId,
|
|
1880
|
+
name: call.function.name,
|
|
1881
|
+
args,
|
|
1882
|
+
callId: call.id
|
|
1883
|
+
});
|
|
1884
|
+
let toolContent;
|
|
1885
|
+
let finishUpdate;
|
|
1886
|
+
if (isChatUiTool(call.function.name)) {
|
|
1887
|
+
try {
|
|
1888
|
+
const interactiveResult = await executeChatInteractiveTool(call.function.name, args, call.id, input.signal);
|
|
1889
|
+
toolContent = interactiveResult.content;
|
|
1890
|
+
finishUpdate = {
|
|
1891
|
+
status: interactiveResult.isError ? "error" : "done",
|
|
1892
|
+
result: JSON.parse(interactiveResult.content)
|
|
1893
|
+
};
|
|
1894
|
+
if (interactiveResult.postResponse) {
|
|
1895
|
+
input.onPostResponseTool?.(interactiveResult.postResponse);
|
|
1896
|
+
terminatesTurn = true;
|
|
1897
|
+
}
|
|
1898
|
+
} catch (error) {
|
|
1899
|
+
if (input.signal?.aborted || error instanceof DOMException && error.name === "AbortError") {
|
|
1900
|
+
throw new ChatAbortedError;
|
|
1901
|
+
}
|
|
1902
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1903
|
+
toolContent = message;
|
|
1904
|
+
finishUpdate = { status: "error", error: message };
|
|
1905
|
+
}
|
|
1906
|
+
} else {
|
|
1907
|
+
const result = await input.invokeTool(call.function.name, args);
|
|
1908
|
+
lastToolResult = result;
|
|
1909
|
+
toolContent = formatToolResult(result);
|
|
1910
|
+
finishUpdate = {
|
|
1911
|
+
status: result.isError ? "error" : "done",
|
|
1912
|
+
result: result.structuredContent ?? result,
|
|
1913
|
+
error: result.isError ? result.content[0]?.text : undefined
|
|
1914
|
+
};
|
|
1915
|
+
}
|
|
1916
|
+
input.toolHandlers?.onFinish(stepId, finishUpdate);
|
|
1917
|
+
apiMessages.push({
|
|
1918
|
+
role: "tool",
|
|
1919
|
+
tool_call_id: call.id,
|
|
1920
|
+
content: toolContent
|
|
1921
|
+
});
|
|
1922
|
+
if (shouldTerminateTurnAfterTool(call.function.name)) {
|
|
1923
|
+
terminatesTurn = true;
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
if (terminatesTurn) {
|
|
1927
|
+
finalContent = completion.content?.trim() || finalContent.trim() || "Choose an option below or type your reply.";
|
|
1928
|
+
input.stream?.onUpdate(finalContent);
|
|
1929
|
+
endedWithPostResponseTool = true;
|
|
1930
|
+
break;
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
if (!endedWithPostResponseTool && apiMessages.at(-1)?.role === "tool") {
|
|
1934
|
+
const completion = await requestLlmCompletion({
|
|
1935
|
+
messages: apiMessages,
|
|
1936
|
+
tools: clientTools,
|
|
1937
|
+
model: input.model,
|
|
1938
|
+
signal: input.signal,
|
|
1939
|
+
stream: input.stream ? {
|
|
1940
|
+
turnId: input.stream.turnId,
|
|
1941
|
+
onUpdate: (content) => {
|
|
1942
|
+
finalContent = content;
|
|
1943
|
+
input.stream?.onUpdate(content);
|
|
1944
|
+
}
|
|
1945
|
+
} : undefined
|
|
1946
|
+
});
|
|
1947
|
+
finalContent = completion.content?.trim() || "Done — see the trace below for details.";
|
|
1948
|
+
input.stream?.onUpdate(finalContent);
|
|
1949
|
+
apiMessages.push({
|
|
1950
|
+
role: "assistant",
|
|
1951
|
+
content: completion.content
|
|
1952
|
+
});
|
|
1953
|
+
}
|
|
1954
|
+
return {
|
|
1955
|
+
assistantMessages: finalContent ? [{ id: input.stream?.turnId, content: finalContent }] : [],
|
|
1956
|
+
apiMessages,
|
|
1957
|
+
lastToolResult
|
|
1958
|
+
};
|
|
1959
|
+
}
|
|
1960
|
+
function resolveAssistantContentForApi(message) {
|
|
1961
|
+
const content = message.content.trim();
|
|
1962
|
+
if (content)
|
|
1963
|
+
return message.content;
|
|
1964
|
+
if (message.replySuggestions?.question.trim()) {
|
|
1965
|
+
return message.replySuggestions.question;
|
|
1966
|
+
}
|
|
1967
|
+
return message.content;
|
|
1968
|
+
}
|
|
1969
|
+
var MAX_HISTORY_USER_TURNS = 12;
|
|
1970
|
+
function trimMessagesForHistory(messages, maxUserTurns) {
|
|
1971
|
+
if (messages.length === 0 || maxUserTurns <= 0)
|
|
1972
|
+
return messages;
|
|
1973
|
+
let userCount = 0;
|
|
1974
|
+
let start = 0;
|
|
1975
|
+
for (let i = messages.length - 1;i >= 0; i--) {
|
|
1976
|
+
if (messages[i]?.role === "user") {
|
|
1977
|
+
userCount++;
|
|
1978
|
+
if (userCount >= maxUserTurns) {
|
|
1979
|
+
start = i;
|
|
1980
|
+
break;
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
return messages.slice(start);
|
|
1985
|
+
}
|
|
1986
|
+
function sanitizeLlmMessages(messages) {
|
|
1987
|
+
const out = [];
|
|
1988
|
+
let pendingToolCallIds = null;
|
|
1989
|
+
for (const msg of messages) {
|
|
1990
|
+
if (msg.role === "assistant" && msg.tool_calls?.length) {
|
|
1991
|
+
out.push(msg);
|
|
1992
|
+
pendingToolCallIds = new Set(msg.tool_calls.map((toolCall) => toolCall.id));
|
|
1993
|
+
continue;
|
|
1994
|
+
}
|
|
1995
|
+
if (msg.role === "tool") {
|
|
1996
|
+
const callId = msg.tool_call_id;
|
|
1997
|
+
if (callId && pendingToolCallIds?.has(callId)) {
|
|
1998
|
+
out.push(msg);
|
|
1999
|
+
pendingToolCallIds.delete(callId);
|
|
2000
|
+
if (pendingToolCallIds.size === 0) {
|
|
2001
|
+
pendingToolCallIds = null;
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
continue;
|
|
2005
|
+
}
|
|
2006
|
+
pendingToolCallIds = null;
|
|
2007
|
+
out.push(msg);
|
|
2008
|
+
}
|
|
2009
|
+
while (out[0]?.role === "tool") {
|
|
2010
|
+
out.shift();
|
|
2011
|
+
}
|
|
2012
|
+
return out;
|
|
2013
|
+
}
|
|
2014
|
+
function buildLlmHistory(messages) {
|
|
2015
|
+
const history = [];
|
|
2016
|
+
for (const msg of trimMessagesForHistory(messages, MAX_HISTORY_USER_TURNS)) {
|
|
2017
|
+
if (msg.role === "user") {
|
|
2018
|
+
history.push({ role: "user", content: msg.content });
|
|
2019
|
+
continue;
|
|
2020
|
+
}
|
|
2021
|
+
if (msg.role !== "assistant")
|
|
2022
|
+
continue;
|
|
2023
|
+
if (msg.activity?.length) {
|
|
2024
|
+
const baseId = history.length;
|
|
2025
|
+
const toolCalls = msg.activity.map((step, index) => ({
|
|
2026
|
+
id: `call_${baseId}_${index}`,
|
|
2027
|
+
type: "function",
|
|
2028
|
+
function: {
|
|
2029
|
+
name: step.name,
|
|
2030
|
+
arguments: JSON.stringify(step.args)
|
|
2031
|
+
}
|
|
2032
|
+
}));
|
|
2033
|
+
history.push({
|
|
2034
|
+
role: "assistant",
|
|
2035
|
+
content: resolveAssistantContentForApi(msg) || null,
|
|
2036
|
+
tool_calls: toolCalls
|
|
2037
|
+
});
|
|
2038
|
+
for (const [index, step] of msg.activity.entries()) {
|
|
2039
|
+
history.push({
|
|
2040
|
+
role: "tool",
|
|
2041
|
+
tool_call_id: `call_${baseId}_${index}`,
|
|
2042
|
+
content: step.error ?? (typeof step.result === "string" ? step.result : JSON.stringify(step.result ?? "Result shown in UI."))
|
|
2043
|
+
});
|
|
2044
|
+
}
|
|
2045
|
+
continue;
|
|
2046
|
+
}
|
|
2047
|
+
if (msg.toolCall) {
|
|
2048
|
+
const id = `call_${history.length}`;
|
|
2049
|
+
history.push({
|
|
2050
|
+
role: "assistant",
|
|
2051
|
+
content: msg.content || null,
|
|
2052
|
+
tool_calls: [
|
|
2053
|
+
{
|
|
2054
|
+
id,
|
|
2055
|
+
type: "function",
|
|
2056
|
+
function: {
|
|
2057
|
+
name: msg.toolCall.name,
|
|
2058
|
+
arguments: JSON.stringify(msg.toolCall.args)
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
]
|
|
2062
|
+
});
|
|
2063
|
+
history.push({
|
|
2064
|
+
role: "tool",
|
|
2065
|
+
tool_call_id: id,
|
|
2066
|
+
content: "Result shown in UI."
|
|
2067
|
+
});
|
|
2068
|
+
continue;
|
|
2069
|
+
}
|
|
2070
|
+
history.push({
|
|
2071
|
+
role: "assistant",
|
|
2072
|
+
content: resolveAssistantContentForApi(msg)
|
|
2073
|
+
});
|
|
2074
|
+
}
|
|
2075
|
+
return sanitizeLlmMessages(history);
|
|
2076
|
+
}
|
|
2077
|
+
async function requireLlmSettings() {
|
|
2078
|
+
const settings = await resolveAssistantLlmSettings();
|
|
2079
|
+
if (!isLlmConfigured(settings)) {
|
|
2080
|
+
throw new LlmNotConfiguredError;
|
|
2081
|
+
}
|
|
2082
|
+
return settings;
|
|
2083
|
+
}
|
|
2084
|
+
function buildChatPayload(body, settings) {
|
|
2085
|
+
const messages = [
|
|
2086
|
+
{
|
|
2087
|
+
role: "system",
|
|
2088
|
+
content: body.systemPrompt ?? settings.systemPrompt ?? DEFAULT_SYSTEM_PROMPT
|
|
2089
|
+
},
|
|
2090
|
+
...body.messages.filter((message) => message.role !== "system")
|
|
2091
|
+
];
|
|
2092
|
+
const payload = {
|
|
2093
|
+
model: resolveRequestModel(body.model, settings),
|
|
2094
|
+
messages
|
|
2095
|
+
};
|
|
2096
|
+
if (body.responseFormat) {
|
|
2097
|
+
payload.response_format = body.responseFormat;
|
|
2098
|
+
}
|
|
2099
|
+
if (body.tools?.length) {
|
|
2100
|
+
payload.tools = body.tools.map((tool) => ({
|
|
2101
|
+
type: "function",
|
|
2102
|
+
function: {
|
|
2103
|
+
name: tool.name,
|
|
2104
|
+
description: tool.description,
|
|
2105
|
+
parameters: tool.inputSchema
|
|
2106
|
+
}
|
|
2107
|
+
}));
|
|
2108
|
+
payload.tool_choice = "auto";
|
|
2109
|
+
}
|
|
2110
|
+
return payload;
|
|
2111
|
+
}
|
|
2112
|
+
function upstreamError(body, status) {
|
|
2113
|
+
const errorRecord = body.error;
|
|
2114
|
+
const message = typeof errorRecord?.message === "string" && errorRecord.message || typeof body.message === "string" && body.message || typeof body.error === "string" && body.error || `LLM request failed (${status})`;
|
|
2115
|
+
const code = typeof body.code === "string" && body.code || "LLM_UPSTREAM_ERROR";
|
|
2116
|
+
return new LlmUpstreamError(message, status, code);
|
|
2117
|
+
}
|
|
2118
|
+
function toClientTool(tool) {
|
|
2119
|
+
return {
|
|
2120
|
+
name: tool.name,
|
|
2121
|
+
description: tool.description,
|
|
2122
|
+
inputSchema: tool.inputSchema
|
|
2123
|
+
};
|
|
2124
|
+
}
|
|
2125
|
+
function parseToolArguments(raw) {
|
|
2126
|
+
try {
|
|
2127
|
+
const parsed = JSON.parse(raw);
|
|
2128
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
2129
|
+
return parsed;
|
|
2130
|
+
}
|
|
2131
|
+
return { params: parsed };
|
|
2132
|
+
} catch {
|
|
2133
|
+
return { params: [raw] };
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
function formatToolResult(result) {
|
|
2137
|
+
if (result.isError) {
|
|
2138
|
+
return result.content.map((c) => c.text).join(`
|
|
2139
|
+
`);
|
|
2140
|
+
}
|
|
2141
|
+
if (result.structuredContent !== undefined) {
|
|
2142
|
+
return JSON.stringify(result.structuredContent);
|
|
2143
|
+
}
|
|
2144
|
+
return result.content.map((c) => c.text).join(`
|
|
2145
|
+
`);
|
|
2146
|
+
}
|
|
2147
|
+
|
|
2148
|
+
// src/core/llm-settings-storage.ts
|
|
2149
|
+
var DEFAULT_LLM_SETTINGS_STORAGE_KEY = "assistant-llm-settings";
|
|
2150
|
+
function buildDefaultLlmSettings() {
|
|
2151
|
+
return {
|
|
2152
|
+
enabled: false,
|
|
2153
|
+
baseUrl: DEFAULT_LLM_BASE_URL,
|
|
2154
|
+
apiKey: null,
|
|
2155
|
+
model: DEFAULT_LLM_MODEL
|
|
2156
|
+
};
|
|
2157
|
+
}
|
|
2158
|
+
function assistantToStored(settings) {
|
|
2159
|
+
return {
|
|
2160
|
+
baseUrl: settings.baseUrl?.trim() || DEFAULT_LLM_BASE_URL,
|
|
2161
|
+
apiKey: settings.apiKey?.trim() || null,
|
|
2162
|
+
model: settings.model?.trim() || DEFAULT_LLM_MODEL,
|
|
2163
|
+
models: settings.models?.length ? [...settings.models] : [],
|
|
2164
|
+
systemPrompt: settings.systemPrompt ?? ""
|
|
2165
|
+
};
|
|
2166
|
+
}
|
|
2167
|
+
function storedToAssistant(stored) {
|
|
2168
|
+
const baseUrl = stored.baseUrl;
|
|
2169
|
+
const apiKey = stored.apiKey;
|
|
2170
|
+
const model = stored.model;
|
|
2171
|
+
return {
|
|
2172
|
+
enabled: isLlmConfigured({
|
|
2173
|
+
enabled: true,
|
|
2174
|
+
baseUrl,
|
|
2175
|
+
apiKey,
|
|
2176
|
+
model
|
|
2177
|
+
}),
|
|
2178
|
+
baseUrl,
|
|
2179
|
+
apiKey,
|
|
2180
|
+
model,
|
|
2181
|
+
models: stored.models.length > 0 ? stored.models : undefined,
|
|
2182
|
+
systemPrompt: stored.systemPrompt || undefined
|
|
2183
|
+
};
|
|
2184
|
+
}
|
|
2185
|
+
function normalizeStoredSettings(raw, base) {
|
|
2186
|
+
if (!raw || typeof raw !== "object")
|
|
2187
|
+
return null;
|
|
2188
|
+
const partial = raw;
|
|
2189
|
+
const baseStored = assistantToStored(base);
|
|
2190
|
+
return {
|
|
2191
|
+
baseUrl: typeof partial.baseUrl === "string" && partial.baseUrl.trim() ? partial.baseUrl.trim() : baseStored.baseUrl,
|
|
2192
|
+
apiKey: typeof partial.apiKey === "string" ? partial.apiKey.trim() || null : partial.apiKey === null ? null : baseStored.apiKey,
|
|
2193
|
+
model: typeof partial.model === "string" && partial.model.trim() ? partial.model.trim() : baseStored.model,
|
|
2194
|
+
models: Array.isArray(partial.models) ? partial.models.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean) : baseStored.models,
|
|
2195
|
+
systemPrompt: typeof partial.systemPrompt === "string" ? partial.systemPrompt : baseStored.systemPrompt
|
|
2196
|
+
};
|
|
2197
|
+
}
|
|
2198
|
+
function normalizeStoredSystemPrompt(storedPrompt, base) {
|
|
2199
|
+
const trimmed = storedPrompt.trim();
|
|
2200
|
+
if (!trimmed)
|
|
2201
|
+
return "";
|
|
2202
|
+
const basePrompt = base.systemPrompt?.trim() ?? "";
|
|
2203
|
+
return trimmed === basePrompt ? "" : trimmed;
|
|
2204
|
+
}
|
|
2205
|
+
function createDefaultStoredSettings(base) {
|
|
2206
|
+
return {
|
|
2207
|
+
baseUrl: base.baseUrl?.trim() || DEFAULT_LLM_BASE_URL,
|
|
2208
|
+
apiKey: base.apiKey?.trim() || null,
|
|
2209
|
+
model: base.model?.trim() || DEFAULT_LLM_MODEL,
|
|
2210
|
+
models: base.models?.length ? [...base.models] : [],
|
|
2211
|
+
systemPrompt: ""
|
|
2212
|
+
};
|
|
2213
|
+
}
|
|
2214
|
+
function storedSettingsHaveOverrides(stored, base) {
|
|
2215
|
+
const normalized = {
|
|
2216
|
+
...stored,
|
|
2217
|
+
systemPrompt: normalizeStoredSystemPrompt(stored.systemPrompt, base)
|
|
2218
|
+
};
|
|
2219
|
+
return JSON.stringify(normalized) !== JSON.stringify(createDefaultStoredSettings(base));
|
|
2220
|
+
}
|
|
2221
|
+
function mergeLlmSettings(base, stored) {
|
|
2222
|
+
if (!stored)
|
|
2223
|
+
return base;
|
|
2224
|
+
const merged = storedToAssistant(stored);
|
|
2225
|
+
return {
|
|
2226
|
+
...merged,
|
|
2227
|
+
systemPrompt: merged.systemPrompt?.trim() || base.systemPrompt,
|
|
2228
|
+
models: merged.models?.length ? merged.models : base.models
|
|
2229
|
+
};
|
|
2230
|
+
}
|
|
2231
|
+
function isLlmSettingsFormDirty(current, saved) {
|
|
2232
|
+
return current.baseUrl !== saved.baseUrl || current.apiKey !== saved.apiKey || current.model !== saved.model || current.modelsText !== saved.modelsText || current.systemPrompt !== saved.systemPrompt;
|
|
2233
|
+
}
|
|
2234
|
+
function resolveSelectedModel(storedModel, defaultModel, availableModels) {
|
|
2235
|
+
const preferred = storedModel.trim();
|
|
2236
|
+
if (preferred)
|
|
2237
|
+
return preferred;
|
|
2238
|
+
if (availableModels.includes(defaultModel))
|
|
2239
|
+
return defaultModel;
|
|
2240
|
+
return availableModels[0] ?? defaultModel;
|
|
2241
|
+
}
|
|
2242
|
+
function peekStoredModel(storageKey) {
|
|
2243
|
+
try {
|
|
2244
|
+
const raw = localStorage.getItem(storageKey);
|
|
2245
|
+
if (!raw)
|
|
2246
|
+
return null;
|
|
2247
|
+
const parsed = JSON.parse(raw);
|
|
2248
|
+
const model = typeof parsed.model === "string" ? parsed.model.trim() : "";
|
|
2249
|
+
return model || null;
|
|
2250
|
+
} catch {
|
|
2251
|
+
return null;
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
function persistStoredModelSelection(storageKey, model) {
|
|
2255
|
+
const trimmed = model.trim();
|
|
2256
|
+
if (!trimmed)
|
|
2257
|
+
return;
|
|
2258
|
+
try {
|
|
2259
|
+
const raw = localStorage.getItem(storageKey);
|
|
2260
|
+
if (!raw)
|
|
2261
|
+
return;
|
|
2262
|
+
const parsed = JSON.parse(raw);
|
|
2263
|
+
if (!parsed || typeof parsed !== "object")
|
|
2264
|
+
return;
|
|
2265
|
+
localStorage.setItem(storageKey, JSON.stringify({ ...parsed, model: trimmed }));
|
|
2266
|
+
} catch {}
|
|
2267
|
+
}
|
|
2268
|
+
var LEGACY_MODEL_STORAGE_KEYS = [
|
|
2269
|
+
"assistant-llm-model",
|
|
2270
|
+
"4d-llm-model"
|
|
2271
|
+
];
|
|
2272
|
+
function migrateLegacyModelStorage(llmSettingsKey, legacyModelKey, base) {
|
|
2273
|
+
const legacyKeys = [
|
|
2274
|
+
...legacyModelKey ? [legacyModelKey] : [],
|
|
2275
|
+
...LEGACY_MODEL_STORAGE_KEYS
|
|
2276
|
+
];
|
|
2277
|
+
for (const key of legacyKeys) {
|
|
2278
|
+
const legacyModel = localStorage.getItem(key)?.trim();
|
|
2279
|
+
if (!legacyModel)
|
|
2280
|
+
continue;
|
|
2281
|
+
const storage = createLlmSettingsStorage(llmSettingsKey);
|
|
2282
|
+
const stored = storage.load(base) ?? createDefaultStoredSettings(base);
|
|
2283
|
+
storage.save({ ...stored, model: legacyModel });
|
|
2284
|
+
localStorage.removeItem(key);
|
|
2285
|
+
break;
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
function parseModelsText(text) {
|
|
2289
|
+
return [
|
|
2290
|
+
...new Set(text.split(/[\n,]/).map((entry) => entry.trim()).filter(Boolean))
|
|
2291
|
+
];
|
|
2292
|
+
}
|
|
2293
|
+
function formatModelsText(models) {
|
|
2294
|
+
return models?.join(", ") ?? "";
|
|
2295
|
+
}
|
|
2296
|
+
function createLlmSettingsStorage(storageKey) {
|
|
2297
|
+
return {
|
|
2298
|
+
load(base) {
|
|
2299
|
+
try {
|
|
2300
|
+
const raw = localStorage.getItem(storageKey);
|
|
2301
|
+
if (!raw)
|
|
2302
|
+
return null;
|
|
2303
|
+
return normalizeStoredSettings(JSON.parse(raw), base);
|
|
2304
|
+
} catch {
|
|
2305
|
+
return null;
|
|
2306
|
+
}
|
|
2307
|
+
},
|
|
2308
|
+
save(settings) {
|
|
2309
|
+
localStorage.setItem(storageKey, JSON.stringify(settings));
|
|
2310
|
+
},
|
|
2311
|
+
clear() {
|
|
2312
|
+
localStorage.removeItem(storageKey);
|
|
2313
|
+
},
|
|
2314
|
+
hasStored() {
|
|
2315
|
+
return localStorage.getItem(storageKey) !== null;
|
|
2316
|
+
}
|
|
2317
|
+
};
|
|
2318
|
+
}
|
|
2319
|
+
function toStoredSettings(values, existingApiKey) {
|
|
2320
|
+
const apiKeyInput = values.apiKey.trim();
|
|
2321
|
+
return {
|
|
2322
|
+
baseUrl: values.baseUrl.trim() || DEFAULT_LLM_BASE_URL,
|
|
2323
|
+
apiKey: apiKeyInput.length > 0 ? apiKeyInput : existingApiKey,
|
|
2324
|
+
model: values.model.trim() || DEFAULT_LLM_MODEL,
|
|
2325
|
+
models: parseModelsText(values.modelsText),
|
|
2326
|
+
systemPrompt: values.systemPrompt
|
|
2327
|
+
};
|
|
2328
|
+
}
|
|
2329
|
+
function createLlmSettingsFormState(settings, hasStoredApiKey, defaultSystemPrompt = DEFAULT_ASSISTANT_SYSTEM_PROMPT) {
|
|
2330
|
+
return {
|
|
2331
|
+
baseUrl: settings.baseUrl,
|
|
2332
|
+
apiKey: "",
|
|
2333
|
+
model: settings.model,
|
|
2334
|
+
modelsText: formatModelsText(settings.models),
|
|
2335
|
+
systemPrompt: settings.systemPrompt ?? "",
|
|
2336
|
+
hasStoredApiKey,
|
|
2337
|
+
defaultSystemPrompt
|
|
2338
|
+
};
|
|
2339
|
+
}
|
|
2340
|
+
function createLlmSettingsFormStateFromStored(stored, defaultSystemPrompt = DEFAULT_ASSISTANT_SYSTEM_PROMPT) {
|
|
2341
|
+
return {
|
|
2342
|
+
baseUrl: stored.baseUrl,
|
|
2343
|
+
apiKey: "",
|
|
2344
|
+
model: stored.model,
|
|
2345
|
+
modelsText: formatModelsText(stored.models),
|
|
2346
|
+
systemPrompt: stored.systemPrompt,
|
|
2347
|
+
hasStoredApiKey: Boolean(stored.apiKey),
|
|
2348
|
+
defaultSystemPrompt
|
|
2349
|
+
};
|
|
2350
|
+
}
|
|
2351
|
+
|
|
2352
|
+
// src/core/create-assistant-store.ts
|
|
2353
|
+
function patchWelcomeMessage(messages, welcomeMessage, model, llmEnabled) {
|
|
2354
|
+
const welcome = welcomeMessage({ llmEnabled, model });
|
|
2355
|
+
return messages.map((message) => message.id === "welcome" ? { ...message, content: welcome.content } : message);
|
|
2356
|
+
}
|
|
2357
|
+
function patchTurnMessage(messages, turnId, patch) {
|
|
2358
|
+
return messages.map((message) => message.id === turnId ? patch(message) : message);
|
|
2359
|
+
}
|
|
2360
|
+
function createTurnMessage(turnId) {
|
|
2361
|
+
return {
|
|
2362
|
+
id: turnId,
|
|
2363
|
+
role: "assistant",
|
|
2364
|
+
content: "",
|
|
2365
|
+
activity: [],
|
|
2366
|
+
streaming: true,
|
|
2367
|
+
timestamp: Date.now()
|
|
2368
|
+
};
|
|
2369
|
+
}
|
|
2370
|
+
function appendActivityStep(messages, turnId, step) {
|
|
2371
|
+
return patchTurnMessage(messages, turnId, (message) => ({
|
|
2372
|
+
...message,
|
|
2373
|
+
activity: [...message.activity ?? [], step]
|
|
2374
|
+
}));
|
|
2375
|
+
}
|
|
2376
|
+
function finishActivityStep(messages, turnId, stepId, update) {
|
|
2377
|
+
return patchTurnMessage(messages, turnId, (message) => ({
|
|
2378
|
+
...message,
|
|
2379
|
+
activity: (message.activity ?? []).map((step) => step.id === stepId ? { ...step, ...update } : step)
|
|
2380
|
+
}));
|
|
2381
|
+
}
|
|
2382
|
+
function finalizeStoppedMessages(messages) {
|
|
2383
|
+
return messages.map((message) => {
|
|
2384
|
+
if (!message.streaming)
|
|
2385
|
+
return message;
|
|
2386
|
+
const activity = (message.activity ?? []).map((step) => step.status === "active" ? { ...step, status: "error", error: "Stopped" } : step);
|
|
2387
|
+
return {
|
|
2388
|
+
...message,
|
|
2389
|
+
streaming: false,
|
|
2390
|
+
activity,
|
|
2391
|
+
content: message.content.trim() || "_(stopped)_"
|
|
2392
|
+
};
|
|
2393
|
+
});
|
|
2394
|
+
}
|
|
2395
|
+
function finalizeErroredMessages(messages, errorMessage) {
|
|
2396
|
+
const hasStreaming = messages.some((message) => message.streaming);
|
|
2397
|
+
if (!hasStreaming) {
|
|
2398
|
+
return [
|
|
2399
|
+
...messages,
|
|
2400
|
+
{
|
|
2401
|
+
id: crypto.randomUUID(),
|
|
2402
|
+
role: "assistant",
|
|
2403
|
+
content: errorMessage,
|
|
2404
|
+
isError: true,
|
|
2405
|
+
timestamp: Date.now()
|
|
2406
|
+
}
|
|
2407
|
+
];
|
|
2408
|
+
}
|
|
2409
|
+
return messages.map((message) => {
|
|
2410
|
+
if (!message.streaming)
|
|
2411
|
+
return message;
|
|
2412
|
+
const activity = (message.activity ?? []).map((step) => step.status === "active" ? { ...step, status: "error", error: errorMessage } : step);
|
|
2413
|
+
return {
|
|
2414
|
+
...message,
|
|
2415
|
+
streaming: false,
|
|
2416
|
+
isError: true,
|
|
2417
|
+
activity,
|
|
2418
|
+
content: errorMessage
|
|
2419
|
+
};
|
|
2420
|
+
});
|
|
2421
|
+
}
|
|
2422
|
+
function clearReplySuggestions(messages) {
|
|
2423
|
+
return messages.map((message) => message.replySuggestions ? { ...message, replySuggestions: undefined } : message);
|
|
2424
|
+
}
|
|
2425
|
+
function createAssistantStore(deps) {
|
|
2426
|
+
const historyKey = deps.storageKeys?.history ?? "assistant-chat-history";
|
|
2427
|
+
const llmSettingsKey = deps.storageKeys?.llmSettings ?? "assistant-llm-settings";
|
|
2428
|
+
const llmSettingsStorage = createLlmSettingsStorage(llmSettingsKey);
|
|
2429
|
+
async function resolveBaseLlmSettings() {
|
|
2430
|
+
if (!deps.llm)
|
|
2431
|
+
return buildDefaultLlmSettings();
|
|
2432
|
+
return typeof deps.llm === "function" ? await deps.llm() : deps.llm;
|
|
2433
|
+
}
|
|
2434
|
+
async function ensureLlmSettingsStored() {
|
|
2435
|
+
const base = await resolveBaseLlmSettings();
|
|
2436
|
+
migrateLegacyModelStorage(llmSettingsKey, deps.storageKeys?.model, base);
|
|
2437
|
+
if (llmSettingsStorage.hasStored())
|
|
2438
|
+
return;
|
|
2439
|
+
llmSettingsStorage.save(createDefaultStoredSettings(base));
|
|
2440
|
+
}
|
|
2441
|
+
async function resolveMergedLlmSettings() {
|
|
2442
|
+
const base = await resolveBaseLlmSettings();
|
|
2443
|
+
const stored = llmSettingsStorage.load(base);
|
|
2444
|
+
return mergeLlmSettings(base, stored);
|
|
2445
|
+
}
|
|
2446
|
+
configureAssistantLlm(resolveMergedLlmSettings);
|
|
2447
|
+
const history = createChatHistoryHelpers({
|
|
2448
|
+
storageKey: historyKey,
|
|
2449
|
+
welcomeMessage: deps.welcomeMessage
|
|
2450
|
+
});
|
|
2451
|
+
const initialSelectedModel = peekStoredModel(llmSettingsKey);
|
|
2452
|
+
let chatAbortController = null;
|
|
2453
|
+
const messages = history.loadInitial({
|
|
2454
|
+
llmEnabled: false,
|
|
2455
|
+
model: initialSelectedModel
|
|
2456
|
+
});
|
|
2457
|
+
const store = create((set, get) => {
|
|
2458
|
+
async function runLlmChatTurn(message) {
|
|
2459
|
+
const tools = await deps.listTools();
|
|
2460
|
+
const storedMessages = get().messages.filter((m) => m.id !== "welcome");
|
|
2461
|
+
const priorMessages = storedMessages.at(-1)?.role === "user" ? storedMessages.slice(0, -1) : storedMessages;
|
|
2462
|
+
const llmHistory = buildLlmHistory(priorMessages);
|
|
2463
|
+
const turnId = crypto.randomUUID();
|
|
2464
|
+
set((state) => ({
|
|
2465
|
+
messages: [...state.messages, createTurnMessage(turnId)]
|
|
2466
|
+
}));
|
|
2467
|
+
await runLlmAgent({
|
|
2468
|
+
userMessage: message,
|
|
2469
|
+
history: llmHistory,
|
|
2470
|
+
tools,
|
|
2471
|
+
model: get().selectedModel ?? undefined,
|
|
2472
|
+
signal: chatAbortController?.signal,
|
|
2473
|
+
stream: {
|
|
2474
|
+
turnId,
|
|
2475
|
+
onUpdate: (content) => {
|
|
2476
|
+
set((state) => ({
|
|
2477
|
+
messages: patchTurnMessage(state.messages, turnId, (msg) => ({
|
|
2478
|
+
...msg,
|
|
2479
|
+
content
|
|
2480
|
+
}))
|
|
2481
|
+
}));
|
|
2482
|
+
}
|
|
2483
|
+
},
|
|
2484
|
+
toolHandlers: {
|
|
2485
|
+
onStart: ({ id, name, args, callId }) => {
|
|
2486
|
+
set((state) => ({
|
|
2487
|
+
messages: appendActivityStep(state.messages, turnId, {
|
|
2488
|
+
id,
|
|
2489
|
+
kind: "tool",
|
|
2490
|
+
name,
|
|
2491
|
+
args,
|
|
2492
|
+
callId,
|
|
2493
|
+
status: "active"
|
|
2494
|
+
})
|
|
2495
|
+
}));
|
|
2496
|
+
},
|
|
2497
|
+
onFinish: (stepId, update) => {
|
|
2498
|
+
set((state) => ({
|
|
2499
|
+
messages: finishActivityStep(state.messages, turnId, stepId, {
|
|
2500
|
+
status: update.status,
|
|
2501
|
+
result: summarizeActivityResult(update.result),
|
|
2502
|
+
error: update.error
|
|
2503
|
+
})
|
|
2504
|
+
}));
|
|
2505
|
+
}
|
|
2506
|
+
},
|
|
2507
|
+
onPostResponseTool: (suggestions) => {
|
|
2508
|
+
set((state) => ({
|
|
2509
|
+
messages: patchTurnMessage(state.messages, turnId, (msg) => ({
|
|
2510
|
+
...msg,
|
|
2511
|
+
replySuggestions: suggestions
|
|
2512
|
+
}))
|
|
2513
|
+
}));
|
|
2514
|
+
},
|
|
2515
|
+
invokeTool: async (name, args) => {
|
|
2516
|
+
const result = await deps.invokeTool(name, args);
|
|
2517
|
+
deps.onToolInvoked?.(result);
|
|
2518
|
+
return result;
|
|
2519
|
+
}
|
|
2520
|
+
});
|
|
2521
|
+
set((state) => ({
|
|
2522
|
+
messages: state.messages.map((msg) => msg.id === turnId ? {
|
|
2523
|
+
...msg,
|
|
2524
|
+
streaming: false,
|
|
2525
|
+
content: msg.content.trim() || (msg.activity?.length ? "" : "I couldn't produce a response.")
|
|
2526
|
+
} : msg),
|
|
2527
|
+
chatLoading: false
|
|
2528
|
+
}));
|
|
2529
|
+
}
|
|
2530
|
+
return {
|
|
2531
|
+
messages,
|
|
2532
|
+
chatLoading: false,
|
|
2533
|
+
llmEnabled: false,
|
|
2534
|
+
llmModel: null,
|
|
2535
|
+
llmModels: [],
|
|
2536
|
+
llmModelsLoading: false,
|
|
2537
|
+
selectedModel: initialSelectedModel,
|
|
2538
|
+
loadLlmStatus: async () => {
|
|
2539
|
+
set({ llmModelsLoading: true });
|
|
2540
|
+
try {
|
|
2541
|
+
await ensureLlmSettingsStored();
|
|
2542
|
+
const base = await resolveBaseLlmSettings();
|
|
2543
|
+
const stored = llmSettingsStorage.load(base) ?? createDefaultStoredSettings(base);
|
|
2544
|
+
const status = await fetchLlmStatus();
|
|
2545
|
+
const defaultModel = status.model ?? stored.model ?? DEFAULT_LLM_MODEL;
|
|
2546
|
+
const baseModels = status.models.length ? status.models : [defaultModel];
|
|
2547
|
+
const selectedModel = resolveSelectedModel(stored.model, defaultModel, baseModels);
|
|
2548
|
+
const llmModels = selectedModel && !baseModels.includes(selectedModel) ? [selectedModel, ...baseModels] : baseModels;
|
|
2549
|
+
set((state) => ({
|
|
2550
|
+
llmEnabled: status.enabled,
|
|
2551
|
+
llmModel: defaultModel,
|
|
2552
|
+
llmModels,
|
|
2553
|
+
selectedModel,
|
|
2554
|
+
messages: patchWelcomeMessage(state.messages, deps.welcomeMessage, selectedModel, status.enabled)
|
|
2555
|
+
}));
|
|
2556
|
+
} finally {
|
|
2557
|
+
set({ llmModelsLoading: false });
|
|
2558
|
+
}
|
|
2559
|
+
},
|
|
2560
|
+
getLlmSettingsForm: async () => {
|
|
2561
|
+
await ensureLlmSettingsStored();
|
|
2562
|
+
const base = await resolveBaseLlmSettings();
|
|
2563
|
+
const defaultSystemPrompt = base.systemPrompt?.trim() || DEFAULT_ASSISTANT_SYSTEM_PROMPT;
|
|
2564
|
+
const stored = llmSettingsStorage.load(base);
|
|
2565
|
+
if (stored) {
|
|
2566
|
+
return createLlmSettingsFormStateFromStored({
|
|
2567
|
+
...stored,
|
|
2568
|
+
systemPrompt: normalizeStoredSystemPrompt(stored.systemPrompt, base)
|
|
2569
|
+
}, defaultSystemPrompt);
|
|
2570
|
+
}
|
|
2571
|
+
return createLlmSettingsFormState(base, Boolean(base.apiKey), defaultSystemPrompt);
|
|
2572
|
+
},
|
|
2573
|
+
saveLlmSettings: async (values) => {
|
|
2574
|
+
const base = await resolveBaseLlmSettings();
|
|
2575
|
+
const defaultSystemPrompt = base.systemPrompt?.trim() || DEFAULT_ASSISTANT_SYSTEM_PROMPT;
|
|
2576
|
+
const current = await resolveAssistantLlmSettings();
|
|
2577
|
+
const normalizedValues = {
|
|
2578
|
+
...values,
|
|
2579
|
+
systemPrompt: values.systemPrompt.trim() === defaultSystemPrompt ? "" : values.systemPrompt
|
|
2580
|
+
};
|
|
2581
|
+
llmSettingsStorage.save(toStoredSettings(normalizedValues, current.apiKey));
|
|
2582
|
+
await get().loadLlmStatus();
|
|
2583
|
+
},
|
|
2584
|
+
clearLlmSettings: async () => {
|
|
2585
|
+
llmSettingsStorage.clear();
|
|
2586
|
+
const base = await resolveBaseLlmSettings();
|
|
2587
|
+
llmSettingsStorage.save(createDefaultStoredSettings(base));
|
|
2588
|
+
await get().loadLlmStatus();
|
|
2589
|
+
},
|
|
2590
|
+
testLlmSettings: async (values) => {
|
|
2591
|
+
const current = await resolveAssistantLlmSettings();
|
|
2592
|
+
const stored = toStoredSettings(values, current.apiKey);
|
|
2593
|
+
if (!stored.apiKey && !isLocalLlmBaseUrl(stored.baseUrl)) {
|
|
2594
|
+
return {
|
|
2595
|
+
ok: false,
|
|
2596
|
+
error: "API key is required for remote LLM providers."
|
|
2597
|
+
};
|
|
2598
|
+
}
|
|
2599
|
+
return testLlmConnection({
|
|
2600
|
+
baseUrl: stored.baseUrl,
|
|
2601
|
+
apiKey: stored.apiKey,
|
|
2602
|
+
model: stored.model
|
|
2603
|
+
});
|
|
2604
|
+
},
|
|
2605
|
+
llmSettingsHasOverrides: async () => {
|
|
2606
|
+
await ensureLlmSettingsStored();
|
|
2607
|
+
const base = await resolveBaseLlmSettings();
|
|
2608
|
+
const stored = llmSettingsStorage.load(base);
|
|
2609
|
+
if (!stored)
|
|
2610
|
+
return false;
|
|
2611
|
+
return storedSettingsHaveOverrides(stored, base);
|
|
2612
|
+
},
|
|
2613
|
+
setSelectedModel: (model) => {
|
|
2614
|
+
const trimmed = model.trim();
|
|
2615
|
+
if (!trimmed)
|
|
2616
|
+
return;
|
|
2617
|
+
const { llmEnabled, llmModels } = get();
|
|
2618
|
+
const models = llmModels.includes(trimmed) ? llmModels : [trimmed, ...llmModels];
|
|
2619
|
+
persistStoredModelSelection(llmSettingsKey, trimmed);
|
|
2620
|
+
set((state) => ({
|
|
2621
|
+
selectedModel: trimmed,
|
|
2622
|
+
llmModels: models,
|
|
2623
|
+
messages: patchWelcomeMessage(state.messages, deps.welcomeMessage, trimmed, llmEnabled)
|
|
2624
|
+
}));
|
|
2625
|
+
},
|
|
2626
|
+
clearChatHistory: () => {
|
|
2627
|
+
if (get().chatLoading)
|
|
2628
|
+
return;
|
|
2629
|
+
const { llmEnabled, selectedModel } = get();
|
|
2630
|
+
history.clear();
|
|
2631
|
+
set({
|
|
2632
|
+
messages: [deps.welcomeMessage({ llmEnabled, model: selectedModel })]
|
|
2633
|
+
});
|
|
2634
|
+
},
|
|
2635
|
+
stopChat: () => {
|
|
2636
|
+
chatAbortController?.abort();
|
|
2637
|
+
rejectAllInteractiveToolWaiters(new DOMException("Aborted", "AbortError"));
|
|
2638
|
+
set((state) => ({
|
|
2639
|
+
messages: finalizeStoppedMessages(state.messages),
|
|
2640
|
+
chatLoading: false
|
|
2641
|
+
}));
|
|
2642
|
+
},
|
|
2643
|
+
submitInteractiveToolResult: (callId, result) => {
|
|
2644
|
+
resolveInteractiveToolResult(callId, result);
|
|
2645
|
+
},
|
|
2646
|
+
cancelInteractiveToolResult: (callId) => {
|
|
2647
|
+
resolveInteractiveToolResult(callId, {
|
|
2648
|
+
cancelled: true,
|
|
2649
|
+
confirmed: false,
|
|
2650
|
+
selected: []
|
|
2651
|
+
});
|
|
2652
|
+
},
|
|
2653
|
+
sendChat: async (message) => {
|
|
2654
|
+
const userMsg = {
|
|
2655
|
+
id: crypto.randomUUID(),
|
|
2656
|
+
role: "user",
|
|
2657
|
+
content: message,
|
|
2658
|
+
timestamp: Date.now()
|
|
2659
|
+
};
|
|
2660
|
+
chatAbortController?.abort();
|
|
2661
|
+
chatAbortController = new AbortController;
|
|
2662
|
+
set((state) => ({
|
|
2663
|
+
messages: [...clearReplySuggestions(state.messages), userMsg],
|
|
2664
|
+
chatLoading: true
|
|
2665
|
+
}));
|
|
2666
|
+
try {
|
|
2667
|
+
if (!get().llmEnabled) {
|
|
2668
|
+
set((state) => ({
|
|
2669
|
+
messages: [
|
|
2670
|
+
...state.messages,
|
|
2671
|
+
{
|
|
2672
|
+
id: crypto.randomUUID(),
|
|
2673
|
+
role: "assistant",
|
|
2674
|
+
content: LLM_UNAVAILABLE_MESSAGE,
|
|
2675
|
+
llmSetupRequired: true,
|
|
2676
|
+
timestamp: Date.now()
|
|
2677
|
+
}
|
|
2678
|
+
],
|
|
2679
|
+
chatLoading: false
|
|
2680
|
+
}));
|
|
2681
|
+
return;
|
|
2682
|
+
}
|
|
2683
|
+
await runLlmChatTurn(message);
|
|
2684
|
+
} catch (error) {
|
|
2685
|
+
if (error instanceof ChatAbortedError || error instanceof DOMException && error.name === "AbortError" || chatAbortController?.signal.aborted) {
|
|
2686
|
+
set((state) => ({
|
|
2687
|
+
messages: finalizeStoppedMessages(state.messages),
|
|
2688
|
+
chatLoading: false
|
|
2689
|
+
}));
|
|
2690
|
+
return;
|
|
2691
|
+
}
|
|
2692
|
+
set((state) => ({
|
|
2693
|
+
messages: finalizeErroredMessages(state.messages, `Chat failed: ${error instanceof Error ? error.message : String(error)}`),
|
|
2694
|
+
chatLoading: false
|
|
2695
|
+
}));
|
|
2696
|
+
} finally {
|
|
2697
|
+
chatAbortController = null;
|
|
2698
|
+
}
|
|
2699
|
+
},
|
|
2700
|
+
retryLastChat: async () => {
|
|
2701
|
+
if (get().chatLoading)
|
|
2702
|
+
return;
|
|
2703
|
+
const { messages: messages2 } = get();
|
|
2704
|
+
let errorIndex = -1;
|
|
2705
|
+
for (let i = messages2.length - 1;i >= 0; i--) {
|
|
2706
|
+
const message = messages2[i];
|
|
2707
|
+
if (message?.role === "assistant" && message.isError) {
|
|
2708
|
+
errorIndex = i;
|
|
2709
|
+
break;
|
|
2710
|
+
}
|
|
2711
|
+
}
|
|
2712
|
+
if (errorIndex < 0)
|
|
2713
|
+
return;
|
|
2714
|
+
let userContent = null;
|
|
2715
|
+
for (let i = errorIndex - 1;i >= 0; i--) {
|
|
2716
|
+
const message = messages2[i];
|
|
2717
|
+
if (message?.role === "user") {
|
|
2718
|
+
userContent = message.content;
|
|
2719
|
+
break;
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
2722
|
+
if (!userContent)
|
|
2723
|
+
return;
|
|
2724
|
+
chatAbortController?.abort();
|
|
2725
|
+
chatAbortController = new AbortController;
|
|
2726
|
+
set((state) => ({
|
|
2727
|
+
messages: state.messages.filter((_, index) => index !== errorIndex),
|
|
2728
|
+
chatLoading: true
|
|
2729
|
+
}));
|
|
2730
|
+
try {
|
|
2731
|
+
if (!get().llmEnabled) {
|
|
2732
|
+
set((state) => ({
|
|
2733
|
+
messages: [
|
|
2734
|
+
...state.messages,
|
|
2735
|
+
{
|
|
2736
|
+
id: crypto.randomUUID(),
|
|
2737
|
+
role: "assistant",
|
|
2738
|
+
content: LLM_UNAVAILABLE_MESSAGE,
|
|
2739
|
+
llmSetupRequired: true,
|
|
2740
|
+
timestamp: Date.now()
|
|
2741
|
+
}
|
|
2742
|
+
],
|
|
2743
|
+
chatLoading: false
|
|
2744
|
+
}));
|
|
2745
|
+
return;
|
|
2746
|
+
}
|
|
2747
|
+
await runLlmChatTurn(userContent);
|
|
2748
|
+
} catch (error) {
|
|
2749
|
+
if (error instanceof ChatAbortedError || error instanceof DOMException && error.name === "AbortError" || chatAbortController?.signal.aborted) {
|
|
2750
|
+
set((state) => ({
|
|
2751
|
+
messages: finalizeStoppedMessages(state.messages),
|
|
2752
|
+
chatLoading: false
|
|
2753
|
+
}));
|
|
2754
|
+
return;
|
|
2755
|
+
}
|
|
2756
|
+
set((state) => ({
|
|
2757
|
+
messages: finalizeErroredMessages(state.messages, `Chat failed: ${error instanceof Error ? error.message : String(error)}`),
|
|
2758
|
+
chatLoading: false
|
|
2759
|
+
}));
|
|
2760
|
+
} finally {
|
|
2761
|
+
chatAbortController = null;
|
|
2762
|
+
}
|
|
2763
|
+
}
|
|
2764
|
+
};
|
|
2765
|
+
});
|
|
2766
|
+
store.subscribe((state, previousState) => {
|
|
2767
|
+
if (state.messages === previousState.messages)
|
|
2768
|
+
return;
|
|
2769
|
+
history.persist(state.messages);
|
|
2770
|
+
});
|
|
2771
|
+
return store;
|
|
2772
|
+
}
|
|
2773
|
+
// src/core/fetch-suggested-prompts.ts
|
|
2774
|
+
function parseSuggestedPromptsResponse(data) {
|
|
2775
|
+
if (!data || typeof data !== "object")
|
|
2776
|
+
return [];
|
|
2777
|
+
const root = data;
|
|
2778
|
+
const raw = Array.isArray(root.prompts) ? root.prompts : Array.isArray(root.suggestions) ? root.suggestions : [];
|
|
2779
|
+
const prompts = [];
|
|
2780
|
+
for (const [index, entry] of raw.entries()) {
|
|
2781
|
+
if (!entry || typeof entry !== "object")
|
|
2782
|
+
continue;
|
|
2783
|
+
const item = entry;
|
|
2784
|
+
const label = typeof item.label === "string" ? item.label.trim() : "";
|
|
2785
|
+
const prompt = typeof item.prompt === "string" ? item.prompt.trim() : typeof item.message === "string" ? item.message.trim() : "";
|
|
2786
|
+
if (!label || !prompt)
|
|
2787
|
+
continue;
|
|
2788
|
+
prompts.push({
|
|
2789
|
+
id: typeof item.id === "string" && item.id.trim() ? item.id.trim() : `prompt-${index + 1}`,
|
|
2790
|
+
label,
|
|
2791
|
+
description: typeof item.description === "string" ? item.description.trim() : typeof item.hint === "string" ? item.hint.trim() : undefined,
|
|
2792
|
+
prompt,
|
|
2793
|
+
icon: typeof item.icon === "string" ? item.icon.trim() : undefined
|
|
2794
|
+
});
|
|
2795
|
+
}
|
|
2796
|
+
return prompts.slice(0, 6);
|
|
2797
|
+
}
|
|
2798
|
+
// src/core/markdown-utils.ts
|
|
2799
|
+
var import_react2 = __toESM(require_react(), 1);
|
|
2800
|
+
function childrenToText(children) {
|
|
2801
|
+
if (typeof children === "string")
|
|
2802
|
+
return children;
|
|
2803
|
+
if (typeof children === "number")
|
|
2804
|
+
return String(children);
|
|
2805
|
+
if (Array.isArray(children))
|
|
2806
|
+
return children.map(childrenToText).join("");
|
|
2807
|
+
if (import_react2.isValidElement(children)) {
|
|
2808
|
+
return childrenToText(children.props.children);
|
|
2809
|
+
}
|
|
2810
|
+
return "";
|
|
2811
|
+
}
|
|
2812
|
+
export {
|
|
2813
|
+
toStoredSettings,
|
|
2814
|
+
testLlmConnection,
|
|
2815
|
+
summarizeActivityResult,
|
|
2816
|
+
storedToAssistant,
|
|
2817
|
+
storedSettingsHaveOverrides,
|
|
2818
|
+
shouldShowChatCommandMenu,
|
|
2819
|
+
sanitizeLlmMessages,
|
|
2820
|
+
runLlmAgent,
|
|
2821
|
+
runAssistantChatCommand,
|
|
2822
|
+
resolveSelectedModel,
|
|
2823
|
+
resolveInteractiveToolResult,
|
|
2824
|
+
resolveAssistantLlmSettings,
|
|
2825
|
+
resetAssistantLlm,
|
|
2826
|
+
requestLlmCompletion,
|
|
2827
|
+
rejectAllInteractiveToolWaiters,
|
|
2828
|
+
persistStoredModelSelection,
|
|
2829
|
+
peekStoredModel,
|
|
2830
|
+
parseSuggestedPromptsResponse,
|
|
2831
|
+
parseModelsText,
|
|
2832
|
+
parseChatCommand,
|
|
2833
|
+
normalizeStoredSystemPrompt,
|
|
2834
|
+
normalizeStoredSettings,
|
|
2835
|
+
migrateLegacyModelStorage,
|
|
2836
|
+
mergeLlmSettings,
|
|
2837
|
+
listChatCommands,
|
|
2838
|
+
isLocalLlmBaseUrl,
|
|
2839
|
+
isLlmUnavailableMessage,
|
|
2840
|
+
isLlmSettingsFormDirty,
|
|
2841
|
+
isLlmConfigured,
|
|
2842
|
+
isChatCommandInput,
|
|
2843
|
+
getFallbackModels,
|
|
2844
|
+
getChatCommandSuggestions,
|
|
2845
|
+
formatModelsText,
|
|
2846
|
+
formatJsonIfLarge,
|
|
2847
|
+
filterChatCommands,
|
|
2848
|
+
fetchProviderModels,
|
|
2849
|
+
fetchLlmStatus,
|
|
2850
|
+
createLlmSettingsStorage,
|
|
2851
|
+
createLlmSettingsFormStateFromStored,
|
|
2852
|
+
createLlmSettingsFormState,
|
|
2853
|
+
createDefaultStoredSettings,
|
|
2854
|
+
createChatHistoryHelpers,
|
|
2855
|
+
createAssistantStore,
|
|
2856
|
+
configureAssistantLlm,
|
|
2857
|
+
clearProviderModelCache,
|
|
2858
|
+
childrenToText,
|
|
2859
|
+
chatActivityStepLabel,
|
|
2860
|
+
buildModelsUrl,
|
|
2861
|
+
buildLlmRequestHeaders,
|
|
2862
|
+
buildLlmHistory,
|
|
2863
|
+
buildDefaultLlmSettings,
|
|
2864
|
+
buildCompletionsUrl,
|
|
2865
|
+
assistantToStored,
|
|
2866
|
+
SUGGEST_REPLIES_TOOL,
|
|
2867
|
+
LlmUpstreamError,
|
|
2868
|
+
LlmNotConfiguredError,
|
|
2869
|
+
LLM_UNAVAILABLE_MESSAGE,
|
|
2870
|
+
DEFAULT_LLM_SETTINGS_STORAGE_KEY,
|
|
2871
|
+
DEFAULT_LLM_MODEL,
|
|
2872
|
+
DEFAULT_LLM_BASE_URL,
|
|
2873
|
+
ChatAbortedError,
|
|
2874
|
+
CONFIRMATION_TOOL,
|
|
2875
|
+
CHOICES_TOOL
|
|
2876
|
+
};
|