deep-read-summarize 0.3.6 → 0.3.9

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/workflow.js CHANGED
@@ -1,77 +1,90 @@
1
- // ============================================================================
2
- // deep-read-summarize — Deep reading & summarization workflow for DSH
3
- // Version: 3.0.0
4
- // ============================================================================
5
- // 【用法】meta → workflow meta;script → workflow script;
6
- // args: { "input": "<url|path>", "type": "auto", "options": { "minWords": 2500, "fastMode": false, "maxChunks": 4, "transcribe": true, "requireCitations": true, "includeTimestamps": false, "cache": true, "outputDir": "./output", "tempDir": "./.tmp" } }
7
- // ============================================================================
8
-
9
- const meta = {
10
- "name": "deep-read-summarize",
11
- "description": "Deep reading & summarization of books/papers/videos/web (v3.0)",
12
- "whenToUse": "User provides a book, paper, video link or web page and wants a deep-read summary saved to Obsidian",
13
- "phases": [
14
- {
15
- "title": "解析器选择",
16
- "detail": "按类型选择解析器插件"
17
- },
18
- {
19
- "title": "获取与分块",
20
- "detail": "Parser fetches content, writes temp file, builds chunk plan"
21
- },
22
- {
23
- "title": "并行精读",
24
- "detail": "N subagents deep-read chunks in parallel (Map)"
25
- },
26
- {
27
- "title": "汇总成稿",
28
- "detail": "Merge into final note (Reduce) with embedded self-check"
29
- },
30
- {
31
- "title": "质量校验",
32
- "detail": "Optional QC loop with retries"
33
- }
34
- ]
35
- };
36
-
37
- // ===== script(复制到 workflow 工具的 script 参数)=====
38
- const RAW_SCRIPT = "// ========== deep-read-summarize v3.0 ==========\n// 3 波次:解析器获取分块 → 并行精读 → 成稿+质量校验\n// 特性:解析器插件化 / 失败纪律(fatal vs 降级) / 幂等 / 成本控制\n\n// ---------- 0. 配置校验(fatal 级错误:必须终止) ----------\nconst input = (args && args.input || \"\").trim();\nif (!input) throw new Error(\"[FATAL] args.input 缺失:请输入内容链接或文件路径\");\nconst forcedType = ((args && args.type) || \"auto\").toLowerCase();\nif ([\"auto\",\"book\",\"paper\",\"video\",\"web\"].indexOf(forcedType) === -1)\n throw new Error(\"[FATAL] args.type 非法:必须为 auto|book|paper|video|web\");\nconst options = (args && args.options) || {};\nconst minWords = options.minWords || 2500;\nconst fastMode = !!options.fastMode;\nconst maxChunks = Math.max(1, Math.min(options.maxChunks || 4, 12));\nconst requireCitations = options.requireCitations !== false;\nconst includeTimestamps = !!options.includeTimestamps;\nconst maxRetries = options.maxRetries || 0;\nconst cacheEnabled = options.cache !== false;\nconst outputDir = options.outputDir || \"./output\";\nconst tempDir = options.tempDir || \"./.tmp\";\nconst tempFile = tempDir.replace(/[\\/]+$/, \"\") + \"/input.txt\";\n\n// ---------- 0.5 幂等检查:输入指纹缓存 ----------\nlet cacheHit = false;\nif (cacheEnabled && Array.isArray(args._processedKeys)) {\n const fpKey = input.trim().slice(0, 300);\n cacheHit = args._processedKeys.indexOf(fpKey) !== -1;\n if (cacheHit) log(\"幂等命中:该输入已处理过,跳过\");\n}\nif (cacheHit) {\n return { ok: true, cached: true, kind: forcedType, title: (args && args.title) || \"cached\", filePath: \"\", chunksCount: 0, fastMode: fastMode, qualityPassed: true, qualityIssues: [], failedChunks: 0, note: \"\" };\n}\n\n// ---------- 1. 解析器选择(由 args._parsers 注入) ----------\nphase(\"解析器选择\");\nconst parsers = args._parsers || {};\nconst kindNames = { book: \"书籍\", paper: \"学术论文\", video: \"视频\", web: \"网页/文章\" };\nconst kindFocus = {\n book: \"按章节主题展开核心论点、论证、关键例子、章节间关系,收集关键概念与可引用原文(含页码/章节)\",\n paper: \"四维精读:1)研究问题与方法 2)结论与贡献 3)局限与批判 4)与同类工作比较;收集术语与可引用原文(含章节/段落)\",\n video: \"按主题脉络组织,提取核心论点、证据、例子、可操作建议,收集关键概念与主讲人原话\" + (includeTimestamps ? \"(含时间戳定位)\" : \"(不标时间戳)\"),\n web: \"提取核心论点、结构拆解、关键概念、可引用原文\"\n};\n\n// ---------- 2. 波次1:解析器获取 + 分块 ----------\nphase(\"获取与分块\");\nconst fetchPrompt = (parsers[forcedType !== \"auto\" ? forcedType : \"web\"] || parsers.web || { buildPrompt: function() { return [\"未知解析器\"]; } })\n .buildPrompt(input, { tempDir: tempDir, tempFile: tempFile, maxChunks: maxChunks, transcribe: options.transcribe !== false });\nconst fetchSchema = {\n type: \"object\",\n properties: {\n kind: { type: \"string\" }, saved: { type: \"boolean\" }, message: { type: \"string\" }, totalLines: { type: \"number\" },\n metadata: { type: \"object\", properties: { title: { type: \"string\" }, author: { type: \"string\" }, year: { type: \"string\" }, language: { type: \"string\" } }, required: [], additionalProperties: true },\n chunkPlan: {\n type: \"array\",\n items: { type: \"object\", properties: { id: { type: \"number\" }, topic: { type: \"string\" }, startLine: { type: \"number\" }, endLine: { type: \"number\" } }, required: [\"id\",\"topic\",\"startLine\",\"endLine\"], additionalProperties: false }\n }\n },\n required: [\"saved\"], additionalProperties: false\n};\n\nconst fetched = await agent(fetchPrompt, { schema: fetchSchema, label: \"获取+分块\", phase: \"获取与分块\" });\n\n// 失败纪律:内容获取失败 = 可降级错误(返回失败结果,不抛 fatal)\nif (!fetched || !fetched.saved) {\n return { ok: false, stage: \"fetch\", fatal: false, message: (fetched && fetched.message) || \"获取失败(可降级:检查输入或手动提供文本)\" };\n}\nlet kind = (fetched.kind && forcedType === \"auto\") ? fetched.kind : forcedType;\nconst chunkPlan = (fetched && fetched.chunkPlan) || [];\nif (chunkPlan.length === 0) return { ok: false, stage: \"fetch\", fatal: false, message: \"分块计划为空\" };\nconst metadata = (fetched && fetched.metadata) || {};\nconst textSource = (metadata && metadata.textSource) || \"unknown\";\nconst srcLabels = { desc: \"视频简介/desc\", subtitle: \"平台字幕\", transcription: \"完整语音转写\", manual: \"用户提供转写文本\" };\nconst srcLabel = srcLabels[textSource] || textSource;\nlog(\"[source] \" + textSource + \" -> \" + srcLabel);\nlog(\"类型:\" + kind + \" 行数:\" + fetched.totalLines + \" 块数:\" + chunkPlan.length);\n\n// ---------- 3. 波次2:并行精读(Map) ----------\nphase(\"并行精读\");\nconst chunkPrompts = chunkPlan.map(function (c) {\n return [\n \"请深度精读以下内容块,输出结构化精读笔记。\",\n \"内容类型:\" + (kindNames[kind] || kind) + \" | 本块主题:\" + c.topic,\n \"精读侧重:\" + (kindFocus[kind] || kindFocus.web),\n \"用 read 工具读取 \" + tempFile + \" 第 \" + c.startLine + \" 到 \" + c.endLine + \" 行(offset=\" + c.startLine + \", limit=\" + (c.endLine - c.startLine + 1) + \"),然后输出:\",\n \"## 本块主题:\" + c.topic,\n \"### 要点(详细展开,保留数据/例子/论证)\",\n \"### 关键概念(术语+解释)\",\n \"### 关键引用(最多2句原文+位置)\" + (requireCitations ? \",必须标注页码/章节/段落位置\" : \"\"),\n \"### 批判观察(如有)\"\n ].join(\"\\n\");\n});\n\nconst reads = [];\nconst readBatch = 3;\nfor (let bi = 0; bi < chunkPrompts.length; bi += readBatch) {\n const batch = chunkPrompts.slice(bi, bi + readBatch);\n const batchReads = await parallel(batch.map(function (p) {\n return function () { return agent(p, { label: \"精读块\", phase: \"并行精读\" }); };\n }));\n for (let k = 0; k < batchReads.length; k++) reads.push(batchReads[k]);\n}\nconst validReads = reads.filter(function (r) { return r && r.trim && r.trim().length > 0; });\n\n// 失败纪律:某块精读失败 = 可降级(跳过该块,标记缺口继续)\nconst failedChunks = chunkPlan.length - validReads.length;\nif (validReads.length === 0) return { ok: false, stage: \"read\", fatal: false, message: \"所有分块精读均失败\" };\nif (failedChunks > 0) log(\"警告:\" + failedChunks + \" 块精读失败,标记缺口继续成稿\");\nlog(\"精读完成:\" + validReads.length + \"/\" + chunkPlan.length);\n\n// ---------- 4. 波次3:成稿 + 内嵌质量自检(Reduce) ----------\nphase(\"汇总成稿\");\nconst today = new Date().toISOString().slice(0, 10);\nconst finalTitle = metadata.title || \"未命名内容\";\nconst safeTitle = finalTitle.replace(/[\\\\/:*?\"<>|]/g, \" \").trim();\nconst mdPath = outputDir.replace(/\\\\$/, \"\") + \"/\" + safeTitle + \".md\";\n\nconst extraSections = fastMode ? [] : [\n \"\", \"## 5. 批判性分析(论证强处/弱处/可质疑之处)\", \"\",\n \"## 6. 个人思考与应用(与已有知识联系、如何应用、行动要点)\", \"\",\n \"## 7. 延伸阅读(相关主题/作者其他作品/参考文献)\", \"\"\n];\n\nconst draftPrompt = [\n \"将以下多块精读结果整合为完整 Obsidian 精读笔记,只输出 Markdown(含 YAML frontmatter)。\",\n \"模板:\", \"---\",\n 'title: \"《' + finalTitle + '》深度精读笔记\"',\n \"aliases: [\" + JSON.stringify(finalTitle) + \"]\",\n \"author: \" + (metadata.author || \"\"),\n \"year: \" + (metadata.year || \"\"),\n \"type: \" + kind,\n \"url: \" + (metadata.url || input),\n \"tags: [精读, \" + (kindNames[kind] || kind) + \"]\",\n \"created: \" + today,\n \"status: 已完成\",\n \"---\",\n \"# 《\" + finalTitle + \"》深度精读笔记\", \"\",\n \"> 一句话核心概括。\", \"\",\n \"## 1. 概述(约500字:主题/背景/核心问题/总体结论)\", \"\",\n \"## 2. 结构拆解(按主题组织,含详细要点;关键结论标注原文出处)\", \"\",\n \"## 3. 关键概念与术语表(表格)\", \"\",\n \"## 4. 关键引用(仅关键结论\" + (requireCitations ? \",必须标注页码/章节/段落\" : \"\") + \")\",\n].concat(extraSections, [\n \"---\",\n \"*笔记整理于 \" + today + \"*\", \"\",\n \"硬性要求:总篇幅≥\" + minWords + \"字;语言与原文一致;术语统一;引用必须真实;视频\" + (includeTimestamps ? \"标注时间戳\" : \"不标注时间戳\") + \"。\",\n \"输出前自检:1)覆盖所有块 2)frontmatter完整 3)各小节齐全 4)引用真实 5)篇幅达标 6)语言一致。\",\n \"\",\n \"各块精读结果:\",\n validReads.map(function (r, i) { return \"\\\\n===== 块 \" + (i + 1) + \" =====\\\\n\" + r; }).join(\"\\\\n\")\n]).join(\"\\n\");\n\nlet draft = await agent(draftPrompt, { label: \"汇总成稿\", phase: \"汇总成稿\" });\nif (!draft || !draft.trim) return { ok: false, stage: \"draft\", fatal: false, message: \"成稿失败\" };\n\n// ---------- 5. 质量校验(轻量重试) ----------\nphase(\"质量校验\");\nlet verified = draft;\nlet passed = false;\nlet issues = [];\nfor (let round = 0; round <= maxRetries; round++) {\n const checkPrompt = [\n \"请对总结笔记做质量校验,逐项检查并输出 JSON:\",\n \"1.coverage 2.citationsReal 3.terminologyConsistent 4.formatComplete 5.lengthMet(≥\" + minWords + \"字) 6.languageConsistent\",\n \"输出:{ \\\"pass\\\": true/false, \\\"issues\\\": [\\\"问题\\\"] },只输出 JSON。\",\n \"笔记:\", verified\n ].join(\"\\n\");\n const checkSchema = { type: \"object\", properties: { pass: { type: \"boolean\" }, issues: { type: \"array\", items: { type: \"string\" } } }, required: [\"pass\",\"issues\"], additionalProperties: false };\n const check = await agent(checkPrompt, { schema: checkSchema, label: \"质量校验\", phase: \"质量校验\" });\n passed = !!(check && check.pass);\n issues = (check && check.issues) || [];\n log(\"校验:\" + (passed ? \"通过\" : \"发现问题 \" + issues.length + \" 条\"));\n if (passed) break;\n if (round < maxRetries) {\n const fixPrompt = [\n \"修正以下笔记以解决校验问题,输出完整修正版:\",\n issues.map(function (s) { return \"- \" + s; }).join(\"\\n\"),\n \"当前笔记:\", verified\n ].join(\"\\n\");\n verified = await agent(fixPrompt, { label: \"修正笔记\", phase: \"质量校验\" });\n }\n}\n\n// ---------- 结果 ----------\nreturn {\n ok: true, kind: kind, title: finalTitle,\n filePath: mdPath, chunksCount: chunkPlan.length, fastMode: fastMode,\n qualityPassed: passed, qualityIssues: issues,\n failedChunks: failedChunks,\n textSource: textSource,\n note: verified\n};";
39
-
40
- // ===== parsers 注册表(运行时注入,实现插件化)=====
41
- const parsers = require("./parsers");
42
- const promptImpl = require("./parsers/_prompt");
43
- const parserRegistry = parsers.registry;
44
-
45
- /**
46
- * 把四个内置解析器(buildPrompt)连同其依赖的 buildFetchPrompt 内联进
47
- * workflow script,使其自包含 —— DSH rc7 的 workflow 工具只把 args(JSON)
48
- * 暴露给脚本,不会注入 args._parsers;脚本必须在自身内部解析器可用。
49
- * 若宿主未来注入 args._parsers,优先使用宿主注入值(向后兼容)。
50
- */
51
- function buildSelfContainedScript() {
52
- const parserSource = (name) =>
53
- parserRegistry.parsers[name].buildPrompt
54
- .toString()
55
- // buildPrompt 闭包引用模块级 prompt(parsers/_prompt),内联后改指 __prompt
56
- .replace(/\bprompt\.buildFetchPrompt\b/g, "__prompt.buildFetchPrompt");
57
-
58
- const impl = [
59
- "const __prompt = { buildFetchPrompt: " + promptImpl.buildFetchPrompt.toString() + " };",
60
- "const __parsers = {",
61
- " book: { buildPrompt: " + parserSource("book") + " },",
62
- " paper: { buildPrompt: " + parserSource("paper") + " },",
63
- " video: { buildPrompt: " + parserSource("video") + " },",
64
- " web: { buildPrompt: " + parserSource("web") + " }",
65
- "};"
66
- ].join("\n");
67
-
68
- const marker = "const parsers = args._parsers || {};";
69
- if (!RAW_SCRIPT.includes(marker)) {
70
- throw new Error("workflow script marker not found: " + marker);
71
- }
72
- return RAW_SCRIPT.replace(marker, impl + "\nconst parsers = args._parsers || __parsers;");
73
- }
74
-
75
- const script = buildSelfContainedScript();
76
-
1
+ // ============================================================================
2
+ // deep-read-summarize — Deep reading & summarization workflow for DSH
3
+ // Version: 3.0.0
4
+ // ============================================================================
5
+ // 【用法】meta → workflow meta;script → workflow script;
6
+ // args: { "input": "<url|path>", "type": "auto", "options": { "minWords": 2500, "fastMode": false, "maxChunks": 4, "transcribe": true, "requireCitations": true, "includeTimestamps": false, "cache": true, "outputDir": "./output", "tempDir": "./.tmp" } }
7
+ // ============================================================================
8
+
9
+ const meta = {
10
+ "name": "deep-read-summarize",
11
+ "description": "Deep reading & summarization of books/papers/videos/web (v3.0)",
12
+ "whenToUse": "User provides a book, paper, video link or web page and wants a deep-read summary saved to Obsidian",
13
+ "phases": [
14
+ {
15
+ "title": "解析器选择",
16
+ "detail": "按类型选择解析器插件"
17
+ },
18
+ {
19
+ "title": "获取与分块",
20
+ "detail": "Parser fetches content, writes temp file, builds chunk plan"
21
+ },
22
+ {
23
+ "title": "并行精读",
24
+ "detail": "N subagents deep-read chunks in parallel (Map)"
25
+ },
26
+ {
27
+ "title": "汇总成稿",
28
+ "detail": "Merge into final note (Reduce) with embedded self-check"
29
+ },
30
+ {
31
+ "title": "质量校验",
32
+ "detail": "Optional QC loop with retries"
33
+ }
34
+ ]
35
+ };
36
+
37
+ // ===== script(复制到 workflow 工具的 script 参数)=====
38
+ const RAW_SCRIPT = "// ========== deep-read-summarize v3.0 ==========\n// 3 波次:解析器获取分块 → 并行精读 → 成稿+质量校验\n// 特性:解析器插件化 / 失败纪律(fatal vs 降级) / 成本控制(maxChunks 强制,块数=子代理数)\n\n// YAML 双引号标量:JSON.stringify 的转义规则是 YAML double-quoted 风格的子集,\n// 标题/作者里出现引号时不会再截断 frontmatter(旧版是裸拼 \"...\")。\nfunction yamlStr(v) { return JSON.stringify(v == null ? \"\" : String(v)); }\n\n// ---------- 0. 配置校验(fatal 级错误:必须终止) ----------\nconst input = (args && args.input || \"\").trim();\nconst forcedType = ((args && args.type) || \"auto\").toLowerCase();\nconst options = (args && args.options) || {};\nconst minWords = options.minWords || 2500;\nconst fastMode = !!options.fastMode;\nconst maxChunks = Math.max(1, Math.min(options.maxChunks || 4, 12));\nconst requireCitations = options.requireCitations !== false;\nconst includeTimestamps = !!options.includeTimestamps;\nconst maxRetries = options.maxRetries || 0;\nconst outputDir = options.outputDir || \"./output\";\nconst tempDir = options.tempDir || \"./.tmp\";\nconst tempFile = tempDir.replace(/[\\/]+$/, \"\") + \"/input.txt\";\nconst whisperModel = options.whisperModel || \"small\";\nconst transcribeLanguage = options.language || \"zh\";\nconst transcribeDevice = options.device || \"cpu\";\n\n// 幂等不在这里做:脚本沙箱没有文件系统,写不了指纹记录。\n// 需要幂等的调用方请用 lib/cache.js(fingerprint / hasProcessed / markProcessed)。\n\n// ---------- 1. 解析器表:构建时把解析器内联为 __parsers(自包含);\n// 宿主若注入 args._parsers 则优先使用 ----------\nconst parsers = args._parsers || {};\nconst parserNames = Object.keys(parsers);\n\n// 配置校验依赖解析器表,必须放在其后\nif (!input) throw new Error(\"[FATAL] args.input 缺失:请输入内容链接或文件路径\");\nif (parserNames.length === 0) throw new Error(\"[FATAL] 解析器表为空:脚本没有内联任何解析器\");\nif (forcedType !== \"auto\" && parserNames.indexOf(forcedType) === -1)\n throw new Error(\"[FATAL] args.type 非法:\" + forcedType + \"(可用:\" + [\"auto\"].concat(parserNames).join(\"|\") + \")\");\n\nphase(\"解析器选择\");\nconst kindNames = { book: \"书籍\", paper: \"学术论文\", video: \"视频\", web: \"网页/文章\" };\nconst kindFocus = {\n book: \"按章节主题展开核心论点、论证、关键例子、章节间关系,收集关键概念与可引用原文(含页码/章节)\",\n paper: \"四维精读:1)研究问题与方法 2)结论与贡献 3)局限与批判 4)与同类工作比较;收集术语与可引用原文(含章节/段落)\",\n video: \"按主题脉络组织,提取核心论点、证据、例子、可操作建议,收集关键概念与主讲人原话\" + (includeTimestamps ? \"(含时间戳定位)\" : \"(不标时间戳)\"),\n web: \"提取核心论点、结构拆解、关键概念、可引用原文\"\n};\n\n// ---------- 2. 波次1:解析器获取 + 分块 ----------\nphase(\"获取与分块\");\nconst fetchPrompt = (parsers[forcedType !== \"auto\" ? forcedType : \"web\"] || parsers.web || { buildPrompt: function() { return [\"未知解析器\"]; } })\n .buildPrompt(input, { tempDir: tempDir, tempFile: tempFile, maxChunks: maxChunks, transcribe: options.transcribe !== false, whisperModel: whisperModel, language: transcribeLanguage, device: transcribeDevice });\n// fetchSchema 由插件在构建时从 schemas/index.js 注入(单一真相,避免两份 schema 漂移)。\n\nconst fetched = await agent(fetchPrompt, { schema: fetchSchema, label: \"获取+分块\", phase: \"获取与分块\" });\n\n// 失败纪律:内容获取失败 = 可降级错误(返回失败结果,不抛 fatal)\nif (!fetched || !fetched.saved) {\n return { ok: false, stage: \"fetch\", fatal: false, message: (fetched && fetched.message) || \"获取失败(可降级:检查输入或手动提供文本)\" };\n}\n// 分块计划收敛:块数 = 子代理数,计划失控会顶穿 workflow 单次调用时限;\n// 同时挡掉倒置/越界的行号区间(原样透传会让 read 收到 limit<=0)。\nconst rawPlan = (fetched && fetched.chunkPlan) || [];\nif (rawPlan.length === 0) return { ok: false, stage: \"fetch\", fatal: false, message: \"分块计划为空\" };\nconst declaredLines = Math.floor(Number(fetched.totalLines) || 0);\nconst chunkPlan = [];\nfor (let i = 0; i < rawPlan.length && chunkPlan.length < maxChunks; i++) {\n const c = rawPlan[i] || {};\n const s = Math.floor(Number(c.startLine) || 0);\n const e = Math.floor(Number(c.endLine) || 0);\n if (s < 1 || e < s) continue;\n if (declaredLines > 0 && s > declaredLines) continue;\n chunkPlan.push({\n id: chunkPlan.length + 1,\n topic: String(c.topic || (\"块 \" + (chunkPlan.length + 1))),\n startLine: s,\n endLine: declaredLines > 0 ? Math.min(e, declaredLines) : e\n });\n}\nif (chunkPlan.length === 0) return { ok: false, stage: \"fetch\", fatal: false, message: \"分块计划无效:行号区间缺失或非法\" };\nif (chunkPlan.length < rawPlan.length) log(\"分块计划收敛:\" + rawPlan.length + \" -> \" + chunkPlan.length + \" 块(上限 \" + maxChunks + \")\");\n\n// 类型:auto 时只接受解析器表里真实存在的类型,否则退回回退解析器,\n// 避免 \"auto\" 这种非法值流进 frontmatter 的 type / tags。\nlet kind = forcedType;\nif (forcedType === \"auto\") {\n kind = (typeof fetched.kind === \"string\" && parserNames.indexOf(fetched.kind) !== -1)\n ? fetched.kind\n : (parserNames.indexOf(\"web\") !== -1 ? \"web\" : parserNames[0]);\n}\nconst metadata = (fetched && fetched.metadata) || {};\nconst textSource = (metadata && metadata.textSource) || \"unknown\";\nconst srcLabels = { desc: \"视频简介/desc\", subtitle: \"平台字幕\", transcription: \"完整语音转写\", manual: \"用户提供转写文本\" };\nconst srcLabel = srcLabels[textSource] || textSource;\nlog(\"[source] \" + textSource + \" -> \" + srcLabel);\nlog(\"类型:\" + kind + \" 行数:\" + fetched.totalLines + \" 块数:\" + chunkPlan.length);\n\n// ---------- 3. 波次2:并行精读(Map) ----------\nphase(\"并行精读\");\nconst chunkPrompts = chunkPlan.map(function (c) {\n return [\n \"请深度精读以下内容块,输出结构化精读笔记。\",\n \"内容类型:\" + (kindNames[kind] || kind) + \" | 本块主题:\" + c.topic,\n \"精读侧重:\" + (kindFocus[kind] || kindFocus.web),\n \"用 read 工具读取 \" + tempFile + \" 第 \" + c.startLine + \" 到 \" + c.endLine + \" 行(offset=\" + c.startLine + \", limit=\" + (c.endLine - c.startLine + 1) + \"),然后输出:\",\n \"## 本块主题:\" + c.topic,\n \"### 要点(详细展开,保留数据/例子/论证)\",\n \"### 关键概念(术语+解释)\",\n \"### 关键引用(最多2句原文+位置)\" + (requireCitations ? \",必须标注页码/章节/段落位置\" : \"\"),\n \"### 批判观察(如有)\"\n ].join(\"\\n\");\n});\n\nconst reads = [];\nconst readBatch = 3;\nfor (let bi = 0; bi < chunkPrompts.length; bi += readBatch) {\n const batch = chunkPrompts.slice(bi, bi + readBatch);\n const batchReads = await parallel(batch.map(function (p) {\n return function () { return agent(p, { label: \"精读块\", phase: \"并行精读\" }); };\n }));\n for (let k = 0; k < batchReads.length; k++) reads.push(batchReads[k]);\n}\nconst validReads = reads.filter(function (r) { return r && r.trim && r.trim().length > 0; });\n\n// 失败纪律:某块精读失败 = 可降级(跳过该块,标记缺口继续)\nconst failedChunks = chunkPlan.length - validReads.length;\nif (validReads.length === 0) return { ok: false, stage: \"read\", fatal: false, message: \"所有分块精读均失败\" };\nif (failedChunks > 0) log(\"警告:\" + failedChunks + \" 块精读失败,标记缺口继续成稿\");\nlog(\"精读完成:\" + validReads.length + \"/\" + chunkPlan.length);\n\n// ---------- 4. 波次3:成稿 + 内嵌质量自检(Reduce) ----------\nphase(\"汇总成稿\");\nconst today = new Date().toISOString().slice(0, 10);\n// 标题先折叠换行/制表与连续空白:否则会同时污染 .md 文件名和 frontmatter。\nconst finalTitle = String(metadata.title || \"\").replace(/[\\r\\n\\t]+/g, \" \").replace(/\\s+/g, \" \").trim() || \"未命名内容\";\n// 文件名清洗:去掉 Windows 非法字符;全部非法时兜底,避免写出 ./output/.md 这种隐藏文件。\nconst safeTitle = finalTitle.replace(/[\\\\/:*?\"<>|]/g, \" \").replace(/\\s+/g, \" \").trim() || \"未命名内容\";\nconst mdPath = outputDir.replace(/\\\\$/, \"\") + \"/\" + safeTitle + \".md\";\n\nconst extraSections = fastMode ? [] : [\n \"\", \"## 5. 批判性分析(论证强处/弱处/可质疑之处)\", \"\",\n \"## 6. 个人思考与应用(与已有知识联系、如何应用、行动要点)\", \"\",\n \"## 7. 延伸阅读(相关主题/作者其他作品/参考文献)\", \"\"\n];\n\nconst draftPrompt = [\n \"将以下多块精读结果整合为完整 Obsidian 精读笔记,只输出 Markdown(含 YAML frontmatter)。\",\n \"模板:\", \"---\",\n 'title: ' + yamlStr(\"《\" + finalTitle + \"》深度精读笔记\"),\n \"aliases: [\" + yamlStr(finalTitle) + \"]\",\n \"author: \" + yamlStr(metadata.author),\n \"year: \" + yamlStr(metadata.year),\n \"type: \" + yamlStr(kind),\n \"url: \" + yamlStr(metadata.url || input),\n \"tags: [精读, \" + (kindNames[kind] || kind) + \"]\",\n \"created: \" + today,\n \"status: 已完成\",\n \"---\",\n \"# 《\" + finalTitle + \"》深度精读笔记\", \"\",\n \"> 一句话核心概括。\", \"\",\n \"## 1. 概述(约500字:主题/背景/核心问题/总体结论)\", \"\",\n \"## 2. 结构拆解(按主题组织,含详细要点;关键结论标注原文出处)\", \"\",\n \"## 3. 关键概念与术语表(表格)\", \"\",\n \"## 4. 关键引用(仅关键结论\" + (requireCitations ? \",必须标注页码/章节/段落\" : \"\") + \")\",\n].concat(extraSections, [\n \"---\",\n \"*笔记整理于 \" + today + \"*\", \"\",\n \"硬性要求:总篇幅≥\" + minWords + \"字;语言与原文一致;术语统一;引用必须真实;视频\" + (includeTimestamps ? \"标注时间戳\" : \"不标注时间戳\") + \"。\",\n \"输出前自检:1)覆盖所有块 2)frontmatter完整 3)各小节齐全 4)引用真实 5)篇幅达标 6)语言一致。\",\n \"\",\n \"各块精读结果:\",\n validReads.map(function (r, i) { return \"\\\\n===== 块 \" + (i + 1) + \" =====\\\\n\" + r; }).join(\"\\\\n\")\n]).join(\"\\n\");\n\nlet draft = await agent(draftPrompt, { label: \"汇总成稿\", phase: \"汇总成稿\" });\nif (!draft || !draft.trim) return { ok: false, stage: \"draft\", fatal: false, message: \"成稿失败\" };\n\n// ---------- 5. 质量校验(轻量重试) ----------\nphase(\"质量校验\");\nlet verified = draft;\nlet passed = false;\nlet issues = [];\nfor (let round = 0; round <= maxRetries; round++) {\n const checkPrompt = [\n \"请对总结笔记做质量校验,逐项检查并输出 JSON:\",\n \"1.coverage 2.citationsReal 3.terminologyConsistent 4.formatComplete 5.lengthMet(≥\" + minWords + \"字) 6.languageConsistent\",\n \"输出:{ \\\"pass\\\": true/false, \\\"issues\\\": [\\\"问题\\\"] },只输出 JSON。\",\n \"笔记:\", verified\n ].join(\"\\n\");\n const checkSchema = { type: \"object\", properties: { pass: { type: \"boolean\" }, issues: { type: \"array\", items: { type: \"string\" } } }, required: [\"pass\",\"issues\"], additionalProperties: false };\n const check = await agent(checkPrompt, { schema: checkSchema, label: \"质量校验\", phase: \"质量校验\" });\n passed = !!(check && check.pass);\n issues = (check && check.issues) || [];\n log(\"校验:\" + (passed ? \"通过\" : \"发现问题 \" + issues.length + \" 条\"));\n if (passed) break;\n if (round < maxRetries) {\n const fixPrompt = [\n \"修正以下笔记以解决校验问题,输出完整修正版:\",\n issues.map(function (s) { return \"- \" + s; }).join(\"\\n\"),\n \"当前笔记:\", verified\n ].join(\"\\n\");\n verified = await agent(fixPrompt, { label: \"修正笔记\", phase: \"质量校验\" });\n }\n}\n\n// ---------- 结果 ----------\nreturn {\n ok: true, kind: kind, title: finalTitle,\n filePath: mdPath, chunksCount: chunkPlan.length, fastMode: fastMode,\n qualityPassed: passed, qualityIssues: issues,\n failedChunks: failedChunks,\n textSource: textSource,\n note: verified\n};";
39
+
40
+ // ===== parsers 注册表(运行时注入,实现插件化)=====
41
+ const parsers = require("./parsers");
42
+ const promptImpl = require("./parsers/_prompt");
43
+ const schemas = require("./schemas");
44
+ const parserRegistry = parsers.registry;
45
+
46
+ /**
47
+ * 把注册表里的解析器(buildPrompt)连同其依赖的 buildFetchPrompt 内联进
48
+ * workflow script,使其自包含 —— DSH rc7 的 workflow 工具只把 args(JSON)
49
+ * 暴露给脚本,不会注入 args._parsers;脚本必须在自身内部解析器可用。
50
+ * 若宿主未来注入 args._parsers,优先使用宿主注入值(向后兼容)。
51
+ *
52
+ * 内联的是 **注册表里的全部解析器**,不是写死的四个:custom-parsers/ 里的
53
+ * 覆盖与自定义类型因此都能真正进入脚本(此前自定义新类型在 type 白名单
54
+ * 和这里两道关都被丢掉)。fetchSchema 同样从 schemas/index.js 注入,
55
+ * 保持单一真相,不再和脚本里的副本各自漂移。
56
+ */
57
+ function buildSelfContainedScript() {
58
+ const parserSource = (name) =>
59
+ parserRegistry.parsers[name].buildPrompt
60
+ .toString()
61
+ // buildPrompt 闭包引用模块级 prompt(parsers/_prompt),内联后改指 __prompt
62
+ .replace(/\bprompt\.buildFetchPrompt\b/g, "__prompt.buildFetchPrompt");
63
+
64
+ const parserNames = Object.keys(parserRegistry.parsers);
65
+ // kind 的合法取值跟着解析器表走(含自定义类型),不再写死四个内置类型。
66
+ const fetchSchema = JSON.parse(JSON.stringify(schemas.fetchResultSchema));
67
+ if (fetchSchema.properties && fetchSchema.properties.kind) {
68
+ fetchSchema.properties.kind.enum = parserNames.slice();
69
+ }
70
+
71
+ const impl = [
72
+ "const __prompt = { buildFetchPrompt: " + promptImpl.buildFetchPrompt.toString() + " };",
73
+ "const __parsers = {",
74
+ parserNames
75
+ .map((name) => " " + JSON.stringify(name) + ": { buildPrompt: " + parserSource(name) + " }")
76
+ .join(",\n"),
77
+ "};",
78
+ "const fetchSchema = " + JSON.stringify(fetchSchema) + ";"
79
+ ].join("\n");
80
+
81
+ const marker = "const parsers = args._parsers || {};";
82
+ if (!RAW_SCRIPT.includes(marker)) {
83
+ throw new Error("workflow script marker not found: " + marker);
84
+ }
85
+ return RAW_SCRIPT.replace(marker, impl + "\nconst parsers = args._parsers || __parsers;");
86
+ }
87
+
88
+ const script = buildSelfContainedScript();
89
+
77
90
  module.exports = { meta, script, parsers, buildSelfContainedScript };
