@chrischall/warapp-mcp 0.0.0 → 0.2.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.
- package/.claude-plugin/marketplace.json +4 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +211 -9
- package/dist/analysis/accept-surrender.js +56 -0
- package/dist/analysis/award.js +159 -0
- package/dist/analysis/bonuses.js +98 -0
- package/dist/analysis/breach.js +62 -0
- package/dist/analysis/calibrate.js +239 -0
- package/dist/analysis/card-support.js +329 -0
- package/dist/analysis/card-threats.js +234 -0
- package/dist/analysis/cards-in-effect.js +130 -0
- package/dist/analysis/chains.js +59 -0
- package/dist/analysis/chokepoints.js +140 -0
- package/dist/analysis/combat.js +231 -0
- package/dist/analysis/commander-safety.js +149 -0
- package/dist/analysis/commitments.js +338 -0
- package/dist/analysis/exchange.js +155 -0
- package/dist/analysis/finished-game.js +136 -0
- package/dist/analysis/game-lessons.js +217 -0
- package/dist/analysis/graph.js +82 -0
- package/dist/analysis/guard-off.js +54 -0
- package/dist/analysis/guess.js +351 -0
- package/dist/analysis/headroom.js +241 -0
- package/dist/analysis/hold-diff.js +64 -0
- package/dist/analysis/how-lost.js +130 -0
- package/dist/analysis/index.js +14 -0
- package/dist/analysis/local-deploy.js +179 -0
- package/dist/analysis/lookahead.js +108 -0
- package/dist/analysis/opponent-profile.js +552 -0
- package/dist/analysis/opponents.js +1253 -0
- package/dist/analysis/outlook.js +695 -0
- package/dist/analysis/overrides.js +60 -0
- package/dist/analysis/picks.js +1879 -0
- package/dist/analysis/plan/after-leftover.js +140 -0
- package/dist/analysis/plan/cap-spend.js +242 -0
- package/dist/analysis/plan/captures.js +1195 -0
- package/dist/analysis/plan/commander.js +236 -0
- package/dist/analysis/plan/completed.js +29 -0
- package/dist/analysis/plan/conceded-out.js +131 -0
- package/dist/analysis/plan/estimates.js +715 -0
- package/dist/analysis/plan/guard-off.js +232 -0
- package/dist/analysis/plan/holds.js +1631 -0
- package/dist/analysis/plan/leftover.js +760 -0
- package/dist/analysis/plan/move-order.js +319 -0
- package/dist/analysis/plan/orders.js +317 -0
- package/dist/analysis/plan/relations.js +702 -0
- package/dist/analysis/plan/report.js +672 -0
- package/dist/analysis/plan/shared.js +1405 -0
- package/dist/analysis/plan/stand-still.js +823 -0
- package/dist/analysis/plan/state.js +44 -0
- package/dist/analysis/plan/strike.js +1416 -0
- package/dist/analysis/plan/targets.js +651 -0
- package/dist/analysis/plan/team.js +299 -0
- package/dist/analysis/plan/threats.js +1001 -0
- package/dist/analysis/plan/transfers.js +328 -0
- package/dist/analysis/plan/util.js +5 -0
- package/dist/analysis/plan/vacated.js +285 -0
- package/dist/analysis/planner.js +2927 -0
- package/dist/analysis/player-record.js +144 -0
- package/dist/analysis/player.js +268 -0
- package/dist/analysis/profile.js +347 -0
- package/dist/analysis/relations.js +1030 -0
- package/dist/analysis/schedule.js +88 -0
- package/dist/analysis/since-last.js +50 -0
- package/dist/analysis/static-seats.js +71 -0
- package/dist/analysis/stress.js +584 -0
- package/dist/analysis/team-brief.js +151 -0
- package/dist/analysis/tripwire.js +644 -0
- package/dist/analysis/turn-sim.js +259 -0
- package/dist/analysis/whereabouts.js +1112 -0
- package/dist/board.js +105 -0
- package/dist/bundle.js +121082 -36148
- package/dist/calibration-source.js +75 -0
- package/dist/cards.js +435 -0
- package/dist/chat-cursor.js +135 -0
- package/dist/chat.js +265 -0
- package/dist/client.js +439 -0
- package/dist/config.js +62 -0
- package/dist/direct/link.js +102 -0
- package/dist/direct/session.js +267 -0
- package/dist/direct/transport.js +424 -0
- package/dist/finished-store.js +357 -0
- package/dist/guess-salt.js +65 -0
- package/dist/hosted.js +24 -0
- package/dist/index.js +33 -0
- package/dist/join-color.js +140 -0
- package/dist/lessons-store.js +356 -0
- package/dist/live.js +287 -0
- package/dist/map-details.js +127 -0
- package/dist/map-stats.js +160 -0
- package/dist/map-store.js +242 -0
- package/dist/move-order.js +141 -0
- package/dist/my-games.js +218 -0
- package/dist/normalize.js +443 -0
- package/dist/notifications.js +143 -0
- package/dist/open-games.js +537 -0
- package/dist/outlook-log.js +165 -0
- package/dist/path-lock.js +22 -0
- package/dist/pick-list.js +193 -0
- package/dist/player-record-store.js +231 -0
- package/dist/player-states.js +31 -0
- package/dist/profile-store.js +727 -0
- package/dist/protocol/bundle.js +375 -0
- package/dist/protocol/codec.js +556 -0
- package/dist/protocol/decoded.js +12 -0
- package/dist/protocol/interp.js +1904 -0
- package/dist/protocol/methods.js +615 -0
- package/dist/protocol/rpc.js +202 -0
- package/dist/push/listener.js +393 -0
- package/dist/push/packets.js +66 -0
- package/dist/push/socketio.js +333 -0
- package/dist/push/websocket.js +179 -0
- package/dist/redact.js +62 -0
- package/dist/relations-store.js +242 -0
- package/dist/replay.js +227 -0
- package/dist/scalars.js +28 -0
- package/dist/scout.js +346 -0
- package/dist/stats.js +291 -0
- package/dist/strategy/card-clock.js +185 -0
- package/dist/strategy/map-notes.js +128 -0
- package/dist/strategy/notes.js +2223 -0
- package/dist/surrender-pending.js +126 -0
- package/dist/team-cards.js +84 -0
- package/dist/team-orders.js +150 -0
- package/dist/teams.js +19 -0
- package/dist/tools/accept-surrender.js +311 -0
- package/dist/tools/award.js +206 -0
- package/dist/tools/begin-turn.js +162 -0
- package/dist/tools/board.js +77 -0
- package/dist/tools/card-advice.js +256 -0
- package/dist/tools/card-effects.js +49 -0
- package/dist/tools/card-plays.js +434 -0
- package/dist/tools/card-support-advice.js +140 -0
- package/dist/tools/chat-inbox.js +158 -0
- package/dist/tools/chat-read-mark.js +179 -0
- package/dist/tools/chat.js +525 -0
- package/dist/tools/check-plan.js +689 -0
- package/dist/tools/commander-check.js +103 -0
- package/dist/tools/commitments.js +216 -0
- package/dist/tools/common.js +143 -0
- package/dist/tools/diplomacy.js +342 -0
- package/dist/tools/end-of-game.js +384 -0
- package/dist/tools/game.js +151 -0
- package/dist/tools/guess-view.js +56 -0
- package/dist/tools/healthcheck.js +90 -0
- package/dist/tools/hints.js +34 -0
- package/dist/tools/how-lost.js +154 -0
- package/dist/tools/index.js +152 -0
- package/dist/tools/join-game.js +327 -0
- package/dist/tools/leave-game.js +181 -0
- package/dist/tools/live-context.js +339 -0
- package/dist/tools/live.js +404 -0
- package/dist/tools/map-details.js +88 -0
- package/dist/tools/map-stats.js +130 -0
- package/dist/tools/map.js +141 -0
- package/dist/tools/my-games.js +193 -0
- package/dist/tools/notifications.js +484 -0
- package/dist/tools/open-games.js +104 -0
- package/dist/tools/opponents.js +163 -0
- package/dist/tools/order-options.js +135 -0
- package/dist/tools/past-games.js +94 -0
- package/dist/tools/picks.js +305 -0
- package/dist/tools/profile-hook.js +156 -0
- package/dist/tools/profile-opponents.js +121 -0
- package/dist/tools/profile-reads.js +99 -0
- package/dist/tools/push.js +445 -0
- package/dist/tools/relations.js +611 -0
- package/dist/tools/resolve.js +45 -0
- package/dist/tools/route.js +36 -0
- package/dist/tools/scout.js +87 -0
- package/dist/tools/session.js +163 -0
- package/dist/tools/strategy.js +257 -0
- package/dist/tools/stress-opponents.js +83 -0
- package/dist/tools/surrender-pending.js +74 -0
- package/dist/tools/surrender.js +247 -0
- package/dist/tools/survival.js +189 -0
- package/dist/tools/team-brief.js +266 -0
- package/dist/tools/team-source.js +222 -0
- package/dist/tools/team.js +178 -0
- package/dist/tools/turn.js +2825 -0
- package/dist/tools/uncommit.js +160 -0
- package/dist/tools/where.js +300 -0
- package/dist/tools/write-kit.js +164 -0
- package/dist/transport-bridge.js +33 -0
- package/dist/trend.js +577 -0
- package/dist/version.js +4 -0
- package/manifest.json +194 -4
- package/mint.yaml +106 -14
- package/package.json +11 -6
- package/server.json +40 -3
- package/skills/warapp-api/SKILL.md +95 -4
- package/skills/warapp-api/references/scout.mjs +348 -0
- package/skills/warapp-api/scripts/warapp.sh +69 -8
- package/skills/warapp-mcp/SKILL.md +1096 -21
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { McpToolError } from '@chrischall/mcp-utils';
|
|
2
|
+
import { registerAdaptiveHealthcheckTool, } from '@chrischall/mcp-utils/fetchproxy';
|
|
3
|
+
import { AUTH_FAILED_HINT, PROBE_GAME_ID, WarappClient } from '../client.js';
|
|
4
|
+
import { readCredentials, TOKEN_URL, WarappConfigError } from '../config.js';
|
|
5
|
+
import { readSessionSync } from '../direct/session.js';
|
|
6
|
+
/**
|
|
7
|
+
* `warapp_healthcheck` — does war.app accept the configured email + token?
|
|
8
|
+
*
|
|
9
|
+
* The probe ({@link WarappClient.probeAuth}) asks GameFeed for a game id that
|
|
10
|
+
* does not exist. war.app checks the credentials first, so the two answers
|
|
11
|
+
* separate cleanly: `Auth failed` is a rejected credential,
|
|
12
|
+
* `ServerGameKeyNotFound` proves the credential works without loading (or
|
|
13
|
+
* caching) any real game.
|
|
14
|
+
*
|
|
15
|
+
* The live-game tools reach war.app a second way — the web-client protocol —
|
|
16
|
+
* now over a direct-first transport: a chrome-less HTTPS leg carrying the
|
|
17
|
+
* linked `AuthToken` session, falling back to the browser bridge. So this is
|
|
18
|
+
* ONE adaptive tool: it answers from the bridge arm once the browser bridge has
|
|
19
|
+
* carried a request in this process (i.e. after the router fell back to it —
|
|
20
|
+
* "on fetchproxy, the bridge probe"), and from the credential arm before that,
|
|
21
|
+
* which is the whole time the direct leg is serving calls ("on direct, the
|
|
22
|
+
* credential probe"). Either way the result carries which leg is active and
|
|
23
|
+
* whether a direct session is linked and how old it is — never the token.
|
|
24
|
+
*/
|
|
25
|
+
export { PROBE_GAME_ID };
|
|
26
|
+
const PROBE_PATH = `/API/GameFeed?GameID=${PROBE_GAME_ID}&GetMap=false`;
|
|
27
|
+
/** The page the bridge arm round-trips through the user's war.app tab. */
|
|
28
|
+
export const BRIDGE_PROBE_PATH = '/';
|
|
29
|
+
/** The non-secret facts about the linked direct session — never the token. */
|
|
30
|
+
function sessionSummary(env, now) {
|
|
31
|
+
const s = readSessionSync(env);
|
|
32
|
+
if (!s)
|
|
33
|
+
return { linked: false };
|
|
34
|
+
const ageSeconds = Math.max(0, Math.round((now() - Date.parse(s.capturedAt)) / 1000));
|
|
35
|
+
return { linked: true, capturedAt: s.capturedAt, ageSeconds };
|
|
36
|
+
}
|
|
37
|
+
/** Which leg is active (+ its configured mode) and the linked-session summary. */
|
|
38
|
+
function transportHealth(status, env, now) {
|
|
39
|
+
return { ...status, session: sessionSummary(env, now) };
|
|
40
|
+
}
|
|
41
|
+
export function registerHealthcheckTool(server, bridge, direct, deps = {}) {
|
|
42
|
+
const now = deps.now ?? Date.now;
|
|
43
|
+
registerAdaptiveHealthcheckTool({
|
|
44
|
+
server,
|
|
45
|
+
prefix: 'warapp',
|
|
46
|
+
hostLabel: 'war.app',
|
|
47
|
+
// The browser bridge is on the path only when THIS connection's
|
|
48
|
+
// direct-first router is on its fetchproxy leg (it fell back, or is pinned
|
|
49
|
+
// to fetchproxy) AND the bridge has carried a request. The fetchproxy
|
|
50
|
+
// bridge is shared process-wide, so its role alone is not enough: another
|
|
51
|
+
// connection may have used it while this one rides the direct leg (always,
|
|
52
|
+
// under WARAPP_TRANSPORT=direct). Otherwise the credential arm answers.
|
|
53
|
+
usingBridge: () => direct.status().transport === 'fetchproxy' && bridge.transport().role !== null,
|
|
54
|
+
bridge: {
|
|
55
|
+
probePath: BRIDGE_PROBE_PATH,
|
|
56
|
+
transport: () => bridge.transport(),
|
|
57
|
+
path: () => transportHealth(direct.status(), deps.env, now),
|
|
58
|
+
probeFn: async (path) => {
|
|
59
|
+
const res = await (await bridge.ready()).fetch({ method: 'GET', path });
|
|
60
|
+
if (res.status !== 200) {
|
|
61
|
+
throw new McpToolError(`war.app answered HTTP ${res.status} through the bridge.`, {
|
|
62
|
+
status: res.status,
|
|
63
|
+
kind: 'http',
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
return res.body;
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
credential: {
|
|
70
|
+
probePath: PROBE_PATH,
|
|
71
|
+
resolveCredential: async () => {
|
|
72
|
+
const health = transportHealth(direct.status(), deps.env, now);
|
|
73
|
+
try {
|
|
74
|
+
readCredentials(deps.env);
|
|
75
|
+
return { source: 'env', detail: health };
|
|
76
|
+
}
|
|
77
|
+
catch (e) {
|
|
78
|
+
if (e instanceof WarappConfigError)
|
|
79
|
+
return { source: null, detail: { ...health, reason: e.message } };
|
|
80
|
+
throw e;
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
probeFn: () => new WarappClient(deps).probeAuth(),
|
|
84
|
+
classifyThrown: (err) => err instanceof McpToolError && err.kind === 'credential_rejected'
|
|
85
|
+
? { kind: 'credential_rejected', hint: AUTH_FAILED_HINT }
|
|
86
|
+
: undefined,
|
|
87
|
+
hints: { no_credential: `Set WARAPP_EMAIL and WARAPP_API_TOKEN (token from ${TOKEN_URL}).` },
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** `_meta` for a war.app tool, with optional spoken aliases. */
|
|
2
|
+
export function mintMeta(intent, aliases) {
|
|
3
|
+
return { mint: aliases ? { domain: 'work', intent, aliases } : { domain: 'work', intent } };
|
|
4
|
+
}
|
|
5
|
+
/** `_meta` for the group's canonical tool for `intent` (it must accept `view: 'brief'`). */
|
|
6
|
+
export function canonicalMeta(intent, aliases) {
|
|
7
|
+
return { mint: { domain: 'work', intent, canonical: true, aliases } };
|
|
8
|
+
}
|
|
9
|
+
/** `_meta` for a war.app lookup, with optional spoken aliases. */
|
|
10
|
+
export function lookupMeta(aliases) {
|
|
11
|
+
return mintMeta('lookup', aliases);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Run `register` with `extra` (a `title`, `_meta`) merged into the config of
|
|
15
|
+
* every tool it registers — for mcp-utils' `registerWrite`, which builds the
|
|
16
|
+
* `registerTool` config itself and takes neither. The SAME server object is
|
|
17
|
+
* patched (not a proxy), so registerWrite's per-server registry still keys on
|
|
18
|
+
* the real server; the original is restored afterwards, even on a throw.
|
|
19
|
+
*/
|
|
20
|
+
export function withToolConfig(server, extra, register) {
|
|
21
|
+
const target = server;
|
|
22
|
+
const hadOwn = Object.hasOwn(target, 'registerTool');
|
|
23
|
+
const original = target.registerTool;
|
|
24
|
+
target.registerTool = (name, config, ...rest) => original.call(server, name, { ...config, ...extra }, ...rest);
|
|
25
|
+
try {
|
|
26
|
+
register();
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
if (hadOwn)
|
|
30
|
+
target.registerTool = original;
|
|
31
|
+
else
|
|
32
|
+
delete target.registerTool;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// How a lost game was lost (#274 item 5), for warapp_get_game (#283: also a seat of mine out of a game still playing): read from the boards this server
|
|
2
|
+
// cached while it played (src/analysis/how-lost.ts), kept name-free in the outlook log so it outlives
|
|
3
|
+
// the board cache, and reported with names through `untrustedText`. No request; never throws.
|
|
4
|
+
import { howLost } from '../analysis/how-lost.js';
|
|
5
|
+
import { readOutlookLog, readOutlookPlayer, recordLoss } from '../outlook-log.js';
|
|
6
|
+
import { readBoardHistory, readCachedOrders, readCachedPlayer } from '../trend.js';
|
|
7
|
+
import { untrustedText } from './common.js';
|
|
8
|
+
/** #283: the seat states that put me out of a game, whether or not the others play on. */
|
|
9
|
+
const OUT_STATES = new Set(['Eliminated', 'Booted', 'SurrenderAccepted']);
|
|
10
|
+
/** The causes a seat's state gives without a board (#283: `seatOut` adds the last turn and outlook). */
|
|
11
|
+
const STATE_CAUSES = {
|
|
12
|
+
SurrenderAccepted: { cause: 'surrendered', line: 'Surrendered (accepted).' },
|
|
13
|
+
Booted: { cause: 'booted', line: 'Booted from the game.' },
|
|
14
|
+
};
|
|
15
|
+
function report(loss, game) {
|
|
16
|
+
const playerName = (id) => untrustedText(game.players.find((p) => p.id === id)?.name ?? id);
|
|
17
|
+
const territoryName = (id) => {
|
|
18
|
+
const t = game.map?.territories.find((x) => x.id === id);
|
|
19
|
+
return t ? untrustedText(t.name) : null;
|
|
20
|
+
};
|
|
21
|
+
const named = (id) => {
|
|
22
|
+
const n = territoryName(id);
|
|
23
|
+
return n ? `${id} ${n}` : String(id);
|
|
24
|
+
};
|
|
25
|
+
const neighbours = loss.neighbours?.map((n) => ({ ...n, ...(n.playerId !== null ? { name: playerName(n.playerId) } : {}) })) ?? null;
|
|
26
|
+
const when = `Eliminated on turn ${loss.turn}${loss.turnCertain ? '' : ' (the last turn cached here; the loss may have come later)'}`;
|
|
27
|
+
const bordered = neighbours?.length
|
|
28
|
+
? ` Bordered by ${neighbours
|
|
29
|
+
.map((n) => `${n.playerId === null ? 'owners hidden by the fog' : n.name} on ${n.territories} territor${n.territories === 1 ? 'y' : 'ies'}${n.armies !== null ? ` (${n.armies} armies in view)` : ''}`)
|
|
30
|
+
.join(', ')}.`
|
|
31
|
+
: '';
|
|
32
|
+
const by = loss.by !== null ? ` to ${playerName(loss.by)}` : '';
|
|
33
|
+
let line;
|
|
34
|
+
const c = loss.commander;
|
|
35
|
+
if (c) {
|
|
36
|
+
const range = c.held ? `${c.held.low}${c.held.high !== c.held.low ? `–${c.held.high}` : ''}` : '';
|
|
37
|
+
const held = c.held
|
|
38
|
+
? ` It held ${c.held.uncertain ? `about ${range}` : range} armies and the commander (${c.armies} at the start of the turn, +${c.deployed} deployed, −${c.movedOut} moved out, +${c.movedIn} moved in${c.walk ? `, the walk's ${c.walk.armies} among them` : ''}); taking that needs at least ${c.attackersNeeded} attackers${c.exact ? '' : ' (at the expectation: the game has luck)'}${c.held.uncertain ? ' — a bound only: an order this count leaves out (a percentage, Attack Only or Transfer Only order, or a card play) touched it' : ''}.`
|
|
39
|
+
: c.walk
|
|
40
|
+
? ` My orders that turn do not say what it held there${c.walk.armies === null ? ' (the walk was a percentage order)' : ''}.`
|
|
41
|
+
: ` It started the turn with ${c.armies} armies and the commander; my orders that turn are not cached, so what it held is unknown.`;
|
|
42
|
+
line = c.walk
|
|
43
|
+
? `${when}: my commander walked from ${named(c.walk.from)} to ${named(c.territoryId)} that turn; it fell on ${named(c.territoryId)}${by}, or on ${named(c.walk.from)} before the walk ran (inferred: losing the commander ends the game for me; which of the two is not known).${held}${bordered}`
|
|
44
|
+
: `${when}: my commander's territory ${named(c.territoryId)} fell${by} (inferred: losing the commander ends the game for me).${held}${bordered}`;
|
|
45
|
+
}
|
|
46
|
+
else if (loss.cause === 'last-territories') {
|
|
47
|
+
const ids = (loss.lastTerritories ?? []).map((t) => named(t.territoryId)).join(', ');
|
|
48
|
+
line = `${when}: my last ${loss.territoriesHeld} territor${loss.territoriesHeld === 1 ? 'y' : 'ies'} fell${by} (${ids}${loss.territoriesHeld > (loss.lastTerritories?.length ?? 0) ? ', …' : ''}).${bordered}`;
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
line = `${when}; the cached board does not show my commander, so the cause is unknown.`;
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
result: 'Eliminated',
|
|
55
|
+
...loss,
|
|
56
|
+
...(c ? { commander: { ...c, territoryName: territoryName(c.territoryId) } } : {}),
|
|
57
|
+
neighbours,
|
|
58
|
+
by: loss.by !== null ? { id: loss.by, name: playerName(loss.by) } : null,
|
|
59
|
+
line,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** The newest turn this server played `gameId` on: a cached board where I held land, or a logged outlook. */
|
|
63
|
+
async function lastPlayed(dir, gameId, me) {
|
|
64
|
+
const log = await readOutlookLog(dir, gameId, me);
|
|
65
|
+
const boards = await readBoardHistory(dir, gameId, me);
|
|
66
|
+
const held = boards
|
|
67
|
+
.filter((b) => b.board.territories.some((t) => t.owner.kind === 'player' && t.owner.playerId === me))
|
|
68
|
+
.map((b) => b.turn);
|
|
69
|
+
const logged = Object.keys(log?.turns ?? {}).map(Number).filter(Number.isInteger);
|
|
70
|
+
const all = [...held, ...logged];
|
|
71
|
+
return all.length ? { turn: Math.max(...all), log } : undefined;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* #283: a surrender or a boot, by my seat's state, with the last turn played here and the outlook logged
|
|
75
|
+
* last (its state, and my armies and income against the strongest side's in view, when logged).
|
|
76
|
+
*/
|
|
77
|
+
function seatOut(result, byState, last, game) {
|
|
78
|
+
if (!last)
|
|
79
|
+
return { result, ...byState };
|
|
80
|
+
const { turn, log } = last;
|
|
81
|
+
const loggedTurn = Math.max(...Object.keys(log?.turns ?? {}).map(Number).filter(Number.isInteger).filter((t) => t <= turn));
|
|
82
|
+
const entry = Number.isFinite(loggedTurn) ? log.turns[String(loggedTurn)] : undefined;
|
|
83
|
+
const head = `${byState.line} The last turn played here was turn ${turn}`;
|
|
84
|
+
if (!entry)
|
|
85
|
+
return { result, ...byState, turn, line: `${head}; no outlook was logged for it.` };
|
|
86
|
+
const held = log.latest && log.latest.turn === loggedTurn && log.latest.state !== null ? { state: log.latest.state, turns: log.latest.heldTurns } : undefined;
|
|
87
|
+
const f = entry.figures;
|
|
88
|
+
const s = f?.strongest;
|
|
89
|
+
const who = s
|
|
90
|
+
? s.team !== undefined
|
|
91
|
+
? `team ${s.team}`
|
|
92
|
+
: untrustedText(game.players.find((p) => p.id === s.playerId)?.name ?? s.playerId)
|
|
93
|
+
: undefined;
|
|
94
|
+
const outlook = {
|
|
95
|
+
turn: loggedTurn,
|
|
96
|
+
state: entry.state,
|
|
97
|
+
...(held ? { held } : {}),
|
|
98
|
+
...(f ? { mine: f.mine } : {}),
|
|
99
|
+
...(s ? { strongest: { id: s.playerId, ...(s.team !== undefined ? { team: s.team } : {}), name: who, armies: s.armies, income: s.income } } : {}),
|
|
100
|
+
};
|
|
101
|
+
const read = `${loggedTurn === turn ? 'its outlook' : `the last outlook logged (turn ${loggedTurn})`} read ${entry.state}${held ? ` (held ${held.turns} turn${held.turns === 1 ? '' : 's'})` : ''}`;
|
|
102
|
+
const figures = !f
|
|
103
|
+
? ' (the armies and income behind it were not logged then)'
|
|
104
|
+
: `: my income ${f.mine.income} and ${f.mine.armies} armies${s ? ` against ${who}'s ${s.income} and ${s.armies} in view` : ', no opponent in view'}`;
|
|
105
|
+
return { result, ...byState, turn, outlook, line: `${head}; ${read}${figures}.` };
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* How `game` was lost, when the account this server cached it for did not win it: once it is finished,
|
|
109
|
+
* or (#283) while it is still playing once my seat is out (eliminated, booted or surrendered). A
|
|
110
|
+
* surrender or a boot by its state, an elimination from the cached boards (kept in the outlook log
|
|
111
|
+
* the first time, read back from there once the boards are gone). `undefined` otherwise.
|
|
112
|
+
*/
|
|
113
|
+
export async function lossReport(dir, game) {
|
|
114
|
+
try {
|
|
115
|
+
const finished = game.state === 'Finished';
|
|
116
|
+
// #283: a seat of mine that is out is reported while the others play on; no disk read otherwise.
|
|
117
|
+
if (!finished && !game.players.some((p) => p.state !== undefined && OUT_STATES.has(p.state)))
|
|
118
|
+
return undefined;
|
|
119
|
+
const me = (await readCachedPlayer(dir, game.id)) ?? (await readOutlookPlayer(dir, game.id));
|
|
120
|
+
if (me === undefined)
|
|
121
|
+
return undefined;
|
|
122
|
+
const state = game.players.find((p) => p.id === me)?.state;
|
|
123
|
+
if (state === undefined || (!finished && !OUT_STATES.has(state)))
|
|
124
|
+
return undefined;
|
|
125
|
+
const byState = STATE_CAUSES[state];
|
|
126
|
+
if (byState)
|
|
127
|
+
return seatOut(state, byState, await lastPlayed(dir, game.id, me), game);
|
|
128
|
+
if (state !== 'Eliminated')
|
|
129
|
+
return undefined;
|
|
130
|
+
const boards = await readBoardHistory(dir, game.id, me);
|
|
131
|
+
const s = game.settings;
|
|
132
|
+
const fresh = howLost({
|
|
133
|
+
me,
|
|
134
|
+
boards,
|
|
135
|
+
orders: await readCachedOrders(dir, game.id, me),
|
|
136
|
+
...(game.map ? { adjacency: new Map(game.map.territories.map((t) => [t.id, t.connectedTo])) } : {}),
|
|
137
|
+
rates: {
|
|
138
|
+
...(s?.offensiveKillRate !== undefined ? { offensiveKillRate: s.offensiveKillRate } : {}),
|
|
139
|
+
...(s?.defensiveKillRate !== undefined ? { defensiveKillRate: s.defensiveKillRate } : {}),
|
|
140
|
+
...(s?.luckModifier !== undefined ? { luck: s.luckModifier } : {}),
|
|
141
|
+
...(s?.roundingMode !== undefined ? { rounding: s.roundingMode } : {}),
|
|
142
|
+
},
|
|
143
|
+
...(game.numberOfTurns !== undefined ? { turnsCompleted: game.numberOfTurns } : {}),
|
|
144
|
+
...(s?.commanders !== undefined ? { commanders: s.commanders } : {}),
|
|
145
|
+
});
|
|
146
|
+
if (fresh)
|
|
147
|
+
await recordLoss(dir, game.id, me, fresh);
|
|
148
|
+
const loss = fresh ?? (await readOutlookLog(dir, game.id, me))?.loss;
|
|
149
|
+
return loss ? report(loss, game) : undefined;
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return undefined;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { defaultMapCache, WarappClient } from '../client.js';
|
|
2
|
+
import { dataDir } from '../config.js';
|
|
3
|
+
import { StatsCollector } from '../stats.js';
|
|
4
|
+
import { registerBeginTurnTool } from './begin-turn.js';
|
|
5
|
+
import { registerBoardTool } from './board.js';
|
|
6
|
+
import { registerChatTools } from './chat.js';
|
|
7
|
+
import { registerChatInboxTool } from './chat-inbox.js';
|
|
8
|
+
import { registerMarkChatReadTool } from './chat-read-mark.js';
|
|
9
|
+
import { registerCheckPlanTool } from './check-plan.js';
|
|
10
|
+
import { registerGameTool } from './game.js';
|
|
11
|
+
import { registerHealthcheckTool } from './healthcheck.js';
|
|
12
|
+
import { createLiveContext } from './live-context.js';
|
|
13
|
+
import { registerJoinGameTool } from './join-game.js';
|
|
14
|
+
import { registerLiveTools } from './live.js';
|
|
15
|
+
import { registerMapTool } from './map.js';
|
|
16
|
+
import { registerMapStatsTool } from './map-stats.js';
|
|
17
|
+
import { registerMyGamesTool } from './my-games.js';
|
|
18
|
+
import { registerNotificationTools } from './notifications.js';
|
|
19
|
+
import { registerOpenGamesTool } from './open-games.js';
|
|
20
|
+
import { registerOpponentsTool } from './opponents.js';
|
|
21
|
+
import { registerPickTools } from './picks.js';
|
|
22
|
+
import { registerPushTools } from './push.js';
|
|
23
|
+
import { registerRelationsTools } from './relations.js';
|
|
24
|
+
import { registerDiplomacyTool } from './diplomacy.js';
|
|
25
|
+
import { registerRouteTool } from './route.js';
|
|
26
|
+
import { registerScoutTool } from './scout.js';
|
|
27
|
+
import { registerSessionTools } from './session.js';
|
|
28
|
+
import { registerStrategyTool } from './strategy.js';
|
|
29
|
+
import { registerSurrenderTool } from './surrender.js';
|
|
30
|
+
import { registerAcceptSurrenderTool } from './accept-surrender.js';
|
|
31
|
+
import { registerTeamTool } from './team.js';
|
|
32
|
+
import { registerTeamBriefTool } from './team-brief.js';
|
|
33
|
+
import { registerTurnTools } from './turn.js';
|
|
34
|
+
import { registerUncommitTool } from './uncommit.js';
|
|
35
|
+
import { registerLeaveGameTool } from './leave-game.js';
|
|
36
|
+
import { registerWhereTool } from './where.js';
|
|
37
|
+
import { registerProfileOpponentsTool } from './profile-opponents.js';
|
|
38
|
+
import { pushListenerFor } from '../push/listener.js';
|
|
39
|
+
import { pushWebSocketLeg } from '../push/websocket.js';
|
|
40
|
+
import { readSession } from '../direct/session.js';
|
|
41
|
+
import { createDirectFirstBridge } from '../direct/transport.js';
|
|
42
|
+
import { isHosted } from '../hosted.js';
|
|
43
|
+
import { createWarappBridge } from '../transport-bridge.js';
|
|
44
|
+
/** Every tool this server serves. index.ts and the tests share this list. */
|
|
45
|
+
export function registerAllTools(server, deps = {}) {
|
|
46
|
+
// One client for the game tools, so they share the map cache. Config is
|
|
47
|
+
// deferred: the client reads credentials per call, never at construction.
|
|
48
|
+
// The map cache is kept on disk too (`<dataDir>/maps/`, src/map-store.ts),
|
|
49
|
+
// local and hosted (a hosted child's per-user data dir persists).
|
|
50
|
+
const client = new WarappClient({ ...deps, dataDir: () => dataDir(deps.env) });
|
|
51
|
+
const env = deps.env;
|
|
52
|
+
// The process's browser bridge (fetchproxy), shared across connections.
|
|
53
|
+
const fetchproxy = deps.bridge ?? createWarappBridge(env ? { env } : {});
|
|
54
|
+
// Wrap it in the direct-first router: the chrome-less AuthToken leg
|
|
55
|
+
// (src/direct/) serves calls when a session is linked and falls back to the
|
|
56
|
+
// browser bridge otherwise (WARAPP_TRANSPORT: auto default | direct |
|
|
57
|
+
// fetchproxy). WarappRpc, the page fetches, the healthcheck and the push
|
|
58
|
+
// socket all take this one bridge, so they all gain direct mode at once.
|
|
59
|
+
// Direct mode is LOCAL-ONLY (src/hosted.ts): on a hosted child the router is
|
|
60
|
+
// pinned to the browser bridge, the session store reads as empty and
|
|
61
|
+
// warapp_link_session is not registered.
|
|
62
|
+
const hosted = isHosted(env ?? process.env);
|
|
63
|
+
const bridge = createDirectFirstBridge({
|
|
64
|
+
store: { read: () => readSession(deps.env) },
|
|
65
|
+
makeBridge: () => fetchproxy,
|
|
66
|
+
...(env ? { env } : {}),
|
|
67
|
+
...(deps.directFetch ? { directFetch: deps.directFetch } : {}),
|
|
68
|
+
});
|
|
69
|
+
const live = createLiveContext({
|
|
70
|
+
client,
|
|
71
|
+
bridge,
|
|
72
|
+
...(deps.env ? { env: deps.env } : {}),
|
|
73
|
+
...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
|
|
74
|
+
...(deps.bundle ? { bundle: deps.bundle } : {}),
|
|
75
|
+
// The cached signed-in account is discarded whenever the account behind the router may have changed.
|
|
76
|
+
identity: () => bridge.identityState(),
|
|
77
|
+
});
|
|
78
|
+
registerHealthcheckTool(server, fetchproxy, bridge, deps);
|
|
79
|
+
// The signed-in account names a finished game's player for its end-of-game pass when no board was cached (#312).
|
|
80
|
+
registerGameTool(server, client, () => dataDir(deps.env), deps.env, () => live.myInviteToken());
|
|
81
|
+
registerMapTool(server, client, live);
|
|
82
|
+
// Opt-in (WARAPP_STATS=1), never hosted: the tool refuses before any request
|
|
83
|
+
// when off. One collector per registration, so its 1 s throttle spans calls.
|
|
84
|
+
registerMapStatsTool(server, {
|
|
85
|
+
collector: new StatsCollector({
|
|
86
|
+
client,
|
|
87
|
+
dir: () => dataDir(deps.env),
|
|
88
|
+
...(deps.sleep ? { sleep: deps.sleep } : {}),
|
|
89
|
+
}),
|
|
90
|
+
mapCache: deps.mapCache ?? defaultMapCache,
|
|
91
|
+
dataDir: () => dataDir(deps.env),
|
|
92
|
+
...(deps.env ? { env: deps.env } : {}),
|
|
93
|
+
});
|
|
94
|
+
registerBoardTool(server, client, live);
|
|
95
|
+
registerRouteTool(server, client);
|
|
96
|
+
registerStrategyTool(server, client, live);
|
|
97
|
+
registerLiveTools(server, live);
|
|
98
|
+
registerPickTools(server, live, deps.env ? { env: deps.env } : {});
|
|
99
|
+
registerMyGamesTool(server, live, deps.env ? { env: deps.env } : {});
|
|
100
|
+
registerOpenGamesTool(server, live);
|
|
101
|
+
registerJoinGameTool(server, live);
|
|
102
|
+
registerLeaveGameTool(server, live);
|
|
103
|
+
registerSurrenderTool(server, live);
|
|
104
|
+
registerAcceptSurrenderTool(server, live);
|
|
105
|
+
registerBeginTurnTool(server, live);
|
|
106
|
+
registerScoutTool(server, live, deps.env ? { env: deps.env } : {});
|
|
107
|
+
registerTurnTools(server, live, deps.env ? { env: deps.env } : {});
|
|
108
|
+
registerCheckPlanTool(server, live);
|
|
109
|
+
registerOpponentsTool(server, live, deps.env ? { env: deps.env } : {});
|
|
110
|
+
// Reads the map statistics cache only when they are on (WARAPP_STATS=1, never hosted).
|
|
111
|
+
registerWhereTool(server, live, deps.env ? { env: deps.env } : {});
|
|
112
|
+
// Opponent profiling, read-only: habits counted from the boards seen (on unless WARAPP_PLAYER_PROFILE=off).
|
|
113
|
+
registerProfileOpponentsTool(server, live, deps.env ? { env: deps.env } : {});
|
|
114
|
+
registerUncommitTool(server, live);
|
|
115
|
+
registerChatTools(server, live, deps.env ? { env: deps.env } : {});
|
|
116
|
+
registerChatInboxTool(server, live);
|
|
117
|
+
// Local and hosted: war.app's own chat read mark, confirm-gated (#311).
|
|
118
|
+
registerMarkChatReadTool(server, live);
|
|
119
|
+
// Local and hosted: the account's own notifications, through its war.app tab.
|
|
120
|
+
registerNotificationTools(server, live, deps.env ? { env: deps.env } : {});
|
|
121
|
+
registerTeamTool(server, live);
|
|
122
|
+
// C4: the team brief, read-only — the facts for a team-chat message, never sent.
|
|
123
|
+
registerTeamBriefTool(server, live);
|
|
124
|
+
// The agreement ledger: one read-only tool, and one that writes only the local ledger (not confirm-gated).
|
|
125
|
+
registerRelationsTools(server, live, deps.env ? { env: deps.env } : {});
|
|
126
|
+
// B3: truce advice (read-only): prices a deal by planning with and without it; reads no chat.
|
|
127
|
+
registerDiplomacyTool(server, live, deps.env ? { env: deps.env } : {});
|
|
128
|
+
// One push socket per process: keyed on the shared fetchproxy bridge so
|
|
129
|
+
// connections share it, with requests routed through the direct-first bridge.
|
|
130
|
+
// While the direct leg is active the push rides a direct WebSocket (the
|
|
131
|
+
// cookie goes only to war.app); otherwise, or when the WebSocket cannot come
|
|
132
|
+
// up, it keeps xhr-polling over the bridge.
|
|
133
|
+
const push = deps.push ??
|
|
134
|
+
pushListenerFor(fetchproxy, {
|
|
135
|
+
transport: () => bridge.ready(),
|
|
136
|
+
webSocket: pushWebSocketLeg(bridge, () => readSession(deps.env)),
|
|
137
|
+
extras: () => live.rpc.extras,
|
|
138
|
+
});
|
|
139
|
+
registerSessionTools(server, {
|
|
140
|
+
transport: {
|
|
141
|
+
activeLeg: () => bridge.status().transport,
|
|
142
|
+
sessionStale: () => bridge.sessionStale(),
|
|
143
|
+
sessionLinked: () => bridge.sessionLinked(),
|
|
144
|
+
},
|
|
145
|
+
pushTransport: () => push.status().transport,
|
|
146
|
+
decoder: () => live.decoderReport(),
|
|
147
|
+
identityChanged: () => live.forgetIdentity(),
|
|
148
|
+
hosted,
|
|
149
|
+
...(env ? { env } : {}),
|
|
150
|
+
});
|
|
151
|
+
registerPushTools(server, live, push, deps.env ? { env: deps.env } : {});
|
|
152
|
+
}
|