CLI protocol
Every platform ships a command-line program that drives its core the way a screen would, so the
behaviour suite (spec/behaviour/) and agents can play a game on any platform from a terminal, with
no simulator or device. The three programs speak exactly this protocol and print the same JSON.
| Platform | Source | Build | Binary |
|---|---|---|---|
| Swift | swift/CanastaCore/Sources/CanastaCLI/ (target CanastaCLI, product canasta-cli) |
cd swift/CanastaCore && swift build --product canasta-cli |
swift/CanastaCore/.build/debug/canasta-cli |
| Kotlin | kotlin/cli/ (Gradle application module :cli) |
cd kotlin && ./gradlew :cli:installDist |
kotlin/cli/build/install/canasta-cli/bin/canasta-cli |
| Rust | rust/canasta-cli/ (workspace member, binary canasta-cli) |
cd rust && cargo build -p canasta-cli |
rust/target/debug/canasta-cli |
Running
canasta-cli --spec <dir><dir> is the repo’s spec/ folder. The program reads every *.json file directly in
<dir>/rulesets/ (not in subfolders), in file-name order, as rule sets, then every *.json file
directly in <dir>/tutorials/, in file-name order, as tutorials loaded
with those rule sets (each file’s name without .json is its id). It takes no other argument.
- Missing or extra arguments: a usage line on stderr, exit status 2, nothing on stdout.
- A rule set that cannot be read or decoded, or a tutorial that cannot be read or does not load: a message on stderr, exit status 1, nothing on stdout.
- Otherwise it prints nothing until the first request. It reads requests from stdin, one per line, and writes exactly one response line to stdout for each request (blank lines get none), in order, flushing stdout after every response. At end of input it exits with status 0.
- stdout carries only response lines. Anything else (logs, the JVM’s notices) goes to stderr, which no client reads.
Text is UTF-8. The program holds one game at a time, in memory; nothing is stored. A caller keeps a
game by asking for its saved-game text (save) and gives it back with
resumeGame; the CLI itself never writes it anywhere.
Requests
A line ends at \n, and only there: a \r elsewhere is part of the line (ls\rls is one line, an
unknownCommand). One trailing \r is removed, then spaces and tabs at both ends. A line that is
then empty is ignored: no response. Otherwise the line is a command word, optionally followed by
spaces or tabs and the rest of the line:
| Request | Means |
|---|---|
ls |
Print the focused node. Nothing may follow the word. |
save |
Print the game as saved-game text (Saving). Nothing may follow the word. |
do <action> |
Run the action with input {}. |
do <action> <json> |
Run the action with this input: everything after the whitespace that follows the action name, to the end of the line. |
<action> is the next run of characters up to a space, tab or the end of the line. Words are
case-sensitive (LS and NewGame are unknown).
A request is checked in this order; the first failure is the response:
- The command is not
ls,saveordo→unknownCommand. lsorsavefollowed by anything, ordowith no action name →badRequest.savewith no game dealt or resumed →noGame. (The steps below are fordo.)- The action is not in the focused node’s
actions(own or lent) →unknownAction. - The input text is not one valid JSON value under strict RFC 8259 (nothing after it but whitespace) →
badJson. Strict means no trailing commas, comments, unquoted keys or words, leading zeros, or numbers outside the IEEE 754 double range. Lenient parsers must not be used. An object that repeats a key is valid JSON and reads as if only the key’s last occurrence were there ({"seat": 7, "seat": 1}is seat 1; Repeated keys). - The input does not fit the action’s input schema (see Inputs) →
invalidInput. - The action runs. A rule the engine enforces fails → that rule error, and nothing changes. For
resumeGame, a save that does not load → that save error, and nothing changes.
Responses
One line of compact JSON (no newline inside it), then \n. Exactly one of:
{"ok":true,"node":{"name":"game","path":["root","game"],"state":{},"actions":[],"children":[]}}{"ok":false,"error":{"kind":"rule","code":"initialMeldTooLow","message":"initialMeldTooLow","context":{"minimum":50,"points":30}}}- Success (
ls, or adowhose action ran):oktrue andnode, the focused node after the request. No other keys. Asavethat succeeds is the one exception:oktrue andsave, the saved-game text as a JSON string, and no other keys ({"ok":true,"save":"{\"format\":\"canastaSave\",…}"}). - Failure:
okfalse anderror, with exactlykind,codeandmessage, and forkindrulealsocontext. Nonode: a failed request changes nothing, solsshows the same node as before it.kindprotocol:codeis one of the table below.kindrule:codeis a rule error raw value from spec/README.md “Errors” (pileFrozen,notYourTurn, …), exactly as the engine returns it.kindsave(only fromresumeGame):codeis a save error raw value from spec/README.md “Saved games” (badJson,notSavedGame,unsupportedVersion,malformed,unknownRuleSet,inconsistent), andmessagethe load’s message exactly (malformed: position.question), so every platform prints the same line.message: never empty. Forkindprotocolit is a short English sentence for people; platforms word it as they like and nobody compares it. Forkindruleit is thecoderepeated ("message":"pileFrozen"): the engine has no wording of its own, so the same refusal prints the same line on every platform. Apps turn the code into words later.context(kindruleonly, always present): the rule error context of a refused game move (draw…answer), an object with only the keys that error has ({"minimum":50,"points":30}forinitialMeldTooLow), and{}for every other error, includingnewGame’s andnextHand’s.
| Protocol code | When |
|---|---|
unknownCommand |
The first word is not ls, save or do |
badRequest |
ls or save with anything after it, or do without an action name |
noGame |
save before any game is dealt or resumed |
unknownAction |
The focused node has no action of that name, its own or lent |
badJson |
The input text is not valid JSON |
invalidInput |
The input does not fit the action’s schema |
Keys in a JSON object may come in any order; clients parse, never compare text. Integers are written
as plain JSON integers (9007199254740991, never 9.007199254740991e15 or 15.0).
Nodes, tree and focus
The app is a tree of nodes, one per screen. Each node is a view model with one shape: State
(everything the screen shows), Action (everything a person can do there), an internal Message,
and update(state, message), the only place state changes. A node prints as:
| Key | Holds |
|---|---|
name |
The node’s name: root or game |
path |
Node names from root down to this node: ["root"], ["root","game"] |
state |
The node’s state as JSON (below). If a person can see it, it is here |
actions |
Every action a person can take here: { "name", "node", "input" }, where node names the node that owns the action and input is the JSON Schema of its input. If a person can do it, it is here |
children |
Names of the node’s child nodes, in order |
- Tree.
rootis always there. It has one child,game, once a game has been dealt or resumed; until then it has none. Later checkpoints add children (a lobby, a score sheet) the same way. - Focus. The CLI always focuses the deepest node: from
root, follow the last child while there is one.lsprints that node, anddoruns actions on it. - Lent actions. A container lends its actions down to the focused node. The focused node’s
actionslists its own actions first, in the order the node declares them, then each ancestor’s actions, nearest ancestor first. An action keeps its owner innode, and running it changes the owner’s state. A child’s actions are never lent upward:drawatrootisunknownAction. - Actions are listed whether or not they are legal right now (whose turn it is, which stage); the engine’s rule error says why one is refused.
- Growing. New actions are appended to a node’s own list, new state keys are added, and nothing is
renamed without a spec change. Clients find actions by
name, never by position.
Inputs
Every input is a JSON object, described by a JSON Schema that uses only type (object, array,
string, integer), properties, required, additionalProperties: false, items, enum,
pattern, minimum and maximum. An input fits its schema when:
- It is an object; it has every
requiredkey; every key it has is inproperties. - A value is never
null(an optional key is left out instead). integer: a JSON number written without a fraction or an exponent (4; not4.0,4e0,-0or"4"), fromminimumtomaximum.stringwithenum: one of the listed strings, exactly.stringwithpattern: a card (^(JK|(A|[2-9]|10|J|Q|K)[CDHS])$).stringwith neither: any JSON string.array: every item fitsitems(an empty array fits).
Inputs leave every game rule to the engine: a seat that does not exist, a card not in the hand or an
empty meld list fits the schema and gets a rule error. Where the same schema appears twice below it is
written once: Small is {"type":"integer","minimum":0,"maximum":99}, Big is
{"type":"integer","minimum":0,"maximum":9007199254740991}, Card is
{"type":"string","pattern":"^(JK|(A|[2-9]|10|J|Q|K)[CDHS])$"}, Cards is
{"type":"array","items":Card} and Melds is {"type":"array","items":Cards}. Every object schema
also has "additionalProperties":false. spec/behaviour/tests/expected.ts holds the same schemas
in full, and the suite compares them exactly.
The root node
State: {"ruleSets":[{"id":"family","name":"Family","players":[4,6],"askPartner":"optional","blackThreesLaidOut":false,"keepThree":false},{"id":"modern-american","name":"Modern American","players":[4],"askPartner":"optional","blackThreesLaidOut":true,"keepThree":true},{"id":"official","name":"Official classic","players":[4,6],"askPartner":"optional","blackThreesLaidOut":false,"keepThree":false}],"tutorials":[{"id":"canasta-first-hand","title":"tutorial.firstHand.title","ruleSet":"family","players":4}]}:
each rule set loaded, in file-name order, with its id, name, players (its player
counts: the tables[] entries’ players, in file order) and askPartner
(its goingOut.askPartner: optional, required or never) and blackThreesLaidOut (its
blackThrees.layOut) and keepThree (its specialHands.keepThree), so a screen offers only the tables a rule set deals, the “may I go out?”
button only where it may be asked, and names the score sheet’s threes row “Threes” where black
threes are laid out and “Red 3s” elsewhere, and offers “Lay out 3” only where a three may be kept. tutorials lists each
tutorial loaded, in file-name order, with its id, title (a strings
key), ruleSet and players.
Actions (own, in this order):
| Action | Input schema | Does |
|---|---|---|
newGame |
{"type":"object","properties":{"ruleSet":{"type":"string","enum":[ids]},"players":Small,"dealer":Small,"seed":Big,"stream":Big,"controllers":{"type":"array","items":{"type":"string","enum":["human","easy","normal"]}},"view":{"type":"string","enum":["all","hotSeat"]}},"required":["ruleSet","players","dealer","seed","stream"]} |
Deals a new game with the deal (new(seed, stream) shuffle) and makes it the game child, replacing any game in progress. The deal’s rule errors (unsupportedPlayerCount, invalidSeat) are its rule errors. controllers names who plays each seat, in seat order: human, or a computer player at level easy or normal; missing means every seat is human. A list whose length is not players does not fit the input (invalidInput, checked with the schema, before the deal). view says whose hands the game shows (Viewing); missing means all. Then computer seats play |
resumeGame |
{"type":"object","properties":{"save":{"type":"string"}},"required":["save"]} |
Loads save, a saved game’s text, with the CLI’s rule sets and makes it the game child, replacing any game in progress: its hand, position, score sheet, controllers, view, handOrder, log and computer players’ sources are the save’s. A save that does not load is that save error, and nothing changes. Then computer seats play |
newTutorial |
{"type":"object","properties":{"tutorial":{"type":"string","enum":[tutorial ids]}},"required":["tutorial"]} |
Deals the tutorial’s deal and makes it the game child, replacing any game in progress, as a tutorial game. Then computer seats play |
[ids] is the loaded rule set ids, in the same order as state.ruleSets, and [tutorial ids] the
loaded tutorial ids, in the same order as state.tutorials. Big‘s maximum is the
cores’ maxSeed (spec/README.md).
The game node
State of a game, every key always present:
| Key | Value |
|---|---|
ruleSet |
The rule set id |
seed, stream |
The newGame seed and stream (hand h is shuffled with new(seed, stream + h − 1)), or the save’s after resumeGame, which may exceed maxSeed (Saved games). Each is written as a JSON integer of its exact unsigned value, 0 to 18446744073709551615: never negative, never a fraction or an exponent, so a core whose integer type is signed 64-bit must write it as unsigned |
hand |
The hand being played, from 1 |
dealer |
The dealer’s seat |
turn |
The seat to play |
turnStage |
draw, play, answer or handOver |
question |
The question of the position: notAsked, tooLate, asked, yes or no |
wentOut |
Whether the hand ended by turn going out (false while it is in play, and when the stock ran out) |
view |
all or hotSeat, from newGame (Viewing) |
viewer |
The viewing seat, or null when no seat is played by a person |
handOrder |
How shown hands are sorted: dealt, rank or suit (sortHand); dealt after newGame |
seats |
One per seat, in seat order: {"seat", "side", "controller", "hand", "handSize", "handPoints", "meldable", "discardable", "declarable", "redThrees", "blackThrees", "bonusCards"}. side is seat % teams; controller is human, easy or normal (from newGame); hand is every card, in handOrder (Hand order: sortHand of the position’s hand), or null when the seat’s hand is hidden; handSize the hand’s length, always shown; handPoints each shown card’s points, one per card of hand, in the same order (null with hand); meldable each shown card’s meldable mark, one per card of hand, in the same order (null with hand); discardable each shown card’s discardable mark, likewise; declarable whether the shown hand is a special hand the seat may declare: its side holds no meld and the hand matches a specialHands.hands entry (whatever the turn: the apps offer “Declare” when it is also the seat’s turn to play; null with hand); redThrees in the order laid; blackThrees the laid black threes (blackThrees.layOut), in the order laid, [] without it; bonusCards how many face-down bonus cards the seat holds (a count: no seat sees them) |
sides |
One per side, in side order: {"side", "gameScore", "opened", "initialMinimum", "melds"}. opened is whether the side holds a meld; initialMinimum is the initial meld minimum for its gameScore; melds in the order laid, each {"rank", "cards", "kind", "isCanasta", "bonus"} with rank the meld’s rank ("A", "3" … "K") or "wild" for a wild meld, and kind, isCanasta and bonus as in scenario expect.melds |
stockCount |
Cards left in the stock (the stock itself is never shown) |
lastCards |
With initialMeld.bonusCards, once the turn card is drawn (the stock holds fewer than minStock cards): minStock − 1, the cards left when it was drawn (Pagat’s “bottom 8”). The apps show a static “Turn card drawn” notice while it is set, never this number as a live count; otherwise null |
specialHand |
Once a hand is over by a declared special hand: {"seat", "name", "cards"}, the seat that declared it, the declared hand’s name and the hand’s cards in hand order (face up: every seat sees them); otherwise null |
pileTop |
The discard pile’s top card, or null when the pile is empty |
pileCount |
Cards in the pile, face-down ones included (the cards under the top are never shown) |
pileHidden |
How many of them are face down |
pileFrozen |
Whether the pile is frozen for everyone |
scoreSheet |
The game’s score sheet: one row per hand that is over, oldest first, the current hand’s row included as soon as it is over: {"hand", "dealer", "wentOut", "concealed", "sides"}. wentOut is the seat that went out, or null when the stock ran out; concealed whether it went out concealed; sides one per side, in side order: {"side", "melds", "canastas", "redThrees", "goingOut", "cardsInHand", "unfinishedCanastas", "total", "gameScore", "nextMinimum"}, the hand score rows, the new game score and the next hand’s opening minimum |
gameOver |
Whether the game is over (the last row’s hand ended it) |
winners |
The winning sides, in side order; [] while the game goes on |
tutorial |
null, or in a tutorial game its current step: {"id", "title", "step", "steps", "coach", "highlight", "expect"}. step is the current step’s index from 0 and steps the number of steps; coach, highlight and expect are the step’s, as in the tutorial file (expect a move with seat and do, a take always with melds, or null at the last step). While a computer seat still has to play, the step shown is already the next one the person will play |
sides[].gameScore and initialMinimum stay the ones the hand started with until nextHand; the
score sheet’s last row already shows the new ones.
The CLI caller plays every human seat; computer seats play themselves.
Viewing
The viewing seat (viewer) is the seat a screen shows the hand of, for hot-seat play where the
people at one table share one screen: the seat to act (turn, or at answer
the asker’s partner; at handOver, turn) when its controller is human; else the first human
seat in seat order; else null (only computers play). It is worked out from the state every time,
whatever view is. view says which hands the state shows:
all: every seat’shand,handPoints,meldable,discardableanddeclarable(the CLI caller plays every seat).hotSeat: only the viewing seat’s; every other seat’s five arenull, and with no viewing seat all of them are.handSize,redThrees,blackThreesandbonusCardsare always shown.
view and handOrder stay the same through nextHand; a newGame sets them afresh, and a
resumeGame to the save’s.
Computer seats
After newGame, after resumeGame, after nextHand and after every game action that succeeds, the
game plays its computer seats: while the hand is not over and the seat to act (turn, or at
answer the asker’s partner) is a computer seat, that seat’s bot chooses one action
(spec/bots.md: chooseAction on the seat’s view, the hand’s log and the seat’s
botRandom(seed, stream + hand − 1, seat) source, made when the hand is dealt, or the save’s after
resumeGame) and the engine applies it. So the response to a request shows the game once a human seat must act, or once the hand
is over. A move for a computer seat gets the engine’s error as usual (notYourTurn: a computer seat
is never left to act). A game with no human seat plays each hand to its end at once; nextHand
plays the next. When a bot has no action (its hand is empty at play, which a position that
loads or that moves reach never has) or the engine refuses its action
(a position no game reaches, such as one card left at play without the canastas to go out), the
request answers that rule error (cardNotInHand for no action) and changes nothing; the game node’s
stepComputer fails the same way.
Actions (own, in this order, then the root’s newGame). Each runs one move of
spec/README.md “Moves” for seat, through the engine’s apply; its fields are
the scenario move fields of the same name.
| Action | Input schema | Move |
|---|---|---|
draw |
{"type":"object","properties":{"seat":Small},"required":["seat"]} |
draw |
take |
{"type":"object","properties":{"seat":Small,"method":{"type":"string","enum":["naturalPair","naturalAndWild","addToMeld"]},"cards":Cards,"melds":Melds},"required":["seat","method","cards"]} |
take; a missing melds is [] |
lay |
{"type":"object","properties":{"seat":Small,"melds":Melds},"required":["seat","melds"]} |
lay |
add |
{"type":"object","properties":{"seat":Small,"rank":{"type":"string","enum":["A","3","4","5","6","7","8","9","10","J","Q","K","wild"]},"cards":Cards},"required":["seat","rank","cards"]} |
add; wild is the side’s wild meld |
discard |
{"type":"object","properties":{"seat":Small,"card":Card},"required":["seat","card"]} |
discard |
ask |
{"type":"object","properties":{"seat":Small},"required":["seat"]} |
ask |
answer |
{"type":"object","properties":{"seat":Small,"answer":{"type":"string","enum":["yes","no"]}},"required":["seat","answer"]} |
answer |
declare |
{"type":"object","properties":{"seat":Small},"required":["seat"]} |
declare |
layOutThree |
{"type":"object","properties":{"seat":Small},"required":["seat"]} |
layOutThree |
nextHand |
{"type":"object","properties":{},"required":[]} |
None: deals the next hand (hand + 1, the next dealer, the new game scores) with new(seed, stream + hand), where hand is the number of the hand just over. Its rule errors are handNotOver and gameOver. The score sheet keeps its rows |
sortHand |
{"type":"object","properties":{"order":{"type":"string","enum":["dealt","rank","suit"]}},"required":["order"]} |
None: sets handOrder, so every shown hand is sorted that way from now on, cards drawn or taken later included. It never fails, at any stage, and changes nothing else: the position’s hands keep their order, and moves still name cards |
Tutorials
A tutorial game plays a tutorial (newTutorial): its deal (seed and
stream are the tutorial’s, or 0 and 0 for a stacked deal), hand 1, the person’s seat human and
every other seat normal, view hotSeat (so only the person’s hand is shown) and handOrder
dealt. It differs from any other game in three ways:
- The person’s moves. A game move (
draw…layOutThree) is first played by the rules as usual: one they refuse gets that rule error. A move they allow is then checked against the current step: one that does not match getsnotTutorialStep(a nudge, not a rule), and one that matches plays the step’s ownexpect, so the meld cards lie as the tutorial lists them. A move for a computer seat is never the step’s, so it getsnotTutorialStepwhen the rules allow it. - Computer seats play the script’s next move, never their bot, whether the game plays them at
once or the caller steps them (
stepComputer).computerToActnames them as in any game. nextHandgets its rule errors (handNotOver) and, once the hand is over,notTutorialStep: a tutorial is one hand.sortHandworks as in any game.
save saves a tutorial game as any game: the save holds no tutorial, so resumeGame continues it
as an ordinary game whose computer seats choose with their bots.
Saving
save prints the game in progress as saved-game text, whatever node is focused: the game node’s
whole state as spec/README.md “Saved games” writes it, the stock, every
hand, the hand’s log and the computer players’ sources included. It changes nothing. The text is for
the caller to keep (an app’s file, the web client’s localStorage) and give back to resumeGame; it
is never shown, since it holds what no seat may see. do resumeGame {"save":<that text>} in any CLI,
on any platform, shows the same game, and every request after it answers as it would have in the
CLI that saved it. Clients parse the text, never compare it.
> save< {"ok":true,"save":"{\"format\":\"canastaSave\",\"version\":1,\"ruleSet\":\"official\",…}"}> do resumeGame {"save":"{\"format\":\"canastaSave\",\"version\":2}"}< {"ok":false,"error":{"kind":"save","code":"unsupportedVersion","message":"unsupportedVersion: 2"}}Zero network
The CLIs have no network service: their only injected source of randomness is the seed in newGame,
and they keep no storage. The behaviour suite enforces it: it starts every CLI inside a network guard
(spec/behaviour/sdk/guard.ts): on macOS sandbox-exec with a profile that denies all network
access, on Linux unshare --user --map-root-user --net (a network namespace with no usable device).
A CLI that tries to connect gets an error at once and its test fails. tests/network.test.ts checks
that the guard is applied and that it refuses a connection.
Example
> ls< {"ok":true,"node":{"name":"root","path":["root"],"state":{"ruleSets":[…]},"actions":[{"name":"newGame","node":"root","input":{…}}],"children":[]}}> do newGame {"ruleSet":"official","players":4,"dealer":0,"seed":15,"stream":54}< {"ok":true,"node":{"name":"game","path":["root","game"],"state":{"ruleSet":"official","seed":15,"stream":54,"dealer":0,"turn":1,"turnStage":"draw",…,"pileTop":"6S","pileCount":1,"pileHidden":0,"pileFrozen":false},"actions":[…],"children":[]}}> do take {"seat":1,"method":"naturalAndWild","cards":["6D","2S"]}< {"ok":false,"error":{"kind":"rule","code":"pileFrozen","message":"pileFrozen"}}> do draw {"seat":1}< {"ok":true,"node":{"name":"game",…,"state":{…,"turn":1,"turnStage":"play",…}}}> do lay {"seat":1,"melds":[["AS","AD","AD"]]}> do discard {"seat":1,"card":"KS"}