@chrischall/warapp-mcp 0.20.0 → 0.22.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.
@@ -0,0 +1,243 @@
1
+ import { bonusTerritories } from './bonuses.js';
2
+ import { armiesToTake } from './combat.js';
3
+ import { neighborsOf } from './graph.js';
4
+ /** The most territories listed (a huge map lists the ones nearest my land first). */
5
+ export const MAX_SITUATION_TERRITORIES = 400;
6
+ /** The most bonuses listed. */
7
+ export const MAX_SITUATION_BONUSES = 60;
8
+ /** The most earlier turns summarised (the newest). */
9
+ export const SITUATION_PAST_TURNS = 10;
10
+ const ownerOf = (t, me) => {
11
+ if (!t || t.owner.kind === 'unknown')
12
+ return 'fog';
13
+ if (t.owner.kind !== 'player')
14
+ return 'neutral';
15
+ return t.owner.playerId === me ? 'me' : t.owner.playerId;
16
+ };
17
+ /** The facts on this board (see the file header). */
18
+ export function situation(input) {
19
+ const { graph: g, board, me } = input;
20
+ const guard = input.guard === false ? 0 : 1;
21
+ const state = new Map(board.territories.map((t) => [t.territoryId, t]));
22
+ const owner = (id) => ownerOf(state.get(id), me);
23
+ const armiesOf = (id) => state.get(id)?.armies ?? null;
24
+ const mine = [...state.keys()].filter((id) => owner(id) === 'me').sort((a, b) => a - b);
25
+ const mineSet = new Set(mine);
26
+ const take = (n) => armiesToTake(n, input.rates);
27
+ // Hops from my land, through any territory.
28
+ const dist = new Map(mine.map((m) => [m, 0]));
29
+ let frontier = mine;
30
+ while (frontier.length) {
31
+ const next = [];
32
+ for (const t of frontier)
33
+ for (const n of neighborsOf(g, t))
34
+ if (!dist.has(n)) {
35
+ dist.set(n, dist.get(t) + 1);
36
+ next.push(n);
37
+ }
38
+ frontier = next;
39
+ }
40
+ const bonusesOf = new Map();
41
+ for (const b of g.map.bonuses)
42
+ for (const t of bonusTerritories(g, b.id))
43
+ bonusesOf.set(t, [...(bonusesOf.get(t) ?? []), b.id]);
44
+ // Every territory in view, plus every hidden one beside my land; nearest first.
45
+ const listed = [...g.territoryById.keys()]
46
+ .filter((id) => owner(id) !== 'fog' || neighborsOf(g, id).some((n) => mineSet.has(n)))
47
+ .sort((a, b) => (dist.get(a) ?? Infinity) - (dist.get(b) ?? Infinity) || a - b);
48
+ const territories = listed.slice(0, MAX_SITUATION_TERRITORIES).map((id) => {
49
+ const t = state.get(id);
50
+ const units = t?.specialUnits?.map((u) => ({ kind: u.kind, owner: u.playerId === me ? 'me' : u.playerId }));
51
+ return {
52
+ id,
53
+ name: g.territoryById.get(id)?.name ?? String(id),
54
+ owner: owner(id),
55
+ armies: armiesOf(id),
56
+ ...(units?.length ? { units } : {}),
57
+ distance: dist.get(id) ?? -1,
58
+ bonuses: bonusesOf.get(id) ?? [],
59
+ neighbors: [...neighborsOf(g, id)],
60
+ };
61
+ });
62
+ // Every positive bonus I touch, that is beside my land, or that another player visibly holds in full.
63
+ const bonuses = [];
64
+ for (const b of g.map.bonuses) {
65
+ if (b.value <= 0)
66
+ continue;
67
+ const members = bonusTerritories(g, b.id);
68
+ let mineN = 0;
69
+ let neutral = 0;
70
+ let fogged = 0;
71
+ const players = new Map();
72
+ for (const t of members) {
73
+ const o = owner(t);
74
+ if (o === 'me')
75
+ mineN++;
76
+ else if (o === 'neutral')
77
+ neutral++;
78
+ else if (o === 'fog')
79
+ fogged++;
80
+ else
81
+ players.set(o, (players.get(o) ?? 0) + 1);
82
+ }
83
+ const heldBy = mineN === members.length ? 'me' : players.size === 1 && [...players.values()][0] === members.length ? [...players.keys()][0] : null;
84
+ const near = members.some((t) => (dist.get(t) ?? Infinity) <= 1);
85
+ if (!near && heldBy === null)
86
+ continue;
87
+ const missing = members.filter((t) => owner(t) !== 'me');
88
+ const hidden = missing.some((t) => armiesOf(t) === null);
89
+ bonuses.push({
90
+ bonusId: b.id,
91
+ name: b.name,
92
+ value: b.value,
93
+ size: members.length,
94
+ mine: mineN,
95
+ neutral,
96
+ fogged,
97
+ players: [...players].sort((x, y) => x[0] - y[0]).map(([player, count]) => ({ player, count })),
98
+ heldBy,
99
+ missing,
100
+ armiesToFinish: hidden ? null : missing.reduce((n, t) => n + (take(armiesOf(t)) ?? Infinity), 0),
101
+ reachable: missing.filter((t) => neighborsOf(g, t).some((n) => mineSet.has(n))),
102
+ });
103
+ }
104
+ // Mine first, then the nearest to done (fewest missing), then the most valuable.
105
+ bonuses.sort((a, b) => Number(b.heldBy === 'me') - Number(a.heldBy === 'me') ||
106
+ a.missing.length - b.missing.length ||
107
+ b.value - a.value ||
108
+ a.bonusId - b.bonusId);
109
+ const opponents = [...input.opponents]
110
+ .filter((o) => o.playerId !== me && !input.friends?.has(o.playerId))
111
+ .sort((a, b) => a.playerId - b.playerId)
112
+ .map((o) => {
113
+ const theirs = [...state.keys()].filter((id) => owner(id) === o.playerId);
114
+ const besideMe = theirs
115
+ .filter((id) => neighborsOf(g, id).some((n) => mineSet.has(n)))
116
+ .map((id) => ({ territoryId: id, armies: armiesOf(id) ?? 0, borders: neighborsOf(g, id).filter((n) => mineSet.has(n)) }));
117
+ return {
118
+ player: o.playerId,
119
+ income: {
120
+ estimate: o.estimate,
121
+ ...(o.source !== undefined ? { source: o.source } : {}),
122
+ ...(o.visibleIncome !== undefined ? { visible: o.visibleIncome } : {}),
123
+ ...(o.tracked !== undefined ? { tracked: o.tracked } : {}),
124
+ ...(o.range !== undefined ? { range: o.range } : {}),
125
+ ...(o.coverage !== undefined ? { coverage: o.coverage } : {}),
126
+ },
127
+ ...(o.history?.length ? { history: o.history.map((h) => ({ turn: h.turn, observed: h.observed })) } : {}),
128
+ territoriesInView: theirs.length,
129
+ armiesInView: theirs.reduce((n, id) => n + (armiesOf(id) ?? 0), 0),
130
+ bonusesHeld: bonuses.filter((b) => b.heldBy === o.playerId).map((b) => ({ bonusId: b.bonusId, value: b.value })),
131
+ besideMe,
132
+ movableBesideMe: besideMe.reduce((n, s) => n + Math.max(0, s.armies - guard), 0),
133
+ };
134
+ });
135
+ let changes = null;
136
+ if (input.previousBoard) {
137
+ const prev = new Map(input.previousBoard.territories.map((t) => [t.territoryId, t]));
138
+ const was = (id) => ownerOf(prev.get(id), me);
139
+ const lost = [];
140
+ const gained = [];
141
+ const moved = [];
142
+ for (const id of [...new Set([...prev.keys(), ...state.keys()])].sort((a, b) => a - b)) {
143
+ const before = was(id);
144
+ const now = owner(id);
145
+ if (before === 'me' && now !== 'me')
146
+ lost.push({ territoryId: id, to: now });
147
+ else if (now === 'me' && before !== 'me')
148
+ gained.push({ territoryId: id, from: before });
149
+ else if (typeof now === 'number' && before === now) {
150
+ const a = prev.get(id)?.armies;
151
+ const b = armiesOf(id);
152
+ if (a !== null && a !== undefined && b !== null && a !== b)
153
+ moved.push({ territoryId: id, owner: now, was: a, now: b });
154
+ }
155
+ }
156
+ moved.sort((x, y) => Math.abs(y.now - y.was) - Math.abs(x.now - x.was) || x.territoryId - y.territoryId);
157
+ changes = { lost, gained, moved: moved.slice(0, MAX_SITUATION_BONUSES) };
158
+ }
159
+ const past = [...(input.pastBoards ?? [])]
160
+ .sort((a, b) => a.turn - b.turn)
161
+ .slice(-SITUATION_PAST_TURNS)
162
+ .map((p) => {
163
+ const at = new Map(p.board.territories.map((t) => [t.territoryId, t]));
164
+ const sides = new Map();
165
+ for (const t of p.board.territories) {
166
+ const o = ownerOf(t, me);
167
+ if (o === 'fog' || o === 'neutral')
168
+ continue;
169
+ const side = sides.get(o) ?? { territories: 0, armies: 0 };
170
+ side.territories++;
171
+ side.armies += t.armies ?? 0;
172
+ sides.set(o, side);
173
+ }
174
+ const held = (o) => g.map.bonuses
175
+ .filter((b) => b.value > 0 && bonusTerritories(g, b.id).every((t) => ownerOf(at.get(t), me) === o))
176
+ .map((b) => b.id);
177
+ return {
178
+ turn: p.turn,
179
+ sides: [...sides]
180
+ .sort((a, b) => (a[0] === 'me' ? -1 : b[0] === 'me' ? 1 : a[0] - b[0]))
181
+ .map(([o, v]) => ({ owner: o, ...v, bonusesHeld: held(o) })),
182
+ ...(p.orders
183
+ ? {
184
+ myOrders: {
185
+ deploys: p.orders.deploys.map((d) => ({ territoryId: d.territoryId, armies: d.armies })),
186
+ moves: p.orders.moves.map((m) => ({ from: m.from, to: m.to, armies: m.armies })),
187
+ },
188
+ }
189
+ : {}),
190
+ };
191
+ });
192
+ return {
193
+ me: {
194
+ income: input.myIncome,
195
+ incomeHistory: [...(input.incomeHistory ?? [])],
196
+ territories: mine.length,
197
+ armies: mine.reduce((n, id) => n + (armiesOf(id) ?? 0), 0),
198
+ bonusesHeld: bonuses.filter((b) => b.heldBy === 'me').map((b) => ({ bonusId: b.bonusId, value: b.value })),
199
+ },
200
+ territories,
201
+ territoriesOmitted: Math.max(0, listed.length - MAX_SITUATION_TERRITORIES),
202
+ bonuses: bonuses.slice(0, MAX_SITUATION_BONUSES),
203
+ bonusesOmitted: Math.max(0, bonuses.length - MAX_SITUATION_BONUSES),
204
+ opponents,
205
+ changes,
206
+ past,
207
+ };
208
+ }
209
+ /** The parts of {@link Situation} a caller can ask for by name. */
210
+ export const FACT_PARTS = ['me', 'territories', 'bonuses', 'opponents', 'changes', 'past'];
211
+ /** What each part holds, for telling the caller what it can ask for. */
212
+ export const FACTS_AVAILABLE = {
213
+ me: 'my income and its history, land, armies and bonuses held',
214
+ territories: 'every territory in view and each hidden one beside my land, nearest first: owner, armies, special units, bonuses, neighbours',
215
+ bonuses: 'each bonus that matters: who holds how much of it, what finishing it costs, the members in reach',
216
+ opponents: "each opponent's income estimate with how it was read (source, visible, tracked, range, coverage, per-turn deploys), its bonuses and its stacks beside me",
217
+ changes: 'what changed since last turn: territories lost and gained, stacks that grew or shrank',
218
+ past: 'each of the last 10 turns kept: every side in view, its bonuses, my orders',
219
+ };
220
+ /** Only the parts asked for (the omitted counts go with their part). */
221
+ export function pickFacts(s, parts) {
222
+ const want = new Set(parts);
223
+ return {
224
+ ...(want.has('me') ? { me: s.me } : {}),
225
+ ...(want.has('territories') ? { territories: s.territories, territoriesOmitted: s.territoriesOmitted } : {}),
226
+ ...(want.has('bonuses') ? { bonuses: s.bonuses, bonusesOmitted: s.bonusesOmitted } : {}),
227
+ ...(want.has('opponents') ? { opponents: s.opponents } : {}),
228
+ ...(want.has('changes') ? { changes: s.changes } : {}),
229
+ ...(want.has('past') ? { past: s.past } : {}),
230
+ };
231
+ }
232
+ /** The one line every plan carries: what more the caller can ask warapp_plan_turn for. */
233
+ export const MORE_ON_REQUEST = 'Ask for more when you want to weigh the plan or build your own: strategy: true adds ranked captures and holds and the plan ' +
234
+ 'beside expand/defend alternatives, each stress-tested; facts: ["me","territories","bonuses","opponents","changes","past"] ' +
235
+ '(any of them) adds the raw game state behind them. Test any orders with warapp_check_plan.';
236
+ /** What to do with the facts: the tools that let the model test and act on its own plan. */
237
+ export const OWN_PLAN_STEPS = [
238
+ 'The plan, options and alternatives are inputs to your judgement, not the answer; ask warapp_plan_turn for the facts your decision needs (facts: me, territories, bonuses, opponents, changes, past).',
239
+ 'Write your own deploys and moves (any mix of the options, the alternatives or neither).',
240
+ 'Test them with warapp_check_plan (every opponent\'s replies, both move orders, one turn ahead); change and test again as needed.',
241
+ 'Look deeper when it matters: warapp_turn_history (what happened turn by turn), warapp_track_opponents and warapp_profile_opponents (how each opponent plays), warapp_plan_route (paths), warapp_get_map (the whole map), warapp_strategy (notes for this game), warapp_get_chat.',
242
+ 'Submit with warapp_submit_turn; when your orders differ from the plan, pass override_reason so the decision log keeps why.',
243
+ ];
@@ -10,6 +10,11 @@
10
10
  // attack deploy on one stack next to a territory I hold (or will hold after my own
