@chrischall/warapp-mcp 0.22.1 → 0.23.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 (66) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +49 -3
  4. package/dist/analysis/coalition.js +3 -2
  5. package/dist/analysis/outlook.js +42 -2
  6. package/dist/analysis/plan/captures.js +2 -0
  7. package/dist/analysis/plan/report.js +2 -2
  8. package/dist/analysis/plan/targets.js +15 -5
  9. package/dist/analysis/plan/threats.js +55 -2
  10. package/dist/analysis/planner.js +2 -1
  11. package/dist/bundle.js +10186 -3727
  12. package/dist/chat.js +93 -3
  13. package/dist/clans.js +308 -0
  14. package/dist/forums.js +70 -0
  15. package/dist/friends.js +83 -0
  16. package/dist/index.js +1 -1
  17. package/dist/invite-code.js +46 -0
  18. package/dist/join-color.js +23 -13
  19. package/dist/ladders.js +360 -0
  20. package/dist/mail.js +295 -0
  21. package/dist/my-games.js +18 -1
  22. package/dist/notifications.js +22 -4
  23. package/dist/open-games.js +29 -2
  24. package/dist/outlook-log.js +1 -0
  25. package/dist/protocol/bundle.js +4 -4
  26. package/dist/protocol/codec.js +1 -1
  27. package/dist/protocol/methods.js +690 -8
  28. package/dist/protocol/rpc.js +28 -3
  29. package/dist/push/socketio.js +2 -2
  30. package/dist/quickmatch.js +264 -0
  31. package/dist/surrender-pending.js +62 -2
  32. package/dist/templates.js +451 -0
  33. package/dist/tools/boot-player.js +165 -0
  34. package/dist/tools/chat.js +19 -0
  35. package/dist/tools/clan-writes.js +208 -0
  36. package/dist/tools/clans.js +181 -0
  37. package/dist/tools/end-game-common.js +49 -0
  38. package/dist/tools/forums.js +535 -0
  39. package/dist/tools/friends.js +50 -0
  40. package/dist/tools/game.js +21 -3
  41. package/dist/tools/index.js +39 -0
  42. package/dist/tools/invites.js +347 -0
  43. package/dist/tools/join-game.js +4 -4
  44. package/dist/tools/ladders.js +418 -0
  45. package/dist/tools/leave-game.js +85 -27
  46. package/dist/tools/live-context.js +2 -2
  47. package/dist/tools/mail.js +600 -0
  48. package/dist/tools/my-games.js +50 -6
  49. package/dist/tools/notifications.js +12 -3
  50. package/dist/tools/nudge.js +178 -0
  51. package/dist/tools/quickmatch.js +481 -0
  52. package/dist/tools/react.js +177 -0
  53. package/dist/tools/session.js +6 -2
  54. package/dist/tools/team-surrender.js +206 -0
  55. package/dist/tools/templates.js +342 -0
  56. package/dist/tools/tournaments.js +495 -0
  57. package/dist/tools/turn.js +1 -1
  58. package/dist/tools/vote-to-end.js +142 -0
  59. package/dist/tools/write-kit.js +22 -1
  60. package/dist/tournaments.js +321 -0
  61. package/dist/version.js +1 -1
  62. package/manifest.json +190 -2
  63. package/mint.yaml +3 -4
  64. package/package.json +1 -1
  65. package/server.json +2 -2
  66. package/skills/warapp-mcp/SKILL.md +39 -6
