ai_co_discuss 0.4.13 → 0.4.16

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 (44) hide show
  1. package/.agents/skills/discuss-host/SKILL.md +42 -42
  2. package/.agents/skills/workflow-creator/SKILL.md +155 -155
  3. package/.agents/skills/workflow-creator/references/model-selection.md +24 -23
  4. package/backend/free_room.py +15 -8
  5. package/backend/schema.sql +3 -1
  6. package/backend/server.py +146 -17
  7. package/docs/THIRD_PARTY_NOTICES.md +721 -1
  8. package/docs/runner.md +4 -2
  9. package/docs/workflow.md +1 -1
  10. package/package.json +10 -3
  11. package/runner/adapters/api.mjs +33 -7
  12. package/runner/adapters/api_files.mjs +21 -0
  13. package/runner/adapters/api_images.mjs +245 -0
  14. package/runner/adapters/index.mjs +186 -186
  15. package/runner/adapters/profiles.mjs +152 -139
  16. package/runner/discussion_launch.mjs +49 -11
  17. package/runner/free_runner.mjs +1286 -1281
  18. package/runner/project_files.mjs +390 -330
  19. package/runner/relay_channel.mjs +326 -325
  20. package/runner/remote_launch.mjs +2 -2
  21. package/runner/stt.mjs +135 -111
  22. package/runner/tts.mjs +180 -172
  23. package/runner/tts_providers.mjs +479 -435
  24. package/runner/workflows.mjs +606 -606
  25. package/web/app.js +82 -12
  26. package/web/backup.js +1 -1
  27. package/web/markdown.css +1 -1
  28. package/web/modern.css +1 -1
  29. package/web/modern.js +663 -40
  30. package/web/office/assets/pptx-source-worker-559Vl2R3.mjs +446 -0
  31. package/web/office/assets/pptx_parser_bg-DON650C_.wasm +0 -0
  32. package/web/office/assets/render-worker-Ck21oePL-D_L2C4am.js +16 -0
  33. package/web/office/chunks/comment-ui-runtime-Bp37ytDC-CEDIeFBy.js +125 -0
  34. package/web/office/chunks/emf--QWY-UlT-D7lCNost.js +1 -0
  35. package/web/office/chunks/font-preload-demand-NqcVKIpX-_QhVEaPJ.js +1 -0
  36. package/web/office/chunks/plot-area-frame-DNYMd9Pf-B0ScWz_J.js +2 -0
  37. package/web/office/chunks/pptx-DbjWegUB-CU8ZIJEP.js +4 -0
  38. package/web/office/chunks/presentation-model-source-DLNioq7T-Demo5cCW.js +1 -0
  39. package/web/office/chunks/render-worker-host-CVr53kg0-DUcW76F6.js +1 -0
  40. package/web/office/chunks/slide-pull-client-3g6TxaKa-BohMnKOC.js +12 -0
  41. package/web/office/chunks/worker-source-ZQE9C1j6-B31UTbq3.js +1 -0
  42. package/web/office/docx.js +21 -0
  43. package/web/office/pptx.js +1 -0
  44. package/web/office/xlsx.js +64 -0