@@ -1,68 +0,0 @@
1
- # transcribe.ps1 - faster-whisper transcription bootstrap (plugin-internal, self-bootstrapping)
2
- # Usage: pwsh transcribe.ps1 -Audio <file> -Out <txt> [-Model small] [-Language zh]
3
- # Deterministic per-user cache so behavior is identical on dev & user machines.
4
- param(
5
- [Parameter(Mandatory=$true)][string]$Audio,
6
- [Parameter(Mandatory=$true)][string]$Out,
7
- [string]$Model = 'small',
8
- [string]$Language = 'zh'
9
- )
10
- $ErrorActionPreference = 'Stop'
11
-
12
- $cacheRoot = Join-Path $env:LOCALAPPDATA 'deep-read-summarize'
13
- $venvDir = Join-Path $cacheRoot 'venv'
14
- $venvPy = Join-Path $venvDir 'Scripts/python.exe'
15
- $hfHome = Join-Path $cacheRoot 'hf'
16
- $pyScript = Join-Path $cacheRoot 'transcribe_run.py'
17
-
18
- New-Item -ItemType Directory -Force -Path $cacheRoot | Out-Null
19
-
20
- $uv = $null
21
- $uvCmd = Get-Command uv -ErrorAction SilentlyContinue
22
- if ($uvCmd) { $uv = $uvCmd.Source }
23
- else { $alt = Join-Path $HOME '.local/bin/uv.exe'; if (Test-Path $alt) { $uv = $alt } }
24
- if (-not $uv) { throw 'uv not found. Please install uv (winget install astral-sh.uv) or ensure it is on PATH.' }
25
-
26
- # Use a China mirror for CPython download (uv pulls python-build-standalone from GitHub, slow in CN),
27
- # and prefer an already-installed 3.12 (avoids the download entirely on many machines).
28
- $env:UV_PYTHON_INSTALL_MIRROR = 'https://ghproxy.com/https://github.com/astral-sh/python-build-standalone/releases/download'
29
-
30
- if (-not (Test-Path $venvPy)) {
31
- # reuse an existing python 3.12 if present; else uv installs 3.12 (via mirror)
32
- $usePy = (py -0p 2>$null | Select-String '3.12' | Select-Object -First 1)
33
- if ($usePy) { $pyArg = '3.12' } else { $pyArg = '3.12' }
34
- & $uv venv --python $pyArg $venvDir
35
- if ($LASTEXITCODE -ne 0) { throw 'uv venv creation failed.' }
36
- }
37
-
38
- & $venvPy -c 'import faster_whisper' 2>$null
39
- if ($LASTEXITCODE -ne 0) {
40
- & $uv pip install --python $venvPy faster-whisper -i https://pypi.tuna.tsinghua.edu.cn/simple
41
- if ($LASTEXITCODE -ne 0) { throw 'faster-whisper install failed (mirror unreachable?).' }
42
- }
43
-
44
- $env:HF_ENDPOINT = 'https://hf-mirror.com'
45
- $env:HF_HOME = $hfHome
46
- # Disable the hf-xet backend: it bypasses the mirror (cas-server.xethub.hf.co) and 401s; the mirror works over plain HTTP.
47
- $env:HF_HUB_DISABLE_XET = '1'
48
- $env:HF_HUB_DISABLE_SYMLINKS_WARNING = '1'
49
- $env:DRS_AUDIO = $Audio
50
- $env:DRS_OUT = $Out
51
- $env:DRS_MODEL = $Model
52
- $env:DRS_LANG = $Language
53
-
54
- $py = @'
55
- import os
56
- from faster_whisper import WhisperModel
57
- m = WhisperModel(os.environ['DRS_MODEL'], device='auto', compute_type='int8')
58
- segs, info = m.transcribe(os.environ['DRS_AUDIO'], vad_filter=True, language=(os.environ.get('DRS_LANG') or None))
59
- with open(os.environ['DRS_OUT'], 'w', encoding='utf-8') as f:
60
- for s in segs:
61
- f.write(s.text.strip() + ' ')
62
- print('DONE', info.language, round(info.duration, 1))
63
- '@
64
- [System.IO.File]::WriteAllText($pyScript, $py, (New-Object System.Text.UTF8Encoding($false)))
65
-
66
- & $venvPy $pyScript
67
- if ($LASTEXITCODE -ne 0) { throw 'transcription failed.' }
68
- Write-Output ('TRANSCRIBED ' + (Get-Item $Out).Length + ' bytes to ' + $Out)