d3ro-voice/packages/core/src/instruction-policy.ts

49 lines
2.4 KiB
TypeScript

// packages/core/src/instruction-policy.ts
// 사용자 LLM 명령어의 서버 쓰기 제약 — 서비스·동기화 어댑터·편집 폼이 같은 정본을 쓴다.
// 값은 서버 custom_instructions CHECK 와 같다(마이그레이션 20260821000005):
// char_length(btrim(name)) BETWEEN 1 AND 80, description ≤ 240, char_length(btrim(prompt)) BETWEEN 1 AND 4000
export const INSTRUCTION_LIMITS = { name: 80, description: 240, prompt: 4000 } as const
export type InstructionLimitField = keyof typeof INSTRUCTION_LIMITS
/** Postgres char_length 와 같은 코드 포인트 수 */
export function charLength(value: string): number {
return [...value].length
}
/** 서버 제한을 넘는 첫 필드. 없으면 null. (이름·프롬프트는 앞뒤 공백을 빼고 센다 — 서버 btrim 과 같다) */
export function instructionLimitViolation(input: {
name?: string
description?: string
prompt?: string
}): InstructionLimitField | null {
if (input.name !== undefined && charLength(input.name.trim()) > INSTRUCTION_LIMITS.name) return 'name'
if (input.description !== undefined && charLength(input.description.trim()) > INSTRUCTION_LIMITS.description) {
return 'description'
}
if (input.prompt !== undefined && charLength(input.prompt.trim()) > INSTRUCTION_LIMITS.prompt) return 'prompt'
return null
}
/** 저장할 수 없는 이유 */
export type InstructionDraftProblem =
| { field: 'name' | 'prompt'; reason: 'empty' }
| { field: InstructionLimitField; reason: 'too-long'; max: number }
/**
* 명령어 초안(생성 또는 부분 수정)을 서버 제약으로 검사한다 (순수 함수).
* 수정(부분 패치)에서는 준 필드만 검사한다 — 빈 이름·빈 프롬프트로 바꾸는 것도 막는다
* (예전엔 생성만 빈 값을 막아, 편집으로 비운 프롬프트가 서버 CHECK 에 계속 거부돼 동기화가 멈췄다).
*/
export function validateInstructionDraft(input: {
name?: string
description?: string
prompt?: string
}): InstructionDraftProblem | null {
if (input.name !== undefined && input.name.trim().length === 0) return { field: 'name', reason: 'empty' }
if (input.prompt !== undefined && input.prompt.trim().length === 0) return { field: 'prompt', reason: 'empty' }
const field = instructionLimitViolation(input)
if (field !== null) return { field, reason: 'too-long', max: INSTRUCTION_LIMITS[field] }
return null
}