@@ -1,330 +1,390 @@
1
- /** Read-only directory and text previews, confined to a room's saved project directories. */
2
- import { createHash } from 'node:crypto';
3
- import { closeSync, fstatSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync } from 'node:fs';
4
- import { isAbsolute, posix, relative, resolve } from 'node:path';
5
- import { adapter_profile } from './adapters/profiles.mjs';
6
- import { PINYIN_TABLE } from './pinyin_table.mjs';
7
-
8
- const DIRECTORY_PAGE_SIZE = 200;
9
- // Leave room for JSON escaping and base64 within the queued relay's 512 KiB encrypted envelope.
10
- const PREVIEW_MAX_BYTES = 128 * 1024;
11
- const DIRECTORY_MAX_BYTES = 128 * 1024;
12
-
13
- /** Resolve a relative project path, including links, without allowing an escape from the project. */
14
- function project_path(root, path) {
15
- if (typeof path !== 'string' || /[\0:]/.test(path) || isAbsolute(path) || path.replaceAll('\\', '/').split('/').includes('..')) {
16
- throw new Error('只能读取项目目录内的相对路径');
17
- }
18
- const target = realpathSync(resolve(root, path));
19
- const inside = relative(root, target);
20
- if (inside === '..' || inside.startsWith('../') || inside.startsWith('..\\') || isAbsolute(inside)) {
21
- throw new Error('此链接指向项目目录之外,无法读取');
22
- }
23
- return target;
24
- }
25
-
26
- /** Describe one entry; broken or external links remain visible but cannot be opened. */
27
- function directory_entry(root, path, entry) {
28
- const child = path ? `${path}/${entry.name}` : entry.name;
29
- try {
30
- const info = statSync(project_path(root, child));
31
- const kind = info.isDirectory() ? 'directory' : info.isFile() ? 'file' : 'unavailable';
32
- return { name: entry.name, path: child, kind, size: info.isFile() ? info.size : null, modified_at: info.mtime.toISOString() };
33
- } catch {
34
- return { name: entry.name, path: child, kind: 'unavailable', size: null, modified_at: null };
35
- }
36
- }
37
-
38
- /** Read a bounded UTF-8 or BOM-marked UTF-16 preview, returning a reason for binary files. */
39
- function text_preview(target) {
40
- const descriptor = openSync(target, 'r');
41
- try {
42
- const info = fstatSync(descriptor);
43
- if (!info.isFile()) throw new Error('只能预览普通文件');
44
- const bytes = Buffer.alloc(Math.min(info.size, PREVIEW_MAX_BYTES));
45
- const length = readSync(descriptor, bytes, 0, bytes.length, 0);
46
- const truncated = info.size > length;
47
- const encoding = bytes[0] === 0xff && bytes[1] === 0xfe ? 'utf-16le'
48
- : bytes[0] === 0xfe && bytes[1] === 0xff ? 'utf-16be' : 'utf-8';
49
- const result = { size: info.size, modified_at: info.mtime.toISOString(), truncated, limit: PREVIEW_MAX_BYTES, encoding };
50
- try {
51
- const text = new TextDecoder(encoding, { fatal: true }).decode(bytes.subarray(0, length), { stream: truncated });
52
- if (/[\u0000-\u0008\u000b\u000e-\u001f]/.test(text)) throw new Error('binary');
53
- return { ...result, text };
54
- } catch { return { ...result, text: null, reason: '此文件为二进制或使用了暂不支持的文本编码' }; }
55
- } finally { closeSync(descriptor); }
56
- }
57
-
58
- /** Folders whose contents are generated or vendored and would drown real matches. */
59
- const SEARCH_SKIPPED = new Set(['.git', 'node_modules', '__pycache__', '.venv', 'venv', '.next', '.cache', '.wrangler']);
60
- const SEARCH_RESULT_LIMIT = 50;
61
- const SEARCH_VISIT_LIMIT = 20000;
62
- const SEARCH_TIME_LIMIT_MS = 1500;
63
-
64
- // Pinyin letters typed in place of hanzi, as while an input method is still composing ("hanc" for 寒潮).
65
- const PINYIN_QUERY = /^[a-z0-9]+$/;
66
- let pinyin_readings = null;
67
-
68
- /** The toneless readings of one hanzi, or null for any other character. */
69
- function readings_of(char) {
70
- if (!pinyin_readings) {
71
- pinyin_readings = new Map();
72
- for (const line of PINYIN_TABLE.split('\n')) {
73
- const syllable = line.match(/^[a-z]+/)[0];
74
- for (const hanzi of line.slice(syllable.length)) {
75
- if (!pinyin_readings.has(hanzi)) pinyin_readings.set(hanzi, []);
76
- pinyin_readings.get(hanzi).push(syllable);
77
- }
78
- }
79
- }
80
- return pinyin_readings.get(char) || null;
81
- }
82
-
83
- /**
84
- * Whether a run of the name's characters spells the letters: each hanzi by a leading part of one of its readings
85
- * (so "hanc", "hc" and "hanchao" all find 寒潮), any other character by itself.
86
- */
87
- function pinyin_match(name, letters) {
88
- const chars = [...name.toLocaleLowerCase()];
89
- if (!chars.some(char => readings_of(char))) return false;
90
- const known = new Map();
91
- const spell = (at, used) => {
92
- if (used === letters.length) return true;
93
- if (at === chars.length) return false;
94
- const key = at * (letters.length + 1) + used;
95
- if (known.has(key)) return known.get(key);
96
- let found = false;
97
- const readings = readings_of(chars[at]);
98
- if (!readings) found = chars[at] === letters[used] && spell(at + 1, used + 1);
99
- for (const reading of readings || []) {
100
- for (let length = 1; !found && length <= reading.length && reading[length - 1] === letters[used + length - 1]; length += 1) {
101
- found = spell(at + 1, used + length);
102
- }
103
- if (found) break;
104
- }
105
- known.set(key, found);
106
- return found;
107
- };
108
- return chars.some((_, start) => spell(start, 0));
109
- }
110
-
111
- /** Rank a name match: exact name, then prefix, then substring, then pinyin; shallower and shorter paths first. */
112
- function search_rank(name, path, needle) {
113
- const lower = name.toLocaleLowerCase();
114
- const tier = lower === needle ? 0 : lower.startsWith(needle) ? 1 : lower.includes(needle) ? 2 : 3;
115
- return [tier, path.split('/').length, path.length];
116
- }
117
-
118
- /** Find files and folders whose name (or path, when the query has a "/") contains the query, case-insensitively, under one root. */
119
- function search_project_files(root, query) {
120
- const needle = query.trim().toLocaleLowerCase().replaceAll('\\', '/');
121
- if (!needle) throw new Error('搜索关键词不能为空');
122
- const by_path = needle.includes('/');
123
- const by_pinyin = !by_path && PINYIN_QUERY.test(needle);
124
- const deadline = Date.now() + SEARCH_TIME_LIMIT_MS;
125
- const matches = [];
126
- const queue = [''];
127
- let visited = 0, complete = true;
128
- while (queue.length) {
129
- if (visited >= SEARCH_VISIT_LIMIT || Date.now() > deadline) { complete = false; break; }
130
- const folder = queue.shift();
131
- let items;
132
- try { items = readdirSync(folder ? resolve(root, folder) : root, { withFileTypes: true }); } catch { continue; }
133
- for (const entry of items) {
134
- visited += 1;
135
- // Links are skipped so a search never leaves the project.
136
- if (entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory())) continue;
137
- const path = folder ? `${folder}/${entry.name}` : entry.name;
138
- if (entry.isDirectory() && !SEARCH_SKIPPED.has(entry.name)) queue.push(path);
139
- if ((by_path ? path : entry.name).toLocaleLowerCase().includes(needle) || (by_pinyin && pinyin_match(entry.name, needle))) {
140
- matches.push({ name: entry.name, path, kind: entry.isDirectory() ? 'directory' : 'file' });
141
- }
142
- }
143
- }
144
- return { matches, complete };
145
- }
146
-
147
- /** Rank and cut the matches of every searched directory together; each entry keeps the `root` it was found in. */
148
- function search_result(query, searches) {
149
- const needle = query.trim().toLocaleLowerCase().replaceAll('\\', '/');
150
- const matches = searches.flatMap(({ matches: found }, root) => found.map(item => ({ ...item, root })));
151
- const ranked = matches.map(item => ({ item, rank: search_rank(item.name, item.path, needle) }))
152
- .sort((left, right) => left.rank[0] - right.rank[0] || left.rank[1] - right.rank[1] || left.rank[2] - right.rank[2]);
153
- return { query, kind: 'search', entries: ranked.slice(0, SEARCH_RESULT_LIMIT).map(({ item }) => item),
154
- total: matches.length, complete: searches.every(search => search.complete) };
155
- }
156
-
157
- /** The room's project directories: the main one (`cwd`) first, then the extra ones in the order they were added. */
158
- export function room_directories(config) {
159
- return [config.cwd, ...(config.extra_directories || [])].filter(Boolean);
160
- }
161
-
162
- /** Whether `directory` is one of the room's project directories or lies inside one; Windows paths compare without case. */
163
- export function inside_room(config, directory) {
164
- const key = path => process.platform === 'win32' ? resolve(path).toLowerCase() : resolve(path);
165
- return room_directories(config).some(root => {
166
- const rest = relative(key(root), key(directory));
167
- return !rest.startsWith('..') && !isAbsolute(rest);
168
- });
169
- }
170
-
171
- /**
172
- * The directory a member works in when it lies outside every project directory of the room, or '' when it works in
173
- * one of them (or the room has none). Such a member only reads the room's directories. A member whose `cwd` is ''
174
- * joined before the room had a project: it keeps its own session's folder and is not outside.
175
- */
176
- export function outside_directory(config, profile) {
177
- const cwd = profile?.cwd ?? config.cwd;
178
- return cwd && room_directories(config).length && !inside_room(config, cwd) ? cwd : '';
179
- }
180
-
181
- /**
182
- * Whether the room's directories stay read-only for this member by the software's own limits, not only by its task
183
- * text: at 只读 for any software whose levels the runner sets, at 可写 only where a sandbox or the file tools hold
184
- * (`limits_directories`); never for an App, a manual member's own permissions, 自动 or 全放开.
185
- */
186
- export function read_only_enforced(profile) {
187
- const facts = adapter_profile(profile?.adapter);
188
- if (!facts?.access_levels) return false;
189
- return profile.project_access === 'read' || (profile.project_access === 'write' && Boolean(facts.capabilities.limits_directories));
190
- }
191
-
192
- /** The room's project root, resolved through links and required to be a folder. */
193
- function project_root(cwd) {
194
- if (!cwd?.trim()) throw new Error('本房间未设置项目目录');
195
- const root = realpathSync(cwd);
196
- if (!statSync(root).isDirectory()) throw new Error('项目目录不是文件夹');
197
- return root;
198
- }
199
-
200
- /**
201
- * List one directory page or preview one file under one project directory, or search names under it; a search over
202
- * several directories is `search_project_roots`.
203
- */
204
- export function read_project_files(cwd, path = '', offset = 0, query = '') {
205
- if (query) return search_project_roots([cwd], query);
206
- if (!Number.isSafeInteger(offset) || offset < 0) throw new Error('目录分页位置无效');
207
- const root = project_root(cwd);
208
- const target = project_path(root, path);
209
- const info = statSync(target);
210
- const normalized = path.replaceAll('\\', '/').split('/').filter(part => part && part !== '.').join('/');
211
- if (info.isFile()) return { path: normalized, kind: 'file', ...text_preview(target) };
212
- if (!info.isDirectory()) throw new Error('只能浏览文件夹或预览普通文件');
213
- const items = readdirSync(target, { withFileTypes: true }).sort((left, right) =>
214
- Number(right.isDirectory()) - Number(left.isDirectory()) || left.name.localeCompare(right.name, 'zh-CN', { numeric: true }));
215
- const entries = [];
216
- let bytes = 0;
217
- for (const entry of items.slice(offset, offset + DIRECTORY_PAGE_SIZE)) {
218
- const item = directory_entry(root, normalized, entry);
219
- bytes += Buffer.byteLength(JSON.stringify(item));
220
- if (entries.length && bytes > DIRECTORY_MAX_BYTES) break;
221
- entries.push(item);
222
- }
223
- return { path: normalized, kind: 'directory', entries, total: items.length,
224
- next_offset: offset + entries.length < items.length ? offset + entries.length : null };
225
- }
226
-
227
- // An HTML page with the files it refers to inlined stays within this size; references past it are left as they are.
228
- export const PAGE_MAX_BYTES = 8 * 1024 * 1024;
229
- // Media types of the files a page may refer to; others are left as they are.
230
- const PAGE_TYPES = {
231
- css: 'text/css', js: 'text/javascript', mjs: 'text/javascript', json: 'application/json', txt: 'text/plain', csv: 'text/csv',
232
- png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', svg: 'image/svg+xml',
233
- ico: 'image/x-icon', bmp: 'image/bmp', woff: 'font/woff', woff2: 'font/woff2', ttf: 'font/ttf', otf: 'font/otf',
234
- mp3: 'audio/mpeg', wav: 'audio/wav', ogg: 'audio/ogg', m4a: 'audio/mp4', mp4: 'video/mp4', webm: 'video/webm',
235
- };
236
- // Script and style bodies are kept apart so only real tags are rewritten; comments are left alone.
237
- const PAGE_PARTS = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)|(<style\b[^>]*>)([\s\S]*?)(<\/style\s*>)|(<!--[\s\S]*?-->)|(<[a-zA-Z][^>]*>)/gi;
238
- const TAG_ATTRIBUTE = /(\s)(src|poster|href|style)(\s*=\s*)(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gi;
239
- const CSS_URL = /url\(\s*(['"]?)([^'")]+)\1\s*\)/gi;
240
- const CSS_IMPORT = /@import\s+(['"])([^'"]+)\1/gi;
241
-
242
- /** The project path a reference in the file at `base` (a folder) names, or null for other URLs (schemes, fragments). */
243
- function page_reference(base, reference) {
244
- const value = reference.trim().replace(/&amp;/g, '&');
245
- if (!value || /^([a-z][a-z0-9+.-]*:|\/\/|#)/i.test(value)) return null;
246
- let path = value.replace(/[?#].*$/, '');
247
- try { path = decodeURIComponent(path); } catch { /* Kept as written. */ }
248
- return posix.normalize(path.startsWith('/') ? path.slice(1) : posix.join(base, path));
249
- }
250
-
251
- /** A referenced project file as a data URL (a style sheet with its own references inlined), or null when it is left as written. */
252
- function page_resource(path, state, depth) {
253
- if (path === null) return null;
254
- if (state.inlined.has(path)) return state.inlined.get(path);
255
- const type = PAGE_TYPES[posix.extname(path).slice(1).toLowerCase()];
256
- if (!type) return null;
257
- let bytes;
258
- try {
259
- if (path.startsWith('..')) throw new Error('outside');
260
- const target = project_path(state.root, path);
261
- if (!statSync(target).isFile()) throw new Error('not a file');
262
- bytes = readFileSync(target);
263
- } catch { state.missing.add(path); return null; }
264
- if (type === 'text/css' && depth < 4) bytes = Buffer.from(page_css(bytes.toString('utf8'), posix.dirname(path), state, depth + 1));
265
- const url = `data:${type};base64,${bytes.toString('base64')}`;
266
- if (url.length > state.budget) { state.skipped.add(path); return null; }
267
- state.budget -= url.length;
268
- state.inlined.set(path, url);
269
- return url;
270
- }
271
-
272
- /** Inline the files a style sheet refers to; `base` is the folder its relative URLs start from. */
273
- function page_css(css, base, state, depth) {
274
- return css.replace(CSS_IMPORT, (whole, quote, reference) => {
275
- const url = page_resource(page_reference(base, reference), state, depth);
276
- return url ? `@import url(${url})` : whole;
277
- }).replace(CSS_URL, (whole, quote, reference) => {
278
- const url = page_resource(page_reference(base, reference), state, depth);
279
- return url ? `url(${url})` : whole;
280
- });
281
- }
282
-
283
- /** Inline the files one tag refers to: `src`/`poster` of any tag, `href` of style sheets and icons, URLs in `style`. */
284
- function page_tag(tag, base, state) {
285
- const name = /^<([a-zA-Z][\w-]*)/.exec(tag)[1].toLowerCase();
286
- const linked = name === 'link' && /\brel\s*=\s*["']?[^"'>]*\b(stylesheet|icon)\b/i.test(tag);
287
- return tag.replace(TAG_ATTRIBUTE, (whole, space, attribute, equals, double, single, bare) => {
288
- const value = double ?? single ?? bare;
289
- const key = attribute.toLowerCase();
290
- if (key === 'style') {
291
- const css = page_css(value, base, state, 0);
292
- return css === value ? whole : `${space}${attribute}${equals}"${css.replace(/"/g, '&quot;')}"`;
293
- }
294
- if (key === 'href' && !linked) return whole;
295
- const url = page_resource(page_reference(base, value), state, 0);
296
- return url ? `${space}${attribute}${equals}"${url}"` : whole;
297
- });
298
- }
299
-
300
- /**
301
- * One HTML file of a project with the style sheets, scripts, images, fonts and media it refers to by relative path
302
- * inlined as data URLs, so it shows in full where only its text can be sent (another device, through the relay).
303
- * Only files inside the project directory are read; references that are missing, outside it or past the size limit
304
- * are left as written and listed. Resources a script asks for while running are not included.
305
- */
306
- export function bundle_project_page(cwd, path) {
307
- const root = project_root(cwd);
308
- const target = project_path(root, path);
309
- if (!/\.html?$/i.test(target)) throw new Error('只能打开 HTML 文件');
310
- const info = statSync(target);
311
- if (!info.isFile()) throw new Error('只能预览普通文件');
312
- if (info.size > PAGE_MAX_BYTES) throw new Error('HTML 文件超过 8 MiB,无法完整显示');
313
- const normalized = path.replaceAll('\\', '/').split('/').filter(part => part && part !== '.').join('/');
314
- const base = posix.dirname(normalized);
315
- const state = { root, budget: PAGE_MAX_BYTES - info.size, inlined: new Map(), missing: new Set(), skipped: new Set() };
316
- const html = readFileSync(target, 'utf8').replace(PAGE_PARTS, (whole, script_open, script_body, script_close, style_open, style_body, style_close, comment, tag) => {
317
- if (script_open) return page_tag(script_open, base, state) + script_body + script_close;
318
- if (style_open) return style_open + page_css(style_body, base, state, 0) + style_close;
319
- return comment ?? page_tag(tag, base, state);
320
- });
321
- const bytes = Buffer.from(html, 'utf8');
322
- return { path: normalized, bytes, version: createHash('sha256').update(bytes).digest('hex').slice(0, 16), modified_at: info.mtime.toISOString(),
323
- missing: [...state.missing], skipped: [...state.skipped] };
324
- }
325
-
326
- /** Search names under every directory of a room at once; each entry's `root` is the index of its directory. */
327
- export function search_project_roots(directories, query) {
328
- if (!directories.length) project_root('');
329
- return search_result(String(query), directories.map(directory => search_project_files(project_root(directory), String(query))));
330
- }
1
+ /** Read-only directory and text previews, confined to a room's saved project directories. */
2
+ import { createHash } from 'node:crypto';
3
+ import { closeSync, fstatSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync } from 'node:fs';
4
+ import { isAbsolute, posix, relative, resolve } from 'node:path';
5
+ import { adapter_profile } from './adapters/profiles.mjs';
6
+ import { PINYIN_TABLE } from './pinyin_table.mjs';
7
+
8
+ const DIRECTORY_PAGE_SIZE = 200;
9
+ // Leave room for JSON escaping and base64 within the queued relay's 512 KiB encrypted envelope.
10
+ const PREVIEW_MAX_BYTES = 128 * 1024;
11
+ const DIRECTORY_MAX_BYTES = 128 * 1024;
12
+
13
+ /** Resolve a relative project path, including links, without allowing an escape from the project. */
14
+ function project_path(root, path) {
15
+ if (typeof path !== 'string' || /[\0:]/.test(path) || isAbsolute(path) || path.replaceAll('\\', '/').split('/').includes('..')) {
16
+ throw new Error('只能读取项目目录内的相对路径');
17
+ }
18
+ const target = realpathSync(resolve(root, path));
19
+ const inside = relative(root, target);
20
+ if (inside === '..' || inside.startsWith('../') || inside.startsWith('..\\') || isAbsolute(inside)) {
21
+ throw new Error('此链接指向项目目录之外,无法读取');
22
+ }
23
+ return target;
24
+ }
25
+
26
+ /** Describe one entry; broken or external links remain visible but cannot be opened. */
27
+ function directory_entry(root, path, entry) {
28
+ const child = path ? `${path}/${entry.name}` : entry.name;
29
+ try {
30
+ const info = statSync(project_path(root, child));
31
+ const kind = info.isDirectory() ? 'directory' : info.isFile() ? 'file' : 'unavailable';
32
+ return { name: entry.name, path: child, kind, size: info.isFile() ? info.size : null, modified_at: info.mtime.toISOString() };
33
+ } catch {
34
+ return { name: entry.name, path: child, kind: 'unavailable', size: null, modified_at: null };
35
+ }
36
+ }
37
+
38
+ /** Read a bounded UTF-8 or BOM-marked UTF-16 preview, returning a reason for binary files. */
39
+ function text_preview(target) {
40
+ const descriptor = openSync(target, 'r');
41
+ try {
42
+ const info = fstatSync(descriptor);
43
+ if (!info.isFile()) throw new Error('只能预览普通文件');
44
+ const bytes = Buffer.alloc(Math.min(info.size, PREVIEW_MAX_BYTES));
45
+ const length = readSync(descriptor, bytes, 0, bytes.length, 0);
46
+ const truncated = info.size > length;
47
+ const encoding = bytes[0] === 0xff && bytes[1] === 0xfe ? 'utf-16le'
48
+ : bytes[0] === 0xfe && bytes[1] === 0xff ? 'utf-16be' : 'utf-8';
49
+ const result = { size: info.size, modified_at: info.mtime.toISOString(), truncated, limit: PREVIEW_MAX_BYTES, encoding };
50
+ try {
51
+ const text = new TextDecoder(encoding, { fatal: true }).decode(bytes.subarray(0, length), { stream: truncated });
52
+ if (/[\u0000-\u0008\u000b\u000e-\u001f]/.test(text)) throw new Error('binary');
53
+ return { ...result, text };
54
+ } catch { return { ...result, text: null, reason: '此文件为二进制或使用了暂不支持的文本编码' }; }
55
+ } finally { closeSync(descriptor); }
56
+ }
57
+
58
+ /** Folders whose contents are generated or vendored and would drown real matches. */
59
+ const SEARCH_SKIPPED = new Set(['.git', 'node_modules', '__pycache__', '.venv', 'venv', '.next', '.cache', '.wrangler']);
60
+ const SEARCH_RESULT_LIMIT = 50;
61
+ const SEARCH_VISIT_LIMIT = 20000;
62
+ const SEARCH_TIME_LIMIT_MS = 1500;
63
+
64
+ // Pinyin letters typed in place of hanzi, as while an input method is still composing ("hanc" for 寒潮).
65
+ const PINYIN_QUERY = /^[a-z0-9]+$/;
66
+ let pinyin_readings = null;
67
+
68
+ /** The toneless readings of one hanzi, or null for any other character. */
69
+ function readings_of(char) {
70
+ if (!pinyin_readings) {
71
+ pinyin_readings = new Map();
72
+ for (const line of PINYIN_TABLE.split('\n')) {
73
+ const syllable = line.match(/^[a-z]+/)[0];
74
+ for (const hanzi of line.slice(syllable.length)) {
75
+ if (!pinyin_readings.has(hanzi)) pinyin_readings.set(hanzi, []);
76
+ pinyin_readings.get(hanzi).push(syllable);
77
+ }
78
+ }
79
+ }
80
+ return pinyin_readings.get(char) || null;
81
+ }
82
+
83
+ /**
84
+ * Whether a run of the name's characters spells the letters: each hanzi by a leading part of one of its readings
85
+ * (so "hanc", "hc" and "hanchao" all find 寒潮), any other character by itself.
86
+ */
87
+ function pinyin_match(name, letters) {
88
+ const chars = [...name.toLocaleLowerCase()];
89
+ if (!chars.some(char => readings_of(char))) return false;
90
+ const known = new Map();
91
+ const spell = (at, used) => {
92
+ if (used === letters.length) return true;
93
+ if (at === chars.length) return false;
94
+ const key = at * (letters.length + 1) + used;
95
+ if (known.has(key)) return known.get(key);
96
+ let found = false;
97
+ const readings = readings_of(chars[at]);
98
+ if (!readings) found = chars[at] === letters[used] && spell(at + 1, used + 1);
99
+ for (const reading of readings || []) {
100
+ for (let length = 1; !found && length <= reading.length && reading[length - 1] === letters[used + length - 1]; length += 1) {
101
+ found = spell(at + 1, used + length);
102
+ }
103
+ if (found) break;
104
+ }
105
+ known.set(key, found);
106
+ return found;
107
+ };
108
+ return chars.some((_, start) => spell(start, 0));
109
+ }
110
+
111
+ /** Rank a name match: exact name, then prefix, then substring, then pinyin; shallower and shorter paths first. */
112
+ function search_rank(name, path, needle) {
113
+ const lower = name.toLocaleLowerCase();
114
+ const tier = lower === needle ? 0 : lower.startsWith(needle) ? 1 : lower.includes(needle) ? 2 : 3;
115
+ return [tier, path.split('/').length, path.length];
116
+ }
117
+
118
+ /** Find files and folders whose name (or path, when the query has a "/") contains the query, case-insensitively, under one root. */
119
+ function search_project_files(root, query) {
120
+ const needle = query.trim().toLocaleLowerCase().replaceAll('\\', '/');
121
+ if (!needle) throw new Error('搜索关键词不能为空');
122
+ const by_path = needle.includes('/');
123
+ const by_pinyin = !by_path && PINYIN_QUERY.test(needle);
124
+ const deadline = Date.now() + SEARCH_TIME_LIMIT_MS;
125
+ const matches = [];
126
+ const queue = [''];
127
+ let visited = 0, complete = true;
128
+ while (queue.length) {
129
+ if (visited >= SEARCH_VISIT_LIMIT || Date.now() > deadline) { complete = false; break; }
130
+ const folder = queue.shift();
131
+ let items;
132
+ try { items = readdirSync(folder ? resolve(root, folder) : root, { withFileTypes: true }); } catch { continue; }
133
+ for (const entry of items) {
134
+ visited += 1;
135
+ // Links are skipped so a search never leaves the project.
136
+ if (entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory())) continue;
137
+ const path = folder ? `${folder}/${entry.name}` : entry.name;
138
+ if (entry.isDirectory() && !SEARCH_SKIPPED.has(entry.name)) queue.push(path);
139
+ if ((by_path ? path : entry.name).toLocaleLowerCase().includes(needle) || (by_pinyin && pinyin_match(entry.name, needle))) {
140
+ matches.push({ name: entry.name, path, kind: entry.isDirectory() ? 'directory' : 'file' });
141
+ }
142
+ }
143
+ }
144
+ return { matches, complete };
145
+ }
146
+
147
+ /** Rank and cut the matches of every searched directory together; each entry keeps the `root` it was found in. */
148
+ function search_result(query, searches) {
149
+ const needle = query.trim().toLocaleLowerCase().replaceAll('\\', '/');
150
+ const matches = searches.flatMap(({ matches: found }, root) => found.map(item => ({ ...item, root })));
151
+ const ranked = matches.map(item => ({ item, rank: search_rank(item.name, item.path, needle) }))
152
+ .sort((left, right) => left.rank[0] - right.rank[0] || left.rank[1] - right.rank[1] || left.rank[2] - right.rank[2]);
153
+ return { query, kind: 'search', entries: ranked.slice(0, SEARCH_RESULT_LIMIT).map(({ item }) => item),
154
+ total: matches.length, complete: searches.every(search => search.complete) };
155
+ }
156
+
157
+ /** The room's project directories: the main one (`cwd`) first, then the extra ones in the order they were added. */
158
+ export function room_directories(config) {
159
+ return [config.cwd, ...(config.extra_directories || [])].filter(Boolean);
160
+ }
161
+
162
+ /** Whether `directory` is one of the room's project directories or lies inside one; Windows paths compare without case. */
163
+ export function inside_room(config, directory) {
164
+ const key = path => process.platform === 'win32' ? resolve(path).toLowerCase() : resolve(path);
165
+ return room_directories(config).some(root => {
166
+ const rest = relative(key(root), key(directory));
167
+ return !rest.startsWith('..') && !isAbsolute(rest);
168
+ });
169
+ }
170
+
171
+ /**
172
+ * The directory a member works in when it lies outside every project directory of the room, or '' when it works in
173
+ * one of them (or the room has none). Such a member only reads the room's directories. A member whose `cwd` is ''
174
+ * joined before the room had a project: it keeps its own session's folder and is not outside.
175
+ */
176
+ export function outside_directory(config, profile) {
177
+ const cwd = profile?.cwd ?? config.cwd;
178
+ return cwd && room_directories(config).length && !inside_room(config, cwd) ? cwd : '';
179
+ }
180
+
181
+ /**
182
+ * Whether the room's directories stay read-only for this member by the software's own limits, not only by its task
183
+ * text: at 只读 for any software whose levels the runner sets, at 可写 only where a sandbox or the file tools hold
184
+ * (`limits_directories`); never for an App, a manual member's own permissions, 自动 or 全放开.
185
+ */
186
+ export function read_only_enforced(profile) {
187
+ const facts = adapter_profile(profile?.adapter);
188
+ if (!facts?.access_levels) return false;
189
+ return profile.project_access === 'read' || (profile.project_access === 'write' && Boolean(facts.capabilities.limits_directories));
190
+ }
191
+
192
+ /** The room's project root, resolved through links and required to be a folder. */
193
+ function project_root(cwd) {
194
+ if (!cwd?.trim()) throw new Error('本房间未设置项目目录');
195
+ const root = realpathSync(cwd);
196
+ if (!statSync(root).isDirectory()) throw new Error('项目目录不是文件夹');
197
+ return root;
198
+ }
199
+
200
+ /**
201
+ * List one directory page or preview one file under one project directory, or search names under it; a search over
202
+ * several directories is `search_project_roots`.
203
+ */
204
+ export function read_project_files(cwd, path = '', offset = 0, query = '') {
205
+ if (query) return search_project_roots([cwd], query);
206
+ if (!Number.isSafeInteger(offset) || offset < 0) throw new Error('目录分页位置无效');
207
+ const root = project_root(cwd);
208
+ const target = project_path(root, path);
209
+ const info = statSync(target);
210
+ const normalized = path.replaceAll('\\', '/').split('/').filter(part => part && part !== '.').join('/');
211
+ if (info.isFile()) return { path: normalized, kind: 'file', ...text_preview(target) };
212
+ if (!info.isDirectory()) throw new Error('只能浏览文件夹或预览普通文件');
213
+ const items = readdirSync(target, { withFileTypes: true }).sort((left, right) =>
214
+ Number(right.isDirectory()) - Number(left.isDirectory()) || left.name.localeCompare(right.name, 'zh-CN', { numeric: true }));
215
+ const entries = [];
216
+ let bytes = 0;
217
+ for (const entry of items.slice(offset, offset + DIRECTORY_PAGE_SIZE)) {
218
+ const item = directory_entry(root, normalized, entry);
219
+ bytes += Buffer.byteLength(JSON.stringify(item));
220
+ if (entries.length && bytes > DIRECTORY_MAX_BYTES) break;
221
+ entries.push(item);
222
+ }
223
+ return { path: normalized, kind: 'directory', entries, total: items.length,
224
+ next_offset: offset + entries.length < items.length ? offset + entries.length : null };
225
+ }
226
+
227
+ // An HTML page with the files it refers to inlined stays within this size; references past it are left as they are.
228
+ export const PAGE_MAX_BYTES = 8 * 1024 * 1024;
229
+ // Media types of the files a page may refer to; others are left as they are.
230
+ const PAGE_TYPES = {
231
+ css: 'text/css', js: 'text/javascript', mjs: 'text/javascript', json: 'application/json', txt: 'text/plain', csv: 'text/csv',
232
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', svg: 'image/svg+xml',
233
+ ico: 'image/x-icon', bmp: 'image/bmp', woff: 'font/woff', woff2: 'font/woff2', ttf: 'font/ttf', otf: 'font/otf',
234
+ mp3: 'audio/mpeg', wav: 'audio/wav', ogg: 'audio/ogg', m4a: 'audio/mp4', mp4: 'video/mp4', webm: 'video/webm',
235
+ };
236
+ // Script and style bodies are kept apart so only real tags are rewritten; comments are left alone.
237
+ const PAGE_PARTS = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)|(<style\b[^>]*>)([\s\S]*?)(<\/style\s*>)|(<!--[\s\S]*?-->)|(<[a-zA-Z][^>]*>)/gi;
238
+ const TAG_ATTRIBUTE = /(\s)(src|poster|href|style)(\s*=\s*)(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gi;
239
+ const CSS_URL = /url\(\s*(['"]?)([^'")]+)\1\s*\)/gi;
240
+ const CSS_IMPORT = /@import\s+(['"])([^'"]+)\1/gi;
241
+
242
+ /** The project path a reference in the file at `base` (a folder) names, or null for other URLs (schemes, fragments). */
243
+ function page_reference(base, reference) {
244
+ const value = reference.trim().replace(/&amp;/g, '&');
245
+ if (!value || /^([a-z][a-z0-9+.-]*:|\/\/|#)/i.test(value)) return null;
246
+ let path = value.replace(/[?#].*$/, '');
247
+ try { path = decodeURIComponent(path); } catch { /* Kept as written. */ }
248
+ return posix.normalize(path.startsWith('/') ? path.slice(1) : posix.join(base, path));
249
+ }
250
+
251
+ /** A referenced project file as a data URL (a style sheet with its own references inlined), or null when it is left as written. */
252
+ function page_resource(path, state, depth) {
253
+ if (path === null) return null;
254
+ if (state.inlined.has(path)) return state.inlined.get(path);
255
+ const type = PAGE_TYPES[posix.extname(path).slice(1).toLowerCase()];
256
+ if (!type) return null;
257
+ let bytes;
258
+ try {
259
+ if (path.startsWith('..')) throw new Error('outside');
260
+ const target = project_path(state.root, path);
261
+ if (!statSync(target).isFile()) throw new Error('not a file');
262
+ bytes = readFileSync(target);
263
+ } catch { state.missing.add(path); return null; }
264
+ if (type === 'text/css' && depth < 4) bytes = Buffer.from(page_css(bytes.toString('utf8'), posix.dirname(path), state, depth + 1));
265
+ const url = `data:${type};base64,${bytes.toString('base64')}`;
266
+ if (url.length > state.budget) { state.skipped.add(path); return null; }
267
+ state.budget -= url.length;
268
+ state.inlined.set(path, url);
269
+ return url;
270
+ }
271
+
272
+ /** Inline the files a style sheet refers to; `base` is the folder its relative URLs start from. */
273
+ function page_css(css, base, state, depth) {
274
+ return css.replace(CSS_IMPORT, (whole, quote, reference) => {
275
+ const url = page_resource(page_reference(base, reference), state, depth);
276
+ return url ? `@import url(${url})` : whole;
277
+ }).replace(CSS_URL, (whole, quote, reference) => {
278
+ const url = page_resource(page_reference(base, reference), state, depth);
279
+ return url ? `url(${url})` : whole;
280
+ });
281
+ }
282
+
283
+ /** Inline the files one tag refers to: `src`/`poster` of any tag, `href` of style sheets and icons, URLs in `style`. */
284
+ function page_tag(tag, base, state) {
285
+ const name = /^<([a-zA-Z][\w-]*)/.exec(tag)[1].toLowerCase();
286
+ const linked = name === 'link' && /\brel\s*=\s*["']?[^"'>]*\b(stylesheet|icon)\b/i.test(tag);
287
+ return tag.replace(TAG_ATTRIBUTE, (whole, space, attribute, equals, double, single, bare) => {
288
+ const value = double ?? single ?? bare;
289
+ const key = attribute.toLowerCase();
290
+ if (key === 'style') {
291
+ const css = page_css(value, base, state, 0);
292
+ return css === value ? whole : `${space}${attribute}${equals}"${css.replace(/"/g, '&quot;')}"`;
293
+ }
294
+ if (key === 'href' && !linked) return whole;
295
+ const url = page_resource(page_reference(base, value), state, 0);
296
+ return url ? `${space}${attribute}${equals}"${url}"` : whole;
297
+ });
298
+ }
299
+
300
+ /**
301
+ * One HTML file of a project with the style sheets, scripts, images, fonts and media it refers to by relative path
302
+ * inlined as data URLs, so it shows in full where only its text can be sent (another device, through the relay).
303
+ * Only files inside the project directory are read; references that are missing, outside it or past the size limit
304
+ * are left as written and listed. Resources a script asks for while running are not included.
305
+ */
306
+ export function bundle_project_page(cwd, path) {
307
+ const root = project_root(cwd);
308
+ const target = project_path(root, path);
309
+ if (!/\.html?$/i.test(target)) throw new Error('只能打开 HTML 文件');
310
+ const info = statSync(target);
311
+ if (!info.isFile()) throw new Error('只能预览普通文件');
312
+ if (info.size > PAGE_MAX_BYTES) throw new Error('HTML 文件超过 8 MiB,无法完整显示');
313
+ const normalized = path.replaceAll('\\', '/').split('/').filter(part => part && part !== '.').join('/');
314
+ const base = posix.dirname(normalized);
315
+ const state = { root, budget: PAGE_MAX_BYTES - info.size, inlined: new Map(), missing: new Set(), skipped: new Set() };
316
+ const html = readFileSync(target, 'utf8').replace(PAGE_PARTS, (whole, script_open, script_body, script_close, style_open, style_body, style_close, comment, tag) => {
317
+ if (script_open) return page_tag(script_open, base, state) + script_body + script_close;
318
+ if (style_open) return style_open + page_css(style_body, base, state, 0) + style_close;
319
+ return comment ?? page_tag(tag, base, state);
320
+ });
321
+ const bytes = Buffer.from(html, 'utf8');
322
+ return { path: normalized, bytes, version: createHash('sha256').update(bytes).digest('hex').slice(0, 16), modified_at: info.mtime.toISOString(),
323
+ missing: [...state.missing], skipped: [...state.skipped] };
324
+ }
325
+
326
+ // Images a Markdown file shows: inline `![alt](path "title")`, `![alt](<path with spaces>)` and reference definitions `[id]: path`.
327
+ const MARKDOWN_IMAGE = /!\[[^\]]*\]\(\s*(?:<([^>]+)>|([^)\s]+))/g;
328
+ const MARKDOWN_DEFINITION = /^ {0,3}\[[^\]]+\]:\s*(?:<([^>]+)>|(\S+))/gm;
329
+ const IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'avif', 'svg', 'bmp', 'ico'];
330
+
331
+ /**
332
+ * The project images one Markdown file refers to by relative path, as `{project path: data URL}` (JSON bytes, sent
333
+ * like a page), so the preview shows them where only text reaches the page (another device, through the relay). The
334
+ * preview resolves each rendered image the same way (`frontend/file-preview.js` `markdown_image_path`). Only image
335
+ * files inside the project are read; missing ones and those past the size limit are listed instead.
336
+ */
337
+ export function bundle_project_markdown(cwd, path) {
338
+ const root = project_root(cwd);
339
+ const target = project_path(root, path);
340
+ if (!/\.(md|markdown)$/i.test(target)) throw new Error('只能打开 Markdown 文件');
341
+ const info = statSync(target);
342
+ if (!info.isFile()) throw new Error('只能预览普通文件');
343
+ if (info.size > PAGE_MAX_BYTES) throw new Error('Markdown 文件超过 8 MiB,图片不载入');
344
+ const normalized = path.replaceAll('\\', '/').split('/').filter(part => part && part !== '.').join('/');
345
+ const base = posix.dirname(normalized);
346
+ const state = { root, budget: PAGE_MAX_BYTES, inlined: new Map(), missing: new Set(), skipped: new Set() };
347
+ const text = readFileSync(target, 'utf8');
348
+ for (const match of [...text.matchAll(MARKDOWN_IMAGE), ...text.matchAll(MARKDOWN_DEFINITION)]) {
349
+ const reference = page_reference(base, match[1] ?? match[2]);
350
+ // A definition may name a link rather than an image; only image files are read.
351
+ if (reference !== null && IMAGE_EXTENSIONS.includes(posix.extname(reference).slice(1).toLowerCase())) page_resource(reference, state, 0);
352
+ }
353
+ const bytes = Buffer.from(JSON.stringify(Object.fromEntries(state.inlined)), 'utf8');
354
+ return { path: normalized, bytes, version: createHash('sha256').update(bytes).digest('hex').slice(0, 16), modified_at: info.mtime.toISOString(),
355
+ missing: [...state.missing], skipped: [...state.skipped] };
356
+ }
357
+
358
+ // Binary files the preview reads whole, by extension: images and media for its viewer and players (the browser decides
359
+ // what it can decode), Office documents and compressed edit projects for its document previews.
360
+ export const MEDIA_TYPES = {
361
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', svg: 'image/svg+xml',
362
+ bmp: 'image/bmp', ico: 'image/x-icon',
363
+ mp4: 'video/mp4', m4v: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime', mkv: 'video/x-matroska', ogv: 'video/ogg',
364
+ mp3: 'audio/mpeg', wav: 'audio/wav', ogg: 'audio/ogg', oga: 'audio/ogg', opus: 'audio/ogg', m4a: 'audio/mp4', aac: 'audio/aac', flac: 'audio/flac',
365
+ // Office documents and the compressed Premiere project, read whole by the page's previews.
366
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
367
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', xls: 'application/vnd.ms-excel',
368
+ ods: 'application/vnd.oasis.opendocument.spreadsheet',
369
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', prproj: 'application/gzip',
370
+ };
371
+
372
+ /**
373
+ * One image, video, audio, Office or compressed edit-project file of a project, checked like any preview: inside the project, a regular file of a
374
+ * known media type. Returns its real path (for the local site to stream), size, type and a version that changes with it.
375
+ */
376
+ export function project_media(cwd, path) {
377
+ const root = project_root(cwd);
378
+ const target = project_path(root, path);
379
+ const content_type = MEDIA_TYPES[posix.extname(target.replaceAll('\\', '/')).slice(1).toLowerCase()];
380
+ if (!content_type) throw new Error('只能打开图片、音视频、Office 文档或剪辑工程文件');
381
+ const info = statSync(target);
382
+ if (!info.isFile()) throw new Error('只能预览普通文件');
383
+ return { file: target, size: info.size, content_type, modified_at: info.mtime.toISOString(), version: `${info.mtimeMs}:${info.size}` };
384
+ }
385
+
386
+ /** Search names under every directory of a room at once; each entry's `root` is the index of its directory. */
387
+ export function search_project_roots(directories, query) {
388
+ if (!directories.length) project_root('');
389
+ return search_result(String(query), directories.map(directory => search_project_files(project_root(directory), String(query))));
390
+ }