inkbone 0.0.0-stage → 2.1.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.
Files changed (143) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +380 -0
  3. package/README.md +384 -2
  4. package/bin/inkbone.mjs +1049 -0
  5. package/configs/genres.json +591 -0
  6. package/configs/messages.json +336 -0
  7. package/configs/platforms.json +66 -0
  8. package/configs/presets.json +265 -0
  9. package/configs/severity.json +59 -0
  10. package/configs/zh-linguistics.json +1040 -0
  11. package/configs/zh-traditional.json +97 -0
  12. package/examples/claude-code-hooks.json +15 -0
  13. package/examples/mcp-config.json +12 -0
  14. package/package.json +62 -4
  15. package/prompts/00-style-architect.md +42 -0
  16. package/prompts/01-beat-planner.md +54 -0
  17. package/prompts/02-paratactic-renderer.md +63 -0
  18. package/prompts/03-targeted-rewriter.md +44 -0
  19. package/prompts/04-evidence-reviewer.md +39 -0
  20. package/prompts/05-reader-simulator.md +54 -0
  21. package/prompts/06-ledger-importer.md +41 -0
  22. package/prompts/07-chapter-settler.md +66 -0
  23. package/resources/bad_vs_good_cases.md +132 -0
  24. package/resources/eval/blind-read-instructions.md +18 -0
  25. package/resources/genre_playbooks/classical-xianxia.md +22 -0
  26. package/resources/genre_playbooks/general-clean.md +19 -0
  27. package/resources/genre_playbooks/historical-court.md +21 -0
  28. package/resources/genre_playbooks/light-fantasy.md +22 -0
  29. package/resources/genre_playbooks/mystery-thriller.md +22 -0
  30. package/resources/genre_playbooks/romance-emotional.md +20 -0
  31. package/resources/genre_playbooks/scifi-wasteland.md +21 -0
  32. package/resources/genre_playbooks/urban-realism.md +22 -0
  33. package/resources/genre_playbooks/wuxia-jianghu.md +21 -0
  34. package/resources/micro_techniques.md +77 -0
  35. package/skills/inkbone/LICENSE +21 -0
  36. package/skills/inkbone/README.md +385 -0
  37. package/skills/inkbone/SKILL.md +162 -0
  38. package/skills/inkbone/benchmarks/eval-set/README.md +49 -0
  39. package/skills/inkbone/benchmarks/eval-set/public-pairs.json +42 -0
  40. package/skills/inkbone/benchmarks/eval-set/seeds.json +42 -0
  41. package/skills/inkbone/bin/inkbone.mjs +1049 -0
  42. package/skills/inkbone/configs/genres.json +591 -0
  43. package/skills/inkbone/configs/messages.json +336 -0
  44. package/skills/inkbone/configs/platforms.json +66 -0
  45. package/skills/inkbone/configs/presets.json +265 -0
  46. package/skills/inkbone/configs/severity.json +59 -0
  47. package/skills/inkbone/configs/zh-linguistics.json +1040 -0
  48. package/skills/inkbone/configs/zh-traditional.json +97 -0
  49. package/skills/inkbone/package.json +64 -0
  50. package/skills/inkbone/prompts/00-style-architect.md +42 -0
  51. package/skills/inkbone/prompts/01-beat-planner.md +54 -0
  52. package/skills/inkbone/prompts/02-paratactic-renderer.md +63 -0
  53. package/skills/inkbone/prompts/03-targeted-rewriter.md +44 -0
  54. package/skills/inkbone/prompts/04-evidence-reviewer.md +39 -0
  55. package/skills/inkbone/prompts/05-reader-simulator.md +54 -0
  56. package/skills/inkbone/prompts/06-ledger-importer.md +41 -0
  57. package/skills/inkbone/prompts/07-chapter-settler.md +66 -0
  58. package/skills/inkbone/resources/bad_vs_good_cases.md +132 -0
  59. package/skills/inkbone/resources/eval/blind-read-instructions.md +18 -0
  60. package/skills/inkbone/resources/genre_playbooks/classical-xianxia.md +22 -0
  61. package/skills/inkbone/resources/genre_playbooks/general-clean.md +19 -0
  62. package/skills/inkbone/resources/genre_playbooks/historical-court.md +21 -0
  63. package/skills/inkbone/resources/genre_playbooks/light-fantasy.md +22 -0
  64. package/skills/inkbone/resources/genre_playbooks/mystery-thriller.md +22 -0
  65. package/skills/inkbone/resources/genre_playbooks/romance-emotional.md +20 -0
  66. package/skills/inkbone/resources/genre_playbooks/scifi-wasteland.md +21 -0
  67. package/skills/inkbone/resources/genre_playbooks/urban-realism.md +22 -0
  68. package/skills/inkbone/resources/genre_playbooks/wuxia-jianghu.md +21 -0
  69. package/skills/inkbone/resources/micro_techniques.md +77 -0
  70. package/skills/inkbone/src/aigc-guard.mjs +83 -0
  71. package/skills/inkbone/src/auditor.mjs +24 -0
  72. package/skills/inkbone/src/benchmark-runner.mjs +71 -0
  73. package/skills/inkbone/src/boundary-compiler.mjs +60 -0
  74. package/skills/inkbone/src/browser-doctor.mjs +30 -0
  75. package/skills/inkbone/src/calibrator.mjs +175 -0
  76. package/skills/inkbone/src/config-loader.mjs +233 -0
  77. package/skills/inkbone/src/continuity.mjs +5 -0
  78. package/skills/inkbone/src/core/aigc-guard.mjs +387 -0
  79. package/skills/inkbone/src/core/auditor.mjs +1074 -0
  80. package/skills/inkbone/src/core/boundary-compiler.mjs +526 -0
  81. package/skills/inkbone/src/core/browser-doctor.mjs +320 -0
  82. package/skills/inkbone/src/core/config-compiler.mjs +434 -0
  83. package/skills/inkbone/src/core/continuity.mjs +158 -0
  84. package/skills/inkbone/src/core/evidence-validator.mjs +77 -0
  85. package/skills/inkbone/src/core/exporter.mjs +423 -0
  86. package/skills/inkbone/src/core/formatter.mjs +241 -0
  87. package/skills/inkbone/src/core/ledger-manager.mjs +843 -0
  88. package/skills/inkbone/src/core/normalizer.mjs +517 -0
  89. package/skills/inkbone/src/core/profiler.mjs +686 -0
  90. package/skills/inkbone/src/core/rule-engine.mjs +1710 -0
  91. package/skills/inkbone/src/core/style-profiler.mjs +229 -0
  92. package/skills/inkbone/src/detector.mjs +270 -0
  93. package/skills/inkbone/src/doctor.mjs +430 -0
  94. package/skills/inkbone/src/evaluation.mjs +311 -0
  95. package/skills/inkbone/src/evidence-validator.mjs +15 -0
  96. package/skills/inkbone/src/exporter.mjs +142 -0
  97. package/skills/inkbone/src/formatter.mjs +34 -0
  98. package/skills/inkbone/src/importer.mjs +230 -0
  99. package/skills/inkbone/src/index.mjs +134 -0
  100. package/skills/inkbone/src/ledger-manager.mjs +22 -0
  101. package/skills/inkbone/src/mcp-server.mjs +950 -0
  102. package/skills/inkbone/src/normalizer.mjs +73 -0
  103. package/skills/inkbone/src/profiler.mjs +17 -0
  104. package/skills/inkbone/src/rule-engine.mjs +91 -0
  105. package/skills/inkbone/src/rule-stats.mjs +142 -0
  106. package/skills/inkbone/src/style-profiler.mjs +25 -0
  107. package/src/aigc-guard.mjs +83 -0
  108. package/src/auditor.mjs +24 -0
  109. package/src/benchmark-runner.mjs +71 -0
  110. package/src/boundary-compiler.mjs +60 -0
  111. package/src/browser-doctor.mjs +30 -0
  112. package/src/calibrator.mjs +175 -0
  113. package/src/config-loader.mjs +233 -0
  114. package/src/continuity.mjs +5 -0
  115. package/src/core/aigc-guard.mjs +387 -0
  116. package/src/core/auditor.mjs +1074 -0
  117. package/src/core/boundary-compiler.mjs +526 -0
  118. package/src/core/browser-doctor.mjs +320 -0
  119. package/src/core/config-compiler.mjs +434 -0
  120. package/src/core/continuity.mjs +158 -0
  121. package/src/core/evidence-validator.mjs +77 -0
  122. package/src/core/exporter.mjs +423 -0
  123. package/src/core/formatter.mjs +241 -0
  124. package/src/core/ledger-manager.mjs +843 -0
  125. package/src/core/normalizer.mjs +517 -0
  126. package/src/core/profiler.mjs +686 -0
  127. package/src/core/rule-engine.mjs +1710 -0
  128. package/src/core/style-profiler.mjs +229 -0
  129. package/src/detector.mjs +270 -0
  130. package/src/doctor.mjs +430 -0
  131. package/src/evaluation.mjs +311 -0
  132. package/src/evidence-validator.mjs +15 -0
  133. package/src/exporter.mjs +142 -0
  134. package/src/formatter.mjs +34 -0
  135. package/src/importer.mjs +230 -0
  136. package/src/index.mjs +134 -0
  137. package/src/ledger-manager.mjs +22 -0
  138. package/src/mcp-server.mjs +950 -0
  139. package/src/normalizer.mjs +73 -0
  140. package/src/profiler.mjs +17 -0
  141. package/src/rule-engine.mjs +91 -0
  142. package/src/rule-stats.mjs +142 -0
  143. package/src/style-profiler.mjs +25 -0
