@tagma/completion-llm-judge 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tagma
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,100 @@
1
+ # @tagma/completion-llm-judge
2
+
3
+ LLM-as-judge completion plugin for [@tagma/sdk](https://www.npmjs.com/package/@tagma/sdk).
4
+
5
+ Uses an OpenAI-compatible chat completions endpoint to verify whether a task's output satisfies a rubric. Complements the deterministic built-in completions (`exit_code`, `file_exists`, `output_check`) when task success is defined semantically rather than by a grep-able pattern.
6
+
7
+ **Default backend**: local [Ollama](https://ollama.com/) with `qwen3:4b` — a small reasoning model that runs on CPU with no API key. Swap `endpoint` + `model` to point at any OpenAI-compatible server (OpenAI, vLLM, llama.cpp, LM Studio, Groq, Together, OpenRouter, ...).
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ bun add @tagma/completion-llm-judge
13
+ ```
14
+
15
+ Then make sure Ollama is running with the default model pulled:
16
+
17
+ ```bash
18
+ ollama pull qwen3:4b
19
+ ollama serve # usually auto-started
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ```yaml
25
+ pipeline:
26
+ name: qa-loop
27
+ plugins:
28
+ - "@tagma/completion-llm-judge"
29
+ tracks:
30
+ - id: qa
31
+ name: QA
32
+ driver: claude-code
33
+ tasks:
34
+ - id: find-bugs
35
+ name: Find failing tests
36
+ prompt: "List all failing tests in the current workspace with their file paths."
37
+ output: ./output/find-bugs.md
38
+ completion:
39
+ type: llm_judge
40
+ rubric: |
41
+ The output must list at least 3 failing tests. Each entry must
42
+ include the test name, the file path, and the assertion that
43
+ failed. The output must not be an empty placeholder.
44
+ # endpoint / model / api_key_env all default to local Ollama + qwen3:4b
45
+ timeout: 120s
46
+ ```
47
+
48
+ Swap to a hosted backend:
49
+
50
+ ```yaml
51
+ completion:
52
+ type: llm_judge
53
+ rubric: "..."
54
+ endpoint: https://api.openai.com/v1/chat/completions
55
+ model: gpt-4o-mini
56
+ api_key_env: OPENAI_API_KEY
57
+ ```
58
+
59
+ Or load it programmatically:
60
+
61
+ ```ts
62
+ import { bootstrapBuiltins, loadPlugins } from '@tagma/sdk';
63
+
64
+ bootstrapBuiltins();
65
+ await loadPlugins(['@tagma/completion-llm-judge']);
66
+ ```
67
+
68
+ ## Config
69
+
70
+ | Field | Type | Default | Notes |
71
+ |--------------------|----------|-------------------------------------------------|-------------------------------------------------------------------------------------------|
72
+ | `rubric` | string | *(required)* | Plain-language success criteria the judge should verify |
73
+ | `model` | string | `qwen3:4b` | Judge model name. Swap for `qwen3:8b`, `deepseek-r1:7b`, `gpt-4o-mini`, etc. |
74
+ | `endpoint` | string | `http://localhost:11434/v1/chat/completions` | OpenAI-compatible chat completions URL. Default points at local Ollama |
75
+ | `api_key_env` | string | *(none)* | Env var holding the bearer token. Leave unset for local Ollama; set for hosted backends |
76
+ | `timeout` | duration | `120s` | Max time to wait for the judge response (reasoning models need more time than chat models)|
77
+ | `max_output_chars` | number | `8000` | Truncate task stdout before judging (head+tail preserved) |
78
+
79
+ ## Behavior
80
+
81
+ - **Verdict format**: the judge is instructed to answer `PASS` or `FAIL` on the first line. Missing or ambiguous answers are treated as FAIL — a judge that errs open defeats the purpose of the gate.
82
+ - **Reasoning-model support**: `<think>...</think>` and `<thinking>...</thinking>` blocks are stripped from the response before verdict parsing, so qwen3, DeepSeek-R1, and other thinkers work without any extra config.
83
+ - **Truncation**: task stdout longer than `max_output_chars` is truncated head-and-tail (70/30 split) with a marker in the middle, so the judge still sees the task's intent and its final summary.
84
+ - **Error handling**: network errors, auth errors, timeout, or malformed responses all mark the task as not-complete and log a warning with the judge's verbatim response (if any).
85
+ - **Abort propagation**: the pipeline abort signal is wired into the judge fetch call, so cancelling a pipeline also cancels any in-flight judge request.
86
+ - **Determinism**: the call uses `temperature: 0` to keep verdicts as stable as the model allows.
87
+
88
+ ## Alternative endpoints
89
+
90
+ Any OpenAI-compatible endpoint works — just point `endpoint` and `api_key_env` at it:
91
+
92
+ - **Local Ollama** (default): `http://localhost:11434/v1/chat/completions`, no API key
93
+ - **OpenAI**: `https://api.openai.com/v1/chat/completions`, `api_key_env: OPENAI_API_KEY`
94
+ - **Local models** via LM Studio, vLLM, llama.cpp OpenAI-compatible servers
95
+ - **Hosted**: Groq, Together, Fireworks, OpenRouter, DeepInfra, etc.
96
+ - **Anthropic** via an OpenAI-compat proxy (e.g. `anthropic-openai-proxy`)
97
+
98
+ ## License
99
+
100
+ MIT
@@ -0,0 +1,6 @@
1
+ import type { CompletionPlugin } from '@tagma/types';
2
+ declare const LlmJudgeCompletion: CompletionPlugin;
3
+ export declare const pluginCategory = "completions";
4
+ export declare const pluginType = "llm_judge";
5
+ export default LlmJudgeCompletion;
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AA6BA,OAAO,KAAK,EACV,gBAAgB,EACjB,MAAM,cAAc,CAAC;AAsItB,QAAA,MAAM,kBAAkB,EAAE,gBA6GzB,CAAC;AAGF,eAAO,MAAM,cAAc,gBAAgB,CAAC;AAC5C,eAAO,MAAM,UAAU,cAAc,CAAC;AACtC,eAAe,kBAAkB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,236 @@
1
+ // ═══ LLM-as-Judge Completion Plugin ═══
2
+ //
3
+ // Uses an OpenAI-compatible chat completions endpoint to verify whether a
4
+ // task's output satisfies a rubric. Complements the deterministic built-in
5
+ // completions (`exit_code`, `file_exists`, `output_check`) with AI-powered
6
+ // checks — useful when success is defined semantically rather than by a
7
+ // grep-able pattern or a file on disk.
8
+ //
9
+ // Default backend is a **local Ollama** server using its OpenAI-compatible
10
+ // route (`/v1/chat/completions`, available since Ollama 0.1.29+), with
11
+ // `qwen3:4b` as a small, cheap-to-run reasoning model. No API key is
12
+ // required for local Ollama; remote endpoints can set `api_key_env` to
13
+ // whatever header the server expects.
14
+ //
15
+ // The judge is instructed to answer PASS/FAIL on the first line. Reasoning
16
+ // models (qwen3, deepseek-r1, etc.) emit `<think>...</think>` blocks in
17
+ // their message content — we strip those before parsing, so the rubric
18
+ // works the same whether the judge model is a thinker or not.
19
+ //
20
+ // Usage in pipeline.yaml:
21
+ // plugins: ["@tagma/completion-llm-judge"]
22
+ // tracks:
23
+ // - tasks:
24
+ // - id: draft
25
+ // completion:
26
+ // type: llm_judge
27
+ // rubric: "Output must list at least 3 failing tests with file paths."
28
+ // # endpoint / model / api_key_env all default to local Ollama + qwen3:4b
29
+ // Ollama exposes an OpenAI-compatible `/v1/chat/completions` route on port
30
+ // 11434 by default. Point this at any OpenAI-compatible server (OpenAI,
31
+ // vLLM, llama.cpp, LM Studio, Groq, Together, etc.) to swap backends.
32
+ const DEFAULT_ENDPOINT = 'http://localhost:11434/v1/chat/completions';
33
+ // qwen3:4b is a small reasoning model (~2.5 GB on disk, runs on CPU) that
34
+ // reliably follows the PASS/FAIL-on-first-line instruction. Swap to
35
+ // `qwen3:8b`, `deepseek-r1:7b`, or a hosted model for stricter judging.
36
+ const DEFAULT_MODEL = 'qwen3:4b';
37
+ const DEFAULT_TIMEOUT_MS = 120_000;
38
+ const DEFAULT_MAX_OUTPUT_CHARS = 8_000;
39
+ const SYSTEM_PROMPT = 'You are a strict quality judge for task outputs.\n' +
40
+ 'Given the task rubric and actual output, answer on the FIRST LINE with exactly "PASS" or "FAIL".\n' +
41
+ 'On subsequent lines you may provide a one-sentence justification.\n' +
42
+ 'Do not use any other format. Do not wrap the answer in code fences.\n' +
43
+ 'If you reason step-by-step internally, still put PASS or FAIL on the first line of your final answer.';
44
+ function parseDurationSafe(raw, fallback) {
45
+ if (raw == null)
46
+ return fallback;
47
+ const str = String(raw).trim();
48
+ const m = str.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);
49
+ if (!m)
50
+ return fallback;
51
+ const n = Number(m[1]);
52
+ switch (m[2]) {
53
+ case 'ms': return n;
54
+ case 'm': return n * 60_000;
55
+ case 'h': return n * 3_600_000;
56
+ case 's':
57
+ default: return n * 1000;
58
+ }
59
+ }
60
+ // Head-and-tail truncation preserves the start of the output (where agents
61
+ // usually declare intent) and the end (where they summarize results),
62
+ // dropping the middle when the combined length exceeds the budget. This
63
+ // keeps the judge's view of the output meaningful even for very long runs.
64
+ function truncateForJudge(text, maxChars) {
65
+ if (text.length <= maxChars)
66
+ return text;
67
+ const marker = '\n...[truncated]...\n';
68
+ const budget = maxChars - marker.length;
69
+ if (budget <= 0)
70
+ return text.slice(0, maxChars);
71
+ const head = Math.floor(budget * 0.7);
72
+ const tail = budget - head;
73
+ return text.slice(0, head) + marker + text.slice(-tail);
74
+ }
75
+ // Strip reasoning-model thinking blocks so verdict parsing sees the real
76
+ // answer. Qwen3 and DeepSeek-R1 both emit `<think>...</think>` inline in
77
+ // message content when served via Ollama's OpenAI-compat route. We also
78
+ // drop the legacy `<thinking>` variant some fine-tunes use. Applied
79
+ // before any trimming so leading whitespace from the stripped block
80
+ // doesn't leak into the first line.
81
+ function stripThinking(content) {
82
+ return content
83
+ .replace(/<think>[\s\S]*?<\/think>/gi, '')
84
+ .replace(/<thinking>[\s\S]*?<\/thinking>/gi, '')
85
+ .trim();
86
+ }
87
+ async function callJudge(endpoint, model, apiKey, messages, timeoutMs, externalSignal) {
88
+ const controller = new AbortController();
89
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
90
+ const onExternalAbort = () => controller.abort();
91
+ if (externalSignal) {
92
+ if (externalSignal.aborted) {
93
+ controller.abort();
94
+ }
95
+ else {
96
+ externalSignal.addEventListener('abort', onExternalAbort, { once: true });
97
+ }
98
+ }
99
+ try {
100
+ const headers = {
101
+ 'content-type': 'application/json',
102
+ };
103
+ // Only send Authorization when we actually have a key — local Ollama
104
+ // doesn't require one, and some OpenAI-compat proxies reject bogus
105
+ // placeholder tokens like "ollama" with 401 instead of ignoring them.
106
+ if (apiKey) {
107
+ headers.authorization = `Bearer ${apiKey}`;
108
+ }
109
+ const res = await fetch(endpoint, {
110
+ method: 'POST',
111
+ headers,
112
+ body: JSON.stringify({
113
+ model,
114
+ messages,
115
+ temperature: 0,
116
+ // `stream: false` is already the default but we set it explicitly
117
+ // because Ollama's OpenAI-compat route streams by default in some
118
+ // older versions.
119
+ stream: false,
120
+ }),
121
+ signal: controller.signal,
122
+ });
123
+ if (!res.ok) {
124
+ const text = await res.text().catch(() => '');
125
+ throw new Error(`judge endpoint ${res.status}: ${text.slice(0, 200)}`);
126
+ }
127
+ const payload = (await res.json());
128
+ const content = payload.choices?.[0]?.message?.content;
129
+ if (typeof content !== 'string') {
130
+ throw new Error('judge endpoint returned no message content');
131
+ }
132
+ return stripThinking(content);
133
+ }
134
+ finally {
135
+ clearTimeout(timer);
136
+ if (externalSignal)
137
+ externalSignal.removeEventListener('abort', onExternalAbort);
138
+ }
139
+ }
140
+ const LlmJudgeCompletion = {
141
+ name: 'llm_judge',
142
+ schema: {
143
+ description: 'Use an LLM to judge whether the task output satisfies a rubric. Answers PASS/FAIL.',
144
+ fields: {
145
+ rubric: {
146
+ type: 'string',
147
+ required: true,
148
+ description: 'Criteria the judge should verify. Plain language.',
149
+ placeholder: 'Output must list at least 3 failing tests with file paths.',
150
+ },
151
+ model: {
152
+ type: 'string',
153
+ default: DEFAULT_MODEL,
154
+ description: 'Judge model name. Default is a small Ollama reasoning model (qwen3:4b). Swap for qwen3:8b, deepseek-r1:7b, or a hosted model for stricter judging.',
155
+ placeholder: DEFAULT_MODEL,
156
+ },
157
+ endpoint: {
158
+ type: 'string',
159
+ default: DEFAULT_ENDPOINT,
160
+ description: 'OpenAI-compatible chat completions endpoint. Defaults to local Ollama (http://localhost:11434/v1/chat/completions).',
161
+ placeholder: DEFAULT_ENDPOINT,
162
+ },
163
+ api_key_env: {
164
+ type: 'string',
165
+ description: 'Env var containing the bearer token for the judge endpoint. Leave unset for local Ollama; set to OPENAI_API_KEY etc. for hosted backends.',
166
+ placeholder: 'OPENAI_API_KEY',
167
+ },
168
+ timeout: {
169
+ type: 'duration',
170
+ default: '120s',
171
+ description: 'Maximum time to wait for the judge response. Reasoning models need more time than chat models.',
172
+ },
173
+ max_output_chars: {
174
+ type: 'number',
175
+ default: DEFAULT_MAX_OUTPUT_CHARS,
176
+ min: 500,
177
+ max: 200_000,
178
+ description: 'Truncate task stdout to this many chars before judging.',
179
+ },
180
+ },
181
+ },
182
+ async check(config, result, ctx) {
183
+ const rubric = config.rubric;
184
+ if (!rubric)
185
+ throw new Error('llm_judge completion: "rubric" is required');
186
+ // api_key_env is optional — when unset we talk to the endpoint
187
+ // anonymously (correct for local Ollama). When the user names an env
188
+ // var, we require it to be populated so config errors fail loudly
189
+ // instead of silently stripping auth.
190
+ const apiKeyEnv = config.api_key_env;
191
+ let apiKey;
192
+ if (apiKeyEnv) {
193
+ apiKey = process.env[apiKeyEnv];
194
+ if (!apiKey) {
195
+ throw new Error(`llm_judge completion: env var ${apiKeyEnv} is not set`);
196
+ }
197
+ }
198
+ const model = config.model ?? DEFAULT_MODEL;
199
+ const endpoint = config.endpoint ?? DEFAULT_ENDPOINT;
200
+ const timeoutMs = parseDurationSafe(config.timeout, DEFAULT_TIMEOUT_MS);
201
+ const maxChars = typeof config.max_output_chars === 'number' && config.max_output_chars > 0
202
+ ? Math.floor(config.max_output_chars)
203
+ : DEFAULT_MAX_OUTPUT_CHARS;
204
+ const userContent = `[Rubric]\n${rubric}\n\n` +
205
+ `[Exit Code]\n${result.exitCode}\n\n` +
206
+ `[Task Output]\n${truncateForJudge(result.stdout, maxChars)}`;
207
+ const messages = [
208
+ { role: 'system', content: SYSTEM_PROMPT },
209
+ { role: 'user', content: userContent },
210
+ ];
211
+ try {
212
+ const content = await callJudge(endpoint, model, apiKey, messages, timeoutMs, ctx.signal);
213
+ const firstLine = (content.split(/\r?\n/, 1)[0] ?? '').trim().toUpperCase();
214
+ const passed = firstLine.startsWith('PASS');
215
+ if (!passed) {
216
+ // Surface the judge's reasoning in logs so pipeline operators can
217
+ // see why an output was rejected without re-running it themselves.
218
+ console.warn(`[llm_judge] verdict=${firstLine || '<empty>'} — full judge response:\n${content}`);
219
+ }
220
+ return passed;
221
+ }
222
+ catch (err) {
223
+ // Treat judge failures as FAIL: a completion gate that errors open
224
+ // is worse than one that errors closed. Operators can re-run the
225
+ // task once the judge endpoint is healthy again.
226
+ const msg = err instanceof Error ? err.message : String(err);
227
+ console.warn(`[llm_judge] judge call failed, marking task as not-complete: ${msg}`);
228
+ return false;
229
+ }
230
+ },
231
+ };
232
+ // ═══ Plugin self-description exports ═══
233
+ export const pluginCategory = 'completions';
234
+ export const pluginType = 'llm_judge';
235
+ export default LlmJudgeCompletion;
236
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAA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/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@tagma/completion-llm-judge",
3
+ "version": "0.1.1",
4
+ "description": "LLM-as-judge completion plugin for tagma-sdk pipelines",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/GoTagma/tagma-mono.git",
9
+ "directory": "packages/completion-llm-judge"
10
+ },
11
+ "bugs": "https://github.com/GoTagma/tagma-mono/issues",
12
+ "homepage": "https://github.com/GoTagma/tagma-mono/tree/main/packages/completion-llm-judge#readme",
13
+ "type": "module",
14
+ "main": "./dist/index.js",
15
+ "module": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "default": "./dist/index.js"
22
+ },
23
+ "./package.json": "./package.json"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "src"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "keywords": [
33
+ "tagma-plugin",
34
+ "tagma",
35
+ "completion",
36
+ "llm-judge",
37
+ "llm-as-judge",
38
+ "openai"
39
+ ],
40
+ "engines": {
41
+ "bun": ">=1.3"
42
+ },
43
+ "tagmaPlugin": {
44
+ "category": "completions",
45
+ "type": "llm_judge"
46
+ },
47
+ "scripts": {
48
+ "build": "tsc -p tsconfig.json",
49
+ "prepublishOnly": "bun run build"
50
+ },
51
+ "peerDependencies": {
52
+ "@tagma/types": "0.2.1"
53
+ },
54
+ "devDependencies": {
55
+ "bun-types": "^1.3.11",
56
+ "typescript": "^5.8.3"
57
+ }
58
+ }
package/src/index.ts ADDED
@@ -0,0 +1,280 @@
1
+ // ═══ LLM-as-Judge Completion Plugin ═══
2
+ //
3
+ // Uses an OpenAI-compatible chat completions endpoint to verify whether a
4
+ // task's output satisfies a rubric. Complements the deterministic built-in
5
+ // completions (`exit_code`, `file_exists`, `output_check`) with AI-powered
6
+ // checks — useful when success is defined semantically rather than by a
7
+ // grep-able pattern or a file on disk.
8
+ //
9
+ // Default backend is a **local Ollama** server using its OpenAI-compatible
10
+ // route (`/v1/chat/completions`, available since Ollama 0.1.29+), with
11
+ // `qwen3:4b` as a small, cheap-to-run reasoning model. No API key is
12
+ // required for local Ollama; remote endpoints can set `api_key_env` to
13
+ // whatever header the server expects.
14
+ //
15
+ // The judge is instructed to answer PASS/FAIL on the first line. Reasoning
16
+ // models (qwen3, deepseek-r1, etc.) emit `<think>...</think>` blocks in
17
+ // their message content — we strip those before parsing, so the rubric
18
+ // works the same whether the judge model is a thinker or not.
19
+ //
20
+ // Usage in pipeline.yaml:
21
+ // plugins: ["@tagma/completion-llm-judge"]
22
+ // tracks:
23
+ // - tasks:
24
+ // - id: draft
25
+ // completion:
26
+ // type: llm_judge
27
+ // rubric: "Output must list at least 3 failing tests with file paths."
28
+ // # endpoint / model / api_key_env all default to local Ollama + qwen3:4b
29
+
30
+ import type {
31
+ CompletionPlugin, CompletionContext, TaskResult,
32
+ } from '@tagma/types';
33
+
34
+ // Ollama exposes an OpenAI-compatible `/v1/chat/completions` route on port
35
+ // 11434 by default. Point this at any OpenAI-compatible server (OpenAI,
36
+ // vLLM, llama.cpp, LM Studio, Groq, Together, etc.) to swap backends.
37
+ const DEFAULT_ENDPOINT = 'http://localhost:11434/v1/chat/completions';
38
+ // qwen3:4b is a small reasoning model (~2.5 GB on disk, runs on CPU) that
39
+ // reliably follows the PASS/FAIL-on-first-line instruction. Swap to
40
+ // `qwen3:8b`, `deepseek-r1:7b`, or a hosted model for stricter judging.
41
+ const DEFAULT_MODEL = 'qwen3:4b';
42
+ const DEFAULT_TIMEOUT_MS = 120_000;
43
+ const DEFAULT_MAX_OUTPUT_CHARS = 8_000;
44
+
45
+ const SYSTEM_PROMPT =
46
+ 'You are a strict quality judge for task outputs.\n' +
47
+ 'Given the task rubric and actual output, answer on the FIRST LINE with exactly "PASS" or "FAIL".\n' +
48
+ 'On subsequent lines you may provide a one-sentence justification.\n' +
49
+ 'Do not use any other format. Do not wrap the answer in code fences.\n' +
50
+ 'If you reason step-by-step internally, still put PASS or FAIL on the first line of your final answer.';
51
+
52
+ interface ChatMessage {
53
+ readonly role: 'system' | 'user';
54
+ readonly content: string;
55
+ }
56
+
57
+ interface ChatCompletionResponse {
58
+ readonly choices?: ReadonlyArray<{
59
+ readonly message?: { readonly content?: string };
60
+ }>;
61
+ }
62
+
63
+ function parseDurationSafe(raw: unknown, fallback: number): number {
64
+ if (raw == null) return fallback;
65
+ const str = String(raw).trim();
66
+ const m = str.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);
67
+ if (!m) return fallback;
68
+ const n = Number(m[1]);
69
+ switch (m[2]) {
70
+ case 'ms': return n;
71
+ case 'm': return n * 60_000;
72
+ case 'h': return n * 3_600_000;
73
+ case 's':
74
+ default: return n * 1000;
75
+ }
76
+ }
77
+
78
+ // Head-and-tail truncation preserves the start of the output (where agents
79
+ // usually declare intent) and the end (where they summarize results),
80
+ // dropping the middle when the combined length exceeds the budget. This
81
+ // keeps the judge's view of the output meaningful even for very long runs.
82
+ function truncateForJudge(text: string, maxChars: number): string {
83
+ if (text.length <= maxChars) return text;
84
+ const marker = '\n...[truncated]...\n';
85
+ const budget = maxChars - marker.length;
86
+ if (budget <= 0) return text.slice(0, maxChars);
87
+ const head = Math.floor(budget * 0.7);
88
+ const tail = budget - head;
89
+ return text.slice(0, head) + marker + text.slice(-tail);
90
+ }
91
+
92
+ // Strip reasoning-model thinking blocks so verdict parsing sees the real
93
+ // answer. Qwen3 and DeepSeek-R1 both emit `<think>...</think>` inline in
94
+ // message content when served via Ollama's OpenAI-compat route. We also
95
+ // drop the legacy `<thinking>` variant some fine-tunes use. Applied
96
+ // before any trimming so leading whitespace from the stripped block
97
+ // doesn't leak into the first line.
98
+ function stripThinking(content: string): string {
99
+ return content
100
+ .replace(/<think>[\s\S]*?<\/think>/gi, '')
101
+ .replace(/<thinking>[\s\S]*?<\/thinking>/gi, '')
102
+ .trim();
103
+ }
104
+
105
+ async function callJudge(
106
+ endpoint: string,
107
+ model: string,
108
+ apiKey: string | undefined,
109
+ messages: readonly ChatMessage[],
110
+ timeoutMs: number,
111
+ externalSignal: AbortSignal | undefined,
112
+ ): Promise<string> {
113
+ const controller = new AbortController();
114
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
115
+
116
+ const onExternalAbort = (): void => controller.abort();
117
+ if (externalSignal) {
118
+ if (externalSignal.aborted) {
119
+ controller.abort();
120
+ } else {
121
+ externalSignal.addEventListener('abort', onExternalAbort, { once: true });
122
+ }
123
+ }
124
+
125
+ try {
126
+ const headers: Record<string, string> = {
127
+ 'content-type': 'application/json',
128
+ };
129
+ // Only send Authorization when we actually have a key — local Ollama
130
+ // doesn't require one, and some OpenAI-compat proxies reject bogus
131
+ // placeholder tokens like "ollama" with 401 instead of ignoring them.
132
+ if (apiKey) {
133
+ headers.authorization = `Bearer ${apiKey}`;
134
+ }
135
+
136
+ const res = await fetch(endpoint, {
137
+ method: 'POST',
138
+ headers,
139
+ body: JSON.stringify({
140
+ model,
141
+ messages,
142
+ temperature: 0,
143
+ // `stream: false` is already the default but we set it explicitly
144
+ // because Ollama's OpenAI-compat route streams by default in some
145
+ // older versions.
146
+ stream: false,
147
+ }),
148
+ signal: controller.signal,
149
+ });
150
+ if (!res.ok) {
151
+ const text = await res.text().catch(() => '');
152
+ throw new Error(`judge endpoint ${res.status}: ${text.slice(0, 200)}`);
153
+ }
154
+ const payload = (await res.json()) as ChatCompletionResponse;
155
+ const content = payload.choices?.[0]?.message?.content;
156
+ if (typeof content !== 'string') {
157
+ throw new Error('judge endpoint returned no message content');
158
+ }
159
+ return stripThinking(content);
160
+ } finally {
161
+ clearTimeout(timer);
162
+ if (externalSignal) externalSignal.removeEventListener('abort', onExternalAbort);
163
+ }
164
+ }
165
+
166
+ const LlmJudgeCompletion: CompletionPlugin = {
167
+ name: 'llm_judge',
168
+ schema: {
169
+ description:
170
+ 'Use an LLM to judge whether the task output satisfies a rubric. Answers PASS/FAIL.',
171
+ fields: {
172
+ rubric: {
173
+ type: 'string',
174
+ required: true,
175
+ description: 'Criteria the judge should verify. Plain language.',
176
+ placeholder: 'Output must list at least 3 failing tests with file paths.',
177
+ },
178
+ model: {
179
+ type: 'string',
180
+ default: DEFAULT_MODEL,
181
+ description:
182
+ 'Judge model name. Default is a small Ollama reasoning model (qwen3:4b). Swap for qwen3:8b, deepseek-r1:7b, or a hosted model for stricter judging.',
183
+ placeholder: DEFAULT_MODEL,
184
+ },
185
+ endpoint: {
186
+ type: 'string',
187
+ default: DEFAULT_ENDPOINT,
188
+ description:
189
+ 'OpenAI-compatible chat completions endpoint. Defaults to local Ollama (http://localhost:11434/v1/chat/completions).',
190
+ placeholder: DEFAULT_ENDPOINT,
191
+ },
192
+ api_key_env: {
193
+ type: 'string',
194
+ description:
195
+ 'Env var containing the bearer token for the judge endpoint. Leave unset for local Ollama; set to OPENAI_API_KEY etc. for hosted backends.',
196
+ placeholder: 'OPENAI_API_KEY',
197
+ },
198
+ timeout: {
199
+ type: 'duration',
200
+ default: '120s',
201
+ description:
202
+ 'Maximum time to wait for the judge response. Reasoning models need more time than chat models.',
203
+ },
204
+ max_output_chars: {
205
+ type: 'number',
206
+ default: DEFAULT_MAX_OUTPUT_CHARS,
207
+ min: 500,
208
+ max: 200_000,
209
+ description: 'Truncate task stdout to this many chars before judging.',
210
+ },
211
+ },
212
+ },
213
+
214
+ async check(
215
+ config: Record<string, unknown>,
216
+ result: TaskResult,
217
+ ctx: CompletionContext,
218
+ ): Promise<boolean> {
219
+ const rubric = config.rubric as string | undefined;
220
+ if (!rubric) throw new Error('llm_judge completion: "rubric" is required');
221
+
222
+ // api_key_env is optional — when unset we talk to the endpoint
223
+ // anonymously (correct for local Ollama). When the user names an env
224
+ // var, we require it to be populated so config errors fail loudly
225
+ // instead of silently stripping auth.
226
+ const apiKeyEnv = config.api_key_env as string | undefined;
227
+ let apiKey: string | undefined;
228
+ if (apiKeyEnv) {
229
+ apiKey = process.env[apiKeyEnv];
230
+ if (!apiKey) {
231
+ throw new Error(`llm_judge completion: env var ${apiKeyEnv} is not set`);
232
+ }
233
+ }
234
+
235
+ const model = (config.model as string | undefined) ?? DEFAULT_MODEL;
236
+ const endpoint = (config.endpoint as string | undefined) ?? DEFAULT_ENDPOINT;
237
+ const timeoutMs = parseDurationSafe(config.timeout, DEFAULT_TIMEOUT_MS);
238
+ const maxChars = typeof config.max_output_chars === 'number' && config.max_output_chars > 0
239
+ ? Math.floor(config.max_output_chars)
240
+ : DEFAULT_MAX_OUTPUT_CHARS;
241
+
242
+ const userContent =
243
+ `[Rubric]\n${rubric}\n\n` +
244
+ `[Exit Code]\n${result.exitCode}\n\n` +
245
+ `[Task Output]\n${truncateForJudge(result.stdout, maxChars)}`;
246
+
247
+ const messages: ChatMessage[] = [
248
+ { role: 'system', content: SYSTEM_PROMPT },
249
+ { role: 'user', content: userContent },
250
+ ];
251
+
252
+ try {
253
+ const content = await callJudge(
254
+ endpoint, model, apiKey, messages, timeoutMs, ctx.signal,
255
+ );
256
+ const firstLine = (content.split(/\r?\n/, 1)[0] ?? '').trim().toUpperCase();
257
+ const passed = firstLine.startsWith('PASS');
258
+ if (!passed) {
259
+ // Surface the judge's reasoning in logs so pipeline operators can
260
+ // see why an output was rejected without re-running it themselves.
261
+ console.warn(
262
+ `[llm_judge] verdict=${firstLine || '<empty>'} — full judge response:\n${content}`,
263
+ );
264
+ }
265
+ return passed;
266
+ } catch (err) {
267
+ // Treat judge failures as FAIL: a completion gate that errors open
268
+ // is worse than one that errors closed. Operators can re-run the
269
+ // task once the judge endpoint is healthy again.
270
+ const msg = err instanceof Error ? err.message : String(err);
271
+ console.warn(`[llm_judge] judge call failed, marking task as not-complete: ${msg}`);
272
+ return false;
273
+ }
274
+ },
275
+ };
276
+
277
+ // ═══ Plugin self-description exports ═══
278
+ export const pluginCategory = 'completions';
279
+ export const pluginType = 'llm_judge';
280
+ export default LlmJudgeCompletion;