@chrischall/warapp-mcp 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,141 @@
1
+ // Territory and bonus links in chat (docs/WEB-PROTOCOL.md "Territory and bonus links in chat").
2
+ //
3
+ // war.app's chat editor shows a link as <span class="ujsChatLink" data-link="t_<id>">Name</span>
4
+ // (`b_<id>` for a bonus). Before posting, the client serializes the editor to `<a t_<id>>Name</a>` and
5
+ // rewrites that (ChatTab's send) to the bare token `<a t=<id>>` — the name and `</a>` are dropped — and the
6
+ // receiving client (ChatChunk's parser) splits a message on `<a t=…>` / `<a b=…>` and renders the id
7
+ // through the map: the territory's or bonus's name, "(???)" for an id the map lacks. The territory token
8
+ // and the bonus token are VERIFIED live (owner, 2026-11-23: sent messages read back through GameRefresh, the
9
+ // links decoded and the text rendered by name).
10
+ //
11
+ // A caller writes `[[t:<id or name>]]` / `[[b:<id or name>]]` in a message; `link_territories` also links
12
+ // every whole-word mention of a territory name. Names are other players' maps' words: callers delimit them.
13
+ import { McpToolError } from '@chrischall/mcp-utils';
14
+ import { UNTRUSTED_LIST_MAX, untrustedList, untrustedText } from './tools/common.js';
15
+ /** A caller's link marker: `[[t:…]]` or `[[b:…]]`. */
16
+ const MARKER = /\[\[([tb]):([^[\]]*)\]\]/g;
17
+ /** The wire token war.app's client sends and parses (its parser takes 1–10 characters of id). */
18
+ const TOKEN = /<a ([tb])=(\d{1,10})>/g;
19
+ /** A marker or a wire token: never auto-linked inside. */
20
+ const PROTECTED = /\[\[[tb]:[^[\]]*\]\]|<a [tb]=\d{1,10}>/g;
21
+ const kindOf = (c) => (c === 't' ? 'territory' : 'bonus');
22
+ const token = (kind, id) => `<a ${kind === 'territory' ? 't' : 'b'}=${id}>`;
23
+ const plural = (kind) => (kind === 'territory' ? 'territories' : 'bonuses');
24
+ export const hasChatLinkMarkers = (text) => new RegExp(MARKER.source).test(text);
25
+ const itemsOf = (map, kind) => (kind === 'territory' ? map.territories : map.bonuses);
26
+ function ambiguous(kind, raw, hits) {
27
+ const label = (i) => `${untrustedText(i.name)} (${i.id})`;
28
+ return new McpToolError(`${JSON.stringify(raw)} matches ${hits.length} ${plural(kind)}: ${untrustedList(hits, UNTRUSTED_LIST_MAX, label)}; nothing was sent.`, { hint: `Link the one you mean by its id: [[${kind === 'territory' ? 't' : 'b'}:<id>]].` });
29
+ }
30
+ /** A marker's target: an id on the map first, else the one case-insensitive exact name (never part of a name). */
31
+ export function resolveChatLink(map, kind, input) {
32
+ const raw = input.trim();
33
+ if (!raw)
34
+ throw new McpToolError(`Name a ${kind} in the link (an id or a name); nothing was sent.`);
35
+ const items = itemsOf(map, kind);
36
+ if (/^\d+$/.test(raw)) {
37
+ const byId = items.find((i) => i.id === Number(raw));
38
+ if (byId)
39
+ return byId;
40
+ }
41
+ const q = raw.toLowerCase();
42
+ const hits = items.filter((i) => i.name.toLowerCase() === q);
43
+ if (hits.length === 1)
44
+ return hits[0];
45
+ if (hits.length === 0) {
46
+ throw new McpToolError(`No ${kind} on this game's map matches ${JSON.stringify(raw)}; nothing was sent.`, {
47
+ hint: `Use the ${kind}'s id, or its full name as the map spells it (warapp_get_map lists them).`,
48
+ });
49
+ }
50
+ throw ambiguous(kind, raw, hits);
51
+ }
52
+ const WORD = /[\p{L}\p{N}_]/u;
53
+ const isWord = (c) => c !== undefined && WORD.test(c);
54
+ /**
55
+ * Every whole-word, case-insensitive mention of a territory name in `text`, the longest name first where names
56
+ * overlap at one place, scanning left to right (a match is never re-entered). A name two territories share is refused.
57
+ */
58
+ function autoLink(text, map, push) {
59
+ const byName = new Map();
60
+ for (const t of map.territories) {
61
+ const k = t.name.trim().toLowerCase();
62
+ if (k)
63
+ byName.set(k, [...(byName.get(k) ?? []), t]);
64
+ }
65
+ const names = [...byName.keys()].sort((a, b) => b.length - a.length);
66
+ const lower = text.toLowerCase();
67
+ let plain = '';
68
+ for (let i = 0; i < text.length;) {
69
+ let hit;
70
+ if (!isWord(text[i - 1])) {
71
+ hit = names.find((n) => lower.startsWith(n, i) && !isWord(text[i + n.length]) && n.length > 0);
72
+ }
73
+ if (hit === undefined) {
74
+ plain += text[i];
75
+ i++;
76
+ continue;
77
+ }
78
+ const hits = byName.get(hit);
79
+ if (hits.length > 1)
80
+ throw ambiguous('territory', text.slice(i, i + hit.length), hits);
81
+ const t = hits[0];
82
+ if (plain)
83
+ push(plain, plain);
84
+ plain = '';
85
+ push(token('territory', t.id), t.name, { kind: 'territory', id: t.id, name: t.name });
86
+ i += hit.length;
87
+ }
88
+ if (plain)
89
+ push(plain, plain);
90
+ }
91
+ /**
92
+ * A caller's message with its `[[t:…]]` / `[[b:…]]` markers (and, with `linkTerritories`, every territory name
93
+ * it mentions) turned into the client's link tokens. With nothing to link the message comes back unchanged.
94
+ * Throws a `McpToolError` (nothing sent) on a name that is unknown or ambiguous.
95
+ */
96
+ export function encodeChatLinks(message, map, opts = {}) {
97
+ let wire = '';
98
+ let rendered = '';
99
+ const links = [];
100
+ const push = (w, r, link) => {
101
+ wire += w;
102
+ rendered += r;
103
+ if (link)
104
+ links.push(link);
105
+ };
106
+ const plainPart = (s) => (opts.linkTerritories ? autoLink(s, map, push) : push(s, s));
107
+ let at = 0;
108
+ for (const m of message.matchAll(PROTECTED)) {
109
+ plainPart(message.slice(at, m.index));
110
+ at = m.index + m[0].length;
111
+ const marker = /^\[\[([tb]):([^[\]]*)\]\]$/.exec(m[0]);
112
+ if (marker) {
113
+ const kind = kindOf(marker[1]);
114
+ const it = resolveChatLink(map, kind, marker[2]);
115
+ push(token(kind, it.id), it.name, { kind, id: it.id, name: it.name });
116
+ }
117
+ else {
118
+ // A token already in the message passes as written (a caller's own `<a t=ID>`).
119
+ push(m[0], m[0]);
120
+ }
121
+ }
122
+ plainPart(message.slice(at));
123
+ if (!links.length)
124
+ return { wire: message, rendered: message, links: [] };
125
+ return { wire, rendered, links };
126
+ }
127
+ /**
128
+ * A received message's link tokens decoded: `text` with each token rendered as its name (an id the map lacks,
129
+ * or no map, keeps the raw token) and `links` in order. A message with no token comes back unchanged.
130
+ */
131
+ export function decodeChatLinks(text, map) {
132
+ const links = [];
133
+ const out = text.replace(TOKEN, (raw, c, digits) => {
134
+ const kind = kindOf(c);
135
+ const id = Number(digits);
136
+ const it = map ? itemsOf(map, kind).find((i) => i.id === id) : undefined;
137
+ links.push({ kind, id, name: it?.name ?? null });
138
+ return it ? it.name : raw;
139
+ });
140
+ return { text: out, links };
141
+ }
@@ -23,7 +23,7 @@ import { createHmac, randomBytes, randomUUID } from 'node:crypto';
23
23
  import { link, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
24
24
  import { join } from 'node:path';
25
25
  import { readEnvVar } from '@chrischall/mcp-utils';
26
- import { addCounts, COUNT_KEYS, MAX_RECORD_PLAYERS, talliesOf, upsertEntry, ZERO_COUNTS, } from './analysis/player-record.js';
26
+ import { addCounts, CORE_COUNT_KEYS, COUNT_KEYS, MAX_RECORD_PLAYERS, talliesOf, upsertEntry, ZERO_COUNTS, } from './analysis/player-record.js';
27
27
  import { withPathLock } from './path-lock.js';
28
28
  import { relationsDir } from './relations-store.js';
29
29
  const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
@@ -97,11 +97,13 @@ export const legacyEntryKey = (salt, gameId, agreementId) => hmac(salt, `agreeme
97
97
  const count = (v) => typeof v === 'number' && Number.isInteger(v) && v >= 0;
98
98
  const intOrNull = (v) => v === null || (typeof v === 'number' && Number.isInteger(v));
99
99
  function talliesFrom(v) {
100
- if (!isRec(v) || !COUNT_KEYS.every((k) => count(v[k])))
100
+ // The exception tallies came later: absent reads as 0, present must be a count.
101
+ if (!isRec(v) || !CORE_COUNT_KEYS.every((k) => count(v[k])) || !COUNT_KEYS.every((k) => v[k] === undefined || count(v[k])))
101
102
  return undefined;
102
103
  const out = { ...ZERO_COUNTS };
103
104
  for (const k of COUNT_KEYS)
104
- out[k] = v[k];
105
+ if (v[k] !== undefined)
106
+ out[k] = v[k];
105
107
  return out;
106
108
  }
107
109
  function entryOf(v) {
@@ -6,6 +6,10 @@
6
6
  // record (src/player-record-store.ts); nothing is sent to war.app. Reads are loose: an unusable
7
7
  // file or entry is dropped, never thrown on.
8
8
  //
9
+ // An agreement's `exceptions` (partner-approved attacks that are no break: territory ids, turns, a
10
+ // direction) may carry a short `note` — the owner's own words, never a chat message, with every player
11
+ // name scrubbed to `Player <id>` before it is written (`scrubNames`). Files written before it have none.
12
+ //
9
13
  // `commitments` (part B4): what my chat messages promised (warapp_send_chat's declared commitments,
10
14
  // never the text), recorded once a message is sent; warapp_submit_turn warns when orders break one.
11
15
  //
@@ -18,7 +22,7 @@ import { randomUUID } from 'node:crypto';
18
22
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
19
23
  import { join } from 'node:path';
20
24
  import { withPathLock } from './path-lock.js';
21
- import { AGREEMENT_STATUSES, MAX_NOTICE_TURNS, } from './analysis/relations.js';
25
+ import { AGREEMENT_STATUSES, EXCEPTION_DIRECTIONS, MAX_EXCEPTION_NOTE, MAX_EXCEPTIONS, MAX_NOTICE_TURNS, } from './analysis/relations.js';
22
26
  import { COMMITMENT_KINDS } from './analysis/commitments.js';
23
27
  import { AVOID_REASONS, intelIsEmpty } from './analysis/intel.js';
24
28
  const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
@@ -86,8 +90,32 @@ export function agreementOf(v) {
86
90
  a.enforced = v.enforced;
87
91
  if (typeof v.retaliated === 'boolean')
88
92
  a.retaliated = v.retaliated;
93
+ const exceptions = Array.isArray(v.exceptions) ? v.exceptions.map(exceptionOf).filter((e) => e !== undefined).slice(-MAX_EXCEPTIONS) : [];
94
+ if (exceptions.length)
95
+ a.exceptions = exceptions;
89
96
  return a;
90
97
  }
98
+ /** A partner-approved exception read back, or `undefined` when it is unusable (files before it have none). */
99
+ function exceptionOf(v) {
100
+ if (!isRec(v) || typeof v.id !== 'string' || !/^e\d{1,9}$/.test(v.id))
101
+ return undefined;
102
+ if (typeof v.direction !== 'string' || !EXCEPTION_DIRECTIONS.includes(v.direction))
103
+ return undefined;
104
+ const territories = ints(v.territories);
105
+ if (!territories?.length || !isInt(v.fromTurn) || !isInt(v.toTurn) || v.fromTurn > v.toTurn || !isInt(v.recordedTurn))
106
+ return undefined;
107
+ const e = {
108
+ id: v.id,
109
+ direction: v.direction,
110
+ territories,
111
+ fromTurn: v.fromTurn,
112
+ toTurn: v.toTurn,
113
+ recordedTurn: v.recordedTurn,
114
+ };
115
+ if (typeof v.note === 'string' && v.note.length)
116
+ e.note = v.note.slice(0, MAX_EXCEPTION_NOTE);
117
+ return e;
118
+ }
91
119
  const COMMITMENT_ID = /^c(\d{1,9})$/;
92
120
  /** A commitment read back, or `undefined` when it is unusable. */
93
121
  export function commitmentOf(v) {
@@ -175,7 +175,7 @@ export function planChatView(read, game, actx, view) {
175
175
  const shownRows = rows.slice(-MAX_PLAN_CHAT_MESSAGES);
176
176
  const messages = shownRows.map(({ i, r }) => {
177
177
  const l = read.lines[i];
178
- const s = shown(l, true, game.players, byInGame, read.me);
178
+ const s = shown(l, true, game.players, byInGame, read.me, game.map);
179
179
  return {
180
180
  from: s.from,
181
181
  fromId: s.fromId,
@@ -160,7 +160,9 @@ export function registerChatInboxTool(server, ctx) {
160
160
  const byInGame = playersByInGameId(game.players);
161
161
  const freshAt = read.lines.map((_, i) => i).filter((i) => fresh[i]);
162
162
  const fresh_ = freshAt.map((i) => read.lines[i]);
163
- const marked = mark_seen ? await markChatSeen(ctx, game.id, me, read, seen, channels) : undefined;
163
+ // #511: marked only once the game is listed — a game `only` filters out stays unread here, so a later
164
+ // call (or warapp_get_chat) still shows it.
165
+ const markSeen = () => (mark_seen ? markChatSeen(ctx, game.id, me, read, seen, channels) : Promise.resolve(undefined));
164
166
  // war.app's own flags for the game (from the list; null when the list was not read or left it out).
165
167
  const flags = list ? unreadChatOf(list.games, game.id) : undefined;
166
168
  // A channel war.app shows unread while this machine has seen all of it: its newest message from another player.
@@ -182,6 +184,7 @@ export function registerChatInboxTool(server, ctx) {
182
184
  if (fresh_.length)
183
185
  gamesWithNew++;
184
186
  if (!fresh_.length && !warappOnlyAt.length && !(flags && channels.some((c) => flags[CHANNEL_FLAG[c]]))) {
187
+ await markSeen();
185
188
  quiet.push(id);
186
189
  continue;
187
190
  }
@@ -201,8 +204,9 @@ export function registerChatInboxTool(server, ctx) {
201
204
  filtered.push(id);
202
205
  continue;
203
206
  }
207
+ const marked = await markSeen();
204
208
  const messages = shownAt.map((i) => ({
205
- ...shown(read.lines[i], fresh[i], game.players, byInGame, me),
209
+ ...shown(read.lines[i], fresh[i], game.players, byInGame, me, game.map),
206
210
  ...readingFields(reading(i, fresh[i])),
207
211
  ...(fresh[i] ? {} : { seenLocally: true }),
208
212
  }));
@@ -8,6 +8,7 @@ import { CHAT_CHANNELS, feedChatLines, fillFromFeed, mergeChatLines, oldestId, r
8
8
  import { advanceCursor, markedChannels, markNew, readChatCursor, unreadCounts, writeChatCursor, } from '../chat-cursor.js';
9
9
  import { parseGameId } from '../client.js';
10
10
  import { inGameId, inGameOf, playersByInGameId } from '../live.js';
11
+ import { decodeChatLinks, encodeChatLinks, hasChatLinkMarkers } from '../chat-links.js';
11
12
  import { CHAT_CHANNEL_PUBLIC, Method, writeGameRefreshParams, writeRetrieveChatParams, writeRetrievePrivateMessageHistoryParams, writeSendChatParams, } from '../protocol/methods.js';
12
13
  import { carriesTeam } from '../teams.js';
13
14
  import { gameIdArg, readAnnotations, respond, UNTRUSTED_PREVIEW_NOTE, untrustedBody, untrustedDescription, untrustedText, } from './common.js';
@@ -23,6 +24,9 @@ import { AUTOMATED_CHAT_OFF, chatAutomationMode } from '../chat-automation.js';
23
24
  import { resolveTeams } from './team-source.js';
24
25
  const DEFAULT_LIMIT = 50;
25
26
  const MAX_CHAT_LENGTH = 2000;
27
+ /** The send preview's note on links: what goes out, and what is verified. */
28
+ 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
+ 'the map. Territory and bonus links are verified live (2026-11-23).';
26
30
  /** The UNVERIFIED notes a chat result carries, by source. */
27
31
  export const CHAT_SOURCE_NOTES = {
28
32
  web: "Read from the web client's GameRefresh reply; its channel, recipient and turn fields come from the client " +
@@ -270,7 +274,7 @@ export async function markChatSeen(ctx, gameId, me, read, cursor, channels) {
270
274
  }
271
275
  const playerOf = (players, byInGame, id) => byInGame.get(id) ?? players.find((p) => p.id === id);
272
276
  /** A line as the tool shows it: players by GameFeed id, names and the text delimited. */
273
- export function shown(line, isNew, players, byInGame, me) {
277
+ export function shown(line, isNew, players, byInGame, me, map) {
274
278
  let from = null;
275
279
  let fromId = null;
276
280
  if (line.sender !== null) {
@@ -286,10 +290,13 @@ export function shown(line, isNew, players, byInGame, me) {
286
290
  const p = playerOf(players, byInGame, line.to);
287
291
  to = { id: p?.id ?? null, name: p ? untrustedText(p.name) : null };
288
292
  }
293
+ // Territory and bonus links (`<a t=ID>` / `<a b=ID>`): rendered as their names, listed in `links`.
294
+ const decoded = decodeChatLinks(line.text, map);
289
295
  return {
290
296
  from,
291
297
  fromId,
292
- text: untrustedBody(line.text),
298
+ text: untrustedBody(decoded.text),
299
+ ...(decoded.links.length ? { links: decoded.links.map((l) => ({ ...l, name: l.name === null ? null : untrustedText(l.name) })) } : {}),
293
300
  ...(line.time !== undefined ? { time: line.time } : {}),
294
301
  turn: line.turn,
295
302
  channel: line.channel,
@@ -360,7 +367,7 @@ export function registerChatTools(server, ctx, opts = {}) {
360
367
  const picked = read.lines.map((l, i) => [l, fresh[i], i]).filter(([l]) => wanted(l));
361
368
  // #415: each message another player sent is labelled, and an unread one advised on (this machine's logs only).
362
369
  const reading = chatReader(read.lines, game, me, await chatAdviceContext(ctx, game, me));
363
- const messages = picked.slice(-n).map(([l, isNew, i]) => ({ ...shown(l, isNew, game.players, byInGame, me), ...readingFields(reading(i, isNew)) }));
370
+ const messages = picked.slice(-n).map(([l, isNew, i]) => ({ ...shown(l, isNew, game.players, byInGame, me, game.map), ...readingFields(reading(i, isNew)) }));
364
371
  const marked = mark_seen
365
372
  ? await markChatSeen(ctx, game.id, me, read, cursor, channel === undefined || channel === 'all' ? [...CHAT_CHANNELS] : [channel])
366
373
  : undefined;
@@ -422,6 +429,10 @@ export function registerChatTools(server, ctx, opts = {}) {
422
429
  'advances the agreement, a notice moves it to notice-by-me); warapp_submit_turn warns when later orders break one. ' +
423
430
  'Pass `automated: true` for a reply the owner did not tell you to send (e.g. an advice\'s `send`): it is refused ' +
424
431
  'unless WARAPP_CHAT_AUTOMATION is on (off by default: the owner sends replies), and even then it is confirm-gated. ' +
432
+ 'Link a territory or bonus as players see it in the official client with `[[t:<id or name>]]` / `[[b:<id or name>]]` ' +
433
+ 'in the message, or set `link_territories` to link every territory name it mentions: names resolve against the ' +
434
+ "game's map (exact, case-insensitive; an unknown or shared name is refused, listing the ids), and the preview shows " +
435
+ 'the message as rendered with its `links`. ' +
425
436
  `${CONFIRM_INJECTION_RULE}`,
426
437
  annotations: toolAnnotations({
427
438
  title: 'Send a war.app chat message',
@@ -432,7 +443,17 @@ export function registerChatTools(server, ctx, opts = {}) {
432
443
  }),
433
444
  inputSchema: z.object({
434
445
  game_id: gameIdArg,
435
- message: z.string().trim().min(1).max(MAX_CHAT_LENGTH).describe('The message text.'),
446
+ message: z
447
+ .string()
448
+ .trim()
449
+ .min(1)
450
+ .max(MAX_CHAT_LENGTH)
451
+ .describe('The message text. `[[t:<id or name>]]` links a territory, `[[b:<id or name>]]` a bonus (shown as its name).'),
452
+ link_territories: z
453
+ .boolean()
454
+ .optional()
455
+ .describe('true: also link every whole-word mention of a territory name in the message, repeats included (the longest ' +
456
+ 'name where names overlap; never inside a [[…]] link). Default false.'),
436
457
  channel: z
437
458
  .enum(['public', 'team'])
438
459
  .optional()
@@ -448,7 +469,7 @@ export function registerChatTools(server, ctx, opts = {}) {
448
469
  .describe('true when you send a reply the owner did not tell you to send (an automated reply). Refused unless ' +
449
470
  'WARAPP_CHAT_AUTOMATION is on; default false (a send the owner asked for).'),
450
471
  }),
451
- async plan({ game_id, message, channel, to, commitments, automated }) {
472
+ async plan({ game_id, message, channel, to, commitments, automated, link_territories }) {
452
473
  // #415: an automated reply is refused with the gate off, before any request.
453
474
  const auto = automated === true;
454
475
  if (auto && (ctx.chatAutomation ?? chatAutomationMode(opts.env ?? process.env)) !== 'on') {
@@ -466,7 +487,17 @@ export function registerChatTools(server, ctx, opts = {}) {
466
487
  // Read the game for every message (#130): one GameFeed does not know is refused here. Its
467
488
  // settings say whether private messages are allowed. Commitments are checked on a plan: the map too.
468
489
  const promises = commitments?.length ? commitments : undefined;
469
- const feed = await ctx.client.getGame(gameId, { map: promises !== undefined, settings: true });
490
+ // Territory and bonus links resolve against the map (src/chat-links.ts); a message with none goes as written.
491
+ const linking = link_territories === true || hasChatLinkMarkers(message);
492
+ const feed = await ctx.client.getGame(gameId, { map: promises !== undefined || linking, settings: true });
493
+ const linked = linking ? encodeChatLinks(message, mapOf(feed), { linkTerritories: link_territories === true }) : undefined;
494
+ const links = linked?.links.length ? linked : undefined;
495
+ const text = links ? links.wire : message;
496
+ if (text.length > MAX_CHAT_LENGTH) {
497
+ throw new McpToolError(`With its links the message is ${text.length} characters, over ${MAX_CHAT_LENGTH}: nothing was sent.`, {
498
+ hint: 'Shorten the message or link fewer places.',
499
+ });
500
+ }
470
501
  // The message goes out as whoever is signed in: bind that account, so an
471
502
  // approval given while one account was signed in never posts as another (#133:
472
503
  // refused when it cannot be read, as every write is).
@@ -543,7 +574,7 @@ export function registerChatTools(server, ctx, opts = {}) {
543
574
  payload: {
544
575
  method: 'SendChat',
545
576
  gameId,
546
- text: message,
577
+ text,
547
578
  channel: chatChannel,
548
579
  recipient: recipient?.id ?? null,
549
580
  ...(promised ? { commitments: promised.commitments } : {}),
@@ -562,6 +593,13 @@ export function registerChatTools(server, ctx, opts = {}) {
562
593
  : 'Other players will see this message; it cannot be unsent.',
563
594
  game: { id: game.id, name: game.name === undefined ? null : untrustedText(game.name), state: game.state },
564
595
  ...(shownRecipient ? { recipient: shownRecipient } : {}),
596
+ ...(links
597
+ ? {
598
+ rendered: untrustedBody(links.rendered),
599
+ links: links.links.map((l) => ({ ...l, name: l.name === null ? null : untrustedText(l.name) })),
600
+ linksNote: LINKS_NOTE,
601
+ }
602
+ : {}),
565
603
  ...(auto ? { automated: true, automatedNote: 'An automated reply (WARAPP_CHAT_AUTOMATION is on): the owner did not ask for this message.' } : {}),
566
604
  ...(promised
567
605
  ? {
@@ -578,7 +616,7 @@ export function registerChatTools(server, ctx, opts = {}) {
578
616
  },
579
617
  state: {
580
618
  gameId,
581
- text: message,
619
+ text,
582
620
  kind,
583
621
  channel: chatChannel,
584
622
  ...(recipient ? { recipient } : {}),
@@ -107,7 +107,8 @@ export function registerCheckPlanTool(server, ctx) {
107
107
  'differ from the default plan by design. ' +
108
108
  'In a free-for-all with a truce in force (the agreement ledger), its partner is still tried — `safe` is safe ' +
109
109
  'against a break too — each reply that attacks a territory a truce covers is marked `breaksTruce`, and ' +
110
- '`safeIfTruceHolds` is the verdict over the other replies (null when every reply is a break). ' +
110
+ '`safeIfTruceHolds` is the verdict over the other replies (null when every reply is a break); a partner-approved ' +
111
+ 'truce exception on this turn opens its territories (no break) and is listed under `relations`. ' +
111
112
  `Refuses outside a turn phase. ${BRIDGE_NOTE} Read-only on ` +
112
113
  'war.app; it never submits orders.'),
113
114
  _meta: lookupMeta(['check my plan', 'stress test my orders', 'what can my opponent do to this turn', 'is this plan safe']),
@@ -646,6 +647,18 @@ export function registerCheckPlanTool(server, ctx) {
646
647
  }
647
648
  : {}),
648
649
  summary,
650
+ // Partner-approved truce exceptions on this turn: normal targets (mine), or open to the partner (theirs).
651
+ ...(binding.some((r) => r.exceptions?.length)
652
+ ? {
653
+ relations: binding
654
+ .filter((r) => r.exceptions?.length)
655
+ .map((r) => ({
656
+ player: who(r.player),
657
+ ...(r.agreement ? { agreement: r.agreement } : {}),
658
+ exceptions: r.exceptions.map((e) => ({ direction: e.direction, territories: e.territories.map(name) })),
659
+ })),
660
+ }
661
+ : {}),
649
662
  exact: report.exact,
650
663
  // Where the teams came from (GameFeed, else the game list), in a team game only.
651
664
  ...(teamSource !== 'none' ? { teamSource } : {}),
@@ -10,7 +10,7 @@ import { z } from 'zod';
10
10
  import { boardIncome, incomeRules, trackGame, trackOpponents } from '../analysis/index.js';
11
11
  import { agreementChange } from '../analysis/commitments.js';
12
12
  import { playerRecord, recordDelta, recordEntryFor } from '../analysis/player-record.js';
13
- import { AGREEMENT_STATUSES, agreementState, breachWatch, MAX_NOTICE_TURNS, newAgreement, OPENING_STATUSES, partyRefusal, scopeRefusal, tacitTruces, TERMINAL_STATUSES, transitionAgreement, TRUCE_OUTGROW_RATIO, trust, truceEndgame, } from '../analysis/relations.js';
13
+ import { AGREEMENT_STATUSES, agreementState, breachWatch, EXCEPTION_DIRECTIONS, MAX_EXCEPTION_NOTE, MAX_NOTICE_TURNS, newAgreement, OPENING_STATUSES, partyRefusal, scopeRefusal, tacitTruces, TERMINAL_STATUSES, transitionAgreement, TRUCE_OUTGROW_RATIO, trust, truceEndgame, withExceptions, } from '../analysis/relations.js';
14
14
  import { AVOID_REASONS, emptyIntel, INCOME_STALE_TURNS, intelIsEmpty } from '../analysis/intel.js';
15
15
  import { boardStateFromLive } from '../live.js';
16
16
  import { entryKey, legacyEntryKey, playerRecordEnabled, playerRecordState, readPlayerRecord, updatePlayerRecord } from '../player-record-store.js';
@@ -27,6 +27,7 @@ import { recordProfile } from './profile-hook.js';
27
27
  import { resolveBonus, resolvePlayer, resolveTerritory } from './resolve.js';
28
28
  import { boardHistory, plannerSettings } from './turn.js';
29
29
  import { captureObservation } from './decision-capture.js';
30
+ import { scrubNames } from '../decision-log.js';
30
31
  import { resolveTeamsFor } from './team-source.js';
31
32
  const VIEWS = ['compact', 'full'];
32
33
  const MAX_SCOPE_ITEMS = 200;
@@ -165,9 +166,27 @@ function agreementView(a, game, map, turn, rung) {
165
166
  },
166
167
  ...(a.enforced !== undefined ? { enforced: a.enforced } : {}),
167
168
  ...(a.retaliated !== undefined ? { retaliated: a.retaliated } : {}),
169
+ ...(a.exceptions?.length
170
+ ? {
171
+ exceptions: a.exceptions.map((e) => ({
172
+ id: e.id,
173
+ direction: e.direction,
174
+ territories: e.territories.map(name),
175
+ turns: [e.fromTurn, e.toTurn],
176
+ inForce: e.fromTurn <= turn && turn <= e.toTurn,
177
+ recordedTurn: e.recordedTurn,
178
+ ...(e.note !== undefined ? { note: untrustedText(e.note) } : {}),
179
+ })),
180
+ }
181
+ : {}),
168
182
  ...(rung === 'full' ? { history: a.history } : {}),
169
183
  };
170
184
  }
185
+ /** An exception's note as stored: trimmed, player names scrubbed (`Player <id>`), capped; absent when empty. */
186
+ export function exceptionNote(note, game) {
187
+ const t = note?.trim();
188
+ return t ? scrubNames(t, game.players).slice(0, MAX_EXCEPTION_NOTE) : undefined;
189
+ }
171
190
  /** An entry as a result shows it: everything but its key. */
172
191
  const entryView = ({ key: _key, ...rest }) => rest;
173
192
  /** The reliability facts on record for `partner` (and its entries), or why there are none. */
@@ -266,6 +285,48 @@ export async function recordBrokenByMe(o) {
266
285
  return o.agreements.map((agreement) => ({ agreement, ledger: 'refused', why: e.message }));
267
286
  }
268
287
  }
288
+ /**
289
+ * `warapp_submit_turn`'s `partner_approved`: record, once the orders are committed, a one-turn `mine`
290
+ * exception on each agreement the orders hit (its territories hit, the note already scrubbed) — under the
291
+ * ledger's lock, then the partner's player record (D5: an exception, never a break). Never throws.
292
+ */
293
+ export async function recordPartnerApproved(o) {
294
+ const { dir, env, game, me, map, turn } = o;
295
+ const graph = graphOf(map);
296
+ const refused = (why) => o.exceptions.map((x) => ({ agreement: x.agreement, territories: [...x.territories], ledger: 'refused', why }));
297
+ try {
298
+ return await withLedgerLock(dir, game.id, me.id, async () => {
299
+ const read = await readLedgerForWrite(dir, game.id, me.id);
300
+ if (read === null || read === 'unreadable')
301
+ return refused(read === null ? 'no ledger for this game' : 'the ledger exists but cannot be read');
302
+ let ledger = read;
303
+ const out = [];
304
+ for (const x of o.exceptions) {
305
+ const territories = [...new Set(x.territories)].sort((a, b) => a - b);
306
+ const found = ledger.agreements.find((a) => a.id === x.agreement);
307
+ if (!found) {
308
+ out.push({ agreement: x.agreement, territories, ledger: 'refused', why: 'not in the ledger' });
309
+ continue;
310
+ }
311
+ const ex = { direction: 'mine', territories, fromTurn: turn, toTurn: turn, recordedTurn: turn, ...(x.note ? { note: x.note } : {}) };
312
+ const moved = withExceptions(found, [ex]);
313
+ const rest = ledger.agreements.filter((a) => a.id !== found.id);
314
+ const next = { ...ledger, agreements: [...rest, moved] };
315
+ if (!(await writeLedger(dir, next))) {
316
+ out.push({ agreement: x.agreement, territories, ledger: 'refused', why: 'the ledger could not be written' });
317
+ continue;
318
+ }
319
+ ledger = next;
320
+ const playerRecord = await updateAgreementRecord({ dir, env, game, me, map, graph, agreement: moved, before: found, created: false, others: rest });
321
+ out.push({ agreement: x.agreement, territories, ledger: 'recorded', id: moved.exceptions.at(-1).id, playerRecord });
322
+ }
323
+ return out;
324
+ });
325
+ }
326
+ catch (e) {
327
+ return refused(e.message);
328
+ }
329
+ }
269
330
  /**
270
331
  * B4 (warapp_send_chat, once a message is sent): record its declared commitments in the ledger as
271
332
  * mine, under the ledger's lock — a propose, accept or notice re-applied to the ledger as it now stands
@@ -336,7 +397,7 @@ export function registerRelationsTools(server, ctx, opts = {}) {
336
397
  'its state this turn (`proposed`, `active`, in `notice` with the turn it ends, or `over` and why: ended, broken, ' +
337
398
  'the partner eliminated or turned AI, only two players left, its end condition met, its notice run), and for a ' +
338
399
  'live one: watch `flags` from your own board history — `broken` (the partner took or attacked a covered territory ' +
339
- 'of yours), `cap-exceeded` (a partner stack on the covered border above the agreed cap), `massing` (its visible ' +
400
+ 'of yours — not one a `theirs` exception you recorded allowed that turn), `cap-exceeded` (a partner stack on the covered border above the agreed cap), `massing` (its visible ' +
340
401
  'armies near the covered border grew two turns running, or an event the fog leaves ambiguous), `outgrowing` (its ' +
341
402
  `estimated income above ${TRUCE_OUTGROW_RATIO}× yours) and \`kept\` (quiet turns) — and \`trust\`: \`clear\`, or \`watch\` ` +
342
403
  'on any flag but kept, on their notice, and in the endgame (no other opponent still a match for either of you). ' +
@@ -439,7 +500,7 @@ export function registerRelationsTools(server, ctx, opts = {}) {
439
500
  });
