@lumesync/studio 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,669 @@
1
+ // CLI:doctor / skill-path / init / start / call / lint / export / package / import
2
+ // start 会以 JSON 输出就绪结果;call 只连接运行中的服务,不另起文档实例。
3
+
4
+ import fs from 'node:fs';
5
+ import fsp from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import process from 'node:process';
8
+ import { spawn } from 'node:child_process';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { ERROR_CODES, StudioError } from '../core/errors.js';
11
+ import { ChatMailbox } from '../chat/mailbox.js';
12
+ import { CoursewareDocument } from '../core/document.js';
13
+ import { EditSession } from '../editing/session.js';
14
+ import { createTools } from '../tools/registry.js';
15
+ import { startServer, packageVersion, skillVersion } from '../server/http.js';
16
+ import { initializeCourseware, ensureEmptyOrCourseware } from '../templates/init.js';
17
+ import { recoverWorkspace } from '../core/transaction.js';
18
+ import { exportCourseware, importCourseware, packageCourseware } from '../core/exporter.js';
19
+ import { readSessionFile, removeSessionFile, writeSessionFile } from '../core/storage.js';
20
+
21
+ const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
22
+
23
+ export const USER_PROMPT = `请使用 LumeSync Studio 创建并持续编辑互动课件。
24
+
25
+ 1. 使用 Node.js 20 或更高版本,通过 npx 运行 @lumesync/studio@1;
26
+ 不要全局安装,不要修改系统全局 MCP 配置。
27
+ 2. 先执行 \`npx --yes @lumesync/studio@1 skill-path --name courseware-authoring\`,
28
+ 读取输出目录中的 SKILL.md 及其要求的参考文件,并遵循其中的
29
+ 课件设计、工具调用、安全和验证规则。
30
+ 3. 在当前工作目录的 ./courseware 下初始化或打开课件,启动本地 Studio 服务;
31
+ host 使用 127.0.0.1,首选端口 4173,端口占用时使用服务选择的空闲端口。
32
+ 4. 等待健康检查成功,把服务实际返回的 previewUrl 发给我;
33
+ 不要只给我启动命令,也不要在服务未就绪时声称预览可用。
34
+ 5. 正式生成课件前先给我课程大纲:学习目标、场景顺序与时长、每页核心内容与互动、
35
+ 练习与评价方式、视觉方向。等我明确确认后再开始制作;大纲阶段不要初始化课件、
36
+ 不要写文件。我提出修改时,只更新大纲并再次确认。
37
+ 6. 根据我确认的大纲与教学目标生成课件。通过 \`lumesync-studio call\` 或本地工具 API
38
+ 修改课件,不要直接覆盖整个课件目录,不要修改 courseware 根目录之外的文件。
39
+ 7. 每轮修改前读取当前文档与 revision,提交结构化 Patch;
40
+ 保留现有场景 ID、组件 ID 和互动题 ID,除非我明确要求重建。
41
+ 8. 普通文案、样式和局部参数调整可直接应用;场景删除、批量重写、
42
+ 正确答案或评分规则变化先展示 Diff 并等待我确认。
43
+ 9. 每轮提交后执行校验并确认浏览器已收到新 revision;
44
+ 最后简要说明修改内容、校验结果和当前预览状态。
45
+ 10. 若出现版本冲突,重新读取最新文档后再修改;若校验失败,
46
+ 修复并重新验证,不要把错误草稿描述为已完成。
47
+ 11. 后续对话中持续按以上规则调整课件,保留可撤销历史。
48
+ 12. 需要分享时使用 \`lumesync-studio package\` 生成单个 \`.lume\` 文件;
49
+ 接收方用 \`lumesync-studio import\` 解包后继续编辑,不要把 \`.studio\` 历史当作课件内容。
50
+ 13. 界面右侧的 AI 对话会写入 Agent 信箱。服务启动后在后台执行
51
+ \`lumesync-studio chat watch --root ./courseware\` 等待新消息;
52
+ 命令会认领并输出一条消息(含选中元素上下文)。修改后用
53
+ \`lumesync-studio chat reply --root ./courseware --text '...' --reply-to <id>\` 回复,
54
+ 然后再次挂起 \`chat watch\`,形成半自动闭环。未回复的认领会自动过期。`;
55
+
56
+ export function parseArgs(argv) {
57
+ const args = { _: [] };
58
+ for (let index = 0; index < argv.length; index += 1) {
59
+ const token = argv[index];
60
+ if (token.startsWith('--')) {
61
+ const key = token.slice(2);
62
+ const next = argv[index + 1];
63
+ if (next === undefined || (next.startsWith('--') && !/^--\d/.test(next))) {
64
+ args[key] = true;
65
+ } else {
66
+ args[key] = next;
67
+ index += 1;
68
+ }
69
+ } else {
70
+ args._.push(token);
71
+ }
72
+ }
73
+ return args;
74
+ }
75
+
76
+ function out(value) {
77
+ process.stdout.write(`${typeof value === 'string' ? value : JSON.stringify(value, null, 2)}\n`);
78
+ }
79
+
80
+ function requireRoot(args) {
81
+ const raw = typeof args.root === 'string' ? args.root : process.env.LUME_STUDIO_ROOT ?? './courseware';
82
+ return path.resolve(process.cwd(), raw);
83
+ }
84
+
85
+ export async function main(argv = process.argv.slice(2)) {
86
+ const args = parseArgs(argv);
87
+ const command = args._[0] ?? 'help';
88
+ try {
89
+ switch (command) {
90
+ case 'doctor':
91
+ return await doctor();
92
+ case 'skill-path':
93
+ return skillPath(args);
94
+ case 'init':
95
+ return await init(args);
96
+ case 'start':
97
+ return await start(args);
98
+ case 'call':
99
+ return await call(args);
100
+ case 'chat':
101
+ return await chat(args);
102
+ case 'lint':
103
+ return await lint(args);
104
+ case 'export':
105
+ return await doExport(args);
106
+ case 'package':
107
+ return await doPackage(args);
108
+ case 'import':
109
+ return await doImport(args);
110
+ case 'prompt':
111
+ return out(USER_PROMPT);
112
+ case 'help':
113
+ case '--help':
114
+ case '-h':
115
+ return help();
116
+ default:
117
+ throw new StudioError(ERROR_CODES.BAD_REQUEST, `未知命令:${command}`, { command }, 2);
118
+ }
119
+ } catch (error) {
120
+ const studio = error instanceof StudioError ? error : new StudioError(ERROR_CODES.INTERNAL, error.message, undefined, 1);
121
+ out(studio.toJSON());
122
+ process.exitCode = studio.status >= 400 ? (studio.status >= 500 ? 3 : 2) : 1;
123
+ return null;
124
+ }
125
+ }
126
+
127
+ function help() {
128
+ out(`LumeSync Studio ${packageVersion()}
129
+
130
+ 用法:
131
+ lumesync-studio doctor
132
+ lumesync-studio skill-path [--name courseware-authoring] [--json]
133
+ lumesync-studio init --root ./courseware [--title 课程名] [--aspect-ratio 16:9]
134
+ lumesync-studio start --root ./courseware [--host 127.0.0.1] [--port 4173]
135
+ [--init] [--template interactive-html] [--open]
136
+ [--log-level info] [--max-body 8388608] [--lan]
137
+ lumesync-studio call <tool> --root ./courseware [--json '<payload>' | --input payload.json]
138
+ lumesync-studio chat pull --root ./courseware [--limit 20] [--history 20]
139
+ lumesync-studio chat list --root ./courseware [--since 0] [--limit 100]
140
+ lumesync-studio chat reply --root ./courseware --text '已调整…' [--reply-to msg_x]
141
+ lumesync-studio chat watch --root ./courseware [--follow] [--timeout 0] [--by watcher-1]
142
+ lumesync-studio lint --root ./courseware [--json]
143
+ lumesync-studio export --root ./courseware --out ./dist/courseware [--force]
144
+ lumesync-studio package --root ./courseware --out ./dist/courseware.lume [--force]
145
+ lumesync-studio import --file ./dist/courseware.lume --out ./courseware [--force]
146
+ lumesync-studio prompt
147
+
148
+ 环境变量:
149
+ LUME_STUDIO_ROOT、LUME_STUDIO_HOST、LUME_STUDIO_PORT、LUME_STUDIO_TEMPLATE、
150
+ LUME_STUDIO_OPEN、LUME_STUDIO_LOG_LEVEL、LUME_STUDIO_MAX_BODY、LUME_STUDIO_LAN
151
+ `);
152
+ }
153
+
154
+ async function doctor() {
155
+ const checks = [];
156
+ checks.push({ name: 'node', ok: Number(process.versions.node.split('.')[0]) >= 20, value: process.versions.node });
157
+ checks.push({ name: 'package', ok: true, value: packageVersion() });
158
+ checks.push({ name: 'skillVersion', ok: true, value: skillVersion() });
159
+ const skills = findSkills();
160
+ checks.push({ name: 'skills', ok: skills.length > 0, value: skills.map((skill) => skill.name).join(', ') });
161
+ checks.push({ name: 'ui', ok: fs.existsSync(path.join(PACKAGE_ROOT, 'ui', 'index.html')), value: 'ui/index.html' });
162
+ checks.push({ name: 'home', ok: fs.existsSync(path.join(PACKAGE_ROOT, 'ui', 'home.html')), value: 'ui/home.html' });
163
+ checks.push({
164
+ name: 'sessionStore',
165
+ ok: fs.existsSync(path.join(PACKAGE_ROOT, 'src', 'core', 'transaction.js')),
166
+ value: 'src/core/transaction.js',
167
+ });
168
+ out({
169
+ ok: checks.every((check) => check.ok),
170
+ protocolVersion: 1,
171
+ packageVersion: packageVersion(),
172
+ skillVersion: skillVersion(),
173
+ checks,
174
+ });
175
+ }
176
+
177
+ function findSkills() {
178
+ const directory = path.join(PACKAGE_ROOT, 'skills');
179
+ if (!fs.existsSync(directory)) return [];
180
+ return fs.readdirSync(directory, { withFileTypes: true })
181
+ .filter((entry) => entry.isDirectory() && fs.existsSync(path.join(directory, entry.name, 'SKILL.md')))
182
+ .map((entry) => ({ name: entry.name, path: path.join(directory, entry.name, 'SKILL.md') }));
183
+ }
184
+
185
+ function skillPath(args) {
186
+ const skills = findSkills();
187
+ const name = typeof args.name === 'string' ? args.name : 'courseware-authoring';
188
+ const found = skills.find((skill) => skill.name === name);
189
+ if (!found) {
190
+ throw new StudioError(ERROR_CODES.ENV_INVALID, `找不到 Skill:${name}`, { name, available: skills.map((skill) => skill.name) }, 404);
191
+ }
192
+ if (args.json) {
193
+ out({ name: found.name, path: found.path, directory: path.dirname(found.path), packageVersion: packageVersion(), skillVersion: skillVersion() });
194
+ } else {
195
+ out(found.path);
196
+ }
197
+ }
198
+
199
+ function initOptions(args) {
200
+ return {
201
+ title: typeof args.title === 'string' ? args.title : undefined,
202
+ subject: typeof args.subject === 'string' ? args.subject : undefined,
203
+ grade: typeof args.grade === 'string' ? args.grade : undefined,
204
+ durationMin: args.duration === undefined ? undefined : Number(args.duration),
205
+ aspectRatio: typeof args['aspect-ratio'] === 'string' ? args['aspect-ratio'] : undefined,
206
+ template: typeof args.template === 'string' ? args.template : process.env.LUME_STUDIO_TEMPLATE ?? 'interactive-html',
207
+ };
208
+ }
209
+
210
+ function assertTemplate(template) {
211
+ if (template !== 'interactive-html') {
212
+ throw new StudioError(ERROR_CODES.ENV_INVALID, `不支持的模板:${template}`, { available: ['interactive-html'] }, 400);
213
+ }
214
+ }
215
+
216
+ async function init(args) {
217
+ const root = requireRoot(args);
218
+ const options = initOptions(args);
219
+ assertTemplate(options.template);
220
+ const state = await ensureEmptyOrCourseware(root);
221
+ if (!state.empty) {
222
+ throw new StudioError(ERROR_CODES.COURSEWARE_INVALID, `目录已包含课件,拒绝覆盖:${root}`, { root }, 409);
223
+ }
224
+ const result = await initializeCourseware(root, options);
225
+ out({ status: 'initialized', root, ...result });
226
+ }
227
+
228
+ async function start(args) {
229
+ const root = requireRoot(args);
230
+ const lan = args.lan === true || truthy(process.env.LUME_STUDIO_LAN);
231
+ const host = typeof args.host === 'string'
232
+ ? args.host
233
+ : process.env.LUME_STUDIO_HOST ?? (lan ? '0.0.0.0' : '127.0.0.1');
234
+ const port = Number(args.port ?? process.env.LUME_STUDIO_PORT ?? 4173);
235
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
236
+ throw new StudioError(ERROR_CODES.BAD_REQUEST, `端口不合法:${args.port}`, { port: args.port }, 400);
237
+ }
238
+ const maxBody = Number(args['max-body'] ?? process.env.LUME_STUDIO_MAX_BODY ?? 8 * 1024 * 1024);
239
+ if (!Number.isInteger(maxBody) || maxBody < 1024) {
240
+ throw new StudioError(ERROR_CODES.BAD_REQUEST, '--max-body 必须是至少 1024 的整数', { maxBody }, 400);
241
+ }
242
+ const logLevel = String(args['log-level'] ?? process.env.LUME_STUDIO_LOG_LEVEL ?? 'info');
243
+ if (!['debug', 'info', 'warn', 'error', 'silent'].includes(logLevel)) {
244
+ throw new StudioError(ERROR_CODES.BAD_REQUEST, '--log-level 必须是 debug/info/warn/error/silent', { logLevel }, 400);
245
+ }
246
+
247
+ // 同一 root 已有兼容健康实例时复用,绝不重复启动第二个服务。
248
+ const existing = await inspectSession(root);
249
+ if (existing.incompatible) {
250
+ throw new StudioError(
251
+ ERROR_CODES.SESSION_EXPIRED,
252
+ '检测到同目录下不兼容的 Studio 会话,请先停止旧进程再启动',
253
+ { session: existing.session },
254
+ 409,
255
+ );
256
+ }
257
+ if (existing.healthy) {
258
+ out({ ...existing.session, status: 'ready', reused: true });
259
+ return null;
260
+ }
261
+
262
+ await fsp.mkdir(root, { recursive: true });
263
+ const releaseLock = await acquireStartLock(root);
264
+ let activeServer = null;
265
+ try {
266
+ await recoverWorkspace(root);
267
+ const state = await ensureEmptyOrCourseware(root);
268
+ if (state.empty) {
269
+ if (args.init !== true) {
270
+ throw new StudioError(ERROR_CODES.COURSEWARE_INVALID, `目录为空,需要 --init 初始化:${root}`, { root }, 422);
271
+ }
272
+ const options = initOptions(args);
273
+ assertTemplate(options.template);
274
+ await initializeCourseware(root, options);
275
+ }
276
+
277
+ const document = await CoursewareDocument.load(root);
278
+ // server 引用需要延迟绑定:工具注册早于服务创建,但调用发生在服务就绪之后。
279
+ const serverRef = {
280
+ describe: () => {
281
+ throw new StudioError(ERROR_CODES.PREVIEW_UNAVAILABLE, '预览服务尚未就绪', undefined, 503);
282
+ },
283
+ broadcast: () => 0,
284
+ waitForAck: async () => ({ acknowledged: false, reason: 'PREVIEW_UNAVAILABLE' }),
285
+ exportCourseware: async () => {
286
+ throw new StudioError(ERROR_CODES.PREVIEW_UNAVAILABLE, '预览服务尚未就绪', undefined, 503);
287
+ },
288
+ packageCourseware: async () => {
289
+ throw new StudioError(ERROR_CODES.PREVIEW_UNAVAILABLE, '预览服务尚未就绪', undefined, 503);
290
+ },
291
+ previewClients: 0,
292
+ };
293
+ const session = new EditSession({ root, document, broadcast: (event) => serverRef.broadcast(event) });
294
+ const chatBox = new ChatMailbox({ root });
295
+ const tools = createTools({ document, session, root, server: serverRef, chat: chatBox });
296
+ // 主页切换课件时复用同一端口:按新 root 重建文档、编辑会话、工具与信箱。
297
+ const activateRoot = async (nextRoot) => {
298
+ await recoverWorkspace(nextRoot);
299
+ const nextDocument = await CoursewareDocument.load(nextRoot);
300
+ const nextSession = new EditSession({
301
+ root: nextRoot,
302
+ document: nextDocument,
303
+ broadcast: (event) => serverRef.broadcast(event),
304
+ });
305
+ const nextChat = new ChatMailbox({ root: nextRoot });
306
+ const nextTools = createTools({
307
+ document: nextDocument,
308
+ session: nextSession,
309
+ root: nextRoot,
310
+ server: serverRef,
311
+ chat: nextChat,
312
+ });
313
+ return { root: nextRoot, document: nextDocument, session: nextSession, tools: nextTools, chat: nextChat };
314
+ };
315
+ const server = await startServer({
316
+ root,
317
+ document,
318
+ session,
319
+ tools,
320
+ chat: chatBox,
321
+ options: {
322
+ host,
323
+ port,
324
+ token: typeof args.token === 'string' ? args.token : undefined,
325
+ strictPort: args['strict-port'] === true,
326
+ maxBody,
327
+ logLevel,
328
+ activateRoot,
329
+ },
330
+ });
331
+ activeServer = server;
332
+ serverRef.describe = server.describe;
333
+ serverRef.broadcast = server.broadcast;
334
+ serverRef.waitForAck = server.waitForAck;
335
+ serverRef.exportCourseware = server.exportCourseware;
336
+ serverRef.packageCourseware = server.packageCourseware;
337
+ serverRef.previewClients = server.previewClients;
338
+
339
+ const describe = {
340
+ ...server.describe(),
341
+ status: document.report.valid ? 'ready' : 'degraded',
342
+ reused: false,
343
+ };
344
+ await writeSessionFile(root, { ...describe, startedAt: describe.startedAt });
345
+ await releaseLock();
346
+ out(describe);
347
+ if (args.open === true || truthy(process.env.LUME_STUDIO_OPEN)) {
348
+ openBrowser(describe.previewUrl);
349
+ }
350
+
351
+ const shutdown = async () => {
352
+ await server.close();
353
+ await removeSessionFile(root, (value) => value?.pid === process.pid && value?.token === server.token);
354
+ process.exit(0);
355
+ };
356
+ process.on('SIGINT', shutdown);
357
+ process.on('SIGTERM', shutdown);
358
+ return null;
359
+ } catch (error) {
360
+ if (activeServer) await activeServer.close().catch(() => {});
361
+ await releaseLock();
362
+ throw error;
363
+ }
364
+ }
365
+
366
+ // 同一 root 的启动互斥,避免两个进程在 session.json 写入前同时启动。
367
+ async function acquireStartLock(root) {
368
+ const studio = path.join(root, '.studio');
369
+ await fsp.mkdir(studio, { recursive: true, mode: 0o700 });
370
+ const lockPath = path.join(studio, 'start.lock');
371
+ const release = async () => {
372
+ try {
373
+ const value = JSON.parse(await fsp.readFile(lockPath, 'utf8'));
374
+ if (value.pid === process.pid) await fsp.rm(lockPath, { force: true });
375
+ } catch {
376
+ // 锁已不存在或已由其他进程清理。
377
+ }
378
+ };
379
+ for (let attempt = 0; attempt < 2; attempt += 1) {
380
+ try {
381
+ const handle = await fsp.open(lockPath, 'wx', 0o600);
382
+ try {
383
+ await handle.writeFile(JSON.stringify({ pid: process.pid, at: new Date().toISOString() }));
384
+ } finally {
385
+ await handle.close();
386
+ }
387
+ return release;
388
+ } catch (error) {
389
+ if (error.code !== 'EEXIST') throw error;
390
+ let owner = null;
391
+ try {
392
+ owner = JSON.parse(await fsp.readFile(lockPath, 'utf8'));
393
+ } catch {
394
+ owner = null;
395
+ }
396
+ if (owner?.pid && pidAlive(owner.pid)) {
397
+ throw new StudioError(
398
+ ERROR_CODES.SESSION_EXPIRED,
399
+ '同一课件目录已有进程正在启动,请稍后重试或检查 session.json',
400
+ { pid: owner.pid, root },
401
+ 409,
402
+ );
403
+ }
404
+ await fsp.rm(lockPath, { force: true }).catch(() => {});
405
+ }
406
+ }
407
+ throw new StudioError(ERROR_CODES.PREVIEW_UNAVAILABLE, '无法获取 Studio 启动锁', { root }, 503);
408
+ }
409
+
410
+ async function call(args) {
411
+ const toolName = args._[1];
412
+ if (!toolName) throw new StudioError(ERROR_CODES.OPERATION_INVALID, '缺少工具名', undefined, 400);
413
+ const root = requireRoot(args);
414
+ const session = await resolveLiveSession(root);
415
+ let payload = {};
416
+ if (typeof args.json === 'string') {
417
+ try {
418
+ payload = JSON.parse(args.json);
419
+ } catch {
420
+ throw new StudioError(ERROR_CODES.BAD_REQUEST, '--json 不是合法 JSON', undefined, 400);
421
+ }
422
+ } else if (typeof args.input === 'string') {
423
+ payload = JSON.parse(await fsp.readFile(path.resolve(process.cwd(), args.input), 'utf8'));
424
+ }
425
+ const value = await invokeRemoteTool(session, toolName, payload);
426
+ if (value !== null) out(value);
427
+ }
428
+
429
+ // 界面对话信箱:pull 拉取待处理消息,list 查看历史,reply 回复。
430
+ async function chat(args) {
431
+ const action = args._[1] ?? 'pull';
432
+ const root = requireRoot(args);
433
+ if (action === 'watch') return await watchChat(root, args);
434
+ const session = await resolveLiveSession(root);
435
+ let tool;
436
+ let payload;
437
+ if (action === 'pull') {
438
+ tool = 'chat.pull';
439
+ payload = { limit: numberArg(args.limit, 20), historyLimit: numberArg(args.history, 20) };
440
+ } else if (action === 'list') {
441
+ tool = 'chat.list';
442
+ payload = { since: numberArg(args.since, 0), limit: numberArg(args.limit, 100) };
443
+ } else if (action === 'reply') {
444
+ if (typeof args.text !== 'string' || args.text.trim() === '') {
445
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, 'chat reply 需要 --text', undefined, 400);
446
+ }
447
+ tool = 'chat.reply';
448
+ payload = {
449
+ text: args.text,
450
+ ...(typeof args['reply-to'] === 'string' ? { inReplyTo: args['reply-to'] } : {}),
451
+ };
452
+ } else {
453
+ throw new StudioError(
454
+ ERROR_CODES.BAD_REQUEST,
455
+ `未知 chat 子命令:${action}`,
456
+ { action, available: ['pull', 'list', 'reply', 'watch'] },
457
+ 2,
458
+ );
459
+ }
460
+ const value = await invokeRemoteTool(session, tool, payload);
461
+ if (value !== null) out(value);
462
+ }
463
+
464
+ function numberArg(value, fallback) {
465
+ const number = Number(value);
466
+ return Number.isFinite(number) ? number : fallback;
467
+ }
468
+
469
+ // 半自动闭环:默认等待一条待处理消息,认领并输出后退出;
470
+ // Agent 处理完并回复后可再次挂起。--follow 则持续输出每条新消息。
471
+ async function watchChat(root, args) {
472
+ const session = await resolveLiveSession(root);
473
+ const follow = args.follow === true;
474
+ const timeoutSeconds = numberArg(args.timeout, 0);
475
+ const deadline = timeoutSeconds > 0 ? Date.now() + timeoutSeconds * 1000 : Infinity;
476
+ const by = typeof args.by === 'string' && args.by.trim() ? args.by.trim().slice(0, 80) : `watcher-${process.pid}`;
477
+ while (Date.now() < deadline) {
478
+ const pulled = await invokeRemoteTool(session, 'chat.pull', { limit: 1, historyLimit: 0 });
479
+ if (pulled === null) return;
480
+ const next = pulled?.result?.pending?.[0];
481
+ if (next) {
482
+ // 认领竞争失败(已被其他监听器拿走)是正常情况,静默跳过继续等待。
483
+ const claimed = await invokeRemoteTool(session, 'chat.claim', { id: next.id, by }, { quiet: true });
484
+ if (claimed?.result) {
485
+ // 使用 NDJSON,便于监听进程逐条输出而不破坏下游解析。
486
+ process.stdout.write(`${JSON.stringify({ status: 'message', ...claimed.result })}\n`);
487
+ if (!follow) return;
488
+ continue;
489
+ }
490
+ }
491
+ await sleep(1000);
492
+ }
493
+ out({ status: 'timeout', by, waitedSeconds: timeoutSeconds });
494
+ process.exitCode = 4;
495
+ }
496
+
497
+ function sleep(ms) {
498
+ return new Promise((resolve) => setTimeout(resolve, ms));
499
+ }
500
+
501
+ async function resolveLiveSession(root) {
502
+ const session = await readSessionFile(root);
503
+ if (!session) {
504
+ throw new StudioError(
505
+ ERROR_CODES.PREVIEW_UNAVAILABLE,
506
+ `未找到运行中的 Studio 服务。请先执行 lumesync-studio start --root ${root}`,
507
+ { root },
508
+ 503,
509
+ );
510
+ }
511
+ assertSessionCompatible(root, session);
512
+ if (!pidAlive(session.pid)) {
513
+ await removeSessionFile(root, (value) => value?.pid === session.pid);
514
+ throw new StudioError(ERROR_CODES.PREVIEW_UNAVAILABLE, 'Studio 进程已退出,请重新启动服务', { pid: session.pid }, 503);
515
+ }
516
+ const health = await fetchHealth(session.healthUrl);
517
+ if (!health) {
518
+ throw new StudioError(ERROR_CODES.PREVIEW_UNAVAILABLE, 'Studio 健康检查失败,不会退化为直接写文件', { healthUrl: session.healthUrl }, 503);
519
+ }
520
+ if (health.previewKey !== session.previewKey) {
521
+ throw new StudioError(ERROR_CODES.SESSION_EXPIRED, '运行中的服务与 session.json 不匹配,请重启服务', undefined, 409);
522
+ }
523
+ return session;
524
+ }
525
+
526
+ async function invokeRemoteTool(session, toolName, payload, { quiet = false } = {}) {
527
+ const response = await fetch(`${session.previewUrl.replace(/\/$/, '')}/api/invoke`, {
528
+ method: 'POST',
529
+ headers: { 'content-type': 'application/json', 'x-studio-token': session.token },
530
+ body: JSON.stringify({ tool: toolName, args: payload }),
531
+ signal: AbortSignal.timeout(30000),
532
+ });
533
+ const value = await response.json().catch(() => null);
534
+ if (!response.ok) {
535
+ const error = value?.error ?? { code: ERROR_CODES.INTERNAL, message: `HTTP ${response.status}` };
536
+ if (!quiet) {
537
+ out({ error });
538
+ process.exitCode = response.status >= 500 ? 3 : 2;
539
+ }
540
+ return null;
541
+ }
542
+ return value;
543
+ }
544
+
545
+ async function lint(args) {
546
+ const root = requireRoot(args);
547
+ await recoverWorkspace(root).catch(() => {});
548
+ const document = await CoursewareDocument.load(root);
549
+ const value = { revision: document.revision, ...document.report };
550
+ if (args.json) out(value);
551
+ else {
552
+ out(`${document.report.valid ? 'OK' : 'FAILED'} — errors ${document.report.errors}, warnings ${document.report.warnings}`);
553
+ for (const item of document.report.items) out(`[${item.level}] ${item.code} ${item.path}: ${item.message}`);
554
+ }
555
+ if (!document.report.valid) process.exitCode = 1;
556
+ }
557
+
558
+ async function doExport(args) {
559
+ const root = requireRoot(args);
560
+ if (!args.out) throw new StudioError(ERROR_CODES.OPERATION_INVALID, 'export 需要 --out', undefined, 400);
561
+ await recoverWorkspace(root).catch(() => {});
562
+ out(await exportCourseware({
563
+ root,
564
+ out: path.resolve(process.cwd(), args.out),
565
+ force: args.force === true,
566
+ }));
567
+ }
568
+
569
+ async function doPackage(args) {
570
+ const root = requireRoot(args);
571
+ if (!args.out) throw new StudioError(ERROR_CODES.OPERATION_INVALID, 'package 需要 --out', undefined, 400);
572
+ const raw = path.resolve(process.cwd(), args.out);
573
+ const target = raw.toLowerCase().endsWith('.lume') ? raw : `${raw}.lume`;
574
+ await recoverWorkspace(root).catch(() => {});
575
+ out(await packageCourseware({ root, out: target, force: args.force === true }));
576
+ }
577
+
578
+ async function doImport(args) {
579
+ if (!args.file) throw new StudioError(ERROR_CODES.OPERATION_INVALID, 'import 需要 --file', undefined, 400);
580
+ if (!args.out) throw new StudioError(ERROR_CODES.OPERATION_INVALID, 'import 需要 --out', undefined, 400);
581
+ out(await importCourseware({
582
+ file: path.resolve(process.cwd(), args.file),
583
+ out: path.resolve(process.cwd(), args.out),
584
+ force: args.force === true,
585
+ }));
586
+ }
587
+
588
+ function assertSessionCompatible(root, session) {
589
+ if (session.protocolVersion !== 1 || session.packageVersion !== packageVersion()) {
590
+ throw new StudioError(
591
+ ERROR_CODES.SESSION_EXPIRED,
592
+ '运行中的服务版本与当前 CLI 不兼容,请停止旧进程后重新启动',
593
+ { running: session.packageVersion, cli: packageVersion(), protocolVersion: session.protocolVersion },
594
+ 409,
595
+ );
596
+ }
597
+ if (path.resolve(session.coursewareRoot) !== path.resolve(root)) {
598
+ throw new StudioError(ERROR_CODES.SESSION_EXPIRED, 'session.json 的课件根目录不匹配', {
599
+ expected: path.resolve(root),
600
+ actual: session.coursewareRoot,
601
+ }, 409);
602
+ }
603
+ }
604
+
605
+ async function inspectSession(root) {
606
+ const session = await readSessionFile(root);
607
+ if (!session) return { healthy: false, incompatible: false, session: null };
608
+ try {
609
+ assertSessionCompatible(root, session);
610
+ } catch {
611
+ return { healthy: false, incompatible: true, session };
612
+ }
613
+ if (!pidAlive(session.pid)) {
614
+ await removeSessionFile(root, (value) => value?.pid === session.pid);
615
+ return { healthy: false, incompatible: false, session };
616
+ }
617
+ const health = await fetchHealth(session.healthUrl);
618
+ if (!health) {
619
+ // 进程仍在但健康检查失败:不启动第二个实例,避免同一 root 双写。
620
+ throw new StudioError(
621
+ ERROR_CODES.PREVIEW_UNAVAILABLE,
622
+ '检测到同目录进程仍在运行但健康检查失败,请先停止旧进程或检查端口占用',
623
+ { pid: session.pid, healthUrl: session.healthUrl },
624
+ 503,
625
+ );
626
+ }
627
+ if (health.previewKey !== session.previewKey) {
628
+ return { healthy: false, incompatible: true, session };
629
+ }
630
+ return { healthy: true, incompatible: false, session: { ...session, ...health, revision: health.revision } };
631
+ }
632
+
633
+ async function fetchHealth(url) {
634
+ try {
635
+ const response = await fetch(url, { signal: AbortSignal.timeout(1500) });
636
+ if (!response.ok) return null;
637
+ return await response.json();
638
+ } catch {
639
+ return null;
640
+ }
641
+ }
642
+
643
+ function pidAlive(pid) {
644
+ if (!Number.isInteger(pid) || pid <= 0) return false;
645
+ try {
646
+ process.kill(pid, 0);
647
+ return true;
648
+ } catch (error) {
649
+ return error.code === 'EPERM';
650
+ }
651
+ }
652
+
653
+ function truthy(value) {
654
+ return ['1', 'true', 'yes', 'on'].includes(String(value ?? '').toLowerCase());
655
+ }
656
+
657
+ function openBrowser(url) {
658
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
659
+ const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
660
+ try {
661
+ const child = spawn(command, args, { stdio: 'ignore', detached: true });
662
+ child.on('error', () => {});
663
+ child.unref();
664
+ } catch {
665
+ // 打开浏览器失败不影响服务启动。
666
+ }
667
+ }
668
+
669
+ export { PACKAGE_ROOT, findSkills };