Kkdjskjd
This commit is contained in:
@@ -1,13 +1,14 @@
|
||||
// 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.
|
||||
// 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 = 700
|
||||
const MAX_TOKENS = 1200
|
||||
|
||||
export class TranslationError extends Error {
|
||||
readonly status: number
|
||||
@@ -22,160 +23,164 @@ export class TranslationError extends Error {
|
||||
// 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.
|
||||
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.
|
||||
|
||||
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.
|
||||
A card exports its type line and an array of abilities:
|
||||
|
||||
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>)
|
||||
export default card('Creature — Human Cleric', [
|
||||
triggered(when.enters(self), [gainLife(you, 1)]),
|
||||
activated([tapCost()], [addMana(you, mana('{G}'))]),
|
||||
])
|
||||
|
||||
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(...)
|
||||
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')
|
||||
.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:
|
||||
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>])
|
||||
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)
|
||||
|
||||
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, itsPower, itsToughness, count(selector), cardsInHand(player),
|
||||
maxCardsInHand(), maxOpponentCount(selector), totalManaValue(selector),
|
||||
totalPower(selector), anyNumber(), eventAmount()
|
||||
|
||||
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:
|
||||
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)
|
||||
|
||||
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>
|
||||
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:
|
||||
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|{R}{G}[, if <condition>])
|
||||
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')
|
||||
|
||||
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.
|
||||
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), 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.
|
||||
Durations: permanent (default), untilEndOfTurn, untilYourNextTurn,
|
||||
untilEndOfYourNextTurn, untilEndOfCombat, untilControllersNextUntapStep,
|
||||
whileSourceOnBattlefield.
|
||||
|
||||
Players: you, opponent, each_opponent, each_player, target_player, that_player,
|
||||
its_controller, its_owner.
|
||||
Players: you, opponent, eachOpponent, eachPlayer, targetPlayer, thatPlayer,
|
||||
itsController, itsOwner.
|
||||
|
||||
Example:
|
||||
on enters(this):
|
||||
gain_life(you, 1)
|
||||
|
||||
activate {T}:
|
||||
add_mana(you, {G})
|
||||
export default card('Creature — Human Cleric', [
|
||||
triggered(when.enters(self), [gainLife(you, 1)]),
|
||||
activated([tapCost()], [addMana(you, mana('{G}'))]),
|
||||
spell([draw(you, 2)]),
|
||||
])`
|
||||
|
||||
spell:
|
||||
draw(you, 2)`
|
||||
|
||||
const SYSTEM_PROMPT = `You translate Magic: The Gathering card text into the card pseudocode language below.
|
||||
const SYSTEM_PROMPT = `You translate Magic: The Gathering card text into the JavaScript card source 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.
|
||||
- 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.
|
||||
|
||||
${PSEUDO_GUIDE}`
|
||||
${SOURCE_GUIDE}`
|
||||
|
||||
function describeCard(card: Card): string {
|
||||
if (card.card_faces?.length) {
|
||||
@@ -226,7 +231,7 @@ export async function translateCard(card: Card, options: TranslateOptions = {}):
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Title': 'Commander card pseudocode translator',
|
||||
'X-Title': 'Commander card source translator',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: options.model ?? process.env.OPENROUTER_MODEL ?? DEFAULT_MODEL,
|
||||
@@ -261,7 +266,7 @@ export async function translateCard(card: Card, options: TranslateOptions = {}):
|
||||
compileImplementation(card, source)
|
||||
} catch (error) {
|
||||
throw new TranslationError(
|
||||
`The model did not return valid pseudocode: ${error instanceof Error ? error.message : String(error)}`,
|
||||
`The model did not return valid card source: ${error instanceof Error ? error.message : String(error)}`,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user