First commit
This commit is contained in:
269
backend/src/effects/translate.ts
Normal file
269
backend/src/effects/translate.ts
Normal file
@@ -0,0 +1,269 @@
|
||||
// Natural language -> card pseudocode through an OpenRouter-hosted model.
|
||||
// The model is told to emit pseudocode 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 = 700
|
||||
|
||||
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 PSEUDO_GUIDE = `Pseudocode is line-oriented. Ability headers sit at column 0 and end with a colon. Their effects are indented two spaces, one call per line. Semicolons separate multiple effects on one line.
|
||||
|
||||
Multi-face cards use "## <exact face name>" lines, one section per face, in card order. Use "(no abilities)" for a face with none. A leading "# Card [status]" line is optional and not needed.
|
||||
|
||||
Ability headers:
|
||||
on <trigger>[ if <condition>][ (may)]:
|
||||
activate <cost>[, <cost>...][ if <condition>][ (N/turn)][ (sorcery speed)][ (may)]:
|
||||
static[ if <condition>]:
|
||||
spell[(may)]:
|
||||
keyword <Keyword>[ value]
|
||||
keywords <Keyword>, <Keyword>
|
||||
additional cost[(may)]: <cost>
|
||||
chapter <I>, <II>[(may)]:
|
||||
level <min>-<max>[: <power>/<toughness>]
|
||||
level <min>+[: <power>/<toughness>]
|
||||
level_pt(<power>/<toughness>)
|
||||
|
||||
Triggers:
|
||||
enters(target), dies(target), attacks(target), blocks(target), attacks_or_blocks(target),
|
||||
enters_or_attacks(target), enters_or_dies(target), leaves_battlefield(target),
|
||||
deals_damage(target, player|creature|permanent|any), deals_combat_damage(...),
|
||||
upkeep(you|opponent|each_player), end_step(...), begin_combat(...),
|
||||
first_main_phase(...), postcombat_main_phase(...), becomes_level(N),
|
||||
cast(you|opponent|each_player, <spell selector>|any spell[, targets this][, or copy][, #N each turn]),
|
||||
draw(you|opponent|each_player[, #N each turn]), counter_placed(target[, counter]),
|
||||
becomes_target(target), gain_life(you|opponent|each_player), lose_life(...)
|
||||
|
||||
Targets:
|
||||
this, the triggering object, the chosen target, any target, target player,
|
||||
target opponent, each opponent, each player, target player or planeswalker,
|
||||
target spell, target ability, target <selector>, each <selector>,
|
||||
up to N target <selector>, N <selector>, this or <selector>, divided(<max>[, <selector>])
|
||||
|
||||
Selectors begin with optional state words: other, tapped, untapped, attacking, token,
|
||||
equipped, enchanted. Then optional colors (white blue black red green colorless),
|
||||
supertypes, subtypes, and types. Suffixes: "you control", "an opponent controls",
|
||||
"you own", "you don't own", "with <keyword>", "without <keyword>",
|
||||
"power N+" / "power N or less", "toughness N+" / "toughness N or less",
|
||||
"mana value N+" / "mana value N or less", "named <name>",
|
||||
"from a graveyard", "from a library", "from a hand", "in exile", "on the battlefield", "on the stack".
|
||||
|
||||
Values: a number, X, count(<selector>), its power, its toughness,
|
||||
cards in your hand, cards in that player's hand, total power of <selector>,
|
||||
total mana value of <selector>, greatest number of <selector> an opponent controls,
|
||||
that much, any number.
|
||||
|
||||
Costs: {T}, {Q}, {2}{G}, {E} xN, +1 loyalty, -2 loyalty, pay N life,
|
||||
discard N card(s)[ at random], discard your hand, sacrifice this, sacrifice <selector>,
|
||||
tap <selector>, exile this from a graveyard, exile N <selector> from your graveyard,
|
||||
reveal <selector> from your hand, return <selector> to its owner's hand,
|
||||
behold <selector>, waterbend <value>, blight <value>, choose <text>,
|
||||
put <counter> counter on <selector>, forage, collect evidence N, mill N card(s).
|
||||
A choice is written (cost or cost) or (cost + cost).
|
||||
|
||||
Effects, one call per line:
|
||||
damage(target, amount[, from source])
|
||||
damage_divided(amount, target)
|
||||
draw(player, amount)
|
||||
discard(player, amount[, at random])
|
||||
mill(player, amount)
|
||||
gain_life(player, amount)
|
||||
lose_life(player, amount)
|
||||
pump(target, power/toughness[, duration])
|
||||
set_pt(target, power/toughness[, duration])
|
||||
grant(target, Keyword[ value][, duration])
|
||||
put_counters(target, counter, amount)
|
||||
remove_counters(target, counter, amount)
|
||||
proliferate()
|
||||
create_token(player, amount, [tapped ]power/toughness colors subtypes types[ with keyword, keyword])
|
||||
destroy(target), exile(target), tap(target), untap(target), regenerate(target)
|
||||
sacrifice(player, target[, unless cost])
|
||||
counter(spell|ability, target[, unless cost])
|
||||
return_to_hand(target), put_on_top(target)
|
||||
return_to_battlefield(target[, tapped][, transformed][, amount counter counters])
|
||||
scry(player, amount), surveil(player, amount)
|
||||
search(player, selector, amount, to hand|battlefield|graveyard|top|bottom[, tapped][, shuffle])
|
||||
shuffle(player)
|
||||
add_mana(player, {G}{G} | amount mana of any color)
|
||||
fight(a, b)
|
||||
energy(player, amount)
|
||||
attach(this, target)
|
||||
restrict(target, cant_attack|cant_block|doesnt_untap[, duration])
|
||||
prevent_damage(target, amount|all[, duration])
|
||||
prevent_combat_damage(target, amount|all[, duration])
|
||||
gain_control(target[, duration])
|
||||
emblem("text")
|
||||
transform(target)
|
||||
pay(cost)
|
||||
look_top(player, amount[, reorder])
|
||||
level_up(N)
|
||||
put_from_among(amount[, selector], to hand|graveyard|battlefield|top|bottom)
|
||||
dig(amount, up to? pick [selector] to hand|battlefield[ tapped], rest bottom|graveyard|top[ any|random][, optional])
|
||||
Other keyword actions: action_name(target) or action_name(amount, detail)
|
||||
|
||||
Nested blocks:
|
||||
if <condition>:
|
||||
<effects>
|
||||
choose <min>[-<max>]:
|
||||
1. <effects separated by ;>
|
||||
2. <effects separated by ;>
|
||||
schedule(next_upkeep|next_end_step):
|
||||
<effects>
|
||||
|
||||
Static effects:
|
||||
pump(target, power/toughness)
|
||||
grant(target, Keyword[ value])
|
||||
restrict(target, rule[ detail][ if <condition>])
|
||||
enters_tapped(target[, unless <condition>])
|
||||
enters_with_counters(target, counter, amount)
|
||||
grant_ability(target):
|
||||
<one ability block>
|
||||
set_pt(target[, base], power/toughness|?)
|
||||
control(target)
|
||||
choose(creature_type|color|card_name|player|opponent|number)
|
||||
replace(dies|leaves_battlefield|discard|draw[, target], instead exile|return_to_hand|return_to_library|prevent)
|
||||
cost_reduction(target, amount[, if <condition>])
|
||||
|
||||
Common conditions: you control <selector>, you control at least N <selector>,
|
||||
an opponent controls <selector>, it is your turn, it isn't your turn,
|
||||
this is tapped, this is untapped, this is attacking, <player> has at least N life,
|
||||
<player> has at most N life, <player> has N+ cards in their graveyard,
|
||||
<player> has no cards in hand, a creature died this turn,
|
||||
you gained at least N life this turn, you drew N+ cards this turn,
|
||||
you cast it from your hand, this is in your graveyard, this is on the battlefield,
|
||||
you're the monarch, you have the initiative, it was kicked,
|
||||
you've cast a spell this turn, you've cast a noncreature spell this turn,
|
||||
no creatures attacked this turn, you do, you don't, otherwise.
|
||||
|
||||
Durations: permanent (default), until end of turn, until your next turn,
|
||||
until end of combat, until its controller's next untap step,
|
||||
for as long as this remains on the battlefield.
|
||||
|
||||
Players: you, opponent, each_opponent, each_player, target_player, that_player,
|
||||
its_controller, its_owner.
|
||||
|
||||
Example:
|
||||
on enters(this):
|
||||
gain_life(you, 1)
|
||||
|
||||
activate {T}:
|
||||
add_mana(you, {G})
|
||||
|
||||
spell:
|
||||
draw(you, 2)`
|
||||
|
||||
const SYSTEM_PROMPT = `You translate Magic: The Gathering card text into the card pseudocode language below.
|
||||
|
||||
Output rules:
|
||||
- Answer with pseudocode only. No explanation, no code fences, no card header, no comments.
|
||||
- Use only the syntax 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 "## <face name>" sections in the given order.
|
||||
|
||||
${PSEUDO_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<string> {
|
||||
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 pseudocode 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 pseudocode: ${error instanceof Error ? error.message : String(error)}`,
|
||||
)
|
||||
}
|
||||
|
||||
return source
|
||||
}
|
||||
Reference in New Issue
Block a user