@chrischall/warapp-mcp 0.0.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +4 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +199 -8
- package/dist/analysis/award.js +159 -0
- package/dist/analysis/bonuses.js +98 -0
- package/dist/analysis/breach.js +62 -0
- package/dist/analysis/card-support.js +329 -0
- package/dist/analysis/card-threats.js +234 -0
- package/dist/analysis/cards-in-effect.js +130 -0
- package/dist/analysis/chains.js +59 -0
- package/dist/analysis/chokepoints.js +140 -0
- package/dist/analysis/combat.js +231 -0
- package/dist/analysis/commander-safety.js +149 -0
- package/dist/analysis/commitments.js +338 -0
- package/dist/analysis/exchange.js +155 -0
- package/dist/analysis/graph.js +82 -0
- package/dist/analysis/guard-off.js +54 -0
- package/dist/analysis/guess.js +351 -0
- package/dist/analysis/headroom.js +241 -0
- package/dist/analysis/hold-diff.js +64 -0
- package/dist/analysis/how-lost.js +130 -0
- package/dist/analysis/index.js +14 -0
- package/dist/analysis/local-deploy.js +159 -0
- package/dist/analysis/lookahead.js +108 -0
- package/dist/analysis/opponent-profile.js +551 -0
- package/dist/analysis/opponents.js +1245 -0
- package/dist/analysis/outlook.js +633 -0
- package/dist/analysis/overrides.js +60 -0
- package/dist/analysis/picks.js +1879 -0
- package/dist/analysis/plan/after-leftover.js +140 -0
- package/dist/analysis/plan/cap-spend.js +242 -0
- package/dist/analysis/plan/captures.js +1195 -0
- package/dist/analysis/plan/commander.js +236 -0
- package/dist/analysis/plan/completed.js +29 -0
- package/dist/analysis/plan/conceded-out.js +131 -0
- package/dist/analysis/plan/estimates.js +715 -0
- package/dist/analysis/plan/guard-off.js +232 -0
- package/dist/analysis/plan/holds.js +1631 -0
- package/dist/analysis/plan/leftover.js +760 -0
- package/dist/analysis/plan/move-order.js +319 -0
- package/dist/analysis/plan/orders.js +317 -0
- package/dist/analysis/plan/relations.js +702 -0
- package/dist/analysis/plan/report.js +672 -0
- package/dist/analysis/plan/shared.js +1218 -0
- package/dist/analysis/plan/stand-still.js +823 -0
- package/dist/analysis/plan/state.js +44 -0
- package/dist/analysis/plan/strike.js +1416 -0
- package/dist/analysis/plan/targets.js +651 -0
- package/dist/analysis/plan/team.js +299 -0
- package/dist/analysis/plan/threats.js +927 -0
- package/dist/analysis/plan/transfers.js +328 -0
- package/dist/analysis/plan/util.js +5 -0
- package/dist/analysis/plan/vacated.js +285 -0
- package/dist/analysis/planner.js +2922 -0
- package/dist/analysis/player-record.js +144 -0
- package/dist/analysis/player.js +268 -0
- package/dist/analysis/profile.js +347 -0
- package/dist/analysis/relations.js +1030 -0
- package/dist/analysis/schedule.js +88 -0
- package/dist/analysis/since-last.js +50 -0
- package/dist/analysis/static-seats.js +71 -0
- package/dist/analysis/stress.js +577 -0
- package/dist/analysis/team-brief.js +151 -0
- package/dist/analysis/tripwire.js +644 -0
- package/dist/analysis/turn-sim.js +259 -0
- package/dist/analysis/whereabouts.js +1109 -0
- package/dist/board.js +105 -0
- package/dist/bundle.js +117959 -36172
- package/dist/cards.js +435 -0
- package/dist/chat-cursor.js +135 -0
- package/dist/chat.js +192 -0
- package/dist/client.js +361 -0
- package/dist/config.js +62 -0
- package/dist/direct/link.js +102 -0
- package/dist/direct/session.js +267 -0
- package/dist/direct/transport.js +424 -0
- package/dist/guess-salt.js +65 -0
- package/dist/hosted.js +24 -0
- package/dist/index.js +33 -0
- package/dist/join-color.js +140 -0
- package/dist/live.js +278 -0
- package/dist/map-stats.js +152 -0
- package/dist/map-store.js +204 -0
- package/dist/move-order.js +141 -0
- package/dist/my-games.js +180 -0
- package/dist/normalize.js +411 -0
- package/dist/open-games.js +537 -0
- package/dist/outlook-log.js +138 -0
- package/dist/path-lock.js +22 -0
- package/dist/pick-list.js +193 -0
- package/dist/player-record-store.js +229 -0
- package/dist/player-states.js +31 -0
- package/dist/profile-store.js +677 -0
- package/dist/protocol/bundle.js +375 -0
- package/dist/protocol/codec.js +556 -0
- package/dist/protocol/decoded.js +12 -0
- package/dist/protocol/interp.js +1904 -0
- package/dist/protocol/methods.js +531 -0
- package/dist/protocol/rpc.js +202 -0
- package/dist/push/listener.js +393 -0
- package/dist/push/packets.js +66 -0
- package/dist/push/socketio.js +333 -0
- package/dist/push/websocket.js +179 -0
- package/dist/redact.js +62 -0
- package/dist/relations-store.js +242 -0
- package/dist/replay.js +215 -0
- package/dist/scalars.js +28 -0
- package/dist/scout.js +346 -0
- package/dist/stats.js +269 -0
- package/dist/strategy/card-clock.js +185 -0
- package/dist/strategy/map-notes.js +128 -0
- package/dist/strategy/notes.js +2168 -0
- package/dist/team-cards.js +84 -0
- package/dist/team-orders.js +150 -0
- package/dist/teams.js +19 -0
- package/dist/tools/award.js +206 -0
- package/dist/tools/begin-turn.js +162 -0
- package/dist/tools/board.js +77 -0
- package/dist/tools/card-advice.js +256 -0
- package/dist/tools/card-effects.js +49 -0
- package/dist/tools/card-plays.js +434 -0
- package/dist/tools/card-support-advice.js +140 -0
- package/dist/tools/chat-inbox.js +146 -0
- package/dist/tools/chat.js +483 -0
- package/dist/tools/check-plan.js +688 -0
- package/dist/tools/commander-check.js +102 -0
- package/dist/tools/commitments.js +216 -0
- package/dist/tools/common.js +143 -0
- package/dist/tools/diplomacy.js +342 -0
- package/dist/tools/game.js +126 -0
- package/dist/tools/guess-view.js +56 -0
- package/dist/tools/healthcheck.js +90 -0
- package/dist/tools/hints.js +34 -0
- package/dist/tools/how-lost.js +154 -0
- package/dist/tools/index.js +142 -0
- package/dist/tools/join-game.js +327 -0
- package/dist/tools/leave-game.js +181 -0
- package/dist/tools/live-context.js +339 -0
- package/dist/tools/live.js +404 -0
- package/dist/tools/map-stats.js +117 -0
- package/dist/tools/map.js +133 -0
- package/dist/tools/my-games.js +123 -0
- package/dist/tools/open-games.js +104 -0
- package/dist/tools/opponents.js +151 -0
- package/dist/tools/order-options.js +135 -0
- package/dist/tools/picks.js +292 -0
- package/dist/tools/profile-hook.js +156 -0
- package/dist/tools/profile-opponents.js +121 -0
- package/dist/tools/profile-reads.js +99 -0
- package/dist/tools/push.js +385 -0
- package/dist/tools/relations.js +611 -0
- package/dist/tools/resolve.js +45 -0
- package/dist/tools/route.js +36 -0
- package/dist/tools/scout.js +87 -0
- package/dist/tools/session.js +163 -0
- package/dist/tools/strategy.js +200 -0
- package/dist/tools/stress-opponents.js +83 -0
- package/dist/tools/surrender.js +240 -0
- package/dist/tools/survival.js +189 -0
- package/dist/tools/team-brief.js +266 -0
- package/dist/tools/team-source.js +222 -0
- package/dist/tools/team.js +182 -0
- package/dist/tools/turn.js +2761 -0
- package/dist/tools/uncommit.js +160 -0
- package/dist/tools/where.js +275 -0
- package/dist/tools/write-kit.js +158 -0
- package/dist/transport-bridge.js +33 -0
- package/dist/trend.js +452 -0
- package/dist/version.js +4 -0
- package/manifest.json +174 -4
- package/mint.yaml +101 -14
- package/package.json +11 -6
- package/server.json +40 -3
- package/skills/warapp-api/SKILL.md +95 -4
- package/skills/warapp-api/references/scout.mjs +348 -0
- package/skills/warapp-api/scripts/warapp.sh +69 -8
- package/skills/warapp-mcp/SKILL.md +969 -21
|
@@ -0,0 +1,2761 @@
|
|
|
1
|
+
// Turn tools: plan a turn from the live board (read-only), and — gated on the
|
|
2
|
+
// user's confirmation — submit one. The plan's `orders` array is the exact
|
|
3
|
+
// input shape of warapp_submit_turn.
|
|
4
|
+
import { CONFIRM_INJECTION_RULE, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { CARD_BLOCKADE, CARD_ORDER_DELAY, CARD_ORDER_PRIORITY, holdsOrderPriority, playsOrderPriority, advisedOrderPriority, CARD_REINFORCEMENT, cardRules, cardTypeByName, cardTypeName, chooseCardPlays, normalizeGuid, cardsToShed, handReadable, isMyCard, readHand, reinforcementArmies, } from '../cards.js';
|
|
7
|
+
import { chargeDeploys, DEFAULT_OFFENSIVE_KILL_RATE, deployPools, expectedKills, specialUnitStrength, winChance, incomeDetail, armyCapPoolsUncertainty, deployCheckUncertainties, overrideUncertainties, neighborsOf, planTurn, planEnemyEstimates, repulsedAttacks, borderGuess, guessSeed, AHEAD_PRESSURE_FACTOR, PRESSURE_FACTOR, symmetricStart, unevenStart, trackGame, trackOpponents, } from '../analysis/index.js';
|
|
8
|
+
import { parseGameId } from '../client.js';
|
|
9
|
+
import { COMMANDER_STRENGTH, luckFraction, straightKills } from '../analysis/combat.js';
|
|
10
|
+
import { guardOffExposure } from '../analysis/guard-off.js';
|
|
11
|
+
import { holdsBelowPlan } from '../analysis/hold-diff.js';
|
|
12
|
+
import { guardCase } from '../analysis/profile.js';
|
|
13
|
+
import { boardStateFromLive, inGameId, playersByInGameId } from '../live.js';
|
|
14
|
+
import { checkMoveOptions, MOVE_MODES } from './order-options.js';
|
|
15
|
+
import { AttackTransferMode, Method, UNVERIFIED_CARD_PLAYS, writeSendOrdersParams, } from '../protocol/methods.js';
|
|
16
|
+
import { SERVER_ERROR_MESSAGES } from '../protocol/rpc.js';
|
|
17
|
+
import { assumedWarning, awardView, firstMoverFor, loadAward, openingThreat } from './award.js';
|
|
18
|
+
import { boardCardsInEffect, CARDS_IN_EFFECT_UNVERIFIED, sanctionMyIncome } from './card-effects.js';
|
|
19
|
+
import { adviseCards, cardGame, cardPieceOption, handOwners, opponentCanHold, opponentReinforcement, TEAM_HAND } from './card-advice.js';
|
|
20
|
+
import { currentTurn, gameIdArg, graphOf, namer, readAnnotations, respond, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedDescription, untrustedText, viewArg, } from './common.js';
|
|
21
|
+
import { lookupMeta, mintMeta } from './hints.js';
|
|
22
|
+
import { chatSummary } from './chat.js';
|
|
23
|
+
import { failureText, loadLiveGame, requireApprovedAccount, writeAccount } from './live-context.js';
|
|
24
|
+
import { BRIDGE_NOTE, playerArg, resolveMe } from './live.js';
|
|
25
|
+
import { guessOrdersOf, guessView } from './guess-view.js';
|
|
26
|
+
import { guessSalt, peekGuessSalt } from '../guess-salt.js';
|
|
27
|
+
import { recordProfile } from './profile-hook.js';
|
|
28
|
+
import { confidentHabits, counterOf, neighboursOf, readOpponents } from './profile-reads.js';
|
|
29
|
+
import { mapOf } from './map.js';
|
|
30
|
+
import { defineGatedWrite, requireMySeat, sendAndVerify } from './write-kit.js';
|
|
31
|
+
import { resolveBonus, resolveTerritory } from './resolve.js';
|
|
32
|
+
import { checkCardFields, newCardPlaySeen, resolveCardTargets, } from './card-plays.js';
|
|
33
|
+
import { boardFromHistory, CACHED_TURNS, readBoardHistory, readCachedOrders, readExpectedIncome, writeBoardCache, writeOrdersCache, } from '../trend.js';
|
|
34
|
+
import { writeGameRecord } from '../replay.js';
|
|
35
|
+
import { gameOutlook } from '../analysis/outlook.js';
|
|
36
|
+
import { neutralizeSeats, seatEndRules, staticSeats } from '../analysis/static-seats.js';
|
|
37
|
+
import { cardArmyCeiling, cardClock } from '../strategy/card-clock.js';
|
|
38
|
+
import { sinceLastTurn } from '../analysis/since-last.js';
|
|
39
|
+
import { recordOutlook } from '../outlook-log.js';
|
|
40
|
+
import { readPickRecord } from '../pick-list.js';
|
|
41
|
+
import { commitmentWarnings } from '../analysis/commitments.js';
|
|
42
|
+
import { planRelationsFrom, truceBreaksIn } from '../analysis/relations.js';
|
|
43
|
+
import { recordBrokenByMe } from './relations.js';
|
|
44
|
+
import { withTeammateOrders } from '../team-orders.js';
|
|
45
|
+
import { claimedCardUses, claimedCardWarning, teamCardClaims, teamCardRoles, teamHandLeft, unclaimedFirst } from '../team-cards.js';
|
|
46
|
+
import { isTeamGame, teammatesOf } from '../teams.js';
|
|
47
|
+
import { readLedger, recordTruceUsage } from '../relations-store.js';
|
|
48
|
+
import { resolveTeams, resolveTeamsFor } from './team-source.js';
|
|
49
|
+
import { stressOpponents } from './stress-opponents.js';
|
|
50
|
+
import { myCommanderTerritory } from '../analysis/commander-safety.js';
|
|
51
|
+
import { commanderCheckOn, guessKeepsCommander } from './commander-check.js';
|
|
52
|
+
import { HEADROOM_COMPACT, headroomView, headroomWarnings, keepTripwires, readTripwires, safeHeadroom, teamsOf, tripwireWarnings, untrustedDeploy } from './survival.js';
|
|
53
|
+
const VIEWS = ['compact', 'full'];
|
|
54
|
+
const GOALS = ['balanced', 'expand', 'complete-bonus', 'defend'];
|
|
55
|
+
/** The only GameFeed state in which turns are played. */
|
|
56
|
+
const TURN_PHASE_STATE = 'Playing';
|
|
57
|
+
const MAX_ORDERS = 500;
|
|
58
|
+
const MAX_FOCUS = 50;
|
|
59
|
+
const MAX_ENEMY_DEPLOY = 10_000;
|
|
60
|
+
/** PLAN-TEAMS C3.3: what `team.sharedBonuses` means, on every plan that has it. */
|
|
61
|
+
const TEAM_SHARED_NOTE = 'One owner per bonus: a bonus pays only the player holding all of it, so the plan never works toward one with a ' +
|
|
62
|
+
"teammate's territory in it. `nearer` is whoever holds the most members ('even' when tied), read from the board at " +
|
|
63
|
+
"the start of the turn; `others` counts the members neither of us holds, a teammate's territory in the fog among them " +
|
|
64
|
+
'(team vision unverified). Advisory: ' +
|
|
65
|
+
'agree in team chat which of you takes each.';
|
|
66
|
+
/** PLAN-TEAMS C3.5: what `team.support` means. */
|
|
67
|
+
const TEAM_SUPPORT_NOTE = "A teammate's border that falls to the threats in view (the plan's own threat model) given the orders they have " +
|
|
68
|
+
"entered — their deploys there in, their orders out of it out, armies moved in left out — where your idle armies beside it " +
|
|
69
|
+
'(what the plan leaves unused beyond what holds your own territory) would make it hold. Advisory: what a plain move ' +
|
|
70
|
+
"onto a teammate's territory does is not yet verified live (V7), so it is never in `orders`, and the teammate's orders " +
|
|
71
|
+
'come from the live board, also unverified (V5). The same idle armies may be counted by a joint capture too.';
|
|
72
|
+
/** PLAN-TEAMS C3.6: what `team.jointCaptures` means. */
|
|
73
|
+
const TEAM_JOINT_NOTE = "A target neither your teammate's entered attack nor yours takes alone, resolved on the turn simulator from those " +
|
|
74
|
+
"attacks only (every other order of the turn left out): yours are the plan's own when it attacks it (`inPlan`), else " +
|
|
75
|
+
'your idle armies beside it. `cases` gives both orders of the two attacks and whether it falls (and to whom), also if ' +
|
|
76
|
+
"its owner first lands its whole deploy estimate there; under a cyclic move order `mustGoFirst` says whose attack must " +
|
|
77
|
+
"run first ('either' when both orders take it). Advisory: never added to `orders`; agree it in team chat. The teammate's " +
|
|
78
|
+
'orders come from the live board (unverified, V5).';
|
|
79
|
+
/** PLAN-TEAMS C3.7: what `cards.team` means. */
|
|
80
|
+
const TEAM_CARDS_NOTE = "Who plays each card of the team hand this turn: a teammate for a card they have already entered a play or discard " +
|
|
81
|
+
"of (so the team never uses one card twice; the plan chooses from the rest), you for a card your orders play or " +
|
|
82
|
+
'discard, nobody for a card held. Read from their entered orders on the live board (unverified, V5); how war.app keys ' +
|
|
83
|
+
"a team's hand is unverified too (V8).";
|
|
84
|
+
const territoryRef = z.union([z.string(), z.number()]);
|
|
85
|
+
const playerRef = z.union([z.string().min(1).max(100), z.number()]);
|
|
86
|
+
const armiesArg = z.coerce.number().int().min(1);
|
|
87
|
+
/** One order of a turn: territories by id or name. */
|
|
88
|
+
const turnOrderArg = z.discriminatedUnion('kind', [
|
|
89
|
+
z.object({
|
|
90
|
+
kind: z.literal('deploy'),
|
|
91
|
+
territory: territoryRef.describe('Territory to deploy on: id or name.'),
|
|
92
|
+
armies: armiesArg.describe('Armies to deploy there.'),
|
|
93
|
+
}),
|
|
94
|
+
z.object({
|
|
95
|
+
kind: z.literal('move'),
|
|
96
|
+
from: territoryRef.describe('Territory the armies leave: id or name.'),
|
|
97
|
+
to: territoryRef.describe('Adjacent territory to attack or transfer into: id or name.'),
|
|
98
|
+
armies: z.coerce
|
|
99
|
+
.number()
|
|
100
|
+
.int()
|
|
101
|
+
.min(0)
|
|
102
|
+
.describe('Armies to send (0 only with `commander`: the commander alone). With `percent`, the percentage 1–100.'),
|
|
103
|
+
mode: z
|
|
104
|
+
.enum(MOVE_MODES)
|
|
105
|
+
.optional()
|
|
106
|
+
.describe('Default "attack-transfer": attacks or transfers by who holds the target when the order runs. "transfer-only" ' +
|
|
107
|
+
'(game setting AllowTransferOnly): does nothing if the target is not yours then — a reinforcement that ' +
|
|
108
|
+
'stays home when the target fell. "attack-only" (AllowAttackOnly): does nothing if the target is yours — e.g. a ' +
|
|
109
|
+
'late order onto your own threatened territory that fires only if it fell.'),
|
|
110
|
+
percent: z
|
|
111
|
+
.boolean()
|
|
112
|
+
.optional()
|
|
113
|
+
.describe('(AllowPercentageAttacks) `armies` is a percentage of what `from` can move when the order runs, so what stays ' +
|
|
114
|
+
'behind scales with the damage taken.'),
|
|
115
|
+
commander: z.boolean().optional().describe('(Commanders games) Take your commander on `from` along.'),
|
|
116
|
+
attack_teammates: z
|
|
117
|
+
.boolean()
|
|
118
|
+
.optional()
|
|
119
|
+
.describe("(Team games) Attack the target even if it is a teammate's, instead of transferring into it."),
|
|
120
|
+
}),
|
|
121
|
+
z.object({
|
|
122
|
+
kind: z.literal('card'),
|
|
123
|
+
card: z
|
|
124
|
+
.string()
|
|
125
|
+
.min(1)
|
|
126
|
+
.max(64)
|
|
127
|
+
.describe('Card to play from your hand: its id (GUID) or its type name, e.g. "Reinforcement".'),
|
|
128
|
+
target: territoryRef
|
|
129
|
+
.optional()
|
|
130
|
+
.describe('Blockade, Emergency Blockade: your territory to blockade. Bomb: a territory next to yours, not yours or a ' +
|
|
131
|
+
"teammate's. Gift: your territory to give away. Reconnaissance: the territory to see. Id or name."),
|
|
132
|
+
player: playerRef
|
|
133
|
+
.optional()
|
|
134
|
+
.describe("Spy: the opponent to see (0 or \"neutral\": the neutral, when the game's Spy card allows it). Sanctions: the player whose " +
|
|
135
|
+
'income it cuts. Gift: who receives `target`. Id or name.'),
|
|
136
|
+
players: z
|
|
137
|
+
.array(playerRef)
|
|
138
|
+
.length(2)
|
|
139
|
+
.optional()
|
|
140
|
+
.describe('Diplomacy: the two players who may not attack each other (usually you and one opponent). Ids or names.'),
|
|
141
|
+
bonus: territoryRef.optional().describe('Surveillance: the bonus to see (id or name).'),
|
|
142
|
+
from: territoryRef.optional().describe('Airlift: your territory the armies leave (id or name).'),
|
|
143
|
+
to: territoryRef.optional().describe("Airlift: your or a teammate's territory they land on (id or name), anywhere on the map."),
|
|
144
|
+
armies: z.coerce
|
|
145
|
+
.number()
|
|
146
|
+
.int()
|
|
147
|
+
.min(0)
|
|
148
|
+
.optional()
|
|
149
|
+
.describe('Airlift: armies to send (at most what stands on `from` after the deploys; 0 only with `commander`: the commander alone).'),
|
|
150
|
+
commander: z
|
|
151
|
+
.boolean()
|
|
152
|
+
.optional()
|
|
153
|
+
.describe('Airlift (Commanders games): take your commander on `from` too — only to a territory of your own.'),
|
|
154
|
+
before: z.coerce
|
|
155
|
+
.number()
|
|
156
|
+
.int()
|
|
157
|
+
.min(1)
|
|
158
|
+
.optional()
|
|
159
|
+
.describe('Order Delay only: the move (1-based, counting the moves of this list in order) the card is written above, ' +
|
|
160
|
+
'so that move and the ones after it wait for the opponents — e.g. `cards.advice.orderDelay.order` from ' +
|
|
161
|
+
'warapp_plan_turn. UNVERIFIED live. Omit (or one past the last move) to write it after every move.'),
|
|
162
|
+
}),
|
|
163
|
+
z.object({
|
|
164
|
+
kind: z.literal('discard'),
|
|
165
|
+
card: z
|
|
166
|
+
.string()
|
|
167
|
+
.min(1)
|
|
168
|
+
.max(64)
|
|
169
|
+
.describe('Card to discard from your hand (any type): its id (GUID) or its type name, e.g. "Order Delay".'),
|
|
170
|
+
}),
|
|
171
|
+
]);
|
|
172
|
+
/** A whole turn's orders, as warapp_plan_turn returns them and warapp_submit_turn takes them. */
|
|
173
|
+
/** Orders for a turn; empty commits a turn with no orders (valid only when the income to deploy is 0). */
|
|
174
|
+
export const turnOrdersArg = z.array(turnOrderArg).max(MAX_ORDERS);
|
|
175
|
+
/** The planner's view of the game settings. */
|
|
176
|
+
export function plannerSettings(s) {
|
|
177
|
+
if (!s)
|
|
178
|
+
return {};
|
|
179
|
+
const out = {};
|
|
180
|
+
if (s.offensiveKillRate !== undefined)
|
|
181
|
+
out.offensiveKillRate = s.offensiveKillRate;
|
|
182
|
+
if (s.defensiveKillRate !== undefined)
|
|
183
|
+
out.defensiveKillRate = s.defensiveKillRate;
|
|
184
|
+
if (s.luckModifier !== undefined)
|
|
185
|
+
out.luckModifier = s.luckModifier;
|
|
186
|
+
if (s.roundingMode !== undefined)
|
|
187
|
+
out.roundingMode = s.roundingMode;
|
|
188
|
+
if (s.oneArmyStandsGuard !== undefined)
|
|
189
|
+
out.oneArmyStandsGuard = s.oneArmyStandsGuard;
|
|
190
|
+
if (s.multiAttack !== undefined)
|
|
191
|
+
out.multiAttack = s.multiAttack;
|
|
192
|
+
if (s.bonusArmyPer !== undefined && s.bonusArmyPer > 0)
|
|
193
|
+
out.bonusArmyPer = s.bonusArmyPer;
|
|
194
|
+
if (s.minimumArmyBonus !== undefined)
|
|
195
|
+
out.baseIncome = s.minimumArmyBonus;
|
|
196
|
+
if (s.localDeployments)
|
|
197
|
+
out.localDeployments = true;
|
|
198
|
+
if (s.noSplit)
|
|
199
|
+
out.noSplit = true;
|
|
200
|
+
if (s.armyCap !== undefined && s.armyCap !== null && s.armyCap > 0)
|
|
201
|
+
out.armyCap = s.armyCap;
|
|
202
|
+
if (s.wastelands && s.wastelands.count > 0)
|
|
203
|
+
out.wastelands = { ...s.wastelands };
|
|
204
|
+
// #271 review: the first turn an opponent may play a Bomb (a bomb reads as a failed attack on my hold).
|
|
205
|
+
const bombFrom = cardClock(s)?.cards.find((c) => c.card === 'Bomb')?.firstPlayableTurn.fastest;
|
|
206
|
+
if (bombFrom !== undefined && bombFrom !== null)
|
|
207
|
+
out.bombFrom = bombFrom;
|
|
208
|
+
// AllowTransferOnly is deliberately not mapped: it toggles the per-order
|
|
209
|
+
// "transfer only" mode, while every planned move is sent as AttackTransfer
|
|
210
|
+
// (mode 3), which transfers between my own territories in any game. The
|
|
211
|
+
// per-order options (#165) are the caller's to set on warapp_submit_turn.
|
|
212
|
+
return out;
|
|
213
|
+
}
|
|
214
|
+
export { currentTurn, turnsCompleted } from './common.js';
|
|
215
|
+
/** My teammates' GameFeed ids (empty outside a team game; GameFeed's team field is unverified). */
|
|
216
|
+
export function friendsOf(players, me) {
|
|
217
|
+
return new Set(teammatesOf(players, me).map((p) => p.id));
|
|
218
|
+
}
|
|
219
|
+
/** Throw unless the game is in a turn phase. */
|
|
220
|
+
export function requireTurnPhase(game) {
|
|
221
|
+
if (game.state === TURN_PHASE_STATE)
|
|
222
|
+
return;
|
|
223
|
+
throw new McpToolError(`Game ${game.id} is not in a turn phase (game state: ${game.state}).`, {
|
|
224
|
+
hint: game.state === 'DistributingTerritories'
|
|
225
|
+
? 'Territories are still being picked: use warapp_get_live_board and warapp_submit_picks.'
|
|
226
|
+
: 'Turns are planned only while the game is being played.',
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
/** Throw unless my seat is still `Playing` (#130): an eliminated, booted or surrendered seat has no turn. */
|
|
230
|
+
export function requirePlayingSeat(game, me) {
|
|
231
|
+
if (me.state === undefined || me.state === 'Playing')
|
|
232
|
+
return;
|
|
233
|
+
throw new McpToolError(`${untrustedText(me.name)} (${me.id}) is no longer playing in game ${game.id} (state: ${me.state}), so there is no turn to play.`, {
|
|
234
|
+
hint: 'warapp_get_game shows each player\'s state.',
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
/** What to say when cards are in play but my hand could not be read (#130). */
|
|
238
|
+
const UNREADABLE_HAND = 'Your hand could not be read from the live board (no player entry for you), so the cards shown as none may be ' +
|
|
239
|
+
'wrong: check the hand in the game — war.app refuses a commit while you hold more cards than the limit (error 51).';
|
|
240
|
+
/** A territory as a preview shows it: its map-maker name delimited. */
|
|
241
|
+
const shownPlace = (x) => ({ id: x.id, name: untrustedText(x.name) });
|
|
242
|
+
/** An order as the preview shows it: every territory name delimited. */
|
|
243
|
+
function shownOrder(o) {
|
|
244
|
+
const out = { ...o };
|
|
245
|
+
for (const k of ['target', 'territory', 'from', 'to', 'bonus', 'player']) {
|
|
246
|
+
const place = o[k];
|
|
247
|
+
if (place)
|
|
248
|
+
out[k] = shownPlace(place);
|
|
249
|
+
}
|
|
250
|
+
if (o.players)
|
|
251
|
+
out.players = o.players.map(shownPlace);
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* How to read back an Order Delay placed among the moves (#186) — a position no live commit has
|
|
256
|
+
* used yet. Error 10 on the commit would mean it is not allowed there; accepted, the card leaves
|
|
257
|
+
* the hand, and the turn's replay shows whether the moves after it ran after the opponents'.
|
|
258
|
+
*/
|
|
259
|
+
export function orderDelayCheck(at) {
|
|
260
|
+
// Two cards above the same move are one position: name each once, in move order.
|
|
261
|
+
const moves = [...new Set(at)].sort((a, b) => a - b);
|
|
262
|
+
return (`The Order Delay${at.length > 1 ? 's were' : ' was'} placed above move${moves.length > 1 ? 's' : ''} ${moves.join(' and ')}, a position not yet verified live. war.app did not refuse it ` +
|
|
263
|
+
'with error 10 (OrdersInIncorrectOrder). Once the turn resolves, check: the card is gone ' +
|
|
264
|
+
"from your hand (warapp_plan_turn's `cards.hand`, or a played Order Delay in the turn's replay), and in the game's replay " +
|
|
265
|
+
"of this turn your moves from that one on ran after the opponents' attacks instead of alternating with them. Report " +
|
|
266
|
+
'what you see, so docs/WEB-PROTOCOL.md can mark the placement verified.');
|
|
267
|
+
}
|
|
268
|
+
/** A targeted card play's targets as the preview and the result name them (names raw here; {@link shownOrder} delimits them). */
|
|
269
|
+
function namedTargets(t) {
|
|
270
|
+
const player = (p) => ({ id: p.id, name: p.name });
|
|
271
|
+
return {
|
|
272
|
+
...(t.territory ? { target: t.territory } : {}),
|
|
273
|
+
...(t.player ? { player: player(t.player) } : {}),
|
|
274
|
+
...(t.players ? { players: t.players.map(player) } : {}),
|
|
275
|
+
...(t.bonus ? { bonus: t.bonus } : {}),
|
|
276
|
+
...(t.from ? { from: t.from } : {}),
|
|
277
|
+
...(t.to ? { to: t.to } : {}),
|
|
278
|
+
...(t.armies !== undefined ? { armies: t.armies } : {}),
|
|
279
|
+
...(t.commander ? { commander: true } : {}),
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
/** The preview's warning for a targeted card play (PLAN-TEAMS part D): its encoding is not verified live (V9). */
|
|
283
|
+
export function unverifiedCardWarning(cards) {
|
|
284
|
+
return (`UNVERIFIED encoding: the ${cards.join(', ')} card play${cards.length > 1 ? 's are' : ' is'} written as the war.app client's ` +
|
|
285
|
+
'own writer does (read from its code), but no commit carrying one has been sent yet. If war.app refuses the orders, nothing ' +
|
|
286
|
+
'is committed: play the card in the game client instead and report the error.');
|
|
287
|
+
}
|
|
288
|
+
/** How to read back a targeted card play (V9) once sent. */
|
|
289
|
+
export function cardPlayCheck(cards) {
|
|
290
|
+
return (`The ${cards.join(', ')} card play${cards.length > 1 ? 's were' : ' was'} sent with an encoding not yet verified live, and war.app ` +
|
|
291
|
+
"did not refuse it. Once the turn resolves, check that the card left your hand (warapp_plan_turn's `cards.hand`) and did what " +
|
|
292
|
+
"it should in the turn's replay (a Gift's territory changed owner, an Airlift's armies moved, Diplomacy or Sanctions shows " +
|
|
293
|
+
'among the cards in effect), and report what you see so docs/WEB-PROTOCOL.md can mark it verified.');
|
|
294
|
+
}
|
|
295
|
+
/** war.app's error 10 on a turn with an Order Delay placed among the moves (#186): the position is refused. */
|
|
296
|
+
function orderDelayRefused(e) {
|
|
297
|
+
return new McpToolError(`war.app refused the orders with error 10 (OrdersInIncorrectOrder): an Order Delay placed among the moves is not ` +
|
|
298
|
+
`accepted there (${failureText(e)}). Nothing was committed.`, { hint: 'Resend without `before` on the Order Delay (it is then written after every move), or play the card in the game client.' });
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* war.app's error 11 (deploys ≠ its income), with a hint naming the modelled
|
|
302
|
+
* number. The live board carries no income figure — war.app's client computes it
|
|
303
|
+
* from the standing — so its own number is the "armies per turn" the game shows.
|
|
304
|
+
*/
|
|
305
|
+
function incomeRefused(e, income, given = false) {
|
|
306
|
+
return new McpToolError(e.message, {
|
|
307
|
+
kind: 'unknown',
|
|
308
|
+
cause: e,
|
|
309
|
+
hint: `The ${given ? 'income given was' : 'modelled income was'} ${income}, and war.app counts differently this turn. ` +
|
|
310
|
+
'Nothing was committed: read the ' +
|
|
311
|
+
'"armies per turn" the game shows (the deploy panel), deploy exactly that, and resend with it as `income` — ' +
|
|
312
|
+
'the deploy-total check then uses that number instead of the model.',
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
/** A territory in an error: its map-maker name delimited (errors are outside the untrusted envelope). */
|
|
316
|
+
const label = (t) => `${untrustedText(t.name)} (${t.id})`;
|
|
317
|
+
/** #165: with mods on, every plan says the rules it assumes may not hold. */
|
|
318
|
+
export function modsWarning(s) {
|
|
319
|
+
if (!s?.mods)
|
|
320
|
+
return [];
|
|
321
|
+
const what = s.mods > 0 ? `${s.mods} mod${s.mods === 1 ? '' : 's'}` : 'mods';
|
|
322
|
+
return [
|
|
323
|
+
`This game runs ${what}: a mod can change the rules (combat, income, orders, cards, special units), so the rules ` +
|
|
324
|
+
'this plan assumes may not hold. Check the mods in the game settings.',
|
|
325
|
+
];
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* #167: a commerce game pays gold and lets players buy armies and cities; the planner plans income as
|
|
329
|
+
* armies only. Said whenever the feed's `Commerce` object carries settings (the shape a commerce
|
|
330
|
+
* game sends is unverified: a plain game sends `{}`).
|
|
331
|
+
*/
|
|
332
|
+
export function commerceWarning(s) {
|
|
333
|
+
if (!s?.commerce)
|
|
334
|
+
return [];
|
|
335
|
+
return [
|
|
336
|
+
'This looks like a commerce game (its Commerce settings are not empty): the plan models income as armies only — ' +
|
|
337
|
+
'it does not model gold, buying armies or cities. Check what gold buys before following it.',
|
|
338
|
+
];
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* #165: One Army Must Stand Guard off. My territories the orders leave at 0 beside an enemy or the
|
|
342
|
+
* fog fall to any single army; an enemy territory at 0 beside me breaks its owner's bonus to a
|
|
343
|
+
* one-army attack. Empty unless the guard is off.
|
|
344
|
+
*/
|
|
345
|
+
export function guardOffWarnings(graph, map, board, me, friends, settings, deploys, moves) {
|
|
346
|
+
if (settings?.oneArmyStandsGuard !== false)
|
|
347
|
+
return [];
|
|
348
|
+
const r = guardOffExposure({ graph, board, me, friends, deploys, moves });
|
|
349
|
+
const name = namer(map);
|
|
350
|
+
const out = [];
|
|
351
|
+
if (r.emptied.length) {
|
|
352
|
+
out.push(`One Army Must Stand Guard is off: these orders leave ${r.emptied.map((id) => label(name(id))).join(', ')} at 0 armies ` +
|
|
353
|
+
'beside an enemy or the fog, and any single army takes an empty territory. Keep an army there if it matters.');
|
|
354
|
+
}
|
|
355
|
+
for (const b of r.breaks) {
|
|
356
|
+
const bonus = map.bonuses.find((x) => x.id === b.bonusId);
|
|
357
|
+
out.push(`One Army Must Stand Guard is off: ${label(name(b.territoryId))} stands at 0, so a one-army attack from ` +
|
|
358
|
+
`${label(name(b.from))} takes it and breaks player ${b.playerId}'s bonus ${untrustedText(bonus?.name ?? String(b.bonusId))} ` +
|
|
359
|
+
`(${b.bonusId}, +${b.value}). These orders do not attack it.`);
|
|
360
|
+
}
|
|
361
|
+
return out;
|
|
362
|
+
}
|
|
363
|
+
/** plan_turn's note when its income counts Reinforcement plays: the deploys need the card orders (#85). */
|
|
364
|
+
function cardIncomeNote(income, cardArmies) {
|
|
365
|
+
return (`Income ${income} includes ${cardArmies} armies from the Reinforcement card play in \`orders\` (${income - cardArmies} ` +
|
|
366
|
+
`from the board): submit the card order with the deploys, or deploy ${income - cardArmies} without it — ` +
|
|
367
|
+
'warapp_submit_turn refuses any other total.');
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* When the surplus deployed is what unplayed Reinforcement cards would add, say so: the total
|
|
371
|
+
* counts a card the orders do not play — warapp_plan_turn's income includes the armies of the
|
|
372
|
+
* Reinforcement plays in its `orders`, so dropping those orders leaves the deploys too high (#85).
|
|
373
|
+
*/
|
|
374
|
+
function unplayedHint(surplus, unplayed) {
|
|
375
|
+
if (surplus <= 0 || !unplayed.length)
|
|
376
|
+
return '';
|
|
377
|
+
const all = unplayed.reduce((s, c) => s + c.armies, 0);
|
|
378
|
+
const one = unplayed.find((c) => c.armies === surplus);
|
|
379
|
+
const cards = one ? [one] : all === surplus ? unplayed : [];
|
|
380
|
+
if (!cards.length)
|
|
381
|
+
return '';
|
|
382
|
+
const what = cards.map((c) => `Reinforcement card ${c.id} (${c.armies} armies)`).join(', ');
|
|
383
|
+
return (` The extra ${surplus} match the ${what}, which these orders have not played: add ` +
|
|
384
|
+
`${cards.length === 1 ? 'its card order' : 'their card orders'} (as warapp_plan_turn's \`orders\` do) or deploy ${surplus} fewer.`);
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Validate resolved orders against the live board and income; throws a clear
|
|
388
|
+
* refusal on the first problem. A deploy total that differs from the income is
|
|
389
|
+
* refused only when the income model is certain: with `incomeUncertain` reasons
|
|
390
|
+
* (see `deployCheckUncertainties`) it is returned as a warning instead, and war.app
|
|
391
|
+
* itself has the last word (error 11). The Local Deployment check is likewise a
|
|
392
|
+
* warning when `poolsUncertain` gives reasons (overridden bonuses, see
|
|
393
|
+
* `overrideUncertainties`).
|
|
394
|
+
*/
|
|
395
|
+
export function validateTurn(args) {
|
|
396
|
+
const warnings = [];
|
|
397
|
+
const { map, board, myInGameId, income, deploys, moves } = args;
|
|
398
|
+
const graph = graphOf(map);
|
|
399
|
+
const standing = new Map(board.map((t) => [t.territoryId, t]));
|
|
400
|
+
const mine = (id) => {
|
|
401
|
+
const t = standing.get(id);
|
|
402
|
+
return t !== undefined && !t.fogged && t.owner === myInGameId;
|
|
403
|
+
};
|
|
404
|
+
// Under Multi-Attack a territory not mine at the start may move on once a move earlier in the list went in.
|
|
405
|
+
const chained = new Set();
|
|
406
|
+
if (args.multiAttack) {
|
|
407
|
+
const reached = new Set();
|
|
408
|
+
const movedOut = new Set();
|
|
409
|
+
for (const m of moves) {
|
|
410
|
+
if (!mine(m.from.id) && !movedOut.has(m.from.id) && reached.has(m.from.id))
|
|
411
|
+
chained.add(m.from.id);
|
|
412
|
+
movedOut.add(m.from.id);
|
|
413
|
+
reached.add(m.to.id);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
// Deploys land before any attack, so only a move's source may be a territory captured earlier in the list.
|
|
417
|
+
const notMine = [
|
|
418
|
+
...deploys.map((d) => d.territory).filter((t) => !mine(t.id)),
|
|
419
|
+
...moves.map((m) => m.from).filter((t) => !mine(t.id) && !chained.has(t.id)),
|
|
420
|
+
];
|
|
421
|
+
if (notMine.length) {
|
|
422
|
+
const unique = [...new Map(notMine.map((t) => [t.id, t])).values()];
|
|
423
|
+
throw new McpToolError(`These territories are not yours at the start of this turn: ${unique.map(label).join(', ')}.`, {
|
|
424
|
+
hint: 'Deploy on, and move from, only territories you hold on the live board (warapp_get_live_board).',
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
const pairs = new Set();
|
|
428
|
+
for (const m of moves) {
|
|
429
|
+
if (!neighborsOf(graph, m.from.id).includes(m.to.id)) {
|
|
430
|
+
throw new McpToolError(`${label(m.from)} does not border ${label(m.to)}.`, {
|
|
431
|
+
hint: 'A move goes to an adjacent territory; reach further over several turns.',
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
const key = `${m.from.id}>${m.to.id}`;
|
|
435
|
+
if (pairs.has(key)) {
|
|
436
|
+
throw new McpToolError(`The move ${label(m.from)} → ${label(m.to)} is listed twice.`, {
|
|
437
|
+
hint: 'Combine them into one move with the total armies.',
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
pairs.add(key);
|
|
441
|
+
}
|
|
442
|
+
if (args.noSplit) {
|
|
443
|
+
const bySource = new Map();
|
|
444
|
+
for (const m of moves) {
|
|
445
|
+
const o = bySource.get(m.from.id) ?? { from: m.from, to: [] };
|
|
446
|
+
o.to.push(m.to);
|
|
447
|
+
bySource.set(m.from.id, o);
|
|
448
|
+
}
|
|
449
|
+
const split = [...bySource.values()].find((o) => o.to.length > 1);
|
|
450
|
+
if (split) {
|
|
451
|
+
throw new McpToolError(`No-Split: ${label(split.from)} issues ${split.to.length} attacks/transfers (to ${split.to.map(label).join(', ')}), ` +
|
|
452
|
+
'but this game allows one per territory.', {
|
|
453
|
+
hint: 'This game uses No-Split: send at most one attack or transfer from each territory each turn; keep the ' +
|
|
454
|
+
'best one and drop the others — it moves the whole stack.',
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
const deployed = deploys.reduce((s, d) => s + d.armies, 0);
|
|
459
|
+
if (deployed !== income && args.incomeUncertain?.length) {
|
|
460
|
+
warnings.push(`These orders deploy ${deployed} armies, but the modelled income is ${income} this turn. The model may be off ` +
|
|
461
|
+
`(${args.incomeUncertain.join(' ')}), so they are not refused here: check the "armies per turn" the game ` +
|
|
462
|
+
'shows — war.app refuses any other total (error 11).');
|
|
463
|
+
}
|
|
464
|
+
else if (deployed !== income) {
|
|
465
|
+
throw new McpToolError(`These orders deploy ${deployed} armies, but your income is ${income} this turn.`, {
|
|
466
|
+
hint: `Deploy exactly ${income} armies — war.app refuses any other total (error 11).${unplayedHint(deployed - income, args.unplayedReinforcements ?? [])}`,
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
const deployedOn = new Map();
|
|
470
|
+
for (const d of deploys)
|
|
471
|
+
deployedOn.set(d.territory.id, (deployedOn.get(d.territory.id) ?? 0) + d.armies);
|
|
472
|
+
// What can move from a territory when the moves start: its armies and deploys, less what it airlifts out.
|
|
473
|
+
// Armies airlifted in cannot move again that turn (the wiki's Airlift Card), so they add nothing.
|
|
474
|
+
const airlifted = new Map();
|
|
475
|
+
for (const a of args.airlifts ?? [])
|
|
476
|
+
airlifted.set(a.from, (airlifted.get(a.from) ?? 0) - a.armies);
|
|
477
|
+
const atMoves = (id) => (standing.get(id)?.armies ?? 0) + (deployedOn.get(id) ?? 0) + (airlifted.get(id) ?? 0);
|
|
478
|
+
if (args.localDeployments) {
|
|
479
|
+
const held = new Set(board.filter((t) => mine(t.territoryId)).map((t) => t.territoryId));
|
|
480
|
+
const pools = deployPools(graph, held, income);
|
|
481
|
+
const use = chargeDeploys(pools, deployedOn);
|
|
482
|
+
if (use.anywhereUsed > pools.anywhere) {
|
|
483
|
+
const short = pools.bonuses
|
|
484
|
+
.map((p) => ({ p, used: use.used.get(p.bonusId) ?? 0 }))
|
|
485
|
+
.filter(({ p, used }) => used < p.value);
|
|
486
|
+
// The refusal names each bonus (delimited); the preview warning, which sits beside
|
|
487
|
+
// the confirmToken, names bonuses by id only.
|
|
488
|
+
const shortfall = (named) => short
|
|
489
|
+
.map(({ p, used }) => `${named ? `${untrustedText(p.name)} ` : ''}(bonus ${p.bonusId}): +${p.value} earned, only ${used} deployed inside it`)
|
|
490
|
+
.join('; ');
|
|
491
|
+
const overspend = `Local Deployment: these orders deploy ${use.anywhereUsed} armies outside the held bonuses' own pools, but only ` +
|
|
492
|
+
`${pools.anywhere} may go anywhere this turn (${use.anywhereUsed - pools.anywhere} too many).`;
|
|
493
|
+
const problem = `${overspend} ${shortfall(true)}.`;
|
|
494
|
+
if (args.poolsUncertain?.length) {
|
|
495
|
+
warnings.push(`${overspend} ${shortfall(false)}. The modelled pools may be off (${args.poolsUncertain.join(' ')}), so they are not refused here: ` +
|
|
496
|
+
"check the game's deploy panel — war.app refuses deploys outside a bonus's own pool.");
|
|
497
|
+
}
|
|
498
|
+
else {
|
|
499
|
+
throw new McpToolError(problem, {
|
|
500
|
+
hint: "This game uses Local Deployment: deploy each held bonus's armies on that bonus's own territories; only " +
|
|
501
|
+
'the rest of your income (base income and card armies) may go anywhere.',
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
// Walk the moves in order: each source's total sent so far against its armies, its deploys and,
|
|
507
|
+
// under Multi-Attack, every army moved in earlier in the list (an attack, a transfer in, then
|
|
508
|
+
// another attack is fine). Without Multi-Attack, armies moved in do not move on this turn.
|
|
509
|
+
const sent = new Map();
|
|
510
|
+
const inflow = new Map();
|
|
511
|
+
let over;
|
|
512
|
+
for (const m of moves) {
|
|
513
|
+
const start = chained.has(m.from.id) ? 0 : atMoves(m.from.id);
|
|
514
|
+
const max = start + (inflow.get(m.from.id) ?? 0) - (args.guard ? 1 : 0);
|
|
515
|
+
// A percentage order takes a share of what is left when it runs: it never over-sends, and what
|
|
516
|
+
// it moves on is at most what the source could move (#165).
|
|
517
|
+
const moved = m.percent ? Math.max(0, max - (sent.get(m.from.id) ?? 0)) : m.armies;
|
|
518
|
+
if (!m.percent) {
|
|
519
|
+
const armies = (sent.get(m.from.id) ?? 0) + m.armies;
|
|
520
|
+
sent.set(m.from.id, armies);
|
|
521
|
+
if (armies > max && !over)
|
|
522
|
+
over = { from: m.from, armies, max };
|
|
523
|
+
}
|
|
524
|
+
if (args.multiAttack)
|
|
525
|
+
inflow.set(m.to.id, (inflow.get(m.to.id) ?? 0) + moved);
|
|
526
|
+
}
|
|
527
|
+
if (over) {
|
|
528
|
+
const { from, armies, max } = over;
|
|
529
|
+
throw new McpToolError(`These orders send ${armies} armies from ${label(from)}, which can send at most ${max} this turn` +
|
|
530
|
+
`${args.guard ? ' (one army stands guard)' : ''}` +
|
|
531
|
+
`${airlifted.has(from.id) ? ', counting this turn\'s Airlift' : ''}` +
|
|
532
|
+
`${inflow.has(from.id) ? '; that counts every army moved in earlier in the list, an upper bound: an attack\'s survivors are fewer' : ''}.`, { hint: 'A territory sends at most its armies plus what is deployed there this turn.' });
|
|
533
|
+
}
|
|
534
|
+
// No-Split moves the whole stack (#124: the wiki, and a live turn that left every source at 0):
|
|
535
|
+
// an order for fewer armies still sends them all, so say what will actually move. A source captured
|
|
536
|
+
// earlier in the list (Multi-Attack) is left out: the armies standing there at the start were the
|
|
537
|
+
// defenders', and what moves on is the capture's survivors, which this cannot size.
|
|
538
|
+
if (args.noSplit) {
|
|
539
|
+
for (const m of moves) {
|
|
540
|
+
if (chained.has(m.from.id))
|
|
541
|
+
continue;
|
|
542
|
+
const max = atMoves(m.from.id) - (args.guard ? 1 : 0);
|
|
543
|
+
if (m.percent ? m.armies < 100 : m.armies < max)
|
|
544
|
+
warnings.push(`No-Split: ${label(m.from)} → ${label(m.to)} sends ${m.percent ? `${m.armies}%` : m.armies}, but this game moves the whole stack: war.app ` +
|
|
545
|
+
`sends all ${max} (its armies plus this turn's deploys there, less the guard), and nothing stays behind to hold ` +
|
|
546
|
+
`${label(m.from)}. Size the order for the whole stack, or move nothing from it.`);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
return { warnings };
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Each move into a territory that is not mine and is visible, sized against what stands there
|
|
553
|
+
* now: a transfer (to my own or a teammate's territory) and a fogged target are left out. Several
|
|
554
|
+
* moves into one target (a multi-source capture, #17) are judged in the order listed, each against
|
|
555
|
+
* what the earlier ones leave (#250), as the planner's `multiSourceCaptures` are built: a softener
|
|
556
|
+
* that fails by design is not flagged when a later leg captures. Taken as one stack they could
|
|
557
|
+
* read wrong either way: 6, 8 and 18 into 7 at 20% kill 1 + 2 + 4 = 7 in turn, but round(6.4) = 6
|
|
558
|
+
* together.
|
|
559
|
+
*/
|
|
560
|
+
export function attackSizes(board, myInGameId, moves, settings, teammates = new Set()) {
|
|
561
|
+
const standing = new Map(board.map((t) => [t.territoryId, t]));
|
|
562
|
+
const off = settings.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
|
|
563
|
+
// A Transfer Only order never attacks; one that attacks teammates attacks a teammate's territory (#165).
|
|
564
|
+
const attacks = moves.filter((m) => {
|
|
565
|
+
const t = standing.get(m.to.id);
|
|
566
|
+
return (m.mode !== 'transfer-only' &&
|
|
567
|
+
t !== undefined &&
|
|
568
|
+
!t.fogged &&
|
|
569
|
+
t.owner !== myInGameId &&
|
|
570
|
+
(m.attackTeammates === true || !teammates.has(t.owner)));
|
|
571
|
+
});
|
|
572
|
+
/** Its attackers as they fight: a percentage order's estimate, my commander as 7 more. */
|
|
573
|
+
const power = (m) => (m.percent ? (m.estimate ?? 0) : m.armies) + (m.commander ? COMMANDER_STRENGTH : 0);
|
|
574
|
+
const together = new Map();
|
|
575
|
+
for (const m of attacks) {
|
|
576
|
+
const g = together.get(m.to.id) ?? { attacks: 0, armies: 0 };
|
|
577
|
+
g.attacks += 1;
|
|
578
|
+
g.armies += power(m);
|
|
579
|
+
together.set(m.to.id, g);
|
|
580
|
+
}
|
|
581
|
+
const combat = {
|
|
582
|
+
...(settings.offensiveKillRate !== undefined ? { offensiveKillRate: settings.offensiveKillRate } : {}),
|
|
583
|
+
...(settings.defensiveKillRate !== undefined ? { defensiveKillRate: settings.defensiveKillRate } : {}),
|
|
584
|
+
...(settings.luckModifier !== undefined ? { luck: settings.luckModifier } : {}),
|
|
585
|
+
...(settings.roundingMode !== undefined ? { rounding: settings.roundingMode } : {}),
|
|
586
|
+
};
|
|
587
|
+
const sequences = new Map();
|
|
588
|
+
for (const id of together.keys()) {
|
|
589
|
+
if (together.get(id).attacks < 2)
|
|
590
|
+
continue;
|
|
591
|
+
const t = standing.get(id);
|
|
592
|
+
sequences.set(id, attackSequence(t.armies ?? 0, specialUnitStrength(t.specialUnits), attacks.filter((m) => m.to.id === id).map(power), combat));
|
|
593
|
+
}
|
|
594
|
+
const seen = new Map();
|
|
595
|
+
return attacks.map((m) => {
|
|
596
|
+
const t = standing.get(m.to.id);
|
|
597
|
+
const group = together.get(m.to.id);
|
|
598
|
+
const defenders = (t.armies ?? 0) + specialUnitStrength(t.specialUnits);
|
|
599
|
+
const sequence = sequences.get(m.to.id);
|
|
600
|
+
const at = seen.get(m.to.id) ?? 0;
|
|
601
|
+
seen.set(m.to.id, at + 1);
|
|
602
|
+
const chance = sequence ? sequence.chance : winChance(power(m), defenders, combat);
|
|
603
|
+
return {
|
|
604
|
+
from: m.from,
|
|
605
|
+
to: m.to,
|
|
606
|
+
armies: m.percent ? (m.estimate ?? 0) : m.armies,
|
|
607
|
+
...(m.percent ? { percent: m.armies } : {}),
|
|
608
|
+
...(m.commander ? { commander: true } : {}),
|
|
609
|
+
defenders,
|
|
610
|
+
expectedKills: Math.round(expectedKills(power(m), off) * 10) / 10,
|
|
611
|
+
winChance: Math.round(chance * 1000) / 1000,
|
|
612
|
+
...(group.attacks > 1 ? { combined: { ...group } } : {}),
|
|
613
|
+
...(sequence ? { facing: sequence.facing[at] } : {}),
|
|
614
|
+
...(sequence && sequence.captor !== undefined && at < sequence.captor ? { softener: true } : {}),
|
|
615
|
+
...(chance === 0 ? { cannotCapture: true } : {}),
|
|
616
|
+
};
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* The submit preview's warning for attacks that cannot capture, or `undefined` when none: a lone
|
|
621
|
+
* attack as before, and attacks on one target together, run in the order listed (#250) — only
|
|
622
|
+
* when even the last of them fails against what the earlier ones leave.
|
|
623
|
+
*/
|
|
624
|
+
export function hopelessAttackWarning(attacks, label) {
|
|
625
|
+
const hopeless = attacks.filter((a) => a.cannotCapture);
|
|
626
|
+
if (!hopeless.length)
|
|
627
|
+
return undefined;
|
|
628
|
+
const lone = hopeless.filter((a) => !a.combined);
|
|
629
|
+
const parts = [];
|
|
630
|
+
if (lone.length)
|
|
631
|
+
parts.push(`${lone.map((a) => `${label(a.from)} → ${label(a.to)}`).join(', ')}: ${lone.length === 1 ? 'this attack' : 'these attacks'} ` +
|
|
632
|
+
"cannot capture against the armies there now at this game's kill rates (see `attacks`).");
|
|
633
|
+
const targets = [...new Set(hopeless.filter((a) => a.combined).map((a) => a.to.id))];
|
|
634
|
+
for (const id of targets) {
|
|
635
|
+
const legs = hopeless.filter((a) => a.combined && a.to.id === id);
|
|
636
|
+
const to = legs[0].to;
|
|
637
|
+
parts.push(`${legs.map((a) => `${label(a.from)} (${a.armies})`).join(', then ')} → ${label(to)}: run in the order listed, each ` +
|
|
638
|
+
`against what the earlier ones leave (the first ones only wear it down), these ${legs.length} attacks ` +
|
|
639
|
+
`cannot capture the ${legs[0].defenders} there now at this game's kill rates (see \`attacks\`: \`facing\`).`);
|
|
640
|
+
}
|
|
641
|
+
return parts.join(' ');
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* Attacks of `powers` armies into `armies` defenders (plus special units fighting as `units`)
|
|
645
|
+
* run one after another: a failed attack kills its share — every defender's army before a
|
|
646
|
+
* commander's strength, which falls only whole — and an attack that wipes out both sides leaves
|
|
647
|
+
* one defender (`turn-sim`'s rule). Exact at 0% luck under straight rounding, as the planner's
|
|
648
|
+
* combined captures (rule 3a) are; otherwise each failed attack kills its expected share and the
|
|
649
|
+
* chance is 1 − Π(1 − each attack's chance against what it meets) over the attacks up to the first
|
|
650
|
+
* one likely to capture (chance ≥ 0.5). The figure is an approximation, not a bound either way: the
|
|
651
|
+
* attacks after the likely captor are left out (what they would meet were it to fail is unknown),
|
|
652
|
+
* which errs low, while each later leg's chance is taken against the expected survivors of the
|
|
653
|
+
* earlier legs — though those legs count only when they fail, and a failed attack kills less than
|
|
654
|
+
* its expected share — which errs high. At the expectation the target is mine after the captor and
|
|
655
|
+
* the later attacks are transfers (facing 0), as in an exact run.
|
|
656
|
+
*/
|
|
657
|
+
function attackSequence(armies, units, powers, combat) {
|
|
658
|
+
const off = combat.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
|
|
659
|
+
const exact = luckFraction(combat.luck) === 0 && combat.rounding !== 'WeightedRandom';
|
|
660
|
+
let left = armies;
|
|
661
|
+
let strength = units;
|
|
662
|
+
let miss = 1;
|
|
663
|
+
let captor;
|
|
664
|
+
const facing = [];
|
|
665
|
+
for (const [i, a] of powers.entries()) {
|
|
666
|
+
const meets = Math.round(left) + strength;
|
|
667
|
+
facing.push(meets);
|
|
668
|
+
const chance = winChance(a, meets, combat);
|
|
669
|
+
miss *= 1 - chance;
|
|
670
|
+
if (exact ? chance === 1 : chance >= 0.5) {
|
|
671
|
+
captor = i;
|
|
672
|
+
break;
|
|
673
|
+
}
|
|
674
|
+
const kills = exact ? straightKills(a, off) : expectedKills(a, off);
|
|
675
|
+
if (kills >= left + strength) {
|
|
676
|
+
// It killed them all yet failed, so both sides were wiped out: one defender stands again.
|
|
677
|
+
left = 1;
|
|
678
|
+
strength = 0;
|
|
679
|
+
}
|
|
680
|
+
else if (kills >= left)
|
|
681
|
+
left = 0;
|
|
682
|
+
else
|
|
683
|
+
left -= kills;
|
|
684
|
+
}
|
|
685
|
+
// After the captor the target is mine (at the expectation, with luck): the later moves are transfers.
|
|
686
|
+
while (facing.length < powers.length)
|
|
687
|
+
facing.push(0);
|
|
688
|
+
const chance = exact ? (captor !== undefined ? 1 : 0) : 1 - miss;
|
|
689
|
+
return { chance, facing, ...(captor !== undefined ? { captor } : {}) };
|
|
690
|
+
}
|
|
691
|
+
/** The card types warapp_submit_turn can play, by the encoder's name. */
|
|
692
|
+
const PLAYABLE = {
|
|
693
|
+
[CARD_REINFORCEMENT]: 'Reinforcement',
|
|
694
|
+
[CARD_ORDER_PRIORITY]: 'OrderPriority',
|
|
695
|
+
[CARD_ORDER_DELAY]: 'OrderDelay',
|
|
696
|
+
[CARD_BLOCKADE]: 'Blockade',
|
|
697
|
+
// PLAN-TEAMS part D: encoded from the bundle's writers, UNVERIFIED live (V9).
|
|
698
|
+
2: 'Spy',
|
|
699
|
+
6: 'Airlift',
|
|
700
|
+
7: 'Gift',
|
|
701
|
+
8: 'Diplomacy',
|
|
702
|
+
9: 'Sanctions',
|
|
703
|
+
10: 'Reconnaissance',
|
|
704
|
+
11: 'Surveillance',
|
|
705
|
+
// Bomb (GameOrderPlayCardBomb) and Emergency Blockade (GameOrderPlayCardAbandon): bundle writers, UNVERIFIED live (V9).
|
|
706
|
+
13: 'Bomb',
|
|
707
|
+
3: 'EmergencyBlockade',
|
|
708
|
+
};
|
|
709
|
+
const handHint = (hand, ids) => `Your hand: ${hand.length ? hand.map((c) => (ids ? `${c.name} (${c.id})` : c.name)).join(', ') : 'no cards'}.`;
|
|
710
|
+
/**
|
|
711
|
+
* Find one card of my hand by GUID or type name, skipping cards already `used`
|
|
712
|
+
* (played or discarded) when matching by type; refuses a card not held and, by
|
|
713
|
+
* GUID, one already used (`twice` names the clash).
|
|
714
|
+
*/
|
|
715
|
+
function findCard(hand, ref, used, twice) {
|
|
716
|
+
const guid = normalizeGuid(ref.trim());
|
|
717
|
+
if (guid !== undefined) {
|
|
718
|
+
const card = hand.find((c) => c.id === guid);
|
|
719
|
+
if (!card)
|
|
720
|
+
throw new McpToolError(`Card ${guid} is not in your hand.`, { hint: handHint(hand, true) });
|
|
721
|
+
if (used.has(card.id)) {
|
|
722
|
+
throw new McpToolError(`The ${card.name} card ${card.id} is ${twice}.`, {
|
|
723
|
+
hint: 'Each card can be played or discarded once.',
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
return card;
|
|
727
|
+
}
|
|
728
|
+
const type = cardTypeByName(ref);
|
|
729
|
+
if (type === undefined) {
|
|
730
|
+
throw new McpToolError(`No card type matches "${ref}".`, {
|
|
731
|
+
hint: 'Name a card by its id (GUID) or its type, e.g. "Reinforcement" or "Order Priority".',
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
const card = hand.find((c) => c.type === type && !used.has(c.id));
|
|
735
|
+
if (!card) {
|
|
736
|
+
throw new McpToolError(`You hold no ${cardTypeName(type)} card${hand.some((c) => c.type === type) ? ' left to use' : ''}.`, {
|
|
737
|
+
hint: handHint(hand, false),
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
return card;
|
|
741
|
+
}
|
|
742
|
+
/**
|
|
743
|
+
* Resolve discards (by GUID or type name) against my hand, after the plays: any
|
|
744
|
+
* card type may be discarded, but not one that is also played or discarded twice.
|
|
745
|
+
*/
|
|
746
|
+
function resolveDiscards(hand, plays, inputs) {
|
|
747
|
+
const used = new Set(plays.map((p) => p.card.id));
|
|
748
|
+
const out = [];
|
|
749
|
+
for (const input of inputs) {
|
|
750
|
+
const card = findCard(hand, input.card, used, 'used twice (played or discarded)');
|
|
751
|
+
used.add(card.id);
|
|
752
|
+
out.push(card);
|
|
753
|
+
}
|
|
754
|
+
return out;
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Resolve card plays (by GUID or type name) against my hand. Refuses a card not
|
|
758
|
+
* held, the same card twice, a card this server cannot play, a Blockade with no
|
|
759
|
+
* target, a target on any other card, and a Reinforcement whose armies are unknown.
|
|
760
|
+
*/
|
|
761
|
+
function resolveCardPlays(map, hand, rules, inputs) {
|
|
762
|
+
const used = new Set();
|
|
763
|
+
const out = [];
|
|
764
|
+
for (const input of inputs) {
|
|
765
|
+
const card = findCard(hand, input.card, used, 'played twice');
|
|
766
|
+
used.add(card.id);
|
|
767
|
+
const kind = PLAYABLE[card.type];
|
|
768
|
+
if (!kind) {
|
|
769
|
+
throw new McpToolError(`Playing a ${card.name} card is not supported here yet.`, {
|
|
770
|
+
hint: 'Play it in the game itself; this tool plays only the built-in cards.',
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
const { card: _card, before: _before, ...targets } = input;
|
|
774
|
+
const hasTarget = input.target !== undefined && String(input.target).trim() !== '';
|
|
775
|
+
if (kind === 'Blockade' && !hasTarget) {
|
|
776
|
+
throw new McpToolError('A Blockade needs a `target`: the territory of yours to blockade.', {
|
|
777
|
+
hint: 'A Blockade turns your territory neutral with multiplied armies — it gives the territory away.',
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
checkCardFields(kind, card.name, targets);
|
|
781
|
+
if (input.before !== undefined && kind !== 'OrderDelay') {
|
|
782
|
+
throw new McpToolError(`Only an Order Delay takes \`before\`, not a ${card.name} card.`, {
|
|
783
|
+
hint: '`before` places an Order Delay among the moves; other card plays run in their own phase.',
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
let armies = 0;
|
|
787
|
+
if (kind === 'Reinforcement') {
|
|
788
|
+
const a = reinforcementArmies(card, rules);
|
|
789
|
+
if (a === undefined) {
|
|
790
|
+
throw new McpToolError(`The armies Reinforcement card ${card.id} adds are unknown, so the deploy total cannot be checked.`, {
|
|
791
|
+
hint: 'Play it in the game itself.',
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
armies = a;
|
|
795
|
+
}
|
|
796
|
+
const play = { card, kind, input: targets, armies, ...(input.before !== undefined ? { before: input.before } : {}) };
|
|
797
|
+
if (kind === 'Blockade') {
|
|
798
|
+
const t = resolveTerritory(map, input.target);
|
|
799
|
+
play.target = { id: t.id, name: t.name };
|
|
800
|
+
}
|
|
801
|
+
out.push(play);
|
|
802
|
+
}
|
|
803
|
+
return out;
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* The team's gathered hand is over the limit while mine is not (#163): a warning, not a refusal,
|
|
807
|
+
* because how war.app keys a team's hand is unverified — a wrong guess must not block a valid turn.
|
|
808
|
+
*/
|
|
809
|
+
function teamHandOver(held, rules, shed, given) {
|
|
810
|
+
return (`The team's hand as read (your cards and your teammates') holds ${held} cards; the limit is ${rules.maxCardsHold}, ` +
|
|
811
|
+
`so ${shed} card${shed === 1 ? '' : 's'} may need to be played or discarded; these orders use ${given}. How war.app keys ` +
|
|
812
|
+
"a team's hand is not yet verified, so this is not refused: check the hand in the game — war.app refuses the commit " +
|
|
813
|
+
'(error 51) if the team is over the limit.');
|
|
814
|
+
}
|
|
815
|
+
/** Cards these orders use that were read only under a teammate's id (V8, #163): a warning, never a refusal. */
|
|
816
|
+
export function teammateCardWarning(cards) {
|
|
817
|
+
return (`${cards.map((c) => `${c.name} ${c.id}`).join(', ')} ${cards.length === 1 ? 'was' : 'were'} read under a teammate, not under you. ` +
|
|
818
|
+
"A team shares one hand, but whether you can play or discard a card held under a teammate is not yet verified: war.app " +
|
|
819
|
+
'refusing it (e.g. error 50, CardInstanceUnavailable) means only that teammate can.');
|
|
820
|
+
}
|
|
821
|
+
/** The required-play refusal (war.app's error 51, `MustUseCard`), raised before anything is sent. */
|
|
822
|
+
function mustPlayCard(hand, rules, shed, given) {
|
|
823
|
+
return new McpToolError(`${SERVER_ERROR_MESSAGES[51]} (You hold ${hand.length}; the limit is ${rules.maxCardsHold}, so ${shed} card${shed === 1 ? '' : 's'} must be played or discarded; these orders use ${given}.)`, {
|
|
824
|
+
hint: `Add card plays or discards, e.g. { "kind": "discard", "card": "${hand[0]?.name ?? 'Order Delay'}" } (warapp_plan_turn suggests which). ${handHint(hand, true)}`,
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
const cardView = (c) => ({ id: c.id, name: c.name, ...(c.armies !== undefined ? { armies: c.armies } : {}) });
|
|
828
|
+
/** The deploys and moves of a sent turn, as opponent tracking reads my orders (#119); card plays left out. */
|
|
829
|
+
export function myOrdersOf(orders) {
|
|
830
|
+
return {
|
|
831
|
+
deploys: orders.flatMap((o) => (o.kind === 'deploy' ? [{ territoryId: o.territoryId, armies: o.armies }] : [])),
|
|
832
|
+
// Left out (#165): a percentage order's count is a percentage, not armies, and a Transfer Only
|
|
833
|
+
// or Attack Only order may not happen at all (it runs only if the target's owner suits it).
|
|
834
|
+
moves: orders.flatMap((o) => o.kind === 'move' && !o.byPercent && (o.mode === undefined || o.mode === AttackTransferMode.AttackTransfer)
|
|
835
|
+
? [{ from: o.from, to: o.to, armies: o.armies, ...(o.commander ? { commander: true } : {}) }]
|
|
836
|
+
: []),
|
|
837
|
+
// #274: a move that takes my commander along is flagged, so a loss report reads where it went.
|
|
838
|
+
sent: orders.flatMap((o) => o.kind === 'move'
|
|
839
|
+
? [
|
|
840
|
+
{
|
|
841
|
+
from: o.from,
|
|
842
|
+
to: o.to,
|
|
843
|
+
...(o.mode === AttackTransferMode.Transfer ? { transferOnly: true } : {}),
|
|
844
|
+
...(o.commander ? { commander: true } : {}),
|
|
845
|
+
},
|
|
846
|
+
]
|
|
847
|
+
: []),
|
|
848
|
+
// Profiles A1: an Airlift or a Gift changes what my territories hold or who holds them.
|
|
849
|
+
cards: orders.flatMap((o) => o.kind === 'card'
|
|
850
|
+
? [
|
|
851
|
+
{
|
|
852
|
+
card: o.card,
|
|
853
|
+
...(o.from !== undefined ? { from: o.from } : {}),
|
|
854
|
+
...(o.to !== undefined ? { to: o.to } : {}),
|
|
855
|
+
...(o.target !== undefined ? { target: o.target } : {}),
|
|
856
|
+
},
|
|
857
|
+
]
|
|
858
|
+
: []),
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
/** Earlier turns that, when all cached, make the GameFeed history read unnecessary. */
|
|
862
|
+
const TREND_TURNS = 2;
|
|
863
|
+
/**
|
|
864
|
+
* My earlier boards of a game, best effort: for each of the last {@link CACHED_TURNS} turns
|
|
865
|
+
* before `turn`, the board this server cached when it planned or tracked that turn (a verified
|
|
866
|
+
* live board), else GameFeed's `GetHistory` standing when the feed sends one (unverified for
|
|
867
|
+
* games in progress). History is read only for turns the cache lacks, and not at all when the
|
|
868
|
+
* last {@link TREND_TURNS} turns are cached. Each carries the deploys and moves
|
|
869
|
+
* `warapp_submit_turn` sent that turn, when it sent them (#119). Empty otherwise; never throws.
|
|
870
|
+
*/
|
|
871
|
+
/** `cacheOnly` (#274): the cached boards alone, never a GameFeed request (warapp_submit_turn's commander check). */
|
|
872
|
+
export async function boardHistory(ctx, game, me, turn, opts = {}) {
|
|
873
|
+
if (turn === null || turn < 2)
|
|
874
|
+
return { boards: [] };
|
|
875
|
+
const byTurn = new Map();
|
|
876
|
+
if (ctx.dataDir)
|
|
877
|
+
for (const b of await readBoardHistory(ctx.dataDir, game.id, me.id, turn))
|
|
878
|
+
if (b.turn >= turn - CACHED_TURNS)
|
|
879
|
+
byTurn.set(b.turn, { source: 'cache', board: b.board });
|
|
880
|
+
// The cached boards are the live boards this server planned on (verified); GameFeed's history
|
|
881
|
+
// standing for a game in progress is unverified. So history only fills turns the cache lacks,
|
|
882
|
+
// and is not fetched at all when the last {@link TREND_TURNS} turns are cached: the threat trend
|
|
883
|
+
// and tracked incomes (#94) need two earlier turns, not just the previous one (#131).
|
|
884
|
+
const recent = Array.from({ length: Math.min(TREND_TURNS, turn - 1) }, (_, i) => turn - 1 - i);
|
|
885
|
+
if (!opts.cacheOnly && !recent.every((k) => byTurn.has(k))) {
|
|
886
|
+
try {
|
|
887
|
+
const withHistory = await ctx.client.getGame(game.id, { history: true });
|
|
888
|
+
// Turn k is played on the board after k − 1 completed turns.
|
|
889
|
+
for (let k = Math.max(1, turn - CACHED_TURNS); k < turn; k++) {
|
|
890
|
+
if (byTurn.has(k))
|
|
891
|
+
continue;
|
|
892
|
+
const board = boardFromHistory(withHistory.history, k - 1, game.players);
|
|
893
|
+
if (board)
|
|
894
|
+
byTurn.set(k, { source: 'history', board });
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
catch {
|
|
898
|
+
// History is optional: the cache stands.
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
// The orders this server sent on those turns (#119): measurements of what an opponent deployed.
|
|
902
|
+
const orders = ctx.dataDir ? await readCachedOrders(ctx.dataDir, game.id, me.id) : new Map();
|
|
903
|
+
const boards = [...byTurn]
|
|
904
|
+
.sort(([a], [b]) => a - b)
|
|
905
|
+
.map(([t, b]) => {
|
|
906
|
+
const o = orders.get(t);
|
|
907
|
+
return { turn: t, board: b.board, ...(o ? { orders: o } : {}), ...(b.source === 'history' ? { source: 'history' } : {}) };
|
|
908
|
+
});
|
|
909
|
+
const previous = byTurn.get(turn - 1);
|
|
910
|
+
return { boards, ...(previous ? { previous } : {}) };
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* The "since last turn" view (#194): one line comparing this turn's income with the next income
|
|
914
|
+
* the previous turn's plan expected, and naming the bonuses broken and territories lost since the
|
|
915
|
+
* previous board. `full` adds the figures and the lists by id and name beside the line.
|
|
916
|
+
*/
|
|
917
|
+
function sinceLastView(s, previousTurn, hasBoard, map, players, rung) {
|
|
918
|
+
const name = namer(map);
|
|
919
|
+
const bonus = (id) => map.bonuses.find((b) => b.id === id)?.name ?? String(id);
|
|
920
|
+
const player = (id) => ({ id, name: players.find((p) => p.id === id)?.name ?? String(id) });
|
|
921
|
+
const when = `when turn ${previousTurn} was planned`;
|
|
922
|
+
// #253: a cut by the army cap is named, so a shortfall it explains is not read as a border lost.
|
|
923
|
+
const inc = s.capCut ? `Income ${s.income} (the army cap took ${s.capCut.cut} of ${s.capCut.uncapped})` : `Income ${s.income}`;
|
|
924
|
+
const head = s.expected === null
|
|
925
|
+
? `${inc}; turn ${previousTurn} was not planned here.`
|
|
926
|
+
: s.income < s.expected
|
|
927
|
+
? `${inc}, ${s.expected - s.income} below the ${s.expected} expected ${when}.`
|
|
928
|
+
: s.income > s.expected
|
|
929
|
+
? `${inc}, ${s.income - s.expected} above the ${s.expected} expected ${when}.`
|
|
930
|
+
: `${inc}, as expected ${when}.`;
|
|
931
|
+
const broken = s.bonusesBroken ?? [];
|
|
932
|
+
const lost = s.territoriesLost ?? [];
|
|
933
|
+
const parts = [
|
|
934
|
+
...(broken.length
|
|
935
|
+
? [`${broken.length === 1 ? 'bonus' : 'bonuses'} broken — ${broken.map((b) => `${bonus(b.bonusId)} (+${b.value})`).join(', ')}`]
|
|
936
|
+
: []),
|
|
937
|
+
...(lost.length
|
|
938
|
+
? [
|
|
939
|
+
`lost ${lost
|
|
940
|
+
.map((t) => `${name(t.territoryId).name} (#${t.territoryId})${t.to !== null ? ` to ${player(t.to).name}` : ''}`)
|
|
941
|
+
.join(', ')}`,
|
|
942
|
+
]
|
|
943
|
+
: []),
|
|
944
|
+
];
|
|
945
|
+
const line = `${head} ${hasBoard ? `Since turn ${previousTurn}: ${parts.length ? parts.join('; ') : 'nothing lost'}.` : `No board of turn ${previousTurn} to compare.`}`;
|
|
946
|
+
if (rung !== 'full')
|
|
947
|
+
return line;
|
|
948
|
+
return {
|
|
949
|
+
income: s.income,
|
|
950
|
+
expected: s.expected,
|
|
951
|
+
expectedTurn: s.expectedTurn,
|
|
952
|
+
shortfall: s.shortfall,
|
|
953
|
+
...(s.capCut ? { armyCapCut: s.capCut } : {}),
|
|
954
|
+
...(hasBoard
|
|
955
|
+
? {
|
|
956
|
+
bonusesBroken: broken.map((b) => ({ id: b.bonusId, name: bonus(b.bonusId), value: b.value })),
|
|
957
|
+
territoriesLost: lost.map((t) => ({ ...name(t.territoryId), to: t.to !== null ? player(t.to) : null })),
|
|
958
|
+
}
|
|
959
|
+
: {}),
|
|
960
|
+
line,
|
|
961
|
+
};
|
|
962
|
+
}
|
|
963
|
+
/**
|
|
964
|
+
* The agreements `breaks` names and the orders that break each, in a sentence (ids only). A Bomb is named
|
|
965
|
+
* by its place among the card plays (`bombPlays`: the index of each Bomb in that list).
|
|
966
|
+
*/
|
|
967
|
+
function breaksText(breaks, moves, bombPlays = []) {
|
|
968
|
+
const one = (b) => `agreement ${b.agreement} with player ${b.with} (${b.state === 'notice' ? 'in notice, still binding' : 'active'}): ` +
|
|
969
|
+
[
|
|
970
|
+
...b.moves.map((m) => `move ${m.index + 1} (${moves[m.index].from.id} → ${m.to}) attacks a territory it covers`),
|
|
971
|
+
...(b.bombs ?? []).map((x) => `the Bomb (card play ${(bombPlays[x.index] ?? x.index) + 1}) on ${x.target} attacks a territory it covers`),
|
|
972
|
+
].join(', ');
|
|
973
|
+
return `These orders break ${breaks.length === 1 ? 'a truce' : `${breaks.length} truces`} — ${breaks.map(one).join('; ')}`;
|
|
974
|
+
}
|
|
975
|
+
/**
|
|
976
|
+
* B4 (warapp_plan_turn): the commitments my chat messages made (the ledger's, warapp_send_chat) that the
|
|
977
|
+
* plan's `moves` would break this turn. The planner never reads them, so the plan is unchanged; this only
|
|
978
|
+
* says so. Empty with no data directory or ledger.
|
|
979
|
+
*/
|
|
980
|
+
async function promiseWarnings(ctx, a) {
|
|
981
|
+
if (!ctx.dataDir)
|
|
982
|
+
return [];
|
|
983
|
+
const ledger = await readLedger(ctx.dataDir, a.game.id, a.me.id);
|
|
984
|
+
if (!ledger?.commitments?.length)
|
|
985
|
+
return [];
|
|
986
|
+
return commitmentWarnings({
|
|
987
|
+
commitments: ledger.commitments,
|
|
988
|
+
agreements: ledger.agreements,
|
|
989
|
+
graph: a.graph,
|
|
990
|
+
board: a.board,
|
|
991
|
+
me: a.me.id,
|
|
992
|
+
turn: a.turn,
|
|
993
|
+
moves: a.moves.map((m) => ({ from: m.from, to: m.to, ...(m.kind === 'transfer' ? { transferOnly: true } : {}) })),
|
|
994
|
+
}).map((w) => `The plan does not read your chat promises: ${w.text}. Change those moves before warapp_submit_turn, or ask the ` +
|
|
995
|
+
'owner and tell the player before breaking it — never silently.');
|
|
996
|
+
}
|
|
997
|
+
/**
|
|
998
|
+
* B2: the truces in force in `game` for `me` this turn — the agreement ledger (warapp_record_agreement)
|
|
999
|
+
* resolved against my board history (`boards`, then `board` as this turn's) into the planner's relations,
|
|
1000
|
+
* and the tacit truces (reported, never planned on). `undefined` with no turn. Shared by
|
|
1001
|
+
* warapp_plan_turn and warapp_check_plan, so both read the same truces.
|
|
1002
|
+
*/
|
|
1003
|
+
export async function truceRelations(ctx, a) {
|
|
1004
|
+
const { game, me, turn, graph, tracks } = a;
|
|
1005
|
+
if (turn === null)
|
|
1006
|
+
return undefined;
|
|
1007
|
+
const ledger = ctx.dataDir ? await readLedger(ctx.dataDir, game.id, me.id) : undefined;
|
|
1008
|
+
return planRelationsFrom({
|
|
1009
|
+
agreements: ledger?.agreements ?? [],
|
|
1010
|
+
graph,
|
|
1011
|
+
board: a.board,
|
|
1012
|
+
boards: [...a.boards, { turn, board: a.board }],
|
|
1013
|
+
me: me.id,
|
|
1014
|
+
turn,
|
|
1015
|
+
players: game.players.map((p) => ({
|
|
1016
|
+
id: p.id,
|
|
1017
|
+
...(p.isAI ? { isAI: true } : {}),
|
|
1018
|
+
...(p.humanTurnedIntoAI ? { humanTurnedIntoAI: true } : {}),
|
|
1019
|
+
...(p.state !== undefined ? { state: p.state } : {}),
|
|
1020
|
+
...(p.team !== undefined ? { team: p.team } : {}),
|
|
1021
|
+
})),
|
|
1022
|
+
incomes: {
|
|
1023
|
+
mine: a.myIncome,
|
|
1024
|
+
opponents: new Map(game.players
|
|
1025
|
+
.filter((p) => p.id !== me.id && (p.state ?? 'Playing') === 'Playing')
|
|
1026
|
+
.map((p) => {
|
|
1027
|
+
const t = tracks?.find((x) => x.playerId === p.id);
|
|
1028
|
+
return [p.id, t && t.firstSeen !== null ? (t.income ?? t.visibleIncome) : null];
|
|
1029
|
+
})),
|
|
1030
|
+
},
|
|
1031
|
+
...(a.diplomacy?.length ? { diplomacy: a.diplomacy } : {}),
|
|
1032
|
+
});
|
|
1033
|
+
}
|
|
1034
|
+
/**
|
|
1035
|
+
* The reads of my opponents in contact on `board` (a territory of theirs next to one of mine) with at
|
|
1036
|
+
* least one habit at the confidence bar or a label (docs/PLAN-PROFILES.md part D); none with profiling
|
|
1037
|
+
* off. Read-only. Never throws: profiling never blocks a plan.
|
|
1038
|
+
*/
|
|
1039
|
+
async function contactReads(ctx, env, game, me, boards, graph, board) {
|
|
1040
|
+
try {
|
|
1041
|
+
const { on, reads } = await readOpponents({ dataDir: ctx.dataDir, env, game, me, teamsKnown: true, boards });
|
|
1042
|
+
if (!on)
|
|
1043
|
+
return undefined;
|
|
1044
|
+
const contact = new Set(neighboursOf(graph, board, me.id));
|
|
1045
|
+
return reads.filter((r) => contact.has(r.id) && (r.labels.length || Object.keys(confidentHabits(r.estimates)).length));
|
|
1046
|
+
}
|
|
1047
|
+
catch {
|
|
1048
|
+
return undefined;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
/**
|
|
1052
|
+
* Everything warapp_plan_turn reads around the live board before it plans, and the planner input it
|
|
1053
|
+
* builds: shared with warapp_advise_diplomacy (B3), so a deal is priced on exactly the plan the turn
|
|
1054
|
+
* tool would make. Writes only what warapp_plan_turn's reads write (the award of picks on turn 1,
|
|
1055
|
+
* the first mover it shows), and not that with `award: false` — the award changes the plan only in a
|
|
1056
|
+
* two-player game, so a free-for-all caller skips it and writes nothing — or `award: 'read'`, which
|
|
1057
|
+
* reads the award as warapp_plan_turn does and keeps nothing (#275 pattern 3).
|
|
1058
|
+
*/
|
|
1059
|
+
export async function livePlanSetup(ctx, a) {
|
|
1060
|
+
const { game, map, me, turn, territories, info, history } = a;
|
|
1061
|
+
const { goal, focusBonusIds = [], reserve, enemyDeploy: enemy_deploy, minWinChance: min_win_chance, firstMover: first_mover } = a.args ?? {};
|
|
1062
|
+
const graph = graphOf(map);
|
|
1063
|
+
// The board as war.app shows it: what is tracked and cached. The plan is made on the board
|
|
1064
|
+
// the award of picks completes (#166): in a two-player game, the opponent's starts my own
|
|
1065
|
+
// pick list proves, where they are still fogged.
|
|
1066
|
+
const seen = withTeammateOrders(boardStateFromLive(territories, me, game.players), info, me, game.players);
|
|
1067
|
+
const write = a.award !== 'read';
|
|
1068
|
+
const award = a.award === false ? undefined : await loadAward(ctx.dataDir, game, me, seen, turn, { write });
|
|
1069
|
+
const board = award?.board ?? seen;
|
|
1070
|
+
const opening = openingThreat(award, game, graph, seen, turn);
|
|
1071
|
+
// #127: who moves first — first_mover, else a turn kept for this game alternated, else the award.
|
|
1072
|
+
const mover = await firstMoverFor(ctx.dataDir, game, me, turn, first_mover, award, { write });
|
|
1073
|
+
const settings = plannerSettings(game.settings);
|
|
1074
|
+
const rules = cardRules(game.settings);
|
|
1075
|
+
// A team shares one hand (#163): mine and my teammates' cards.
|
|
1076
|
+
const owners = handOwners(game, me);
|
|
1077
|
+
const hand = readHand(info, owners);
|
|
1078
|
+
const handUnknown = rules.inPlay.length > 0 && !handReadable(info, owners);
|
|
1079
|
+
const inGame = cardGame(game, me);
|
|
1080
|
+
// PLAN-TEAMS C3.7: a card my teammate has entered a play or discard of is theirs this turn, so my plan
|
|
1081
|
+
// chooses from the rest (their orders: V5; the team hand's keying: V8 — both unverified live).
|
|
1082
|
+
const { left: myHand, claimed: teamClaimed } = teamHandLeft(hand, inGame.team ? teamCardClaims(seen.teammateOrders, new Set(teammatesOf(game.players, me).map((p) => p.id))) : []);
|
|
1083
|
+
// V8: of what is left, a card read under a teammate's id is not mine to play (unverified): chooseCardPlays
|
|
1084
|
+
// and the card advice play, discard and advise only my own, so no card is both claimed and advised to me.
|
|
1085
|
+
const cards = chooseCardPlays(myHand, rules, inGame);
|
|
1086
|
+
const myCards = myHand.filter((c) => isMyCard(c, inGame.me));
|
|
1087
|
+
// The board's income, card armies out: what the truces' trust reads (as warapp_check_plan passes it).
|
|
1088
|
+
// #253: cut by the army cap (min(income, cap × income − my armies on the board)), before Sanctions.
|
|
1089
|
+
const incomeOnBoard = incomeDetail(graph, board, me.id, game.settings);
|
|
1090
|
+
const boardIncome = incomeOnBoard.income;
|
|
1091
|
+
const incomeCap = incomeOnBoard.cap;
|
|
1092
|
+
// PLAN-TEAMS D3: the cards in effect the decoder is sure of — Sanctions on me cut this turn's income,
|
|
1093
|
+
// a Diplomacy card with a player makes it no foe this turn (T9).
|
|
1094
|
+
const effect = boardCardsInEffect(game, me, turn, info);
|
|
1095
|
+
const sanction = sanctionMyIncome(boardIncome, effect, { localDeployments: settings.localDeployments === true });
|
|
1096
|
+
const income = sanction.income + cards.extraArmies;
|
|
1097
|
+
const trend = history.previous;
|
|
1098
|
+
const previousOrders = turn !== null ? history.boards.find((b) => b.turn === turn - 1)?.orders : undefined;
|
|
1099
|
+
// The opponents over my board history: one observed over 2+ turns gets its tracked income;
|
|
1100
|
+
// one still playing with nothing in view gets a received lower bound and a warning (#94).
|
|
1101
|
+
const tracks = turn !== null
|
|
1102
|
+
? trackOpponents(graph, [...history.boards, { turn, board: seen }], me.id, settings, trackGame(game.players, game.settings, map, game.endRules))
|
|
1103
|
+
: undefined;
|
|
1104
|
+
// #240: territories my cached orders show failed attacks on, their owner reinforcing them each
|
|
1105
|
+
// time, on two or more of the last three turns: a further attack is sized for its owner's deploy.
|
|
1106
|
+
const repulsed = turn !== null ? repulsedAttacks(graph, [...history.boards, { turn, board: seen }], me.id, settings) : [];
|
|
1107
|
+
// #178: won, lost, even or stuck, from my boards over the last turns (a basis, not a verdict).
|
|
1108
|
+
// #201: the planner reads it too — a decided game shortens its payback horizon.
|
|
1109
|
+
const cardArmies = cardArmyCeiling(game.settings);
|
|
1110
|
+
const outlookInput = {
|
|
1111
|
+
graph,
|
|
1112
|
+
me: me.id,
|
|
1113
|
+
boards: [...history.boards, ...(turn !== null ? [{ turn, board: seen }] : [])],
|
|
1114
|
+
settings,
|
|
1115
|
+
game: trackGame(game.players, game.settings, map, game.endRules),
|
|
1116
|
+
cards: rules.inPlay.length > 0,
|
|
1117
|
+
// #205: what the card clock lets cards add, so a fogged card game can still be bounded.
|
|
1118
|
+
...(cardArmies ? { cardArmies } : {}),
|
|
1119
|
+
};
|
|
1120
|
+
// The plan reads the outlook (#201: winning or losing only); #218 then feeds the outlook the
|
|
1121
|
+
// plan's main front, so its front forecast and the plan's front outlook are one computation.
|
|
1122
|
+
const outlook = gameOutlook(outlookInput);
|
|
1123
|
+
const picking = ctx.dataDir ? await readPickRecord(ctx.dataDir, game.id, me.id) : undefined;
|
|
1124
|
+
// Players still in the game besides me (a break is worth less when the bonus's loss is shared).
|
|
1125
|
+
const opponents = game.players.filter((p) => p.id !== me.id && (p.state ?? 'Playing') === 'Playing').length;
|
|
1126
|
+
const gameContext = {
|
|
1127
|
+
players: game.players.map((p) => ({
|
|
1128
|
+
id: p.id,
|
|
1129
|
+
...(p.team !== undefined ? { team: p.team } : {}),
|
|
1130
|
+
...(p.state !== undefined ? { state: p.state } : {}),
|
|
1131
|
+
...(p.isAI ? { isAI: true } : {}),
|
|
1132
|
+
...(p.humanTurnedIntoAI ? { humanTurnedIntoAI: true } : {}),
|
|
1133
|
+
})),
|
|
1134
|
+
// #178, #270: who the game ends with, and whether a surrendered or booted seat is an AI's.
|
|
1135
|
+
...(game.endRules && Object.keys(seatEndRules(game.endRules)).length ? { endRules: seatEndRules(game.endRules) } : {}),
|
|
1136
|
+
turn,
|
|
1137
|
+
...(game.settings?.fog !== undefined ? { fog: game.settings.fog } : {}),
|
|
1138
|
+
...(game.settings?.commanders !== undefined ? { commanders: game.settings.commanders } : {}),
|
|
1139
|
+
// PLAN-TEAMS C3.6: a joint capture under a cyclic order says whose attack must run first.
|
|
1140
|
+
...(isTeamGame(game.players) && game.settings?.moveOrder !== undefined ? { moveOrder: game.settings.moveOrder } : {}),
|
|
1141
|
+
cards: rules.inPlay.length > 0,
|
|
1142
|
+
// #119: a 1v1 that started even gets the fog prior (an opponent in the fog earns at least my income).
|
|
1143
|
+
symmetricStart: symmetricStart(game.settings),
|
|
1144
|
+
// #235: why not, when it was not (the plan says so in a free-for-all).
|
|
1145
|
+
...(unevenStart(game.settings) ? { unevenStart: unevenStart(game.settings) } : {}),
|
|
1146
|
+
// #166: the opponent's opening simulated from the starts the award proved, as the prior.
|
|
1147
|
+
...(opening ? { opening } : {}),
|
|
1148
|
+
// #164: an opponent's Reinforcement card, from the turn the card clock says one can be in hand.
|
|
1149
|
+
...(opponentReinforcement(game.settings, hand) ? { reinforcement: opponentReinforcement(game.settings, hand) } : {}),
|
|
1150
|
+
};
|
|
1151
|
+
// B2: the truces in force, from the agreement ledger (warapp_record_agreement) and my board
|
|
1152
|
+
// history, and the tacit truces (reported, never planned on).
|
|
1153
|
+
const truces = await truceRelations(ctx, {
|
|
1154
|
+
game, me, turn, graph, board: seen, boards: history.boards, myIncome: boardIncome, tracks, diplomacy: effect.diplomacy,
|
|
1155
|
+
});
|
|
1156
|
+
// The per-opponent estimates the plan works from (as planTurn reads them), for the tripwire and the border guess.
|
|
1157
|
+
const { estimates } = planEnemyEstimates({
|
|
1158
|
+
graph,
|
|
1159
|
+
board,
|
|
1160
|
+
me: me.id,
|
|
1161
|
+
// #253: the fog prior reads my income before the army cap's cut, as the planner's does.
|
|
1162
|
+
income: income - cards.extraArmies,
|
|
1163
|
+
...(incomeCap ? { incomeCap } : {}),
|
|
1164
|
+
settings,
|
|
1165
|
+
...(trend ? { previousBoard: trend.board } : {}),
|
|
1166
|
+
...(trend && previousOrders ? { previousOrders } : {}),
|
|
1167
|
+
...(tracks ? { tracks } : {}),
|
|
1168
|
+
game: gameContext,
|
|
1169
|
+
turn,
|
|
1170
|
+
...(effect.sanctionsOnOthers.length ? { sanctions: effect.sanctionsOnOthers } : {}),
|
|
1171
|
+
});
|
|
1172
|
+
// #275 (b): the opponents whose estimate an observation broke: their held-bonus borders are sized for
|
|
1173
|
+
// the larger of what tripped it and my own income (the board's, card armies out).
|
|
1174
|
+
const teams = teamsOf(game.players);
|
|
1175
|
+
const trip = await readTripwires({
|
|
1176
|
+
dataDir: ctx.dataDir,
|
|
1177
|
+
gameId: game.id,
|
|
1178
|
+
me: me.id,
|
|
1179
|
+
turn,
|
|
1180
|
+
graph,
|
|
1181
|
+
boards: turn !== null ? [...history.boards, { turn, board: seen }] : [],
|
|
1182
|
+
settings,
|
|
1183
|
+
...(teams ? { teams } : {}),
|
|
1184
|
+
estimates,
|
|
1185
|
+
...(effect.diplomacy.length ? { peace: effect.diplomacy.map((d) => d.player) } : {}),
|
|
1186
|
+
...(a.teamsKnown === false ? { teamsKnown: false } : {}),
|
|
1187
|
+
gameSettings: game.settings,
|
|
1188
|
+
map,
|
|
1189
|
+
staticSeats: staticSeats(game.players, game.endRules, me.id),
|
|
1190
|
+
});
|
|
1191
|
+
const untrusted = trip.tripwires.map((w) => ({ player: w.player, deploy: untrustedDeploy(w, boardIncome) }));
|
|
1192
|
+
const input = {
|
|
1193
|
+
graph,
|
|
1194
|
+
board,
|
|
1195
|
+
me: me.id,
|
|
1196
|
+
income,
|
|
1197
|
+
...(untrusted.length ? { untrusted } : {}),
|
|
1198
|
+
cardArmies: cards.extraArmies,
|
|
1199
|
+
...(incomeCap ? { incomeCap } : {}),
|
|
1200
|
+
...(truces?.relations.length ? { relations: truces.relations } : {}),
|
|
1201
|
+
settings,
|
|
1202
|
+
...(trend ? { previousBoard: trend.board } : {}),
|
|
1203
|
+
// #226: my orders on that turn, when this server sent them: a failed attack's kills count back.
|
|
1204
|
+
...(trend && previousOrders ? { previousOrders } : {}),
|
|
1205
|
+
...(repulsed.length ? { repulsed } : {}),
|
|
1206
|
+
...(turn !== null ? { turn } : {}),
|
|
1207
|
+
game: gameContext,
|
|
1208
|
+
...(tracks ? { tracks } : {}),
|
|
1209
|
+
// G2 (D3): Sanctions on another player the decoder is sure of cut its estimate read off the board.
|
|
1210
|
+
...(effect.sanctionsOnOthers.length ? { sanctions: effect.sanctionsOnOthers } : {}),
|
|
1211
|
+
options: {
|
|
1212
|
+
// No goal: the game profile picks it and tunes the plan (an explicit goal overrides it).
|
|
1213
|
+
adapt: true,
|
|
1214
|
+
outlook: { state: outlook.state, turns: outlook.turns },
|
|
1215
|
+
// #201: the picking board's neutrals, so a fogged one keeps its size (wastelands).
|
|
1216
|
+
...(picking?.neutrals ? { rememberedNeutrals: new Map(picking.neutrals) } : {}),
|
|
1217
|
+
...(goal !== undefined ? { goal } : {}),
|
|
1218
|
+
focusBonusIds,
|
|
1219
|
+
...(opponents > 0 ? { opponents } : {}),
|
|
1220
|
+
holdsOrderPriority: holdsOrderPriority(myCards, cards),
|
|
1221
|
+
...(playsOrderPriority(cards) ? { orderPriorityForced: true } : {}),
|
|
1222
|
+
...(reserve !== undefined ? { reserve } : {}),
|
|
1223
|
+
...(enemy_deploy !== undefined ? { enemyDeploy: enemy_deploy } : {}),
|
|
1224
|
+
...(min_win_chance !== undefined ? { minWinChance: min_win_chance } : {}),
|
|
1225
|
+
// #127/#179: who moves first (firstMoverFor: first_mover, else the remembered turn, else the award).
|
|
1226
|
+
...(mover.firstMover !== undefined ? { movesFirst: mover.firstMover === 'me' } : {}),
|
|
1227
|
+
// #215 review: from the award (unverified), the schedule and card advice use it, holds do not.
|
|
1228
|
+
...(mover.firstMover !== undefined && !mover.verified ? { movesFirstUnverified: true } : {}),
|
|
1229
|
+
...(opponentCanHold(game.settings, 'Order Priority', turn) ? { opponentsMayHoldOrderPriority: true } : {}),
|
|
1230
|
+
// #163: an opponent may hold a Bomb by now: holds are sized as if halved, two stacks over one.
|
|
1231
|
+
...(opponentCanHold(game.settings, 'Bomb', turn) ? { opponentsMayHoldBomb: true } : {}),
|
|
1232
|
+
// #127: what a capture's card pieces are worth, for a plan that would capture nothing.
|
|
1233
|
+
...cardPieceOption(game.settings, hand),
|
|
1234
|
+
},
|
|
1235
|
+
};
|
|
1236
|
+
return {
|
|
1237
|
+
graph, seen, award, board, opening, mover, settings, rules, owners, hand, myHand, myCards, teamClaimed, handUnknown, inGame, cards,
|
|
1238
|
+
boardIncome, income, trend, previousOrders, tracks, outlookInput, outlook, picking, opponents, gameContext, truces, input,
|
|
1239
|
+
effect, sanction, incomeCap, capUnknown: incomeOnBoard.capUnknown === true, estimates, trip, teams,
|
|
1240
|
+
};
|
|
1241
|
+
}
|
|
1242
|
+
/**
|
|
1243
|
+
* #274: whether these orders leave my commander takeable by a single-deploy reply (`commanderCheckOn`,
|
|
1244
|
+
* src/tools/commander-check.ts: the one check, which warapp_check_plan reports too), each reply sized at
|
|
1245
|
+
* the larger of the opponent's estimate (as warapp_check_plan has it, from the cached boards only: no
|
|
1246
|
+
* GameFeed request) and my own income. One computation for warapp_submit_turn's refusal and
|
|
1247
|
+
* warapp_plan_turn's commander block, so the plan never calls safe what the submit refuses. Undefined
|
|
1248
|
+
* when my commander is not on the board.
|
|
1249
|
+
*/
|
|
1250
|
+
async function commanderCheck(ctx, a) {
|
|
1251
|
+
if (myCommanderTerritory(a.seen, a.me.id) === undefined)
|
|
1252
|
+
return undefined;
|
|
1253
|
+
const graph = graphOf(a.map);
|
|
1254
|
+
const settings = plannerSettings(a.game.settings);
|
|
1255
|
+
const [history, award] = await Promise.all([
|
|
1256
|
+
boardHistory(ctx, a.game, a.me, a.turn, { cacheOnly: true }),
|
|
1257
|
+
loadAward(ctx.dataDir, a.game, a.me, a.seen, a.turn),
|
|
1258
|
+
]);
|
|
1259
|
+
const opening = openingThreat(award, a.game, graph, a.seen, a.turn);
|
|
1260
|
+
// stressOpponents reads a static seat's territories as neutrals (#270), on its own `board` too.
|
|
1261
|
+
const so = stressOpponents({
|
|
1262
|
+
graph,
|
|
1263
|
+
map: a.map,
|
|
1264
|
+
game: a.game,
|
|
1265
|
+
me: a.me,
|
|
1266
|
+
board: award?.board ?? a.seen,
|
|
1267
|
+
seen: a.seen,
|
|
1268
|
+
boards: history.boards,
|
|
1269
|
+
...(history.previous ? { previous: history.previous.board } : {}),
|
|
1270
|
+
turn: a.turn,
|
|
1271
|
+
settings,
|
|
1272
|
+
hand: a.hand,
|
|
1273
|
+
info: a.info,
|
|
1274
|
+
...(opening ? { opening } : {}),
|
|
1275
|
+
});
|
|
1276
|
+
// #275: an untrusted opponent's reply is sized at least at the figure its tripwire gave it, as
|
|
1277
|
+
// warapp_check_plan's stress test tries it (read only: warapp_plan_turn keeps the marks).
|
|
1278
|
+
const tripwires = a.tripwires ??
|
|
1279
|
+
(await readTripwires({
|
|
1280
|
+
dataDir: ctx.dataDir,
|
|
1281
|
+
gameId: a.game.id,
|
|
1282
|
+
me: a.me.id,
|
|
1283
|
+
turn: a.turn,
|
|
1284
|
+
graph,
|
|
1285
|
+
boards: a.turn !== null ? [...history.boards, { turn: a.turn, board: a.seen }] : [],
|
|
1286
|
+
settings,
|
|
1287
|
+
...(teamsOf(a.game.players) ? { teams: teamsOf(a.game.players) } : {}),
|
|
1288
|
+
estimates: so.estimates,
|
|
1289
|
+
...(so.effect.diplomacy.length ? { peace: so.effect.diplomacy.map((d) => d.player) } : {}),
|
|
1290
|
+
...(a.teamsKnown === false ? { teamsKnown: false } : {}),
|
|
1291
|
+
gameSettings: a.game.settings,
|
|
1292
|
+
map: a.map,
|
|
1293
|
+
staticSeats: staticSeats(a.game.players, a.game.endRules, a.me.id),
|
|
1294
|
+
})).tripwires;
|
|
1295
|
+
const untrusted = new Map(tripwires.map((w) => [w.player, untrustedDeploy(w, a.income)]));
|
|
1296
|
+
return commanderCheckOn({
|
|
1297
|
+
graph,
|
|
1298
|
+
me: a.me.id,
|
|
1299
|
+
settings,
|
|
1300
|
+
so,
|
|
1301
|
+
income: a.income,
|
|
1302
|
+
...(untrusted.size ? { untrusted } : {}),
|
|
1303
|
+
deploys: a.deploys,
|
|
1304
|
+
moves: a.moves,
|
|
1305
|
+
orderPriority: a.orderPriority,
|
|
1306
|
+
...(a.floor !== undefined ? { floor: a.floor } : {}),
|
|
1307
|
+
...(a.killedBy !== undefined ? { killedBy: a.killedBy } : {}),
|
|
1308
|
+
...(a.airlifts ? { airlifts: a.airlifts } : {}),
|
|
1309
|
+
...(a.cardTargets ? { cardTargets: a.cardTargets } : {}),
|
|
1310
|
+
});
|
|
1311
|
+
}
|
|
1312
|
+
/**
|
|
1313
|
+
* warapp_plan_turn's border guess for `plan` (src/analysis/guess.ts), on the inputs `livePlanSetup` gave it:
|
|
1314
|
+
* one call shared with the comparison below (#275 pattern 3), so both draw the same split.
|
|
1315
|
+
*/
|
|
1316
|
+
function planBorderGuess(setup, plan, me, seed, enemyDeploy) {
|
|
1317
|
+
return borderGuess({
|
|
1318
|
+
graph: setup.graph,
|
|
1319
|
+
// #270: a static seat's territories are neutrals here, as in the plan the guess splits.
|
|
1320
|
+
board: neutralizeSeats(setup.board, staticSeats(setup.gameContext.players, setup.gameContext.endRules, me.id)),
|
|
1321
|
+
me: me.id,
|
|
1322
|
+
settings: setup.settings,
|
|
1323
|
+
plan,
|
|
1324
|
+
estimates: setup.estimates,
|
|
1325
|
+
...(enemyDeploy !== undefined ? { enemyDeploy } : {}),
|
|
1326
|
+
...(setup.gameContext.players ? { players: setup.gameContext.players } : {}),
|
|
1327
|
+
// #275 (b): no guess against an opponent whose estimate is untrusted.
|
|
1328
|
+
...(setup.trip.tripwires.length ? { untrusted: setup.trip.tripwires.map((w) => w.player) } : {}),
|
|
1329
|
+
seed,
|
|
1330
|
+
});
|
|
1331
|
+
}
|
|
1332
|
+
/** What the comparison with the default plan (#275 pattern 3) says the plan was. */
|
|
1333
|
+
export const BELOW_PLAN_BASIS = 'the plan warapp_plan_turn makes now on this board with no goal, focus, reserve, enemy_deploy or first_mover ' +
|
|
1334
|
+
'(the award of picks read as it reads it, nothing written), or its border guess when the ' +
|
|
1335
|
+
'deploys given are the guess\'s; a plan made with options may differ, and a figure is what that plan leaves ' +
|
|
1336
|
+
'standing there, surplus included, not the least that holds the border';
|
|
1337
|
+
/** The same deploys, merged per territory (order and splitting ignored). */
|
|
1338
|
+
function sameDeploys(a, b) {
|
|
1339
|
+
const total = (ds) => {
|
|
1340
|
+
const m = new Map();
|
|
1341
|
+
for (const d of ds)
|
|
1342
|
+
if (d.armies)
|
|
1343
|
+
m.set(d.territoryId, (m.get(d.territoryId) ?? 0) + d.armies);
|
|
1344
|
+
return m;
|
|
1345
|
+
};
|
|
1346
|
+
const x = total(a);
|
|
1347
|
+
const y = total(b);
|
|
1348
|
+
return x.size === y.size && [...x].every(([t, n]) => y.get(t) === n);
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* #275 pattern 3: the borders `given` leaves below what the default plan leaves on them — planTurn on the
|
|
1352
|
+
* same live board with default options, made as warapp_plan_turn makes it (`livePlanSetup` with
|
|
1353
|
+
* `award: 'read'`: the award of picks read, nothing written; the caller passes the same board history),
|
|
1354
|
+
* one plan per call — with the difference (src/analysis/hold-diff.ts). When the given deploys are that
|
|
1355
|
+
* plan's border guess (warapp_plan_turn's `guessOrders`, drawn with the salt kept here; none is made when
|
|
1356
|
+
* no salt is), the guess is the reference, since it only moves the plan's deploys between borders.
|
|
1357
|
+
* `cacheOnly`: the history given is the board cache alone, and the recent turns it lacks are named
|
|
1358
|
+
* (`historyGap`). `undefined` when the plan cannot be made. Never throws.
|
|
1359
|
+
*/
|
|
1360
|
+
export async function bordersBelowPlan(ctx, a) {
|
|
1361
|
+
try {
|
|
1362
|
+
const { given, cacheOnly, ...rest } = a;
|
|
1363
|
+
const setup = await livePlanSetup(ctx, { ...rest, award: 'read' });
|
|
1364
|
+
const plan = planTurn(setup.input);
|
|
1365
|
+
const salt = await peekGuessSalt(ctx.dataDir);
|
|
1366
|
+
const guessed = salt === undefined ? undefined : planBorderGuess(setup, plan, a.me, guessSeed(a.game.id, a.turn, salt));
|
|
1367
|
+
const guess = guessed?.kind === 'guess' && sameDeploys(given.deploys, guessed.deploys) ? guessed : undefined;
|
|
1368
|
+
const rows = holdsBelowPlan({
|
|
1369
|
+
graph: setup.graph,
|
|
1370
|
+
board: setup.board,
|
|
1371
|
+
// #270: a static seat's territories are neutrals, as in the plan compared.
|
|
1372
|
+
staticSeats: staticSeats(setup.gameContext.players, setup.gameContext.endRules, a.me.id),
|
|
1373
|
+
me: a.me.id,
|
|
1374
|
+
settings: setup.settings,
|
|
1375
|
+
...(setup.teams ? { teams: setup.teams } : {}),
|
|
1376
|
+
plan: {
|
|
1377
|
+
deploys: guess ? guess.deploys : plan.deploys,
|
|
1378
|
+
// #274: the plan's commander walk takes it along, as the given orders do.
|
|
1379
|
+
moves: plan.moves.map((m) => ({ from: m.from, to: m.to, armies: m.armies, ...(m.commander ? { withCommander: true } : {}) })),
|
|
1380
|
+
},
|
|
1381
|
+
conceded: plan.conceded,
|
|
1382
|
+
given,
|
|
1383
|
+
});
|
|
1384
|
+
const turn = a.turn;
|
|
1385
|
+
const held = new Set(a.history.boards.map((b) => b.turn));
|
|
1386
|
+
const historyGap = cacheOnly && turn !== null && turn >= 2
|
|
1387
|
+
? Array.from({ length: Math.min(TREND_TURNS, turn - 1) }, (_, i) => turn - 1 - i)
|
|
1388
|
+
.filter((k) => !held.has(k))
|
|
1389
|
+
.sort((x, y) => x - y)
|
|
1390
|
+
: [];
|
|
1391
|
+
return { rows, against: guess ? 'guess' : 'plan', ...(historyGap.length ? { historyGap } : {}) };
|
|
1392
|
+
}
|
|
1393
|
+
catch {
|
|
1394
|
+
return undefined;
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
/** #275 pattern 3: the preview's warning for the borders left below what the default plan leaves there, by id; none when there are none. */
|
|
1398
|
+
export function belowPlanWarning(below) {
|
|
1399
|
+
const rows = below?.rows;
|
|
1400
|
+
if (!rows?.length)
|
|
1401
|
+
return undefined;
|
|
1402
|
+
const ref = below.against === 'guess' ? "warapp_plan_turn's border guess" : 'the default plan';
|
|
1403
|
+
return (`These orders leave ${rows.length} border${rows.length === 1 ? '' : 's'} below what ${ref} leaves standing there (#275): ` +
|
|
1404
|
+
rows.map((r) => `territory ${r.territory} with ${r.left} where the plan leaves ${r.planLeaves} (${r.short} short)`).join('; ') +
|
|
1405
|
+
`. Compared with ${BELOW_PLAN_BASIS}. A border named may still hold (the plan's figure carries its surplus): ` +
|
|
1406
|
+
'check the headroom before moving armies back, and keep orders warapp_plan_turn made with options as they are.' +
|
|
1407
|
+
(below.historyGap
|
|
1408
|
+
? ` The board cache lacks turn${below.historyGap.length === 1 ? '' : 's'} ${below.historyGap.join(' and ')}, which ` +
|
|
1409
|
+
"warapp_plan_turn reads from GameFeed's history: its plan may differ from the one compared with here, so do not undo its orders for this line."
|
|
1410
|
+
: ''));
|
|
1411
|
+
}
|
|
1412
|
+
export function registerTurnTools(server, ctx, opts = {}) {
|
|
1413
|
+
/**
|
|
1414
|
+
* B2: after `warapp_submit_turn` with `break_agreement`, mark the agreements its orders broke
|
|
1415
|
+
* broken-by-me — only once the orders are confirmed committed (`committed`); otherwise say how to
|
|
1416
|
+
* record it by hand. Never throws.
|
|
1417
|
+
*/
|
|
1418
|
+
const recordBreaks = async (st, committed) => {
|
|
1419
|
+
const ids = st.breaks ?? [];
|
|
1420
|
+
const notRecorded = (why) => ids.map((agreement) => ({ agreement, ledger: 'not-recorded', why }));
|
|
1421
|
+
if (!committed)
|
|
1422
|
+
return notRecorded('the orders are not confirmed committed: once warapp_get_game shows them in, record it with warapp_record_agreement (status broken-by-me)');
|
|
1423
|
+
if (!ctx.dataDir)
|
|
1424
|
+
return notRecorded('this server keeps no data directory');
|
|
1425
|
+
try {
|
|
1426
|
+
const { game } = await resolveTeams(ctx, await ctx.client.getGame(st.gameId, { settings: true }));
|
|
1427
|
+
const me = game.players.find((p) => p.id === st.feedPlayerId);
|
|
1428
|
+
if (!me)
|
|
1429
|
+
return notRecorded('you are no longer listed in the game');
|
|
1430
|
+
return await recordBrokenByMe({ dir: ctx.dataDir, env: opts.env, game, me, map: mapOf(game), agreements: ids, turn: st.turnNumber });
|
|
1431
|
+
}
|
|
1432
|
+
catch (e) {
|
|
1433
|
+
return notRecorded(`re-reading the game failed (${failureText(e)}): record it with warapp_record_agreement (status broken-by-me)`);
|
|
1434
|
+
}
|
|
1435
|
+
};
|
|
1436
|
+
server.registerTool('warapp_plan_turn', {
|
|
1437
|
+
title: 'Plan my turn in a war.app game',
|
|
1438
|
+
description: untrustedDescription('Plan one turn for you in an in-progress war.app (Warzone) game from the live board, the map and the ' +
|
|
1439
|
+
"game's settings: your income, deploys and attacks/transfers by territory name and id (each attack with " +
|
|
1440
|
+
'`winChance`, its exact capture probability), the expected captures, completed bonuses and next income ' +
|
|
1441
|
+
'(with `nextIncomeIfConcededFall` and `bonusesAtRisk` when the plan concedes borders of a bonus you hold), ' +
|
|
1442
|
+
'the borders given up (`conceded`), the `frontier` budget, your cards (plays and discards when you must), ' +
|
|
1443
|
+
'warnings and the reasoning. Its `orders` array is exactly what warapp_submit_turn takes — review it with ' +
|
|
1444
|
+
'the user first. Every plan reads the game profile (`profile`: format 1v1/ffa/teams, phase, standing ' +
|
|
1445
|
+
'ahead/even/behind/unknown on income) and returns the `outlook` (winning/losing/even/stalemate from ' +
|
|
1446
|
+
'armies + 3 × income held over 3 turns of boards, with its `basis`; thresholds unmeasured, so advice, not a verdict; ' +
|
|
1447
|
+
'an opponent is bounded above by all it can have received (its start, or an even share of the map; each turn\'s most it could earn; ' +
|
|
1448
|
+
'a fixed Reinforcement card by the card clock) — a scenario\'s starts, a Gift card or a progressive Reinforcement card leave it unbounded, and then `winning` is never read; ' +
|
|
1449
|
+
'once winning or losing, payback tests count the turns the game has left instead of 10). With no `goal` the profile picks and tunes it (`goalSource` ' +
|
|
1450
|
+
'"profile"): defend when behind outside a 1v1, else balanced — in an FFA with two or more opponents, no ' +
|
|
1451
|
+
'second front; in a 1v1, one strike stack facing the opponent; ahead in a 1v1, fog pressure ' +
|
|
1452
|
+
`up to ${AHEAD_PRESSURE_FACTOR}× a typical neutral capture. Goals: "balanced" (default) — income per army ` +
|
|
1453
|
+
'across holds, bonuses and breaking enemy bonuses, at least 30% on expansion; "expand" — neutrals only; ' +
|
|
1454
|
+
'"complete-bonus" — also attacks players to finish bonuses; "defend" — threatened borders worth holding ' +
|
|
1455
|
+
'first. An opponent next to the fog may be pressured: each of its visible territories attacked, sized for ' +
|
|
1456
|
+
`its full deploy plus a margin, at most ${PRESSURE_FACTOR}× a typical neutral capture each — one visible ` +
|
|
1457
|
+
'territory too costly blocks the pressure on all of them. Threats assume each enemy deploys `enemy_deploy` (default per opponent: ' +
|
|
1458
|
+
'base income plus its visible bonuses, or its observed deploy when larger — its tracked income, carried across turns, once ' +
|
|
1459
|
+
'warapp_track_opponents has 2+ turns of it — and in an even-start 1v1 at least your income when it borders the fog; ' +
|
|
1460
|
+
'exact where the fog shows every owner (No, Light, Dense fog); plus its Reinforcement card from the turn the card clock says it can hold one; ' +
|
|
1461
|
+
'a neighbour whose armies the fog hides counts its unaccounted armies (at most two turns of its income), and a large stack that left view counts where it can reach, with a warning a turn ahead where it can stand beside a border next turn; ' +
|
|
1462
|
+
'growth beside the fog beyond twice what it was expected to deploy reads as a move out of the fog, not a deploy). Obeys the kill rates, luck, rounding, Local ' +
|
|
1463
|
+
'Deployment, No-Split (one order per territory, with its whole stack) and commanders; plays Reinforcement (in a team ' +
|
|
1464
|
+
"game only when cards must be shed, and only cards read under you: the hand is the team's), and Order Priority only when the plan advises it (a " +
|
|
1465
|
+
'withdrawal worth a card, a commander strike) or it is the card that must go (over the hold limit the cards worth ' +
|
|
1466
|
+
'least in this game leave first; the timing cards are kept longest); never Blockade, Order Delay, Bomb or Emergency ' +
|
|
1467
|
+
'Blockade — `cards.advice` says where those pay (Order Delay above the calm orders, a Bomb target or hold it, an ' +
|
|
1468
|
+
"Emergency Blockade wall; Diplomacy on the opponent pressing you hardest when two or more do, Sanctions on the leader, an Airlift onto a " +
|
|
1469
|
+
"border of yours or a teammate's that falls without it, a Gift that completes a teammate's bonus, Spy, Reconnaissance or Surveillance " +
|
|
1470
|
+
'where the fog hides what the plan needs (never with fog off) — each with an `order` to pass to ' +
|
|
1471
|
+
"warapp_submit_turn, never added to the orders), and the warnings flag an opponent's Bomb or Emergency Blockade and the cards in effect. Moves are listed in the " +
|
|
1472
|
+
"order to send them (both players' orders interleave). The full rule list is in the planner's header and the warapp-mcp skill. " +
|
|
1473
|
+
'When this server kept your pick list (warapp_submit_picks or warapp_get_my_picks during distribution), ' +
|
|
1474
|
+
'`award` says what the award of picks showed: the territories of your list that are another player\'s ' +
|
|
1475
|
+
'start for certain (in a two-player game they are planned as the opponent\'s while still fogged, with the ' +
|
|
1476
|
+
'starting armies on turn 1), whether you were awarded first or second and who moves first this turn under ' +
|
|
1477
|
+
"a `Cycle` move order, and with commanders the opponent's first award when the award pins it. " +
|
|
1478
|
+
'In a Commanders game, `commander` reports your commander every turn: its territory, the armies there after the ' +
|
|
1479
|
+
'plan, `movesToEnemy` (to the nearest enemy or fogged territory), `killedBy` (the smallest deploy, made by each ' +
|
|
1480
|
+
'opponent, at which a reply kills it, with `player` and, when two opponents striking together are that reply, ' +
|
|
1481
|
+
'`partner`; null when none reaches it this turn) and whether it holds at the larger of the estimate and your income ' +
|
|
1482
|
+
'(`safe`, `needs`); when it does not, the first warning says so and whether warapp_submit_turn would refuse such ' +
|
|
1483
|
+
'orders (not without Commanders in the settings, nor when only an `enemy_deploy` what-if makes it unsafe). ' +
|
|
1484
|
+
'Within three moves of an enemy or the fog, with a safer territory of yours reachable, your commander walks one ' +
|
|
1485
|
+
'step a turn toward safety: a move in `orders` with `commander: true` (encoding not yet verified live), said in ' +
|
|
1486
|
+
'the first warning. ' +
|
|
1487
|
+
'`sinceLastTurn` is one line: this turn\'s income (cards aside) against the next income the previous ' +
|
|
1488
|
+
"turn's plan expected (kept per game, from a plan without `goal` or `enemy_deploy`: a what-if plan keeps no figure), " +
|
|
1489
|
+
'and the bonuses broken and territories lost since the previous board. ' +
|
|
1490
|
+
'`headroom` lists, weakest first, each border of yours with the smallest single deploy by a neighbouring opponent that ' +
|
|
1491
|
+
'takes it after the plan\'s orders (carried out on the turn simulator, both move orders unless the first mover is known), ' +
|
|
1492
|
+
'whether that is below your income, and what falls with it (the bonuses it breaks, the territories behind it and their ' +
|
|
1493
|
+
'bonus income): an estimate is a floor, so this says how wrong it may be. When one observation broke an opponent\'s ' +
|
|
1494
|
+
'estimate by 1.5× or more (a stack out of the fog, a capture, or an attack of yours it held, needing more than the estimate ' +
|
|
1495
|
+
'allowed), the first warning says so for the next 3 turns, and the borders of your held bonuses facing it are sized for the ' +
|
|
1496
|
+
'larger of what it implied and your own income. ' +
|
|
1497
|
+
'With an army cap, `income` is what the cap leaves, min(income, cap × income − your armies on the board) (verified by ' +
|
|
1498
|
+
'six live cases; the line names a cut), and `incomeCapped` gives the arithmetic; Reinforcement card armies come on top. ' +
|
|
1499
|
+
'In a free-for-all, `relations` reports each truce recorded with warapp_record_agreement as the plan treated it ' +
|
|
1500
|
+
'(no covered territory of the partner attacked while it is active or in notice; a covered border facing only ' +
|
|
1501
|
+
'the partner held against its stacks with no deploy, except your commander\'s, a valuable border, or while trust ' +
|
|
1502
|
+
'is watch; a border cap kept), `advice` says `give-notice` when the endgame or the partner outgrowing you made ' +
|
|
1503
|
+
'the trust watch, a truce the board shows broken is planned as an ordinary opponent, and `tacit` lists quiet ' +
|
|
1504
|
+
'borders with no agreement (a report, never a truce). The plan never reads what your chat promised ' +
|
|
1505
|
+
"(warapp_send_chat's `commitments`): a warning says when its moves would break one still in force. " +
|
|
1506
|
+
"In a team game a bonus with a teammate's territory in it is never planned toward (one owner per bonus), and " +
|
|
1507
|
+
'`team.sharedBonuses` lists each bonus you and a teammate both hold members of and who is `nearer` to holding it. ' +
|
|
1508
|
+
"With a teammate's entered orders on the live board (unverified live): an otherwise equal capture on the opponent they " +
|
|
1509
|
+
'attack goes first; `team.support` (their border your idle armies would make hold) and `team.jointCaptures` (a target ' +
|
|
1510
|
+
'neither takes alone) are advice, never in `orders`; `cards.team` says who plays each card, leaving theirs to them. ' +
|
|
1511
|
+
'`firstMover` is who the plan takes to move first this turn (null when unknown) and its `source`: ' +
|
|
1512
|
+
'"explicit" (`first_mover`), "award", or "remembered" — a turn this server kept, alternated (two players, ' +
|
|
1513
|
+
'cyclic order). ' +
|
|
1514
|
+
'When one opponent touches two or more of your borders and no fixed split of the deploys there holds them all, ' +
|
|
1515
|
+
'`guess` is a randomized split, weighted by what each border is worth, against an opponent who would read a fixed ' +
|
|
1516
|
+
'one, and `guessOrders` the plan\'s `orders` with that split — optional (the user chooses; `orders` stay the ' +
|
|
1517
|
+
"plan's), and a model: one opponent, one deploy, its visible stacks. " +
|
|
1518
|
+
'`reads` (opponent profiles, as warapp_profile_opponents reads them; reported only, the plan never uses them): ' +
|
|
1519
|
+
'each opponent in contact with a habit at the confidence bar or a label — its labels, `lastAttackTurn` (the last turn it attacked you), those habits with `n` and ' +
|
|
1520
|
+
'`basis`, `gamesMet` — a likelihood, never a certainty, and never to be quoted to another player. ' +
|
|
1521
|
+
`Refuses outside a turn phase. ${BRIDGE_NOTE} Read-only on war.app; it never submits orders.`),
|
|
1522
|
+
_meta: lookupMeta(['plan my turn', 'warzone turn plan', 'what should i deploy', 'suggest my orders']),
|
|
1523
|
+
annotations: readAnnotations('Plan a war.app turn'),
|
|
1524
|
+
inputSchema: z.object({
|
|
1525
|
+
game_id: gameIdArg,
|
|
1526
|
+
player: playerArg,
|
|
1527
|
+
goal: z
|
|
1528
|
+
.enum(GOALS)
|
|
1529
|
+
.optional()
|
|
1530
|
+
.describe('Omit to let the game profile pick (defend when behind on income outside a 1v1, else balanced, tuned to the format). ' +
|
|
1531
|
+
'balanced (default): best income per army across holds, bonuses and breaking enemy bonuses; expand: take ' +
|
|
1532
|
+
'neutrals only; complete-bonus: also attack players to finish bonuses; defend: hold threatened borders first. ' +
|
|
1533
|
+
'A goal given here overrides the profile.'),
|
|
1534
|
+
focus: z
|
|
1535
|
+
.array(z.union([z.string(), z.number()]))
|
|
1536
|
+
.max(MAX_FOCUS)
|
|
1537
|
+
.optional()
|
|
1538
|
+
.describe('Bonuses to work on first (ids or names), even when the planner would call them uneconomic.'),
|
|
1539
|
+
reserve: z.coerce
|
|
1540
|
+
.number()
|
|
1541
|
+
.int()
|
|
1542
|
+
.min(0)
|
|
1543
|
+
.optional()
|
|
1544
|
+
.describe('Armies of income held out of captures (they are still deployed, on the most exposed border).'),
|
|
1545
|
+
enemy_deploy: z.coerce
|
|
1546
|
+
.number()
|
|
1547
|
+
.int()
|
|
1548
|
+
.min(0)
|
|
1549
|
+
.max(MAX_ENEMY_DEPLOY)
|
|
1550
|
+
.optional()
|
|
1551
|
+
.describe('Armies every enemy is assumed to deploy next turn when judging threats. Default, per opponent: base ' +
|
|
1552
|
+
'income plus every bonus it visibly holds, whatever its stack next to you (never below the base income), ' +
|
|
1553
|
+
'or what it was observed to deploy when larger, carried across turns (growth beside the fog beyond twice ' +
|
|
1554
|
+
'what it was expected to deploy reads as a move out of the fog, not a deploy). In an even-start 1v1 an opponent ' +
|
|
1555
|
+
'bordering the fog is assumed to earn at least your income. Income in the fog is unseen, so raise it if ' +
|
|
1556
|
+
'you know they earn more.'),
|
|
1557
|
+
min_win_chance: z.coerce
|
|
1558
|
+
.number()
|
|
1559
|
+
.min(0.5)
|
|
1560
|
+
.max(1)
|
|
1561
|
+
.optional()
|
|
1562
|
+
.describe('The least win chance each ordinary capture is sized for, 0.5–1. Default: 1 (certain: every roll and ' +
|
|
1563
|
+
'rounding takes it) with no luck, 0.95 with luck on. Below 1, each capture gets the fewest armies whose ' +
|
|
1564
|
+
'exact win chance (game kill rates, luck, rounding) reaches it — cheaper, but it can fail — and the ' +
|
|
1565
|
+
'captures a bonus still needs reach it together. Attacks sized for a worst case (finishing a player off, ' +
|
|
1566
|
+
'fog pressure, commander strikes) stay certain.'),
|
|
1567
|
+
first_mover: z
|
|
1568
|
+
.enum(['me', 'opponent'])
|
|
1569
|
+
.optional()
|
|
1570
|
+
.describe('Who moves first this turn, when you know (as warapp_check_plan takes it; Cycle and No-Luck Cycle move ' +
|
|
1571
|
+
'orders swap the first mover every turn: whoever moved second last turn moves first now). Give the ' +
|
|
1572
|
+
"cycle's order, not one an Order Priority or Order Delay card changed. When you move " +
|
|
1573
|
+
"first, your first order already runs before the opponent's, so Order Priority is not advised (unless the " +
|
|
1574
|
+
'opponent may hold one too and the order ends a player). In a ' +
|
|
1575
|
+
'two-player game under a cyclic order it is remembered and later turns default to it, alternated; ' +
|
|
1576
|
+
'omitted, the default is that, else the award of picks, else unknown (`firstMover` says which).'),
|
|
1577
|
+
view: viewArg(VIEWS, 'compact (default) gives the plan and orders (the profile as format, phase and standing); "full" adds each ' +
|
|
1578
|
+
'move\'s reason, the whole profile and the settings the plan assumed.'),
|
|
1579
|
+
}),
|
|
1580
|
+
}, async ({ game_id, player, goal, focus, reserve, enemy_deploy, min_win_chance, first_mover, view }) => {
|
|
1581
|
+
// The chat comes in the same GameFeed read: the fallback for the unread counts (part A1).
|
|
1582
|
+
const feed = await ctx.client.getGame(game_id, { settings: true, chat: true });
|
|
1583
|
+
requireTurnPhase(feed);
|
|
1584
|
+
const map = mapOf(feed);
|
|
1585
|
+
const focusBonusIds = (focus ?? []).map((b) => resolveBonus(map, b).id);
|
|
1586
|
+
const turn = currentTurn(feed);
|
|
1587
|
+
// My seat is checked before the board is read (#130): an eliminated or booted seat has no turn,
|
|
1588
|
+
// so nothing is read for it. Then the live board and the board history are independent reads:
|
|
1589
|
+
// in parallel, not in series (#131). History needed my seat anyway, so the board waiting for it
|
|
1590
|
+
// adds no step to the slowest chain (account, then history). Accepted trade-off of not
|
|
1591
|
+
// serializing them: when the board read fails, a history read already under way still reaches
|
|
1592
|
+
// GameFeed after the tool has returned (one wasted, harmless read; boardHistory never throws).
|
|
1593
|
+
const seat = await resolveMe(ctx, feed.players, player);
|
|
1594
|
+
requirePlayingSeat(feed, seat);
|
|
1595
|
+
// The teams: GameFeed's, else the game list's (asked once per game, kept).
|
|
1596
|
+
const { game, me, source: teamSource, known: teamsKnown } = await resolveTeamsFor(ctx, feed, seat);
|
|
1597
|
+
const [{ territories, info }, history, chat] = await Promise.all([
|
|
1598
|
+
loadLiveGame(ctx, game),
|
|
1599
|
+
boardHistory(ctx, game, me, turn),
|
|
1600
|
+
// Unread chat per channel (counts only), so the agent reads chat before it submits.
|
|
1601
|
+
chatSummary(ctx, game),
|
|
1602
|
+
]);
|
|
1603
|
+
const setup = await livePlanSetup(ctx, {
|
|
1604
|
+
game, map, me, turn, territories, info, history, teamsKnown,
|
|
1605
|
+
args: {
|
|
1606
|
+
...(goal !== undefined ? { goal } : {}),
|
|
1607
|
+
focusBonusIds,
|
|
1608
|
+
...(reserve !== undefined ? { reserve } : {}),
|
|
1609
|
+
...(enemy_deploy !== undefined ? { enemyDeploy: enemy_deploy } : {}),
|
|
1610
|
+
...(min_win_chance !== undefined ? { minWinChance: min_win_chance } : {}),
|
|
1611
|
+
...(first_mover !== undefined ? { firstMover: first_mover } : {}),
|
|
1612
|
+
},
|
|
1613
|
+
});
|
|
1614
|
+
const { graph, seen, award, board, mover, rules, hand, myHand, myCards, teamClaimed, handUnknown, inGame, cards, income, trend, tracks } = setup;
|
|
1615
|
+
const { settings, outlookInput, truces, effect, sanction, estimates } = setup;
|
|
1616
|
+
let { outlook } = setup;
|
|
1617
|
+
const plan = planTurn(setup.input);
|
|
1618
|
+
// #228: and the plan's profile standing, so an `even` outlook beside `behind` says why they differ.
|
|
1619
|
+
// Neither changes whether the turn reads winning or losing (the state the plan acted on): losing
|
|
1620
|
+
// on the estimate reads the front on my boards' incomes, never the plan's (#228 review); only a
|
|
1621
|
+
// stalemate may follow the plan's front, which the planner ignores.
|
|
1622
|
+
if (turn !== null && (plan.front || plan.profile.standing === 'ahead' || plan.profile.standing === 'behind'))
|
|
1623
|
+
outlook = gameOutlook({
|
|
1624
|
+
...outlookInput,
|
|
1625
|
+
...(plan.front
|
|
1626
|
+
? { front: { turn, from: plan.front.from, at: plan.front.at, myIncome: plan.front.myIncome, theirIncome: plan.front.theirIncome } }
|
|
1627
|
+
: {}),
|
|
1628
|
+
standing: plan.profile.standing,
|
|
1629
|
+
});
|
|
1630
|
+
// #194: since last turn — this turn's income (cards aside) against the next income the previous
|
|
1631
|
+
// turn's plan expected, and what was lost since the previous board. Read before this turn's write.
|
|
1632
|
+
const expectedNow = ctx.dataDir && turn !== null && turn >= 2 ? await readExpectedIncome(ctx.dataDir, game.id, me.id, turn - 1) : undefined;
|
|
1633
|
+
const since = turn !== null && turn >= 2 && (trend || expectedNow !== undefined)
|
|
1634
|
+
? sinceLastTurn({
|
|
1635
|
+
graph,
|
|
1636
|
+
previous: trend?.board,
|
|
1637
|
+
current: seen,
|
|
1638
|
+
me: me.id,
|
|
1639
|
+
income: income - cards.extraArmies,
|
|
1640
|
+
expected: expectedNow,
|
|
1641
|
+
expectedTurn: turn - 1,
|
|
1642
|
+
armyCap: setup.incomeCap,
|
|
1643
|
+
})
|
|
1644
|
+
: undefined;
|
|
1645
|
+
// A what-if plan (an explicit goal or enemy_deploy) keeps the board but not its expected income:
|
|
1646
|
+
// next turn's "since last turn" compares with the plan the profile chose, not the last one asked for.
|
|
1647
|
+
const whatIf = goal !== undefined || enemy_deploy !== undefined;
|
|
1648
|
+
if (ctx.dataDir && turn !== null)
|
|
1649
|
+
await writeBoardCache(ctx.dataDir, game.id, me.id, turn, seen, whatIf ? undefined : plan.expected.nextIncome);
|
|
1650
|
+
// #275 (b): this turn's estimates and the untrusted marks, for the next turns' tripwire. Kept on a
|
|
1651
|
+
// what-if plan too, unlike its neighbours: both come from the boards alone — the estimates are the
|
|
1652
|
+
// default ones (planEnemyEstimates never reads enemy_deploy or goal) and a mark is an observation —
|
|
1653
|
+
// so a what-if writes exactly what the default plan would, and skipping it could drop a mark.
|
|
1654
|
+
await keepTripwires(ctx.dataDir, game.id, me.id, turn, setup.trip);
|
|
1655
|
+
// The opponent profile (docs/PLAN-PROFILES.md A2): the turns these boards show, never on a what-if plan.
|
|
1656
|
+
if (ctx.dataDir && turn !== null && !whatIf)
|
|
1657
|
+
await recordProfile(ctx.dataDir, opts.env, game, me, [...history.boards, { turn, board: seen }], teamsKnown);
|
|
1658
|
+
// Part D (docs/PLAN-PROFILES.md section 11): each opponent in contact, its labels and the habits
|
|
1659
|
+
// at the confidence bar. Reported only: the planner above read none of it (owner decision P1).
|
|
1660
|
+
// None with profiling off, or while the teams cannot be read (any player may be my teammate).
|
|
1661
|
+
const reads = turn !== null && teamsKnown ? await contactReads(ctx, opts.env ?? process.env, game, me, [...history.boards, { turn, board: seen }], graph, seen) : undefined;
|
|
1662
|
+
if (ctx.dataDir && turn !== null)
|
|
1663
|
+
await writeGameRecord(ctx.dataDir, game);
|
|
1664
|
+
if (ctx.dataDir && turn !== null)
|
|
1665
|
+
await recordOutlook(ctx.dataDir, game.id, me.id, outlook);
|
|
1666
|
+
// B2: what each honoured truce freed this turn and what a break would have cost (T6), for "has it
|
|
1667
|
+
// been useful in play?" (not a what-if plan).
|
|
1668
|
+
const used = (plan.relations ?? []).filter((r) => r.honoured && r.agreement !== undefined);
|
|
1669
|
+
if (ctx.dataDir && turn !== null && !whatIf && used.length)
|
|
1670
|
+
await recordTruceUsage(ctx.dataDir, game.id, me.id, turn, used.map((r) => ({
|
|
1671
|
+
agreementId: r.agreement,
|
|
1672
|
+
armiesFreed: r.armiesFreed,
|
|
1673
|
+
lossIfBroken: r.lossIfBroken ? r.lossIfBroken.armies : null,
|
|
1674
|
+
incomeLostIfBroken: r.lossIfBroken ? r.lossIfBroken.bonusValue : null,
|
|
1675
|
+
})));
|
|
1676
|
+
const name = namer(map);
|
|
1677
|
+
/** Another player by id, its name delimited as untrusted text. */
|
|
1678
|
+
const playerRef = (id) => {
|
|
1679
|
+
const p = game.players.find((x) => x.id === id);
|
|
1680
|
+
return { id, name: p ? untrustedText(p.name) : null };
|
|
1681
|
+
};
|
|
1682
|
+
// #163: Order Delay's place, my Bomb and Emergency Blockade, the opponents' when they can hold one,
|
|
1683
|
+
// and the cards in effect; D2: my Diplomacy, Sanctions, Airlift and Gift. Advice only: the orders
|
|
1684
|
+
// below are the plan's (and the advised Order Delay).
|
|
1685
|
+
// D3: a relation that is only a Diplomacy card is no truce to the card advice (it reads the card itself).
|
|
1686
|
+
const inForce = (truces?.relations ?? []).filter((r) => (r.state === 'active' || r.state === 'notice') && !r.card);
|
|
1687
|
+
const advice = rules.inPlay.length
|
|
1688
|
+
? adviseCards({
|
|
1689
|
+
game, me, turn, info, hand: myHand, choice: cards, plan, board, graph, settings, label: (id) => `${name(id).name} (#${id})`,
|
|
1690
|
+
truceCovered: new Set(inForce.flatMap((r) => r.coveredTheirs)),
|
|
1691
|
+
truces: inForce.map((r) => ({ player: r.player, state: r.state, coveredMine: r.coveredMine, ...(r.endsTurn !== undefined ? { endsTurn: r.endsTurn } : {}) })),
|
|
1692
|
+
...(effect.diplomacy.length ? { enforced: new Set(effect.diplomacy.map((d) => d.player)) } : {}),
|
|
1693
|
+
...(sanction.applied ? { sanctionsApplied: true } : {}),
|
|
1694
|
+
})
|
|
1695
|
+
: { view: {}, warnings: [] };
|
|
1696
|
+
// B4: the planner does not read what my chat messages promised (words change no estimate), so a
|
|
1697
|
+
// plan that breaks a commitment still in force says so here; warapp_submit_turn warns again.
|
|
1698
|
+
const promised = turn !== null ? await promiseWarnings(ctx, { game, me, turn, graph, board: seen, moves: plan.moves }) : [];
|
|
1699
|
+
// #275 (b): an untrusted estimate is the first thing said.
|
|
1700
|
+
const myIncome = income - cards.extraArmies;
|
|
1701
|
+
const warnings = [
|
|
1702
|
+
// The figure the planner used (the board's income, before Sanctions on me), never recomputed.
|
|
1703
|
+
...tripwireWarnings(setup.trip.tripwires, (w) => setup.input.untrusted?.find((u) => u.player === w.player)?.deploy ?? untrustedDeploy(w, setup.boardIncome), (p) => setup.trip.estimatesNow.get(p),
|
|
1704
|
+
// Under enemy_deploy the planner ignores the mark (#275 review): say what the what-if used.
|
|
1705
|
+
enemy_deploy),
|
|
1706
|
+
...(me.hasCommittedOrders
|
|
1707
|
+
? [
|
|
1708
|
+
'You have already committed orders this turn; warapp_submit_turn will refuse until you withdraw them ' +
|
|
1709
|
+
'with warapp_uncommit_turn (or modify orders in the game).',
|
|
1710
|
+
]
|
|
1711
|
+
: []),
|
|
1712
|
+
...(award ? assumedWarning(award) : []),
|
|
1713
|
+
...mover.warnings,
|
|
1714
|
+
...(handUnknown ? [UNREADABLE_HAND] : []),
|
|
1715
|
+
...(inGame.team && rules.inPlay.length ? [TEAM_HAND] : []),
|
|
1716
|
+
...teamClaimed.map((c) => `${c.card.name} (${c.card.id}): player ${c.player} has already entered a ${c.kind} of it, so this plan leaves it to them ` +
|
|
1717
|
+
'(PLAN-TEAMS C3.7: read from their entered orders, unverified live).'),
|
|
1718
|
+
...cards.warnings,
|
|
1719
|
+
...advice.warnings,
|
|
1720
|
+
...(cards.extraArmies > 0 ? [cardIncomeNote(income, cards.extraArmies)] : []),
|
|
1721
|
+
...sanction.warnings,
|
|
1722
|
+
...effect.unsure,
|
|
1723
|
+
...deployCheckUncertainties(game.settings, {
|
|
1724
|
+
sanctionsApplied: sanction.applied,
|
|
1725
|
+
...(setup.incomeCap ? { armyCap: setup.incomeCap } : {}),
|
|
1726
|
+
}).map((r) => `Income ${income} may be off: ${r}`),
|
|
1727
|
+
...(setup.capUnknown ? [`Income ${income} is not cut by the army cap: an army count of yours is unreadable on the board.`] : []),
|
|
1728
|
+
...[armyCapPoolsUncertainty(setup.incomeCap, settings.localDeployments)].filter((r) => r !== undefined),
|
|
1729
|
+
...(tracks ?? []).flatMap((t) => t.warnings),
|
|
1730
|
+
...plan.warnings,
|
|
1731
|
+
...promised,
|
|
1732
|
+
...modsWarning(game.settings),
|
|
1733
|
+
...commerceWarning(game.settings),
|
|
1734
|
+
...guardOffWarnings(graph, map, board, me.id, friendsOf(game.players, me), game.settings, plan.deploys, plan.moves),
|
|
1735
|
+
];
|
|
1736
|
+
// The plan advises Order Priority (a withdrawal, a commander strike): play the one I
|
|
1737
|
+
// hold, so the orders as returned carry it rather than only the advice.
|
|
1738
|
+
const advised = plan.cardAdvice === 'order-priority' ? advisedOrderPriority(myCards, cards) : undefined;
|
|
1739
|
+
const plays = advised ? [...cards.plays, advised] : cards.plays;
|
|
1740
|
+
// #163: an Order Delay that had to go is played where the plan advises it, not discarded.
|
|
1741
|
+
const playedDelay = advice.view.orderDelay?.card;
|
|
1742
|
+
const orders = [
|
|
1743
|
+
...cards.discards.filter((c) => c.id !== playedDelay).map((c) => ({ kind: 'discard', card: c.id })),
|
|
1744
|
+
...plays.map((c) => ({ kind: 'card', card: c.id })),
|
|
1745
|
+
...plan.deploys.map((d) => ({ kind: 'deploy', territory: d.territoryId, armies: d.armies })),
|
|
1746
|
+
// #274: my commander's walk takes it along (the #165 option, encoding unverified live).
|
|
1747
|
+
...plan.moves.map((m) => ({ kind: 'move', from: m.from, to: m.to, armies: m.armies, ...(m.commander ? { commander: true } : {}) })),
|
|
1748
|
+
// #186: the advised Order Delay, placed above its move (war.app accepted the placement live;
|
|
1749
|
+
// whether the later moves wait for the opponent's is not yet seen in a replay).
|
|
1750
|
+
...(advice.view.orderDelay ? [advice.view.orderDelay.order] : []),
|
|
1751
|
+
];
|
|
1752
|
+
// The border guess (docs/STRATEGY.md "Guessing at a border"): a randomized split of the deploys
|
|
1753
|
+
// the plan spends on one opponent's borders, when no fixed split holds them all. Optional: the
|
|
1754
|
+
// plan's own orders stay as they are; guessOrders carries the draw.
|
|
1755
|
+
// #274: my commander every turn (a Commanders game, it on the board): where the plan leaves it, the
|
|
1756
|
+
// armies there, the moves to the nearest enemy or fog, and the smallest single deploy that kills it.
|
|
1757
|
+
// The very check warapp_submit_turn runs on these orders (commanderCheck: its opponents, teams,
|
|
1758
|
+
// free-for-all lead and Order Priority, each reply at the larger of its estimate and my income), so
|
|
1759
|
+
// the block never calls safe what the submit would refuse; enemy_deploy only raises the replies.
|
|
1760
|
+
const checked = await commanderCheck(ctx, {
|
|
1761
|
+
game,
|
|
1762
|
+
me,
|
|
1763
|
+
map,
|
|
1764
|
+
seen,
|
|
1765
|
+
turn,
|
|
1766
|
+
info,
|
|
1767
|
+
hand,
|
|
1768
|
+
income: setup.boardIncome,
|
|
1769
|
+
tripwires: setup.trip.tripwires,
|
|
1770
|
+
deploys: plan.deploys,
|
|
1771
|
+
moves: plan.moves.map((m) => ({ from: m.from, to: m.to, armies: m.armies, ...(m.commander ? { withCommander: true } : {}) })),
|
|
1772
|
+
orderPriority: plays.some((c) => c.type === CARD_ORDER_PRIORITY),
|
|
1773
|
+
...(enemy_deploy !== undefined ? { floor: enemy_deploy } : {}),
|
|
1774
|
+
killedBy: true,
|
|
1775
|
+
});
|
|
1776
|
+
const guard = checked?.safety;
|
|
1777
|
+
const replyDeploy = checked?.replyDeploy ?? 0;
|
|
1778
|
+
const commanderLine = guard
|
|
1779
|
+
? `Your commander on territory ${guard.territory}: ${guard.armies} armies there after the plan, ${guard.distance === null ? 'no enemy or fog on the map' : `${guard.distance} move${guard.distance === 1 ? '' : 's'} from the nearest enemy or fog`}; ${guard.killedBy
|
|
1780
|
+
? `a deploy of ${guard.killedBy.deploy} by each opponent kills it (${guard.killedBy.partner !== undefined
|
|
1781
|
+
? `players ${guard.killedBy.opponent} and ${guard.killedBy.partner} striking it together`
|
|
1782
|
+
: `player ${guard.killedBy.opponent}'s reply`})`
|
|
1783
|
+
: 'no single deploy reaches it this turn'}.`
|
|
1784
|
+
: undefined;
|
|
1785
|
+
if (checked?.text) {
|
|
1786
|
+
// Name the submit's refusal only when the submit would make it (#274 review): it checks only a
|
|
1787
|
+
// Commanders game, and sizes the replies without enemy_deploy.
|
|
1788
|
+
let submit;
|
|
1789
|
+
if (game.settings?.commanders !== true) {
|
|
1790
|
+
submit = 'warapp_submit_turn does not check the commander in this game (Commanders is not on in its settings).';
|
|
1791
|
+
}
|
|
1792
|
+
else if (enemy_deploy === undefined) {
|
|
1793
|
+
submit = 'warapp_submit_turn refuses these orders unless accept_commander_risk is true.';
|
|
1794
|
+
}
|
|
1795
|
+
else {
|
|
1796
|
+
const plain = await commanderCheck(ctx, {
|
|
1797
|
+
game,
|
|
1798
|
+
me,
|
|
1799
|
+
map,
|
|
1800
|
+
seen,
|
|
1801
|
+
turn,
|
|
1802
|
+
info,
|
|
1803
|
+
hand,
|
|
1804
|
+
income: setup.boardIncome,
|
|
1805
|
+
tripwires: setup.trip.tripwires,
|
|
1806
|
+
deploys: plan.deploys,
|
|
1807
|
+
moves: plan.moves.map((m) => ({ from: m.from, to: m.to, armies: m.armies, ...(m.commander ? { withCommander: true } : {}) })),
|
|
1808
|
+
orderPriority: plays.some((c) => c.type === CARD_ORDER_PRIORITY),
|
|
1809
|
+
});
|
|
1810
|
+
submit = plain?.text
|
|
1811
|
+
? 'warapp_submit_turn refuses these orders unless accept_commander_risk is true (it finds the risk without enemy_deploy too).'
|
|
1812
|
+
: `This is under enemy_deploy ${enemy_deploy}: warapp_submit_turn, which sizes the replies without it, would not refuse these orders.`;
|
|
1813
|
+
}
|
|
1814
|
+
warnings.unshift(`${commanderLine} ${checked.text} ${submit}`);
|
|
1815
|
+
}
|
|
1816
|
+
const guessed = planBorderGuess(setup, plan, me, guessSeed(game.id, turn, await guessSalt(ctx.dataDir)), enemy_deploy);
|
|
1817
|
+
let guess = guessed.kind === 'guess' ? guessed : undefined;
|
|
1818
|
+
let guessSkip = guessed.kind === 'skipped' ? { reason: guessed.reason, message: guessed.message } : undefined;
|
|
1819
|
+
// #274: the draw's deploys go through the submit's own commander check too. The guess keeps the
|
|
1820
|
+
// plan's deploy where my commander stands or walks to; should its draw still leave the commander
|
|
1821
|
+
// takeable where the plan's orders do not, warapp_submit_turn would refuse it: no guess then.
|
|
1822
|
+
if (guess && checked) {
|
|
1823
|
+
const drawn = await commanderCheck(ctx, {
|
|
1824
|
+
game,
|
|
1825
|
+
me,
|
|
1826
|
+
map,
|
|
1827
|
+
seen,
|
|
1828
|
+
turn,
|
|
1829
|
+
info,
|
|
1830
|
+
hand,
|
|
1831
|
+
income: setup.boardIncome,
|
|
1832
|
+
tripwires: setup.trip.tripwires,
|
|
1833
|
+
deploys: guess.deploys,
|
|
1834
|
+
moves: plan.moves.map((m) => ({ from: m.from, to: m.to, armies: m.armies, ...(m.commander ? { withCommander: true } : {}) })),
|
|
1835
|
+
orderPriority: plays.some((c) => c.type === CARD_ORDER_PRIORITY),
|
|
1836
|
+
...(enemy_deploy !== undefined ? { floor: enemy_deploy } : {}),
|
|
1837
|
+
});
|
|
1838
|
+
if (!guessKeepsCommander(checked, drawn)) {
|
|
1839
|
+
const message = `The border guess was dropped: its draw leaves your commander on territory ${drawn.safety.territory} takeable (${drawn.safety.killers} of the replies tried), where the plan's own split does not, and warapp_submit_turn would refuse it.`;
|
|
1840
|
+
warnings.push(message);
|
|
1841
|
+
guess = undefined;
|
|
1842
|
+
guessSkip = { reason: 'commander', message };
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
// #275 (a): the smallest single deploy that takes each border of mine after the plan's orders.
|
|
1846
|
+
const headroom = safeHeadroom({
|
|
1847
|
+
graph,
|
|
1848
|
+
board,
|
|
1849
|
+
// #270: a static seat's territories are neutrals, as the plan reads them.
|
|
1850
|
+
staticSeats: staticSeats(game.players, game.endRules, me.id),
|
|
1851
|
+
me: me.id,
|
|
1852
|
+
deploys: plan.deploys,
|
|
1853
|
+
// #274: the commander walk carries it along, as warapp_check_plan's table on these orders does.
|
|
1854
|
+
moves: plan.moves.map((m) => ({ from: m.from, to: m.to, armies: m.armies, ...(m.commander ? { withCommander: true } : {}) })),
|
|
1855
|
+
settings,
|
|
1856
|
+
...(setup.teams ? { teams: setup.teams } : {}),
|
|
1857
|
+
...(mover.firstMover !== undefined && mover.verified ? { firstMover: mover.firstMover } : {}),
|
|
1858
|
+
...(advised ? { orderPriority: true } : {}),
|
|
1859
|
+
});
|
|
1860
|
+
const guessOrders = guess ? guessOrdersOf(orders, guess) : undefined;
|
|
1861
|
+
return respond(view, VIEWS, (rung) => ({
|
|
1862
|
+
game: { id: game.id, name: game.name ?? null, turn: currentTurn(game) },
|
|
1863
|
+
player: { id: me.id, name: me.name },
|
|
1864
|
+
// Part A1: messages not yet marked seen (warapp_get_chat reads them); absent when no chat can be read.
|
|
1865
|
+
...(chat ? { chat } : {}),
|
|
1866
|
+
goal: plan.goal,
|
|
1867
|
+
goalSource: goal !== undefined ? 'explicit' : 'profile',
|
|
1868
|
+
// #276: the guard case first, on or off, with what it means for interior defence.
|
|
1869
|
+
profile: rung === 'full'
|
|
1870
|
+
? { guard: guardCase(game.settings), ...plan.profile }
|
|
1871
|
+
: {
|
|
1872
|
+
guard: guardCase(game.settings),
|
|
1873
|
+
format: plan.profile.format,
|
|
1874
|
+
phase: plan.profile.phase,
|
|
1875
|
+
standing: plan.profile.standing,
|
|
1876
|
+
...(plan.profile.standingSource === 'tracked' ? { standingSource: 'tracked' } : {}),
|
|
1877
|
+
...(plan.profile.endsWith !== null ? { endsWith: plan.profile.endsWith } : {}),
|
|
1878
|
+
},
|
|
1879
|
+
// #178: the outlook and its basis; full adds each turn judged.
|
|
1880
|
+
outlook: rung === 'full' ? outlook : { state: outlook.state, basis: outlook.basis },
|
|
1881
|
+
// Part D: the opponent reads (reported only, never planned on); absent when none is at the bar.
|
|
1882
|
+
...(reads?.length
|
|
1883
|
+
? {
|
|
1884
|
+
reads: reads.map((r) => ({
|
|
1885
|
+
player: playerRef(r.id),
|
|
1886
|
+
labels: r.labels,
|
|
1887
|
+
// #264: when it last attacked me (null: no observed turn shows it), beside the labels.
|
|
1888
|
+
lastAttackTurn: r.lastAttackTurn,
|
|
1889
|
+
habits: confidentHabits(r.estimates),
|
|
1890
|
+
...(r.gamesMet !== undefined ? { gamesMet: r.gamesMet } : {}),
|
|
1891
|
+
...(rung === 'full' ? { counter: counterOf(r.labels) } : {}),
|
|
1892
|
+
})),
|
|
1893
|
+
}
|
|
1894
|
+
: {}),
|
|
1895
|
+
income,
|
|
1896
|
+
// #253: the army cap's arithmetic (min(income, round(cap × income) − my armies on the board)), when the game has one.
|
|
1897
|
+
...(setup.incomeCap ? { incomeCapped: setup.incomeCap } : {}),
|
|
1898
|
+
enemyDeploy: plan.enemyDeploy,
|
|
1899
|
+
// #127: who moves first this turn and how it is known; null when unknown.
|
|
1900
|
+
firstMover: mover.view,
|
|
1901
|
+
// #166: what the award of picks showed (absent when no pick list is kept for this game).
|
|
1902
|
+
...(award ? { award: awardView(award, game, turn, name) } : {}),
|
|
1903
|
+
trendSource: trend?.source ?? null,
|
|
1904
|
+
// #194: since last turn, when the previous turn's board or plan is known.
|
|
1905
|
+
...(since && turn !== null
|
|
1906
|
+
? { sinceLastTurn: sinceLastView(since, turn - 1, trend !== undefined, map, game.players, rung) }
|
|
1907
|
+
: {}),
|
|
1908
|
+
// #274: my commander, every turn of a Commanders game while it is on the board.
|
|
1909
|
+
...(guard
|
|
1910
|
+
? {
|
|
1911
|
+
commander: {
|
|
1912
|
+
text: commanderLine,
|
|
1913
|
+
territory: name(guard.territory),
|
|
1914
|
+
armies: guard.armies,
|
|
1915
|
+
movesToEnemy: guard.distance,
|
|
1916
|
+
killedBy: guard.killedBy
|
|
1917
|
+
? {
|
|
1918
|
+
deploy: guard.killedBy.deploy,
|
|
1919
|
+
player: playerRef(guard.killedBy.opponent),
|
|
1920
|
+
...(guard.killedBy.partner !== undefined ? { partner: playerRef(guard.killedBy.partner) } : {}),
|
|
1921
|
+
}
|
|
1922
|
+
: null,
|
|
1923
|
+
safe: guard.killers === 0 && !guard.lostUnanswered,
|
|
1924
|
+
needs: guard.needs,
|
|
1925
|
+
replyDeploy,
|
|
1926
|
+
},
|
|
1927
|
+
}
|
|
1928
|
+
: {}),
|
|
1929
|
+
conceded: plan.conceded.map(name),
|
|
1930
|
+
// #163: Order Delay when it is the only card advised (it is then in cards.advice.orderDelay too).
|
|
1931
|
+
cardAdvice: plan.cardAdvice ?? (advice.view.orderDelay ? 'order-delay' : null),
|
|
1932
|
+
multiSourceCaptures: plan.multiSourceCaptures.map(name),
|
|
1933
|
+
// #71: the frontier budget, one line on compact.
|
|
1934
|
+
frontier: rung === 'full'
|
|
1935
|
+
? plan.frontier
|
|
1936
|
+
: `${plan.frontier.borders} borders (${plan.frontier.enemyBorders} facing an enemy): holding them next turn needs ${plan.frontier.holdCost}, next income ${plan.expected.nextIncome}${plan.expected.nextIncomeIfConcededFall !== undefined &&
|
|
1937
|
+
plan.expected.nextIncomeIfConcededFall < plan.expected.nextIncome
|
|
1938
|
+
? `, ${plan.expected.nextIncomeIfConcededFall} if the conceded borders fall`
|
|
1939
|
+
: ''}${
|
|
1940
|
+
// #128: the figure the frontier is judged against, when it leaves out more (contested bonuses).
|
|
1941
|
+
plan.frontier.income < (plan.expected.nextIncomeIfConcededFall ?? plan.expected.nextIncome)
|
|
1942
|
+
? `; the plan counts on ${plan.frontier.income}`
|
|
1943
|
+
: ''}`,
|
|
1944
|
+
// #275 (a): each border's headroom, the weakest first (compact: the first few).
|
|
1945
|
+
headroom: headroomView(headroom, map, myIncome, rung === 'full', !teamsKnown),
|
|
1946
|
+
...(rung !== 'full' && headroom.length > HEADROOM_COMPACT ? { headroomMore: headroom.length - HEADROOM_COMPACT } : {}),
|
|
1947
|
+
// #72: the offensive options considered, full view only.
|
|
1948
|
+
...(rung === 'full' ? { offence: plan.offence.map((o) => ({ ...o, target: name(o.target) })) } : {}),
|
|
1949
|
+
// #167: each attack on a player judged by its exchange, full view only.
|
|
1950
|
+
...(rung === 'full' && plan.exchanges
|
|
1951
|
+
? { exchanges: plan.exchanges.map((e) => ({ ...e, from: name(e.from), to: name(e.to) })) }
|
|
1952
|
+
: {}),
|
|
1953
|
+
// #179: turns to eliminate each visible opponent, full view only.
|
|
1954
|
+
...(rung === 'full' && plan.eta ? { eta: plan.eta } : {}),
|
|
1955
|
+
// #179: where an opponent down to a few territories can go this turn, full view only.
|
|
1956
|
+
...(rung === 'full' && plan.exits
|
|
1957
|
+
? {
|
|
1958
|
+
exits: plan.exits.map((e) => ({
|
|
1959
|
+
player: e.player,
|
|
1960
|
+
stacks: e.stacks.map((x) => ({
|
|
1961
|
+
territory: name(x.territory),
|
|
1962
|
+
movable: x.movable,
|
|
1963
|
+
own: x.own.map(name),
|
|
1964
|
+
neutrals: x.neutrals.map(name),
|
|
1965
|
+
mine: x.mine.map(name),
|
|
1966
|
+
})),
|
|
1967
|
+
})),
|
|
1968
|
+
}
|
|
1969
|
+
: {}),
|
|
1970
|
+
cards: {
|
|
1971
|
+
hand: hand.map(cardView),
|
|
1972
|
+
...(handUnknown ? { handReadable: false } : {}),
|
|
1973
|
+
maxCardsHold: rules.maxCardsHold ?? null,
|
|
1974
|
+
playRequired: cards.required,
|
|
1975
|
+
plays: plays.map(cardView),
|
|
1976
|
+
discards: cards.discards.map(cardView),
|
|
1977
|
+
armiesFromCards: cards.extraArmies,
|
|
1978
|
+
...(Object.keys(advice.view).length ? { advice: advice.view } : {}),
|
|
1979
|
+
// PLAN-TEAMS C3.7: in a team game, who plays each card of the team hand this turn.
|
|
1980
|
+
...(inGame.team && hand.length
|
|
1981
|
+
? {
|
|
1982
|
+
team: {
|
|
1983
|
+
roles: teamCardRoles(hand, teamClaimed, {
|
|
1984
|
+
plays: [
|
|
1985
|
+
...plays,
|
|
1986
|
+
...(advice.view.orderDelay && orders.some((o) => o.kind === 'card' && o.card === advice.view.orderDelay.card)
|
|
1987
|
+
? myHand.filter((c) => c.id === advice.view.orderDelay.card)
|
|
1988
|
+
: []),
|
|
1989
|
+
],
|
|
1990
|
+
discards: cards.discards,
|
|
1991
|
+
}).map((r) => ({ ...r, by: r.by === null || r.by === 'me' ? r.by : playerRef(r.by) })),
|
|
1992
|
+
note: TEAM_CARDS_NOTE,
|
|
1993
|
+
},
|
|
1994
|
+
}
|
|
1995
|
+
: {}),
|
|
1996
|
+
},
|
|
1997
|
+
deploys: plan.deploys.map((d) => ({ territory: name(d.territoryId), armies: d.armies })),
|
|
1998
|
+
moves: plan.moves.map((m) => ({
|
|
1999
|
+
from: name(m.from),
|
|
2000
|
+
to: name(m.to),
|
|
2001
|
+
armies: m.armies,
|
|
2002
|
+
kind: m.kind,
|
|
2003
|
+
...(m.commander ? { commander: true } : {}),
|
|
2004
|
+
...(m.winChance !== undefined ? { winChance: Math.round(m.winChance * 1000) / 1000 } : {}),
|
|
2005
|
+
...(rung === 'full' ? { reason: m.reason } : {}),
|
|
2006
|
+
})),
|
|
2007
|
+
expected: {
|
|
2008
|
+
captures: plan.expected.captures.map(name),
|
|
2009
|
+
bonusesCompleted: plan.expected.bonusesCompleted.map((id) => {
|
|
2010
|
+
const b = map.bonuses.find((x) => x.id === id);
|
|
2011
|
+
return { id, name: b.name, value: b.value };
|
|
2012
|
+
}),
|
|
2013
|
+
nextIncome: plan.expected.nextIncome,
|
|
2014
|
+
// #109: present only when the plan's concessions put income at risk.
|
|
2015
|
+
...(plan.expected.nextIncomeIfConcededFall !== undefined
|
|
2016
|
+
? {
|
|
2017
|
+
nextIncomeIfConcededFall: plan.expected.nextIncomeIfConcededFall,
|
|
2018
|
+
bonusesAtRisk: (plan.expected.bonusesAtRisk ?? []).map((b) => ({
|
|
2019
|
+
id: b.bonusId,
|
|
2020
|
+
name: b.name,
|
|
2021
|
+
value: b.value,
|
|
2022
|
+
conceded: b.conceded.map(name),
|
|
2023
|
+
})),
|
|
2024
|
+
}
|
|
2025
|
+
: {}),
|
|
2026
|
+
},
|
|
2027
|
+
// B2: each truce as the plan treated it, the advice about them, and the tacit truces.
|
|
2028
|
+
...(plan.relations
|
|
2029
|
+
? {
|
|
2030
|
+
relations: plan.relations.map((r) => ({
|
|
2031
|
+
...r,
|
|
2032
|
+
player: playerRef(r.player),
|
|
2033
|
+
relaxed: r.relaxed.map(name),
|
|
2034
|
+
fullHold: r.fullHold.map((f) => ({ territory: name(f.territory), why: f.why })),
|
|
2035
|
+
...(r.capMoved ? { capMoved: r.capMoved.map((m) => ({ from: name(m.from), to: name(m.to), armies: m.armies })) } : {}),
|
|
2036
|
+
...(r.breach ? { breach: { ...r.breach, territories: r.breach.territories.map(name) } } : {}),
|
|
2037
|
+
lossIfBroken: r.lossIfBroken
|
|
2038
|
+
? {
|
|
2039
|
+
...r.lossIfBroken,
|
|
2040
|
+
from: name(r.lossIfBroken.from),
|
|
2041
|
+
to: name(r.lossIfBroken.to),
|
|
2042
|
+
territories: r.lossIfBroken.territories.map(name),
|
|
2043
|
+
bonuses: r.lossIfBroken.bonuses.map((b) => ({ id: b.id, name: map.bonuses.find((x) => x.id === b.id)?.name ?? String(b.id), value: b.value })),
|
|
2044
|
+
}
|
|
2045
|
+
: null,
|
|
2046
|
+
})),
|
|
2047
|
+
}
|
|
2048
|
+
: {}),
|
|
2049
|
+
...(plan.advice ? { advice: plan.advice.map((a) => ({ ...a, player: playerRef(a.player) })) } : {}),
|
|
2050
|
+
// PLAN-TEAMS D3: the cards in effect the plan relied on (an unverified decoder, so `verified: false`).
|
|
2051
|
+
...(effect.diplomacy.length || sanction.applied || effect.sanctionsOnOthers.length
|
|
2052
|
+
? {
|
|
2053
|
+
cardsInEffect: {
|
|
2054
|
+
...(effect.diplomacy.length ? { diplomacy: effect.diplomacy.map((d) => ({ player: playerRef(d.player), untilTurn: d.untilTurn })) } : {}),
|
|
2055
|
+
// G2: Sanctions on other players; `estimateCut` says whether the plan cut its estimate
|
|
2056
|
+
// (only a figure read off the board: an observed deploy may already carry the cut).
|
|
2057
|
+
...(effect.sanctionsOnOthers.length
|
|
2058
|
+
? {
|
|
2059
|
+
sanctionsOnOthers: effect.sanctionsOnOthers.map((x) => ({
|
|
2060
|
+
player: playerRef(x.player),
|
|
2061
|
+
percentage: x.percentage,
|
|
2062
|
+
untilTurn: x.untilTurn,
|
|
2063
|
+
estimateCut: estimates.find((e) => e.playerId === x.player)?.sanctioned?.applied === true,
|
|
2064
|
+
})),
|
|
2065
|
+
}
|
|
2066
|
+
: {}),
|
|
2067
|
+
...(sanction.applied
|
|
2068
|
+
? { sanctionsOnMe: effect.sanctionsOnMe.map((x) => ({ percentage: x.percentage, untilTurn: x.untilTurn })), incomeBefore: setup.boardIncome, incomeAfter: sanction.income }
|
|
2069
|
+
: {}),
|
|
2070
|
+
verified: false,
|
|
2071
|
+
note: CARDS_IN_EFFECT_UNVERIFIED,
|
|
2072
|
+
},
|
|
2073
|
+
}
|
|
2074
|
+
: {}),
|
|
2075
|
+
// Where the teams came from (GameFeed, else the game list), in a team game only.
|
|
2076
|
+
...(teamSource !== 'none' ? { teamSource } : {}),
|
|
2077
|
+
// PLAN-TEAMS C3.3: the bonuses I share with a teammate, advisory.
|
|
2078
|
+
...(plan.team
|
|
2079
|
+
? {
|
|
2080
|
+
team: {
|
|
2081
|
+
sharedBonuses: plan.team.sharedBonuses.map((b) => ({
|
|
2082
|
+
bonus: { id: b.bonusId, name: map.bonuses.find((x) => x.id === b.bonusId)?.name ?? String(b.bonusId), value: b.value },
|
|
2083
|
+
mine: b.mine.map(name),
|
|
2084
|
+
teammates: b.teammates.map((m) => ({ player: playerRef(m.player), territories: m.territories.map(name) })),
|
|
2085
|
+
others: b.others.length,
|
|
2086
|
+
nearer: b.nearer === null ? 'even' : b.nearer === me.id ? 'me' : playerRef(b.nearer),
|
|
2087
|
+
})),
|
|
2088
|
+
note: TEAM_SHARED_NOTE,
|
|
2089
|
+
// C3.5: a teammate's border my idle armies would make hold (advisory, V7).
|
|
2090
|
+
...(plan.team.support
|
|
2091
|
+
? {
|
|
2092
|
+
support: {
|
|
2093
|
+
borders: plan.team.support.map((x) => ({
|
|
2094
|
+
territory: name(x.territory),
|
|
2095
|
+
teammate: playerRef(x.teammate),
|
|
2096
|
+
armies: x.armies,
|
|
2097
|
+
threat: x.threat,
|
|
2098
|
+
player: playerRef(x.player),
|
|
2099
|
+
need: x.need,
|
|
2100
|
+
from: x.from.map((f) => ({ territory: name(f.territory), armies: f.armies })),
|
|
2101
|
+
})),
|
|
2102
|
+
note: TEAM_SUPPORT_NOTE,
|
|
2103
|
+
},
|
|
2104
|
+
}
|
|
2105
|
+
: {}),
|
|
2106
|
+
// C3.6: a target my teammate and I take only together (advisory).
|
|
2107
|
+
...(plan.team.jointCaptures
|
|
2108
|
+
? {
|
|
2109
|
+
jointCaptures: {
|
|
2110
|
+
targets: plan.team.jointCaptures.map((j) => {
|
|
2111
|
+
const who = (id) => (id === me.id ? 'me' : playerRef(id));
|
|
2112
|
+
return {
|
|
2113
|
+
target: name(j.target),
|
|
2114
|
+
owner: playerRef(j.owner),
|
|
2115
|
+
teammate: j.teammate.map((x) => ({ player: playerRef(x.player), from: name(x.from), armies: x.armies, ...(x.percent ? { percent: true } : {}) })),
|
|
2116
|
+
mine: j.mine.map((x) => ({ from: name(x.from), armies: x.armies })),
|
|
2117
|
+
inPlan: j.inPlan,
|
|
2118
|
+
cases: j.cases.map((c) => ({
|
|
2119
|
+
first: who(c.first),
|
|
2120
|
+
captured: c.captured,
|
|
2121
|
+
by: c.by === null ? null : who(c.by),
|
|
2122
|
+
capturedIfReinforced: c.capturedIfReinforced,
|
|
2123
|
+
})),
|
|
2124
|
+
...(j.mustGoFirst !== undefined ? { mustGoFirst: j.mustGoFirst === null ? 'either' : who(j.mustGoFirst) } : {}),
|
|
2125
|
+
exact: j.exact,
|
|
2126
|
+
};
|
|
2127
|
+
}),
|
|
2128
|
+
note: TEAM_JOINT_NOTE,
|
|
2129
|
+
},
|
|
2130
|
+
}
|
|
2131
|
+
: {}),
|
|
2132
|
+
},
|
|
2133
|
+
}
|
|
2134
|
+
: {}),
|
|
2135
|
+
...(truces?.tacit.length
|
|
2136
|
+
? { tacit: truces.tacit.map((t) => ({ player: playerRef(t.player), quietTurns: t.quietTurns, border: t.border.map(name) })) }
|
|
2137
|
+
: {}),
|
|
2138
|
+
warnings,
|
|
2139
|
+
rationale: plan.rationale,
|
|
2140
|
+
orders,
|
|
2141
|
+
// The border guess, only when there is one; why there is none, full view only.
|
|
2142
|
+
...(guess
|
|
2143
|
+
? {
|
|
2144
|
+
guess: guessView(guess, rung, name, game.players.find((p) => p.id === guess.opponent)?.name ?? null),
|
|
2145
|
+
guessOrders,
|
|
2146
|
+
}
|
|
2147
|
+
: rung === 'full' && guessSkip
|
|
2148
|
+
? { guessSkipped: guessSkip }
|
|
2149
|
+
: {}),
|
|
2150
|
+
...(rung === 'full'
|
|
2151
|
+
? {
|
|
2152
|
+
settings: {
|
|
2153
|
+
...settings,
|
|
2154
|
+
// #257: the planner's switch under its own name, and beside it the game's own
|
|
2155
|
+
// per-order options as GameFeed states them (null when it does not).
|
|
2156
|
+
idleTransfers: settings.idleTransfers ?? true,
|
|
2157
|
+
allowTransferOnly: game.settings?.allowTransferOnly ?? null,
|
|
2158
|
+
allowAttackOnly: game.settings?.allowAttackOnly ?? null,
|
|
2159
|
+
localDeployments: settings.localDeployments ?? false,
|
|
2160
|
+
noSplit: settings.noSplit ?? false,
|
|
2161
|
+
},
|
|
2162
|
+
}
|
|
2163
|
+
: {}),
|
|
2164
|
+
}));
|
|
2165
|
+
});
|
|
2166
|
+
const submitSchema = z.object({
|
|
2167
|
+
game_id: gameIdArg,
|
|
2168
|
+
player: playerArg,
|
|
2169
|
+
income: z.coerce
|
|
2170
|
+
.number()
|
|
2171
|
+
.int()
|
|
2172
|
+
.min(0)
|
|
2173
|
+
.max(MAX_ENEMY_DEPLOY)
|
|
2174
|
+
.optional()
|
|
2175
|
+
.describe('Only after war.app refused the modelled total (error 11): the "armies per turn" the game shows, before card ' +
|
|
2176
|
+
'plays. The deploys are then checked against it (plus played Reinforcement armies) instead of the model; ' +
|
|
2177
|
+
'the preview shows both.'),
|
|
2178
|
+
orders: turnOrdersArg.describe('The turn\'s orders (card plays and discards, deploys and attacks/transfers), territories by id or name, cards by id or type ' +
|
|
2179
|
+
'name — e.g. the `orders` array warapp_plan_turn returns. Deploys must total exactly your income plus the ' +
|
|
2180
|
+
'armies of played Reinforcement cards. An empty list commits a turn with no orders, as the game client allows; ' +
|
|
2181
|
+
'it is accepted only when that total is 0.'),
|
|
2182
|
+
break_agreement: z
|
|
2183
|
+
.boolean()
|
|
2184
|
+
.optional()
|
|
2185
|
+
.describe('Only when an order attacks (or a Bomb hits) a territory an active or in-notice truce covers (warapp_get_relations): true breaks ' +
|
|
2186
|
+
'it on purpose — the preview names the agreement, and once the orders are committed the ledger records it ' +
|
|
2187
|
+
'broken-by-me (the partner\'s player record too). Without it such orders are refused. Ask the owner first.'),
|
|
2188
|
+
accept_commander_risk: z
|
|
2189
|
+
.boolean()
|
|
2190
|
+
.optional()
|
|
2191
|
+
.describe('Only in a Commanders game, when the orders leave your commander takeable by a single-deploy reply (the refusal ' +
|
|
2192
|
+
'says so and names the armies that would hold): true submits them anyway, and the result records the risk ' +
|
|
2193
|
+
'taken (`commanderRiskAccepted`). Losing the commander loses the game: ask the owner first.'),
|
|
2194
|
+
});
|
|
2195
|
+
defineGatedWrite(server, {
|
|
2196
|
+
title: 'Submit my turn in a war.app game',
|
|
2197
|
+
_meta: mintMeta('change', ['submit my turn', 'commit orders', 'send my orders', 'end my turn']),
|
|
2198
|
+
}, {
|
|
2199
|
+
name: 'warapp_submit_turn',
|
|
2200
|
+
description: 'Commit your orders for the current turn of a war.app (Warzone) game: card plays, deploys, then ' +
|
|
2201
|
+
'attacks/transfers (territories by id or name, cards by id or type name — usually the `orders` from ' +
|
|
2202
|
+
'warapp_plan_turn, reviewed with the user). Plays Reinforcement, Order Priority, Order Delay and Blockade ' +
|
|
2203
|
+
'(with a `target` of yours; an Order Delay goes after every move unless it has `before`: a move number to ' +
|
|
2204
|
+
'place it above, unverified live) from your hand, and the targeted cards — Spy (`player`), Reconnaissance ' +
|
|
2205
|
+
'(`target`), Surveillance (`bonus`), Airlift (`from` yours, `to` yours or a teammate\'s, `armies`, optional ' +
|
|
2206
|
+
'`commander`), Gift (`target` yours, `player`), Diplomacy (`players`: two), Sanctions (`player`), Bomb (`target` ' +
|
|
2207
|
+
"next to yours, not yours or a teammate's) and Emergency Blockade (`target` yours, never your commander's), encoded " +
|
|
2208
|
+
'as the client does but not yet verified live, each refused where war.app would refuse it (a commander is never ' +
|
|
2209
|
+
'gifted or airlifted to a teammate, no Spy or Sanctions on yourself or a teammate, no Diplomacy between ' +
|
|
2210
|
+
'teammates); discards any card (`{ kind: "discard", card }`); refuses ' +
|
|
2211
|
+
'when your hand is over the hold limit and the orders do not play or discard enough cards; in a team game warns ' +
|
|
2212
|
+
'when they play or discard a card your teammate has already entered (a card named by type is one nobody ' +
|
|
2213
|
+
'entered when there is one). The ' +
|
|
2214
|
+
'orders reach the game and cannot be withdrawn here; when the turn resolves, other players see the results. ' +
|
|
2215
|
+
'Validated against the live board first: deploys on and moves from your own territories, moves to ' +
|
|
2216
|
+
'adjacent ones, no more armies than a territory has, deploys totalling exactly your income plus played ' +
|
|
2217
|
+
'Reinforcement armies (only a preview warning when a setting such as an army cap makes the modelled ' +
|
|
2218
|
+
'income uncertain; after war.app\'s error 11, resend with the game\'s own number as `income`); under Local Deployment, each held bonus\'s armies deployed inside that bonus; under ' +
|
|
2219
|
+
'No-Split, at most one attack or transfer per territory (and a warning when one sends less than the whole ' +
|
|
2220
|
+
'stack, which war.app moves anyway); under Multi-Attack, a move (not a deploy) may go on from a ' +
|
|
2221
|
+
'territory an earlier move in the list captures (warapp_plan_turn obeys these and the kill rates). ' +
|
|
2222
|
+
'A move may carry options, each refused unless the game allows it: `mode` "transfer-only" (AllowTransferOnly) ' +
|
|
2223
|
+
'or "attack-only" (AllowAttackOnly), `percent` (AllowPercentageAttacks: `armies` is a percentage of what can ' +
|
|
2224
|
+
'move when it runs), `commander` (take your commander along; `armies` 0 sends it alone) and ' +
|
|
2225
|
+
'`attack_teammates` (team games); these are encoded as the client does but not yet verified live. ' +
|
|
2226
|
+
'With One Army Must Stand Guard off the preview names territories left empty; with mods on it says the rules may differ. ' +
|
|
2227
|
+
'The preview sizes each attack against the armies standing there now (`attacks`: expected kills, win chance; ' +
|
|
2228
|
+
'several attacks on one target in the order listed, each against what the earlier ones leave) ' +
|
|
2229
|
+
'and warns about one that cannot capture; it also warns (never refuses) when the orders leave a border of a bonus you hold ' +
|
|
2230
|
+
'falling to a single deploy below your own income (the headroom table, as warapp_plan_turn has it), and when they leave ' +
|
|
2231
|
+
'a border below what the default plan made now (warapp_plan_turn with no options, or its border guess when the deploys ' +
|
|
2232
|
+
'are the guess\'s) leaves standing there, naming each with the difference (the plan\'s figure carries its surplus). An order that attacks (or a Bomb that hits) a territory an active or in-notice truce ' +
|
|
2233
|
+
'covers (the agreement ledger) is refused unless `break_agreement` is true; then the preview names the agreement ' +
|
|
2234
|
+
'and, once the orders are committed, the ledger records it broken-by-me. In a Commanders game, orders that ' +
|
|
2235
|
+
'leave your commander takeable by one opponent\'s single deploy, or two striking together when you lead a ' +
|
|
2236
|
+
'free-for-all (each reply sized at the larger of its estimate and your income, on the live board; your Airlifts counted, ' +
|
|
2237
|
+
'after the deploys and before the moves) are refused with the armies that would hold, and so is a Blockade or Gift ' +
|
|
2238
|
+
'of a territory your commander stands on before or after the orders, unless `accept_commander_risk` ' +
|
|
2239
|
+
'is true (the result then records `commanderRiskAccepted`). Always sent as ' +
|
|
2240
|
+
'the signed-in war.app account; refuses if you have already committed this turn. Success is confirmed from ' +
|
|
2241
|
+
`game state (turn advanced, or your orders marked committed). ${BRIDGE_NOTE} ${CONFIRM_INJECTION_RULE}`,
|
|
2242
|
+
annotations: toolAnnotations({
|
|
2243
|
+
title: 'Submit a war.app turn',
|
|
2244
|
+
readOnly: false,
|
|
2245
|
+
destructive: true,
|
|
2246
|
+
idempotent: false,
|
|
2247
|
+
openWorld: true,
|
|
2248
|
+
}),
|
|
2249
|
+
inputSchema: submitSchema,
|
|
2250
|
+
async plan({ game_id, player, orders, income: givenIncome, break_agreement, accept_commander_risk }) {
|
|
2251
|
+
const feed = await ctx.client.getGame(parseGameId(game_id), { settings: true });
|
|
2252
|
+
requireTurnPhase(feed);
|
|
2253
|
+
// The bridge always acts as the signed-in account: an explicit `player` naming anyone
|
|
2254
|
+
// else is refused, and so is a call when that account cannot be read (never trust `player` alone).
|
|
2255
|
+
const seat = await requireMySeat(ctx, feed, { player, playing: false });
|
|
2256
|
+
requirePlayingSeat(feed, seat);
|
|
2257
|
+
if (seat.hasCommittedOrders) {
|
|
2258
|
+
throw new McpToolError(`You have already committed orders for this turn of game ${feed.id}.`, {
|
|
2259
|
+
hint: 'To change them, withdraw them first with warapp_uncommit_turn (confirm-gated), then submit again — ' +
|
|
2260
|
+
'or use "Modify orders" in the game itself; this tool does not replace committed orders.',
|
|
2261
|
+
});
|
|
2262
|
+
}
|
|
2263
|
+
// The teams (the teammate set): GameFeed's, else the game list's (asked once per game, kept).
|
|
2264
|
+
const { game, me, known: teamsKnown } = await resolveTeamsFor(ctx, feed, seat);
|
|
2265
|
+
const turnNumber = currentTurn(game);
|
|
2266
|
+
if (turnNumber === null || game.numberOfTurns === undefined) {
|
|
2267
|
+
throw new McpToolError(`GameFeed did not say how many turns game ${game.id} has had, so the turn number is unknown.`, {
|
|
2268
|
+
hint: 'Retry in a moment; no orders were sent.',
|
|
2269
|
+
});
|
|
2270
|
+
}
|
|
2271
|
+
const map = mapOf(game);
|
|
2272
|
+
const deploys = [];
|
|
2273
|
+
const moves = [];
|
|
2274
|
+
const cardInputs = [];
|
|
2275
|
+
const discardInputs = [];
|
|
2276
|
+
for (const o of orders) {
|
|
2277
|
+
if (o.kind === 'card') {
|
|
2278
|
+
const { kind: _kind, ...card } = o;
|
|
2279
|
+
cardInputs.push(card);
|
|
2280
|
+
}
|
|
2281
|
+
else if (o.kind === 'discard') {
|
|
2282
|
+
discardInputs.push({ card: o.card });
|
|
2283
|
+
}
|
|
2284
|
+
else if (o.kind === 'deploy') {
|
|
2285
|
+
const t = resolveTerritory(map, o.territory);
|
|
2286
|
+
deploys.push({ territory: { id: t.id, name: t.name }, armies: o.armies });
|
|
2287
|
+
}
|
|
2288
|
+
else {
|
|
2289
|
+
const f = resolveTerritory(map, o.from);
|
|
2290
|
+
const t = resolveTerritory(map, o.to);
|
|
2291
|
+
moves.push({
|
|
2292
|
+
from: { id: f.id, name: f.name },
|
|
2293
|
+
to: { id: t.id, name: t.name },
|
|
2294
|
+
armies: o.armies,
|
|
2295
|
+
...(o.mode !== undefined && o.mode !== 'attack-transfer' ? { mode: o.mode } : {}),
|
|
2296
|
+
...(o.percent ? { percent: true } : {}),
|
|
2297
|
+
...(o.commander ? { commander: true } : {}),
|
|
2298
|
+
...(o.attack_teammates ? { attackTeammates: true } : {}),
|
|
2299
|
+
});
|
|
2300
|
+
}
|
|
2301
|
+
}
|
|
2302
|
+
const { territories, info } = await loadLiveGame(ctx, game);
|
|
2303
|
+
const board = withTeammateOrders(boardStateFromLive(territories, me, game.players), info, me, game.players);
|
|
2304
|
+
const playerId = inGameId(me);
|
|
2305
|
+
const rules = cardRules(game.settings);
|
|
2306
|
+
// A team shares one hand (#163): cards under my teammates may be played or discarded too. But how
|
|
2307
|
+
// war.app keys a team's hand is unverified, so the hard refusal (error 51) counts only my own cards,
|
|
2308
|
+
// as before, and the team's gathered count is a warning until a live team board verifies it.
|
|
2309
|
+
const owners = handOwners(game, me);
|
|
2310
|
+
const myHand = readHand(info, playerId);
|
|
2311
|
+
const hand = owners.length > 1 ? readHand(info, owners) : myHand;
|
|
2312
|
+
const handUnknown = rules.inPlay.length > 0 && !handReadable(info, playerId);
|
|
2313
|
+
// G3: the cards my teammates' entered orders already play or discard (V5, unverified live). A card named
|
|
2314
|
+
// by its type resolves to one nobody entered when there is one; one named by id that they entered is warned of.
|
|
2315
|
+
const { claimed } = teamHandLeft(hand, teamCardClaims(board.teammateOrders, new Set(teammatesOf(game.players, me).map((p) => p.id))));
|
|
2316
|
+
const pickFrom = unclaimedFirst(hand, claimed);
|
|
2317
|
+
const plays = resolveCardPlays(map, pickFrom, rules, cardInputs);
|
|
2318
|
+
// #186: an Order Delay's `before` names a move of this list (1-based); one past the last is the default.
|
|
2319
|
+
for (const p of plays) {
|
|
2320
|
+
if (p.before !== undefined && p.before > moves.length + 1) {
|
|
2321
|
+
throw new McpToolError(`Order Delay \`before\` ${p.before} is past this turn's ${moves.length} move${moves.length === 1 ? '' : 's'}.`, { hint: `Give a move number 1–${moves.length + 1} (${moves.length + 1}, or no \`before\`, writes it after every move).` });
|
|
2322
|
+
}
|
|
2323
|
+
}
|
|
2324
|
+
/** The move (1-based) an Order Delay is placed above, when it is placed among the moves. */
|
|
2325
|
+
const placedAt = (p) => (p.before !== undefined && p.before <= moves.length ? p.before : undefined);
|
|
2326
|
+
const discards = resolveDiscards(pickFrom, plays, discardInputs);
|
|
2327
|
+
// Every play and discard takes its card out of the hand; war.app refuses (error 51) while more
|
|
2328
|
+
// than MaxCardsHold remain (verified, #20).
|
|
2329
|
+
const used = plays.length + discards.length;
|
|
2330
|
+
const shed = cardsToShed(myHand, rules);
|
|
2331
|
+
if (used < shed)
|
|
2332
|
+
throw mustPlayCard(myHand, rules, shed, used);
|
|
2333
|
+
const teamShed = owners.length > 1 ? cardsToShed(hand, rules) : 0;
|
|
2334
|
+
for (const p of plays) {
|
|
2335
|
+
const t = p.target && territories.find((x) => x.territoryId === p.target.id);
|
|
2336
|
+
if (p.target && (!t || t.fogged || t.owner !== playerId)) {
|
|
2337
|
+
throw new McpToolError(`${label(p.target)} is not yours at the start of this turn, so it cannot be blockaded.`, {
|
|
2338
|
+
hint: 'A Blockade targets a territory you hold on the live board (warapp_get_live_board).',
|
|
2339
|
+
});
|
|
2340
|
+
}
|
|
2341
|
+
// A Blockade turns the territory neutral: my commander there would be lost with it (#163).
|
|
2342
|
+
if (t?.specialUnits?.some((u) => u.kind === 'commander' && u.owner === playerId)) {
|
|
2343
|
+
throw new McpToolError(`${label(p.target)} holds your commander, so it cannot be blockaded.`, {
|
|
2344
|
+
hint: 'A Blockade makes the territory neutral and your commander on it would be lost (a commander must stay on your land). Move the commander out first, or blockade another territory.',
|
|
2345
|
+
});
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
// A move into a teammate's territory is a transfer (GameFeed's team field is unverified). The live
|
|
2349
|
+
// board keys owners by in-game id; a teammate without a GameFeed player id (an AI seat) owns nothing by one.
|
|
2350
|
+
const teammates = new Set([...playersByInGameId(teammatesOf(game.players, me)).keys()]);
|
|
2351
|
+
const deployedOn = new Map();
|
|
2352
|
+
for (const d of deploys)
|
|
2353
|
+
deployedOn.set(d.territory.id, (deployedOn.get(d.territory.id) ?? 0) + d.armies);
|
|
2354
|
+
// PLAN-TEAMS part D: the targeted cards, refused where war.app's validator (the bundle's) would refuse them.
|
|
2355
|
+
const cardContext = {
|
|
2356
|
+
map,
|
|
2357
|
+
board: territories,
|
|
2358
|
+
me,
|
|
2359
|
+
myInGameId: playerId,
|
|
2360
|
+
players: game.players,
|
|
2361
|
+
teammates: friendsOf(game.players, me),
|
|
2362
|
+
settings: game.settings,
|
|
2363
|
+
rules,
|
|
2364
|
+
deployedOn,
|
|
2365
|
+
movesFrom: new Set(moves.map((m) => m.from.id)),
|
|
2366
|
+
seen: newCardPlaySeen(),
|
|
2367
|
+
};
|
|
2368
|
+
for (const p of plays) {
|
|
2369
|
+
if (UNVERIFIED_CARD_PLAYS.has(p.kind))
|
|
2370
|
+
p.targets = resolveCardTargets(p.kind, p.card.name, p.input, cardContext);
|
|
2371
|
+
}
|
|
2372
|
+
// An Emergency Blockade (phase 37) turns its territory neutral before an Airlift (phase 43) runs.
|
|
2373
|
+
for (const p of plays) {
|
|
2374
|
+
const a = p.kind === 'Airlift' ? p.targets : undefined;
|
|
2375
|
+
const hit = a && [a.from, a.to].find((t) => t && cardContext.seen.blockaded.has(t.id));
|
|
2376
|
+
if (hit) {
|
|
2377
|
+
throw new McpToolError(`${label(hit)} is blockaded before the Airlift runs, so the Airlift ${hit === a.from ? 'from' : 'to'} it cannot happen.`, {
|
|
2378
|
+
hint: 'The Emergency Blockade turns the territory neutral first: airlift elsewhere, or blockade another territory.',
|
|
2379
|
+
});
|
|
2380
|
+
}
|
|
2381
|
+
}
|
|
2382
|
+
if (cardContext.seen.commanderAirlifted && moves.some((m) => m.commander)) {
|
|
2383
|
+
throw new McpToolError('Your commander is both airlifted and taken along on a move.', {
|
|
2384
|
+
hint: 'The Airlift runs before the moves; take the commander in one order only.',
|
|
2385
|
+
});
|
|
2386
|
+
}
|
|
2387
|
+
// #165: each move's options, refused unless the game allows them.
|
|
2388
|
+
const options = checkMoveOptions({ moves, board: territories, myInGameId: playerId, settings: game.settings, teammates, deployedOn });
|
|
2389
|
+
// #253: the army cap's cut included (min(income, round(cap × income) − my armies on the board)).
|
|
2390
|
+
const incomeOnBoard = incomeDetail(graphOf(map), board, me.id, game.settings);
|
|
2391
|
+
const modelled = incomeOnBoard.income;
|
|
2392
|
+
const cardArmies = plays.reduce((sum, p) => sum + p.armies, 0);
|
|
2393
|
+
// #130: war.app's own number, given after an error 11, replaces the model for the check.
|
|
2394
|
+
const income = (givenIncome ?? modelled) + cardArmies;
|
|
2395
|
+
const overridden = givenIncome !== undefined && givenIncome !== modelled
|
|
2396
|
+
? `income ${givenIncome} given (the game's armies per turn), modelled ${modelled}`
|
|
2397
|
+
: undefined;
|
|
2398
|
+
// B2: an order that attacks a territory an active or in-notice truce covers is refused unless the
|
|
2399
|
+
// caller breaks the agreement on purpose (the plan never orders a surprise break, T7).
|
|
2400
|
+
const bombs = plays.flatMap((p, play) => p.kind === 'Bomb' && p.targets?.territory ? [{ play, target: p.targets.territory.id }] : []);
|
|
2401
|
+
const bombPlays = bombs.map((x) => x.play);
|
|
2402
|
+
const ledger = ctx.dataDir ? await readLedger(ctx.dataDir, game.id, me.id) : undefined;
|
|
2403
|
+
const breaks = ctx.dataDir
|
|
2404
|
+
? truceBreaksIn({
|
|
2405
|
+
agreements: ledger?.agreements ?? [],
|
|
2406
|
+
graph: graphOf(map),
|
|
2407
|
+
board,
|
|
2408
|
+
me: me.id,
|
|
2409
|
+
turn: turnNumber,
|
|
2410
|
+
players: game.players.map((p) => ({
|
|
2411
|
+
id: p.id,
|
|
2412
|
+
isAI: p.isAI,
|
|
2413
|
+
humanTurnedIntoAI: p.humanTurnedIntoAI,
|
|
2414
|
+
...(p.state !== undefined ? { state: p.state } : {}),
|
|
2415
|
+
...(p.team !== undefined ? { team: p.team } : {}),
|
|
2416
|
+
})),
|
|
2417
|
+
moves: moves.map((m) => ({ from: m.from.id, to: m.to.id, ...(m.mode !== undefined ? { mode: m.mode } : {}) })),
|
|
2418
|
+
// A Bomb halves its target's armies: an attack on the partner like a move into it.
|
|
2419
|
+
bombs: bombs.map((x) => x.target),
|
|
2420
|
+
})
|
|
2421
|
+
: [];
|
|
2422
|
+
if (breaks.length && break_agreement !== true) {
|
|
2423
|
+
throw new McpToolError(`${breaksText(breaks, moves, bombPlays)}: nothing was sent.`, {
|
|
2424
|
+
hint: 'Drop those orders, or give notice (warapp_record_agreement status notice-by-me) and wait until it runs. ' +
|
|
2425
|
+
'If the partner broke it first, record broken-by-them with warapp_record_agreement. To break it on purpose ' +
|
|
2426
|
+
'(ask the owner first), resend with break_agreement: true — the ledger then records it broken-by-me.',
|
|
2427
|
+
});
|
|
2428
|
+
}
|
|
2429
|
+
const { warnings } = validateTurn({
|
|
2430
|
+
map,
|
|
2431
|
+
board: territories,
|
|
2432
|
+
myInGameId: playerId,
|
|
2433
|
+
income,
|
|
2434
|
+
guard: game.settings?.oneArmyStandsGuard ?? true,
|
|
2435
|
+
deploys,
|
|
2436
|
+
moves,
|
|
2437
|
+
airlifts: plays.flatMap((p) => p.kind === 'Airlift' && p.targets?.from && p.targets.to && p.targets.armies !== undefined
|
|
2438
|
+
? [{ from: p.targets.from.id, to: p.targets.to.id, armies: p.targets.armies }]
|
|
2439
|
+
: []),
|
|
2440
|
+
localDeployments: game.settings?.localDeployments ?? false,
|
|
2441
|
+
noSplit: game.settings?.noSplit ?? false,
|
|
2442
|
+
multiAttack: game.settings?.multiAttack ?? false,
|
|
2443
|
+
unplayedReinforcements: hand.flatMap((c) => {
|
|
2444
|
+
if (c.type !== CARD_REINFORCEMENT || plays.some((p) => p.card.id === c.id))
|
|
2445
|
+
return [];
|
|
2446
|
+
const armies = reinforcementArmies(c, rules);
|
|
2447
|
+
return armies === undefined ? [] : [{ id: c.id, armies }];
|
|
2448
|
+
}),
|
|
2449
|
+
incomeUncertain: givenIncome !== undefined
|
|
2450
|
+
? []
|
|
2451
|
+
: deployCheckUncertainties(game.settings, incomeOnBoard.cap ? { armyCap: incomeOnBoard.cap } : {}),
|
|
2452
|
+
poolsUncertain: [
|
|
2453
|
+
...overrideUncertainties(game.settings),
|
|
2454
|
+
...(overridden ? [`The ${overridden}, so the bonus pools may differ too.`] : []),
|
|
2455
|
+
// J1 review: the cap's cut total is modelled, how war.app takes it out of the pools is not.
|
|
2456
|
+
...[armyCapPoolsUncertainty(incomeOnBoard.cap, game.settings?.localDeployments)].filter((r) => r !== undefined),
|
|
2457
|
+
],
|
|
2458
|
+
});
|
|
2459
|
+
if (overridden)
|
|
2460
|
+
warnings.unshift(`Deploys checked against the ${overridden}.`);
|
|
2461
|
+
// J1 review: as warapp_plan_turn says, an unreadable army count of mine leaves the cap unapplied.
|
|
2462
|
+
else if (givenIncome === undefined && incomeOnBoard.capUnknown)
|
|
2463
|
+
warnings.unshift(`Deploys checked against income ${modelled}, not cut by the army cap: an army count of yours is unreadable on the board, ` +
|
|
2464
|
+
"so the cap's cut could not be worked out (pass the game's own number as income if it differs).");
|
|
2465
|
+
if (breaks.length)
|
|
2466
|
+
warnings.unshift(`${breaksText(breaks, moves, bombPlays)}. break_agreement is true: once these orders are committed the ledger records ` +
|
|
2467
|
+
`${breaks.length === 1 ? 'it' : 'them'} broken-by-me, and the partner's player record says so. That is final: ` +
|
|
2468
|
+
'withdrawing the orders afterwards (warapp_uncommit_turn) does not undo it.');
|
|
2469
|
+
// B4: what my chat messages promised (warapp_send_chat's commitments): a warning, never a refusal.
|
|
2470
|
+
const promises = commitmentWarnings({
|
|
2471
|
+
commitments: ledger?.commitments ?? [],
|
|
2472
|
+
agreements: ledger?.agreements ?? [],
|
|
2473
|
+
graph: graphOf(map),
|
|
2474
|
+
board,
|
|
2475
|
+
me: me.id,
|
|
2476
|
+
turn: turnNumber,
|
|
2477
|
+
moves: moves.map((m) => ({ from: m.from.id, to: m.to.id, ...(m.mode === 'transfer-only' ? { transferOnly: true } : {}) })),
|
|
2478
|
+
});
|
|
2479
|
+
for (const p of promises)
|
|
2480
|
+
warnings.push(p.unchecked
|
|
2481
|
+
? `Your chat ${p.text}. Find out whose it is before committing these orders: if it is that player's, keep the ` +
|
|
2482
|
+
'promise (change them), or ask the owner and tell the player before breaking it — never silently.'
|
|
2483
|
+
: `Your chat ${p.text}. Keep the promise (change these orders), or ask the owner and tell the player before ` +
|
|
2484
|
+
'breaking it — never silently.');
|
|
2485
|
+
warnings.push(...options.warnings);
|
|
2486
|
+
warnings.push(...modsWarning(game.settings), ...guardOffWarnings(graphOf(map), map, board, me.id, friendsOf(game.players, me), game.settings, deploys.map((d) => ({ territoryId: d.territory.id, armies: d.armies })), moves.map((m, i) => ({ from: m.from.id, to: m.to.id, armies: m.percent ? (options.estimates.get(i) ?? 0) : m.armies }))));
|
|
2487
|
+
if (handUnknown)
|
|
2488
|
+
warnings.push(UNREADABLE_HAND);
|
|
2489
|
+
for (const p of plays)
|
|
2490
|
+
warnings.push(...(p.targets?.warnings ?? []));
|
|
2491
|
+
const unverifiedPlays = [...new Set(plays.filter((p) => UNVERIFIED_CARD_PLAYS.has(p.kind)).map((p) => p.card.name))];
|
|
2492
|
+
if (unverifiedPlays.length)
|
|
2493
|
+
warnings.push(unverifiedCardWarning(unverifiedPlays));
|
|
2494
|
+
if (used < teamShed)
|
|
2495
|
+
warnings.push(teamHandOver(hand.length, rules, teamShed, used));
|
|
2496
|
+
// V8: a card read only under a teammate's id may be theirs to play; war.app has the last word.
|
|
2497
|
+
const theirs = [...plays.map((p) => p.card), ...discards].filter((c) => !isMyCard(c, playerId));
|
|
2498
|
+
if (theirs.length)
|
|
2499
|
+
warnings.push(teammateCardWarning(theirs));
|
|
2500
|
+
const clash = claimedCardWarning(claimedCardUses([...plays.map((p) => ({ card: p.card, kind: 'play' })), ...discards.map((c) => ({ card: c, kind: 'discard' }))], claimed));
|
|
2501
|
+
if (clash)
|
|
2502
|
+
warnings.push(clash);
|
|
2503
|
+
const placedDelays = plays.filter((p) => placedAt(p) !== undefined);
|
|
2504
|
+
for (const p of placedDelays) {
|
|
2505
|
+
const m = moves[placedAt(p) - 1];
|
|
2506
|
+
warnings.push(`Order Delay is written above move ${placedAt(p)} (${label(m.from)} → ${label(m.to)}), so that move and the ones ` +
|
|
2507
|
+
"after it wait until the opponents' attacks have run. UNVERIFIED live: no commit has yet placed the card among " +
|
|
2508
|
+
"the moves. war.app refusing it with error 10 (OrdersInIncorrectOrder) means it is not allowed there — resend " +
|
|
2509
|
+
'without `before`.');
|
|
2510
|
+
}
|
|
2511
|
+
if (plays.some((p) => p.kind === 'OrderDelay' && placedAt(p) === undefined)) {
|
|
2512
|
+
// Phase 50, after every move, is the only live-verified position for the card.
|
|
2513
|
+
warnings.push("Order Delay is written after every move (its only verified position), so it delays none of this turn's " +
|
|
2514
|
+
'orders: playing it only spends the card, as a discard would. Give it `before` (a move number) to place it ' +
|
|
2515
|
+
'among the moves (unverified live).');
|
|
2516
|
+
}
|
|
2517
|
+
// #274: in a Commanders game, orders that leave my commander takeable by one deploy are refused
|
|
2518
|
+
// unless accepted on purpose; each reply sized at the larger of the opponent's estimate and my income.
|
|
2519
|
+
const commanderChecked = game.settings?.commanders === true
|
|
2520
|
+
? await commanderCheck(ctx, {
|
|
2521
|
+
game,
|
|
2522
|
+
me,
|
|
2523
|
+
map,
|
|
2524
|
+
seen: board,
|
|
2525
|
+
turn: turnNumber,
|
|
2526
|
+
info,
|
|
2527
|
+
hand,
|
|
2528
|
+
income: givenIncome ?? modelled,
|
|
2529
|
+
...(teamsKnown ? {} : { teamsKnown: false }),
|
|
2530
|
+
deploys: deploys.map((d) => ({ territoryId: d.territory.id, armies: d.armies })),
|
|
2531
|
+
moves: moves.map((m) => ({
|
|
2532
|
+
from: m.from.id,
|
|
2533
|
+
to: m.to.id,
|
|
2534
|
+
armies: m.armies,
|
|
2535
|
+
...(m.mode === 'attack-only' || m.mode === 'transfer-only' ? { mode: m.mode } : {}),
|
|
2536
|
+
...(m.percent ? { byPercent: true } : {}),
|
|
2537
|
+
...(m.commander ? { withCommander: true } : {}),
|
|
2538
|
+
...(m.attackTeammates ? { attackTeammates: true } : {}),
|
|
2539
|
+
})),
|
|
2540
|
+
orderPriority: plays.some((p) => p.kind === 'OrderPriority'),
|
|
2541
|
+
// The Airlifts are simulated (after the deploys, before the moves); a Blockade or Gift of the
|
|
2542
|
+
// commander's territory is not, and is refused there unless accepted.
|
|
2543
|
+
airlifts: plays.flatMap((p) => p.kind === 'Airlift' && p.targets?.from && p.targets.to
|
|
2544
|
+
? [{ from: p.targets.from.id, to: p.targets.to.id, armies: p.targets.armies ?? 0, ...(p.targets.commander ? { commander: true } : {}) }]
|
|
2545
|
+
: []),
|
|
2546
|
+
cardTargets: plays.flatMap((p) => {
|
|
2547
|
+
const t = p.target ?? p.targets?.territory;
|
|
2548
|
+
return t ? [{ kind: p.kind, territory: t.id }] : [];
|
|
2549
|
+
}),
|
|
2550
|
+
})
|
|
2551
|
+
: undefined;
|
|
2552
|
+
const commanderRisk = commanderChecked?.risk && commanderChecked.text ? { risk: commanderChecked.risk, text: commanderChecked.text } : undefined;
|
|
2553
|
+
if (commanderRisk && accept_commander_risk !== true) {
|
|
2554
|
+
const anyway = 'To submit these orders anyway (ask the owner first), resend with accept_commander_risk: true.';
|
|
2555
|
+
// Under Local Deployment a deploy there must come from a pool that reaches it (#274 review).
|
|
2556
|
+
const local = game.settings?.localDeployments === true
|
|
2557
|
+
? ' Under Local Deployment only free income or the pool of a bonus that contains that territory may be deployed there; an Airlift onto it is the other way.'
|
|
2558
|
+
: '';
|
|
2559
|
+
throw new McpToolError(`${commanderRisk.text} Nothing was sent.`, {
|
|
2560
|
+
hint: commanderRisk.risk.replies === 0 && commanderChecked?.cards?.length
|
|
2561
|
+
? `Play the card on a territory your commander does not stand on, or keep the commander off it. ${anyway}`
|
|
2562
|
+
: commanderRisk.risk.needs !== null
|
|
2563
|
+
? `Put at least ${commanderRisk.risk.needs} armies on territory ${commanderRisk.risk.territory} after your orders (deploy more there, airlift fewer off it, or move fewer out), or move the commander away from the enemy; warapp_check_plan shows every reply.${local} ${anyway}`
|
|
2564
|
+
: `Move the commander away from the enemy; warapp_check_plan shows every reply. ${anyway}`,
|
|
2565
|
+
});
|
|
2566
|
+
}
|
|
2567
|
+
if (commanderRisk)
|
|
2568
|
+
warnings.unshift(`accept_commander_risk is true: ${commanderRisk.text}`);
|
|
2569
|
+
const attacks = attackSizes(territories, playerId, moves.map((m, i) => ({ ...m, ...(options.estimates.has(i) ? { estimate: options.estimates.get(i) } : {}) })), plannerSettings(game.settings), teammates);
|
|
2570
|
+
const hopeless = hopelessAttackWarning(attacks, label);
|
|
2571
|
+
if (hopeless)
|
|
2572
|
+
warnings.push(hopeless);
|
|
2573
|
+
// #275 (c): a border of a held bonus these orders leave falling to a deploy below my own income.
|
|
2574
|
+
// A warning, never a refusal; the stress test (warapp_check_plan) tries the replies in full.
|
|
2575
|
+
const subTeams = teamsOf(game.players);
|
|
2576
|
+
const givenDeploys = deploys.map((d) => ({ territoryId: d.territory.id, armies: d.armies }));
|
|
2577
|
+
const givenMoves = moves.map((m, i) => ({
|
|
2578
|
+
from: m.from.id,
|
|
2579
|
+
to: m.to.id,
|
|
2580
|
+
armies: m.percent ? (options.estimates.get(i) ?? 0) : m.armies,
|
|
2581
|
+
...(m.mode === 'attack-only' || m.mode === 'transfer-only' ? { mode: m.mode } : {}),
|
|
2582
|
+
...(m.commander ? { withCommander: true } : {}),
|
|
2583
|
+
...(m.attackTeammates ? { attackTeammates: true } : {}),
|
|
2584
|
+
}));
|
|
2585
|
+
warnings.push(...headroomWarnings(safeHeadroom({
|
|
2586
|
+
graph: graphOf(map),
|
|
2587
|
+
board,
|
|
2588
|
+
// #270: a static seat deploys nothing; its territories are neutrals here.
|
|
2589
|
+
staticSeats: staticSeats(game.players, game.endRules, me.id),
|
|
2590
|
+
me: me.id,
|
|
2591
|
+
deploys: givenDeploys,
|
|
2592
|
+
moves: givenMoves,
|
|
2593
|
+
settings: plannerSettings(game.settings),
|
|
2594
|
+
...(subTeams ? { teams: subTeams } : {}),
|
|
2595
|
+
...(plays.some((p) => p.kind === 'OrderPriority') ? { orderPriority: true } : {}),
|
|
2596
|
+
}), modelled, !teamsKnown));
|
|
2597
|
+
// #275 pattern 3: a border these orders leave below what the default plan leaves there (one plan, a warning).
|
|
2598
|
+
const belowPlan = belowPlanWarning(await bordersBelowPlan(ctx, {
|
|
2599
|
+
game, map, me, turn: turnNumber, territories, info, teamsKnown,
|
|
2600
|
+
// The board cache alone (warapp_plan_turn writes it each turn): no GameFeed request is added here.
|
|
2601
|
+
// A turn it lacks, which warapp_plan_turn would read from GameFeed's history, is named in the warning.
|
|
2602
|
+
history: await boardHistory(ctx, game, me, turnNumber, { cacheOnly: true }),
|
|
2603
|
+
cacheOnly: true,
|
|
2604
|
+
given: { deploys: givenDeploys, moves: givenMoves },
|
|
2605
|
+
}));
|
|
2606
|
+
if (belowPlan)
|
|
2607
|
+
warnings.push(belowPlan);
|
|
2608
|
+
// Deploys first (as the client sends them), merged per territory.
|
|
2609
|
+
const merged = new Map();
|
|
2610
|
+
for (const d of deploys) {
|
|
2611
|
+
const m = merged.get(d.territory.id);
|
|
2612
|
+
if (m)
|
|
2613
|
+
m.armies += d.armies;
|
|
2614
|
+
else
|
|
2615
|
+
merged.set(d.territory.id, { ...d });
|
|
2616
|
+
}
|
|
2617
|
+
const send = [
|
|
2618
|
+
...discards.map((c) => ({ kind: 'discard', cardId: c.id })),
|
|
2619
|
+
...plays.map((p) => ({
|
|
2620
|
+
kind: 'card',
|
|
2621
|
+
card: p.kind,
|
|
2622
|
+
cardId: p.card.id,
|
|
2623
|
+
...(p.target ? { target: p.target.id } : {}),
|
|
2624
|
+
...(p.targets ? p.targets.fields : {}),
|
|
2625
|
+
...(placedAt(p) !== undefined ? { beforeMove: placedAt(p) - 1 } : {}),
|
|
2626
|
+
})),
|
|
2627
|
+
...[...merged.values()].map((d) => ({ kind: 'deploy', territoryId: d.territory.id, armies: d.armies })),
|
|
2628
|
+
...moves.map((m, i) => {
|
|
2629
|
+
const commander = options.commanders.get(i);
|
|
2630
|
+
return {
|
|
2631
|
+
kind: 'move',
|
|
2632
|
+
from: m.from.id,
|
|
2633
|
+
to: m.to.id,
|
|
2634
|
+
armies: m.armies,
|
|
2635
|
+
...(m.mode === 'attack-only' ? { mode: AttackTransferMode.Attack } : m.mode === 'transfer-only' ? { mode: AttackTransferMode.Transfer } : {}),
|
|
2636
|
+
...(m.percent ? { byPercent: true } : {}),
|
|
2637
|
+
...(m.attackTeammates ? { attackTeammates: true } : {}),
|
|
2638
|
+
...(commander ? { commander } : {}),
|
|
2639
|
+
};
|
|
2640
|
+
}),
|
|
2641
|
+
];
|
|
2642
|
+
const named = [
|
|
2643
|
+
...discards.map((c) => ({ kind: 'discard', card: cardView(c) })),
|
|
2644
|
+
...plays.map((p) => ({
|
|
2645
|
+
kind: 'card',
|
|
2646
|
+
card: cardView(p.card),
|
|
2647
|
+
...(p.target ? { target: p.target } : {}),
|
|
2648
|
+
...(p.targets ? namedTargets(p.targets) : {}),
|
|
2649
|
+
...(placedAt(p) !== undefined ? { before: placedAt(p) } : {}),
|
|
2650
|
+
})),
|
|
2651
|
+
...[...merged.values()].map((d) => ({ kind: 'deploy', territory: d.territory, armies: d.armies })),
|
|
2652
|
+
...moves.map((m) => ({
|
|
2653
|
+
kind: 'move',
|
|
2654
|
+
from: m.from,
|
|
2655
|
+
to: m.to,
|
|
2656
|
+
armies: m.armies,
|
|
2657
|
+
...(m.mode === 'attack-only' || m.mode === 'transfer-only' ? { mode: m.mode } : {}),
|
|
2658
|
+
...(m.percent ? { percent: true } : {}),
|
|
2659
|
+
...(m.commander ? { commander: true } : {}),
|
|
2660
|
+
...(m.attackTeammates ? { attackTeammates: true } : {}),
|
|
2661
|
+
})),
|
|
2662
|
+
];
|
|
2663
|
+
return {
|
|
2664
|
+
gate: {
|
|
2665
|
+
action: 'warapp.submit_turn',
|
|
2666
|
+
// By id only: player and territory names are other people's words and go,
|
|
2667
|
+
// delimited, in the labelled fields of `willSend`.
|
|
2668
|
+
summary: `Commit ${send.length} order${send.length === 1 ? '' : 's'} for player ${me.id} in game ${game.id}, turn ${turnNumber}`,
|
|
2669
|
+
account: writeAccount(me.id),
|
|
2670
|
+
target: game.id,
|
|
2671
|
+
payload: { method: 'SendOrders', gameId: game.id, playerId, turnNumber, orders: send },
|
|
2672
|
+
willSend: { game: game.id, player: untrustedText(me.name), turn: turnNumber, income, orders: named.map(shownOrder) },
|
|
2673
|
+
preview: {
|
|
2674
|
+
account: shownAccount(me.name, me.id),
|
|
2675
|
+
note: 'These orders reach the game; once the turn resolves, other players see the results.',
|
|
2676
|
+
...(attacks.length ? { attacks: attacks.map((a) => ({ ...a, from: shownPlace(a.from), to: shownPlace(a.to) })) } : {}),
|
|
2677
|
+
...(warnings.length ? { warnings } : {}),
|
|
2678
|
+
untrusted: UNTRUSTED_PREVIEW_NOTE,
|
|
2679
|
+
},
|
|
2680
|
+
},
|
|
2681
|
+
state: {
|
|
2682
|
+
gameId: game.id,
|
|
2683
|
+
playerId,
|
|
2684
|
+
feedPlayerId: me.id,
|
|
2685
|
+
turnsBefore: game.numberOfTurns,
|
|
2686
|
+
turnNumber,
|
|
2687
|
+
orders: send,
|
|
2688
|
+
named,
|
|
2689
|
+
income,
|
|
2690
|
+
...(givenIncome !== undefined ? { incomeGiven: true } : {}),
|
|
2691
|
+
...(placedDelays.length ? { orderDelayCheck: orderDelayCheck(placedDelays.map((p) => placedAt(p))) } : {}),
|
|
2692
|
+
...(unverifiedPlays.length ? { cardPlayCheck: cardPlayCheck(unverifiedPlays) } : {}),
|
|
2693
|
+
...(breaks.length ? { breaks: breaks.map((b) => b.agreement) } : {}),
|
|
2694
|
+
...(commanderRisk ? { commanderRisk: commanderRisk.risk } : {}),
|
|
2695
|
+
},
|
|
2696
|
+
};
|
|
2697
|
+
},
|
|
2698
|
+
async execute(st) {
|
|
2699
|
+
await requireApprovedAccount(ctx, writeAccount(st.feedPlayerId));
|
|
2700
|
+
const base = {
|
|
2701
|
+
game: st.gameId,
|
|
2702
|
+
turn: st.turnNumber,
|
|
2703
|
+
orders: st.named,
|
|
2704
|
+
...(st.orderDelayCheck ? { orderDelayCheck: st.orderDelayCheck } : {}),
|
|
2705
|
+
...(st.cardPlayCheck ? { cardPlayCheck: st.cardPlayCheck } : {}),
|
|
2706
|
+
};
|
|
2707
|
+
const check = `Check warapp_get_game: a \`turn\` above ${st.turnNumber} means this turn resolved; still ${st.turnNumber} with ` +
|
|
2708
|
+
'your `committed` true means the orders are in. Do not resend these orders blindly — a second commit for ' +
|
|
2709
|
+
'the same turn is not known to be safe, and once the turn has resolved they would commit to the next one.';
|
|
2710
|
+
const unconfirmed = (warning) => ({ status: 'unknown', outcome: 'unconfirmed', ...base, warning });
|
|
2711
|
+
const result = await sendAndVerify({
|
|
2712
|
+
send: async () => {
|
|
2713
|
+
// The reply's bool is war.app's "vacation ended" flag — never a success signal.
|
|
2714
|
+
await ctx.rpc.call('SendOrders', Method.SendOrders, (w) => writeSendOrdersParams(w, st.gameId, st.playerId, st.orders, st.turnNumber));
|
|
2715
|
+
// Sent: keep my deploys and moves for opponent tracking (#119). Best effort, never throws.
|
|
2716
|
+
if (ctx.dataDir)
|
|
2717
|
+
await writeOrdersCache(ctx.dataDir, st.gameId, st.feedPlayerId, st.turnNumber, myOrdersOf(st.orders));
|
|
2718
|
+
},
|
|
2719
|
+
// war.app refused them (e.g. 11: deploys ≠ income; 208: the turn already advanced): nothing committed.
|
|
2720
|
+
refused: (e) => {
|
|
2721
|
+
if (e.code === 11)
|
|
2722
|
+
return incomeRefused(e, st.income, st.incomeGiven);
|
|
2723
|
+
if (e.code === 10 && st.orderDelayCheck)
|
|
2724
|
+
return orderDelayRefused(e);
|
|
2725
|
+
return undefined;
|
|
2726
|
+
},
|
|
2727
|
+
unanswered: (failure) => ({
|
|
2728
|
+
status: 'unknown',
|
|
2729
|
+
outcome: 'unknown',
|
|
2730
|
+
...base,
|
|
2731
|
+
warning: `war.app did not confirm these orders (${failure}), so they may already have been committed. ${check}`,
|
|
2732
|
+
}),
|
|
2733
|
+
readBack: () => ctx.client.getGame(st.gameId, { map: false }),
|
|
2734
|
+
unreadable: (failure) => unconfirmed(`The orders were sent, but re-reading the game failed (${failure}). ${check}`),
|
|
2735
|
+
classify: (after) => {
|
|
2736
|
+
if (after.numberOfTurns !== undefined && after.numberOfTurns > st.turnsBefore) {
|
|
2737
|
+
return {
|
|
2738
|
+
status: 'resolved',
|
|
2739
|
+
outcome: 'confirmed',
|
|
2740
|
+
...base,
|
|
2741
|
+
detail: `The turn resolved: the game is now on turn ${after.numberOfTurns + 1}.`,
|
|
2742
|
+
};
|
|
2743
|
+
}
|
|
2744
|
+
if (after.players.find((p) => p.id === st.feedPlayerId)?.hasCommittedOrders) {
|
|
2745
|
+
return {
|
|
2746
|
+
status: 'committed',
|
|
2747
|
+
outcome: 'confirmed',
|
|
2748
|
+
...base,
|
|
2749
|
+
detail: 'Your orders are committed; the turn resolves when every player has committed.',
|
|
2750
|
+
};
|
|
2751
|
+
}
|
|
2752
|
+
return unconfirmed(`The orders were sent, but the game does not yet show them committed or the turn advanced. ${check}`);
|
|
2753
|
+
},
|
|
2754
|
+
});
|
|
2755
|
+
const withRisk = st.commanderRisk ? { ...result, commanderRiskAccepted: st.commanderRisk } : result;
|
|
2756
|
+
if (!st.breaks?.length)
|
|
2757
|
+
return withRisk;
|
|
2758
|
+
return { ...withRisk, agreementsBroken: await recordBreaks(st, result.outcome === 'confirmed') };
|
|
2759
|
+
},
|
|
2760
|
+
});
|
|
2761
|
+
}
|