Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions desktop/ClientLab.Launcher/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ public static int Main(string[] args)
AttachParentConsole();
return Services.CompileCommand.RunAsync(args, DataDirectory).GetAwaiter().GetResult();
}
if (args.FirstOrDefault() == "--prepare")
{
AttachParentConsole();
return Services.PrepareCommand.RunAsync(DataDirectory).GetAwaiter().GetResult();
}
if (args.FirstOrDefault() == "--build-host")
{
AttachParentConsole();
Expand Down
63 changes: 63 additions & 0 deletions desktop/ClientLab.Launcher/Services/PrepareCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using System.Text.Json.Nodes;

namespace NosCore.ClientLab.Launcher.Services;

/// <summary>
/// <c>ClientLab --prepare [--game &lt;install&gt;] [--emcc &lt;compiler&gt;] [--data-dir &lt;folder&gt;]</c>: the launcher's
/// Prepare without its window. It brings the data folder's game to the current official client (copying what
/// <c>--game</c> already has), recompiles it from the committed symbols and compiles the runtime, then prints
/// <c>CLIENTLAB_RUNTIME=&lt;folder&gt;</c>. <c>ClientLab --serve</c> with the same data folder then serves it.
/// </summary>
internal static class PrepareCommand
{
public static async Task<int> RunAsync(string dataDirectory)
{
await using var app = new LauncherCoordinator(SourceAssets.Resolve(), dataDirectory);
var changes = new JsonObject();
if (Program.Option("--game") is { Length: > 0 } game)
{
if (!Directory.Exists(game))
{
Console.Error.WriteLine($"Game folder not found: {game}");
return 2;
}
changes["import_dir"] = Path.GetFullPath(game);
}
if (Program.Option("--emcc") is { Length: > 0 } emcc) changes["emcc"] = Path.GetFullPath(emcc);
if (changes.Count > 0) app.SaveSettings(changes);

app.Logged += line => Console.WriteLine(line);
using var stop = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; stop.Cancel(); app.Cancel(); };
// Download and compile progress only lives in the status line, so it is echoed when it changes.
var reporter = Task.Run(async () =>
{
var last = "";
while (!stop.IsCancellationRequested)
{
var snapshot = app.Snapshot();
var line = $"[{snapshot["stage"]}] {snapshot["message"]} ({snapshot["progress"]?.GetValue<double>() ?? 0:P0})";
if (line != last) { Console.WriteLine(line); last = line; }
try { await Task.Delay(TimeSpan.FromSeconds(5), stop.Token); } catch (OperationCanceledException) { }
}
});
try
{
await app.StartAndWaitAsync("prepare");
var active = app.Snapshot()["active"];
Console.WriteLine("CLIENTLAB_RUNTIME=" + active?["runtime"]);
Console.WriteLine("CLIENTLAB_GAME=" + active?["client"]);
return 0;
}
catch (Exception error) when (error is InvalidOperationException or InvalidDataException or OperationCanceledException)
{
Console.Error.WriteLine("clientlab --prepare: " + error.Message);
return 1;
}
finally
{
stop.Cancel();
await reporter;
}
}
}
29 changes: 28 additions & 1 deletion docs/BROWSER-AUTOMATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,32 @@ Host/Sec-Fetch-Site/Origin checks, while other sites' requests are refused.
Game options the page saves (Config.ini) go to the data folder, as in the desktop window. On Windows the executable
attaches to the terminal that started it, so its output shows there.

## Preparing a game without the window (`--prepare`)

`--prepare` runs the launcher's Prepare step from a terminal: it brings the data folder's game to the current official
client (files `--game` already has are copied instead of downloaded), recompiles it from the committed
`symbols/<md5>/` with the seeds the launcher derives itself, compiles the runtime, and makes it the data folder's
active build. It prints `CLIENTLAB_RUNTIME=<folder>` and `CLIENTLAB_GAME=<folder>` when done, and exits non-zero with
the reason otherwise. A second run with an unchanged client reuses the build and returns at once.

