@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.
@@ -10,26 +10,19 @@
10
10
  * Text content is extracted from message_end events which contain the
11
11
  * complete assistant message with content blocks.
12
12
  *
13
+ * The process lifecycle (spawn/parse/abort/timeout) is shared with the OMP
14
+ * provider via PiStyleProvider (pi-style-provider.js); this file defines
15
+ * Pi's CLI surface: argv construction, model resolution, and env merging.
16
+ *
13
17
  * Pi provides built-in analysis modes (default, multi-model) and supports
14
18
  * additional models via config.providers.pi.models in ~/.pair-review/config.json.
15
19
  * User-configured models can use `provider/model` format (e.g., 'google/gemini-2.5-flash')
16
20
  * for cross-provider switching, which translates to `--provider <provider> --model <model>`.
17
21
  */
18
22
 
19
- const crypto = require('crypto');
20
23
  const path = require('path');
21
- const os = require('os');
22
- const fs = require('fs');
23
- const { spawn } = require('child_process');
24
- const { AIProvider, registerProvider, quoteShellArgs } = require('./provider');
25
- const logger = require('../utils/logger');
26
- const { extractJSON } = require('../utils/json-extractor');
27
- const { CancellationError, isAnalysisCancelled } = require('../routes/shared');
28
- const { createPiLineParser } = require('./stream-parser');
29
- const { wireAbortToChild, makeAbortError, killChildSafely } = require('./abort-signal-wiring');
30
-
31
- // Directory containing bin scripts (git-diff-lines, etc.)
32
- const BIN_DIR = path.join(__dirname, '..', '..', 'bin');
24
+ const { registerProvider } = require('./provider');
25
+ const { PiStyleProvider } = require('./pi-style-provider');
33
26
 
34
27
  // Path to the bundled Pi task extension, which provides a generic subagent tool
35
28
  // for delegating work to isolated pi subprocesses during analysis
