feat: ship Wave 5-6 multi-surface hygiene, optimization, and bug fixes

This commit is contained in:
Yun Chan 2026-11-14 11:51:41 +09:00
parent 01ef3293cf
commit 66b6b45ba9
399 changed files with 17828 additions and 11330 deletions

View file

@ -7,6 +7,7 @@ import { configGet, configSet } from './ConfigService'
import { normalizeLoopbackUrl } from '../utils/loopback'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
import type { LLMAction } from '@d3ro/core/types'
import { redactPII, redactPIIMessages, rehydrateText } from '@d3ro/core/utils/pii-redactor'
import { resolveSystemPrompt } from './llm-prompts'
interface OnlineGenerateResponse {
@ -41,35 +42,38 @@ class OnlineLLMService extends EventEmitter {
return token
}
async processText(
text: string,
action: LLMAction,
targetLanguage?: string,
customPrompt?: string
private async _postOnlineRequest(
endpoint: string,
payload: Record<string, unknown>,
externalSignal?: AbortSignal
): Promise<string> {
const token = this._ensureAuth()
const apiUrl = normalizeLoopbackUrl(configGet('onlineApiUrl') ?? 'http://127.0.0.1:5000')
const systemPrompt = resolveSystemPrompt(action, targetLanguage, customPrompt)
// cancelGeneration() 이 실제로 이 요청을 끊도록 컨트롤러를 등록한다(예전엔 한 번도 할당되지 않아 no-op).
this._abortController?.abort()
const controller = new AbortController()
this._abortController = controller
const onExternalAbort = (): void => {
controller.abort()
}
if (externalSignal) {
if (externalSignal.aborted) {
controller.abort()
} else {
externalSignal.addEventListener('abort', onExternalAbort, { once: true })
}
}
try {
const response = await fetch(`${apiUrl}/api/llm/generate`, {
const response = await fetch(`${apiUrl}${endpoint}`, {
signal: controller.signal,
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
prompt: text,
systemPrompt,
model: configGet('llmModelId') ?? 'd3ro-gpt4o-mini',
temperature: 0.7,
maxTokens: 2048
})
body: JSON.stringify(payload)
})
if (response.status === 401) {
@ -87,11 +91,11 @@ class OnlineLLMService extends EventEmitter {
)
}
const data = (await response.json()) as OnlineGenerateResponse
if (!data.text || !data.text.trim()) {
const data = (await response.json()) as Partial<OnlineGenerateResponse> | null
if (typeof data?.text !== 'string' || data.text.trim().length === 0) {
throw new D3ROError(ErrorCode.LLMProcessingFailed, 'Online LLM returned empty text')
}
return data.text.trim()
return data.text
} catch (err) {
if (err instanceof D3ROError) throw err
if (controller.signal.aborted) {
@ -102,37 +106,48 @@ class OnlineLLMService extends EventEmitter {
`온라인 API 서버 연결 실패: ${err instanceof Error ? err.message : String(err)}`
)
} finally {
externalSignal?.removeEventListener('abort', onExternalAbort)
if (this._abortController === controller) this._abortController = null
}
}
async processText(
text: string,
action: LLMAction,
targetLanguage?: string,
customPrompt?: string
): Promise<string> {
this._ensureAuth()
const systemPrompt = resolveSystemPrompt(action, targetLanguage, customPrompt)
const redaction = redactPII(text, 'tokenize')
const rawText = await this._postOnlineRequest('/api/llm/generate', {
prompt: redaction.redactedText,
systemPrompt,
model: configGet('llmModelId') ?? 'd3ro-gpt4o-mini',
temperature: 0.7,
maxTokens: 2048
})
return rehydrateText(rawText.trim(), redaction.tokens)
}
async *chatStream(
messages: Array<{ role: string; content: string }>,
options?: { model?: string; temperature?: number }
options?: { model?: string; temperature?: number; signal?: AbortSignal }
): AsyncGenerator<string, string> {
const token = this._ensureAuth()
const apiUrl = normalizeLoopbackUrl(configGet('onlineApiUrl') ?? 'http://127.0.0.1:5000')
const response = await fetch(`${apiUrl}/api/llm/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
messages: messages.map((m) => ({ role: m.role, content: m.content })),
this._ensureAuth()
const redactedBatch = redactPIIMessages(messages)
const rawText = await this._postOnlineRequest(
'/api/llm/chat',
{
messages: redactedBatch.messages.map((m) => ({ role: m.role, content: m.content })),
model: options?.model ?? configGet('llmModelId') ?? 'd3ro-gpt4o-mini',
temperature: options?.temperature ?? 0.7
})
})
if (!response.ok) {
throw new D3ROError(ErrorCode.LLMProcessingFailed, `Online API Error: ${response.status}`)
}
const data = (await response.json()) as OnlineGenerateResponse
yield data.text
return data.text
},
options?.signal
)
const restored = rehydrateText(rawText, redactedBatch.tokens)
yield restored
return restored
}
cancelGeneration(): void {
@ -152,7 +167,7 @@ class OnlineLLMService extends EventEmitter {
let instance: OnlineLLMService | null = null
export function resetOnlineLLMServiceForTests(): void {
if (instance) instance.removeAllListeners()
if (instance) instance.dispose()
instance = null
}