// 고른 스냅(사진 + 입은 상품 목록)에서 카드에 쓸 옷 목록을 Claude CLI로 뽑는다: 자리별 한글 이름표와 그림용 영어 설명. import { execFile } from 'node:child_process' import { tmpdir } from 'node:os' const SLOT_ORDER = ['top', 'outer', 'bottom', 'shoes', 'bag'] const PERSONA_TEXT = { f20: '20-30대 여자', m20: '20-30대 남자', f40: '40대 이상 여자', m40: '40대 이상 남자' } const schema = { type: 'object', properties: { style: { type: 'string', description: '이 코디를 한 단어로 (예: 꾸안꾸, 오피스룩, 캐주얼, 미니멀, 스트릿, 데일리)' }, items: { type: 'array', minItems: 4, maxItems: 5, items: { type: 'object', properties: { slot: { type: 'string', enum: SLOT_ORDER }, label: { type: 'string', description: '카드 이름표. 한글 2~7자 (예: 스트라이프 티, 와이드 슬랙스, 로퍼)' }, prompt: { type: 'string', description: '그림용 영어 설명 한 구절: 색(대문자)·소재·실루엣 (예: a CHARCOAL wool single-breasted blazer)' }, }, required: ['slot', 'label', 'prompt'], additionalProperties: false, }, }, }, required: ['style', 'items'], additionalProperties: false, } function buildPrompt(pick, persona, weather) { const goods = pick.goods.map((g, i) => `${i + 1}. [${g.category1} > ${g.category2}] ${g.brand} ${g.name}`).join('\n') const files = [pick.files.image, ...pick.files.thumbs.map((t) => t.path)] return [ `무신사 스냅 코디 사진과 그 코디에 태그된 상품 목록이다. ${PERSONA_TEXT[persona]} 카드에 쓸 옷 목록을 만든다.`, `오늘 서울 날씨: 아침 ${weather.morningC}도, 낮 최고 ${weather.maxC}도.`, '', '먼저 Read 도구로 이 파일들을 본다(첫 파일이 코디 사진, 나머지는 상품 썸네일):', ...files.map((f) => `- ${f}`), '', '태그된 상품:', goods, '', '규칙:', '- 태그된 상품에 있는 옷만 넣는다. 사진에 보여도 상품 목록에 없는 옷·가방은 넣지 않는다.', '- 자리(slot)는 top·bottom·shoes 는 반드시, 상품 목록에 겉옷이 있으면 outer 도, 가방이 있으면 bag 도 넣는다. 최대 5개, 자리마다 하나.', '- 원피스면 top 으로 넣고 bottom 은 생략하지 말고 같은 원피스를 bottom 에 다시 넣지 않는다 → 원피스는 top, bottom 자리에는 사진의 다른 하의가 없으면 shoes·bag 으로 4개를 채운다.', '- 옷 이름은 상품명 기준, 색은 사진 기준.', '- label 은 카드 이름표라 짧고 쉬운 한글(브랜드·영어 금지). prompt 는 영어 한 구절, 색은 대문자.', '- style 은 코디 분위기 한 단어.', 'JSON 으로만 답한다.', ].join('\n') } /** @returns {Promise<{ style: string, items: { slot: string, label: string, prompt: string }[] }>} */ export function extractOutfit(pick, persona, weather) { const args = ['-p', buildPrompt(pick, persona, weather), '--output-format', 'json', '--json-schema', JSON.stringify(schema), '--tools', 'Read', '--allowedTools', 'Read', '--no-session-persistence', '--model', 'sonnet'] return new Promise((done, fail) => { execFile('claude', args, { cwd: tmpdir(), timeout: 240_000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => { if (err) return fail(new Error(`Claude CLI 실행 실패: ${err.message}. 터미널에서 claude 로그인 상태를 확인하세요.`)) let out try { out = JSON.parse(stdout) } catch { return fail(new Error(`Claude 답을 읽지 못했어요: ${stdout.slice(0, 300)}`)) } const result = out.structured_output ?? (typeof out.result === 'string' ? JSON.parse(out.result) : null) if (out.is_error || !result?.items?.length) return fail(new Error(`Claude가 옷 목록을 주지 못했어요: ${String(out.result ?? '').slice(0, 300)}`)) const seen = new Set() const items = result.items.filter((it) => SLOT_ORDER.includes(it.slot) && !seen.has(it.slot) && seen.add(it.slot)) items.sort((a, b) => SLOT_ORDER.indexOf(a.slot) - SLOT_ORDER.indexOf(b.slot)) done({ style: String(result.style ?? '').trim() || '데일리', items }) }) }) }