@@ -0,0 +1,177 @@
1
+ // warapp_react_to_message: add or remove the signed-in account's reaction on one game chat message (#634) with the web
2
+ // client's SetReaction (287) — the message's React menu: thumbs up, thumbs down, heart, laugh, angry. Other players
3
+ // see a reaction, so it is confirm-gated like a chat send, and an automated one (the owner did not ask for it) is
4
+ // behind WARAPP_CHAT_AUTOMATION as warapp_send_chat's is. The message is found in the web chat read (GameFeed's
5
+ // messages carry no id); the effect is read from the reply, the message's reactions after it. The encoding and the
6
+ // reply are read from the client bundle: UNVERIFIED live.
7
+ import { CONFIRM_INJECTION_RULE, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
8
+ import { z } from 'zod';
9
+ import { AUTOMATED_CHAT_OFF, chatAutomationMode } from '../chat-automation.js';
10
+ import { readSetReactionReply, REACTION_TYPES } from '../chat.js';
11
+ import { parseGameId } from '../client.js';
12
+ import { Method, REACTION_REFUSED, REACTION_TIMED_OUT, writeSetReactionParams } from '../protocol/methods.js';
13
+ import { WarappServerError } from '../protocol/rpc.js';
14
+ import { chatMe, readChat } from './chat.js';
15
+ import { gameIdArg, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedBody, untrustedText } from './common.js';
16
+ import { mintMeta } from './hints.js';
17
+ import { requireApprovedAccount, writeAccount } from './live-context.js';
18
+ import { accountUnknown, defineGatedWrite, mySeat, refuse, requireMe, sendAndVerify } from './write-kit.js';
19
+ /** What every result and preview says about the method. */
20
+ const UNVERIFIED = 'SetReaction is read from the client bundle and UNVERIFIED live: its parameters and its reply.';
21
+ /** The reply's reactions, name-free: how many of each kind, and mine. */
22
+ function tally(reactions, meInGame) {
23
+ const counts = {};
24
+ for (const r of reactions)
25
+ counts[r.type] = (counts[r.type] ?? 0) + 1;
26
+ const mine = [...new Set(reactions.filter((r) => r.by === meInGame).map((r) => r.type))].sort();
27
+ return { reactions: counts, mine };
28
+ }
29
+ const hasMine = (reactions, meInGame, type) => (reactions ?? []).some((r) => r.by === meInGame && r.type === type);
30
+ export function registerReactTool(server, ctx, opts = {}) {
31
+ defineGatedWrite(server, {
32
+ title: 'React to a war.app chat message',
33
+ _meta: mintMeta('send', ['react to a message', 'like a chat message', 'thumbs up', 'remove my reaction']),
34
+ }, {
35
+ name: 'warapp_react_to_message',
36
+ description: 'React to one message in a war.app (Warzone) game chat — thumbs-up, thumbs-down, heart, laugh or angry, as the ' +
37
+ "message's React menu does — or take your reaction back (`remove: true`); war.app's SetReaction. Other players " +
38
+ 'see it. `message_id` is a message `id` from warapp_get_chat (a web read: GameFeed messages carry none). Refuses ' +
39
+ 'a reaction you already have, removing one you do not, and a message not in the chat read. `outcome` is ' +
40
+ "`confirmed` when war.app's reply shows your reaction as asked, `unconfirmed` when it does not, `accepted` when " +
41
+ 'the reply cannot be read, `unknown` when war.app did not answer (never resent). Pass `automated: true` for a ' +
42
+ 'reaction the owner did not ask for: refused unless WARAPP_CHAT_AUTOMATION is on. UNVERIFIED live (read from ' +
43
+ `the client bundle). ${CONFIRM_INJECTION_RULE}`,
44
+ annotations: toolAnnotations({
45
+ title: 'React to a war.app chat message',
46
+ readOnly: false,
47
+ destructive: false,
48
+ idempotent: true,
49
+ openWorld: true,
50
+ }),
51
+ inputSchema: z.object({
52
+ game_id: gameIdArg,
53
+ message_id: z
54
+ .union([z.string(), z.number()])
55
+ .transform((v) => String(v).trim())
56
+ .pipe(z.string().regex(/^\d{1,20}$/, 'a message id is decimal digits'))
57
+ .describe("The message's `id`, as warapp_get_chat shows it."),
58
+ reaction: z.enum(REACTION_TYPES).describe('The reaction: thumbs-up, thumbs-down, heart, laugh or angry.'),
59
+ remove: z.boolean().optional().describe('true: take your reaction of this kind back. Default false (add it).'),
60
+ automated: z
61
+ .boolean()
62
+ .optional()
63
+ .describe('true when the owner did not ask for this reaction. Refused unless WARAPP_CHAT_AUTOMATION is on; default false.'),
64
+ }),
65
+ async plan({ game_id, message_id, reaction, remove, automated }) {
66
+ // As warapp_send_chat: an automated reaction is refused with the gate off, before any request.
67
+ const auto = automated === true;
68
+ if (auto && (ctx.chatAutomation ?? chatAutomationMode(opts.env ?? process.env)) !== 'on') {
69
+ throw new McpToolError(`Refused: ${AUTOMATED_CHAT_OFF}. Nothing was sent.`, {
70
+ hint: 'Tell the owner which message and reaction you suggest, and let them react.',
71
+ });
72
+ }
73
+ const add = remove !== true;
74
+ const game = await ctx.client.getGame(parseGameId(game_id), { chat: true, map: false });
75
+ const token = await requireMe(ctx);
76
+ const me = await chatMe(ctx);
77
+ if (!me || me.token !== token)
78
+ throw accountUnknown(ctx);
79
+ const seat = mySeat(game, token);
80
+ const read = await readChat(ctx, game, me);
81
+ if (read?.source !== 'web' || read.feedFill?.web === 0) {
82
+ refuse(`Game ${game.id}'s chat could not be read from the web client, so message ${message_id} cannot be found and nothing was sent.`, 'Read it with warapp_get_chat: a message can be reacted to once its `source` is `web`.');
83
+ }
84
+ const line = read.lines.find((l) => l.id === message_id);
85
+ if (!line) {
86
+ refuse(`Message ${message_id} was not found in game ${game.id}'s chat, so nothing was sent.`, 'Take the `id` of a message from warapp_get_chat.');
87
+ }
88
+ const has = hasMine(line.reactions, me.inGameId, reaction);
89
+ if (add && has)
90
+ refuse(`You already reacted ${reaction} to message ${message_id}, so nothing was sent.`, 'Pass `remove: true` to take it back.');
91
+ if (!add && !has && !line.reactionsUnread) {
92
+ refuse(`Message ${message_id} has no ${reaction} reaction of yours, so there is nothing to remove and nothing was sent.`, 'Check its `reactions` with warapp_get_chat.');
93
+ }
94
+ const account = writeAccount(token);
95
+ const summary = add
96
+ ? `React ${reaction} to message ${message_id} in game ${game.id}`
97
+ : `Remove your ${reaction} reaction from message ${message_id} in game ${game.id}`;
98
+ return {
99
+ gate: {
100
+ action: 'warapp.react_to_message',
101
+ summary,
102
+ account,
103
+ target: game.id,
104
+ payload: { method: 'SetReaction', gameId: game.id, messageId: message_id, reaction, add },
105
+ willSend: { game: game.id, message: message_id, reaction, add },
106
+ preview: {
107
+ account: shownAccount(seat.name, seat.id),
108
+ sends: `${summary}.`,
109
+ note: 'Other players in the game see your reaction.',
110
+ message: {
111
+ id: message_id,
112
+ channel: line.channel,
113
+ senderInGameId: line.sender,
114
+ text: untrustedBody(line.text),
115
+ },
116
+ game: { id: game.id, name: game.name === undefined ? null : untrustedText(game.name), state: game.state },
117
+ ...(line.reactionsUnread ? { reactionsUnread: 'The message\'s current reactions could not be read.' } : {}),
118
+ ...(auto ? { automated: true, automatedNote: 'An automated reaction (WARAPP_CHAT_AUTOMATION is on): the owner did not ask for it.' } : {}),
119
+ unverified: UNVERIFIED,
120
+ untrusted: UNTRUSTED_PREVIEW_NOTE,
121
+ },
122
+ },
123
+ state: {
124
+ gameId: game.id,
125
+ messageId: message_id,
126
+ reaction,
127
+ add,
128
+ meInGame: me.inGameId,
129
+ account,
130
+ ...(auto ? { automated: true } : {}),
131
+ },
132
+ };
133
+ },
134
+ async execute({ gameId, messageId, reaction, add, meInGame, account, automated }) {
135
+ await requireApprovedAccount(ctx, account);
136
+ const base = { gameId, messageId, reaction, ...(automated ? { automated: true } : {}) };
137
+ const done = add ? 'reacted' : 'removed';
138
+ let reply;
139
+ return sendAndVerify({
140
+ send: async () => {
141
+ reply = await ctx.rpc.call('SetReaction', Method.SetReaction, (w) => writeSetReactionParams(w, { messageId, type: REACTION_TYPES.indexOf(reaction), add }));
142
+ },
143
+ refused: (e) => {
144
+ if (e.code === REACTION_TIMED_OUT)
145
+ return new WarappServerError(e.code, `You can't react while you're timed out (war.app error ${e.code})`);
146
+ if (REACTION_REFUSED.includes(e.code))
147
+ return new WarappServerError(e.code, `You can't react to this message (war.app error ${e.code})`);
148
+ return undefined;
149
+ },
150
+ unanswered: (failure) => ({
151
+ ...base,
152
+ status: 'unknown',
153
+ outcome: 'unknown',
154
+ warning: `war.app did not answer (${failure}), so the reaction may or may not be set; it was not resent. Check warapp_get_chat.`,
155
+ unverified: UNVERIFIED,
156
+ }),
157
+ readBack: async () => {
158
+ const reactions = reply ? readSetReactionReply(await ctx.bundle(), reply.body) : undefined;
159
+ if (!reactions)
160
+ throw new Error('the reply could not be read');
161
+ return reactions;
162
+ },
163
+ unreadable: () => ({ ...base, status: done, outcome: 'accepted', unverified: UNVERIFIED }),
164
+ classify: (reactions) => hasMine(reactions, meInGame, reaction) === add
165
+ ? { ...base, status: done, outcome: 'confirmed', ...tally(reactions, meInGame), unverified: UNVERIFIED }
166
+ : {
167
+ ...base,
168
+ status: 'unconfirmed',
169
+ outcome: 'unconfirmed',
170
+ ...tally(reactions, meInGame),
171
+ warning: "war.app accepted the request, but its reply does not show your reaction as asked. Check warapp_get_chat before trying again.",
172
+ unverified: UNVERIFIED,
173
+ },
174
+ });
175
+ },
176
+ });
177
+ }
@@ -105,7 +105,8 @@ export function registerSessionTools(server, deps) {
105
105
  ' `pace` lists the multi-day games waiting on you whose boot is under 6 hours away (boot time plus your banked ' +
106
106
  'time, less your turn so far), and `bootWarning` names them: from the game list this server last read ' +
107
107
  '(warapp_my_games, the chat inbox), else it reads the list itself (one war.app request, over a working direct ' +
108
- 'session only — never by waiting on the browser bridge); `paceUnread` says why when it could not.'),
108
+ 'session only — never by waiting on the browser bridge); `paceUnread` says why when it could not. `mail` is war.app\'s ' +
109
+ 'unread-mail check from its newest reply (`flagged`; null before any; unverified live): read mail with warapp_mail_inbox.'),
109
110
  _meta: lookupMeta(['war.app session', 'is war.app linked', 'direct transport status']),
