dsh-zju-lecture-note 2.2.5 → 2.2.7

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