@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.
Files changed (177) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +199 -8
  4. package/dist/analysis/award.js +159 -0
  5. package/dist/analysis/bonuses.js +98 -0
  6. package/dist/analysis/breach.js +62 -0
  7. package/dist/analysis/card-support.js +329 -0
  8. package/dist/analysis/card-threats.js +234 -0
  9. package/dist/analysis/cards-in-effect.js +130 -0
  10. package/dist/analysis/chains.js +59 -0
  11. package/dist/analysis/chokepoints.js +140 -0
  12. package/dist/analysis/combat.js +231 -0
  13. package/dist/analysis/commander-safety.js +149 -0
  14. package/dist/analysis/commitments.js +338 -0
  15. package/dist/analysis/exchange.js +155 -0
  16. package/dist/analysis/graph.js +82 -0
  17. package/dist/analysis/guard-off.js +54 -0
  18. package/dist/analysis/guess.js +351 -0
  19. package/dist/analysis/headroom.js +241 -0
  20. package/dist/analysis/hold-diff.js +64 -0
  21. package/dist/analysis/how-lost.js +130 -0
  22. package/dist/analysis/index.js +14 -0
  23. package/dist/analysis/local-deploy.js +159 -0
  24. package/dist/analysis/lookahead.js +108 -0
  25. package/dist/analysis/opponent-profile.js +551 -0
  26. package/dist/analysis/opponents.js +1245 -0
  27. package/dist/analysis/outlook.js +633 -0
  28. package/dist/analysis/overrides.js +60 -0
  29. package/dist/analysis/picks.js +1879 -0
  30. package/dist/analysis/plan/after-leftover.js +140 -0
  31. package/dist/analysis/plan/cap-spend.js +242 -0
  32. package/dist/analysis/plan/captures.js +1195 -0
  33. package/dist/analysis/plan/commander.js +236 -0
  34. package/dist/analysis/plan/completed.js +29 -0
  35. package/dist/analysis/plan/conceded-out.js +131 -0
  36. package/dist/analysis/plan/estimates.js +715 -0
  37. package/dist/analysis/plan/guard-off.js +232 -0
  38. package/dist/analysis/plan/holds.js +1631 -0
  39. package/dist/analysis/plan/leftover.js +760 -0
  40. package/dist/analysis/plan/move-order.js +319 -0
  41. package/dist/analysis/plan/orders.js +317 -0
  42. package/dist/analysis/plan/relations.js +702 -0
  43. package/dist/analysis/plan/report.js +672 -0
  44. package/dist/analysis/plan/shared.js +1218 -0
  45. package/dist/analysis/plan/stand-still.js +823 -0
  46. package/dist/analysis/plan/state.js +44 -0
  47. package/dist/analysis/plan/strike.js +1416 -0
  48. package/dist/analysis/plan/targets.js +651 -0
  49. package/dist/analysis/plan/team.js +299 -0
  50. package/dist/analysis/plan/threats.js +927 -0
  51. package/dist/analysis/plan/transfers.js +328 -0
  52. package/dist/analysis/plan/util.js +5 -0
  53. package/dist/analysis/plan/vacated.js +285 -0
  54. package/dist/analysis/planner.js +2922 -0
  55. package/dist/analysis/player-record.js +144 -0
  56. package/dist/analysis/player.js +268 -0
  57. package/dist/analysis/profile.js +347 -0
  58. package/dist/analysis/relations.js +1030 -0
  59. package/dist/analysis/schedule.js +88 -0
  60. package/dist/analysis/since-last.js +50 -0
  61. package/dist/analysis/static-seats.js +71 -0
  62. package/dist/analysis/stress.js +577 -0
  63. package/dist/analysis/team-brief.js +151 -0
  64. package/dist/analysis/tripwire.js +644 -0
  65. package/dist/analysis/turn-sim.js +259 -0
  66. package/dist/analysis/whereabouts.js +1109 -0
  67. package/dist/board.js +105 -0
  68. package/dist/bundle.js +117959 -36172
  69. package/dist/cards.js +435 -0
  70. package/dist/chat-cursor.js +135 -0
  71. package/dist/chat.js +192 -0
  72. package/dist/client.js +361 -0
  73. package/dist/config.js +62 -0
  74. package/dist/direct/link.js +102 -0
  75. package/dist/direct/session.js +267 -0
  76. package/dist/direct/transport.js +424 -0
  77. package/dist/guess-salt.js +65 -0
  78. package/dist/hosted.js +24 -0
  79. package/dist/index.js +33 -0
  80. package/dist/join-color.js +140 -0
  81. package/dist/live.js +278 -0
  82. package/dist/map-stats.js +152 -0
  83. package/dist/map-store.js +204 -0
  84. package/dist/move-order.js +141 -0
  85. package/dist/my-games.js +180 -0
  86. package/dist/normalize.js +411 -0
  87. package/dist/open-games.js +537 -0
  88. package/dist/outlook-log.js +138 -0
  89. package/dist/path-lock.js +22 -0
  90. package/dist/pick-list.js +193 -0
  91. package/dist/player-record-store.js +229 -0
  92. package/dist/player-states.js +31 -0
  93. package/dist/profile-store.js +677 -0
  94. package/dist/protocol/bundle.js +375 -0
  95. package/dist/protocol/codec.js +556 -0
  96. package/dist/protocol/decoded.js +12 -0
  97. package/dist/protocol/interp.js +1904 -0
  98. package/dist/protocol/methods.js +531 -0
  99. package/dist/protocol/rpc.js +202 -0
  100. package/dist/push/listener.js +393 -0
  101. package/dist/push/packets.js +66 -0
  102. package/dist/push/socketio.js +333 -0
  103. package/dist/push/websocket.js +179 -0
  104. package/dist/redact.js +62 -0
  105. package/dist/relations-store.js +242 -0
  106. package/dist/replay.js +215 -0
  107. package/dist/scalars.js +28 -0
  108. package/dist/scout.js +346 -0
  109. package/dist/stats.js +269 -0
  110. package/dist/strategy/card-clock.js +185 -0
  111. package/dist/strategy/map-notes.js +128 -0
  112. package/dist/strategy/notes.js +2168 -0
  113. package/dist/team-cards.js +84 -0
  114. package/dist/team-orders.js +150 -0
  115. package/dist/teams.js +19 -0
  116. package/dist/tools/award.js +206 -0
  117. package/dist/tools/begin-turn.js +162 -0
  118. package/dist/tools/board.js +77 -0
  119. package/dist/tools/card-advice.js +256 -0
  120. package/dist/tools/card-effects.js +49 -0
  121. package/dist/tools/card-plays.js +434 -0
  122. package/dist/tools/card-support-advice.js +140 -0
  123. package/dist/tools/chat-inbox.js +146 -0
  124. package/dist/tools/chat.js +483 -0
  125. package/dist/tools/check-plan.js +688 -0
  126. package/dist/tools/commander-check.js +102 -0
  127. package/dist/tools/commitments.js +216 -0
  128. package/dist/tools/common.js +143 -0
  129. package/dist/tools/diplomacy.js +342 -0
  130. package/dist/tools/game.js +126 -0
  131. package/dist/tools/guess-view.js +56 -0
  132. package/dist/tools/healthcheck.js +90 -0
  133. package/dist/tools/hints.js +34 -0
  134. package/dist/tools/how-lost.js +154 -0
  135. package/dist/tools/index.js +142 -0
  136. package/dist/tools/join-game.js +327 -0
  137. package/dist/tools/leave-game.js +181 -0
  138. package/dist/tools/live-context.js +339 -0
  139. package/dist/tools/live.js +404 -0
  140. package/dist/tools/map-stats.js +117 -0
  141. package/dist/tools/map.js +133 -0
  142. package/dist/tools/my-games.js +123 -0
  143. package/dist/tools/open-games.js +104 -0
  144. package/dist/tools/opponents.js +151 -0
  145. package/dist/tools/order-options.js +135 -0
  146. package/dist/tools/picks.js +292 -0
  147. package/dist/tools/profile-hook.js +156 -0
  148. package/dist/tools/profile-opponents.js +121 -0
  149. package/dist/tools/profile-reads.js +99 -0
  150. package/dist/tools/push.js +385 -0
  151. package/dist/tools/relations.js +611 -0
  152. package/dist/tools/resolve.js +45 -0
  153. package/dist/tools/route.js +36 -0
  154. package/dist/tools/scout.js +87 -0
  155. package/dist/tools/session.js +163 -0
  156. package/dist/tools/strategy.js +200 -0
  157. package/dist/tools/stress-opponents.js +83 -0
  158. package/dist/tools/surrender.js +240 -0
  159. package/dist/tools/survival.js +189 -0
  160. package/dist/tools/team-brief.js +266 -0
  161. package/dist/tools/team-source.js +222 -0
  162. package/dist/tools/team.js +182 -0
  163. package/dist/tools/turn.js +2761 -0
  164. package/dist/tools/uncommit.js +160 -0
  165. package/dist/tools/where.js +275 -0
  166. package/dist/tools/write-kit.js +158 -0
  167. package/dist/transport-bridge.js +33 -0
  168. package/dist/trend.js +452 -0
  169. package/dist/version.js +4 -0
  170. package/manifest.json +174 -4
  171. package/mint.yaml +101 -14
  172. package/package.json +11 -6
  173. package/server.json +40 -3
  174. package/skills/warapp-api/SKILL.md +95 -4
  175. package/skills/warapp-api/references/scout.mjs +348 -0
  176. package/skills/warapp-api/scripts/warapp.sh +69 -8
  177. package/skills/warapp-mcp/SKILL.md +969 -21