11
11
  // orders) and attack it with everything that stack can move, its commander too;
12
12
  // reinforce deploy on a territory my plan attacks and sit still;
13
+ // gather (#593 5c) deploy on a territory my plan attacks and move every stack of its own
14
+ // beside it in first (all each can move, its commander left behind): the bait a
15
+ // lightly held territory beside a big stack is. Tried when one of those stacks can
16
+ // move, with it moving first only and never when I am known to move first, as a dodge
17
+ // is (moving second, its stacks strike what I took: the attack reply covers that);
13
18
  // all-attack every stack with a target attacks at once, the deploy on the largest: once
14
19
  // spread (each stack takes the most valuable target no other has taken) and once
15
20
  // concentrated (each takes its most valuable target). Tried when two or more
@@ -249,6 +254,15 @@ export function stressPlan(input) {
249
254
  const dep = deployOn(opp, s);
250
255
  if (myTargets.has(s) && dep > 0)
251
256
  candidates.push({ player: opp.id, kind: 'reinforce', deployTo: s, deploy: dep, orders: [] });
257
+ // #593 5c: its stacks beside the target move in first, largest first.
258
+ if (myTargets.has(s) && input.firstMover !== 'me') {
259
+ const beside = neighborsOf(graph, s)
260
+ .filter((n) => start.get(n)?.owner === opp.id && (start.get(n)?.armies ?? 0) > guard)
261
+ .sort((a, b) => (start.get(b)?.armies ?? 0) - (start.get(a)?.armies ?? 0) || a - b);
262
+ if (beside.length) {
263
+ candidates.push({ player: opp.id, kind: 'gather', deployTo: s, deploy: dep, orders: beside.map((n) => ({ from: n, to: s, armies: allOf(n, 0) })) });
264
+ }
265
+ }
252
266
  }
