dsh-zju-lecture-note 2.2.6 → 2.2.8

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.
package/lib/bridge.js CHANGED
@@ -7,13 +7,62 @@
7
7
  */
8
8
 
9
9
  import { spawn } from "node:child_process";
10
- import { existsSync, readFileSync } from "node:fs";
10
+ import { existsSync, readFileSync, statSync } from "node:fs";
11
11
  import { dirname, join, resolve } from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
13
 
14
14
  const PLUGIN_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
15
15
  const SERVER_PATH = join(PLUGIN_ROOT, "mcp_server.py");
16
16
 
17
+ /** Refused call message: never fall back to the plugin directory. */
18
+ export const WORKSPACE_UNAVAILABLE =
19
+ "工作区不可用,已拒绝执行以避免写入插件目录";
20
+
21
+ /** How many workspace-scoped Python children stay alive at the same time. */
22
+ const DEFAULT_MAX_WORKSPACES = 2;
23
+
24
+ /**
25
+ * Settings copied into the Python child environment at spawn time.
26
+ *
27
+ * A change to any of these cannot reach a running child, so the next call has
28
+ * to start a new one. `timeoutMs` is deliberately absent: it is applied to the
29
+ * JSON-RPC request and does not need a respawn.
30
+ */
31
+ const SPAWN_SETTING_KEYS = [
32
+ "python",
33
+ "enableSlides",
34
+ "slidesAsSource",
35
+ "embedSlideImages",
36
+ "enableStudyNotes",
37
+ "enableLoginTools",
38
+ "renderPdf",
39
+ "typstAutoInstall",
40
+ "typstPath",
41
+ "typstMirror",
42
+ ];
43
+
44
+ /**
45
+ * Last-line redaction for Python stderr before it reaches the host log.
46
+ *
47
+ * Python already redacts cookies, but dependency downloads write mirror URLs
48
+ * (userinfo / signed query) straight to stderr. The same text is also kept in
49
+ * `stderrTail`, which is appended to start-up errors returned to the model.
50
+ */
51
+ const STDERR_REDACTIONS = [
52
+ // 整个头部值都要吃掉:Cookie 头是 "a=1; b=2",只替换第一个 token 仍会漏。
53
+ [/(Cookie|Authorization|Bearer)\s*[:=]\s*[^\r\n]+/gi, "$1: [REDACTED]"],
54
+ [/\/\/[^/@\s]+:[^/@\s]+@/g, "//"],
55
+ [/([?&])(token|key|secret|signature)=[^&\s]+/gi, "$1$2=[REDACTED]"],
56
+ ];
57
+
58
+ export function redactStderr(text) {
59
+ let value = String(text ?? "");
60
+ for (const [pattern, replacement] of STDERR_REDACTIONS) {
61
+ value = value.replace(pattern, replacement);
62
+ }
63
+ return value;
64
+ }
65
+
17
66
  const PLUGIN_VERSION = (() => {
18
67
  try {
19
68
  return JSON.parse(readFileSync(join(PLUGIN_ROOT, "package.json"), "utf8")).version || "0.0.0";
@@ -64,6 +113,25 @@ export function pythonCandidates(explicit) {
64
113
  return candidates;
65
114
  }
66
115
 
116
+ /**
117
+ * One Python child per workspace.
118
+ *
119
+ * cwd and `ZJU_WORKSPACE` are fixed at spawn time, so a process is never
120
+ * shared between sessions: session B must not resolve a relative path
121
+ * against session A's directory.
122
+ */
123
+ class WorkspaceSession {
124
+ constructor(workspace) {
125
+ this.workspace = workspace;
126
+ this.process = null;
127
+ this.buffer = "";
128
+ this.pending = new Map();
129
+ this.starting = null;
130
+ this.stderrTail = [];
131
+ this.disposed = false;
132
+ }
133
+ }
134
+
67
135
  export class ZjuBridge {
68
136
  constructor(options = {}) {
69
137
  this.python = options.python || "";
@@ -74,6 +142,12 @@ export class ZjuBridge {
74
142
  * pre-1.5.1 default (enabled), matching the Python core's MCP default.
75
143
  */
76
144
  this.enableSlides = options.enableSlides !== false;
145
+ /**
146
+ * Projection as a note source: the agent must fetch/download the
147
+ * screenshots before writing. Independent of `embedSlideImages`, which
148
+ * only decides whether key pages are inserted into the Markdown.
149
+ */
150
+ this.slidesAsSource = this.enableSlides && options.slidesAsSource === true;
77
151
  this.embedSlideImages = this.enableSlides && options.embedSlideImages === true;
78
152
  /** Optional fill-in study-note workflow; default true for direct users. */
79
153
  this.enableStudyNotes = options.enableStudyNotes !== false;
@@ -87,41 +161,170 @@ export class ZjuBridge {
87
161
  * point is that a fresh machine can typeset without extra steps.
88
162
  */
89
163
  this.typstAutoInstall = options.typstAutoInstall !== false;
90
- this.process = null;
91
- this.buffer = "";
92
- this.pending = new Map();
164
+ /**
165
+ * Optional explicit Typst executable and download mirror. Empty keeps the
166
+ * parent environment / built-in lookup order, so a user who never touched
167
+ * these fields sees exactly the pre-2.2.7 behaviour.
168
+ */
169
+ this.typstPath = options.typstPath || "";
170
+ this.typstMirror = options.typstMirror || "";
171
+ this.maxWorkspaces = Math.max(
172
+ 1,
173
+ Number(options.maxWorkspaces) > 0 ? Math.floor(Number(options.maxWorkspaces)) : DEFAULT_MAX_WORKSPACES,
174
+ );
93
175
  this.nextId = 1;
94
- this.starting = null;
95
176
  this.lastError = null;
96
177
  /**
97
- * Session workspace, used as the Python child's cwd and exported as
98
- * ZJU_WORKSPACE. The server is a child process, so its cwd is never the
99
- * directory the agent works in; without this a relative note path such as
100
- * `知识总结.md` resolved nowhere and the tool said the file did not exist.
178
+ * Session workspace declared by the host, used as the Python child's cwd
179
+ * and exported as ZJU_WORKSPACE. There is deliberately **no** fallback to
180
+ * PLUGIN_ROOT: a missing workspace means the call is refused, otherwise a
181
+ * relative path could be resolved (and written) inside the plugin.
101
182
  */
102
183
  this.workspace = "";
184
+ /** Workspace of the most recently spawned child (diagnostics only). */
103
185
  this.spawnedWorkspace = null;
186
+ /** workspace key -> WorkspaceSession, insertion order = LRU order. */
187
+ this.sessions = new Map();
104
188
  /** 最近 20 行 Python stderr,用于把启动失败的真实原因带进错误消息。 */
105
189
  this.stderrTail = [];
106
190
  }
107
191
 
192
+ /**
193
+ * Replace the configuration of a live bridge after a settings edit.
194
+ *
195
+ * Every switch below is mirrored into the Python child environment at spawn
196
+ * time, so changing one cannot reach an already-running child. Workspace
197
+ * sessions are therefore dropped when a spawn-affecting value changed; the
198
+ * next tool call spawns a child with the new values. A timeout-only edit
199
+ * keeps the children alive because it only changes the JS request timer.
200
+ * This is what makes a GUI save observable to the agent in the same session
201
+ * instead of only after a full restart.
202
+ *
203
+ * @param {object} options same shape as the constructor options
204
+ * @returns {boolean} whether anything actually changed
205
+ */
206
+ configure(options = {}) {
207
+ const enableSlides = options.enableSlides !== false;
208
+ const next = {
209
+ python: options.python || "",
210
+ timeoutMs: options.timeoutMs || 120000,
211
+ enableSlides,
212
+ slidesAsSource: enableSlides && options.slidesAsSource === true,
213
+ embedSlideImages: enableSlides && options.embedSlideImages === true,
214
+ enableStudyNotes: options.enableStudyNotes !== false,
215
+ enableLoginTools: options.enableLoginTools !== false,
216
+ renderPdf: options.renderPdf === true,
217
+ typstAutoInstall: options.typstAutoInstall !== false,
218
+ typstPath: options.typstPath || "",
219
+ typstMirror: options.typstMirror || "",
220
+ };
221
+ const changed = Object.keys(next).some((key) => this[key] !== next[key]);
222
+ const spawnChanged = SPAWN_SETTING_KEYS.some((key) => this[key] !== next[key]);
223
+ Object.assign(this, next);
224
+ if (spawnChanged) this.#disposeSessions();
225
+ return changed;
226
+ }
227
+
228
+ /** Drop every workspace session; the next call spawns with current values. */
229
+ #disposeSessions() {
230
+ for (const session of this.sessions.values()) {
231
+ this.#disposeSession(session);
232
+ }
233
+ this.sessions.clear();
234
+ }
235
+
108
236
  /**
109
237
  * Declare the workspace for the next call.
110
238
  *
111
- * The child cannot change its cwd, so a changed workspace recycles the
112
- * process — but only when nothing is in flight, otherwise an in-flight
113
- * call would be rejected just to change a directory.
239
+ * A relative path is resolved against the host's process directory exactly
240
+ * once, here, so `call()` always sees an absolute path to validate.
114
241
  *
115
242
  * @param {string | undefined} directory absolute session workspace
116
243
  */
117
244
  useWorkspace(directory) {
118
245
  const next = typeof directory === "string" ? directory.trim() : "";
119
- if (!next || next === this.workspace) return;
120
- this.workspace = next;
246
+ this.workspace = next ? resolve(next) : "";
121
247
  }
122
248
 
123
- async #spawn(candidate) {
124
- const cwd = this.workspace && existsSync(this.workspace) ? this.workspace : PLUGIN_ROOT;
249
+ #workspaceError(workspace) {
250
+ if (!workspace) {
251
+ return `${WORKSPACE_UNAVAILABLE}: 会话没有声明工作区`;
252
+ }
253
+ try {
254
+ if (!existsSync(workspace) || !statSync(workspace).isDirectory()) {
255
+ return `${WORKSPACE_UNAVAILABLE}: 目录不存在 (${workspace})`;
256
+ }
257
+ } catch {
258
+ return `${WORKSPACE_UNAVAILABLE}: 目录不可访问 (${workspace})`;
259
+ }
260
+ return "";
261
+ }
262
+
263
+ #sessionKey(workspace) {
264
+ return process.platform === "win32" ? workspace.toLowerCase() : workspace;
265
+ }
266
+
267
+ #sessionFor(workspace) {
268
+ const key = this.#sessionKey(workspace);
269
+ const existing = this.sessions.get(key);
270
+ if (existing) {
271
+ // Re-insert so Map order keeps the least recently used entry first.
272
+ this.sessions.delete(key);
273
+ this.sessions.set(key, existing);
274
+ return existing;
275
+ }
276
+ const session = new WorkspaceSession(workspace);
277
+ this.sessions.set(key, session);
278
+ this.#enforceLimit();
279
+ return session;
280
+ }
281
+
282
+ #enforceLimit() {
283
+ while (this.sessions.size > this.maxWorkspaces) {
284
+ let victimKey = null;
285
+ let victim = null;
286
+ for (const [key, session] of this.sessions) {
287
+ if (session.pending.size === 0 && !session.starting) {
288
+ victimKey = key;
289
+ victim = session;
290
+ break;
291
+ }
292
+ }
293
+ if (!victim) {
294
+ const first = this.sessions.entries().next();
295
+ if (first.done) return;
296
+ victimKey = first.value[0];
297
+ victim = first.value[1];
298
+ }
299
+ this.sessions.delete(victimKey);
300
+ this.#disposeSession(victim);
301
+ }
302
+ }
303
+
304
+ #killChild(session, reason) {
305
+ const child = session.process;
306
+ session.process = null;
307
+ for (const [, entry] of session.pending) entry.reject(new Error(reason));
308
+ session.pending.clear();
309
+ if (!child) return;
310
+ try {
311
+ child.stdin.end();
312
+ } catch {
313
+ /* ignore */
314
+ }
315
+ try {
316
+ child.kill();
317
+ } catch {
318
+ /* ignore */
319
+ }
320
+ }
321
+
322
+ #disposeSession(session) {
323
+ session.disposed = true;
324
+ this.#killChild(session, "ZJU Lecture 服务已关闭(工作区已切换)");
325
+ }
326
+
327
+ async #spawn(candidate, session) {
125
328
  const env = {
126
329
  ...process.env,
127
330
  PYTHONUTF8: "1",
@@ -130,20 +333,27 @@ export class ZjuBridge {
130
333
  // The plugin setting is authoritative for its own Python child; the
131
334
  // env vars remain the switches for plain MCP hosts.
132
335
  ZJU_ENABLE_SLIDES: this.enableSlides ? "1" : "0",
336
+ ZJU_SLIDES_SOURCE: this.slidesAsSource ? "1" : "0",
133
337
  ZJU_EMBED_SLIDES: this.embedSlideImages ? "1" : "0",
134
338
  ZJU_ENABLE_STUDY_NOTES: this.enableStudyNotes ? "1" : "0",
135
339
  ZJU_ENABLE_LOGIN_TOOLS: this.enableLoginTools ? "1" : "0",
136
340
  ZJU_RENDER_PDF: this.renderPdf ? "1" : "0",
137
341
  ZJU_TYPST_AUTO_INSTALL: this.typstAutoInstall ? "1" : "0",
342
+ // Always explicit: the session workspace is the only writable root.
343
+ ZJU_WORKSPACE: session.workspace,
138
344
  };
139
- if (cwd !== PLUGIN_ROOT) env.ZJU_WORKSPACE = cwd;
345
+ // An explicit setting wins over an inherited environment variable; an
346
+ // empty field leaves the parent environment (the MCP/CLI fallback) intact.
347
+ if (this.typstPath) env.ZJU_TYPST_BIN = this.typstPath;
348
+ if (this.typstMirror) env.ZJU_TYPST_MIRROR = this.typstMirror;
140
349
  const child = spawn(candidate.command, [...candidate.args, SERVER_PATH], {
141
- cwd,
350
+ cwd: session.workspace,
142
351
  stdio: ["pipe", "pipe", "pipe"],
143
352
  windowsHide: true,
144
353
  env,
145
354
  });
146
- this.spawnedWorkspace = cwd;
355
+ session.process = child;
356
+ this.spawnedWorkspace = session.workspace;
147
357
 
148
358
  await new Promise((done, fail) => {
149
359
  let settled = false;
@@ -161,38 +371,49 @@ export class ZjuBridge {
161
371
  });
162
372
  });