@@ -0,0 +1,229 @@
1
+ // 零版权风险“安全拆书”风格画像引擎(纯内存、零文件系统依赖,绝不输出任何范文原句)
2
+ import { profileText } from "./profiler.mjs";
3
+ import { stripSpokenDialogue } from "./rule-engine.mjs";
4
+ import { resolveLocaleBundle } from "./formatter.mjs";
5
+
6
+ const PROFILE_METRICS = [
7
+ "sentLenMean",
8
+ "sentLenCV",
9
+ "flowingSentRatio",
10
+ "ultraShortSentRatio",
11
+ "dePer100Han",
12
+ "longModPerClause",
13
+ "nestedDePer1kHan",
14
+ "mattr50",
15
+ "hapaxRatio",
16
+ "topicAnchorRatio",
17
+ "sentsPerParaMean",
18
+ "paraLenMean",
19
+ "emDashPer1kHan",
20
+ "dialogueCharRatio",
21
+ ];
22
+
23
+ // 预设距离匹配所用的核心维度及其归一化尺度
24
+ const PRESET_COMPARE_AXES = [
25
+ { metric: "mattr50", gate: "maxMattr50", scale: 0.06 },
26
+ { metric: "sentLenCV", gate: "minSentLenCV", scale: 0.25 },
27
+ { metric: "flowingSentRatio", gate: "minFlowingSentRatio", scale: 0.25 },
28
+ { metric: "ultraShortSentRatio", gate: "minUltraShortSentRatio", scale: 0.12 },
29
+ { metric: "dePer100Han", gate: "maxDePer100Han", scale: 2.0 },
30
+ { metric: "longModPerClause", gate: "maxLongModPerClause", scale: 0.15 },
31
+ { metric: "emDashPer1kHan", gate: "maxEmDashPer1kHan", scale: 0.8 },
32
+ ];
33
+
34
+ function quantile(sorted, q) {
35
+ if (!sorted || sorted.length === 0) return 0;
36
+ const pos = (sorted.length - 1) * q;
37
+ const lo = Math.floor(pos);
38
+ const hi = Math.ceil(pos);
39
+ const val = sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo);
40
+ return Math.round(val * 1000) / 1000;
41
+ }
42
+
43
+ function clamp(val, min, max, decimals = 3) {
44
+ const factor = 10 ** decimals;
45
+ return Math.round(Math.max(min, Math.min(max, val)) * factor) / factor;
46
+ }
47
+
48
+ // 计算单篇文本中的对白字符占有效汉字的比例
49
+ function computeDialogueCharRatio(text, lingConfig, totalHan) {
50
+ if (!totalHan || totalHan <= 0) return 0;
51
+ const lines = String(text || "").split(/\r?\n/u);
52
+ let spokenTotal = 0;
53
+ for (const line of lines) {
54
+ const trimmed = line.trim();
55
+ if (!trimmed) continue;
56
+ const info = stripSpokenDialogue(trimmed, lingConfig, " ");
57
+ spokenTotal += info.spokenChars || 0;
58
+ }
59
+ return clamp(spokenTotal / Math.max(totalHan, 1), 0, 1, 3);
60
+ }
61
+
62
+ // 从多篇样本计算纯统计节奏画像、最接近内置预设以及可直接写入 novel.json 的 customGates
63
+ export function analyzeStyleProfile(texts, lingConfig, presetsConfig, options = {}) {
64
+ if (!lingConfig || !presetsConfig) {
65
+ throw new Error("lingConfig and presetsConfig are required for analyzeStyleProfile.");
66
+ }
67
+ const cleanTexts = (Array.isArray(texts) ? texts : [texts]).filter(
68
+ (t) => typeof t === "string" && t.trim().length > 0
69
+ );
70
+ if (cleanTexts.length === 0) {
71
+ throw new Error("At least one non-empty text sample is required for style-profile.");
72
+ }
73
+
74
+ let totalHan = 0;
75
+ const perSampleMetrics = cleanTexts.map((text) => {
76
+ const prof = profileText(text, lingConfig);
77
+ const m = prof.metrics;
78
+ totalHan += m.totalHan || 0;
79
+ return {
80
+ ...m,
81
+ dialogueCharRatio: computeDialogueCharRatio(text, lingConfig, m.totalHan),
82
+ };
83
+ });
84
+
85
+ const metrics = {};
86
+ for (const key of PROFILE_METRICS) {
87
+ const vals = perSampleMetrics
88
+ .map((row) => row[key])
89
+ .filter((v) => typeof v === "number" && Number.isFinite(v))
90
+ .sort((a, b) => a - b);
91
+ if (vals.length === 0) continue;
92
+ metrics[key] = {
93
+ p10: quantile(vals, 0.1),
94
+ median: quantile(vals, 0.5),
95
+ p90: quantile(vals, 0.9),
96
+ min: vals[0],
97
+ max: vals[vals.length - 1],
98
+ };
99
+ }
100
+
101
+ // 与全部内置预设做归一化距离比对,找出风格最贴近的基座预设
102
+ const presetEntries = Object.values(presetsConfig.presets || {});
103
+ const presetDistances = presetEntries
104
+ .map((preset) => {
105
+ let sqSum = 0;
106
+ let count = 0;
107
+ for (const axis of PRESET_COMPARE_AXES) {
108
+ const sampleVal = metrics[axis.metric]?.median;
109
+ const gateVal = preset.gates?.[axis.gate];
110
+ if (typeof sampleVal !== "number" || typeof gateVal !== "number") continue;
111
+ const diff = (sampleVal - gateVal) / axis.scale;
112
+ sqSum += diff * diff;
113
+ count += 1;
114
+ }
115
+ const distance = count > 0 ? Math.round(Math.sqrt(sqSum / count) * 1000) / 1000 : 999;
116
+ return { id: preset.id, title: preset.title, distance };
117
+ })
118
+ .sort((a, b) => a.distance - b.distance);
119
+
120
+ const nearestPreset = presetDistances[0] || {
121
+ id: presetsConfig.defaultPreset || "modern-clean",
122
+ title: "",
123
+ distance: 0,
124
+ };
125
+
126
+ // 基于样本 p10/median/p90 推导带安全缓冲带的 customGates(可直接粘贴进 novel.json)
127
+ const p90Para = metrics.paraLenMean?.p90 ?? 70;
128
+ const p90De = metrics.dePer100Han?.p90 ?? 4.5;
129
+ const p90LongMod = metrics.longModPerClause?.p90 ?? 0.28;
130
+ const p90NestedDe = metrics.nestedDePer1kHan?.p90 ?? 1.5;
131
+ const p90Mattr = metrics.mattr50?.p90 ?? 0.94;
132
+ const p10CV = metrics.sentLenCV?.p10 ?? 0.52;
133
+ const p10Sents = metrics.sentsPerParaMean?.p10 ?? 1.15;
134
+ const p90Sents = metrics.sentsPerParaMean?.p90 ?? 3.2;
135
+ const p90EmDash = metrics.emDashPer1kHan?.p90 ?? 0.6;
136
+ const medDialogue = metrics.dialogueCharRatio?.median ?? 0.25;
137
+
138
+ const suggestedGates = {
139
+ maxParagraphHanChars: Math.round(clamp(p90Para * 2.2, 120, 320, 0)),
140
+ minSentLenCV: clamp(p10CV * 0.9, 0.38, 0.72, 2),
141
+ maxDePer100Han: clamp(p90De + 0.6, 3.0, 7.5, 2),
142
+ maxLongModPerClause: clamp(p90LongMod + 0.08, 0.16, 0.5, 2),
143
+ maxNestedDePer1kHan: clamp(p90NestedDe + 0.5, 0.8, 3.5, 2),
144
+ maxMattr50: clamp(p90Mattr + 0.015, 0.86, 0.97, 3),
145
+ minSentsPerPara: clamp(p10Sents * 0.85, 1.0, 2.2, 2),
146
+ maxSentsPerPara: clamp(p90Sents * 1.15, 2.2, 4.5, 2),
147
+ maxEmDashPer1kHan: clamp(p90EmDash + 0.4, 0.4, 2.5, 2),
148
+ maxDialogueDrySpellHan: medDialogue >= 0.3 ? 800 : medDialogue >= 0.15 ? 1000 : 1300,
149
+ };
150
+
151
+ // 提炼风格画像标签代码(展示中文由 messages.json 映射)
152
+ const medSent = metrics.sentLenMean?.median ?? 22;
153
+ const medFlow = metrics.flowingSentRatio?.median ?? 0.15;
154
+ const paceTier =
155
+ medSent <= 18 ? "paceFast" : medFlow >= 0.28 || medSent >= 28 ? "paceFlowing" : "paceBalanced";
156
+ const dialogueTier =
157
+ medDialogue >= 0.35 ? "dialogueHigh" : medDialogue >= 0.15 ? "dialogueMedium" : "dialogueLow";
158
+ const medDe = metrics.dePer100Han?.median ?? 4.2;
159
+ const modifierStyle = medDe <= 3.8 ? "modClean" : medDe <= 5.2 ? "modModerate" : "modDense";
160
+
161
+ return {
162
+ kind: "inkbone-style-profile",
163
+ label: options.label || "",
164
+ sampleCount: cleanTexts.length,
165
+ totalHan,
166
+ reliable: cleanTexts.length >= 3 && totalHan >= 6000,
167
+ nearestPreset,
168
+ presetDistances: presetDistances.slice(0, 4),
169
+ traits: {
170
+ paceTier,
171
+ dialogueTier,
172
+ modifierStyle,
173
+ dialogueCharRatioMedian: medDialogue,
174
+ },
175
+ metrics,
176
+ suggestedGates,
177
+ novelConfigSnippet: {
178
+ preset: nearestPreset.id,
179
+ customGates: suggestedGates,
180
+ },
181
+ };
182
+ }
183
+
184
+ // 渲染零原文泄露的双语文风画像 Markdown 报告
185
+ export function formatStyleProfileMarkdown(profile, options = {}) {
186
+ const { bundle } = resolveLocaleBundle(options.messagesConfig, options.lang);
187
+ const sp = bundle.styleProfile || {};
188
+ const mLabels = bundle.metricLabels || {};
189
+
190
+ const lines = [
191
+ sp.title || "# InkBone Style Profile",
192
+ "",
193
+ `- **${sp.samplesLabel || "Samples"}**: ${profile.sampleCount} | **${sp.totalHanLabel || "Total Han"}**: ${profile.totalHan}`,
194
+ `- **${sp.nearestPresetLabel || "Nearest Preset"}**: \`${profile.nearestPreset.id}\` (${profile.nearestPreset.title || ""}) [dist=${profile.nearestPreset.distance}]`,
195
+ `- **${sp.paceLabel || "Pacing"}**: ${sp[profile.traits.paceTier] || profile.traits.paceTier} | **${sp.dialogueLabel || "Dialogue"}**: ${sp[profile.traits.dialogueTier] || profile.traits.dialogueTier} (${Math.round((profile.traits.dialogueCharRatioMedian || 0) * 100)}%) | **${sp.modifierLabel || "Modifiers"}**: ${sp[profile.traits.modifierStyle] || profile.traits.modifierStyle}`,
196
+ "",
197
+ sp.metricsHeading || "## Quantiles (p10 / median / p90)",
198
+ "",
199
+ "| Metric | p10 | median | p90 |",
200
+ "| :--- | ---: | ---: | ---: |",
201
+ ];
202
+
203
+ const keyOrder = [
204
+ "sentLenMean",
205
+ "sentLenCV",
206
+ "dePer100Han",
207
+ "mattr50",
208
+ "emDashPer1kHan",
209
+ "paraLenMean",
210
+ "dialogueCharRatio",
211
+ ];
212
+ for (const key of keyOrder) {
213
+ const stat = profile.metrics[key];
214
+ if (!stat) continue;
215
+ const label = mLabels[key] ? `${mLabels[key]} (\`${key}\`)` : `\`${key}\``;
216
+ lines.push(`| ${label} | ${stat.p10} | ${stat.median} | ${stat.p90} |`);
217
+ }
218
+
219
+ lines.push(
220
+ "",
221
+ sp.gatesHeading || "## Suggested customGates for novel.json",
222
+ "",
223
+ "```json",
224
+ JSON.stringify(profile.novelConfigSnippet, null, 2),
225
+ "```"
226
+ );
227
+
228
+ return lines.join("\n");
229
+ }
@@ -0,0 +1,270 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ const DEFAULT_ZHUQUE_ENDPOINT =
6
+ "https://ai-gateway.edgeone.link/v1/providers/zhuque-text/classify";
7
+
8
+ // 解析单文件内容中的键值环境变量
9
+ function parseEnvFile(filePath) {
10
+ const vars = {};
11
+ if (!fs.existsSync(filePath)) return vars;
12
+ const lines = fs.readFileSync(filePath, "utf8").split(/\r?\n/u);
13
+ for (const raw of lines) {
14
+ const line = raw.trim();
15
+ if (!line || line.startsWith("#")) continue;
16
+ const eqIdx = line.indexOf("=");
17
+ if (eqIdx <= 0) continue;
18
+ const key = line.slice(0, eqIdx).trim();
19
+ let val = line.slice(eqIdx + 1).trim();
20
+ if (
21
+ (val.startsWith('"') && val.endsWith('"')) ||
22
+ (val.startsWith("'") && val.endsWith("'"))
23
+ ) {
24
+ val = val.slice(1, -1);
25
+ }
26
+ vars[key] = val;
27
+ }
28
+ return vars;
29
+ }
30
+
31
+ // 按环境变量与上级目录 .env 文件顺序解析朱雀 API 密钥
32
+ export function resolveZhuqueApiKey(options = {}) {
33
+ if (options.apiKey) return options.apiKey;
34
+ if (process.env.ZHUQUE_API_KEY) return process.env.ZHUQUE_API_KEY;
35
+ if (process.env.MAKERS_MODELS_KEY) return process.env.MAKERS_MODELS_KEY;
36
+
37
+ let curDir = options.startDir ? path.resolve(options.startDir) : process.cwd();
38
+ for (let depth = 0; depth < 5; depth += 1) {
39
+ const envPath = path.join(curDir, ".env");
40
+ const parsed = parseEnvFile(envPath);
41
+ if (parsed.ZHUQUE_API_KEY) return parsed.ZHUQUE_API_KEY;
42
+ if (parsed.MAKERS_MODELS_KEY) return parsed.MAKERS_MODELS_KEY;
43
+ const parent = path.dirname(curDir);
44
+ if (parent === curDir) break;
45
+ curDir = parent;
46
+ }
47
+ return "";
48
+ }
49
+
50
+ // 剥离 Markdown 标题井号并支持按行号截取局部区间以节省 API Token
51
+ export function prepareDetectorInput(rawMarkdown, lineRange = null) {
52
+ const allRawLines = rawMarkdown.split(/\r?\n/u);
53
+ let startIdx = 0;
54
+ let endIdx = allRawLines.length - 1;
55
+ if (Array.isArray(lineRange) && lineRange.length === 2) {
56
+ startIdx = Math.max(0, Math.min(allRawLines.length - 1, lineRange[0] - 1));
57
+ endIdx = Math.max(startIdx, Math.min(allRawLines.length - 1, lineRange[1] - 1));
58
+ }
59
+
60
+ const cleanLines = [];
61
+ const lineStartOffsets = [];
62
+ let offset = 0;
63
+
64
+ for (let idx = startIdx; idx <= endIdx; idx += 1) {
65
+ const cleaned = allRawLines[idx].replace(/^#{1,6}\s+/u, "");
66
+ lineStartOffsets.push({ line: idx + 1, start: offset });
67
+ cleanLines.push(cleaned);
68
+ offset += Array.from(cleaned).length + 1;
69
+ }
70
+
71
+ const text = cleanLines.join("\n");
72
+
73
+ // 根据字符起止偏移反查对应的原始 Markdown 行号区间
74
+ function mapSpanToLines(startChar, charLen) {
75
+ const endChar = Math.max(startChar, startChar + charLen - 1);
76
+ let startLine = startIdx + 1;
77
+ let endLine = endIdx + 1;
78
+ for (let i = 0; i < lineStartOffsets.length; i += 1) {
79
+ if (lineStartOffsets[i].start <= startChar) {
80
+ startLine = lineStartOffsets[i].line;
81
+ }
82
+ if (lineStartOffsets[i].start <= endChar) {
83
+ endLine = lineStartOffsets[i].line;
84
+ }
85
+ }
86
+ return { startLine, endLine };
87
+ }
88
+
89
+ return { text, mapSpanToLines, lineSpan: [startIdx + 1, endIdx + 1] };
90
+ }
91
+
92
+ // 将接口返回的单个微窗口转换为结构化诊断记录
93
+ function formatSegment(seg, mapSpanToLines) {
94
+ const pos = Array.isArray(seg.position) ? seg.position : [0, 0];
95
+ const startOffset = Number(pos[0] || 0);
96
+ const length = Number(pos[1] || Array.from(seg.text || "").length);
97
+ const { startLine, endLine } = mapSpanToLines(startOffset, length);
98
+ const compact = String(seg.text || "").replace(/\s+/gu, " ").trim();
99
+ const chars = Array.from(compact);
100
+ const head = chars.slice(0, 26).join("");
101
+ const tail = chars.length > 30 ? chars.slice(-20).join("") : "";
102
+
103
+ let category = "human";
104
+ if (seg.label === 1) category = "ai";
105
+ else if (seg.label === 2) category = "suspected_ai";
106
+
107
+ return {
108
+ order: seg.order,
109
+ category,
110
+ label: seg.label,
111
+ aigc: Number(Number(seg.conf || 0).toFixed(4)),
112
+ chars: length,
113
+ startLine,
114
+ endLine,
115
+ preview: tail ? `${head} ... ${tail}` : head,
116
+ };
117
+ }
118
+
119
+ // 在本地合并相邻同标签微窗口并计算字符加权置信度,免去二次调用 API 的双倍开销
120
+ export function mergeFineWindowsLocally(fineWindows) {
121
+ if (fineWindows.length === 0) return [];
122
+ const merged = [];
123
+ for (const win of fineWindows) {
124
+ const prev = merged[merged.length - 1];
125
+ if (prev && prev.label === win.label) {
126
+ const totalChars = prev.chars + win.chars;
127
+ const weighted =
128
+ totalChars > 0
129
+ ? (prev.aigc * prev.chars + win.aigc * win.chars) / totalChars
130
+ : win.aigc;
131
+ prev.aigc = Number(weighted.toFixed(4));
132
+ prev.chars = totalChars;
133
+ prev.endLine = win.endLine;
134
+ const headPart = prev.preview.split(" ... ")[0];
135
+ const tailParts = win.preview.split(" ... ");
136
+ const tailPart = tailParts[tailParts.length - 1];
137
+ prev.preview = `${headPart} ... ${tailPart}`;
138
+ } else {
139
+ merged.push({
140
+ order: merged.length + 1,
141
+ category: win.category,
142
+ label: win.label,
143
+ aigc: win.aigc,
144
+ chars: win.chars,
145
+ startLine: win.startLine,
146
+ endLine: win.endLine,
147
+ preview: win.preview,
148
+ });
149
+ }
150
+ }
151
+ return merged;
152
+ }
153
+
154
+ // 读取本地磁盘缓存以避免对完全一致的文本重复消耗 Token
155
+ function readCacheEntry(cachePath, digest) {
156
+ if (!cachePath || !fs.existsSync(cachePath)) return null;
157
+ try {
158
+ const store = JSON.parse(fs.readFileSync(cachePath, "utf8"));
159
+ return store[digest] || null;
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+
165
+ // 将单次 API 响应写入本地缓存(最多保留最近 100 条哈希记录)
166
+ function writeCacheEntry(cachePath, digest, payload) {
167
+ if (!cachePath) return;
168
+ let store = {};
169
+ if (fs.existsSync(cachePath)) {
170
+ try {
171
+ store = JSON.parse(fs.readFileSync(cachePath, "utf8"));
172
+ } catch {
173
+ store = {};
174
+ }
175
+ }
176
+ store[digest] = payload;
177
+ const keys = Object.keys(store);
178
+ if (keys.length > 100) {
179
+ for (const oldKey of keys.slice(0, keys.length - 100)) {
180
+ delete store[oldKey];
181
+ }
182
+ }
183
+ fs.writeFileSync(cachePath, JSON.stringify(store, null, 2) + "\n");
184
+ }
185
+
186
+ // 单请求高性价比朱雀检测:仅发送 1 次 is_merge=false 请求并在本地合成合并报告与缓存
187
+ export async function detectWithZhuque(rawMarkdown, options = {}) {
188
+ const threshold =
189
+ typeof options.threshold === "number" ? options.threshold : 0.5;
190
+ const { text, mapSpanToLines, lineSpan } = prepareDetectorInput(
191
+ rawMarkdown,
192
+ options.lineRange || null
193
+ );
194
+
195
+ const digest = crypto.createHash("sha256").update(text).digest("hex");
196
+ const cachePath =
197
+ options.cache === false
198
+ ? null
199
+ : options.cachePath || path.resolve(process.cwd(), ".zhuque-cache.json");
200
+
201
+ let payload = !options.noCache ? readCacheEntry(cachePath, digest) : null;
202
+ let cached = Boolean(payload);
203
+
204
+ if (!payload) {
205
+ const apiKey = resolveZhuqueApiKey(options);
206
+ if (!apiKey) {
207
+ throw new Error("Missing ZHUQUE_API_KEY in environment or .env file.");
208
+ }
209
+ const fetchFn = options.fetchImpl || globalThis.fetch;
210
+ const endpoint = options.endpoint || DEFAULT_ZHUQUE_ENDPOINT;
211
+ const response = await fetchFn(endpoint, {
212
+ method: "POST",
213
+ headers: {
214
+ Authorization: `Bearer ${apiKey}`,
215
+ "Content-Type": "application/json",
216
+ },
217
+ body: JSON.stringify({
218
+ text,
219
+ is_merge: false,
220
+ }),
221
+ });
222
+
223
+ if (!response.ok) {
224
+ const errText = await response.text();
225
+ throw new Error(
226
+ `Zhuque API HTTP ${response.status}: ${errText.slice(0, 240)}`
227
+ );
228
+ }
229
+ payload = await response.json();
230
+ if (payload.status && payload.status !== "success") {
231
+ throw new Error(`Zhuque API error: ${payload.msg || payload.status}`);
232
+ }
233
+ writeCacheEntry(cachePath, digest, payload);
234
+ cached = false;
235
+ }
236
+
237
+ const ratios = payload.labels_ratio || {};
238
+ const humanPct = Number((Number(ratios["0"] || 0) * 100).toFixed(2));
239
+ const aiPct = Number((Number(ratios["1"] || 0) * 100).toFixed(2));
240
+ const suspectedPct = Number((Number(ratios["2"] || 0) * 100).toFixed(2));
241
+
242
+ const fineWindows = (payload.segment_labels || []).map((s) =>
243
+ formatSegment(s, mapSpanToLines)
244
+ );
245
+ const mergedSegments = mergeFineWindowsLocally(fineWindows);
246
+ const flaggedWindows = fineWindows.filter((w) => w.aigc >= threshold);
247
+ const pass = mergedSegments.every((s) => s.aigc < threshold);
248
+
249
+ return {
250
+ pass,
251
+ cached,
252
+ lineSpan,
253
+ inputChars: Array.from(text).length,
254
+ tokenUsage: payload.makers_models_usage || payload.usage || null,
255
+ threshold,
256
+ humanPct,
257
+ suspectedPct,
258
+ aiPct,
259
+ softmaxConfidence: Number(
260
+ Number(payload.softmax_confidence || 0).toFixed(4)
261
+ ),
262
+ ratioConfidence: Number(
263
+ Number(payload.ratio_confidence || 0).toFixed(4)
264
+ ),
265
+ segments: mergedSegments,
266
+ flaggedWindowCount: flaggedWindows.length,
267
+ flaggedWindows,
268
+ fineWindows,
269
+ };
270
+ }