@ -1,8 +1,6 @@
// ProcessingHelper.ts
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { spawn } from "node:child_process"
import { ScreenshotHelper } from "./ScreenshotHelper"
import { IProcessingHelperDeps } from "./main"
import * as axios from "axios"
@ -27,7 +25,7 @@ interface GeminiResponse {
candidates : Array < {
content : {
parts : Array < {
text ? : string ;
text : string ;
} > ;
} ;
finishReason : string ;
@ -55,7 +53,6 @@ export class ProcessingHelper {
// AbortControllers for API requests
private currentProcessingAbortController : AbortController | null = null
private currentExtraProcessingAbortController : AbortController | null = null
private currentFollowUpAbortController : AbortController | null = null
constructor ( deps : IProcessingHelperDeps ) {
this . deps = deps
@ -480,7 +477,7 @@ export class ProcessingHelper {
const messages = [
{
role : "system" as const ,
content : "You are a coding challenge interpreter. Analyze the screenshot of the coding problem and extract all relevant information. Return the information in JSON format with these fields: problem_statement, constraints, example_input, example_output , problem_type. Set problem_type to 'system_design' if the screenshots ask you to design a system, product or architecture rather than write code, otherwise 'coding'. Use exactly these keys and no others. For a system design question, put the design question itself in problem_statement, word for word. Example or possible questions that a page says might be asked count as design questions; if several are listed, include all of them, numbered. Put surrounding guidance such as tips or evaluation criteria in constraints . Just return the structured JSON without any other text."
content : "You are a coding challenge interpreter. Analyze the screenshot of the coding problem and extract all relevant information. Return the information in JSON format with these fields: problem_statement, constraints, example_input, example_output . Just return the structured JSON without any other text."
} ,
{
role : "user" as const ,
@ -499,9 +496,10 @@ export class ProcessingHelper {
// Send to OpenAI Vision API
const extractionResponse = await this . openaiClient . chat . completions . create ( {
model : config.extractionModel || "gpt- 6.1-sol ",
model : config.extractionModel || "gpt- 4o ",
messages : messages ,
max_completion_tokens : 16000
max_tokens : 4000 ,
temperature : 0.2
} ) ;
// Parse the response
@ -533,7 +531,7 @@ export class ProcessingHelper {
role : "user" ,
parts : [
{
text : ` You are a coding challenge interpreter. Analyze the screenshots of the coding problem and extract all relevant information. Return the information in JSON format with these fields: problem_statement, constraints, example_input, example_output , problem_type. Set problem_type to 'system_design' if the screenshots ask you to design a system, product or architecture rather than write code, otherwise 'coding'. Use exactly these keys and no others. For a system design question, put the design question itself in problem_statement, word for word. Example or possible questions that a page says might be asked count as design questions; if several are listed, include all of them, numbered. Put surrounding guidance such as tips or evaluation criteria in constraints . Just return the structured JSON without any other text. Preferred coding language we gonna use for this problem is ${ language } . `
text : ` You are a coding challenge interpreter. Analyze the screenshots of the coding problem and extract all relevant information. Return the information in JSON format with these fields: problem_statement, constraints, example_input, example_output . Just return the structured JSON without any other text. Preferred coding language we gonna use for this problem is ${ language } . `
} ,
. . . imageDataList . map ( data = > ( {
inlineData : {
@ -547,11 +545,12 @@ export class ProcessingHelper {
// Make API request to Gemini
const response = await axios . default . post (
` https://generativelanguage.googleapis.com/v1beta/models/ ${ config . extractionModel || "gemini- 3.8 -flash"} :generateContent?key= ${ this . geminiApiKey } ` ,
` https://generativelanguage.googleapis.com/v1beta/models/ ${ config . extractionModel || "gemini- 2.0 -flash"} :generateContent?key= ${ this . geminiApiKey } ` ,
{
contents : geminiMessages ,
generationConfig : {
maxOutputTokens : 16000
temperature : 0.2 ,
maxOutputTokens : 4000
}
} ,
{ signal }
@ -563,7 +562,7 @@ export class ProcessingHelper {
throw new Error ( "Empty response from Gemini API" ) ;
}
const responseText = responseData . candidates [ 0 ] . content . parts .map ( part = > part . text ? ? "" ) . join ( "" ) ;
const responseText = responseData . candidates [ 0 ] . content . parts [0 ] . text ;
// Handle when Gemini might wrap the JSON in markdown code blocks
const jsonText = responseText . replace ( /```json|```/g , '' ) . trim ( ) ;
@ -575,8 +574,8 @@ export class ProcessingHelper {
error : "Failed to process with Gemini API. Please check your API key or try again later."
} ;
}
} else if ( config . apiProvider === "anthropic" || config . apiProvider === "claude-code" ) {
if ( config . apiProvider === "anthropic" && ! this . anthropicClient ) {
} else if ( config . apiProvider === "anthropic" ) {
if ( ! this . anthropicClient ) {
return {
success : false ,
error : "Anthropic API key not configured. Please check your settings."
@ -590,7 +589,7 @@ export class ProcessingHelper {
content : [
{
type : "text" as const ,
text : ` Extract the coding problem details from these screenshots. Return in JSON format with these fields: problem_statement, constraints, example_input, example_output , problem_type. Set problem_type to 'system_design' if the screenshots ask you to design a system, product or architecture rather than write code, otherwise 'coding'. Use exactly these keys and no others. For a system design question, put the design question itself in problem_statement, word for word. Example or possible questions that a page says might be asked count as design questions; if several are listed, include all of them, numbered. Put surrounding guidance such as tips or evaluation criteria in constraints . Preferred coding language is ${ language } . Return only the JSON object, with no other text .`
text : ` Extract the coding problem details from these screenshots. Return in JSON format with these fields: problem_statement, constraints, example_input, example_output . Preferred coding language is ${ language } .`
} ,
. . . imageDataList . map ( data = > ( {
type : "image" as const ,
@ -604,19 +603,19 @@ export class ProcessingHelper {
}
] ;
const responseText = config . apiProvider === "claude-code"
? await this . runClaudeCode ( config . extractionModel || "opus" , messages , signal )
: await this . createAnthropicText ( config . extractionModel || "claude-opus-5-5" , messages ) ;
// Claude sometimes wraps the JSON in a sentence or a code fence; keep only the object
const jsonText = responseText . slice ( responseText . indexOf ( "{" ) , responseText . lastIndexOf ( "}" ) + 1 ) ;
const response = await this . anthropicClient . messages . create ( {
model : config.extractionModel || "claude-3-7-sonnet-20250219" ,
max_tokens : 4000 ,
messages : messages ,
temperature : 0.2
} ) ;
const responseText = ( response . content [ 0 ] as { type : 'text' , text : string } ) . text ;
const jsonText = responseText . replace ( /```json|```/g , '' ) . trim ( ) ;
problemInfo = JSON . parse ( jsonText ) ;
} catch ( error : any ) {
console . error ( "Error using Anthropic API:" , error ) ;
if ( config . apiProvider === "claude-code" ) {
return { success : false , error : ` Claude Code: ${ error . message } ` } ;
}
// Add specific handling for Claude's limitations
if ( error . status === 429 ) {
return {
@ -734,41 +733,8 @@ export class ProcessingHelper {
} ) ;
}
// System design questions get a written design instead of code and complexity
const isSystemDesign = problemInfo . problem_type === "system_design" ;
// Create prompt for solution generation
const promptText = isSystemDesign ? `
Answer the following system design interview question the way a strong candidate would , following the Hello Interview delivery framework .
QUESTION :
$ { problemInfo . problem_statement }
ADDITIONAL CONTEXT :
$ { problemInfo . constraints || "None provided." }
If several design questions are listed , answer the first one and name the others in one line at the very end .
Use exactly these markdown sections , in this order :
# # Functional Requirements
( the top 3 core requirements as "Users should be able to..." statements , then a short "Below the line (out of scope)" list )
# # Non - Functional Requirements
( the 3 to 5 that matter most as "The system should..." statements , quantified where possible , such as "search latency under 500ms" or "availability over consistency" , then a short "Below the line" list ; include a scale estimate only where it changes the design )
# # Core Entities
( a bulleted list of entity names with a few words each , not a full schema )
# # API
( REST endpoints covering each functional requirement , such as "GET /businesses?query&lat&long&category -> Business[]" ; take the user from the auth token , never from the request body )
# # High - Level Design
( build it up one functional requirement at a time , with a # # # subsection per requirement saying which components serve it and how a request flows through them ; finish with one small ASCII diagram of the complete design , listing next to each database only the fields that matter )
# # Deep Dives
( the 3 or 4 problems an interviewer would probe to meet the non - functional requirements , each as a # # # heading phrased as a question ; under each , give a Bad , Good and Great solution in a line or two apiece saying what each gets wrong , then explain the Great one in more depth )
# # Key Decisions
( one bullet per decision , in the form "Decision: chosen option over the alternative, because of the trade-off" )
Only for a data - processing system such as a web crawler , add a # # Data Flow section after API listing the steps from input to output .
Keep the high - level design simple and save the complexity for the deep dives . Always write the full answer : cover every section above completely , with no length limit , and never shorten a section , skip one or replace it with a summary . Use short bullets wherever prose isn ' t needed .
` : `
const promptText = `
Generate a detailed solution for the following coding problem :
PROBLEM STATEMENT :
@ -809,12 +775,13 @@ Your solution should be efficient, well-commented, and handle edge cases.
// Send to OpenAI API
const solutionResponse = await this . openaiClient . chat . completions . create ( {
model : config.solutionModel || "gpt- 6.1-sol ",
model : config.solutionModel || "gpt- 4o ",
messages : [
{ role : "system" , content : "You are an expert coding interview assistant. Provide clear, optimal solutions with detailed explanations." } ,
{ role : "user" , content : promptText }
] ,
max_completion_tokens : 16000
max_tokens : 4000 ,
temperature : 0.2
} ) ;
responseContent = solutionResponse . choices [ 0 ] . message . content ;
@ -842,11 +809,12 @@ Your solution should be efficient, well-commented, and handle edge cases.
// Make API request to Gemini
const response = await axios . default . post (
` https://generativelanguage.googleapis.com/v1beta/models/ ${ config . solutionModel || "gemini- 3.8 -flash"} :generateContent?key= ${ this . geminiApiKey } ` ,
` https://generativelanguage.googleapis.com/v1beta/models/ ${ config . solutionModel || "gemini- 2.0 -flash"} :generateContent?key= ${ this . geminiApiKey } ` ,
{
contents : geminiMessages ,
generationConfig : {
maxOutputTokens : 16000
temperature : 0.2 ,
maxOutputTokens : 4000
}
} ,
{ signal }
@ -858,7 +826,7 @@ Your solution should be efficient, well-commented, and handle edge cases.
throw new Error ( "Empty response from Gemini API" ) ;
}
responseContent = responseData . candidates [ 0 ] . content . parts .map ( part = > part . text ? ? "" ) . join ( "" ) ;
responseContent = responseData . candidates [ 0 ] . content . parts [0 ] . text ;
} catch ( error ) {
console . error ( "Error using Gemini API for solution:" , error ) ;
return {
@ -866,9 +834,9 @@ Your solution should be efficient, well-commented, and handle edge cases.
error : "Failed to generate solution with Gemini API. Please check your API key or try again later."
} ;
}
} else if ( config . apiProvider === "anthropic" || config . apiProvider === "claude-code" ) {
} else if ( config . apiProvider === "anthropic" ) {
// Anthropic processing
if ( config . apiProvider === "anthropic" && ! this . anthropicClient ) {
if ( ! this . anthropicClient ) {
return {
success : false ,
error : "Anthropic API key not configured. Please check your settings."
@ -889,16 +857,17 @@ Your solution should be efficient, well-commented, and handle edge cases.
] ;
// Send to Anthropic API
responseContent = config . apiProvider === "claude-code"
? await this . runClaudeCode ( config . solutionModel || "opus" , messages , signal )
: await this . createAnthropicText ( config . solutionModel || "claude-opus-5-5" , messages ) ;
const response = await this . anthropicClient . messages . create ( {
model : config.solutionModel || "claude-3-7-sonnet-20250219" ,
max_tokens : 4000 ,
messages : messages ,
temperature : 0.2
} ) ;
responseContent = ( response . content [ 0 ] as { type : 'text' , text : string } ) . text ;
} catch ( error : any ) {
console . error ( "Error using Anthropic API for solution:" , error ) ;
if ( config . apiProvider === "claude-code" ) {
return { success : false , error : ` Claude Code: ${ error . message } ` } ;
}
// Add specific handling for Claude's limitations
if ( error . status === 429 ) {
return {
@ -919,26 +888,6 @@ Your solution should be efficient, well-commented, and handle edge cases.
}
}
if ( isSystemDesign ) {
// The whole write-up is the design; its Key Decisions bullets fill the thoughts list
const decisionsMatch = responseContent ? . match ( /##\s*Key Decisions\s*\n([\s\S]*?)(?=\n##\s|$)/i ) ;
const decisions = decisionsMatch
? decisionsMatch [ 1 ] . split ( "\n" )
. filter ( ( line ) = > /^\s*(?:[-*•]|\d+\.)\s+/ . test ( line ) )
. map ( ( line ) = > line . replace ( /^\s*(?:[-*•]|\d+\.)\s+/ , "" ) . trim ( ) )
: [ ] ;
return {
success : true ,
data : {
code : responseContent ,
thoughts : decisions.length > 0 ? decisions : [ "See the design below" ] ,
time_complexity : "" ,
space_complexity : ""
}
} ;
}
// Extract parts from the response
const codeMatch = responseContent . match ( /```(?:\w+)?\s*([\s\S]*?)```/ ) ;
const code = codeMatch ? codeMatch [ 1 ] . trim ( ) : responseContent ;
@ -1118,9 +1067,10 @@ If you include code examples, use proper markdown code blocks with language spec
}
const debugResponse = await this . openaiClient . chat . completions . create ( {
model : config.debuggingModel || "gpt- 6.1-sol ",
model : config.debuggingModel || "gpt- 4o ",
messages : messages ,
max_completion_tokens : 16000
max_tokens : 4000 ,
temperature : 0.2
} ) ;
debugContent = debugResponse . choices [ 0 ] . message . content ;
@ -1180,11 +1130,12 @@ If you include code examples, use proper markdown code blocks with language spec
}
const response = await axios . default . post (
` https://generativelanguage.googleapis.com/v1beta/models/ ${ config . debuggingModel || "gemini- 3.8 -flash"} :generateContent?key= ${ this . geminiApiKey } ` ,
` https://generativelanguage.googleapis.com/v1beta/models/ ${ config . debuggingModel || "gemini- 2.0 -flash"} :generateContent?key= ${ this . geminiApiKey } ` ,
{
contents : geminiMessages ,
generationConfig : {
maxOutputTokens : 16000
temperature : 0.2 ,
maxOutputTokens : 4000
}
} ,
{ signal }
@ -1196,7 +1147,7 @@ If you include code examples, use proper markdown code blocks with language spec
throw new Error ( "Empty response from Gemini API" ) ;
}
debugContent = responseData . candidates [ 0 ] . content . parts .map ( part = > part . text ? ? "" ) . join ( "" ) ;
debugContent = responseData . candidates [ 0 ] . content . parts [0 ] . text ;
} catch ( error ) {
console . error ( "Error using Gemini API for debugging:" , error ) ;
return {
@ -1204,14 +1155,14 @@ If you include code examples, use proper markdown code blocks with language spec
error : "Failed to process debug request with Gemini API. Please check your API key or try again later."
} ;
}
} else if ( config . apiProvider === "anthropic" || config . apiProvider === "claude-code" ) {
if ( config . apiProvider === "anthropic" && ! this . anthropicClient ) {
} else if ( config . apiProvider === "anthropic" ) {
if ( ! this . anthropicClient ) {
return {
success : false ,
error : "Anthropic API key not configured. Please check your settings."
} ;
}
try {
const debugPrompt = `
You are a coding interview assistant helping debug and improve solutions . Analyze these screenshots which include either error messages , incorrect outputs , or test cases , and provide detailed debugging help .
@ -1264,16 +1215,17 @@ If you include code examples, use proper markdown code blocks with language spec
} ) ;
}
debugContent = config . apiProvider === "claude-code"
? await this . runClaudeCode ( config . debuggingModel || "opus" , messages , signal )
: await this . createAnthropicText ( config . debuggingModel || "claude-opus-5-5" , messages ) ;
const response = await this . anthropicClient . messages . create ( {
model : config.debuggingModel || "claude-3-7-sonnet-20250219" ,
max_tokens : 4000 ,
messages : messages ,
temperature : 0.2
} ) ;
debugContent = ( response . content [ 0 ] as { type : 'text' , text : string } ) . text ;
} catch ( error : any ) {
console . error ( "Error using Anthropic API for debugging:" , error ) ;
if ( config . apiProvider === "claude-code" ) {
return { success : false , error : ` Claude Code: ${ error . message } ` } ;
}
// Add specific handling for Claude's limitations
if ( error . status === 429 ) {
return {
@ -1338,128 +1290,9 @@ If you include code examples, use proper markdown code blocks with language spec
}
}
/ * *
* Answer a follow - up question about a system design answer . The question , the design
* and the earlier follow - ups go in as a single prompt , so every provider ( including the
* Claude Code CLI , which takes one turn per call ) sees the whole conversation .
* /
public async answerFollowUp ( request : {
design : string
history : Array < { question : string ; answer : string } >
question : string
} ) : Promise < { success : boolean ; data? : string ; error? : string } > {
const problemInfo = this . deps . getProblemInfo ( ) ;
const config = configHelper . loadConfig ( ) ;
const earlierFollowUps = request . history
. map ( ( turn ) = > ` Q: ${ turn . question } \ nA: ${ turn . answer } ` )
. join ( "\n\n" ) ;
const promptText = `
You are an expert system design interview assistant . You answered the system design question below ; now answer a follow - up question about your design .
QUESTION :
$ { problemInfo ? . problem_statement || "Not available." }
ADDITIONAL CONTEXT :
$ { problemInfo ? . constraints || "None provided." }
YOUR DESIGN :
$ { request . design }
$ { earlierFollowUps ? ` \ nEARLIER FOLLOW-UPS: \ n ${ earlierFollowUps } \ n ` : "" }
FOLLOW - UP QUESTION :
$ { request . question }
Always give the full write - up : answer the follow - up completely and in depth , with no length limit , building on the design above rather than repeating it . If it changes a requirement or adds a constraint , walk through everything in the design that changes and why . Use markdown with short bullets wherever prose isn ' t needed , and add an ASCII diagram if it helps .
` ;
this . currentFollowUpAbortController = new AbortController ( ) ;
const { signal } = this . currentFollowUpAbortController ;
try {
let answer : string | null | undefined ;
if ( config . apiProvider === "openai" ) {
if ( ! this . openaiClient ) {
return { success : false , error : "OpenAI API key not configured. Please check your settings." } ;
}
const response = await this . openaiClient . chat . completions . create ( {
model : config.solutionModel || "gpt-6.1-sol" ,
messages : [ { role : "user" , content : promptText } ] ,
max_completion_tokens : 16000
} , { signal } ) ;
answer = response . choices [ 0 ] . message . content ;
} else if ( config . apiProvider === "gemini" ) {
if ( ! this . geminiApiKey ) {
return { success : false , error : "Gemini API key not configured. Please check your settings." } ;
}
const response = await axios . default . post (
` https://generativelanguage.googleapis.com/v1beta/models/ ${ config . solutionModel || "gemini-3.8-flash" } :generateContent?key= ${ this . geminiApiKey } ` ,
{
contents : [ { role : "user" , parts : [ { text : promptText } ] } ] ,
generationConfig : {
maxOutputTokens : 16000
}
} ,
{ signal }
) ;
const responseData = response . data as GeminiResponse ;
answer = responseData . candidates ? . [ 0 ] ? . content ? . parts ? . map ( part = > part . text ? ? "" ) . join ( "" ) ;
} else if ( config . apiProvider === "anthropic" || config . apiProvider === "claude-code" ) {
if ( config . apiProvider === "anthropic" && ! this . anthropicClient ) {
return { success : false , error : "Anthropic API key not configured. Please check your settings." } ;
}
const messages = [
{
role : "user" as const ,
content : [ { type : "text" as const , text : promptText } ]
}
] ;
answer = config . apiProvider === "claude-code"
? await this . runClaudeCode ( config . solutionModel || "opus" , messages , signal )
: await this . createAnthropicText ( config . solutionModel || "claude-opus-5-5" , messages , signal ) ;
}
if ( ! answer ? . trim ( ) ) {
return { success : false , error : "The model returned an empty answer. Please try again." } ;
}
return { success : true , data : answer.trim ( ) } ;
} catch ( error : any ) {
console . error ( "Error answering follow-up:" , error ) ;
if ( signal . aborted ) {
return { success : false , error : "The follow-up was canceled." } ;
}
return {
success : false ,
error : config.apiProvider === "claude-code"
? ` Claude Code: ${ error . message } `
: error . message || "Failed to answer the follow-up. Please try again."
} ;
} finally {
// A reset may already have replaced this controller with a newer request's
if ( this . currentFollowUpAbortController ? . signal === signal ) {
this . currentFollowUpAbortController = null ;
}
}
}
public cancelOngoingRequests ( ) : void {
let wasCancelled = false
if ( this . currentFollowUpAbortController ) {
this . currentFollowUpAbortController . abort ( )
this . currentFollowUpAbortController = null
}
if ( this . currentProcessingAbortController ) {
this . currentProcessingAbortController . abort ( )
this . currentProcessingAbortController = null
@ -1481,125 +1314,4 @@ Always give the full write-up: answer the follow-up completely and in depth, wit
mainWindow . webContents . send ( this . deps . PROCESSING_EVENTS . NO_SCREENSHOTS )
}
}
/ * *
* Send a request to Claude and return the text of its reply .
* Current Claude models think before answering ( thinking tokens count toward
* max_tokens ) and reject a custom temperature . Opus and Sonnet requests opt into
* server - side refusal fallbacks ; Haiku has none .
* /
private async createAnthropicText (
model : string ,
messages : Anthropic.Beta.Messages.BetaMessageParam [ ] ,
signal? : AbortSignal
) : Promise < string > {
if ( ! this . anthropicClient ) {
throw new Error ( "Anthropic client not initialized" ) ;
}
// SDK 0.39 predates the fallbacks parameter, hence the cast below
const fallbackParams = model . startsWith ( "claude-haiku" )
? { }
: { betas : [ "server-side-fallback-2026-07-01" ] , fallbacks : "default" } ;
const response = await this . anthropicClient . beta . messages . create ( {
model ,
max_tokens : 16000 ,
messages ,
. . . fallbackParams
} as Anthropic . Beta . Messages . MessageCreateParamsNonStreaming , { signal } ) ;
if ( ( response . stop_reason as string ) === "refusal" ) {
throw new Error ( "Claude declined to answer this request." ) ;
}
return response . content
. filter ( ( block ) : block is Anthropic . Beta . Messages . BetaTextBlock = > block . type === "text" )
. map ( ( block ) = > block . text )
. join ( "" ) ;
}
/ * *
* Send a request through the local Claude Code CLI , so it counts against the user ' s
* Claude subscription instead of API billing . Messages go in as stream - json , which lets
* screenshots travel inline , with every tool disabled and the user ' s own Claude Code
* customizations ( CLAUDE . md , hooks , MCP servers ) switched off by -- safe - mode .
* /
private runClaudeCode (
model : string ,
messages : Anthropic.Beta.Messages.BetaMessageParam [ ] ,
signal? : AbortSignal
) : Promise < string > {
// Drop the variables a parent Claude Code session sets (a nested session refuses to
// start) and any API key, so the CLI signs in with the subscription
const env : NodeJS.ProcessEnv = { } ;
for ( const [ name , value ] of Object . entries ( process . env ) ) {
if ( ! /^(CLAUDECODE$|CLAUDE_CODE_|CLAUDE_PID$|CLAUDE_EFFORT$|ANTHROPIC_API_KEY$)/ . test ( name ) ) {
env [ name ] = value ;
}
}
// Apps opened from Finder get a minimal PATH, so add the usual install locations
env . PATH = [ env . PATH , path . join ( os . homedir ( ) , ".local" , "bin" ) , "/opt/homebrew/bin" , "/usr/local/bin" ]
. filter ( Boolean )
. join ( path . delimiter ) ;
const args = [
"-p" ,
"--input-format" , "stream-json" ,
"--output-format" , "stream-json" ,
"--verbose" ,
"--model" , model ,
// Matches the API's default for Opus; Claude Code's own default runs far longer per answer
"--effort" , "medium" ,
"--tools" , "" ,
"--safe-mode" ,
"--no-session-persistence" ,
"--system-prompt" , "You are an expert coding interview assistant. Follow the user's instructions exactly and answer directly."
] ;
return new Promise ( ( resolve , reject ) = > {
const child = spawn ( "claude" , args , {
cwd : app.getPath ( "temp" ) ,
env ,
signal ,
timeout : 5 * 60 * 1000
} ) ;
let stdout = "" ;
let stderr = "" ;
child . stdout . on ( "data" , ( chunk ) = > { stdout += chunk ; } ) ;
child . stderr . on ( "data" , ( chunk ) = > { stderr += chunk ; } ) ;
// A failed spawn also fails the stdin write; the process "error" event reports it
child . stdin . on ( "error" , ( ) = > { } ) ;
child . on ( "error" , ( error : NodeJS.ErrnoException ) = > {
reject ( error . code === "ENOENT"
? new Error ( "Claude Code isn't installed or isn't on your PATH. Install it from claude.com/claude-code and sign in with your Claude account." )
: error ) ;
} ) ;
child . on ( "close" , ( code ) = > {
// The final stream-json event is the result: { type: "result", is_error, result }
let result : { is_error? : boolean ; result? : string } | undefined ;
for ( const line of stdout . split ( "\n" ) ) {
try {
const event = JSON . parse ( line ) ;
if ( event . type === "result" ) result = event ;
} catch {
// Not a JSON event line
}
}
if ( result && ! result . is_error && typeof result . result === "string" ) {
resolve ( result . result ) ;
} else {
reject ( new Error ( result ? . result || stderr . trim ( ) || ` exited with code ${ code } without a result ` ) ) ;
}
} ) ;
child . stdin . end (
messages . map ( ( message ) = > JSON . stringify ( { type : "user" , message } ) ) . join ( "\n" ) + "\n"
) ;
} ) ;
}
}