163
373
 
374
+ if (session.disposed) {
375
+ try {
376
+ child.kill();
377
+ } catch {
378
+ /* ignore */
379
+ }
380
+ throw new Error("工作区会话已关闭");
381
+ }
382
+
164
383
  child.stdout.setEncoding("utf8");
165
- child.stdout.on("data", (chunk) => this.#onData(chunk));
384
+ child.stdout.on("data", (chunk) => this.#onData(session, chunk));
166
385
  child.stderr.setEncoding("utf8");
167
386
  child.stderr.on("data", (chunk) => {
168
- const text = String(chunk).trim();
387
+ const text = redactStderr(String(chunk).trim());
169
388
  if (!text) return;
389
+ session.stderrTail.push(...text.split(/\r?\n/));
390
+ if (session.stderrTail.length > 20) session.stderrTail = session.stderrTail.slice(-20);
170
391
  this.stderrTail.push(...text.split(/\r?\n/));
171
392
  if (this.stderrTail.length > 20) this.stderrTail = this.stderrTail.slice(-20);
172
393
  process.stderr.write(`[zju-lecture] ${text}\n`);
173
394
  });
174
395
  child.on("exit", (code, signal) => {
175
- this.process = null;
396
+ if (session.process === child) session.process = null;
176
397
  const reason = `Python 服务已退出 (code=${code}, signal=${signal})`;
177
- for (const [, entry] of this.pending) entry.reject(new Error(reason));
178
- this.pending.clear();
398
+ for (const [, entry] of session.pending) entry.reject(new Error(reason));
399
+ session.pending.clear();
179
400
  });
180
401
 
181
402
  return child;
182
403
  }
183
404
 
184
- #onData(chunk) {
185
- this.buffer += chunk;
186
- let index = this.buffer.indexOf("\n");
405
+ #onData(session, chunk) {
406
+ session.buffer += chunk;
407
+ let index = session.buffer.indexOf("\n");
187
408
  while (index !== -1) {
188
- const line = this.buffer.slice(0, index).trim();
189
- this.buffer = this.buffer.slice(index + 1);
190
- if (line) this.#onLine(line);
191
- index = this.buffer.indexOf("\n");
409
+ const line = session.buffer.slice(0, index).trim();
410
+ session.buffer = session.buffer.slice(index + 1);
411
+ if (line) this.#onLine(session, line);
412
+ index = session.buffer.indexOf("\n");
192
413
  }
193
414
  }
