vzcode 2.34.0 → 2.36.0

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.
Files changed (52) hide show
  1. package/dist/assets/buildWorker-BZlya278.js +687 -0
  2. package/dist/assets/index-Cj-ERpBu.css +1 -0
  3. package/dist/assets/index-DD7vzp4U.js +364 -0
  4. package/dist/assets/{worker-D8p1JlHW.js → worker-1oQYaz-F.js} +251 -251
  5. package/dist/assets/worker-BfgPD8zR.js +125 -0
  6. package/dist/assets/{worker-k7HZ3t-V.js → worker-CoJaqtpi.js} +12 -12
  7. package/dist/index.html +2 -2
  8. package/dist/ot.js +180 -2
  9. package/dist/server/createServer.js +281 -0
  10. package/dist/server/index.js +6 -269
  11. package/package.json +14 -3
  12. package/src/client/CodeEditor/getOrCreateEditor.tsx +0 -14
  13. package/src/client/VZCodeContext/chatSessionHelpers.ts +17 -0
  14. package/src/client/VZCodeContext/useAIChatSession.ts +325 -0
  15. package/src/client/VZCodeContext/useVZCodeState.ts +23 -279
  16. package/src/client/VZSidebar/AIChatWrapper.tsx +85 -0
  17. package/src/client/VZSidebar/VisualEditor/VisualEditor.tsx +95 -208
  18. package/src/client/VZSidebar/VisualEditor/colorUtils.ts +39 -0
  19. package/src/client/VZSidebar/VisualEditor/status.ts +2 -40
  20. package/src/client/VZSidebar/VisualEditor/updateConfig.ts +10 -1
  21. package/src/client/VZSidebar/VisualEditor/utils.ts +49 -65
  22. package/src/client/VZSidebar/index.tsx +2 -2
  23. package/src/client/definitionJumpListeners.ts +47 -0
  24. package/src/client/useKeyboardShortcuts.ts +23 -28
  25. package/src/client/useOpenDirectories.ts +0 -1
  26. package/src/llm-streaming-server/README.md +5 -3
  27. package/src/llm-streaming-ui/README.md +44 -42
  28. package/src/llm-streaming-ui/components/ChatInput.tsx +6 -19
  29. package/src/llm-streaming-ui/components/DiffView.tsx +6 -24
  30. package/src/llm-streaming-ui/components/FileEditingIndicator.tsx +1 -1
  31. package/src/llm-streaming-ui/components/Message.tsx +11 -27
  32. package/src/llm-streaming-ui/components/MessageList.tsx +15 -29
  33. package/src/llm-streaming-ui/components/Spinner.scss +37 -0
  34. package/src/llm-streaming-ui/components/Spinner.tsx +59 -0
  35. package/src/llm-streaming-ui/components/bootstrap.ts +16 -0
  36. package/src/llm-streaming-ui/components/icons.tsx +68 -0
  37. package/src/llm-streaming-ui/components/index.tsx +34 -30
  38. package/src/llm-streaming-ui/index.ts +13 -0
  39. package/src/llm-streaming-ui/props.ts +137 -0
  40. package/src/ot.ts +221 -4
  41. package/src/server/createServer.ts +413 -0
  42. package/src/server/index.ts +8 -333
  43. package/dist/assets/buildWorker-DylWm2VX.js +0 -687
  44. package/dist/assets/index-Dyt9tpmu.css +0 -1
  45. package/dist/assets/index-nL6to42p.js +0 -364
  46. package/dist/assets/worker-b9bkZkXK.js +0 -116
  47. package/src/client/AIAssist/AIAssistCodeMirrorKeyMap.ts +0 -42
  48. package/src/client/AIAssist/generateFilesContext.ts +0 -25
  49. package/src/client/AIAssist/index.ts +0 -2
  50. package/src/client/CodeEditor/InteractiveWidgets/highlightWidgets.ts +0 -79
  51. /package/src/{client → llm-streaming-ui}/hooks/useAutoScroll.ts +0 -0
  52. /package/src/{client → llm-streaming-ui}/utils/scrollUtils.ts +0 -0
