dislop 0.9.1 → 1.0.1
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 +360 -252
- package/README.zh-CN.md +390 -240
- 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 +173 -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 +290 -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/references/essay.md +1 -1
- package/skills/dislop/references/essay.zh-CN.md +1 -1
- package/skills/dislop/references/office.md +1 -1
- package/skills/dislop/references/office.zh-CN.md +1 -1
- package/skills/dislop/references/web-ui.md +1 -1
- package/skills/dislop/references/web-ui.zh-CN.md +1 -1
- package/skills/dislop/references/work-docs.md +1 -1
- package/skills/dislop/references/work-docs.zh-CN.md +1 -1
- package/src/cli-main.mjs +210 -0
- package/src/commands/check-fix.mjs +169 -0
- package/src/commands/doctor.mjs +110 -0
- package/src/commands/init.mjs +49 -0
- package/src/commands/login.mjs +82 -0
- package/src/commands/model.mjs +130 -0
- package/src/commands/packs.mjs +44 -0
- package/src/commands/verify.mjs +133 -0
- package/src/commands/voice.mjs +84 -0
- package/src/kernel/config.mjs +232 -0
- package/src/kernel/document-model.mjs +1412 -0
- package/src/kernel/fact-gate.mjs +615 -0
- package/src/kernel/file-discovery.mjs +139 -0
- package/src/{binary-node.mjs → kernel/ooxml-binary.mjs} +532 -893
- package/src/kernel/pack-loader.mjs +715 -0
- package/src/kernel/patcher.mjs +341 -0
- package/src/kernel/pipeline.mjs +267 -0
- package/src/kernel/prompt-assembler.mjs +307 -0
- package/src/kernel/voice-profile.mjs +177 -0
- package/src/mcp/stdio-server.mjs +372 -0
- package/src/runners/auto-fix.mjs +59 -0
- package/src/runners/interactive-tty.mjs +461 -0
- package/src/runners/reporters.mjs +256 -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 +136 -0
- package/src/runtime/providers/gemini.mjs +91 -0
- package/src/runtime/providers/local-model.mjs +139 -0
- package/src/runtime/providers/openai-compat.mjs +130 -0
- package/src/runtime/router.mjs +315 -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,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
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { extractStructuredJson } from "../json-extract.mjs";
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_CLOUD_REVIEW_URL = "https://dislop.com/api/v1/review";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Tier 1 Official Cloud adapter (`POST https://dislop.com/api/v1/review`).
|
|
7
|
+
*/
|
|
8
|
+
export async function invokeCloudProvider({
|
|
9
|
+
credentials,
|
|
10
|
+
payload,
|
|
11
|
+
doc,
|
|
12
|
+
promptRules,
|
|
13
|
+
timeoutMs = 45000,
|
|
14
|
+
fetchImpl = globalThis.fetch,
|
|
15
|
+
env = process.env,
|
|
16
|
+
}) {
|
|
17
|
+
const endpoint = env.DISLOP_CLOUD_URL || credentials?.endpoint || DEFAULT_CLOUD_REVIEW_URL;
|
|
18
|
+
const token = credentials?.accessToken || credentials?.token || credentials?.apiKey;
|
|
19
|
+
if (!token) {
|
|
20
|
+
const err = new Error("Missing Official Cloud token in credentials.json. Run 'dislop login'.");
|
|
21
|
+
err.authError = true;
|
|
22
|
+
throw err;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const controller = new AbortController();
|
|
26
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
27
|
+
|
|
28
|
+
try {
|
|
29
|
+
const res = await fetchImpl(endpoint, {
|
|
30
|
+
method: "POST",
|
|
31
|
+
headers: {
|
|
32
|
+
"Content-Type": "application/json",
|
|
33
|
+
Authorization: `Bearer ${token}`,
|
|
34
|
+
"User-Agent": "dislop-cli/1.0.1",
|
|
35
|
+
},
|
|
36
|
+
body: JSON.stringify({
|
|
37
|
+
schema: "dislop.review-request/1",
|
|
38
|
+
text: Array.isArray(doc?.segments)
|
|
39
|
+
? doc.segments.map((s) => s.text).join("\n\n")
|
|
40
|
+
: String(payload?.userPrompt || ""),
|
|
41
|
+
file: doc?.filePath || "",
|
|
42
|
+
format: doc?.format || "md",
|
|
43
|
+
modality: doc?.format || "md",
|
|
44
|
+
language: doc?.language || "en",
|
|
45
|
+
systemPrompt: payload.systemPrompt,
|
|
46
|
+
userPrompt: payload.userPrompt,
|
|
47
|
+
rules: promptRules,
|
|
48
|
+
}),
|
|
49
|
+
signal: controller.signal,
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
if (res.status === 401 || res.status === 403) {
|
|
53
|
+
const err = new Error(`Official Cloud authentication failed (HTTP ${res.status}). Run 'dislop login'.`);
|
|
54
|
+
err.authError = true;
|
|
55
|
+
throw err;
|
|
56
|
+
}
|
|
57
|
+
if (!res.ok) {
|
|
58
|
+
const bodyText = await res.text().catch(() => "");
|
|
59
|
+
throw new Error(`Official Cloud request failed (HTTP ${res.status}): ${bodyText.slice(0, 240)}`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const data = await res.json();
|
|
63
|
+
if (data && typeof data === "object" && Array.isArray(data.items)) {
|
|
64
|
+
return data;
|
|
65
|
+
}
|
|
66
|
+
if (data && typeof data === "object" && Array.isArray(data.findings)) {
|
|
67
|
+
return adaptLegacyCloudFindings(data, doc, promptRules);
|
|
68
|
+
}
|
|
69
|
+
if (typeof data?.content === "string") {
|
|
70
|
+
return extractStructuredJson(data.content);
|
|
71
|
+
}
|
|
72
|
+
return data;
|
|
73
|
+
} finally {
|
|
74
|
+
clearTimeout(timer);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function adaptLegacyCloudFindings(data, doc, promptRules = []) {
|
|
79
|
+
const proseFallbackRule =
|
|
80
|
+
promptRules.find((r) => r.ruleId.endsWith("/stealth-vapor"))?.ruleId ||
|
|
81
|
+
promptRules[0]?.ruleId ||
|
|
82
|
+
`${doc.language || "en"}/prose/stealth-vapor`;
|
|
83
|
+
const mountedByFull = new Map(promptRules.map((r) => [r.ruleId, r.ruleId]));
|
|
84
|
+
const mountedByBare = new Map();
|
|
85
|
+
for (const r of promptRules) {
|
|
86
|
+
const bare = r.ruleId.split("/").pop();
|
|
87
|
+
if (!mountedByBare.has(bare)) mountedByBare.set(bare, r.ruleId);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const items = [];
|
|
91
|
+
for (const f of data.findings || []) {
|
|
92
|
+
if (!f || typeof f !== "object") continue;
|
|
93
|
+
const rawQuote = String(f.anchor?.quote || f.revision?.find || "").trim();
|
|
94
|
+
const seg =
|
|
95
|
+
(rawQuote && doc.segments.find((s) => s.text.includes(rawQuote))) ||
|
|
96
|
+
(rawQuote && doc.segments.find((s) => rawQuote.includes(s.text))) ||
|
|
97
|
+
null;
|
|
98
|
+
if (!seg) continue;
|
|
99
|
+
|
|
100
|
+
const quote = seg.text.includes(rawQuote) ? rawQuote : seg.text;
|
|
101
|
+
const bareId = f.ruleId ? String(f.ruleId).split("/").pop() : "";
|
|
102
|
+
const ruleId =
|
|
103
|
+
mountedByFull.get(f.ruleId) || mountedByBare.get(bareId) || proseFallbackRule;
|
|
104
|
+
const priority = f.severity === "error" ? "strong" : f.severity === "warning" ? "moderate" : "hint";
|
|
105
|
+
const rev = f.revision || {};
|
|
106
|
+
|
|
107
|
+
let actionType = "prompt";
|
|
108
|
+
let fixSafety = "manual";
|
|
109
|
+
let suggestedReplacement = "";
|
|
110
|
+
let rewritePrompt = String(rev.instruction || rev.question || f.why || "").trim();
|
|
111
|
+
if (rev.kind === "edit") {
|
|
112
|
+
const rep = String(rev.replace ?? "");
|
|
113
|
+
actionType = rep === "" ? "delete" : "replace";
|
|
114
|
+
fixSafety = "review";
|
|
115
|
+
suggestedReplacement = rep;
|
|
116
|
+
rewritePrompt = "";
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
items.push({
|
|
120
|
+
ruleId,
|
|
121
|
+
targetId: seg.id,
|
|
122
|
+
priority,
|
|
123
|
+
fixSafety,
|
|
124
|
+
actionType,
|
|
125
|
+
originalQuote: quote,
|
|
126
|
+
suggestedReplacement,
|
|
127
|
+
reason: String(f.why || "").trim() || "Editorial issue flagged by Official Cloud.",
|
|
128
|
+
rewritePrompt,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return {
|
|
133
|
+
documentToneAnchor: String(data?.llmReview?.summary || "").trim(),
|
|
134
|
+
items,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { extractStructuredJson } from "../json-extract.mjs";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Tier 2 Google Gemini `:generateContent` adapter.
|
|
5
|
+
*/
|
|
6
|
+
export async function invokeGeminiProvider({
|
|
7
|
+
provider,
|
|
8
|
+
payload,
|
|
9
|
+
timeoutMs = 60000,
|
|
10
|
+
fetchImpl = globalThis.fetch,
|
|
11
|
+
}) {
|
|
12
|
+
const baseUrl = String(
|
|
13
|
+
provider.baseUrl || "https://generativelanguage.googleapis.com/v1beta",
|
|
14
|
+
).replace(/\/+$/, "");
|
|
15
|
+
const model = String(provider.model || "gemini-3.8-flash").replace(/^models\//, "");
|
|
16
|
+
|
|
17
|
+
if (!provider.apiKey) {
|
|
18
|
+
const err = new Error(`Gemini provider '${provider.name}' is missing an API key`);
|
|
19
|
+
err.authError = true;
|
|
20
|
+
throw err;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const url = `${baseUrl}/models/${encodeURIComponent(model)}:generateContent`;
|
|
24
|
+
const controller = new AbortController();
|
|
25
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
26
|
+
|
|
27
|
+
try {
|
|
28
|
+
const res = await fetchImpl(url, {
|
|
29
|
+
method: "POST",
|
|
30
|
+
headers: {
|
|
31
|
+
"Content-Type": "application/json",
|
|
32
|
+
"x-goog-api-key": provider.apiKey,
|
|
33
|
+
},
|
|
34
|
+
body: JSON.stringify({
|
|
35
|
+
systemInstruction: {
|
|
36
|
+
parts: [{ text: payload.systemPrompt }],
|
|
37
|
+
},
|
|
38
|
+
contents: [
|
|
39
|
+
{
|
|
40
|
+
role: "user",
|
|
41
|
+
parts: [{ text: payload.userPrompt }],
|
|
42
|
+
},
|
|
43
|
+
],
|
|
44
|
+
generationConfig: {
|
|
45
|
+
temperature: 0.1,
|
|
46
|
+
maxOutputTokens: provider.maxOutputTokens || 8192,
|
|
47
|
+
responseMimeType: "application/json",
|
|
48
|
+
},
|
|
49
|
+
}),
|
|
50
|
+
signal: controller.signal,
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
if (res.status === 401 || res.status === 403) {
|
|
54
|
+
const err = new Error(`Gemini provider '${provider.name}' rejected API key (HTTP ${res.status})`);
|
|
55
|
+
err.authError = true;
|
|
56
|
+
throw err;
|
|
57
|
+
}
|
|
58
|
+
if (!res.ok) {
|
|
59
|
+
const errText = await res.text().catch(() => "");
|
|
60
|
+
throw new Error(`Gemini provider '${provider.name}' HTTP ${res.status}: ${errText.slice(0, 240)}`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const json = await res.json();
|
|
64
|
+
const candidate = json?.candidates?.[0] || {};
|
|
65
|
+
const finishReason = candidate?.finishReason || "";
|
|
66
|
+
const parts = candidate?.content?.parts || [];
|
|
67
|
+
const content = parts
|
|
68
|
+
.filter((p) => !p?.thought)
|
|
69
|
+
.map((p) => p.text || "")
|
|
70
|
+
.join("\n")
|
|
71
|
+
.trim();
|
|
72
|
+
if (!content) {
|
|
73
|
+
if (finishReason === "MAX_TOKENS") {
|
|
74
|
+
throw new Error(`Gemini provider '${provider.name}' truncated output at MAX_TOKENS before returning JSON`);
|
|
75
|
+
}
|
|
76
|
+
throw new Error(`Gemini provider '${provider.name}' returned empty candidate parts`);
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
return extractStructuredJson(content);
|
|
80
|
+
} catch (parseErr) {
|
|
81
|
+
if (finishReason === "MAX_TOKENS") {
|
|
82
|
+
throw new Error(
|
|
83
|
+
`Gemini provider '${provider.name}' hit MAX_TOKENS while emitting JSON: ${parseErr.message}`,
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
throw parseErr;
|
|
87
|
+
}
|
|
88
|
+
} finally {
|
|
89
|
+
clearTimeout(timer);
|
|
90
|
+
}
|
|
91
|
+
}
|