// 설명 문서: /docs/specs/bada-bong-language-settings.md (v0.3.0) // 실행 시작 시 언어만 읽어 고정한다. UI 언어·서버 locale·모델 콘텐츠는 참조하지 않는다. const fs = require('node:fs'); const path = require('node:path'); const log = require('./logger').makeLogger('agent-reply-language'); const names = Object.freeze({ ko: 'Korean', en: 'English', 'zh-Hans': 'Simplified Chinese', ja: 'Japanese', hu: 'Hungarian', 'de-AT': 'Austrian German', es: 'Spanish', ms: 'Malay', vi: 'Vietnamese', de: 'German' }); const valid = value => typeof value === 'string' && (value === 'auto' || Object.hasOwn(names, value)); const plain = value => value !== null && typeof value === 'object' && !Array.isArray(value); const interactivePreferences = new WeakSet(); function desktopDefault() { let fd; try { fd = fs.openSync(path.join(require('../context').CLAUDE_DIR, 'settings.json'), 'r'); const stat = fs.fstatSync(fd); if (!stat.isFile() || stat.size > 1024 * 1024) { log.warn('SETTINGS_REPLY_LANGUAGE_BOUNDS'); return 'auto'; } // 커지는 파일도 상한을 넘겨 읽지 않는다. 파일 내용/오류 메시지는 출력하지 않는다. const buffer = Buffer.alloc(1024 * 1024 + 1); const bytes = fs.readSync(fd, buffer, 0, buffer.length, 0); if (bytes > 1024 * 1024) { log.warn('SETTINGS_REPLY_LANGUAGE_BOUNDS'); return 'auto'; } const value = JSON.parse(buffer.subarray(0, bytes).toString('utf8')); if (!plain(value) || Object.hasOwn(value, 'replyLocale') && !valid(value.replyLocale)) log.warn('SETTINGS_REPLY_LANGUAGE_INVALID'); return plain(value) && valid(value.replyLocale) ? value.replyLocale : 'auto'; } catch (error) { if (error?.code !== 'ENOENT') log.warn(error instanceof SyntaxError ? 'SETTINGS_REPLY_LANGUAGE_JSON' : 'SETTINGS_REPLY_LANGUAGE_READ'); return 'auto'; } finally { if (fd !== undefined) { try { fs.closeSync(fd); } catch { /* 읽기 실패와 무관하게 소유 FD를 반환한다. */ } } } } function snapshot(defaultLocale, nodeLocales = Object.create(null)) { return Object.freeze({ version: 1, defaultLocale, nodeLocales: Object.freeze(nodeLocales) }); } function capture(nodes, options = {}) { const inherited = options.usageParent?.replyLanguage?.defaultLocale; const defaultLocale = valid(options.replyLocale) ? options.replyLocale : valid(inherited) ? inherited : desktopDefault(); const nodeLocales = Object.create(null); for (const node of nodes || []) if (typeof node?.id === 'string' && valid(node.config?.replyLocale)) nodeLocales[node.id] = node.config.replyLocale; return snapshot(defaultLocale, nodeLocales); } function restore(value, nodes) { if (value === undefined || value === null) return snapshot('auto'); const invalid = () => { log.warn('REPLY_LANGUAGE_SNAPSHOT_INVALID'); throw Object.assign(new Error('Invalid reply language snapshot'), { code: 'REPLY_LANGUAGE_SNAPSHOT_INVALID' }); }; if (!plain(value) || Object.keys(value).sort().join(',') !== 'defaultLocale,nodeLocales,version' || value.version !== 1 || !valid(value.defaultLocale) || !plain(value.nodeLocales)) return invalid(); const ids = new Set((nodes || []).map(node => node.id)), nodeLocales = Object.create(null); for (const [id, locale] of Object.entries(value.nodeLocales)) { if (!ids.has(id) || !valid(locale)) return invalid(); nodeLocales[id] = locale; } return snapshot(value.defaultLocale, nodeLocales); } function attach(run, value) { Object.defineProperty(run, 'replyLanguage', { value, enumerable: true, writable: false, configurable: false }); } function localeFor(run, node) { const value = run?.replyLanguage; const locale = value?.nodeLocales && Object.hasOwn(value.nodeLocales, node?.id) ? value.nodeLocales[node.id] : value?.defaultLocale; return valid(locale) ? locale : 'auto'; } function instruction(run, node) { const locale = localeFor(run, node); return locale === 'auto' ? '' : '\n\n[Response language preference]\nWrite natural-language explanations and human-readable JSON string values in ' + names[locale] + ', unless the user explicitly requests another language. Preserve required output schemas, JSON keys, enum values, code, commands, paths, identifiers, and quoted source text exactly. Do not translate machine-readable contracts or change the requested task.'; } function append(prompt, run, node) { return prompt + instruction(run, node); } function interactiveAppend(prompt, run, node) { if (localeFor(run, node) !== 'auto') { interactivePreferences.add(run); return append(prompt, run, node); } // 동일 대화에 남은 이전 턴의 언어 지시만 해제한다. 세션/PTY를 재시작하지 않는다. return interactivePreferences.has(run) ? prompt + '\n\n[Response language preference reset]\nThe previous response-language preference no longer applies. Follow the language requested by the current task, or its language when unspecified. Preserve required output schemas, JSON keys, enum values, code, commands, paths, identifiers, and quoted source text exactly.' : prompt; } module.exports = { valid, capture, restore, attach, localeFor, instruction, append, interactiveAppend };