```bash
ClientLab --prepare --data-dir ~/clientlab-data [--game <existing install>] [--emcc <path to emcc>]
ClientLab --serve --data-dir ~/clientlab-data --user <account> --password <password> --auth-url http://127.0.0.1:7001 \
--host 127.0.0.1 --port 8090
```

`--emcc` uses that Emscripten instead of letting the launcher fetch its own tools, which a machine behind a proxy may
not reach. On a fresh Linux machine, the whole route from nothing to a served client is:

```bash
git clone --depth 1 https://github.com/emscripten-core/emsdk.git && emsdk/emsdk install latest && emsdk/emsdk activate latest
dotnet build desktop/ClientLab.Launcher -c Release
dotnet desktop/ClientLab.Launcher/bin/Release/net10.0/ClientLab.dll --prepare --data-dir ~/clientlab-data \
--emcc "$PWD/emsdk/upstream/emscripten/emcc"
```

`--host 127.0.0.1` matters for a local NosCore: without it the client dials the address the login server hands out.

## Browser launcher

The browser launcher uses the desktop launcher's C# coordinator, authentication state
Expand Down Expand Up @@ -157,7 +183,8 @@ claude mcp add clientlab -- node /path/to/NosCore.ClientLab/recomp/web/mcp.mjs -
`enter_world` picks the first server and channel and the character slot; the other tools then work on the character
in the world. On another server's character select, pass `slot` (or start the MCP with `--slot x,y`) as the
character's position on a screenshot. `screenshot` returns its size, and `click` and `slot` take that screenshot's
pixel coordinates, whatever the window size.
pixel coordinates, whatever the window size. `screenshot` with `save` also writes the PNG to a file, and
`before_after` puts two saved screenshots side by side under captions in one PNG, ready for a pull request.

The launcher serves the web files built into it, extracted under `%LOCALAPPDATA%\NosCore.ClientLab\sources\<hash>`;
a rebuilt launcher extracts a new copy. To try edits to `recomp/web` without rebuilding, start it with
Expand Down
55 changes: 50 additions & 5 deletions recomp/web/mcp.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
// --guard guard.json keeps the guard settings across restarts (default: next to --log)
// Register it with an MCP client, for example: claude mcp add clientlab -- node /path/to/recomp/web/mcp.mjs
import { createRequire } from 'node:module';
import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { createInterface } from 'node:readline';

