feat(commands): multi-select ordered command pipeline with step reordering and single-pass composition (AI-05, AI-07)

This commit is contained in:
Yun Chan 2026-10-31 02:54:54 +09:00
parent f49acf0105
commit 10af20a0ad
157 changed files with 29455 additions and 913 deletions

View file

@ -30,6 +30,7 @@ import { getLlmGateway } from './llm/LlmGateway'
import { buildInstructionInvocation, resolveTargetLanguage } from './llm-prompts'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
import { cleanDictatedText } from '@d3ro/core/dictation-cleaner'
import { composeInstructionPipelinePrompt, parseActiveInstructionIds } from '@d3ro/core/instruction-template'
import { TIMING } from '@d3ro/core/constants'
import { RecognitionState, AudioState } from '@d3ro/core/types'
import type { KeyBindingActionId, VoiceMode, VoiceState, LLMAction } from '@d3ro/core/types'
@ -132,6 +133,8 @@ class SessionRun {
audioStarted = false
/** 사용자가 이미 정지를 요청했다 — 두 번째 release/토글은 무시한다 */
stopRequested = false
/** 이 세션을 시작한 키바인딩 액션 */
actionId: KeyBindingActionId = 'dictation'
sttReady = false
transcribing = false
audioBuffer: Buffer[] = []
@ -266,31 +269,7 @@ class VoiceModeService extends EventEmitter {
*/
connectKeyBindings(): void {
this._keyBindingHandler = (payload) => {
switch (payload.actionId) {
case 'caption':
// Phase 10.1: caption은 VoiceModeService가 아닌 CaptionService로 라우팅.
// 토글이므로 press만 처리하고 release는 버린다.
if (payload.type === 'pressed') this._toggleCaption()
return
case 'dictation':
case 'hands-free':
case 'command':
break
default:
// 음성 세션 액션만 여기서 처리한다. 팝업·제안 액션은 bootstrap이 직접 구독한다
// (허용 목록이 아니면 새 액션이 생길 때마다 받아쓰기로 오인돼 녹음이 켜진다).
return
}
const holdMode = resolveGestureHoldMode(payload.actionId, payload.holdMode)
const action: VoiceAction = {
type: payload.type === 'pressed' ? 'press' : 'release',
timestamp: payload.timestamp,
mode: resolveGestureMode(payload.actionId, payload.isDoublePress),
actionId: payload.actionId,
holdMode
}
this._enqueueAction(action)
this.handleShortcutTrigger(payload)
}
getKeyBindingService().on('triggered', this._keyBindingHandler)
@ -298,9 +277,47 @@ class VoiceModeService extends EventEmitter {
logger.info('Key binding events connected')
}
/**
* 키바인딩 트리거 이벤트를 받아 세션 액션 큐에 넣는다.
*/
handleShortcutTrigger(payload: KeyBindingTriggerPayload): void {
switch (payload.actionId) {
case 'caption':
// Phase 10.1: caption은 VoiceModeService가 아닌 CaptionService로 라우팅.
// 토글이므로 press만 처리하고 release는 버린다.
if (payload.type === 'pressed') void this._toggleCaption()
return
case 'dictation':
case 'hands-free':
case 'command':
break
default:
// 음성 세션 액션만 여기서 처리한다. 팝업·제안 액션은 bootstrap이 직접 구독한다
// (허용 목록이 아니면 새 액션이 생길 때마다 받아쓰기로 오인돼 녹음이 켜진다).
return
}
const holdMode = this._resolveHoldMode(payload.actionId, payload.holdMode)
const action: VoiceAction = {
type: payload.type === 'pressed' ? 'press' : 'release',
timestamp: payload.timestamp,
mode: resolveGestureMode(payload.actionId, payload.isDoublePress),
actionId: payload.actionId,
holdMode
}
this._enqueueAction(action)
}
_resolveHoldMode(actionId: KeyBindingActionId, specHoldMode = false): boolean {
return resolveGestureHoldMode(actionId, specHoldMode)
}
// ── 세션 제어 ──────────────────────────────────────────
async startSession(mode: VoiceMode): Promise<void> {
async startSession(
mode: VoiceMode,
options?: { actionId?: KeyBindingActionId },
): Promise<void> {
if (this._disposed) return
if (this._session && !this._isInTerminalState()) {
logger.warn('Session already active, ignoring startSession')
@ -380,6 +397,7 @@ class VoiceModeService extends EventEmitter {
// 세션 생성
const run = new SessionRun(randomUUID())
run.actionId = options?.actionId ?? (mode === 'hands-free' ? 'hands-free' : 'dictation')
run.captureSelection = windowContext !== null
run.windowContext = windowContext
this._run = run
@ -469,7 +487,7 @@ class VoiceModeService extends EventEmitter {
// 핫키를 뗀 뒤라 복사 단축키가 안전하다 — LLM 이 쓸 것이 확실하면 전사와 병렬로 선택 텍스트를
// 캡처한다. 원문 삽입 경로(none·LLM 불가)에선 보내지 않는다: 쓰지도 않을 Ctrl+C 가 터미널에선
// 프로세스를 중단시킨다. 음성 단축키로 LLM 경로가 될 수도 있으면 LLM 단계에서 늦게 캡처한다.
if (routeUsesLlm(this._resolveLlmRoute(null))) this._startSelectionCapture(run)
if (routeUsesLlm(this._resolveLlmRoute(null, run.actionId))) this._startSelectionCapture(run)
// 버퍼가 있으면 STT에 전달
if (run.audioBuffer.length > 0 && run.sttReady) {
@ -924,20 +942,30 @@ class VoiceModeService extends EventEmitter {
return
}
if (this._session) {
this._session.transcription = result.text
let rawText = result.text
try {
const { getDictionaryService } = await import('./DictionaryService')
const corrected = getDictionaryService().applyDictionaryCorrections(rawText)
rawText = corrected.text
} catch {
// DictionaryService 미초기화 시 무시
}
this.emit('transcription-update', { text: result.text, isFinal: true })
if (this._session) {
this._session.transcription = rawText
}
this.emit('transcription-update', { text: rawText, isFinal: true })
// Phase 10.5: 음성 단축키 — 키워드 매칭으로 LLM 명령어 자동 선택
let effectiveText = result.text
// 'command' 핫키로 진입한 세션은 voiceCommandsEnabled 설정과 무관하게 음성 명령 매칭을 항상 수행한다.
let effectiveText = rawText
let overrideInstructionId: string | null = null
try {
const { getVoiceCommandService } = await import('./VoiceCommandService')
const vcSvc = getVoiceCommandService()
if (vcSvc.isEnabled()) {
const match = vcSvc.match(result.text)
if (run.actionId === 'command' || vcSvc.isEnabled()) {
const match = vcSvc.match(rawText)
if (match.matched && match.instructionId) {
effectiveText = match.cleanedText
overrideInstructionId = match.instructionId
@ -952,7 +980,7 @@ class VoiceModeService extends EventEmitter {
// 결정적 구어 군더더기·추임새·말바꾸기·중복·동음이의어 1차 정리 (LLM 유무와 무관하게 0ms 즉시 적용)
effectiveText = cleanDictatedText(effectiveText)
const route = this._resolveLlmRoute(overrideInstructionId)
const route = this._resolveLlmRoute(overrideInstructionId, run.actionId)
if (route.kind === 'insert-raw') {
if (route.reason === 'llm-unavailable') {
this.emit('error', {
@ -999,10 +1027,16 @@ class VoiceModeService extends EventEmitter {
}
/** 현재 설정으로 LLM 후처리 경로를 결정한다 (정책은 @d3ro/core/voice-llm-route 가 소유) */
private _resolveLlmRoute(overrideInstructionId: string | null): VoiceLlmRoute {
private _resolveLlmRoute(
overrideInstructionId: string | null,
actionId: KeyBindingActionId | undefined = this._run?.actionId,
): VoiceLlmRoute {
const backend = configGet('llmBackend')
const configuredAction = configGet('defaultLLMAction')
const defaultAction =
actionId === 'command' && configuredAction === 'none' ? 'refine' : configuredAction
return resolveVoiceLlmRoute({
defaultAction: configGet('defaultLLMAction'),
defaultAction,
overrideInstructionId,
activeChainId: configGet('activeChainId') ?? null,
activeInstructionId: configGet('activeInstructionId') ?? null,
@ -1073,19 +1107,33 @@ class VoiceModeService extends EventEmitter {
}
}
/** 지시문(음성 단축키 또는 활성 지시문)으로 처리한다. 지시문이 없으면 지시문 없이 custom 처리 */
/** 지시문(음성 단축키 또는 활성 지시문·파이프라인)으로 처리한다. 지시문이 없으면 지시문 없이 custom 처리 */
private async _processWithInstruction(userText: string, instructionId: string | null): Promise<string> {
let invocationText = userText
let instructionPrompt: string | undefined
if (instructionId) {
const { getCustomInstructionService } = await import('./CustomInstructionService')
const instruction = getCustomInstructionService().getById(instructionId)
if (instruction) {
const svc = getCustomInstructionService()
const ids = parseActiveInstructionIds(instructionId)
const matched = ids
.map((id) => svc.getById(id))
.filter((item): item is NonNullable<typeof item> => item !== null)
if (matched.length === 1) {
const instruction = matched[0]
const invocation = buildInstructionInvocation(instruction.prompt, userText, resolveTargetLanguage())
invocationText = invocation.text
instructionPrompt = invocation.systemPrompt
logger.info(`Using custom instruction: "${instruction.name}"`)
} else if (matched.length >= 2) {
const composedPrompt = composeInstructionPipelinePrompt(matched)
const invocation = buildInstructionInvocation(composedPrompt, userText, resolveTargetLanguage())
invocationText = invocation.text
instructionPrompt = invocation.systemPrompt
logger.info(
`Using custom instruction pipeline (${matched.length} steps): ${matched.map((i) => i.name).join(' → ')}`,
)
} else {
logger.warn(`Custom instruction not found: ${instructionId} — processing without an instruction`)
}
@ -1275,7 +1323,7 @@ class VoiceModeService extends EventEmitter {
)
switch (intent.kind) {
case 'start':
await this.startSession(intent.mode)
await this.startSession(intent.mode, { actionId: action.actionId })
break
case 'stop':
// Speakly 패턴: 딜레이 없이 즉시 stop (딜레이가 race condition 유발)