@chrischall/warapp-mcp 0.23.1 → 0.24.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/dist/chat.js CHANGED
@@ -17,6 +17,7 @@ import { asInt } from './scalars.js';
17
17
  export const GAME_DETAILS_AND_CHAT = 'warlight.shared.GameDetailsAndChat';
18
18
  export const GAME_MESSAGE = 'warlight.shared.GameMessage';
19
19
  export const MESSAGE_REACTION = 'warlight.shared.MessageReaction';
20
+ export const GAME_GROUP = 'warlight.shared.GameGroup';
20
21
  /**
21
22
  * `warlight.shared.ReactionType`, one byte, by its value (#634): the client's reaction menu lists exactly these five
22
23
  * (its labels "Thumbs up", "Thumbs down", "Heart", "Laugh", "Angry").
@@ -24,6 +25,14 @@ export const MESSAGE_REACTION = 'warlight.shared.MessageReaction';
24
25
  export const REACTION_TYPES = ['thumbs-up', 'thumbs-down', 'heart', 'laugh', 'angry'];
25
26
  /** GameDetailsAndChat's reactions (243): a dict of message id → that message's reactions, read by position. */
26
27
  const GDC_REACTIONS = 5;
28
+ /** GameDetailsAndChat's game groups: a list of optional `GameGroup`, last. */
29
+ const GDC_GROUPS = 6;
30
+ /**
31
+ * GameGroup field positions in read order (docs/WEB-PROTOCOL.md, Chat): colour, creator, moderator, game id, the group
32
+ * id, metadata, name, then the members as text (a JSON array of in-game ids, the creator included).
33
+ */
34
+ const GG = { creator: 1, gameId: 3, id: 4, name: 6, members: 7 };
35
+ const GAME_GROUP_FIELDS = 8;
27
36
  /**
28
37
  * GameMessage field positions in read order, and its whole field count (protocol 243: the shared images,
29
38
  * an optional list of strings, at 5, and the reactions, an optional list of records, at 7).
@@ -195,6 +204,70 @@ function applyReactionsDict(lines, dict) {
195
204
  setReactions(line, byId.get(line.id));
196
205
  }
197
206
  }
207
+ /** The members text of a GameGroup: a JSON array of in-game ids, else `null`. */
208
+ function groupMembers(text) {
209
+ if (typeof text !== 'string')
210
+ return null;
211
+ try {
212
+ const v = JSON.parse(text);
213
+ if (!Array.isArray(v))
214
+ return null;
215
+ const ids = v.map((x) => (typeof x === 'string' && /^-?\d+$/.test(x) ? Number(x) : x));
216
+ return ids.every(isInt) ? ids : null;
217
+ }
218
+ catch {
219
+ return null;
220
+ }
221
+ }
222
+ /**
223
+ * The game's groups from a GameRefresh reply (the body at the result-present flag): `[]` when the list is there and
224
+ * empty, `undefined` when it is absent, there is no result, or the shape is not understood. Never throws.
225
+ */
226
+ export function readGameGroups(bundle, body) {
227
+ try {
228
+ if (!body.bool())
229
+ return undefined;
230
+ const ret = bundle.readClass(GAME_DETAILS_AND_CHAT, body);
231
+ if (!isObj(ret) || ret.$type !== GAME_DETAILS_AND_CHAT)
232
+ return undefined;
233
+ const list = fields(ret)[GDC_GROUPS];
234
+ if (!Array.isArray(list))
235
+ return undefined;
236
+ const out = [];
237
+ for (const g of list) {
238
+ if (g === null)
239
+ continue;
240
+ if (!isObj(g) || g.$type !== GAME_GROUP)
241
+ return undefined;
242
+ const f = fields(g);
243
+ if (f.length !== GAME_GROUP_FIELDS)
244
+ return undefined;
245
+ const [id, gameId, creator, name] = [f[GG.id], f[GG.gameId], f[GG.creator], f[GG.name]];
246
+ if (!isInt(id) || !isInt(gameId) || !isInt(creator) || typeof name !== 'string')
247
+ return undefined;
248
+ out.push({ id, gameId, creator, name, members: groupMembers(f[GG.members]) });
249
+ }
250
+ return out;
251
+ }
252
+ catch {
253
+ return undefined;
254
+ }
255
+ }
256
+ /**
257
+ * The CreateGameGroup reply: a present flag, then the group's first message, whose game-group field is the new group's
258
+ * id. `undefined` when there is no result or no group id in it. Never throws.
259
+ */
260
+ export function readCreateGameGroupReply(bundle, body) {
261
+ try {
262
+ if (!body.bool())
263
+ return undefined;
264
+ const line = webLine(bundle.readClass(GAME_MESSAGE, body));
265
+ return line?.group;
266
+ }
267
+ catch {
268
+ return undefined;
269
+ }
270
+ }
198
271
  /**
199
272
  * The SendChat reply: the updated message list, read straight after the result-present flag (each
200
273
  * message behind its own present flag), oldest first; `undefined` when it cannot be read. The replies of
@@ -103,6 +103,8 @@ export const Method = {
103
103
  ForumVote: 204,
104
104
  WatchForumThread: 328,
105
105
  GetGroupForumThreads: 354,
106
+ /** A game group: a private conversation of several players in one game (the bundle's writer; UNVERIFIED live). */
107
+ CreateGameGroup: 356,
106
108
  Subscribe: 243,
