@chrischall/warapp-mcp 0.23.2 → 0.25.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.
@@ -2,14 +2,15 @@
2
2
  // (`GetChat=true`, channels unknown), with what is new since the messages were last marked seen; send
3
3
  // through the web-client protocol (`SendChat`) publicly, to my team or privately, gated on the user's
4
4
  // confirmation — a message reaches other players and cannot be unsent.
5
+ import { WarappServerError } from '../protocol/rpc.js';
5
6
  import { CONFIRM_INJECTION_RULE, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
6
7
  import { z } from 'zod';
7
- import { CHAT_CHANNELS, feedChatLines, fillFromFeed, mergeChatLines, oldestId, readGameRefreshChat, readMessageHistoryReply, readSendChatReply, } from '../chat.js';
8
+ import { CHAT_CHANNELS, feedChatLines, fillFromFeed, mergeChatLines, oldestId, readCreateGameGroupReply, readGameGroups, readGameRefreshChat, readMessageHistoryReply, readSendChatReply, } from '../chat.js';
8
9
  import { advanceCursor, markedChannels, markNew, readChatCursor, unreadCounts, writeChatCursor, } from '../chat-cursor.js';
9
10
  import { parseGameId } from '../client.js';
10
11
  import { inGameId, inGameOf, playersByInGameId } from '../live.js';
11
12
  import { decodeChatLinks, encodeChatLinks, hasChatLinkMarkers } from '../chat-links.js';
12
- import { CHAT_CHANNEL_PUBLIC, Method, writeGameRefreshParams, writeRetrieveChatParams, writeRetrievePrivateMessageHistoryParams, writeSendChatParams, } from '../protocol/methods.js';
13
+ import { CHAT_CHANNEL_PUBLIC, Method, writeGameRefreshParams, writeRetrieveChatParams, writeCreateGameGroupParams, writeRetrievePrivateMessageHistoryParams, writeSendChatParams, } from '../protocol/methods.js';
13
14
  import { carriesTeam } from '../teams.js';
14
15
  import { gameIdArg, readAnnotations, respond, UNTRUSTED_PREVIEW_NOTE, untrustedBody, untrustedDescription, untrustedText, } from './common.js';
15
16
  import { checkMessageCommitments, commitmentsArg, COMMITMENTS_NOTE, DEFAULT_PLAN_CHECKED } from './commitments.js';
@@ -24,6 +25,139 @@ import { AUTOMATED_CHAT_OFF, chatAutomationMode } from '../chat-automation.js';
24
25
  import { resolveTeams } from './team-source.js';
25
26
  const DEFAULT_LIMIT = 50;
26
27
  const MAX_CHAT_LENGTH = 2000;
28
+ /** The most players one game-group message names (`to` as a list). */
29
+ export const MAX_GROUP_RECIPIENTS = 10;
30
+ /** The most characters of a new game group's name. */
31
+ const MAX_GROUP_NAME = 50;
32
+ /** A new game group's name when no other can be made (the members' names unreadable): it is shown to the members. */
33
+ export const DEFAULT_GROUP_NAME = 'Group chat';
34
+ /**
35
+ * The waits before resending a message to a game group this call just created, after war.app refused it with 752
36
+ * (NotInGameGroup). Live 2026-11-30: right after CreateGameGroup war.app refused a message to the new group's right id
37
+ * (read back from the chat), and took the same message minutes later. A refusal posts nothing, so resending is safe.
38
+ * Mutable for tests only.
39
+ */
40
+ export const GROUP_SEND_RETRY = { delaysMs: [2_000, 4_000, 8_000, 16_000] };
41
+ const NOT_IN_GAME_GROUP = 752;
42
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
43
+ const CONTROL_CHARS = /\p{Cc}/gu;
44
+ /** A name for war.app: control characters out, whitespace runs one space, trimmed. */
45
+ const cleanName = (name) => name.replace(CONTROL_CHARS, '').replace(/\s+/g, ' ').trim();
46
+ /** `text` cut to MAX_GROUP_NAME characters with an ellipsis, never splitting a surrogate pair. */
47
+ function cutName(text) {
48
+ if (text.length <= MAX_GROUP_NAME)
49
+ return text;
50
+ let end = MAX_GROUP_NAME - 1;
51
+ const code = text.charCodeAt(end - 1);
52
+ if (code >= 0xd800 && code <= 0xdbff)
53
+ end -= 1;
54
+ return `${text.slice(0, end)}…`;
55
+ }
56
+ /**
57
+ * A new game group's default name from its members' names, the first (me) first: "Ann, Bob and Cat". Over
58
+ * {@link MAX_GROUP_NAME} characters it names as many as fit, then "and N more"; still too long, it is cut to 49 and an
59
+ * ellipsis. The raw names (war.app shows the name; only the preview delimits it), control characters stripped; with
60
+ * fewer than two names left, {@link DEFAULT_GROUP_NAME}.
61
+ */
62
+ export function defaultGroupName(names) {
63
+ const clean = names.map(cleanName).filter((n) => n !== '');
64
+ if (clean.length < 2)
65
+ return DEFAULT_GROUP_NAME;
66
+ const and = (first, last) => `${first.join(', ')} and ${last}`;
67
+ const full = and(clean.slice(0, -1), clean.at(-1));
68
+ if (full.length <= MAX_GROUP_NAME)
69
+ return full;
70
+ for (let k = clean.length - 1; k >= 1; k--) {
71
+ const some = and(clean.slice(0, k), `${clean.length - k} more`);
72
+ if (some.length <= MAX_GROUP_NAME)
73
+ return some;
74
+ }
75
+ return cutName(and(clean.slice(0, 1), `${clean.length - 1} more`));
76
+ }
77
+ /** What the preview says of a new group's name: it cannot be changed. */
78
+ const GROUP_NAME_NOTE = 'war.app cannot rename or delete a game group, and the members see its name and a creation line in the game chat, ' +
79
+ 'so choose the name now (`group_name`).';
80
+ /** CreateGameGroup's refusals as the client words them. */
81
+ const GROUP_REFUSALS = {
82
+ 227: 'a player in it has blocked you',
83
+ 751: 'this game does not allow game groups',
84
+ 752: 'you are not in that group',
85
+ 753: 'you do not moderate that group',
86
+ };
87
+ /** Ids as "1, 2 and 3". */
88
+ const listIds = (ids) => (ids.length > 1 ? `${ids.slice(0, -1).join(', ')} and ${ids.at(-1)}` : String(ids[0]));
89
+ /** Whether a group holds exactly me and `members` (in-game ids). */
90
+ const sameMembers = (g, meInGame, members) => {
91
+ const want = new Set([meInGame, ...members]);
92
+ return g.members !== null && new Set(g.members).size === want.size && g.members.every((m) => want.has(m));
93
+ };
94
+ /**
95
+ * The id of the group this call just created, from the chat GameRefresh (the read warapp_get_chat makes): the game's
96
+ * newest group of exactly me and `members` under `name` when the reply lists the groups, else the newest line in a
97
+ * group with no sender whose text names it (the creation line). Live 2026-11-30 the id read from CreateGameGroup's
98
+ * reply was refused (752), and the chat's id worked. `undefined` when neither shows it or the read fails. Never throws.
99
+ */
100
+ async function createdGroupInChat(ctx, gameId, lobby, meInGame, members, name, replyId) {
101
+ try {
102
+ const env = await ctx.rpc.call('GameRefresh', Method.GameRefresh, (w) => writeGameRefreshParams(w, { gameId, chat: true, nonChat: false, lobby }));
103
+ const bundle = await ctx.bundle();
104
+ const groups = readGameGroups(bundle, env.body.fork());
105
+ const group = groups
106
+ ?.filter((g) => g.gameId === gameId && g.name === name && sameMembers(g, meInGame, members))
107
+ .sort((a, b) => b.id - a.id)[0];
108
+ if (group)
109
+ return group.id;
110
+ // Message ids are decimal text, past a double's precision: the newest is the longest, then the greatest; else the last.
111
+ const newer = (a, b) => {
112
+ const [x, y] = [a.id ?? '', b.id ?? ''];
113
+ return x.length !== y.length ? x.length > y.length : x >= y;
114
+ };
115
+ // #682: a creation line only names the group by its name, which an older group may share. War.app numbers groups
116
+ // upwards (live: 11193, then 11194), so only the line of the game's highest group read, at or above the reply's id,
117
+ // can be the new group's: else the line is an older group's, and its players must not get the message.
118
+ const lines = readGameRefreshChat(bundle, env.body) ?? [];
119
+ const highest = Math.max(-Infinity, ...lines.flatMap((l) => (l.group !== undefined ? [l.group] : [])));
120
+ let line;
121
+ for (const l of lines) {
122
+ if (l.group !== undefined && l.sender === null && l.text.includes(name) && (!line || newer(l, line)))
123
+ line = l;
124
+ }
125
+ if (line?.group === undefined || line.group !== highest || (replyId !== undefined && line.group < replyId))
126
+ return undefined;
127
+ return line.group;
128
+ }
129
+ catch {
130
+ return undefined;
131
+ }
132
+ }
133
+ /**
134
+ * The game's newest group holding exactly me and `members` (in-game ids), from one GameRefresh with the game details.
135
+ * `read: false` when the groups could not be read (a failed request, or a reply without them). Never throws.
136
+ */
137
+ async function existingGroup(ctx, game, meInGame, members) {
138
+ // Which GameRefresh carries the groups is UNVERIFIED live (live, the details-only read did not): the chat read
139
+ // warapp_get_chat makes first, then the details read.
140
+ const read = async (chat) => {
141
+ try {
142
+ const env = await ctx.rpc.call('GameRefresh', Method.GameRefresh, (w) => writeGameRefreshParams(w, { gameId: game.id, chat, nonChat: !chat, lobby: game.state === 'WaitingForPlayers' }));
143
+ return readGameGroups(await ctx.bundle(), env.body);
144
+ }
145
+ catch {
146
+ return undefined;
147
+ }
148
+ };
149
+ try {
150
+ const groups = (await read(true)) ?? (await read(false));
151
+ if (!groups)
152
+ return { read: false };
153
+ const same = groups.filter((g) => g.gameId === game.id && sameMembers(g, meInGame, members)).sort((a, b) => b.id - a.id);
154
+ return same[0] ? { read: true, group: same[0] } : { read: true };
155
+ }
156
+ catch {
157
+ return { read: false };
158
+ }
159
+ }
160
+ const GROUP_UNVERIFIED = 'Game groups (creating one, and a message to one) are read from the client bundle and UNVERIFIED live.';
27
161
  /** The send preview's note on links: what goes out, and what is verified. */
28
162
  const LINKS_NOTE = 'Each link goes out as the client\'s token (`<a t=ID>` territory, `<a b=ID>` bonus) and players see the name from ' +
29
163
  'the map. Territory and bonus links are verified live (2026-11-23).';
@@ -317,6 +451,8 @@ export function shown(line, isNew, players, byInGame, me, map) {
317
451
  channel: line.channel,
318
452
  ...(line.team !== undefined ? { team: line.team } : {}),
319
453
  ...(to ? { to } : {}),
454
+ // A game-group message's group id (warapp_send_chat's `group_id` sends into it).
455
+ ...(line.group !== undefined ? { group: line.group } : {}),
320
456
  // #387: a private message addressed to me, so a watcher can flag diplomacy the moment it arrives.
321
457
  ...(line.channel === 'private' && me !== undefined && line.to === me.inGameId ? { toMe: true } : {}),
322
458
  // #634: what the sender shared and who reacted, all their own words (delimited).
@@ -436,8 +572,11 @@ export function registerChatTools(server, ctx, opts = {}) {
436
572
  }, {
437
573
  name: 'warapp_send_chat',
438
574
  description: 'Post a chat message in a war.app (Warzone) game — to the whole game, to your team (`channel: "team"`, in ' +
439
- 'a team game), or privately to one named player (`to`; refused when the game turns private messages ' +
440
- 'off). The message reaches other players and cannot be unsent. Sent through your signed-in war.app tab ' +
575
+ 'a team game), or privately to one named player (`to`), or to several together (`to` as a list: a war.app game ' +
576
+ 'group, reused when one of exactly you and them exists, else created first in the same call, named by `group_name` or ' +
577
+ "by default the members' names, yours first — war.app cannot rename or delete a group, so choose the name — and its id " +
578
+ 'read back from the game chat before the message goes to it; UNVERIFIED live); ' +
579
+ 'private sends are refused when the game turns private messages off. The message reaches other players and cannot be unsent. Sent through your signed-in war.app tab ' +
441
580
  '(ContextMint Bridge); the game is read from GameFeed first, so the GameFeed credentials are needed too. ' +
442
581
  "The result's `outcome` is `confirmed` when war.app's reply lists it as your newest message on that " +
443
582
  'channel, `accepted` when the reply cannot be read, `unconfirmed` when it does not show it. ' +
@@ -446,12 +585,15 @@ export function registerChatTools(server, ctx, opts = {}) {
446
585
  'orders already submitted) and the agreement ledger, a commitment they do not carry refuses the send, and once ' +
447
586
  'the message is confirmed or accepted they are recorded in the ledger as yours (a propose or accept creates or ' +
448
587
  'advances the agreement, a notice moves it to notice-by-me); warapp_submit_turn warns when later orders break one. ' +
588
+ 'An n-way truce (a pact "p<n>"): propose or accept with `players`, or accept/notice by its id — every party must read ' +
589
+ 'the message (a game group holding all of them, or public), and a notice on one of three or more needs `rest` (ask the owner). ' +
449
590
  'Pass `automated: true` for a reply the owner did not tell you to send (e.g. an advice\'s `send`): it is refused ' +
450
591
  'unless WARAPP_CHAT_AUTOMATION is on (off by default: the owner sends replies), and even then it is confirm-gated. ' +
451
592
  'Link a territory or bonus as players see it in the official client with `[[t:<id or name>]]` / `[[b:<id or name>]]` ' +
452
593
  'in the message, or set `link_territories` to link every territory name it mentions: names resolve against the ' +
453
594
  "game's map (exact, case-insensitive; an unknown or shared name is refused, listing the ids), and the preview shows " +
454
- 'the message as rendered with its `links`. ' +
595
+ 'the message as rendered with its `links`. Every send is confirmed with the two-step preview and `confirmToken`, ' +
596
+ 'never an elicitation prompt (live, a client accepted one the owner never saw). ' +
455
597
  `${CONFIRM_INJECTION_RULE}`,
456
598
  annotations: toolAnnotations({
457
599
  title: 'Send a war.app chat message',
@@ -478,9 +620,28 @@ export function registerChatTools(server, ctx, opts = {}) {
478
620
  .optional()
479
621
  .describe('"public" (default): the whole game. "team": your team only (a team game). Not with `to`.'),
480
622
  to: z
481
- .union([z.string(), z.number()])
623
+ .union([z.string(), z.number(), z.array(z.union([z.string(), z.number()])).min(1).max(MAX_GROUP_RECIPIENTS)])
482
624
  .optional()
483
- .describe('A player (name or GameFeed id) to message privately. Omit to post to a channel.'),
625
+ .describe('A player (name or GameFeed id) to message privately, or a list of 2 to ' +
626
+ `${MAX_GROUP_RECIPIENTS} players to message together in a game group (one private conversation they all read). ` +
627
+ 'Omit to post to a channel.'),
628
+ group_name: z
629
+ .string()
630
+ .trim()
631
+ .min(1)
632
+ .max(MAX_GROUP_NAME)
633
+ .optional()
634
+ .describe('A list `to` only (a list of one player with it makes a group of you and that player): the name of the game group if one has to be created (default: the members\' names, yours first, ' +
635
+ `e.g. "Ann, Bob and Cat", or "Ann, Bob and 2 more" past ${MAX_GROUP_NAME} characters). The members see it, and ` +
636
+ 'war.app cannot rename or delete a group: choose it before confirming. An existing group of exactly these players ' +
637
+ 'is reused, keeping its name.'),
638
+ group_id: z
639
+ .number()
640
+ .int()
641
+ .positive()
642
+ .optional()
643
+ .describe('A list `to` only (a list of one player with it sends to a group of you and that player): send into this existing game group (its id, as warapp_get_chat shows a group message\'s `group`) ' +
644
+ 'instead of finding or creating one. war.app refuses it when you are not in that group.'),
484
645
  commitments: commitmentsArg,
485
646
  automated: z
486
647
  .boolean()
@@ -488,7 +649,7 @@ export function registerChatTools(server, ctx, opts = {}) {
488
649
  .describe('true when you send a reply the owner did not tell you to send (an automated reply). Refused unless ' +
489
650
  'WARAPP_CHAT_AUTOMATION is on; default false (a send the owner asked for).'),
490
651
  }),
491
- async plan({ game_id, message, channel, to, commitments, automated, link_territories }) {
652
+ async plan({ game_id, message, channel, to, group_name, group_id, commitments, automated, link_territories }) {
492
653
  // #415: an automated reply is refused with the gate off, before any request.
493
654
  const auto = automated === true;
494
655
  if (auto && (ctx.chatAutomation ?? chatAutomationMode(opts.env ?? process.env)) !== 'on') {
@@ -497,7 +658,30 @@ export function registerChatTools(server, ctx, opts = {}) {
497
658
  });
498
659
  }
499
660
  const gameId = parseGameId(game_id);
500
- const privately = to !== undefined && String(to).trim() !== '';
661
+ // A list `to` of two or more players is a game group; a list of one is a private message to that player,
662
+ // unless `group_name` or `group_id` asks for a game group (of me and that player).
663
+ const toList = Array.isArray(to) ? to.filter((x) => String(x).trim() !== '') : undefined;
664
+ const grouped = toList !== undefined && (toList.length >= 2 || (toList.length === 1 && (group_name !== undefined || group_id !== undefined)));
665
+ const single = toList ? (toList.length === 1 ? toList[0] : undefined) : Array.isArray(to) ? undefined : to;
666
+ const privately = grouped || (single !== undefined && String(single).trim() !== '');
667
+ if (toList !== undefined && toList.length === 0) {
668
+ throw new McpToolError('`to` lists no player: nothing was sent.', { hint: 'Name the players to message, or omit `to` to post to the whole game.' });
669
+ }
670
+ if (group_name !== undefined && !grouped) {
671
+ throw new McpToolError('`group_name` names a game group, which only a list of two or more players in `to` uses: nothing was sent.', {
672
+ hint: 'Pass `to` as a list of the players to message together, or drop `group_name`.',
673
+ });
674
+ }
675
+ if (group_id !== undefined && !grouped) {
676
+ throw new McpToolError('`group_id` names a game group, which only a list of two or more players in `to` uses: nothing was sent.', {
677
+ hint: 'Pass `to` as the list of the players in that group (not you), or drop `group_id`.',
678
+ });
679
+ }
680
+ if (group_id !== undefined && group_name !== undefined) {
681
+ throw new McpToolError('`group_name` is for a group this call creates, and `group_id` sends into an existing one: nothing was sent.', {
682
+ hint: 'Drop `group_name` (the group keeps its name) or drop `group_id`.',
683
+ });
684
+ }
501
685
  if (privately && channel === 'team') {
502
686
  throw new McpToolError('A private message (`to`) cannot also go to the team channel: nothing was sent.', {
503
687
  hint: 'Omit `to` to message your team, or omit `channel` to message one player privately.',
@@ -538,11 +722,54 @@ export function registerChatTools(server, ctx, opts = {}) {
538
722
  let chatChannel = CHAT_CHANNEL_PUBLIC;
539
723
  let recipient;
540
724
  let shownRecipient;
725
+ let group;
726
+ let groupsRead = true;
541
727
  if (privately) {
542
728
  if (game.settings?.privateMessaging === false) {
543
729
  throw new McpToolError(`Game ${gameId} turns private messaging off (its PrivateMessaging setting), so nothing was sent.`, { hint: 'Post to the whole game instead: the host turned private messages off.' });
544
730
  }
545
- const p = resolvePlayer(game.players, to);
731
+ }
732
+ if (grouped) {
733
+ const people = toList.map((x) => resolvePlayer(game.players, x));
734
+ const mine = people.find((p) => p.id === me);
735
+ if (mine) {
736
+ throw new McpToolError(`${untrustedText(mine.name)} (${mine.id}) is you: list only the other players in \`to\`. Nothing was sent.`, {
737
+ hint: 'The group includes you anyway: name the players to message with you.',
738
+ });
739
+ }
740
+ const twice = people.find((p, i) => people.findIndex((q) => q.id === p.id) !== i);
741
+ if (twice) {
742
+ throw new McpToolError(`Player ${twice.id} is named twice in \`to\`: nothing was sent.`, { hint: 'Name each player once.' });
743
+ }
744
+ if (meInGame === undefined) {
745
+ throw new McpToolError(`Your seat in game ${gameId} has no in-game id, so a game group cannot be made: nothing was sent.`, {
746
+ hint: 'Message each player privately instead.',
747
+ });
748
+ }
749
+ kind = 'group';
750
+ const members = people.map((p) => inGameId(p));
751
+ const recipients = people.map((p) => ({ id: p.id, name: untrustedText(p.name) }));
752
+ if (group_id !== undefined) {
753
+ // The caller names the group: no read, nothing created; war.app checks I am in it.
754
+ group = { id: group_id, name: '', members, recipients, given: true };
755
+ }
756
+ else {
757
+ const found = await existingGroup(ctx, game, meInGame, members);
758
+ groupsRead = found.read;
759
+ // A new group's name: the one given, else the members' names, mine first (raw: war.app shows it).
760
+ const given = group_name === undefined ? '' : cleanName(group_name);
761
+ const name = given || defaultGroupName([seat?.name ?? '', ...people.map((p) => p.name)]);
762
+ group = {
763
+ ...(found.group
764
+ ? { id: found.group.id, name: untrustedText(found.group.name) }
765
+ : { name, lobby: game.state === 'WaitingForPlayers' }),
766
+ members,
767
+ recipients,
768
+ };
769
+ }
770
+ }
771
+ else if (privately) {
772
+ const p = resolvePlayer(game.players, single);
546
773
  if (p.id === me) {
547
774
  throw new McpToolError(`${untrustedText(p.name)} (${p.id}) is you: a private message to yourself was not sent.`, {
548
775
  hint: 'Name another player in `to`, or omit it to post to the whole game.',
@@ -571,23 +798,37 @@ export function registerChatTools(server, ctx, opts = {}) {
571
798
  });
572
799
  }
573
800
  // A truce changes only with its partner told (D3): the check knows who reads the message.
574
- const audience = kind === 'private' ? { kind: 'private', to: shownRecipient.id } : kind === 'team' ? { kind: 'team', team: chatChannel } : { kind: 'public' };
801
+ const audience = kind === 'private'
802
+ ? { kind: 'private', to: shownRecipient.id }
803
+ : kind === 'group'
804
+ ? { kind: 'group', to: group.recipients.map((r) => r.id) }
805
+ : kind === 'team'
806
+ ? { kind: 'team', team: chatChannel }
807
+ : { kind: 'public' };
575
808
  promised = await checkMessageCommitments(ctx, game, seat, promises, audience, teamsKnown);
576
809
  }
577
- const words = kind === 'private'
578
- ? `privately to player ${shownRecipient.id} only`
579
- : kind === 'team'
580
- ? `to your team (team ${chatChannel}) only`
581
- : 'to everyone in the game';
810
+ const groupIds = group ? listIds(group.recipients.map((r) => r.id)) : '';
811
+ const words = kind === 'group'
812
+ ? `privately to ${group.recipients.length === 1 ? 'player' : 'players'} ${groupIds} only, in a game group (${group.id !== undefined ? `group ${group.id}, which exists` : 'created first'})`
813
+ : kind === 'private'
814
+ ? `privately to player ${shownRecipient.id} only`
815
+ : kind === 'team'
816
+ ? `to your team (team ${chatChannel}) only`
817
+ : 'to everyone in the game';
582
818
  const teamName = `your team (team ${chatChannel})`;
583
819
  return {
584
820
  gate: {
585
821
  action: 'warapp.send_chat',
586
- summary: kind === 'private'
587
- ? `Send a private chat message to player ${shownRecipient.id} in game ${gameId}`
588
- : kind === 'team'
589
- ? `Send a chat message to ${teamName} in game ${gameId}`
590
- : `Post a chat message to everyone in game ${gameId}`,
822
+ // Live 2026-11-30 a client accepted the elicitation with no prompt shown to the owner: every send is the
823
+ // two-step preview + confirmToken, never an elicitation (every other confirm setting still applies).
824
+ env: { ...(opts.env ?? process.env), MCP_CONFIRM_ELICITATION: 'off' },
825
+ summary: kind === 'group'
826
+ ? `Send a group chat message to ${group.recipients.length === 1 ? 'player' : 'players'} ${groupIds} in game ${gameId}`
827
+ : kind === 'private'
828
+ ? `Send a private chat message to player ${shownRecipient.id} in game ${gameId}`
829
+ : kind === 'team'
830
+ ? `Send a chat message to ${teamName} in game ${gameId}`
831
+ : `Post a chat message to everyone in game ${gameId}`,
591
832
  account,
592
833
  target: gameId,
593
834
  payload: {
@@ -596,11 +837,16 @@ export function registerChatTools(server, ctx, opts = {}) {
596
837
  text,
597
838
  channel: chatChannel,
598
839
  recipient: recipient?.id ?? null,
840
+ ...(group
841
+ ? { group: group.id ?? null, createGroup: group.id === undefined ? { name: group.name, members: group.members } : null }
842
+ : {}),
599
843
  ...(promised ? { commitments: promised.commitments } : {}),
600
844
  },
601
845
  willSend: {
602
846
  game: gameId,
603
- to: shownRecipient?.name ?? (kind === 'team' ? teamName : 'everyone in the game'),
847
+ to: group
848
+ ? group.recipients.map((r) => r.name).join(', ')
849
+ : (shownRecipient?.name ?? (kind === 'team' ? teamName : 'everyone in the game')),
604
850
  message,
605
851
  },
606
852
  preview: {
@@ -612,6 +858,28 @@ export function registerChatTools(server, ctx, opts = {}) {
612
858
  : 'Other players will see this message; it cannot be unsent.',
613
859
  game: { id: game.id, name: game.name === undefined ? null : untrustedText(game.name), state: game.state },
614
860
  ...(shownRecipient ? { recipient: shownRecipient } : {}),
861
+ ...(group
862
+ ? {
863
+ recipients: group.recipients,
864
+ group: group.given
865
+ ? { id: group.id, given: true }
866
+ : group.id !== undefined
867
+ ? { id: group.id, name: group.name, reused: true }
868
+ : { create: true, name: untrustedText(group.name) },
869
+ groupNote: (group.given
870
+ ? `The message goes into game group ${group.id}, as given (its members are not read here: war.app refuses it when you are not in that group).`
871
+ : group.id !== undefined
872
+ ? `The game's group ${group.id} holds exactly you and these players: the message goes there.`
873
+ : groupsRead
874
+ ? 'No game group of exactly you and these players exists: one is created first, named as shown, and the message goes to it.'
875
+ : "The game's groups could not be read, so a new group is created first, named as shown, and the message goes to it, even if one of exactly these players exists.") +
876
+ (group.id === undefined
877
+ ? " The new group's id is read back from the game's chat before the message goes (war.app's reply's id was refused live)."
878
+ : '') +
879
+ ` ${GROUP_UNVERIFIED}`,
880
+ ...(group.id === undefined ? { nameNote: GROUP_NAME_NOTE } : {}),
881
+ }
882
+ : {}),
615
883
  ...(links
616
884
  ? {
617
885
  rendered: untrustedBody(links.rendered),
@@ -639,6 +907,7 @@ export function registerChatTools(server, ctx, opts = {}) {
639
907
  kind,
640
908
  channel: chatChannel,
641
909
  ...(recipient ? { recipient } : {}),
910
+ ...(group ? { group } : {}),
642
911
  ...(meInGame !== undefined ? { meInGame } : {}),
643
912
  ...(auto ? { automated: true } : {}),
644
913
  account,
@@ -655,23 +924,131 @@ export function registerChatTools(server, ctx, opts = {}) {
655
924
  },
656
925
  };
657
926
  },
658
- async execute({ gameId, text, kind, channel, recipient, meInGame, account, commitments, automated }) {
927
+ async execute({ gameId, text, kind, channel, recipient, group, meInGame, account, commitments, automated }) {
659
928
  await requireApprovedAccount(ctx, account);
660
- const to = recipient?.name ?? (kind === 'team' ? `your team (team ${channel})` : 'everyone in the game');
929
+ const to = group?.recipients ?? recipient?.name ?? (kind === 'team' ? `your team (team ${channel})` : 'everyone in the game');
661
930
  const marked = automated ? { automated: true } : {};
662
- const base = { status: 'sent', game: gameId, channel: kind, to, ...marked };
931
+ // Like an unconfirmed send, a result whose message never left says what became of the commitments.
932
+ const withNotSentCommitments = (r) => commitments
933
+ ? {
934
+ ...r,
935
+ commitments: {
936
+ recorded: [],
937
+ why: 'The message was NOT sent (the game group could not be confirmed), so its commitments were not made: nothing to record.',
938
+ },
939
+ }
940
+ : r;
941
+ // A group message: the group first (created when none of exactly these players exists), its id read back from
942
+ // the game's chat, then the message to it.
943
+ let groupId = group?.id;
944
+ let created;
945
+ if (group && groupId === undefined) {
946
+ let createReply;
947
+ const notSent = (warning) => ({
948
+ status: 'unknown',
949
+ outcome: 'unknown',
950
+ game: gameId,
951
+ channel: kind,
952
+ to,
953
+ ...marked,
954
+ group: { id: null, created: 'unknown', name: untrustedText(group.name) },
955
+ warning,
956
+ });
957
+ const findIt = 'Look for it with warapp_get_chat (a group message, or its creation line, shows its `group`), then send with ' +
958
+ '`group_id` and the same `to`, so no other group is made.';
959
+ const made = await sendAndVerify({
960
+ send: async () => {
961
+ createReply = await ctx.rpc.call('CreateGameGroup', Method.CreateGameGroup, (w) => writeCreateGameGroupParams(w, { gameId, name: group.name, members: group.members }));
962
+ },
963
+ refused: (e) => new McpToolError(`war.app refused to create the game group (${GROUP_REFUSALS[e.code] ?? e.message}; war.app error ${e.code}): nothing was sent.`, { hint: 'Message each player privately instead, or post to the whole game.' }),
964
+ unanswered: (failure) => notSent(`war.app did not answer the game group's creation (${failure}), so a group may now exist, but the message was NOT sent. ${findIt}`),
965
+ // Both ids: the reply's, and the chat's (preferred: live 2026-11-30 the reply's was refused with 752).
966
+ readBack: async () => {
967
+ const replyId = createReply ? readCreateGameGroupReply(await ctx.bundle(), createReply.body) : undefined;
968
+ return { replyId, chatId: await createdGroupInChat(ctx, gameId, group.lobby ?? false, meInGame, group.members, group.name, replyId) };
969
+ },
970
+ unreadable: (failure) => notSent(`war.app accepted the game group's creation, but ${failure}, so a group may now exist, but the message was NOT sent. ${findIt}`),
971
+ classify: (ids) => ids,
972
+ });
973
+ if ('status' in made)
974
+ return withNotSentCommitments(made);
975
+ const { replyId, chatId } = made;
976
+ if (chatId === undefined && replyId === undefined) {
977
+ return withNotSentCommitments(notSent("war.app accepted the game group's creation, but neither its reply nor the game's chat names the group, so a group " +
978
+ `may now exist, but the message was NOT sent. ${findIt}`));
979
+ }
980
+ groupId = chatId ?? replyId;
981
+ created =
982
+ chatId === undefined
983
+ ? {
984
+ idFrom: 'reply',
985
+ warning: `The chat read did not show the new group, so the message went to the id war.app's reply named (${replyId}); ` +
986
+ 'live 2026-11-30 a reply\'s id was refused. Check the group with warapp_get_chat.',
987
+ }
988
+ : replyId !== undefined && replyId !== chatId
989
+ ? {
990
+ idFrom: 'chat',
991
+ replyId,
992
+ warning: `war.app's reply named group ${replyId}, but the game's chat shows group ${chatId} of exactly you and these ` +
993
+ `players under that name: the message went to group ${chatId}.`,
994
+ }
995
+ : { idFrom: 'chat' };
996
+ }
997
+ const groupOut = group
998
+ ? {
999
+ group: created
1000
+ ? { id: groupId, created: true, name: untrustedText(group.name), idFrom: created.idFrom, ...(created.replyId !== undefined ? { replyId: created.replyId } : {}) }
1001
+ : { id: groupId, created: false },
1002
+ }
1003
+ : {};
1004
+ const base = { status: 'sent', game: gameId, channel: kind, to, ...groupOut, ...marked };
663
1005
  let reply;
1006
+ let retried = 0;
664
1007
  const result = await sendAndVerify({
665
1008
  send: async () => {
666
- reply = await ctx.rpc.call('SendChat', Method.SendChat, (w) => writeSendChatParams(w, { gameId, text, channel, ...(recipient ? { recipient: recipient.id } : {}) }));
1009
+ for (;;) {
1010
+ try {
1011
+ reply = await ctx.rpc.call('SendChat', Method.SendChat, (w) => writeSendChatParams(w, {
1012
+ gameId,
1013
+ text,
1014
+ channel,
1015
+ ...(recipient ? { recipient: recipient.id } : {}),
1016
+ ...(groupId !== undefined ? { group: groupId } : {}),
1017
+ }));
1018
+ return;
1019
+ }
1020
+ catch (e) {
1021
+ // A group this call created refuses messages for a while (752): wait and send again. Only a refusal,
1022
+ // which posts nothing, is resent; never a group given by id or found, never any other failure.
1023
+ const delay = GROUP_SEND_RETRY.delaysMs[retried];
1024
+ if (!created || !(e instanceof WarappServerError) || e.code !== NOT_IN_GAME_GROUP || delay === undefined)
1025
+ throw e;
1026
+ retried += 1;
1027
+ await wait(delay);
1028
+ }
1029
+ }
667
1030
  },
668
- // A refusal is rethrown (nothing was posted; 36, too many messages, is never retried).
1031
+ // A refusal is rethrown (nothing was posted; 36, too many messages, is never retried). A group's refusal names
1032
+ // the group, and says so when this call created it (it stays).
1033
+ ...(groupId !== undefined
1034
+ ? {
1035
+ refused: (e) => new McpToolError(`war.app refused the message to game group ${groupId} (${GROUP_REFUSALS[e.code] ?? e.message}; war.app error ${e.code})` +
1036
+ (group?.id === undefined
1037
+ ? '. The group was created and stays (its members see it), but nothing was sent.'
1038
+ : ': nothing was sent.'), {
1039
+ hint: group?.id === undefined
1040
+ ? `To try again in that group, pass \`group_id: ${groupId}\` with the same \`to\`, so no other group is made.`
1041
+ : 'Check the group id with warapp_get_chat (a group message shows its `group`).',
1042
+ }),
1043
+ }
1044
+ : {}),
669
1045
  unanswered: (failure) => ({
670
1046
  status: 'unknown',
671
1047
  outcome: 'unknown',
672
1048
  game: gameId,
673
1049
  channel: kind,
674
1050
  to,
1051
+ ...groupOut,
675
1052
  ...marked,
676
1053
  warning: `war.app did not confirm this message (${failure}), so it may ` +
677
1054
  'already have been posted. Check warapp_get_chat before sending it again.',
@@ -686,11 +1063,13 @@ export function registerChatTools(server, ctx, opts = {}) {
686
1063
  // A reply this server cannot read: war.app's acceptance is all there is.
687
1064
  unreadable: () => ({ ...base, outcome: 'accepted' }),
688
1065
  classify: (lines) => {
689
- const onChannel = (l) => kind === 'private'
690
- ? l.channel === 'private' && l.to === recipient?.id
691
- : kind === 'team'
692
- ? l.channel === 'team' && l.team === channel
693
- : l.channel === 'public';
1066
+ const onChannel = (l) => kind === 'group'
1067
+ ? l.group === groupId
1068
+ : kind === 'private'
1069
+ ? l.channel === 'private' && l.to === recipient?.id
1070
+ : kind === 'team'
1071
+ ? l.channel === 'team' && l.team === channel
1072
+ : l.channel === 'public';
694
1073
  const newest = lines.filter((l) => meInGame !== undefined && l.sender === meInGame && onChannel(l)).at(-1);
695
1074
  const same = (a) => a.replace(/\s+/g, ' ').trim() === text.replace(/\s+/g, ' ').trim();
696
1075
  if (newest && same(newest.text))
@@ -703,15 +1082,19 @@ export function registerChatTools(server, ctx, opts = {}) {
703
1082
  };
704
1083
  },
705
1084
  });
1085
+ // How the new group's id was read, before anything the send itself warns of.
1086
+ const warning = [created?.warning, 'warning' in result ? result.warning : undefined].filter(Boolean).join(' ');
1087
+ const sent = retried ? { ...result, retriedAfterCreate: retried } : result;
1088
+ const out = warning ? { ...sent, warning } : sent;
706
1089
  if (!commitments)
707
- return result;
1090
+ return out;
708
1091
  // B4: a message war.app confirmed or accepted made its promises: record them as mine. Otherwise
709
1092
  // whether it went out is open, and so is whether the promises were made.
710
- if (result.outcome === 'confirmed' || result.outcome === 'accepted') {
711
- return { ...result, commitments: { recorded: await recordSent(gameId, Number(account), commitments), note: COMMITMENTS_NOTE } };
1093
+ if (out.outcome === 'confirmed' || out.outcome === 'accepted') {
1094
+ return { ...out, commitments: { recorded: await recordSent(gameId, Number(account), commitments), note: COMMITMENTS_NOTE } };
712
1095
  }
713
1096
  return {
714
- ...result,
1097
+ ...out,
715
1098
  commitments: {
716
1099
  recorded: [],
717
1100
  why: 'The message is not confirmed sent, so its commitments were not recorded. Check warapp_get_chat: if it went out, ' +