@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,611 @@
1
+ // The agreement ledger's tools (docs/PLAN-TEAMS.md A2): `warapp_get_relations` (read-only on war.app;
2
+ // it caches the board it read, like warapp_track_opponents) and `warapp_record_agreement`, which
3
+ // writes only the server's own ledger (`<dataDir>/relations/<gameId>-<playerId>.json`) and the
4
+ // cross-game player record (src/player-record-store.ts; owner decision D5 of 2026-11-14: on, local
5
+ // and hosted, name-free per-agreement entries and tallies) — nothing is sent to war.app or to any
6
+ // player, so it is not confirm-gated. An agreement exists only because the player recorded it here with
7
+ // structured terms: chat is never parsed into one, and words change no flag — only the board does.
8
+ import { McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
9
+ import { z } from 'zod';
10
+ import { boardIncome, incomeRules, trackGame, trackOpponents } from '../analysis/index.js';
11
+ import { agreementChange } from '../analysis/commitments.js';
12
+ import { playerRecord, recordDelta, recordEntryFor } from '../analysis/player-record.js';
13
+ import { AGREEMENT_STATUSES, agreementState, breachWatch, MAX_NOTICE_TURNS, newAgreement, OPENING_STATUSES, partyRefusal, scopeRefusal, tacitTruces, TERMINAL_STATUSES, transitionAgreement, TRUCE_OUTGROW_RATIO, trust, truceEndgame, } from '../analysis/relations.js';
14
+ import { boardStateFromLive } from '../live.js';
15
+ import { entryKey, legacyEntryKey, playerRecordEnabled, playerRecordState, readPlayerRecord, updatePlayerRecord } from '../player-record-store.js';
16
+ import { emptyLedger, nextAgreementId, nextCommitmentId, readLedger, readLedgerForWrite, withLedgerLock, writeLedger } from '../relations-store.js';
17
+ import { isTeamGame, teammatesOf } from '../teams.js';
18
+ import { readBoardHistory, readCachedOrders, writeBoardCache } from '../trend.js';
19
+ import { writeGameRecord } from '../replay.js';
20
+ import { currentTurn, gameIdArg, graphOf, namer, readAnnotations, respond, untrustedDescription, untrustedText, viewArg } from './common.js';
21
+ import { lookupMeta, mintMeta } from './hints.js';
22
+ import { loadLiveGame } from './live-context.js';
23
+ import { BRIDGE_NOTE, playerArg, resolveMe } from './live.js';
24
+ import { mapOf } from './map.js';
25
+ import { recordProfile } from './profile-hook.js';
26
+ import { resolveBonus, resolvePlayer, resolveTerritory } from './resolve.js';
27
+ import { boardHistory, plannerSettings } from './turn.js';
28
+ import { resolveTeamsFor } from './team-source.js';
29
+ const VIEWS = ['compact', 'full'];
30
+ const MAX_SCOPE_ITEMS = 200;
31
+ /** What the results say about the board-derived parts. */
32
+ export const RELATIONS_NOTE = 'Flags come from your own board history (the boards warapp_plan_turn, warapp_track_opponents and this tool ' +
33
+ 'cached, with the orders warapp_submit_turn sent): a fog reveal is never an event, and an event the fog leaves ' +
34
+ 'open is `massing`, never `broken`. Chat is never read into an agreement and never moves a flag. A truce ' +
35
+ 'that two players agree to but the game does not enforce (no Diplomacy card) is a promise, not a rule.';
36
+ /** How the write is described: the server's data directory only (local or a hosted child's per-user dir), never war.app or a player. */
37
+ export const LEDGER_NOTE = "Written only to the server's data directory (the agreement ledger and the partner's name-free player record); " +
38
+ 'nothing is sent to war.app or to any player.';
39
+ const playerRef = z.union([z.string(), z.number()]);
40
+ /** The players as the ledger needs them. */
41
+ export const relationPlayers = (players) => players.map((p) => ({
42
+ id: p.id,
43
+ isAI: p.isAI,
44
+ humanTurnedIntoAI: p.humanTurnedIntoAI,
45
+ ...(p.state !== undefined ? { state: p.state } : {}),
46
+ ...(p.team !== undefined ? { team: p.team } : {}),
47
+ }));
48
+ const alive = (p) => p.state === undefined || p.state === 'Playing';
49
+ function incomesOf(graph, boards, game, me, map) {
50
+ const newest = [...boards].sort((a, b) => a.turn - b.turn).at(-1);
51
+ const opponents = new Map();
52
+ // A teammate is no opponent: its income is no rival's (#246).
53
+ const mates = new Set(teammatesOf(game.players, me).map((p) => p.id));
54
+ for (const p of game.players)
55
+ if (p.id !== me.id && !mates.has(p.id) && alive(p))
56
+ opponents.set(p.id, null);
57
+ if (!newest)
58
+ return { mine: null, opponents };
59
+ const held = new Set(newest.board.territories.filter((t) => t.owner.kind === 'player' && t.owner.playerId === me.id).map((t) => t.territoryId));
60
+ const mine = boardIncome(graph, held, incomeRules(game.settings)).total;
61
+ const tracks = trackOpponents(graph, boards, me.id, plannerSettings(game.settings), trackGame(game.players, game.settings, map, game.endRules));
62
+ for (const t of tracks)
63
+ if (opponents.has(t.playerId))
64
+ opponents.set(t.playerId, t.firstSeen === null ? null : (t.income ?? t.visibleIncome));
65
+ return { mine, opponents };
66
+ }
67
+ /** Whether the truce with `partner` is in its endgame; `null` when an income it needs is unknown. */
68
+ function endgameOf(incomes, partner) {
69
+ const p = incomes.opponents.get(partner);
70
+ if (incomes.mine === null || p === null || p === undefined)
71
+ return null;
72
+ const others = [...incomes.opponents].filter(([id]) => id !== partner);
73
+ if (others.some(([, v]) => v === null))
74
+ return null;
75
+ return truceEndgame({ mine: incomes.mine, partner: p, others: others.map(([, v]) => v) });
76
+ }
77
+ /** Who leads by estimated income on the newest board: me, the partner or another; `unknown` when an income is. */
78
+ function leaderOf(incomes, partner) {
79
+ if (incomes.mine === null)
80
+ return 'unknown';
81
+ let best = { who: 'me', v: incomes.mine };
82
+ for (const [id, v] of [...incomes.opponents].sort(([a], [b]) => a - b)) {
83
+ if (v === null)
84
+ return 'unknown';
85
+ if (v > best.v)
86
+ best = { who: id === partner ? 'partner' : 'other', v };
87
+ }
88
+ return best.who;
89
+ }
90
+ /** The strongest flag a break showed: broken, then over the cap, massing, outgrowing. */
91
+ function strongestFlag(flags) {
92
+ for (const kind of ['broken', 'cap-exceeded', 'massing', 'outgrowing'])
93
+ if (flags.some((f) => f.kind === kind))
94
+ return kind;
95
+ return null;
96
+ }
97
+ /** My cached boards of `game` (with my cached orders), oldest first: no request. */
98
+ async function cachedBoards(dir, game, me) {
99
+ const orders = await readCachedOrders(dir, game.id, me.id);
100
+ return (await readBoardHistory(dir, game.id, me.id)).map((b) => {
101
+ const o = orders.get(b.turn);
102
+ return { turn: b.turn, board: b.board, ...(o ? { orders: o } : {}) };
103
+ });
104
+ }
105
+ /** The game's format for a record entry: players seated, teams, and the free-for-all's size still playing. */
106
+ const formatOf = (game) => {
107
+ const teams = isTeamGame(game.players);
108
+ return { players: game.players.length, teams, ffaSize: teams ? null : game.players.filter(alive).length };
109
+ };
110
+ /** A scope from the tool's arguments, by id. `nothing` ends the refusal: what the caller did not do. */
111
+ export function scopeFrom(map, territories, bonuses, nothing = 'nothing was recorded') {
112
+ if (territories?.length && bonuses?.length) {
113
+ throw new McpToolError(`Give \`territories\` or \`bonuses\`, not both: ${nothing}.`, {
114
+ hint: 'A truce covers all of your territories (omit both), some territories, or the territories of some bonuses.',
115
+ });
116
+ }
117
+ if (territories?.length)
118
+ return { territories: [...new Set(territories.map((t) => resolveTerritory(map, t).id))].sort((a, b) => a - b) };
119
+ if (bonuses?.length)
120
+ return { bonuses: [...new Set(bonuses.map((b) => resolveBonus(map, b).id))].sort((a, b) => a - b) };
121
+ return 'all';
122
+ }
123
+ /** An agreement as a result shows it: players by id with a delimited name, territories and bonuses by id and name. */
124
+ function agreementView(a, game, map, turn, rung) {
125
+ const name = namer(map);
126
+ const player = (id) => {
127
+ const p = game.players.find((x) => x.id === id);
128
+ return { id, name: p ? untrustedText(p.name) : null };
129
+ };
130
+ const scope = a.terms.scope;
131
+ const state = agreementState(a, turn, relationPlayers(game.players));
132
+ return {
133
+ id: a.id,
134
+ with: player(a.with),
135
+ kind: a.kind,
136
+ status: a.status,
137
+ state: state.phase,
138
+ ...(state.endsTurn !== undefined ? { endsTurn: state.endsTurn } : {}),
139
+ ...(state.reason ? { overBecause: state.reason } : {}),
140
+ createdTurn: a.createdTurn,
141
+ ...(a.agreedTurn !== undefined ? { agreedTurn: a.agreedTurn } : {}),
142
+ ...(a.noticeTurn !== undefined ? { noticeTurn: a.noticeTurn } : {}),
143
+ ...(a.endedTurn !== undefined ? { endedTurn: a.endedTurn } : {}),
144
+ terms: {
145
+ scope: scope === 'all'
146
+ ? 'all'
147
+ : 'territories' in scope
148
+ ? { territories: scope.territories.map(name) }
149
+ : {
150
+ bonuses: scope.bonuses.map((id) => {
151
+ const b = map.bonuses.find((x) => x.id === id);
152
+ return { id, name: b?.name ?? String(id), value: b?.value ?? null };
153
+ }),
154
+ },
155
+ noticeTurns: a.terms.noticeTurns,
156
+ ...(a.terms.borderCap !== undefined ? { borderCap: a.terms.borderCap } : {}),
157
+ ...(a.terms.untilTurn !== undefined ? { untilTurn: a.terms.untilTurn } : {}),
158
+ ...(a.terms.untilPlayerOut !== undefined ? { untilPlayerOut: player(a.terms.untilPlayerOut) } : {}),
159
+ ...(a.terms.against !== undefined ? { against: player(a.terms.against) } : {}),
160
+ },
161
+ ...(a.enforced !== undefined ? { enforced: a.enforced } : {}),
162
+ ...(a.retaliated !== undefined ? { retaliated: a.retaliated } : {}),
163
+ ...(rung === 'full' ? { history: a.history } : {}),
164
+ };
165
+ }
166
+ /** An entry as a result shows it: everything but its key. */
167
+ const entryView = ({ key: _key, ...rest }) => rest;
168
+ /** The reliability facts on record for `partner` (and its entries), or why there are none. */
169
+ export async function recordFor(dir, partner, env) {
170
+ if (!playerRecordEnabled(env))
171
+ return { record: 'off' };
172
+ if (!dir)
173
+ return { record: null };
174
+ const r = await readPlayerRecord(dir, partner, env);
175
+ if (r === null || r === 'off' || r === 'unreadable')
176
+ return { record: r };
177
+ return { record: playerRecord(r.tallies, r.entries), entries: r.entries };
178
+ }
179
+ /**
180
+ * The cross-game record (D5) for one change to an agreement: its name-free entry, "proposed again" on
181
+ * this partner's earlier agreements in this game when it proposes anew, and the tallies its transition
182
+ * earns; a break also records its strongest flag and its context from my cached boards. Call it inside
183
+ * the ledger's lock (a different file and lock, never nested on itself), so entries land in the order the
184
+ * ledger changed. Shared by warapp_record_agreement and warapp_submit_turn's `break_agreement`.
185
+ */
186
+ export async function updateAgreementRecord(o) {
187
+ const { dir, env, game, me, map, graph, agreement, before, created, others } = o;
188
+ if (!playerRecordEnabled(env))
189
+ return 'off';
190
+ let breachFlag;
191
+ let context;
192
+ if (agreement.status !== before?.status && (agreement.status === 'broken-by-them' || agreement.status === 'broken-by-me')) {
193
+ const boards = await cachedBoards(dir, game, me);
194
+ breachFlag = strongestFlag(breachWatch({ agreement, graph, boards, me: me.id }));
195
+ const incomes = incomesOf(graph, boards, game, me, map);
196
+ const partnerIncome = incomes.opponents.get(agreement.with) ?? null;
197
+ context = {
198
+ endgame: endgameOf(incomes, agreement.with),
199
+ leader: leaderOf(incomes, agreement.with),
200
+ outgrowing: incomes.mine !== null && incomes.mine > 0 && partnerIncome !== null ? partnerIncome > TRUCE_OUTGROW_RATIO * incomes.mine : null,
201
+ };
202
+ }
203
+ const earlier = created && agreement.status === 'proposed-by-them' ? others.filter((a) => a.with === agreement.with && TERMINAL_STATUSES.has(a.status)) : [];
204
+ const now = Date.now();
205
+ return updatePlayerRecord(dir, agreement.with, (salt, current) => {
206
+ // An entry written before my account was in the key is found under the older key and kept there.
207
+ const onRecord = (id) => current.entries.find((e) => e.key === entryKey(salt, me.id, game.id, id)) ??
208
+ current.entries.find((e) => e.key === legacyEntryKey(salt, game.id, id));
209
+ const previous = onRecord(agreement.id);
210
+ const key = previous?.key ?? entryKey(salt, me.id, game.id, agreement.id);
211
+ const again = earlier
212
+ .map((a) => onRecord(a.id))
213
+ .filter((e) => e !== undefined && !e.proposedAgain)
214
+ .map((e) => ({ ...e, proposedAgain: true, updated: now }));
215
+ const entry = recordEntryFor(agreement, { key, format: formatOf(game), now, ...(breachFlag !== undefined ? { breachFlag } : {}), ...(context ? { context } : {}) }, previous);
216
+ return { delta: recordDelta(before, agreement), entries: [...again, entry] };
217
+ }, env, now);
218
+ }
219
+ /**
220
+ * B2 (`warapp_submit_turn`'s `break_agreement`): mark each agreement broken by me on `turn`, through the
221
+ * same path as warapp_record_agreement — the ledger's transition under its lock, then the partner's
222
+ * player record (D5). Never throws: what could not be recorded says why.
223
+ */
224
+ export async function recordBrokenByMe(o) {
225
+ const { dir, env, game, me, map, turn } = o;
226
+ const graph = graphOf(map);
227
+ try {
228
+ return await withLedgerLock(dir, game.id, me.id, async () => {
229
+ const read = await readLedgerForWrite(dir, game.id, me.id);
230
+ if (read === null || read === 'unreadable') {
231
+ const why = read === null ? 'no ledger for this game' : 'the ledger exists but cannot be read';
232
+ return o.agreements.map((agreement) => ({ agreement, ledger: 'refused', why }));
233
+ }
234
+ let ledger = read;
235
+ const out = [];
236
+ for (const id of o.agreements) {
237
+ const found = ledger.agreements.find((a) => a.id === id);
238
+ if (!found) {
239
+ out.push({ agreement: id, ledger: 'refused', why: 'not in the ledger' });
240
+ continue;
241
+ }
242
+ const moved = transitionAgreement(found, 'broken-by-me', turn);
243
+ if ('refused' in moved) {
244
+ out.push({ agreement: id, ledger: 'refused', why: moved.refused });
245
+ continue;
246
+ }
247
+ const rest = ledger.agreements.filter((a) => a.id !== id);
248
+ const next = { ...ledger, agreements: [...rest, moved.agreement] };
249
+ if (!(await writeLedger(dir, next))) {
250
+ out.push({ agreement: id, ledger: 'refused', why: 'the ledger could not be written' });
251
+ continue;
252
+ }
253
+ ledger = next;
254
+ const playerRecord = await updateAgreementRecord({ dir, env, game, me, map, graph, agreement: moved.agreement, before: found, created: false, others: rest });
255
+ out.push({ agreement: id, ledger: 'recorded', playerRecord });
256
+ }
257
+ return out;
258
+ });
259
+ }
260
+ catch (e) {
261
+ return o.agreements.map((agreement) => ({ agreement, ledger: 'refused', why: e.message }));
262
+ }
263
+ }
264
+ /**
265
+ * B4 (warapp_send_chat, once a message is sent): record its declared commitments in the ledger as
266
+ * mine, under the ledger's lock — a propose, accept or notice re-applied to the ledger as it now stands
267
+ * (`agreementChange`, the same rule the check used, so the agreement id is the ledger's own) and moved
268
+ * through warapp_record_agreement's path (the partner's player record, D5, when `game` is given); a
269
+ * no-attack or will-attack as the check made it. Never throws: what could not be recorded says why.
270
+ */
271
+ export async function recordCommitments(o) {
272
+ const { dir, env, gameId, meId, turn, players } = o;
273
+ const refusedAll = (why) => o.commitments.map(({ commitment }, index) => ({ index, kind: commitment.kind, why }));
274
+ try {
275
+ return await withLedgerLock(dir, gameId, meId, async () => {
276
+ const read = await readLedgerForWrite(dir, gameId, meId);
277
+ if (read === 'unreadable')
278
+ return refusedAll('the ledger exists but cannot be read');
279
+ let ledger = read ?? emptyLedger(gameId, meId);
280
+ const out = [];
281
+ const changes = [];
282
+ for (const [index, { commitment: c, record }] of o.commitments.entries()) {
283
+ let entry = record;
284
+ if (c.kind === 'propose' || c.kind === 'accept' || c.kind === 'notice') {
285
+ const change = agreementChange(c, { agreements: ledger.agreements, turn, me: meId, players, nextAgreementId: (agreements) => nextAgreementId({ agreements }) });
286
+ if ('refused' in change) {
287
+ out.push({ index, kind: c.kind, why: change.refused });
288
+ continue;
289
+ }
290
+ const a = change.agreement;
291
+ ledger = { ...ledger, agreements: [...ledger.agreements.filter((x) => x.id !== a.id), a] };
292
+ if (change.agreement !== change.before)
293
+ changes.push({ ...change, at: out.length });
294
+ entry =
295
+ c.kind === 'notice'
296
+ ? { sentTurn: turn, kind: 'notice', agreement: a.id, with: a.with, endsTurn: record.kind === 'notice' ? record.endsTurn : turn + a.terms.noticeTurns }
297
+ : { sentTurn: turn, kind: c.kind, agreement: a.id, with: a.with };
298
+ out.push({ index, kind: c.kind, agreement: { id: a.id, status: a.status } });
299
+ }
300
+ else {
301
+ out.push({ index, kind: c.kind });
302
+ }
303
+ const id = nextCommitmentId(ledger);
304
+ ledger = { ...ledger, commitments: [...(ledger.commitments ?? []), { id, ...entry }] };
305
+ out[out.length - 1].id = id;
306
+ }
307
+ if (!(await writeLedger(dir, ledger)))
308
+ return refusedAll('the ledger could not be written');
309
+ for (const ch of changes) {
310
+ const shown = out[ch.at].agreement;
311
+ if (!o.game) {
312
+ shown.playerRecord = 'failed';
313
+ continue;
314
+ }
315
+ const { game, me, map } = o.game;
316
+ const others = ledger.agreements.filter((a) => a.id !== ch.agreement.id);
317
+ shown.playerRecord = await updateAgreementRecord({ dir, env, game, me, map, graph: graphOf(map), agreement: ch.agreement, before: ch.before, created: ch.created, others });
318
+ }
319
+ return out;
320
+ });
321
+ }
322
+ catch (e) {
323
+ return refusedAll(e.message);
324
+ }
325
+ }
326
+ export function registerRelationsTools(server, ctx, opts = {}) {
327
+ const env = opts.env;
328
+ server.registerTool('warapp_get_relations', {
329
+ title: 'Read my agreements in a war.app game',
330
+ description: untrustedDescription('Read the agreements (truces) you recorded with warapp_record_agreement for a war.app (Warzone) game, each with ' +
331
+ 'its state this turn (`proposed`, `active`, in `notice` with the turn it ends, or `over` and why: ended, broken, ' +
332
+ 'the partner eliminated or turned AI, only two players left, its end condition met, its notice run), and for a ' +
333
+ 'live one: watch `flags` from your own board history — `broken` (the partner took or attacked a covered territory ' +
334
+ 'of yours), `cap-exceeded` (a partner stack on the covered border above the agreed cap), `massing` (its visible ' +
335
+ 'armies near the covered border grew two turns running, or an event the fog leaves ambiguous), `outgrowing` (its ' +
336
+ `estimated income above ${TRUCE_OUTGROW_RATIO}× yours) and \`kept\` (quiet turns) — and \`trust\`: \`clear\`, or \`watch\` ` +
337
+ 'on any flag but kept, on their notice, and in the endgame (no other opponent still a match for either of you). ' +
338
+ 'Also `tacit`: neighbours with no agreement whose shared border stayed quiet three turns or more — reported, never ' +
339
+ "relied on. The cross-game player record (on unless WARAPP_PLAYER_RECORD=off, local and hosted) gives each partner's " +
340
+ '`record`: how it kept earlier agreements — tallies, a kept rate, its notices honoured or broken, its breaks in ' +
341
+ 'the endgame or while leading, retaliation, proposing again and turns to a break (`full` adds the entries) — keyed ' +
342
+ 'by a salted hash, never its id or name. `playerRecord` says on, off or unreadable. Words in chat never change a ' +
343
+ `flag or the trust: only the board does. ${BRIDGE_NOTE} Read-only on war.app; it caches the board it read.`),
344
+ _meta: lookupMeta(['my truces', 'agreements', 'is my truce holding', 'diplomacy', 'who kept their word']),
345
+ annotations: readAnnotations('Read war.app agreements'),
346
+ inputSchema: z.object({
347
+ game_id: gameIdArg,
348
+ player: playerArg,
349
+ view: viewArg(VIEWS, 'compact (default) gives each agreement, its state, trust, flags and the partner\'s record; "full" adds each agreement\'s status history and the partner\'s record entries.'),
350
+ }),
351
+ }, async ({ game_id, player, view }) => {
352
+ const feed = await ctx.client.getGame(game_id, { settings: true });
353
+ const seat = await resolveMe(ctx, feed.players, player);
354
+ // The teams, once my seat is found: GameFeed's, else the game list's (asked once per game, kept).
355
+ const { game, me, known: teamsKnown } = await resolveTeamsFor(ctx, feed, seat);
356
+ const map = mapOf(game);
357
+ const graph = graphOf(map);
358
+ const turn = currentTurn(game) ?? 0;
359
+ const ledger = (ctx.dataDir ? await readLedger(ctx.dataDir, game.id, me.id) : undefined) ?? emptyLedger(game.id, me.id);
360
+ const notes = [RELATIONS_NOTE];
361
+ let boards = [];
362
+ let live = false;
363
+ if (game.state === 'Playing' && currentTurn(game) !== null) {
364
+ boards = (await boardHistory(ctx, game, me, turn)).boards;
365
+ try {
366
+ const { territories } = await loadLiveGame(ctx, game);
367
+ const board = boardStateFromLive(territories, me, game.players);
368
+ boards = [...boards.filter((b) => b.turn !== turn), { turn, board }];
369
+ live = true;
370
+ if (ctx.dataDir) {
371
+ await writeBoardCache(ctx.dataDir, game.id, me.id, turn, board);
372
+ await writeGameRecord(ctx.dataDir, game);
373
+ await recordProfile(ctx.dataDir, env, game, me, boards, teamsKnown);
374
+ }
375
+ }
376
+ catch {
377
+ notes.push(`The live board could not be read: flags come from the cached boards only (turns ${boards.map((b) => b.turn).join(', ') || 'none'}).`);
378
+ }
379
+ }
380
+ else {
381
+ notes.push(`Game state ${game.state}: no board is read, so there are no flags.`);
382
+ }
383
+ const incomes = incomesOf(graph, boards, game, me, map);
384
+ const agreements = [];
385
+ for (const a of ledger.agreements) {
386
+ const state = agreementState(a, turn, relationPlayers(game.players));
387
+ const live_ = state.phase === 'active' || state.phase === 'notice';
388
+ const flags = a.agreedTurn !== undefined
389
+ ? breachWatch({
390
+ agreement: a,
391
+ graph,
392
+ boards,
393
+ me: me.id,
394
+ ...(live_ && incomes.mine !== null ? { incomes: { mine: incomes.mine, partner: incomes.opponents.get(a.with) ?? null } } : {}),
395
+ })
396
+ : [];
397
+ const endgame = live_ ? endgameOf(incomes, a.with) : null;
398
+ agreements.push({
399
+ agreement: a,
400
+ flags,
401
+ ...(live_ ? { trust: trust(a, flags, { endgame: endgame === true }), endgame } : {}),
402
+ ...(await recordFor(ctx.dataDir, a.with, env)),
403
+ });
404
+ }
405
+ // A teammate's quiet border is no tacit truce (#246): left out like a partner with an agreement.
406
+ const excluded = new Set([
407
+ ...ledger.agreements.filter((a) => !TERMINAL_STATUSES.has(a.status)).map((a) => a.with),
408
+ ...teammatesOf(game.players, me).map((p) => p.id),
409
+ ]);
410
+ const tacit = tacitTruces({ graph, boards, me: me.id, exclude: excluded });
411
+ const recordState = await playerRecordState(ctx.dataDir, env);
412
+ const name = namer(map);
413
+ const playerName = (id) => {
414
+ const p = game.players.find((x) => x.id === id);
415
+ return { id, name: p ? untrustedText(p.name) : null };
416
+ };
417
+ return respond(view, VIEWS, (rung) => ({
418
+ game: { id: game.id, name: game.name === undefined ? null : untrustedText(game.name), state: game.state, turn },
419
+ player: { id: me.id, name: untrustedText(me.name) },
420
+ agreements: agreements.map((x) => ({
421
+ ...agreementView(x.agreement, game, map, turn, rung),
422
+ ...(x.trust ? { trust: x.trust, endgame: x.endgame } : {}),
423
+ flags: x.flags.map((f) => ({ ...f, territories: f.territories.map(name) })),
424
+ record: x.record,
425
+ ...(rung === 'full' && x.entries ? { recordEntries: x.entries.map(entryView) } : {}),
426
+ })),
427
+ tacit: tacit.map((t) => ({ player: playerName(t.player), quietTurns: t.quietTurns, border: t.border.map(name) })),
428
+ boards: { turns: boards.map((b) => b.turn).sort((a, b) => a - b), live },
429
+ incomes: { mine: incomes.mine, opponents: Object.fromEntries(incomes.opponents) },
430
+ playerRecord: recordState,
431
+ notes,
432
+ }));
433
+ });
434
+ server.registerTool('warapp_record_agreement', {
435
+ title: 'Record an agreement in a war.app game',
436
+ _meta: mintMeta('change', ['record a truce', 'we agreed a truce', 'they broke the truce', 'give notice']),
437
+ description: untrustedDescription('Record a truce you made, proposed or received in a war.app (Warzone) free-for-all, or a change to one, in this ' +
438
+ "machine's agreement ledger. Nothing is sent to war.app or to any player (so there is no confirmation " +
439
+ 'step): it records what was agreed, so warapp_get_relations can watch the board for it. Create one with ' +
440
+ '`with` (the partner) and `status` proposed-by-me, proposed-by-them or agreed, and its terms: what it covers ' +
441
+ '(all of your territories, or `territories`, or the territories of `bonuses`), `notice_turns` (0–3, default 1), ' +
442
+ 'an optional `border_cap`, and an end (`until_turn`, `until_player_out`). Update one by `agreement_id` and the ' +
443
+ 'new `status`: agreed, notice-by-me, notice-by-them, ended, broken-by-them, broken-by-me (terms change only ' +
444
+ 'while proposed; an ended or broken agreement takes nothing more but `retaliated` after broken-by-me). Refused ' +
445
+ 'for a partner who is you, an AI, out of the game or your teammate, in a 1v1 or once two players remain, and for ' +
446
+ 'a territory or bonus not on the map. An agreement exists only because you record it here: chat is never read ' +
447
+ 'into one. With the cross-game player record on (owner decision D5: on unless WARAPP_PLAYER_RECORD=off, local and ' +
448
+ 'hosted), each agreement is also kept per partner under a salted hash, name-free (no id, no name, no game, no ' +
449
+ 'message): the format, the turns agreed and ended, the shape of the terms, the outcome, a break\'s turn, flag and ' +
450
+ 'context (endgame, who led, outgrowing), retaliation and proposing again, with tallies; `playerRecord` says ' +
451
+ 'updated, off or failed.'),
452
+ annotations: toolAnnotations({ title: 'Record a war.app agreement', readOnly: false, destructive: false, idempotent: false, openWorld: true }),
453
+ inputSchema: z.object({
454
+ game_id: gameIdArg,
455
+ player: playerArg,
456
+ agreement_id: z.string().trim().min(1).max(20).optional().describe('The agreement to update (e.g. "a1"). Omit to record a new one.'),
457
+ with: playerRef.optional().describe('The partner (name or GameFeed id). Required for a new agreement.'),
458
+ status: z.enum(AGREEMENT_STATUSES).optional().describe('The status to record. Required for a new agreement.'),
459
+ territories: z.array(playerRef).max(MAX_SCOPE_ITEMS).optional().describe('Only these territories (names or ids) are covered.'),
460
+ bonuses: z.array(playerRef).max(MAX_SCOPE_ITEMS).optional().describe("Only these bonuses' territories (names or ids) are covered."),
461
+ notice_turns: z.coerce.number().int().min(0).max(MAX_NOTICE_TURNS).optional().describe('Turns of notice before it ends (default 1).'),
462
+ border_cap: z.coerce.number().int().min(0).optional().describe('The most armies either side keeps on a territory of the covered border.'),
463
+ until_turn: z.coerce.number().int().min(1).optional().describe('The last turn it binds (this turn or later).'),
464
+ until_player_out: playerRef.optional().describe('It ends when this player (name or id) is out of the game.'),
465
+ against: playerRef.optional().describe('The player (name or id) it is aimed at, when it names one.'),
466
+ retaliated: z.boolean().optional().describe('After broken-by-me: whether the partner retaliated.'),
467
+ }),
468
+ }, async (args) => {
469
+ if (!ctx.dataDir) {
470
+ throw new McpToolError('This server has no data directory, so there is no ledger to record into: nothing was recorded.', {
471
+ hint: 'Set MCP_DATA_DIR, or run with a writable home directory.',
472
+ });
473
+ }
474
+ const dir = ctx.dataDir;
475
+ const feed = await ctx.client.getGame(args.game_id, { settings: true });
476
+ if (feed.state !== 'Playing' && feed.state !== 'DistributingTerritories') {
477
+ throw new McpToolError(`Game ${feed.id} is ${feed.state}: agreements are recorded only while it is being played. Nothing was recorded.`, {
478
+ hint: 'Record an agreement once the game has started (picks included).',
479
+ });
480
+ }
481
+ const seat = await resolveMe(ctx, feed.players, args.player);
482
+ // The teams (a teammate is refused as a partner), once my seat is found: GameFeed's, else the game
483
+ // list's (asked once per game, kept).
484
+ const { game, me } = await resolveTeamsFor(ctx, feed, seat);
485
+ const map = mapOf(game);
486
+ const graph = graphOf(map);
487
+ const turn = Math.max(0, currentTurn(game) ?? 0);
488
+ const players = relationPlayers(game.players);
489
+ const refuse = (why, hint) => {
490
+ throw new McpToolError(`${why}: nothing was recorded.`, { hint });
491
+ };
492
+ const termsGiven = args.territories !== undefined ||
493
+ args.bonuses !== undefined ||
494
+ args.notice_turns !== undefined ||
495
+ args.border_cap !== undefined ||
496
+ args.until_turn !== undefined ||
497
+ args.until_player_out !== undefined ||
498
+ args.against !== undefined;
499
+ const otherPlayer = (ref, what, partner) => {
500
+ const p = resolvePlayer(game.players, ref);
501
+ if (p.id === me.id || p.id === partner)
502
+ refuse(`${what} must be a third player, not you or the partner`, `Name the player ${what === '`against`' ? 'the truce is aimed at' : 'whose fall ends it'}.`);
503
+ return p.id;
504
+ };
505
+ const termsFrom = (base, partner) => {
506
+ const scope = args.territories !== undefined || args.bonuses !== undefined ? scopeFrom(map, args.territories, args.bonuses) : (base?.scope ?? 'all');
507
+ const why = scopeRefusal(graph, scope);
508
+ if (why)
509
+ refuse(why, 'Name territories and bonuses on this map.');
510
+ const t = { scope, noticeTurns: args.notice_turns ?? base?.noticeTurns ?? 1 };
511
+ const cap = args.border_cap ?? base?.borderCap;
512
+ if (cap !== undefined)
513
+ t.borderCap = cap;
514
+ if (args.until_turn !== undefined && args.until_turn < turn)
515
+ refuse(`until_turn ${args.until_turn} is before this turn (${turn})`, 'Give this turn or a later one as the last turn it binds.');
516
+ const until = args.until_turn ?? base?.untilTurn;
517
+ if (until !== undefined)
518
+ t.untilTurn = until;
519
+ const out = args.until_player_out !== undefined ? otherPlayer(args.until_player_out, '`until_player_out`', partner) : base?.untilPlayerOut;
520
+ if (out !== undefined)
521
+ t.untilPlayerOut = out;
522
+ const against = args.against !== undefined ? otherPlayer(args.against, '`against`', partner) : base?.against;
523
+ if (against !== undefined)
524
+ t.against = against;
525
+ return t;
526
+ };
527
+ /** The change `args` make to `ledger`: the agreement after it, and as it stood. Refuses what cannot be recorded. */
528
+ const change = (ledger) => {
529
+ let agreement;
530
+ let before;
531
+ let created = false;
532
+ if (args.agreement_id === undefined) {
533
+ if (args.with === undefined || args.status === undefined)
534
+ refuse('A new agreement needs `with` (the partner) and `status`', 'Pass `agreement_id` to update one already recorded.');
535
+ if (!OPENING_STATUSES.includes(args.status))
536
+ refuse(`A new agreement starts as ${OPENING_STATUSES.join(', ')}, not ${args.status}`, 'Record it as agreed first, then update it.');
537
+ const partner = resolvePlayer(game.players, args.with);
538
+ const why = partyRefusal(players, me.id, partner.id);
539
+ if (why)
540
+ refuse(`No truce with player ${partner.id}: ${why}`, 'A truce is with another human player still in a free-for-all.');
541
+ const open = ledger.agreements.find((a) => a.with === partner.id && !TERMINAL_STATUSES.has(a.status));
542
+ if (open)
543
+ refuse(`Agreement ${open.id} with player ${partner.id} is still ${open.status}`, `Update it with agreement_id "${open.id}", or end it first.`);
544
+ if (args.retaliated !== undefined)
545
+ refuse('`retaliated` applies only after broken-by-me', 'Record it on the broken agreement.');
546
+ agreement = newAgreement(nextAgreementId(ledger), partner.id, args.status, turn, termsFrom(undefined, partner.id));
547
+ created = true;
548
+ }
549
+ else {
550
+ const found = ledger.agreements.find((a) => a.id === args.agreement_id);
551
+ if (!found)
552
+ refuse(`Game ${game.id} has no agreement ${JSON.stringify(args.agreement_id)}`, 'warapp_get_relations lists the agreements recorded.');
553
+ agreement = found;
554
+ before = found;
555
+ if (args.with !== undefined && resolvePlayer(game.players, args.with).id !== agreement.with)
556
+ refuse(`Agreement ${agreement.id} is with player ${agreement.with}`, 'Omit `with` when updating, or record a new agreement.');
557
+ if (args.status === undefined && !termsGiven && args.retaliated === undefined)
558
+ refuse('Nothing to record: give a new `status`, terms, or `retaliated`', 'Pass the status the agreement moved to.');
559
+ if (termsGiven) {
560
+ if (agreement.status !== 'proposed-by-me' && agreement.status !== 'proposed-by-them')
561
+ refuse(`The terms of agreement ${agreement.id} (${agreement.status}) can no longer change`, 'End it and record a new agreement with the new terms.');
562
+ agreement = { ...agreement, terms: termsFrom(agreement.terms, agreement.with) };
563
+ }
564
+ if (args.status !== undefined && args.status !== agreement.status) {
565
+ const moved = transitionAgreement(agreement, args.status, turn);
566
+ if ('refused' in moved)
567
+ refuse(moved.refused, 'warapp_get_relations shows its status.');
568
+ agreement = moved.agreement;
569
+ // A new commitment needs a party who can still keep it; ending or recording a break does not.
570
+ if (args.status === 'agreed' || args.status === 'proposed-by-me' || args.status === 'proposed-by-them') {
571
+ const why = partyRefusal(players, me.id, agreement.with);
572
+ if (why)
573
+ refuse(`Agreement ${agreement.id} cannot become ${args.status}: ${why}`, 'Record it as ended instead.');
574
+ }
575
+ }
576
+ if (args.retaliated !== undefined) {
577
+ if (agreement.status !== 'broken-by-me')
578
+ refuse('`retaliated` applies only after broken-by-me', 'Record it on the agreement you broke.');
579
+ agreement = { ...agreement, retaliated: args.retaliated };
580
+ }
581
+ }
582
+ return { agreement, before, created };
583
+ };
584
+ const updateRecord = (agreement, before, created, others) => updateAgreementRecord({ dir, env, game, me, map, graph, agreement, before, created, others });
585
+ // Read, change and write the ledger under its in-process lock: two calls never lose each other's change.
586
+ const { agreement, created, recorded } = await withLedgerLock(dir, game.id, me.id, async () => {
587
+ const read = await readLedgerForWrite(dir, game.id, me.id);
588
+ if (read === 'unreadable') {
589
+ throw new McpToolError(`The ledger for game ${game.id} exists but cannot be read: nothing was recorded, and the file was left as it is.`, {
590
+ hint: "Inspect or move aside the game's file under the server's data directory (relations/), then record again.",
591
+ });
592
+ }
593
+ const ledger = read ?? emptyLedger(game.id, me.id);
594
+ const c = change(ledger);
595
+ const rest = ledger.agreements.filter((a) => a.id !== c.agreement.id);
596
+ if (!(await writeLedger(dir, { ...ledger, agreements: [...rest, c.agreement] }))) {
597
+ throw new McpToolError(`The ledger for game ${game.id} could not be written: nothing was recorded.`, {
598
+ hint: "Check that the server's data directory is writable.",
599
+ });
600
+ }
601
+ return { ...c, recorded: await updateRecord(c.agreement, c.before, c.created, rest) };
602
+ });
603
+ return respond(undefined, ['compact'], () => ({
604
+ game: { id: game.id, turn },
605
+ recorded: created ? 'created' : 'updated',
606
+ agreement: agreementView(agreement, game, map, turn, 'full'),
607
+ playerRecord: recorded,
608
+ written: LEDGER_NOTE,
609
+ }));
610
+ });
611
+ }
@@ -0,0 +1,45 @@
1
+ // Resolve a territory or player named by a caller: an id, an exact name
2
+ // (case-insensitive), or a unique part of a name. Errors listing candidates show
3
+ // each name through `untrustedText` (names are other players' and map makers'
4
+ // words, and errors are not inside the untrusted envelope) and cap the list.
5
+ import { McpToolError } from '@chrischall/mcp-utils';
6
+ import { UNTRUSTED_LIST_MAX, untrustedList, untrustedText } from './common.js';
7
+ function pick(items, input, what) {
8
+ const raw = String(input).trim();
9
+ if (!raw)
10
+ throw new McpToolError(`Name a ${what} (an id or a name).`);
11
+ if (/^\d+$/.test(raw)) {
12
+ const byId = items.find((i) => i.id === Number(raw));
13
+ if (byId)
14
+ return byId;
15
+ }
16
+ const q = raw.toLowerCase();
17
+ const exact = items.filter((i) => i.name.toLowerCase() === q);
18
+ const hits = exact.length ? exact : items.filter((i) => i.name.toLowerCase().includes(q));
19
+ if (hits.length === 1)
20
+ return hits[0];
21
+ const label = (i) => `${untrustedText(i.name)} (${i.id})`;
22
+ if (hits.length === 0) {
23
+ throw new McpToolError(`No ${what} matches ${JSON.stringify(raw)}.`, {
24
+ hint: `Use the ${what}'s id, or part of its name as spelled in the game.`,
25
+ });
26
+ }
27
+ throw new McpToolError(`${JSON.stringify(raw)} matches ${hits.length} ${what === 'territory' ? 'territories' : `${what}${what.endsWith('s') ? 'es' : 's'}`}: ` +
28
+ `${untrustedList(hits, UNTRUSTED_LIST_MAX, label)}.`, { hint: `Pass the id of the one you mean.` });
29
+ }
30
+ export function resolveTerritory(map, input) {
31
+ return pick(map.territories, input, 'territory');
32
+ }
33
+ export function resolveBonus(map, input) {
34
+ return pick(map.bonuses, input, 'bonus');
35
+ }
36
+ /** A player by id or name; with no input, an error listing who to choose from. */
37
+ export function resolvePlayer(players, input) {
38
+ if (input === undefined || String(input).trim() === '') {
39
+ const list = untrustedList(players, UNTRUSTED_LIST_MAX, (p) => `${untrustedText(p.name)} (${p.id})`);
40
+ throw new McpToolError(`Say which player to analyze the board for: ${list || 'the game lists no players'}.`, {
41
+ hint: 'Pass `player` as a name or id — usually your own war.app name.',
42
+ });
43
+ }
44
+ return pick(players, input, 'player');
45
+ }