110
111
  annotations: readAnnotations('war.app session status'),
111
112
  inputSchema: z.object({}),
@@ -118,7 +119,10 @@ export function registerSessionTools(server, deps) {
118
119
  const pace = await deps.pace?.(now(), direct);
119
120
  const paceRead = pace && !('error' in pace) ? pace : undefined;
120
121
  const bootWarning = paceWarning(paceRead);
121
- const paceFields = paceRead ? { pace: paceRead, ...(bootWarning ? { bootWarning } : {}) } : pace && 'error' in pace ? { paceUnread: pace.error } : {};
122
+ const paceFields = {
123
+ ...(paceRead ? { pace: paceRead, ...(bootWarning ? { bootWarning } : {}) } : pace && 'error' in pace ? { paceUnread: pace.error } : {}),
124
+ ...(deps.mail ? { mail: deps.mail() } : {}),
125
+ };
122
126
  if (hosted && hostToken === 'ok') {
123
127
  const pt = deps.pushTransport?.();
124
128
  const wall = deps.transport.wall?.() ?? null;
@@ -0,0 +1,206 @@
1
+ // warapp_team_surrender (#630): propose that my whole team surrenders, accept or decline a teammate's
2
+ // proposal, or withdraw my own, with the web client's TeamSurrender (70), gated on the user's
3
+ // confirmation. The encoder is read from the client bundle and golden-pinned, UNVERIFIED live
4
+ // (docs/WEB-PROTOCOL.md "Team surrender").
5
+ //
6
+ // The proposal lives only in the game details: each GamePlayer's team-surrender vote (field 31; 0 none,
7
+ // 1 proposed, 2 yes, 3 no) beside its team (30). The plan reads them and refuses what the client would not
8
+ // offer: no team of two or more still playing, a proposal already open (propose), none open or already
9
+ // voted (accept, decline), or one not mine (withdraw). If every teammate accepts, everyone on the team
10
+ // surrenders. The outcome is read back from the details and GameFeed, never from the reply (no result).
11
+ import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
12
+ import { z } from 'zod';
13
+ import { Method, TeamSurrenderAction, writeTeamSurrenderParams } from '../protocol/methods.js';
14
+ import { teamSurrenderOf } from '../surrender-pending.js';
15
+ import { gameIdArg, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedText } from './common.js';
16
+ import { gameInPlay, requireDetailsSeats, seatLabel, seatsView } from './end-game-common.js';
17
+ import { mintMeta } from './hints.js';
18
+ import { requireApprovedAccount, writeAccount } from './live-context.js';
19
+ import { noBrowserNote } from './session.js';
20
+ import { readDetailsSeats } from './surrender-pending.js';
21
+ import { defineGatedWrite, refuse, sendAndVerify, worded } from './write-kit.js';
22
+ /** The TeamSurrender refusals, worded from the client's own messages (read from the bundle, UNVERIFIED live). */
23
+ const TEAM_SURRENDER_ERRORS = {
24
+ 4: 'war.app says the game has ended, so a team surrender is not available.',
25
+ 7: 'war.app says you are no longer in the game, so a team surrender is not available.',
26
+ 230: 'war.app says your seat no longer takes part in the game, so a team surrender is not available.',
27
+ 758: 'war.app says a team surrender is not available right now (TeamSurrenderNotAvailable).',
28
+ 759: 'Someone on your team has already proposed that your team surrenders (TeamSurrenderAlreadyProposed).',
29
+ 760: 'That team surrender is not open any more: the player who proposed it may have withdrawn it (NoTeamSurrenderProposal).',
30
+ 761: 'Only the player who proposed the team surrender can withdraw it (OnlyProposerCanRevokeTeamSurrender).',
31
+ };
32
+ const ACTIONS = Object.keys(TeamSurrenderAction);
33
+ /** Refuse an action the current vote does not allow (the client's own offers). */
34
+ function checkAction(gameId, ts, action, meInGame, label) {
35
+ const hint = 'warapp_my_games shows the team-surrender vote of each game (`teamSurrender`).';
36
+ if (action === 'propose') {
37
+ if (ts.open) {
38
+ refuse(ts.proposer === meInGame
39
+ ? `You have already proposed a team surrender in game ${gameId}; nothing was sent.`
40
+ : `${label(ts.proposer)} has already proposed a team surrender in game ${gameId}: accept or decline it instead; nothing was sent.`, hint);
41
+ }
42
+ return;
43
+ }
44
+ if (!ts.open)
45
+ refuse(`No team surrender is open in game ${gameId}, so there is nothing to ${action}; nothing was sent.`, hint);
46
+ if (action === 'withdraw') {
47
+ if (ts.proposer !== meInGame) {
48
+ refuse(`Only the player who proposed the team surrender (${label(ts.proposer)}) can withdraw it; nothing was sent.`, 'Decline it instead.');
49
+ }
50
+ return;
51
+ }
52
+ if (ts.proposer === meInGame)
53
+ refuse(`You proposed the team surrender in game ${gameId}; withdraw it instead of voting on it. Nothing was sent.`, hint);
54
+ if (ts.myVote !== 'none')
55
+ refuse(`You have already voted ${ts.myVote} on the team surrender in game ${gameId}; nothing was sent.`, hint);
56
+ }
57
+ /** What the action does here, for the preview (ids only). */
58
+ function consequence(gameId, ts, action, meInGame) {
59
+ const others = ts.team.filter((id) => id !== meInGame);
60
+ switch (action) {
61
+ case 'propose':
62
+ return (`This proposes that your whole team surrenders in game ${gameId}: your ${others.length} teammate(s) still playing are asked, and ` +
63
+ 'if every one of them accepts, everyone on your team surrenders — your team loses the game and none of you can rejoin.');
64
+ case 'accept': {
65
+ const left = ts.waiting.filter((id) => id !== meInGame);
66
+ return left.length
67
+ ? `This votes YES to your team surrendering in game ${gameId}. ${left.length} teammate(s) have still to vote; once every one accepts, ` +
68
+ 'everyone on your team surrenders — your team loses the game and none of you can rejoin.'
69
+ : `This votes YES to your team surrendering in game ${gameId}, and yours is the last vote: your whole team surrenders now — ` +
70
+ 'your team loses the game and none of you can rejoin.';
71
+ }
72
+ case 'decline':
73
+ return `This votes NO on the team surrender in game ${gameId}: the proposal ends and your team stays in the game.`;
74
+ case 'withdraw':
75
+ return `This withdraws your proposal that your team surrenders in game ${gameId}: your team stays in the game.`;
76
+ }
77
+ }
78
+ /** The vote as a preview or result shows it: each seat by both ids, the names untrusted. */
79
+ function voteView(game, ts) {
80
+ return {
81
+ team: seatsView(game, ts.team),
82
+ open: ts.open,
83
+ proposer: ts.proposer === null ? null : seatsView(game, [ts.proposer])[0],
84
+ yes: seatsView(game, ts.yes),
85
+ no: seatsView(game, ts.no),
86
+ waiting: seatsView(game, ts.waiting),
87
+ myVote: ts.myVote,
88
+ };
89
+ }
90
+ export function registerTeamSurrenderTool(server, ctx) {
91
+ defineGatedWrite(server, {
92
+ title: 'Propose or vote on a team surrender in a war.app game',
93
+ _meta: mintMeta('change', ['team surrender', 'surrender as a team', 'propose team surrender warzone']),
94
+ }, {
95
+ name: 'warapp_team_surrender',
96
+ description: 'Propose that your whole team surrenders in a war.app (Warzone) team game, accept (vote yes) or decline (vote no) a ' +
97
+ "teammate's proposal, or withdraw your own, as the signed-in account (the client's TeamSurrender). If every teammate " +
98
+ 'still playing accepts, everyone on the team surrenders: the team loses and none of you can rejoin; one no ends the ' +
99
+ 'proposal. To surrender only your own seat use warapp_surrender. The plan reads the vote from the game details and ' +
100
+ 'refuses what the client would not offer: no team of two or more still playing, a proposal already open (propose), ' +
101
+ 'none open or a vote already cast (accept, decline), or one you did not make (withdraw); finished games and games you ' +
102
+ 'are not playing are refused too. The preview shows the vote (proposer, yes, no, still to vote; by GameFeed and in-game ' +
103
+ 'id) and what the action does. The outcome is read back from the details and GameFeed (`proposed`, `accepted`, ' +
104
+ '`declined`, `withdrawn`, `surrendered`; `unconfirmed`, `unknown`). The encoding is read from the client bundle, ' +
105
+ `UNVERIFIED live.${noBrowserNote(ctx.hosted)} ${CONFIRM_INJECTION_RULE}`,
106
+ annotations: toolAnnotations({
107
+ title: 'Propose or vote on a team surrender in a war.app game',
108
+ readOnly: false,
109
+ destructive: true,
110
+ idempotent: false,
111
+ openWorld: true,
112
+ }),
113
+ inputSchema: z.object({
114
+ game_id: gameIdArg,
115
+ action: z
116
+ .enum(ACTIONS)
117
+ .describe('propose (ask the team to surrender together), accept (vote yes), decline (vote no) or withdraw (take back your proposal).'),
118
+ }),
119
+ async plan({ game_id, action }) {
120
+ const { gameId, me, game, seat, meInGame } = await gameInPlay(ctx, game_id, 'a team surrender');
121
+ const seats = await requireDetailsSeats(ctx, gameId, 'the team-surrender vote');
122
+ const ts = teamSurrenderOf(seats, meInGame);
123
+ if (ts === undefined)
124
+ refuse(`The team-surrender vote in game ${gameId} could not be read from the game details, so nothing was sent.`, 'Retry shortly.');
125
+ if (!ts.available) {
126
+ refuse(`A team surrender is not available in game ${gameId}: your team has fewer than two players still playing, or the game has no teams. Nothing was sent.`, 'warapp_surrender surrenders only your own seat.');
127
+ }
128
+ const label = (id) => seatLabel(game, id);
129
+ checkAction(gameId, ts, action, meInGame, label);
130
+ const warning = consequence(gameId, ts, action, meInGame);
131
+ return {
132
+ gate: {
133
+ action: `warapp.team_surrender.${action}`,
134
+ summary: `Team surrender in war.app game ${gameId}: ${action}`,
135
+ account: writeAccount(me),
136
+ target: gameId,
137
+ payload: { method: 'TeamSurrender', gameId, action: TeamSurrenderAction[action] },
138
+ willSend: { game: gameId, action },
139
+ preview: {
140
+ warning,
141
+ account: shownAccount(seat.name, me),
142
+ game: { id: gameId, name: game.name === undefined ? null : untrustedText(game.name), state: game.state },
143
+ vote: voteView(game, ts),
144
+ unverified: 'TeamSurrender is read from the client bundle and not yet verified live; the outcome is read back from game state.',
145
+ untrusted: UNTRUSTED_PREVIEW_NOTE,
146
+ },
147
+ },
148
+ state: { gameId, me, meInGame, action },
149
+ };
150
+ },
151
+ async execute({ gameId, me, meInGame, action }) {
152
+ await requireApprovedAccount(ctx, writeAccount(me));
153
+ const game = { id: gameId };
154
+ return sendAndVerify({
155
+ send: async () => {
156
+ await ctx.rpc.call('TeamSurrender', Method.TeamSurrender, (w) => writeTeamSurrenderParams(w, { gameId, action }));
157
+ },
158
+ refused: worded(TEAM_SURRENDER_ERRORS),
159
+ unanswered: (failure) => ({
160
+ status: 'unknown',
161
+ outcome: 'unknown',
162
+ game,
163
+ action,
164
+ warning: `war.app did not confirm the team-surrender ${action} (${failure}), so it may already have gone through. Check warapp_my_games before doing anything else.`,
165
+ }),
166
+ readBack: async () => ({ after: await ctx.client.getGame(gameId, { map: false }), seats: await readDetailsSeats(ctx, gameId) }),
167
+ unreadable: (failure) => ({
168
+ status: 'unconfirmed',
169
+ outcome: 'unconfirmed',
170
+ game,
171
+ action,
172
+ warning: `war.app took the request, but GameFeed could not be read back (${failure}). Check warapp_my_games.`,
173
+ }),
174
+ classify: ({ after, seats }) => {
175
+ const mine = after.players.find((p) => p.id === me);
176
+ const state = { yourState: mine?.state ?? null, gameState: after.state };
177
+ // #645: a surrendered seat or a finished game is evidence for a proposal or a yes only; a decline or a
178
+ // withdraw never ends the game, so on a finished one it is read from the vote like any other.
179
+ const ends = action === 'propose' || action === 'accept';
180
+ if (ends && (mine?.state === 'SurrenderAccepted' || after.state === 'Finished')) {
181
+ return { status: 'surrendered', outcome: 'confirmed', game, action, ...state };
182
+ }
183
+ const ts = seats ? teamSurrenderOf(seats, meInGame) : undefined;
184
+ const done = ts?.available === true &&
185
+ ((action === 'propose' && ts.myVote === 'proposed') ||
186
+ (action === 'accept' && ts.myVote === 'yes') ||
187
+ (action === 'decline' && (ts.myVote === 'no' || !ts.open)) ||
188
+ (action === 'withdraw' && !ts.open));
189
+ if (done) {
190
+ const status = { propose: 'proposed', accept: 'accepted', decline: 'declined', withdraw: 'withdrawn' }[action];
191
+ return { status, outcome: 'confirmed', game, action, ...state, vote: voteView(after, ts) };
192
+ }
193
+ return {
194
+ status: 'unconfirmed',
195
+ outcome: 'unconfirmed',
196
+ game,
197
+ action,
198
+ ...state,
199
+ warning: (seats ? 'war.app took the request, but the game details do not show it yet. ' : 'war.app took the request, but the game details could not be read back. ') +
200
+ 'Check warapp_my_games shortly; do not send it again blindly.',
201
+ };
202
+ },
203
+ });
204
+ },
205
+ });
206
+ }