ai_co_discuss 0.5.19 → 0.5.21

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 (74) hide show
  1. package/.agents/skills/discuss-participant/SKILL.md +2 -1
  2. package/.agents/skills/share-card/SKILL.md +15 -0
  3. package/.agents/skills/share-card/references/share-card.md +43 -0
  4. package/.agents/skills/workflow-creator/SKILL.md +3 -0
  5. package/backend/execution_diagnostics.py +149 -0
  6. package/backend/free_room.py +133 -40
  7. package/backend/message_queue.py +6 -4
  8. package/backend/room_trace.py +219 -0
  9. package/backend/schema.sql +7 -1
  10. package/backend/server.py +113 -8
  11. package/docs/en/guide/cli.md +20 -0
  12. package/docs/en/guide/faq.md +1 -0
  13. package/docs/en/guide/members.md +3 -1
  14. package/docs/en/guide/rooms.md +7 -3
  15. package/docs/en/guide/workflows.md +2 -0
  16. package/docs/en/guide/working.md +9 -4
  17. package/docs/guide/cli.md +20 -0
  18. package/docs/guide/faq.md +1 -0
  19. package/docs/guide/members.md +3 -1
  20. package/docs/guide/rooms.md +7 -3
  21. package/docs/guide/workflows.md +2 -0
  22. package/docs/guide/working.md +9 -4
  23. package/frontend/locales/en/app.json +8 -0
  24. package/frontend/locales/en/backend.json +5 -0
  25. package/frontend/locales/en/discussion.json +10 -3
  26. package/frontend/locales/en/execution-diagnostics.json +32 -0
  27. package/frontend/locales/en/room.json +1 -0
  28. package/frontend/locales/en/settings.json +5 -0
  29. package/package.json +3 -2
  30. package/runner/adapters/antigravity_cli.mjs +15 -1
  31. package/runner/adapters/api.mjs +27 -3
  32. package/runner/adapters/api_images.mjs +1 -1
  33. package/runner/adapters/api_pi.mjs +30 -1
  34. package/runner/adapters/cli.mjs +15 -6
  35. package/runner/adapters/codex_bridge.mjs +20 -6
  36. package/runner/adapters/codex_cli.mjs +2 -1
  37. package/runner/codiscuss.mjs +7 -0
  38. package/runner/discuss.py +24 -2
  39. package/runner/discussion_launch.mjs +1 -1
  40. package/runner/discussion_setup.mjs +1 -1
  41. package/runner/discussion_skills.mjs +1 -1
  42. package/runner/expert_prompts.mjs +4 -3
  43. package/runner/free_runner.mjs +102 -24
  44. package/runner/i18n_en.mjs +45 -2
  45. package/runner/remote_launch.mjs +2 -2
  46. package/runner/share_card.mjs +1314 -0
  47. package/runner/share_service.mjs +25 -7
  48. package/runner/share_shared.mjs +28 -7
  49. package/runner/site_deploy.mjs +125 -4
  50. package/runner/timeline_metrics.mjs +185 -0
  51. package/runner/workflows.mjs +38 -9
  52. package/web/app.js +303 -81
  53. package/web/i18n.js +3 -3
  54. package/web/modern.css +1 -1
  55. package/web/modern.js +98 -67
  56. package/workflows/decision-council/SKILL.md +2 -1
  57. package/workflows/decision-council/flow.json +15 -15
  58. package/workflows/story-serial/agents/writer.md +1 -1
  59. package/workflows/story-serial/flow.json +456 -123
  60. package/workflows/story-serial/workflows/aigc-reduce/flow.json +134 -13
  61. package/workflows/story-serial/workflows/character-play/flow.json +212 -25
  62. package/workflows/story-serial/workflows/jack-sparrow/flow.json +67 -23
  63. package/workflows/story-serial/workflows/luke-nichols/flow.json +67 -23
  64. package/workflows/story-serial/workflows/revise-episodes/flow.json +184 -23
  65. package/workflows/story-serial/workflows/tidy-docs/flow.json +256 -19
  66. package/workflows/tri-model-dev/SKILL.md +72 -0
  67. package/workflows/tri-model-dev/agents/advisor.md +22 -0
  68. package/workflows/tri-model-dev/agents/backend.md +25 -0
  69. package/workflows/tri-model-dev/agents/reviewer.md +38 -0
  70. package/workflows/tri-model-dev/flow.json +397 -0
  71. package/workflows/tri-model-dev/workflows/browser-verify/SKILL.md +22 -0
  72. package/workflows/tri-model-dev/workflows/browser-verify/agents/browser_ops.md +18 -0
  73. package/workflows/tri-model-dev/workflows/browser-verify/flow.json +136 -0
  74. package/workflows/trpg-classic/flow.json +17 -17
