glitchless-mcp 0.14.0 → 0.15.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/README.md +9 -8
- package/package.json +3 -2
- package/src/context.js +65 -19
- package/src/pictures.js +106 -0
- package/src/session-view.js +198 -0
- package/src/tools/analytics.js +28 -7
- package/src/tools/core.js +72 -17
- package/src/tools/dashboard.js +46 -27
- package/src/tools/revenue.js +19 -4
- package/src/tools/store-reviews.js +27 -10
- package/src/tools/workspace.js +39 -12
package/README.md
CHANGED
|
@@ -28,7 +28,8 @@ every tool takes `game` (a name or id). The key acts as you, with your role in t
|
|
|
28
28
|
or touches billing or people. `npx -y glitchless-mcp whoami` shows where you're signed in, `logout` deletes the saved
|
|
29
29
|
key, and Settings → Keys & access in the dashboard lists and revokes keys. An agent can also sign in from inside a
|
|
30
30
|
chat with the `glitchless_sign_in` tool: it shows the link and code, and the running server switches over once you
|
|
31
|
-
approve.
|
|
31
|
+
approve. The saved key is only ever sent to the server it was saved for: point `GLITCHLESS_URL` at another one (a
|
|
32
|
+
meetup's own box) and the MCP server connects without it, so set `GLITCHLESS_API_KEY` if that server has a key.
|
|
32
33
|
|
|
33
34
|
## Serve it over HTTP yourself
|
|
34
35
|
|
|
@@ -46,7 +47,7 @@ clients send it as `Authorization: Bearer`.
|
|
|
46
47
|
|
|
47
48
|
| Variable | What |
|
|
48
49
|
| --- | --- |
|
|
49
|
-
| `GLITCHLESS_URL` | Your Glitchless server. Default: the signed-in workspace's, else `http://localhost:7777
|
|
50
|
+
| `GLITCHLESS_URL` | Your Glitchless server. Default: the signed-in workspace's, else `http://localhost:7777`. A saved sign-in goes only to the server it was saved for |
|
|
50
51
|
| `GLITCHLESS_API_KEY` | A key, if the server needs one: a workspace key (`gl_ws_…`) for every game, or a secret key (`gl_sk_…`) for one. Overrides a sign-in. Keep it out of git and out of the game |
|
|
51
52
|
| `GLITCHLESS_GAME` | With a workspace key, the game to use when a call doesn't name one. Optional |
|
|
52
53
|
| `GLITCHLESS_SERVICE` | The service to use when a call doesn't name one. Optional |
|
|
@@ -91,23 +92,23 @@ above go in its environment.
|
|
|
91
92
|
| --- | --- |
|
|
92
93
|
| `glitchless_list_games` | Which games report to the server, with their versions and environments; signed in to a workspace, every game in it with its client token |
|
|
93
94
|
| `glitchless_sign_in` | Connect to a Glitchless Cloud workspace: a link and a code for the person to approve |
|
|
94
|
-
| `glitchless_create_game` | A new game in the workspace, with its client token and intake URL; `demo: true` makes the demo game (a week of sample play) |
|
|
95
|
+
| `glitchless_create_game` | A new game in the workspace, with its client token and intake URL; `demo: true` makes the demo game (a week of sample play); `rename` (with `game`) renames one instead, its client token, service and data unchanged |
|
|
95
96
|
| `glitchless_share_links` | A read-only link to one board page, for a dev log, Discord or a game's "Live stats" link (`page`); lists them, and revokes one (`revoke`) |
|
|
96
97
|
| `glitchless_triage` | The headline numbers (sessions, players, crash-free sessions, frame time, rage quits), then ranked findings: stutter per level and what it correlates with, leaks, top errors, difficulty spikes. Start here |
|
|
97
|
-
| `glitchless_mark_known` | Mark a finding the game's owner accepts as known, so the weekly summary stops listing it (triage shows it last, with the note); `clear: true` removes the mark |
|
|
98
|
+
| `glitchless_mark_known` | Mark a finding the game's owner accepts as known, so the weekly summary stops listing it (triage shows it last, with the note); with `player` or `session` instead, the team's own play, read as testers in every tool; `clear: true` removes the mark |
|
|
98
99
|
| `glitchless_resolve_error` | Resolve an error issue the game's owner fixed or accepts: hidden from the Errors page, triage and the weekly summary until it fires again in a newer version (`any_version`: any); `clear: true` unresolves it |
|
|
99
100
|
| `glitchless_alerts` | A game's alerts: where they go, which rules are on, the weekly summary, the env, and the last sends; `glitchless_set_alerts` turns rules, the weekly summary and email on or off, sets the env, removes the webhook and sends a test (a webhook URL is added in Settings → Alerts) |
|
|
100
101
|
| `glitchless_performance` | Frame time per level, with draw calls, geometry counts and game gauges |
|
|
101
102
|
| `glitchless_get_error` | One error issue, with its stack and the gameplay before it |
|
|
102
|
-
| `glitchless_player_funnel` | Per level: starts, completions, deaths and their causes, disconnects, rage quits; split by what describes the attempt (tier, party size, class), runs per level, and retention; with `hotspots`, where players die on a level, clustered in world coordinates |
|
|
103
|
+
| `glitchless_player_funnel` | Per level: starts, completions, deaths and their causes, disconnects, rage quits; split by what describes the attempt (tier, party size, class), runs per level, and retention; with `hotspots`, where players die on a level, in a zone or anywhere in the game (a hub with no levels), clustered in world coordinates |
|
|
103
104
|
| `glitchless_events` | The game's own events (whatever it sends with `track`, and the streams it counts with `count`): counts, attribute breakdowns, rates, distributions and funnels, and the session properties it sets |
|
|
104
105
|
| `glitchless_dashboard` | The game's dashboard: its pages, and one board's panels with their numbers |
|
|
105
|
-
| `glitchless_set_dashboard` | Save the game's pages: boards of panels in its own words, and the built-in views it keeps. Needs a key with the dashboard scope |
|
|
106
|
+
| `glitchless_set_dashboard` | Save the game's pages: boards of panels in its own words, and the built-in views it keeps; and, each alone if you like, the boards' accent, logo and banner (the header behind each board's title) and a level's, zone's or the whole game's heatmap background (a picture from a file or base64 and its world bounds). Needs a key with the dashboard scope |
|
|
106
107
|
| `glitchless_compare_versions` | Two or more versions side by side, in the game's own stats first, to confirm a fix with real players |
|
|
107
108
|
| `glitchless_session` | One play session in detail, with its whole event timeline |
|
|
108
109
|
| `glitchless_bug_reports` | Bug reports players sent from inside the game: their notes, levels, positions and sessions, and one report's screenshot when asked |
|
|
109
|
-
| `glitchless_store` | For a game connected to a store (Glitchless Cloud: Steam, Google Play, the App Store): what players wrote there, by store, build or version, sentiment, topic (stutter, lag, fps, freeze, crash), device and, on Steam, Steam Deck, each build with the frame-time p95 and crash-free sessions measured on it; with `show: "vitals"`, what Google Play (slow rendering, crash and ANR rates, the slowest devices and GPUs) or the App Store (hang rate, launch time, animation hitches, hang signatures) measured of each version, next to what Glitchless measured, and where the two disagree |
|
|
110
|
-
| `glitchless_revenue` | For a game connected to RevenueCat
|
|
110
|
+
| `glitchless_store` | For a game connected to a store (Glitchless Cloud: Steam, Google Play, the App Store, Roblox): what players wrote there, by store, build or version, sentiment, topic (stutter, lag, fps, freeze, crash), device and, on Steam, Steam Deck, each build with the frame-time p95 and crash-free sessions measured on it; with `show: "vitals"`, what Google Play (slow rendering, crash and ANR rates, the slowest devices and GPUs) or the App Store (hang rate, launch time, animation hitches, hang signatures) or Roblox (crash rate and frame rate by place version and platform, and its retention) measured of each version, next to what Glitchless measured, and where the two disagree |
|
|
111
|
+
| `glitchless_revenue` | For a game connected to RevenueCat, its own Stripe account or Roblox (Glitchless Cloud; `source` picks one, else each): its real revenue by day and revenue per player measured. RevenueCat's (production purchases only): installs (new customers) and active users, MRR, active subscriptions and trials, and revenue by version where RevenueCat splits it. Stripe's: refunds, disputes, fees and net, new paying customers, revenue by product, and by version and platform for purchases the game tied to a session. Roblox's: Robux earned (and what they'd be worth through DevEx), paying users, daily active and new users, and D1, D7 and D30 retention. All next to the sessions, players and new players Glitchless measured and what the game's own purchase events add up to |
|
|
111
112
|
| `glitchless_match` | A multiplayer game's matches (the worst by lag or disconnects on request), or one match from every side, 30 seconds at a time: each player's ping, frame time and outcome, the server's ticks, and whether the whole lobby lagged at once (the server) or one player did (their connection) |
|
|
112
113
|
| `glitchless_network` | Ping, lag (play over 150 ms), packet loss and disconnects by level, version, platform, kind of connection and region, with the worst matches and the network findings |
|
|
113
114
|
| `glitchless_servers` | A game's dedicated servers in server mode: servers running now and their players, tick time against its budget by players connected, map and version, crashes with the matches they ended, and memory that climbs. Every other tool reads them with service `<game>.server` |
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "glitchless-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"mcpName": "io.github.glitchless-gg/glitchless",
|
|
5
|
-
"description": "Coding agents can build a game. They can't see anyone play it. Glitchless lets them. The MCP server for Glitchless, game observability for coding agents: Claude Code, Codex, Cursor and others read real players' stutters, crashes, custom metrics and ranked findings in Unity, Godot, Unreal, Three.js, Phaser and GameMaker games, build the game's own dashboard, and run playtest bots.",
|
|
5
|
+
"description": "Coding agents can build a game. They can't see anyone play it. Glitchless lets them. The MCP server for Glitchless, game observability for coding agents: Claude Code, Codex, Cursor and others read real players' stutters, crashes, custom metrics and ranked findings in Unity, Godot, Unreal, Three.js, Roblox, Phaser and GameMaker games, build the game's own dashboard, and run playtest bots.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"mcp",
|
|
8
8
|
"mcp-server",
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
"threejs",
|
|
17
17
|
"godot",
|
|
18
18
|
"unreal-engine",
|
|
19
|
+
"roblox",
|
|
19
20
|
"performance",
|
|
20
21
|
"playtesting",
|
|
21
22
|
"ai-agents",
|
package/src/context.js
CHANGED
|
@@ -9,7 +9,7 @@ import path from 'node:path';
|
|
|
9
9
|
import { McpServer } from '@modelcontextprotocol/server';
|
|
10
10
|
import { z } from 'zod';
|
|
11
11
|
|
|
12
|
-
export const VERSION = '0.
|
|
12
|
+
export const VERSION = '0.15.0';
|
|
13
13
|
|
|
14
14
|
// Where `glitchless-mcp login` keeps its workspace key: { url, token, workspace: { id, name }, scopes }.
|
|
15
15
|
export const CREDENTIALS_FILE = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'glitchless', 'credentials.json');
|
|
@@ -28,15 +28,34 @@ export function connection({ base, apiKey = '', service = '', game = '', fetch =
|
|
|
28
28
|
return { base: String(base).replace(/\/$/, ''), apiKey, service, game, fetch, client, games: null };
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
31
|
+
const originOf = (u) => {
|
|
32
|
+
try {
|
|
33
|
+
return new URL(u).origin;
|
|
34
|
+
} catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// On stdio, the one connection: GLITCHLESS_URL and GLITCHLESS_API_KEY win, else the saved sign-in. A saved key goes
|
|
40
|
+
// only to the server it was saved for, so pointing GLITCHLESS_URL at a meetup's own server never hands it a Glitchless
|
|
41
|
+
// Cloud key: the connection goes without one (an open self-hosted server needs none), and `savedFor`, the origin the
|
|
42
|
+
// sign-in is for, says why on a 401. Over HTTP each request runs with the connection its bearer token gives
|
|
43
|
+
// (createServer's `connection`).
|
|
44
|
+
export function stdioConnection(env = process.env) {
|
|
45
|
+
const saved = env.GLITCHLESS_API_KEY ? null : readCredentials();
|
|
46
|
+
const savedAt = saved?.token ? originOf(saved.url) : null;
|
|
47
|
+
const fits = Boolean(saved?.token) && (!env.GLITCHLESS_URL || (savedAt !== null && originOf(env.GLITCHLESS_URL) === savedAt));
|
|
48
|
+
return {
|
|
49
|
+
...connection({
|
|
50
|
+
base: env.GLITCHLESS_URL || (fits ? saved.url : '') || 'http://localhost:7777',
|
|
51
|
+
apiKey: env.GLITCHLESS_API_KEY || (fits ? saved.token : ''),
|
|
52
|
+
service: env.GLITCHLESS_SERVICE || '',
|
|
53
|
+
game: env.GLITCHLESS_GAME || '',
|
|
54
|
+
}),
|
|
55
|
+
savedFor: saved?.token && !fits ? (savedAt ?? String(saved.url)) : null,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
const local = stdioConnection();
|
|
40
59
|
const connections = new AsyncLocalStorage();
|
|
41
60
|
const conn = () => connections.getStore() ?? local;
|
|
42
61
|
|
|
@@ -47,7 +66,13 @@ export const isWorkspace = () => conn().apiKey.startsWith('gl_ws_');
|
|
|
47
66
|
|
|
48
67
|
// After a sign-in from inside the agent (glitchless_sign_in): the running server switches to the new key.
|
|
49
68
|
export function useCredentials({ url, token }) {
|
|
50
|
-
Object.assign(local, { base: String(url).replace(/\/$/, ''), apiKey: token, games: null });
|
|
69
|
+
Object.assign(local, { base: String(url).replace(/\/$/, ''), apiKey: token, games: null, savedFor: null });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// What a 401 adds when the saved sign-in was kept from this server: where it's for, and how to give this one a key.
|
|
73
|
+
function signInHint(status) {
|
|
74
|
+
const { savedFor, base: at } = conn();
|
|
75
|
+
return status === 401 && savedFor ? ` The saved sign-in is for ${savedFor} and isn't sent to another server: set GLITCHLESS_API_KEY for ${at}.` : '';
|
|
51
76
|
}
|
|
52
77
|
|
|
53
78
|
// The games a workspace key reaches, cached briefly; the game each call names (by name or id), else the one the
|
|
@@ -104,7 +129,7 @@ export async function query(name, params = {}) {
|
|
|
104
129
|
const qs = new URLSearchParams();
|
|
105
130
|
for (const [k, v] of Object.entries(params)) if (v != null && v !== '') qs.set(k, String(v));
|
|
106
131
|
const res = await conn().fetch(`${base()}/v1/query/${name}?${qs}`, { headers: await headers() });
|
|
107
|
-
if (!res.ok) throw new Error(`Glitchless API ${name} → HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`);
|
|
132
|
+
if (!res.ok) throw new Error(`Glitchless API ${name} → HTTP ${res.status}: ${(await res.text()).slice(0, 200)}${signInHint(res.status)}`);
|
|
108
133
|
const data = await res.json();
|
|
109
134
|
const call = calls.getStore();
|
|
110
135
|
if (call && data?.meta) Object.assign(call, { meta: data.meta, from: params.from });
|
|
@@ -136,10 +161,23 @@ export async function write(method, p, body) {
|
|
|
136
161
|
});
|
|
137
162
|
const data = await res.json().catch(() => ({}));
|
|
138
163
|
if (res.status === 403) throw new Error(`${data.error || 'forbidden'}. Saving a dashboard needs a key with the dashboard scope (a workspace key from glitchless_sign_in has it).`);
|
|
139
|
-
if (!res.ok) throw new Error(`Glitchless API ${method} ${p} → HTTP ${res.status}: ${data.error || ''}`);
|
|
164
|
+
if (!res.ok) throw new Error(`Glitchless API ${method} ${p} → HTTP ${res.status}: ${data.error || ''}${signInHint(res.status)}`);
|
|
165
|
+
return data;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// A body that isn't JSON (a picture: PUT /v1/maps), with the same headers as write().
|
|
169
|
+
export async function upload(method, p, bytes, type) {
|
|
170
|
+
const res = await conn().fetch(`${base()}${p}`, { method, headers: await headers({ 'content-type': type }), body: bytes });
|
|
171
|
+
const data = await res.json().catch(() => ({}));
|
|
172
|
+
if (res.status === 403) throw new Error(`${data.error || 'forbidden'}. Uploading needs a key with the dashboard scope (a workspace key from glitchless_sign_in has it).`);
|
|
173
|
+
if (!res.ok) throw new Error(`Glitchless API ${method} ${p.split('?')[0]} → HTTP ${res.status}: ${data.error || ''}${signInHint(res.status)}`);
|
|
140
174
|
return data;
|
|
141
175
|
}
|
|
142
176
|
|
|
177
|
+
// Whether this call is answered by a server over HTTP (the hosted one, or `glitchless-mcp serve`), which can't read the
|
|
178
|
+
// agent's files: a tool that takes a file path takes its contents there instead.
|
|
179
|
+
export const isRemote = () => !!calls.getStore()?.remote;
|
|
180
|
+
|
|
143
181
|
export async function resolveService(service) {
|
|
144
182
|
if (service) return service;
|
|
145
183
|
if (defaultService()) return defaultService();
|
|
@@ -153,8 +191,16 @@ export function range(hours = 24) {
|
|
|
153
191
|
return { from: to - hours * 3600e3, to };
|
|
154
192
|
}
|
|
155
193
|
|
|
156
|
-
|
|
157
|
-
|
|
194
|
+
// rows: one row of each list per line (a level, an event, a match), so a long answer stays short and still reads as JSON.
|
|
195
|
+
export function reply(title, data, { rows = false } = {}) {
|
|
196
|
+
return { content: [{ type: 'text', text: `${title}${windowNote()}\n\n${rows ? rowsJSON(data) : JSON.stringify(data, null, 2)}` }] };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// JSON with a line per top-level field, and a line per element of a list of objects.
|
|
200
|
+
function rowsJSON(data) {
|
|
201
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) return JSON.stringify(data);
|
|
202
|
+
const field = (v) => (Array.isArray(v) && v.length && v.every((x) => x && typeof x === 'object') ? `[\n${v.map((x) => ` ${JSON.stringify(x)}`).join(',\n')}\n ]` : JSON.stringify(v));
|
|
203
|
+
return `{\n${Object.entries(data).filter(([, v]) => v !== undefined).map(([k, v]) => ` ${JSON.stringify(k)}: ${field(v)}`).join(',\n')}\n}`;
|
|
158
204
|
}
|
|
159
205
|
|
|
160
206
|
export function fail(err) {
|
|
@@ -230,7 +276,7 @@ export function createServer({ remote = false, scopes = null, connection: c = nu
|
|
|
230
276
|
const { inputSchema = {}, ...config } = t.config;
|
|
231
277
|
server.registerTool(t.name, { ...config, title: titleOf(t), inputSchema: z.object({ game: gameField, ...inputSchema }) }, (args = {}, ctx) => {
|
|
232
278
|
const run = () =>
|
|
233
|
-
calls.run({ game: args.game, server }, async () => {
|
|
279
|
+
calls.run({ game: args.game, server, remote }, async () => {
|
|
234
280
|
try {
|
|
235
281
|
return await t.handler(args, ctx);
|
|
236
282
|
} catch (err) {
|
|
@@ -245,7 +291,7 @@ export function createServer({ remote = false, scopes = null, connection: c = nu
|
|
|
245
291
|
|
|
246
292
|
function instructions(remote) {
|
|
247
293
|
return [
|
|
248
|
-
'Glitchless is observability for games made with Three.js, Phaser, Babylon.js, PlayCanvas
|
|
294
|
+
'Glitchless is observability for games made with Unity, Godot, Unreal, Three.js, Roblox, Phaser, Babylon.js, PlayCanvas or GameMaker.',
|
|
249
295
|
remote
|
|
250
296
|
? "You're connected to the person's Glitchless workspace: glitchless_list_games lists every game (and says what to do when there is none, or a game has no data yet), glitchless_create_game makes one and hands back its client token (demo: true makes the demo game, Zoomies with a week of sample play, to try every tool on before a real game sends data), every tool takes game (by name), and glitchless_share_links makes a read-only link to a board. If a game hasn't sent data yet, say so first and give the person its next step (glitchless_list_games has it) before answering anything else."
|
|
251
297
|
: "On Glitchless Cloud, glitchless_sign_in connects you to the person's whole workspace (they approve a code in the browser): then glitchless_list_games lists every game, glitchless_create_game makes one and hands back its client token, every tool takes game (by name), and glitchless_share_links makes a read-only link to a board.",
|
|
@@ -253,8 +299,8 @@ function instructions(remote) {
|
|
|
253
299
|
'When players or playtesters send bug reports from inside the game (an F8 form or a button), glitchless_bug_reports lists them with what they wrote, the level and where they stood, and opens one with its screenshot.',
|
|
254
300
|
'For metrics the game defines itself (what it sends with track() and count(): plays, purchases, paywall views, kills and gold, and so on) and funnels between them, use glitchless_events; it also lists the session properties the game sets (rank, class, region), which every read tool takes as props.',
|
|
255
301
|
'For a multiplayer game, glitchless_network gives ping, packet loss and disconnects by level, region, platform, kind of connection and version; glitchless_match lists matches or opens one from every side, telling a whole lobby lagging (the server) from one player lagging (their connection); and glitchless_servers reads the game\'s dedicated servers (tick time against its budget by players connected, crashes that ended matches, memory that climbs).',
|
|
256
|
-
'For a game connected to a store (Steam, Google Play, the App Store), glitchless_store reads what players wrote there by build, with the hardware and Steam Deck playtime reviewers show, next to what Glitchless measured on that build, and with show "vitals" what the store itself measured (slow rendering, crashes, ANRs, hangs) next to Glitchless, version by version.',
|
|
257
|
-
"For a game connected to RevenueCat or to its own Stripe account, glitchless_revenue reads its real revenue by day, version and country (RevenueCat: production purchases only, by store too, installs and active users; Stripe: refunds, fees, net, new paying customers and revenue by product), next to the sessions, players and new players Glitchless measured and what the game's own purchase events add up to.",
|
|
302
|
+
'For a game connected to a store (Steam, Google Play, the App Store, Roblox), glitchless_store reads what players wrote there by build, with the hardware and Steam Deck playtime reviewers show, next to what Glitchless measured on that build, and with show "vitals" what the store itself measured (slow rendering, crashes, ANRs, hangs; on Roblox, crash rate and frame rate by place version and platform, and its retention) next to Glitchless, version by version.',
|
|
303
|
+
"For a game connected to RevenueCat or to its own Stripe account, glitchless_revenue reads its real revenue by day, version and country (RevenueCat: production purchases only, by store too, installs and active users; Stripe: refunds, fees, net, new paying customers and revenue by product), next to the sessions, players and new players Glitchless measured and what the game's own purchase events add up to. For a Roblox game connected to Roblox, it reads the Robux it earned (and what they'd be worth through DevEx), its daily active and new users and its D1, D7 and D30 retention, which the anonymous Roblox SDK can't count.",
|
|
258
304
|
"Each game has its own dashboard, a list of pages (boards of panels, and built-in views such as Errors, Sessions and Live Tail): read it with glitchless_dashboard, and after instrumenting a game, design one that fits it with glitchless_set_dashboard.",
|
|
259
305
|
...(remote
|
|
260
306
|
? ['After shipping a fix (bump the version passed to Glitchless.init), use glitchless_compare_versions to confirm it with real players.']
|
package/src/pictures.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// The pictures an agent gives a game's boards through glitchless_set_dashboard: heatmap backgrounds (`background`, a
|
|
2
|
+
// picture of a level, a zone or the whole game with the world bounds its edges stand for, so the paths and deaths on
|
|
3
|
+
// a positions panel and the Heatmaps view read as the place they happened in: the server's PUT /v1/maps, SPEC §3b
|
|
4
|
+
// Backgrounds) and the brand's logo and banner (`logo`, `banner`: PUT /v1/brand/logo and /v1/brand/banner, §3b
|
|
5
|
+
// Branding). The local server reads a picture from a file on this computer; any server takes it as base64.
|
|
6
|
+
import fs from 'node:fs/promises';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { z } from 'zod';
|
|
9
|
+
import { write, upload, base, isRemote } from './context.js';
|
|
10
|
+
|
|
11
|
+
const TYPES = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp' };
|
|
12
|
+
|
|
13
|
+
// A picture's bytes and type from { file } (only a local server reads files: the hosted one is told the curl to run
|
|
14
|
+
// instead, `url` being where it goes) or { image } (base64 or a data: URL).
|
|
15
|
+
async function readPicture({ file, image }, url) {
|
|
16
|
+
if (file) {
|
|
17
|
+
if (isRemote()) throw new Error(`this server can't read files on your computer: pass the picture as image (base64), or upload it yourself with a secret key that has the dashboard scope: curl -X PUT '${url}' -H 'x-glitchless-api-key: <key>' --data-binary @${file}`);
|
|
18
|
+
return { bytes: await fs.readFile(path.resolve(file)), type: TYPES[path.extname(file).toLowerCase()] || 'application/octet-stream' };
|
|
19
|
+
}
|
|
20
|
+
return { bytes: Buffer.from(image.replace(/^data:[^,]*,/, ''), 'base64'), type: 'application/octet-stream' };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// One place's background for set_dashboard's `background`: save a picture (a file here, or base64) with its world
|
|
24
|
+
// bounds, or remove: true to remove the upload. Returns { text, map? }.
|
|
25
|
+
export async function saveBackground(svc, { level, zone, file, image, axis, bounds, remove }) {
|
|
26
|
+
if (level && zone) throw new Error('give level or zone, not both (neither: the whole game)');
|
|
27
|
+
const place = level ? { level } : zone ? { zone } : {};
|
|
28
|
+
const name = level ? `level ${level}` : zone ? `zone ${zone}` : 'the whole game';
|
|
29
|
+
const where = new URLSearchParams({ service: svc, ...place });
|
|
30
|
+
if (remove) {
|
|
31
|
+
await write('DELETE', `/v1/maps?${where}`);
|
|
32
|
+
return { text: `Removed the uploaded background of ${name}.` };
|
|
33
|
+
}
|
|
34
|
+
if (!file && !image) throw new Error('give background.file or background.image (the picture), or background.remove: true');
|
|
35
|
+
if (!bounds) throw new Error('give bounds: the world coordinates the picture covers, { "min": [a, b], "max": [a, b] }');
|
|
36
|
+
where.set('axis', axis || 'xz');
|
|
37
|
+
where.set('min', bounds.min.join(','));
|
|
38
|
+
where.set('max', bounds.max.join(','));
|
|
39
|
+
const { bytes, type } = await readPicture({ file, image }, `${base()}/v1/maps?${where}`);
|
|
40
|
+
const { map } = await upload('PUT', `/v1/maps?${where}`, bytes, type);
|
|
41
|
+
// A picture shaped unlike its bounds is stretched to fit them: often bounds that don't match its edges.
|
|
42
|
+
const [w, h] = map.size;
|
|
43
|
+
const shape = w / h / ((bounds.max[0] - bounds.min[0]) / (bounds.max[1] - bounds.min[1]));
|
|
44
|
+
const note = shape > 1.15 || shape < 0.87 ? `The picture is ${w} × ${h} pixels but the bounds are ${round(bounds.max[0] - bounds.min[0])} × ${round(bounds.max[1] - bounds.min[1])} world units: it is stretched to fit them. Check that its edges are the bounds.` : null;
|
|
45
|
+
return { text: `Saved the background of ${name}: ${w} × ${h} pixels, ${map.axis === 'xy' ? 'a side view' : 'seen from above'}. The Heatmaps view and positions panels of ${name} draw on it now.${note ? ` ${note}` : ''}`, map };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// The game's backgrounds, captured and uploaded, for glitchless_dashboard; null from a server without them.
|
|
49
|
+
export async function listBackgrounds(svc) {
|
|
50
|
+
return (await write('GET', `/v1/maps?service=${encodeURIComponent(svc)}`).catch(() => null))?.maps ?? null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// The schema of set_dashboard's `background`.
|
|
54
|
+
export const backgroundSchema = z
|
|
55
|
+
.object({
|
|
56
|
+
level: z.string().optional().describe('The level, as the game passes it to levelStart'),
|
|
57
|
+
zone: z.string().optional().describe('Or the zone, as the game passes it to setZone (leave out level and zone for the whole game)'),
|
|
58
|
+
file: z.string().optional().describe('The picture: a PNG, JPEG or WebP file on this computer. Only the local server (npx glitchless-mcp) reads files; the hosted one takes image'),
|
|
59
|
+
image: z.string().optional().describe("The picture as base64 (or a data: URL), where the server can't read your files"),
|
|
60
|
+
axis: z.enum(['xz', 'xy']).optional().describe('xz: seen from above, x across and z down the picture (default); xy: a side view, x across and y up'),
|
|
61
|
+
bounds: z
|
|
62
|
+
.object({ min: z.tuple([z.number(), z.number()]), max: z.tuple([z.number(), z.number()]) })
|
|
63
|
+
.optional()
|
|
64
|
+
.describe('The world coordinates the picture covers on the axis\'s two coordinates: { "min": [x, z], "max": [x, z] } for xz, e.g. { "min": [-120, -80], "max": [120, 80] }'),
|
|
65
|
+
remove: z.boolean().optional().describe("Remove this place's uploaded background (an SDK's capture, if any, shows again)"),
|
|
66
|
+
})
|
|
67
|
+
.describe("A place's heatmap background, so the Heatmaps view and positions panels (where players went and died) read as the room they happened in: a top-down picture of a hub, a lobby or a level and the world bounds its edges stand for, with no SDK code. The place is a level, a zone the game sets with setZone, or neither: the whole game, for a game whose players move about with no level set (a hub); a zone with no picture of its own uses the whole game's. With axis xz (seen from above, the default) the picture's left edge is bounds.min[0] (x) and its right edge bounds.max[0], its top edge bounds.min[1] (z) and its bottom edge bounds.max[1]; with xy (a side view) its top is bounds.max[1] (y). Get the bounds from the game's own level data (the floor's corners), not by guessing. An upload is drawn over whatever an SDK captured for that place; remove: true goes back to the capture. PNG, JPEG or WebP, at most 256 KB and 4096 pixels a side: a JPEG about 1024 pixels across fits. Send it alone to change only the background, one place a call; glitchless_dashboard lists the game's backgrounds");
|
|
68
|
+
|
|
69
|
+
function round(v) {
|
|
70
|
+
return Math.round(v * 100) / 100;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// The brand's logo or banner (kind) for set_dashboard: an image ({ file } or { image }), remove: true, and for the
|
|
74
|
+
// banner a focus (top, center or bottom: what stays in view when it is cropped to a strip). Returns a line to show.
|
|
75
|
+
export async function saveBrandImage(svc, kind, { file, image, remove, focus }) {
|
|
76
|
+
const q = `service=${encodeURIComponent(svc)}`;
|
|
77
|
+
const said = [];
|
|
78
|
+
if (remove) {
|
|
79
|
+
await write('DELETE', `/v1/brand/${kind}?${q}`);
|
|
80
|
+
said.push(`Removed the ${kind}.`);
|
|
81
|
+
} else if (file || image) {
|
|
82
|
+
const { bytes, type } = await readPicture({ file, image }, `${base()}/v1/brand/${kind}?${q}`);
|
|
83
|
+
const { brand } = await upload('PUT', `/v1/brand/${kind}?${q}`, bytes, type);
|
|
84
|
+
const b = brand?.[kind];
|
|
85
|
+
said.push(`Saved the ${kind}${b ? `: ${b.width} × ${b.height} pixels` : ''}.`);
|
|
86
|
+
}
|
|
87
|
+
if (focus) {
|
|
88
|
+
await write('PUT', `/v1/brand?${q}`, { banner_focus: focus });
|
|
89
|
+
said.push(`The banner keeps its ${focus} in view.`);
|
|
90
|
+
}
|
|
91
|
+
if (!said.length) throw new Error(`give ${kind}.file or ${kind}.image (the picture), ${kind}.remove: true${kind === 'banner' ? ', or banner.focus' : ''}`);
|
|
92
|
+
return said.join(' ');
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// The schema of set_dashboard's `logo` and `banner`.
|
|
96
|
+
const picture = {
|
|
97
|
+
file: z.string().optional().describe('A PNG, JPEG or WebP file on this computer. Only the local server (npx glitchless-mcp) reads files; the hosted one takes image'),
|
|
98
|
+
image: z.string().optional().describe("The picture as base64 (or a data: URL), where the server can't read your files"),
|
|
99
|
+
remove: z.boolean().optional().describe('Remove it'),
|
|
100
|
+
};
|
|
101
|
+
export const logoSchema = z
|
|
102
|
+
.object(picture)
|
|
103
|
+
.describe("The game's logo, shown by its name on its boards and share links: PNG, JPEG or WebP (never SVG), at most 100 KB and 1024 × 1024 pixels; the dashboard fits it inside 256 px. Use the game's own logo or icon from its files; ask before making one up");
|
|
104
|
+
export const bannerSchema = z
|
|
105
|
+
.object({ ...picture, focus: z.enum(['top', 'center', 'bottom']).optional().describe('What stays in view when the banner is cropped to a strip (default center); can be sent alone') })
|
|
106
|
+
.describe("The game's banner (its key art), the header behind each board's title, with a dark scrim so the title reads on any picture: PNG, JPEG or WebP, at most 300 KB and 4096 × 2048 pixels; the dashboard crops it to 1600 × 400 around its focus (a short strip on a phone), so a wide picture works best. Use the game's own key art or a capture of it from its files; ask before making one up");
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// What glitchless_session hands an agent from the session query's answer ({ session, timeline, frames }, SPEC §3): by
|
|
2
|
+
// default a summary, level by level in the order they were played (time, tries, deaths and their causes, the game's own
|
|
3
|
+
// events counted, hitches, rage inputs and how it ended there), then how the session ended. A 10-minute session's full
|
|
4
|
+
// answer is tens of thousands of characters, more than an agent can keep in mind next to the code; the summary is a
|
|
5
|
+
// couple of thousand. timelineView() gives the events themselves, filtered to one level or some kinds of event.
|
|
6
|
+
|
|
7
|
+
// The SDKs' own custom events: listed apart (rage inputs) or left out of a level's events (the game's own).
|
|
8
|
+
const SDK_EVENTS = new Set(['rage_input', 'screen_change', 'app_resume', 'webgl_context_restored', 'annotation', 'assets_loaded']);
|
|
9
|
+
// What doesn't go in a level's timeline: frame and server windows are per 5 s, and positions come 4 times a second.
|
|
10
|
+
const WINDOWS = new Set(['frame_window', 'server_window', 'pos', 'map']);
|
|
11
|
+
const ENDS = { level_complete: 'completed', level_fail: 'failed', level_abandon: 'abandoned' };
|
|
12
|
+
|
|
13
|
+
const secs = (ms) => Math.round(ms / 100) / 10;
|
|
14
|
+
const median = (xs) => {
|
|
15
|
+
const v = xs.filter((x) => typeof x === 'number' && Number.isFinite(x)).sort((a, b) => a - b);
|
|
16
|
+
return v.length ? v[Math.floor((v.length - 1) / 2)] : null;
|
|
17
|
+
};
|
|
18
|
+
const add = (o, k, n = 1) => (o[k] = (o[k] || 0) + n);
|
|
19
|
+
const place = (e) => (e.x != null || e.y != null ? { x: e.x ?? null, y: e.y ?? null, z: e.z ?? null } : {});
|
|
20
|
+
|
|
21
|
+
export function sessionSummary({ session = {}, timeline = [], frames = [], server_windows: windows = [] }) {
|
|
22
|
+
const events = [...timeline].sort((a, b) => a.ts - b.ts);
|
|
23
|
+
const t0 = session.start ?? events[0]?.ts ?? 0;
|
|
24
|
+
const end = Math.max(t0 + (session.duration_s ?? 0) * 1000, events.at(-1)?.ts ?? t0);
|
|
25
|
+
const at = (ts) => secs(ts - t0);
|
|
26
|
+
const levels = new Map();
|
|
27
|
+
const row = (level) => {
|
|
28
|
+
let l = levels.get(level);
|
|
29
|
+
if (!l) levels.set(level, (l = { level, first_at_s: null, time_s: 0, tries: 0, completed: 0, failed: 0, abandoned: 0, deaths: 0, causes: {}, fail_causes: {}, events: {}, hitches: 0, worst_hitch_ms: null, hitch_causes: {}, errors: 0, rage_inputs: [], outcome: null }));
|
|
30
|
+
return l;
|
|
31
|
+
};
|
|
32
|
+
// Time on a level runs from its start to its end (complete, fail, abandon), the next level's start, or the session's end.
|
|
33
|
+
let open = null; // { level, from }
|
|
34
|
+
const close = (ts, outcome) => {
|
|
35
|
+
if (!open) return;
|
|
36
|
+
const l = row(open.level);
|
|
37
|
+
l.time_s += (ts - open.from) / 1000;
|
|
38
|
+
l.outcome = outcome;
|
|
39
|
+
open = null;
|
|
40
|
+
};
|
|
41
|
+
const menu = { time_s: 0, events: {}, hitches: 0, errors: 0 };
|
|
42
|
+
const errors = new Map();
|
|
43
|
+
const hitches = [];
|
|
44
|
+
const rage = [];
|
|
45
|
+
const reports = [];
|
|
46
|
+
let disconnects = 0;
|
|
47
|
+
for (const e of events) {
|
|
48
|
+
if (e.type === 'level_start') {
|
|
49
|
+
close(e.ts, 'left');
|
|
50
|
+
const l = row(e.level);
|
|
51
|
+
l.tries++;
|
|
52
|
+
if (l.first_at_s == null) l.first_at_s = at(e.ts);
|
|
53
|
+
if (e.attrs && Object.keys(e.attrs).length) l.attrs = e.attrs;
|
|
54
|
+
open = { level: e.level, from: e.ts };
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (ENDS[e.type] && e.level != null) {
|
|
58
|
+
const l = row(e.level);
|
|
59
|
+
l[ENDS[e.type]]++;
|
|
60
|
+
if (e.type === 'level_fail' && e.cause) add(l.fail_causes, e.cause);
|
|
61
|
+
if (open?.level === e.level) close(e.ts, ENDS[e.type]);
|
|
62
|
+
else l.outcome = ENDS[e.type];
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
// Everything else counts where it happened: its own level, else the level being played, else the menus.
|
|
66
|
+
const where = e.level ?? open?.level ?? null;
|
|
67
|
+
const l = where != null ? row(where) : null;
|
|
68
|
+
if (l && l.first_at_s == null) l.first_at_s = at(e.ts);
|
|
69
|
+
switch (e.type) {
|
|
70
|
+
case 'death':
|
|
71
|
+
if (l) {
|
|
72
|
+
l.deaths++;
|
|
73
|
+
add(l.causes, e.cause ?? 'unknown');
|
|
74
|
+
}
|
|
75
|
+
break;
|
|
76
|
+
case 'custom':
|
|
77
|
+
if (e.name === 'rage_input') {
|
|
78
|
+
const r = { at_s: at(e.ts), level: where, key: e.attrs?.key ?? null, presses: e.attrs?.count ?? null, ...place(e) };
|
|
79
|
+
rage.push(r);
|
|
80
|
+
if (l) l.rage_inputs.push(r);
|
|
81
|
+
} else if (!SDK_EVENTS.has(e.name)) add(l ? l.events : menu.events, e.name);
|
|
82
|
+
break;
|
|
83
|
+
case 'counts':
|
|
84
|
+
for (const c of e.counts || []) if (c?.name) add(l ? l.events : menu.events, c.name, c.n || 1);
|
|
85
|
+
break;
|
|
86
|
+
case 'hitch': {
|
|
87
|
+
const ms = e.duration_ms ?? e.ms ?? null;
|
|
88
|
+
hitches.push({ at_s: at(e.ts), level: where, ms, causes: e.causes ?? [] });
|
|
89
|
+
const into = l ?? menu;
|
|
90
|
+
into.hitches++;
|
|
91
|
+
if (l && ms != null && !(l.worst_hitch_ms >= ms)) l.worst_hitch_ms = Math.round(ms);
|
|
92
|
+
if (l) for (const c of e.causes || []) add(l.hitch_causes, c);
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
case 'error': {
|
|
96
|
+
(l ?? menu).errors++;
|
|
97
|
+
const key = e.fingerprint ?? e.message;
|
|
98
|
+
const x = errors.get(key);
|
|
99
|
+
if (x) x.count++;
|
|
100
|
+
else errors.set(key, { fingerprint: e.fingerprint ?? null, kind: e.kind ?? null, message: String(e.message ?? '').slice(0, 160), first_at_s: at(e.ts), level: where, count: 1 });
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
case 'bug_report':
|
|
104
|
+
reports.push({ at_s: at(e.ts), level: where, note: String(e.note ?? '').slice(0, 160), ...place(e) });
|
|
105
|
+
break;
|
|
106
|
+
case 'disconnect':
|
|
107
|
+
disconnects++;
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
close(end, session.ended === false ? 'still playing' : 'session ended');
|
|
112
|
+
const played = [...levels.values()].reduce((a, l) => a + l.time_s, 0);
|
|
113
|
+
menu.time_s = Math.max(0, Math.round(((end - t0) / 1000 - played) * 10) / 10);
|
|
114
|
+
const byLevel = new Map();
|
|
115
|
+
for (const f of frames) (byLevel.get(f.level ?? null) || byLevel.set(f.level ?? null, []).get(f.level ?? null)).push(f);
|
|
116
|
+
const frameStats = (list = []) => (list.length ? { windows: list.length, fps: median(list.map((f) => f.fps)), p95_ms: median(list.map((f) => f.p95)), worst_ms: Math.max(...list.map((f) => f.max ?? 0)) || null } : null);
|
|
117
|
+
const rows = [...levels.values()].map((l) => {
|
|
118
|
+
const f = frameStats(byLevel.get(l.level));
|
|
119
|
+
return {
|
|
120
|
+
level: l.level,
|
|
121
|
+
first_at_s: l.first_at_s,
|
|
122
|
+
time_s: Math.round(l.time_s * 10) / 10,
|
|
123
|
+
tries: l.tries,
|
|
124
|
+
...(l.attrs ? { attrs: l.attrs } : {}),
|
|
125
|
+
completed: l.completed,
|
|
126
|
+
...(l.failed ? { failed: l.failed, ...(Object.keys(l.fail_causes).length ? { fail_causes: l.fail_causes } : {}) } : {}),
|
|
127
|
+
...(l.abandoned ? { abandoned: l.abandoned } : {}),
|
|
128
|
+
deaths: l.deaths,
|
|
129
|
+
...(Object.keys(l.causes).length ? { causes: l.causes } : {}),
|
|
130
|
+
...(Object.keys(l.events).length ? { events: l.events } : {}),
|
|
131
|
+
hitches: l.hitches,
|
|
132
|
+
...(l.hitches ? { worst_hitch_ms: l.worst_hitch_ms, ...(Object.keys(l.hitch_causes).length ? { hitch_causes: l.hitch_causes } : {}) } : {}),
|
|
133
|
+
...(f ? { frames: f } : {}),
|
|
134
|
+
...(l.errors ? { errors: l.errors } : {}),
|
|
135
|
+
...(l.rage_inputs.length ? { rage_inputs: l.rage_inputs.map(({ level, ...r }) => r) } : {}),
|
|
136
|
+
outcome: l.outcome,
|
|
137
|
+
};
|
|
138
|
+
});
|
|
139
|
+
const s = session;
|
|
140
|
+
const menuFrames = frameStats(byLevel.get(null));
|
|
141
|
+
return {
|
|
142
|
+
session: {
|
|
143
|
+
session_id: s.session_id,
|
|
144
|
+
player_id: s.player_id ?? null,
|
|
145
|
+
session_type: s.session_type,
|
|
146
|
+
...(s.marked_tester ? { marked_tester: true } : {}),
|
|
147
|
+
version: s.version,
|
|
148
|
+
env: s.env,
|
|
149
|
+
start: s.start != null ? new Date(s.start).toISOString() : null,
|
|
150
|
+
duration_s: s.duration_s,
|
|
151
|
+
device: [s.browser, s.os, s.gpu, s.gpu_tier && `${s.gpu_tier} tier`, s.steam_deck && 'Steam Deck'].filter(Boolean).join(', ') || null,
|
|
152
|
+
...(s.props ? { props: s.props } : {}),
|
|
153
|
+
...(s.groups?.length ? { groups: s.groups.map(({ kind, id, attrs }) => ({ kind, id, ...(attrs ? { attrs } : {}) })) } : {}),
|
|
154
|
+
frame_p50_ms: s.p50 ?? null,
|
|
155
|
+
frame_p95_ms: s.p95 ?? null,
|
|
156
|
+
pct_over_budget: s.pct_over_budget ?? null,
|
|
157
|
+
},
|
|
158
|
+
levels: rows,
|
|
159
|
+
...(menu.time_s || Object.keys(menu.events).length || menu.hitches || menu.errors ? { outside_levels: { time_s: menu.time_s, ...(Object.keys(menu.events).length ? { events: menu.events } : {}), hitches: menu.hitches, ...(menuFrames ? { frames: menuFrames } : {}), ...(menu.errors ? { errors: menu.errors } : {}) } } : {}),
|
|
160
|
+
hitches: { count: hitches.length, worst: [...hitches].sort((a, b) => (b.ms ?? 0) - (a.ms ?? 0)).slice(0, 5) },
|
|
161
|
+
...(errors.size ? { errors: [...errors.values()] } : {}),
|
|
162
|
+
...(rage.length ? { rage_inputs: rage } : {}),
|
|
163
|
+
...(reports.length ? { bug_reports: reports } : {}),
|
|
164
|
+
...(disconnects ? { disconnects } : {}),
|
|
165
|
+
...(windows.length ? { server: { windows: windows.length, tick_p95_max: Math.max(...windows.map((w) => w.tick_p95 ?? 0)) || null, players_max: Math.max(...windows.map((w) => w.players ?? 0)) } } : {}),
|
|
166
|
+
outcome: {
|
|
167
|
+
ended: s.ended ?? null,
|
|
168
|
+
crashed: Boolean(s.crashed),
|
|
169
|
+
rage_quit: Boolean(s.rage_quit),
|
|
170
|
+
...(s.rage_quit && s.rage ? { rage: s.rage } : {}),
|
|
171
|
+
last_level: rows.at(-1)?.level ?? null,
|
|
172
|
+
levels_completed: s.completed ?? rows.filter((l) => l.completed).map((l) => l.level),
|
|
173
|
+
},
|
|
174
|
+
timeline_events: events.filter((e) => !WINDOWS.has(e.type)).length,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// The events themselves: `level` keeps that level's (its own, and what happened while it was played), `types` the
|
|
179
|
+
// events of those types or custom event names ("death,hitch", "room_done"; "frames" adds the frame windows). Each
|
|
180
|
+
// gets `at_s`, seconds from the session's start. At most `limit`, from the first; `total` says how many matched.
|
|
181
|
+
export function timelineView({ session = {}, timeline = [], frames = [] }, { level = null, types = null, limit = 150 } = {}) {
|
|
182
|
+
const want = types ? new Set(String(types).split(',').map((x) => x.trim()).filter(Boolean)) : null;
|
|
183
|
+
const events = [...timeline].sort((a, b) => a.ts - b.ts);
|
|
184
|
+
const t0 = session.start ?? events[0]?.ts ?? 0;
|
|
185
|
+
let current = null;
|
|
186
|
+
const out = [];
|
|
187
|
+
for (const e of events) {
|
|
188
|
+
if (e.type === 'level_start') current = e.level;
|
|
189
|
+
const where = e.level ?? current;
|
|
190
|
+
if (ENDS[e.type] && e.level === current) current = null;
|
|
191
|
+
if (WINDOWS.has(e.type)) continue;
|
|
192
|
+
if (level != null && where !== level) continue;
|
|
193
|
+
if (want && !want.has(e.type) && !(e.name && want.has(e.name)) && !(e.type === 'counts' && (e.counts || []).some((c) => want.has(c.name)))) continue;
|
|
194
|
+
out.push({ at_s: secs(e.ts - t0), ...e });
|
|
195
|
+
}
|
|
196
|
+
const windows = want?.has('frames') || want?.has('frame_window') ? frames.filter((f) => level == null || f.level === level).map(({ ctx, ...f }) => ({ at_s: secs(f.ts - t0), ...f, ...ctx })) : null;
|
|
197
|
+
return { total: out.length, events: out.slice(0, limit), ...(windows ? { frames: windows.slice(0, limit) } : {}) };
|
|
198
|
+
}
|
package/src/tools/analytics.js
CHANGED
|
@@ -5,7 +5,7 @@ import { query, resolveService, range, reply, common, tool, filters } from '../c
|
|
|
5
5
|
|
|
6
6
|
tool(
|
|
7
7
|
'glitchless_events',
|
|
8
|
-
"The game's own metrics, from the custom events it sends with track() and the streams it counts with count() (marked counted: summed on the device per window, so their numbers have sums and averages but no spread): each event's count in the window, the sessions and players that sent it, how its attribute values break down (for example plays by mode, paywall views by placement, purchases started vs done; a list attribute such as a deck by element, each event counted once under each), the sums of its numeric attributes per currency (revenue: the amount of purchase events) and their p50, p90 and p99, and `hours`, the hours played in the window, to turn any count into a rate per hour. Give `funnel` to count the sessions that went from one event to the next, in that order. With name and `rate` (a flag such as \"won\", or a word outcome \"result=win\") or `avg` (a numeric attribute), it measures that event: overall, or with `by` per value (win rate by hero, with a 95% interval for each, next to the overall rate). With name and `of` (a numeric attribute), it gives that attribute's distribution: percentiles and a histogram, optionally `by` a split. `properties` lists what the game set for its sessions with setProperties (rank, class, region, a preset), each with its values and their sessions and players; identifier_like marks one with more than 200 values a day, which is an ID rather than a property. Every read tool filters by them (props) and splits by them (by \"$rank\").",
|
|
8
|
+
"The game's own metrics, from the custom events it sends with track() and the streams it counts with count() (marked counted: summed on the device per window, so their numbers have sums and averages but no spread): each event's count in the window, the sessions and players that sent it, how its attribute values break down (for example plays by mode, paywall views by placement, purchases started vs done; a list attribute such as a deck by element, each event counted once under each), the sums of its numeric attributes per currency (revenue: the amount of purchase events) and their p50, p90 and p99, and `hours`, the hours played in the window, to turn any count into a rate per hour. Give `funnel` to count the sessions that went from one event to the next, in that order. With name and `rate` (a flag such as \"won\", or a word outcome \"result=win\") or `avg` (a numeric attribute), it measures that event: overall, or with `by` per value (win rate by hero, with a 95% interval for each, next to the overall rate). With name and `of` (a numeric attribute), it gives that attribute's distribution: percentiles and a histogram, optionally `by` a split. With name and `first`, when sessions first sent it: the median and p90 seconds from a session's start to its first one (time in the lobby before first leaving it), and the share of ended sessions that never sent it (31 days or less). `properties` lists what the game set for its sessions with setProperties (rank, class, region, a preset), each with its values and their sessions and players; identifier_like marks one with more than 200 values a day, which is an ID rather than a property. Every read tool filters by them (props) and splits by them (by \"$rank\"). By default each attribute shows its top 5 values (a numeric one its average and percentiles) and each property its top 5: `detail: true` gives every value with its sessions.",
|
|
9
9
|
{
|
|
10
10
|
...common,
|
|
11
11
|
name: z.string().optional().describe('Only this event, e.g. "paywall". With rate, avg or of, the event to measure; it can carry a filter like a panel\'s event: "match_end:mode=ranked", or "battle_end:deck=hog_rider+ice_spirit" for decks with both'),
|
|
@@ -15,10 +15,12 @@ tool(
|
|
|
15
15
|
of: z.string().optional().describe('A numeric attribute whose distribution to give, e.g. "duration_s" (match length) or "placement"'),
|
|
16
16
|
by: z.string().optional().describe('With rate, avg or of: split by an attribute (a list splits by element), $version, $level, $zone, $platform, $browser, $device_tier, $link (the kind of connection), or a session property ("$rank")'),
|
|
17
17
|
min: z.number().int().optional().describe('With rate or avg and by: the fewest events a row needs (default 30 for a rate, 10 for an average); smaller rows are counted in small'),
|
|
18
|
+
first: z.boolean().optional().describe('With name: the seconds from each session\'s start to its first such event (median_s, p90_s, over the sessions that sent it) and the ended sessions that never sent it (never, ended, never_pct). For a lobby: how long players stay before first leaving, and how many never leave. Works for events a Roblox server sends for a player'),
|
|
19
|
+
detail: z.boolean().optional().describe("Every value of every attribute and property, with its sessions (default: the top 5 of each)"),
|
|
18
20
|
},
|
|
19
|
-
async ({ service, hours, name, funnel, rate, avg, of, by, min, ...f }) => {
|
|
21
|
+
async ({ service, hours, name, funnel, rate, avg, of, by, min, first, detail, ...f }) => {
|
|
20
22
|
const svc = await resolveService(service);
|
|
21
|
-
const d = await query('events', { service: svc, ...filters(f), name: name?.split(/[:=]/)[0].trim(), event: name, funnel, rate, avg, of, by, min, ...range(hours) });
|
|
23
|
+
const d = await query('events', { service: svc, ...filters(f), name: name?.split(/[:=]/)[0].trim(), event: name, funnel, rate, avg, of, by, min, ...(first ? { first: 1 } : {}), ...range(hours) });
|
|
22
24
|
const brief = d.events
|
|
23
25
|
.slice(0, 15)
|
|
24
26
|
.map((e) => `${e.name}${e.counted ? ' (counted)' : ''}: ${e.count} in ${e.sessions} session(s)${(e.sums || []).length ? `; ${e.sums.map((x) => `${x.attr} sum ${x.sum}${x.currency ? ` ${x.currency}` : ''}`).join(', ')}` : ''}`)
|
|
@@ -28,17 +30,36 @@ tool(
|
|
|
28
30
|
const m = d.measure;
|
|
29
31
|
const measured = m ? `\n${m.event} ${m.rate ? `rate of ${m.rate}` : `average ${m.avg}`}${m.by ? ` by ${m.by}` : ''}: ${m.empty ? m.why : m.rows ? `${m.rows.length} rows, overall ${m.overall}${m.rate ? '%' : ''}` : `${m.value}${m.unit === '%' ? '%' : ''} of ${m.events} events`}` : '';
|
|
30
32
|
const dist = d.distribution ? `\n${d.distribution.event} ${d.distribution.of}: ${d.distribution.empty ? d.distribution.why : `p50 ${d.distribution.p50}, p90 ${d.distribution.p90} of ${d.distribution.count}`}` : '';
|
|
31
|
-
|
|
32
|
-
|
|
33
|
+
const fs = d.first;
|
|
34
|
+
const firstLine = fs ? `\n${fs.event}, first in a session: ${fs.empty ? fs.why : `${fs.median_s == null ? 'no session sent it' : `median ${fs.median_s} s after the session started, p90 ${fs.p90_s} s (${fs.sessions} sessions)`}; ${fs.never_pct == null ? 'no session has ended yet' : `${fs.never_pct}% of ${fs.ended} ended sessions never sent it`}`}` : '';
|
|
35
|
+
return reply(`Custom events for ${svc} (${hours || 24}h, ${d.sessions} sessions, ${d.hours ?? 0} hours played):\n${brief || 'None in this window. A game sends them with track(name, attrs), and streams with count(name, attrs).'}${propLine}${measured}${dist}${firstLine}${detail ? '' : '\n(Top 5 values of each attribute and property: detail: true gives them all.)'}`, {
|
|
36
|
+
events: d.events.map(({ series, ...e }) => (detail ? e : compactEvent(e))),
|
|
33
37
|
hours_played: d.hours ?? null,
|
|
34
|
-
properties: props,
|
|
38
|
+
properties: detail ? props : props.map(compactProperty),
|
|
35
39
|
...(d.funnel ? { funnel: d.funnel } : {}),
|
|
36
40
|
...(m ? { measure: (({ ts, series, ...x }) => x)(m) } : {}),
|
|
37
41
|
...(d.distribution ? { distribution: d.distribution } : {}),
|
|
38
|
-
|
|
42
|
+
...(fs ? { first: fs } : {}),
|
|
43
|
+
}, { rows: !detail });
|
|
39
44
|
},
|
|
40
45
|
);
|
|
41
46
|
|
|
47
|
+
// An event as glitchless_events lists it by default: each attribute's top values ({ value: events }) and how many it
|
|
48
|
+
// has, or a numeric one's average and percentiles, instead of every value with its sessions.
|
|
49
|
+
const TOP = 5;
|
|
50
|
+
function compactEvent({ attrs = [], ...e }) {
|
|
51
|
+
return { ...e, attrs: Object.fromEntries(attrs.map((a) => [a.key, compactAttr(a)])) };
|
|
52
|
+
}
|
|
53
|
+
function compactAttr(a) {
|
|
54
|
+
const values = a.values || [];
|
|
55
|
+
if (a.avg != null || a.p50 != null) return { avg: a.avg ?? null, ...(a.p50 != null ? { p50: a.p50, p90: a.p90, p99: a.p99 } : {}), values: values.length };
|
|
56
|
+
return { ...(a.list ? { list: true } : {}), top: Object.fromEntries(values.slice(0, TOP).map((v) => [v.value, v.count])), ...(values.length > TOP ? { more_values: values.length - TOP } : {}) };
|
|
57
|
+
}
|
|
58
|
+
// A session property's top values ({ value: sessions }).
|
|
59
|
+
function compactProperty({ values = [], ...p }) {
|
|
60
|
+
return { ...p, top: Object.fromEntries(values.slice(0, TOP).map((v) => [v.value, v.sessions])), ...(values.length > TOP ? { more_values: values.length - TOP } : {}) };
|
|
61
|
+
}
|
|
62
|
+
|
|
42
63
|
tool(
|
|
43
64
|
'glitchless_compare_versions',
|
|
44
65
|
'Compare game versions side by side, in the game\'s own terms first: the stats on its boards (glitchless_dashboard) and its own events per session, then the built-in measures it reports (frame time overall and per level, the share of frames over their own screen\'s budget, hitches/min, crash-free and error-free sessions, errors per session, level completion, rage-quit rate, deaths per session, geometry growth). Use it to confirm a fix or a design change after shipping a new version. Versions come in release order (when each first showed up at all, not in this window), so by default it compares the newest with the one before it, also while players of older versions still play. For a game on Steam, by "steam_branch" compares Steam branches instead (a beta against "public"), and by "steam_build" Steam builds: a and b are then branch names or build ids. By a session property ("class", "spender"; glitchless_events lists them) it compares that property\'s values the same way, the most sessions first (over 31 days or less): a and b are then values.',
|