package/src/ot.ts CHANGED
@@ -15,8 +15,6 @@ DiffMatchPatch.DIFF_DELETE = DIFF_DELETE;
15
15
  DiffMatchPatch.DIFF_INSERT = DIFF_INSERT;
16
16
  DiffMatchPatch.DIFF_EQUAL = DIFF_EQUAL;
17
17
 
18
- const diffMatchPatch = DiffMatchPatch;
19
-
20
18
  export const { json1Presence, textUnicode } =
21
19
  OTJSON1Presence;
22
20
 
@@ -26,11 +24,230 @@ export const otType = json1Presence.type;
26
24
  // Applies an OT op to an object.
27
25
  export const apply = otType.apply;
28
26
 
27
+ // ---------------------------------------------------------------------------
28
+ // Unicode-safe text diffing
29
+ // ---------------------------------------------------------------------------
30
+ //
31
+ // `json0-ot-diff` asks diff-match-patch for text patches and converts the
32
+ // resulting offsets into `textUnicode` (ot-text-unicode) operations. This is
33
+ // incorrect for text containing astral-plane characters (emoji, etc.):
34
+ //
35
+ // 1. diff-match-patch measures offsets in UTF-16 code units, while
36
+ // ot-text-unicode measures them in Unicode code points.
37
+ // 2. diff-match-patch can split a surrogate pair across diffs (it may treat
38
+ // the high and low halves of an emoji as independent characters).
39
+ //
40
+ // Both produce operations that either fail to apply ("The op is too long for
41
+ // this document", "Invalid offset - splits unicode bytes") or apply
42
+ // incorrectly.
43
+ //
44
+ // The fix: when either string contains astral characters, encode each astral
45
+ // code point as a single unused BMP placeholder before diffing. One UTF-16
46
+ // unit then equals one code point and surrogate pairs can never be split. The
47
+ // generated text operation is decoded back to the original characters.
48
+ // Strings without astral characters keep using the original (correct and
49
+ // faster) code path.
50
+
51
+ const hasSurrogates = (value: string): boolean =>
52
+ /[\uD800-\uDFFF]/.test(value);
53
+
54
+ const textDiffMatchPatch = new DiffMatchPatch();
55
+
56
+ // State describing the string currently being diffed by json0-ot-diff.
57
+ let currentOldValue = '';
58
+ let currentNewValue = '';
59
+ let pendingTextEdit = false;
60
+ let needsUnicodeSafeDiff = false;
61
+
62
+ interface AstralEncoding {
63
+ encodedOldValue: string;
64
+ encodedNewValue: string;
65
+ decode: (value: string) => string;
66
+ }
67
+
68
+ // `for...of` over a string iterates code points; an astral code point is
69
+ // represented as two UTF-16 code units (i.e. `char.length === 2`).
70
+ const encodeAstralCharacters = (
71
+ oldValue: string,
72
+ newValue: string,
73
+ ): AstralEncoding | null => {
74
+ if (
75
+ !hasSurrogates(oldValue) &&
76
+ !hasSurrogates(newValue)
77
+ ) {
78
+ return null;
79
+ }
80
+
81
+ // BMP characters already used by the input, so placeholders never collide.
82
+ const used = new Set<string>();
83
+ for (const char of oldValue) used.add(char);
84
+ for (const char of newValue) used.add(char);
85
+
86
+ const astralCharacters = new Set<string>();
87
+ for (const char of oldValue) {
88
+ if (char.length === 2) astralCharacters.add(char);
89
+ }
90
+ for (const char of newValue) {
91
+ if (char.length === 2) astralCharacters.add(char);
92
+ }
93
+
94
+ const astralToPlaceholder = new Map<string, string>();
95
+ const placeholderToAstral = new Map<string, string>();
96
+
97
+ // Assign each distinct astral code point an unused, non-surrogate BMP code
98
+ // point. The BMP has ~63k usable code points, far more than the number of
99
+ // distinct astral characters found in practice.
100
+ let candidate = 0xe000;
101
+ const nextPlaceholder = (): string => {
102
+ for (let attempts = 0; attempts < 0x10000; attempts++) {
103
+ if (candidate > 0xffff) candidate = 0x0020;
104
+ const placeholder = String.fromCharCode(candidate++);
105
+ if (!used.has(placeholder)) return placeholder;
106
+ }
107
+ throw new Error(
108
+ 'Unable to encode astral characters for diffing',
109
+ );
110
+ };
111
+
112
+ for (const astral of astralCharacters) {
113
+ const placeholder = nextPlaceholder();
114
+ astralToPlaceholder.set(astral, placeholder);
115
+ placeholderToAstral.set(placeholder, astral);
116
+ }
117
+
118
+ const encode = (value: string): string => {
119
+ let encoded = '';
120
+ for (const char of value) {
121
+ encoded +=
122
+ char.length === 2
123
+ ? (astralToPlaceholder.get(char) as string)
124
+ : char;
125
+ }
126
+ return encoded;
127
+ };
128
+
129
+ const decode = (value: string): string => {
130
+ let decoded = '';
131
+ for (const char of value) {
132
+ decoded += placeholderToAstral.get(char) ?? char;
133
+ }
134
+ return decoded;
135
+ };
136
+
137
+ return {
138
+ encodedOldValue: encode(oldValue),
139
+ encodedNewValue: encode(newValue),
140
+ decode,
141
+ };
142
+ };
143
+
144
+ // Builds an ot-text-unicode operation from diff-match-patch's diffs. Skips are
145
+ // counted in code points, which (after encoding) equal UTF-16 units.
146
+ const buildTextOp = (
147
+ oldValue: string,
148
+ newValue: string,
149
+ ): Array<unknown> => {
150
+ const encoding = encodeAstralCharacters(
151
+ oldValue,
152
+ newValue,
153
+ );
154
+ const oldText = encoding
155
+ ? encoding.encodedOldValue
156
+ : oldValue;
157
+ const newText = encoding
158
+ ? encoding.encodedNewValue
159
+ : newValue;
160
+ const decode = encoding
161
+ ? encoding.decode
162
+ : (value: string) => value;
163
+
164
+ const diffs = textDiffMatchPatch.diff_main(
165
+ oldText,
166
+ newText,
167
+ );
168
+
169
+ const components: Array<unknown> = [];
170
+ for (const [operation, text] of diffs) {
171
+ if (text.length === 0) continue;
172
+ if (operation === DIFF_EQUAL) {
173
+ components.push(text.length);
174
+ } else if (operation === DIFF_DELETE) {
175
+ components.push({ d: decode(text) });
176
+ } else if (operation === DIFF_INSERT) {
177
+ components.push(decode(text));
178
+ }
179
+ }
180
+
181
+ // Canonicalize: merge adjacent skips and drop a trailing skip, as required
182
+ // by ot-text-unicode's op validation.
183
+ const op: Array<unknown> = [];
184
+ for (const component of components) {
185
+ if (typeof component === 'number') {
186
+ if (component <= 0) continue;
187
+ const last = op[op.length - 1];
188
+ if (typeof last === 'number') {
189
+ op[op.length - 1] = last + component;
190
+ } else {
191
+ op.push(component);
192
+ }
193
+ } else {
194
+ op.push(component);
195
+ }
196
+ }
197
+ while (
198
+ op.length > 0 &&
199
+ typeof op[op.length - 1] === 'number'
200
+ ) {
201
+ op.pop();
202
+ }
203
+ return op;
204
+ };
205
+
206
+ class UnicodeSafeDiffMatchPatch extends DiffMatchPatch {
207
+ patch_make(a: any, b?: any): any {
208
+ currentOldValue = a;
209
+ currentNewValue = b;
210
+ pendingTextEdit = true;
211
+ needsUnicodeSafeDiff =
212
+ hasSurrogates(a) || hasSurrogates(b);
213
+ return b === undefined
214
+ ? super.patch_make(a)
215
+ : super.patch_make(a, b);
216
+ }
217
+ }
218
+
219
+ // Wrap the json1 type so text edits for strings containing astral characters
220
+ // are built by the unicode-safe routine above. All other operations (and text
221
+ // without astral characters) delegate unchanged.
222
+ const unicodeSafeJson1 = {
223
+ ...json1Presence,
224
+ editOp: (
225
+ path: Array<string | number>,
226
+ type: unknown,
227
+ op: unknown,
228
+ ) => {
229
+ if (type === textUnicode.type && needsUnicodeSafeDiff) {
230
+ if (pendingTextEdit) {
231
+ pendingTextEdit = false;
232
+ return json1Presence.editOp(
233
+ path,
234
+ type,
235
+ buildTextOp(currentOldValue, currentNewValue),
236
+ );
237
+ }
238
+ // The full text op was already emitted for this string; the
239
+ // remaining edits reported by json0-ot-diff are redundant.
240
+ return json1Presence.editOp(path, type, []);
241
+ }
242
+ return json1Presence.editOp(path, type, op);
243
+ },
244
+ };
245
+
29
246
  export const diff = (a, b) =>