@@ -0,0 +1,1314 @@
1
+ /**
2
+ * Share-card tools for room AI members: `codiscuss share-card materials` (shareable-scope collaboration metrics,
3
+ * concurrency curve and material index) and `codiscuss share-card render` (local static HTML → PNG via an isolated,
4
+ * sandboxed local Chromium/Edge browser controlled over private process pipes). Uses only Node.js built-in modules.
5
+ */
6
+ import { spawn } from 'node:child_process';
7
+ import { createHash, randomBytes } from 'node:crypto';
8
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
9
+ import { createServer } from 'node:http';
10
+ import { tmpdir } from 'node:os';
11
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path';
12
+ import { setTimeout as delay } from 'node:timers/promises';
13
+ import { parseArgs } from 'node:util';
14
+
15
+ import { kill_process_tree } from './adapters/common.mjs';
16
+ import { adapter_capabilities } from './adapters/profiles.mjs';
17
+ import { configuration_snapshot, read_registry, service_home } from './discussion_service.mjs';
18
+ import { local_settings } from './discussion_setup.mjs';
19
+ import { site_fetch } from './entry_client.mjs';
20
+ import { t } from './i18n.mjs';
21
+ import {
22
+ create_share_core,
23
+ is_share_question_receipt,
24
+ SHARE_FILE_KINDS,
25
+ SHARE_HOME_FOLDERS,
26
+ SHARE_SENSITIVE_PATTERNS,
27
+ } from './share_shared.mjs';
28
+ import { collaboration_metrics, format_duration } from './timeline_metrics.mjs';
29
+
30
+ export const SHARE_CARD_COVER_SPEC = Object.freeze({
31
+ width_css_px: 750,
32
+ scale: 2,
33
+ export_width_px: 1500,
34
+ recommended_height_css_px: [560, 1100],
35
+ min_height_css_px: 200,
36
+ max_height_css_px: 1500,
37
+ max_aspect_ratio: '2:1',
38
+ format: 'png',
39
+ accepted_image_formats: ['png', 'jpg', 'jpeg', 'webp'],
40
+ default_background: '#12141c',
41
+ });
42
+
43
+ const READ_ONLY_HEADER = 'X-Discussion-Read-Only';
44
+ const MAX_HTML_BYTES = 10 * 1024 * 1024;
45
+ const MAX_TIMELINE_PAGES = 20;
46
+ const MAX_MESSAGE_PAGES = 50;
47
+ const MESSAGES_PER_PAGE = 200;
48
+ const DEFAULT_HIGHLIGHTS = 12;
49
+ const DEFAULT_CURVE_STEPS = 240;
50
+ const DEFAULT_RENDER_TIMEOUT_MS = 30_000;
51
+ const MIN_WIDTH_PX = 320;
52
+ const MAX_WIDTH_PX = 1500;
53
+ const HARD_MAX_HEIGHT_PX = 2400;
54
+ const HEX_COLOR = /^#([0-9a-fA-F]{6})$/;
55
+ const SLASH_COMMAND = /^\/(?:goal|discuss)\b/i;
56
+ const SHORT_ACK = /^(?:继续|好的?|行|ok|yes|收到|同意|开始|可以|确认|嗯|明白|go|continue)[。!!.,,\s]*$/iu;
57
+ const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
58
+ const SANDBOX_ERROR_PATTERN = /no usable sandbox|running as root without --no-sandbox|zygote.*sandbox|suid sandbox|user namespace|clone.*eperm|setuid_sandbox/i;
59
+
60
+ const STATIC_ASSET_TYPES = Object.freeze({
61
+ '.css': 'text/css; charset=utf-8',
62
+ '.png': 'image/png',
63
+ '.jpg': 'image/jpeg',
64
+ '.jpeg': 'image/jpeg',
65
+ '.gif': 'image/gif',
66
+ '.webp': 'image/webp',
67
+ '.avif': 'image/avif',
68
+ '.svg': 'image/svg+xml',
69
+ '.ico': 'image/x-icon',
70
+ '.woff': 'font/woff',
71
+ '.woff2': 'font/woff2',
72
+ '.ttf': 'font/ttf',
73
+ '.otf': 'font/otf',
74
+ });
75
+
76
+ // Strict CSP: zero JavaScript execution, zero external network or cross-port requests, local static assets & data URLs only.
77
+ export const RENDER_CSP = "sandbox allow-same-origin; default-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; script-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; media-src 'none'; form-action 'none'; base-uri 'self'";
78
+
79
+ const SHARE_CORE = create_share_core({
80
+ t,
81
+ display_name: (name) => name,
82
+ collapse_visual_fences: (text, label) => String(text || '').replace(/```visual\b[\s\S]*?(?:```|$)/g, `[${label}]`),
83
+ is_text_attachment: () => false,
84
+ });
85
+
86
+ export class ShareCardError extends Error {
87
+ constructor(message, { code = 'invalid', ...details } = {}) {
88
+ super(message);
89
+ this.code = code;
90
+ this.details = details;
91
+ }
92
+ }
93
+
94
+ /** Refuse share-card commands in tool-lockdown / external runs so restricted members cannot read local files or start browsers. */
95
+ export function assert_share_card_allowed(access = {}, env = process.env) {
96
+ if (env.CODISCUSS_TOOL_LOCKDOWN === '1' || access?.tool_lockdown || access?.transport === 'external') {
97
+ throw new ShareCardError(t('本次运行已收窄,不能使用 share-card 命令'), { code: 'lockdown' });
98
+ }
99
+ }
100
+
101
+ function read_access_file(explicit_path = '', env = process.env) {
102
+ const path = explicit_path || env.DISCUSS_ACCESS_FILE || '';
103
+ if (path) {
104
+ if (!existsSync(path)) {
105
+ throw new ShareCardError(t('凭据文件不存在:{path}', { path }), { code: 'auth' });
106
+ }
107
+ try {
108
+ const value = JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, ''));
109
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('not object');
110
+ return value;
111
+ } catch {
112
+ throw new ShareCardError(t('凭据文件不是有效的 JSON 对象'), { code: 'auth' });
113
+ }
114
+ }
115
+ const inline = String(env.DISCUSS_ACCESS || '').trim();
116
+ if (!inline) return {};
117
+ try {
118
+ const value = JSON.parse(inline);
119
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('not object');
120
+ return value;
121
+ } catch {
122
+ throw new ShareCardError(t('DISCUSS_ACCESS 不是有效的 JSON 对象'), { code: 'auth' });
123
+ }
124
+ }
125
+
126
+ function has_task_credential(access) {
127
+ return Boolean(access && (access.site || access.token || access.room || access.member));
128
+ }
129
+
130
+ function normalize_site_url(raw) {
131
+ const text = String(raw || '').trim();
132
+ if (!text) return '';
133
+ let parsed;
134
+ try { parsed = new URL(text); } catch {
135
+ throw new ShareCardError(t('站点地址无效,请使用 http(s)://主机[:端口],不带路径、凭据或查询'), { code: 'invalid_site' });
136
+ }
137
+ if (!['http:', 'https:'].includes(parsed.protocol) || !parsed.hostname || parsed.username || parsed.password
138
+ || parsed.search || parsed.hash || !['', '/'].includes(parsed.pathname)) {
139
+ throw new ShareCardError(t('站点地址无效,请使用 http(s)://主机[:端口],不带路径、凭据或查询'), { code: 'invalid_site' });
140
+ }
141
+ return parsed.origin;
142
+ }
143
+
144
+ /**
145
+ * Resolve target site and auth headers for `share-card materials`, matching `runner/discuss.py`:
146
+ * - When a task credential is present, the target site MUST match the credential's bound site.
147
+ * - Same room sends `X-Discussion-Token`; another room on the same bound site omits the token and sends `X-Discussion-Read-Only: 1`.
148
+ */
149
+ export function resolve_materials_auth({ explicit_site = '', room_id = '', access = {}, env = process.env } = {}) {
150
+ const bound = has_task_credential(access);
151
+ const bound_site = access.site ? normalize_site_url(access.site) : '';
152
+ const requested_raw = explicit_site || env.DISCUSS_URL || access.site || (!bound ? `http://127.0.0.1:${local_settings().port || 8765}` : '');
153
+ const site = normalize_site_url(requested_raw);
154
+ if (!site) {
155
+ throw new ShareCardError(t('请用 --site、DISCUSS_URL 或任务凭据指定目标站点'), { code: 'invalid_site' });
156
+ }
157
+ if (!bound) return { site, headers: {}, cross_room: false };
158
+ if (!bound_site || bound_site !== site) {
159
+ throw new ShareCardError(t('凭据文件不属于本次站点'), { code: 'auth' });
160
+ }
161
+ if (access.room && room_id && room_id !== access.room) {
162
+ return { site, headers: { [READ_ONLY_HEADER]: '1' }, cross_room: true };
163
+ }
164
+ const token = access.token;
165
+ if (typeof token !== 'string' || !token.trim()) {
166
+ throw new ShareCardError(t('凭据文件中的 token 无效'), { code: 'auth' });
167
+ }
168
+ return { site, headers: { 'X-Discussion-Token': token }, cross_room: false };
169
+ }
170
+
171
+ async function room_json(site, path, headers, fetcher) {
172
+ const response = await fetcher(`${site}${path}`, { method: 'GET', headers, redirect: 'error' });
173
+ if (!response.ok) {
174
+ const detail = await response.json().catch(() => ({}));
175
+ throw new ShareCardError(detail.error || t('读取房间数据失败(HTTP {status})', { status: response.status }), {
176
+ code: 'http_error', http_status: response.status, path,
177
+ });
178
+ }
179
+ return response.json();
180
+ }
181
+
182
+ function compile_project_patterns(folders = []) {
183
+ const known = [...new Set(folders.filter((item) => typeof item === 'string' && item.trim()))]
184
+ .sort((a, b) => b.length - a.length);
185
+ return known.map((folder) => SHARE_CORE.share_folder_pattern(folder)).filter(Boolean);
186
+ }
187
+
188
+ function collect_known_folders(room_entry, raw_objects = [], extra_folders = []) {
189
+ const known = new Set(extra_folders.filter((item) => typeof item === 'string' && item.trim()));
190
+ const config = room_entry?.config;
191
+ if (config) {
192
+ for (const dir of [config.cwd, config.workdir, ...(config.extra_directories || [])]) {
193
+ if (typeof dir === 'string' && dir.trim()) known.add(dir);
194
+ }
195
+ for (const profile of Object.values(config.participants || {})) {
196
+ if (typeof profile?.cwd === 'string' && profile.cwd.trim()) known.add(profile.cwd);
197
+ }
198
+ }
199
+ const visit = (value) => {
200
+ if (!value || typeof value !== 'object') return;
201
+ if (Array.isArray(value)) { for (const item of value) visit(item); return; }
202
+ for (const [key, item] of Object.entries(value)) {
203
+ if (key === 'cwd' && typeof item === 'string' && item.trim()) known.add(item);
204
+ else if (item && typeof item === 'object') visit(item);
205
+ }
206
+ };
207
+ for (const obj of raw_objects) visit(obj);
208
+ return [...known];
209
+ }
210
+
211
+ function scrub_paths(text, project_patterns = []) {
212
+ const collapsed = String(text || '').replace(/```visual\b[\s\S]*?(?:```|$)/g, `[${t('交互式可视化')}]`);
213
+ const without_project = project_patterns.reduce(
214
+ (value, pattern) => value.replace(pattern, (match, separator) => (separator ? '' : t('项目目录'))),
215
+ collapsed,
216
+ );
217
+ return SHARE_HOME_FOLDERS.reduce((value, pattern) => value.replace(pattern, () => '~'), without_project);
218
+ }
219
+
220
+ function plain_excerpt(text, limit = 240, project_patterns = []) {
221
+ const cleaned = scrub_paths(text, project_patterns)
222
+ .replace(/```[\s\S]*?```/g, ' ')
223
+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
224
+ .replace(/[`*_>#|]+|~~+/g, ' ')
225
+ .replace(/\s+/g, ' ')
226
+ .trim();
227
+ if (cleaned.length <= limit) return cleaned;
228
+ return `${cleaned.slice(0, Math.max(0, limit - 1)).trimEnd()}…`;
229
+ }
230
+
231
+ function has_sensitive_text(text, project_patterns = []) {
232
+ const value = scrub_paths(text, project_patterns);
233
+ if (!value) return false;
234
+ return SHARE_SENSITIVE_PATTERNS.some((pattern) => {
235
+ pattern.lastIndex = 0;
236
+ return pattern.test(value);
237
+ });
238
+ }
239
+
240
+ function file_kind(file_name) {
241
+ return SHARE_FILE_KINDS.find(([, pattern]) => pattern.test(file_name || ''))?.[0] || 'text';
242
+ }
243
+
244
+ function safe_dest_filename(file_name) {
245
+ const cleaned = basename(String(file_name || 'image.png'))
246
+ .replace(/[^\p{L}\p{M}\p{N} ._-]/gu, '_')
247
+ .trim();
248
+ return cleaned && cleaned !== '.' && cleaned !== '..' ? cleaned : 'image.png';
249
+ }
250
+
251
+ /** Pick the first substantive user request, reusing `is_share_question_receipt`; returns null when only receipts exist. */
252
+ function pick_opening_request(user_messages, project_patterns = []) {
253
+ const substantive = user_messages.find((message) => {
254
+ if (is_share_question_receipt(message.text)) return false;
255
+ const body = plain_excerpt(message.text, 400, project_patterns);
256
+ if (!body || SLASH_COMMAND.test(body)) return false;
257
+ return !SHORT_ACK.test(body);
258
+ });
259
+ return substantive || null;
260
+ }
261
+
262
+ function build_curve_steps(steps, start_ms, span_ms, label_of, max_steps) {
263
+ if (!steps.length || !span_ms) return { sampled: false, steps: [] };
264
+ const map_step = (step) => ({
265
+ start_ms: step.start,
266
+ end_ms: step.end,
267
+ from: Number(((step.start - start_ms) / span_ms).toFixed(5)),
268
+ to: Number(((step.end - start_ms) / span_ms).toFixed(5)),
269
+ total: step.total,
270
+ members: step.members.map((entry) => ({ name: entry.member, label: label_of(entry.member), count: entry.count })),
271
+ });
272
+ if (steps.length <= max_steps) return { sampled: false, steps: steps.map(map_step) };
273
+ // Bucket long multi-day rooms cleanly while preserving the peak concurrent member count per bucket.
274
+ const bucket_ms = span_ms / max_steps;
275
+ const sampled = [];
276
+ for (let index = 0; index < max_steps; index += 1) {
277
+ const b_start = Math.round(start_ms + index * bucket_ms);
278
+ const b_end = index + 1 === max_steps ? start_ms + span_ms : Math.round(start_ms + (index + 1) * bucket_ms);
279
+ let peak_step = null;
280
+ for (const step of steps) {
281
+ if (step.end <= b_start || step.start >= b_end) continue;
282
+ if (!peak_step || step.total > peak_step.total) peak_step = step;
283
+ }
284
+ sampled.push({
285
+ start_ms: b_start,
286
+ end_ms: b_end,
287
+ from: Number(((b_start - start_ms) / span_ms).toFixed(5)),
288
+ to: Number(((b_end - start_ms) / span_ms).toFixed(5)),
289
+ total: peak_step ? peak_step.total : 0,
290
+ members: peak_step ? peak_step.members.map((entry) => ({ name: entry.member, label: label_of(entry.member), count: entry.count })) : [],
291
+ });
292
+ }
293
+ return { sampled: true, steps: sampled };
294
+ }
295
+
296
+ function pick_highlights(messages, max_highlights) {
297
+ const candidates = messages.filter((message) => message.kind !== 'system' && message.kind !== 'notice' && message.source !== 'notice' && message.text);
298
+ if (candidates.length <= max_highlights) return candidates;
299
+ const head_count = Math.max(2, Math.floor(max_highlights / 3));
300
+ const tail_count = max_highlights - head_count;
301
+ const head = candidates.slice(0, head_count);
302
+ const tail = candidates.slice(-tail_count);
303
+ const seen = new Set(head.map((item) => item.id));
304
+ return [...head, ...tail.filter((item) => !seen.has(item.id))];
305
+ }
306
+
307
+ /**
308
+ * Read shareable-scope collaboration metrics, concurrency curve, and material index for a room.
309
+ *
310
+ * @param {object} options Connection and shaping parameters.
311
+ * @returns {Promise<object>} Structured share-card material bundle.
312
+ */
313
+ export async function share_card_materials({
314
+ site = '',
315
+ room_id = '',
316
+ token = '',
317
+ access = {},
318
+ headers = null,
319
+ home = service_home(),
320
+ folders = [],
321
+ max_highlights = DEFAULT_HIGHLIGHTS,
322
+ max_steps = DEFAULT_CURVE_STEPS,
323
+ max_message_pages = MAX_MESSAGE_PAGES,
324
+ max_timeline_pages = MAX_TIMELINE_PAGES,
325
+ fetcher = site_fetch,
326
+ env = process.env,
327
+ } = {}) {
328
+ assert_share_card_allowed(access, env);
329
+ const target_room = room_id || access?.room || '';
330
+ if (!target_room || !/^[A-Za-z0-9_-]+$/.test(target_room)) {
331
+ throw new ShareCardError(t('请提供有效的房间编号(可经 --room 或任务凭据自动补齐)'), { code: 'invalid_room' });
332
+ }
333
+ let resolved_site;
334
+ let request_headers;
335
+ if (has_task_credential(access)) {
336
+ const auth = resolve_materials_auth({ explicit_site: site, room_id: target_room, access, env });
337
+ resolved_site = auth.site;
338
+ request_headers = auth.headers;
339
+ } else {
340
+ resolved_site = normalize_site_url(site || env.DISCUSS_URL || `http://127.0.0.1:${local_settings().port || 8765}`);
341
+ request_headers = headers || (token ? { 'X-Discussion-Token': token } : {});
342
+ }
343
+ const base = `/api/rooms/${encodeURIComponent(target_room)}`;
344
+ const room = await room_json(resolved_site, base, request_headers, fetcher);
345
+
346
+ // Only executions whose linked messages appear in the visible transcript can contribute to the card.
347
+ const visible_messages = [];
348
+ const visible_ids = new Set();
349
+ let messages_truncated = false;
350
+ for (let after = 0, page = 0; ; page += 1) {
351
+ if (page >= max_message_pages) { messages_truncated = true; break; }
352
+ const query = new URLSearchParams({ limit: String(MESSAGES_PER_PAGE), cards: '1', after: String(after) });
353
+ const batch = await room_json(resolved_site, `${base}/messages?${query}`, request_headers, fetcher);
354
+ const items = batch.messages || [];
355
+ for (const message of items) {
356
+ if (message.withdrawn) continue;
357
+ visible_messages.push(message);
358
+ visible_ids.add(message.id);
359
+ }
360
+ if (!batch.has_more) break;
361
+ const next_after = batch.next_after ?? items.at(-1)?.id;
362
+ if (!items.length || !next_after || next_after <= after) { messages_truncated = true; break; }
363
+ after = next_after;
364
+ }
365
+ visible_messages.sort((a, b) => a.id - b.id);
366
+
367
+ // Read execution timeline (paginating backwards via `before` when `earlier` is true, up to `max_timeline_pages`).
368
+ const by_exec_key = new Map();
369
+ let now_ms = Date.now();
370
+ let timeline_truncated = false;
371
+ let timeline_pages_read = 0;
372
+ for (let before = 0, page = 0; ; page += 1) {
373
+ if (page >= max_timeline_pages) { timeline_truncated = true; break; }
374
+ const query = new URLSearchParams({ segments: '0', ...(before ? { before: String(before) } : {}) });
375
+ const timeline = await room_json(resolved_site, `${base}/timeline?${query}`, request_headers, fetcher);
376
+ timeline_pages_read += 1;
377
+ if (page === 0 && timeline.now) now_ms = timeline.now * 1000;
378
+ const rows = timeline.executions || [];
379
+ let min_id = Infinity;
380
+ for (const execution of rows) {
381
+ if (execution.source === 'external') continue;
382
+ if (execution.id < min_id) min_id = execution.id;
383
+ const linked_ids = [execution.task_id, execution.request_message_id, execution.answer_id].filter(Boolean);
384
+ if (linked_ids.some(id => !visible_ids.has(id)) || (messages_truncated && !linked_ids.length)) continue;
385
+ const key = `${execution.source}:${execution.id}`;
386
+ if (!by_exec_key.has(key)) by_exec_key.set(key, execution);
387
+ }
388
+ if (!timeline.earlier || !rows.length || !Number.isFinite(min_id) || (before && min_id >= before)) break;
389
+ before = min_id;
390
+ }
391
+
392
+ let sites = [];
393
+ try {
394
+ const site_data = await room_json(resolved_site, `${base}/sites`, request_headers, fetcher);
395
+ sites = (site_data.sites || [])
396
+ .filter((item) => item.status === 'active')
397
+ .map((item) => ({ site_id: item.site_id, title: item.title || '', url: item.url, status: item.status, expires_at: item.expires_at || '' }));
398
+ } catch { /* Sites endpoint is optional on older or minimal servers. */ }
399
+
400
+ const room_entry = find_room_config(home, target_room, resolved_site);
401
+ const project_patterns = compile_project_patterns(collect_known_folders(room_entry, [room, [...by_exec_key.values()]], folders));
402
+
403
+ const members = (room.members || []).filter((member) => member.status !== 'removed');
404
+ const label_map = new Map(members.map((member) => [member.name, member.label || member.name]));
405
+ const role_map = new Map(members.map((member) => [member.name, member.role || 'member']));
406
+ const label_of = (name) => label_map.get(name) || name;
407
+
408
+ const executions = [...by_exec_key.values()];
409
+ const collab = collaboration_metrics(executions, now_ms);
410
+ const { model } = collab;
411
+ const span_ms = collab.span_ms;
412
+ const { sampled, steps } = build_curve_steps(model.steps, model.start, span_ms, label_of, max_steps);
413
+
414
+ const user_messages = visible_messages.filter((message) => message.author === '用户' && message.text);
415
+ const opening = pick_opening_request(user_messages, project_patterns);
416
+ const latest_user = user_messages.at(-1) || null;
417
+ const format_user_msg = (message) => {
418
+ if (!message) return null;
419
+ const sensitive = has_sensitive_text(message.text, project_patterns);
420
+ return {
421
+ id: message.id,
422
+ created_at: message.created_at || '',
423
+ sensitive_flagged: sensitive,
424
+ text: sensitive ? '' : plain_excerpt(message.text, 360, project_patterns),
425
+ };
426
+ };
427
+
428
+ const highlights = pick_highlights(visible_messages, max_highlights).map((message) => {
429
+ const raw_text = message.text || '';
430
+ const raw_summary = message.summary || '';
431
+ const sensitive = has_sensitive_text(raw_text, project_patterns) || has_sensitive_text(raw_summary, project_patterns);
432
+ return {
433
+ id: message.id,
434
+ author: message.author,
435
+ author_label: message.author_label || label_of(message.author),
436
+ role: message.author === '用户' ? 'user' : (role_map.get(message.author) || 'member'),
437
+ created_at: message.created_at || '',
438
+ sensitive_flagged: sensitive,
439
+ summary: sensitive ? '' : plain_excerpt(raw_summary, 200, project_patterns),
440
+ excerpt: sensitive ? '' : plain_excerpt(raw_text, 280, project_patterns),
441
+ attachment_count: (message.attachments || []).length,
442
+ };
443
+ });
444
+
445
+ const attachments = [];
446
+ const images = [];
447
+ const kind_counts = new Map();
448
+ for (const message of visible_messages) {
449
+ for (const file of message.attachments || []) {
450
+ const kind = file_kind(file.file_name);
451
+ const size = Number(file.size) || 0;
452
+ const entry = {
453
+ id: file.id,
454
+ message_id: message.id,
455
+ author: message.author_label || label_of(message.author),
456
+ created_at: message.created_at || '',
457
+ file_name: file.file_name,
458
+ kind,
459
+ size,
460
+ content_type: String(file.content_type || '').split(';')[0].trim(),
461
+ };
462
+ attachments.push(entry);
463
+ const group = kind_counts.get(kind) || { kind, count: 0, bytes: 0 };
464
+ group.count += 1;
465
+ group.bytes += size;
466
+ kind_counts.set(kind, group);
467
+ if (kind === 'image' || entry.content_type.startsWith('image/')) {
468
+ const dest_name = safe_dest_filename(file.file_name);
469
+ images.push({
470
+ ...entry,
471
+ suggested_file_name: dest_name,
472
+ download_command: /^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/.test(file.id)
473
+ ? `codiscuss attachment download ${target_room} ${file.id} --dest "./${dest_name}"` : null,
474
+ });
475
+ }
476
+ }
477
+ }
478
+ images.sort((a, b) => b.message_id - a.message_id);
479
+
480
+ return {
481
+ room: {
482
+ id: room.id || target_room,
483
+ title: room.title || '',
484
+ goal: has_sensitive_text(room.goal, project_patterns) ? '' : plain_excerpt(room.goal || '', 360, project_patterns),
485
+ created_at: room.created_at || '',
486
+ message_count: visible_messages.length,
487
+ members: members.map((member) => ({
488
+ name: member.name,
489
+ label: member.label || member.name,
490
+ role: member.role || 'member',
491
+ adapter: member.adapter || '',
492
+ })),
493
+ },
494
+ scope: {
495
+ shareable_only: true,
496
+ withdrawn_excluded: true,
497
+ external_executions_excluded: true,
498
+ messages_truncated,
499
+ timeline_truncated,
500
+ truncated: messages_truncated || timeline_truncated,
501
+ curve_sampled: sampled,
502
+ timeline_pages_read,
503
+ max_messages: max_message_pages * MESSAGES_PER_PAGE,
504
+ max_timeline_pages,
505
+ note: t('统计按可分享范围计算:排除已撤回消息及其关联执行和外部执行,并按分页回溯历史时间线;网页“并发全景”默认仅展示最近 100 次且不剔除撤回执行,两者数字可能略有差异。'),
506
+ },
507
+ metrics: {
508
+ span_ms: collab.span_ms,
509
+ span_text: collab.span_text,
510
+ busy_ms: collab.busy_ms,
511
+ busy_text: collab.busy_text,
512
+ busy_percent: collab.busy_percent,
513
+ idle_ms: collab.idle_ms,
514
+ idle_text: collab.idle_text,
515
+ runs: collab.runs,
516
+ self_started: collab.self_started,
517
+ self_started_percent: collab.self_started_percent,
518
+ peak_concurrency: collab.peak_concurrency,
519
+ unattended: collab.unattended,
520
+ active_members: collab.member_totals.map((entry) => ({
521
+ name: entry.member,
522
+ label: label_of(entry.member),
523
+ runs: entry.runs,
524
+ work_ms: entry.work_ms,
525
+ work_text: entry.work_text,
526
+ })),
527
+ },
528
+ concurrency_curve: {
529
+ start_ms: model.start,
530
+ end_ms: model.end,
531
+ span_ms,
532
+ peak: model.peak,
533
+ sampled,
534
+ members: model.members.map((name, index) => ({ name, label: label_of(name), color_index: index })),
535
+ steps,
536
+ idle_gaps: model.idle.map((gap) => ({
537
+ start_ms: gap.start,
538
+ end_ms: gap.end,
539
+ from: span_ms ? Number(((gap.start - model.start) / span_ms).toFixed(5)) : 0,
540
+ to: span_ms ? Number(((gap.end - model.start) / span_ms).toFixed(5)) : 0,
541
+ duration_ms: gap.end - gap.start,
542
+ duration_text: format_duration(gap.end - gap.start),
543
+ })),
544
+ tasks: model.tasks.map((task) => ({
545
+ key: task.key,
546
+ label: has_sensitive_text(task.task, project_patterns) ? '' : plain_excerpt(task.task, 120, project_patterns),
547
+ opened: task.opened,
548
+ start_ms: task.start,
549
+ end_ms: task.end,
550
+ from: span_ms ? Number(((task.start - model.start) / span_ms).toFixed(5)) : 0,
551
+ to: span_ms ? Number(((task.end - model.start) / span_ms).toFixed(5)) : 0,
552
+ duration_ms: task.end - task.start,
553
+ duration_text: format_duration(task.end - task.start),
554
+ })),
555
+ },
556
+ materials: {
557
+ opening_request: format_user_msg(opening),
558
+ latest_user_message: format_user_msg(latest_user),
559
+ total_messages: visible_messages.length,
560
+ highlights,
561
+ images,
562
+ attachments_by_kind: [...kind_counts.values()],
563
+ attachments,
564
+ sites,
565
+ },
566
+ cover_spec: {
567
+ ...SHARE_CARD_COVER_SPEC,
568
+ note: t('分享面板会自动在封面下方拼接统一的扫码底栏(二维码、域名和最新有效期),并可吸取封面底边颜色;封面 HTML 中请勿绘制二维码、分享链接或有效期。'),
569
+ },
570
+ };
571
+ }
572
+
573
+ // ---- Member file-permission boundaries for `share-card render` ----
574
+
575
+ function normalize_for_compare(path) {
576
+ const value = resolve(path);
577
+ return process.platform === 'win32' ? value.toLowerCase() : value;
578
+ }
579
+
580
+ function is_same_or_inside(root_dir, target_path) {
581
+ const root = normalize_for_compare(root_dir);
582
+ const target = normalize_for_compare(target_path);
583
+ const rel = relative(root, target);
584
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
585
+ }
586
+
587
+ function overlapping_dirs(left, right) {
588
+ if (!left || !right) return false;
589
+ return is_same_or_inside(left, right) || is_same_or_inside(right, left);
590
+ }
591
+
592
+ /** Resolve a path that may not exist yet by calling `realpathSync` on its nearest existing ancestor. */
593
+ function resolve_future_real_path(target_path) {
594
+ const abs = resolve(target_path);
595
+ if (existsSync(abs)) return realpathSync(abs);
596
+ const parts = [];
597
+ let current = abs;
598
+ while (!existsSync(current)) {
599
+ const parent = dirname(current);
600
+ if (parent === current) return abs;
601
+ parts.unshift(basename(current));
602
+ current = parent;
603
+ }
604
+ return join(realpathSync(current), ...parts);
605
+ }
606
+
607
+ function find_room_config(home, room_id, site = '') {
608
+ if (!room_id || !home) return null;
609
+ const normalized_site = site ? site.replace(/\/+$/, '') : '';
610
+ for (const config_path of read_registry(home)) {
611
+ try {
612
+ const { config } = configuration_snapshot(config_path);
613
+ if (config.room !== room_id) continue;
614
+ if (normalized_site && config.site && config.site.replace(/\/+$/, '') !== normalized_site) continue;
615
+ return { config, config_path };
616
+ } catch { /* Ignore unreadable configs. */ }
617
+ }
618
+ return null;
619
+ }
620
+
621
+ function member_hash_dir(name) {
622
+ return createHash('sha256').update(String(name)).digest('hex').slice(0, 16);
623
+ }
624
+
625
+ function service_drafts_dir(home, runtime_dir) {
626
+ const key = createHash('sha256').update(resolve(runtime_dir)).digest('hex');
627
+ return join(home, 'drafts', key);
628
+ }
629
+
630
+ function push_real_dir(list, dir) {
631
+ if (!dir) return;
632
+ try {
633
+ const real = existsSync(dir) ? realpathSync(dir) : resolve_future_real_path(dir);
634
+ if (existsSync(real) && !statSync(real).isDirectory()) return;
635
+ if (!list.some((item) => normalize_for_compare(item) === normalize_for_compare(real))) list.push(real);
636
+ } catch { /* Ignore invalid directory. */ }
637
+ }
638
+
639
+ /**
640
+ * Resolve the allowed read and write roots for a member task calling `share-card render`, using the real on-disk
641
+ * launch config format (`data_directory`, stable participant key, and effective `project_access` including `auto`).
642
+ * Returns `null` only when no task credential is present (plain manual CLI invocation by the computer owner).
643
+ */
644
+ export function resolve_member_render_roots(access = {}, home = service_home()) {
645
+ if (!has_task_credential(access)) return null;
646
+ const read_roots = [];
647
+ const write_roots = [];
648
+ const found = find_room_config(home, access.room, access.site);
649
+ if (!found) {
650
+ if (access.draft_directory) {
651
+ push_real_dir(read_roots, access.draft_directory);
652
+ push_real_dir(write_roots, access.draft_directory);
653
+ return { read_roots, write_roots };
654
+ }
655
+ throw new ShareCardError(t('无法确认成员的文件权限,已拒绝渲染'), { code: 'auth' });
656
+ }
657
+
658
+ const { config, config_path } = found;
659
+ const member_name = typeof access.member === 'string' ? access.member : '';
660
+ const participants = config.participants || {};
661
+ if (member_name && !Object.hasOwn(participants, member_name)) {
662
+ throw new ShareCardError(t('凭据中的成员不在房间配置内,已拒绝渲染'), { code: 'auth' });
663
+ }
664
+ const profile = member_name ? participants[member_name] : null;
665
+
666
+ // Match runner/discussion_runner.mjs:96: real configs store `data_directory` (with `directory` only added in memory).
667
+ const runtime_dir = resolve(config.data_directory || config.directory || join(dirname(resolve(config_path)), `discussion-${config.room}`));
668
+
669
+ // Every member may read/write inside its own drafts folder, and read (not write) its own runtime folder (attachments).
670
+ if (member_name) {
671
+ const hash = member_hash_dir(member_name);
672
+ const draft_bases = [config.draft_directory || (home ? service_drafts_dir(home, runtime_dir) : `${runtime_dir}-drafts`)];
673
+ const legacy_drafts = `${runtime_dir}-drafts`;
674
+ if (!config.draft_directory && existsSync(legacy_drafts)) draft_bases.push(legacy_drafts);
675
+ for (const draft_base of draft_bases) {
676
+ const own_drafts = join(draft_base, hash);
677
+ push_real_dir(read_roots, own_drafts);
678
+ push_real_dir(write_roots, own_drafts);
679
+ }
680
+ const own_runtime = join(runtime_dir, 'members', hash);
681
+ if (existsSync(own_runtime)) push_real_dir(read_roots, own_runtime);
682
+ } else if (access.draft_directory) {
683
+ push_real_dir(read_roots, access.draft_directory);
684
+ push_real_dir(write_roots, access.draft_directory);
685
+ }
686
+
687
+ // Project directories obey effective `project_access` (read | write | auto | full | own | none) and adapter capability.
688
+ const project_access = profile?.project_access || config.project_access || 'read';
689
+ const adapter_allows_project = !profile?.adapter || adapter_capabilities(profile.adapter).project !== false;
690
+ if (project_access !== 'none' && adapter_allows_project) {
691
+ const room_cwd = config.cwd || config.workdir || '';
692
+ const member_cwd = profile?.cwd ?? room_cwd;
693
+ const can_write_main = ['write', 'auto', 'full', 'own'].includes(project_access);
694
+ if (member_cwd && existsSync(member_cwd)) {
695
+ push_real_dir(read_roots, member_cwd);
696
+ if (can_write_main) push_real_dir(write_roots, member_cwd);
697
+ }
698
+ const outside_room = Boolean(room_cwd && member_cwd && !overlapping_dirs(room_cwd, member_cwd));
699
+ const can_write_extra = !outside_room && can_write_main;
700
+ const all_room_dirs = [room_cwd, ...(config.extra_directories || [])].filter(Boolean);
701
+ for (const dir of all_room_dirs) {
702
+ if ((member_cwd && overlapping_dirs(dir, member_cwd)) || !existsSync(dir)) continue;
703
+ push_real_dir(read_roots, dir);
704
+ if (can_write_extra) push_real_dir(write_roots, dir);
705
+ }
706
+ }
707
+
708
+ if (!read_roots.length || !write_roots.length) {
709
+ throw new ShareCardError(t('无法确认成员的文件权限,已拒绝渲染'), { code: 'auth' });
710
+ }
711
+ return { read_roots, write_roots };
712
+ }
713
+
714
+ function assert_path_within(roots, target_path, message) {
715
+ if (!roots) return;
716
+ if (!roots.some((root) => is_same_or_inside(root, target_path))) {
717
+ throw new ShareCardError(message, { code: 'auth' });
718
+ }
719
+ }
720
+
721
+ // ---- Trusted local Chromium-family browser discovery ----
722
+
723
+ /**
724
+ * Locate an installed Chromium-family browser (Edge / Chrome / Chromium / Brave) strictly from trusted OS installation
725
+ * locations — never from user-supplied CLI flags, `PATH`, or user-writable AppData folders.
726
+ *
727
+ * @param {object} [options] Optional platform/env/fs overrides for unit tests.
728
+ * @returns {string} Absolute path to a trusted installed browser, or '' when none is found.
729
+ */
730
+ export function find_browser({
731
+ platform = process.platform,
732
+ env = process.env,
733
+ exists = existsSync,
734
+ is_file = (path) => { try { return statSync(path).isFile(); } catch { return false; } },
735
+ } = {}) {
736
+ const candidates = platform === 'win32' ? [
737
+ join(env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)', 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
738
+ join(env.ProgramFiles || 'C:\\Program Files', 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
739
+ join(env.ProgramFiles || 'C:\\Program Files', 'Google', 'Chrome', 'Application', 'chrome.exe'),
740
+ join(env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)', 'Google', 'Chrome', 'Application', 'chrome.exe'),
741
+ join(env.ProgramFiles || 'C:\\Program Files', 'BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe'),
742
+ ] : platform === 'darwin' ? [
743
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
744
+ '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
745
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
746
+ '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
747
+ ] : [
748
+ '/usr/bin/google-chrome',
749
+ '/usr/bin/google-chrome-stable',
750
+ '/usr/bin/chromium',
751
+ '/usr/bin/chromium-browser',
752
+ '/usr/bin/microsoft-edge',
753
+ '/usr/bin/microsoft-edge-stable',
754
+ '/usr/bin/brave-browser',
755
+ '/snap/bin/chromium',
756
+ '/usr/lib/chromium/chromium',
757
+ '/usr/lib/chromium-browser/chromium-browser',
758
+ ];
759
+ for (const path of candidates) {
760
+ if (path && exists(path) && is_file(path)) return path;
761
+ }
762
+ return '';
763
+ }
764
+
765
+ /** Build Chromium launch arguments: private `--remote-debugging-pipe` (zero TCP port), OS sandbox kept, profile isolated. */
766
+ export function browser_render_args(profile_dir, { scale = 2 } = {}) {
767
+ return [
768
+ '--headless=new',
769
+ '--disable-gpu',
770
+ '--hide-scrollbars',
771
+ '--no-first-run',
772
+ '--no-default-browser-check',
773
+ '--disable-extensions',
774
+ '--disable-sync',
775
+ '--disable-background-networking',
776
+ '--disable-component-update',
777
+ '--disable-default-apps',
778
+ '--mute-audio',
779
+ `--user-data-dir=${profile_dir}`,
780
+ `--force-device-scale-factor=${scale}`,
781
+ '--remote-debugging-pipe',
782
+ 'about:blank',
783
+ ];
784
+ }
785
+
786
+ function parse_hex_color(value) {
787
+ const match = HEX_COLOR.exec(String(value || '').trim());
788
+ if (!match) {
789
+ throw new ShareCardError(t('背景色必须是 6 位十六进制颜色,例如 #12141c'), { code: 'invalid_option', option: 'background' });
790
+ }
791
+ const hex = match[1];
792
+ return { r: parseInt(hex.slice(0, 2), 16), g: parseInt(hex.slice(2, 4), 16), b: parseInt(hex.slice(4, 6), 16), a: 1 };
793
+ }
794
+
795
+ function parse_png_dimensions(buffer) {
796
+ if (!Buffer.isBuffer(buffer) || buffer.length < 24 || !buffer.subarray(0, 8).equals(PNG_SIGNATURE)) {
797
+ throw new ShareCardError(t('浏览器未输出有效的 PNG 图片'), { code: 'render_failed' });
798
+ }
799
+ return { width_px: buffer.readUInt32BE(16), height_px: buffer.readUInt32BE(20) };
800
+ }
801
+
802
+ function is_inside_dir(base_dir, target_path) {
803
+ const rel = relative(base_dir, target_path);
804
+ return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
805
+ }
806
+
807
+ /**
808
+ * Serve one local static HTML file and allowlisted static assets inside its own directory over loopback with strict CSP.
809
+ */
810
+ async function start_static_render_server(html_file, read_roots = null) {
811
+ const html_real = realpathSync(html_file);
812
+ const base_dir = realpathSync(dirname(html_real));
813
+ const html_body = readFileSync(html_real);
814
+ const token = randomBytes(16).toString('hex');
815
+ const prefix = `/${token}/`;
816
+ const headers_base = {
817
+ 'X-Content-Type-Options': 'nosniff',
818
+ 'Referrer-Policy': 'no-referrer',
819
+ 'Cache-Control': 'no-store',
820
+ };
821
+ const server = createServer((req, res) => {
822
+ try {
823
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
824
+ res.writeHead(405, headers_base); res.end(); return;
825
+ }
826
+ let pathname;
827
+ try {
828
+ pathname = decodeURIComponent(new URL(req.url || '/', 'http://127.0.0.1').pathname);
829
+ } catch {
830
+ res.writeHead(400, headers_base); res.end(); return;
831
+ }
832
+ if (!pathname.startsWith(prefix)) {
833
+ res.writeHead(404, headers_base); res.end(); return;
834
+ }
835
+ const rel = pathname.slice(prefix.length);
836
+ if (!rel || rel === 'index.html') {
837
+ res.writeHead(200, { ...headers_base, 'Content-Type': 'text/html; charset=utf-8', 'Content-Security-Policy': RENDER_CSP });
838
+ res.end(req.method === 'HEAD' ? undefined : html_body);
839
+ return;
840
+ }
841
+ if (rel.includes('\0') || rel.startsWith('/') || rel.split('/').includes('..')) {
842
+ res.writeHead(403, headers_base); res.end(); return;
843
+ }
844
+ const ext = extname(rel).toLowerCase();
845
+ const mime = STATIC_ASSET_TYPES[ext];
846
+ if (!mime) {
847
+ res.writeHead(403, headers_base); res.end(); return;
848
+ }
849
+ const candidate = resolve(base_dir, rel);
850
+ if (!existsSync(candidate)) {
851
+ res.writeHead(404, headers_base); res.end(); return;
852
+ }
853
+ let resolved_asset;
854
+ try { resolved_asset = realpathSync(candidate); } catch { res.writeHead(404, headers_base); res.end(); return; }
855
+ if (!is_inside_dir(base_dir, resolved_asset) || !statSync(resolved_asset).isFile()) {
856
+ res.writeHead(403, headers_base); res.end(); return;
857
+ }
858
+ if (read_roots && !read_roots.some((root) => is_same_or_inside(root, resolved_asset))) {
859
+ res.writeHead(403, headers_base); res.end(); return;
860
+ }
861
+ res.writeHead(200, { ...headers_base, 'Content-Type': mime });
862
+ res.end(req.method === 'HEAD' ? undefined : readFileSync(resolved_asset));
863
+ } catch {
864
+ if (!res.headersSent) res.writeHead(500, headers_base);
865
+ res.end();
866
+ }
867
+ });
868
+ await new Promise((resolve_ready, reject_ready) => {
869
+ server.once('error', reject_ready);
870
+ server.listen(0, '127.0.0.1', resolve_ready);
871
+ });
872
+ const { port } = server.address();
873
+ const prefix_url = `http://127.0.0.1:${port}${prefix}`;
874
+ return {
875
+ prefix_url,
876
+ url: `${prefix_url}index.html`,
877
+ close: () => new Promise((done) => server.close(() => done())),
878
+ };
879
+ }
880
+
881
+ /** Check whether a request URL inside the headless render page stays within the ephemeral static server or inline data. */
882
+ export function is_allowed_render_url(url, prefix_url) {
883
+ const value = String(url || '');
884
+ return value === 'about:blank' || value.startsWith(prefix_url) || value.startsWith('data:');
885
+ }
886
+
887
+ /** Translate Chromium startup/exit diagnostics into a clear error, explicitly surfacing OS sandbox unavailability. */
888
+ export function classify_browser_exit_error(code, stderr_text = '') {
889
+ if (SANDBOX_ERROR_PATTERN.test(stderr_text)) {
890
+ return new ShareCardError(
891
+ t('本机浏览器的操作系统沙箱不可用(例如 Linux 以 root 运行或禁用了 user namespace),出于安全要求不会关闭沙箱;请改用启用沙箱的普通用户重试,或直接提供 PNG/JPG/WebP 图片。'),
892
+ { code: 'browser_sandbox_unavailable', stderr: stderr_text.slice(-400) },
893
+ );
894
+ }
895
+ return new ShareCardError(t('本地浏览器提前退出(退出码 {code})', { code: code ?? t('未知') }), {
896
+ code: 'browser_launch_failed',
897
+ stderr: stderr_text.slice(-400),
898
+ });
899
+ }
900
+
901
+ /** Process-private CDP JSON-RPC transport over Chromium's `--remote-debugging-pipe` (fd 3 write, fd 4 read, NUL-delimited). */
902
+ class CdpPipeSession {
903
+ constructor(writer, reader, timeout_ms) {
904
+ this.writer = writer;
905
+ this.reader = reader;
906
+ this.timeout_ms = timeout_ms;
907
+ this.next_id = 1;
908
+ this.pending = new Map();
909
+ this.waiters = new Set();
910
+ this.listeners = new Map();
911
+ this.buffer = Buffer.alloc(0);
912
+ this.closed = false;
913
+
914
+ this.reader.on('data', (chunk) => {
915
+ this.buffer = Buffer.concat([this.buffer, chunk]);
916
+ for (;;) {
917
+ const zero = this.buffer.indexOf(0);
918
+ if (zero < 0) break;
919
+ const raw = this.buffer.subarray(0, zero).toString('utf8');
920
+ this.buffer = this.buffer.subarray(zero + 1);
921
+ this.handle_message(raw);
922
+ }
923
+ });
924
+ this.writer.on('error', () => {});
925
+ this.reader.on('error', () => {});
926
+ }
927
+
928
+ handle_message(raw) {
929
+ let msg;
930
+ try { msg = JSON.parse(raw); } catch { return; }
931
+ if (msg.id && this.pending.has(msg.id)) {
932
+ const entry = this.pending.get(msg.id);
933
+ this.pending.delete(msg.id);
934
+ clearTimeout(entry.timer);
935
+ if (msg.error) entry.reject(new ShareCardError(msg.error.message || t('浏览器渲染命令失败'), { code: 'render_failed' }));
936
+ else entry.resolve(msg.result || {});
937
+ } else if (msg.method && this.listeners.has(msg.method)) {
938
+ for (const handler of [...this.listeners.get(msg.method)]) handler(msg.params || {}, msg.sessionId || '');
939
+ }
940
+ }
941
+
942
+ send(method, params = {}, session_id = '') {
943
+ if (this.closed) return Promise.reject(new ShareCardError(t('浏览器连接已关闭'), { code: 'render_failed' }));
944
+ const id = this.next_id++;
945
+ return new Promise((resolve_cmd, reject_cmd) => {
946
+ const timer = setTimeout(() => {
947
+ this.pending.delete(id);
948
+ reject_cmd(new ShareCardError(t('浏览器渲染步骤超时:{method}', { method }), { code: 'render_timeout' }));
949
+ }, this.timeout_ms);
950
+ timer.unref();
951
+ this.pending.set(id, { resolve: resolve_cmd, reject: reject_cmd, timer });
952
+ const payload = session_id ? { id, method, params, sessionId: session_id } : { id, method, params };
953
+ try {
954
+ this.writer.write(`${JSON.stringify(payload)}\0`);
955
+ } catch (error) {
956
+ this.pending.delete(id);
957
+ clearTimeout(timer);
958
+ reject_cmd(new ShareCardError(t('向本地浏览器发送渲染指令失败:{reason}', { reason: error.message }), { code: 'render_failed' }));
959
+ }
960
+ });
961
+ }
962
+
963
+ on(method, handler) {
964
+ if (!this.listeners.has(method)) this.listeners.set(method, new Set());
965
+ this.listeners.get(method).add(handler);
966
+ return () => this.listeners.get(method)?.delete(handler);
967
+ }
968
+
969
+ wait_for(method, expected_session = '') {
970
+ if (this.closed) return Promise.reject(new ShareCardError(t('浏览器连接已关闭'), { code: 'render_failed' }));
971
+ return new Promise((resolve_evt, reject_evt) => {
972
+ const cleanup = () => {
973
+ clearTimeout(timer);
974
+ off();
975
+ this.waiters.delete(waiter);
976
+ };
977
+ const timer = setTimeout(() => {
978
+ cleanup();
979
+ reject_evt(new ShareCardError(t('等待页面加载完成超时'), { code: 'render_timeout' }));
980
+ }, this.timeout_ms);
981
+ timer.unref();
982
+ const off = this.on(method, (params, session_id) => {
983
+ if (expected_session && session_id !== expected_session) return;
984
+ cleanup();
985
+ resolve_evt(params);
986
+ });
987
+ const waiter = { reject: (error) => { cleanup(); reject_evt(error); } };
988
+ this.waiters.add(waiter);
989
+ });
990
+ }
991
+
992
+ fail_all(error) {
993
+ this.closed = true;
994
+ for (const entry of this.pending.values()) {
995
+ clearTimeout(entry.timer);
996
+ entry.reject(error);
997
+ }
998
+ this.pending.clear();
999
+ for (const waiter of [...this.waiters]) waiter.reject(error);
1000
+ this.waiters.clear();
1001
+ }
1002
+
1003
+ close() {
1004
+ this.fail_all(new ShareCardError(t('浏览器连接已关闭'), { code: 'render_failed' }));
1005
+ try { this.writer.end(); } catch { /* Already closed. */ }
1006
+ try { this.reader.destroy(); } catch { /* Already closed. */ }
1007
+ }
1008
+ }
1009
+
1010
+ async function wait_child_exit(child, timeout_ms = 2000) {
1011
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
1012
+ await new Promise((done) => {
1013
+ const timer = setTimeout(done, timeout_ms);
1014
+ timer.unref();
1015
+ child.once('close', () => { clearTimeout(timer); done(); });
1016
+ });
1017
+ }
1018
+
1019
+ async function remove_dir_quiet(path) {
1020
+ for (let attempt = 0; attempt < 5; attempt += 1) {
1021
+ try { rmSync(path, { recursive: true, force: true }); return; }
1022
+ catch { await delay(80 * (attempt + 1)); }
1023
+ }
1024
+ }
1025
+
1026
+ /**
1027
+ * Render a local static HTML file into a PNG cover image via a sandboxed, profile-isolated trusted local browser
1028
+ * controlled over process-private `--remote-debugging-pipe` (zero TCP listening port).
1029
+ *
1030
+ * @param {object} options Rendering parameters.
1031
+ * @returns {Promise<object>} Export receipt with output path, CSS/pixel dimensions, byte size, and browser path.
1032
+ */
1033
+ export async function render_share_card_html({
1034
+ html_path,
1035
+ out_path,
1036
+ width = SHARE_CARD_COVER_SPEC.width_css_px,
1037
+ height = null,
1038
+ max_height = SHARE_CARD_COVER_SPEC.max_height_css_px,
1039
+ scale = SHARE_CARD_COVER_SPEC.scale,
1040
+ background = SHARE_CARD_COVER_SPEC.default_background,
1041
+ access = {},
1042
+ home = service_home(),
1043
+ timeout_ms = DEFAULT_RENDER_TIMEOUT_MS,
1044
+ env = process.env,
1045
+ spawner = spawn,
1046
+ browser_resolver = () => find_browser({ env }),
1047
+ capture_override = null,
1048
+ } = {}) {
1049
+ assert_share_card_allowed(access, env);
1050
+ if (!html_path) throw new ShareCardError(t('请指定要导出的本地 HTML 文件路径'), { code: 'invalid_option' });
1051
+ if (!out_path) throw new ShareCardError(t('请通过 --out 指定输出 PNG 文件路径'), { code: 'invalid_option' });
1052
+
1053
+ const member_roots = resolve_member_render_roots(access, home);
1054
+ const resolved_html = resolve(html_path);
1055
+ if (!existsSync(resolved_html) || !statSync(resolved_html).isFile()) {
1056
+ throw new ShareCardError(t('HTML 文件不存在:{path}', { path: html_path }), { code: 'file_not_found' });
1057
+ }
1058
+ const real_html = realpathSync(resolved_html);
1059
+ assert_path_within(member_roots?.read_roots, real_html, t('无权读取该 HTML 文件:路径超出成员允许的目录范围'));
1060
+
1061
+ const resolved_out = resolve_future_real_path(out_path);
1062
+ assert_path_within(member_roots?.write_roots, resolved_out, t('无权写入该输出路径:请输出到成员有写权限的目录或自己的草稿目录'));
1063
+
1064
+ const file_size = statSync(real_html).size;
1065
+ if (file_size > MAX_HTML_BYTES) {
1066
+ throw new ShareCardError(t('HTML 文件超过 10 MiB 上限,无法导出'), { code: 'file_too_large' });
1067
+ }
1068
+
1069
+ const parsed_width = Number(width);
1070
+ const parsed_max_height = Number(max_height);
1071
+ const parsed_scale = Number(scale);
1072
+ const parsed_height = height === null || height === undefined || height === '' ? null : Number(height);
1073
+ if (!Number.isInteger(parsed_width) || parsed_width < MIN_WIDTH_PX || parsed_width > MAX_WIDTH_PX) {
1074
+ throw new ShareCardError(t('宽度须为 {min}–{max} 之间的整数像素', { min: MIN_WIDTH_PX, max: MAX_WIDTH_PX }), { code: 'invalid_option' });
1075
+ }
1076
+ if (!Number.isInteger(parsed_max_height) || parsed_max_height < SHARE_CARD_COVER_SPEC.min_height_css_px || parsed_max_height > HARD_MAX_HEIGHT_PX) {
1077
+ throw new ShareCardError(t('最大高度须为 {min}–{max} 之间的整数像素', { min: SHARE_CARD_COVER_SPEC.min_height_css_px, max: HARD_MAX_HEIGHT_PX }), { code: 'invalid_option' });
1078
+ }
1079
+ if (parsed_height !== null && (!Number.isInteger(parsed_height) || parsed_height < SHARE_CARD_COVER_SPEC.min_height_css_px || parsed_height > parsed_max_height)) {
1080
+ throw new ShareCardError(t('高度须为 {min}–{max} 之间的整数像素', { min: SHARE_CARD_COVER_SPEC.min_height_css_px, max: parsed_max_height }), { code: 'invalid_option' });
1081
+ }
1082
+ if (!Number.isFinite(parsed_scale) || parsed_scale < 1 || parsed_scale > 3) {
1083
+ throw new ShareCardError(t('缩放倍率(--scale)须在 1 到 3 之间'), { code: 'invalid_option' });
1084
+ }
1085
+ const bg_color = parse_hex_color(background);
1086
+
1087
+ const browser_path = browser_resolver();
1088
+ if (!browser_path) {
1089
+ throw new ShareCardError(t('未在系统可信安装位置找到可用的本地浏览器(Edge / Chrome / Chromium),无法将 HTML 导出为 PNG。请安装 Edge、Chrome 或 Chromium;也可以直接提供 PNG/JPG/WebP 图片。'), {
1090
+ code: 'browser_missing',
1091
+ });
1092
+ }
1093
+
1094
+ const work_dir = mkdtempSync(join(tmpdir(), 'codiscuss-share-card-'));
1095
+ const profile_dir = join(work_dir, 'profile');
1096
+ let server = null;
1097
+ let child = null;
1098
+ let pipe = null;
1099
+ try {
1100
+ mkdirSync(profile_dir, { recursive: true, mode: 0o700 });
1101
+ server = await start_static_render_server(real_html, member_roots?.read_roots || null);
1102
+ const args = browser_render_args(profile_dir, { scale: parsed_scale });
1103
+ let png_buffer;
1104
+ let final_height;
1105
+ let measured_height;
1106
+ if (capture_override) {
1107
+ const captured = await capture_override({
1108
+ browser_path, args, profile_dir, url: server.url, prefix_url: server.prefix_url,
1109
+ width: parsed_width, height: parsed_height, max_height: parsed_max_height, scale: parsed_scale, bg_color,
1110
+ });
1111
+ png_buffer = captured.png;
1112
+ measured_height = captured.measured_height;
1113
+ final_height = captured.final_height;
1114
+ } else {
1115
+ let stderr_buf = '';
1116
+ child = spawner(browser_path, args, {
1117
+ windowsHide: true,
1118
+ shell: false,
1119
+ stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'],
1120
+ });
1121
+ child.stderr?.on('data', (chunk) => {
1122
+ stderr_buf = (stderr_buf + chunk.toString('utf8')).slice(-4096);
1123
+ });
1124
+ pipe = new CdpPipeSession(child.stdio[3], child.stdio[4], timeout_ms);
1125
+ child.once('error', (error) => {
1126
+ pipe.fail_all(new ShareCardError(t('无法启动本地浏览器:{reason}', { reason: error.message }), { code: 'browser_launch_failed' }));
1127
+ });
1128
+ child.once('close', (code) => {
1129
+ if (!pipe.closed) pipe.fail_all(classify_browser_exit_error(code, stderr_buf));
1130
+ });
1131
+
1132
+ const { targetId } = await pipe.send('Target.createTarget', { url: 'about:blank' });
1133
+ const { sessionId } = await pipe.send('Target.attachToTarget', { targetId, flatten: true });
1134
+ await pipe.send('Page.enable', {}, sessionId);
1135
+ // Intercept every request (including top-level navigations such as meta refresh) and allow only our static token URL or data:.
1136
+ await pipe.send('Fetch.enable', { patterns: [{ urlPattern: '*' }] }, sessionId);
1137
+ pipe.on('Fetch.requestPaused', (params, event_session) => {
1138
+ if (event_session !== sessionId) return;
1139
+ const req_url = params.request?.url || '';
1140
+ if (is_allowed_render_url(req_url, server.prefix_url)) {
1141
+ pipe.send('Fetch.continueRequest', { requestId: params.requestId }, sessionId).catch(() => {});
1142
+ } else {
1143
+ pipe.send('Fetch.failRequest', { requestId: params.requestId, errorReason: 'BlockedByClient' }, sessionId).catch(() => {});
1144
+ }
1145
+ });
1146
+
1147
+ const initial_height = parsed_height || Math.min(900, parsed_max_height);
1148
+ await pipe.send('Emulation.setDeviceMetricsOverride', {
1149
+ width: parsed_width, height: initial_height, deviceScaleFactor: parsed_scale, mobile: false,
1150
+ }, sessionId);
1151
+ await pipe.send('Emulation.setDefaultBackgroundColorOverride', { color: bg_color }, sessionId);
1152
+
1153
+ const loaded = pipe.wait_for('Page.loadEventFired', sessionId);
1154
+ loaded.catch(() => {});
1155
+ await pipe.send('Page.navigate', { url: server.url }, sessionId);
1156
+ await loaded;
1157
+
1158
+ const metrics = await pipe.send('Page.getLayoutMetrics', {}, sessionId);
1159
+ measured_height = Math.ceil(metrics.cssContentSize?.height || metrics.contentSize?.height || initial_height);
1160
+ final_height = parsed_height ?? Math.min(parsed_max_height, Math.max(SHARE_CARD_COVER_SPEC.min_height_css_px, measured_height));
1161
+ if (final_height !== initial_height) {
1162
+ await pipe.send('Emulation.setDeviceMetricsOverride', {
1163
+ width: parsed_width, height: final_height, deviceScaleFactor: parsed_scale, mobile: false,
1164
+ }, sessionId);
1165
+ }
1166
+ const shot = await pipe.send('Page.captureScreenshot', {
1167
+ format: 'png',
1168
+ fromSurface: true,
1169
+ clip: { x: 0, y: 0, width: parsed_width, height: final_height, scale: 1 },
1170
+ }, sessionId);
1171
+ png_buffer = Buffer.from(shot.data || '', 'base64');
1172
+
1173
+ await pipe.send('Browser.close').catch(() => {});
1174
+ await wait_child_exit(child, 2000);
1175
+ }
1176
+
1177
+ const { width_px, height_px } = parse_png_dimensions(png_buffer);
1178
+ mkdirSync(dirname(resolved_out), { recursive: true });
1179
+ writeFileSync(resolved_out, png_buffer);
1180
+
1181
+ return {
1182
+ output: resolved_out,
1183
+ width_css_px: parsed_width,
1184
+ height_css_px: final_height,
1185
+ measured_height_css_px: measured_height,
1186
+ width_px,
1187
+ height_px,
1188
+ scale: parsed_scale,
1189
+ bytes: png_buffer.length,
1190
+ clipped: parsed_height === null && measured_height > parsed_max_height,
1191
+ browser: browser_path,
1192
+ };
1193
+ } finally {
1194
+ pipe?.close();
1195
+ if (child && child.exitCode === null && child.signalCode === null) {
1196
+ kill_process_tree(child, () => { try { child.kill(); } catch { /* Already exited. */ } });
1197
+ await wait_child_exit(child, 1500);
1198
+ }
1199
+ await server?.close().catch(() => {});
1200
+ await remove_dir_quiet(work_dir);
1201
+ }
1202
+ }
1203
+
1204
+ export const SHARE_CARD_CLI_HELP = () => t(`AI CoDiscuss 分享卡封面工具
1205
+
1206
+ 用法:
1207
+ codiscuss share-card materials [房间ID] [--site URL] [--access-file FILE] [--max-highlights N] [--max-steps N]
1208
+ codiscuss share-card render <HTML文件> --out <PNG文件> [--width 750] [--height N] [--max-height 1500] [--scale 2] [--background #12141c]
1209
+
1210
+ 子命令:
1211
+ materials 按可分享范围读取房间的协作指标、并发曲线与必要素材索引(排除已撤回消息、私聊与敏感片段,输出截断标记)
1212
+ render 使用系统可信安装位置的隔离沙箱浏览器(进程私有控制通道、无 TCP 调试端口)将本地静态 HTML 导出为高清 PNG 封面图
1213
+
1214
+ 选项:
1215
+ --room ROOM 目标房间编号(省略时取凭据绑定的房间;传其他房间编号可跨房间只读取材)
1216
+ --site, --url SITE 站点地址(带任务凭据时须与凭据绑定站点一致)
1217
+ --access-file FILE 任务凭据文件(默认读取 DISCUSS_ACCESS_FILE)
1218
+ --max-highlights N 返回的代表发言索引上限(默认 12)
1219
+ --max-steps N 并发曲线最大时间步数(默认 240,超出时按峰值采样)
1220
+ --out, -o FILE render 输出的 PNG 路径(持任务凭据时须在允许写入的目录或自己的草稿目录内;本机房主手动运行时沿用当前账号文件权限)
1221
+ --width N render CSS 宽度(像素,默认 750,范围 320–1500)
1222
+ --height N render 固定 CSS 高度(省略时按内容自适应)
1223
+ --max-height N render 最大 CSS 高度(默认 1500,范围 200–2400)
1224
+ --scale N render 像素倍率(默认 2,750×2 = 1500px 宽)
1225
+ --background HEX render 默认底色(默认 #12141c)
1226
+ --json 以 JSON 输出(默认)
1227
+ -h, --help 显示帮助
1228
+ `);
1229
+
1230
+ /** CLI entrypoint for `codiscuss share-card <subcommand>`. */
1231
+ export async function share_card_cli(args, { home = service_home(), fetcher = site_fetch, env = process.env, stdout = process.stdout, stderr = process.stderr } = {}) {
1232
+ let values;
1233
+ let positionals;
1234
+ try {
1235
+ ({ values, positionals } = parseArgs({
1236
+ args,
1237
+ allowPositionals: true,
1238
+ options: {
1239
+ room: { type: 'string' },
1240
+ site: { type: 'string' },
1241
+ url: { type: 'string' },
1242
+ 'access-file': { type: 'string' },
1243
+ 'max-highlights': { type: 'string' },
1244
+ 'max-steps': { type: 'string' },
1245
+ file: { type: 'string' },
1246
+ out: { type: 'string', short: 'o' },
1247
+ width: { type: 'string' },
1248
+ height: { type: 'string' },
1249
+ 'max-height': { type: 'string' },
1250
+ scale: { type: 'string' },
1251
+ background: { type: 'string' },
1252
+ json: { type: 'boolean' },
1253
+ help: { type: 'boolean', short: 'h' },
1254
+ },
1255
+ }));
1256
+ } catch (error) {
1257
+ stderr.write(`${JSON.stringify({ ok: false, error: { message: error.message, code: 'invalid_option' } }, null, 2)}\n`);
1258
+ process.exitCode = 1;
1259
+ return;
1260
+ }
1261
+ const sub = positionals[0] || '';
1262
+ if (values.help || !sub || sub === 'help') {
1263
+ stdout.write(SHARE_CARD_CLI_HELP());
1264
+ return;
1265
+ }
1266
+ try {
1267
+ const access = read_access_file(values['access-file'], env);
1268
+ assert_share_card_allowed(access, env);
1269
+ let data;
1270
+ if (sub === 'materials') {
1271
+ const room_id = values.room || positionals[1] || access.room || '';
1272
+ const max_highlights = values['max-highlights'] ? Math.max(1, Math.min(100, Number(values['max-highlights']) || DEFAULT_HIGHLIGHTS)) : DEFAULT_HIGHLIGHTS;
1273
+ const max_steps = values['max-steps'] ? Math.max(10, Math.min(1000, Number(values['max-steps']) || DEFAULT_CURVE_STEPS)) : DEFAULT_CURVE_STEPS;
1274
+ data = await share_card_materials({
1275
+ site: values.site || values.url || '',
1276
+ room_id,
1277
+ access,
1278
+ home,
1279
+ max_highlights,
1280
+ max_steps,
1281
+ fetcher,
1282
+ env,
1283
+ });
1284
+ } else if (sub === 'render') {
1285
+ const html_path = values.file || positionals[1] || '';
1286
+ data = await render_share_card_html({
1287
+ html_path,
1288
+ out_path: values.out || '',
1289
+ width: values.width ?? SHARE_CARD_COVER_SPEC.width_css_px,
1290
+ height: values.height ?? null,
1291
+ max_height: values['max-height'] ?? SHARE_CARD_COVER_SPEC.max_height_css_px,
1292
+ scale: values.scale ?? SHARE_CARD_COVER_SPEC.scale,
1293
+ background: values.background ?? SHARE_CARD_COVER_SPEC.default_background,
1294
+ access,
1295
+ home,
1296
+ env,
1297
+ });
1298
+ } else {
1299
+ throw new ShareCardError(t('未知子命令:{sub};运行 codiscuss share-card --help 查看用法', { sub }), { code: 'unknown_subcommand' });
1300
+ }
1301
+ stdout.write(`${JSON.stringify({ ok: true, data }, null, 2)}\n`);
1302
+ } catch (error) {
1303
+ const payload = {
1304
+ ok: false,
1305
+ error: {
1306
+ message: error.message,
1307
+ code: error.code || 'error',
1308
+ ...(error.details || {}),
1309
+ },
1310
+ };
1311
+ stderr.write(`${JSON.stringify(payload, null, 2)}\n`);
1312
+ process.exitCode = 1;
1313
+ }
1314
+ }