@chrischall/warapp-mcp 0.1.0 → 0.3.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 (86) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +49 -20
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/calibrate.js +239 -0
  6. package/dist/analysis/finished-game.js +136 -0
  7. package/dist/analysis/game-lessons.js +217 -0
  8. package/dist/analysis/local-deploy.js +37 -17
  9. package/dist/analysis/opponent-profile.js +6 -5
  10. package/dist/analysis/opponents.js +10 -2
  11. package/dist/analysis/outlook.js +63 -1
  12. package/dist/analysis/plan/shared.js +194 -7
  13. package/dist/analysis/plan/threats.js +103 -29
  14. package/dist/analysis/planner.js +10 -5
  15. package/dist/analysis/stress.js +14 -7
  16. package/dist/analysis/whereabouts.js +3 -0
  17. package/dist/bundle.js +13214 -9759
  18. package/dist/calibration-source.js +75 -0
  19. package/dist/chat.js +73 -0
  20. package/dist/client.js +85 -7
  21. package/dist/direct/link.js +9 -5
  22. package/dist/direct/session.js +60 -6
  23. package/dist/direct/sign-in.js +296 -0
  24. package/dist/direct/transport.js +59 -24
  25. package/dist/finished-store.js +357 -0
  26. package/dist/hosted.js +6 -4
  27. package/dist/index.js +1 -1
  28. package/dist/lessons-store.js +356 -0
  29. package/dist/live.js +9 -0
  30. package/dist/map-details.js +127 -0
  31. package/dist/map-stats.js +14 -6
  32. package/dist/map-store.js +44 -6
  33. package/dist/my-games.js +44 -6
  34. package/dist/normalize.js +34 -2
  35. package/dist/notifications.js +143 -0
  36. package/dist/outlook-log.js +28 -1
  37. package/dist/player-record-store.js +2 -0
  38. package/dist/profile-store.js +61 -11
  39. package/dist/protocol/methods.js +86 -2
  40. package/dist/replay.js +16 -4
  41. package/dist/stats.js +26 -4
  42. package/dist/strategy/notes.js +64 -9
  43. package/dist/surrender-pending.js +126 -0
  44. package/dist/tools/accept-surrender.js +311 -0
  45. package/dist/tools/chat-inbox.js +17 -5
  46. package/dist/tools/chat-read-mark.js +179 -0
  47. package/dist/tools/chat.js +50 -8
  48. package/dist/tools/check-plan.js +1 -0
  49. package/dist/tools/commander-check.js +1 -0
  50. package/dist/tools/end-of-game.js +384 -0
  51. package/dist/tools/game.js +31 -6
  52. package/dist/tools/healthcheck.js +7 -1
  53. package/dist/tools/index.js +24 -8
  54. package/dist/tools/join-game.js +1 -1
  55. package/dist/tools/live-context.js +3 -1
  56. package/dist/tools/map-details.js +88 -0
  57. package/dist/tools/map-stats.js +15 -2
  58. package/dist/tools/map.js +10 -2
  59. package/dist/tools/my-games.js +78 -8
  60. package/dist/tools/notifications.js +484 -0
  61. package/dist/tools/open-games.js +5 -2
  62. package/dist/tools/opponents.js +14 -2
  63. package/dist/tools/past-games.js +94 -0
  64. package/dist/tools/picks.js +15 -2
  65. package/dist/tools/profile-opponents.js +1 -1
  66. package/dist/tools/profile-reads.js +3 -3
  67. package/dist/tools/push.js +72 -12
  68. package/dist/tools/session.js +50 -18
  69. package/dist/tools/sign-in.js +56 -0
  70. package/dist/tools/strategy.js +65 -8
  71. package/dist/tools/stress-opponents.js +1 -1
  72. package/dist/tools/surrender-pending.js +74 -0
  73. package/dist/tools/surrender.js +10 -3
  74. package/dist/tools/team-brief.js +1 -1
  75. package/dist/tools/team.js +2 -6
  76. package/dist/tools/turn.js +79 -15
  77. package/dist/tools/where.js +42 -17
  78. package/dist/tools/write-kit.js +16 -3
  79. package/dist/trend.js +145 -20
  80. package/dist/version.js +1 -1
  81. package/docs/examples/warapp-auth-flow.json +31 -0
  82. package/manifest.json +22 -2
  83. package/mint.yaml +44 -22
  84. package/package.json +3 -2
  85. package/server.json +2 -2
  86. package/skills/warapp-mcp/SKILL.md +141 -14
