@chrischall/warapp-mcp 0.24.0 → 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.
@@ -5,18 +5,20 @@
5
5
  // and hosted, name-free per-agreement entries and tallies) — nothing is sent to war.app or to any
6
6
  // player, so it is not confirm-gated. An agreement exists only because the player recorded it here with
7
7
  // structured terms: chat is never parsed into one, and words change no flag — only the board does.
8
- import { modRelationsView, readModAlliances } from './mod-alliances.js';
8
+ import { modPacts, modRelationsView, readModAlliances } from './mod-alliances.js';
9
+ import { boardCardsInEffect } from './card-effects.js';
9
10
  import { McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
10
11
  import { z } from 'zod';
11
12
  import { boardIncome, incomeRules, trackGame, trackOpponents } from '../analysis/index.js';
12
13
  import { agreementChange } from '../analysis/commitments.js';
13
14
  import { playerRecord, recordDelta, recordEntryFor } from '../analysis/player-record.js';
14
- import { AGREEMENT_STATUSES, agreementState, breachWatch, capSelfCheck, EXCEPTION_DIRECTIONS, MAX_CAPS, MAX_EXCEPTION_NOTE, MAX_NOTICE_TURNS, newAgreement, OPENING_STATUSES, partyRefusal, scopeRefusal, tacitTruces, TERMINAL_STATUSES, transitionAgreement, TRUCE_OUTGROW_RATIO, trust, truceEndgame, withCaps, withExceptions, } from '../analysis/relations.js';
15
+ import { AGREEMENT_STATUSES, agreementState, breachWatch, capSelfCheck, EXCEPTION_DIRECTIONS, MAX_CAPS, MAX_EXCEPTION_NOTE, MAX_NOTICE_TURNS, MAX_PARTIES, newAgreement, PACT_RESTS, OPENING_STATUSES, partyRefusal, scopeRefusal, tacitTruces, TERMINAL_STATUSES, transitionAgreement, TRUCE_OUTGROW_RATIO, trust, truceEndgame, withCaps, withExceptions, } from '../analysis/relations.js';
16
+ import { pactState, pactsWithoutMe, pactViews, pairwiseView } from '../analysis/pacts.js';
15
17
  import { AVOID_REASONS, emptyIntel, INCOME_STALE_TURNS, intelIsEmpty } from '../analysis/intel.js';
16
18
  import { boardStateFromLive } from '../live.js';
17
19
  import { entryKey, legacyEntryKey, playerRecordEnabled, playerRecordState, readPlayerRecord, updatePlayerRecord } from '../player-record-store.js';
18
- import { emptyLedger, nextAgreementId, nextCommitmentId, readLedger, readLedgerForWrite, withLedgerLock, writeLedger } from '../relations-store.js';
19
- import { isTeamGame, teammatesOf } from '../teams.js';
20
+ import { emptyLedger, ledgerTruces, nextAgreementId, nextCommitmentId, nextPactId, readLedger, readLedgerForWrite, withLedgerLock, writeLedger, } from '../relations-store.js';
21
+ import { carriesTeam, isTeamGame, teammatesOf } from '../teams.js';
20
22
  import { readBoardHistory, readCachedOrders, writeBoardCache } from '../trend.js';
21
23
  import { writeGameRecord } from '../replay.js';
22
24
  import { currentTurn, gameIdArg, graphOf, namer, readAnnotations, respond, untrustedDescription, untrustedText, viewArg } from './common.js';
@@ -128,18 +130,33 @@ export function scopeFrom(map, territories, bonuses, nothing = 'nothing was reco
128
130
  return { bonuses: [...new Set(bonuses.map((b) => resolveBonus(map, b).id))].sort((a, b) => a - b) };
129
131
  return 'all';
130
132
  }
131
- /** An agreement as a result shows it: players by id with a delimited name, territories and bonuses by id and name. */
132
- function agreementView(a, game, map, turn, rung) {
133
+ /**
134
+ * An agreement as a result shows it: players by id with a delimited name, territories and bonuses by id and name.
135
+ * #680: a pact (`parties`) adds its parties, source, whether it includes me now (`me`), each party's notice and
136
+ * those gone; its state is the pact's (`pactState`).
137
+ */
138
+ function agreementView(a, game, map, turn, rung, me) {
133
139
  const name = namer(map);
134
140
  const player = (id) => {
135
141
  const p = game.players.find((x) => x.id === id);
136
142
  return { id, name: p ? untrustedText(p.name) : null };
137
143
  };
138
144
  const scope = a.terms.scope;
139
- const state = agreementState(a, turn, relationPlayers(game.players));
145
+ const pact = a.parties !== undefined ? pactState(a, turn, relationPlayers(game.players), me ?? 0) : undefined;
146
+ const state = pact ?? agreementState(a, turn, relationPlayers(game.players));
140
147
  return {
141
148
  id: a.id,
142
149
  with: player(a.with),
150
+ ...(pact
151
+ ? {
152
+ parties: a.parties.map(player),
153
+ source: a.source ?? 'ledger',
154
+ includesMe: pact.includesMe,
155
+ ...(pact.leaving.length ? { leaving: pact.leaving.map((l) => ({ player: player(l.player), endsTurn: l.endsTurn })) } : {}),
156
+ ...(pact.left.length && pact.phase !== 'over' ? { left: pact.left.map(player) } : {}),
157
+ ...(a.notices?.length ? { notices: a.notices.map((n) => ({ player: player(n.player), turn: n.turn, ...(n.rest ? { rest: n.rest } : {}) })) } : {}),
158
+ }
159
+ : {}),
143
160
  kind: a.kind,
144
161
  status: a.status,
145
162
  state: state.phase,
@@ -273,6 +290,31 @@ export async function updateAgreementRecord(o) {
273
290
  return { delta: recordDelta(before, agreement), entries: [...again, entry] };
274
291
  }, env, now);
275
292
  }
293
+ /**
294
+ * #680: the cross-game record for one change to a pact. A pact I am a party to keeps today's record per partner:
295
+ * one entry per other party, the change read as the pairwise agreement it amounts to (`pairwiseView`); a pact
296
+ * without me touches no record (`not-mine`). `failed` when any partner's write failed.
297
+ */
298
+ export async function updatePactRecord(o) {
299
+ const { pact, before, me } = o;
300
+ const parties = pact.parties ?? [];
301
+ if (!parties.includes(me.id))
302
+ return 'not-mine';
303
+ if (!playerRecordEnabled(o.env))
304
+ return 'off';
305
+ let result = 'updated';
306
+ for (const partner of parties.filter((p) => p !== me.id)) {
307
+ const r = await updateAgreementRecord({
308
+ ...o,
309
+ agreement: pairwiseView(pact, me.id, partner),
310
+ before: before ? pairwiseView(before, me.id, partner) : undefined,
311
+ others: [],
312
+ });
313
+ if (r === 'failed')
314
+ result = 'failed';
315
+ }
316
+ return result;
317
+ }
276
318
  /**
277
319
  * B2 (`warapp_submit_turn`'s `break_agreement`): mark each agreement broken by me on `turn`, through the
278
320
  * same path as warapp_record_agreement — the ledger's transition under its lock, then the partner's
@@ -290,7 +332,26 @@ export async function recordBrokenByMe(o) {
290
332
  }
291
333
  let ledger = read;
292
334
  const out = [];
293
- for (const id of o.agreements) {
335
+ // #680: a pact's views share its id: each id is marked once.
336
+ for (const id of [...new Set(o.agreements)]) {
337
+ const pact = ledger.pacts?.find((a) => a.id === id);
338
+ if (pact) {
339
+ // #680: breaking the truce with one partner of a pact breaks the whole pact (record a new one among the rest).
340
+ const moved = transitionAgreement(pact, 'broken-by-me', turn);
341
+ if ('refused' in moved) {
342
+ out.push({ agreement: id, ledger: 'refused', why: moved.refused });
343
+ continue;
344
+ }
345
+ const next = { ...ledger, pacts: [...(ledger.pacts ?? []).filter((a) => a.id !== id), moved.agreement] };
346
+ if (!(await writeLedger(dir, next))) {
347
+ out.push({ agreement: id, ledger: 'refused', why: 'the ledger could not be written' });
348
+ continue;
349
+ }
350
+ ledger = next;
351
+ const recorded = await updatePactRecord({ dir, env, game, me, map, graph, pact: moved.agreement, before: pact, created: false });
352
+ out.push({ agreement: id, ledger: 'recorded', playerRecord: recorded === 'not-mine' ? 'off' : recorded });
353
+ continue;
354
+ }
294
355
  const found = ledger.agreements.find((a) => a.id === id);
295
356
  if (!found) {
296
357
  out.push({ agreement: id, ledger: 'refused', why: 'not in the ledger' });
@@ -336,6 +397,21 @@ export async function recordPartnerApproved(o) {
336
397
  const out = [];
337
398
  for (const x of o.exceptions) {
338
399
  const territories = [...new Set(x.territories)].sort((a, b) => a - b);
400
+ const pact = ledger.pacts?.find((a) => a.id === x.agreement);
401
+ if (pact) {
402
+ // #680: a pact's exception applies to every partner's view of it.
403
+ const ex = { direction: 'mine', territories, fromTurn: turn, toTurn: turn, recordedTurn: turn, ...(x.note ? { note: x.note } : {}) };
404
+ const moved = withExceptions(pact, [ex]);
405
+ const next = { ...ledger, pacts: [...(ledger.pacts ?? []).filter((a) => a.id !== pact.id), moved] };
406
+ if (!(await writeLedger(dir, next))) {
407
+ out.push({ agreement: x.agreement, territories, ledger: 'refused', why: 'the ledger could not be written' });
408
+ continue;
409
+ }
410
+ ledger = next;
411
+ const recorded = await updatePactRecord({ dir, env, game, me, map, graph, pact: moved, before: pact, created: false });
412
+ out.push({ agreement: x.agreement, territories, ledger: 'recorded', id: moved.exceptions.at(-1).id, playerRecord: recorded === 'not-mine' ? 'off' : recorded });
413
+ continue;
414
+ }
339
415
  const found = ledger.agreements.find((a) => a.id === x.agreement);
340
416
  if (!found) {
341
417
  out.push({ agreement: x.agreement, territories, ledger: 'refused', why: 'not in the ledger' });
@@ -381,19 +457,32 @@ export async function recordCommitments(o) {
381
457
  for (const [index, { commitment: c, record }] of o.commitments.entries()) {
382
458
  let entry = record;
383
459
  if (c.kind === 'propose' || c.kind === 'accept' || c.kind === 'notice') {
384
- const change = agreementChange(c, { agreements: ledger.agreements, turn, me: meId, players, nextAgreementId: (agreements) => nextAgreementId({ agreements }) });
460
+ const change = agreementChange(c, {
461
+ agreements: ledger.agreements,
462
+ pacts: ledger.pacts,
463
+ turn,
464
+ me: meId,
465
+ players,
466
+ nextAgreementId: (agreements) => nextAgreementId({ agreements }),
467
+ nextPactId: (pacts) => nextPactId({ pacts }),
468
+ });
385
469
  if ('refused' in change) {
386
470
  out.push({ index, kind: c.kind, why: change.refused });
387
471
  continue;
388
472
  }
389
473
  const a = change.agreement;
390
- ledger = { ...ledger, agreements: [...ledger.agreements.filter((x) => x.id !== a.id), a] };
474
+ // #685: a pact's change lands in the ledger's own `pacts` list.
475
+ if (a.parties !== undefined)
476
+ ledger = { ...ledger, pacts: [...(ledger.pacts ?? []).filter((x) => x.id !== a.id), a] };
477
+ else
478
+ ledger = { ...ledger, agreements: [...ledger.agreements.filter((x) => x.id !== a.id), a] };
391
479
  if (change.agreement !== change.before)
392
480
  changes.push({ ...change, at: out.length });
481
+ const parties = a.parties !== undefined ? { parties: a.parties.filter((p) => p !== meId) } : {};
393
482
  entry =
394
483
  c.kind === 'notice'
395
- ? { sentTurn: turn, kind: 'notice', agreement: a.id, with: a.with, endsTurn: record.kind === 'notice' ? record.endsTurn : turn + a.terms.noticeTurns }
396
- : { sentTurn: turn, kind: c.kind, agreement: a.id, with: a.with };
484
+ ? { sentTurn: turn, kind: 'notice', agreement: a.id, with: a.with, ...parties, endsTurn: record.kind === 'notice' ? record.endsTurn : turn + a.terms.noticeTurns }
485
+ : { sentTurn: turn, kind: c.kind, agreement: a.id, with: a.with, ...parties };
397
486
  out.push({ index, kind: c.kind, agreement: { id: a.id, status: a.status } });
398
487
  }
399
488
  else {
@@ -412,6 +501,11 @@ export async function recordCommitments(o) {
412
501
  continue;
413
502
  }
414
503
  const { game, me, map } = o.game;
504
+ if (ch.agreement.parties !== undefined) {
505
+ const r = await updatePactRecord({ dir, env, game, me, map, graph: graphOf(map), pact: ch.agreement, before: ch.before, created: ch.created });
506
+ shown.playerRecord = r === 'not-mine' ? 'failed' : r;
507
+ continue;
508
+ }
415
509
  const others = ledger.agreements.filter((a) => a.id !== ch.agreement.id);
416
510
  shown.playerRecord = await updateAgreementRecord({ dir, env, game, me, map, graph: graphOf(map), agreement: ch.agreement, before: ch.before, created: ch.created, others });
417
511
  }
@@ -440,7 +534,16 @@ export function registerRelationsTools(server, ctx, opts = {}) {
440
534
  '`record`: how it kept earlier agreements — tallies, a kept rate, its notices honoured or broken, its breaks in ' +
441
535
  'the endgame or while leading, retaliation, proposing again and turns to a break (`full` adds the entries) — keyed ' +
442
536
  'by a salted hash, never its id or name. `playerRecord` says on, off or unreadable. Words in chat never change a ' +
443
- 'flag or the trust: only the board does. Each agreement carries `source: "ledger"`; in a game running the Diplomacy 2 ' +
537
+ 'flag or the trust: only the board does. Each agreement carries its `source` and `includesMe`: a two-party truce ' +
538
+ 'is `ledger`; a pact (#680, id `p<n>`, with `parties`) is `ledger` when recorded with you in it — watched per ' +
539
+ 'partner in `partners`, as the pairwise truces it amounts to — or `reported` between other players (`leaving` and ' +
540
+ '`notices` give each party\'s notice: a party leaves once its own has run). `pactsBetweenOthers` lists every pact ' +
541
+ 'between other players binding this turn: reported, one you left, a Diplomacy card between two others (`card`, ' +
542
+ 'only when the decoder is sure) and a Diplomacy 2 alliance between two others (`mod`) — report only. #686: a reported pact or one you ' +
543
+ 'left is watched over your boards as your own truces are: `flags` (`broken`: a party took, in view, a territory another party held; ' +
544
+ '`massing`: one lost into the fog beside another party, or a take a Gift may explain — never `broken`) and `broken: true`, after ' +
545
+ 'which it no longer counts as a pact for the joint-attack check or the coalition advice. The ledger keeps its status unless you ' +
546
+ 'record it; a `card` or `mod` pact follows the game. In a game running the Diplomacy 2 ' +
444
547
  'mod (mod 191) `modAlliances` lists the mod\'s alliances with you (`source: "mod"`, UNVERIFIED live) with `mismatches` ' +
445
548
  '(`mod-only`: allied with no agreement recorded; `ledger-only`: a truce the game does not enforce) and `notices` (an ' +
446
549
  `ally's break, shown once it applied). ${BRIDGE_NOTE} Read-only on war.app; it caches the board it read.`),
@@ -463,10 +566,13 @@ export function registerRelationsTools(server, ctx, opts = {}) {
463
566
  const notes = [RELATIONS_NOTE];
464
567
  let boards = [];
465
568
  let live = false;
569
+ // #680: the Diplomacy cards between two other players on the live board (the decoder's "only when sure").
570
+ let diplomacyOthers;
466
571
  if (game.state === 'Playing' && currentTurn(game) !== null) {
467
572
  boards = (await boardHistory(ctx, game, me, turn)).boards;
468
573
  try {
469
- const { territories } = await loadLiveGame(ctx, game);
574
+ const { territories, info } = await loadLiveGame(ctx, game);
575
+ diplomacyOthers = boardCardsInEffect(game, me, turn, info).diplomacyOthers;
470
576
  const board = boardStateFromLive(territories, me, game.players);
471
577
  boards = [...boards.filter((b) => b.turn !== turn), { turn, board }];
472
578
  live = true;
@@ -486,6 +592,24 @@ export function registerRelationsTools(server, ctx, opts = {}) {
486
592
  }
487
593
  const incomes = incomesOf(graph, boards, game, me, map);
488
594
  const agreements = [];
595
+ // #680: a pact I am in is watched per partner, as the pairwise truce it amounts to.
596
+ const partnersOf = new Map();
597
+ for (const p of ledger.pacts ?? []) {
598
+ const views = [];
599
+ for (const v of pactViews(p, me.id)) {
600
+ const state = agreementState(v, turn, relationPlayers(game.players));
601
+ const live_ = state.phase === 'active' || state.phase === 'notice';
602
+ const flags = v.agreedTurn !== undefined && live_ ? breachWatch({ agreement: v, graph, boards, me: me.id, ...cardsInPlay(game), ...(incomes.mine !== null ? { incomes: { mine: incomes.mine, partner: incomes.opponents.get(v.with) ?? null } } : {}) }) : [];
603
+ const endgame = live_ ? endgameOf(incomes, v.with) : null;
604
+ views.push({
605
+ agreement: v,
606
+ flags: live_ ? [...flags, ...capSelfCheck(v, boards, me.id)] : flags,
607
+ ...(live_ ? { trust: trust(v, flags, { endgame: endgame === true }), endgame } : {}),
608
+ ...(await recordFor(ctx.dataDir, v.with, env)),
609
+ });
610
+ }
611
+ partnersOf.set(p.id, views);
612
+ }
489
613
  for (const a of ledger.agreements) {
490
614
  const state = agreementState(a, turn, relationPlayers(game.players));
491
615
  const live_ = state.phase === 'active' || state.phase === 'notice';
@@ -510,17 +634,29 @@ export function registerRelationsTools(server, ctx, opts = {}) {
510
634
  }
511
635
  // A teammate's quiet border is no tacit truce (#246): left out like a partner with an agreement.
512
636
  const excluded = new Set([
513
- ...ledger.agreements.filter((a) => !TERMINAL_STATUSES.has(a.status)).map((a) => a.with),
637
+ ...ledgerTruces(ledger).filter((a) => !TERMINAL_STATUSES.has(a.status)).map((a) => a.with),
514
638
  ...teammatesOf(game.players, me).map((p) => p.id),
515
639
  ]);
516
640
  const tacit = tacitTruces({ graph, boards, me: me.id, exclude: excluded });
517
641
  const recordState = await playerRecordState(ctx.dataDir, env);
518
642
  // The Diplomacy 2 mod's alliances beside the ledger's (a game without the mod: no request, no field).
519
- const liveAgreements = ledger.agreements.filter((a) => {
643
+ const liveAgreements = ledgerTruces(ledger).filter((a) => {
520
644
  const st = agreementState(a, turn, relationPlayers(game.players));
521
645
  return st.phase === 'active' || st.phase === 'notice';
522
646
  });
523
- const modView = modRelationsView(await readModAlliances(ctx, game, me), liveAgreements, (id) => {
647
+ const modRead = await readModAlliances(ctx, game, me);
648
+ // #680: every pact between other players binding this turn (the ledger's, the cards', the mod's): report only.
649
+ // #686: watched over my boards for breaches (report only: the ledger keeps a reported pact's status unless recorded).
650
+ const othersPacts = pactsWithoutMe({
651
+ pacts: ledger.pacts,
652
+ me: me.id,
653
+ turn,
654
+ players: relationPlayers(game.players),
655
+ diplomacy: diplomacyOthers,
656
+ mod: modPacts(modRead),
657
+ watch: { graph, boards, ...cardsInPlay(game) },
658
+ });
659
+ const modView = modRelationsView(modRead, liveAgreements, (id) => {
524
660
  const p = game.players.find((x) => x.id === id);
525
661
  return { id, name: p ? untrustedText(p.name) : null };
526
662
  });
@@ -532,14 +668,53 @@ export function registerRelationsTools(server, ctx, opts = {}) {
532
668
  return respond(view, VIEWS, (rung) => ({
533
669
  game: { id: game.id, name: game.name === undefined ? null : untrustedText(game.name), state: game.state, turn },
534
670
  player: { id: me.id, name: untrustedText(me.name) },
535
- agreements: agreements.map((x) => ({
536
- source: 'ledger',
537
- ...agreementView(x.agreement, game, map, turn, rung),
538
- ...(x.trust ? { trust: x.trust, endgame: x.endgame } : {}),
539
- flags: x.flags.map((f) => ({ ...f, territories: f.territories.map(name) })),
540
- record: x.record,
541
- ...(rung === 'full' && x.entries ? { recordEntries: x.entries.map(entryView) } : {}),
542
- })),
671
+ agreements: [
672
+ ...agreements.map((x) => ({
673
+ source: 'ledger',
674
+ includesMe: true,
675
+ ...agreementView(x.agreement, game, map, turn, rung),
676
+ ...(x.trust ? { trust: x.trust, endgame: x.endgame } : {}),
677
+ flags: x.flags.map((f) => ({ ...f, territories: f.territories.map(name) })),
678
+ record: x.record,
679
+ ...(rung === 'full' && x.entries ? { recordEntries: x.entries.map(entryView) } : {}),
680
+ })),
681
+ // #680: the pacts, each with its parties, source and whether it includes me now; one I am in is watched per partner.
682
+ ...(ledger.pacts ?? []).map((p) => {
683
+ const partners = partnersOf.get(p.id) ?? [];
684
+ return {
685
+ ...agreementView(p, game, map, turn, rung, me.id),
686
+ ...(partners.length
687
+ ? {
688
+ partners: partners.map((x) => ({
689
+ player: playerName(x.agreement.with),
690
+ state: agreementState(x.agreement, turn, relationPlayers(game.players)).phase,
691
+ ...(x.trust ? { trust: x.trust, endgame: x.endgame } : {}),
692
+ flags: x.flags.map((f) => ({ ...f, territories: f.territories.map(name) })),
693
+ record: x.record,
694
+ ...(rung === 'full' && x.entries ? { recordEntries: x.entries.map(entryView) } : {}),
695
+ })),
696
+ }
697
+ : {}),
698
+ };
699
+ }),
700
+ ],
701
+ ...(othersPacts.length
702
+ ? {
703
+ pactsBetweenOthers: othersPacts.map((k) => ({
704
+ parties: k.parties.map(playerName),
705
+ source: k.source,
706
+ includesMe: false,
707
+ ...(k.agreement ? { agreement: k.agreement } : {}),
708
+ ...(k.untilTurn !== undefined ? { untilTurn: k.untilTurn } : {}),
709
+ ...(k.endsTurn !== undefined ? { endsTurn: k.endsTurn } : {}),
710
+ // #686: what my boards show of the parties keeping it; `broken`: it no longer counts as a pact.
711
+ ...(k.broken ? { broken: true } : {}),
712
+ ...(k.flags?.length
713
+ ? { flags: k.flags.map((f) => ({ ...f, by: playerName(f.by), against: playerName(f.against), territories: f.territories.map(name) })) }
714
+ : {}),
715
+ })),
716
+ }
717
+ : {}),
543
718
  tacit: tacit.map((t) => ({ player: playerName(t.player), quietTurns: t.quietTurns, border: t.border.map(name) })),
544
719
  ...(ledger.coordination?.length ? { coordination: ledger.coordination.map((c) => coordinationView(c, game, map, turn)) } : {}),
545
720
  ...(modView ? { modAlliances: modView } : {}),
@@ -579,13 +754,34 @@ export function registerRelationsTools(server, ctx, opts = {}) {
579
754
  'hosted), each agreement is also kept per partner under a salted hash, name-free (no id, no name, no game, no ' +
580
755
  'message): the format, the turns agreed and ended, the shape of the terms, the outcome, a break\'s turn, flag and ' +
581
756
  'context (endgame, who led, outgrowing), retaliation and proposing again, with tallies; `playerRecord` says ' +
582
- 'updated, off or failed.'),
757
+ 'updated, off or failed. #680: `parties` (instead of `with`, 2–10 names or ids) records a pact (id `p<n>`): you and ' +
758
+ 'two or more others — every partner planned exactly as a two-party truce with the same terms, the player record kept ' +
759
+ 'per partner, a break of it by your orders breaking the whole pact — or other players only, recorded as `reported` ' +
760
+ '(agreed only, no propose or accept, no terms of yours, no player record: `playerRecord` is not-mine), which is ' +
761
+ 'report only: never a change to your orders. On a pact each party gives its own notice (notice-by-me, or ' +
762
+ 'notice-by-them with `notice_by`; status agreed with `notice_by` withdraws it). On a pact of three or more still ' +
763
+ 'bound a notice needs `rest` — ask the owner, it is never decided automatically: `continue` (the party leaves once ' +
764
+ 'its notice has run, the rest go on while two or more remain) or `end` (the whole pact ends then); without it ' +
765
+ 'nothing is recorded. A party out of the game or turned AI still leaves on its own, the rest going on.'),
583
766
  annotations: toolAnnotations({ title: 'Record a war.app agreement', readOnly: false, destructive: false, idempotent: false, openWorld: true }),
584
767
  inputSchema: z.object({
585
768
  game_id: gameIdArg,
586
769
  player: playerArg,
587
770
  agreement_id: z.string().trim().min(1).max(20).optional().describe('The agreement to update (e.g. "a1"). Omit to record a new one.'),
588
- with: playerRef.optional().describe('The partner (name or GameFeed id). Required for a new agreement.'),
771
+ with: playerRef.optional().describe('The partner (name or GameFeed id). A new agreement needs it or `parties`.'),
772
+ parties: z
773
+ .array(playerRef)
774
+ .min(2)
775
+ .max(MAX_PARTIES)
776
+ .optional()
777
+ .describe(`#680: every party (names or GameFeed ids, 2–${MAX_PARTIES}) of a new agreement, instead of \`with\`: you and two or more others (an n-way truce, a pact \`p<n>\`), or other players only (a pact between them, recorded as \`reported\`: status agreed only, no propose or accept). You and one other is an ordinary two-party truce.`),
778
+ notice_by: playerRef
779
+ .optional()
780
+ .describe("#680, a pact only: the party (name or id) whose notice this records (status notice-by-them) or withdraws (status agreed; default you). Each party's notice is its own: it leaves once its notice has run."),
781
+ rest: z
782
+ .enum(PACT_RESTS)
783
+ .optional()
784
+ .describe("A notice on a pact of three or more still bound only, and required there: what becomes of the rest of the truce. Ask the owner — it is never decided automatically. `continue`: the leaver leaves once its notice has run, the others stay bound while two or more remain; `end`: the whole pact ends when that notice has run."),
589
785
  status: z.enum(AGREEMENT_STATUSES).optional().describe('The status to record. Required for a new agreement.'),
590
786
  territories: z.array(playerRef).max(MAX_SCOPE_ITEMS).optional().describe('Only these territories (names or ids) are covered.'),
591
787
  bonuses: z.array(playerRef).max(MAX_SCOPE_ITEMS).optional().describe("Only these bonuses' territories (names or ids) are covered."),
@@ -667,8 +863,9 @@ export function registerRelationsTools(server, ctx, opts = {}) {
667
863
  const capsGiven = !!args.caps?.length || !!args.caps_remove?.length;
668
864
  const otherPlayer = (ref, what, partner) => {
669
865
  const p = resolvePlayer(game.players, ref);
670
- if (p.id === me.id || p.id === partner)
671
- refuse(`${what} must be a third player, not you or the partner`, `Name the player ${what === '`against`' ? 'the truce is aimed at' : 'whose fall ends it'}.`);
866
+ const party = typeof partner === 'number' ? p.id === partner : partner.includes(p.id);
867
+ if (p.id === me.id || party)
868
+ refuse(`${what} must be a third player, not you or ${typeof partner === 'number' ? 'the partner' : 'a party'}`, `Name the player ${what === '`against`' ? 'the truce is aimed at' : 'whose fall ends it'}.`);
672
869
  return p.id;
673
870
  };
674
871
  const termsFrom = (base, partner) => {
@@ -745,23 +942,196 @@ export function registerRelationsTools(server, ctx, opts = {}) {
745
942
  }
746
943
  return list;
747
944
  };
945
+ /** #680: the parties `args` name, resolved (no one twice); `undefined` without `parties`. */
946
+ const partiesArg = () => {
947
+ if (args.parties === undefined)
948
+ return undefined;
949
+ if (args.with !== undefined)
950
+ refuse('Give `with` or `parties`, not both', 'Name every party in `parties`, you included when you are one.');
951
+ const ids = args.parties.map((r) => resolvePlayer(game.players, r).id);
952
+ const twice = ids.find((id, i) => ids.indexOf(id) !== i);
953
+ if (twice !== undefined)
954
+ refuse(`${twice === me.id ? 'You are' : `Player ${twice} is`} named twice among the parties`, 'Name each party once.');
955
+ return ids.sort((a, b) => a - b);
956
+ };
957
+ if (args.parties !== undefined && args.agreement_id !== undefined)
958
+ refuse("A pact's parties cannot change", 'End it and record a new one with the new parties.');
959
+ const parties = args.agreement_id === undefined ? partiesArg() : undefined;
960
+ // You and one other is an ordinary two-party truce: recorded exactly as `with` records it.
961
+ const pairOnly = parties !== undefined && parties.length === 2 && parties.includes(me.id) ? parties.find((p) => p !== me.id) : undefined;
962
+ const isPactChange = args.agreement_id !== undefined ? /^p\d+$/.test(args.agreement_id) : parties !== undefined && pairOnly === undefined;
963
+ if (args.notice_by !== undefined && !isPactChange)
964
+ refuse('`notice_by` applies only to a pact (an agreement with `parties`)', 'Record notice on a two-party truce with status notice-by-me or notice-by-them.');
965
+ if (args.rest !== undefined && (!isPactChange || args.agreement_id === undefined || (args.status !== 'notice-by-me' && args.status !== 'notice-by-them')))
966
+ refuse('`rest` applies only to a notice on a pact (status notice-by-me or notice-by-them with `agreement_id` "p<n>")', 'Omit `rest`: a two-party truce ends with its notice, and only a party\'s notice on a pact asks what becomes of the rest.');
967
+ /** #680: the change `args` make to a pact in `ledger`. Refuses what cannot be recorded. */
968
+ const changePact = (ledger) => {
969
+ if (args.agreement_id === undefined) {
970
+ const ids = parties;
971
+ if (args.status === undefined)
972
+ refuse('A new agreement needs `status`', 'Pass `agreement_id` to update one already recorded.');
973
+ if (args.retaliated !== undefined)
974
+ refuse('`retaliated` applies only after broken-by-me', 'Record it on the broken agreement.');
975
+ if (coordGiven)
976
+ refuse('A coordination is agreed with one partner', 'Record it with `with` (the partner), not on a pact.');
977
+ const withMe = ids.includes(me.id);
978
+ const others = ids.filter((p) => p !== me.id);
979
+ if (withMe) {
980
+ if (!OPENING_STATUSES.includes(args.status))
981
+ refuse(`A new agreement starts as ${OPENING_STATUSES.join(', ')}, not ${args.status}`, 'Record it as agreed first, then update it.');
982
+ for (const x of others) {
983
+ const why = partyRefusal(players, me.id, x);
984
+ if (why)
985
+ refuse(`No truce with player ${x}: ${why}`, 'A truce is with other human players still in a free-for-all.');
986
+ const open = ledger.agreements.find((a) => a.with === x && !TERMINAL_STATUSES.has(a.status));
987
+ if (open)
988
+ refuse(`Agreement ${open.id} with player ${x} is still ${open.status}`, `End it first (agreement_id "${open.id}"), then record the pact.`);
989
+ const pact = (ledger.pacts ?? []).find((a) => !TERMINAL_STATUSES.has(a.status) && pactState(a, turn, players, me.id).includesMe && a.parties.includes(x));
990
+ if (pact)
991
+ refuse(`Pact ${pact.id} already binds you and player ${x}`, `End it first (agreement_id "${pact.id}"), then record the new one.`);
992
+ }
993
+ }
994
+ else {
995
+ if (args.status !== 'agreed')
996
+ refuse(`An agreement between other players is recorded only as agreed (reported), not ${args.status}`, 'There is no propose or accept flow for a pact you are not in: record it once they have agreed.');
997
+ if (args.territories !== undefined || args.bonuses !== undefined || args.border_cap !== undefined)
998
+ refuse('A pact between other players covers everything between them: no `territories`, `bonuses` or `border_cap`', 'Omit them.');
999
+ if (args.exceptions?.length || capsGiven)
1000
+ refuse('A pact between other players takes no `exceptions` or `caps`', 'Those are your own promises: record them on a truce of yours.');
1001
+ for (const x of ids) {
1002
+ const p = players.find((q) => q.id === x);
1003
+ if (p.isAI || p.humanTurnedIntoAI)
1004
+ refuse(`Player ${x} is an AI: it keeps no agreement`, 'A pact is between human players.');
1005
+ if (p.state !== undefined && p.state !== 'Playing')
1006
+ refuse(`Player ${x} is no longer playing (${p.state})`, 'A pact is between players still in the game.');
1007
+ }
1008
+ for (const x of ids)
1009
+ for (const y of ids) {
1010
+ const [px, py] = [players.find((q) => q.id === x), players.find((q) => q.id === y)];
1011
+ if (x < y && carriesTeam(px.team) && px.team === py.team)
1012
+ refuse(`Players ${x} and ${y} are teammates`, 'Teammates are allies already: a pact between them changes nothing.');
1013
+ }
1014
+ const same = (ledger.pacts ?? []).find((a) => !TERMINAL_STATUSES.has(a.status) && a.parties.length === ids.length && a.parties.every((p, i) => p === ids[i]));
1015
+ if (same)
1016
+ refuse(`Pact ${same.id} between these players is still ${same.status}`, `Update it with agreement_id "${same.id}".`);
1017
+ }
1018
+ const terms = termsFrom(undefined, ids);
1019
+ const pact = {
1020
+ ...newAgreement(nextPactId(ledger), others[0], args.status, turn, terms),
1021
+ parties: ids,
1022
+ source: withMe ? 'ledger' : 'reported',
1023
+ };
1024
+ return { agreement: pact, before: undefined, created: true };
1025
+ }
1026
+ const found = (ledger.pacts ?? []).find((a) => a.id === args.agreement_id);
1027
+ if (!found)
1028
+ refuse(`Game ${game.id} has no agreement ${JSON.stringify(args.agreement_id)}`, 'warapp_get_relations lists the agreements recorded.');
1029
+ let pact = found;
1030
+ if (args.with !== undefined)
1031
+ refuse(`${pact.id} is a pact: it has \`parties\`, not \`with\``, 'Omit `with` when updating a pact.');
1032
+ if (args.status === undefined && !termsGiven && args.retaliated === undefined && !args.exceptions?.length && !capsGiven && !coordGiven)
1033
+ refuse('Nothing to record: give a new `status`, terms, `retaliated`, `exceptions` or `caps`', 'Pass the status the agreement moved to.');
1034
+ if (coordGiven)
1035
+ refuse('A coordination is agreed with one partner', 'Record it with `with` (the partner), not on a pact.');
1036
+ const now = pactState(pact, turn, players, me.id);
1037
+ // Mine while I am a party and my own notice has not run; a pact I left or never joined is report only.
1038
+ const mine = pact.parties.includes(me.id) && !now.left.includes(me.id);
1039
+ if (!mine && (args.exceptions?.length || capsGiven))
1040
+ refuse(`Pact ${pact.id} does not include you: it takes no \`exceptions\` or \`caps\``, 'Those are your own promises: record them on a truce of yours.');
1041
+ if (termsGiven) {
1042
+ if (pact.status !== 'proposed-by-me' && pact.status !== 'proposed-by-them')
1043
+ refuse(`The terms of agreement ${pact.id} (${pact.status}) can no longer change`, 'End it and record a new agreement with the new terms.');
1044
+ pact = { ...pact, terms: termsFrom(pact.terms, pact.parties) };
1045
+ }
1046
+ const by = args.notice_by !== undefined ? resolvePlayer(game.players, args.notice_by).id : undefined;
1047
+ const status = args.status;
1048
+ if (status === 'notice-by-me' || status === 'notice-by-them') {
1049
+ if (status === 'notice-by-me' && !mine)
1050
+ refuse(`Pact ${pact.id} does not include you: there is no notice of yours to give`, 'Record theirs with notice-by-them and `notice_by`.');
1051
+ if (status === 'notice-by-me' && by !== undefined && by !== me.id)
1052
+ refuse('notice-by-me is your own notice', 'Record theirs with notice-by-them and `notice_by`.');
1053
+ const who = status === 'notice-by-me' ? me.id : by;
1054
+ if (who === undefined)
1055
+ refuse('notice-by-them on a pact needs `notice_by`: the party that gave it', 'Name the party giving notice.');
1056
+ if (who === me.id && status === 'notice-by-them')
1057
+ refuse('notice-by-them names another party', 'Record your own with notice-by-me.');
1058
+ if (!now.remaining.includes(who))
1059
+ refuse(`Player ${who} is not a party still bound by pact ${pact.id}`, 'warapp_get_relations lists its parties.');
1060
+ if (pact.status !== 'agreed')
1061
+ refuse(`Pact ${pact.id} is ${pact.status}: notice applies only once it is agreed`, 'Record it as agreed first, or end it.');
1062
+ if (pact.notices?.some((n) => n.player === who))
1063
+ refuse(`Player ${who} already gave notice on pact ${pact.id}`, 'Its notice is running.');
1064
+ // The owner's decision: what becomes of the rest of a truce of three or more is never decided automatically.
1065
+ if (args.rest === undefined && now.remaining.length >= 3)
1066
+ refuse(`A notice on pact ${pact.id} (${now.remaining.length} parties still bound) needs \`rest\`: what becomes of the rest of the truce`, `Ask the owner how the rest of the truce should be handled, then record the notice again with rest "continue" (player ${who} leaves once its notice has run; the others stay bound) or rest "end" (the whole pact ends when the notice has run).`);
1067
+ const notice = { player: who, turn, ...(args.rest !== undefined ? { rest: args.rest } : {}) };
1068
+ pact = { ...pact, notices: [...(pact.notices ?? []), notice], history: [...pact.history, { turn, status, by: who }] };
1069
+ }
1070
+ else if (status === 'agreed' && pact.status === 'agreed') {
1071
+ const who = by ?? me.id;
1072
+ if (!pact.notices?.some((n) => n.player === who))
1073
+ refuse(`Player ${who} has no notice running on pact ${pact.id}`, 'Nothing to withdraw.');
1074
+ const rest = pact.notices.filter((n) => n.player !== who);
1075
+ const { notices: _n, ...base } = pact;
1076
+ pact = { ...base, ...(rest.length ? { notices: rest } : {}), history: [...pact.history, { turn, status: 'agreed', by: who }] };
1077
+ }
1078
+ else if (status !== undefined && status !== pact.status) {
1079
+ if (!mine && status !== 'ended')
1080
+ refuse(`Pact ${pact.id} does not include you: it can only be recorded as ended (or a party's notice)`, 'Record ended, or notice-by-them with `notice_by`.');
1081
+ const moved = transitionAgreement(pact, status, turn);
1082
+ if ('refused' in moved)
1083
+ refuse(moved.refused, 'warapp_get_relations shows its status.');
1084
+ pact = moved.agreement;
1085
+ if (status === 'agreed' || status === 'proposed-by-me' || status === 'proposed-by-them')
1086
+ for (const x of now.remaining.filter((p) => p !== me.id)) {
1087
+ const why = partyRefusal(players, me.id, x);
1088
+ if (why)
1089
+ refuse(`Pact ${pact.id} cannot become ${status}: ${why}`, 'Record it as ended instead.');
1090
+ }
1091
+ }
1092
+ if (args.retaliated !== undefined) {
1093
+ if (pact.status !== 'broken-by-me')
1094
+ refuse('`retaliated` applies only after broken-by-me', 'Record it on the agreement you broke.');
1095
+ pact = { ...pact, retaliated: args.retaliated };
1096
+ }
1097
+ if (args.exceptions?.length)
1098
+ pact = withExceptions(pact, exceptionsFrom());
1099
+ if (capsGiven) {
1100
+ if (TERMINAL_STATUSES.has(pact.status))
1101
+ refuse(`Agreement ${pact.id} is ${pact.status}: caps apply only while it is proposed, agreed or in notice`, 'Record a new agreement to promise a cap.');
1102
+ const remove = (args.caps_remove ?? []).map((t) => resolveTerritory(map, t).id);
1103
+ for (const t of remove)
1104
+ if (!pact.caps?.some((c) => c.territory === t))
1105
+ refuse(`Agreement ${pact.id} has no cap on territory ${t}`, 'warapp_get_relations lists the caps recorded.');
1106
+ const caps = (args.caps ?? []).map((c) => {
1107
+ const note = exceptionNote(c.note, game);
1108
+ return { territory: resolveTerritory(map, c.territory).id, max: c.max, addedTurn: turn, ...(note ? { note } : {}) };
1109
+ });
1110
+ pact = withCaps(pact, caps, remove);
1111
+ }
1112
+ return { agreement: pact, before: found, created: false };
1113
+ };
748
1114
  /** The change `args` make to `ledger`: the agreement after it, and as it stood. Refuses what cannot be recorded. */
749
1115
  const change = (ledger) => {
750
1116
  let agreement;
751
1117
  let before;
752
1118
  let created = false;
753
1119
  if (args.agreement_id === undefined) {
754
- if (args.with === undefined || args.status === undefined)
755
- refuse('A new agreement needs `with` (the partner) and `status`', 'Pass `agreement_id` to update one already recorded.');
1120
+ if ((args.with === undefined && pairOnly === undefined) || args.status === undefined)
1121
+ refuse('A new agreement needs `with` (the partner) or `parties`, and `status`', 'Pass `agreement_id` to update one already recorded.');
756
1122
  if (!OPENING_STATUSES.includes(args.status))
757
1123
  refuse(`A new agreement starts as ${OPENING_STATUSES.join(', ')}, not ${args.status}`, 'Record it as agreed first, then update it.');
758
- const partner = resolvePlayer(game.players, args.with);
1124
+ const partner = resolvePlayer(game.players, pairOnly ?? args.with);
759
1125
  const why = partyRefusal(players, me.id, partner.id);
760
1126
  if (why)
761
1127
  refuse(`No truce with player ${partner.id}: ${why}`, 'A truce is with another human player still in a free-for-all.');
762
1128
  const open = ledger.agreements.find((a) => a.with === partner.id && !TERMINAL_STATUSES.has(a.status));
763
1129
  if (open)
764
1130
  refuse(`Agreement ${open.id} with player ${partner.id} is still ${open.status}`, `Update it with agreement_id "${open.id}", or end it first.`);
1131
+ // #680: a pact of mine that already binds the partner.
1132
+ const pact = (ledger.pacts ?? []).find((a) => !TERMINAL_STATUSES.has(a.status) && pactState(a, turn, players, me.id).includesMe && a.parties.includes(partner.id));
1133
+ if (pact)
1134
+ refuse(`Pact ${pact.id} already binds you and player ${partner.id}`, `Update it with agreement_id "${pact.id}", or end it first.`);
765
1135
  if (args.retaliated !== undefined)
766
1136
  refuse('`retaliated` applies only after broken-by-me', 'Record it on the broken agreement.');
767
1137
  agreement = newAgreement(nextAgreementId(ledger), partner.id, args.status, turn, termsFrom(undefined, partner.id));
@@ -839,6 +1209,14 @@ export function registerRelationsTools(server, ctx, opts = {}) {
839
1209
  throw unwritable();
840
1210
  return { coordination };
841
1211
  }
1212
+ if (isPactChange) {
1213
+ const c = changePact(ledger);
1214
+ const pacts = [...(ledger.pacts ?? []).filter((a) => a.id !== c.agreement.id), c.agreement];
1215
+ if (!(await writeLedger(dir, { ...ledger, pacts })))
1216
+ throw unwritable();
1217
+ const recorded = await updatePactRecord({ dir, env, game, me, map, graph, pact: c.agreement, before: c.before, created: c.created });
1218
+ return { ...c, coordination: ledger.coordination, recorded };
1219
+ }
842
1220
  const c = change(ledger);
843
1221
  const coordination = coordGiven ? coordinationFrom(ledger, c.agreement.with) : ledger.coordination;
844
1222
  const rest = ledger.agreements.filter((a) => a.id !== c.agreement.id);
@@ -854,7 +1232,7 @@ export function registerRelationsTools(server, ctx, opts = {}) {
854
1232
  return respond(undefined, ['compact'], () => ({
855
1233
  game: { id: game.id, turn },
856
1234
  recorded: created ? 'created' : 'updated',
857
- agreement: agreementView(agreement, game, map, turn, 'full'),
1235
+ agreement: agreementView(agreement, game, map, turn, 'full', me.id),
858
1236
  ...coordView,
859
1237
  playerRecord: recorded,
860
1238
  written: LEDGER_NOTE,