@in-the-loop-labs/pair-review 5.1.1 → 5.2.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/README.md +12 -4
- package/package.json +3 -2
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
- package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
- package/public/index.html +5 -2
- package/public/js/index.js +106 -9
- package/src/ai/index.js +1 -0
- package/src/ai/omp/review-config.yml +13 -0
- package/src/ai/omp-provider.js +279 -0
- package/src/ai/pi-format.js +535 -0
- package/src/ai/pi-provider.js +38 -963
- package/src/ai/pi-style-provider.js +526 -0
- package/src/ai/provider.js +2 -0
- package/src/chat/chat-providers.js +34 -11
- package/src/chat/omp-bridge.js +111 -0
- package/src/chat/pi-bridge.js +42 -34
- package/src/chat/session-manager.js +30 -4
- package/src/config.js +32 -3
- package/src/links/host-names.js +200 -0
- package/src/local-review.js +7 -3
- package/src/main.js +21 -1
- package/src/review-config.js +81 -5
- package/src/routes/config.js +16 -0
- package/src/routes/local.js +1 -1
- package/src/routes/pr.js +2 -1
- package/src/routes/setup.js +1 -1
- package/src/settings/registry.js +1 -1
- package/src/setup/local-setup.js +5 -3
- package/src/single-port.js +1 -1
- package/src/utils/local-path-input.js +64 -8
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
// Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* Shared base class for Pi-style providers.
|
|
4
|
+
*
|
|
5
|
+
* Pi (pi-provider.js) and its fork OMP (omp-provider.js) emit the same
|
|
6
|
+
* `--mode json` JSONL event stream and are driven through an identical
|
|
7
|
+
* Node.js process lifecycle: spawn with @file prompt delivery, buffered
|
|
8
|
+
* JSONL line accumulation, abort/cancellation wiring, timeout handling,
|
|
9
|
+
* tmp-file cleanup, and the LLM-extraction fallback. That lifecycle lives
|
|
10
|
+
* here so a fix lands in both providers at once.
|
|
11
|
+
*
|
|
12
|
+
* What deliberately does NOT live here is the CLI surface — argv
|
|
13
|
+
* construction, model resolution, and env merging differ between the two
|
|
14
|
+
* CLIs (advisor overlay, task extension, --provider splitting, tool sets)
|
|
15
|
+
* and stay in the subclasses.
|
|
16
|
+
*
|
|
17
|
+
* Subclass contract — the subclass constructor must set:
|
|
18
|
+
* this.cliCmd - resolved CLI command (ENV > config > default precedence)
|
|
19
|
+
* this.cliName - display name used in log/error messages ('Pi', 'OMP')
|
|
20
|
+
* this.useShell - true when cliCmd is multi-word and needs shell mode
|
|
21
|
+
* this.baseArgs - full analysis argv (the prompt is appended via @file)
|
|
22
|
+
* this.extraEnv - extra env vars merged into the child environment
|
|
23
|
+
* and must implement:
|
|
24
|
+
* buildArgsForModel(model) - extraction argv for a given model
|
|
25
|
+
* and may override:
|
|
26
|
+
* _resolveEnvForModel(model) - extraction env for a given model
|
|
27
|
+
* (defaults to the analysis-model extraEnv)
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
const crypto = require('crypto');
|
|
31
|
+
const path = require('path');
|
|
32
|
+
const os = require('os');
|
|
33
|
+
const fs = require('fs');
|
|
34
|
+
const { spawn } = require('child_process');
|
|
35
|
+
const { AIProvider, quoteShellArgs } = require('./provider');
|
|
36
|
+
const logger = require('../utils/logger');
|
|
37
|
+
const { extractJSON } = require('../utils/json-extractor');
|
|
38
|
+
const { CancellationError, isAnalysisCancelled } = require('../routes/shared');
|
|
39
|
+
const { createPiLineParser } = require('./stream-parser');
|
|
40
|
+
const { wireAbortToChild, makeAbortError, killChildSafely } = require('./abort-signal-wiring');
|
|
41
|
+
const {
|
|
42
|
+
MAX_PI_CAPTURED_STDERR_CHARS,
|
|
43
|
+
PI_STDERR_HEAD_CHARS,
|
|
44
|
+
PI_STDERR_TAIL_CHARS,
|
|
45
|
+
appendHeadTailBuffer,
|
|
46
|
+
formatHeadTailBuffer,
|
|
47
|
+
accumulatePiResponseLine,
|
|
48
|
+
appendPiChunkToLineBuffer,
|
|
49
|
+
finalizePiResponseParsing,
|
|
50
|
+
logPiStreamLine
|
|
51
|
+
} = require('./pi-format');
|
|
52
|
+
|
|
53
|
+
// Directory containing bin scripts (git-diff-lines, etc.)
|
|
54
|
+
const BIN_DIR = path.join(__dirname, '..', '..', 'bin');
|
|
55
|
+
|
|
56
|
+
class PiStyleProvider extends AIProvider {
|
|
57
|
+
/**
|
|
58
|
+
* Execute the CLI with a prompt
|
|
59
|
+
* @param {string} prompt - The prompt to send to the CLI
|
|
60
|
+
* @param {Object} options - Optional configuration
|
|
61
|
+
* @returns {Promise<Object>} Parsed response or error
|
|
62
|
+
*/
|
|
63
|
+
async execute(prompt, options = {}) {
|
|
64
|
+
return new Promise((resolve, reject) => {
|
|
65
|
+
const { cwd = process.cwd(), timeout = 900000, level = 'unknown', analysisId, registerProcess, onStreamEvent, logPrefix, abortSignal } = options;
|
|
66
|
+
|
|
67
|
+
const levelPrefix = logPrefix || `[Level ${level}]`;
|
|
68
|
+
logger.info(`${levelPrefix} Executing ${this.cliName} CLI...`);
|
|
69
|
+
logger.info(`${levelPrefix} Prompt: ${prompt.length} bytes`);
|
|
70
|
+
|
|
71
|
+
// Write prompt to a temp file and use the CLI's @file syntax as a positional arg.
|
|
72
|
+
// This bypasses devx stdin interference that breaks --mode json output.
|
|
73
|
+
const tmpFile = path.join(os.tmpdir(), `pair-review-prompt-${Date.now()}-${process.pid}-${crypto.randomUUID()}.txt`);
|
|
74
|
+
fs.writeFileSync(tmpFile, prompt);
|
|
75
|
+
const cleanupTmpFile = () => { try { fs.unlinkSync(tmpFile); } catch { /* ignore */ } };
|
|
76
|
+
|
|
77
|
+
let fullCommand;
|
|
78
|
+
let fullArgs;
|
|
79
|
+
|
|
80
|
+
if (this.useShell) {
|
|
81
|
+
fullCommand = `${this.cliCmd} ${quoteShellArgs([...this.baseArgs, `@${tmpFile}`]).join(' ')}`;
|
|
82
|
+
fullArgs = [];
|
|
83
|
+
} else {
|
|
84
|
+
fullCommand = this.cliCmd;
|
|
85
|
+
fullArgs = [...this.baseArgs, `@${tmpFile}`];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const child = spawn(fullCommand, fullArgs, {
|
|
89
|
+
cwd,
|
|
90
|
+
env: {
|
|
91
|
+
...process.env,
|
|
92
|
+
...this.extraEnv,
|
|
93
|
+
PATH: `${BIN_DIR}:${process.env.PATH}`
|
|
94
|
+
},
|
|
95
|
+
shell: this.useShell,
|
|
96
|
+
detached: this.useShell
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// Close stdin immediately — prompt is delivered via @file, but some
|
|
100
|
+
// wrappers (e.g., devx) keep the process alive until stdin is closed.
|
|
101
|
+
child.stdin.end();
|
|
102
|
+
|
|
103
|
+
const pid = child.pid;
|
|
104
|
+
logger.debug(`${levelPrefix} ${this.cliName} CLI command: ${fullCommand} ${fullArgs.join(' ')}`);
|
|
105
|
+
logger.info(`${levelPrefix} Spawned ${this.cliName} CLI process: PID ${pid}`);
|
|
106
|
+
|
|
107
|
+
// Register process for cancellation tracking if analysisId provided
|
|
108
|
+
if (analysisId && registerProcess) {
|
|
109
|
+
registerProcess(analysisId, child);
|
|
110
|
+
logger.info(`${levelPrefix} Registered process ${pid} for analysis ${analysisId}`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Wire AbortSignal -> SIGTERM for tour/summary cancellation.
|
|
114
|
+
const abortWiring = wireAbortToChild(child, abortSignal, { logPrefix: levelPrefix, shell: this.useShell });
|
|
115
|
+
|
|
116
|
+
const stderrCapture = {
|
|
117
|
+
head: '',
|
|
118
|
+
tail: '',
|
|
119
|
+
headFull: false,
|
|
120
|
+
omittedChars: 0
|
|
121
|
+
};
|
|
122
|
+
let stderrTruncated = false;
|
|
123
|
+
let timeoutId = null;
|
|
124
|
+
let settled = false; // Guard against multiple resolve/reject calls
|
|
125
|
+
let lineCount = 0; // Count of JSONL lines received
|
|
126
|
+
const lineBufferState = {
|
|
127
|
+
buffer: '',
|
|
128
|
+
lineTruncated: false,
|
|
129
|
+
warningLogged: false
|
|
130
|
+
};
|
|
131
|
+
const responseState = {
|
|
132
|
+
textContent: '',
|
|
133
|
+
seenTexts: new Set(),
|
|
134
|
+
rawOutput: '',
|
|
135
|
+
rawOutputTruncated: false
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const settle = (fn, value) => {
|
|
139
|
+
if (settled) return;
|
|
140
|
+
settled = true;
|
|
141
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
142
|
+
abortWiring.detach();
|
|
143
|
+
fn(value);
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
// Use the buffered Pi line parser to accumulate text_delta fragments
|
|
147
|
+
// before emitting, preventing the UI from being flooded with tiny updates.
|
|
148
|
+
const streamLineParser = onStreamEvent ? createPiLineParser() : null;
|
|
149
|
+
const emitStreamLine = (line) => {
|
|
150
|
+
if (!streamLineParser || !line?.trim()) return;
|
|
151
|
+
|
|
152
|
+
const event = streamLineParser(line, { cwd });
|
|
153
|
+
if (!event) return;
|
|
154
|
+
|
|
155
|
+
try {
|
|
156
|
+
onStreamEvent(event);
|
|
157
|
+
} catch (error) {
|
|
158
|
+
logger.warn(`${levelPrefix} ${this.cliName} stream event callback error: ${error.message}`);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
// Set timeout
|
|
163
|
+
if (timeout) {
|
|
164
|
+
timeoutId = setTimeout(() => {
|
|
165
|
+
logger.error(`${levelPrefix} Process ${pid} timed out after ${timeout}ms`);
|
|
166
|
+
killChildSafely(child, { logPrefix: levelPrefix, shell: this.useShell });
|
|
167
|
+
settle(reject, new Error(`${levelPrefix} ${this.cliName} CLI timed out after ${timeout}ms`));
|
|
168
|
+
}, timeout);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Stream and log JSONL lines as they arrive for debugging visibility
|
|
172
|
+
child.stdout.on('data', (data) => {
|
|
173
|
+
const chunk = data.toString();
|
|
174
|
+
const lines = appendPiChunkToLineBuffer(lineBufferState, chunk, levelPrefix, this.cliName);
|
|
175
|
+
|
|
176
|
+
for (const line of lines) {
|
|
177
|
+
if (!line.trim()) continue;
|
|
178
|
+
lineCount++;
|
|
179
|
+
emitStreamLine(line);
|
|
180
|
+
this.logStreamLine(line, lineCount, levelPrefix);
|
|
181
|
+
accumulatePiResponseLine(line, responseState, levelPrefix, this.cliName);
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
// Collect stderr
|
|
186
|
+
child.stderr.on('data', (data) => {
|
|
187
|
+
const chunk = data.toString();
|
|
188
|
+
appendHeadTailBuffer(stderrCapture, chunk, PI_STDERR_HEAD_CHARS, PI_STDERR_TAIL_CHARS);
|
|
189
|
+
if (stderrCapture.omittedChars > 0 && !stderrTruncated) {
|
|
190
|
+
stderrTruncated = true;
|
|
191
|
+
logger.warn(
|
|
192
|
+
`${levelPrefix} ${this.cliName} CLI stderr exceeded ${MAX_PI_CAPTURED_STDERR_CHARS} chars; retaining a head+tail excerpt (${stderrCapture.omittedChars} chars omitted so far)`
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
// Handle completion
|
|
198
|
+
child.on('close', (code) => {
|
|
199
|
+
cleanupTmpFile();
|
|
200
|
+
if (settled) return; // Already settled by timeout or error
|
|
201
|
+
|
|
202
|
+
// Detach is centralized in `settle`.
|
|
203
|
+
|
|
204
|
+
// BackgroundQueue-driven cancellation — mirror of claude-provider.
|
|
205
|
+
if (abortWiring.cancelled()) {
|
|
206
|
+
logger.info(`${levelPrefix} ${this.cliName} CLI terminated by user cancel (exit code ${code})`);
|
|
207
|
+
settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Check for cancellation signals (SIGTERM=143, SIGKILL=137)
|
|
212
|
+
const isCancellationCode = code === 143 || code === 137;
|
|
213
|
+
if (isCancellationCode && analysisId && isAnalysisCancelled(analysisId)) {
|
|
214
|
+
logger.info(`${levelPrefix} ${this.cliName} CLI terminated due to analysis cancellation (exit code ${code})`);
|
|
215
|
+
settle(reject, new CancellationError(`${levelPrefix} Analysis cancelled by user`));
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Also check for cancellation even with exit code 0 (the CLI may handle
|
|
220
|
+
// SIGTERM gracefully and exit cleanly rather than with code 143)
|
|
221
|
+
if (analysisId && isAnalysisCancelled(analysisId)) {
|
|
222
|
+
logger.info(`${levelPrefix} ${this.cliName} CLI exited with code ${code} but analysis was cancelled`);
|
|
223
|
+
settle(reject, new CancellationError(`${levelPrefix} Analysis cancelled by user`));
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const stderr = formatHeadTailBuffer(stderrCapture);
|
|
228
|
+
|
|
229
|
+
// Always log stderr if present
|
|
230
|
+
if (stderr.trim()) {
|
|
231
|
+
if (code !== 0) {
|
|
232
|
+
logger.error(`${levelPrefix} ${this.cliName} CLI stderr (exit code ${code}): ${stderr}`);
|
|
233
|
+
} else {
|
|
234
|
+
logger.warn(`${levelPrefix} ${this.cliName} CLI stderr (success): ${stderr}`);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (code !== 0) {
|
|
239
|
+
logger.error(`${levelPrefix} ${this.cliName} CLI exited with code ${code}`);
|
|
240
|
+
settle(reject, new Error(`${levelPrefix} ${this.cliName} CLI exited with code ${code}: ${stderr}`));
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// Process any remaining buffered line
|
|
245
|
+
if (lineBufferState.buffer.trim()) {
|
|
246
|
+
lineCount++;
|
|
247
|
+
emitStreamLine(lineBufferState.buffer);
|
|
248
|
+
this.logStreamLine(lineBufferState.buffer, lineCount, levelPrefix);
|
|
249
|
+
accumulatePiResponseLine(lineBufferState.buffer, responseState, levelPrefix, this.cliName);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
logger.info(`${levelPrefix} ${this.cliName} CLI completed - received ${lineCount} JSONL events`);
|
|
253
|
+
|
|
254
|
+
// Parse the JSONL response
|
|
255
|
+
const parsed = finalizePiResponseParsing({
|
|
256
|
+
textContent: responseState.textContent,
|
|
257
|
+
rawOutput: responseState.rawOutput,
|
|
258
|
+
rawOutputTruncated: responseState.rawOutputTruncated
|
|
259
|
+
}, level, levelPrefix, this.cliName);
|
|
260
|
+
if (parsed.success) {
|
|
261
|
+
logger.success(`${levelPrefix} Successfully parsed JSON response`);
|
|
262
|
+
|
|
263
|
+
// Log a summary of the response
|
|
264
|
+
if (parsed.data?.suggestions) {
|
|
265
|
+
const count = Array.isArray(parsed.data.suggestions) ? parsed.data.suggestions.length : 0;
|
|
266
|
+
logger.info(`${levelPrefix} [response] ${count} suggestions extracted`);
|
|
267
|
+
} else if (parsed.data) {
|
|
268
|
+
const jsonStr = JSON.stringify(parsed.data);
|
|
269
|
+
logger.info(`${levelPrefix} [response] ${jsonStr.length} chars of JSON data`);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
settle(resolve, parsed.data);
|
|
273
|
+
} else {
|
|
274
|
+
// Regex extraction failed, try LLM-based extraction as fallback
|
|
275
|
+
logger.warn(`${levelPrefix} Regex extraction failed: ${parsed.error}`);
|
|
276
|
+
// Pass extracted text content to LLM fallback (not raw JSONL stdout).
|
|
277
|
+
// The text content is the actual LLM response text extracted from JSONL
|
|
278
|
+
// events and is much smaller and more relevant than the full JSONL stream.
|
|
279
|
+
const llmFallbackInput = parsed.textContent || responseState.rawOutput;
|
|
280
|
+
logger.info(`${levelPrefix} LLM fallback input length: ${llmFallbackInput.length} characters (${parsed.textContent ? 'text content' : 'raw fallback output'})`);
|
|
281
|
+
logger.info(`${levelPrefix} Attempting LLM-based JSON extraction fallback...`);
|
|
282
|
+
|
|
283
|
+
// The CLI child has already exited, so a cancel arriving now only makes
|
|
284
|
+
// the abort wiring kill something already dead. The `settled` guard
|
|
285
|
+
// below only covers a cancel that landed BEFORE the await, so without
|
|
286
|
+
// the checks below one landing during extraction would settle as a
|
|
287
|
+
// normal result. The signal is read alongside the wiring flag as the
|
|
288
|
+
// source of truth.
|
|
289
|
+
const cancelledDuringExtraction = () =>
|
|
290
|
+
abortWiring.cancelled() || abortSignal?.aborted === true;
|
|
291
|
+
|
|
292
|
+
// Use async IIFE to handle the async LLM extraction
|
|
293
|
+
(async () => {
|
|
294
|
+
// Guard: if already settled (by timeout, process error, or cancellation),
|
|
295
|
+
// skip the LLM extraction entirely to avoid misleading log output
|
|
296
|
+
if (settled) return;
|
|
297
|
+
|
|
298
|
+
try {
|
|
299
|
+
// `abortSignal` lets the extraction spawn be killed rather than
|
|
300
|
+
// merely abandoned until its own 60s timeout.
|
|
301
|
+
const llmExtracted = await this.extractJSONWithLLM(llmFallbackInput, { level, analysisId, registerProcess, logPrefix: levelPrefix, abortSignal });
|
|
302
|
+
if (cancelledDuringExtraction()) {
|
|
303
|
+
logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
|
|
304
|
+
settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
if (llmExtracted.success) {
|
|
308
|
+
logger.success(`${levelPrefix} LLM extraction fallback succeeded`);
|
|
309
|
+
settle(resolve, llmExtracted.data);
|
|
310
|
+
} else {
|
|
311
|
+
logger.warn(`${levelPrefix} LLM extraction fallback also failed: ${llmExtracted.error}`);
|
|
312
|
+
logger.info(`${levelPrefix} Raw response preview: ${llmFallbackInput.substring(0, 500)}...`);
|
|
313
|
+
settle(resolve, { raw: llmFallbackInput, parsed: false });
|
|
314
|
+
}
|
|
315
|
+
} catch (llmError) {
|
|
316
|
+
// An abort that kills the extraction spawn surfaces here as a
|
|
317
|
+
// thrown error; it is a cancellation, not a parse failure.
|
|
318
|
+
if (cancelledDuringExtraction()) {
|
|
319
|
+
logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
|
|
320
|
+
settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
logger.warn(`${levelPrefix} LLM extraction fallback error: ${llmError.message}`);
|
|
324
|
+
settle(resolve, { raw: llmFallbackInput, parsed: false });
|
|
325
|
+
}
|
|
326
|
+
})();
|
|
327
|
+
}
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
// Handle errors
|
|
331
|
+
child.on('error', (error) => {
|
|
332
|
+
cleanupTmpFile();
|
|
333
|
+
// Detach happens inside `settle`.
|
|
334
|
+
if (error.code === 'ENOENT') {
|
|
335
|
+
logger.error(`${levelPrefix} ${this.cliName} CLI not found. Please ensure ${this.cliName} CLI is installed.`);
|
|
336
|
+
// Static lookup resolves against the runtime subclass, so this
|
|
337
|
+
// reports the concrete provider's install instructions.
|
|
338
|
+
settle(reject, new Error(`${levelPrefix} ${this.cliName} CLI not found. ${this.constructor.getInstallInstructions()}`));
|
|
339
|
+
} else {
|
|
340
|
+
logger.error(`${levelPrefix} ${this.cliName} process error: ${error}`);
|
|
341
|
+
settle(reject, error);
|
|
342
|
+
}
|
|
343
|
+
});
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Log a streaming JSONL line for debugging visibility.
|
|
349
|
+
* Extracts meaningful info from each event type without being too verbose.
|
|
350
|
+
*
|
|
351
|
+
* Uses logger.streamDebug() which only logs when --debug-stream flag is enabled.
|
|
352
|
+
*
|
|
353
|
+
* @param {string} line - A single JSONL line
|
|
354
|
+
* @param {number} lineNum - Line number for reference
|
|
355
|
+
* @param {string} levelPrefix - Level prefix for log messages
|
|
356
|
+
*/
|
|
357
|
+
logStreamLine(line, lineNum, levelPrefix) {
|
|
358
|
+
logPiStreamLine(line, lineNum, levelPrefix);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Parse a CLI JSONL response.
|
|
363
|
+
* With --mode json the CLI outputs JSONL with structured events.
|
|
364
|
+
* Text content is in message_end events with content blocks,
|
|
365
|
+
* and in message_update events with text_delta.
|
|
366
|
+
*
|
|
367
|
+
* @param {string} stdout - Raw stdout from the CLI (JSONL format)
|
|
368
|
+
* @param {string|number} level - Analysis level for logging
|
|
369
|
+
* @returns {{success: boolean, data?: Object, error?: string}}
|
|
370
|
+
*/
|
|
371
|
+
parseResponse(stdout, level, logPrefix) {
|
|
372
|
+
const levelPrefix = logPrefix || `[Level ${level}]`;
|
|
373
|
+
|
|
374
|
+
try {
|
|
375
|
+
// Split by newlines and parse each JSON line
|
|
376
|
+
const lines = stdout.trim().split('\n').filter(line => line.trim());
|
|
377
|
+
const responseState = {
|
|
378
|
+
textContent: '',
|
|
379
|
+
seenTexts: new Set(),
|
|
380
|
+
rawOutput: '',
|
|
381
|
+
rawOutputTruncated: false
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
for (const line of lines) {
|
|
385
|
+
accumulatePiResponseLine(line, responseState, levelPrefix, this.cliName);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
return finalizePiResponseParsing({
|
|
389
|
+
textContent: responseState.textContent,
|
|
390
|
+
rawOutput: responseState.rawOutput,
|
|
391
|
+
rawOutputTruncated: responseState.rawOutputTruncated
|
|
392
|
+
}, level, levelPrefix, this.cliName);
|
|
393
|
+
|
|
394
|
+
} catch (parseError) {
|
|
395
|
+
// stdout might not be valid JSONL at all, try extracting JSON from it
|
|
396
|
+
const extracted = extractJSON(stdout, level, levelPrefix);
|
|
397
|
+
if (extracted.success) {
|
|
398
|
+
return extracted;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
return { success: false, error: `JSONL parse error: ${parseError.message}` };
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Resolve the extra env vars for a given model. The default returns the
|
|
407
|
+
* analysis-model env computed in the constructor; subclasses override this
|
|
408
|
+
* to re-merge env for the requested model so getExtractionConfig() picks up
|
|
409
|
+
* model-specific env for the extraction model.
|
|
410
|
+
*
|
|
411
|
+
* @param {string} model - The model identifier
|
|
412
|
+
* @returns {Object} Env vars to merge into the child environment
|
|
413
|
+
*/
|
|
414
|
+
_resolveEnvForModel(model) {
|
|
415
|
+
return this.extraEnv;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* Get CLI configuration for LLM extraction
|
|
420
|
+
* @param {string} model - The model to use for extraction
|
|
421
|
+
* @returns {Object} Configuration for spawning extraction process
|
|
422
|
+
*/
|
|
423
|
+
getExtractionConfig(model) {
|
|
424
|
+
// Use the already-resolved command from the constructor (this.cliCmd)
|
|
425
|
+
// which respects: ENV > config > default precedence
|
|
426
|
+
const cliCmd = this.cliCmd;
|
|
427
|
+
const useShell = this.useShell;
|
|
428
|
+
|
|
429
|
+
// Build args consistently using the shared method, applying provider and model extra_args
|
|
430
|
+
const args = this.buildArgsForModel(model);
|
|
431
|
+
|
|
432
|
+
// Resolve env for the extraction model (not the cached analysis-model env)
|
|
433
|
+
// so a distinct fast-tier extraction model carries its own env.
|
|
434
|
+
const env = this._resolveEnvForModel(model);
|
|
435
|
+
|
|
436
|
+
// Use @file syntax for prompt delivery (bypasses devx stdin interference)
|
|
437
|
+
if (useShell) {
|
|
438
|
+
return {
|
|
439
|
+
command: `${cliCmd} ${quoteShellArgs(args).join(' ')}`,
|
|
440
|
+
args: [],
|
|
441
|
+
useShell: true,
|
|
442
|
+
promptViaFile: true,
|
|
443
|
+
env
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
return {
|
|
447
|
+
command: cliCmd,
|
|
448
|
+
args,
|
|
449
|
+
useShell: false,
|
|
450
|
+
promptViaFile: true,
|
|
451
|
+
env
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Test if the CLI is available
|
|
457
|
+
* Uses the command configured in the instance (respects ENV > config > default precedence)
|
|
458
|
+
* @param {number} [timeoutMs=10000] - Timeout in milliseconds for the probe
|
|
459
|
+
* @returns {Promise<boolean>}
|
|
460
|
+
*/
|
|
461
|
+
async testAvailability(timeoutMs = 10000) {
|
|
462
|
+
return new Promise((resolve) => {
|
|
463
|
+
// For availability test, we just need to check --version
|
|
464
|
+
// Use the already-resolved command from the constructor (this.cliCmd)
|
|
465
|
+
// which respects: ENV > config > default precedence
|
|
466
|
+
const useShell = this.useShell;
|
|
467
|
+
const command = useShell ? `${this.cliCmd} --version` : this.cliCmd;
|
|
468
|
+
const args = useShell ? [] : ['--version'];
|
|
469
|
+
|
|
470
|
+
// Log the actual command for debugging config/override issues
|
|
471
|
+
const fullCmd = useShell ? command : `${command} ${args.join(' ')}`;
|
|
472
|
+
const name = this.constructor.getProviderName();
|
|
473
|
+
logger.debug(`${name} availability check: ${fullCmd}`);
|
|
474
|
+
|
|
475
|
+
const child = spawn(command, args, {
|
|
476
|
+
env: {
|
|
477
|
+
...process.env,
|
|
478
|
+
...this.extraEnv,
|
|
479
|
+
PATH: `${BIN_DIR}:${process.env.PATH}`
|
|
480
|
+
},
|
|
481
|
+
shell: useShell
|
|
482
|
+
});
|
|
483
|
+
|
|
484
|
+
let stdout = '';
|
|
485
|
+
let settled = false;
|
|
486
|
+
|
|
487
|
+
// Timeout guard: if the CLI hangs, resolve false
|
|
488
|
+
const availabilityTimeout = setTimeout(() => {
|
|
489
|
+
if (settled) return;
|
|
490
|
+
settled = true;
|
|
491
|
+
logger.warn(`${name} CLI availability check timed out after ${Math.round(timeoutMs / 1000)}s`);
|
|
492
|
+
// Not `shell: useShell`: the probe spawn is not `detached`, so
|
|
493
|
+
// group-kill would ESRCH and leave the child running.
|
|
494
|
+
killChildSafely(child, { logPrefix: '[availability]' });
|
|
495
|
+
resolve(false);
|
|
496
|
+
}, timeoutMs);
|
|
497
|
+
|
|
498
|
+
child.stdout.on('data', (data) => {
|
|
499
|
+
stdout += data.toString();
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
child.on('close', (code) => {
|
|
503
|
+
if (settled) return;
|
|
504
|
+
settled = true;
|
|
505
|
+
clearTimeout(availabilityTimeout);
|
|
506
|
+
if (code === 0) {
|
|
507
|
+
logger.info(`${name} CLI available: ${stdout.trim()}`);
|
|
508
|
+
resolve(true);
|
|
509
|
+
} else {
|
|
510
|
+
logger.warn(`${name} CLI not available or returned unexpected output`);
|
|
511
|
+
resolve(false);
|
|
512
|
+
}
|
|
513
|
+
});
|
|
514
|
+
|
|
515
|
+
child.on('error', (error) => {
|
|
516
|
+
if (settled) return;
|
|
517
|
+
settled = true;
|
|
518
|
+
clearTimeout(availabilityTimeout);
|
|
519
|
+
logger.warn(`${name} CLI not available: ${error.message}`);
|
|
520
|
+
resolve(false);
|
|
521
|
+
});
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
module.exports = { PiStyleProvider };
|
package/src/ai/provider.js
CHANGED
|
@@ -692,6 +692,7 @@ function applyConfigOverrides(config) {
|
|
|
692
692
|
env: providerConfig.env,
|
|
693
693
|
load_skills: providerConfig.load_skills,
|
|
694
694
|
app_extensions: providerConfig.app_extensions,
|
|
695
|
+
advisor: providerConfig.advisor,
|
|
695
696
|
availability_timeout_seconds: providerConfig.availability_timeout_seconds,
|
|
696
697
|
models: AliasClass.getModels() !== BaseClass.getModels() ? AliasClass.getModels() : null,
|
|
697
698
|
disabled_models: aliasDisabled,
|
|
@@ -750,6 +751,7 @@ function applyConfigOverrides(config) {
|
|
|
750
751
|
env: providerConfig.env,
|
|
751
752
|
load_skills: providerConfig.load_skills,
|
|
752
753
|
app_extensions: providerConfig.app_extensions,
|
|
754
|
+
advisor: providerConfig.advisor,
|
|
753
755
|
availability_timeout_seconds: providerConfig.availability_timeout_seconds,
|
|
754
756
|
models: processedModels,
|
|
755
757
|
disabled_models: disabledModels,
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* Chat Provider Registry
|
|
4
4
|
*
|
|
5
|
-
* Defines named chat providers (Pi, Copilot, OpenCode, Claude, Codex, Cursor) with
|
|
6
|
-
* default commands/args, config overrides, and availability checks.
|
|
5
|
+
* Defines named chat providers (Pi, OMP, Copilot, OpenCode, Claude, Codex, Cursor) with
|
|
6
|
+
* their default commands/args, config overrides, and availability checks.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
const { spawn } = require('child_process');
|
|
@@ -24,6 +24,17 @@ const CHAT_PROVIDERS = {
|
|
|
24
24
|
name: 'Pi (RPC)',
|
|
25
25
|
type: 'pi',
|
|
26
26
|
},
|
|
27
|
+
// OMP (Oh My Pi) is a Pi fork that speaks the same RPC protocol with a
|
|
28
|
+
// slightly different CLI surface (see OmpBridge). Like the built-in Pi
|
|
29
|
+
// definition, `command` is intentionally omitted: OmpBridge resolves its own
|
|
30
|
+
// default at runtime, and the availability check delegates to the AI
|
|
31
|
+
// provider's cached probe (which honors PAIR_REVIEW_OMP_CMD and
|
|
32
|
+
// providers.omp.command).
|
|
33
|
+
omp: {
|
|
34
|
+
id: 'omp',
|
|
35
|
+
name: 'OMP (RPC)',
|
|
36
|
+
type: 'omp',
|
|
37
|
+
},
|
|
27
38
|
'copilot-acp': {
|
|
28
39
|
id: 'copilot-acp',
|
|
29
40
|
name: 'Copilot (ACP)',
|
|
@@ -205,6 +216,16 @@ function isAcpProvider(id) {
|
|
|
205
216
|
return provider?.type === 'acp';
|
|
206
217
|
}
|
|
207
218
|
|
|
219
|
+
/**
|
|
220
|
+
* Check if a provider ID corresponds to an OMP (Oh My Pi) provider.
|
|
221
|
+
* @param {string} id
|
|
222
|
+
* @returns {boolean}
|
|
223
|
+
*/
|
|
224
|
+
function isOmpProvider(id) {
|
|
225
|
+
const provider = getChatProvider(id);
|
|
226
|
+
return provider?.type === 'omp';
|
|
227
|
+
}
|
|
228
|
+
|
|
208
229
|
/**
|
|
209
230
|
* Check if a provider ID corresponds to a Claude Code provider.
|
|
210
231
|
* @param {string} id
|
|
@@ -262,15 +283,16 @@ async function checkChatProviderAvailability(id, _deps) {
|
|
|
262
283
|
});
|
|
263
284
|
}
|
|
264
285
|
|
|
265
|
-
// Delegate to the AI provider's cached availability only for the built-in
|
|
266
|
-
// chat
|
|
267
|
-
// provider already probed. The built-in `pi`
|
|
268
|
-
// `command` (PiBridge
|
|
269
|
-
//
|
|
270
|
-
//
|
|
271
|
-
//
|
|
272
|
-
|
|
273
|
-
|
|
286
|
+
// Delegate to the AI provider's cached availability only for the built-in
|
|
287
|
+
// Pi/OMP chat providers with no command override — i.e. the same binary the
|
|
288
|
+
// AI provider already probed. The built-in `pi`/`omp` definitions
|
|
289
|
+
// intentionally omit `command` (PiBridge/OmpBridge resolve their own default
|
|
290
|
+
// at runtime), so `!provider.command` cleanly distinguishes them. Custom
|
|
291
|
+
// `type: 'pi'`/`type: 'omp'` providers and built-ins overridden with a
|
|
292
|
+
// different `command` point at a different binary, so they fall through to
|
|
293
|
+
// the `<command> --version` probe below (which honors `timeout`).
|
|
294
|
+
if ((provider.type === 'pi' || provider.type === 'omp') && !provider.command) {
|
|
295
|
+
const cached = getCachedAvailability(provider.type);
|
|
274
296
|
return { available: cached?.available || false, error: cached?.error };
|
|
275
297
|
}
|
|
276
298
|
|
|
@@ -402,6 +424,7 @@ module.exports = {
|
|
|
402
424
|
getChatProvider,
|
|
403
425
|
getAllChatProviders,
|
|
404
426
|
isAcpProvider,
|
|
427
|
+
isOmpProvider,
|
|
405
428
|
isClaudeCodeProvider,
|
|
406
429
|
isCodexProvider,
|
|
407
430
|
checkChatProviderAvailability,
|