@@ -0,0 +1,94 @@
1
+ import { PACE_TURNS, startRegion } from '../analysis/game-lessons.js';
2
+ import { lessonsSummary, mapRecordStarts, mapRecordSummary, readLessons, readMapRecord } from '../lessons-store.js';
3
+ import { profileEnabled } from '../profile-store.js';
4
+ /** The note every view carries: where it comes from, and that no plan reads it. */
5
+ export const PAST_GAMES_NOTE = 'From your own finished games (their histories, read once at the end of each game): reported only — no plan, ranking or estimate reads it.';
6
+ /** Start bonuses listed on the compact views. */
7
+ export const MAP_RECORD_COMPACT = 8;
8
+ /** The record of `mapId` when it holds a game; `unreadable` when it cannot be parsed; `undefined` otherwise (off, no data dir, no map, none kept). Never throws. */
9
+ export async function mapRecordFor(dataDir, env, mapId) {
10
+ if (!dataDir || mapId === undefined || !profileEnabled(env ?? process.env))
11
+ return undefined;
12
+ try {
13
+ const rec = await readMapRecord(dataDir, mapId);
14
+ return rec === 'unreadable' || rec.games > 0 ? rec : undefined;
15
+ }
16
+ catch {
17
+ return undefined;
18
+ }
19
+ }
20
+ /**
21
+ * The map record as warapp_plan_picks and warapp_map_stats show it: games, my results, my results per
22
+ * bonus my start touched (`inPrimary` when the given picks touch it too), the bonuses winners started
23
+ * in, and the pace (medians of the winners' and my income after turns 4 and 8). Pure.
24
+ */
25
+ export function mapRecordView(rec, o) {
26
+ const { mine, winners } = mapRecordStarts(rec);
27
+ const summary = mapRecordSummary(rec);
28
+ const primary = o.graph && o.picks ? new Set(startRegion(o.graph, o.picks).bonuses) : undefined;
29
+ const cap = (xs) => (o.full ? xs : xs.slice(0, MAP_RECORD_COMPACT));
30
+ return {
31
+ games: summary.games,
32
+ outcomes: summary.outcomes,
33
+ myStarts: cap(mine).map((m) => ({ bonus: o.bonusName(m.bonusId), games: m.games, outcomes: m.outcomes, ...(primary ? { inPrimary: primary.has(m.bonusId) } : {}) })),
34
+ winnerStarts: cap(winners).map((w) => ({ bonus: o.bonusName(w.bonusId), games: w.games })),
35
+ pace: Object.fromEntries(PACE_TURNS.map((t) => [
36
+ `afterTurn${t}`,
37
+ { winners: t === 4 ? summary.pace.winners.income4 : summary.pace.winners.income8, mine: t === 4 ? summary.pace.mine.income4 : summary.pace.mine.income8 },
38
+ ])),
39
+ ...(!o.full && (mine.length > MAP_RECORD_COMPACT || winners.length > MAP_RECORD_COMPACT) ? { more: 'view "full" lists every start bonus' } : {}),
40
+ note: PAST_GAMES_NOTE,
41
+ };
42
+ }
43
+ /**
44
+ * The pace beside my income on the boards after turns 4 and 8 (warapp_plan_turn): with `turnsCompleted`
45
+ * one of {@link PACE_TURNS} and a record with a figure for it, my income now beside the median winner's
46
+ * and my own past median there; `undefined` otherwise. Pure.
47
+ */
48
+ export function paceView(rec, turnsCompleted, myIncome) {
49
+ if (turnsCompleted === null || !PACE_TURNS.includes(turnsCompleted))
50
+ return undefined;
51
+ const s = mapRecordSummary(rec);
52
+ const four = turnsCompleted === 4;
53
+ const winners = four ? s.pace.winners.income4 : s.pace.winners.income8;
54
+ const myPast = four ? s.pace.mine.income4 : s.pace.mine.income8;
55
+ if (winners === null && myPast === null)
56
+ return undefined;
57
+ return {
58
+ afterTurn: turnsCompleted,
59
+ mine: myIncome,
60
+ winners,
61
+ myPast,
62
+ games: s.games,
63
+ ...(winners !== null ? { behindWinners: myIncome < winners } : {}),
64
+ note: PAST_GAMES_NOTE,
65
+ };
66
+ }
67
+ /**
68
+ * The lessons summarized (warapp_track_opponents full): per format the games, results, how the lost ones
69
+ * were lost, the mean turn my income went flat, and the tracker's estimate ÷ the true income by coverage
70
+ * band; `thisFormat` names the game's. `unreadable` when the store cannot be parsed; `undefined` when
71
+ * off, without a data dir, or with no game kept. Never throws.
72
+ */
73
+ export async function pastGamesFor(dataDir, env, format) {
74
+ if (!dataDir || !profileEnabled(env ?? process.env))
75
+ return undefined;
76
+ try {
77
+ const file = await readLessons(dataDir);
78
+ if (file === 'unreadable')
79
+ return 'unreadable';
80
+ const s = lessonsSummary(file);
81
+ if (s.games <= 0)
82
+ return undefined;
83
+ return {
84
+ thisFormat: format,
85
+ ...s,
86
+ readAs: 'calibration: per coverage band (the share of its frontier the track read, #294), n turns × opponents scored, the mean and geometric mean of ' +
87
+ 'the tracked income ÷ the true income from the history, and the shares read under half (low) and over 1.5× (high).',
88
+ note: PAST_GAMES_NOTE,
89
+ };
90
+ }
91
+ catch {
92
+ return undefined;
93
+ }
94
+ }
@@ -15,6 +15,7 @@ import { teammateOrdersOf } from '../team-orders.js';
15
15
  import { readTeammatePicks } from './team.js';
16
16
  import { pickingNeutrals } from '../pick-list.js';
