Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209import { esc } from './util.js';
// Bridge between the document and the LLM: a numbered serialization the model// can refer to, and an interpreter for the JSON edit operations it returns.
const DATA_LIMIT = 160;
export function serializeForLLM (doc, { scope = 'document', maxLen = 200000 } = {}) { const parts = []; const walk = (node, indent) => { if (node.nodeType === 3) { const t = node.data.trim(); if (t) parts.push(`${indent}${esc(t)}`); return; } if (node.nodeType !== 1) return; const kid = doc.kid(node); let s = `${indent}<${node.tagName} kid="${kid}"`; for (const a of node.attributes) { if (a.name.startsWith('data-kavu-')) continue; let v = a.value; if (v.length > DATA_LIMIT && /^\s*data:/.test(v)) v = `${v.slice(0, 40)}…[data URI elided, ${v.length} chars]`; else if (v.length > 4000) v = `${v.slice(0, 4000)}…[truncated, ${v.length} chars]`; s += ` ${a.name}="${esc(v)}"`; } const kids = [...node.childNodes].filter(k => k.nodeType === 1 || (k.nodeType === 3 && k.data.trim())); if (!kids.length) { parts.push(s + '/>'); return; } const inline = kids.every(k => k.nodeType === 3) || ['text', 'tspan', 'textPath', 'title', 'desc', 'style'].includes(node.localName); if (inline) { let inner = ''; for (const k of node.childNodes) { if (k.nodeType === 3) inner += esc(k.data); else if (k.nodeType === 1) { const save = parts.length; walk(k, ''); inner += parts.splice(save).join(''); } } if (node.localName === 'style' && inner.length > 6000) inner = inner.slice(0, 6000) + '…[truncated]'; parts.push(`${s}>${inner}</${node.tagName}>`); return; } parts.push(s + '>'); for (const k of kids) walk(k, indent + ' '); parts.push(`${indent}</${node.tagName}>`); }; if (scope === 'selection' && doc.selectedElements.length) { // A brief root context plus the selected subtrees. const r = doc.root; let head = `<svg kid="${doc.kid(r)}"`; for (const a of r.attributes) if (!a.name.startsWith('data-kavu-')) head += ` ${a.name}="${esc(a.value)}"`; parts.push(head + '>'); const ids = doc.ids(); if (ids.length) parts.push(` <!-- other ids in the document: ${ids.slice(0, 80).join(', ')} -->`); parts.push(' <!-- … only the selected subtree(s) follow … -->'); for (const el of doc.selectedElements) walk(el, ' '); parts.push('</svg>'); } else { walk(doc.root, ''); } let text = parts.join('\n'); if (text.length > maxLen) text = text.slice(0, maxLen) + '\n<!-- document truncated -->'; return text;}
export const SYSTEM_PROMPT = `You are the editing assistant inside kavu, an SVG editor. You receive an SVG document in which every element carries a temporary kid="N" attribute that identifies it. The user asks for changes; you answer with a JSON object describing edit operations. Output only JSON, no prose before or after it.
Response shape:{"summary": "one or two sentences on what you changed", "ops": [ ... ]}
Operations:- {"op":"set","kid":N,"attrs":{"fill":"#f00","stroke":null}} — set attributes on element N; null removes one. Prefer presentation attributes over the style attribute.- {"op":"text","kid":N,"text":"..."} — replace the text content of element N (text, tspan, title, desc, style…).- {"op":"insert","parent":N,"index":I,"svg":"<circle cx='5' cy='5' r='2'/>"} — insert markup as children of element N at index I (omit index to append). The markup may hold several elements. Never include kid attributes in markup you write.- {"op":"replace","kid":N,"svg":"..."} — replace element N with new markup.- {"op":"remove","kid":N}- {"op":"move","kid":N,"parent":P,"index":I}- {"op":"wrap","kids":[N,M],"svg":"<g id='group'/>"} — wrap the listed elements in the given container.- {"op":"document","svg":"<svg …>…</svg>"} — replace the whole document. Use only for wholesale rewrites or when starting from a blank document.
Rules:- Refer only to kids that exist in the document you were given.- Make the smallest change that satisfies the request; leave everything else exactly as it is.- Long data: URIs are shown elided as "…[data URI elided]"; never write that placeholder back, just leave those attributes alone.- New gradients, filters, patterns, markers, clipPaths and masks go in <defs> with unique ids and are referenced with url(#id).- Keep ids unique. Use meaningful ids for new elements the user may want to find later.- If asked a question, or if no change is needed, return {"summary": "...", "ops": []} with the answer in the summary.- When designing new artwork, use good composition and colour, sensible stroke widths, and the document's existing viewBox.`;
export function buildUserMessage (doc, request, { scope }) { const svg = serializeForLLM(doc, { scope }); const sel = doc.selectedElements; const lines = [`Document:\n\`\`\`svg\n${svg}\n\`\`\``]; if (sel.length) { lines.push(`Selected element${sel.length > 1 ? 's' : ''}: ${sel.map(e => `kid ${doc.kid(e)} (${e.localName}${e.id ? '#' + e.id : ''})`).join(', ')}. When the request says "this" or "it", it means the selection.`); } lines.push(`Request: ${request}`); return lines.join('\n\n');}
// Tolerant JSON extraction: fences, prose, <think> blocks.export function extractJSON (text) { if (text == null) return null; let t = String(text).replace(/<think>[\s\S]*?<\/think>/gi, '').trim(); try { return JSON.parse(t); } catch { /* keep trying */ } const fence = t.match(/```(?:json)?\s*([\s\S]*?)```/); if (fence) { try { return JSON.parse(fence[1].trim()); } catch { /* keep trying */ } } const start = t.indexOf('{'); if (start >= 0) { // scan for the matching brace, respecting strings let depth = 0, inStr = false, escp = false; for (let i = start; i < t.length; i++) { const c = t[i]; if (inStr) { if (escp) escp = false; else if (c === '\\') escp = true; else if (c === '"') inStr = false; continue; } if (c === '"') inStr = true; else if (c === '{') depth++; else if (c === '}') { depth--; if (!depth) { try { return JSON.parse(t.slice(start, i + 1)); } catch { break; } } } } // Last resort: to the last brace const end = t.lastIndexOf('}'); if (end > start) { try { return JSON.parse(t.slice(start, end + 1)); } catch { /* give up */ } } } return null;}
// Apply the ops. Returns { applied, errors, touched }.export function applyOps (doc, ops) { const errors = []; const touched = []; let applied = 0; const need = (kid, what = 'kid') => { const n = doc.byKid(kid); if (!n) throw new Error(`${what} ${kid} does not exist`); return n; }; const list = Array.isArray(ops) ? ops : []; for (const [i, op] of list.entries()) { try { switch (op.op) { case 'set': case 'setAttrs': case 'setAttr': { const el = need(op.kid); const attrs = op.attrs || (op.name ? { [op.name]: op.value } : {}); for (const [k, v] of Object.entries(attrs)) { if (typeof v === 'string' && /\[data URI elided/.test(v)) continue; doc.setAttr(el, k, v, { commit: false }); } touched.push(el); applied++; break; } case 'text': case 'setText': { const el = need(op.kid); doc.setText(el, String(op.text ?? ''), { commit: false }); touched.push(el); applied++; break; } case 'insert': { const parent = need(op.parent ?? op.kid, 'parent'); const nodes = doc.parseFragment(op.svg || ''); doc.insert(parent, nodes, op.index ?? null, { commit: false }); touched.push(...nodes.filter(n => n.nodeType === 1)); applied++; break; } case 'replace': { const el = need(op.kid); if (el === doc.root) throw new Error('cannot replace the root; use the document op'); const nodes = doc.parseFragment(op.svg || ''); doc.insert(el.parentNode, nodes, [...el.parentNode.childNodes].indexOf(el), { commit: false }); doc.remove(el, { commit: false }); touched.push(...nodes.filter(n => n.nodeType === 1)); applied++; break; } case 'remove': case 'delete': { const el = need(op.kid); if (el === doc.root) throw new Error('cannot remove the root'); doc.remove(el, { commit: false }); applied++; break; } case 'move': { const el = need(op.kid); const parent = need(op.parent, 'parent'); if (!doc.move(el, parent, op.index ?? null, { commit: false })) throw new Error('invalid move'); touched.push(el); applied++; break; } case 'wrap': { const els = (op.kids || [op.kid]).map(k => need(k)); const [wrapper] = doc.parseFragment(op.svg || '<g/>'); els.sort((a, b) => (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING) ? -1 : 1); els[0].parentNode.insertBefore(wrapper, els[0]); for (const e of els) wrapper.appendChild(e); doc.emit('change', { kind: 'structure', nodes: [wrapper] }); touched.push(wrapper); applied++; break; } case 'document': case 'replaceDocument': { doc.parse(op.svg); doc.selection = []; doc.emit('change', { kind: 'document' }); doc.emit('selection', { selection: [] }); applied++; break; } default: throw new Error(`unknown op "${op.op}"`); } } catch (err) { errors.push(`op ${i + 1} (${op.op || '?'}): ${err.message}`); } } if (applied) doc.commit('Assistant edit'); return { applied, errors, touched: touched.filter(n => doc.root.contains(n)) };}