107
109
  /** #633: the client's "Game Invite Code" screen (`GameInviteCode` reply); read from the bundle, UNVERIFIED live. */
108
110
  GetGameByInviteCode: 295,
@@ -486,6 +488,23 @@ function checkIds(ids, what) {
486
488
  function writeOptionalIntList(w, ids) {
487
489
  w.bool(true).list(ids, (ww, id) => ww.int32(id));
488
490
  }
491
+ /** The colour a new game group gets: the client's default, "Normal". */
492
+ export const GAME_GROUP_COLOUR = 13811880;
493
+ /**
494
+ * CreateGameGroup(auth, …) — the client's "Create Game Group": the int32 game id, the name (string), the int32 colour
495
+ * ({@link GAME_GROUP_COLOUR}), then a present, counted list of the other members' int32 in-game ids. Reply: a present
496
+ * flag and the group's first `GameMessage`, whose game-group field is the new group's id. Read from the bundle's
497
+ * writer; UNVERIFIED live.
498
+ */
499
+ export function writeCreateGameGroupParams(w, p) {
500
+ if (p.members.length === 0)
501
+ throw new RangeError('no members');
502
+ checkIds(p.members, 'player id');
503
+ if (p.name.trim() === '')
504
+ throw new RangeError('a game group needs a name');
505
+ w.int32(p.gameId).string(p.name).int32(GAME_GROUP_COLOUR);
506
+ writeOptionalIntList(w, p.members);
507
+ }
489
508
  /**
490
509
  * CreatePrivateDiscussion(auth, …) — the client's "Send mail": the subject (string), a present list (int32 count) of
491
510
  * the recipients' int32 ids, the body (string), an optional list of shared-image strings (sent absent), then the
@@ -829,20 +848,27 @@ export function writeRetrievePrivateMessageHistoryParams(w, p) {
829
848
  /**
830
849
  * SendChat(auth, …) per docs/WEB-PROTOCOL.md (read from the client's
831
850
  * serializer; the owner verifies it live): game id, text, channel, optional
832
- * private recipient, optional game-group id (absent), two marker strings
851
+ * private recipient, optional game-group id, two marker strings
833
852
  * (`-1`: seen nothing), two optional "last seen" dicts (absent). An optional int32 is a
834
853
  * present flag then the value.
835
854
  */
836
855
  export function writeSendChatParams(w, p) {
856
+ if (p.group !== undefined && p.recipient !== undefined)
857
+ throw new RangeError('a message cannot go both to a group and privately');
837
858
  w.int32(p.gameId).string(p.text).int32(p.channel ?? CHAT_CHANNEL_PUBLIC);
838
859
  if (p.recipient === undefined)
839
860
  w.bool(false);
840
861
  else
841
862
  w.bool(true).int32(p.recipient);
863
+ if (p.group === undefined)
864
+ w.bool(false);
865
+ else {
866
+ checkIds([p.group], 'game group id');
867
+ w.bool(true).int32(p.group);
868
+ }
842
869
  // The two chat markers are the last message seen on each channel: war.app parses them as numbers
843
870
  // (ParseLongSafe), so a null one is refused (server error 1); a client that has seen nothing sends `-1`.
844
- w.bool(false) // game-group id
845
- .string(NO_CHAT_MARKER)
871
+ w.string(NO_CHAT_MARKER)
846
872
  .string(NO_CHAT_MARKER)
847
873
  .bool(false)
848
874
  .bool(false)
@@ -6,7 +6,7 @@
6
6
  import { profileFormatOf } from '../analysis/opponent-profile.js';
7
7
  import { trackGame } from '../analysis/opponents.js';
8
8
  import { applyBonusOverrides } from '../analysis/overrides.js';
9
- import { aggregateBenchmarks, aggregateEstimates, benchmarkByEra, estimateSamples, openingBenchmark, openingEra, openingFlags, ratioSummary, } from '../analysis/calibrate.js';
9
+ import { aggregateBenchmarks, aggregateEstimates, benchmarkByEra, earlyLossesByEra, estimateSamples, openingBenchmark, openingEra, openingFlags, openingLosses, ratioSummary, } from '../analysis/calibrate.js';
10
10
  import { addCalibration } from '../analysis/game-lessons.js';
11
11
  import { calibrationSources } from '../calibration-source.js';
12
12
  import { holdsSeat } from '../player-states.js';
@@ -32,6 +32,7 @@ export async function calibrationHarness(dir, opts = {}) {
32
32
  const byFormat = {};
33
33
  const benchByFormat = {};
34
34
  const eraEntries = [];
35
+ const lossEntries = [];
35
36
  let done = 0;
36
37
  for (const input of src.inputs) {
37
38
  opts.signal?.throwIfAborted();
@@ -76,13 +77,28 @@ export async function calibrationHarness(dir, opts = {}) {
76
77
  winners: seated.filter((p) => p.state === 'Won').map((p) => p.id),
77
78
  ...(opts.turns ? { turns: opts.turns } : {}),
78
79
  });
80
+ // #503: the era (turn-1 time where known — no record keeps one yet — else the game id).
81
+ const o = input.opening;
82
+ const { era, basis } = openingEra({ planned: o.planned, ...(o.gameId !== undefined ? { gameId: o.gameId } : {}) });
83
+ // #506: land lost to a player in the opening, mine against the winner's (a teammate's capture is no loss).
84
+ const allies = (id) => {
85
+ const team = seated.find((p) => p.id === id)?.team;
86
+ return typeof team === 'number' && team >= 0 ? seated.filter((p) => p.id !== id && p.team === team).map((p) => p.id) : [];
87
+ };
88
+ const won = seated.filter((p) => p.state === 'Won').map((p) => p.id);
89
+ const iWon = won.includes(me);
90
+ const winner = iWon ? me : won[0];
91
+ lossEntries.push({
92
+ era,
93
+ format,
94
+ mine: openingLosses({ player: me, history: h.boards, allies: allies(me) }),
95
+ winner: winner === undefined ? null : openingLosses({ player: winner, history: h.boards, allies: allies(winner) }),
96
+ iWon,
97
+ });
79
98
  if (bench.turns.length) {
80
99
  counts.benchmarked++;
81
100
  (benchByFormat[format] ??= []).push(bench);
82
- // #503: the era (turn-1 time where known — no record keeps one yet — else the game id) and the
83
- // opening window's flags (turns with no orders of mine, a boot of my seat).
84
- const o = input.opening;
85
- const { era, basis } = openingEra({ planned: o.planned, ...(o.gameId !== undefined ? { gameId: o.gameId } : {}) });
101
+ // #503: the opening window's flags (turns with no orders of mine, a boot of my seat).
86
102
  const flags = openingFlags({
87
103
  me,
88
104
  history: h.boards,
@@ -105,5 +121,5 @@ export async function calibrationHarness(dir, opts = {}) {
105
121
  for (const [format, list] of Object.entries(benchByFormat))
106
122
  benchmark[format] = aggregateBenchmarks(list);
107
123
  benchmark.all = aggregateBenchmarks(Object.values(benchByFormat).flat());
108
- return { counts, calibration, benchmark, byEra: benchmarkByEra(eraEntries) };
124
+ return { counts, calibration, benchmark, byEra: benchmarkByEra(eraEntries), earlyLosses: earlyLossesByEra(lossEntries) };
109
125
  }
@@ -0,0 +1,133 @@
1
+ // warapp_calibration's `harness: true` as a background job. The harness replays every finished game and can run
2
+ // for most of an hour on a hosted data dir; a tool call cannot wait that long: Claude Code ends a call silent for
3
+ // CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT, mcp-host ends any call after 30 minutes, and claude.ai sends no progress token,
4
+ // so per-game progress cannot keep the call alive (mcp-utils docs/CLIENT-BEHAVIOUR.md). So the first call starts
5
+ // the run and returns; later calls read its progress, then its result, which is kept at
6
+ // `<dataDir>/calibration/harness.json` (aggregates only, name-free) so a restart still has it.
7
+ //
8
+ // The run goes in a worker thread (src/tools/calibration-worker.ts): each game is synchronous planner work, and on
9
+ // the main thread a long game would hold every other tool call of the server (the play session's) until it ended.
10
+ // Without the worker's file (a test run from src/) it runs on the main thread, yielding between games.
11
+ import { existsSync } from 'node:fs';
12
+ import { readFile } from 'node:fs/promises';
13
+ import { join } from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { Worker } from 'node:worker_threads';
16
+ import { writeJsonAtomic } from '../map-store.js';
17
+ import { calibrationHarness } from './calibration-harness.js';
18
+ /** A run is stopped after this long (a stuck worker must not hold the job forever). */
19
+ export const HARNESS_LIMIT_MS = 3 * 60 * 60 * 1000;
20
+ export const harnessFolder = (dir) => join(dir, 'calibration');
21
+ export const harnessResultPath = (dir) => join(harnessFolder(dir), 'harness.json');
22
+ const jobs = new Map();
23
+ /** Forget every job in memory (a restart, in tests). */
24
+ export function resetHarnessJobs() {
25
+ for (const j of jobs.values())
26
+ if (j.state === 'running')
27
+ j.stop();
28
+ jobs.clear();
29
+ }
30
+ async function readSaved(dir) {
31
+ try {
32
+ const v = JSON.parse(await readFile(harnessResultPath(dir), 'utf8'));
33
+ return typeof v.finishedAt === 'string' && typeof v.result === 'object' && v.result !== null ? v : undefined;
34
+ }
35
+ catch {
36
+ return undefined;
37
+ }
38
+ }
39
+ const iso = (ms) => new Date(ms).toISOString();
40
+ const minutes = (ms) => Math.round(ms / 60_000);
41
+ /**
42
+ * The harness job over `dir`: starts a run when none is running and none is saved (or `rerun`), else reports
43
+ * the running one or the saved result. Never waits on the run. `peek` reads the state only: it starts nothing and
44
+ * leaves a failure to be reported (`none` when there is no run and no saved result).
45
+ */
46
+ export async function harnessJob(dir, opts = {}) {
47
+ const now = opts.now ?? Date.now;
48
+ const limit = opts.limitMs ?? HARNESS_LIMIT_MS;
49
+ const job = jobs.get(dir);
50
+ if (job?.state === 'running') {
51
+ const ran = now() - job.startedAt;
52
+ if (ran > limit) {
53
+ job.stop();
54
+ const error = `The harness was stopped after ${minutes(limit)} minute${minutes(limit) === 1 ? '' : 's'} (${job.done} of ${job.total ?? '?'} games done).`;
55
+ jobs.set(dir, { state: 'failed', error });
56
+ return harnessJob(dir, opts);
57
+ }
58
+ const previous = await readSaved(dir);
59
+ return { status: 'running', done: job.done, total: job.total, startedAt: iso(job.startedAt), minutesRunning: minutes(ran), ...(previous ? { previous } : {}) };
60
+ }
61
+ if (job?.state === 'failed') {
62
+ // Reported once: the next call starts again.
63
+ if (!opts.peek)
64
+ jobs.delete(dir);
65
+ return { status: 'failed', error: job.error };
66
+ }
67
+ const saved = await readSaved(dir);
68
+ if (saved && !opts.rerun)
69
+ return { status: 'done', finishedAt: saved.finishedAt, result: saved.result };
70
+ if (opts.peek)
71
+ return { status: 'none' };
72
+ const startedAt = now();
73
+ const running = { state: 'running', startedAt, done: 0, total: null, stop: () => undefined };
74
+ const handle = (opts.run ?? defaultRunner())(dir, (done, total) => {
75
+ running.done = done;
76
+ running.total = total;
77
+ });
78
+ running.stop = handle.stop;
79
+ jobs.set(dir, running);
80
+ handle.done.then(async (result) => {
81
+ if (jobs.get(dir) !== running)
82
+ return;
83
+ try {
84
+ await writeJsonAtomic(harnessResultPath(dir), harnessFolder(dir), { finishedAt: iso(now()), result });
85
+ jobs.delete(dir);
86
+ }
87
+ catch (e) {
88
+ jobs.set(dir, { state: 'failed', error: `The harness finished but its result could not be saved: ${messageOf(e)}` });
89
+ }
90
+ }, (e) => {
91
+ if (jobs.get(dir) === running)
92
+ jobs.set(dir, { state: 'failed', error: messageOf(e) });
93
+ });
94
+ return { status: 'started', startedAt: iso(startedAt), ...(saved ? { previous: saved } : {}) };
95
+ }
96
+ const messageOf = (e) => (e instanceof Error ? e.message : String(e)).slice(0, 300);
97
+ /** The worker's file beside this module, as tsc emits it (dist/tools/) or as the bundle sits (dist/). */
98
+ export function workerFile(base = import.meta.url) {
99
+ for (const rel of ['./calibration-worker.js', './tools/calibration-worker.js']) {
100
+ const p = fileURLToPath(new URL(rel, base));
101
+ if (existsSync(p))
102
+ return p;
103
+ }
104
+ return undefined;
105
+ }
106
+ function defaultRunner() {
107
+ const file = workerFile();
108
+ return file ? workerRunner(file) : inProcessRunner;
109
+ }
110
+ /** The harness in a worker thread: it posts `progress`, then `done` or `error`. */
111
+ export function workerRunner(file) {
112
+ return (dir, onProgress) => {
113
+ const worker = new Worker(file, { workerData: { dir } });
114
+ const done = new Promise((resolve, reject) => {
115
+ worker.on('message', (m) => {
116
+ if (m.type === 'progress')
117
+ onProgress(m.done, m.total);
118
+ else if (m.type === 'done')
119
+ resolve(m.result);
120
+ else if (m.type === 'error')
121
+ reject(new Error(m.message));
122
+ });
123
+ worker.on('error', reject);
124
+ worker.on('exit', (code) => reject(new Error(`The harness worker exited (code ${code}) before it finished.`)));
125
+ });
126
+ return { done, stop: () => void worker.terminate() };
127
+ };
128
+ }
129
+ /** The harness on this thread (no worker file): it yields between games and stops between them. */
130
+ export const inProcessRunner = (dir, onProgress) => {
131
+ const stop = new AbortController();
132
+ return { done: calibrationHarness(dir, { progress: onProgress, signal: stop.signal }), stop: () => stop.abort(new Error('The harness was stopped.')) };
133
+ };
@@ -0,0 +1,10 @@
1
+ // The worker thread src/tools/calibration-job.ts runs the #318 harness in, so its synchronous planner work never
2
+ // holds the server's other tool calls. It posts `progress` after each game, then `done` with the result (aggregates
3
+ // only, name-free) or `error` with a message.
4
+ import { parentPort, workerData } from 'node:worker_threads';
5
+ import { calibrationHarness } from './calibration-harness.js';
6
+ const port = parentPort;
7
+ if (port) {
8
+ const { dir } = workerData;
9
+ calibrationHarness(dir, { progress: (done, total) => port.postMessage({ type: 'progress', done, total }) }).then((result) => port.postMessage({ type: 'done', result }), (e) => port.postMessage({ type: 'error', message: e instanceof Error ? e.message : String(e) }));
10
+ }
@@ -3,17 +3,36 @@
3
3
  // can run the calibration on a hosted server whose data directory no local script can reach. The pure part is
4
4
  // src/analysis/income-calibration.ts; `harness: true` adds the #318 harness (src/tools/calibration-harness.ts).
5
5
  // Name-free: games are numbered by their place in the report, never by id; no player is named or numbered.
6
- import { callerWantsProgress, currentCallSignal, reportProgress, toolAnnotations } from '@chrischall/mcp-utils';
6
+ import { toolAnnotations } from '@chrischall/mcp-utils';
7
7
  import { z } from 'zod';
8
8
  import { incomeCalibration, incomeSamples } from '../analysis/income-calibration.js';
9
9
  import { profileFormatOf } from '../analysis/opponent-profile.js';
10
10
  import { listDecisionLogs, readDecisionLog } from '../decision-log.js';
11
11
  import { holdsSeat } from '../player-states.js';
12
12
  import { readGameRecord } from '../replay.js';
13
- import { calibrationHarness, HARNESS_APPROXIMATIONS } from './calibration-harness.js';
13
+ import { HARNESS_APPROXIMATIONS } from './calibration-harness.js';
14
+ import { harnessJob } from './calibration-job.js';
14
15
  import { respond } from './common.js';
15
16
  import { mintMeta } from './hints.js';
16
17
  import { refuse } from './write-kit.js';
18
+ /** How long a call waits for a harness run before answering with its progress (a small data dir answers at once). */
19
+ export const HARNESS_WAIT_MS = 25_000;
20
+ /**
21
+ * The harness job (src/tools/calibration-job.ts) as one call reads it: started or read, then waited on up to
22
+ * `waitMs` for the result. Never waits longer, so no call outlasts a client's timeout.
23
+ */
24
+ export async function harnessView(dir, rerun, waitMs = HARNESS_WAIT_MS) {
25
+ let view = await harnessJob(dir, { rerun });
26
+ const until = Date.now() + waitMs;
27
+ while ((view.status === 'started' || view.status === 'running') && Date.now() < until) {
28
+ await new Promise((r) => setTimeout(r, Math.min(500, Math.max(0, until - Date.now()))));
29
+ const peek = await harnessJob(dir, { peek: true });
30
+ if (peek.status === 'none')
31
+ break;
32
+ view = peek.status === 'failed' ? await harnessJob(dir) : peek;
33
+ }
34
+ return view;
35
+ }
17
36
  /** Scored rows returned at most with `samples: true`. */
18
37
  export const MAX_SAMPLES = 2000;
19
38
  export const CALIBRATION_NOTE = 'Each sample is one income estimate a planned turn worked from, against that opponent\'s true income (base plus ' +
@@ -71,17 +90,23 @@ export function registerCalibrationTool(server, dataDir) {
71
90
  'two thirds of the truth, the tracker step that held it (rise cap, tripwire, window, could-earn ceiling, ' +
72
91
  'ambiguous armies, readings, a later stage, or no track; logged since #586); and what correcting the ' +
73
92
  'tracked figure by its coverage band would have read at dampings 0 to 1 (leave one game out). `samples: true` adds the scored rows ' +
74
- `(at most ${MAX_SAMPLES}), name-free, as a fixture set; \`harness: true\` also runs the #318 harness over the ` +
75
- 'cached boards (tracker, fog prior and plan estimate by coverage band, and the opening benchmark), which can ' +
76
- 'take a while on many games. Games are numbered by their place in the report, never by id, and no player is ' +
77
- 'named. Makes no war.app request and writes nothing. Read-only.',
93
+ `(at most ${MAX_SAMPLES}), name-free, as a fixture set; \`harness: true\` adds the #318 harness over the ` +
94
+ 'cached boards (tracker, fog prior and plan estimate by coverage band, and the opening benchmark): it runs in the ' +
95
+ 'background, since it can take most of an hour on many games, so the first call starts it and later calls say ' +
96
+ '`running` (games done of total) until it is `done`; the result is kept, so a later call returns it at once ' +
97
+ '(`rerun: true` starts a fresh run). Games are numbered by their place in the report, never by id, and no player ' +
98
+ 'is named. Makes no war.app request; writes only the harness result, in this server\'s own data. Read-only.',
78
99
  annotations: toolAnnotations({ title: 'Income estimate calibration', readOnly: true, destructive: false, idempotent: true, openWorld: false }),
79
100
  inputSchema: z.object({
80
101
  samples: z.boolean().optional().describe(`Also return the scored rows, name-free (default false; at most ${MAX_SAMPLES}).`),
81
- harness: z.boolean().optional().describe('Also run the #318 harness over the cached boards and the opening benchmark (default false).'),
102
+ harness: z
103
+ .boolean()
104
+ .optional()
105
+ .describe('Also the #318 harness over the cached boards and the opening benchmark (default false): started in the background on the first call; call again until its status is `done`.'),
106
+ rerun: z.boolean().optional().describe('With `harness`, start a fresh harness run over a kept result (default false).'),
82
107
  format: z.enum(['1v1', 'ffa', 'team']).optional().describe('Only games of this format.'),
83
108
  }),
84
- }, async ({ samples, harness, format }) => {
109
+ }, async ({ samples, harness, rerun, format }) => {
85
110
  const dir = dataDir();
86
111
  if (!dir)
87
112
  refuse('This server has no data directory, so there is nothing to score.', 'Nothing to do here.');
@@ -89,19 +114,7 @@ export function registerCalibrationTool(server, dataDir) {
89
114
  const games = format ? src.games.filter((g) => g.format === format) : src.games;
90
115
  const report = incomeCalibration(games);
91
116
  const rows = samples ? incomeSamples(games) : [];
92
- // The harness replays every finished game, which can outlast the 300 s a call may stay silent:
93
- // progress after each game keeps the call alive, and a cancelled call stops between games.
94
- const signal = currentCallSignal();
95
- const extra = harness
96
- ? await calibrationHarness(dir, {
97
- ...(callerWantsProgress()
98
- ? {
99
- progress: (done, total) => void reportProgress(done, total, `calibration harness: ${done} of ${total} games`).catch(() => undefined),
100
- }
101
- : {}),
102
- ...(signal ? { signal } : {}),
103
- })
104
- : undefined;
117
+ const job = harness ? await harnessView(dir, rerun === true) : undefined;
105
118
  return respond(undefined, ['compact'], () => ({
106
119
  readAs: CALIBRATION_NOTE,
107
120
  sources: {
@@ -119,7 +132,25 @@ export function registerCalibrationTool(server, dataDir) {
119
132
  "game's history is read (warapp_backfill_history, warapp_my_games' sweep, warapp_get_game on it).",
120
133
  }),
121
134
  ...(samples ? { samples: rows.slice(0, MAX_SAMPLES), ...(rows.length > MAX_SAMPLES ? { samplesLeftOut: rows.length - MAX_SAMPLES } : {}) } : {}),
122
- ...(extra ? { harness: { ...extra, approximations: HARNESS_APPROXIMATIONS } } : {}),
135
+ ...(job ? { harness: harnessOut(job) } : {}),
123
136
  }));
124
137
  });
125
138
  }
139
+ /** The job as the tool reports it: the result with its approximations, or where the run stands and what to do. */
140
+ function harnessOut(job) {
141
+ switch (job.status) {
142
+ case 'done':
143
+ return { status: 'done', finishedAt: job.finishedAt, ...job.result, approximations: HARNESS_APPROXIMATIONS, note: 'A kept result: `rerun: true` starts a fresh run.' };
144
+ case 'failed':
145
+ return { status: 'failed', error: job.error, note: 'Call again with `harness: true` to start a fresh run.' };
146
+ case 'started':
147
+ case 'running':
148
+ return {
149
+ ...job,
150
+ ...(job.previous ? { previous: { finishedAt: job.previous.finishedAt, ...job.previous.result, approximations: HARNESS_APPROXIMATIONS } } : {}),
151
+ note: 'The harness runs in the background: call warapp_calibration with `harness: true` again in a few minutes for its progress, then its result.',
152
+ };
153
+ default:
154
+ return job;
155
+ }
156
+ }