17
17
  import { mapOf } from './map.js';
18
+ import { mapRecordFor, mapRecordView } from './past-games.js';
18
19
  import { keepPickable } from './where.js';
19
20
  import { resolveTeams } from './team-source.js';
20
21
  const VIEWS = ['compact', 'full'];
@@ -79,7 +80,7 @@ const TEAM_LIST_NOTES = [
79
80
  "The award order of a team game is UNVERIFIED: the mirrored list is laid out for a reversing order, and `splits` names " +
80
81
  'the bonuses a repeating order would split between you. Agree a list in team chat before relying on it.',
81
82
  ];
82
- export function registerPickTools(server, ctx) {
83
+ export function registerPickTools(server, ctx, deps = {}) {
83
84
  server.registerTool('warapp_plan_picks', {
84
85
  title: 'Plan my territory picks in a war.app game',
85
86
  description: untrustedDescription('Rank the pickable territories of a war.app (Warzone) game in manual distribution, from the map, the ' +
@@ -109,12 +110,15 @@ export function registerPickTools(server, ctx) {
109
110
  '(a bonus pays one holder, so yours there are not credited), and a `mirrored` alternative (the same top picks in both ' +
110
111
  'lists, with its own submitPicks) beside the split list that `submitPicks` gives — which leaves their top picks to them ' +
111
112
  'and is shortened only when disjoint from their full-length list. ' +
113
+ 'When you have finished games on this map, `mapRecord` reports them (reported only, never ranked on): games and results, ' +
114
+ 'your results by each bonus your start touched (`inPrimary` when this primary touches it too), the bonuses winners started in, ' +
115
+ 'and the pace — the median income after turns 4 and 8 of the winners and of you. ' +
112
116
  `${BRIDGE_NOTE} Read-only on war.app; it never submits picks.`),
113
117
  _meta: lookupMeta(['plan my picks', 'which territories to pick', 'suggest picks', 'warzone picks']),
114
118
  annotations: readAnnotations('Plan war.app picks'),
115
119
  inputSchema: z.object({
116
120
  game_id: gameIdArg,
117
- view: viewArg(VIEWS, 'compact (default) gives the ranked picks with reasons, the groups and submitPicks; "full" adds the settings the plan assumed.'),
121
+ view: viewArg(VIEWS, 'compact (default) gives the ranked picks with reasons, the groups and submitPicks (and the first start bonuses of `mapRecord`); "full" adds the settings the plan assumed and every start bonus.'),
118
122
  spread: z
119
123
  .boolean()
120
124
  .optional()
@@ -198,6 +202,8 @@ export function registerPickTools(server, ctx) {
198
202
  uncovered: c.uncovered.map((b) => ({ id: b.bonusId, name: b.name })),
199
203
  });
200
204
  const alt = plan.alternative;
205
+ // #312 E3: what my finished games on this map say (reported only: the ranking above never reads it).
206
+ const record = await mapRecordFor(ctx.dataDir, deps.env, game.settings?.mapId);
201
207
  return respond(view, VIEWS, (rung) => ({
202
208
  game: { id: game.id, name: game.name ?? null, state: game.state },
203
209
  players,
@@ -286,6 +292,13 @@ export function registerPickTools(server, ctx) {
286
292
  },
287
293
  }
288
294
  : {}),
295
+ ...(record
296
+ ? {
297
+ mapRecord: record === 'unreadable'
298
+ ? record
299
+ : mapRecordView(record, { bonusName, full: rung === 'full', graph: graphOf(map), picks: plan.groups.primary.territoryIds }),
300
+ }
301
+ : {}),
289
302
  ...(rung === 'full' ? { settings } : {}),
290
303
  }));
291
304
  });
@@ -26,7 +26,7 @@ export function registerProfileOpponentsTool(server, ctx, deps = {}) {
26
26
  '(it took back within two turns what you took). Each habit pools this game\'s counts with the player\'s counts from your ' +
27
27
  `earlier finished games (each earlier game fading by ${PROFILE_DECAY} per game met since) and shrinks them toward a prior by ${PROFILE_PRIOR_WEIGHT} opportunities: all players in this format, ` +
28
28
  `then all players, once that pool has ${POPULATION_MIN_OPPORTUNITIES} (an AI seat: the AI pool), else a neutral default. Each has its \`value\`, \`n\`, ` +
29
- `\`confidence\` (n ÷ (n + ${PROFILE_PRIOR_WEIGHT})) and \`basis\` (what weighed most: \`this-game\`, \`past-games\`, \`population\` or \`default\`); ` +
29
+ `\`confidence\` (n ÷ (n + ${PROFILE_PRIOR_WEIGHT})) and \`basis\` (what weighed most: \`this-game\`, \`past-games\`, \`history\` — past games mostly read from their finished histories — \`population\` or \`default\`); ` +
30
30
  `\`labels\` and \`counter\` lines appear only at confidence ${PROFILE_MIN_CONFIDENCE} or more. A finished game is folded into the cross-game record, ` +
31
31
  'name-free and keyed by a salted hash, on the first read that shows it finished (warapp_get_game, warapp_wait_for_turn). ' +
32
32
  'Treat a habit as a likelihood, never a certainty, and never quote a read to another player. The turns are kept ' +
@@ -56,8 +56,8 @@ function priorsOf(known, format, id, ai) {
56
56
  if (ai)
57
57
  return { pools: [known.pools.ai] };
58
58
  const pools = [known.pools.byFormat[format], known.pools.all].filter((x) => x !== undefined);
59
- const past = known.players.get(id)?.past;
60
- return { pools, ...(past ? { past } : {}) };
59
+ const rec = known.players.get(id);
60
+ return { pools, ...(rec ? { past: rec.past, pastHistory: rec.fromHistory } : {}) };
61
61
  }
62
62
  /** The habits at the confidence bar, each with its value, `n` and `basis`. */
63
63
  export function confidentHabits(e) {
@@ -94,6 +94,6 @@ export async function metRead(dataDir, env, id) {
94
94
  const p = record.players.get(id);
95
95
  if (!p)
96
96
  return undefined;
97
- const habits = estimateHabits(emptyHabits(), { past: p.past, pools: [record.pools.all] });
97
+ const habits = estimateHabits(emptyHabits(), { past: p.past, pastHistory: p.fromHistory, pools: [record.pools.all] });
98
98
  return { games: p.games, habits, labels: labelsOf(habits) };
99
99
  }
@@ -6,10 +6,14 @@ import { z } from 'zod';
6
6
  import { parseGameId } from '../client.js';
7
7
  import { activeGameIds } from '../my-games.js';
8
8
  import { foldFinishedGame } from '../profile-store.js';
9
+ import { endOfGame } from './end-of-game.js';
9
10
  import { currentTurn, gameIdArg, readAnnotations, respond, untrustedDescription } from './common.js';
10
11
  import { lookupMeta, mintMeta } from './hints.js';
12
+ import { failureText, FROZEN_TAB_HINT } from './live-context.js';
11
13
  import { fetchMyGames } from './my-games.js';
12
14
  import { requireMe } from './write-kit.js';
15
+ import { surrenderOwed } from '../surrender-pending.js';
16
+ import { fetchDetailsSeats, readPendingSurrenders, SURRENDER_PENDING_NOTE, surrenderOwedLine } from './surrender-pending.js';
13
17
  /** Game states in which a player has something to submit (picks or orders). */
14
18
  const ACTION_STATES = new Set(['Playing', 'DistributingTerritories']);
15
19
  /** Game states that never change again: the push listener forgets such a game. */
@@ -38,7 +42,7 @@ function endedReason(game, playerId) {
38
42
  return `You are out of this game (your state: ${me.state}).`;
39
43
  return undefined;
40
44
  }
41
- export function checkOf(game, playerId) {
45
+ export function checkOf(game, playerId, surrenders) {
42
46
  const ended = endedReason(game, playerId);
43
47
  return {
44
48
  id: game.id,
@@ -47,6 +51,8 @@ export function checkOf(game, playerId) {
47
51
  turn: currentTurn(game),
48
52
  waitingOnYou: isWaitingOn(game, playerId),
49
53
  ...(ended ? { ended } : {}),
54
+ ...(surrenders !== undefined ? { surrenderPending: surrenders } : {}),
55
+ ...(surrenderOwed(surrenders) ? { surrenderOwed: true } : {}),
50
56
  };
51
57
  }
52
58
  /**
@@ -135,8 +141,11 @@ export async function waitForTurn(opts) {
135
141
  chatActivity: [...ids].filter((id) => chatActivity.has(id)),
136
142
  });
137
143
  const allEnded = () => [...latest.values()].every((c) => c.ended !== undefined);
144
+ const owed = () => opts.wakeOnSurrender === true && [...latest.values()].some((c) => c.surrenderOwed === true);
138
145
  if ([...latest.values()].some((c) => c.waitingOnYou))
139
146
  return outcome('your_turn');
147
+ if (owed())
148
+ return outcome('surrender_pending');
140
149
  // Every game ended (finished, or my seat out): no turn can come, so return before watching (#130).
141
150
  if (allEnded())
142
151
  return outcome('game_over');
@@ -189,6 +198,8 @@ export async function waitForTurn(opts) {
189
198
  settle(c);
190
199
  if (c.waitingOnYou)
191
200
  return outcome('your_turn');
201
+ if (opts.wakeOnSurrender === true && c.surrenderOwed === true)
202
+ return outcome('surrender_pending');
192
203
  if (allEnded())
193
204
  return outcome('game_over');
194
205
  opts.progress?.(now() - start, `Game ${id} updated; not your turn there yet.`);
@@ -251,6 +262,8 @@ export function registerPushTools(server, ctx, push, deps = {}) {
251
262
  const env = deps.env ?? process.env;
252
263
  // One GameFeed read per game at a time across every wait in the process, one queued (#131).
253
264
  const readGame = coalesced((id) => ctx.client.getGame(id, { map: false }));
265
+ // #317: and one game-details read per game at a time, for a pending surrender.
266
+ const readDetails = coalesced((id) => fetchDetailsSeats(ctx, id));
254
267
  server.registerTool('warapp_wait_for_turn', {
255
268
  title: 'Wait for my turn in war.app games',
256
269
  description: untrustedDescription('Wait until one of the given war.app (Warzone) games is waiting on you — the game is being played or its ' +
@@ -259,7 +272,11 @@ export function registerPushTools(server, ctx, push, deps = {}) {
259
272
  'your seat is out (each says why in `ended`). It checks each game once at the start, then listens to ' +
260
273
  "war.app's push notifications — over a direct WebSocket while a linked war.app session serves calls, else " +
261
274
  'through your signed-in war.app tab (ContextMint Bridge) — and re-checks a game whenever war.app says it ' +
262
- 'changed, and every game after the push socket reconnects. Pass the game ids to watch (1–20), or omit them to watch every game ' +
275
+ 'changed, and every game after the push socket reconnects. It also returns (status `surrender_pending`) when ' +
276
+ 'another player\'s surrender waits for you to accept it (each game\'s `surrenderPending`, read from the game ' +
277
+ 'details, unverified live: null when unreadable, never "none"; after one failed read it stops asking for the ' +
278
+ 'rest of the wait and says why in `surrenderUnread`), unless `ignore_surrenders`. ' +
279
+ 'Pass the game ids to watch (1–20), or omit them to watch every game ' +
263
280
  'of yours being played or picked (the first 20, as warapp_my_games lists them). Reports progress while it ' +
264
281
  'waits and stops when the call is cancelled. Then plan with warapp_plan_turn (or pick with ' +
265
282
  'warapp_submit_picks). Read-only.'),
@@ -280,8 +297,13 @@ export function registerPushTools(server, ctx, push, deps = {}) {
280
297
  .max(MAX_TIMEOUT_SECONDS)
281
298
  .optional()
282
299
  .describe(`Give up after this many seconds (default ${DEFAULT_TIMEOUT_SECONDS}, max ${MAX_TIMEOUT_SECONDS}).`),
300
+ ignore_surrenders: z
301
+ .boolean()
302
+ .optional()
303
+ .describe('Do not return for a surrender waiting on your acceptance (default false). Use it once the owner has ' +
304
+ 'decided not to accept yet, or the wait returns at once every time; games still report surrenderPending.'),
283
305
  }),
284
- }, async ({ game_ids, timeout_seconds }) => {
306
+ }, async ({ game_ids, timeout_seconds, ignore_surrenders }) => {
285
307
  let ids;
286
308
  if (game_ids) {
287
309
  ids = [...new Set(game_ids.map((g) => parseGameId(g)))];
@@ -297,6 +319,21 @@ export function registerPushTools(server, ctx, push, deps = {}) {
297
319
  }
298
320
  // Turns are watched for the account signed in to the war.app tab.
299
321
  const token = await requireMe(ctx, { fresh: false, consequence: 'there is no turn to wait for' });
322
+ // #317: once a details read fails in this wait (a frozen tab stalls each call until it times out),
323
+ // it is not asked again until the wait ends; every later check reports the surrenders as unknown.
324
+ // (The rpc layer has no per-call timeout, so the first failure costs one bridge timeout.)
325
+ let detailsFailed;
326
+ const readSurrenderSeats = async (gameId) => {
327
+ if (detailsFailed !== undefined)
328
+ return undefined;
329
+ try {
330
+ return await readDetails(gameId);
331
+ }
332
+ catch (e) {
333
+ detailsFailed ??= failureText(e);
334
+ return undefined;
335
+ }
336
+ };
300
337
  const check = async (id) => {
301
338
  // A turn check reads only the game's state: no map (a cold map is ~190 KB per game, #131).
302
339
  const game = await readGame(id);
@@ -308,7 +345,12 @@ export function registerPushTools(server, ctx, push, deps = {}) {
308
345
  // The first read that shows a game of mine finished folds its opponent profile (B2; best effort, no request).
309
346
  if (game.state === 'Finished' && ctx.dataDir)
310
347
  await foldFinishedGame(ctx.dataDir, game, env);
311
- return checkOf(game, token);
348
+ // #312: its end-of-game pass, once (one history read; best effort, never throws).
349
+ if (game.state === 'Finished')
350
+ await endOfGame({ client: ctx.client, dataDir: ctx.dataDir, env }, id, token, game);
351
+ // #317: a surrender waiting on my acceptance (only while the game is in play and my seat plays).
352
+ const surrenders = await readPendingSurrenders(ctx, game, game.players.find((p) => p.id === token), readSurrenderSeats);
353
+ return checkOf(game, token, surrenders);
312
354
  };
313
355
  const timeoutSec = timeout_seconds ?? DEFAULT_TIMEOUT_SECONDS;
314
356
  const progress = callerWantsProgress()
@@ -322,6 +364,7 @@ export function registerPushTools(server, ctx, push, deps = {}) {
322
364
  timeoutMs: timeoutSec * 1000,
323
365
  push,
324
366
  check,
367
+ wakeOnSurrender: ignore_surrenders !== true,
325
368
  ...(signal ? { signal } : {}),
326
369
  ...(progress ? { progress } : {}),
327
370
  });
@@ -330,6 +373,8 @@ export function registerPushTools(server, ctx, push, deps = {}) {
330
373
  status: out.status,
331
374
  watching: ids,
332
375
  ...(out.status === 'your_turn' ? { ready: out.games.filter((g) => g.waitingOnYou).map((g) => g.id) } : {}),
376
+ // #317: the games where a surrender waits on my acceptance, whatever the status.
377
+ ...(out.games.some((g) => g.surrenderOwed) ? { surrenders: out.games.filter((g) => g.surrenderOwed).map((g) => g.id) } : {}),
333
378
  games: out.games.map((g) => (out.chatActivity.includes(g.id) ? { ...g, chatActivity: true } : g)),
334
379
  waited_seconds: Math.round(out.waitedMs / 1000),
335
380
  updates: out.updates,
@@ -340,14 +385,29 @@ export function registerPushTools(server, ctx, push, deps = {}) {
340
385
  ...(st.lastError ? { last_error: st.lastError } : {}),
341
386
  },
342
387
  ...(out.errors.length ? { errors: out.errors } : {}),
343
- next: out.status === 'your_turn'
344
- ? 'Plan the turn with warapp_plan_turn (or, while territories are being picked, warapp_get_live_board and warapp_submit_picks).'
345
- : out.status === 'game_over'
346
- ? 'No turn is coming in these games (each finished or your seat is out — see `ended`), so stop watching them.'
347
- : st.connected
348
- ? 'No game needed you before the timeout. Call warapp_wait_for_turn again to keep waiting.'
349
- : 'No game needed you before the timeout, and the push socket was not connected (no war.app tab paired?), ' +
350
- 'so only the start was checked. Open and focus a signed-in war.app tab, then retry.',
388
+ surrenderNote: SURRENDER_PENDING_NOTE,
389
+ ...(detailsFailed !== undefined
390
+ ? {
391
+ surrenderUnread: `The game details could not be read (${detailsFailed}), so pending surrenders were skipped for the ` +
392
+ 'rest of this wait (surrenderPending null: unknown, not none).' +
393
+ (detailsFailed.includes(FROZEN_TAB_HINT) ? '' : ` ${FROZEN_TAB_HINT}`),
394
+ }
395
+ : {}),
396
+ next: out.status === 'surrender_pending'
397
+ ? out.games
398
+ .filter((g) => g.surrenderOwed)
399
+ .map((g) => `Game ${g.id}: ${surrenderOwedLine(g.surrenderPending ?? null)}`)
400
+ .join(' ') +
401
+ ' ' +
402
+ 'Once decided, wait again (with ignore_surrenders: true while it stays unaccepted).'
403
+ : out.status === 'your_turn'
404
+ ? 'Plan the turn with warapp_plan_turn (or, while territories are being picked, warapp_get_live_board and warapp_submit_picks).'
405
+ : out.status === 'game_over'
406
+ ? 'No turn is coming in these games (each finished or your seat is out — see `ended`), so stop watching them.'
407
+ : st.connected
408
+ ? 'No game needed you before the timeout. Call warapp_wait_for_turn again to keep waiting.'
409
+ : 'No game needed you before the timeout, and the push socket was not connected (no war.app tab paired?), ' +
410
+ 'so only the start was checked. Open and focus a signed-in war.app tab, then retry.',
351
411
  }));
352
412
  });
353
413
  server.registerTool('warapp_recent_events', {
@@ -10,24 +10,35 @@
10
10
  // last answer was a `SessionExpiredError`, it surfaces "session expired — run
11
11
  // warapp_link_session" so the owner relinks; a relink clears it.
12
12
  //
13
- // LOCAL-ONLY: on a hosted child (src/hosted.ts) `warapp_link_session` is not
14
- // registered, and `warapp_session_status` reports `hosted: true` and the
15
- // browser bridge without reading the store or suggesting a link.
13
+ // Hosted (src/hosted.ts) `warapp_link_session` is never registered: a hosted
14
+ // child stores no session. Its session, when it has one, is the AuthToken
15
+ // mcp-host captured at sign-in (WARAPP_AUTH_TOKEN, #333): `warapp_session_status`
16
+ // then reports `hosted: true`, `linked: true`, `linkedBy: 'host'` and the active leg (no
17
+ // capture time, no age), and a signed-out one points at the connection's
18
+ // "Sign in". Without it the status reports the browser bridge, as before,
19
+ // without suggesting a link.
16
20
  //
17
21
  // SECURITY: the AuthToken is a full-account credential. Neither tool returns,
18
22
  // logs, or previews it; the status output carries only `capturedAt`/`host`/age.
19
23
  import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
20
24
  import { z } from 'zod';
21
25
  import { linkSession } from '../direct/link.js';
22
- import { readSession, SESSION_HOST } from '../direct/session.js';
26
+ import { hostedTokenState, readSession, SESSION_HOST } from '../direct/session.js';
27
+ import { HOST_SIGN_IN_ADVICE } from '../direct/transport.js';
23
28
  import { isHosted } from '../hosted.js';
24
29
  import { lookupMeta, mintMeta } from './hints.js';
25
30
  import { readAnnotations, respond, untrustedDescription } from './common.js';
26
31
  import { defineGatedWrite } from './write-kit.js';
27
32
  const HINT_NOT_LINKED = 'No war.app session is linked. Run warapp_link_session to use the direct (no-browser) transport; the browser ' +
28
33
  'bridge is used until then.';
29
- const NOTE_HOSTED = 'This server is hosted: the direct (no-browser) transport is local-only, so war.app calls go through the browser ' +
30
- 'bridge and your signed-in war.app tab.';
34
+ const NOTE_HOSTED = 'This server is hosted: it reaches war.app directly only from the session captured at sign-in, and this ' +
35
+ 'connection has none, so war.app calls go through the browser bridge and your signed-in war.app tab. ' +
36
+ HOST_SIGN_IN_ADVICE;
37
+ const NOTE_HOSTED_DIRECT = 'This server is hosted and signed in to war.app by mcp-host: war.app calls go directly to war.app with the ' +
38
+ 'session captured at sign-in, and fall back to the browser bridge only when that session stops working.';
39
+ const NOTE_HOSTED_MALFORMED = 'This server is hosted, and the war.app session mcp-host passed it is not usable, so war.app calls go through ' +
40
+ `the browser bridge and your signed-in war.app tab. ${HOST_SIGN_IN_ADVICE}`;
41
+ const HINT_HOST_EXPIRED = `The war.app session this connection signed in with is signed out. ${HOST_SIGN_IN_ADVICE}`;
31
42
  const HINT_EXPIRED = 'The linked war.app session is signed out (war.app answered a direct call signed-out this run). Run ' +
32
43
  'warapp_link_session to relink.';
33
44
  /**
@@ -42,6 +53,7 @@ export function registerSessionTools(server, deps) {
42
53
  const link = deps.link ?? ((opts) => linkSession({ ...(deps.env ? { env: deps.env } : {}), ...opts }));
43
54
  const now = deps.now ?? Date.now;
44
55
  const hosted = deps.hosted ?? isHosted(deps.env ?? process.env);
56
+ const hostToken = hosted ? (deps.hostToken ?? hostedTokenState(deps.env ?? process.env)) : 'none';
45
57
  /** The board decoder, once a live tool has loaded the client bundle (#148). */
46
58
  const decoderView = () => {
47
59
  if (!deps.decoder)
@@ -66,21 +78,41 @@ export function registerSessionTools(server, deps) {
66
78
  };
67
79
  server.registerTool('warapp_session_status', {
68
80
  title: 'war.app direct-transport session status',
69
- description: untrustedDescription(hosted
70
- ? 'Report which transport serves war.app calls on this hosted server (always the browser bridge: the ' +
71
- 'direct, no-browser transport is local-only) and which transport the turn-notification push socket ' +
72
- 'rides (websocket or xhr-polling) once it has run, and, once a live board has been read, which client ' +
73
- 'bundle decodes boards (a cached stand-in or not) and which of its reader helpers were verified. Read-only.'
74
- : 'Report whether a signed-in war.app session is linked for the direct (no-browser) transport, when it was ' +
75
- 'captured and how old it is, which transport is currently active (direct, or the browser bridge), and ' +
76
- 'which transport the turn-notification push socket rides (websocket or xhr-polling) once it has run, ' +
77
- 'and, once a live board has been read, which client bundle decodes boards (a cached stand-in or not) and ' +
78
- 'which of its reader helpers were verified. ' +
79
- 'Never shows the session cookie. Read-only; use warapp_link_session to link or relink.'),
81
+ description: untrustedDescription(hosted && hostToken === 'ok'
82
+ ? 'Report which transport serves war.app calls on this hosted server (direct to war.app with the session ' +
83
+ 'mcp-host captured at sign-in, or the browser bridge after that session stops working) and which ' +
84
+ 'transport the turn-notification push socket rides (websocket or xhr-polling) once it has run, and, once ' +
85
+ 'a live board has been read, which client bundle decodes boards (a cached stand-in or not) and which of ' +
86
+ 'its reader helpers were verified. Never shows the session cookie. Read-only.'
87
+ : hosted
88
+ ? 'Report which transport serves war.app calls on this hosted server (the browser bridge: hosted, the ' +
89
+ 'direct, no-browser transport runs only from the session captured at sign-in, and this connection ' +
90
+ 'has none) and which transport the turn-notification push socket ' +
91
+ 'rides (websocket or xhr-polling) once it has run, and, once a live board has been read, which client ' +
92
+ 'bundle decodes boards (a cached stand-in or not) and which of its reader helpers were verified. Read-only.'
93
+ : 'Report whether a signed-in war.app session is linked for the direct (no-browser) transport, when it was ' +
94
+ 'captured and how old it is, which transport is currently active (direct, or the browser bridge), and ' +
95
+ 'which transport the turn-notification push socket rides (websocket or xhr-polling) once it has run, ' +
96
+ 'and, once a live board has been read, which client bundle decodes boards (a cached stand-in or not) and ' +
97
+ 'which of its reader helpers were verified. ' +
98
+ 'Never shows the session cookie. Read-only; use warapp_link_session to link or relink.'),
80
99
  _meta: lookupMeta(['war.app session', 'is war.app linked', 'direct transport status']),
81
100
  annotations: readAnnotations('war.app session status'),
82
101
  inputSchema: z.object({}),
83
102
  }, async () => {
103
+ if (hosted && hostToken === 'ok') {
104
+ const pt = deps.pushTransport?.();
105
+ const base = {
106
+ hosted: true,
107
+ linked: true,
108
+ linkedBy: 'host',
109
+ activeTransport: deps.transport.activeLeg(),
110
+ ...(pt ? { pushTransport: pt } : {}),
111
+ ...decoderView(),
112
+ hostedNote: NOTE_HOSTED_DIRECT,
113
+ };
114
+ return respond(undefined, ['compact'], () => deps.transport.sessionStale() ? { ...base, sessionExpired: true, hint: HINT_HOST_EXPIRED } : base);
115
+ }
84
116
  if (hosted) {
85
117
  const pt = deps.pushTransport?.();
86
118
  return respond(undefined, ['compact'], () => ({
@@ -89,7 +121,7 @@ export function registerSessionTools(server, deps) {
89
121
  activeTransport: 'fetchproxy',
90
122
  ...(pt ? { pushTransport: pt } : {}),
91
123
  ...decoderView(),
92
- hostedNote: NOTE_HOSTED,
124
+ hostedNote: hostToken === 'malformed' ? NOTE_HOSTED_MALFORMED : NOTE_HOSTED,
93
125
  }));
94
126
  }
95
127
  const session = await read();
@@ -0,0 +1,56 @@
1
+ // `warapp_sign_in` — the war.app sign-in mcp-host's hosted authFlow calls as its
2
+ // `capture` (#333 part B, docs/examples/warapp-auth-flow.json).
3
+ //
4
+ // Registered ONLY on a hosted child (src/hosted.ts). Locally the way to the
5
+ // direct transport stays warapp_link_session, which takes the cookie off the
6
+ // signed-in tab and never returns it.
7
+ //
8
+ // THE ONE DOCUMENTED EXCEPTION to "the AuthToken is never in a tool result":
9
+ // this tool's result is `{ authToken }`, because mcp-host's `capture` reads the
10
+ // credential out of the capture tool's result (`path: authToken`) and seals it
11
+ // as the per-user secret WARAPP_AUTH_TOKEN. The caller already holds the
12
+ // account's email and password, so the result grants it nothing it did not
13
+ // have. Nothing else about the account is returned, and a refusal's text never
14
+ // holds the email, the password or a cookie value (src/direct/sign-in.ts).
15
+ // Hiding it from the connector's tool menu (mcp-host `enabledTools`) is the
16
+ // owner's choice, not a default: a flow's step and capture calls are never
17
+ // checked against that allowlist, so the sign-in would still run, but the gate
18
+ // is fail-closed — once set, the connection's resources (warapp://strategy) and
19
+ // prompts are gone, and every tool a later release adds stays hidden until the
20
+ // list is edited by hand (docs/PLAN-DIRECT.md, registration change step 3).
21
+ //
22
+ // Not confirm-gated: the flow calls it with exactly the arguments its document
23
+ // declares, and a gate would need another argument there. It is not read-only
24
+ // (it signs in, creating a war.app session), it reaches no player, and it is
25
+ // not idempotent (each call is a sign-in attempt war.app may count).
26
+ import { toolAnnotations } from '@chrischall/mcp-utils';
27
+ import { z } from 'zod';
28
+ import { signIn } from '../direct/sign-in.js';
29
+ import { mintMeta } from './hints.js';
30
+ export function registerSignInTool(server, deps = {}) {
31
+ const run = deps.signIn ?? signIn;
32
+ server.registerTool('warapp_sign_in', {
33
+ title: 'Sign in to war.app (host sign-in flow)',
34
+ description: "For the host's sign-in flow only, not for chat use: signs in to war.app once with the account's email " +
35
+ 'and password and returns the session cookie war.app sets, as `authToken`, which the host keeps as this ' +
36
+ "connection's own secret so later calls reach war.app without a browser. The password is used for this one " +
37
+ 'sign-in and never stored. A refusal (wrong email or password, a captcha or bot check, a network failure) ' +
38
+ 'is an error that says which, and is never retried, because war.app may count failed sign-ins.',
39
+ _meta: mintMeta('other', ['sign in to war.app']),
40
+ annotations: toolAnnotations({
41
+ title: 'Sign in to war.app',
42
+ readOnly: false,
43
+ destructive: false,
44
+ idempotent: false,
45
+ openWorld: true,
46
+ }),
47
+ inputSchema: z.object({
48
+ email: z.string().min(1).max(320).describe("The war.app account's email."),
49
+ password: z.string().min(1).max(1024).describe("The war.app account's password, used once and never stored."),
50
+ }),
51
+ }, async ({ email, password }, ctx) => {
52
+ const { authToken } = await run({ email, password }, { signal: ctx.mcpReq.signal });
53
+ // The capture reads this top-level key; nothing else about the account is returned.
54
+ return { content: [{ type: 'text', text: JSON.stringify({ authToken }) }] };
55
+ });
56
+ }