const require = createRequire(import.meta.url);
Expand All @@ -27,7 +28,7 @@ const defaults = { url: arg('--url', 'http://127.0.0.1:8090/'), params: arg('--p
slot: (arg('--slot', process.env.CLIENTLAB_SLOT || '') || null)?.split(',').map(Number) };
defaults.guard = arg('--guard', process.env.CLIENTLAB_GUARD || (defaults.log ? `${defaults.log}.guard.json` : ''));
// Reads (state, screenshots, memory) are left out of the action log.
const QUIET = new Set(['client_state', 'skills', 'inventory', 'map_grid', 'dialogs', 'screenshot', 'client_log', 'read_memory',
const QUIET = new Set(['client_state', 'skills', 'inventory', 'map_grid', 'dialogs', 'screenshot', 'before_after', 'client_log', 'read_memory',
'find_signature', 'client_api', 'packets', 'wait_for', 'portals']);
function logAction(name, args, content, error) {
if (!defaults.log || QUIET.has(name)) return;
Expand Down Expand Up @@ -304,12 +305,51 @@ async function click([x, y], { button = 'left', double = false, layout: scaled =
}
}

async function screenshot() {
function writePng(file, png) {
const path = resolve(file);
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, png);
return path;
}

async function screenshot({ save } = {}) {
await ensurePage();
const o = await canvasOrigin();
const png = await page.screenshot({ clip: { x: o.x, y: o.y, width: o.width, height: o.height } });
const saved = save ? `, saved to ${writePng(save, png)}` : '';
return [{ type: 'image', data: png.toString('base64'), mimeType: 'image/png' },
json(`${o.shot.width}x${o.shot.height}: click and enter_world's slot take these pixel coordinates`)];
json(`${o.shot.width}x${o.shot.height}: click and enter_world's slot take these pixel coordinates${saved}`)];
}

// Two saved screenshots side by side under their captions, drawn by a throwaway headless page so the game page and
// an attached app are left alone.
async function beforeAfter({ before, after, out, labels = ['Before', 'After'] }) {
const images = [before, after].map((file) => {
if (!existsSync(file)) throw new Error(`no screenshot at ${file}`);
return `data:image/png;base64,${readFileSync(file).toString('base64')}`;
});
const composer = await chromium.launch({ headless: true });
try {
const sheet = await composer.newPage();
const png = Buffer.from(await sheet.evaluate(async ({ images, labels }) => {
const loaded = await Promise.all(images.map((src) => new Promise((ok, fail) => {
const img = new Image(); img.onload = () => ok(img); img.onerror = () => fail(new Error('not a PNG')); img.src = src;
})));
const gap = 16, caption = 40;
const canvas = document.createElement('canvas');
canvas.width = loaded[0].width + loaded[1].width + gap;
canvas.height = Math.max(loaded[0].height, loaded[1].height) + caption;
const g = canvas.getContext('2d');
g.fillStyle = '#ffffff'; g.fillRect(0, 0, canvas.width, canvas.height);
g.fillStyle = '#000000'; g.font = 'bold 24px sans-serif'; g.textBaseline = 'middle';
let x = 0;
loaded.forEach((img, i) => { g.fillText(labels[i], x + 8, caption / 2); g.drawImage(img, x, caption); x += img.width + gap; });
return atob(canvas.toDataURL('image/png').split(',')[1]).split('').map((c) => c.charCodeAt(0));
}, { images, labels }));
return [{ type: 'image', data: png.toString('base64'), mimeType: 'image/png' }, json(`saved to ${writePng(out, png)}`)];
} finally {
await composer.close();
}
}

async function enterWorld({ slot = defaults.slot } = {}) {
Expand Down Expand Up @@ -769,7 +809,12 @@ const TOOLS = [
run: (a) => control({ op: 'pet_move', x: a.x, y: a.y, pet: a.pet }).then(json) },
{ name: 'rest', description: 'Sit down or stand up; returns once the server has confirmed it.', inputSchema: obj({ timeout: { type: 'number', description: 'Seconds' } }),
run: (a) => rest(a).then(json) },
{ name: 'screenshot', description: 'The game screen, with its size in pixels; click takes the same pixel coordinates.', inputSchema: obj(), run: () => screenshot() },
{ name: 'screenshot', description: 'The game screen, with its size in pixels; click takes the same pixel coordinates. save also writes the PNG to that file.',
inputSchema: obj({ save: { type: 'string', description: 'PNG file to write (folders are created)' } }), run: (a) => screenshot(a) },
{ name: 'before_after', description: 'Put two saved screenshots side by side under captions (Before and After by default) and write the PNG to out, for a pull request.',
inputSchema: obj({ before: { type: 'string' }, after: { type: 'string' }, out: { type: 'string' },
labels: { type: 'array', items: { type: 'string' }, description: 'The two captions' } }, ['before', 'after', 'out']),
run: (a) => beforeAfter(a) },
{ name: 'click', description: 'Click the game screen at [x,y] in screenshot pixels, for windows and dialogues.',
inputSchema: obj({ x: { type: 'integer' }, y: { type: 'integer' }, button: { type: 'string', enum: ['left', 'right'] }, double: { type: 'boolean' } }, ['x', 'y']),
run: (a) => click([a.x, a.y], a).then(() => json('clicked')) },
Expand Down
Loading