dislop 0.9.1 → 1.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.
- package/.claude-plugin/marketplace.json +3 -3
- package/.claude-plugin/plugin.json +2 -2
- package/.codex-plugin/plugin.json +7 -8
- package/.cursor-plugin/plugin.json +2 -3
- package/.pre-commit-hooks.yaml +5 -12
- package/PRODUCT.md +19 -63
- package/README.md +358 -249
- package/README.zh-CN.md +391 -237
- package/action.yml +30 -39
- package/bin/dislop-mcp.mjs +3 -4
- package/bin/dislop.mjs +4 -4594
- package/gemini-extension.json +2 -2
- package/llms-install.md +68 -0
- package/package.json +17 -63
- package/packs/common/artifact-qa/pack.json +5 -0
- package/packs/common/artifact-qa/prompts/rules.md +11 -0
- package/packs/common/artifact-qa/scripts/index.mjs +235 -0
- package/packs/common/slide-deck/pack.json +6 -0
- package/packs/common/slide-deck/prompts/rules.md +11 -0
- package/packs/common/slide-deck/scripts/index.mjs +62 -0
- package/packs/common/web-ui/pack.json +6 -0
- package/packs/common/web-ui/prompts/rules.md +11 -0
- package/packs/common/web-ui/scripts/index.mjs +80 -0
- package/packs/en/artifact-qa/pack.json +6 -0
- package/packs/en/artifact-qa/prompts/rules.md +14 -0
- package/packs/en/artifact-qa/scripts/index.mjs +90 -0
- package/packs/en/prose/pack.json +7 -0
- package/packs/en/prose/prompts/rules.md +26 -0
- package/packs/en/prose/scripts/index.mjs +293 -0
- package/packs/en/slide-deck/pack.json +7 -0
- package/packs/en/slide-deck/prompts/rules.md +17 -0
- package/packs/en/slide-deck/scripts/index.mjs +81 -0
- package/packs/en/web-ui/pack.json +7 -0
- package/packs/en/web-ui/prompts/rules.md +20 -0
- package/packs/en/web-ui/scripts/index.mjs +103 -0
- package/packs/zh/artifact-qa/pack.json +6 -0
- package/packs/zh/artifact-qa/prompts/rules.md +14 -0
- package/packs/zh/artifact-qa/scripts/index.mjs +89 -0
- package/packs/zh/prose/pack.json +7 -0
- package/packs/zh/prose/prompts/rules.md +26 -0
- package/packs/zh/prose/scripts/index.mjs +305 -0
- package/packs/zh/slide-deck/pack.json +7 -0
- package/packs/zh/slide-deck/prompts/rules.md +17 -0
- package/packs/zh/slide-deck/scripts/index.mjs +75 -0
- package/packs/zh/web-ui/pack.json +7 -0
- package/packs/zh/web-ui/prompts/rules.md +20 -0
- package/packs/zh/web-ui/scripts/index.mjs +98 -0
- package/plugin.json +5 -6
- package/server.json +2 -2
- package/skills/deslop-docs/SKILL.md +10 -8
- package/skills/deslop-slides-docx/SKILL.md +7 -8
- package/skills/deslop-verify/SKILL.md +7 -8
- package/skills/deslop-web-ui/SKILL.md +7 -8
- package/skills/dislop/SKILL.md +16 -28
- package/skills/dislop/agents/openai.yaml +1 -1
- package/skills/dislop/references/essay.md +6 -6
- package/skills/dislop/references/essay.zh-CN.md +6 -6
- package/skills/dislop/references/office.md +5 -5
- package/skills/dislop/references/office.zh-CN.md +5 -5
- package/skills/dislop/references/web-ui.md +4 -4
- package/skills/dislop/references/web-ui.zh-CN.md +4 -4
- package/skills/dislop/references/work-docs.md +7 -7
- package/skills/dislop/references/work-docs.zh-CN.md +7 -7
- package/src/cli-main.mjs +292 -0
- package/src/commands/check-fix.mjs +324 -0
- package/src/commands/doctor.mjs +132 -0
- package/src/commands/init.mjs +55 -0
- package/src/commands/login.mjs +82 -0
- package/src/commands/model.mjs +130 -0
- package/src/commands/packs.mjs +81 -0
- package/src/commands/verify.mjs +165 -0
- package/src/commands/voice.mjs +84 -0
- package/src/commands/worklog.mjs +424 -0
- package/src/kernel/config.mjs +759 -0
- package/src/kernel/document-model.mjs +1432 -0
- package/src/kernel/fact-gate.mjs +775 -0
- package/src/kernel/file-discovery.mjs +296 -0
- package/src/{binary-node.mjs → kernel/ooxml-binary.mjs} +615 -890
- package/src/kernel/pack-loader.mjs +801 -0
- package/src/kernel/pack-validator.mjs +491 -0
- package/src/kernel/patcher.mjs +471 -0
- package/src/kernel/pipeline.mjs +530 -0
- package/src/kernel/prompt-assembler.mjs +336 -0
- package/src/kernel/version.mjs +7 -0
- package/src/kernel/voice-profile.mjs +180 -0
- package/src/mcp/stdio-server.mjs +442 -0
- package/src/runners/auto-fix.mjs +74 -0
- package/src/runners/interactive-tty.mjs +488 -0
- package/src/runners/reporters.mjs +272 -0
- package/src/runtime/chunker.mjs +87 -0
- package/src/runtime/json-extract.mjs +144 -0
- package/src/runtime/privacy-gate.mjs +97 -0
- package/src/runtime/providers/anthropic.mjs +65 -0
- package/src/runtime/providers/cloud.mjs +138 -0
- package/src/runtime/providers/gemini.mjs +91 -0
- package/src/runtime/providers/local-model.mjs +147 -0
- package/src/runtime/providers/openai-compat.mjs +130 -0
- package/src/runtime/router.mjs +324 -0
- package/src/runtime/worklog.mjs +904 -0
- package/src/sdk/index.mjs +137 -0
- package/models/manifest.json +0 -90
- package/models/pocket-slop-v1.json +0 -1
- package/packs/business-brief/pack.json +0 -937
- package/packs/core/pack.json +0 -209
- package/packs/deck-and-ui/pack.json +0 -539
- package/packs/engineering-spec/pack.json +0 -144
- package/packs/executive-deck/pack.json +0 -98
- package/packs/literary-essay/pack.json +0 -344
- package/packs/regulated-comms/pack.json +0 -99
- package/patterns/ai-tic-rubric.json +0 -252
- package/patterns/banks/composite-fusion.json +0 -48
- package/patterns/banks/discourse-rhythm.json +0 -95
- package/patterns/banks/lexical-signals.json +0 -92
- package/patterns/banks/syntactic-frames.json +0 -52
- package/patterns/banks/visual-deck.json +0 -44
- package/patterns/dimensions/artifacts.json +0 -121
- package/patterns/dimensions/discourse.json +0 -438
- package/patterns/dimensions/lexical.json +0 -198
- package/patterns/dimensions/rhythm.json +0 -258
- package/patterns/dimensions/syntactic.json +0 -285
- package/patterns/dimensions/visual-and-deck.json +0 -530
- package/patterns/taxonomy.json +0 -112
- package/src/core.mjs +0 -5497
- package/src/dislop/review-picker.vim +0 -114
- package/src/local-model.mjs +0 -997
- package/src/pattern-engine.mjs +0 -1003
- package/src/pocket-model.mjs +0 -729
- package/src/review-apply.mjs +0 -151
- package/src/review-client.mjs +0 -1073
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { formatDisplayCoordinate } from "../kernel/document-model.mjs";
|
|
3
|
+
import { applyPatchesToText, renderUnifiedDiff } from "../kernel/patcher.mjs";
|
|
4
|
+
import { DISLOP_VERSION } from "../kernel/version.mjs";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Render `--format json` (`dislop.report/1` verbatim for single file; array of `dislop.report/1` for multi-file).
|
|
8
|
+
*/
|
|
9
|
+
export function formatJsonReports(results) {
|
|
10
|
+
if (results.length === 1) {
|
|
11
|
+
return `${JSON.stringify(results[0].report, null, 2)}\n`;
|
|
12
|
+
}
|
|
13
|
+
return `${JSON.stringify(results.map((r) => r.report), null, 2)}\n`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Render `--format agent`: token-compact structured feed for Coding & Writing Agents.
|
|
18
|
+
*/
|
|
19
|
+
export function formatAgentReports(results) {
|
|
20
|
+
const blocks = [];
|
|
21
|
+
|
|
22
|
+
for (const { report } of results) {
|
|
23
|
+
const defectTotal = (report.summary.defects.error || 0) + (report.summary.defects.warning || 0);
|
|
24
|
+
const suggestionTotal =
|
|
25
|
+
(report.summary.suggestions.strong || 0) +
|
|
26
|
+
(report.summary.suggestions.moderate || 0) +
|
|
27
|
+
(report.summary.suggestions.hint || 0);
|
|
28
|
+
|
|
29
|
+
const coverageNote =
|
|
30
|
+
report.coverage && report.coverage.segmentCount === 0 ? " coverage=0-segments" : "";
|
|
31
|
+
const lines = [
|
|
32
|
+
`# dislop file=${report.file} engine=${report.engine} defects=${defectTotal} suggestions=${suggestionTotal}${coverageNote}`,
|
|
33
|
+
];
|
|
34
|
+
if (report.coverage && report.coverage.segmentCount === 0) {
|
|
35
|
+
lines.push(
|
|
36
|
+
`# notice: ${report.coverage.notice || "0 inspectable text segments extracted; only container checks ran."}`,
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
for (const item of report.items) {
|
|
41
|
+
const coord = formatDisplayCoordinate(item.targetId, item.line);
|
|
42
|
+
const headerKind =
|
|
43
|
+
item.kind === "defect"
|
|
44
|
+
? `DEFECT(${item.severity},${item.fixSafety})`
|
|
45
|
+
: `SUGGESTION(${item.priority},${item.fixSafety})`;
|
|
46
|
+
lines.push(`${coord} ${headerKind} ${item.ruleId}`);
|
|
47
|
+
lines.push(` quote: ${JSON.stringify(item.originalQuote)}`);
|
|
48
|
+
lines.push(` reason: ${item.reason}`);
|
|
49
|
+
|
|
50
|
+
if (item.actionType === "delete" && item.fixSafety !== "manual") {
|
|
51
|
+
lines.push(" fix: DELETE");
|
|
52
|
+
} else if (item.suggestedReplacement) {
|
|
53
|
+
lines.push(` fix: ${JSON.stringify(item.suggestedReplacement)}`);
|
|
54
|
+
} else if (item.rewritePrompt) {
|
|
55
|
+
lines.push(` prompt: ${item.rewritePrompt}`);
|
|
56
|
+
}
|
|
57
|
+
if (item.verificationNote) {
|
|
58
|
+
lines.push(` note: ${item.verificationNote}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
blocks.push(lines.join("\n"));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return `${blocks.join("\n\n")}\n`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Render `--format sarif` (SARIF 2.1.0).
|
|
70
|
+
* Maps `Suggestion` items strictly to `"note"` so IDE/GitHub integrations NEVER display red errors for prose.
|
|
71
|
+
*/
|
|
72
|
+
export function formatSarifReports(results) {
|
|
73
|
+
const rulesMap = new Map();
|
|
74
|
+
const sarifResults = [];
|
|
75
|
+
|
|
76
|
+
for (const { report } of results) {
|
|
77
|
+
for (const item of report.items) {
|
|
78
|
+
if (!rulesMap.has(item.ruleId)) {
|
|
79
|
+
rulesMap.set(item.ruleId, {
|
|
80
|
+
id: item.ruleId,
|
|
81
|
+
shortDescription: { text: item.reason },
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const level =
|
|
86
|
+
item.kind === "defect"
|
|
87
|
+
? item.severity === "error"
|
|
88
|
+
? "error"
|
|
89
|
+
: "warning"
|
|
90
|
+
: "note";
|
|
91
|
+
|
|
92
|
+
sarifResults.push({
|
|
93
|
+
ruleId: item.ruleId,
|
|
94
|
+
level,
|
|
95
|
+
message: {
|
|
96
|
+
text: item.rewritePrompt ? `${item.reason} (${item.rewritePrompt})` : item.reason,
|
|
97
|
+
},
|
|
98
|
+
locations: [
|
|
99
|
+
{
|
|
100
|
+
physicalLocation: {
|
|
101
|
+
artifactLocation: { uri: report.file },
|
|
102
|
+
region: {
|
|
103
|
+
startLine: item.line || 1,
|
|
104
|
+
snippet: { text: item.originalQuote },
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
],
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const sarif = {
|
|
114
|
+
$schema: "https://json.schemastore.org/sarif-2.1.0.json",
|
|
115
|
+
version: "2.1.0",
|
|
116
|
+
runs: [
|
|
117
|
+
{
|
|
118
|
+
tool: {
|
|
119
|
+
driver: {
|
|
120
|
+
name: "dislop",
|
|
121
|
+
version: DISLOP_VERSION,
|
|
122
|
+
informationUri: "https://dislop.com",
|
|
123
|
+
rules: Array.from(rulesMap.values()),
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
results: sarifResults,
|
|
127
|
+
},
|
|
128
|
+
],
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
return `${JSON.stringify(sarif, null, 2)}\n`;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Render `--format diff`: preview unified diff for all `safe` / `review` items without modifying disk.
|
|
136
|
+
*/
|
|
137
|
+
export function formatDiffReports(results) {
|
|
138
|
+
const chunks = [];
|
|
139
|
+
for (const { doc, items, report } of results) {
|
|
140
|
+
const patchable = items.filter(
|
|
141
|
+
(i) =>
|
|
142
|
+
i.fixSafety !== "manual" &&
|
|
143
|
+
(i.actionType === "delete" || (i.actionType === "replace" && i.suggestedReplacement !== "")),
|
|
144
|
+
);
|
|
145
|
+
if (patchable.length === 0) continue;
|
|
146
|
+
|
|
147
|
+
if (doc.format === "docx" || doc.format === "pptx") {
|
|
148
|
+
for (const p of patchable) {
|
|
149
|
+
chunks.push(
|
|
150
|
+
`--- a/${report.file} [${p.targetId}]\n+++ b/${report.file} [${p.targetId}]\n-${p.originalQuote}\n+${p.actionType === "delete" ? "" : p.suggestedReplacement}`,
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (!fs.existsSync(doc.filePath)) continue;
|
|
157
|
+
const orig = fs.readFileSync(doc.filePath, "utf8");
|
|
158
|
+
const next = applyPatchesToText(
|
|
159
|
+
orig,
|
|
160
|
+
doc,
|
|
161
|
+
patchable.map((i) => ({
|
|
162
|
+
targetId: i.targetId,
|
|
163
|
+
locator: i._locator || null,
|
|
164
|
+
originalQuote: i.originalQuote,
|
|
165
|
+
replacement: i.actionType === "delete" ? "" : i.suggestedReplacement,
|
|
166
|
+
})),
|
|
167
|
+
);
|
|
168
|
+
const diff = renderUnifiedDiff(report.file, orig, next);
|
|
169
|
+
if (diff) chunks.push(diff);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return chunks.length > 0 ? `${chunks.join("\n\n")}\n` : "";
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Render `--format text`: Dual-Track human-readable terminal report.
|
|
177
|
+
*/
|
|
178
|
+
export function formatTextReports(results, { lang = "en" } = {}) {
|
|
179
|
+
const sections = [];
|
|
180
|
+
|
|
181
|
+
for (const { report } of results) {
|
|
182
|
+
const defects = report.items.filter((i) => i.kind === "defect");
|
|
183
|
+
const suggestions = report.items.filter((i) => i.kind === "suggestion");
|
|
184
|
+
|
|
185
|
+
const lines = [
|
|
186
|
+
`${report.file} (engine: ${report.engine}, packs: ${report.mountedPacks.join(", ")})`,
|
|
187
|
+
];
|
|
188
|
+
|
|
189
|
+
if (report.documentToneAnchor) {
|
|
190
|
+
lines.push(` Tone: ${report.documentToneAnchor}`);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (report.coverage && report.coverage.segmentCount === 0) {
|
|
194
|
+
lines.push(
|
|
195
|
+
lang === "zh"
|
|
196
|
+
? ` \u63d0\u793a: ${report.coverage.notice || "\u672a\u63d0\u53d6\u5230\u53ef\u5ba1\u8ba1\u6587\u672c\u6bb5\u843d\uff08\u53ef\u80fd\u662f\u626b\u63cf\u4ef6\u6216\u7eaf\u56fe\u7247\u5bb9\u5668\uff09\uff0c\u4ec5\u8fd0\u884c\u4e86\u5bb9\u5668\u5c42\u68c0\u67e5\u3002"}`
|
|
197
|
+
: ` Notice: ${report.coverage.notice || "0 inspectable prose segments extracted (scanned PDF or visual-only container); container-level checks only."}`,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (defects.length === 0 && suggestions.length === 0) {
|
|
202
|
+
lines.push(
|
|
203
|
+
lang === "zh"
|
|
204
|
+
? " \u672a\u53d1\u73b0\u5df2\u77e5\u786c\u4f24\u6216\u53bb\u5473\u5efa\u8bae\u3002"
|
|
205
|
+
: " No artifact defects or editorial suggestions found.",
|
|
206
|
+
);
|
|
207
|
+
sections.push(lines.join("\n"));
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
if (defects.length > 0) {
|
|
212
|
+
lines.push(lang === "zh" ? "\n [\u4ea4\u4ed8\u786c\u4f24 DEFECTS]" : "\n [DEFECTS]");
|
|
213
|
+
for (const d of defects) {
|
|
214
|
+
const coord = formatDisplayCoordinate(d.targetId, d.line);
|
|
215
|
+
lines.push(` - ${d.severity.toUpperCase().padEnd(7)} ${coord} ${d.ruleId} (${d.fixSafety})`);
|
|
216
|
+
lines.push(` Quote : "${d.originalQuote}"`);
|
|
217
|
+
lines.push(` Reason: ${d.reason}`);
|
|
218
|
+
if (d.actionType === "delete" && d.fixSafety !== "manual") {
|
|
219
|
+
lines.push(" Fix : (Delete span)");
|
|
220
|
+
} else if (d.suggestedReplacement) {
|
|
221
|
+
lines.push(` Fix : "${d.suggestedReplacement}"`);
|
|
222
|
+
} else if (d.rewritePrompt) {
|
|
223
|
+
lines.push(` Action: ${d.rewritePrompt}`);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (suggestions.length > 0) {
|
|
229
|
+
lines.push(
|
|
230
|
+
lang === "zh"
|
|
231
|
+
? "\n [\u7f16\u8f91\u5efa\u8bae SUGGESTIONS \u2014 exit 0]"
|
|
232
|
+
: "\n [SUGGESTIONS — non-blocking, exit 0]",
|
|
233
|
+
);
|
|
234
|
+
for (const s of suggestions) {
|
|
235
|
+
const coord = formatDisplayCoordinate(s.targetId, s.line);
|
|
236
|
+
lines.push(` - ${s.priority.toUpperCase().padEnd(8)} ${coord} ${s.ruleId} (${s.fixSafety})`);
|
|
237
|
+
lines.push(` Quote : "${s.originalQuote}"`);
|
|
238
|
+
lines.push(` Reason: ${s.reason}`);
|
|
239
|
+
if (s.actionType === "delete" && s.fixSafety !== "manual") {
|
|
240
|
+
lines.push(" Fix : (Delete sentence)");
|
|
241
|
+
} else if (s.suggestedReplacement) {
|
|
242
|
+
lines.push(` Fix : "${s.suggestedReplacement}"`);
|
|
243
|
+
} else if (s.rewritePrompt) {
|
|
244
|
+
lines.push(` Prompt: ${s.rewritePrompt}`);
|
|
245
|
+
}
|
|
246
|
+
if (s.verificationNote) {
|
|
247
|
+
lines.push(` Gate : ${s.verificationNote}`);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
sections.push(lines.join("\n"));
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return `${sections.join("\n\n")}\n`;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function renderReports(results, format = "text", { lang = "en" } = {}) {
|
|
259
|
+
switch (format) {
|
|
260
|
+
case "json":
|
|
261
|
+
return formatJsonReports(results);
|
|
262
|
+
case "agent":
|
|
263
|
+
return formatAgentReports(results);
|
|
264
|
+
case "sarif":
|
|
265
|
+
return formatSarifReports(results);
|
|
266
|
+
case "diff":
|
|
267
|
+
return formatDiffReports(results);
|
|
268
|
+
case "text":
|
|
269
|
+
default:
|
|
270
|
+
return formatTextReports(results, { lang });
|
|
271
|
+
}
|
|
272
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Estimate token count conservatively across Latin and CJK scripts.
|
|
3
|
+
*/
|
|
4
|
+
export function estimateTokens(text) {
|
|
5
|
+
const s = String(text || "");
|
|
6
|
+
if (!s) return 0;
|
|
7
|
+
const cjk = (s.match(/[\u4e00-\u9fff\u3000-\u303f\uff00-\uffef]/g) || []).length;
|
|
8
|
+
const other = s.length - cjk;
|
|
9
|
+
return Math.ceil(cjk / 1.5 + other / 3.6);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Partition `doc.segments` along paragraph boundaries with a 1-paragraph read-only
|
|
14
|
+
* lookbehind (`[CTX-P{k}]`) whenever input exceeds `maxInputTokens`.
|
|
15
|
+
*/
|
|
16
|
+
export function buildSlidingWindowChunks(doc, { maxInputTokens = 12000, reservedOverheadTokens = 1800 } = {}) {
|
|
17
|
+
const segments = doc.segments || [];
|
|
18
|
+
if (segments.length === 0) return [];
|
|
19
|
+
|
|
20
|
+
const budget = Math.max(600, maxInputTokens - reservedOverheadTokens);
|
|
21
|
+
|
|
22
|
+
// Group segments by paragraphId preserving document order
|
|
23
|
+
const paraGroups = [];
|
|
24
|
+
let currentGroup = null;
|
|
25
|
+
for (const seg of segments) {
|
|
26
|
+
if (!currentGroup || currentGroup.paragraphId !== seg.paragraphId) {
|
|
27
|
+
currentGroup = {
|
|
28
|
+
paragraphId: seg.paragraphId,
|
|
29
|
+
segments: [],
|
|
30
|
+
tokens: 0,
|
|
31
|
+
};
|
|
32
|
+
paraGroups.push(currentGroup);
|
|
33
|
+
}
|
|
34
|
+
currentGroup.segments.push(seg);
|
|
35
|
+
currentGroup.tokens += estimateTokens(`[${seg.id}] ${seg.text}\n`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const totalTokens = paraGroups.reduce((acc, g) => acc + g.tokens, 0);
|
|
39
|
+
if (totalTokens <= budget) {
|
|
40
|
+
return [
|
|
41
|
+
{
|
|
42
|
+
chunkIndex: 0,
|
|
43
|
+
readonlyContext: [],
|
|
44
|
+
segments: [...segments],
|
|
45
|
+
},
|
|
46
|
+
];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const chunks = [];
|
|
50
|
+
let currentParas = [];
|
|
51
|
+
let currentTokens = 0;
|
|
52
|
+
let prevLastParagraph = null;
|
|
53
|
+
|
|
54
|
+
const flushChunk = () => {
|
|
55
|
+
if (currentParas.length === 0) return;
|
|
56
|
+
const readonlyContext = prevLastParagraph
|
|
57
|
+
? [
|
|
58
|
+
{
|
|
59
|
+
ctxId: `CTX-${prevLastParagraph.paragraphId}`,
|
|
60
|
+
paragraphId: prevLastParagraph.paragraphId,
|
|
61
|
+
text: prevLastParagraph.segments.map((s) => s.text).join(" "),
|
|
62
|
+
},
|
|
63
|
+
]
|
|
64
|
+
: [];
|
|
65
|
+
|
|
66
|
+
chunks.push({
|
|
67
|
+
chunkIndex: chunks.length,
|
|
68
|
+
readonlyContext,
|
|
69
|
+
segments: currentParas.flatMap((g) => g.segments),
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
prevLastParagraph = currentParas[currentParas.length - 1];
|
|
73
|
+
currentParas = [];
|
|
74
|
+
currentTokens = 0;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
for (const grp of paraGroups) {
|
|
78
|
+
if (currentParas.length > 0 && currentTokens + grp.tokens > budget) {
|
|
79
|
+
flushChunk();
|
|
80
|
+
}
|
|
81
|
+
currentParas.push(grp);
|
|
82
|
+
currentTokens += grp.tokens;
|
|
83
|
+
}
|
|
84
|
+
flushChunk();
|
|
85
|
+
|
|
86
|
+
return chunks;
|
|
87
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 3-stage structured output fallback & state-machine JSON sanitizer.
|
|
3
|
+
* Handles reasoning model `<think>...</think>` blocks, Markdown code fences,
|
|
4
|
+
* trailing commas, and unescaped literal control newlines inside JSON string values.
|
|
5
|
+
*/
|
|
6
|
+
export function extractStructuredJson(rawText) {
|
|
7
|
+
const input = String(rawText ?? "").trim();
|
|
8
|
+
if (!input) {
|
|
9
|
+
throw new Error("Empty LLM response body");
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// Strip `<think>...</think>` blocks emitted by reasoning models
|
|
13
|
+
const stripped = input.replace(/<think\b[^>]*>[\s\S]*?<\/think>/gi, "").trim();
|
|
14
|
+
|
|
15
|
+
// Stage 1: Direct JSON.parse
|
|
16
|
+
try {
|
|
17
|
+
return JSON.parse(stripped);
|
|
18
|
+
} catch {
|
|
19
|
+
// proceed to Stage 2
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Stage 2: Fenced ```json ... ``` or ``` ... ``` block
|
|
23
|
+
const fenceRe = /```(?:json|JSON)?\s*\r?\n([\s\S]*?)\r?\n?```/g;
|
|
24
|
+
let fm;
|
|
25
|
+
while ((fm = fenceRe.exec(stripped)) !== null) {
|
|
26
|
+
const candidate = fm[1].trim();
|
|
27
|
+
try {
|
|
28
|
+
return JSON.parse(candidate);
|
|
29
|
+
} catch {
|
|
30
|
+
try {
|
|
31
|
+
return JSON.parse(sanitizeJsonStringStateMachine(candidate));
|
|
32
|
+
} catch {
|
|
33
|
+
// continue scanning
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Stage 3: Balanced object/array state-machine scan + sanitizer
|
|
39
|
+
const balanced = findFirstBalancedJsonContainer(stripped);
|
|
40
|
+
if (balanced) {
|
|
41
|
+
try {
|
|
42
|
+
return JSON.parse(balanced);
|
|
43
|
+
} catch {
|
|
44
|
+
const sanitized = sanitizeJsonStringStateMachine(balanced);
|
|
45
|
+
return JSON.parse(sanitized);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
throw new Error("Unable to extract valid JSON object from LLM response");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function findFirstBalancedJsonContainer(text) {
|
|
53
|
+
const firstBrace = text.indexOf("{");
|
|
54
|
+
const firstBracket = text.indexOf("[");
|
|
55
|
+
let start = -1;
|
|
56
|
+
if (firstBrace !== -1 && firstBracket !== -1) start = Math.min(firstBrace, firstBracket);
|
|
57
|
+
else start = firstBrace !== -1 ? firstBrace : firstBracket;
|
|
58
|
+
if (start === -1) return null;
|
|
59
|
+
|
|
60
|
+
const stack = [];
|
|
61
|
+
let inString = false;
|
|
62
|
+
let escaped = false;
|
|
63
|
+
|
|
64
|
+
for (let i = start; i < text.length; i += 1) {
|
|
65
|
+
const ch = text[i];
|
|
66
|
+
if (inString) {
|
|
67
|
+
if (escaped) {
|
|
68
|
+
escaped = false;
|
|
69
|
+
} else if (ch === "\\") {
|
|
70
|
+
escaped = true;
|
|
71
|
+
} else if (ch === '"') {
|
|
72
|
+
inString = false;
|
|
73
|
+
}
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (ch === '"') {
|
|
78
|
+
inString = true;
|
|
79
|
+
} else if (ch === "{") {
|
|
80
|
+
stack.push("}");
|
|
81
|
+
} else if (ch === "[") {
|
|
82
|
+
stack.push("]");
|
|
83
|
+
} else if (ch === "}" || ch === "]") {
|
|
84
|
+
if (stack.length === 0) return null;
|
|
85
|
+
const expected = stack.pop();
|
|
86
|
+
if (ch !== expected) return null;
|
|
87
|
+
if (stack.length === 0) {
|
|
88
|
+
return text.slice(start, i + 1);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function sanitizeJsonStringStateMachine(raw) {
|
|
97
|
+
let out = "";
|
|
98
|
+
let inString = false;
|
|
99
|
+
let escaped = false;
|
|
100
|
+
|
|
101
|
+
for (let i = 0; i < raw.length; i += 1) {
|
|
102
|
+
const ch = raw[i];
|
|
103
|
+
if (inString) {
|
|
104
|
+
if (escaped) {
|
|
105
|
+
out += ch;
|
|
106
|
+
escaped = false;
|
|
107
|
+
} else if (ch === "\\") {
|
|
108
|
+
out += ch;
|
|
109
|
+
escaped = true;
|
|
110
|
+
} else if (ch === '"') {
|
|
111
|
+
out += ch;
|
|
112
|
+
inString = false;
|
|
113
|
+
} else if (ch === "\n") {
|
|
114
|
+
out += "\\n";
|
|
115
|
+
} else if (ch === "\r") {
|
|
116
|
+
// skip bare CR inside string
|
|
117
|
+
} else if (ch === "\t") {
|
|
118
|
+
out += "\\t";
|
|
119
|
+
} else {
|
|
120
|
+
out += ch;
|
|
121
|
+
}
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (ch === '"') {
|
|
126
|
+
inString = true;
|
|
127
|
+
out += ch;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Strip trailing commas before `}` or `]` outside strings
|
|
132
|
+
if (ch === ",") {
|
|
133
|
+
let lookahead = i + 1;
|
|
134
|
+
while (lookahead < raw.length && /\s/.test(raw[lookahead])) lookahead += 1;
|
|
135
|
+
if (raw[lookahead] === "}" || raw[lookahead] === "]") {
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
out += ch;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import readline from "node:readline";
|
|
2
|
+
import { readJsonFileStrict, writeJsonFileSecure } from "../kernel/config.mjs";
|
|
3
|
+
|
|
4
|
+
export function isLoopbackHostname(hostname) {
|
|
5
|
+
const h = String(hostname || "")
|
|
6
|
+
.trim()
|
|
7
|
+
.toLowerCase()
|
|
8
|
+
.replace(/^\[|\]$/g, "");
|
|
9
|
+
return h === "localhost" || h === "127.0.0.1" || h === "::1" || h === "0.0.0.0";
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function extractHostname(baseUrl) {
|
|
13
|
+
try {
|
|
14
|
+
return new URL(baseUrl).hostname.toLowerCase();
|
|
15
|
+
} catch {
|
|
16
|
+
return "";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function askYesNoLine(question, { stdin = process.stdin, stderr = process.stderr } = {}) {
|
|
21
|
+
return new Promise((resolve) => {
|
|
22
|
+
const rl = readline.createInterface({
|
|
23
|
+
input: stdin,
|
|
24
|
+
output: stderr,
|
|
25
|
+
});
|
|
26
|
+
rl.question(question, (answer) => {
|
|
27
|
+
rl.close();
|
|
28
|
+
const normalized = String(answer || "").trim().toLowerCase();
|
|
29
|
+
resolve(normalized === "y" || normalized === "yes");
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* First-run privacy consent gate for ambient environment API keys (`privacy-gate.mjs`).
|
|
36
|
+
* - Loopback endpoints (`127.0.0.1`, `localhost`) are always approved.
|
|
37
|
+
* - Keys configured directly in `config.json` (or hosts already in `config.approvedHosts`) are approved.
|
|
38
|
+
* - Explicit `--engine byok` CLI invocation counts as explicit user authorization for the run.
|
|
39
|
+
* - Ambient env-only keys in TTY prompt once and persist `approvedHosts` in `~/.config/dislop/config.json`.
|
|
40
|
+
* - Ambient env-only keys in Non-TTY never upload silently; skips Tier 2 with a `stderr` notice.
|
|
41
|
+
*/
|
|
42
|
+
export async function checkPrivacyConsent({
|
|
43
|
+
provider,
|
|
44
|
+
config,
|
|
45
|
+
isTty,
|
|
46
|
+
explicitByokFlag = false,
|
|
47
|
+
stdin = process.stdin,
|
|
48
|
+
stderr = process.stderr,
|
|
49
|
+
promptFn = null,
|
|
50
|
+
}) {
|
|
51
|
+
const host = extractHostname(provider.baseUrl);
|
|
52
|
+
if (!host || isLoopbackHostname(host)) {
|
|
53
|
+
return { approved: true, host };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Pre-authorized host or explicit config-sourced provider (not ambient env discovery)
|
|
57
|
+
if (!provider.fromAmbientEnv) {
|
|
58
|
+
return { approved: true, host };
|
|
59
|
+
}
|
|
60
|
+
if ((config.approvedHosts || []).map((h) => h.toLowerCase()).includes(host)) {
|
|
61
|
+
return { approved: true, host };
|
|
62
|
+
}
|
|
63
|
+
if (explicitByokFlag) {
|
|
64
|
+
return { approved: true, host };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (!isTty) {
|
|
68
|
+
stderr.write(
|
|
69
|
+
`[dislop] Skipping unapproved ambient key ${provider.envVarName} for '${host}' in non-interactive mode (pass --engine byok or add '${host}' to approvedHosts in config.json).\n`,
|
|
70
|
+
);
|
|
71
|
+
return { approved: false, host };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const question = `Detected ${provider.envVarName}. Allow dislop to send document text to ${host} for review? [y/N] `;
|
|
75
|
+
const accepted = promptFn ? await promptFn(question, host) : await askYesNoLine(question, { stdin, stderr });
|
|
76
|
+
|
|
77
|
+
if (!accepted) {
|
|
78
|
+
return { approved: false, host };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Persist host approval to user config.json
|
|
82
|
+
try {
|
|
83
|
+
const existing = readJsonFileStrict(config.userConfigPath) || {};
|
|
84
|
+
const prevHosts = Array.isArray(existing.approvedHosts) ? existing.approvedHosts : [];
|
|
85
|
+
const nextHosts = Array.from(new Set([...prevHosts, host]));
|
|
86
|
+
writeJsonFileSecure(
|
|
87
|
+
config.userConfigPath,
|
|
88
|
+
{ ...existing, approvedHosts: nextHosts },
|
|
89
|
+
{ mode: 0o600 },
|
|
90
|
+
);
|
|
91
|
+
config.approvedHosts = Array.from(new Set([...(config.approvedHosts || []), host]));
|
|
92
|
+
} catch {
|
|
93
|
+
// Even if disk persistence fails (e.g., read-only home), honor approval for current invocation
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return { approved: true, host };
|
|
97
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { extractStructuredJson } from "../json-extract.mjs";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Tier 2 Anthropic `/v1/messages` adapter.
|
|
5
|
+
*/
|
|
6
|
+
export async function invokeAnthropicProvider({
|
|
7
|
+
provider,
|
|
8
|
+
payload,
|
|
9
|
+
timeoutMs = 60000,
|
|
10
|
+
fetchImpl = globalThis.fetch,
|
|
11
|
+
}) {
|
|
12
|
+
const baseUrl = String(provider.baseUrl || "https://api.anthropic.com/v1").replace(/\/+$/, "");
|
|
13
|
+
const url = `${baseUrl}/messages`;
|
|
14
|
+
const model = provider.model || "claude-3-5-haiku-latest";
|
|
15
|
+
|
|
16
|
+
if (!provider.apiKey) {
|
|
17
|
+
const err = new Error(`Anthropic provider '${provider.name}' is missing an API key`);
|
|
18
|
+
err.authError = true;
|
|
19
|
+
throw err;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const controller = new AbortController();
|
|
23
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
24
|
+
|
|
25
|
+
try {
|
|
26
|
+
const res = await fetchImpl(url, {
|
|
27
|
+
method: "POST",
|
|
28
|
+
headers: {
|
|
29
|
+
"Content-Type": "application/json",
|
|
30
|
+
"x-api-key": provider.apiKey,
|
|
31
|
+
"anthropic-version": "2023-06-01",
|
|
32
|
+
},
|
|
33
|
+
body: JSON.stringify({
|
|
34
|
+
model,
|
|
35
|
+
max_tokens: provider.maxOutputTokens || 4096,
|
|
36
|
+
temperature: 0.1,
|
|
37
|
+
system: payload.systemPrompt,
|
|
38
|
+
messages: [{ role: "user", content: payload.userPrompt }],
|
|
39
|
+
}),
|
|
40
|
+
signal: controller.signal,
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
if (res.status === 401 || res.status === 403) {
|
|
44
|
+
const err = new Error(`Anthropic provider '${provider.name}' rejected API key (HTTP ${res.status})`);
|
|
45
|
+
err.authError = true;
|
|
46
|
+
throw err;
|
|
47
|
+
}
|
|
48
|
+
if (!res.ok) {
|
|
49
|
+
const errText = await res.text().catch(() => "");
|
|
50
|
+
throw new Error(`Anthropic provider '${provider.name}' HTTP ${res.status}: ${errText.slice(0, 240)}`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const json = await res.json();
|
|
54
|
+
const textBlocks = Array.isArray(json?.content)
|
|
55
|
+
? json.content.filter((b) => b.type === "text").map((b) => b.text)
|
|
56
|
+
: [];
|
|
57
|
+
const content = textBlocks.join("\n").trim();
|
|
58
|
+
if (!content) {
|
|
59
|
+
throw new Error(`Anthropic provider '${provider.name}' returned empty text content`);
|
|
60
|
+
}
|
|
61
|
+
return extractStructuredJson(content);
|
|
62
|
+
} finally {
|
|
63
|
+
clearTimeout(timer);
|
|
64
|
+
}
|
|
65
|
+
}
|