@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,307 @@
1
+ // 界面对话信箱:把聊天消息与选中元素上下文持久化到 .studio/chat.jsonl。
2
+ // 浏览器只负责写入用户消息;启动 Studio 的 Agent 通过 chat.pull 拉取,
3
+ // 修改课件后用 chat.reply 回复。文件不进课件包,也不参与校验和。
4
+
5
+ import { randomBytes } from 'node:crypto';
6
+ import fsp from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import { ERROR_CODES, StudioError } from '../core/errors.js';
9
+ import { ensureStudioDir, STUDIO_DIR, writeFileAtomic } from '../core/storage.js';
10
+
11
+ const CHAT_FILE = 'chat.jsonl';
12
+ const CLAIMS_FILE = 'chat-claims.json';
13
+ const MAX_BYTES = 1024 * 1024;
14
+ const KEEP_LINES = 800;
15
+ const MAX_TEXT = 4000;
16
+ const MAX_SELECTION_HTML = 1200;
17
+ const DEFAULT_CLAIM_MS = 5 * 60 * 1000;
18
+ const ROLES = new Set(['user', 'agent', 'system']);
19
+
20
+ export class ChatMailbox {
21
+ constructor({ root } = {}) {
22
+ this.root = path.resolve(root);
23
+ this.queue = Promise.resolve();
24
+ this.file = null;
25
+ this.claimsFile = null;
26
+ this.claims = null;
27
+ this.nextSeq = 1;
28
+ this.loaded = false;
29
+ }
30
+
31
+ // 所有写入串行化,避免同一进程内两条消息交错。
32
+ enqueue(task) {
33
+ const run = this.queue.then(task, task);
34
+ this.queue = run.catch(() => {});
35
+ return run;
36
+ }
37
+
38
+ async ensureFile() {
39
+ if (this.file) return this.file;
40
+ const studioDir = await ensureStudioDir(this.root);
41
+ const file = path.join(studioDir, CHAT_FILE);
42
+ await assertRegularOrMissing(file);
43
+ this.file = file;
44
+ return file;
45
+ }
46
+
47
+ append(payload) {
48
+ return this.enqueue(async () => {
49
+ const role = payload?.role;
50
+ if (!ROLES.has(role)) {
51
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, 'role 必须是 user、agent 或 system', { role }, 400);
52
+ }
53
+ const text = normalizeText(payload?.text);
54
+ const selection = sanitizeSelection(payload?.selection);
55
+ if (!text) {
56
+ if (role === 'agent') {
57
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, 'Agent 回复不能为空', undefined, 400);
58
+ }
59
+ if (!selection) {
60
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '消息内容不能为空', undefined, 400);
61
+ }
62
+ }
63
+ const file = await this.ensureFile();
64
+ if (!this.loaded) await this.load();
65
+ const message = {
66
+ seq: this.nextSeq,
67
+ id: `msg_${randomBytes(6).toString('base64url')}`,
68
+ role,
69
+ text,
70
+ selection,
71
+ inReplyTo: typeof payload?.inReplyTo === 'string' ? payload.inReplyTo.slice(0, 80) : null,
72
+ revision: Number.isInteger(payload?.revision) ? payload.revision : null,
73
+ createdAt: new Date().toISOString(),
74
+ };
75
+ this.nextSeq += 1;
76
+ await fsp.appendFile(file, `${JSON.stringify(message)}\n`, { mode: 0o600 });
77
+ await fsp.chmod(file, 0o600).catch(() => {});
78
+ // 同步内存视图,保证同一实例后续 pull/list 立即看到新消息。
79
+ this.messages = [...(this.messages ?? []), message].slice(-KEEP_LINES);
80
+ // Agent 回复即视为处理完成,立即释放认领,避免监听器重复处理。
81
+ if (role === 'agent' && message.inReplyTo) await this.dropClaim(message.inReplyTo);
82
+ await rotateIfNeeded(file);
83
+ return message;
84
+ });
85
+ }
86
+
87
+ // 认领一条用户消息:同一时间只允许一个监听器处理,租约到期后自动放回待办。
88
+ claim({ id, by, ttlMs = DEFAULT_CLAIM_MS } = {}) {
89
+ return this.enqueue(async () => {
90
+ if (typeof id !== 'string' || id.length < 3) {
91
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '消息 id 不合法', { id }, 400);
92
+ }
93
+ const owner = typeof by === 'string' && by.trim() ? by.trim().slice(0, 80) : 'agent';
94
+ const ttl = Math.min(Math.max(Number(ttlMs) || DEFAULT_CLAIM_MS, 5000), 30 * 60 * 1000);
95
+ const claims = await this.loadClaims();
96
+ pruneClaims(claims);
97
+ const existing = claims[id];
98
+ const now = Date.now();
99
+ if (existing && existing.expiresAt > now && existing.by !== owner) {
100
+ return { claimed: false, by: existing.by, expiresAt: existing.expiresAt };
101
+ }
102
+ const message = (await this.readAll()).find((item) => item.id === id);
103
+ if (!message) {
104
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '消息不存在', { id }, 404);
105
+ }
106
+ if (message.role !== 'user') {
107
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '只能认领用户消息', { id, role: message.role }, 400);
108
+ }
109
+ claims[id] = { by: owner, expiresAt: now + ttl };
110
+ await this.persistClaims();
111
+ return { claimed: true, by: owner, expiresAt: claims[id].expiresAt, message };
112
+ });
113
+ }
114
+
115
+ async release({ id } = {}) {
116
+ return this.enqueue(async () => {
117
+ const claims = await this.loadClaims();
118
+ const existed = Boolean(claims[id]);
119
+ if (existed) {
120
+ delete claims[id];
121
+ await this.persistClaims();
122
+ }
123
+ return { released: existed };
124
+ });
125
+ }
126
+
127
+ async claimedIds() {
128
+ const claims = await this.loadClaims();
129
+ pruneClaims(claims);
130
+ return Object.keys(claims);
131
+ }
132
+
133
+ async loadClaims() {
134
+ if (this.claims) return this.claims;
135
+ const studioDir = await ensureStudioDir(this.root);
136
+ const file = path.join(studioDir, CLAIMS_FILE);
137
+ await assertRegularOrMissing(file);
138
+ this.claimsFile = file;
139
+ let value = null;
140
+ try {
141
+ value = JSON.parse(await fsp.readFile(file, 'utf8'));
142
+ } catch (error) {
143
+ if (error.code !== 'ENOENT') value = null;
144
+ }
145
+ this.claims = value && typeof value.claims === 'object' && value.claims ? { ...value.claims } : {};
146
+ pruneClaims(this.claims);
147
+ return this.claims;
148
+ }
149
+
150
+ async persistClaims() {
151
+ if (!this.claimsFile) await this.loadClaims();
152
+ await writeFileAtomic(this.claimsFile, `${JSON.stringify({ version: 1, claims: this.claims }, null, 2)}\n`, { mode: 0o600 });
153
+ }
154
+
155
+ async dropClaim(id) {
156
+ const claims = await this.loadClaims();
157
+ if (!claims[id]) return;
158
+ delete claims[id];
159
+ await this.persistClaims();
160
+ }
161
+
162
+ async list({ since = 0, limit = 100 } = {}) {
163
+ const messages = await this.readAll();
164
+ const start = Number.isFinite(Number(since)) ? Math.max(0, Math.trunc(Number(since))) : 0;
165
+ const size = Math.min(Math.max(Number(limit) || 100, 1), 200);
166
+ const filtered = messages.filter((message) => message.seq > start).slice(0, size);
167
+ return {
168
+ messages: filtered,
169
+ cursor: filtered.length > 0 ? filtered[filtered.length - 1].seq : start,
170
+ total: messages.length,
171
+ };
172
+ }
173
+
174
+ // 尚未被 Agent 回复、也未被监听器认领的用户消息,按时间正序返回。
175
+ async pending({ limit = 20 } = {}) {
176
+ const messages = await this.readAll();
177
+ const claims = await this.loadClaims();
178
+ pruneClaims(claims);
179
+ const replied = new Set(
180
+ messages.filter((message) => message.role === 'agent' && message.inReplyTo).map((message) => message.inReplyTo),
181
+ );
182
+ const waiting = messages.filter(
183
+ (message) => message.role === 'user' && !replied.has(message.id) && !claims[message.id],
184
+ );
185
+ // 先到先处理,避免持续有新消息时旧消息被饿死。
186
+ return waiting.slice(0, Math.min(Math.max(Number(limit) || 20, 1), 50));
187
+ }
188
+
189
+ async readAll() {
190
+ if (!this.loaded) await this.load();
191
+ return this.messages ?? [];
192
+ }
193
+
194
+ async load() {
195
+ const file = await this.ensureFile();
196
+ let text = '';
197
+ try {
198
+ text = await fsp.readFile(file, 'utf8');
199
+ } catch (error) {
200
+ if (error.code !== 'ENOENT') throw error;
201
+ }
202
+ const messages = [];
203
+ let maxSeq = 0;
204
+ for (const line of text.split('\n')) {
205
+ if (!line.trim()) continue;
206
+ let value;
207
+ try {
208
+ value = JSON.parse(line);
209
+ } catch {
210
+ continue;
211
+ }
212
+ if (!value || !ROLES.has(value.role) || typeof value.id !== 'string') continue;
213
+ const seq = Number.isInteger(value.seq) && value.seq > 0 ? value.seq : messages.length + 1;
214
+ maxSeq = Math.max(maxSeq, seq);
215
+ messages.push({
216
+ ...value,
217
+ seq,
218
+ text: normalizeText(value.text),
219
+ selection: sanitizeSelection(value.selection),
220
+ inReplyTo: typeof value.inReplyTo === 'string' ? value.inReplyTo : null,
221
+ revision: Number.isInteger(value.revision) ? value.revision : null,
222
+ });
223
+ }
224
+ this.messages = messages.slice(-KEEP_LINES);
225
+ this.nextSeq = maxSeq + 1;
226
+ this.loaded = true;
227
+ }
228
+ }
229
+
230
+ function normalizeText(value) {
231
+ return typeof value === 'string' ? value.trim().slice(0, MAX_TEXT) : '';
232
+ }
233
+
234
+ // 清理过期租约;调用方持有内存中的 claims 对象。
235
+ function pruneClaims(claims) {
236
+ const now = Date.now();
237
+ for (const [id, claim] of Object.entries(claims)) {
238
+ if (!claim || !Number.isFinite(claim.expiresAt) || claim.expiresAt <= now) delete claims[id];
239
+ }
240
+ }
241
+
242
+ function shortString(value, max) {
243
+ return typeof value === 'string' && value ? value.slice(0, max) : null;
244
+ }
245
+
246
+ function sanitizeSelection(selection) {
247
+ if (!selection || typeof selection !== 'object') return null;
248
+ const rect = selection.rect && typeof selection.rect === 'object'
249
+ ? {
250
+ x: toInt(selection.rect.x),
251
+ y: toInt(selection.rect.y),
252
+ width: toInt(selection.rect.width),
253
+ height: toInt(selection.rect.height),
254
+ }
255
+ : null;
256
+ const value = {
257
+ sceneId: shortString(selection.sceneId, 120),
258
+ selector: shortString(selection.selector, 240),
259
+ tag: shortString(selection.tag, 40),
260
+ id: shortString(selection.id, 120),
261
+ classes: shortString(selection.classes, 200),
262
+ text: shortString(selection.text, 200),
263
+ outerHTML: shortString(selection.outerHTML, MAX_SELECTION_HTML),
264
+ rect,
265
+ };
266
+ if (!value.selector && !value.tag) return null;
267
+ return value;
268
+ }
269
+
270
+ function toInt(value) {
271
+ const number = Number(value);
272
+ return Number.isFinite(number) ? Math.round(number) : 0;
273
+ }
274
+
275
+ async function assertRegularOrMissing(file) {
276
+ try {
277
+ const stat = await fsp.lstat(file);
278
+ if (stat.isSymbolicLink()) {
279
+ throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, `拒绝访问符号链接:${STUDIO_DIR}/${CHAT_FILE}`, undefined, 403);
280
+ }
281
+ if (!stat.isFile()) {
282
+ throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, `目标不是普通文件:${STUDIO_DIR}/${CHAT_FILE}`, undefined, 403);
283
+ }
284
+ } catch (error) {
285
+ if (error instanceof StudioError) throw error;
286
+ if (error.code !== 'ENOENT') throw error;
287
+ }
288
+ }
289
+
290
+ // 超出体积上限时保留最近若干条,避免信箱无限增长。
291
+ async function rotateIfNeeded(file) {
292
+ let stat;
293
+ try {
294
+ stat = await fsp.stat(file);
295
+ } catch {
296
+ return;
297
+ }
298
+ if (stat.size <= MAX_BYTES) return;
299
+ let text = '';
300
+ try {
301
+ text = await fsp.readFile(file, 'utf8');
302
+ } catch {
303
+ return;
304
+ }
305
+ const lines = text.split('\n').filter(Boolean).slice(-KEEP_LINES);
306
+ await writeFileAtomic(file, `${lines.join('\n')}${lines.length ? '\n' : ''}`, { mode: 0o600 });
307
+ }