30
247
  jsondiff(
31
248
  a,
32
249
  b,
33
- diffMatchPatch,
34
- json1Presence,
250
+ UnicodeSafeDiffMatchPatch,
251
+ unicodeSafeJson1,
35
252
  textUnicode,
36
253
  );
@@ -0,0 +1,413 @@
1
+ import WebSocketJSONStream from '@teamwork/websocket-json-stream';
2
+ import bodyParser from 'body-parser';
3
+ import express from 'express';
4
+ import fs from 'fs';
5
+ import http from 'http';
6
+ import path from 'path';
7
+ import ShareDB from 'sharedb';
8
+ import { fileURLToPath } from 'url';
9
+ import { WebSocketServer } from 'ws';
10
+ import { json1Presence } from '../ot.js';
11
+ import { computeInitialDocument } from './computeInitialDocument.js';
12
+ import { handleAIAssist } from './handleAIAssist.js';
13
+ import { handleAICopilot } from './handleAICopilot.js';
14
+ import { handleAIChatMessage } from './handleAIChatMessage.js';
15
+ import { isDirectory } from './isDirectory.js';
16
+ import { createToken } from './livekit.js';
17
+ import './setupEnv.js';
18
+
19
+ // The time in milliseconds by which auto-saving is debounced.
20
+ const autoSaveDebounceTimeMS = 800;
21
+
22
+ // The time in milliseconds by which auto-saving is throttled
23
+ // when the user is interacting with the widgets in the editor.
24
+ const throttleTimeMS = 100;
25
+
26
+ // The image file utility used when writing files to disk.
27
+ const isImageFile = (fileName) => {
28
+ return (
29
+ fileName.match(
30
+ /\.(png|jpg|jpeg|gif|bmp|svg|webp)$/i,
31
+ ) !== null
32
+ );
33
+ };
34
+
35
+ export interface CreateVZCodeServerOptions {
36
+ /** Workspace root whose files are loaded and auto-saved. */
37
+ cwd?: string;
38
+ /**
39
+ * Directory of client build assets to serve statically. Defaults to
40
+ * the repo's `dist` directory. Pass `null` to disable static serving.
41
+ */
42
+ serveStaticDir?: string | null;
43
+ /**
44
+ * Whether to write changed files to disk automatically. Defaults to
45
+ * `true`. Tests can disable this and call `save()` directly.
46
+ */
47
+ autoSave?: boolean;
48
+ }
49
+
50
+ export interface VZCodeServer {
51
+ app: express.Express;
52
+ httpServer: http.Server;
53
+ shareDBBackend: ShareDB;
54
+ /** The server-side ShareDB document for the workspace. */
55
+ shareDBDoc: any;
56
+ /** Resolves once the initial ShareDB document has been created. */
57
+ ready: Promise<void>;
58
+ /** Write changed files to disk (same routine used by auto-save). */
59
+ save: () => void;
60
+ /** Start listening; resolves with the actual bound port. */
61
+ listen: (port: number) => Promise<number>;
62
+ /** Stop the HTTP/WebSocket servers and close ShareDB. */
63
+ close: () => Promise<void>;
64
+ }
65
+
66
+ /**
67
+ * Creates a VZCode server instance without starting it.
68
+ *
69
+ * Splitting construction from `listen`/`open` makes the server testable
70
+ * in-process (see `test/serverE2E.test.ts`). The production entry point
71
+ * `src/server/index.ts` is a thin wrapper around this factory.
72
+ */
73
+ export const createVZCodeServer = (
74
+ options: CreateVZCodeServerOptions = {},
75
+ ): VZCodeServer => {
76
+ const cwd = options.cwd ?? process.cwd();
77
+ const autoSave = options.autoSave ?? true;
78
+
79
+ // Resolve file names from the ShareDB document against the workspace
80
+ // root, so the server can operate on a directory other than the
81
+ // process's current working directory.
82
+ const resolvePath = (name: string): string =>
83
+ path.resolve(cwd, name);
84
+
85
+ const serveStaticDir =
86
+ options.serveStaticDir === undefined
87
+ ? path.join(
88
+ path.dirname(fileURLToPath(import.meta.url)),
89
+ '..',
90
+ '..',
91
+ 'dist',
92
+ )
93
+ : options.serveStaticDir;
94
+
95
+ const initialDocument = computeInitialDocument({
96
+ fullPath: cwd,
97
+ });
98
+
99
+ // Register our custom OT type,
100
+ // because it does not ship with ShareDB.
101
+ ShareDB.types.register(json1Presence.type);
102
+
103
+ const app = express();
104
+
105
+ // Use ShareDB over WebSocket
106
+ const shareDBBackend = new ShareDB({
107
+ // Enable presence
108
+ presence: true,
109
+ doNotForwardSendPresenceErrorsToClient: true,
110
+ });
111
+ const httpServer = http.createServer(app);
112
+ const wss = new WebSocketServer({ server: httpServer });
113
+ wss.on('connection', (ws) => {
114
+ const clientStream = new WebSocketJSONStream(ws);
115
+ shareDBBackend.listen(clientStream);
116
+
117
+ // Prevent server crashes on errors.
118
+ clientStream.on('error', (error) => {
119
+ console.log('clientStream error: ' + error.message);
120
+ });
121
+
122
+ // Handle errors
123
+ ws.on('error', (error) => {
124
+ console.log('ws error: ' + error.message);
125
+ });
126
+
127
+ // Handle disconnections
128
+ ws.on('close', () => {
129
+ clientStream.end();
130
+ });
131
+ });
132
+
133
+ // Serve static files
134
+ if (serveStaticDir) {
135
+ app.use(express.static(serveStaticDir));
136
+ }
137
+
138
+ // Create the initial "document",
139
+ // which is a representation of files on disk.
140
+ const shareDBConnection = shareDBBackend.connect();
141
+ const shareDBDoc = shareDBConnection.get(
142
+ 'documents',
143
+ '1',
144
+ );
145
+
146
+ // The state of the document when files were last auto-saved.
147
+ let previousDocument = initialDocument;
148
+
149
+ // Saves the files that changed.
150
+ const save = () => {
151
+ const currentDocument = shareDBDoc.data;
152
+
153
+ // Take a look at each file (key) previously and currently.
154
+ const allKeys = Object.keys({
155
+ ...currentDocument.files,
156
+ ...previousDocument.files,
157
+ });
158
+
159
+ const directoriesToDelete = [];
160
+
161
+ for (const key of allKeys) {
162
+ const previous = previousDocument.files[key];
163
+ const current = currentDocument.files[key];
164
+
165
+ // If this file was neither created nor deleted...
166
+ if (previous && current) {
167
+ // Handle changing of text content.
168
+ if (previous.text !== current.text) {
169
+ if (isImageFile(current.name)) {
170
+ // Write image files as binary from base64
171
+ const buffer = Buffer.from(
172
+ current.text,
173
+ 'base64',
174
+ );
175
+ fs.writeFileSync(
176
+ resolvePath(current.name),
177
+ buffer,
178
+ );
179
+ } else {
180
+ // Write non-image files as text
181
+ fs.writeFileSync(
182
+ resolvePath(current.name),
183
+ current.text,
184
+ );
185
+ }
186
+ }
187
+
188
+ // Handle renaming files.
189
+ if (previous.name !== current.name) {
190
+ if (isDirectory(previous.name)) {
191
+ // If the directory itself is being renamed,
192
+ // Phase I: Ignore it, and get the files moved
193
+ // Phase II: Keep track of these, and delete them after
194
+ // all the files moved.
195
+ directoriesToDelete.push(previous.name);
196
+ } else {
197
+ const newDir = path.dirname(current.name);
198
+
199
+ // Check if the new directory exists, if not, create it
200
+ if (!fs.existsSync(resolvePath(newDir))) {
201
+ fs.mkdirSync(resolvePath(newDir), {
202
+ recursive: true,
203
+ });
204
+ }
205
+
206
+ // Move the file to the new directory
207
+ fs.renameSync(
208
+ resolvePath(previous.name),
209
+ resolvePath(current.name),
210
+ );
211
+ }
212
+ }
213
+ }
214
+
215
+ // handle deleting files and directories.
216
+ if (previous && !current) {
217
+ const stats = fs.statSync(
218
+ resolvePath(previous.name),
219
+ );
220
+ //Check if the file path we are trying to delete is a directory
221
+ if (!stats.isDirectory()) {
222
+ fs.unlinkSync(resolvePath(previous.name));
223
+ } else {
224
+ //Performs directory deletion.
225
+ fs.rm(
226
+ resolvePath(previous.name),
227
+ {
228
+ recursive: true, //Makes sure that all files in directory are deleted.
229
+ },
230
+ (error) => {
231
+ if (error) {
232
+ console.log(error);
233
+ }
234
+ },
235
+ );
236
+ }
237
+ }
238
+
239
+ // Handle creating files and Directories.
240
+ if (!previous && current) {
241
+ //File Creation
242
+ if (!isDirectory(current.name)) {
243
+ if (isImageFile(current.name)) {
244
+ // Write image files as binary from base64
245
+ const buffer = Buffer.from(
246
+ current.text,
247
+ 'base64',
248
+ );
249
+ fs.writeFileSync(
250
+ resolvePath(current.name),
251
+ buffer,
252
+ );
253
+ } else {
254
+ // Write non-image files as text
255
+ fs.writeFileSync(
256
+ resolvePath(current.name),
257
+ current.text,
258
+ );
259
+ }
260
+ } else {
261
+ fs.mkdirSync(resolvePath(current.name), {
262
+ recursive: true,
263
+ });
264
+ }
265
+ }
266
+ }
267
+ // TODO deleted all directories under directoriesToDelete
268
+
269
+ for (const dir of directoriesToDelete) {
270
+ //Performs directory deletion.
271
+ fs.rm(
272
+ resolvePath(dir),
273
+ {
274
+ recursive: true, //Makes sure that all files in directory are deleted.
275
+ },
276
+ (error) => {
277
+ if (error) {
278
+ console.log(error);
279
+ }
280
+ },
281
+ );
282
+ }
283
+
284
+ previousDocument = currentDocument;
285
+ };
286
+
287
+ let lastExecutedTime = Date.now();
288
+ let lastChangeTimeout; // This timeout ensures the last change is saved
289
+
290
+ // Function to throttle the saving
291
+ function throttleSave() {
292
+ const now = Date.now();
293
+ const timeSinceLastExecution = now - lastExecutedTime;
294
+
295
+ if (timeSinceLastExecution > throttleTimeMS) {
296
+ save();
297
+ lastExecutedTime = now;
298
+ } else {
299
+ // Clear the previous timeout and set a new one to save the last change
300
+ clearTimeout(lastChangeTimeout);
301
+ lastChangeTimeout = setTimeout(() => {
302
+ save();
303
+ lastExecutedTime = now;
304
+ }, throttleTimeMS - timeSinceLastExecution);
305
+ }
306
+ }
307
+
308
+ // Function to debounce the saving
309
+ let debounceTimeout;
310
+ function debounceSave() {
311
+ clearTimeout(debounceTimeout);
312
+ debounceTimeout = setTimeout(
313
+ save,
314
+ autoSaveDebounceTimeMS,
315
+ );
316
+ }
317
+
318
+ // Create the document, then subscribe so that the server-side doc
319
+ // receives ops from connected clients.
320
+ const ready = new Promise<void>((resolve, reject) => {
321
+ shareDBDoc.create(
322
+ initialDocument,
323
+ json1Presence.type.uri,
324
+ (createError) => {
325
+ if (createError) return reject(createError);
326
+ shareDBDoc.subscribe((subscribeError) => {
327
+ if (subscribeError) return reject(subscribeError);
328
+
329
+ if (autoSave) {
330
+ // Subscribe to listen for modifications
331
+ shareDBDoc.on('op', () => {
332
+ if (shareDBDoc.data.isInteracting) {
333
+ throttleSave();
334
+ } else {
335
+ debounceSave();
336
+ }
337
+ });
338
+ }
339
+
340
+ resolve();
341
+ });
342
+ },
343
+ );
344
+ });
345
+
346
+ // Handle AI Assist requests.
347
+ app.post(
348
+ '/ai-assist',
349
+ bodyParser.json(),
350
+ handleAIAssist(shareDBDoc),
351
+ );
352
+
353
+ // Handle AI Copilot requests.
354
+ app.post(
355
+ '/ai-copilot',
356
+ bodyParser.json(),
357
+ handleAICopilot(),
358
+ );
359
+
360
+ // Handle AI Chat Message requests.
361
+ app.post(
362
+ '/ai-chat-message',
363
+ bodyParser.json(),
364
+ handleAIChatMessage({
365
+ shareDBDoc,
366
+ onCreditDeduction: undefined,
367
+ }),
368
+ );
369
+
370
+ // Livekit Token Generator
371
+ app.get('/livekit-token', async (req, res) => {
372
+ const { room, username } = req.query;
373
+ res.send(await createToken(room, username));
374
+ });
375
+
376
+ const listen = (port: number): Promise<number> =>
377
+ new Promise((resolve, reject) => {
378
+ const onError = (error: Error) => reject(error);
379
+ httpServer.once('error', onError);
380
+ httpServer.listen(port, () => {
381
+ httpServer.removeListener('error', onError);
382
+ const address = httpServer.address();
383
+ const actualPort =
384
+ address && typeof address === 'object'
385
+ ? address.port
386
+ : port;
387
+ resolve(actualPort);
388
+ });
389
+ });
390
+
391
+ const close = (): Promise<void> =>
392
+ new Promise((resolve, reject) => {
393
+ clearTimeout(lastChangeTimeout);
394
+ clearTimeout(debounceTimeout);
395
+ wss.close(() => {
396
+ httpServer.close((error) => {
397
+ if (error) return reject(error);
398
+ shareDBBackend.close(() => resolve());
399
+ });
400
+ });
401
+ });
402
+
403
+ return {
404
+ app,
405
+ httpServer,
406
+ shareDBBackend,
407
+ shareDBDoc,
408
+ ready,
409
+ save,
410
+ listen,
411
+ close,
412
+ };
413
+ };