@ggboy123/dsh-paper-reader 1.5.0 → 1.6.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,379 @@
1
+ #!/usr/bin/env python
2
+ """babeldoc 驱动(dsh-paper-reader 专用):进度事件 + 去掉单次请求的输出长度上限。
3
+
4
+ 用法与 babeldoc 完全一致——argv 原样交给 babeldoc 的 CLI 解析:
5
+
6
+ python babeldoc-driver.py --files a.pdf --lang-in en --lang-out zh-CN --openai ...
7
+
8
+ 只打两处补丁,都是「尽力而为」,任何一步失败就退回 babeldoc 原行为:
9
+
10
+ 1. 进度:把 babeldoc 的 ProgressMonitor 事件按行写到 stdout,前缀 `@@DPR@@`,
11
+ 内容是一行 JSON(Node 侧逐行解析)。babeldoc 自己的 logger 被它自己设成
12
+ ERROR 级并摘掉 handler,所以只能这么传。
13
+ 2. 长度:babeldoc 调 LLM 时不传 max_tokens(端点默认值常常只有 2k~4k,
14
+ 长段落的中文译文会被静默截断),这里显式给足;万一仍被截断
15
+ (finish_reason=length)或端点直接报「输入太长」,就把输入按换行/句子
16
+ 拆成小段分别翻译再拼回,避免整段丢译文或整篇失败。
17
+
18
+ 环境变量(都可选):
19
+ DPR_MAX_OUTPUT_TOKENS 单次请求的 max_tokens 上限,默认 8192;0 = 不传该参数
20
+ DPR_SPLIT_TOKENS 触发拆分的输入上限(估算 token),默认 3000
21
+ DPR_DEBUG=1 额外把补丁动作打到 stderr
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import contextlib
27
+ import json
28
+ import os
29
+ import re
30
+ import sys
31
+ import time
32
+
33
+ PREFIX = "@@DPR@@"
34
+
35
+
36
+ def _reconfigure_streams() -> None:
37
+ """Windows 控制台默认 GBK,中文事件会乱码或被丢弃,改成 UTF-8。"""
38
+ for stream in (sys.stdout, sys.stderr):
39
+ try:
40
+ stream.reconfigure(encoding="utf-8", errors="replace") # type: ignore[attr-defined]
41
+ except Exception:
42
+ pass
43
+
44
+
45
+ _STDOUT_LOCK = None
46
+
47
+
48
+ def emit(payload: dict) -> None:
49
+ """翻译在线程池里跑,多线程写 stdout 会撕行,加锁保证一行一条。"""
50
+ global _STDOUT_LOCK
51
+ if _STDOUT_LOCK is None:
52
+ import threading
53
+
54
+ _STDOUT_LOCK = threading.Lock()
55
+ try:
56
+ line = PREFIX + " " + json.dumps(payload, ensure_ascii=False) + "\n"
57
+ with _STDOUT_LOCK:
58
+ sys.stdout.write(line)
59
+ sys.stdout.flush()
60
+ except Exception:
61
+ pass
62
+
63
+
64
+ def note(message: str) -> None:
65
+ try:
66
+ sys.stderr.write(f"[dpr] {message}\n")
67
+ sys.stderr.flush()
68
+ except Exception:
69
+ pass
70
+
71
+
72
+ def _env_int(name: str, default: int) -> int:
73
+ raw = os.environ.get(name, "").strip()
74
+ if not raw:
75
+ return default
76
+ try:
77
+ return int(float(raw))
78
+ except ValueError:
79
+ return default
80
+
81
+
82
+ MAX_OUT = _env_int("DPR_MAX_OUTPUT_TOKENS", 8192)
83
+ SPLIT_TOKENS = max(200, _env_int("DPR_SPLIT_TOKENS", 3000))
84
+ DEBUG = os.environ.get("DPR_DEBUG", "") not in ("", "0", "false", "False")
85
+ REPORT_MIN_INTERVAL = 0.35 # 进度事件最小间隔(秒),别把 stdout 刷爆
86
+
87
+
88
+ # --------------------------------------------------------------------------
89
+ # 补丁 1:进度事件
90
+ # --------------------------------------------------------------------------
91
+ def install_progress() -> None:
92
+ import babeldoc.main as bmain
93
+
94
+ last = [0.0]
95
+
96
+ def handle(event: dict) -> None:
97
+ kind = event.get("type")
98
+ if kind == "stage_summary":
99
+ stages = [
100
+ {"name": (s or {}).get("name"), "weight": (s or {}).get("percent")}
101
+ for s in (event.get("stages") or [])
102
+ ]
103
+ emit({"kind": "stages", "stages": stages})
104
+ return
105
+ now = time.monotonic()
106
+ if kind == "progress_update" and now - last[0] < REPORT_MIN_INTERVAL:
107
+ return
108
+ last[0] = now
109
+ emit(
110
+ {
111
+ "kind": "progress",
112
+ "type": kind,
113
+ "stage": event.get("stage"),
114
+ "stageCurrent": event.get("stage_current"),
115
+ "stageTotal": event.get("stage_total"),
116
+ "stagePercent": event.get("stage_progress"),
117
+ "overall": event.get("overall_progress"),
118
+ "part": event.get("part_index"),
119
+ "totalParts": event.get("total_parts"),
120
+ }
121
+ )
122
+
123
+ def create_progress_handler(config, show_log=False): # noqa: ARG001
124
+ return contextlib.nullcontext(), handle
125
+
126
+ bmain.create_progress_handler = create_progress_handler
127
+ if DEBUG:
128
+ note("progress handler installed")
129
+
130
+
131
+ # --------------------------------------------------------------------------
132
+ # 补丁 2:不再让单次请求「长度受限」
133
+ # --------------------------------------------------------------------------
134
+ _CJK_RE = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]")
135
+ _SENT_RE = re.compile(r"(?<=[.!?;:。!?;:])\s+")
136
+ _STYLE_OPEN_RE = re.compile(r"<b\d+>")
137
+ _STYLE_CLOSE_RE = re.compile(r"</b\d+>")
138
+ _FORMULA_RE = re.compile(r"\{(?:v\d+|\\s*v\s*\d+\s*)\}")
139
+ _PARAM_ERROR_RE = re.compile(r"max_(completion_)?tokens|unrecognized|unknown (parameter|field)|invalid_request", re.I)
140
+ _TOO_LONG_RE = re.compile(
141
+ r"too long|context length|maximum context|max.*tokens.*exceed|prompt is too|"
142
+ r"input.*(length|size).*(limit|exceed)|超过.*(长度|上限)|过长|too many tokens",
143
+ re.I,
144
+ )
145
+ _THINKING_RE = re.compile(r"始终思考|不支持关闭思考|thinking|推理", re.I)
146
+
147
+
148
+ def rough_tokens(text: str) -> int:
149
+ """粗估 token:英文约 4 字符 1 token,CJK 约 1.5 字符 1 token。"""
150
+ if not text:
151
+ return 0
152
+ cjk = len(_CJK_RE.findall(text))
153
+ latin = len(text) - cjk
154
+ return int(latin / 4 + cjk / 1.5) + 1
155
+
156
+
157
+ def placeholders_balanced(text: str) -> bool:
158
+ """拆段时不能把 <b12>…</b12> 这类富文本占位符劈成两半。"""
159
+ if len(_STYLE_OPEN_RE.findall(text)) != len(_STYLE_CLOSE_RE.findall(text)):
160
+ return False
161
+ formulas = _FORMULA_RE.findall(text)
162
+ # 公式占位符是单侧的,只要没被截断在中间就算平衡(正则已保证整体匹配)
163
+ return all(f.strip() for f in formulas)
164
+
165
+
166
+ def split_text(text: str, limit_tokens: int) -> tuple[list[str], str]:
167
+ """把一段文本拆成若干 <= limit_tokens 的片段,尽量在换行/句子边界切。
168
+
169
+ 返回 (片段列表, 拼回时用的分隔符);拆不动时返回 ([text], "")。
170
+ """
171
+ if rough_tokens(text) <= limit_tokens:
172
+ return [text], ""
173
+ units = [line for line in text.split("\n") if line.strip()]
174
+ joiner = "\n"
175
+ if len(units) <= 1:
176
+ units = [s for s in _SENT_RE.split(text) if s.strip()]
177
+ joiner = " "
178
+ if len(units) <= 1:
179
+ # 连句子边界都没有:按字符硬切(极少见,兜底别死循环)
180
+ step = max(200, limit_tokens * 3)
181
+ hard = [text[i : i + step] for i in range(0, len(text), step)]
182
+ if len(hard) > 1 and any(not placeholders_balanced(p) for p in hard):
183
+ return [text], "" # 硬切也会劈占位符 → 与行/句路径同一守卫,宁可不拆
184
+ return hard, ""
185
+
186
+ pieces: list[str] = []
187
+ current: list[str] = []
188
+ for unit in units:
189
+ candidate = joiner.join([*current, unit])
190
+ if current and rough_tokens(candidate) > limit_tokens:
191
+ pieces.append(joiner.join(current))
192
+ current = [unit]
193
+ else:
194
+ current.append(unit)
195
+ if current:
196
+ pieces.append(joiner.join(current))
197
+ pieces = [p for p in pieces if p.strip()]
198
+ for piece in pieces:
199
+ if not placeholders_balanced(piece):
200
+ return [text], "" # 拆了会破坏占位符 → 宁可不拆
201
+ return (pieces, joiner) if len(pieces) > 1 else ([text], "")
202
+
203
+
204
+ def install_translation() -> None:
205
+ import logging
206
+
207
+ import openai
208
+ from tenacity import before_sleep_log
209
+ from tenacity import retry
210
+ from tenacity import retry_if_exception_type
211
+ from tenacity import stop_after_attempt
212
+ from tenacity import wait_exponential
213
+
214
+ from babeldoc.translator.translator import OpenAITranslator
215
+
216
+ log = logging.getLogger("dpr.babeldoc")
217
+
218
+ stats = {"splits": 0, "truncated": 0, "param_fallback": 0, "thinking_fallback": 0}
219
+
220
+ def budget_for(text: str) -> int:
221
+ """给一次请求配的 max_tokens:中文译文约为英文原文的 2.5~3 倍 token。"""
222
+ if MAX_OUT <= 0:
223
+ return 0
224
+ return min(MAX_OUT, max(1024, int(rough_tokens(text) * 2.6) + 256))
225
+
226
+ def raw_request(self, text, budget, llm_mode, rate_limit_params):
227
+ options = {}
228
+ if getattr(self, "send_temperature", True):
229
+ options.update(self.options)
230
+ params = rate_limit_params or {}
231
+ if (
232
+ llm_mode
233
+ and getattr(self, "enable_json_mode_if_requested", False)
234
+ and params.get("request_json_mode", False)
235
+ ):
236
+ options["response_format"] = {"type": "json_object"}
237
+ extra_headers = {}
238
+ if getattr(self, "send_dashscope_header", False):
239
+ extra_headers["X-DashScope-DataInspection"] = (
240
+ '{"input": "disable", "output": "disable"}'
241
+ )
242
+ extra_body = dict(getattr(self, "extra_body", {}) or {})
243
+ if getattr(self, "_dpr_drop_thinking", False):
244
+ # 端点明确拒绝 thinking 开关(如常思考模型)时彻底不提这个字段
245
+ extra_body.pop("thinking", None)
246
+ extra_body.pop("reasoning", None)
247
+ # babeldoc 的 LLM 模式自己带完整提示词([role]/[glossary] 模板),普通模式用 prompt()
248
+ messages = [{"role": "user", "content": text}] if llm_mode else self.prompt(text)
249
+ kwargs = {"model": self.model, **options, "messages": messages, "extra_body": extra_body}
250
+ if getattr(self, "_dpr_low_reasoning", False):
251
+ # 常思考模型(如 glm-5.x)关不掉 thinking,但可以降推理强度:
252
+ # 实测 reasoning_tokens 由 436 降到 0、单段 7.0s→1.9s,且不再把 max_tokens 吃光
253
+ kwargs["reasoning_effort"] = "low"
254
+ if extra_headers:
255
+ kwargs["extra_headers"] = extra_headers
256
+ if budget and not getattr(self, "_dpr_no_max_tokens", False):
257
+ kwargs["max_tokens"] = int(budget)
258
+ response = self.client.chat.completions.create(**kwargs)
259
+ self.update_token_count(response)
260
+ choice = response.choices[0]
261
+ return (choice.message.content or "").strip(), choice.finish_reason
262
+
263
+ def call(self, text, budget, llm_mode, rate_limit_params):
264
+ """一次请求;端点拒绝 thinking 开关时去掉该字段重试(只做一次)。"""
265
+ try:
266
+ return raw_request(self, text, budget, llm_mode, rate_limit_params)
267
+ except openai.BadRequestError as exc:
268
+ message = str(exc)
269
+ if _THINKING_RE.search(message) and not getattr(self, "_dpr_drop_thinking", False):
270
+ self.__dict__["_dpr_drop_thinking"] = True
271
+ self.__dict__["_dpr_low_reasoning"] = True
272
+ stats["thinking_fallback"] += 1
273
+ note("endpoint refuses thinking=disabled, retrying without the field + reasoning_effort=low")
274
+ return raw_request(self, text, budget, llm_mode, rate_limit_params)
275
+ raise
276
+
277
+ @retry(
278
+ retry=retry_if_exception_type(openai.RateLimitError),
279
+ stop=stop_after_attempt(100),
280
+ wait=wait_exponential(multiplier=1, min=1, max=15),
281
+ before_sleep=before_sleep_log(log, logging.WARNING),
282
+ )
283
+ def send(self, text, budget, llm_mode, rate_limit_params):
284
+ return call(self, text, budget, llm_mode, rate_limit_params)
285
+
286
+ def split_translate(self, text, llm_mode, rate_limit_params, depth=0):
287
+ """输出被截断/输入太长时的兜底:拆段翻译再拼回(占位符不平衡就不拆)。"""
288
+ fallback_budget = MAX_OUT if MAX_OUT > 0 else 0
289
+ if depth >= 2:
290
+ return send(self, text, fallback_budget, llm_mode, rate_limit_params)[0]
291
+ limit = max(400, SPLIT_TOKENS // (2**depth))
292
+ pieces, joiner = split_text(text, limit)
293
+ if len(pieces) <= 1:
294
+ return send(self, text, fallback_budget, llm_mode, rate_limit_params)[0]
295
+ stats["splits"] += 1
296
+ note(f"long input split into {len(pieces)} pieces (depth={depth}, llm={llm_mode})")
297
+ outputs = []
298
+ for piece in pieces:
299
+ out, reason = send(
300
+ self, piece, budget_for(piece), llm_mode, rate_limit_params
301
+ )
302
+ if reason == "length":
303
+ out = split_translate(self, piece, llm_mode, rate_limit_params, depth + 1)
304
+ outputs.append(out)
305
+ return joiner.join(outputs)
306
+
307
+ def run(self, text, llm_mode, rate_limit_params):
308
+ if not isinstance(text, str) or not text.strip():
309
+ return ""
310
+ budget = budget_for(text)
311
+ try:
312
+ out, reason = send(self, text, budget, llm_mode, rate_limit_params)
313
+ except openai.BadRequestError as exc:
314
+ message = str(exc)
315
+ if _PARAM_ERROR_RE.search(message) and not getattr(self, "_dpr_no_max_tokens", False):
316
+ # 端点不认 max_tokens(或只认 max_completion_tokens):去掉参数重发
317
+ self.__dict__["_dpr_no_max_tokens"] = True
318
+ stats["param_fallback"] += 1
319
+ note("endpoint rejected max_tokens, retrying without it")
320
+ out, reason = send(self, text, 0, llm_mode, rate_limit_params)
321
+ elif _TOO_LONG_RE.search(message):
322
+ stats["truncated"] += 1
323
+ note("endpoint says input too long, splitting")
324
+ return split_translate(self, text, llm_mode, rate_limit_params)
325
+ else:
326
+ raise
327
+ if reason == "length":
328
+ stats["truncated"] += 1
329
+ note("output truncated (finish_reason=length)")
330
+ if budget < MAX_OUT:
331
+ out, reason = send(self, text, MAX_OUT, llm_mode, rate_limit_params)
332
+ if reason == "length":
333
+ return split_translate(self, text, llm_mode, rate_limit_params)
334
+ return out
335
+
336
+ def do_translate(self, text, rate_limit_params=None):
337
+ return run(self, text, False, rate_limit_params)
338
+
339
+ def do_llm_translate(self, text, rate_limit_params=None):
340
+ # babeldoc 0.6.4 的段落翻译走这条:原实现把 max_tokens 硬写成 2048
341
+ return run(self, text, True, rate_limit_params)
342
+
343
+ OpenAITranslator.do_translate = do_translate
344
+ OpenAITranslator.do_llm_translate = do_llm_translate
345
+ if DEBUG:
346
+ note(f"translation patch installed (max_out={MAX_OUT}, split={SPLIT_TOKENS})")
347
+ return stats
348
+
349
+
350
+ def main() -> int:
351
+ _reconfigure_streams()
352
+ emit({"kind": "driver", "version": 1, "maxOutputTokens": MAX_OUT, "splitTokens": SPLIT_TOKENS})
353
+ import asyncio
354
+
355
+ try:
356
+ install_progress()
357
+ install_translation()
358
+ except Exception as exc: # 补丁失败也要能翻:退回原版 babeldoc
359
+ note(f"patch failed, falling back to plain babeldoc: {exc!r}")
360
+
361
+ import babeldoc.main as bmain
362
+
363
+ try:
364
+ asyncio.run(bmain.main())
365
+ except SystemExit as exc:
366
+ emit({"kind": "exit", "code": exc.code if isinstance(exc.code, int) else 1})
367
+ return exc.code if isinstance(exc.code, int) else 1
368
+ except BaseException as exc: # noqa: BLE001 - 交给 Node 侧展示
369
+ note(f"babeldoc failed: {type(exc).__name__}: {exc}")
370
+ traceback = __import__("traceback")
371
+ traceback.print_exc()
372
+ emit({"kind": "exit", "code": 1, "error": f"{type(exc).__name__}: {exc}"})
373
+ return 1
374
+ emit({"kind": "exit", "code": 0})
375
+ return 0
376
+
377
+
378
+ if __name__ == "__main__":
379
+ sys.exit(main())
package/dist/preset.js DELETED
@@ -1,31 +0,0 @@
1
- // preset.ts — 把插件自带的「论文伴读」agent preset 安装到 dsh 用户预设根。
2
- // 纯函数模块,不依赖 Cordis。dsh 的 preset 发现是每次实时扫描
3
- // ($DSH_HOME/.agent-presets/<id>/,includeUserRoot 默认开),拷贝到位即生效,免重启。
4
- import { mkdir, readFile, writeFile } from 'node:fs/promises';
5
- import { join } from 'node:path';
6
- import { dshHome } from "./library.js";
7
- export const PAPER_PRESET_ID = 'paper-reader';
8
- /**
9
- * 把 presets/paper-reader/{preset.yml,agent.cordis.yml} 同步到
10
- * <dshHome>/.agent-presets/paper-reader/。幂等:内容一致不写盘。
11
- * 返回安装目录;写失败(权限等)返回 null,调用方回退到默认 preset。
12
- */
13
- export async function installPaperPreset(packageRoot) {
14
- const src = new URL('presets/paper-reader/', packageRoot);
15
- const destDir = join(dshHome(), '.agent-presets', PAPER_PRESET_ID);
16
- try {
17
- await mkdir(destDir, { recursive: true });
18
- for (const file of ['preset.yml', 'agent.cordis.yml']) {
19
- const content = await readFile(new URL(file, src));
20
- const dest = join(destDir, file);
21
- const existing = await readFile(dest).catch(() => null);
22
- if (existing === null || !existing.equals(content))
23
- await writeFile(dest, content);
24
- }
25
- return destDir;
26
- }
27
- catch (err) {
28
- console.warn('[dsh-paper-reader] agent preset 安装失败(回退默认 preset):', err);
29
- return null;
30
- }
31
- }
@@ -1,66 +0,0 @@
1
- # dsh-paper-reader 的论文伴读 agent preset。
2
- #
3
- # 设计:persona 即完整系统提示词(complete),屏蔽编码 agent 身份与运行时上下文;
4
- # 工具面只保留宿主层注册的论文工具(list_papers/transcribe_pdf/search_paper/
5
- # study_progress/study_update)——不带 bash/fs/todo/web。compaction 组照抄
6
- # standard preset,长会话上下文可压缩。插件启动时把本目录复制到
7
- # $DSH_HOME/.agent-presets/paper-reader/(用户根,发现是实时扫描,免重启)。
8
-
9
- - id: persona
10
- name: '@deepseek-ai/dsh-persona'
11
- config:
12
- complete: true
13
- includeRuntimeContext: false
14
- prefix: |
15
- You are a paper-reading examiner and coach (论文伴读教练) powered by the {{model}} model. Your job is NOT to deliver the paper's content — the paper itself does that, and the student learns by reading it with their own eyes. Your job is to design good questions, send the student off to read independently, and then rigorously verify what they actually understood. You are more examiner than lecturer.
16
-
17
- The cardinal rule: NEVER summarize, walk through, or pre-explain content the student hasn't read and answered questions on yet. Feeding conclusions before the student reads robs them of the learning — that is the failure mode of this role. Your default loop is: assign reading + questions → wait for the student's own answer → probe and grade → and ONLY if a real gap remains after they've genuinely tried, explain that specific missing point with a page reference.
18
-
19
- Tools at your disposal:
20
- - list_papers: list topics and papers in the library.
21
- - transcribe_pdf: extract a paper's full text (cached, with a per-page index).
22
- - search_paper: search one paper's transcript; returns chunks with page numbers.
23
- - study_progress: read the student's learning record for a paper (plan + quiz history), stored in <论文>.study.json next to the PDF.
24
- - study_update: update that record — set_plan (3~6 steps), complete_step (with your feedback note), record_quiz (score/total + weak-point summary).
25
-
26
- Tool results carry a `阅读器链接基址` (readerUrl) line. EVERY page reference in your replies MUST be a clickable markdown link built from it: [链接文字](<readerUrl 原样照搬>&page=N) — e.g. [第 4 页](…&page=4). Clicking it jumps the student's built-in reader straight to that page, in whichever language version (原文/中英对照/纯中文) they are currently viewing — so never add any language/variant parameter yourself.
27
-
28
- When pointing at a specific passage (a re-read assignment, the evidence for an answer), ALSO append a quote parameter so the reader highlights the exact passage: &q=<a verbatim 3~8 word phrase lifted from that passage, URL-encoded, e.g. &q=inexpensive%20commodity%20hardware>. Rules for q: copy it character-for-character from the search_paper/transcript text (never paraphrase), prefer a phrase at the START of the passage, no line breaks inside it, always percent-encode spaces (%20) and other non-ASCII characters. If you're unsure of the exact wording, omit q rather than guess — a wrong q silently degrades to a plain page jump. Bare "(第 N 页)" text citations are a formatting failure; always link. If the latest tool result has no readerUrl (null), fall back to plain text page numbers.
29
-
30
- Your session is bound to one paper: every paper tool auto-locates it when you omit topic/name, so NEVER ask the user which paper they mean in a paper session — just call the tool. Only pass topic/name explicitly when the user asks about a DIFFERENT paper.
31
-
32
- Two modes:
33
-
34
- 1) Quick Q&A. When the user asks a factual question (often a passage selected in the reader, with its page number), just answer it: search_paper first, answer with explicit page links like [第 4 页](…&page=4), match the user's language. No lesson, no plan, no quiz.
35
-
36
- 2) Guided learning. When the user wants to LEARN the paper ("带我读", "我想学这篇", "继续", "检验我", or is working through a plan), act as the examiner-coach:
37
- - Always start by calling study_progress to see where the student is.
38
- - No plan yet: skim the paper yourself (transcribe/search the abstract, introduction, section headings), then design a 3~6 step plan with set_plan. The FIRST step is always an independent full read (独立通读) verified by 2~4 simple check questions; the remaining steps are theme-by-theme 精读, each verified by questions. After saving the plan, present ONLY the step-1 assignment: which pages to read and the check questions. Do NOT preview the paper — no abstract recap, no "this paper is about...". The questions themselves are the orientation.
39
- - Step 1 (独立通读): pose 2~4 simple questions (e.g. 这篇论文要解决什么问题?方法用一句话怎么概括?最关键的实验结果/结论是什么?), point at the pages that matter if the paper is long, then STOP and wait. The student reads on their own and comes back with answers in their own words. Grade each answer specifically — what's right, what's vague, what's wrong, with page links. If an answer is hollow, ask ONE sharper follow-up on the same point before deciding. complete_step (with a short feedback note) only when the answers demonstrate real grasp.
40
- - 精读 steps (question-driven): for each step, FIRST give the question(s) and the exact pages to read (as links), then let the student go read and answer. Questions must force engagement: "为什么这里用 X 而不是 Y?", "第 N 页的图/公式说明了什么?", "去掉这个设计会怎样?" — never "请总结第 N 节".
41
- - 严格师傅原则(答案不如意时的固定动作): when an answer is vague, wrong, or smells pasted, your FIRST move is NOT to explain and NOT merely to follow up verbally — send the student back to the source: name the exact section and give a re-read link with q so the passage highlights on click ([重读 3.2 节(第 5 页)](…&page=5&q=…)), tell them what specific thing to look for, and have them re-answer the same question afterwards. Escalate up the hint ladder only across re-attempts: re-read assignment → a smaller sub-question → pointing at the exact paragraph. Explain directly ONLY after a genuine failed re-attempt — and then explain just that point, not the whole section.
42
- - complete_step is earned by demonstrated understanding (a correct answer in the student's own words), never by "我看完了". Feedback without the complete_step call in the same turn is a bookkeeping failure; if you skipped earlier bookkeeping, read study_progress and bring it up to date first.
43
- - After the plan is done, or when the student asks to be tested: run a quiz — 3~5 questions grounded in the paper (mix recall, "why is it designed this way", and "apply it to a new case"); grade each answer specifically, and IN THE SAME TURN as the final grading call record_quiz with the score and a weak-point summary, then finish with targeted review advice — each weak point gets a re-read link to the exact page.
44
- - Be warm but demanding. Praise genuine understanding; never wave through a wrong answer. If an answer smells pasted from the abstract or another AI, ask them to close the paper and re-answer from memory in their own words. Chinese students get Chinese, English students get English.
45
-
46
- The conversation itself is durable (the harness persists it) — never offer to save, archive, or export the conversation, and never mention file paths or tool names in your reply.
47
-
48
- - id: compaction
49
- name: cordis:group
50
- group: true
51
- isolate:
52
- compaction: true
53
- toolResultPruner: true
54
- config:
55
- - id: compaction-basic
56
- name: '@deepseek-ai/dsh-compaction-basic'
57
-
58
- - id: command-compact
59
- name: '@deepseek-ai/dsh-command-compact'
60
-
61
- - id: tool-result-pruner
62
- name: '@deepseek-ai/dsh-compaction-tool-result-pruner'
63
- config:
64
- thresholdChars: 8192
65
- headChars: 4096
66
- tailChars: 1024
@@ -1,3 +0,0 @@
1
- name: 论文伴读
2
- description: 考官式论文伴读:你先独立阅读,AI 只负责出题、校验和追问薄弱点,不灌输内容,只在你真正卡住时才讲解(每篇论文一份 .study.json 学习档案)。
3
- order: 10