194
415
 
195
- #onLine(line) {
416
+ #onLine(session, line) {
196
417
  let message;
197
418
  try {
198
419
  message = JSON.parse(line);
@@ -200,43 +421,39 @@ export class ZjuBridge {
200
421
  return;
201
422
  }
202
423
  if (!message || typeof message !== "object") return;
203
- const entry = this.pending.get(message.id);
424
+ const entry = session.pending.get(message.id);
204
425
  if (!entry) return;
205
- this.pending.delete(message.id);
426
+ session.pending.delete(message.id);
206
427
  entry.resolve(message);
207
428
  }
208
429
 
209
- async #ensureProcess() {
210
- if (this.process) {
211
- // The workspace moved (another session): recycle only when idle.
212
- const stale = this.workspace && this.spawnedWorkspace !== this.workspace;
213
- if (!stale || this.pending.size > 0) return this.process;
214
- this.dispose();
215
- }
216
- if (this.starting) return this.starting;
430
+ async #ensureProcess(session) {
431
+ if (session.disposed) throw new Error("ZJU Lecture 工作区会话已关闭");
432
+ if (session.process) return session.process;
433
+ if (session.starting) return session.starting;
217
434
 
218
- this.starting = (async () => {
435
+ session.starting = (async () => {
219
436
  if (!existsSync(SERVER_PATH)) {
220
437
  throw new Error(`找不到 ZJU Lecture 服务端: ${SERVER_PATH}`);
221
438
  }
222
439
  const failures = [];
223
440
  for (const candidate of pythonCandidates(this.python)) {
224
- const before = this.stderrTail.length;
441
+ const before = session.stderrTail.length;
225
442
  try {
226
- const child = await this.#spawn(candidate);
227
- this.process = child;
228
- await this.#request("initialize", {
443
+ const child = await this.#spawn(candidate, session);
444
+ await this.#request(session, "initialize", {
229
445
  protocolVersion: "2024-11-05",
230
446
  capabilities: {},
231
447
  clientInfo: { name: "dsh-zju-lecture-note", version: PLUGIN_VERSION },
232
448
  });
233
- this.#notify("notifications/initialized", {});
449
+ this.#notify(session, "notifications/initialized", {});
234
450
  return child;
235
451
  } catch (error) {
236
452
  // 启动失败时必须清掉 process 引用,否则下一次调用会以为服务端还活着,
237
453
  // 直接把请求写进一个已死的 stdin;顺手把 stderr 里的真实原因带出来。
238
- this.dispose();
239
- const detail = this.stderrTail.slice(before).join(" | ").trim();
454
+ // 注意这里只杀掉当前子进程,会话本身仍可换下一个解释器重试。
455
+ this.#killChild(session, "ZJU Lecture 服务启动失败");
456
+ const detail = session.stderrTail.slice(before).join(" | ").trim();
240
457
  failures.push(`${candidate.command}: ${error.message}${detail ? ` [stderr] ${detail}` : ""}`);
241
458
  }
242
459
  }
@@ -244,39 +461,39 @@ export class ZjuBridge {
244
461
  })();
245
462
 
246
463
  try {
247
- return await this.starting;
464
+ return await session.starting;
248
465
  } finally {
249
- this.starting = null;
466
+ session.starting = null;
250
467
  }
251
468
  }
