File size: 14,643 Bytes
bfdb3c0 e40073c bfdb3c0 e40073c bfdb3c0 e40073c bfdb3c0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 | /**
* TUI-style conversation module for desktop.
*
* Reuses TUI's approach of directly calling provider APIs via HTTP,
* without going through the cc-haha sidecar or CLI subprocess.
*
* Supports all provider types:
* - Anthropic protocol: firstParty, openrouter, openai, local
* - OpenAI protocol: nvidia (NIM), opencode
*
* Config is read from ~/.claude.json via getTuiConfig().
*/
import { getTuiConfig } from '../api/config'
// βββ Types ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export type ConversationMessage = {
role: 'user' | 'assistant'
content: string
}
export type ConversationStreamEvent =
| { type: 'text_delta'; text: string }
| { type: 'thinking_delta'; thinking: string }
| { type: 'content_block_start'; index: number; blockType: string }
| { type: 'content_block_stop'; index: number }
| { type: 'message_stop'; usage?: { input_tokens?: number; output_tokens?: number } }
| { type: 'error'; message: string }
| { type: 'done' }
export type ConversationResult = {
content: string
usage?: { input_tokens: number; output_tokens: number }
}
// βββ Provider client factory ββββββββββββββββββββββββββββββββββββββββββββββββ
type ProviderClientConfig = {
baseUrl: string
apiKey: string
model: string
/** Anthropic Messages API vs OpenAI Chat Completions */
protocol: 'anthropic' | 'openai'
}
async function resolveProviderConfig(model?: string): Promise<ProviderClientConfig> {
const config = await getTuiConfig()
const authProvider = (config.authProvider as string) || 'anthropic'
// Resolve API key and base URL based on provider
switch (authProvider) {
case 'openrouter': {
const apiKey = config.openRouterApiKey as string
if (!apiKey) throw new Error('OpenRouter API key not configured. Run /login first.')
return {
baseUrl: (process.env as Record<string, string>).OPENROUTER_BASE_URL || 'https://openrouter.ai/api/v1',
apiKey,
model: model || 'anthropic/claude-sonnet-4-6',
protocol: 'anthropic',
}
}
case 'nvidia': {
const apiKey = config.nvidiaApiKey as string
if (!apiKey) throw new Error('NVIDIA NIM API key not configured. Run /login first.')
const nvidiaBaseUrl = (config.nvidiaBaseUrl as string) || 'https://integrate.api.nvidia.com/v1'
return {
baseUrl: nvidiaBaseUrl,
apiKey,
model: model || (config.nvidiaModel as string) || 'nvidia/llama-3.1-nemotron-70b-instruct',
protocol: 'openai',
}
}
case 'opencode': {
const apiKey = config.openCodeApiKey as string
return {
baseUrl: 'https://opencode.ai/zen/v1',
apiKey: apiKey || 'public',
model: model || (config.openCodeModelName as string) || 'big-pickle',
protocol: 'openai',
}
}
case 'openai': {
const apiKey = (config.openAiApiKey as string) || (config.openAiAccessToken as string)
if (!apiKey) throw new Error('OpenAI API key not configured.')
return {
baseUrl: (process.env as Record<string, string>).OPENAI_BASE_URL || 'https://api.openai.com/v1',
apiKey,
model: model || 'gpt-5.4-codex',
protocol: 'openai',
}
}
case 'local': {
const localBaseUrl = config.localBaseUrl as string
if (!localBaseUrl) throw new Error('Local provider base URL not configured.')
return {
baseUrl: localBaseUrl,
apiKey: 'local-model',
model: model || (config.localModelName as string) || 'local-model',
protocol: 'openai', // Most local providers use OpenAI-compatible API
}
}
default: {
// First-party Anthropic
const apiKey = config.anthropicApiKey as string
if (!apiKey) throw new Error('Anthropic API key not configured.')
return {
baseUrl: (process.env as Record<string, string>).ANTHROPIC_BASE_URL || 'https://api.anthropic.com/v1',
apiKey,
model: model || 'claude-sonnet-4-6',
protocol: 'anthropic',
}
}
}
}
// βββ HTTP helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function anthropicHeaders(apiKey: string): Record<string, string> {
return {
'Content-Type': 'application/json',
'x-api-key': apiKey,
'anthropic-version': '2023-06-01',
'User-Agent': 'versperclaw-desktop/1.0',
}
}
function openaiHeaders(apiKey: string): Record<string, string> {
return {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
'User-Agent': 'versperclaw-desktop/1.0',
}
}
// βββ OpenAI protocol streaming βββββββββββββββββββββββββββββββββββββββββββββββ
async function* streamOpenAI(
config: ProviderClientConfig,
messages: ConversationMessage[],
signal?: AbortSignal,
): AsyncGenerator<ConversationStreamEvent> {
const body = {
model: config.model,
messages: messages.map(m => ({ role: m.role, content: m.content })),
stream: true,
}
let res: Response
try {
res = await fetch(`${config.baseUrl.replace(/\/$/, '')}/chat/completions`, {
method: 'POST',
headers: openaiHeaders(config.apiKey),
body: JSON.stringify(body),
signal,
})
} catch (err) {
const name = err instanceof TypeError ? err.name : ''
const msg = err instanceof Error ? err.message : String(err)
console.error('[tuiConversation] OpenAI fetch failed:', { name, message: msg, url: config.baseUrl, model: config.model })
yield { type: 'error', message: `Network error: ${msg}${name ? ` (${name})` : ''}` }
yield { type: 'done' }
return
}
if (!res.ok) {
const errBody = await res.text().catch(() => '')
yield { type: 'error', message: `API error ${res.status}: ${errBody}` }
yield { type: 'done' }
return
}
if (!res.body) {
yield { type: 'error', message: 'No response body' }
yield { type: 'done' }
return
}
const decoder = new TextDecoder()
const reader = res.body.getReader()
let buffer = ''
let hasReceivedContent = false
const IDLE_TIMEOUT_MS = 3000
yield { type: 'content_block_start', index: 0, blockType: 'text' }
while (true) {
if (signal?.aborted) break
// Race between read and idle timeout. Some local providers (Ollama, LM Studio,
// etc.) never send [DONE] or close the SSE connection after the response is
// complete. The timeout lets us detect this and finish cleanly.
const readPromise = reader.read()
const timeoutPromise = new Promise<{ done: true; value: undefined }>((resolve) =>
setTimeout(() => resolve({ done: true, value: undefined }), IDLE_TIMEOUT_MS),
)
const { done, value } = await Promise.race([readPromise, timeoutPromise])
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() || ''
for (const line of lines) {
if (!line.startsWith('data: ')) continue
const raw = line.slice(6).trim()
if (raw === '[DONE]') {
yield { type: 'content_block_stop', index: 0 }
yield { type: 'message_stop' }
yield { type: 'done' }
return
}
try {
const chunk = JSON.parse(raw)
const delta = chunk.choices?.[0]?.delta
if (!delta) continue
if (delta.content) {
yield { type: 'text_delta', text: delta.content }
}
if (delta.reasoning_content) {
yield { type: 'thinking_delta', thinking: delta.reasoning_content }
}
} catch {
// Skip malformed JSON
}
}
}
yield { type: 'content_block_stop', index: 0 }
yield { type: 'message_stop' }
yield { type: 'done' }
}
// βββ Public API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Send a conversation message and stream the response.
* Works for all provider types, bypassing the cc-haha sidecar.
*
* Usage:
* ```ts
* for await (const event of sendMessage([...messages])) {
* if (event.type === 'text_delta') { updateUI(event.text) }
* if (event.type === 'done') { break }
* }
* ```
*/
export async function* sendMessage(
messages: ConversationMessage[],
options?: {
model?: string
system?: string
signal?: AbortSignal
},
): AsyncGenerator<ConversationStreamEvent> {
const config = await resolveProviderConfig(options?.model)
if (config.protocol === 'anthropic') {
// Re-implement Anthropic streaming inline with proper yield support
const body: Record<string, unknown> = {
model: config.model,
messages,
max_tokens: 4096,
stream: true,
}
if (options?.system) body.system = options.system
let res: Response
try {
res = await fetch(`${config.baseUrl.replace(/\/$/, '')}/messages`, {
method: 'POST',
headers: anthropicHeaders(config.apiKey),
body: JSON.stringify(body),
signal: options?.signal,
})
} catch (err) {
const name = err instanceof TypeError ? err.name : ''
const msg = err instanceof Error ? err.message : String(err)
console.error('[tuiConversation] Anthropic fetch failed:', { name, message: msg, url: config.baseUrl, model: config.model })
yield { type: 'error', message: `Network error: ${msg}${name ? ` (${name})` : ''}` }
yield { type: 'done' }
return
}
if (!res.ok) {
const errBody = await res.text().catch(() => '')
yield { type: 'error', message: `API error ${res.status}: ${errBody}` }
yield { type: 'done' }
return
}
if (!res.body) {
yield { type: 'error', message: 'No response body' }
yield { type: 'done' }
return
}
const decoder = new TextDecoder()
const reader = res.body.getReader()
let buffer = ''
let usage: { input_tokens?: number; output_tokens?: number } | undefined
try {
while (true) {
if (options?.signal?.aborted) break
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() || ''
for (const line of lines) {
if (line.startsWith('data: ')) {
const raw = line.slice(6).trim()
if (!raw) continue
try {
const data = JSON.parse(raw)
if (data.type === 'content_block_start') {
yield {
type: 'content_block_start',
index: data.index ?? 0,
blockType: data.content_block?.type ?? 'text',
}
} else if (data.type === 'content_block_delta') {
const delta = data.delta
if (delta?.type === 'text_delta' && delta.text) {
yield { type: 'text_delta', text: delta.text }
} else if (delta?.type === 'thinking_delta' && delta.thinking) {
yield { type: 'thinking_delta', thinking: delta.thinking }
}
} else if (data.type === 'content_block_stop') {
yield { type: 'content_block_stop', index: data.index ?? 0 }
} else if (data.type === 'message_start' && data.message?.usage) {
usage = data.message.usage
} else if (data.type === 'message_delta' && data.delta?.stop_reason) {
if (data.usage) usage = data.usage
} else if (data.type === 'message_stop') {
yield { type: 'message_stop', usage }
yield { type: 'done' }
return
}
} catch {
// Skip malformed JSON
}
}
}
}
} finally {
reader.releaseLock()
}
if (!options?.signal?.aborted) {
yield { type: 'message_stop', usage }
yield { type: 'done' }
}
} else {
// OpenAI protocol
yield* streamOpenAI(config, messages, options?.signal)
}
}
/**
* Non-streaming send - returns the complete result.
*/
export async function sendMessageSync(
messages: ConversationMessage[],
options?: {
model?: string
system?: string
signal?: AbortSignal
},
): Promise<ConversationResult> {
const config = await resolveProviderConfig(options?.model)
if (config.protocol === 'anthropic') {
const body: Record<string, unknown> = {
model: config.model,
messages,
max_tokens: 4096,
}
if (options?.system) body.system = options.system
const res = await fetch(`${config.baseUrl.replace(/\/$/, '')}/messages`, {
method: 'POST',
headers: anthropicHeaders(config.apiKey),
body: JSON.stringify(body),
signal: options?.signal,
})
if (!res.ok) {
const errBody = await res.text().catch(() => '')
throw new Error(`API error ${res.status}: ${errBody}`)
}
const data = (await res.json()) as {
content: Array<{ type: string; text?: string }>
usage?: { input_tokens: number; output_tokens: number }
}
const text = data.content
?.filter((b) => b.type === 'text')
.map((b) => b.text)
.join('\n') ?? ''
return { content: text, usage: data.usage }
}
// OpenAI protocol
const body = {
model: config.model,
messages: messages.map(m => ({ role: m.role, content: m.content })),
}
const res = await fetch(`${config.baseUrl.replace(/\/$/, '')}/chat/completions`, {
method: 'POST',
headers: openaiHeaders(config.apiKey),
body: JSON.stringify(body),
signal: options?.signal,
})
if (!res.ok) {
const errBody = await res.text().catch(() => '')
throw new Error(`API error ${res.status}: ${errBody}`)
}
const data = (await res.json()) as {
choices: Array<{ message: { content: string | null } }>
usage?: { prompt_tokens: number; completion_tokens: number }
}
return {
content: data.choices?.[0]?.message?.content ?? '',
usage: data.usage ? { input_tokens: data.usage.prompt_tokens, output_tokens: data.usage.completion_tokens } : undefined,
}
}
|