@tensorpass/aiconnect-react 0.1.9 → 0.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- 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 +1 -0
- package/dist/index.js.map +1 -1
- package/dist/moduleMessages.d.ts +3 -0
- package/dist/moduleMessages.js +15 -0
- package/dist/moduleMessages.js.map +1 -1
- package/dist/modules/AiSearch.js +3 -3
- package/dist/modules/AiSearch.js.map +1 -1
- package/dist/modules/parts/AnswerCode.d.ts +8 -0
- package/dist/modules/parts/AnswerCode.js +43 -0
- package/dist/modules/parts/AnswerCode.js.map +1 -0
- package/dist/modules/parts/AnswerText.js +8 -4
- package/dist/modules/parts/AnswerText.js.map +1 -1
- package/dist/modules/parts/ChatFrame.js +1 -1
- package/dist/modules/parts/ChatFrame.js.map +1 -1
- package/dist/modules/parts/ModuleFoot.d.ts +6 -2
- package/dist/modules/parts/ModuleFoot.js +24 -4
- package/dist/modules/parts/ModuleFoot.js.map +1 -1
- package/dist/modules/parts/answerMarkdown.d.ts +6 -1
- package/dist/modules/parts/answerMarkdown.js +65 -14
- package/dist/modules/parts/answerMarkdown.js.map +1 -1
- package/dist/modules/parts/icons.d.ts +1 -0
- package/dist/modules/parts/icons.js +1 -0
- package/dist/modules/parts/icons.js.map +1 -1
- package/dist/modules/parts/moduleCredit.d.ts +6 -0
- package/dist/modules/parts/moduleCredit.js +23 -0
- package/dist/modules/parts/moduleCredit.js.map +1 -0
- package/dist/modules/types.d.ts +2 -0
- package/dist/modules/types.js +2 -2
- package/dist/modules/types.js.map +1 -1
- package/dist/styles.css +97 -0
- package/dist/useAiChat.js +16 -7
- package/dist/useAiChat.js.map +1 -1
- package/package.json +3 -3
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
// The answer's text as the blocks a module draws: paragraphs, headings,
|
|
2
|
-
//
|
|
3
|
-
// even when asked for plain text, so the module shows it as formatting. A mark the stream has
|
|
4
|
-
// closed yet stays plain text until its closing half arrives
|
|
1
|
+
// The answer's text as the blocks a module draws: paragraphs, headings, bulleted or numbered lists,
|
|
2
|
+
// each made of inline runs (plain, bold, italic, code, link), and fenced code blocks. Models write light
|
|
3
|
+
// Markdown even when asked for plain text, so the module shows it as formatting. A mark the stream has
|
|
4
|
+
// not closed yet stays plain text until its closing half arrives, while a code block shows the lines
|
|
5
|
+
// received so far as soon as its fence opens. An image is never drawn, since it would
|
|
5
6
|
// load by itself: its description stays as text. A bare web address becomes a link labelled with its
|
|
6
7
|
// host and path, and a link inside bold or italic text stays a link. A link the conversation's guards
|
|
7
8
|
// do not allow stays as its words.
|
|
@@ -18,8 +19,12 @@ const INLINE = new RegExp([
|
|
|
18
19
|
String.raw `\*([^*\s][^*\n]*?)\*`,
|
|
19
20
|
].join('|'), 'gi');
|
|
20
21
|
const BULLET = /^\s*[-*•]\s+(.*)$/;
|
|
21
|
-
const NUMBERED = /^\s
|
|
22
|
+
const NUMBERED = /^\s*(\d+)[.)]\s+(.*)$/;
|
|
22
23
|
const HEADING = /^\s*#{1,6}\s+(.*)$/;
|
|
24
|
+
// A fence of three backticks or tildes or more opens a code block, the first word after it naming the
|
|
25
|
+
// code's language. A backtick fence's line holds no other backtick, as in CommonMark.
|
|
26
|
+
const FENCE = /^([ \t]*)(\x60{3,}|~{3,})(.*)$/;
|
|
27
|
+
const PARTIAL_FENCE = /^[ \t]*(\x60{1,2}|~{1,2})$/;
|
|
23
28
|
const WEB_OR_MAIL = /^(https?:\/\/|mailto:)/i;
|
|
24
29
|
const SCHEME = /^https?:\/\//i;
|
|
25
30
|
const LABEL_LENGTH = 40;
|
|
@@ -78,13 +83,14 @@ export function inlineRuns(text) {
|
|
|
78
83
|
function listItem(line) {
|
|
79
84
|
const bullet = BULLET.exec(line);
|
|
80
85
|
if (bullet) {
|
|
81
|
-
return { ordered: false, text: bullet[1] };
|
|
86
|
+
return { ordered: false, number: 1, text: bullet[1] };
|
|
82
87
|
}
|
|
83
88
|
const numbered = NUMBERED.exec(line);
|
|
84
|
-
return numbered ? { ordered: true,
|
|
89
|
+
return numbered ? { ordered: true, number: Number(numbered[1]), text: numbered[2] } : null;
|
|
85
90
|
}
|
|
86
91
|
// Adds a line to the blocks read so far: a list item joins the list above it, a heading stands
|
|
87
|
-
// alone, and other lines join the paragraph above them until a blank line ends it.
|
|
92
|
+
// alone, and other lines join the paragraph above them until a blank line ends it. A numbered list
|
|
93
|
+
// keeps the number of its first item, so the steps a code block splits go on counting.
|
|
88
94
|
function addLine(blocks, line, afterBlank) {
|
|
89
95
|
const last = blocks.at(-1);
|
|
90
96
|
const item = listItem(line);
|
|
@@ -93,7 +99,8 @@ function addLine(blocks, line, afterBlank) {
|
|
|
93
99
|
last.items.push(inlineRuns(item.text));
|
|
94
100
|
}
|
|
95
101
|
else {
|
|
96
|
-
|
|
102
|
+
const start = item.ordered ? { start: item.number } : {};
|
|
103
|
+
blocks.push({ kind: 'list', ordered: item.ordered, ...start, items: [inlineRuns(item.text)] });
|
|
97
104
|
}
|
|
98
105
|
return;
|
|
99
106
|
}
|
|
@@ -117,14 +124,58 @@ export function keepAllowedLinks(blocks, allowed) {
|
|
|
117
124
|
}
|
|
118
125
|
return run.kind === 'link' && !allowed(run.href) ? { kind: 'text', text: run.text } : run;
|
|
119
126
|
});
|
|
120
|
-
return blocks.map((block) =>
|
|
121
|
-
|
|
122
|
-
|
|
127
|
+
return blocks.map((block) => {
|
|
128
|
+
if (block.kind === 'code') {
|
|
129
|
+
return block;
|
|
130
|
+
}
|
|
131
|
+
return block.kind === 'list' ? { ...block, items: block.items.map(runs) } : { ...block, runs: runs(block.runs) };
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
// Opens a code block on a fence line, after the blocks read so far.
|
|
135
|
+
function openCode(line, blocks) {
|
|
136
|
+
const fence = FENCE.exec(line);
|
|
137
|
+
if (!fence) {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
const [, indent, marks, info] = fence;
|
|
141
|
+
if (marks.startsWith('\x60') && info.includes('\x60')) {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
const block = { kind: 'code', language: info.trim().split(/\s+/)[0], text: '' };
|
|
145
|
+
blocks.push(block);
|
|
146
|
+
return { block, marks, indent: indent.length, lines: [] };
|
|
147
|
+
}
|
|
148
|
+
// Adds a line to an open code block, or closes it on a fence of the same mark at least as long. Each
|
|
149
|
+
// line loses the fence's own indentation, so a block written under a list item keeps only its own.
|
|
150
|
+
function addCodeLine(code, line) {
|
|
151
|
+
const mark = line.trim();
|
|
152
|
+
if (mark.length >= code.marks.length && [...mark].every((char) => char === code.marks[0])) {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
const indent = Math.min(line.length - line.trimStart().length, code.indent);
|
|
156
|
+
code.lines.push(line.slice(indent));
|
|
157
|
+
code.block.text = code.lines.join('\n').trimEnd();
|
|
158
|
+
return code;
|
|
123
159
|
}
|
|
124
|
-
|
|
160
|
+
// The blocks of an answer. While it streams, a last line that may be the start of a fence (one or two
|
|
161
|
+
// backticks or tildes) waits for the next piece, so the visitor never sees the marks themselves.
|
|
162
|
+
export function answerBlocks(text, streaming = false) {
|
|
163
|
+
const lines = text.split('\n');
|
|
164
|
+
if (streaming && PARTIAL_FENCE.test(lines.at(-1) ?? '')) {
|
|
165
|
+
lines.pop();
|
|
166
|
+
}
|
|
125
167
|
const blocks = [];
|
|
126
168
|
let afterBlank = true;
|
|
127
|
-
|
|
169
|
+
let code = null;
|
|
170
|
+
for (const line of lines) {
|
|
171
|
+
if (code) {
|
|
172
|
+
code = addCodeLine(code, line);
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
code = openCode(line, blocks);
|
|
176
|
+
if (code) {
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
128
179
|
if (!line.trim()) {
|
|
129
180
|
afterBlank = true;
|
|
130
181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,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;IAC5F,CAAC,CAAC,CAAC;IACH,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM;QACjD,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;QAC5C,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;AAC7C,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,MAAM,MAAM,GAAkB,EAAE,CAAC;IACjC,IAAI,UAAU,GAAG,IAAI,CAAC;IACtB,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;QACpC,IAAI,CAAC,IAAI,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 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"]}
|
|
1
|
+
{"version":3,"file":"answerMarkdown.js","sourceRoot":"","sources":["../../../src/modules/parts/answerMarkdown.ts"],"names":[],"mappings":"AAAA,oGAAoG;AACpG,yGAAyG;AACzG,uGAAuG;AACvG,qGAAqG;AACrG,sFAAsF;AACtF,qGAAqG;AACrG,sGAAsG;AACtG,mCAAmC;AAEnC,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAexD,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,2BAA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E,CAAC;YACT,SAAS;QACX,CAAC;QACD,IAAI,CAAC,IAAI,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, bulleted or numbered lists,\n// each made of inline runs (plain, bold, italic, code, link), and fenced code blocks. Models write light\n// Markdown even when asked for plain text, so the module shows it as formatting. A mark the stream has\n// not closed yet stays plain text until its closing half arrives, while a code block shows the lines\n// received so far as soon as its fence opens. 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; start?: number; items: InlineRun[][] }\n | { kind: 'code'; language: string; text: string };\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+(.*)$/;\n// A fence of three backticks or tildes or more opens a code block, the first word after it naming the\n// code's language. A backtick fence's line holds no other backtick, as in CommonMark.\nconst FENCE = /^([ \\t]*)(\\x60{3,}|~{3,})(.*)$/;\nconst PARTIAL_FENCE = /^[ \\t]*(\\x60{1,2}|~{1,2})$/;\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 number: number;\n text: string;\n}\n\nfunction listItem(line: string): ListItemLine | null {\n const bullet = BULLET.exec(line);\n if (bullet) {\n return { ordered: false, number: 1, text: bullet[1] };\n }\n const numbered = NUMBERED.exec(line);\n return numbered ? { ordered: true, number: Number(numbered[1]), text: numbered[2] } : 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. A numbered list\n// keeps the number of its first item, so the steps a code block splits go on counting.\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 const start = item.ordered ? { start: item.number } : {};\n blocks.push({ kind: 'list', ordered: item.ordered, ...start, 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) => {\n if (block.kind === 'code') {\n return block;\n }\n return block.kind === 'list' ? { ...block, items: block.items.map(runs) } : { ...block, runs: runs(block.runs) };\n });\n}\n\ntype CodeBlock = Extract<AnswerBlock, { kind: 'code' }>;\n\ninterface OpenCode {\n block: CodeBlock;\n marks: string;\n indent: number;\n lines: string[];\n}\n\n// Opens a code block on a fence line, after the blocks read so far.\nfunction openCode(line: string, blocks: AnswerBlock[]): OpenCode | null {\n const fence = FENCE.exec(line);\n if (!fence) {\n return null;\n }\n const [, indent, marks, info] = fence;\n if (marks.startsWith('\\x60') && info.includes('\\x60')) {\n return null;\n }\n const block: CodeBlock = { kind: 'code', language: info.trim().split(/\\s+/)[0], text: '' };\n blocks.push(block);\n return { block, marks, indent: indent.length, lines: [] };\n}\n\n// Adds a line to an open code block, or closes it on a fence of the same mark at least as long. Each\n// line loses the fence's own indentation, so a block written under a list item keeps only its own.\nfunction addCodeLine(code: OpenCode, line: string): OpenCode | null {\n const mark = line.trim();\n if (mark.length >= code.marks.length && [...mark].every((char) => char === code.marks[0])) {\n return null;\n }\n const indent = Math.min(line.length - line.trimStart().length, code.indent);\n code.lines.push(line.slice(indent));\n code.block.text = code.lines.join('\\n').trimEnd();\n return code;\n}\n\n// The blocks of an answer. While it streams, a last line that may be the start of a fence (one or two\n// backticks or tildes) waits for the next piece, so the visitor never sees the marks themselves.\nexport function answerBlocks(text: string, streaming = false): AnswerBlock[] {\n const lines = text.split('\\n');\n if (streaming && PARTIAL_FENCE.test(lines.at(-1) ?? '')) {\n lines.pop();\n }\n const blocks: AnswerBlock[] = [];\n let afterBlank = true;\n let code: OpenCode | null = null;\n for (const line of lines) {\n if (code) {\n code = addCodeLine(code, line);\n continue;\n }\n code = openCode(line, blocks);\n if (code) {\n continue;\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"]}
|
|
@@ -6,6 +6,7 @@ export declare const SendIcon: () => import("react").JSX.Element;
|
|
|
6
6
|
export declare const CloseIcon: () => import("react").JSX.Element;
|
|
7
7
|
export declare const NewChatIcon: () => import("react").JSX.Element;
|
|
8
8
|
export declare const SearchIcon: () => import("react").JSX.Element;
|
|
9
|
+
export declare const CopyIcon: () => import("react").JSX.Element;
|
|
9
10
|
export declare const CheckIcon: () => import("react").JSX.Element;
|
|
10
11
|
export declare const ArrowIcon: () => import("react").JSX.Element;
|
|
11
12
|
export declare const PaperclipIcon: () => import("react").JSX.Element;
|
|
@@ -9,6 +9,7 @@ export const SendIcon = () => _jsx(Stroke, { size: 18, width: 2.4, children: _js
|
|
|
9
9
|
export const CloseIcon = () => _jsx(Stroke, { size: 18, children: _jsx("path", { d: "M6 6l12 12M18 6 6 18" }) });
|
|
10
10
|
export const NewChatIcon = () => (_jsxs(Stroke, { size: 18, children: [_jsx("path", { d: "M12 4H7a3 3 0 0 0-3 3v10a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3v-5" }), _jsx("path", { d: "M17.5 3.5a2.1 2.1 0 0 1 3 3L13 14l-4 1 1-4z" })] }));
|
|
11
11
|
export const SearchIcon = () => (_jsxs(Stroke, { size: 18, children: [_jsx("circle", { cx: "11", cy: "11", r: "6.5" }), _jsx("path", { d: "m20 20-4.2-4.2" })] }));
|
|
12
|
+
export const CopyIcon = () => (_jsxs(Stroke, { size: 14, width: 2.2, children: [_jsx("rect", { x: "8", y: "8", width: "12", height: "12", rx: "2.5" }), _jsx("path", { d: "M16 8V6.5A2.5 2.5 0 0 0 13.5 4h-7A2.5 2.5 0 0 0 4 6.5v7A2.5 2.5 0 0 0 6.5 16H8" })] }));
|
|
12
13
|
export const CheckIcon = () => _jsx(Stroke, { size: 12, width: 3, children: _jsx("path", { d: "m5 12 5 5 9-10" }) });
|
|
13
14
|
// Points along the reading direction; the stylesheet mirrors it in right to left.
|
|
14
15
|
export const ArrowIcon = () => _jsx(Stroke, { size: 16, className: "aic-arrow", children: _jsx("path", { d: "M5 12h14M13 6l6 6-6 6" }) });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"icons.js","sourceRoot":"","sources":["../../../src/modules/parts/icons.tsx"],"names":[],"mappings":";AAIA,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AASjE,SAAS,MAAM,CAAC,EAAE,QAAQ,EAAE,IAAI,GAAG,EAAE,EAAE,KAAK,GAAG,CAAC,EAAE,SAAS,EAAe;IACxE,OAAO,CACL,cAAK,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAC,WAAW,EAAC,IAAI,EAAC,MAAM,EAAC,MAAM,EAAC,cAAc,EACzG,WAAW,EAAE,KAAK,EAAE,aAAa,EAAC,OAAO,EAAC,cAAc,EAAC,OAAO,iBAAa,MAAM,EAAC,SAAS,EAAC,OAAO,YACpG,QAAQ,GACL,CACP,CAAC;AACJ,CAAC;AAED,yFAAyF;AACzF,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,EAAE,IAAI,GAAG,EAAE,EAAE,SAAS,EAAyC,EAAE,EAAE,CAAC,CAC3F,KAAC,MAAM,IAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,iBAAiB,EAAE,SAAS,EAAE,SAAS,YAC/D,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,eAAgB,SAAS,EAAE,QAAQ,KAAK,GAAG,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,IAA3C,GAAG,CAA4C,CAAC,GACnF,CACV,CAAC;AAEF,MAAM,CAAC,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,KAAC,MAAM,IAAC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AAM,IAAC,IAAI,EAAE,EAAE,aACd,eAAM,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,KAAK,EAAC,GAAG,EAAC,MAAM,EAAC,IAAI,EAAC,EAAE,EAAC,GAAG,GAAG,EACjD,eAAM,CAAC,EAAC,uCAAuC,GAAG,IAC3C,CACV,CAAC;AAEF,MAAM,CAAC,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,CAC5B,MAAC,MAAM,IAAC,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,GAAG,aAC1B,eAAM,CAAC,EAAC,4DAA4D,GAAG,EACvE,eAAM,CAAC,EAAC,yBAAyB,GAAG,IAC7B,CACV,CAAC;AAEF,uFAAuF;AACvF,MAAM,CAAC,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,KAAC,MAAM,IAAC,IAAI,EAAE,EAAE,EAAE,SAAS,EAAC,WAAW,YAAC,eAAM,CAAC,EAAC,eAAe,GAAG,GAAS,CAAC;AAE1G,MAAM,CAAC,MAAM,WAAW,GAAG,GAAG,EAAE,CAAC,KAAC,MAAM,IAAC,IAAI,EAAE,EAAE,EAAE,SAAS,EAAC,WAAW,YAAC,eAAM,CAAC,EAAC,cAAc,GAAG,GAAS,CAAC","sourcesContent":["// The modules' drawn icons, in the AI Wallet's one stroke family (24 grid, round caps and joins).\n// The wave is the wallet's mark: the contactless arcs that light up while the visitor's AI answers.\n\nimport type { ReactNode } from 'react';\nimport { WAVE_ARCS, WAVE_STROKE_WIDTH } from '../../launcher.ts';\n\ninterface StrokeProps {\n children: ReactNode;\n size?: number;\n width?: number;\n className?: string;\n}\n\nfunction Stroke({ children, size = 18, width = 2, className }: StrokeProps) {\n return (\n <svg className={className} width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth={width} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">\n {children}\n </svg>\n );\n}\n\n// The three arcs, each its own path so a live answer can light them one after the other.\nexport const WaveIcon = ({ size = 18, className }: { size?: number; className?: string }) => (\n <Stroke size={size} width={WAVE_STROKE_WIDTH} className={className}>\n {WAVE_ARCS.map((arc, index) => <path key={arc} className={`aic-w${index + 1}`} d={arc} />)}\n </Stroke>\n);\n\nexport const SendIcon = () => <Stroke size={18} width={2.4}><path d=\"M12 19V5M6 11l6-6 6 6\" /></Stroke>;\n\nexport const CloseIcon = () => <Stroke size={18}><path d=\"M6 6l12 12M18 6 6 18\" /></Stroke>;\n\nexport const NewChatIcon = () => (\n <Stroke size={18}>\n <path d=\"M12 4H7a3 3 0 0 0-3 3v10a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3v-5\" />\n <path d=\"M17.5 3.5a2.1 2.1 0 0 1 3 3L13 14l-4 1 1-4z\" />\n </Stroke>\n);\n\nexport const SearchIcon = () => (\n <Stroke size={18}><circle cx=\"11\" cy=\"11\" r=\"6.5\" /><path d=\"m20 20-4.2-4.2\" /></Stroke>\n);\n\nexport const CheckIcon = () => <Stroke size={12} width={3}><path d=\"m5 12 5 5 9-10\" /></Stroke>;\n\n// Points along the reading direction; the stylesheet mirrors it in right to left.\nexport const ArrowIcon = () => <Stroke size={16} className=\"aic-arrow\"><path d=\"M5 12h14M13 6l6 6-6 6\" /></Stroke>;\n\nexport const PaperclipIcon = () => (\n <Stroke size={18}>\n <path d=\"m20 11.5-7.8 7.8a5 5 0 0 1-7-7l8.4-8.4a3.3 3.3 0 0 1 4.7 4.7l-8.4 8.4a1.7 1.7 0 0 1-2.4-2.4l7.7-7.7\" />\n </Stroke>\n);\n\nexport const MicIcon = () => (\n <Stroke size={18}>\n <rect x=\"9\" y=\"3\" width=\"6\" height=\"11\" rx=\"3\" />\n <path d=\"M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21\" />\n </Stroke>\n);\n\nexport const FileIcon = () => (\n <Stroke size={18} width={1.8}>\n <path d=\"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z\" />\n <path d=\"M14 3v5h5M9 13h6M9 17h4\" />\n </Stroke>\n);\n\n// Points back along the reading direction; the stylesheet mirrors it in right to left.\nexport const BackIcon = () => <Stroke size={18} className=\"aic-arrow\"><path d=\"m15 6-6 6 6 6\" /></Stroke>;\n\nexport const ForwardIcon = () => <Stroke size={18} className=\"aic-arrow\"><path d=\"m9 6 6 6-6 6\" /></Stroke>;\n"]}
|
|
1
|
+
{"version":3,"file":"icons.js","sourceRoot":"","sources":["../../../src/modules/parts/icons.tsx"],"names":[],"mappings":";AAIA,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AASjE,SAAS,MAAM,CAAC,EAAE,QAAQ,EAAE,IAAI,GAAG,EAAE,EAAE,KAAK,GAAG,CAAC,EAAE,SAAS,EAAe;IACxE,OAAO,CACL,cAAK,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAC,WAAW,EAAC,IAAI,EAAC,MAAM,EAAC,MAAM,EAAC,cAAc,EACzG,WAAW,EAAE,KAAK,EAAE,aAAa,EAAC,OAAO,EAAC,cAAc,EAAC,OAAO,iBAAa,MAAM,EAAC,SAAS,EAAC,OAAO,YACpG,QAAQ,GACL,CACP,CAAC;AACJ,CAAC;AAED,yFAAyF;AACzF,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,EAAE,IAAI,GAAG,EAAE,EAAE,SAAS,EAAyC,EAAE,EAAE,CAAC,CAC3F,KAAC,MAAM,IAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,iBAAiB,EAAE,SAAS,EAAE,SAAS,YAC/D,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,eAAgB,SAAS,EAAE,QAAQ,KAAK,GAAG,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,IAA3C,GAAG,CAA4C,CAAC,GACnF,CACV,CAAC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mark: the contactless arcs that light up while the visitor's AI answers.\n\nimport type { ReactNode } from 'react';\nimport { WAVE_ARCS, WAVE_STROKE_WIDTH } from '../../launcher.ts';\n\ninterface StrokeProps {\n children: ReactNode;\n size?: number;\n width?: number;\n className?: string;\n}\n\nfunction Stroke({ children, size = 18, width = 2, className }: StrokeProps) {\n return (\n <svg className={className} width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth={width} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">\n {children}\n </svg>\n );\n}\n\n// The three arcs, each its own path so a live answer can light them one after the other.\nexport const WaveIcon = ({ size = 18, className }: { size?: number; className?: string }) => (\n <Stroke size={size} width={WAVE_STROKE_WIDTH} className={className}>\n {WAVE_ARCS.map((arc, index) => <path key={arc} className={`aic-w${index + 1}`} d={arc} />)}\n </Stroke>\n);\n\nexport const SendIcon = () => <Stroke size={18} width={2.4}><path d=\"M12 19V5M6 11l6-6 6 6\" /></Stroke>;\n\nexport const CloseIcon = () => <Stroke size={18}><path d=\"M6 6l12 12M18 6 6 18\" /></Stroke>;\n\nexport const NewChatIcon = () => (\n <Stroke size={18}>\n <path d=\"M12 4H7a3 3 0 0 0-3 3v10a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3v-5\" />\n <path d=\"M17.5 3.5a2.1 2.1 0 0 1 3 3L13 14l-4 1 1-4z\" />\n </Stroke>\n);\n\nexport const SearchIcon = () => (\n <Stroke size={18}><circle cx=\"11\" cy=\"11\" r=\"6.5\" /><path d=\"m20 20-4.2-4.2\" /></Stroke>\n);\n\nexport const CopyIcon = () => (\n <Stroke size={14} width={2.2}>\n <rect x=\"8\" y=\"8\" width=\"12\" height=\"12\" rx=\"2.5\" />\n <path d=\"M16 8V6.5A2.5 2.5 0 0 0 13.5 4h-7A2.5 2.5 0 0 0 4 6.5v7A2.5 2.5 0 0 0 6.5 16H8\" />\n </Stroke>\n);\n\nexport const CheckIcon = () => <Stroke size={12} width={3}><path d=\"m5 12 5 5 9-10\" /></Stroke>;\n\n// Points along the reading direction; the stylesheet mirrors it in right to left.\nexport const ArrowIcon = () => <Stroke size={16} className=\"aic-arrow\"><path d=\"M5 12h14M13 6l6 6-6 6\" /></Stroke>;\n\nexport const PaperclipIcon = () => (\n <Stroke size={18}>\n <path d=\"m20 11.5-7.8 7.8a5 5 0 0 1-7-7l8.4-8.4a3.3 3.3 0 0 1 4.7 4.7l-8.4 8.4a1.7 1.7 0 0 1-2.4-2.4l7.7-7.7\" />\n </Stroke>\n);\n\nexport const MicIcon = () => (\n <Stroke size={18}>\n <rect x=\"9\" y=\"3\" width=\"6\" height=\"11\" rx=\"3\" />\n <path d=\"M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21\" />\n </Stroke>\n);\n\nexport const FileIcon = () => (\n <Stroke size={18} width={1.8}>\n <path d=\"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z\" />\n <path d=\"M14 3v5h5M9 13h6M9 17h4\" />\n </Stroke>\n);\n\n// Points back along the reading direction; the stylesheet mirrors it in right to left.\nexport const BackIcon = () => <Stroke size={18} className=\"aic-arrow\"><path d=\"m15 6-6 6 6 6\" /></Stroke>;\n\nexport const ForwardIcon = () => <Stroke size={18} className=\"aic-arrow\"><path d=\"m9 6 6 6-6 6\" /></Stroke>;\n"]}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { WalletHost } from '@tensorpass/aiconnect';
|
|
2
|
+
export type ModuleCredit = boolean | {
|
|
3
|
+
href?: string;
|
|
4
|
+
};
|
|
5
|
+
export declare function creditShown(credit: ModuleCredit | undefined, walletHost: WalletHost | null): boolean;
|
|
6
|
+
export declare function creditHref(credit: ModuleCredit, pageHost: string): string;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// The TensorPass credit a module draws at its foot when the site turns `credit` on: where its link goes,
|
|
2
|
+
// and whether it shows. Inside the TensorPass app the visitor is already in TensorPass, so the credit stays
|
|
3
|
+
// out there. The link names the site as its source, as the credits sites wrote themselves did.
|
|
4
|
+
const TENSORPASS_URL = 'https://tensorpass.app/';
|
|
5
|
+
export function creditShown(credit, walletHost) {
|
|
6
|
+
return Boolean(credit) && walletHost !== 'app';
|
|
7
|
+
}
|
|
8
|
+
// The credit's link: the site's own address when it gives one, else TensorPass's with the site's host, without
|
|
9
|
+
// www, as the source. A page rendered on the server has no host yet and names it once it runs in the browser.
|
|
10
|
+
export function creditHref(credit, pageHost) {
|
|
11
|
+
if (typeof credit === 'object' && credit.href) {
|
|
12
|
+
return credit.href;
|
|
13
|
+
}
|
|
14
|
+
const url = new URL(TENSORPASS_URL);
|
|
15
|
+
const source = pageHost.replace(/^www\./i, '');
|
|
16
|
+
if (source) {
|
|
17
|
+
url.searchParams.set('utm_source', source);
|
|
18
|
+
}
|
|
19
|
+
url.searchParams.set('utm_medium', 'referral');
|
|
20
|
+
url.searchParams.set('utm_campaign', 'ai_credit');
|
|
21
|
+
return url.href;
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=moduleCredit.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"moduleCredit.js","sourceRoot":"","sources":["../../../src/modules/parts/moduleCredit.ts"],"names":[],"mappings":"AAAA,yGAAyG;AACzG,4GAA4G;AAC5G,+FAA+F;AAO/F,MAAM,cAAc,GAAG,yBAAyB,CAAC;AAEjD,MAAM,UAAU,WAAW,CAAC,MAAgC,EAAE,UAA6B;IACzF,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,UAAU,KAAK,KAAK,CAAC;AACjD,CAAC;AAED,+GAA+G;AAC/G,8GAA8G;AAC9G,MAAM,UAAU,UAAU,CAAC,MAAoB,EAAE,QAAgB;IAC/D,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;QAC9C,OAAO,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;IACD,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,cAAc,CAAC,CAAC;IACpC,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;IAC/C,IAAI,MAAM,EAAE,CAAC;QACX,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;IAC7C,CAAC;IACD,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;IAC/C,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;IAClD,OAAO,GAAG,CAAC,IAAI,CAAC;AAClB,CAAC","sourcesContent":["// The TensorPass credit a module draws at its foot when the site turns `credit` on: where its link goes,\n// and whether it shows. Inside the TensorPass app the visitor is already in TensorPass, so the credit stays\n// out there. The link names the site as its source, as the credits sites wrote themselves did.\n\nimport type { WalletHost } from '@tensorpass/aiconnect';\n\n// `true` draws the credit with its link to TensorPass; `{ href }` sends the link to the site's own address.\nexport type ModuleCredit = boolean | { href?: string };\n\nconst TENSORPASS_URL = 'https://tensorpass.app/';\n\nexport function creditShown(credit: ModuleCredit | undefined, walletHost: WalletHost | null): boolean {\n return Boolean(credit) && walletHost !== 'app';\n}\n\n// The credit's link: the site's own address when it gives one, else TensorPass's with the site's host, without\n// www, as the source. A page rendered on the server has no host yet and names it once it runs in the browser.\nexport function creditHref(credit: ModuleCredit, pageHost: string): string {\n if (typeof credit === 'object' && credit.href) {\n return credit.href;\n }\n const url = new URL(TENSORPASS_URL);\n const source = pageHost.replace(/^www\\./i, '');\n if (source) {\n url.searchParams.set('utm_source', source);\n }\n url.searchParams.set('utm_medium', 'referral');\n url.searchParams.set('utm_campaign', 'ai_credit');\n return url.href;\n}\n"]}
|
package/dist/modules/types.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { ReactNode, Ref } from 'react';
|
|
|
2
2
|
import type { GuardPolicy, ToolSource } from '@tensorpass/aiconnect';
|
|
3
3
|
import type { AttachmentPolicy, PreparedAttachment } from '@tensorpass/aiconnect/attachments';
|
|
4
4
|
import type { ChatTurn } from '../useAiChat.ts';
|
|
5
|
+
import type { ModuleCredit } from './parts/moduleCredit.ts';
|
|
5
6
|
export interface ToolResultsContext {
|
|
6
7
|
attachments: PreparedAttachment[];
|
|
7
8
|
}
|
|
@@ -21,6 +22,7 @@ export interface AiModuleProps {
|
|
|
21
22
|
attachments?: AttachmentPolicy;
|
|
22
23
|
renderToolResults?: (turn: ChatTurn, context: ToolResultsContext) => ReactNode;
|
|
23
24
|
footer?: ReactNode;
|
|
25
|
+
credit?: ModuleCredit;
|
|
24
26
|
analytics?: string;
|
|
25
27
|
ref?: Ref<AiModuleHandle>;
|
|
26
28
|
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, the site's own line under the question box, and the handle
|
|
4
|
-
// through. The modules that float over the page add how they open.
|
|
3
|
+
// its tool results, the site's own line and the TensorPass credit under the question box, and the handle
|
|
4
|
+
// its own controls ask 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,yGAAyG;AACzG,wFAAwF","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 and the TensorPass credit under the question box, and the handle\n// its own controls ask 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';\nimport type { ModuleCredit } from './parts/moduleCredit.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 // The TensorPass mark and the line \"AI features powered by TensorPass\" in the page's language, under the\n // question box beside `footer`, linked to TensorPass with the site's host as the source. `{ href }` sends\n // the link to the site's own address. Inside the TensorPass app, where the visitor already is, it stays out.\n credit?: ModuleCredit;\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
|
@@ -656,6 +656,7 @@
|
|
|
656
656
|
/* src/modules/styles/answer.css */
|
|
657
657
|
.aic-answer {
|
|
658
658
|
display: grid;
|
|
659
|
+
grid-template-columns: minmax(0, 1fr);
|
|
659
660
|
gap: 10px;
|
|
660
661
|
width: 100%;
|
|
661
662
|
color: var(--aic-m-ink-2);
|
|
@@ -721,6 +722,84 @@
|
|
|
721
722
|
.aic-answer a:hover {
|
|
722
723
|
text-decoration-color: currentColor;
|
|
723
724
|
}
|
|
725
|
+
.aic-answer .aic-code {
|
|
726
|
+
min-width: 0;
|
|
727
|
+
overflow: hidden;
|
|
728
|
+
border: 1px solid var(--aic-border);
|
|
729
|
+
border-radius: 12px;
|
|
730
|
+
background: var(--aic-m-fill);
|
|
731
|
+
}
|
|
732
|
+
.aic-code-bar {
|
|
733
|
+
display: flex;
|
|
734
|
+
align-items: center;
|
|
735
|
+
gap: 8px;
|
|
736
|
+
min-height: 34px;
|
|
737
|
+
padding-block: 2px;
|
|
738
|
+
padding-inline: 12px 4px;
|
|
739
|
+
border-block-end: 1px solid var(--aic-border);
|
|
740
|
+
}
|
|
741
|
+
.aic-code-language {
|
|
742
|
+
overflow: hidden;
|
|
743
|
+
color: var(--aic-muted);
|
|
744
|
+
font-family: var(--aic-mono);
|
|
745
|
+
font-size: 12px;
|
|
746
|
+
font-weight: 600;
|
|
747
|
+
line-height: 1.2;
|
|
748
|
+
text-overflow: ellipsis;
|
|
749
|
+
white-space: nowrap;
|
|
750
|
+
}
|
|
751
|
+
.aic-code-copy {
|
|
752
|
+
display: inline-flex;
|
|
753
|
+
flex: none;
|
|
754
|
+
align-items: center;
|
|
755
|
+
gap: 6px;
|
|
756
|
+
min-height: 28px;
|
|
757
|
+
margin: 0;
|
|
758
|
+
margin-inline-start: auto;
|
|
759
|
+
padding: 4px 8px;
|
|
760
|
+
border: 0;
|
|
761
|
+
border-radius: 8px;
|
|
762
|
+
background: none;
|
|
763
|
+
color: var(--aic-muted);
|
|
764
|
+
font-family: inherit;
|
|
765
|
+
font-size: 13px;
|
|
766
|
+
font-weight: 700;
|
|
767
|
+
line-height: 1.2;
|
|
768
|
+
cursor: pointer;
|
|
769
|
+
}
|
|
770
|
+
.aic-code-copy:hover,
|
|
771
|
+
.aic-code-copy[data-copied] {
|
|
772
|
+
color: var(--aic-ink);
|
|
773
|
+
}
|
|
774
|
+
.aic-code-copy svg {
|
|
775
|
+
width: 14px;
|
|
776
|
+
height: 14px;
|
|
777
|
+
}
|
|
778
|
+
.aic-answer pre {
|
|
779
|
+
margin: 0;
|
|
780
|
+
padding: 12px 14px;
|
|
781
|
+
overflow-x: auto;
|
|
782
|
+
color: var(--aic-ink);
|
|
783
|
+
font-family: var(--aic-mono);
|
|
784
|
+
font-size: 13.5px;
|
|
785
|
+
line-height: 1.55;
|
|
786
|
+
text-align: left;
|
|
787
|
+
white-space: pre;
|
|
788
|
+
overflow-wrap: normal;
|
|
789
|
+
tab-size: 2;
|
|
790
|
+
-webkit-overflow-scrolling: touch;
|
|
791
|
+
}
|
|
792
|
+
.aic-answer pre:focus-visible {
|
|
793
|
+
outline: 2px solid var(--aic-focus);
|
|
794
|
+
outline-offset: -2px;
|
|
795
|
+
}
|
|
796
|
+
.aic-answer pre code {
|
|
797
|
+
padding: 0;
|
|
798
|
+
border-radius: 0;
|
|
799
|
+
background: none;
|
|
800
|
+
font-size: inherit;
|
|
801
|
+
font-weight: 400;
|
|
802
|
+
}
|
|
724
803
|
.aic-caret {
|
|
725
804
|
display: inline-block;
|
|
726
805
|
width: 8px;
|
|
@@ -886,6 +965,24 @@
|
|
|
886
965
|
.aic-module-foot a {
|
|
887
966
|
color: inherit;
|
|
888
967
|
}
|
|
968
|
+
.aic-credit {
|
|
969
|
+
display: inline-flex;
|
|
970
|
+
align-items: center;
|
|
971
|
+
gap: 0.4em;
|
|
972
|
+
vertical-align: middle;
|
|
973
|
+
text-decoration: none;
|
|
974
|
+
}
|
|
975
|
+
.aic-module-foot > * + .aic-credit {
|
|
976
|
+
margin-inline-start: 10px;
|
|
977
|
+
}
|
|
978
|
+
.aic-credit:hover {
|
|
979
|
+
text-decoration: underline;
|
|
980
|
+
}
|
|
981
|
+
.aic-credit-mark {
|
|
982
|
+
flex: none;
|
|
983
|
+
width: 0.85em;
|
|
984
|
+
height: 0.85em;
|
|
985
|
+
}
|
|
889
986
|
.aic-search .aic-module-foot {
|
|
890
987
|
padding: 0;
|
|
891
988
|
text-align: start;
|
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,W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CAAC;QAC1F,CAAC,CAAC,CAAC;QACH,UAAU,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO;QACL,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,cAAc,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,IAAI,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,IAAI,IAAI;QAC5G,SAAS,EAAE,KAAK,CAAC,MAAM,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 { 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"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AC,CAAC,CAAC;IAEb,uGAAuG;IACvG,MAAM,cAAc,GAAG,WAAW,CAAC,GAAG,EAAE;QACtC,QAAQ,CAAC,CAAC,OAAO,EAAE,EAAE;YACnB,MAAM,IAAI,GAAG,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;YAC5B,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;QAC1F,CAAC,CAAC,CAAC;QACH,UAAU,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO;QACL,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,cAAc,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,IAAI,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,IAAI,IAAI;QAC5G,SAAS,EAAE,KAAK,CAAC,MAAM,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.11",
|
|
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.11",
|
|
38
|
+
"@tensorpass/aiconnect-design": "0.1.11"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"react": ">=19"
|