// Natural language -> card source through an OpenRouter-hosted model. // The model is told to emit the JavaScript card DSL only, and the answer is // parsed before it reaches the editor, so prose or a guess never becomes an // implementation. import type { Card } from '../cards.js' import { compileImplementation } from './implementations.js' export const DEFAULT_MODEL = 'google/gemini-2.5-flash-lite' const ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions' const MAX_TOKENS = 1200 export class TranslationError extends Error { readonly status: number constructor(message: string, status = 502) { super(message) this.name = 'TranslationError' this.status = status } } // Kept compact: it is both the model's only context and the format contract. // Anything not listed here is rejected by the parser, so the model must not // invent operations. export const SOURCE_GUIDE = `The source is a JavaScript expression evaluated by a safe interpreter. It is never run as JavaScript: only the names listed here exist. A card exports its type line and an array of abilities: export default card('Creature — Human Cleric', [ triggered(when.enters(self), [gainLife(you, 1)]), activated([tapCost()], [addMana(you, mana('{G}'))]), ]) Multi-face cards export face sections in card order: export default faces( face('Front', 'Instant', [ ...abilities ]), face('Back', 'Creature — Human', [ ...abilities ]), ) Abilities: keyword('Flying') one keyword keyword('Ward', '{2}') keyword with a value keywords('Flying', 'Trample') several simple keywords triggered(event, [effects], { condition, optional }) activated([costs], [effects], { condition, timing: 'sorcery', activationsPerTurn, optional }) staticAbility([staticEffects], { condition }) spell([effects], { optional }) additionalCost([costs], { optional }) alternativeCost([costs], { condition }) overload('{6}{U}') chapter(['I', 'II'], [effects], { optional }) levelBand(min, max, power, toughness) max may be null levelPt(power, toughness) unsupported('short reason', 'original oracle text') Any effect list (triggered, activated, staticAbility, spell, chapter, ifThen, schedule and each modal mode) takes an array or a callback: () => effect, or () => { effect; effect }. Triggers (when.*): enters(target), dies(target), attacks(target), blocks(target), attacksOrBlocks(target), entersOrAttacks(target), entersOrDies(target), leavesBattlefield(target), dealsDamage(target, 'player'|'creature'|'permanent'|'any', { combat }), upkeep(who), endStep(who), beginCombat(who), firstMainPhase(who), postcombatMainPhase(who), cast(who, spellSelector, { targetsSelf, orCopy, ordinal }), becomesLevel(N), draw(who, ordinal), counterPlaced(target, counter), becomesTarget(target), lifeGained(who), lifeLost(who) who is you, opponent or eachPlayer. Selectors (chainable): permanents, cards, creatures .withType('land'), .withSubtype('dragon'), .withSupertype('legendary') .withColor('white'|'blue'|'black'|'red'|'green'|'colorless') .withoutColor('white'|'blue'|'black'|'red'|'green'|'colorless') .withoutType('creature'), .withKeyword('flying'), .withoutKeyword('flying') .other(), .tapped(), .untapped(), .attacking(), .token(), .nontoken() .equipped(), .enchanted(), .youControl(), .opponentControls(), .controlledBy('you'|'opponent'|'any') .ownedBy('you'|'opponent'), .named('Name'), .inZone('battlefield'|'hand'|'graveyard'|'library'|'exile'|'stack'|'command') .withCounter('+1/+1', 1), .powerAtLeast(N), .powerAtMost(N), .toughnessAtLeast(N), .toughnessAtMost(N), .manaValueAtLeast(N), .manaValueAtMost(N), .matchingAny() Targets: self, triggerSubject, previousTarget, anyTarget, targetPlayerOrPlaneswalker target(selector, { count, upTo, includeSelf }) one target each(selector) every matching object pick(selector, { count, upTo }) choose without targeting divided(N, selector) or divided('any', selector) damage divided among targets targetSpell(selector), targetAbility(selector) target(you|opponent|eachOpponent|eachPlayer|targetPlayer|thatPlayer|itsController|itsOwner) Values: a number, X, itsPower, itsToughness, count(selector), cardsInHand(player), maxCardsInHand(), maxOpponentCount(selector), totalManaValue(selector), totalPower(selector), anyNumber(), eventAmount() Costs: manaCost('{2}{G}'), tapCost(), untapCost(), tapOther(selector), energyCost(N), loyalty(N), payLife(value), discardCost(value, { player, random }), sacrificeCost(selector), sacrificeSelf(), exileSelf(), exileFromGraveyard(selector, amount), reveal(selector), choice([[cost, ...], [cost, ...]]), returnToHandCost(selector), behold(selector), waterbend(value), blight(value), chooseCost('text'), putCounterCost(counter, selector), removeCountersCost(counter, amount, selector), forage(), collectEvidence(N), millCost(value) Effects: damage(target, amount, fromSource), damageDivided(amount, target) draw(player, amount), discard(player, amount, { random }), mill(player, amount) gainLife(player, amount), loseLife(player, amount) pump(target, power, toughness, duration), setPt(target, power, toughness, { duration }) grant(target, keyword, { value, duration }), putCounters(target, counter, amount) removeCounters(target, counter, amount), proliferate() createToken(player, amount, token({ types, subtypes, colors, power, toughness, keywords, tapped })) createToken(player, amount, copyOf(target, { notLegendary })) destroy(target), exile(target), sacrifice(player, target, unlessCost) counter('spell'|'ability', target, unlessCost), returnToHand(target) returnToBattlefield(target, { tapped, transformed, counters: { counter, amount } }) putOnTop(target), tap(target), untap(target), scry(player, amount), surveil(player, amount) search(player, selector, amount, { destination, tapped, shuffle, zones, split }) shuffle(player), addMana(player, mana('{G}{G}') | anyColor(value, { oneColor, restriction })) fight(a, b), regenerate(target), energy(player, amount), attach(target) restrict(target, 'cant_attack'|'cant_block'|'doesnt_untap', duration) keywordAction('action name', { target, amount, detail }) preventDamage(target, amount | 'all', { combatOnly, duration }) gainControl(target, duration), emblem('text'), transform(target) pay([costs]), ifThen(condition, [effects]), modal(min, max, [[effects], [effects]]) lookTop(player, amount, { reorder }), schedule('next_upkeep'|'next_end_step', [effects]) levelUp(N), putFromAmong(player, amount, { selector, destination }), dig(player, amount, { ... }) exileGraveyards(), hideaway(amount), playExiled(player, { free }) Static effects: staticPump(target, power, toughness), staticGrant(target, keyword, { value }) grantAbility(target, ability), staticRestrict(target, rule, { value, comparison, detail, condition }) entersTapped(target, { unless }), entersWithCounters(target, counter, amount) staticSetPt(target, power, toughness, { base }), control(target) choose('creature_type'|'color'|'card_name'|'player'|'opponent'|'number') replace(what, { target, instead }), costReduction(target, amount | '{R}{G}', { condition }) costIncrease(amount, { spellType }), searchRestriction('you'|'opponent', amount), exileInsteadOfGraveyard('you'|'opponent') Conditions: youControl(selector, atLeast), opponentControls(selector, atLeast), yourTurn(), notYourTurn(), sourceTapped(), sourceUntapped(), sourceAttacking(), lifeAtLeast(player, N), lifeAtMost(player, N), lifeAboveStarting(player, N), cardsInGraveyard(player, N), handEmpty(player), creatureDiedThisTurn('you'|'opponent'), youGainedLifeThisTurn(N), youDrewCardsThisTurn(N), spellsCastLastTurn(who, N), noSpellsLastTurn(), attackedThisTurn(), youAttackedThisTurn(), defendingPlayerControls(selector), targets(selector), wasKicked(), youCastIt({ fromHand }), inGraveyard(), onBattlefield(), monarch(), initiative(), citysBlessing(), suspended(), bargained(), wasCreature(), opponentLostLifeThisTurn(), lifeChangedThisTurn(), descendedThisTurn(), permanentLeftBattlefieldThisTurn(), nonlandPermanentsEnteredThisTurn(N), attackedWithTotalPower(N), yourCreaturesTotalPower(N), opponentControlsMoreLands(), distinctPowers(N), graveyardCardTypes(N), noObjects(selector), cardsInHandAtMost(who, N), notTheirTurn(), noAttackers(), opponentPoison(N), tributeNotPaid(), hadCounters(counter), manaFromTreasure(), manaSpent(N), noManaSpent(), manaSymbolSpent('{G}'), kickedWith('{2}'), moreCardsThanEachOpponent(), firstCombatPhase(), notToken(), castSpellThisTurn({ noncreature }), fullParty(), graveyardCount(selector, N), creaturePowerGreaterThanBase('power'|'toughness'), ifYouDo(), ifYouDont(), otherwise(), youControlCommander(), distinctNames(selector, N), opponentDamagedThisTurn(N), attackedWithCreatures(N), libraryAtMost(N) Durations: permanent (default), untilEndOfTurn, untilYourNextTurn, untilEndOfYourNextTurn, untilEndOfCombat, untilControllersNextUntapStep, whileSourceOnBattlefield. Players: you, opponent, eachOpponent, eachPlayer, targetPlayer, thatPlayer, itsController, itsOwner. Example: export default card('Creature — Human Cleric', [ triggered(when.enters(self), [gainLife(you, 1)]), activated([tapCost()], [addMana(you, mana('{G}'))]), spell([draw(you, 2)]), ])` const SYSTEM_PROMPT = `You translate Magic: The Gathering card text into the JavaScript card source language below. Output rules: - Answer with card source only. No explanation, no code fences, no comments. - Start with card('Type line', [...]) using the exact type line given for the card. - Use only the names and shapes below. Never invent an operation or a keyword argument. - If an ability cannot be expressed, use: unsupported('short reason', 'original oracle text') - For multi-face cards, output only the faces(...) sections in the given order. ${SOURCE_GUIDE}` function describeCard(card: Card): string { if (card.card_faces?.length) { const faces = card.card_faces.map(face => [ `## ${face.name}`, face.type_line ? `Type: ${face.type_line}` : '', face.oracle_text || '(no abilities)', ].filter(Boolean).join('\n')) return [`Card: ${card.name}`, `Layout: ${card.layout}`, ...faces].join('\n\n') } return [ `Card: ${card.name}`, `Type: ${card.type_line}`, `Oracle text:\n${card.oracle_text || '(no abilities)'}`, ].join('\n') } /** Removes the code fence models add out of habit. Everything else is kept. */ export function cleanTranslation(text: string): string { const trimmed = text.trim() const fenced = trimmed.match(/^```[^\n]*\n([\s\S]*?)\n```$/) return (fenced ? fenced[1] : trimmed).trim() } interface ChatResponse { choices?: Array<{ message?: { content?: unknown } }> error?: { message?: string } } export interface TranslateOptions { apiKey?: string model?: string fetch?: typeof fetch } export async function translateCard(card: Card, options: TranslateOptions = {}): Promise { const apiKey = options.apiKey ?? process.env.OPENROUTER_API_KEY if (!apiKey) { throw new TranslationError('OPENROUTER_API_KEY is not set on the backend.', 503) } const fetchImpl = options.fetch ?? fetch let response: Response try { response = await fetchImpl(ENDPOINT, { method: 'POST', headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', 'X-Title': 'Commander card source translator', }, body: JSON.stringify({ model: options.model ?? process.env.OPENROUTER_MODEL ?? DEFAULT_MODEL, messages: [ { role: 'system', content: SYSTEM_PROMPT }, { role: 'user', content: describeCard(card) }, ], temperature: 0, max_tokens: MAX_TOKENS, }), signal: AbortSignal.timeout(60_000), }) } catch (error) { throw new TranslationError(`Could not reach OpenRouter: ${error instanceof Error ? error.message : String(error)}`) } const data = await response.json().catch(() => undefined) as ChatResponse | undefined if (!response.ok) { const detail = data?.error?.message ? `: ${data.error.message}` : '' throw new TranslationError(`OpenRouter returned ${response.status}${detail}`) } const content = data?.choices?.[0]?.message?.content if (typeof content !== 'string') { throw new TranslationError('OpenRouter returned no text.') } const source = cleanTranslation(content) if (!source) throw new TranslationError('OpenRouter returned an empty answer.') try { compileImplementation(card, source) } catch (error) { throw new TranslationError( `The model did not return valid card source: ${error instanceof Error ? error.message : String(error)}`, ) } return source }