253
267
  if (reach.size >= 2) {
254
268
  const bySize = [...reach.keys()].sort((a, b) => (start.get(b)?.armies ?? 0) - (start.get(a)?.armies ?? 0) || a - b);
@@ -412,6 +426,11 @@ export function stressPlan(input) {
412
426
  deployTo: c.deployTo,
413
427
  deploy: c.deploy,
414
428
  ...(single ? { from: c.orders[0].from, to: c.orders[0].to, armies: sent ?? 0 } : {}),
429
+ ...(c.kind === 'gather'
430
+ ? {
431
+ movedIn: c.orders.map((o, i) => ({ from: o.from, armies: r.log.find((e) => e.player === c.player && e.index === i)?.sent ?? 0 })),
432
+ }
433
+ : {}),
415
434
  ...(c.kind === 'all-attack' || c.kind === 'joint' ? { attacks: sides.flatMap((x) => x.orders.map((o) => ({ from: o.from, to: o.to }))) } : {}),
416
435
  ...(c.partner ? { partner: c.partner.player, partnerDeployTo: c.partner.deployTo, partnerDeploy: c.partner.deploy } : {}),
417
436
  ...(run.firstOpponent !== undefined ? { firstOpponent: run.firstOpponent } : {}),
@@ -433,7 +452,7 @@ export function stressPlan(input) {
433
452
  /** Two outcomes are the same when they cost me the same things. */
434
453
  const signature = (x) => JSON.stringify({ ...x, firstMover: undefined, firstOpponent: undefined });
435
454
  const runsFor = (c) => {
436
- const firsts = c.kind === 'dodge' ? ['opponent'] : input.firstMover !== undefined ? [input.firstMover] : ['me', 'opponent'];
455
+ const firsts = c.kind === 'dodge' || c.kind === 'gather' ? ['opponent'] : input.firstMover !== undefined ? [input.firstMover] : ['me', 'opponent'];
437
456
  if (!c.partner)
438
457
  return firsts.map((f) => ({ firstMover: f, moveOrder: f === 'me' ? [me, c.player] : [c.player, me] }));
439
458
  const pair = [c.player, c.partner.player];