440
501
  server.registerTool('warapp_record_agreement', {
441
502
  title: 'Record an agreement in a war.app game',
442
- _meta: mintMeta('change', ['record a truce', 'we agreed a truce', 'they broke the truce', 'give notice']),
503
+ _meta: mintMeta('change', ['record a truce', 'we agreed a truce', 'they broke the truce', 'give notice', 'truce exception']),
443
504
  description: untrustedDescription('Record a truce you made, proposed or received in a war.app (Warzone) free-for-all, or a change to one, in this ' +
444
505
  "machine's agreement ledger. Nothing is sent to war.app or to any player (so there is no confirmation " +
445
506
  'step): it records what was agreed, so warapp_get_relations can watch the board for it. Create one with ' +
@@ -449,7 +510,12 @@ export function registerRelationsTools(server, ctx, opts = {}) {
449
510
  'new `status`: agreed, notice-by-me, notice-by-them, ended, broken-by-them, broken-by-me (terms change only ' +
450
511
  'while proposed; an ended or broken agreement takes nothing more but `retaliated` after broken-by-me). Refused ' +
451
512
  'for a partner who is you, an AI, out of the game or your teammate, in a 1v1 or once two players remain, and for ' +
452
- 'a territory or bonus not on the map. An agreement exists only because you record it here: chat is never read ' +
513
+ 'a territory or bonus not on the map. `exceptions` records partner-approved exceptions that are no break, in any ' +
514
+ 'status (agreed included): each lists `territories`, `turns` (one turn or [from, to], inclusive), `direction` ' +
515
+ '(mine: the partner agreed I may attack its covered territories there — warapp_plan_turn targets them and ' +
516
+ 'warapp_submit_turn sends the attack without break_agreement; theirs: I agreed it may attack or take mine — ' +
517
+ 'warapp_get_relations raises no `broken` flag for it) and an optional `note` (player names scrubbed). The player ' +
518
+ 'record counts exceptions apart from breaks. An agreement exists only because you record it here: chat is never read ' +
453
519
  'into one. With the cross-game player record on (owner decision D5: on unless WARAPP_PLAYER_RECORD=off, local and ' +
454
520
  'hosted), each agreement is also kept per partner under a salted hash, name-free (no id, no name, no game, no ' +
455
521
  'message): the format, the turns agreed and ended, the shape of the terms, the outcome, a break\'s turn, flag and ' +
@@ -470,6 +536,21 @@ export function registerRelationsTools(server, ctx, opts = {}) {
470
536
  until_player_out: playerRef.optional().describe('It ends when this player (name or id) is out of the game.'),
471
537
  against: playerRef.optional().describe('The player (name or id) it is aimed at, when it names one.'),
472
538
  retaliated: z.boolean().optional().describe('After broken-by-me: whether the partner retaliated.'),
539
+ exceptions: z
540
+ .array(z.object({
541
+ territories: z.array(playerRef).min(1).max(MAX_SCOPE_ITEMS).describe('The territories (names or ids) the exception opens.'),
542
+ turns: z
543
+ .union([z.coerce.number().int().min(1), z.array(z.coerce.number().int().min(1)).length(2)])
544
+ .describe('One turn, or [from, to] (inclusive).'),
545
+ direction: z
546
+ .enum(EXCEPTION_DIRECTIONS)
547
+ .optional()
548
+ .describe('mine (default): the partner agreed I may attack these; theirs: I agreed the partner may attack or take these of mine.'),
549
+ note: z.string().max(MAX_EXCEPTION_NOTE).optional().describe("The owner's own words on what was agreed (player names are scrubbed)."),
550
+ }))
551
+ .max(10)
552
+ .optional()
553
+ .describe('Partner-approved exceptions to add: attacks the partner agreed to, which are no break. Any status.'),
473
554
  }),
474
555
  }, async (args) => {
475
556
  if (!ctx.dataDir) {
@@ -530,6 +611,21 @@ export function registerRelationsTools(server, ctx, opts = {}) {
530
611
  t.against = against;
531
612
  return t;
532
613
  };
614
+ /** The exceptions `args` add, resolved and checked: territories by id, turns in order, the note scrubbed. */
615
+ const exceptionsFrom = () => (args.exceptions ?? []).map((x) => {
616
+ const [fromTurn, toTurn] = typeof x.turns === 'number' ? [x.turns, x.turns] : [x.turns[0], x.turns[1]];
617
+ if (fromTurn > toTurn)
618
+ refuse(`An exception's turns [${fromTurn}, ${toTurn}] run backwards`, 'Give [from, to] with from ≤ to, or one turn.');
619
+ const note = exceptionNote(x.note, game);
620
+ return {
621
+ direction: x.direction ?? 'mine',
622
+ territories: [...new Set(x.territories.map((t) => resolveTerritory(map, t).id))].sort((a, b) => a - b),
623
+ fromTurn,
624
+ toTurn,
625
+ recordedTurn: turn,
626
+ ...(note ? { note } : {}),
627
+ };
628
+ });
533
629
  /** The change `args` make to `ledger`: the agreement after it, and as it stood. Refuses what cannot be recorded. */
534
630
  const change = (ledger) => {
535
631
  let agreement;
@@ -560,8 +656,8 @@ export function registerRelationsTools(server, ctx, opts = {}) {
560
656
  before = found;
561
657
  if (args.with !== undefined && resolvePlayer(game.players, args.with).id !== agreement.with)
562
658
  refuse(`Agreement ${agreement.id} is with player ${agreement.with}`, 'Omit `with` when updating, or record a new agreement.');
563
- if (args.status === undefined && !termsGiven && args.retaliated === undefined)
564
- refuse('Nothing to record: give a new `status`, terms, or `retaliated`', 'Pass the status the agreement moved to.');
659
+ if (args.status === undefined && !termsGiven && args.retaliated === undefined && !args.exceptions?.length)
660
+ refuse('Nothing to record: give a new `status`, terms, `retaliated` or `exceptions`', 'Pass the status the agreement moved to.');
565
661
  if (termsGiven) {
566
662
  if (agreement.status !== 'proposed-by-me' && agreement.status !== 'proposed-by-them')
567
663
  refuse(`The terms of agreement ${agreement.id} (${agreement.status}) can no longer change`, 'End it and record a new agreement with the new terms.');
@@ -585,6 +681,8 @@ export function registerRelationsTools(server, ctx, opts = {}) {
585
681
  agreement = { ...agreement, retaliated: args.retaliated };
586
682
  }
587
683
  }
684
+ if (args.exceptions?.length)
685
+ agreement = withExceptions(agreement, exceptionsFrom());
588
686
  return { agreement, before, created };
589
687
  };
590
688
  const updateRecord = (agreement, before, created, others) => updateAgreementRecord({ dir, env, game, me, map, graph, agreement, before, created, others });