252
469
 
253
- #write(payload) {
254
- const child = this.process;
470
+ #write(session, payload) {
471
+ const child = session.process;
255
472
  if (!child || child.stdin.destroyed) throw new Error("ZJU Lecture 服务未运行");
256
473
  child.stdin.write(`${JSON.stringify(payload)}\n`);
257
474
  }
258
475
 
259
- #notify(method, params) {
260
- this.#write({ jsonrpc: "2.0", method, params });
476
+ #notify(session, method, params) {
477
+ this.#write(session, { jsonrpc: "2.0", method, params });
261
478
  }
262
479
 
263
- #request(method, params, timeoutMs = this.timeoutMs) {
480
+ #request(session, method, params, timeoutMs = this.timeoutMs) {
264
481
  const id = this.nextId++;
265
- const child = this.process;
482
+ const child = session.process;
266
483
  if (!child) return Promise.reject(new Error("ZJU Lecture 服务未运行"));
267
484
  const limit = Number(timeoutMs) > 0 ? Number(timeoutMs) : this.timeoutMs;
268
485
  return new Promise((resolve, reject) => {
269
486
  const timer = setTimeout(() => {
270
- this.pending.delete(id);
487
+ session.pending.delete(id);
271
488
  // Recycle the Python child only when nothing else is in flight. A
272
489
  // timeout used to kill the process and with it the in-memory cookie
273
490
  // cache — one slow call silently logged the user out.
274
- const idle = this.pending.size === 0;
275
- if (idle) this.dispose();
491
+ const idle = session.pending.size === 0;
492
+ if (idle) this.#disposeSession(session);
276
493
  const suffix = idle ? "" : "(其他调用仍在进行,服务进程保持运行)";
277
494
  reject(new Error(`调用 ${method} 超时(${limit} ms)${suffix}`));
278
495
  }, limit);
279
- this.pending.set(id, {
496
+ session.pending.set(id, {
280
497
  resolve: (value) => {
281
498
  clearTimeout(timer);
282
499
  resolve(value);
@@ -286,14 +503,20 @@ export class ZjuBridge {
286
503
  reject(error);
287
504
  },
288
505
  });
289
- this.#write({ jsonrpc: "2.0", id, method, params });
506
+ this.#write(session, { jsonrpc: "2.0", id, method, params });
290
507
  });
291
508
  }
292
509
 
293
510
  /** Call one MCP tool and return its text payload. */
294
511
  async call(toolName, args = {}, options = {}) {
295
- await this.#ensureProcess();
512
+ const workspace = this.workspace;
513
+ const invalid = this.#workspaceError(workspace);
514
+ if (invalid) throw new Error(invalid);
515
+
516
+ const session = this.#sessionFor(workspace);
517
+ await this.#ensureProcess(session);
296
518
  const response = await this.#request(
519
+ session,
297
520
  "tools/call",
298
521
  {
299
522
  name: toolName,
@@ -324,20 +547,6 @@ export class ZjuBridge {
324
547
  }
325
548
 
326
549
  dispose() {
327
- const child = this.process;
328
- this.process = null;
329
- for (const [, entry] of this.pending) entry.reject(new Error("ZJU Lecture 服务已关闭"));
330
- this.pending.clear();
331
- if (!child) return;
332
- try {
333
- child.stdin.end();
334
- } catch {
335
- /* ignore */
336
- }
337
- try {
338
- child.kill();
339
- } catch {
340
- /* ignore */
341
- }
550
+ this.#disposeSessions();
342
551
  }
343
552
  }