@tensorpass/aiconnect-react 0.1.8 → 0.1.10
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/answerSteps.d.ts +1 -0
- package/dist/answerSteps.js +13 -0
- package/dist/answerSteps.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/modules/AiSearch.js +5 -4
- package/dist/modules/AiSearch.js.map +1 -1
- package/dist/modules/parts/AnswerText.js +2 -2
- package/dist/modules/parts/AnswerText.js.map +1 -1
- package/dist/modules/parts/ChatFrame.js +2 -1
- package/dist/modules/parts/ChatFrame.js.map +1 -1
- package/dist/modules/parts/Conversation.d.ts +4 -1
- package/dist/modules/parts/Conversation.js +13 -4
- package/dist/modules/parts/Conversation.js.map +1 -1
- package/dist/modules/parts/ModuleFoot.d.ts +4 -0
- package/dist/modules/parts/ModuleFoot.js +8 -0
- package/dist/modules/parts/ModuleFoot.js.map +1 -0
- package/dist/modules/parts/answerMarkdown.d.ts +2 -2
- package/dist/modules/parts/answerMarkdown.js +40 -8
- package/dist/modules/parts/answerMarkdown.js.map +1 -1
- package/dist/modules/types.d.ts +6 -2
- package/dist/modules/types.js +2 -2
- package/dist/modules/types.js.map +1 -1
- package/dist/styles.css +26 -0
- package/dist/useAiChat.js +16 -7
- package/dist/useAiChat.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function appendAnswer(answer: string, delta: string, newStep: boolean): string;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// The answer of a turn as the visitor reads it: the text the model writes before a tool call and the text
|
|
2
|
+
// it writes after the result are two paragraphs, where streaming them end to end ran a sentence into the
|
|
3
|
+
// next one ("how it works.You start").
|
|
4
|
+
const ENDS_IN_SPACE = /\s$/;
|
|
5
|
+
// Adds a streamed piece to the answer. The first piece of a step that follows a tool call opens a new
|
|
6
|
+
// paragraph, unless the answer is still empty or already ends in white space.
|
|
7
|
+
export function appendAnswer(answer, delta, newStep) {
|
|
8
|
+
if (!newStep || !answer || ENDS_IN_SPACE.test(answer)) {
|
|
9
|
+
return answer + delta;
|
|
10
|
+
}
|
|
11
|
+
return `${answer}\n\n${delta}`;
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=answerSteps.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"answerSteps.js","sourceRoot":"","sources":["../src/answerSteps.ts"],"names":[],"mappings":"AAAA,0GAA0G;AAC1G,yGAAyG;AACzG,uCAAuC;AAEvC,MAAM,aAAa,GAAG,KAAK,CAAC;AAE5B,sGAAsG;AACtG,8EAA8E;AAC9E,MAAM,UAAU,YAAY,CAAC,MAAc,EAAE,KAAa,EAAE,OAAgB;IAC1E,IAAI,CAAC,OAAO,IAAI,CAAC,MAAM,IAAI,aAAa,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QACtD,OAAO,MAAM,GAAG,KAAK,CAAC;IACxB,CAAC;IACD,OAAO,GAAG,MAAM,OAAO,KAAK,EAAE,CAAC;AACjC,CAAC","sourcesContent":["// The answer of a turn as the visitor reads it: the text the model writes before a tool call and the text\n// it writes after the result are two paragraphs, where streaming them end to end ran a sentence into the\n// next one (\"how it works.You start\").\n\nconst ENDS_IN_SPACE = /\\s$/;\n\n// Adds a streamed piece to the answer. The first piece of a step that follows a tool call opens a new\n// paragraph, unless the answer is still empty or already ends in white space.\nexport function appendAnswer(answer: string, delta: string, newStep: boolean): string {\n if (!newStep || !answer || ENDS_IN_SPACE.test(answer)) {\n return answer + delta;\n }\n return `${answer}\\n\\n${delta}`;\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -21,4 +21,5 @@ export { AiChatPopup } from './modules/AiChatPopup.tsx';
|
|
|
21
21
|
export type { AiChatPopupProps } from './modules/AiChatPopup.tsx';
|
|
22
22
|
export { AiSearch } from './modules/AiSearch.tsx';
|
|
23
23
|
export type { AiSearchProps } from './modules/AiSearch.tsx';
|
|
24
|
-
export type { AiModuleHandle, AiModuleProps, AiOverlayProps } from './modules/types.ts';
|
|
24
|
+
export type { AiModuleHandle, AiModuleProps, AiOverlayProps, ToolResultsContext } from './modules/types.ts';
|
|
25
|
+
export { BrandMark } from './BrandMark.tsx';
|
package/dist/index.js
CHANGED
|
@@ -9,4 +9,5 @@ export { AiChatPage } from "./modules/AiChatPage.js";
|
|
|
9
9
|
export { AiChatPanel } from "./modules/AiChatPanel.js";
|
|
10
10
|
export { AiChatPopup } from "./modules/AiChatPopup.js";
|
|
11
11
|
export { AiSearch } from "./modules/AiSearch.js";
|
|
12
|
+
export { BrandMark } from "./BrandMark.js";
|
|
12
13
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,wBAAyB,CAAC;AAE1E,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAqB,CAAC;AAEpD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAG3C,OAAO,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAExD,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAEvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA4B,CAAC;AAE1D,OAAO,EAAE,UAAU,EAAE,MAAM,yBAA0B,CAAC;AAEtD,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA2B,CAAC;AAExD,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA2B,CAAC;AAExD,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAwB,CAAC","sourcesContent":["export { AiConnectProvider, useAiConnect } from './AiConnectProvider.tsx';\nexport type { AiConnectProviderProps } from './AiConnectProvider.tsx';\nexport { ConnectButton } from './ConnectButton.tsx';\nexport type { ConnectButtonProps } from './ConnectButton.tsx';\nexport { useAiChat } from './useAiChat.ts';\nexport type { AskedQuestion, ChatTurn, ToolActivity, UseAiChatOptions } from './useAiChat.ts';\nexport type { AttachmentPolicy, PreparedAttachment } from '@tensorpass/aiconnect/attachments';\nexport { builtInLauncherMessages } from './launcher.ts';\nexport type { LauncherLocale, LauncherMessages } from './launcher.ts';\nexport { builtInMessages, builtInModuleMessages } from './messages.ts';\nexport type { Locale, ModuleMessages, PickerMessages, RefusalStep } from './messages.ts';\nexport { builtInWebMessages } from './webAccountMessages.ts';\nexport type { WebAccountMessages } from './webAccountMessages.ts';\nexport { AiChatInline } from './modules/AiChatInline.tsx';\nexport type { AiChatInlineProps } from './modules/AiChatInline.tsx';\nexport { AiChatPage } from './modules/AiChatPage.tsx';\nexport type { AiChatPageProps } from './modules/AiChatPage.tsx';\nexport { AiChatPanel } from './modules/AiChatPanel.tsx';\nexport type { AiChatPanelProps } from './modules/AiChatPanel.tsx';\nexport { AiChatPopup } from './modules/AiChatPopup.tsx';\nexport type { AiChatPopupProps } from './modules/AiChatPopup.tsx';\nexport { AiSearch } from './modules/AiSearch.tsx';\nexport type { AiSearchProps } from './modules/AiSearch.tsx';\nexport type { AiModuleHandle, AiModuleProps, AiOverlayProps } from './modules/types.ts';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,wBAAyB,CAAC;AAE1E,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAqB,CAAC;AAEpD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAG3C,OAAO,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAExD,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAEvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA4B,CAAC;AAE1D,OAAO,EAAE,UAAU,EAAE,MAAM,yBAA0B,CAAC;AAEtD,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA2B,CAAC;AAExD,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA2B,CAAC;AAExD,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAwB,CAAC;AAGlD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAiB,CAAC","sourcesContent":["export { AiConnectProvider, useAiConnect } from './AiConnectProvider.tsx';\nexport type { AiConnectProviderProps } from './AiConnectProvider.tsx';\nexport { ConnectButton } from './ConnectButton.tsx';\nexport type { ConnectButtonProps } from './ConnectButton.tsx';\nexport { useAiChat } from './useAiChat.ts';\nexport type { AskedQuestion, ChatTurn, ToolActivity, UseAiChatOptions } from './useAiChat.ts';\nexport type { AttachmentPolicy, PreparedAttachment } from '@tensorpass/aiconnect/attachments';\nexport { builtInLauncherMessages } from './launcher.ts';\nexport type { LauncherLocale, LauncherMessages } from './launcher.ts';\nexport { builtInMessages, builtInModuleMessages } from './messages.ts';\nexport type { Locale, ModuleMessages, PickerMessages, RefusalStep } from './messages.ts';\nexport { builtInWebMessages } from './webAccountMessages.ts';\nexport type { WebAccountMessages } from './webAccountMessages.ts';\nexport { AiChatInline } from './modules/AiChatInline.tsx';\nexport type { AiChatInlineProps } from './modules/AiChatInline.tsx';\nexport { AiChatPage } from './modules/AiChatPage.tsx';\nexport type { AiChatPageProps } from './modules/AiChatPage.tsx';\nexport { AiChatPanel } from './modules/AiChatPanel.tsx';\nexport type { AiChatPanelProps } from './modules/AiChatPanel.tsx';\nexport { AiChatPopup } from './modules/AiChatPopup.tsx';\nexport type { AiChatPopupProps } from './modules/AiChatPopup.tsx';\nexport { AiSearch } from './modules/AiSearch.tsx';\nexport type { AiSearchProps } from './modules/AiSearch.tsx';\nexport type { AiModuleHandle, AiModuleProps, AiOverlayProps, ToolResultsContext } from './modules/types.ts';\nexport { BrandMark } from './BrandMark.tsx';\n"]}
|
package/dist/modules/AiSearch.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
// A search bar that answers. The visitor types or dictates a question in the site's search bar, and the
|
|
3
3
|
// answer streams in a card under it, with the tools it ran, the site's own result cards and the account
|
|
4
|
-
// that answers.
|
|
5
|
-
// bar and the answer.
|
|
4
|
+
// that answers. The site's own line, when it gives one, closes the module. Each search starts a new
|
|
5
|
+
// conversation; Escape or the bar's clear button empties the bar and the answer.
|
|
6
6
|
import { useId, useRef, useState } from 'react';
|
|
7
7
|
import { useAiConnect } from "../AiConnectProvider.js";
|
|
8
8
|
import { AccountBadge } from "./parts/AccountBadge.js";
|
|
@@ -15,6 +15,7 @@ import { Suggestions, TurnBody } from "./parts/Conversation.js";
|
|
|
15
15
|
import { ArrowIcon, CloseIcon, SearchIcon } from "./parts/icons.js";
|
|
16
16
|
import { ModuleAnalytics } from "./parts/moduleAnalytics.js";
|
|
17
17
|
import { moduleClass } from "./parts/moduleClass.js";
|
|
18
|
+
import { ModuleFoot } from "./parts/ModuleFoot.js";
|
|
18
19
|
import { useModuleChat } from "./parts/useModuleChat.js";
|
|
19
20
|
import { useModuleHandle } from "./parts/useModuleHandle.js";
|
|
20
21
|
// The answer's card: the answer, or the connection step while the question waits for it, then the
|
|
@@ -26,7 +27,7 @@ function SearchResult(view) {
|
|
|
26
27
|
if (!turn && !chat.pendingQuestion) {
|
|
27
28
|
return null;
|
|
28
29
|
}
|
|
29
|
-
return (_jsxs("div", { className: "aic-search-result", role: "region", "aria-live": "polite", "aria-busy": chat.busy, children: [turn ? (_jsx(TurnBody, { turn: turn, view: view, live: chat.busy, stopped: chat.stopped.includes(chat.turns.length - 1), linkAllowed: chat.linkAllowed })) : _jsx(ConnectStep, { pending: true, compact: true }), chat.error ? (_jsxs("div", { className: "aic-error", role: "alert", children: [_jsx("p", { children: chat.error }), _jsx("button", { type: "button", className: "aic-text-button", onClick: chat.retry, children: moduleMessages.retry })] })) : null, state.status === 'connected' ? (_jsx("footer", { className: "aic-search-foot", children: _jsx(AccountBadge, { live: chat.busy }) })) : null] }));
|
|
30
|
+
return (_jsxs("div", { className: "aic-search-result", role: "region", "aria-live": "polite", "aria-busy": chat.busy, children: [turn ? (_jsx(TurnBody, { turn: turn, view: view, live: chat.busy, stopped: chat.stopped.includes(chat.turns.length - 1), linkAllowed: chat.linkAllowed, attachments: turn.attachments ?? [] })) : _jsx(ConnectStep, { pending: true, compact: true }), chat.error ? (_jsxs("div", { className: "aic-error", role: "alert", children: [_jsx("p", { children: chat.error }), _jsx("button", { type: "button", className: "aic-text-button", onClick: chat.retry, children: moduleMessages.retry })] })) : null, state.status === 'connected' ? (_jsx("footer", { className: "aic-search-foot", children: _jsx(AccountBadge, { live: chat.busy }) })) : null] }));
|
|
30
31
|
}
|
|
31
32
|
// The search bar's text and keys: Enter searches, starting a new conversation, and Escape or the
|
|
32
33
|
// clear button empties the bar and the answer.
|
|
@@ -82,6 +83,6 @@ export function AiSearch({ ref, ...props }) {
|
|
|
82
83
|
const bar = useSearchBar(chat);
|
|
83
84
|
useModuleHandle(ref, bar.search);
|
|
84
85
|
const started = chat.turns.length > 0 || Boolean(chat.pendingQuestion);
|
|
85
|
-
return (_jsx(ModuleAnalytics.Provider, { value: props.analytics, children: _jsxs("div", { className: moduleClass('search', props.className), dir: moduleMessages.dir, children: [_jsx(SearchBar, { bar: bar, chat: chat, started: started, placeholder: props.placeholder, analytics: props.analytics, voice: Boolean(props.attachments) && props.attachments?.voice !== false }), started ? (_jsx(SearchResult, { chat: chat, toolLabels: props.toolLabels, renderToolResults: props.renderToolResults })) : _jsx(Suggestions, { items: props.suggestions, onPick: bar.search })] }) }));
|
|
86
|
+
return (_jsx(ModuleAnalytics.Provider, { value: props.analytics, children: _jsxs("div", { className: moduleClass('search', props.className), dir: moduleMessages.dir, children: [_jsx(SearchBar, { bar: bar, chat: chat, started: started, placeholder: props.placeholder, analytics: props.analytics, voice: Boolean(props.attachments) && props.attachments?.voice !== false }), started ? (_jsx(SearchResult, { chat: chat, toolLabels: props.toolLabels, renderToolResults: props.renderToolResults })) : _jsx(Suggestions, { items: props.suggestions, onPick: bar.search }), _jsx(ModuleFoot, { children: props.footer })] }) }));
|
|
86
87
|
}
|
|
87
88
|
//# sourceMappingURL=AiSearch.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AiSearch.js","sourceRoot":"","sources":["../../src/modules/AiSearch.tsx"],"names":[],"mappings":";AAAA,wGAAwG;AACxG,wGAAwG;AACxG,oGAAoG;AACpG,sBAAsB;AAEtB,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,MAAM,yBAA0B,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,yBAA0B,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAsB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAoC,CAAC;AAClE,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,gCAAiC,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAyB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,yBAA0B,CAAC;AAEjE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,kBAAmB,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,e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er streams in a card under it, with the tools it ran, the site's own result cards and the account\n// that answers. Each search starts a new conversation; Escape or the bar's clear button empties the\n// bar and the answer.\n\nimport { useId, useRef, useState } from 'react';\nimport type { FormEvent, KeyboardEvent } from 'react';\nimport { useAiConnect } from '../AiConnectProvider.tsx';\nimport { AccountBadge } from './parts/AccountBadge.tsx';\nimport { StopButton } from './parts/Composer.tsx';\nimport { DictationBar } from './parts/dictation/DictationBar.tsx';\nimport { MicButton, useVoiceAvailable } from './parts/dictation/MicButton.tsx';\nimport { useDictation } from './parts/dictation/useDictation.ts';\nimport { ConnectStep } from './parts/ConnectStep.tsx';\nimport { Suggestions, TurnBody } from './parts/Conversation.tsx';\nimport type { TurnView } from './parts/Conversation.tsx';\nimport { ArrowIcon, CloseIcon, SearchIcon } from './parts/icons.tsx';\nimport { ModuleAnalytics } from './parts/moduleAnalytics.ts';\nimport { moduleClass } from './parts/moduleClass.ts';\nimport { useModuleChat } from './parts/useModuleChat.ts';\nimport { useModuleHandle } from './parts/useModuleHandle.ts';\nimport type { ModuleChat } from './parts/useModuleChat.ts';\nimport type { AiModuleProps } from './types.ts';\n\nexport type AiSearchProps = Omit<AiModuleProps, 'title' | 'intro'>;\n\n// The answer's card: the answer, or the connection step while the question waits for it, then the\n// account that answers once the visitor's AI is connected.\nfunction SearchResult(view: TurnView & { chat: ModuleChat }) {\n const { chat } = view;\n const { state, moduleMessages } = useAiConnect();\n const turn = chat.turns.at(-1);\n if (!turn && !chat.pendingQuestion) {\n return null;\n }\n return (\n <div className=\"aic-search-result\" role=\"region\" aria-live=\"polite\" aria-busy={chat.busy}>\n {turn ? (\n <TurnBody turn={turn} view={view} live={chat.busy} stopped={chat.stopped.includes(chat.turns.length - 1)}\n linkAllowed={chat.linkAllowed} />\n ) : <ConnectStep pending compact />}\n {chat.error ? (\n <div className=\"aic-error\" role=\"alert\">\n <p>{chat.error}</p>\n <button type=\"button\" className=\"aic-text-button\" onClick={chat.retry}>{moduleMessages.retry}</button>\n </div>\n ) : null}\n {state.status === 'connected' ? (\n <footer className=\"aic-search-foot\"><AccountBadge live={chat.busy} /></footer>\n ) : null}\n </div>\n );\n}\n\n// The search bar's text and keys: Enter searches, starting a new conversation, and Escape or the\n// clear button empties the bar and the answer.\nfunction useSearchBar(chat: ModuleChat) {\n const [text, setText] = useState('');\n const search = (question: string) => {\n setText(question);\n chat.reset();\n chat.ask(question);\n };\n const clear = () => {\n setText('');\n chat.reset();\n };\n const onSubmit = (event: FormEvent) => {\n event.preventDefault();\n if (text.trim()) {\n search(text);\n }\n };\n const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {\n if (event.key === 'Escape' && text) {\n event.preventDefault();\n clear();\n }\n };\n return { text, setText, search, clear, onSubmit, onKeyDown };\n}\n\ntype SearchBarProps = Pick<AiSearchProps, 'placeholder' | 'analytics'> & {\n bar: ReturnType<typeof useSearchBar>;\n chat: ModuleChat;\n started: boolean;\n voice: boolean;\n};\n\n// The field with its buttons: clear once there is something to clear, which hands the field back\n// for the next question, then send, or Stop while the answer streams.\nfunction SearchBar({ bar, chat, started, placeholder, analytics, voice }: SearchBarProps) {\n const { moduleMessages } = useAiConnect();\n const inputId = useId();\n const input = useRef<HTMLInputElement>(null);\n const sendTracking = analytics ? { 'data-analytics': `${analytics}-send` } : {};\n const dictation = useDictation(chat.dictation, (words) => {\n bar.setText((current) => [current.trimEnd(), words].filter(Boolean).join(' '));\n input.current?.focus();\n });\n const voiceOn = useVoiceAvailable(chat.dictation, voice);\n const clear = () => {\n bar.clear();\n input.current?.focus();\n };\n if (dictation.status !== 'idle') {\n return (\n <form className=\"aic-search-bar\" role=\"search\" data-dictating onSubmit={(event) => event.preventDefault()}>\n <DictationBar dictation={dictation} />\n </form>\n );\n }\n return (\n <form className=\"aic-search-bar\" role=\"search\" onSubmit={bar.onSubmit}>\n <label htmlFor={inputId} className=\"aic-visually-hidden\">{moduleMessages.searchLabel}</label>\n <SearchIcon />\n <input ref={input} id={inputId} className=\"aic-search-input\" type=\"search\" enterKeyHint=\"search\"\n autoComplete=\"off\" value={bar.text} placeholder={placeholder ?? moduleMessages.searchPlaceholder}\n onKeyDown={bar.onKeyDown} onChange={(event) => bar.setText(event.target.value)} />\n {(bar.text || started) && !chat.busy ? (\n <button type=\"button\" className=\"aic-search-clear\" onClick={clear} aria-label={moduleMessages.clear}>\n <CloseIcon />\n </button>\n ) : null}\n {voiceOn && !chat.busy ? <MicButton onClick={() => void dictation.start()} /> : null}\n {chat.busy ? <StopButton onStop={chat.stop} /> : (\n <button type=\"submit\" className=\"aic-send\" disabled={!bar.text.trim()} aria-label={moduleMessages.send}\n {...sendTracking}>\n <ArrowIcon />\n </button>\n )}\n </form>\n );\n}\n\nexport function AiSearch({ ref, ...props }: AiSearchProps) {\n const { moduleMessages } = useAiConnect();\n const chat = useModuleChat(props);\n const bar = useSearchBar(chat);\n useModuleHandle(ref, bar.search);\n const started = chat.turns.length > 0 || Boolean(chat.pendingQuestion);\n return (\n <ModuleAnalytics.Provider value={props.analytics}>\n <div className={moduleClass('search', props.className)} dir={moduleMessages.dir}>\n <SearchBar bar={bar} chat={chat} started={started} placeholder={props.placeholder}\n analytics={props.analytics} voice={Boolean(props.attachments) && props.attachments?.voice !== false} />\n {started ? (\n <SearchResult chat={chat} toolLabels={props.toolLabels} renderToolResults={props.renderToolResults} />\n ) : <Suggestions items={props.suggestions} onPick={bar.search} />}\n </div>\n </ModuleAnalytics.Provider>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AiSearch.js","sourceRoot":"","sources":["../../src/modules/AiSearch.tsx"],"names":[],"mappings":";AAAA,wGAAwG;AACxG,wGAAwG;AACxG,oGAAoG;AACpG,iFAAiF;AAEjF,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,MAAM,yBAA0B,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,yBAA0B,CAAC;AACxD,OAAO,EAAE,UA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AG,EAAE,cAAc,CAAC,GAAG,aAC7E,KAAC,SAAS,IAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,CAAC,WAAW,EAC/E,SAAS,EAAE,KAAK,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,KAAK,CAAC,WAAW,EAAE,KAAK,KAAK,KAAK,GAAI,EACxG,OAAO,CAAC,CAAC,CAAC,CACT,KAAC,YAAY,IAAC,IAAI,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,iBAAiB,EAAE,KAAK,CAAC,iBAAiB,GAAI,CACvG,CAAC,CAAC,CAAC,KAAC,WAAW,IAAC,KAAK,EAAE,KAAK,CAAC,WAAW,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,GAAI,EACjE,KAAC,UAAU,cAAE,KAAK,CAAC,MAAM,GAAc,IACnC,GACmB,CAC5B,CAAC;AACJ,CAAC","sourcesContent":["// A search bar that answers. The visitor types or dictates a question in the site's search bar, and the\n// answer streams in a card under it, with the tools it ran, the site's own result cards and the account\n// that answers. The site's own line, when it gives one, closes the module. Each search starts a new\n// conversation; Escape or the bar's clear button empties the bar and the answer.\n\nimport { useId, useRef, useState } from 'react';\nimport type { FormEvent, KeyboardEvent } from 'react';\nimport { useAiConnect } from '../AiConnectProvider.tsx';\nimport { AccountBadge } from './parts/AccountBadge.tsx';\nimport { StopButton } from './parts/Composer.tsx';\nimport { DictationBar } from './parts/dictation/DictationBar.tsx';\nimport { MicButton, useVoiceAvailable } from './parts/dictation/MicButton.tsx';\nimport { useDictation } from './parts/dictation/useDictation.ts';\nimport { ConnectStep } from './parts/ConnectStep.tsx';\nimport { Suggestions, TurnBody } from './parts/Conversation.tsx';\nimport type { TurnView } from './parts/Conversation.tsx';\nimport { ArrowIcon, CloseIcon, SearchIcon } from './parts/icons.tsx';\nimport { ModuleAnalytics } from './parts/moduleAnalytics.ts';\nimport { moduleClass } from './parts/moduleClass.ts';\nimport { ModuleFoot } from './parts/ModuleFoot.tsx';\nimport { useModuleChat } from './parts/useModuleChat.ts';\nimport { useModuleHandle } from './parts/useModuleHandle.ts';\nimport type { ModuleChat } from './parts/useModuleChat.ts';\nimport type { AiModuleProps } from './types.ts';\n\nexport type AiSearchProps = Omit<AiModuleProps, 'title' | 'intro'>;\n\n// The answer's card: the answer, or the connection step while the question waits for it, then the\n// account that answers once the visitor's AI is connected.\nfunction SearchResult(view: TurnView & { chat: ModuleChat }) {\n const { chat } = view;\n const { state, moduleMessages } = useAiConnect();\n const turn = chat.turns.at(-1);\n if (!turn && !chat.pendingQuestion) {\n return null;\n }\n return (\n <div className=\"aic-search-result\" role=\"region\" aria-live=\"polite\" aria-busy={chat.busy}>\n {turn ? (\n <TurnBody turn={turn} view={view} live={chat.busy} stopped={chat.stopped.includes(chat.turns.length - 1)}\n linkAllowed={chat.linkAllowed} attachments={turn.attachments ?? []} />\n ) : <ConnectStep pending compact />}\n {chat.error ? (\n <div className=\"aic-error\" role=\"alert\">\n <p>{chat.error}</p>\n <button type=\"button\" className=\"aic-text-button\" onClick={chat.retry}>{moduleMessages.retry}</button>\n </div>\n ) : null}\n {state.status === 'connected' ? (\n <footer className=\"aic-search-foot\"><AccountBadge live={chat.busy} /></footer>\n ) : null}\n </div>\n );\n}\n\n// The search bar's text and keys: Enter searches, starting a new conversation, and Escape or the\n// clear button empties the bar and the answer.\nfunction useSearchBar(chat: ModuleChat) {\n const [text, setText] = useState('');\n const search = (question: string) => {\n setText(question);\n chat.reset();\n chat.ask(question);\n };\n const clear = () => {\n setText('');\n chat.reset();\n };\n const onSubmit = (event: FormEvent) => {\n event.preventDefault();\n if (text.trim()) {\n search(text);\n }\n };\n const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {\n if (event.key === 'Escape' && text) {\n event.preventDefault();\n clear();\n }\n };\n return { text, setText, search, clear, onSubmit, onKeyDown };\n}\n\ntype SearchBarProps = Pick<AiSearchProps, 'placeholder' | 'analytics'> & {\n bar: ReturnType<typeof useSearchBar>;\n chat: ModuleChat;\n started: boolean;\n voice: boolean;\n};\n\n// The field with its buttons: clear once there is something to clear, which hands the field back\n// for the next question, then send, or Stop while the answer streams.\nfunction SearchBar({ bar, chat, started, placeholder, analytics, voice }: SearchBarProps) {\n const { moduleMessages } = useAiConnect();\n const inputId = useId();\n const input = useRef<HTMLInputElement>(null);\n const sendTracking = analytics ? { 'data-analytics': `${analytics}-send` } : {};\n const dictation = useDictation(chat.dictation, (words) => {\n bar.setText((current) => [current.trimEnd(), words].filter(Boolean).join(' '));\n input.current?.focus();\n });\n const voiceOn = useVoiceAvailable(chat.dictation, voice);\n const clear = () => {\n bar.clear();\n input.current?.focus();\n };\n if (dictation.status !== 'idle') {\n return (\n <form className=\"aic-search-bar\" role=\"search\" data-dictating onSubmit={(event) => event.preventDefault()}>\n <DictationBar dictation={dictation} />\n </form>\n );\n }\n return (\n <form className=\"aic-search-bar\" role=\"search\" onSubmit={bar.onSubmit}>\n <label htmlFor={inputId} className=\"aic-visually-hidden\">{moduleMessages.searchLabel}</label>\n <SearchIcon />\n <input ref={input} id={inputId} className=\"aic-search-input\" type=\"search\" enterKeyHint=\"search\"\n autoComplete=\"off\" value={bar.text} placeholder={placeholder ?? moduleMessages.searchPlaceholder}\n onKeyDown={bar.onKeyDown} onChange={(event) => bar.setText(event.target.value)} />\n {(bar.text || started) && !chat.busy ? (\n <button type=\"button\" className=\"aic-search-clear\" onClick={clear} aria-label={moduleMessages.clear}>\n <CloseIcon />\n </button>\n ) : null}\n {voiceOn && !chat.busy ? <MicButton onClick={() => void dictation.start()} /> : null}\n {chat.busy ? <StopButton onStop={chat.stop} /> : (\n <button type=\"submit\" className=\"aic-send\" disabled={!bar.text.trim()} aria-label={moduleMessages.send}\n {...sendTracking}>\n <ArrowIcon />\n </button>\n )}\n </form>\n );\n}\n\nexport function AiSearch({ ref, ...props }: AiSearchProps) {\n const { moduleMessages } = useAiConnect();\n const chat = useModuleChat(props);\n const bar = useSearchBar(chat);\n useModuleHandle(ref, bar.search);\n const started = chat.turns.length > 0 || Boolean(chat.pendingQuestion);\n return (\n <ModuleAnalytics.Provider value={props.analytics}>\n <div className={moduleClass('search', props.className)} dir={moduleMessages.dir}>\n <SearchBar bar={bar} chat={chat} started={started} placeholder={props.placeholder}\n analytics={props.analytics} voice={Boolean(props.attachments) && props.attachments?.voice !== false} />\n {started ? (\n <SearchResult chat={chat} toolLabels={props.toolLabels} renderToolResults={props.renderToolResults} />\n ) : <Suggestions items={props.suggestions} onPick={bar.search} />}\n <ModuleFoot>{props.footer}</ModuleFoot>\n </div>\n </ModuleAnalytics.Provider>\n );\n}\n"]}
|
|
@@ -8,9 +8,9 @@ import { answerBlocks, keepAllowedLinks, onSite } from "./answerMarkdown.js";
|
|
|
8
8
|
function Run({ run }) {
|
|
9
9
|
switch (run.kind) {
|
|
10
10
|
case 'strong':
|
|
11
|
-
return _jsx("strong", { children: run.
|
|
11
|
+
return _jsx("strong", { children: _jsx(Runs, { runs: run.runs, caret: null }) });
|
|
12
12
|
case 'em':
|
|
13
|
-
return _jsx("em", { children: run.
|
|
13
|
+
return _jsx("em", { children: _jsx(Runs, { runs: run.runs, caret: null }) });
|
|
14
14
|
case 'code':
|
|
15
15
|
return _jsx("code", { children: run.text });
|
|
16
16
|
case 'link': {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AnswerText.js","sourceRoot":"","sources":["../../../src/modules/parts/AnswerText.tsx"],"names":[],"mappings":";AAAA,iGAAiG;AACjG,mGAAmG;AACnG,wGAAwG;AACxG,4CAA4C;AAE5C,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAEhC,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAG7E,SAAS,GAAG,CAAC,EAAE,GAAG,EAAsB;IACtC,QAAQ,GAA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AAC;IACrG,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACxB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,KAAK,GAAG,SAAS,CAAC,CAAC,CAAC,eAAM,SAAS,EAAC,WAAW,iBAAa,MAAM,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;IACnF,OAAO,CACL,cAAK,SAAS,EAAC,YAAY,kBAAe,OAAO,IAAI,SAAS,YAC3D,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAC5B,KAAC,KAAK,IAAa,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,KAAK,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAtE,KAAK,CAAqE,CACvF,CAAC,GACE,CACP,CAAC;AACJ,CAAC","sourcesContent":["// The answer as it streams: its light Markdown drawn as paragraphs, headings and lists, with the\n// cyan caret at the end of the text while more is coming. Only the links the conversation's guards\n// allow are drawn, and those to other sites open in a new tab. A safe answer that replaced what a guard\n// stopped is marked, for the site's styles.\n\nimport { useMemo } from 'react';\nimport type { ReactNode } from 'react';\nimport { answerBlocks, keepAllowedLinks, onSite } from './answerMarkdown.ts';\nimport type { AnswerBlock, InlineRun } from './answerMarkdown.ts';\n\nfunction Run({ run }: { run: InlineRun }) {\n switch (run.kind) {\n case 'strong':\n return <strong><Runs runs={run.runs} caret={null} /></strong>;\n case 'em':\n return <em><Runs runs={run.runs} caret={null} /></em>;\n case 'code':\n return <code>{run.text}</code>;\n case 'link': {\n const external = !onSite(run.href);\n return (\n <a href={run.href} target={external ? '_blank' : undefined} rel={external ? 'noreferrer' : undefined}>\n {run.text}\n </a>\n );\n }\n default:\n return <>{run.text}</>;\n }\n}\n\nfunction Runs({ runs, caret }: { runs: InlineRun[]; caret: ReactNode }) {\n return <>{runs.map((run, index) => <Run key={index} run={run} />)}{caret}</>;\n}\n\nfunction Block({ block, caret }: { block: AnswerBlock; caret: ReactNode }) {\n if (block.kind === 'list') {\n const items = block.items.map((runs, index) => (\n <li key={index}><Runs runs={runs} caret={index === block.items.length - 1 ? caret : null} /></li>\n ));\n return block.ordered ? <ol>{items}</ol> : <ul>{items}</ul>;\n }\n const className = block.kind === 'heading' ? 'aic-answer-heading' : undefined;\n return <p className={className}><Runs runs={block.runs} caret={caret} /></p>;\n}\n\ninterface AnswerTextProps {\n text: string;\n streaming: boolean;\n linkAllowed: (href: string) => boolean;\n blocked?: boolean;\n}\n\nexport function AnswerText({ text, streaming, linkAllowed, blocked }: AnswerTextProps) {\n const blocks = useMemo(() => keepAllowedLinks(answerBlocks(text), linkAllowed), [text, linkAllowed]);\n if (blocks.length === 0) {\n return null;\n }\n const caret = streaming ? <span className=\"aic-caret\" aria-hidden=\"true\" /> : null;\n return (\n <div className=\"aic-answer\" data-blocked={blocked || undefined}>\n {blocks.map((block, index) => (\n <Block key={index} block={block} caret={index === blocks.length - 1 ? caret : null} />\n ))}\n </div>\n );\n}\n"]}
|
|
@@ -8,6 +8,7 @@ import { Composer } from "./Composer.js";
|
|
|
8
8
|
import { Conversation } from "./Conversation.js";
|
|
9
9
|
import { CloseIcon, NewChatIcon } from "./icons.js";
|
|
10
10
|
import { ModuleAnalytics } from "./moduleAnalytics.js";
|
|
11
|
+
import { ModuleFoot } from "./ModuleFoot.js";
|
|
11
12
|
function RoundButton({ label, onClick, children }) {
|
|
12
13
|
return (_jsx("button", { type: "button", className: "aic-round", "aria-label": label, title: label, onClick: onClick, children: children }));
|
|
13
14
|
}
|
|
@@ -20,6 +21,6 @@ export function ChatFrame({ module, chat, fieldRef, ...header }) {
|
|
|
20
21
|
const { moduleMessages } = useAiConnect();
|
|
21
22
|
const policy = module.attachments;
|
|
22
23
|
const attachments = useAttachments(attachmentsOn(policy) ? policy : undefined);
|
|
23
|
-
return (_jsx(ModuleAnalytics.Provider, { value: module.analytics, children: _jsxs(DropZone, { policy: attachments.policy, onFiles: attachments.add, children: [_jsx(FrameHeader, { chat: chat, ...header }), _jsx(Conversation, { chat: chat, intro: module.intro ?? moduleMessages.intro, suggestions: module.suggestions, toolLabels: module.toolLabels, renderToolResults: module.renderToolResults }), _jsx(Composer, { busy: chat.busy, placeholder: module.placeholder ?? moduleMessages.placeholder, onSend: chat.ask, onStop: chat.stop, fieldRef: fieldRef, attachments: attachments.policy ? attachments : undefined, reads: chat.reads, dictation: chat.dictation, voice: Boolean(policy) && policy?.voice !== false })] }) }));
|
|
24
|
+
return (_jsx(ModuleAnalytics.Provider, { value: module.analytics, children: _jsxs(DropZone, { policy: attachments.policy, onFiles: attachments.add, children: [_jsx(FrameHeader, { chat: chat, ...header }), _jsx(Conversation, { chat: chat, intro: module.intro ?? moduleMessages.intro, suggestions: module.suggestions, toolLabels: module.toolLabels, renderToolResults: module.renderToolResults }), _jsx(Composer, { busy: chat.busy, placeholder: module.placeholder ?? moduleMessages.placeholder, onSend: chat.ask, onStop: chat.stop, fieldRef: fieldRef, attachments: attachments.policy ? attachments : undefined, reads: chat.reads, dictation: chat.dictation, voice: Boolean(policy) && policy?.voice !== false }), _jsx(ModuleFoot, { children: module.footer })] }) }));
|
|
24
25
|
}
|
|
25
26
|
//# sourceMappingURL=ChatFrame.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ChatFrame.js","sourceRoot":"","sources":["../../../src/modules/parts/ChatFrame.tsx"],"names":[],"mappings":";AAKA,OAAO,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAClE,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA6B,CAAC;AAE3D,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAoB,CAAC;AAClD,OAAO,EAAE,QAAQ,EAAE,MAAM,2BAA4B,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAgB,CAAC;AAC1C,OAAO,EAAE,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Ac,CAAC,KAAK,EAAE,WAAW,EAAE,MAAM,CAAC,WAAW,EACpG,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,iBAAiB,EAAE,MAAM,CAAC,iBAAiB,GAAI,EAChF,KAAC,QAAQ,IAAC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,MAAM,CAAC,WAAW,IAAI,cAAc,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,EACxG,MAAM,EAAE,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,EAChG,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,MAAM,EAAE,KAAK,KAAK,KAAK,GAAI,EACrG,KAAC,UAAU,cAAE,MAAM,CAAC,MAAM,GAAc,IAC/B,GACc,CAC5B,CAAC;AACJ,CAAC","sourcesContent":["// The frame every chat module shares: a header with the module's title, the account that answers\n// and its buttons, then the conversation, then the question box, then the site's own line when it gives\n// one. When the site takes attachments, files dropped anywhere on the frame join the question.\n\nimport type { ReactNode, RefObject } from 'react';\nimport { attachmentsOn } from '@tensorpass/aiconnect/attachments';\nimport { useAiConnect } from '../../AiConnectProvider.tsx';\nimport type { AiModuleProps } from '../types.ts';\nimport { AccountBadge } from './AccountBadge.tsx';\nimport { DropZone } from './attachments/DropZone.tsx';\nimport { useAttachments } from './attachments/useAttachments.ts';\nimport { Composer } from './Composer.tsx';\nimport { Conversation } from './Conversation.tsx';\nimport { CloseIcon, NewChatIcon } from './icons.tsx';\nimport { ModuleAnalytics } from './moduleAnalytics.ts';\nimport { ModuleFoot } from './ModuleFoot.tsx';\nimport type { ModuleChat } from './useModuleChat.ts';\n\nexport interface ChatFrameProps {\n module: AiModuleProps;\n chat: ModuleChat;\n title: string;\n titleId: string;\n fieldRef: RefObject<HTMLTextAreaElement | null>;\n onClose?: () => void;\n}\n\nfunction RoundButton({ label, onClick, children }: { label: string; onClick: () => void; children: ReactNode }) {\n return (\n <button type=\"button\" className=\"aic-round\" aria-label={label} title={label} onClick={onClick}>{children}</button>\n );\n}\n\nfunction FrameHeader({ chat, title, titleId, onClose }: Omit<ChatFrameProps, 'module' | 'fieldRef'>) {\n const { moduleMessages } = useAiConnect();\n const started = chat.turns.length > 0 || Boolean(chat.pendingQuestion);\n return (\n <header className=\"aic-head\">\n <div className=\"aic-head-text\">\n <h2 id={titleId} className=\"aic-head-title\">{title}</h2>\n <AccountBadge live={chat.busy} />\n </div>\n {started ? (\n <RoundButton label={moduleMessages.newChat} onClick={chat.reset}><NewChatIcon /></RoundButton>\n ) : null}\n {onClose ? <RoundButton label={moduleMessages.close} onClick={onClose}><CloseIcon /></RoundButton> : null}\n </header>\n );\n}\n\nexport function ChatFrame({ module, chat, fieldRef, ...header }: ChatFrameProps) {\n const { moduleMessages } = useAiConnect();\n const policy = module.attachments;\n const attachments = useAttachments(attachmentsOn(policy) ? policy : undefined);\n return (\n <ModuleAnalytics.Provider value={module.analytics}>\n <DropZone policy={attachments.policy} onFiles={attachments.add}>\n <FrameHeader chat={chat} {...header} />\n <Conversation chat={chat} intro={module.intro ?? moduleMessages.intro} suggestions={module.suggestions}\n toolLabels={module.toolLabels} renderToolResults={module.renderToolResults} />\n <Composer busy={chat.busy} placeholder={module.placeholder ?? moduleMessages.placeholder} onSend={chat.ask}\n onStop={chat.stop} fieldRef={fieldRef} attachments={attachments.policy ? attachments : undefined}\n reads={chat.reads} dictation={chat.dictation} voice={Boolean(policy) && policy?.voice !== false} />\n <ModuleFoot>{module.footer}</ModuleFoot>\n </DropZone>\n </ModuleAnalytics.Provider>\n );\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { PreparedAttachment } from '@tensorpass/aiconnect/attachments';
|
|
1
2
|
import type { ChatTurn } from '../../useAiChat.ts';
|
|
2
3
|
import type { AiModuleProps } from '../types.ts';
|
|
3
4
|
import type { ModuleChat } from './useModuleChat.ts';
|
|
@@ -8,12 +9,14 @@ export interface TurnBodyProps {
|
|
|
8
9
|
stopped: boolean;
|
|
9
10
|
view: TurnView;
|
|
10
11
|
linkAllowed: (href: string) => boolean;
|
|
12
|
+
attachments: PreparedAttachment[];
|
|
11
13
|
}
|
|
12
|
-
export declare function TurnBody({ turn, live, stopped, view, linkAllowed }: TurnBodyProps): import("react").JSX.Element;
|
|
14
|
+
export declare function TurnBody({ turn, live, stopped, view, linkAllowed, attachments }: TurnBodyProps): import("react").JSX.Element;
|
|
13
15
|
export declare function Suggestions({ items, onPick }: {
|
|
14
16
|
items?: string[];
|
|
15
17
|
onPick: (question: string) => void;
|
|
16
18
|
}): import("react").JSX.Element | null;
|
|
19
|
+
export declare function attachmentsSoFar(turns: ChatTurn[]): PreparedAttachment[][];
|
|
17
20
|
export interface ConversationProps extends TurnView {
|
|
18
21
|
chat: ModuleChat;
|
|
19
22
|
intro: string;
|
|
@@ -6,7 +6,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
|
|
|
6
6
|
// streams and the site's own result cards, and the last answer's error comes with a way to ask again,
|
|
7
7
|
// or, for a TensorPass account without a plan, the offer to subscribe. The view follows the answer down
|
|
8
8
|
// while the visitor stays at the bottom.
|
|
9
|
-
import { useEffect, useRef } from 'react';
|
|
9
|
+
import { useEffect, useMemo, useRef } from 'react';
|
|
10
10
|
import { useAiConnect } from "../../AiConnectProvider.js";
|
|
11
11
|
import { ConnectRing } from "../../ConnectRing.js";
|
|
12
12
|
import { AnswerText } from "./AnswerText.js";
|
|
@@ -27,10 +27,10 @@ function Question({ text, attachments, unread }) {
|
|
|
27
27
|
}
|
|
28
28
|
// What a turn shows under its question: the tools as they run, a thinking line until the first
|
|
29
29
|
// words arrive, the answer, whether the visitor stopped it, and the site's own result cards.
|
|
30
|
-
export function TurnBody({ turn, live, stopped, view, linkAllowed }) {
|
|
30
|
+
export function TurnBody({ turn, live, stopped, view, linkAllowed, attachments }) {
|
|
31
31
|
const { moduleMessages } = useAiConnect();
|
|
32
32
|
const toolRunning = turn.tools.some((activity) => activity.result === null);
|
|
33
|
-
const results = view.renderToolResults?.(turn);
|
|
33
|
+
const results = view.renderToolResults?.(turn, { attachments });
|
|
34
34
|
return (_jsxs(_Fragment, { children: [_jsx(ToolActivityList, { tools: turn.tools, labels: view.toolLabels }), live && !turn.answer && !toolRunning ? (_jsxs("p", { className: "aic-thinking", children: [_jsx(WaveIcon, { size: 16, className: "aic-live-arcs" }), moduleMessages.thinking] })) : null, _jsx(AnswerText, { text: turn.answer, streaming: live && Boolean(turn.answer), linkAllowed: linkAllowed, blocked: Boolean(turn.blocked) }), stopped ? _jsxs("p", { className: "aic-stopped", children: [_jsx("i", { "aria-hidden": "true" }), moduleMessages.stopped] }) : null, results ? _jsx("div", { className: "aic-results", children: results }) : null] }));
|
|
35
35
|
}
|
|
36
36
|
export function Suggestions({ items, onPick }) {
|
|
@@ -62,11 +62,20 @@ function useFollowAnswer(logRef, chat) {
|
|
|
62
62
|
}
|
|
63
63
|
};
|
|
64
64
|
}
|
|
65
|
+
// For each turn, every file the visitor added up to it, oldest first.
|
|
66
|
+
export function attachmentsSoFar(turns) {
|
|
67
|
+
const added = [];
|
|
68
|
+
return turns.map((turn) => {
|
|
69
|
+
added.push(...(turn.attachments ?? []));
|
|
70
|
+
return [...added];
|
|
71
|
+
});
|
|
72
|
+
}
|
|
65
73
|
export function Conversation({ chat, intro, suggestions, ...view }) {
|
|
66
74
|
const { moduleMessages } = useAiConnect();
|
|
67
75
|
const logRef = useRef(null);
|
|
68
76
|
const onScroll = useFollowAnswer(logRef, chat);
|
|
77
|
+
const attachments = useMemo(() => attachmentsSoFar(chat.turns), [chat.turns]);
|
|
69
78
|
const empty = chat.turns.length === 0 && !chat.pendingQuestion;
|
|
70
|
-
return (_jsxs("div", { ref: logRef, className: "aic-log", role: "log", "aria-busy": chat.busy, onScroll: onScroll, children: [empty ? (_jsxs("div", { className: "aic-empty", children: [_jsx("div", { className: "aic-empty-ring", children: _jsx(ConnectRing, { live: false }) }), _jsx("h3", { className: "aic-intro", children: intro }), _jsx(Suggestions, { items: suggestions, onPick: chat.ask }), _jsx(ConnectStep, { pending: false })] })) : null, _jsxs("ol", { className: "aic-turns", children: [chat.turns.map((turn, index) => (_jsxs("li", { className: "aic-turn", children: [_jsx(Question, { text: turn.question, attachments: turn.attachments, unread: turn.unread }), _jsx(TurnBody, { turn: turn, view: view, stopped: chat.stopped.includes(index), linkAllowed: chat.linkAllowed, live: chat.busy && index === chat.turns.length - 1 })] }, index))), chat.pendingQuestion ? (_jsxs("li", { className: "aic-turn", children: [_jsx(Question, { text: chat.pendingQuestion.text, attachments: chat.pendingQuestion.attachments }), _jsx(ConnectStep, { pending: true })] })) : null] }), chat.refusal === PLAN_INACTIVE ? _jsx(PlanOffer, { onActive: chat.retry }) : null, chat.error && chat.refusal !== PLAN_INACTIVE ? (_jsxs("div", { className: "aic-error", role: "alert", children: [_jsx("p", { children: chat.error }), _jsx("button", { type: "button", className: "aic-text-button", onClick: chat.retry, children: moduleMessages.retry })] })) : null] }));
|
|
79
|
+
return (_jsxs("div", { ref: logRef, className: "aic-log", role: "log", "aria-busy": chat.busy, onScroll: onScroll, children: [empty ? (_jsxs("div", { className: "aic-empty", children: [_jsx("div", { className: "aic-empty-ring", children: _jsx(ConnectRing, { live: false }) }), _jsx("h3", { className: "aic-intro", children: intro }), _jsx(Suggestions, { items: suggestions, onPick: chat.ask }), _jsx(ConnectStep, { pending: false })] })) : null, _jsxs("ol", { className: "aic-turns", children: [chat.turns.map((turn, index) => (_jsxs("li", { className: "aic-turn", children: [_jsx(Question, { text: turn.question, attachments: turn.attachments, unread: turn.unread }), _jsx(TurnBody, { turn: turn, view: view, stopped: chat.stopped.includes(index), linkAllowed: chat.linkAllowed, live: chat.busy && index === chat.turns.length - 1, attachments: attachments[index] })] }, index))), chat.pendingQuestion ? (_jsxs("li", { className: "aic-turn", children: [_jsx(Question, { text: chat.pendingQuestion.text, attachments: chat.pendingQuestion.attachments }), _jsx(ConnectStep, { pending: true })] })) : null] }), chat.refusal === PLAN_INACTIVE ? _jsx(PlanOffer, { onActive: chat.retry }) : null, chat.error && chat.refusal !== PLAN_INACTIVE ? (_jsxs("div", { className: "aic-error", role: "alert", children: [_jsx("p", { children: chat.error }), _jsx("button", { type: "button", className: "aic-text-button", onClick: chat.retry, children: moduleMessages.retry })] })) : null] }));
|
|
71
80
|
}
|
|
72
81
|
//# sourceMappingURL=Conversation.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Conversation.js","sourceRoot":"","sources":["../../../src/modules/parts/Conversation.tsx"],"names":[],"mappings":";AAAA,oGAAoG;AACpG,yGAAyG;AACzG,uGAAuG;AACvG,wGAAwG;AACxG,sGAAsG;AACtG,wGAAwG;AACxG,yCAAyC;AAEzC,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAE1C,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA6B,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAuB,CAAC;AAIpD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAkB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAkC,CAAC;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAmB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAiB,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,YAAa,CAAC;AAClD,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAoB,CAAC;AAatD,6EAA6E;AAC7E,MAAM,aAAa,GAAG,eAAe,CAAC;AAEtC,kFAAkF;AAClF,MA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AAE,IAAI,CAAC,WAAW,EACpG,IAAI,EAAE,IAAI,CAAC,IAAI,IAAI,KAAK,KAAK,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,GAAI,KAHjD,KAAK,CAIT,CACN,CAAC,EACD,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CACtB,cAAI,SAAS,EAAC,UAAU,aACtB,KAAC,QAAQ,IAAC,IAAI,EAAE,IAAI,CAAC,eAAe,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,eAAe,CAAC,WAAW,GAAI,EAC5F,KAAC,WAAW,IAAC,OAAO,SAAG,IACpB,CACN,CAAC,CAAC,CAAC,IAAI,IACL,EACJ,IAAI,CAAC,OAAO,KAAK,aAAa,CAAC,CAAC,CAAC,KAAC,SAAS,IAAC,QAAQ,EAAE,IAAI,CAAC,KAAK,GAAI,CAAC,CAAC,CAAC,IAAI,EAC3E,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,OAAO,KAAK,aAAa,CAAC,CAAC,CAAC,CAC9C,eAAK,SAAS,EAAC,WAAW,EAAC,IAAI,EAAC,OAAO,aACrC,sBAAI,IAAI,CAAC,KAAK,GAAK,EACnB,iBAAQ,IAAI,EAAC,QAAQ,EAAC,SAAS,EAAC,iBAAiB,EAAC,OAAO,EAAE,IAAI,CAAC,KAAK,YAAG,cAAc,CAAC,KAAK,GAAU,IAClG,CACP,CAAC,CAAC,CAAC,IAAI,IACJ,CACP,CAAC;AACJ,CAAC","sourcesContent":["// The conversation of a chat module. Empty, it shows its heading, the suggested questions, then the\n// connection step, under the wallet's ring in the full page mode. The step appears once the first wallet\n// check ends, so it comes last and the heading and the questions the page rendered stay in place. Then\n// each turn shows the visitor's question with its files, the site's tools as they run, the answer as it\n// streams and the site's own result cards, and the last answer's error comes with a way to ask again,\n// or, for a TensorPass account without a plan, the offer to subscribe. The view follows the answer down\n// while the visitor stays at the bottom.\n\nimport { useEffect, useRef } from 'react';\nimport type { RefObject } from 'react';\nimport { useAiConnect } from '../../AiConnectProvider.tsx';\nimport { ConnectRing } from '../../ConnectRing.tsx';\nimport type { PreparedAttachment } from '@tensorpass/aiconnect/attachments';\nimport type { ChatTurn } from '../../useAiChat.ts';\nimport type { AiModuleProps } from '../types.ts';\nimport { AnswerText } from './AnswerText.tsx';\nimport { QuestionAttachments } from './attachments/AttachmentRows.tsx';\nimport { ConnectStep } from './ConnectStep.tsx';\nimport { PlanOffer } from './PlanOffer.tsx';\nimport { useActionAttribute } from './moduleAnalytics.ts';\nimport { ArrowIcon, WaveIcon } from './icons.tsx';\nimport { ToolActivityList } from './ToolActivity.tsx';\nimport type { ModuleChat } from './useModuleChat.ts';\n\nexport type TurnView = Pick<AiModuleProps, 'toolLabels' | 'renderToolResults'>;\n\nexport interface TurnBodyProps {\n turn: ChatTurn;\n live: boolean;\n stopped: boolean;\n view: TurnView;\n linkAllowed: (href: string) => boolean;\n}\n\n// The plan gateway's refusal of a TensorPass account without a subscription.\nconst PLAN_INACTIVE = 'plan_inactive';\n\n// How close to the bottom, in pixels, the visitor counts as following the answer.\nconst FOLLOW_DISTANCE = 56;\n\ninterface QuestionProps {\n text: string;\n attachments?: PreparedAttachment[];\n // The images and pages the answering model did not read.\n unread?: number;\n}\n\nfunction Question({ text, attachments, unread }: QuestionProps) {\n const { moduleMessages, state } = useAiConnect();\n const account = state.status === 'connected' ? state.providerName : '';\n return (\n <>\n {attachments?.length ? <QuestionAttachments attachments={attachments} /> : null}\n {text ? (\n <p className=\"aic-question\" dir=\"auto\">\n <span className=\"aic-visually-hidden\">{moduleMessages.question}: </span>{text}\n </p>\n ) : null}\n {unread ? (\n <p className=\"aic-unread\">\n {moduleMessages.unreadPages.replaceAll('{count}', String(unread)).replaceAll('{account}', account)}\n </p>\n ) : null}\n </>\n );\n}\n\n// What a turn shows under its question: the tools as they run, a thinking line until the first\n// words arrive, the answer, whether the visitor stopped it, and the site's own result cards.\nexport function TurnBody({ turn, live, stopped, view, linkAllowed }: TurnBodyProps) {\n const { moduleMessages } = useAiConnect();\n const toolRunning = turn.tools.some((activity) => activity.result === null);\n const results = view.renderToolResults?.(turn);\n return (\n <>\n <ToolActivityList tools={turn.tools} labels={view.toolLabels} />\n {live && !turn.answer && !toolRunning ? (\n <p className=\"aic-thinking\"><WaveIcon size={16} className=\"aic-live-arcs\" />{moduleMessages.thinking}</p>\n ) : null}\n <AnswerText text={turn.answer} streaming={live && Boolean(turn.answer)} linkAllowed={linkAllowed}\n blocked={Boolean(turn.blocked)} />\n {stopped ? <p className=\"aic-stopped\"><i aria-hidden=\"true\" />{moduleMessages.stopped}</p> : null}\n {results ? <div className=\"aic-results\">{results}</div> : null}\n </>\n );\n}\n\nexport function Suggestions({ items, onPick }: { items?: string[]; onPick: (question: string) => void }) {\n const { moduleMessages } = useAiConnect();\n const tracking = useActionAttribute('suggestion');\n if (!items?.length) {\n return null;\n }\n return (\n <ul className=\"aic-suggestions\" aria-label={moduleMessages.suggestionsLabel}>\n {items.map((question) => (\n <li key={question}>\n <button type=\"button\" className=\"aic-suggestion\" onClick={() => onPick(question)} {...tracking}>\n <span>{question}</span><ArrowIcon />\n </button>\n </li>\n ))}\n </ul>\n );\n}\n\n// Keeps the log scrolled to its end while the visitor reads at the bottom, and lets them scroll up.\n// An empty conversation stays at its top, where its heading is.\nfunction useFollowAnswer(logRef: RefObject<HTMLDivElement | null>, chat: ModuleChat) {\n const following = useRef(true);\n const asked = chat.turns.length + (chat.pendingQuestion ? 1 : 0);\n useEffect(() => {\n following.current = true;\n }, [asked]);\n useEffect(() => {\n const log = logRef.current;\n if (log && asked > 0 && following.current) {\n log.scrollTop = log.scrollHeight;\n }\n });\n return () => {\n const log = logRef.current;\n if (log) {\n following.current = log.scrollHeight - log.scrollTop - log.clientHeight < FOLLOW_DISTANCE;\n }\n };\n}\n\nexport interface ConversationProps extends TurnView {\n chat: ModuleChat;\n intro: string;\n suggestions?: string[];\n}\n\nexport function Conversation({ chat, intro, suggestions, ...view }: ConversationProps) {\n const { moduleMessages } = useAiConnect();\n const logRef = useRef<HTMLDivElement>(null);\n const onScroll = useFollowAnswer(logRef, chat);\n const empty = chat.turns.length === 0 && !chat.pendingQuestion;\n return (\n <div ref={logRef} className=\"aic-log\" role=\"log\" aria-busy={chat.busy} onScroll={onScroll}>\n {empty ? (\n <div className=\"aic-empty\">\n <div className=\"aic-empty-ring\"><ConnectRing live={false} /></div>\n <h3 className=\"aic-intro\">{intro}</h3>\n <Suggestions items={suggestions} onPick={chat.ask} />\n <ConnectStep pending={false} />\n </div>\n ) : null}\n <ol className=\"aic-turns\">\n {chat.turns.map((turn, index) => (\n <li key={index} className=\"aic-turn\">\n <Question text={turn.question} attachments={turn.attachments} unread={turn.unread} />\n <TurnBody turn={turn} view={view} stopped={chat.stopped.includes(index)} linkAllowed={chat.linkAllowed}\n live={chat.busy && index === chat.turns.length - 1} />\n </li>\n ))}\n {chat.pendingQuestion ? (\n <li className=\"aic-turn\">\n <Question text={chat.pendingQuestion.text} attachments={chat.pendingQuestion.attachments} />\n <ConnectStep pending />\n </li>\n ) : null}\n </ol>\n {chat.refusal === PLAN_INACTIVE ? <PlanOffer onActive={chat.retry} /> : null}\n {chat.error && chat.refusal !== PLAN_INACTIVE ? (\n <div className=\"aic-error\" role=\"alert\">\n <p>{chat.error}</p>\n <button type=\"button\" className=\"aic-text-button\" onClick={chat.retry}>{moduleMessages.retry}</button>\n </div>\n ) : null}\n </div>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Conversation.js","sourceRoot":"","sources":["../../../src/modules/parts/Conversation.tsx"],"names":[],"mappings":";AAAA,oGAAoG;AACpG,yGAAyG;AACzG,uGAAuG;AACvG,wGAAwG;AACxG,sGAAsG;AACtG,wGAAwG;AACxG,yCAAyC;AAEzC,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAEnD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA6B,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,M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AU,aACtB,KAAC,QAAQ,IAAC,IAAI,EAAE,IAAI,CAAC,eAAe,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,eAAe,CAAC,WAAW,GAAI,EAC5F,KAAC,WAAW,IAAC,OAAO,SAAG,IACpB,CACN,CAAC,CAAC,CAAC,IAAI,IACL,EACJ,IAAI,CAAC,OAAO,KAAK,aAAa,CAAC,CAAC,CAAC,KAAC,SAAS,IAAC,QAAQ,EAAE,IAAI,CAAC,KAAK,GAAI,CAAC,CAAC,CAAC,IAAI,EAC3E,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,OAAO,KAAK,aAAa,CAAC,CAAC,CAAC,CAC9C,eAAK,SAAS,EAAC,WAAW,EAAC,IAAI,EAAC,OAAO,aACrC,sBAAI,IAAI,CAAC,KAAK,GAAK,EACnB,iBAAQ,IAAI,EAAC,QAAQ,EAAC,SAAS,EAAC,iBAAiB,EAAC,OAAO,EAAE,IAAI,CAAC,KAAK,YAAG,cAAc,CAAC,KAAK,GAAU,IAClG,CACP,CAAC,CAAC,CAAC,IAAI,IACJ,CACP,CAAC;AACJ,CAAC","sourcesContent":["// The conversation of a chat module. Empty, it shows its heading, the suggested questions, then the\n// connection step, under the wallet's ring in the full page mode. The step appears once the first wallet\n// check ends, so it comes last and the heading and the questions the page rendered stay in place. Then\n// each turn shows the visitor's question with its files, the site's tools as they run, the answer as it\n// streams and the site's own result cards, and the last answer's error comes with a way to ask again,\n// or, for a TensorPass account without a plan, the offer to subscribe. The view follows the answer down\n// while the visitor stays at the bottom.\n\nimport { useEffect, useMemo, useRef } from 'react';\nimport type { RefObject } from 'react';\nimport { useAiConnect } from '../../AiConnectProvider.tsx';\nimport { ConnectRing } from '../../ConnectRing.tsx';\nimport type { PreparedAttachment } from '@tensorpass/aiconnect/attachments';\nimport type { ChatTurn } from '../../useAiChat.ts';\nimport type { AiModuleProps } from '../types.ts';\nimport { AnswerText } from './AnswerText.tsx';\nimport { QuestionAttachments } from './attachments/AttachmentRows.tsx';\nimport { ConnectStep } from './ConnectStep.tsx';\nimport { PlanOffer } from './PlanOffer.tsx';\nimport { useActionAttribute } from './moduleAnalytics.ts';\nimport { ArrowIcon, WaveIcon } from './icons.tsx';\nimport { ToolActivityList } from './ToolActivity.tsx';\nimport type { ModuleChat } from './useModuleChat.ts';\n\nexport type TurnView = Pick<AiModuleProps, 'toolLabels' | 'renderToolResults'>;\n\nexport interface TurnBodyProps {\n turn: ChatTurn;\n live: boolean;\n stopped: boolean;\n view: TurnView;\n linkAllowed: (href: string) => boolean;\n // Every file the visitor added up to this turn.\n attachments: PreparedAttachment[];\n}\n\n// The plan gateway's refusal of a TensorPass account without a subscription.\nconst PLAN_INACTIVE = 'plan_inactive';\n\n// How close to the bottom, in pixels, the visitor counts as following the answer.\nconst FOLLOW_DISTANCE = 56;\n\ninterface QuestionProps {\n text: string;\n attachments?: PreparedAttachment[];\n // The images and pages the answering model did not read.\n unread?: number;\n}\n\nfunction Question({ text, attachments, unread }: QuestionProps) {\n const { moduleMessages, state } = useAiConnect();\n const account = state.status === 'connected' ? state.providerName : '';\n return (\n <>\n {attachments?.length ? <QuestionAttachments attachments={attachments} /> : null}\n {text ? (\n <p className=\"aic-question\" dir=\"auto\">\n <span className=\"aic-visually-hidden\">{moduleMessages.question}: </span>{text}\n </p>\n ) : null}\n {unread ? (\n <p className=\"aic-unread\">\n {moduleMessages.unreadPages.replaceAll('{count}', String(unread)).replaceAll('{account}', account)}\n </p>\n ) : null}\n </>\n );\n}\n\n// What a turn shows under its question: the tools as they run, a thinking line until the first\n// words arrive, the answer, whether the visitor stopped it, and the site's own result cards.\nexport function TurnBody({ turn, live, stopped, view, linkAllowed, attachments }: TurnBodyProps) {\n const { moduleMessages } = useAiConnect();\n const toolRunning = turn.tools.some((activity) => activity.result === null);\n const results = view.renderToolResults?.(turn, { attachments });\n return (\n <>\n <ToolActivityList tools={turn.tools} labels={view.toolLabels} />\n {live && !turn.answer && !toolRunning ? (\n <p className=\"aic-thinking\"><WaveIcon size={16} className=\"aic-live-arcs\" />{moduleMessages.thinking}</p>\n ) : null}\n <AnswerText text={turn.answer} streaming={live && Boolean(turn.answer)} linkAllowed={linkAllowed}\n blocked={Boolean(turn.blocked)} />\n {stopped ? <p className=\"aic-stopped\"><i aria-hidden=\"true\" />{moduleMessages.stopped}</p> : null}\n {results ? <div className=\"aic-results\">{results}</div> : null}\n </>\n );\n}\n\nexport function Suggestions({ items, onPick }: { items?: string[]; onPick: (question: string) => void }) {\n const { moduleMessages } = useAiConnect();\n const tracking = useActionAttribute('suggestion');\n if (!items?.length) {\n return null;\n }\n return (\n <ul className=\"aic-suggestions\" aria-label={moduleMessages.suggestionsLabel}>\n {items.map((question) => (\n <li key={question}>\n <button type=\"button\" className=\"aic-suggestion\" onClick={() => onPick(question)} {...tracking}>\n <span>{question}</span><ArrowIcon />\n </button>\n </li>\n ))}\n </ul>\n );\n}\n\n// Keeps the log scrolled to its end while the visitor reads at the bottom, and lets them scroll up.\n// An empty conversation stays at its top, where its heading is.\nfunction useFollowAnswer(logRef: RefObject<HTMLDivElement | null>, chat: ModuleChat) {\n const following = useRef(true);\n const asked = chat.turns.length + (chat.pendingQuestion ? 1 : 0);\n useEffect(() => {\n following.current = true;\n }, [asked]);\n useEffect(() => {\n const log = logRef.current;\n if (log && asked > 0 && following.current) {\n log.scrollTop = log.scrollHeight;\n }\n });\n return () => {\n const log = logRef.current;\n if (log) {\n following.current = log.scrollHeight - log.scrollTop - log.clientHeight < FOLLOW_DISTANCE;\n }\n };\n}\n\n// For each turn, every file the visitor added up to it, oldest first.\nexport function attachmentsSoFar(turns: ChatTurn[]): PreparedAttachment[][] {\n const added: PreparedAttachment[] = [];\n return turns.map((turn) => {\n added.push(...(turn.attachments ?? []));\n return [...added];\n });\n}\n\nexport interface ConversationProps extends TurnView {\n chat: ModuleChat;\n intro: string;\n suggestions?: string[];\n}\n\nexport function Conversation({ chat, intro, suggestions, ...view }: ConversationProps) {\n const { moduleMessages } = useAiConnect();\n const logRef = useRef<HTMLDivElement>(null);\n const onScroll = useFollowAnswer(logRef, chat);\n const attachments = useMemo(() => attachmentsSoFar(chat.turns), [chat.turns]);\n const empty = chat.turns.length === 0 && !chat.pendingQuestion;\n return (\n <div ref={logRef} className=\"aic-log\" role=\"log\" aria-busy={chat.busy} onScroll={onScroll}>\n {empty ? (\n <div className=\"aic-empty\">\n <div className=\"aic-empty-ring\"><ConnectRing live={false} /></div>\n <h3 className=\"aic-intro\">{intro}</h3>\n <Suggestions items={suggestions} onPick={chat.ask} />\n <ConnectStep pending={false} />\n </div>\n ) : null}\n <ol className=\"aic-turns\">\n {chat.turns.map((turn, index) => (\n <li key={index} className=\"aic-turn\">\n <Question text={turn.question} attachments={turn.attachments} unread={turn.unread} />\n <TurnBody turn={turn} view={view} stopped={chat.stopped.includes(index)} linkAllowed={chat.linkAllowed}\n live={chat.busy && index === chat.turns.length - 1} attachments={attachments[index]} />\n </li>\n ))}\n {chat.pendingQuestion ? (\n <li className=\"aic-turn\">\n <Question text={chat.pendingQuestion.text} attachments={chat.pendingQuestion.attachments} />\n <ConnectStep pending />\n </li>\n ) : null}\n </ol>\n {chat.refusal === PLAN_INACTIVE ? <PlanOffer onActive={chat.retry} /> : null}\n {chat.error && chat.refusal !== PLAN_INACTIVE ? (\n <div className=\"aic-error\" role=\"alert\">\n <p>{chat.error}</p>\n <button type=\"button\" className=\"aic-text-button\" onClick={chat.retry}>{moduleMessages.retry}</button>\n </div>\n ) : null}\n </div>\n );\n}\n"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
export function ModuleFoot({ children }) {
|
|
3
|
+
if (children === undefined || children === null || children === false) {
|
|
4
|
+
return null;
|
|
5
|
+
}
|
|
6
|
+
return _jsx("div", { className: "aic-module-foot", children: children });
|
|
7
|
+
}
|
|
8
|
+
//# sourceMappingURL=ModuleFoot.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ModuleFoot.js","sourceRoot":"","sources":["../../../src/modules/parts/ModuleFoot.tsx"],"names":[],"mappings":";AAKA,MAAM,UAAU,UAAU,CAAC,EAAE,QAAQ,EAA4B;IAC/D,IAAI,QAAQ,KAAK,SAAS,IAAI,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,KAAK,EAAE,CAAC;QACtE,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,cAAK,SAAS,EAAC,iBAAiB,YAAE,QAAQ,GAAO,CAAC;AAC3D,CAAC","sourcesContent":["// The site's own line at the foot of a module, such as a credit or a privacy note. A module draws\n// nothing there unless the site gives the line.\n\nimport type { ReactNode } from 'react';\n\nexport function ModuleFoot({ children }: { children?: ReactNode }) {\n if (children === undefined || children === null || children === false) {\n return null;\n }\n return <div className=\"aic-module-foot\">{children}</div>;\n}\n"]}
|
|
@@ -2,14 +2,27 @@
|
|
|
2
2
|
// lists, each made of inline runs (plain, bold, italic, code, link). Models write light Markdown
|
|
3
3
|
// even when asked for plain text, so the module shows it as formatting. A mark the stream has not
|
|
4
4
|
// closed yet stays plain text until its closing half arrives. An image is never drawn, since it would
|
|
5
|
-
// load by itself: its description stays as text. A
|
|
6
|
-
//
|
|
5
|
+
// load by itself: its description stays as text. A bare web address becomes a link labelled with its
|
|
6
|
+
// host and path, and a link inside bold or italic text stays a link. A link the conversation's guards
|
|
7
|
+
// do not allow stays as its words.
|
|
7
8
|
import { leadsToSitePage } from '@tensorpass/aiconnect';
|
|
8
|
-
|
|
9
|
+
// A bare address ends before a space, a closing bracket, a quote or an asterisk, and never on the
|
|
10
|
+
// punctuation that closes a sentence: the same address the answer guard reads (LINK_TARGET in core).
|
|
11
|
+
const BARE_ADDRESS = String.raw `[^\s)\]>"'\x60*]*[^\s)\]>"'\x60*.,;:!?]`;
|
|
12
|
+
const INLINE = new RegExp([
|
|
13
|
+
String.raw `\*\*([^*\n]+)\*\*`,
|
|
14
|
+
String.raw `\x60([^\x60\n]+)\x60`,
|
|
15
|
+
String.raw `!\[([^\]\n]*)\]\([^)\s]+\)`,
|
|
16
|
+
String.raw `\[([^\]\n]+)\]\(([^)\s]+)\)`,
|
|
17
|
+
String.raw `\b((?:https?:\/\/|www\.)${BARE_ADDRESS})`,
|
|
18
|
+
String.raw `\*([^*\s][^*\n]*?)\*`,
|
|
19
|
+
].join('|'), 'gi');
|
|
9
20
|
const BULLET = /^\s*[-*•]\s+(.*)$/;
|
|
10
21
|
const NUMBERED = /^\s*\d+[.)]\s+(.*)$/;
|
|
11
22
|
const HEADING = /^\s*#{1,6}\s+(.*)$/;
|
|
12
23
|
const WEB_OR_MAIL = /^(https?:\/\/|mailto:)/i;
|
|
24
|
+
const SCHEME = /^https?:\/\//i;
|
|
25
|
+
const LABEL_LENGTH = 40;
|
|
13
26
|
// Whether `href` stays on the page's own site, read as the conversation's guards read it.
|
|
14
27
|
export function onSite(href) {
|
|
15
28
|
return leadsToSitePage(href, globalThis.location?.origin);
|
|
@@ -18,10 +31,20 @@ export function onSite(href) {
|
|
|
18
31
|
function opensSafely(href) {
|
|
19
32
|
return WEB_OR_MAIL.test(href) || onSite(href);
|
|
20
33
|
}
|
|
34
|
+
// A bare address as a reader scans it: the host without www and the path, cut at LABEL_LENGTH.
|
|
35
|
+
function addressLabel(href) {
|
|
36
|
+
const url = new URL(href);
|
|
37
|
+
const label = `${url.host.replace(/^www\./i, '')}${url.pathname.replace(/\/$/, '')}`;
|
|
38
|
+
return label.length > LABEL_LENGTH ? `${label.slice(0, LABEL_LENGTH - 1)}…` : label;
|
|
39
|
+
}
|
|
40
|
+
function addressRun(address) {
|
|
41
|
+
const href = SCHEME.test(address) ? address : `https://${address}`;
|
|
42
|
+
return URL.canParse(href) ? { kind: 'link', text: addressLabel(href), href } : { kind: 'text', text: address };
|
|
43
|
+
}
|
|
21
44
|
function markRun(match) {
|
|
22
|
-
const [whole, strong, code, imageText, linkText, href, em] = match;
|
|
45
|
+
const [whole, strong, code, imageText, linkText, href, address, em] = match;
|
|
23
46
|
if (strong !== undefined) {
|
|
24
|
-
return { kind: 'strong',
|
|
47
|
+
return { kind: 'strong', runs: inlineRuns(strong) };
|
|
25
48
|
}
|
|
26
49
|
if (code !== undefined) {
|
|
27
50
|
return { kind: 'code', text: code };
|
|
@@ -32,7 +55,10 @@ function markRun(match) {
|
|
|
32
55
|
if (linkText !== undefined) {
|
|
33
56
|
return opensSafely(href) ? { kind: 'link', text: linkText, href } : { kind: 'text', text: whole };
|
|
34
57
|
}
|
|
35
|
-
|
|
58
|
+
if (address !== undefined) {
|
|
59
|
+
return addressRun(address);
|
|
60
|
+
}
|
|
61
|
+
return { kind: 'em', runs: inlineRuns(em) };
|
|
36
62
|
}
|
|
37
63
|
export function inlineRuns(text) {
|
|
38
64
|
const runs = [];
|
|
@@ -82,9 +108,15 @@ function addLine(blocks, line, afterBlank) {
|
|
|
82
108
|
}
|
|
83
109
|
blocks.push({ kind: 'paragraph', runs: inlineRuns(line) });
|
|
84
110
|
}
|
|
85
|
-
// The blocks with every link the guards do not allow turned back into its words
|
|
111
|
+
// The blocks with every link the guards do not allow turned back into its words, inside bold and
|
|
112
|
+
// italic text too.
|
|
86
113
|
export function keepAllowedLinks(blocks, allowed) {
|
|
87
|
-
const runs = (items) => items.map((run) =>
|
|
114
|
+
const runs = (items) => items.map((run) => {
|
|
115
|
+
if (run.kind === 'strong' || run.kind === 'em') {
|
|
116
|
+
return { ...run, runs: runs(run.runs) };
|
|
117
|
+
}
|
|
118
|
+
return run.kind === 'link' && !allowed(run.href) ? { kind: 'text', text: run.text } : run;
|
|
119
|
+
});
|
|
88
120
|
return blocks.map((block) => (block.kind === 'list'
|
|
89
121
|
? { ...block, items: block.items.map(runs) }
|
|
90
122
|
: { ...block, runs: runs(block.runs) }));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"answerMarkdown.js","sourceRoot":"","sources":["../../../src/modules/parts/answerMarkdown.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,iGAAiG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,CAAC,IAAI,EAAE,EAAE,CAAC;YACjB,UAAU,GAAG,IAAI,CAAC;YAClB,SAAS;QACX,CAAC;QACD,OAAO,CAAC,MAAM,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC;QAClC,UAAU,GAAG,KAAK,CAAC;IACrB,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// The answer's text as the blocks a module draws: paragraphs, headings, and bulleted or numbered\n// lists, each made of inline runs (plain, bold, italic, code, link). Models write light Markdown\n// even when asked for plain text, so the module shows it as formatting. A mark the stream has not\n// closed yet stays plain text until its closing half arrives. An image is never drawn, since it would\n// load by itself: its description stays as text. A link the conversation's guards do not allow stays\n// as its words.\n\nimport { leadsToSitePage } from '@tensorpass/aiconnect';\n\nexport type InlineRun =\n | { kind: 'text'; text: string }\n | { kind: 'strong'; text: string }\n | { kind: 'em'; text: string }\n | { kind: 'code'; text: string }\n | { kind: 'link'; text: string; href: string };\n\nexport type AnswerBlock =\n | { kind: 'paragraph'; runs: InlineRun[] }\n | { kind: 'heading'; runs: InlineRun[] }\n | { kind: 'list'; ordered: boolean; items: InlineRun[][] };\n\nconst INLINE = /\\*\\*([^*\\n]+)\\*\\*|`([^`\\n]+)`|!\\[([^\\]\\n]*)\\]\\([^)\\s]+\\)|\\[([^\\]\\n]+)\\]\\(([^)\\s]+)\\)|\\*([^*\\s][^*\\n]*?)\\*/g;\nconst BULLET = /^\\s*[-*•]\\s+(.*)$/;\nconst NUMBERED = /^\\s*\\d+[.)]\\s+(.*)$/;\nconst HEADING = /^\\s*#{1,6}\\s+(.*)$/;\nconst WEB_OR_MAIL = /^(https?:\\/\\/|mailto:)/i;\n\n// Whether `href` stays on the page's own site, read as the conversation's guards read it.\nexport function onSite(href: string): boolean {\n return leadsToSitePage(href, globalThis.location?.origin);\n}\n\n// Links open only to the web, to mail, or to a page of the site itself.\nfunction opensSafely(href: string): boolean {\n return WEB_OR_MAIL.test(href) || onSite(href);\n}\n\nfunction markRun(match: RegExpExecArray): InlineRun {\n const [whole, strong, code, imageText, linkText, href, em] = match;\n if (strong !== undefined) {\n return { kind: 'strong', text: strong };\n }\n if (code !== undefined) {\n return { kind: 'code', text: code };\n }\n if (imageText !== undefined) {\n return { kind: 'text', text: imageText };\n }\n if (linkText !== undefined) {\n return opensSafely(href) ? { kind: 'link', text: linkText, href } : { kind: 'text', text: whole };\n }\n return { kind: 'em', text: em };\n}\n\nexport function inlineRuns(text: string): InlineRun[] {\n const runs: InlineRun[] = [];\n let cursor = 0;\n for (const match of text.matchAll(INLINE)) {\n if (match.index > cursor) {\n runs.push({ kind: 'text', text: text.slice(cursor, match.index) });\n }\n runs.push(markRun(match));\n cursor = match.index + match[0].length;\n }\n if (cursor < text.length) {\n runs.push({ kind: 'text', text: text.slice(cursor) });\n }\n return runs;\n}\n\ninterface ListItemLine {\n ordered: boolean;\n text: string;\n}\n\nfunction listItem(line: string): ListItemLine | null {\n const bullet = BULLET.exec(line);\n if (bullet) {\n return { ordered: false, text: bullet[1] };\n }\n const numbered = NUMBERED.exec(line);\n return numbered ? { ordered: true, text: numbered[1] } : null;\n}\n\n// Adds a line to the blocks read so far: a list item joins the list above it, a heading stands\n// alone, and other lines join the paragraph above them until a blank line ends it.\nfunction addLine(blocks: AnswerBlock[], line: string, afterBlank: boolean): void {\n const last = blocks.at(-1);\n const item = listItem(line);\n if (item) {\n if (last?.kind === 'list' && last.ordered === item.ordered) {\n last.items.push(inlineRuns(item.text));\n } else {\n blocks.push({ kind: 'list', ordered: item.ordered, items: [inlineRuns(item.text)] });\n }\n return;\n }\n const heading = HEADING.exec(line);\n if (heading) {\n blocks.push({ kind: 'heading', runs: inlineRuns(heading[1]) });\n return;\n }\n if (last?.kind === 'paragraph' && !afterBlank) {\n last.runs.push({ kind: 'text', text: '\\n' }, ...inlineRuns(line));\n return;\n }\n blocks.push({ kind: 'paragraph', runs: inlineRuns(line) });\n}\n\n// The blocks with every link the guards do not allow turned back into its words.\nexport function keepAllowedLinks(blocks: AnswerBlock[], allowed: (href: string) => boolean): AnswerBlock[] {\n const runs = (items: InlineRun[]) => items.map((run): InlineRun => (\n run.kind === 'link' && !allowed(run.href) ? { kind: 'text', text: run.text } : run\n ));\n return blocks.map((block) => (block.kind === 'list'\n ? { ...block, items: block.items.map(runs) }\n : { ...block, runs: runs(block.runs) }));\n}\n\nexport function answerBlocks(text: string): AnswerBlock[] {\n const blocks: AnswerBlock[] = [];\n let afterBlank = true;\n for (const line of text.split('\\n')) {\n if (!line.trim()) {\n afterBlank = true;\n continue;\n }\n addLine(blocks, line, afterBlank);\n afterBlank = false;\n }\n return blocks;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"answerMarkdown.js","sourceRoot":"","sources":["../../../src/modules/parts/answerMarkdown.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,iGAAiG;AACjG,kGAAkG;AAClG,sGAAsG;AACtG,qGAAqG;AACrG,sGAAsG;AACtG,mCAAmC;AAEnC,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAcxD,kGAAkG;AAClG,qGAAqG;AACrG,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAA,yCAAyC,CAAC;AACzE,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC;IACxB,MAAM,CAAC,GAAG,CAAA,mBAAmB;IAC7B,MAAM,CAAC,GAAG,CAAA,sBAAsB;IAChC,MAAM,CAAC,GAAG,CAAA,4BAA4B;IACtC,MAAM,CAAC,GAAG,CAAA,6BAA6B;IACvC,MAAM,CAAC,GAAG,CAAA,2BAA2B,YAAY,GAAG;IACpD,MAAM,CAAC,GAAG,CAAA,sBAAsB;CACjC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC;AACnB,MAAM,MAAM,GAAG,mBAAmB,CAAC;AACnC,MAAM,QAAQ,GAAG,qBAAqB,CAAC;AACvC,MAAM,OAAO,GAAG,oBAAoB,CAAC;AACrC,MAAM,WAAW,GAAG,yBAAyB,CAAC;A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a module draws: paragraphs, headings, and bulleted or numbered\n// lists, each made of inline runs (plain, bold, italic, code, link). Models write light Markdown\n// even when asked for plain text, so the module shows it as formatting. A mark the stream has not\n// closed yet stays plain text until its closing half arrives. An image is never drawn, since it would\n// load by itself: its description stays as text. A bare web address becomes a link labelled with its\n// host and path, and a link inside bold or italic text stays a link. A link the conversation's guards\n// do not allow stays as its words.\n\nimport { leadsToSitePage } from '@tensorpass/aiconnect';\n\nexport type InlineRun =\n | { kind: 'text'; text: string }\n | { kind: 'strong'; runs: InlineRun[] }\n | { kind: 'em'; runs: InlineRun[] }\n | { kind: 'code'; text: string }\n | { kind: 'link'; text: string; href: string };\n\nexport type AnswerBlock =\n | { kind: 'paragraph'; runs: InlineRun[] }\n | { kind: 'heading'; runs: InlineRun[] }\n | { kind: 'list'; ordered: boolean; items: InlineRun[][] };\n\n// A bare address ends before a space, a closing bracket, a quote or an asterisk, and never on the\n// punctuation that closes a sentence: the same address the answer guard reads (LINK_TARGET in core).\nconst BARE_ADDRESS = String.raw`[^\\s)\\]>\"'\\x60*]*[^\\s)\\]>\"'\\x60*.,;:!?]`;\nconst INLINE = new RegExp([\n String.raw`\\*\\*([^*\\n]+)\\*\\*`,\n String.raw`\\x60([^\\x60\\n]+)\\x60`,\n String.raw`!\\[([^\\]\\n]*)\\]\\([^)\\s]+\\)`,\n String.raw`\\[([^\\]\\n]+)\\]\\(([^)\\s]+)\\)`,\n String.raw`\\b((?:https?:\\/\\/|www\\.)${BARE_ADDRESS})`,\n String.raw`\\*([^*\\s][^*\\n]*?)\\*`,\n].join('|'), 'gi');\nconst BULLET = /^\\s*[-*•]\\s+(.*)$/;\nconst NUMBERED = /^\\s*\\d+[.)]\\s+(.*)$/;\nconst HEADING = /^\\s*#{1,6}\\s+(.*)$/;\nconst WEB_OR_MAIL = /^(https?:\\/\\/|mailto:)/i;\nconst SCHEME = /^https?:\\/\\//i;\nconst LABEL_LENGTH = 40;\n\n// Whether `href` stays on the page's own site, read as the conversation's guards read it.\nexport function onSite(href: string): boolean {\n return leadsToSitePage(href, globalThis.location?.origin);\n}\n\n// Links open only to the web, to mail, or to a page of the site itself.\nfunction opensSafely(href: string): boolean {\n return WEB_OR_MAIL.test(href) || onSite(href);\n}\n\n// A bare address as a reader scans it: the host without www and the path, cut at LABEL_LENGTH.\nfunction addressLabel(href: string): string {\n const url = new URL(href);\n const label = `${url.host.replace(/^www\\./i, '')}${url.pathname.replace(/\\/$/, '')}`;\n return label.length > LABEL_LENGTH ? `${label.slice(0, LABEL_LENGTH - 1)}…` : label;\n}\n\nfunction addressRun(address: string): InlineRun {\n const href = SCHEME.test(address) ? address : `https://${address}`;\n return URL.canParse(href) ? { kind: 'link', text: addressLabel(href), href } : { kind: 'text', text: address };\n}\n\nfunction markRun(match: RegExpExecArray): InlineRun {\n const [whole, strong, code, imageText, linkText, href, address, em] = match;\n if (strong !== undefined) {\n return { kind: 'strong', runs: inlineRuns(strong) };\n }\n if (code !== undefined) {\n return { kind: 'code', text: code };\n }\n if (imageText !== undefined) {\n return { kind: 'text', text: imageText };\n }\n if (linkText !== undefined) {\n return opensSafely(href) ? { kind: 'link', text: linkText, href } : { kind: 'text', text: whole };\n }\n if (address !== undefined) {\n return addressRun(address);\n }\n return { kind: 'em', runs: inlineRuns(em) };\n}\n\nexport function inlineRuns(text: string): InlineRun[] {\n const runs: InlineRun[] = [];\n let cursor = 0;\n for (const match of text.matchAll(INLINE)) {\n if (match.index > cursor) {\n runs.push({ kind: 'text', text: text.slice(cursor, match.index) });\n }\n runs.push(markRun(match));\n cursor = match.index + match[0].length;\n }\n if (cursor < text.length) {\n runs.push({ kind: 'text', text: text.slice(cursor) });\n }\n return runs;\n}\n\ninterface ListItemLine {\n ordered: boolean;\n text: string;\n}\n\nfunction listItem(line: string): ListItemLine | null {\n const bullet = BULLET.exec(line);\n if (bullet) {\n return { ordered: false, text: bullet[1] };\n }\n const numbered = NUMBERED.exec(line);\n return numbered ? { ordered: true, text: numbered[1] } : null;\n}\n\n// Adds a line to the blocks read so far: a list item joins the list above it, a heading stands\n// alone, and other lines join the paragraph above them until a blank line ends it.\nfunction addLine(blocks: AnswerBlock[], line: string, afterBlank: boolean): void {\n const last = blocks.at(-1);\n const item = listItem(line);\n if (item) {\n if (last?.kind === 'list' && last.ordered === item.ordered) {\n last.items.push(inlineRuns(item.text));\n } else {\n blocks.push({ kind: 'list', ordered: item.ordered, items: [inlineRuns(item.text)] });\n }\n return;\n }\n const heading = HEADING.exec(line);\n if (heading) {\n blocks.push({ kind: 'heading', runs: inlineRuns(heading[1]) });\n return;\n }\n if (last?.kind === 'paragraph' && !afterBlank) {\n last.runs.push({ kind: 'text', text: '\\n' }, ...inlineRuns(line));\n return;\n }\n blocks.push({ kind: 'paragraph', runs: inlineRuns(line) });\n}\n\n// The blocks with every link the guards do not allow turned back into its words, inside bold and\n// italic text too.\nexport function keepAllowedLinks(blocks: AnswerBlock[], allowed: (href: string) => boolean): AnswerBlock[] {\n const runs = (items: InlineRun[]): InlineRun[] => items.map((run): InlineRun => {\n if (run.kind === 'strong' || run.kind === 'em') {\n return { ...run, runs: runs(run.runs) };\n }\n return run.kind === 'link' && !allowed(run.href) ? { kind: 'text', text: run.text } : run;\n });\n return blocks.map((block) => (block.kind === 'list'\n ? { ...block, items: block.items.map(runs) }\n : { ...block, runs: runs(block.runs) }));\n}\n\nexport function answerBlocks(text: string): AnswerBlock[] {\n const blocks: AnswerBlock[] = [];\n let afterBlank = true;\n for (const line of text.split('\\n')) {\n if (!line.trim()) {\n afterBlank = true;\n continue;\n }\n addLine(blocks, line, afterBlank);\n afterBlank = false;\n }\n return blocks;\n}\n"]}
|
package/dist/modules/types.d.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import type { ReactNode, Ref } from 'react';
|
|
2
2
|
import type { GuardPolicy, ToolSource } from '@tensorpass/aiconnect';
|
|
3
|
-
import type { AttachmentPolicy } from '@tensorpass/aiconnect/attachments';
|
|
3
|
+
import type { AttachmentPolicy, PreparedAttachment } from '@tensorpass/aiconnect/attachments';
|
|
4
4
|
import type { ChatTurn } from '../useAiChat.ts';
|
|
5
|
+
export interface ToolResultsContext {
|
|
6
|
+
attachments: PreparedAttachment[];
|
|
7
|
+
}
|
|
5
8
|
export interface AiModuleHandle {
|
|
6
9
|
ask: (question: string) => void;
|
|
7
10
|
}
|
|
@@ -16,7 +19,8 @@ export interface AiModuleProps {
|
|
|
16
19
|
toolLabels?: Record<string, string>;
|
|
17
20
|
guards?: GuardPolicy;
|
|
18
21
|
attachments?: AttachmentPolicy;
|
|
19
|
-
renderToolResults?: (turn: ChatTurn) => ReactNode;
|
|
22
|
+
renderToolResults?: (turn: ChatTurn, context: ToolResultsContext) => ReactNode;
|
|
23
|
+
footer?: ReactNode;
|
|
20
24
|
analytics?: string;
|
|
21
25
|
ref?: Ref<AiModuleHandle>;
|
|
22
26
|
className?: string;
|
package/dist/modules/types.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// The props every interface module shares: what the visitor's AI is told, the site's tools, the copy
|
|
2
2
|
// the site sets for its own voice, the guards it tunes, the files and voice it takes, how the site draws
|
|
3
|
-
// its tool results,
|
|
4
|
-
// how they open.
|
|
3
|
+
// its tool results, the site's own line under the question box, and the handle its own controls ask
|
|
4
|
+
// through. The modules that float over the page add how they open.
|
|
5
5
|
export {};
|
|
6
6
|
//# sourceMappingURL=types.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/modules/types.ts"],"names":[],"mappings":"AAAA,qGAAqG;AACrG,yGAAyG;AACzG,
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/modules/types.ts"],"names":[],"mappings":"AAAA,qGAAqG;AACrG,yGAAyG;AACzG,oGAAoG;AACpG,mEAAmE","sourcesContent":["// The props every interface module shares: what the visitor's AI is told, the site's tools, the copy\n// the site sets for its own voice, the guards it tunes, the files and voice it takes, how the site draws\n// its tool results, the site's own line under the question box, and the handle its own controls ask\n// through. The modules that float over the page add how they open.\n\nimport type { ReactNode, Ref } from 'react';\nimport type { GuardPolicy, ToolSource } from '@tensorpass/aiconnect';\nimport type { AttachmentPolicy, PreparedAttachment } from '@tensorpass/aiconnect/attachments';\nimport type { ChatTurn } from '../useAiChat.ts';\n\n// What the conversation holds when a turn's results are drawn.\nexport interface ToolResultsContext {\n // Every file the visitor added up to this turn, oldest first, as prepared for the model: a card that\n // sends a request with the visitor's photos reads them here, whichever question carried them.\n attachments: PreparedAttachment[];\n}\n\n// What a site's own controls can do with a module through its `ref`.\nexport interface AiModuleHandle {\n // Sends the question as if the visitor had typed it in the module. A module that floats opens first.\n ask: (question: string) => void;\n}\n\nexport interface AiModuleProps {\n // What the visitor's AI is told about the site and its tools before the first question.\n system: string;\n // The site's tools. Give `mcp` instead to read them from the site's MCP server.\n tools?: ToolSource;\n // The address of the site's MCP server, such as `/api/mcp`. The module connects to it when the\n // first question is sent.\n mcp?: string;\n // The heading of the module. The built in copy says \"Ask AI\" (or \"AI mode\" for the full page).\n title?: string;\n // The heading of an empty conversation.\n intro?: string;\n placeholder?: string;\n // Questions the visitor can send with one click before asking their own.\n suggestions?: string[];\n // A plain name for each tool, shown while it runs in place of the tool's own name.\n toolLabels?: Record<string, string>;\n // The site's own values for the guards the conversation runs under: its internal names, the hosts\n // and addresses its answers may give, the tools it shows, its safe answer. The guards run with their\n // defaults without it.\n guards?: GuardPolicy;\n // The files and the voice the visitor may add to a question: images, PDFs and text files dropped, pasted\n // or attached, and dictation into the question field. Leave it out to keep the question box text only;\n // `{}` turns on every kind with the default caps.\n attachments?: AttachmentPolicy;\n // Draws a turn's tool results the site's way, such as its own result cards, under the answer.\n // The turn holds the answer and every tool call with its raw result.\n renderToolResults?: (turn: ChatTurn, context: ToolResultsContext) => ReactNode;\n // The site's own line under the question box, such as a credit or a privacy note. Nothing is drawn\n // without it.\n footer?: ReactNode;\n // A name for the module's actions in the site's click analytics: the install and connect buttons, the\n // send button and the suggestions carry `data-analytics` with it, such as `chat-install` or `chat-send`.\n analytics?: string;\n // Receives the module's handle, for a field or a button of the site's own that sends the module a\n // question, such as an ask bar in the page's opening that opens the side panel.\n ref?: Ref<AiModuleHandle>;\n className?: string;\n}\n\nexport interface AiOverlayProps {\n // Whether the module is open, when the site controls it. Leave it out to let the module keep it.\n open?: boolean;\n // Whether the module starts open, when the module keeps the state itself.\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n // Hides the module's own button, for a site that opens the module from a button of its own.\n hideLauncher?: boolean;\n // The text of the module's own button.\n launcherLabel?: string;\n}\n"]}
|
package/dist/styles.css
CHANGED
|
@@ -871,6 +871,25 @@
|
|
|
871
871
|
margin: 0;
|
|
872
872
|
padding: 8px 14px 14px;
|
|
873
873
|
}
|
|
874
|
+
.aic-composer:has(~ .aic-module-foot) {
|
|
875
|
+
padding-bottom: 6px;
|
|
876
|
+
}
|
|
877
|
+
.aic-module-foot {
|
|
878
|
+
flex: none;
|
|
879
|
+
margin: 0;
|
|
880
|
+
padding: 0 14px 10px;
|
|
881
|
+
color: var(--aic-muted);
|
|
882
|
+
font-size: 12px;
|
|
883
|
+
line-height: 1.4;
|
|
884
|
+
text-align: center;
|
|
885
|
+
}
|
|
886
|
+
.aic-module-foot a {
|
|
887
|
+
color: inherit;
|
|
888
|
+
}
|
|
889
|
+
.aic-search .aic-module-foot {
|
|
890
|
+
padding: 0;
|
|
891
|
+
text-align: start;
|
|
892
|
+
}
|
|
874
893
|
.aic-field {
|
|
875
894
|
display: flex;
|
|
876
895
|
align-items: flex-end;
|
|
@@ -1161,6 +1180,13 @@
|
|
|
1161
1180
|
.aic-page .aic-composer {
|
|
1162
1181
|
padding: 8px 12px max(12px, env(safe-area-inset-bottom));
|
|
1163
1182
|
}
|
|
1183
|
+
.aic-composer:has(~ .aic-module-foot) {
|
|
1184
|
+
padding-bottom: 6px;
|
|
1185
|
+
}
|
|
1186
|
+
.aic-panel .aic-module-foot,
|
|
1187
|
+
.aic-popup .aic-module-foot {
|
|
1188
|
+
padding: 0 12px max(10px, env(safe-area-inset-bottom));
|
|
1189
|
+
}
|
|
1164
1190
|
}
|
|
1165
1191
|
|
|
1166
1192
|
/* src/modules/styles/search.css */
|
package/dist/useAiChat.js
CHANGED
|
@@ -10,26 +10,35 @@ import { createChatGuard, GuardStop, runConversation } from '@tensorpass/aiconne
|
|
|
10
10
|
import { partsForModel, UNKNOWN_READS } from '@tensorpass/aiconnect/attachments';
|
|
11
11
|
import { useAiConnect } from "./AiConnectProvider.js";
|
|
12
12
|
import { failedAnswerText } from "./messages.js";
|
|
13
|
+
import { appendAnswer } from "./answerSteps.js";
|
|
13
14
|
import { withinRequestBudget } from "./transcriptBudget.js";
|
|
14
15
|
// Before the first question there is no answer, so no link to draw.
|
|
15
16
|
const NO_LINKS = () => false;
|
|
16
17
|
function updateLast(turns, change) {
|
|
17
18
|
return [...turns.slice(0, -1), change(turns.at(-1))];
|
|
18
19
|
}
|
|
19
|
-
// Writes the conversation's progress into the last turn, as the answer streams and the tools run.
|
|
20
|
-
//
|
|
21
|
-
// own turn.
|
|
20
|
+
// Writes the conversation's progress into the last turn, as the answer streams and the tools run. The
|
|
21
|
+
// words the model writes after a tool's result start a paragraph of their own. A conversation that was
|
|
22
|
+
// stopped writes nothing more, so a question sent right after it keeps its own turn.
|
|
22
23
|
function lastTurnHooks(setTurns, signal, guard) {
|
|
23
24
|
const updateTurn = (change) => {
|
|
24
25
|
if (!signal.aborted) {
|
|
25
26
|
setTurns((current) => updateLast(current, change));
|
|
26
27
|
}
|
|
27
28
|
};
|
|
29
|
+
let newStep = false;
|
|
28
30
|
return {
|
|
29
|
-
onText: (delta) =>
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
31
|
+
onText: (delta) => {
|
|
32
|
+
const opensStep = newStep;
|
|
33
|
+
newStep = false;
|
|
34
|
+
updateTurn((turn) => ({ ...turn, answer: appendAnswer(turn.answer, delta, opensStep) }));
|
|
35
|
+
},
|
|
36
|
+
onToolCall: (call) => {
|
|
37
|
+
newStep = true;
|
|
38
|
+
updateTurn((turn) => ({
|
|
39
|
+
...turn, tools: [...turn.tools, { call, result: null, visible: guard.toolVisible(call.name) }],
|
|
40
|
+
}));
|
|
41
|
+
},
|
|
33
42
|
onToolResult: (call, result) => updateTurn((turn) => ({
|
|
34
43
|
...turn, tools: turn.tools.map((activity) => (activity.call.id === call.id ? { ...activity, result } : activity)),
|
|
35
44
|
})),
|
package/dist/useAiChat.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAiChat.js","sourceRoot":"","sources":["../src/useAiChat.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,gGAAgG;AAChG,mGAAmG;AACnG,gGAAgG;AAChG,6FAA6F;AAC7F,yGAAyG;AACzG,sFAAsF;AAEtF,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEtD,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAKpF,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAEjF,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAyB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAqC5D,oEAAoE;AACpE,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC;AAE7B,SAAS,UAAU,CAAC,KAAiB,EAAE,MAAoC;IACzE,OAAO,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAE,CAAC,CAAC,CAAC;AACxD,CAAC;AAED,kGAAkG;AAClG,mGAAmG;AACnG,YAAY;AACZ,SAAS,aAAa,CACpB,QA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tools. The site renders `turns`:\n// what the visitor asked, the answer as it streams, and every tool call with its raw result, so\n// tool results can be shown as the site's own cards. `stop` ends the answer in the wallet too, and\n// the turn keeps the text streamed so far. Every conversation runs under its guards, tuned with\n// `guards`: a question or an answer they stop shows the site's safe answer in its place, and\n// `linkAllowed` tells the interface which links of an answer it may draw. A question may carry the files\n// the visitor attached, which reach the model as the account that answers reads them.\n\nimport { useCallback, useRef, useState } from 'react';\nimport type { Dispatch, RefObject, SetStateAction } from 'react';\nimport { createChatGuard, GuardStop, runConversation } from '@tensorpass/aiconnect';\nimport type {\n ChatGuard, ChatMessage, ConnectionState, ContentPart, ConversationHooks, GuardPolicy, ProviderSession, ToolCall,\n ToolSource,\n} from '@tensorpass/aiconnect';\nimport { partsForModel, UNKNOWN_READS } from '@tensorpass/aiconnect/attachments';\nimport type { PreparedAttachment } from '@tensorpass/aiconnect/attachments';\nimport { useAiConnect } from './AiConnectProvider.tsx';\nimport { failedAnswerText } from './messages.ts';\nimport type { ModuleMessages } from './messages.ts';\nimport { withinRequestBudget } from './transcriptBudget.ts';\n\nexport interface ToolActivity {\n call: ToolCall;\n result: string | null;\n // False for a tool the site keeps out of the `visibleTools` of its guards, whose activity the\n // interface does not show.\n visible?: boolean;\n}\n\n// A question as the visitor sends it: the text they typed or dictated and the files they attached.\nexport interface AskedQuestion {\n text: string;\n attachments: PreparedAttachment[];\n}\n\nexport interface ChatTurn {\n question: string;\n // The files the visitor attached to the question.\n attachments?: PreparedAttachment[];\n // The attached images and pages the answering model does not read, such as images for a text only model.\n unread?: number;\n answer: string;\n tools: ToolActivity[];\n // The guard stopped the question before it left the page, or the answer as it came; `answer` then\n // holds the site's safe answer.\n blocked?: 'question' | 'answer';\n}\n\nexport interface UseAiChatOptions {\n system: string;\n tools?: ToolSource;\n // The site's own values for the guards every conversation runs under, read at the conversation's first\n // question.\n guards?: GuardPolicy;\n}\n\n// Before the first question there is no answer, so no link to draw.\nconst NO_LINKS = () => false;\n\nfunction updateLast(turns: ChatTurn[], change: (turn: ChatTurn) => ChatTurn): ChatTurn[] {\n return [...turns.slice(0, -1), change(turns.at(-1)!)];\n}\n\n// Writes the conversation's progress into the last turn, as the answer streams and the tools run.\n// A conversation that was stopped writes nothing more, so a question sent right after it keeps its\n// own turn.\nfunction lastTurnHooks(\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>, signal: AbortSignal, guard: ChatGuard,\n): ConversationHooks {\n const updateTurn = (change: (turn: ChatTurn) => ChatTurn) => {\n if (!signal.aborted) {\n setTurns((current) => updateLast(current, change));\n }\n };\n return {\n onText: (delta) => updateTurn((turn) => ({ ...turn, answer: turn.answer + delta })),\n onToolCall: (call) => updateTurn((turn) => ({\n ...turn, tools: [...turn.tools, { call, result: null, visible: guard.toolVisible(call.name) }],\n })),\n onToolResult: (call, result) => updateTurn((turn) => ({\n ...turn, tools: turn.tools.map((activity) => (activity.call.id === call.id ? { ...activity, result } : activity)),\n })),\n };\n}\n\ninterface QuestionRun {\n session: ProviderSession;\n tools?: ToolSource;\n guard: ChatGuard;\n transcript: RefObject<ChatMessage[]>;\n asked: ChatMessage;\n controller: AbortController;\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>;\n}\n\n// Runs one question on the visitor's model and keeps the exchange in the transcript. A question that\n// was stopped or failed adds nothing to it.\nasync function answerQuestion({ session, tools, guard, transcript, asked, controller, setTurns }: QuestionRun) {\n const added = await runConversation({\n session,\n tools,\n guard,\n messages: withinRequestBudget([...transcript.current, asked]),\n signal: controller.signal,\n ...lastTurnHooks(setTurns, controller.signal, guard),\n });\n transcript.current = [...transcript.current, asked, ...added];\n}\n\n// Shows the safe answer in place of what a guard stopped: the site's own, or the module's words for a\n// stopped question or answer. A stopped answer stays in the transcript as the safe answer, so the model\n// reads the exchange without the text it should not have written; a stopped question never reaches it.\nfunction showStop(stop: GuardStop, run: QuestionRun, copy: ModuleMessages) {\n const safeAnswer = run.guard.policy.safeAnswer ?? (stop.stage === 'question' ? copy.guardQuestion : copy.guardAnswer);\n run.setTurns((current) => updateLast(current, (turn) => ({ ...turn, answer: safeAnswer, blocked: stop.stage })));\n if (stop.stage === 'answer') {\n run.transcript.current = [...run.transcript.current, run.asked, { role: 'assistant', content: safeAnswer }];\n }\n}\n\n// An answer that failed: its words, and the code the provider gave its refusal, such as `plan_inactive`\n// for a TensorPass account without a plan, by which the module offers what fits.\nexport interface AnswerFailure {\n text: string;\n code: string | null;\n}\n\n// A web account's 429 keeps the provider's own message, such as the gateway's limit of requests from one\n// site, since the module's words for a 429 send the visitor to another account in the wallet.\nfunction answerFailure(reason: unknown, connection: Extract<ConnectionState, { status: 'connected' }>,\n copy: ModuleMessages): AnswerFailure {\n const { status, code } = (reason ?? {}) as { status?: unknown; code?: unknown };\n const text = connection.account && status === 429 && reason instanceof Error\n ? reason.message\n : failedAnswerText(reason, connection.providerName, copy);\n return { text, code: typeof code === 'string' ? code : null };\n}\n\n// What a question's run needs from the hook besides the question.\ninterface SendContext {\n connection: Extract<ConnectionState, { status: 'connected' }>;\n guard: ChatGuard;\n tools?: ToolSource;\n transcript: RefObject<ChatMessage[]>;\n abort: RefObject<AbortController | null>;\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>;\n setFailure: Dispatch<SetStateAction<AnswerFailure | null>>;\n setBusy: Dispatch<SetStateAction<boolean>>;\n copy: ModuleMessages;\n}\n\n// The visitor's message: the text, then the attachments as the account that answers reads them.\nasync function askedMessage(question: AskedQuestion, context: SendContext): Promise<ChatMessage> {\n if (question.attachments.length === 0) {\n return { role: 'user', content: question.text };\n }\n const { parts, unread } = await partsForModel(question.attachments, context.connection.reads ?? UNKNOWN_READS);\n if (unread) {\n context.setTurns((current) => updateLast(current, (turn) => ({ ...turn, unread })));\n }\n const text: ContentPart[] = question.text ? [{ type: 'text', text: question.text }] : [];\n return { role: 'user', content: [...text, ...parts] };\n}\n\n// Sends one question and writes its outcome: the answer, the guard's safe answer, or the failure.\nasync function sendQuestion(question: AskedQuestion, context: SendContext): Promise<void> {\n const { connection, guard, tools, transcript, abort, setTurns, setFailure, setBusy, copy } = context;\n const controller = new AbortController();\n abort.current = controller;\n setBusy(true);\n setFailure(null);\n setTurns((current) => [...current, {\n question: question.text, attachments: question.attachments, answer: '', tools: [],\n }]);\n const run: QuestionRun = { session: connection.session, tools, guard, transcript, controller, setTurns,\n asked: { role: 'user', content: question.text } };\n try {\n run.asked = await askedMessage(question, context);\n await answerQuestion(run);\n } catch (reason) {\n if (reason instanceof GuardStop) {\n showStop(reason, run, copy);\n } else if (!controller.signal.aborted) {\n // An answer the site stopped itself ends without an error.\n setFailure(answerFailure(reason, connection, copy));\n }\n } finally {\n // A question sent after a stop has taken over; its own end clears `busy`.\n if (abort.current === controller) {\n setBusy(false);\n }\n }\n}\n\nexport function useAiChat({ system, tools, guards }: UseAiChatOptions) {\n const { client, state, moduleMessages } = useAiConnect();\n const transcript = useRef<ChatMessage[]>([{ role: 'system', content: system }]);\n const abort = useRef<AbortController | null>(null);\n // The conversation's guard: created at its first question and kept until `reset`, in a ref for the\n // questions and in the state for the links the interface draws.\n const activeGuard = useRef<ChatGuard | null>(null);\n const [guard, setGuard] = useState<ChatGuard | null>(null);\n const [turns, setTurns] = useState<ChatTurn[]>([]);\n const [busy, setBusy] = useState(false);\n const [failure, setFailure] = useState<AnswerFailure | null>(null);\n\n // The session is read from the client when the question is sent, so a question kept while the\n // wallet connected the site goes out as soon as the client is connected.\n const send = useCallback(async (question: string | AskedQuestion) => {\n const connection = client.state;\n const asked = typeof question === 'string' ? { text: question, attachments: [] } : question;\n const text = asked.text.trim();\n if (connection.status !== 'connected' || (!text && asked.attachments.length === 0)) {\n return;\n }\n activeGuard.current ??= createChatGuard(guards);\n setGuard(activeGuard.current);\n await sendQuestion({ ...asked, text }, { connection, guard: activeGuard.current, tools, transcript, abort,\n setTurns, setFailure, setBusy, copy: moduleMessages });\n }, [client, tools, guards, moduleMessages]);\n\n const stop = useCallback(() => abort.current?.abort(), []);\n\n const reset = useCallback(() => {\n abort.current?.abort();\n transcript.current = [{ role: 'system', content: system }];\n activeGuard.current = null;\n setGuard(null);\n setTurns([]);\n setFailure(null);\n }, [system]);\n\n // Takes back the last turn when it failed with nothing to show, so asking it again does not repeat it.\n const dropFailedTurn = useCallback(() => {\n setTurns((current) => {\n const last = current.at(-1);\n return last && !last.answer && last.tools.length === 0 ? current.slice(0, -1) : current;\n });\n setFailure(null);\n }, []);\n\n return {\n turns, send, stop, reset, dropFailedTurn, busy, error: failure?.text ?? null, refusal: failure?.code ?? null,\n connected: state.status === 'connected',\n reads: (state.status === 'connected' ? state.reads : undefined) ?? UNKNOWN_READS,\n dictation: (state.status === 'connected' ? state.dictation : undefined) ?? null,\n linkAllowed: guard?.linkAllowed ?? NO_LINKS,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"useAiChat.js","sourceRoot":"","sources":["../src/useAiChat.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,gGAAgG;AAChG,mGAAmG;AACnG,gGAAgG;AAChG,6FAA6F;AAC7F,yGAAyG;AACzG,sFAAsF;AAEtF,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEtD,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAKpF,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAEjF,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAyB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEjD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAqC5D,oEAAoE;AACpE,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC;AAE7B,SAAS,UAAU,CAAC,KAAiB,EAAE,MAAoC;IACzE,OAAO,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC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AM,KAAK,WAAW;QACvC,KAAK,EAAE,CAAC,KAAK,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,aAAa;QAChF,SAAS,EAAE,CAAC,KAAK,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,IAAI;QAC/E,WAAW,EAAE,KAAK,EAAE,WAAW,IAAI,QAAQ;KAC5C,CAAC;AACJ,CAAC","sourcesContent":["// A conversation with the visitor's own model, using the site's tools. The site renders `turns`:\n// what the visitor asked, the answer as it streams, and every tool call with its raw result, so\n// tool results can be shown as the site's own cards. `stop` ends the answer in the wallet too, and\n// the turn keeps the text streamed so far. Every conversation runs under its guards, tuned with\n// `guards`: a question or an answer they stop shows the site's safe answer in its place, and\n// `linkAllowed` tells the interface which links of an answer it may draw. A question may carry the files\n// the visitor attached, which reach the model as the account that answers reads them.\n\nimport { useCallback, useRef, useState } from 'react';\nimport type { Dispatch, RefObject, SetStateAction } from 'react';\nimport { createChatGuard, GuardStop, runConversation } from '@tensorpass/aiconnect';\nimport type {\n ChatGuard, ChatMessage, ConnectionState, ContentPart, ConversationHooks, GuardPolicy, ProviderSession, ToolCall,\n ToolSource,\n} from '@tensorpass/aiconnect';\nimport { partsForModel, UNKNOWN_READS } from '@tensorpass/aiconnect/attachments';\nimport type { PreparedAttachment } from '@tensorpass/aiconnect/attachments';\nimport { useAiConnect } from './AiConnectProvider.tsx';\nimport { failedAnswerText } from './messages.ts';\nimport type { ModuleMessages } from './messages.ts';\nimport { appendAnswer } from './answerSteps.ts';\nimport { withinRequestBudget } from './transcriptBudget.ts';\n\nexport interface ToolActivity {\n call: ToolCall;\n result: string | null;\n // False for a tool the site keeps out of the `visibleTools` of its guards, whose activity the\n // interface does not show.\n visible?: boolean;\n}\n\n// A question as the visitor sends it: the text they typed or dictated and the files they attached.\nexport interface AskedQuestion {\n text: string;\n attachments: PreparedAttachment[];\n}\n\nexport interface ChatTurn {\n question: string;\n // The files the visitor attached to the question.\n attachments?: PreparedAttachment[];\n // The attached images and pages the answering model does not read, such as images for a text only model.\n unread?: number;\n answer: string;\n tools: ToolActivity[];\n // The guard stopped the question before it left the page, or the answer as it came; `answer` then\n // holds the site's safe answer.\n blocked?: 'question' | 'answer';\n}\n\nexport interface UseAiChatOptions {\n system: string;\n tools?: ToolSource;\n // The site's own values for the guards every conversation runs under, read at the conversation's first\n // question.\n guards?: GuardPolicy;\n}\n\n// Before the first question there is no answer, so no link to draw.\nconst NO_LINKS = () => false;\n\nfunction updateLast(turns: ChatTurn[], change: (turn: ChatTurn) => ChatTurn): ChatTurn[] {\n return [...turns.slice(0, -1), change(turns.at(-1)!)];\n}\n\n// Writes the conversation's progress into the last turn, as the answer streams and the tools run. The\n// words the model writes after a tool's result start a paragraph of their own. A conversation that was\n// stopped writes nothing more, so a question sent right after it keeps its own turn.\nfunction lastTurnHooks(\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>, signal: AbortSignal, guard: ChatGuard,\n): ConversationHooks {\n const updateTurn = (change: (turn: ChatTurn) => ChatTurn) => {\n if (!signal.aborted) {\n setTurns((current) => updateLast(current, change));\n }\n };\n let newStep = false;\n return {\n onText: (delta) => {\n const opensStep = newStep;\n newStep = false;\n updateTurn((turn) => ({ ...turn, answer: appendAnswer(turn.answer, delta, opensStep) }));\n },\n onToolCall: (call) => {\n newStep = true;\n updateTurn((turn) => ({\n ...turn, tools: [...turn.tools, { call, result: null, visible: guard.toolVisible(call.name) }],\n }));\n },\n onToolResult: (call, result) => updateTurn((turn) => ({\n ...turn, tools: turn.tools.map((activity) => (activity.call.id === call.id ? { ...activity, result } : activity)),\n })),\n };\n}\n\ninterface QuestionRun {\n session: ProviderSession;\n tools?: ToolSource;\n guard: ChatGuard;\n transcript: RefObject<ChatMessage[]>;\n asked: ChatMessage;\n controller: AbortController;\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>;\n}\n\n// Runs one question on the visitor's model and keeps the exchange in the transcript. A question that\n// was stopped or failed adds nothing to it.\nasync function answerQuestion({ session, tools, guard, transcript, asked, controller, setTurns }: QuestionRun) {\n const added = await runConversation({\n session,\n tools,\n guard,\n messages: withinRequestBudget([...transcript.current, asked]),\n signal: controller.signal,\n ...lastTurnHooks(setTurns, controller.signal, guard),\n });\n transcript.current = [...transcript.current, asked, ...added];\n}\n\n// Shows the safe answer in place of what a guard stopped: the site's own, or the module's words for a\n// stopped question or answer. A stopped answer stays in the transcript as the safe answer, so the model\n// reads the exchange without the text it should not have written; a stopped question never reaches it.\nfunction showStop(stop: GuardStop, run: QuestionRun, copy: ModuleMessages) {\n const safeAnswer = run.guard.policy.safeAnswer ?? (stop.stage === 'question' ? copy.guardQuestion : copy.guardAnswer);\n run.setTurns((current) => updateLast(current, (turn) => ({ ...turn, answer: safeAnswer, blocked: stop.stage })));\n if (stop.stage === 'answer') {\n run.transcript.current = [...run.transcript.current, run.asked, { role: 'assistant', content: safeAnswer }];\n }\n}\n\n// An answer that failed: its words, and the code the provider gave its refusal, such as `plan_inactive`\n// for a TensorPass account without a plan, by which the module offers what fits.\nexport interface AnswerFailure {\n text: string;\n code: string | null;\n}\n\n// A web account's 429 keeps the provider's own message, such as the gateway's limit of requests from one\n// site, since the module's words for a 429 send the visitor to another account in the wallet.\nfunction answerFailure(reason: unknown, connection: Extract<ConnectionState, { status: 'connected' }>,\n copy: ModuleMessages): AnswerFailure {\n const { status, code } = (reason ?? {}) as { status?: unknown; code?: unknown };\n const text = connection.account && status === 429 && reason instanceof Error\n ? reason.message\n : failedAnswerText(reason, connection.providerName, copy);\n return { text, code: typeof code === 'string' ? code : null };\n}\n\n// What a question's run needs from the hook besides the question.\ninterface SendContext {\n connection: Extract<ConnectionState, { status: 'connected' }>;\n guard: ChatGuard;\n tools?: ToolSource;\n transcript: RefObject<ChatMessage[]>;\n abort: RefObject<AbortController | null>;\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>;\n setFailure: Dispatch<SetStateAction<AnswerFailure | null>>;\n setBusy: Dispatch<SetStateAction<boolean>>;\n copy: ModuleMessages;\n}\n\n// The visitor's message: the text, then the attachments as the account that answers reads them.\nasync function askedMessage(question: AskedQuestion, context: SendContext): Promise<ChatMessage> {\n if (question.attachments.length === 0) {\n return { role: 'user', content: question.text };\n }\n const { parts, unread } = await partsForModel(question.attachments, context.connection.reads ?? UNKNOWN_READS);\n if (unread) {\n context.setTurns((current) => updateLast(current, (turn) => ({ ...turn, unread })));\n }\n const text: ContentPart[] = question.text ? [{ type: 'text', text: question.text }] : [];\n return { role: 'user', content: [...text, ...parts] };\n}\n\n// Sends one question and writes its outcome: the answer, the guard's safe answer, or the failure.\nasync function sendQuestion(question: AskedQuestion, context: SendContext): Promise<void> {\n const { connection, guard, tools, transcript, abort, setTurns, setFailure, setBusy, copy } = context;\n const controller = new AbortController();\n abort.current = controller;\n setBusy(true);\n setFailure(null);\n setTurns((current) => [...current, {\n question: question.text, attachments: question.attachments, answer: '', tools: [],\n }]);\n const run: QuestionRun = { session: connection.session, tools, guard, transcript, controller, setTurns,\n asked: { role: 'user', content: question.text } };\n try {\n run.asked = await askedMessage(question, context);\n await answerQuestion(run);\n } catch (reason) {\n if (reason instanceof GuardStop) {\n showStop(reason, run, copy);\n } else if (!controller.signal.aborted) {\n // An answer the site stopped itself ends without an error.\n setFailure(answerFailure(reason, connection, copy));\n }\n } finally {\n // A question sent after a stop has taken over; its own end clears `busy`.\n if (abort.current === controller) {\n setBusy(false);\n }\n }\n}\n\nexport function useAiChat({ system, tools, guards }: UseAiChatOptions) {\n const { client, state, moduleMessages } = useAiConnect();\n const transcript = useRef<ChatMessage[]>([{ role: 'system', content: system }]);\n const abort = useRef<AbortController | null>(null);\n // The conversation's guard: created at its first question and kept until `reset`, in a ref for the\n // questions and in the state for the links the interface draws.\n const activeGuard = useRef<ChatGuard | null>(null);\n const [guard, setGuard] = useState<ChatGuard | null>(null);\n const [turns, setTurns] = useState<ChatTurn[]>([]);\n const [busy, setBusy] = useState(false);\n const [failure, setFailure] = useState<AnswerFailure | null>(null);\n\n // The session is read from the client when the question is sent, so a question kept while the\n // wallet connected the site goes out as soon as the client is connected.\n const send = useCallback(async (question: string | AskedQuestion) => {\n const connection = client.state;\n const asked = typeof question === 'string' ? { text: question, attachments: [] } : question;\n const text = asked.text.trim();\n if (connection.status !== 'connected' || (!text && asked.attachments.length === 0)) {\n return;\n }\n activeGuard.current ??= createChatGuard(guards);\n setGuard(activeGuard.current);\n await sendQuestion({ ...asked, text }, { connection, guard: activeGuard.current, tools, transcript, abort,\n setTurns, setFailure, setBusy, copy: moduleMessages });\n }, [client, tools, guards, moduleMessages]);\n\n const stop = useCallback(() => abort.current?.abort(), []);\n\n const reset = useCallback(() => {\n abort.current?.abort();\n transcript.current = [{ role: 'system', content: system }];\n activeGuard.current = null;\n setGuard(null);\n setTurns([]);\n setFailure(null);\n }, [system]);\n\n // Takes back the last turn when it failed with nothing to show, so asking it again does not repeat it.\n const dropFailedTurn = useCallback(() => {\n setTurns((current) => {\n const last = current.at(-1);\n return last && !last.answer && last.tools.length === 0 ? current.slice(0, -1) : current;\n });\n setFailure(null);\n }, []);\n\n return {\n turns, send, stop, reset, dropFailedTurn, busy, error: failure?.text ?? null, refusal: failure?.code ?? null,\n connected: state.status === 'connected',\n reads: (state.status === 'connected' ? state.reads : undefined) ?? UNKNOWN_READS,\n dictation: (state.status === 'connected' ? state.dictation : undefined) ?? null,\n linkAllowed: guard?.linkAllowed ?? NO_LINKS,\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tensorpass/aiconnect-react",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.10",
|
|
4
4
|
"description": "React provider picker and chat hook for AI Connect.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": [
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
"build": "rm -rf dist tsconfig.tsbuildinfo && tsc -b && esbuild src/styles.css --bundle --outfile=dist/styles.css --log-level=warning && cp src/modules/styles/launchers.css dist/launchers.css"
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@tensorpass/aiconnect": "0.1.
|
|
38
|
-
"@tensorpass/aiconnect-design": "0.1.
|
|
37
|
+
"@tensorpass/aiconnect": "0.1.10",
|
|
38
|
+
"@tensorpass/aiconnect-design": "0.1.10"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"react": ">=19"
|