@@ -0,0 +1,154 @@
1
+ // How a lost game was lost (#274 item 5), for warapp_get_game (#283: also a seat of mine out of a game still playing): read from the boards this server
2
+ // cached while it played (src/analysis/how-lost.ts), kept name-free in the outlook log so it outlives
3
+ // the board cache, and reported with names through `untrustedText`. No request; never throws.
4
+ import { howLost } from '../analysis/how-lost.js';
5
+ import { readOutlookLog, readOutlookPlayer, recordLoss } from '../outlook-log.js';
6
+ import { readBoardHistory, readCachedOrders, readCachedPlayer } from '../trend.js';
7
+ import { untrustedText } from './common.js';
8
+ /** #283: the seat states that put me out of a game, whether or not the others play on. */
9
+ const OUT_STATES = new Set(['Eliminated', 'Booted', 'SurrenderAccepted']);
10
+ /** The causes a seat's state gives without a board (#283: `seatOut` adds the last turn and outlook). */
11
+ const STATE_CAUSES = {
12
+ SurrenderAccepted: { cause: 'surrendered', line: 'Surrendered (accepted).' },
13
+ Booted: { cause: 'booted', line: 'Booted from the game.' },
14
+ };
15
+ function report(loss, game) {
16
+ const playerName = (id) => untrustedText(game.players.find((p) => p.id === id)?.name ?? id);
17
+ const territoryName = (id) => {
18
+ const t = game.map?.territories.find((x) => x.id === id);
19
+ return t ? untrustedText(t.name) : null;
20
+ };
21
+ const named = (id) => {
22
+ const n = territoryName(id);
23
+ return n ? `${id} ${n}` : String(id);
24
+ };
25
+ const neighbours = loss.neighbours?.map((n) => ({ ...n, ...(n.playerId !== null ? { name: playerName(n.playerId) } : {}) })) ?? null;
26
+ const when = `Eliminated on turn ${loss.turn}${loss.turnCertain ? '' : ' (the last turn cached here; the loss may have come later)'}`;
27
+ const bordered = neighbours?.length
28
+ ? ` Bordered by ${neighbours
29
+ .map((n) => `${n.playerId === null ? 'owners hidden by the fog' : n.name} on ${n.territories} territor${n.territories === 1 ? 'y' : 'ies'}${n.armies !== null ? ` (${n.armies} armies in view)` : ''}`)
30
+ .join(', ')}.`
31
+ : '';
32
+ const by = loss.by !== null ? ` to ${playerName(loss.by)}` : '';
33
+ let line;
34
+ const c = loss.commander;
35
+ if (c) {
36
+ const range = c.held ? `${c.held.low}${c.held.high !== c.held.low ? `–${c.held.high}` : ''}` : '';
37
+ const held = c.held
38
+ ? ` It held ${c.held.uncertain ? `about ${range}` : range} armies and the commander (${c.armies} at the start of the turn, +${c.deployed} deployed, −${c.movedOut} moved out, +${c.movedIn} moved in${c.walk ? `, the walk's ${c.walk.armies} among them` : ''}); taking that needs at least ${c.attackersNeeded} attackers${c.exact ? '' : ' (at the expectation: the game has luck)'}${c.held.uncertain ? ' — a bound only: an order this count leaves out (a percentage, Attack Only or Transfer Only order, or a card play) touched it' : ''}.`
39
+ : c.walk
40
+ ? ` My orders that turn do not say what it held there${c.walk.armies === null ? ' (the walk was a percentage order)' : ''}.`
41
+ : ` It started the turn with ${c.armies} armies and the commander; my orders that turn are not cached, so what it held is unknown.`;
42
+ line = c.walk
43
+ ? `${when}: my commander walked from ${named(c.walk.from)} to ${named(c.territoryId)} that turn; it fell on ${named(c.territoryId)}${by}, or on ${named(c.walk.from)} before the walk ran (inferred: losing the commander ends the game for me; which of the two is not known).${held}${bordered}`
44
+ : `${when}: my commander's territory ${named(c.territoryId)} fell${by} (inferred: losing the commander ends the game for me).${held}${bordered}`;
45
+ }
46
+ else if (loss.cause === 'last-territories') {
47
+ const ids = (loss.lastTerritories ?? []).map((t) => named(t.territoryId)).join(', ');
48
+ line = `${when}: my last ${loss.territoriesHeld} territor${loss.territoriesHeld === 1 ? 'y' : 'ies'} fell${by} (${ids}${loss.territoriesHeld > (loss.lastTerritories?.length ?? 0) ? ', …' : ''}).${bordered}`;
49
+ }
50
+ else {
51
+ line = `${when}; the cached board does not show my commander, so the cause is unknown.`;
52
+ }
53
+ return {
54
+ result: 'Eliminated',
55
+ ...loss,
56
+ ...(c ? { commander: { ...c, territoryName: territoryName(c.territoryId) } } : {}),
57
+ neighbours,
58
+ by: loss.by !== null ? { id: loss.by, name: playerName(loss.by) } : null,
59
+ line,
60
+ };
61
+ }
62
+ /** The newest turn this server played `gameId` on: a cached board where I held land, or a logged outlook. */
63
+ async function lastPlayed(dir, gameId, me) {
64
+ const log = await readOutlookLog(dir, gameId, me);
65
+ const boards = await readBoardHistory(dir, gameId, me);
66
+ const held = boards
67
+ .filter((b) => b.board.territories.some((t) => t.owner.kind === 'player' && t.owner.playerId === me))
68
+ .map((b) => b.turn);
69
+ const logged = Object.keys(log?.turns ?? {}).map(Number).filter(Number.isInteger);
70
+ const all = [...held, ...logged];
71
+ return all.length ? { turn: Math.max(...all), log } : undefined;
72
+ }
73
+ /**
74
+ * #283: a surrender or a boot, by my seat's state, with the last turn played here and the outlook logged
75
+ * last (its state, and my armies and income against the strongest side's in view, when logged).
76
+ */
77
+ function seatOut(result, byState, last, game) {
78
+ if (!last)
79
+ return { result, ...byState };
80
+ const { turn, log } = last;
81
+ const loggedTurn = Math.max(...Object.keys(log?.turns ?? {}).map(Number).filter(Number.isInteger).filter((t) => t <= turn));
82
+ const entry = Number.isFinite(loggedTurn) ? log.turns[String(loggedTurn)] : undefined;
83
+ const head = `${byState.line} The last turn played here was turn ${turn}`;
84
+ if (!entry)
85
+ return { result, ...byState, turn, line: `${head}; no outlook was logged for it.` };
86
+ const held = log.latest && log.latest.turn === loggedTurn && log.latest.state !== null ? { state: log.latest.state, turns: log.latest.heldTurns } : undefined;
87
+ const f = entry.figures;
88
+ const s = f?.strongest;
89
+ const who = s
90
+ ? s.team !== undefined
91
+ ? `team ${s.team}`
92
+ : untrustedText(game.players.find((p) => p.id === s.playerId)?.name ?? s.playerId)
93
+ : undefined;
94
+ const outlook = {
95
+ turn: loggedTurn,
96
+ state: entry.state,
97
+ ...(held ? { held } : {}),
98
+ ...(f ? { mine: f.mine } : {}),
99
+ ...(s ? { strongest: { id: s.playerId, ...(s.team !== undefined ? { team: s.team } : {}), name: who, armies: s.armies, income: s.income } } : {}),
100
+ };
101
+ const read = `${loggedTurn === turn ? 'its outlook' : `the last outlook logged (turn ${loggedTurn})`} read ${entry.state}${held ? ` (held ${held.turns} turn${held.turns === 1 ? '' : 's'})` : ''}`;
102
+ const figures = !f
103
+ ? ' (the armies and income behind it were not logged then)'
104
+ : `: my income ${f.mine.income} and ${f.mine.armies} armies${s ? ` against ${who}'s ${s.income} and ${s.armies} in view` : ', no opponent in view'}`;
105
+ return { result, ...byState, turn, outlook, line: `${head}; ${read}${figures}.` };
106
+ }
107
+ /**
108
+ * How `game` was lost, when the account this server cached it for did not win it: once it is finished,
109
+ * or (#283) while it is still playing once my seat is out (eliminated, booted or surrendered). A
110
+ * surrender or a boot by its state, an elimination from the cached boards (kept in the outlook log
111
+ * the first time, read back from there once the boards are gone). `undefined` otherwise.
112
+ */
113
+ export async function lossReport(dir, game) {
114
+ try {
115
+ const finished = game.state === 'Finished';
116
+ // #283: a seat of mine that is out is reported while the others play on; no disk read otherwise.
117
+ if (!finished && !game.players.some((p) => p.state !== undefined && OUT_STATES.has(p.state)))
118
+ return undefined;
119
+ const me = (await readCachedPlayer(dir, game.id)) ?? (await readOutlookPlayer(dir, game.id));
120
+ if (me === undefined)
121
+ return undefined;
122
+ const state = game.players.find((p) => p.id === me)?.state;
123
+ if (state === undefined || (!finished && !OUT_STATES.has(state)))
124
+ return undefined;
125
+ const byState = STATE_CAUSES[state];
126
+ if (byState)
127
+ return seatOut(state, byState, await lastPlayed(dir, game.id, me), game);
128
+ if (state !== 'Eliminated')
129
+ return undefined;
130
+ const boards = await readBoardHistory(dir, game.id, me);
131
+ const s = game.settings;
132
+ const fresh = howLost({
133
+ me,
134
+ boards,
135
+ orders: await readCachedOrders(dir, game.id, me),
136
+ ...(game.map ? { adjacency: new Map(game.map.territories.map((t) => [t.id, t.connectedTo])) } : {}),
137
+ rates: {
138
+ ...(s?.offensiveKillRate !== undefined ? { offensiveKillRate: s.offensiveKillRate } : {}),
139
+ ...(s?.defensiveKillRate !== undefined ? { defensiveKillRate: s.defensiveKillRate } : {}),
140
+ ...(s?.luckModifier !== undefined ? { luck: s.luckModifier } : {}),
141
+ ...(s?.roundingMode !== undefined ? { rounding: s.roundingMode } : {}),
142
+ },
143
+ ...(game.numberOfTurns !== undefined ? { turnsCompleted: game.numberOfTurns } : {}),
144
+ ...(s?.commanders !== undefined ? { commanders: s.commanders } : {}),
145
+ });
146
+ if (fresh)
147
+ await recordLoss(dir, game.id, me, fresh);
148
+ const loss = fresh ?? (await readOutlookLog(dir, game.id, me))?.loss;
149
+ return loss ? report(loss, game) : undefined;
150
+ }
151
+ catch {
152
+ return undefined;
153
+ }
154
+ }
@@ -0,0 +1,142 @@
1
+ import { defaultMapCache, WarappClient } from '../client.js';
2
+ import { dataDir } from '../config.js';
3
+ import { StatsCollector } from '../stats.js';
4
+ import { registerBeginTurnTool } from './begin-turn.js';
5
+ import { registerBoardTool } from './board.js';
6
+ import { registerChatTools } from './chat.js';
7
+ import { registerChatInboxTool } from './chat-inbox.js';
8
+ import { registerCheckPlanTool } from './check-plan.js';
9
+ import { registerGameTool } from './game.js';
10
+ import { registerHealthcheckTool } from './healthcheck.js';
11
+ import { createLiveContext } from './live-context.js';
12
+ import { registerJoinGameTool } from './join-game.js';
13
+ import { registerLiveTools } from './live.js';
14
+ import { registerMapTool } from './map.js';
15
+ import { registerMapStatsTool } from './map-stats.js';
16
+ import { registerMyGamesTool } from './my-games.js';
17
+ import { registerOpenGamesTool } from './open-games.js';
18
+ import { registerOpponentsTool } from './opponents.js';
19
+ import { registerPickTools } from './picks.js';
20
+ import { registerPushTools } from './push.js';
21
+ import { registerRelationsTools } from './relations.js';
22
+ import { registerDiplomacyTool } from './diplomacy.js';
23
+ import { registerRouteTool } from './route.js';
24
+ import { registerScoutTool } from './scout.js';
25
+ import { registerSessionTools } from './session.js';
26
+ import { registerStrategyTool } from './strategy.js';
27
+ import { registerSurrenderTool } from './surrender.js';
28
+ import { registerTeamTool } from './team.js';
29
+ import { registerTeamBriefTool } from './team-brief.js';
30
+ import { registerTurnTools } from './turn.js';
31
+ import { registerUncommitTool } from './uncommit.js';
32
+ import { registerLeaveGameTool } from './leave-game.js';
33
+ import { registerWhereTool } from './where.js';
34
+ import { registerProfileOpponentsTool } from './profile-opponents.js';
35
+ import { pushListenerFor } from '../push/listener.js';
36
+ import { pushWebSocketLeg } from '../push/websocket.js';
37
+ import { readSession } from '../direct/session.js';
38
+ import { createDirectFirstBridge } from '../direct/transport.js';
39
+ import { isHosted } from '../hosted.js';
40
+ import { createWarappBridge } from '../transport-bridge.js';
41
+ /** Every tool this server serves. index.ts and the tests share this list. */
42
+ export function registerAllTools(server, deps = {}) {
43
+ // One client for the game tools, so they share the map cache. Config is
44
+ // deferred: the client reads credentials per call, never at construction.
45
+ // The map cache is kept on disk too (`<dataDir>/maps/`, src/map-store.ts),
46
+ // local and hosted (a hosted child's per-user data dir persists).
47
+ const client = new WarappClient({ ...deps, dataDir: () => dataDir(deps.env) });
48
+ const env = deps.env;
49
+ // The process's browser bridge (fetchproxy), shared across connections.
50
+ const fetchproxy = deps.bridge ?? createWarappBridge(env ? { env } : {});
51
+ // Wrap it in the direct-first router: the chrome-less AuthToken leg
52
+ // (src/direct/) serves calls when a session is linked and falls back to the
53
+ // browser bridge otherwise (WARAPP_TRANSPORT: auto default | direct |
54
+ // fetchproxy). WarappRpc, the page fetches, the healthcheck and the push
55
+ // socket all take this one bridge, so they all gain direct mode at once.
56
+ // Direct mode is LOCAL-ONLY (src/hosted.ts): on a hosted child the router is
57
+ // pinned to the browser bridge, the session store reads as empty and
58
+ // warapp_link_session is not registered.
59
+ const hosted = isHosted(env ?? process.env);
60
+ const bridge = createDirectFirstBridge({
61
+ store: { read: () => readSession(deps.env) },
62
+ makeBridge: () => fetchproxy,
63
+ ...(env ? { env } : {}),
64
+ ...(deps.directFetch ? { directFetch: deps.directFetch } : {}),
65
+ });
66
+ const live = createLiveContext({
67
+ client,
68
+ bridge,
69
+ ...(deps.env ? { env: deps.env } : {}),
70
+ ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
71
+ ...(deps.bundle ? { bundle: deps.bundle } : {}),
72
+ // The cached signed-in account is discarded whenever the account behind the router may have changed.
73
+ identity: () => bridge.identityState(),
74
+ });
75
+ registerHealthcheckTool(server, fetchproxy, bridge, deps);
76
+ registerGameTool(server, client, () => dataDir(deps.env), deps.env);
77
+ registerMapTool(server, client);
78
+ // Opt-in (WARAPP_STATS=1), never hosted: the tool refuses before any request
79
+ // when off. One collector per registration, so its 1 s throttle spans calls.
80
+ registerMapStatsTool(server, {
81
+ collector: new StatsCollector({
82
+ client,
83
+ dir: () => dataDir(deps.env),
84
+ ...(deps.sleep ? { sleep: deps.sleep } : {}),
85
+ }),
86
+ mapCache: deps.mapCache ?? defaultMapCache,
87
+ ...(deps.env ? { env: deps.env } : {}),
88
+ });
89
+ registerBoardTool(server, client, live);
90
+ registerRouteTool(server, client);
91
+ registerStrategyTool(server, client);
92
+ registerLiveTools(server, live);
93
+ registerPickTools(server, live);
94
+ registerMyGamesTool(server, live);
95
+ registerOpenGamesTool(server, live);
96
+ registerJoinGameTool(server, live);
97
+ registerLeaveGameTool(server, live);
98
+ registerSurrenderTool(server, live);
99
+ registerBeginTurnTool(server, live);
100
+ registerScoutTool(server, live, deps.env ? { env: deps.env } : {});
101
+ registerTurnTools(server, live, deps.env ? { env: deps.env } : {});
102
+ registerCheckPlanTool(server, live);
103
+ registerOpponentsTool(server, live, deps.env ? { env: deps.env } : {});
104
+ // Reads the map statistics cache only when they are on (WARAPP_STATS=1, never hosted).
105
+ registerWhereTool(server, live, deps.env ? { env: deps.env } : {});
106
+ // Opponent profiling, read-only: habits counted from the boards seen (on unless WARAPP_PLAYER_PROFILE=off).
107
+ registerProfileOpponentsTool(server, live, deps.env ? { env: deps.env } : {});
108
+ registerUncommitTool(server, live);
109
+ registerChatTools(server, live, deps.env ? { env: deps.env } : {});
110
+ registerChatInboxTool(server, live);
111
+ registerTeamTool(server, live);
112
+ // C4: the team brief, read-only — the facts for a team-chat message, never sent.
113
+ registerTeamBriefTool(server, live);
114
+ // The agreement ledger: one read-only tool, and one that writes only the local ledger (not confirm-gated).
115
+ registerRelationsTools(server, live, deps.env ? { env: deps.env } : {});
116
+ // B3: truce advice (read-only): prices a deal by planning with and without it; reads no chat.
117
+ registerDiplomacyTool(server, live, deps.env ? { env: deps.env } : {});
118
+ // One push socket per process: keyed on the shared fetchproxy bridge so
119
+ // connections share it, with requests routed through the direct-first bridge.
120
+ // While the direct leg is active the push rides a direct WebSocket (the
121
+ // cookie goes only to war.app); otherwise, or when the WebSocket cannot come
122
+ // up, it keeps xhr-polling over the bridge.
123
+ const push = deps.push ??
124
+ pushListenerFor(fetchproxy, {
125
+ transport: () => bridge.ready(),
126
+ webSocket: pushWebSocketLeg(bridge, () => readSession(deps.env)),
127
+ extras: () => live.rpc.extras,
128
+ });
129
+ registerSessionTools(server, {
130
+ transport: {
131
+ activeLeg: () => bridge.status().transport,
132
+ sessionStale: () => bridge.sessionStale(),
133
+ sessionLinked: () => bridge.sessionLinked(),
134
+ },
135
+ pushTransport: () => push.status().transport,
136
+ decoder: () => live.decoderReport(),
137
+ identityChanged: () => live.forgetIdentity(),
138
+ hosted,
139
+ ...(env ? { env } : {}),
140
+ });
141
+ registerPushTools(server, live, push, deps.env ? { env: deps.env } : {});
142
+ }
@@ -0,0 +1,327 @@
1
+ // warapp_join_game: take an open seat in a game from war.app's open games list
2
+ // (AcceptOpenSeat, method 61), gated on the user's confirmation. The game is
3
+ // re-read from the list first, so the preview shows what is actually being
4
+ // joined, and the join is reported only once GameFeed (or GetMyGames) shows
5
+ // the account in the game. war.app needs a colour with the join (src/join-color.ts):
6
+ // the account's preferred one, else its secondary, else a standard colour still free.
7
+ import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
8
+ import { z } from 'zod';
9
+ import { parseGameId } from '../client.js';
10
+ import { chooseJoinColor, readAccountColors, STANDARD_COLORS } from '../join-color.js';
11
+ import { feedScreen, joiningPolicy, parseOpenGamesPage } from '../open-games.js';
12
+ import { GAME_COLOR_COUNT, Method, readAcceptOpenSeatReturn, writeAcceptOpenSeatParams, } from '../protocol/methods.js';
13
+ import { WarappServerError } from '../protocol/rpc.js';
14
+ import { gameIdArg, UNTRUSTED_PREVIEW_NOTE, untrustedText } from './common.js';
15
+ import { noBrowserNote } from './session.js';
16
+ import { mintMeta } from './hints.js';
17
+ import { requireApprovedAccount, writeAccount } from './live-context.js';
18
+ import { fetchMyGames } from './my-games.js';
19
+ import { markLotteries, openGamesPage } from './open-games.js';
20
+ import { holdsSeat, playerStateName } from '../player-states.js';
21
+ import { NO_TEAM } from '../teams.js';
22
+ import { accountUnknown, defineGatedWrite, refuse, sendAndVerify } from './write-kit.js';
23
+ /** war.app's "already in the game" code: the client treats it as a successful join. */
24
+ const ALREADY_JOINED = 121;
25
+ /** war.app's generic assertion failure; with "color is null" it is a join sent without a colour. */
26
+ const ASSERT_FAILED = 1;
27
+ const COLOR_UNAVAILABLE = 'That color is not available. Please pick a different color (pass color: a war.app colour index ' +
28
+ `0–${STANDARD_COLORS - 1} that no player in the game has).`;
29
+ /**
30
+ * The client's wording for the other refusals it handles on a join (254, 473
31
+ * and 750 are in the RPC error table). These codes are only read here, where
32
+ * their meaning is the join's.
33
+ */
34
+ const JOIN_ERRORS = {
35
+ 4: 'Could not join the game because it has already begun.',
36
+ 7: 'Sorry, the host has removed you.',
37
+ 8: COLOR_UNAVAILABLE,
38
+ 15: 'Sorry, this game is already full.',
39
+ 75: COLOR_UNAVAILABLE,
40
+ 88: 'Could not join the game because it has been deleted.',
41
+ 120: 'Could not join the game because the open seat is no longer available.',
42
+ 227: 'Sorry, the creator of this game has added you to their block list. You cannot join this game.',
43
+ 239: "Sorry, you don't meet the prerequisites the host has entered for open seats in this game.",
44
+ 390: COLOR_UNAVAILABLE,
45
+ };
46
+ /** The wording for a join refusal this tool names itself, or undefined. */
47
+ function joinErrorWording(e) {
48
+ if (e.code === ASSERT_FAILED && /color is null/i.test(e.message)) {
49
+ return 'war.app refused the join because it was sent with no colour ("color is null").';
50
+ }
51
+ return JOIN_ERRORS[e.code];
52
+ }
53
+ /** The open game `gameId`, refused when it cannot (or should not) be joined. */
54
+ function joinable(games, gameId, allowTeam, acceptFee) {
55
+ const game = games.find((g) => g.id === gameId);
56
+ if (!game) {
57
+ refuse(`Game ${gameId} is not on war.app's open games list, so it was not joined.`, 'It may have started or filled, be hidden from this account by prerequisites, or already include you. ' +
58
+ 'Pick a game from warapp_list_open_games.');
59
+ }
60
+ if (game.openSeats === 0)
61
+ refuse(`Game ${gameId} has no open seat.`, 'Pick another game from warapp_list_open_games.');
62
+ if (game.rules.includes('Custom scenario')) {
63
+ refuse(`Game ${gameId} uses a custom scenario, which needs a starting slot this tool does not pick.`, 'Join it from war.app instead.');
64
+ }
65
+ if (game.rules.includes('Mods')) {
66
+ refuse(`Game ${gameId} uses mods, which can hook the join in ways this tool cannot reproduce.`, 'Join it from war.app instead.');
67
+ }
68
+ if (game.teamGame && !allowTeam) {
69
+ refuse(`Game ${gameId} is a team game.`, "Pass team: a team number with an open seat (the preview lists them), or allow_team: true to take the first open seat's team.");
70
+ }
71
+ if (game.entryFeeCoins > 0 && !acceptFee) {
72
+ refuse(`Game ${gameId} costs ${game.entryFeeCoins} coins to join.`, 'Pass accept_entry_fee: true to pay it, or pick a free game.');
73
+ }
74
+ return game;
75
+ }
76
+ const TEAM_CHOICE_NOTE = "The team is sent as the chosen open seat's team, the int32 AcceptOpenSeat already carries (the client's team " +
77
+ 'picker passes it; read from the client bundle, UNVERIFIED live). Seats are by in-game id; an AI seat plays by rule.';
78
+ /**
79
+ * The team to join (C4): `requested` when an open seat carries it — refused when the team is full (its players
80
+ * seated, no open seat) or not in the game — else the first open seat's team; NO_TEAM outside a team game (a
81
+ * team asked for there is refused).
82
+ */
83
+ function chooseTeam(game, lobby, requested) {
84
+ const offered = [...new Set(game.openSeatTeams ?? [])].sort((a, b) => a - b);
85
+ if (requested === undefined)
86
+ return game.teamGame ? (game.openSeatTeams?.[0] ?? NO_TEAM) : NO_TEAM;
87
+ if (!game.teamGame)
88
+ refuse(`Game ${game.id} is not a team game, so it has no team to choose.`, 'Leave team out.');
89
+ if (game.randomTeamsOf !== undefined)
90
+ refuse(`Game ${game.id} deals random teams, so a team cannot be chosen.`, 'Leave team out (allow_team: true) to join it.');
91
+ if (offered.includes(requested))
92
+ return requested;
93
+ const list = offered.length ? offered.join(', ') : 'none';
94
+ if (lobby?.seated.some((p) => p.team === requested))
95
+ refuse(`Team ${requested} is full in game ${game.id}: no open seat is on it.`, `Teams with an open seat: ${list}.`);
96
+ refuse(`Team ${requested} is not offered in game ${game.id}.`, `Teams with an open seat: ${list}.`);
97
+ }
98
+ /** The preview's team section (C4): the team joined, the teams offered, and the seats already on it by id, human or AI. */
99
+ function teamView(game, lobby, team) {
100
+ return {
101
+ id: team,
102
+ offered: [...new Set(game.openSeatTeams ?? [])].sort((a, b) => a - b),
103
+ seats: (lobby?.seated ?? [])
104
+ .filter((p) => p.team === team)
105
+ .sort((a, b) => a.id - b.id)
106
+ .map((p) => ({ inGameId: p.id, kind: p.ai ? 'ai' : 'human' })),
107
+ openSeats: (game.openSeatTeams ?? []).filter((t) => t === team).length,
108
+ note: TEAM_CHOICE_NOTE,
109
+ };
110
+ }
111
+ /** Refuse a lobby the signed-in account (in-game id `me`) already holds a seat in. */
112
+ function refuseJoined(lobby, gameId, me) {
113
+ if (lobby?.seatedPlayerIds.includes(me)) {
114
+ refuse(`You have already joined game ${gameId}.`, 'It is in warapp_my_games; pick another game from warapp_list_open_games.');
115
+ }
116
+ }
117
+ /** The colour to send: the one asked for (refused when a lobby player has it), else the client's choice. */
118
+ function joinColor(requested, html, bundle, lobby, gameId) {
119
+ const taken = lobby?.colorsTaken ?? [];
120
+ if (requested !== undefined) {
121
+ if (taken.includes(requested)) {
122
+ refuse(`Colour ${requested} is taken by another player in game ${gameId}.`, 'Pass another color, or leave it out to let this tool pick one.');
123
+ }
124
+ return { color: requested, source: 'requested' };
125
+ }
126
+ const chosen = chooseJoinColor(readAccountColors(html, bundle), taken);
127
+ if (!chosen) {
128
+ refuse(`Every standard colour is taken in game ${gameId}.`, `Pass color: a war.app colour index (${STANDARD_COLORS}–${GAME_COLOR_COUNT - 1}) your account has unlocked.`);
129
+ }
130
+ return chosen;
131
+ }
132
+ /**
133
+ * The lobby's screen from its GameFeed settings (#132): the open-games record carries no neutral
134
+ * sizes or fog, GameFeed does. Best effort — a failed read leaves the preview without a screen.
135
+ */
136
+ async function lobbyScreen(ctx, gameId) {
137
+ try {
138
+ const game = await ctx.client.getGame(gameId, { settings: true, map: false });
139
+ const { screen, gaps } = feedScreen(game.settings ?? { cards: [], raw: {} });
140
+ return screen
141
+ ? { screen, gaps }
142
+ : { screen: null, gaps, note: "GameFeed's settings name no neutral size, so the neutral-cost screen was skipped." };
143
+ }
144
+ catch (e) {
145
+ return {
146
+ screen: null,
147
+ gaps: [],
148
+ note: `GameFeed could not read the lobby (${e instanceof Error ? e.message : String(e)}), so there is no neutral-cost or fog screen.`,
149
+ };
150
+ }
151
+ }
152
+ /** Whether GameFeed, else GetMyGames, shows the signed-in account in the game. */
153
+ async function confirmSeated(ctx, gameId) {
154
+ const token = await ctx.myInviteToken();
155
+ if (token !== undefined) {
156
+ try {
157
+ const game = await ctx.client.getGame(gameId, { map: false });
158
+ if (game.players.some((p) => p.id === token && holdsSeat(p.state)))
159
+ return true;
160
+ }
161
+ catch {
162
+ // No GameFeed credentials or a failed read: try the web client's list.
163
+ }
164
+ }
165
+ try {
166
+ const { me, games } = await fetchMyGames(ctx);
167
+ return games.some((g) => g.id === gameId && g.players.some((p) => p.id === me && holdsSeat(playerStateName(p.stateCode))));
168
+ }
169
+ catch {
170
+ return false;
171
+ }
172
+ }
173
+ export function registerJoinGameTool(server, ctx) {
174
+ defineGatedWrite(server, {
175
+ title: 'Join an open war.app game',
176
+ _meta: mintMeta('change', ['join game', 'join a warzone game', 'take an open seat']),
177
+ }, {
178
+ name: 'warapp_join_game',
179
+ description: 'Join an open war.app (Warzone) game: take an open seat in a game from warapp_list_open_games. The game ' +
180
+ 'is re-read from war.app\'s open games list first; team games, coin entry fees, custom scenarios and mod ' +
181
+ 'games are refused unless allowed (scenario and mod games always), and so is a game you already joined. ' +
182
+ 'It joins with your preferred colour, else your secondary, else a free standard colour (or the color you ' +
183
+ 'pass); the preview shows which, plus a screen from the lobby\'s GameFeed settings (does the cheapest ' +
184
+ 'neutral cost at most one turn of base income; Light Fog) and `policy`: whether the lobby keeps the ' +
185
+ 'joining policy (no Commerce, mods or custom scenarios; that cheap neutral; at most four seats; a boot time ' +
186
+ 'of at least 12 hours; no lottery — `lottery`, read from the data as warapp_list_open_games does) — advisory, the join is not refused for it. You become a player and are expected ' +
187
+ 'to take turns — leaving later means declining or being booted.' +
188
+ `${noBrowserNote(ctx.hosted)} ${CONFIRM_INJECTION_RULE}`,
189
+ annotations: toolAnnotations({
190
+ title: 'Join an open war.app game',
191
+ readOnly: false,
192
+ destructive: true,
193
+ idempotent: false,
194
+ openWorld: true,
195
+ }),
196
+ inputSchema: z.object({
197
+ game_id: gameIdArg,
198
+ allow_team: z.boolean().optional().describe("Allow joining a team game on the first open seat's team (default false)."),
199
+ team: z.coerce
200
+ .number()
201
+ .int()
202
+ .min(0)
203
+ .optional()
204
+ .describe('In a team game: the team to join (a team number with an open seat; the preview lists the teams offered and ' +
205
+ 'the seats on the chosen one). Implies allow_team. Refused outside a team game, with random teams, and for a ' +
206
+ 'team that is full or not in the game.'),
207
+ accept_entry_fee: z
208
+ .boolean()
209
+ .optional()
210
+ .describe('Allow paying a coin entry fee (default false: only free games).'),
211
+ color: z
212
+ .number()
213
+ .int()
214
+ .min(0)
215
+ .max(GAME_COLOR_COUNT - 1)
216
+ .optional()
217
+ .describe(`The colour to play as: a war.app colour index (0–${STANDARD_COLORS - 1} are the standard colours; ` +
218
+ 'higher ones need an unlock). Default: your preferred colour, else your secondary, else the first ' +
219
+ 'standard colour no player in the game has.'),
220
+ }),
221
+ async plan({ game_id, allow_team, team: askedTeam, accept_entry_fee, color: requested }) {
222
+ const gameId = parseGameId(game_id);
223
+ // One fresh read gives the account the gate binds and its in-game id (sliced from the
224
+ // token TEXT, #130), so the already-joined check is for that same account. A join always
225
+ // acts as the signed-in account, so it is refused when that cannot be read (#133).
226
+ const [html, me] = await Promise.all([openGamesPage(ctx), ctx.myIdentity({ fresh: true })]);
227
+ if (me === undefined)
228
+ throw accountUnknown(ctx.hosted);
229
+ const { token, inGameId: myId } = me;
230
+ const bundle = await ctx.bundle();
231
+ const parsed = parseOpenGamesPage(html, bundle);
232
+ const lobby = parsed.lobbies.get(gameId);
233
+ refuseJoined(lobby, gameId, myId);
234
+ const listed = joinable(parsed.games, gameId, (allow_team ?? false) || askedTeam !== undefined, accept_entry_fee ?? false);
235
+ const team = chooseTeam(listed, lobby, askedTeam);
236
+ const { color, source } = joinColor(requested, html, bundle, lobby, gameId);
237
+ // #217: the lobby's screen, then whether it is a lottery (its map read only for that settings shape).
238
+ const screened = await lobbyScreen(ctx, gameId);
239
+ const [game] = (await markLotteries(ctx, [listed]));
240
+ return {
241
+ gate: {
242
+ action: 'warapp.join_game',
243
+ summary: `Join war.app game ${gameId} (${game.pace}, ${game.openSeats} open of ${game.seats} seats)`,
244
+ account: writeAccount(token),
245
+ target: gameId,
246
+ payload: { method: 'AcceptOpenSeat', gameId, team, color },
247
+ willSend: { game: gameId, team: team === NO_TEAM ? 'none' : team, color },
248
+ preview: {
249
+ game: {
250
+ id: game.id,
251
+ name: untrustedText(game.name),
252
+ url: game.url,
253
+ pace: game.pace,
254
+ ...(game.bootTime ? { bootTime: game.bootTime } : {}),
255
+ players: game.players,
256
+ openSeats: game.openSeats,
257
+ seats: game.seats,
258
+ teamGame: game.teamGame,
259
+ entryFeeCoins: game.entryFeeCoins,
260
+ prizeCoins: game.prizeCoins,
261
+ rules: game.rules,
262
+ ...(game.lottery !== undefined ? { lottery: game.lottery, lotteryBasis: game.lotteryBasis } : {}),
263
+ plannerGaps: [...game.plannerGaps, ...screened.gaps],
264
+ },
265
+ // #132: worth joining only when the cheapest neutral costs at most a turn of base income.
266
+ screen: screened.screen,
267
+ ...(screened.note ? { screenNote: screened.note } : {}),
268
+ // #134: the owner's joining policy — advisory, the join is not refused for it.
269
+ policy: joiningPolicy(game, screened.screen),
270
+ color: { index: color, source },
271
+ // C4: in a team game, the team joined and who already sits on it.
272
+ ...(game.teamGame ? { team: teamView(game, lobby, team) } : {}),
273
+ account: String(token),
274
+ note: 'Joining makes you a player who must take turns until the game ends.',
275
+ untrusted: UNTRUSTED_PREVIEW_NOTE,
276
+ },
277
+ },
278
+ state: {
279
+ gameId,
280
+ name: game.name,
281
+ url: game.url,
282
+ team,
283
+ color,
284
+ account: String(token),
285
+ },
286
+ };
287
+ },
288
+ async execute({ gameId, name, url, team, color, account }) {
289
+ await requireApprovedAccount(ctx, account);
290
+ const game = { id: gameId, name, url };
291
+ let vacationEnded = false;
292
+ const extra = () => (vacationEnded ? { vacationEnded: true } : {});
293
+ const notShown = () => ({
294
+ status: 'unconfirmed',
295
+ outcome: 'unconfirmed',
296
+ game,
297
+ ...extra(),
298
+ warning: 'war.app accepted the join, but neither GameFeed nor your games list shows you in the game yet, so ' +
299
+ 'this could not confirm it. Check warapp_my_games shortly.',
300
+ });
301
+ return sendAndVerify({
302
+ send: async () => {
303
+ const env = await ctx.rpc.call('AcceptOpenSeat', Method.AcceptOpenSeat, (w) => writeAcceptOpenSeatParams(w, { gameId, team, color }));
304
+ vacationEnded = readAcceptOpenSeatReturn(env.body)?.vacationEnded ?? false;
305
+ },
306
+ // "Already in the game": the client treats it as a successful join.
307
+ refused: (e) => {
308
+ if (e.code === ALREADY_JOINED)
309
+ return 'ignore';
310
+ const wording = joinErrorWording(e);
311
+ return wording ? new WarappServerError(e.code, `${wording} (war.app error ${e.code})`) : undefined;
312
+ },
313
+ unanswered: (failure) => ({
314
+ status: 'unknown',
315
+ outcome: 'unknown',
316
+ game,
317
+ warning: `war.app did not confirm the join (${failure}), so you may ` +
318
+ 'already have joined. Check warapp_my_games before trying again.',
319
+ }),
320
+ // Never throws: a failed read is "not shown".
321
+ readBack: () => confirmSeated(ctx, gameId),
322
+ unreadable: () => notShown(),
323
+ classify: (seated) => (seated ? { status: 'joined', outcome: 'confirmed', game, ...extra() } : notShown()),
324
+ });
325
+ },
326
+ });
327
+ }