@@ -43,16 +36,6 @@ const REVIEW_SKILL_PATH = path.join(__dirname, '..', '..', '.pi', 'skills', 'rev
43
36
  // in parallel for diverse multi-perspective code review
44
37
  const ROULETTE_SKILL_PATH = path.join(__dirname, '..', '..', '.pi', 'skills', 'review-roulette', 'SKILL.md');
45
38
 
46
- // Keep raw stream capture bounded so large JSONL sessions cannot exhaust V8's
47
- // maximum string size. Assistant text is still extracted incrementally from all
48
- // complete JSONL lines and used as the primary parse/fallback input.
49
- const MAX_PI_CAPTURED_STDOUT_CHARS = 5 * 1024 * 1024;
50
- const MAX_PI_CAPTURED_STDERR_CHARS = 1 * 1024 * 1024;
51
- const MAX_PI_LINE_CHARS = 2 * 1024 * 1024;
52
- const PI_STDERR_HEAD_CHARS = 128 * 1024;
53
- const PI_STDERR_TAIL_CHARS = MAX_PI_CAPTURED_STDERR_CHARS - PI_STDERR_HEAD_CHARS;
54
- const PI_TRUNCATED_LINE_MARKER = '...[line truncated]...';
55
-
56
39
  /**
57
40
  * Pi model definitions
58
41
  *
@@ -105,353 +88,7 @@ const PI_MODELS = [
105
88
  }
106
89
  ];
107
90
 
108
- /**
109
- * Extract text from assistant content, handling both array-of-blocks and
110
- * string content. Uses a Set for dedup to avoid incorrect substring matching.
111
- *
112
- * @param {Array|string} content - Content from an assistant message
113
- * @param {Set<string>} seenTexts - Set tracking already-seen text blocks
114
- * @returns {string} Extracted text (may be empty if all blocks were duplicates)
115
- */
116
- function extractAssistantText(content, seenTexts) {
117
- let text = '';
118
- if (Array.isArray(content)) {
119
- for (const block of content) {
120
- if (block.type === 'text' && block.text) {
121
- if (!seenTexts.has(block.text)) {
122
- seenTexts.add(block.text);
123
- text += block.text;
124
- }
125
- }
126
- }
127
- } else if (typeof content === 'string') {
128
- if (!seenTexts.has(content)) {
129
- seenTexts.add(content);
130
- text += content;
131
- }
132
- }
133
- return text;
134
- }
135
-
136
- /**
137
- * Determine whether a parsed JSON object looks like a Pi JSONL event envelope
138
- * rather than a final review result payload.
139
- *
140
- * @param {Object} value - Parsed JSON object
141
- * @returns {boolean} True when the object appears to be a Pi event
142
- */
143
- function isPiEventEnvelope(value) {
144
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
145
- return false;
146
- }
147
-
148
- if (typeof value.type !== 'string') {
149
- return false;
150
- }
151
-
152
- if (
153
- value.message ||
154
- Array.isArray(value.messages) ||
155
- value.assistantMessageEvent ||
156
- value.toolName ||
157
- value.toolCallId ||
158
- Object.hasOwn(value, 'partialResult') ||
159
- Object.hasOwn(value, 'result') ||
160
- Object.hasOwn(value, 'version')
161
- ) {
162
- return true;
163
- }
164
-
165
- return /_(start|update|end)$/.test(value.type) || value.type === 'session';
166
- }
167
-
168
- /**
169
- * Append a chunk to a captured stream buffer without exceeding the configured
170
- * maximum. Returns the updated buffer and whether truncation occurred.
171
- *
172
- * @param {string} existing - Existing captured output
173
- * @param {string} chunk - New output chunk
174
- * @param {number} maxChars - Maximum number of chars to retain
175
- * @returns {{value: string, truncated: boolean}}
176
- */
177
- function appendWithLimit(existing, chunk, maxChars) {
178
- if (!chunk || maxChars <= 0) {
179
- return { value: existing, truncated: false };
180
- }
181
-
182
- const remaining = maxChars - existing.length;
183
- if (remaining <= 0) {
184
- return { value: existing, truncated: true };
185
- }
186
-
187
- if (chunk.length <= remaining) {
188
- return { value: existing + chunk, truncated: false };
189
- }
190
-
191
- return {
192
- value: existing + chunk.slice(0, remaining),
193
- truncated: true
194
- };
195
- }
196
-
197
- /**
198
- * Append a chunk to a bounded head+tail buffer so error logs preserve both the
199
- * start and end of noisy stderr output.
200
- *
201
- * @param {{head: string, tail: string, headFull: boolean, omittedChars: number}} buffer - Buffer state
202
- * @param {string} chunk - New stderr chunk
203
- * @param {number} maxHeadChars - Max chars to retain from the start
204
- * @param {number} maxTailChars - Max chars to retain from the end
205
- */
206
- function appendHeadTailBuffer(buffer, chunk, maxHeadChars, maxTailChars) {
207
- if (!chunk) return;
208
-
209
- if (!buffer.headFull) {
210
- const remainingHead = maxHeadChars - buffer.head.length;
211
- if (chunk.length <= remainingHead) {
212
- buffer.head += chunk;
213
- if (buffer.head.length >= maxHeadChars) {
214
- buffer.headFull = true;
215
- }
216
- return;
217
- }
218
-
219
- const safeHead = Math.max(remainingHead, 0);
220
- buffer.head += chunk.slice(0, safeHead);
221
- buffer.headFull = true;
222
-
223
- const overflow = chunk.slice(safeHead);
224
- if (overflow.length > maxTailChars) {
225
- buffer.omittedChars += overflow.length - maxTailChars;
226
- buffer.tail = overflow.slice(-maxTailChars);
227
- } else {
228
- buffer.tail = overflow;
229
- }
230
- return;
231
- }
232
-
233
- const combinedTail = buffer.tail + chunk;
234
- if (combinedTail.length > maxTailChars) {
235
- buffer.omittedChars += combinedTail.length - maxTailChars;
236
- buffer.tail = combinedTail.slice(-maxTailChars);
237
- } else {
238
- buffer.tail = combinedTail;
239
- }
240
- }
241
-
242
- /**
243
- * Render a bounded head+tail buffer as a string for logs and error messages.
244
- *
245
- * @param {{head: string, tail: string, headFull: boolean, omittedChars: number}} buffer - Buffer state
246
- * @returns {string} Formatted stderr capture
247
- */
248
- function formatHeadTailBuffer(buffer) {
249
- if (buffer.omittedChars === 0) {
250
- return `${buffer.head}${buffer.tail}`;
251
- }
252
-
253
- return `${buffer.head}\n...[${buffer.omittedChars} chars omitted]...\n${buffer.tail}`;
254
- }
255
-
256
- /**
257
- * Extract final assistant text from a Pi JSONL event.
258
- *
259
- * @param {Object} event - Parsed Pi event object
260
- * @param {Set<string>} seenTexts - Set tracking already-seen text blocks
261
- * @returns {string} Extracted text from the event
262
- */
263
- function extractPiEventText(event, seenTexts) {
264
- let text = '';
265
-
266
- if (event.type === 'message_end' && event.message?.role === 'assistant') {
267
- text += extractAssistantText(event.message.content, seenTexts);
268
- }
269
-
270
- if (event.type === 'turn_end' && event.message?.role === 'assistant') {
271
- text += extractAssistantText(event.message.content, seenTexts);
272
- }
273
-
274
- if (event.type === 'agent_end' && Array.isArray(event.messages)) {
275
- for (const msg of event.messages) {
276
- if (msg.role === 'assistant') {
277
- text += extractAssistantText(msg.content, seenTexts);
278
- }
279
- }
280
- }
281
-
282
- return text;
283
- }
284
-
285
- /**
286
- * Accumulate only raw lines that could plausibly help the direct JSON fallback.
287
- * Pi JSONL event envelopes are intentionally excluded because they are noisy
288
- * transport records, not the final review result.
289
- *
290
- * @param {string} line - One stdout line
291
- * @param {{rawOutput: string, rawOutputTruncated: boolean}} state - Parse state
292
- * @param {string} levelPrefix - Prefix used in logs
293
- * @param {{status: 'parsed', value: Object} | {status: 'failed'}} [parseResult] - Optional parse result reuse
294
- */
295
- function accumulatePiRawFallbackLine(line, state, levelPrefix, parseResult) {
296
- if (!line?.trim()) return;
297
-
298
- let parsed;
299
- let parseFailed = false;
300
-
301
- if (parseResult?.status === 'parsed') {
302
- parsed = parseResult.value;
303
- } else if (parseResult?.status === 'failed') {
304
- parseFailed = true;
305
- } else {
306
- try {
307
- parsed = JSON.parse(line);
308
- } catch {
309
- parseFailed = true;
310
- }
311
- }
312
-
313
- if (!parseFailed && isPiEventEnvelope(parsed)) {
314
- return;
315
- }
316
-
317
- const capture = appendWithLimit(state.rawOutput, `${line}\n`, MAX_PI_CAPTURED_STDOUT_CHARS);
318
- state.rawOutput = capture.value;
319
-
320
- if (capture.truncated && !state.rawOutputTruncated) {
321
- state.rawOutputTruncated = true;
322
- logger.warn(
323
- `${levelPrefix} Pi CLI raw-output fallback exceeded ${MAX_PI_CAPTURED_STDOUT_CHARS} chars; retaining only the first ${MAX_PI_CAPTURED_STDOUT_CHARS} chars`
324
- );
325
- }
326
- }
327
-
328
- /**
329
- * Parse a single Pi JSONL line into accumulated assistant text.
330
- *
331
- * @param {string} line - One JSONL line
332
- * @param {{textContent: string, seenTexts: Set<string>, rawOutput: string, rawOutputTruncated: boolean}} state - Parse state
333
- * @param {string} levelPrefix - Prefix used in logs
334
- */
335
- function accumulatePiResponseLine(line, state, levelPrefix) {
336
- if (!line?.trim()) return;
337
-
338
- let parseResult;
339
- try {
340
- const event = JSON.parse(line);
341
- state.textContent += extractPiEventText(event, state.seenTexts);
342
- parseResult = { status: 'parsed', value: event };
343
- } catch {
344
- logger.debug(`${levelPrefix} Skipping malformed JSONL line: ${line.substring(0, 100)}`);
345
- parseResult = { status: 'failed' };
346
- }
347
-
348
- accumulatePiRawFallbackLine(line, state, levelPrefix, parseResult);
349
- }
350
-
351
- /**
352
- * Append stdout data to the pending JSONL line buffer while capping any single
353
- * unterminated line to avoid retaining multi-megabyte tool payloads in memory.
354
- *
355
- * @param {{buffer: string, lineTruncated: boolean, warningLogged: boolean}} state - Pending line state
356
- * @param {string} chunk - New stdout chunk
357
- * @param {string} levelPrefix - Prefix used in logs
358
- * @returns {string[]} Complete lines extracted from the chunk
359
- */
360
- function appendPiChunkToLineBuffer(state, chunk, levelPrefix) {
361
- if (!chunk) return [];
362
-
363
- const lines = [];
364
- let cursor = 0;
365
-
366
- while (cursor < chunk.length) {
367
- if (state.lineTruncated) {
368
- const nextNewline = chunk.indexOf('\n', cursor);
369
- if (nextNewline === -1) {
370
- return lines;
371
- }
372
-
373
- lines.push(state.buffer);
374
- state.buffer = '';
375
- state.lineTruncated = false;
376
- cursor = nextNewline + 1;
377
- continue;
378
- }
379
-
380
- const nextNewline = chunk.indexOf('\n', cursor);
381
- const segmentEnd = nextNewline === -1 ? chunk.length : nextNewline;
382
- const segment = chunk.slice(cursor, segmentEnd);
383
- const remainingCapacity = MAX_PI_LINE_CHARS - state.buffer.length;
384
-
385
- if (segment.length <= remainingCapacity) {
386
- state.buffer += segment;
387
- if (nextNewline !== -1) {
388
- lines.push(state.buffer);
389
- state.buffer = '';
390
- }
391
- cursor = segmentEnd + (nextNewline === -1 ? 0 : 1);
392
- continue;
393
- }
394
-
395
- const safeCapacity = Math.max(remainingCapacity, 0);
396
- state.buffer += segment.slice(0, safeCapacity) + PI_TRUNCATED_LINE_MARKER;
397
- state.lineTruncated = true;
398
-
399
- if (!state.warningLogged) {
400
- state.warningLogged = true;
401
- logger.warn(
402
- `${levelPrefix} Pi CLI emitted a JSONL event longer than ${MAX_PI_LINE_CHARS} chars; truncating the pending line buffer until the next newline`
403
- );
404
- }
405
-
406
- if (nextNewline !== -1) {
407
- lines.push(state.buffer);
408
- state.buffer = '';
409
- state.lineTruncated = false;
410
- cursor = nextNewline + 1;
411
- continue;
412
- }
413
-
414
- return lines;
415
- }
416
-
417
- return lines;
418
- }
419
-
420
- /**
421
- * Finalize Pi response parsing from incrementally extracted assistant text and
422
- * a bounded raw-output fallback buffer.
423
- *
424
- * @param {Object} input - Parse inputs
425
- * @param {string} input.textContent - Assistant text extracted from JSONL events
426
- * @param {string} input.rawOutput - Bounded raw stdout capture
427
- * @param {boolean} [input.rawOutputTruncated=false] - Whether raw stdout was truncated
428
- * @param {string|number} level - Analysis level for logging
429
- * @param {string} levelPrefix - Prefix used in logs
430
- * @returns {{success: boolean, data?: Object, error?: string, textContent?: string}}
431
- */
432
- function finalizePiResponseParsing({ textContent, rawOutput, rawOutputTruncated = false }, level, levelPrefix) {
433
- if (textContent) {
434
- const extracted = extractJSON(textContent, level, levelPrefix);
435
- if (extracted.success) {
436
- return extracted;
437
- }
438
-
439
- logger.warn(`${levelPrefix} Text content is not JSON, treating as raw text`);
440
- return { success: false, error: 'Text content is not valid JSON', textContent };
441
- }
442
-
443
- if (rawOutputTruncated) {
444
- logger.warn(`${levelPrefix} Pi CLI raw-output fallback was truncated before assistant text could be recovered`);
445
- return {
446
- success: false,
447
- error: 'Pi CLI raw-output fallback was truncated before assistant text could be recovered'
448
- };
449
- }
450
-
451
- return extractJSON(rawOutput, level, levelPrefix);
452
- }
453
-
454
- class PiProvider extends AIProvider {
91
+ class PiProvider extends PiStyleProvider {
455
92
  /**
456
93
  * @param {string|null} [model='default'] - Model identifier or null/undefined for default mode
457
94
  * @param {Object} configOverrides - Config overrides from providers config
@@ -552,494 +189,40 @@ class PiProvider extends AIProvider {
552
189
  const providerArgs = configOverrides.extra_args || [];
553
190
  const modelArgs = configModel?.extra_args || [];
554
191
 
555
- // PI_CMD tells the task extension how to invoke pi for subtasks.
556
- // This is essential when pi is invoked through a wrapper (e.g., 'devx pi --').
557
- // Merge env: defaults → built-in model → provider config → per-model config.
558
- // Later entries override earlier ones, so model-specific settings (e.g.,
559
- // review-roulette's PI_TASK_MAX_DEPTH=2) take precedence over defaults.
560
- this.extraEnv = {
561
- PI_TASK_MAX_DEPTH: '1',
562
- ...(builtIn?.env || {}),
563
- ...(configOverrides.env || {}),
564
- ...(configModel?.env || {}),
565
- PI_CMD: piCmd,
566
- };
567
-
568
- // Store base command and args (prompt added in execute)
569
- this.piCmd = piCmd;
192
+ // Store base command (used by the shared execute/extraction/availability
193
+ // paths in PiStyleProvider) and args (prompt added in execute)
194
+ this.cliCmd = piCmd;
195
+ this.cliName = 'Pi';
196
+ this.extraEnv = this._resolveEnvForModel(resolvedModel);
570
197
  this.baseArgs = [...baseArgs, ...builtInArgs, ...providerArgs, ...modelArgs];
571
-
572
- // configOverrides already stored at top of constructor for _resolveCliModelArgs
573
- }
574
-
575
- /**
576
- * Execute Pi CLI with a prompt
577
- * @param {string} prompt - The prompt to send to Pi
578
- * @param {Object} options - Optional configuration
579
- * @returns {Promise<Object>} Parsed response or error
580
- */
581
- async execute(prompt, options = {}) {
582
- return new Promise((resolve, reject) => {
583
- const { cwd = process.cwd(), timeout = 900000, level = 'unknown', analysisId, registerProcess, onStreamEvent, logPrefix, abortSignal } = options;
584
-
585
- const levelPrefix = logPrefix || `[Level ${level}]`;
586
- logger.info(`${levelPrefix} Executing Pi CLI...`);
587
- logger.info(`${levelPrefix} Prompt: ${prompt.length} bytes`);
588
-
589
- // Write prompt to a temp file and use Pi's @file syntax as a positional arg.
590
- // This bypasses devx stdin interference that breaks --mode json output.
591
- const tmpFile = path.join(os.tmpdir(), `pair-review-prompt-${Date.now()}-${process.pid}-${crypto.randomUUID()}.txt`);
592
- fs.writeFileSync(tmpFile, prompt);
593
- const cleanupTmpFile = () => { try { fs.unlinkSync(tmpFile); } catch { /* ignore */ } };
594
-
595
- let fullCommand;
596
- let fullArgs;
597
-
598
- if (this.useShell) {
599
- fullCommand = `${this.piCmd} ${quoteShellArgs([...this.baseArgs, `@${tmpFile}`]).join(' ')}`;
600
- fullArgs = [];
601
- } else {
602
- fullCommand = this.piCmd;
603
- fullArgs = [...this.baseArgs, `@${tmpFile}`];
604
- }
605
-
606
- const pi = spawn(fullCommand, fullArgs, {
607
- cwd,
608
- env: {
609
- ...process.env,
610
- ...this.extraEnv,
611
- PATH: `${BIN_DIR}:${process.env.PATH}`
612
- },
613
- shell: this.useShell,
614
- detached: this.useShell
615
- });
616
-
617
- // Close stdin immediately — prompt is delivered via @file, but some
618
- // wrappers (e.g., devx) keep the process alive until stdin is closed.
619
- pi.stdin.end();
620
-
621
- const pid = pi.pid;
622
- logger.debug(`${levelPrefix} Pi CLI command: ${fullCommand} ${fullArgs.join(' ')}`);
623
- logger.info(`${levelPrefix} Spawned Pi CLI process: PID ${pid}`);
624
-
625
- // Register process for cancellation tracking if analysisId provided
626
- if (analysisId && registerProcess) {
627
- registerProcess(analysisId, pi);
628
- logger.info(`${levelPrefix} Registered process ${pid} for analysis ${analysisId}`);
629
- }
630
-
631
- // Wire AbortSignal -> SIGTERM for tour/summary cancellation.
632
- const abortWiring = wireAbortToChild(pi, abortSignal, { logPrefix: levelPrefix, shell: this.useShell });
633
-
634
- const stderrCapture = {
635
- head: '',
636
- tail: '',
637
- headFull: false,
638
- omittedChars: 0
639
- };
640
- let stderrTruncated = false;
641
- let timeoutId = null;
642
- let settled = false; // Guard against multiple resolve/reject calls
643
- let lineCount = 0; // Count of JSONL lines received
644
- const lineBufferState = {
645
- buffer: '',
646
- lineTruncated: false,
647
- warningLogged: false
648
- };
649
- const responseState = {
650
- textContent: '',
651
- seenTexts: new Set(),
652
- rawOutput: '',
653
- rawOutputTruncated: false
654
- };
655
-
656
- const settle = (fn, value) => {
657
- if (settled) return;
658
- settled = true;
659
- if (timeoutId) clearTimeout(timeoutId);
660
- abortWiring.detach();
661
- fn(value);
662
- };
663
-
664
- // Use the buffered Pi line parser to accumulate text_delta fragments
665
- // before emitting, preventing the UI from being flooded with tiny updates.
666
- const streamLineParser = onStreamEvent ? createPiLineParser() : null;
667
- const emitStreamLine = (line) => {
668
- if (!streamLineParser || !line?.trim()) return;
669
-
670
- const event = streamLineParser(line, { cwd });
671
- if (!event) return;
672
-
673
- try {
674
- onStreamEvent(event);
675
- } catch (error) {
676
- logger.warn(`${levelPrefix} Pi stream event callback error: ${error.message}`);
677
- }
678
- };
679
-
680
- // Set timeout
681
- if (timeout) {
682
- timeoutId = setTimeout(() => {
683
- logger.error(`${levelPrefix} Process ${pid} timed out after ${timeout}ms`);
684
- killChildSafely(pi, { logPrefix: levelPrefix, shell: this.useShell });
685
- settle(reject, new Error(`${levelPrefix} Pi CLI timed out after ${timeout}ms`));
686
- }, timeout);
687
- }
688
-
689
- // Stream and log JSONL lines as they arrive for debugging visibility
690
- pi.stdout.on('data', (data) => {
691
- const chunk = data.toString();
692
- const lines = appendPiChunkToLineBuffer(lineBufferState, chunk, levelPrefix);
693
-
694
- for (const line of lines) {
695
- if (!line.trim()) continue;
696
- lineCount++;
697
- emitStreamLine(line);
698
- this.logStreamLine(line, lineCount, levelPrefix);
699
- accumulatePiResponseLine(line, responseState, levelPrefix);
700
- }
701
- });
702
-
703
- // Collect stderr
704
- pi.stderr.on('data', (data) => {
705
- const chunk = data.toString();
706
- appendHeadTailBuffer(stderrCapture, chunk, PI_STDERR_HEAD_CHARS, PI_STDERR_TAIL_CHARS);
707
- if (stderrCapture.omittedChars > 0 && !stderrTruncated) {
708
- stderrTruncated = true;
709
- logger.warn(
710
- `${levelPrefix} Pi CLI stderr exceeded ${MAX_PI_CAPTURED_STDERR_CHARS} chars; retaining a head+tail excerpt (${stderrCapture.omittedChars} chars omitted so far)`
711
- );
712
- }
713
- });
714
-
715
- // Handle completion
716
- pi.on('close', (code) => {
717
- cleanupTmpFile();
718
- if (settled) return; // Already settled by timeout or error
719
-
720
- // Detach is centralized in `settle`.
721
-
722
- // BackgroundQueue-driven cancellation — mirror of claude-provider.
723
- if (abortWiring.cancelled()) {
724
- logger.info(`${levelPrefix} Pi CLI terminated by user cancel (exit code ${code})`);
725
- settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
726
- return;
727
- }
728
-
729
- // Check for cancellation signals (SIGTERM=143, SIGKILL=137)
730
- const isCancellationCode = code === 143 || code === 137;
731
- if (isCancellationCode && analysisId && isAnalysisCancelled(analysisId)) {
732
- logger.info(`${levelPrefix} Pi CLI terminated due to analysis cancellation (exit code ${code})`);
733
- settle(reject, new CancellationError(`${levelPrefix} Analysis cancelled by user`));
734
- return;
735
- }
736
-
737
- // Also check for cancellation even with exit code 0 (Pi CLI may handle
738
- // SIGTERM gracefully and exit cleanly rather than with code 143)
739
- if (analysisId && isAnalysisCancelled(analysisId)) {
740
- logger.info(`${levelPrefix} Pi CLI exited with code ${code} but analysis was cancelled`);
741
- settle(reject, new CancellationError(`${levelPrefix} Analysis cancelled by user`));
742
- return;
743
- }
744
-
745
- const stderr = formatHeadTailBuffer(stderrCapture);
746
-
747
- // Always log stderr if present
748
- if (stderr.trim()) {
749
- if (code !== 0) {
750
- logger.error(`${levelPrefix} Pi CLI stderr (exit code ${code}): ${stderr}`);
751
- } else {
752
- logger.warn(`${levelPrefix} Pi CLI stderr (success): ${stderr}`);
753
- }
754
- }
755
-
756
- if (code !== 0) {
757
- logger.error(`${levelPrefix} Pi CLI exited with code ${code}`);
758
- settle(reject, new Error(`${levelPrefix} Pi CLI exited with code ${code}: ${stderr}`));
759
- return;
760
- }
761
-
762
- // Process any remaining buffered line
763
- if (lineBufferState.buffer.trim()) {
764
- lineCount++;
765
- emitStreamLine(lineBufferState.buffer);
766
- this.logStreamLine(lineBufferState.buffer, lineCount, levelPrefix);
767
- accumulatePiResponseLine(lineBufferState.buffer, responseState, levelPrefix);
768
- }
769
-
770
- logger.info(`${levelPrefix} Pi CLI completed - received ${lineCount} JSONL events`);
771
-
772
- // Parse the Pi JSONL response
773
- const parsed = finalizePiResponseParsing({
774
- textContent: responseState.textContent,
775
- rawOutput: responseState.rawOutput,
776
- rawOutputTruncated: responseState.rawOutputTruncated
777
- }, level, levelPrefix);
778
- if (parsed.success) {
779
- logger.success(`${levelPrefix} Successfully parsed JSON response`);
780
-
781
- // Log a summary of the response
782
- if (parsed.data?.suggestions) {
783
- const count = Array.isArray(parsed.data.suggestions) ? parsed.data.suggestions.length : 0;
784
- logger.info(`${levelPrefix} [response] ${count} suggestions extracted`);
785
- } else if (parsed.data) {
786
- const jsonStr = JSON.stringify(parsed.data);
787
- logger.info(`${levelPrefix} [response] ${jsonStr.length} chars of JSON data`);
788
- }
789
-
790
- settle(resolve, parsed.data);
791
- } else {
792
- // Regex extraction failed, try LLM-based extraction as fallback
793
- logger.warn(`${levelPrefix} Regex extraction failed: ${parsed.error}`);
794
- // Pass extracted text content to LLM fallback (not raw JSONL stdout).
795
- // The text content is the actual LLM response text extracted from JSONL
796
- // events and is much smaller and more relevant than the full JSONL stream.
797
- const llmFallbackInput = parsed.textContent || responseState.rawOutput;
798
- logger.info(`${levelPrefix} LLM fallback input length: ${llmFallbackInput.length} characters (${parsed.textContent ? 'text content' : 'raw fallback output'})`);
799
- logger.info(`${levelPrefix} Attempting LLM-based JSON extraction fallback...`);
800
-
801
- // The pi child has already exited, so a cancel arriving now only makes
802
- // the abort wiring kill something already dead. The `settled` guard
803
- // below only covers a cancel that landed BEFORE the await, so without
804
- // the checks below one landing during extraction would settle as a
805
- // normal result. The signal is read alongside the wiring flag as the
806
- // source of truth.
807
- const cancelledDuringExtraction = () =>
808
- abortWiring.cancelled() || abortSignal?.aborted === true;
809
-
810
- // Use async IIFE to handle the async LLM extraction
811
- (async () => {
812
- // Guard: if already settled (by timeout, process error, or cancellation),
813
- // skip the LLM extraction entirely to avoid misleading log output
814
- if (settled) return;
815
-
816
- try {
817
- // `abortSignal` lets the extraction spawn be killed rather than
818
- // merely abandoned until its own 60s timeout.
819
- const llmExtracted = await this.extractJSONWithLLM(llmFallbackInput, { level, analysisId, registerProcess, logPrefix: levelPrefix, abortSignal });
820
- if (cancelledDuringExtraction()) {
821
- logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
822
- settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
823
- return;
824
- }
825
- if (llmExtracted.success) {
826
- logger.success(`${levelPrefix} LLM extraction fallback succeeded`);
827
- settle(resolve, llmExtracted.data);
828
- } else {
829
- logger.warn(`${levelPrefix} LLM extraction fallback also failed: ${llmExtracted.error}`);
830
- logger.info(`${levelPrefix} Raw response preview: ${llmFallbackInput.substring(0, 500)}...`);
831
- settle(resolve, { raw: llmFallbackInput, parsed: false });
832
- }
833
- } catch (llmError) {
834
- // An abort that kills the extraction spawn surfaces here as a
835
- // thrown error; it is a cancellation, not a parse failure.
836
- if (cancelledDuringExtraction()) {
837
- logger.info(`${levelPrefix} Cancelled by user during LLM extraction fallback`);
838
- settle(reject, makeAbortError(`${levelPrefix} Cancelled by user`));
839
- return;
840
- }
841
- logger.warn(`${levelPrefix} LLM extraction fallback error: ${llmError.message}`);
842
- settle(resolve, { raw: llmFallbackInput, parsed: false });
843
- }
844
- })();
845
- }
846
- });
847
-
848
- // Handle errors
849
- pi.on('error', (error) => {
850
- cleanupTmpFile();
851
- // Detach happens inside `settle`.
852
- if (error.code === 'ENOENT') {
853
- logger.error(`${levelPrefix} Pi CLI not found. Please ensure Pi CLI is installed.`);
854
- settle(reject, new Error(`${levelPrefix} Pi CLI not found. ${PiProvider.getInstallInstructions()}`));
855
- } else {
856
- logger.error(`${levelPrefix} Pi process error: ${error}`);
857
- settle(reject, error);
858
- }
859
- });
860
- });
861
198
  }
862
199
 
863
200
  /**
864
- * Log a streaming JSONL line for debugging visibility
865
- * Extracts meaningful info from each event type without being too verbose
201
+ * Resolve the extra env vars for a given model.
202
+ * Merge order: defaults → built-in model → provider config → per-model config.
203
+ * Later entries override earlier ones, so model-specific settings (e.g.,
204
+ * review-roulette's PI_TASK_MAX_DEPTH=2) take precedence over defaults.
866
205
  *
867
- * Uses logger.streamDebug() which only logs when --debug-stream flag is enabled.
206
+ * PI_CMD tells the task extension how to invoke pi for subtasks.
207
+ * This is essential when pi is invoked through a wrapper (e.g., 'devx pi --').
868
208
  *
869
- * @param {string} line - A single JSONL line
870
- * @param {number} lineNum - Line number for reference
871
- * @param {string} levelPrefix - Level prefix for log messages
872
- */
873
- logStreamLine(line, lineNum, levelPrefix) {
874
- // Early exit if stream debugging is disabled
875
- if (!logger.isStreamDebugEnabled()) return;
876
-
877
- try {
878
- const event = JSON.parse(line);
879
- const type = event.type || 'unknown';
880
-
881
- // Log different event types with appropriate detail
882
- switch (type) {
883
- case 'session':
884
- logger.streamDebug(`${levelPrefix} [#${lineNum}] Session started: ${event.id || 'unknown'}`);
885
- break;
886
-
887
- case 'turn_start':
888
- logger.streamDebug(`${levelPrefix} [#${lineNum}] Turn started`);
889
- break;
890
-
891
- case 'turn_end': {
892
- const msg = event.message;
893
- if (msg?.role) {
894
- logger.streamDebug(`${levelPrefix} [#${lineNum}] Turn ended (${msg.role})`);
895
- } else {
896
- logger.streamDebug(`${levelPrefix} [#${lineNum}] Turn ended`);
897
- }
898
- break;
899
- }
900
-
901
- case 'message_start': {
902
- const msg = event.message;
903
- const role = msg?.role || 'unknown';
904
- logger.streamDebug(`${levelPrefix} [#${lineNum}] Message started (${role})`);
905
- break;
906
- }
907
-
908
- case 'message_update': {
909
- const assistantEvent = event.assistantMessageEvent;
910
- if (assistantEvent?.type === 'text_delta' && assistantEvent?.delta) {
911
- const preview = assistantEvent.delta.length > 60
912
- ? assistantEvent.delta.substring(0, 60) + '...'
913
- : assistantEvent.delta;
914
- logger.streamDebug(`${levelPrefix} [#${lineNum}] text_delta: ${preview.replace(/\n/g, '\\n')}`);
915
- } else if (assistantEvent?.type) {
916
- logger.streamDebug(`${levelPrefix} [#${lineNum}] message_update: ${assistantEvent.type}`);
917
- } else {
918
- logger.streamDebug(`${levelPrefix} [#${lineNum}] message_update`);
919
- }
920
- break;
921
- }
922
-
923
- case 'message_end': {
924
- const msg = event.message;
925
- const role = msg?.role || 'unknown';
926
- logger.streamDebug(`${levelPrefix} [#${lineNum}] Message ended (${role})`);
927
- break;
928
- }
929
-
930
- case 'tool_execution_start': {
931
- const toolName = event.toolName || 'unknown';
932
- const toolId = event.toolCallId || '';
933
- const idPart = toolId ? ` [${toolId.substring(0, 8)}]` : '';
934
-
935
- let inputPreview = '';
936
- const args = event.args;
937
- if (args) {
938
- if (typeof args === 'string') {
939
- inputPreview = args.length > 60 ? args.substring(0, 60) + '...' : args;
940
- } else if (typeof args === 'object') {
941
- if (args.command) {
942
- inputPreview = `cmd="${args.command.substring(0, 50)}${args.command.length > 50 ? '...' : ''}"`;
943
- } else if (args.file_path || args.path) {
944
- inputPreview = `path="${args.file_path || args.path}"`;
945
- } else {
946
- const keys = Object.keys(args);
947
- inputPreview = `{${keys.slice(0, 3).join(', ')}${keys.length > 3 ? '...' : ''}}`;
948
- }
949
- }
950
- }
951
-
952
- const inputPart = inputPreview ? ` ${inputPreview}` : '';
953
- logger.streamDebug(`${levelPrefix} [#${lineNum}] tool_start: ${toolName}${idPart}${inputPart}`);
954
- break;
955
- }
956
-
957
- case 'tool_execution_update': {
958
- const partial = event.partialResult || '';
959
- if (partial) {
960
- const preview = typeof partial === 'string'
961
- ? (partial.length > 60 ? partial.substring(0, 60) + '...' : partial)
962
- : JSON.stringify(partial).substring(0, 60);
963
- logger.streamDebug(`${levelPrefix} [#${lineNum}] tool_update: ${preview.replace(/\n/g, '\\n')}`);
964
- } else {
965
- logger.streamDebug(`${levelPrefix} [#${lineNum}] tool_update`);
966
- }
967
- break;
968
- }
969
-
970
- case 'tool_execution_end': {
971
- const isError = event.isError || false;
972
- const statusPart = isError ? ' ERROR' : ' OK';
973
- const result = event.result || '';
974
- let resultPreview = '';
975
- if (typeof result === 'string' && result.length > 0) {
976
- resultPreview = result.length > 60 ? result.substring(0, 60) + '...' : result;
977
- resultPreview = resultPreview.replace(/\n/g, '\\n');
978
- }
979
- const previewPart = resultPreview ? ` ${resultPreview}` : '';
980
- logger.streamDebug(`${levelPrefix} [#${lineNum}] tool_end${statusPart}${previewPart}`);
981
- break;
982
- }
983
-
984
- case 'agent_start':
985
- logger.streamDebug(`${levelPrefix} [#${lineNum}] Agent started`);
986
- break;
987
-
988
- case 'agent_end':
989
- logger.streamDebug(`${levelPrefix} [#${lineNum}] Agent ended`);
990
- break;
991
-
992
- default:
993
- logger.streamDebug(`${levelPrefix} [#${lineNum}] ${type}`);
994
- }
995
- } catch {
996
- // If we can't parse the line, log the full content for debugging
997
- logger.streamDebug(`${levelPrefix} [#${lineNum}] (unparseable): ${line}`);
998
- }
999
- }
1000
-
1001
- /**
1002
- * Parse Pi CLI JSONL response
1003
- * Pi with --mode json outputs JSONL with structured events.
1004
- * Text content is in message_end events with content blocks,
1005
- * and in message_update events with text_delta.
209
+ * Used both by the constructor (analysis model) and by the shared
210
+ * getExtractionConfig() (extraction model), so the extraction fallback picks
211
+ * up env configured on its own (possibly fast-tier) model.
1006
212
  *
1007
- * @param {string} stdout - Raw stdout from Pi CLI (JSONL format)
1008
- * @param {string|number} level - Analysis level for logging
1009
- * @returns {{success: boolean, data?: Object, error?: string}}
213
+ * @param {string} modelId - Model identifier
214
+ * @returns {Object} Env vars to merge into the child environment
1010
215
  */
1011
- parsePiResponse(stdout, level, logPrefix) {
1012
- const levelPrefix = logPrefix || `[Level ${level}]`;
1013
-
1014
- try {
1015
- // Split by newlines and parse each JSON line
1016
- const lines = stdout.trim().split('\n').filter(line => line.trim());
1017
- const responseState = {
1018
- textContent: '',
1019
- seenTexts: new Set(),
1020
- rawOutput: '',
1021
- rawOutputTruncated: false
1022
- };
1023
-
1024
- for (const line of lines) {
1025
- accumulatePiResponseLine(line, responseState, levelPrefix);
1026
- }
1027
-
1028
- return finalizePiResponseParsing({
1029
- textContent: responseState.textContent,
1030
- rawOutput: responseState.rawOutput,
1031
- rawOutputTruncated: responseState.rawOutputTruncated
1032
- }, level, levelPrefix);
1033
-
1034
- } catch (parseError) {
1035
- // stdout might not be valid JSONL at all, try extracting JSON from it
1036
- const extracted = extractJSON(stdout, level, levelPrefix);
1037
- if (extracted.success) {
1038
- return extracted;
1039
- }
1040
-
1041
- return { success: false, error: `JSONL parse error: ${parseError.message}` };
1042
- }
216
+ _resolveEnvForModel(modelId) {
217
+ const builtIn = PI_MODELS.find(m => m.id === modelId);
218
+ const configModel = this.configOverrides?.models?.find(m => m.id === modelId);
219
+ return {
220
+ PI_TASK_MAX_DEPTH: '1',
221
+ ...(builtIn?.env || {}),
222
+ ...(this.configOverrides?.env || {}),
223
+ ...(configModel?.env || {}),
224
+ PI_CMD: this.cliCmd
225
+ };
1043
226
  }
1044
227
 
1045
228
  /**
@@ -1081,118 +264,18 @@ class PiProvider extends AIProvider {
1081
264
  // excluded for extraction. Extraction is a simple JSON-parsing task that doesn't
1082
265
  // need skills or other analysis-specific configuration.
1083
266
 
1084
- // Base args for pi non-interactive JSON mode (extraction only -- no tools needed)
267
+ // Base args for pi non-interactive JSON mode (extraction only -- no tools needed).
268
+ // load_skills: mirror the analysis run — when the user disabled skill
269
+ // auto-discovery, the extraction fallback must not re-enable it.
1085
270
  const sessionArgs = process.env.PAIR_REVIEW_PI_SESSION ? [] : ['--no-session'];
1086
- const baseArgs = ['-p', '--mode', 'json', ...cliModelArgs, '--no-tools', ...sessionArgs];
271
+ const skillArgs = this.configOverrides?.load_skills === false ? ['--no-skills'] : [];
272
+ const baseArgs = ['-p', '--mode', 'json', ...cliModelArgs, '--no-tools', ...sessionArgs, ...skillArgs];
1087
273
  const configModel = this.configOverrides?.models?.find(m => m.id === model);
1088
274
  const providerArgs = this.configOverrides?.extra_args || [];
1089
275
  const modelArgs = configModel?.extra_args || [];
1090
276
  return [...baseArgs, ...providerArgs, ...modelArgs];
1091
277
  }
1092
278
 
1093
- /**
1094
- * Get CLI configuration for LLM extraction
1095
- * @param {string} model - The model to use for extraction
1096
- * @returns {Object} Configuration for spawning extraction process
1097
- */
1098
- getExtractionConfig(model) {
1099
- // Use the already-resolved command from the constructor (this.piCmd)
1100
- // which respects: ENV > config > default precedence
1101
- const piCmd = this.piCmd;
1102
- const useShell = this.useShell;
1103
-
1104
- // Build args consistently using the shared method, applying provider and model extra_args
1105
- const args = this.buildArgsForModel(model);
1106
-
1107
- // Use @file syntax for prompt delivery (bypasses devx stdin interference)
1108
- if (useShell) {
1109
- return {
1110
- command: `${piCmd} ${quoteShellArgs(args).join(' ')}`,
1111
- args: [],
1112
- useShell: true,
1113
- promptViaFile: true,
1114
- env: this.extraEnv
1115
- };
1116
- }
1117
- return {
1118
- command: piCmd,
1119
- args,
1120
- useShell: false,
1121
- promptViaFile: true,
1122
- env: this.extraEnv
1123
- };
1124
- }
1125
-
1126
- /**
1127
- * Test if Pi CLI is available
1128
- * Uses the command configured in the instance (respects ENV > config > default precedence)
1129
- * @param {number} [timeoutMs=10000] - Timeout in milliseconds for the probe
1130
- * @returns {Promise<boolean>}
1131
- */
1132
- async testAvailability(timeoutMs = 10000) {
1133
- return new Promise((resolve) => {
1134
- // For availability test, we just need to check --version
1135
- // Use the already-resolved command from the constructor (this.piCmd)
1136
- // which respects: ENV > config > default precedence
1137
- const useShell = this.useShell;
1138
- const command = useShell ? `${this.piCmd} --version` : this.piCmd;
1139
- const args = useShell ? [] : ['--version'];
1140
-
1141
- // Log the actual command for debugging config/override issues
1142
- const fullCmd = useShell ? command : `${command} ${args.join(' ')}`;
1143
- const name = this.constructor.getProviderName();
1144
- logger.debug(`${name} availability check: ${fullCmd}`);
1145
-
1146
- const pi = spawn(command, args, {
1147
- env: {
1148
- ...process.env,
1149
- ...this.extraEnv,
1150
- PATH: `${BIN_DIR}:${process.env.PATH}`
1151
- },
1152
- shell: useShell
1153
- });
1154
-
1155
- let stdout = '';
1156
- let settled = false;
1157
-
1158
- // Timeout guard: if the CLI hangs, resolve false
1159
- const availabilityTimeout = setTimeout(() => {
1160
- if (settled) return;
1161
- settled = true;
1162
- logger.warn(`${name} CLI availability check timed out after ${Math.round(timeoutMs / 1000)}s`);
1163
- // Not `shell: useShell`: the probe spawn is not `detached`, so
1164
- // group-kill would ESRCH and leave the child running.
1165
- killChildSafely(pi, { logPrefix: '[availability]' });
1166
- resolve(false);
1167
- }, timeoutMs);
1168
-
1169
- pi.stdout.on('data', (data) => {
1170
- stdout += data.toString();
1171
- });
1172
-
1173
- pi.on('close', (code) => {
1174
- if (settled) return;
1175
- settled = true;
1176
- clearTimeout(availabilityTimeout);
1177
- if (code === 0) {
1178
- logger.info(`${name} CLI available: ${stdout.trim()}`);
1179
- resolve(true);
1180
- } else {
1181
- logger.warn(`${name} CLI not available or returned unexpected output`);
1182
- resolve(false);
1183
- }
1184
- });
1185
-
1186
- pi.on('error', (error) => {
1187
- if (settled) return;
1188
- settled = true;
1189
- clearTimeout(availabilityTimeout);
1190
- logger.warn(`${name} CLI not available: ${error.message}`);
1191
- resolve(false);
1192
- });
1193
- });
1194
- }
1195
-
1196
279
  static getProviderName() {
1197
280
  return 'Pi';
1198
281
  }
@@ -1223,11 +306,3 @@ class PiProvider extends AIProvider {
1223
306
  registerProvider('pi', PiProvider);
1224
307
 
1225
308
  module.exports = PiProvider;
1226
- // Test-only exports. Underscore prefix signals internal helpers that should
1227
- // not be consumed from production code paths.
1228
- module.exports._extractAssistantText = extractAssistantText;
1229
- module.exports._isPiEventEnvelope = isPiEventEnvelope;
1230
- module.exports._appendWithLimit = appendWithLimit;
1231
- module.exports._appendHeadTailBuffer = appendHeadTailBuffer;
1232
- module.exports._formatHeadTailBuffer = formatHeadTailBuffer;
1233
- module.exports._finalizePiResponseParsing = finalizePiResponseParsing;