@widgetic/chat 0.1.39 → 0.1.40
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 +71 -0
- package/dist/components/Chat.svelte +35 -1
- package/dist/components/Chat.svelte.d.ts +29 -0
- package/dist/components/ChatComposer.svelte +5 -1
- package/dist/components/ChatMessages.svelte +545 -210
- package/dist/components/ChatMessages.svelte.d.ts +18 -0
- package/dist/components/agent/AgentAvatar.svelte +153 -0
- package/dist/components/agent/AgentAvatar.svelte.d.ts +27 -0
- package/dist/components/agent/AgentTurn.svelte +64 -0
- package/dist/components/agent/AgentTurn.svelte.d.ts +32 -0
- package/dist/components/agent/AvatarBoundary.svelte +29 -0
- package/dist/components/agent/AvatarBoundary.svelte.d.ts +20 -0
- package/dist/components/agent/CodeCard.svelte +288 -0
- package/dist/components/agent/CodeCard.svelte.d.ts +12 -0
- package/dist/components/agent/GenerationModule.svelte +99 -0
- package/dist/components/agent/GenerationModule.svelte.d.ts +16 -0
- package/dist/components/agent/MemberAvatar.svelte +87 -0
- package/dist/components/agent/MemberAvatar.svelte.d.ts +8 -0
- package/dist/components/index.d.ts +5 -0
- package/dist/components/index.js +9 -0
- package/dist/i18n/messages.d.ts +31 -9
- package/dist/i18n/messages.js +31 -9
- package/dist/types/agent.d.ts +74 -0
- package/dist/types/agent.js +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js +2 -0
- package/dist/utils/agentTurn.d.ts +219 -0
- package/dist/utils/agentTurn.js +301 -0
- package/dist/utils/bubbleFit.d.ts +75 -0
- package/dist/utils/bubbleFit.js +116 -0
- package/dist/utils/bubbleShrinkWrap.d.ts +32 -0
- package/dist/utils/bubbleShrinkWrap.js +360 -0
- package/dist/utils/codeHighlight.d.ts +13 -0
- package/dist/utils/codeHighlight.js +61 -0
- package/dist/utils/codePrettier.d.ts +6 -0
- package/dist/utils/codePrettier.js +34 -0
- package/dist/utils/codeStreamFormat.d.ts +90 -0
- package/dist/utils/codeStreamFormat.js +429 -0
- package/dist/utils/generationArchiveStore.d.ts +5 -0
- package/dist/utils/generationArchiveStore.js +1 -0
- package/dist/utils/index.d.ts +2 -0
- package/dist/utils/index.js +3 -0
- package/package.json +3 -2
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Formatting code while it is still being written.
|
|
3
|
+
*
|
|
4
|
+
* The code card shows what the assistant has written so far, formatted the way Prettier would. Prettier needs a whole
|
|
5
|
+
* program, and what has arrived is the first part of one: it ends in the middle of a function, of a JSX element, of a line.
|
|
6
|
+
* So the text is cut after its last whole line, whatever is still open at the cut is closed (`)`, `]`, `}` and the closing
|
|
7
|
+
* tags of the elements that are open), the result is formatted, and the formatted text is cut again where the real text
|
|
8
|
+
* ended (Prettier maps a cursor position through the formatting for that), so the closing text added for the format never
|
|
9
|
+
* shows. What came after the cut (the line being typed) follows as it is.
|
|
10
|
+
*
|
|
11
|
+
* Everything here is plain TypeScript with no import of Prettier (the caller hands in `format`), so it is tested as it is.
|
|
12
|
+
*/
|
|
13
|
+
/** What is known at one line break of the text. */
|
|
14
|
+
export interface LineEndSnapshot {
|
|
15
|
+
/** The index just after the line break: the text before it is whole lines. */
|
|
16
|
+
index: number;
|
|
17
|
+
/**
|
|
18
|
+
* What closes everything that is still open at this line break, or null when the line break is inside a string, a comment,
|
|
19
|
+
* a template or a tag (a cut there cannot be completed).
|
|
20
|
+
*/
|
|
21
|
+
closers: string | null;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Reads the text once and notes, at each of its last line breaks, what is open there. It knows strings, template literals,
|
|
25
|
+
* comments, regular expressions, brackets and JSX (tags, attributes, expression containers and text), which is what code
|
|
26
|
+
* made by an assistant for a widget is made of. It does not have to be a parser: whatever it gets wrong makes a cut that
|
|
27
|
+
* Prettier then refuses, and the next earlier cut is tried.
|
|
28
|
+
*
|
|
29
|
+
* @param source The code so far.
|
|
30
|
+
* @param keepLast How many of the last line breaks to keep (the cuts worth trying are the newest ones).
|
|
31
|
+
*/
|
|
32
|
+
export declare function scanLineEnds(source: string, keepLast?: number): LineEndSnapshot[];
|
|
33
|
+
/** What the code is, for the words that colour it and for whether Prettier can format it. */
|
|
34
|
+
export type CodeKind = 'script' | 'markup' | 'json' | 'plain';
|
|
35
|
+
/** Reads the start of the code to tell what it is. Code that starts in the middle of a file is plain: nothing is guessed. */
|
|
36
|
+
export declare function detectCodeKind(source: string): CodeKind;
|
|
37
|
+
/** The number of lines of the code, the way an editor counts them (a last line break does not start a line). */
|
|
38
|
+
export declare function countCodeLines(source: string): number;
|
|
39
|
+
/**
|
|
40
|
+
* Formats a whole text and tells where the character at `cursorOffset` ended up, the way Prettier's `formatWithCursor` does.
|
|
41
|
+
* It rejects when the text does not parse.
|
|
42
|
+
*/
|
|
43
|
+
export type FormatWithCursor = (text: string, cursorOffset: number) => Promise<{
|
|
44
|
+
formatted: string;
|
|
45
|
+
cursorOffset: number;
|
|
46
|
+
}>;
|
|
47
|
+
/** The code as the card shows it: a formatted start, then whatever has been written since as it was written. */
|
|
48
|
+
export interface FormattedCode {
|
|
49
|
+
/** The part that went through the formatter (empty when none did). */
|
|
50
|
+
formattedStart: string;
|
|
51
|
+
/** The rest, as it was written: the line being typed, or all of it when nothing could be formatted. */
|
|
52
|
+
writtenAfter: string;
|
|
53
|
+
/** What to draw: `formattedStart`, a line break, `writtenAfter`. */
|
|
54
|
+
text: string;
|
|
55
|
+
/** Whether any of it went through the formatter. */
|
|
56
|
+
isFormatted: boolean;
|
|
57
|
+
/** How many characters of the source the formatted start stands for. */
|
|
58
|
+
formattedSourceLength: number;
|
|
59
|
+
}
|
|
60
|
+
/** How many of the last line breaks are tried as the place to cut, newest first (each try is a run of Prettier). */
|
|
61
|
+
export declare const MAX_CUTS_TRIED = 8;
|
|
62
|
+
/**
|
|
63
|
+
* Whether the cut of a formatted text is the same code as the text it was cut for. Prettier never drops code, so a cut that
|
|
64
|
+
* is a lot shorter points at a wrong mapping of the cursor, and one that is a lot longer has kept the closing text.
|
|
65
|
+
*/
|
|
66
|
+
export declare function isFaithfulCut(sourcePrefix: string, formattedPrefix: string): boolean;
|
|
67
|
+
/**
|
|
68
|
+
* Formats the code that has arrived so far, as far as it can be formatted.
|
|
69
|
+
*
|
|
70
|
+
* With the whole text complete (`isComplete`) the whole text is tried first. Otherwise, or when that is refused, the text is
|
|
71
|
+
* cut after one of its last whole lines (newest first, `MAX_CUTS_TRIED` of them), what is still open there is closed, the
|
|
72
|
+
* result is formatted and cut again at the place the real text ended. Nothing parses at some cuts (a function with no body
|
|
73
|
+
* yet, a `try` with no `catch`): the next earlier one is tried. When none works the code is shown as written.
|
|
74
|
+
*
|
|
75
|
+
* It never rejects.
|
|
76
|
+
*/
|
|
77
|
+
export declare function formatCodeSoFar(source: string, format: FormatWithCursor, options: {
|
|
78
|
+
isComplete: boolean;
|
|
79
|
+
maxCutsTried?: number;
|
|
80
|
+
}): Promise<FormattedCode>;
|
|
81
|
+
/**
|
|
82
|
+
* A formatter that remembers its last result, so that a new character on the line being typed does not run Prettier again:
|
|
83
|
+
* only a new whole line (or the end of the code) does. The calls are not to overlap: the caller drops a result that was
|
|
84
|
+
* overtaken by a newer text (see `CodeCard`).
|
|
85
|
+
*/
|
|
86
|
+
export declare function createStreamingFormatter(format: FormatWithCursor): {
|
|
87
|
+
format(source: string, isComplete: boolean): Promise<FormattedCode>;
|
|
88
|
+
/** Forgets the last result (a new run starts, or the text is a different one). */
|
|
89
|
+
reset(): void;
|
|
90
|
+
};
|
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Formatting code while it is still being written.
|
|
3
|
+
*
|
|
4
|
+
* The code card shows what the assistant has written so far, formatted the way Prettier would. Prettier needs a whole
|
|
5
|
+
* program, and what has arrived is the first part of one: it ends in the middle of a function, of a JSX element, of a line.
|
|
6
|
+
* So the text is cut after its last whole line, whatever is still open at the cut is closed (`)`, `]`, `}` and the closing
|
|
7
|
+
* tags of the elements that are open), the result is formatted, and the formatted text is cut again where the real text
|
|
8
|
+
* ended (Prettier maps a cursor position through the formatting for that), so the closing text added for the format never
|
|
9
|
+
* shows. What came after the cut (the line being typed) follows as it is.
|
|
10
|
+
*
|
|
11
|
+
* Everything here is plain TypeScript with no import of Prettier (the caller hands in `format`), so it is tested as it is.
|
|
12
|
+
*/
|
|
13
|
+
const IDENTIFIER_CHARACTER = /[A-Za-z0-9_$]/;
|
|
14
|
+
const TAG_NAME_START = /[A-Za-z]/;
|
|
15
|
+
const TAG_NAME_CHARACTER = /[A-Za-z0-9_.:$-]/;
|
|
16
|
+
const WHITESPACE = /\s/;
|
|
17
|
+
/** The characters after which an expression starts, so a `<` begins a JSX element and a `/` a regular expression. */
|
|
18
|
+
const EXPRESSION_START_CHARACTERS = '([{,=:?!&|+-*%^~<>;}';
|
|
19
|
+
/** The words after which an expression starts (`return <div />`, `typeof /x/`). */
|
|
20
|
+
const EXPRESSION_START_WORDS = new Set([
|
|
21
|
+
'return',
|
|
22
|
+
'case',
|
|
23
|
+
'default',
|
|
24
|
+
'yield',
|
|
25
|
+
'await',
|
|
26
|
+
'typeof',
|
|
27
|
+
'else',
|
|
28
|
+
'in',
|
|
29
|
+
'of',
|
|
30
|
+
'void',
|
|
31
|
+
'delete',
|
|
32
|
+
'throw',
|
|
33
|
+
'new',
|
|
34
|
+
'do',
|
|
35
|
+
'instanceof'
|
|
36
|
+
]);
|
|
37
|
+
/** The text that closes what is open, innermost first, or null when something open cannot be closed by text (a string, a tag). */
|
|
38
|
+
function closersOf(openFrames) {
|
|
39
|
+
let closers = '';
|
|
40
|
+
for (let frameIndex = openFrames.length - 1; frameIndex >= 0; frameIndex--) {
|
|
41
|
+
const frame = openFrames[frameIndex];
|
|
42
|
+
if (frame.kind === 'paren')
|
|
43
|
+
closers += ')';
|
|
44
|
+
else if (frame.kind === 'bracket')
|
|
45
|
+
closers += ']';
|
|
46
|
+
else if (frame.kind === 'brace')
|
|
47
|
+
closers += '}';
|
|
48
|
+
else if (frame.kind === 'element')
|
|
49
|
+
closers += `</${frame.name}>`;
|
|
50
|
+
else
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
return closers;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Reads the text once and notes, at each of its last line breaks, what is open there. It knows strings, template literals,
|
|
57
|
+
* comments, regular expressions, brackets and JSX (tags, attributes, expression containers and text), which is what code
|
|
58
|
+
* made by an assistant for a widget is made of. It does not have to be a parser: whatever it gets wrong makes a cut that
|
|
59
|
+
* Prettier then refuses, and the next earlier cut is tried.
|
|
60
|
+
*
|
|
61
|
+
* @param source The code so far.
|
|
62
|
+
* @param keepLast How many of the last line breaks to keep (the cuts worth trying are the newest ones).
|
|
63
|
+
*/
|
|
64
|
+
export function scanLineEnds(source, keepLast = 24) {
|
|
65
|
+
const openFrames = [];
|
|
66
|
+
const snapshots = [];
|
|
67
|
+
let index = 0;
|
|
68
|
+
// The last character and word of code before the point being read: they tell a JSX element or a regular expression from a
|
|
69
|
+
// comparison or a division
|
|
70
|
+
let previousSignificant = '';
|
|
71
|
+
let previousWord = '';
|
|
72
|
+
/** Notes a line break (`lineBreakIndex` is the index of the `\n`); inside a literal nothing can be completed. */
|
|
73
|
+
function noteLineBreak(lineBreakIndex, insideLiteral) {
|
|
74
|
+
snapshots.push({ index: lineBreakIndex + 1, closers: insideLiteral ? null : closersOf(openFrames) });
|
|
75
|
+
if (snapshots.length > keepLast)
|
|
76
|
+
snapshots.shift();
|
|
77
|
+
}
|
|
78
|
+
function expressionMayStart() {
|
|
79
|
+
if (previousSignificant === '')
|
|
80
|
+
return true;
|
|
81
|
+
if (EXPRESSION_START_WORDS.has(previousWord))
|
|
82
|
+
return true;
|
|
83
|
+
return EXPRESSION_START_CHARACTERS.includes(previousSignificant);
|
|
84
|
+
}
|
|
85
|
+
/** Reads a tag name from `fromIndex`; returns the index after it. */
|
|
86
|
+
function readTagName(fromIndex) {
|
|
87
|
+
let next = fromIndex;
|
|
88
|
+
while (next < source.length && TAG_NAME_CHARACTER.test(source[next] ?? ''))
|
|
89
|
+
next += 1;
|
|
90
|
+
return { name: source.slice(fromIndex, next), next };
|
|
91
|
+
}
|
|
92
|
+
while (index < source.length) {
|
|
93
|
+
const character = source[index];
|
|
94
|
+
const nextCharacter = source[index + 1] ?? '';
|
|
95
|
+
const topFrame = openFrames[openFrames.length - 1];
|
|
96
|
+
// --- inside a tag: `<div className="a" onClick={() => go()}` -------------------------------------------------
|
|
97
|
+
if (topFrame?.kind === 'tag') {
|
|
98
|
+
if (character === '\n') {
|
|
99
|
+
noteLineBreak(index, true);
|
|
100
|
+
index += 1;
|
|
101
|
+
}
|
|
102
|
+
else if (character === '"' || character === "'") {
|
|
103
|
+
// An attribute's string has no escapes and may span lines
|
|
104
|
+
index += 1;
|
|
105
|
+
while (index < source.length && source[index] !== character) {
|
|
106
|
+
if (source[index] === '\n')
|
|
107
|
+
noteLineBreak(index, true);
|
|
108
|
+
index += 1;
|
|
109
|
+
}
|
|
110
|
+
index += 1;
|
|
111
|
+
}
|
|
112
|
+
else if (character === '{') {
|
|
113
|
+
openFrames.push({ kind: 'brace' });
|
|
114
|
+
previousSignificant = '{';
|
|
115
|
+
previousWord = '';
|
|
116
|
+
index += 1;
|
|
117
|
+
}
|
|
118
|
+
else if (character === '/' && nextCharacter === '>') {
|
|
119
|
+
// <br /> : nothing was opened
|
|
120
|
+
openFrames.pop();
|
|
121
|
+
previousSignificant = '>';
|
|
122
|
+
previousWord = '';
|
|
123
|
+
index += 2;
|
|
124
|
+
}
|
|
125
|
+
else if (character === '>') {
|
|
126
|
+
openFrames.pop();
|
|
127
|
+
if (topFrame.closing) {
|
|
128
|
+
if (openFrames[openFrames.length - 1]?.kind === 'element')
|
|
129
|
+
openFrames.pop();
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
openFrames.push({ kind: 'element', name: topFrame.name });
|
|
133
|
+
}
|
|
134
|
+
previousSignificant = '>';
|
|
135
|
+
previousWord = '';
|
|
136
|
+
index += 1;
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
index += 1;
|
|
140
|
+
}
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
// --- inside the text of a template literal ---------------------------------------------------------------------
|
|
144
|
+
if (topFrame?.kind === 'template') {
|
|
145
|
+
if (character === '\\') {
|
|
146
|
+
index += 2;
|
|
147
|
+
}
|
|
148
|
+
else if (character === '`') {
|
|
149
|
+
openFrames.pop();
|
|
150
|
+
previousSignificant = '`';
|
|
151
|
+
previousWord = '';
|
|
152
|
+
index += 1;
|
|
153
|
+
}
|
|
154
|
+
else if (character === '$' && nextCharacter === '{') {
|
|
155
|
+
openFrames.push({ kind: 'brace' });
|
|
156
|
+
previousSignificant = '{';
|
|
157
|
+
previousWord = '';
|
|
158
|
+
index += 2;
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
if (character === '\n')
|
|
162
|
+
noteLineBreak(index, true);
|
|
163
|
+
index += 1;
|
|
164
|
+
}
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
// --- inside the children of a JSX element: text, tags and `{expressions}` ---------------------------------------
|
|
168
|
+
if (topFrame?.kind === 'element') {
|
|
169
|
+
if (character === '<' && nextCharacter === '/') {
|
|
170
|
+
const { name, next } = readTagName(index + 2);
|
|
171
|
+
openFrames.push({ kind: 'tag', name, closing: true });
|
|
172
|
+
index = next;
|
|
173
|
+
}
|
|
174
|
+
else if (character === '<' && (TAG_NAME_START.test(nextCharacter) || nextCharacter === '>')) {
|
|
175
|
+
const { name, next } = readTagName(index + 1);
|
|
176
|
+
openFrames.push({ kind: 'tag', name, closing: false });
|
|
177
|
+
index = next;
|
|
178
|
+
}
|
|
179
|
+
else if (character === '{') {
|
|
180
|
+
openFrames.push({ kind: 'brace' });
|
|
181
|
+
previousSignificant = '{';
|
|
182
|
+
previousWord = '';
|
|
183
|
+
index += 1;
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
186
|
+
if (character === '\n')
|
|
187
|
+
noteLineBreak(index, false);
|
|
188
|
+
index += 1;
|
|
189
|
+
}
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
// --- code (the top level, or inside brackets and braces) -------------------------------------------------------
|
|
193
|
+
if (character === '\n') {
|
|
194
|
+
noteLineBreak(index, false);
|
|
195
|
+
index += 1;
|
|
196
|
+
}
|
|
197
|
+
else if (WHITESPACE.test(character)) {
|
|
198
|
+
index += 1;
|
|
199
|
+
}
|
|
200
|
+
else if (character === '/' && nextCharacter === '/') {
|
|
201
|
+
// A line comment runs to the end of the line (the line break itself is read next)
|
|
202
|
+
while (index < source.length && source[index] !== '\n')
|
|
203
|
+
index += 1;
|
|
204
|
+
}
|
|
205
|
+
else if (character === '/' && nextCharacter === '*') {
|
|
206
|
+
index += 2;
|
|
207
|
+
while (index < source.length && !(source[index] === '*' && source[index + 1] === '/')) {
|
|
208
|
+
if (source[index] === '\n')
|
|
209
|
+
noteLineBreak(index, true);
|
|
210
|
+
index += 1;
|
|
211
|
+
}
|
|
212
|
+
index += 2;
|
|
213
|
+
}
|
|
214
|
+
else if (character === '"' || character === "'") {
|
|
215
|
+
index += 1;
|
|
216
|
+
while (index < source.length && source[index] !== character && source[index] !== '\n') {
|
|
217
|
+
index += source[index] === '\\' ? 2 : 1;
|
|
218
|
+
}
|
|
219
|
+
// A string that stops at a line break was never closed: the break is read as a line break inside a literal
|
|
220
|
+
if (source[index] === '\n')
|
|
221
|
+
noteLineBreak(index, true);
|
|
222
|
+
index += 1;
|
|
223
|
+
previousSignificant = character;
|
|
224
|
+
previousWord = '';
|
|
225
|
+
}
|
|
226
|
+
else if (character === '`') {
|
|
227
|
+
openFrames.push({ kind: 'template' });
|
|
228
|
+
index += 1;
|
|
229
|
+
}
|
|
230
|
+
else if (character === '(' || character === '[' || character === '{') {
|
|
231
|
+
openFrames.push({ kind: character === '(' ? 'paren' : character === '[' ? 'bracket' : 'brace' });
|
|
232
|
+
previousSignificant = character;
|
|
233
|
+
previousWord = '';
|
|
234
|
+
index += 1;
|
|
235
|
+
}
|
|
236
|
+
else if (character === ')' || character === ']' || character === '}') {
|
|
237
|
+
const wantedKind = character === ')' ? 'paren' : character === ']' ? 'bracket' : 'brace';
|
|
238
|
+
if (topFrame?.kind === wantedKind)
|
|
239
|
+
openFrames.pop();
|
|
240
|
+
previousSignificant = character;
|
|
241
|
+
previousWord = '';
|
|
242
|
+
index += 1;
|
|
243
|
+
}
|
|
244
|
+
else if (character === '<' && (TAG_NAME_START.test(nextCharacter) || nextCharacter === '>') && expressionMayStart()) {
|
|
245
|
+
const { name, next } = readTagName(index + 1);
|
|
246
|
+
openFrames.push({ kind: 'tag', name, closing: false });
|
|
247
|
+
index = next;
|
|
248
|
+
}
|
|
249
|
+
else if (character === '/' && expressionMayStart()) {
|
|
250
|
+
// A regular expression: up to the next `/` that is not escaped and not inside [...]
|
|
251
|
+
index += 1;
|
|
252
|
+
let insideClass = false;
|
|
253
|
+
while (index < source.length && source[index] !== '\n') {
|
|
254
|
+
const regexCharacter = source[index];
|
|
255
|
+
if (regexCharacter === '\\')
|
|
256
|
+
index += 1;
|
|
257
|
+
else if (regexCharacter === '[')
|
|
258
|
+
insideClass = true;
|
|
259
|
+
else if (regexCharacter === ']')
|
|
260
|
+
insideClass = false;
|
|
261
|
+
else if (regexCharacter === '/' && !insideClass)
|
|
262
|
+
break;
|
|
263
|
+
index += 1;
|
|
264
|
+
}
|
|
265
|
+
index += 1;
|
|
266
|
+
previousSignificant = '/';
|
|
267
|
+
previousWord = '';
|
|
268
|
+
}
|
|
269
|
+
else if (IDENTIFIER_CHARACTER.test(character)) {
|
|
270
|
+
let wordEnd = index;
|
|
271
|
+
while (wordEnd < source.length && IDENTIFIER_CHARACTER.test(source[wordEnd] ?? ''))
|
|
272
|
+
wordEnd += 1;
|
|
273
|
+
previousWord = source.slice(index, wordEnd);
|
|
274
|
+
previousSignificant = source[wordEnd - 1];
|
|
275
|
+
index = wordEnd;
|
|
276
|
+
}
|
|
277
|
+
else {
|
|
278
|
+
previousSignificant = character;
|
|
279
|
+
previousWord = '';
|
|
280
|
+
index += 1;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return snapshots;
|
|
284
|
+
}
|
|
285
|
+
// --- what kind of code it is -----------------------------------------------------------------------------------------
|
|
286
|
+
/** The start of a script (JavaScript, TypeScript, JSX, TSX): a directive, an import or export, or a declaration. */
|
|
287
|
+
const SCRIPT_START = /^(?:\s*(?:\/\/[^\n]*|\/\*[\s\S]*?\*\/))*\s*(?:['"]use (?:client|strict|server)['"];?|import\b|export\b|const\b|let\b|var\b|function\b|async\b|class\b|interface\b|type\b|enum\b|declare\b|namespace\b|abstract\b|@)/;
|
|
288
|
+
/** The start of a page or a Svelte component, which Prettier has no parser for here. */
|
|
289
|
+
const MARKUP_START = /^\s*(?:<!doctype|<html|<script|<style|<svelte|<template)/i;
|
|
290
|
+
/** Reads the start of the code to tell what it is. Code that starts in the middle of a file is plain: nothing is guessed. */
|
|
291
|
+
export function detectCodeKind(source) {
|
|
292
|
+
const start = source.slice(0, 400);
|
|
293
|
+
if (MARKUP_START.test(start))
|
|
294
|
+
return 'markup';
|
|
295
|
+
if (SCRIPT_START.test(start))
|
|
296
|
+
return 'script';
|
|
297
|
+
if (/^\s*[[{]/.test(start) && /["']\s*:/.test(start))
|
|
298
|
+
return 'json';
|
|
299
|
+
if (/^\s*</.test(start))
|
|
300
|
+
return 'markup';
|
|
301
|
+
return 'plain';
|
|
302
|
+
}
|
|
303
|
+
/** The number of lines of the code, the way an editor counts them (a last line break does not start a line). */
|
|
304
|
+
export function countCodeLines(source) {
|
|
305
|
+
if (source.trim() === '')
|
|
306
|
+
return 0;
|
|
307
|
+
const trimmedSource = source.endsWith('\n') ? source.slice(0, -1) : source;
|
|
308
|
+
let lineCount = 1;
|
|
309
|
+
for (let index = 0; index < trimmedSource.length; index++)
|
|
310
|
+
if (trimmedSource[index] === '\n')
|
|
311
|
+
lineCount += 1;
|
|
312
|
+
return lineCount;
|
|
313
|
+
}
|
|
314
|
+
/** Joins a formatted start and what was written after it. */
|
|
315
|
+
function composeFormattedCode(formattedStart, writtenAfter, formattedSourceLength) {
|
|
316
|
+
const text = formattedStart === '' ? writtenAfter : writtenAfter === '' ? formattedStart : `${formattedStart}\n${writtenAfter}`;
|
|
317
|
+
return { formattedStart, writtenAfter, text, isFormatted: formattedStart !== '', formattedSourceLength };
|
|
318
|
+
}
|
|
319
|
+
/** How many of the last line breaks are tried as the place to cut, newest first (each try is a run of Prettier). */
|
|
320
|
+
export const MAX_CUTS_TRIED = 8;
|
|
321
|
+
/** Without spaces and the marks Prettier adds or takes away, so two versions of a text can be compared by their words. */
|
|
322
|
+
function squeezeForComparison(text) {
|
|
323
|
+
return text.replace(/[\s,;()]/g, '');
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Where to cut the formatted text: at the cursor, and after the `;` or `,` that Prettier put right behind it (the end of the
|
|
327
|
+
* last statement, the trailing comma of the last item). The closing text added for the format holds no such marks, so the ones
|
|
328
|
+
* that follow the cursor are Prettier's own, and they belong to the line that ends at the cursor.
|
|
329
|
+
*/
|
|
330
|
+
function keepAddedPunctuation(formatted, cursorOffset) {
|
|
331
|
+
let end = cursorOffset;
|
|
332
|
+
while (end < formatted.length && (formatted[end] === ';' || formatted[end] === ','))
|
|
333
|
+
end += 1;
|
|
334
|
+
return end;
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Whether the cut of a formatted text is the same code as the text it was cut for. Prettier never drops code, so a cut that
|
|
338
|
+
* is a lot shorter points at a wrong mapping of the cursor, and one that is a lot longer has kept the closing text.
|
|
339
|
+
*/
|
|
340
|
+
export function isFaithfulCut(sourcePrefix, formattedPrefix) {
|
|
341
|
+
const sourceLength = squeezeForComparison(sourcePrefix).length;
|
|
342
|
+
const formattedLength = squeezeForComparison(formattedPrefix).length;
|
|
343
|
+
return formattedLength >= sourceLength * 0.9 - 4 && formattedLength <= sourceLength * 1.1 + 8;
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Formats the code that has arrived so far, as far as it can be formatted.
|
|
347
|
+
*
|
|
348
|
+
* With the whole text complete (`isComplete`) the whole text is tried first. Otherwise, or when that is refused, the text is
|
|
349
|
+
* cut after one of its last whole lines (newest first, `MAX_CUTS_TRIED` of them), what is still open there is closed, the
|
|
350
|
+
* result is formatted and cut again at the place the real text ended. Nothing parses at some cuts (a function with no body
|
|
351
|
+
* yet, a `try` with no `catch`): the next earlier one is tried. When none works the code is shown as written.
|
|
352
|
+
*
|
|
353
|
+
* It never rejects.
|
|
354
|
+
*/
|
|
355
|
+
export async function formatCodeSoFar(source, format, options) {
|
|
356
|
+
if (source.trim() === '')
|
|
357
|
+
return composeFormattedCode('', source, 0);
|
|
358
|
+
// Only scripts are laid out: Prettier recovers from errors in what it reads, so it would "format" a page or a Svelte
|
|
359
|
+
// component into something that is not what was written
|
|
360
|
+
if (detectCodeKind(source) !== 'script')
|
|
361
|
+
return composeFormattedCode('', source, 0);
|
|
362
|
+
if (options.isComplete) {
|
|
363
|
+
try {
|
|
364
|
+
const whole = await format(source, source.length);
|
|
365
|
+
return composeFormattedCode(whole.formatted.trimEnd(), '', source.length);
|
|
366
|
+
}
|
|
367
|
+
catch {
|
|
368
|
+
// It does not parse as a whole (a gap between two parts of the stream, a language Prettier has no parser for here):
|
|
369
|
+
// the cuts below format as much of it as can be
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
const maxCutsTried = options.maxCutsTried ?? MAX_CUTS_TRIED;
|
|
373
|
+
const cuts = scanLineEnds(source, maxCutsTried * 3)
|
|
374
|
+
.filter((cut) => cut.closers !== null)
|
|
375
|
+
.reverse()
|
|
376
|
+
.slice(0, maxCutsTried);
|
|
377
|
+
for (const cut of cuts) {
|
|
378
|
+
const sourcePrefix = source.slice(0, cut.index).trimEnd();
|
|
379
|
+
if (sourcePrefix === '')
|
|
380
|
+
continue;
|
|
381
|
+
const closers = cut.closers ?? '';
|
|
382
|
+
const textToFormat = closers ? `${sourcePrefix}\n${closers}` : sourcePrefix;
|
|
383
|
+
try {
|
|
384
|
+
const result = await format(textToFormat, sourcePrefix.length);
|
|
385
|
+
// The cursor is not mapped when the text has no place for it
|
|
386
|
+
if (result.cursorOffset < 0)
|
|
387
|
+
continue;
|
|
388
|
+
const formattedPrefix = result.formatted.slice(0, keepAddedPunctuation(result.formatted, result.cursorOffset)).trimEnd();
|
|
389
|
+
if (!isFaithfulCut(sourcePrefix, formattedPrefix))
|
|
390
|
+
continue;
|
|
391
|
+
return composeFormattedCode(formattedPrefix, source.slice(cut.index), cut.index);
|
|
392
|
+
}
|
|
393
|
+
catch {
|
|
394
|
+
// This cut does not parse yet: the next earlier one is tried
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
return composeFormattedCode('', source, 0);
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* A formatter that remembers its last result, so that a new character on the line being typed does not run Prettier again:
|
|
401
|
+
* only a new whole line (or the end of the code) does. The calls are not to overlap: the caller drops a result that was
|
|
402
|
+
* overtaken by a newer text (see `CodeCard`).
|
|
403
|
+
*/
|
|
404
|
+
export function createStreamingFormatter(format) {
|
|
405
|
+
/** The last cut that was formatted when it was the newest line break of the text. */
|
|
406
|
+
let remembered = null;
|
|
407
|
+
return {
|
|
408
|
+
async format(source, isComplete) {
|
|
409
|
+
if (remembered && !isComplete && source.startsWith(remembered.sourcePrefix)) {
|
|
410
|
+
const writtenAfter = source.slice(remembered.sourcePrefix.length);
|
|
411
|
+
// No line break since the cut: only the line being typed has changed
|
|
412
|
+
if (!writtenAfter.includes('\n')) {
|
|
413
|
+
return composeFormattedCode(remembered.formattedStart, writtenAfter, remembered.sourcePrefix.length);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
const result = await formatCodeSoFar(source, format, { isComplete });
|
|
417
|
+
const cutWasNewestLineBreak = !source.slice(result.formattedSourceLength).includes('\n');
|
|
418
|
+
remembered =
|
|
419
|
+
result.isFormatted && !isComplete && cutWasNewestLineBreak
|
|
420
|
+
? { sourcePrefix: source.slice(0, result.formattedSourceLength), formattedStart: result.formattedStart }
|
|
421
|
+
: null;
|
|
422
|
+
return result;
|
|
423
|
+
},
|
|
424
|
+
/** Forgets the last result (a new run starts, or the text is a different one). */
|
|
425
|
+
reset() {
|
|
426
|
+
remembered = null;
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
}
|
|
@@ -3,6 +3,11 @@ export type GenerationArchiveRecord = {
|
|
|
3
3
|
thinking: string;
|
|
4
4
|
code: string;
|
|
5
5
|
thoughtSeconds: number | null;
|
|
6
|
+
/**
|
|
7
|
+
* The words of the prompt this work answered, so it is shown under that turn and under no other (a reload brings back the
|
|
8
|
+
* last run of a conversation, which is not always the turn that is newest now). Records saved before this was kept have none.
|
|
9
|
+
*/
|
|
10
|
+
prompt?: string;
|
|
6
11
|
updatedAt: number;
|
|
7
12
|
};
|
|
8
13
|
export declare function loadGenerationArchive(conversationId: string | null | undefined): Promise<GenerationArchiveRecord | null>;
|
|
@@ -37,6 +37,7 @@ export async function loadGenerationArchive(conversationId) {
|
|
|
37
37
|
thinking: row.thinking ?? '',
|
|
38
38
|
code: row.code ?? '',
|
|
39
39
|
thoughtSeconds: row.thoughtSeconds ?? null,
|
|
40
|
+
prompt: typeof row.prompt === 'string' ? row.prompt : '',
|
|
40
41
|
updatedAt: row.updatedAt ?? 0,
|
|
41
42
|
});
|
|
42
43
|
};
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -6,4 +6,6 @@ export { readThinkingTail, readCodegenStreamTail, generationActivityPhase, thoug
|
|
|
6
6
|
export type { GenerationActivityPhase } from './generationActivity.js';
|
|
7
7
|
export { readGenerationPlanFromMetadata, mapWidgetPlanToPlanCard, } from './generationPlan.js';
|
|
8
8
|
export type { GenerationPlanWire, MappedGenerationPlanCard, WidgetPlanTaskStatusWire, } from './generationPlan.js';
|
|
9
|
+
export { AGENT_AVATAR_PIXELS, CURRENT_USER_PLACEHOLDER_ID, LOCAL_SERVICE_USER_ID, MAX_KEPT_GENERATION_CHARS, agentAvatarLabelKey, agentAvatarPixels, agentLookSignature, avatarStartAfter, finishedGenerationBelongsTo, finishedModulesView, keepFinishedGeneration, keptWorkIsOutdated, liveAgentLook, liveModulesView, memberDisplayName, memberMailtoHref, memberTooltipEmail, normalizePromptText, pageNamesPeople, resolveChatMember, settledAgentLook, soundStateOf, turnOutcome } from './agentTurn.js';
|
|
10
|
+
export type { AgentAvatarSize, AgentLook, AvatarStart, FinishedGeneration, GenerationModulesView, SoundStateInput, TurnOutcome, TurnReplyFacts } from './agentTurn.js';
|
|
9
11
|
export type { AttachmentType, AttachmentValidation, PendingAttachment, UploadStatus } from '../types/index.js';
|
package/dist/utils/index.js
CHANGED
|
@@ -6,3 +6,6 @@ export { VERSION_RATINGS, ratingAfterPress, ratingOfVersion, isRatableVersionRep
|
|
|
6
6
|
export { setLogsEnabled, chatLog, chatWarn, chatError } from './logger.js';
|
|
7
7
|
export { readThinkingTail, readCodegenStreamTail, generationActivityPhase, thoughtDurationSeconds, generationActivityAriaKey, } from './generationActivity.js';
|
|
8
8
|
export { readGenerationPlanFromMetadata, mapWidgetPlanToPlanCard, } from './generationPlan.js';
|
|
9
|
+
// The assistant's turn: its avatar's looks, the judgement of a finished turn, who wrote a message, what is kept of the work.
|
|
10
|
+
// A page that is not the chat (the workflows assistant) follows the same choreography through these.
|
|
11
|
+
export { AGENT_AVATAR_PIXELS, CURRENT_USER_PLACEHOLDER_ID, LOCAL_SERVICE_USER_ID, MAX_KEPT_GENERATION_CHARS, agentAvatarLabelKey, agentAvatarPixels, agentLookSignature, avatarStartAfter, finishedGenerationBelongsTo, finishedModulesView, keepFinishedGeneration, keptWorkIsOutdated, liveAgentLook, liveModulesView, memberDisplayName, memberMailtoHref, memberTooltipEmail, normalizePromptText, pageNamesPeople, resolveChatMember, settledAgentLook, soundStateOf, turnOutcome } from './agentTurn.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@widgetic/chat",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.40",
|
|
4
4
|
"license": "SEE LICENSE IN LICENSE",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -61,7 +61,9 @@
|
|
|
61
61
|
"svelte": "^5.25.6"
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
64
|
+
"@chenglou/pretext": "^1.0.0",
|
|
64
65
|
"highlight.js": "^11.11.1",
|
|
66
|
+
"prettier": "^3.1.1",
|
|
65
67
|
"socket.io-client": "^4.7.5"
|
|
66
68
|
},
|
|
67
69
|
"devDependencies": {
|
|
@@ -80,7 +82,6 @@
|
|
|
80
82
|
"eslint-config-prettier": "^9.1.0",
|
|
81
83
|
"eslint-plugin-svelte": "^2.36.0",
|
|
82
84
|
"postcss": "^8.5.3",
|
|
83
|
-
"prettier": "^3.1.1",
|
|
84
85
|
"prettier-plugin-svelte": "^3.1.2",
|
|
85
86
|
"svelte": "^5.25.6",
|
|
86
87
|
"svelte-check": "^4.0.0",
|