ravensight-playtest 0.8.3 → 0.10.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.
Files changed (66) hide show
  1. package/README.md +280 -66
  2. package/addons/ravensight_driver/driver.gd +666 -21
  3. package/docs/ADAPTERS.md +11 -7
  4. package/docs/NATIVE_RUNNER.md +3 -1
  5. package/docs/godot-driver.md +127 -13
  6. package/package.json +8 -6
  7. package/src/api/client.js +4 -3
  8. package/src/cli.js +84 -25
  9. package/src/commands/check.js +30 -4
  10. package/src/commands/fakeCore.js +1 -0
  11. package/src/commands/hosted.js +41 -12
  12. package/src/commands/init.js +17 -1
  13. package/src/commands/run.js +209 -14
  14. package/src/commands/upload.js +6 -2
  15. package/src/commands/validate.js +1 -1
  16. package/src/commands/validateHosted.js +50 -5
  17. package/src/config.js +33 -2
  18. package/src/hosted/archivePreflight.js +7 -7
  19. package/src/hosted/buildUpload.js +89 -8
  20. package/src/hosted/recordedRun.js +141 -26
  21. package/src/hosted/status.js +19 -10
  22. package/src/run/actionSelector.js +14 -3
  23. package/src/run/aggregate.js +57 -3
  24. package/src/run/anygame/controlbook.js +179 -0
  25. package/src/run/anygame/genre.js +179 -0
  26. package/src/run/anygame/index.js +258 -0
  27. package/src/run/anygame/language.js +336 -0
  28. package/src/run/anygame/memory.js +330 -0
  29. package/src/run/anygame/shared-hashes.json +10 -0
  30. package/src/run/anygame/shared.js +24 -0
  31. package/src/run/anygame/sound.js +342 -0
  32. package/src/run/args.js +75 -8
  33. package/src/run/choiceCheck.js +312 -0
  34. package/src/run/context.js +254 -13
  35. package/src/run/drivers/godot-observation.js +93 -6
  36. package/src/run/drivers/godot.js +769 -46
  37. package/src/run/drivers/recording.js +24 -4
  38. package/src/run/drivers/web.js +1242 -77
  39. package/src/run/edgePass.js +731 -0
  40. package/src/run/fixLoop.js +5 -4
  41. package/src/run/focus.js +65 -0
  42. package/src/run/gamepad.js +108 -0
  43. package/src/run/godotEdgePass.js +235 -0
  44. package/src/run/godotTesterProbes.js +192 -0
  45. package/src/run/headings.js +21 -0
  46. package/src/run/honesty.js +544 -0
  47. package/src/run/inputs.js +256 -0
  48. package/src/run/marks.js +142 -0
  49. package/src/run/personaLoop.js +1000 -79
  50. package/src/run/phone.js +7 -0
  51. package/src/run/pixels.js +215 -0
  52. package/src/run/playClock.js +162 -0
  53. package/src/run/readiness.js +585 -0
  54. package/src/run/refusal.js +67 -0
  55. package/src/run/regions.js +119 -0
  56. package/src/run/report.js +14 -2
  57. package/src/run/reportChecks.js +472 -0
  58. package/src/run/resume.js +3 -2
  59. package/src/run/screenshots.js +161 -0
  60. package/src/run/strip.js +114 -0
  61. package/src/run/testerLedger.js +312 -0
  62. package/src/run/testerProbes.js +584 -0
  63. package/src/run/thinRun.js +102 -0
  64. package/src/run/timeFreeze.js +79 -0
  65. package/src/run/tools.js +454 -29
  66. package/src/runDefaults.js +24 -2
@@ -20,6 +20,7 @@
20
20
  // with RAVENSIGHT_PLAYTEST_TOKEN / _RUN_ID / _JOB_ID / _PERSONA set so the
21
21
  // game's own Ravensight SDK tags every event it tracks as synthetic,
22
22
  // 4. dial 127.0.0.1, say hello{token}, and poll ping until the game answers.
23
+ import { createHash } from 'node:crypto';
23
24
  import { spawn } from 'node:child_process';
24
25
  import { track } from '../liveWork.js';
25
26
  import { randomBytes } from 'node:crypto';
@@ -28,6 +29,7 @@ import fs from 'node:fs/promises';
28
29
  import path from 'node:path';
29
30
 
30
31
  import { buildObservation, needsVision } from './godot-observation.js';
32
+ import { pngFingerprint, screenDelta, significant } from '../pixels.js';
31
33
  import {
32
34
  detectGodotBinary,
33
35
  reservePort,
@@ -38,6 +40,10 @@ import {
38
40
  setIniEntry,
39
41
  } from './godot-project.js';
40
42
  import { screenshotName } from './driver.js';
43
+ import { STRIP_MIN_MS, stripNote, stripTimes, stripTokens } from '../strip.js';
44
+ import {
45
+ DEFAULT_DRAG_MS, KEY_REPEAT_DELAY_MS, MAX_DRAG_MS, MAX_HOLD_MS as INPUT_MAX_HOLD_MS, dragPath, mouseButton, sequenceEvents, wheelNotches
46
+ } from '../inputs.js';
41
47
  import { DriverRpcError, GodotRpcClient } from './godot-rpc.js';
42
48
  import { detectFfmpeg } from '../../detect.js';
43
49
  import { recordingLimits, recordingViewport, recordingDirectory, recordingMetadata, saveRecording, encodeFrames } from './recording.js';
@@ -54,11 +60,53 @@ export const BOOT_POLL_MS = 250;
54
60
  */
55
61
  export const MAX_HOLD_MS = 5000;
56
62
 
63
+ /**
64
+ * How deep the scene tree is read. Six levels cut a card grid off at its
65
+ * container, so the cards and the labels inside them never reached the
66
+ * persona; twelve reaches a label inside a card inside a grid inside a screen.
67
+ */
68
+ export const DEFAULT_TREE_DEPTH = 12;
69
+
70
+ /**
71
+ * The frame the model is shown: JPEG, at the window's own size. The proxy
72
+ * reserves a request by its bytes, so a PNG of a busy screen would reserve a
73
+ * large share of a run's model budget for one look; the same frame as JPEG is
74
+ * a fraction of it. Evidence screenshots stay PNG.
75
+ */
76
+ export const MODEL_FRAME = Object.freeze({ format: 'jpeg', quality: 0.6, mediaType: 'image/jpeg' });
77
+
78
+ /** The frames a recording is made of. */
79
+ export const VIDEO_FRAME = Object.freeze({ format: 'jpeg', quality: 0.8 });
80
+
81
+ /**
82
+ * A frame capture that failed this soon before the game exited is put down to
83
+ * the exit. The screenshot in flight when a game dies fails as its socket
84
+ * closes, which Node usually sees before the process exit itself.
85
+ */
86
+ export const EXIT_ATTRIBUTION_MS = 2000;
87
+
88
+ /**
89
+ * A subtree the depth cut left unread is read on its own, this many at most
90
+ * per snapshot and this much deeper each, so a label below the cut (a card
91
+ * whose text sits thirteen levels down) still reaches the persona. Past the
92
+ * limit the outline says `+N more`, as before.
93
+ */
94
+ export const MAX_CUT_EXPANSIONS = 32;
95
+ export const CUT_EXPANSION_DEPTH = 8;
96
+
97
+ /** The width of the small PNG two screens are compared by. */
98
+ export const PROBE_WIDTH = 320;
99
+
100
+ /** The most nodes a click target that matched several is answered with. */
101
+ const MAX_MATCHES_NAMED = 4;
102
+
103
+ const PRESSABLE_TYPE = /Button|LineEdit|TextEdit|Slider|CheckBox|CheckButton|OptionButton|ItemList|Tree/;
104
+
57
105
  /** The longest wait action, matching the browser driver's. */
58
106
  export const MAX_WAIT_MS = 10000;
59
107
 
60
108
  /** The most keys one action may hold down together (a diagonal is two). */
61
- export const MAX_HELD_KEYS = 3;
109
+ export const MAX_HELD_KEYS = 6;
62
110
 
63
111
  /** In the path of every user:// a lockstep run creates, so stop removes only those. */
64
112
  const USER_DIR_MARKER = 'ravensight-lockstep';
@@ -199,6 +247,18 @@ const SOURCE_LINE = /^\s+at:\s*(.+)$/;
199
247
  * @param {Array<Array<number>>} [clicks] - where the driver says each click landed
200
248
  * @returns {Array<Object>}
201
249
  */
250
+ /**
251
+ * What a select did, in the game's own words for the option.
252
+ *
253
+ * @param {{kind?: string, option?: string, value?: number, min?: number, max?: number}|undefined} answer
254
+ * @returns {string|null}
255
+ */
256
+ export function selectDetail(answer) {
257
+ if (!answer) return null;
258
+ if (answer.kind === 'range') return `Set it to ${Math.round(Number(answer.value) * 1000) / 1000} (it runs from ${answer.min} to ${answer.max}).`;
259
+ return `Chose ${JSON.stringify(String(answer.option ?? ''))}.`;
260
+ }
261
+
202
262
  export function traceableEvents(events, clicks = []) {
203
263
  let index = 0;
204
264
  return events.map((event) => {
@@ -211,6 +271,27 @@ export function traceableEvents(events, clicks = []) {
211
271
  });
212
272
  }
213
273
 
274
+ /**
275
+ * A line for the model when the picture it is shown is not at click scale
276
+ * (a window wider than the frame limit), or '' when a point on the picture is
277
+ * the point to click.
278
+ *
279
+ * @param {{width?: number, height?: number, window?: number[]}} shot
280
+ * @returns {string}
281
+ */
282
+ export function frameScaleNote(shot) {
283
+ const [windowWidth, windowHeight] = Array.isArray(shot?.window) ? shot.window.map(Number) : [];
284
+ const width = Number(shot?.width);
285
+ if (!Number.isFinite(windowWidth) || !Number.isFinite(width) || width <= 0 || windowWidth <= 0 || Math.abs(windowWidth - width) < 1) return '';
286
+ const factor = Math.round((windowWidth / width) * 100) / 100;
287
+ return `note: the picture is ${width} pixels wide and the window is ${windowWidth}x${windowHeight}: multiply a point read off the picture by ${factor} for click x and y. The centre(x,y) figures in the outline are already in window pixels.`;
288
+ }
289
+
290
+ /** The addon could not find the node a click or key named: the target was wrong, not the game. */
291
+ function isTargetMiss(error) {
292
+ return /node not found/i.test(String(error?.rpcMessage ?? ''));
293
+ }
294
+
214
295
  export class GodotDriver {
215
296
  constructor({
216
297
  projectDir,
@@ -225,7 +306,7 @@ export class GodotDriver {
225
306
  bootTimeoutMs = BOOT_TIMEOUT_MS,
226
307
  callTimeoutMs = 15000,
227
308
  exitTimeoutMs = 5000,
228
- treeDepth = 6,
309
+ treeDepth = DEFAULT_TREE_DEPTH,
229
310
  settleFrames = 2,
230
311
  keepTemp = false,
231
312
  // The game's clock is frozen between actions (time_scale 0) and runs only
@@ -257,6 +338,16 @@ export class GodotDriver {
257
338
  this.name = DRIVER_NAME;
258
339
  // The key action holds its keys for hold_ms (and with_keys together).
259
340
  this.supportsHold = true;
341
+ // The pointer tools this driver can do (../tools.js). There is no select:
342
+ // a Godot dropdown is opened and picked with clicks.
343
+ this._basePointerTools = Object.freeze(['drag', 'hover', 'scroll', 'sequence']);
344
+ // The game stands still between actions, so thinking costs no play time.
345
+ this.frozenBetweenActions = Boolean(lockstep || pauseBetweenActions);
346
+ // The scripted checks after play are the Godot ones (../godotEdgePass.js).
347
+ this.edgeKind = 'godot';
348
+ // Frames taken while the last input played (../strip.js), for the next look.
349
+ this._strip = null;
350
+ this._stripCount = 0;
260
351
  this.projectDir = projectDir;
261
352
  this.runDir = runDir;
262
353
  this.godotPath = godotPath;
@@ -321,6 +412,12 @@ export class GodotDriver {
321
412
  this._shotIndex = 0;
322
413
  this._frameIndex = 0;
323
414
  this._lastHash = null;
415
+ // The tree of the last snapshot, which a click target is resolved against.
416
+ this._lastTree = null;
417
+ // The last observation's text and small frame, to say "unchanged".
418
+ this._lastObservedHash = null;
419
+ this._lastProbe = null;
420
+ this._lastUsedVision = false;
324
421
  this._logTail = [];
325
422
  this._logPending = '';
326
423
  this._consoleQueue = [];
@@ -334,9 +431,147 @@ export class GodotDriver {
334
431
  return !this._stopped && this.exitCode !== null && this.exitCode !== 0;
335
432
  }
336
433
 
434
+ /**
435
+ * The pointer tools this driver can do (../tools.js). select needs addon
436
+ * 1.5.0: an older addon in the project keeps the four it had, and a dropdown
437
+ * is then opened and picked with clicks.
438
+ */
439
+ get pointerTools() {
440
+ return this.addonAtLeast(1, 5) ? [...this._basePointerTools, 'select'] : this._basePointerTools;
441
+ }
442
+
443
+ /** Whether the addon the game answered with is at least this version. */
444
+ addonAtLeast(major, minor) {
445
+ const [a, b] = String(this.ping?.driver_version ?? '0.0').split('.').map(Number);
446
+ return a > major || (a === major && b >= minor);
447
+ }
448
+
449
+ /** The ticks of a step, counted from one, that a strip's frames are due on. */
450
+ _stripTicks(ms, ticks) {
451
+ if (this.headless || !this.addonAtLeast(1, 5) || !(ms >= STRIP_MIN_MS)) return null;
452
+ const times = stripTimes(ms);
453
+ return { times, ticks: times.map((at) => Math.min(Math.max(1, Math.round((at / 1000) * this.ticksPerSecond)), ticks)) };
454
+ }
455
+
456
+ /** Read what the frames showed, and keep it for the look that follows. */
457
+ async _settleStrip(times) {
458
+ this._strip = null;
459
+ if (!times || times.length === 0) return;
460
+ let status;
461
+ try {
462
+ status = await this.rpc.call('strip_status', {});
463
+ } catch (error) {
464
+ if (error instanceof DriverRpcError) return;
465
+ throw error;
466
+ }
467
+ if (!status || !(status.frames > 0)) return;
468
+ const used = times.slice(0, status.frames);
469
+ const facts = { times: used, moved: Boolean(status.moved), endedWhereItBegan: Boolean(status.moved && status.ended_as_began) };
470
+ this._stripFacts = { frames: status.frames, moved: facts.moved };
471
+ this._stripMoved = facts.moved;
472
+ const said = stripNote(facts);
473
+ this._lastDetail = this._lastDetail ? `${this._lastDetail}\n${said}` : said;
474
+ if (facts.moved) this._strip = facts;
475
+ }
476
+
477
+ /** Sleep on the wall clock, taking a strip frame at each of its times. */
478
+ async _sleepWithStrip(ms) {
479
+ if (this.headless || !this.addonAtLeast(1, 5) || !(ms >= STRIP_MIN_MS)) { await this._sleep(ms); return null; }
480
+ const scale = Number(this._resumeScale) > 0 ? Number(this._resumeScale) : 1;
481
+ const times = stripTimes(Math.round(ms * scale));
482
+ await this.rpc.call('strip_begin', {}).catch(() => {});
483
+ const started = this._now();
484
+ for (const at of times.map((time) => holdWallMs(time, this._resumeScale))) {
485
+ const wait = started + at - this._now();
486
+ if (wait > 0) await this._sleep(wait);
487
+ await this.rpc.call('strip_frame', {}).catch(() => {});
488
+ }
489
+ const rest = started + ms - this._now();
490
+ if (rest > 0) await this._sleep(rest);
491
+ return times;
492
+ }
493
+
494
+ /**
495
+ * Let the game run for a time with no input: game time in lockstep, the
496
+ * wall clock otherwise. For the runner's own checks after play.
497
+ */
498
+ async runFor(ms, { action = 'edge_wait', events = [] } = {}) {
499
+ if (this.lockstep) return this.step(events, this._ticksFor(ms), { action, args: { ms } });
500
+ const pausing = this.pauseBetweenActions && this._paused;
501
+ try {
502
+ if (pausing) await this._resume();
503
+ await this._sleep(ms);
504
+ } finally {
505
+ if (pausing && this.rpc && !this.rpc.closed) await this._freeze().catch(() => {});
506
+ }
507
+ return null;
508
+ }
509
+
510
+ /** One key down or up for the runner's own checks, however this run sends keys. */
511
+ async sendKey(key, pressed, ms = 0) {
512
+ if (this.lockstep) return this.step([{ type: 'key', keycode: key, pressed }], Math.max(1, this._ticksFor(ms)), { action: 'edge_key', args: { key, pressed } });
513
+ const pausing = this.pauseBetweenActions && this._paused;
514
+ try {
515
+ if (pausing) await this._resume();
516
+ await this.rpc.call('key', { keycode: key, pressed });
517
+ if (ms > 0) await this._sleep(ms);
518
+ } finally {
519
+ if (pausing && this.rpc && !this.rpc.closed) await this._freeze().catch(() => {});
520
+ }
521
+ return null;
522
+ }
523
+
524
+ /**
525
+ * Start the game a second time on the same save folder, without a window,
526
+ * let it run a moment and stop it: does a game that has saved come back?
527
+ * Only on a run with a save folder of its own (lockstep).
528
+ *
529
+ * @returns {Promise<{booted: boolean, error?: string, log?: string}|null>} null when it cannot be tried
530
+ */
531
+ async restartCheck({ runMs = 1500, bootTimeoutMs = 30000 } = {}) {
532
+ if (!this.lockstep || !this.projectCopy || !this.godot || !String(this.userDataDir ?? '').includes(USER_DIR_MARKER)) return null;
533
+ const port = await this._choosePort();
534
+ const token = randomBytes(24).toString('hex');
535
+ const lines = [];
536
+ const env = { ...allowlistedEnv(this.env), ...(this.extraEnv ?? {}), RAVENSIGHT_DRIVER: '1', RAVENSIGHT_DRIVER_PORT: String(port), RAVENSIGHT_DRIVER_TOKEN: token };
537
+ const child = this._spawn(this.godot.path, ['--path', this.projectCopy, '--headless', '--', '--ravensight-driver', `--ravensight-driver-port=${port}`], { cwd: this.projectCopy, env, stdio: ['ignore', 'pipe', 'pipe'] });
538
+ let exit = null;
539
+ child.on('exit', (code, signal) => { exit = { code, signal }; });
540
+ child.on('error', () => { exit = { code: -1, signal: null }; });
541
+ for (const stream of [child.stdout, child.stderr]) stream?.on('data', (chunk) => { lines.push(...chunk.toString('utf8').split('\n').filter(Boolean)); if (lines.length > 200) lines.splice(0, lines.length - 200); });
542
+ const rpc = new GodotRpcClient({ port, timeoutMs: this.callTimeoutMs });
543
+ const tail = () => lines.slice(-8).join('\n');
544
+ try {
545
+ try {
546
+ await rpc.connect({ attempts: Math.max(1, Math.ceil(bootTimeoutMs / BOOT_POLL_MS)), delayMs: BOOT_POLL_MS });
547
+ await rpc.call('hello', { token });
548
+ } catch (error) {
549
+ return { booted: false, error: exit ? `the game exited with code ${exit.code} while starting` : `the game did not answer within ${Math.round(bootTimeoutMs / 1000)} seconds of starting (${error.message})`, log: tail() };
550
+ }
551
+ await rpc.call('wait_frames', { n: BOOT_SETTLE_FRAMES }).catch(() => {});
552
+ await this._sleep(runMs);
553
+ const alive = exit === null && await rpc.call('ping').then(() => true, () => false);
554
+ const fatal = lines.filter((line) => BOOT_FATAL_LINE.some((pattern) => pattern.test(line)));
555
+ const errors = lines.filter((line) => ERROR_LINE.test(line.trim())).slice(0, 4);
556
+ if (!alive) return { booted: false, error: exit ? `the game exited with code ${exit.code} a moment after starting` : 'the game stopped answering a moment after starting', log: tail() };
557
+ if (fatal.length > 0) return { booted: false, error: `the game's scripts did not load on the second start: ${fatal.slice(0, 2).map((line) => line.trim()).join(' | ')}`, log: tail() };
558
+ const state = await rpc.call('get_state', { max_depth: 1, visible_only: true }).catch(() => null);
559
+ const files = await rpc.call('user_files', {}).catch(() => null);
560
+ return { booted: true, scene: state?.current_scene_file ?? state?.current_scene ?? null, files: files?.files ?? null, errors };
561
+ } finally {
562
+ await rpc.call('quit', { code: 0 }).catch(() => {});
563
+ rpc.close?.();
564
+ await new Promise((resolve) => setTimeout(resolve, 200));
565
+ if (exit === null) child.kill('SIGKILL');
566
+ }
567
+ }
568
+
337
569
  async launch({ recordVideo = false, viewport, signal } = {}) {
338
570
  if (signal?.aborted) throw new Error('run canceled before game launch');
339
571
  if (viewport) this.viewport = viewport;
572
+ // 'auto' is the default recording: kept on this machine when it can be
573
+ // made (a window and ffmpeg), and never a reason to change how the game runs.
574
+ this._recordAuto = recordVideo === 'auto';
340
575
  if (recordVideo) {
341
576
  const size = recordingViewport(this.viewport, this._recordingLimits);
342
577
  this.viewport = { w: size.width, h: size.height };
@@ -374,7 +609,7 @@ export class GodotDriver {
374
609
  args.push('--fixed-fps', String(this.ticksPerSecond));
375
610
  await this._isolateUserData();
376
611
  }
377
- if (recordVideo) args.push('--audio-driver', 'Dummy');
612
+ if (recordVideo && !this._recordAuto) args.push('--audio-driver', 'Dummy');
378
613
  if (this.headless) args.push('--headless');
379
614
  else args.push('--resolution', `${this.viewport.w}x${this.viewport.h}`);
380
615
  args.push('--', '--ravensight-driver', `--ravensight-driver-port=${this.port}`);
@@ -543,11 +778,13 @@ export class GodotDriver {
543
778
  * @param {{action?: string, args?: Object, digest?: boolean, redacted?: boolean}} [record]
544
779
  * @returns {Promise<{tick: number, digest?: Object}>}
545
780
  */
546
- async step(events, ticks, { action = 'step', args = {}, digest = true, redacted = false } = {}) {
781
+ async step(events, ticks, { action = 'step', args = {}, digest = true, redacted = false, stripAt = null, stripNew = false } = {}) {
547
782
  const whole = Math.min(Math.max(Math.round(Number(ticks) || 1), 1), MAX_STEP_TICKS);
548
783
  const answer = await this.rpc.call(
549
784
  'step',
550
- { events, ticks: whole, digest },
785
+ // Frames for a strip read the screen on these ticks; they are no part of
786
+ // the trace, and a replay without them plays the same game.
787
+ { events, ticks: whole, digest, ...(stripAt ? { strip_at: stripAt, ...(stripNew ? { strip_new: true } : {}) } : {}) },
551
788
  // A windowed game may be held to the display's rate.
552
789
  { timeoutMs: this.callTimeoutMs + whole * STEP_MS_PER_TICK },
553
790
  );
@@ -577,21 +814,25 @@ export class GodotDriver {
577
814
  const settle = Math.max(0, this.settleFrames);
578
815
  switch (action.kind) {
579
816
  case 'key': {
580
- const keys = [action.key, ...(Array.isArray(action.keys) ? action.keys : [])]
581
- .filter((key) => typeof key === 'string' && key !== '')
582
- .slice(0, MAX_HELD_KEYS);
817
+ const keys = this._keysOf(action);
583
818
  const holdMs = holdWallMs(action.holdMs, this._resumeScale);
584
819
  const args = { key: action.key, keys: action.keys, hold_ms: action.holdMs };
820
+ // A key held past a keyboard's delay repeats, as a keyboard's does: the
821
+ // addon echoes the last key on the ticks a keyboard would.
822
+ const repeats = holdMs >= KEY_REPEAT_DELAY_MS;
823
+ const heldTicks = holdMs > 0 ? this._ticksFor(holdMs) : 1;
824
+ const strip = this._stripTicks(Number(action.holdMs) || 0, heldTicks);
585
825
  await this.step(
586
- keys.map((key) => ({ type: 'key', keycode: key, pressed: true })),
587
- holdMs > 0 ? this._ticksFor(holdMs) : 1,
588
- { action: 'key', args, digest: false },
826
+ keys.map((key, index) => ({ type: 'key', keycode: key, pressed: true, ...(repeats && index === keys.length - 1 ? { repeat: true } : {}) })),
827
+ heldTicks,
828
+ { action: 'key', args, digest: false, ...(strip ? { stripAt: strip.ticks, stripNew: true } : {}) },
589
829
  );
590
830
  await this.step(
591
831
  [...keys].reverse().map((key) => ({ type: 'key', keycode: key, pressed: false })),
592
832
  Math.max(settle, 1),
593
833
  { action: 'key_release', args },
594
834
  );
835
+ await this._settleStrip(strip ? strip.times : null);
595
836
  return;
596
837
  }
597
838
  case 'type': {
@@ -616,13 +857,91 @@ export class GodotDriver {
616
857
  await this.step([], Math.max(settle, 2), { action: 'settle', args: {} });
617
858
  return;
618
859
  }
860
+ case 'select': {
861
+ const event = { type: 'select', node_path: action.target, ...(action.option !== undefined ? { option: action.option } : {}), ...(action.value !== undefined ? { value: action.value } : {}) };
862
+ const answer = await this.step([event], 2 + settle, { action: 'select', args: event });
863
+ this._lastDetail = selectDetail(answer.selects?.[0]);
864
+ return;
865
+ }
619
866
  case 'click': {
620
867
  const target = action.target;
621
868
  const where = typeof target === 'string'
622
869
  ? { node_path: target }
623
870
  : { x: target?.x ?? 0, y: target?.y ?? 0 };
624
- const event = { type: 'click', ...where, ...(action.button ? { button: action.button } : {}), ...(action.double ? { double: true } : {}) };
625
- await this.step([event], 2 + settle, { action: 'click', args: where });
871
+ const extras = { ...(action.button ? { button: action.button } : {}), ...(action.double ? { double: true } : {}) };
872
+ const hold = Math.min(Math.max(Number(action.holdMs) || 0, 0), INPUT_MAX_HOLD_MS);
873
+ if (hold > 0) {
874
+ // A held press: down, the game runs for the hold, up.
875
+ const strip = this._stripTicks(hold, this._ticksFor(hold));
876
+ await this.step([{ type: 'mouse', kind: 'move', ...where }, { type: 'mouse', kind: 'down', ...where, ...extras }], this._ticksFor(hold), { action: 'click_hold', args: { ...where, hold_ms: hold, ...extras }, digest: false, ...(strip ? { stripAt: strip.ticks, stripNew: true } : {}) });
877
+ await this.step([{ type: 'mouse', kind: 'up', ...where, ...extras }], 2 + settle, { action: 'click_release', args: where });
878
+ await this._settleStrip(strip ? strip.times : null);
879
+ return;
880
+ }
881
+ const event = { type: 'click', ...where, ...extras };
882
+ await this.step([event], 2 + settle, { action: 'click', args: { ...where, ...extras } });
883
+ return;
884
+ }
885
+ case 'drag': {
886
+ const plan = this._dragPlan(action);
887
+ const args = { from: action.from, to: action.to, steps: plan.path.length, duration_ms: plan.duration, ...(plan.button !== 'left' ? { button: plan.button } : {}) };
888
+ const press = { button: plan.button };
889
+ await this.step(
890
+ [{ type: 'mouse', kind: 'move', ...action.from }, { type: 'mouse', kind: 'down', ...action.from, ...press }],
891
+ plan.hold > 0 ? this._ticksFor(plan.hold) : 1,
892
+ { action: 'drag_press', args, digest: false },
893
+ );
894
+ const ticksPerMove = Math.max(1, Math.round(this._ticksFor(plan.duration) / plan.path.length));
895
+ for (const point of plan.path) {
896
+ await this.step([{ type: 'mouse', kind: 'move', ...point }], ticksPerMove, { action: 'drag_move', args: point, digest: false });
897
+ }
898
+ await this.step([{ type: 'mouse', kind: 'up', ...action.to, ...press }], 2 + settle, { action: 'drag_release', args });
899
+ this._lastDetail = `Dragged from (${action.from.x},${action.from.y}) to (${action.to.x},${action.to.y}) in ${plan.path.length} moves over ${Math.round(plan.duration)} ms of game time.`;
900
+ return;
901
+ }
902
+ case 'hover': {
903
+ await this.step([{ type: 'mouse', kind: 'move', ...action.target }], 2 + settle, { action: 'hover', args: action.target });
904
+ this._lastDetail = `The pointer rests at (${action.target.x},${action.target.y}).`;
905
+ return;
906
+ }
907
+ case 'scroll': {
908
+ const modifier = String(action.modifier || '').toLowerCase();
909
+ const held = { ...(/^(?:ctrl|control)$/.test(modifier) ? { ctrl: true } : {}), ...(modifier === 'shift' ? { shift: true } : {}), ...(/^(?:alt|option)$/.test(modifier) ? { alt: true } : {}) };
910
+ const notches = wheelNotches(action.dx, action.dy);
911
+ for (const [index, notch] of notches.entries()) {
912
+ await this.step([{ type: 'mouse', kind: 'wheel', ...action.target, dx: notch.dx, dy: notch.dy, ...held }], index === notches.length - 1 ? 2 + settle : 1, { action: 'scroll', args: { ...action.target, ...notch, ...held }, digest: index === notches.length - 1 });
913
+ }
914
+ this._lastDetail = `Turned the wheel ${notches.length} notch(es) with the pointer at (${action.target.x},${action.target.y}).`;
915
+ return;
916
+ }
917
+ case 'sequence': {
918
+ // Every press and release on the tick its time falls on: exact, and
919
+ // the same on a replay.
920
+ const byTick = new Map();
921
+ for (const event of sequenceEvents(action.steps)) {
922
+ const tick = Math.round((event.atMs / 1000) * this.ticksPerSecond);
923
+ if (!byTick.has(tick)) byTick.set(tick, []);
924
+ const stepOf = event.step;
925
+ if (stepOf.key) {
926
+ const parts = this._keysOf({ key: stepOf.key });
927
+ for (const part of event.down ? parts : [...parts].reverse()) byTick.get(tick).push({ type: 'key', keycode: part, pressed: event.down });
928
+ } else {
929
+ if (event.down) byTick.get(tick).push({ type: 'mouse', kind: 'move', x: stepOf.x, y: stepOf.y });
930
+ byTick.get(tick).push({ type: 'mouse', kind: event.down ? 'down' : 'up', x: stepOf.x, y: stepOf.y, button: stepOf.button });
931
+ }
932
+ }
933
+ const ticks = [...byTick.keys()].sort((a, b) => a - b);
934
+ // The strip's frames fall on ticks of the whole sequence; each step is
935
+ // handed the ones inside it.
936
+ const strip = this._stripTicks(Number(action.durationMs) || 0, MAX_STEP_TICKS * 8);
937
+ for (const [index, tick] of ticks.entries()) {
938
+ const last = index === ticks.length - 1;
939
+ const span = last ? Math.max(settle, 1) : Math.max(1, ticks[index + 1] - tick);
940
+ const due = strip ? strip.ticks.map((at) => at - tick).filter((at) => at >= 1 && at <= span) : null;
941
+ await this.step(byTick.get(tick), span, { action: 'sequence', args: { at_tick: tick }, digest: last, ...(strip ? { stripAt: due, stripNew: index === 0 } : {}) });
942
+ }
943
+ await this._settleStrip(strip ? strip.times : null);
944
+ this._lastDetail = `Played ${action.steps.length} timed input(s) over ${action.durationMs} ms of game time, each on the tick its time falls on (${this.ticksPerSecond} ticks a second).`;
626
945
  return;
627
946
  }
628
947
  case 'press_action': {
@@ -734,7 +1053,7 @@ export class GodotDriver {
734
1053
  this.exitSignal = signal;
735
1054
  if (log) log.end();
736
1055
  if (!this._stopped && this._recordingStartedAt != null) {
737
- this._endCapture(code === 0 ? 'game_exited' : 'game_crashed');
1056
+ this._endCaptureOnExit(code === 0 ? 'game_exited' : 'game_crashed');
738
1057
  void this._finalizeRecording().catch(() => {});
739
1058
  }
740
1059
  });
@@ -769,6 +1088,34 @@ export class GodotDriver {
769
1088
  }
770
1089
  }
771
1090
 
1091
+ /**
1092
+ * When the video's own clock began (its first frame), or null with no
1093
+ * recording: what a finding's video time is measured from.
1094
+ * @returns {number|null}
1095
+ */
1096
+ recordingStartedAt() {
1097
+ return this._frames.length > 0 ? this._frames[0].at : null;
1098
+ }
1099
+
1100
+ /**
1101
+ * How the game ended on its own, when it did: the process exited (a crash,
1102
+ * or the game quitting itself), or it stopped answering while still alive
1103
+ * (a freeze). Null while it runs, and after the runner stopped it.
1104
+ *
1105
+ * @param {Error} [error] what a call just failed with
1106
+ * @returns {{kind: 'crashed'|'frozen'|'exited', message: string, log?: string}|null}
1107
+ */
1108
+ gameEnded(error = null) {
1109
+ if (this._stopped) return null;
1110
+ const log = this._logTail.slice(-12).join('\n');
1111
+ if (this.exitCode !== null || this.exitSignal) {
1112
+ if (this.exitCode === 0) return { kind: 'exited', message: 'the game process ended on its own with exit code 0', log };
1113
+ return { kind: 'crashed', message: `the game process exited ${this.exitSignal ? `on signal ${this.exitSignal}` : `with code ${this.exitCode}`}`, log };
1114
+ }
1115
+ if (error && error.name === 'DriverTimeoutError') return { kind: 'frozen', message: `the game did not answer the runner (${error.message})`, log };
1116
+ return null;
1117
+ }
1118
+
772
1119
  async observe({ vision } = {}) {
773
1120
  this._step += 1;
774
1121
  const snapshot = await this._snapshot();
@@ -793,15 +1140,43 @@ export class GodotDriver {
793
1140
  ? Math.round((this.tick / this.ticksPerSecond) * 1000)
794
1141
  : (this._startedAt === null ? 0 : this._now() - this._startedAt),
795
1142
  });
796
- const wantVision = vision ?? needsVision(observation);
1143
+ // Frames taken while the last input played are shown with this look, so
1144
+ // it carries a picture whether or not the outline alone would need one.
1145
+ const strip = this._strip;
1146
+ this._strip = null;
1147
+ const wantVision = vision ?? (needsVision(observation) || Boolean(strip));
1148
+ let probe = null;
797
1149
  if (wantVision && !this.headless) {
798
- const shot = await this._rawScreenshot();
1150
+ const shot = await this._rawScreenshot(MODEL_FRAME, { strip: Boolean(strip) });
1151
+ if (shot && strip && shot.strip > 0) {
1152
+ const rowHeight = Math.round((shot.height * 0.25) / 1.25);
1153
+ observation.strip = { frames: shot.strip, times: strip.times.slice(0, shot.strip), ...stripTokens(shot.width, shot.height - rowHeight) };
1154
+ this._stripCount += 1;
1155
+ if (this.runDir) {
1156
+ // Kept beside the run, on this machine: what the persona was shown.
1157
+ const file = path.join(this.runDir, 'strips', `strip-${String(this._stripCount).padStart(2, '0')}-step-${this._step}.jpg`);
1158
+ await fs.mkdir(path.dirname(file), { recursive: true }).then(() => fs.writeFile(file, Buffer.from(shot.data, 'base64'))).catch(() => {});
1159
+ }
1160
+ }
799
1161
  if (shot) {
1162
+ const mediaType = shot.format === 'jpeg' ? MODEL_FRAME.mediaType : 'image/png';
800
1163
  // screenshotBase64 is the name the persona's tools read; the old
801
1164
  // screenshot_b64 is kept for anything that reads the observation raw.
802
- observation = { ...observation, screenshot_b64: shot.data, screenshotBase64: shot.data, screenshotMediaType: 'image/png' };
1165
+ observation = { ...observation, screenshot_b64: shot.data, screenshotBase64: shot.data, screenshotMediaType: mediaType };
1166
+ const scale = frameScaleNote(shot);
1167
+ if (scale) observation.text = `${scale}\n${observation.text}`;
1168
+ probe = await this._probe();
803
1169
  }
804
1170
  }
1171
+ // The same screen as the last one shown is sent as a marker (../tools.js):
1172
+ // the same text, and when the persona is playing from the picture, a
1173
+ // picture a player would call the same.
1174
+ const sameText = this._lastObservedHash !== null && this._lastObservedHash === observation.hash;
1175
+ const samePicture = !observation.screenshotBase64 || (probe !== null && this._lastProbe !== null && !significant(screenDelta(this._lastProbe, probe)));
1176
+ if (sameText && samePicture && !observation.strip && this._lastUsedVision === Boolean(observation.screenshotBase64)) observation.unchanged = true;
1177
+ this._lastObservedHash = observation.hash;
1178
+ this._lastUsedVision = Boolean(observation.screenshotBase64);
1179
+ this._lastProbe = probe;
805
1180
  // changed detection compares outline hashes only, never this observation's
806
1181
  // own hash: the observation text also carries the game state section, so
807
1182
  // comparing the two kinds of hash reported "changed" on every single act.
@@ -809,6 +1184,171 @@ export class GodotDriver {
809
1184
  return observation;
810
1185
  }
811
1186
 
1187
+ /**
1188
+ * The frame a model is shown for a saved screenshot: the same screen as
1189
+ * JPEG, or null when there is no viewport to read.
1190
+ *
1191
+ * @returns {Promise<{data: string, mediaType: string, note: string}|null>}
1192
+ */
1193
+ async modelFrame() {
1194
+ if (this.headless) return null;
1195
+ const shot = await this._rawScreenshot(MODEL_FRAME);
1196
+ if (!shot) return null;
1197
+ return { data: shot.data, mediaType: shot.format === 'jpeg' ? MODEL_FRAME.mediaType : 'image/png', note: frameScaleNote(shot) };
1198
+ }
1199
+
1200
+ /**
1201
+ * The screen as a small PNG, saved nowhere: what the runner compares to
1202
+ * tell a scene it has not seen before (../screenshots.js).
1203
+ *
1204
+ * @returns {Promise<Buffer|null>}
1205
+ */
1206
+ async screenProbe() {
1207
+ if (this.headless) return null;
1208
+ try {
1209
+ const shot = await this.rpc.call('screenshot', { max_width: PROBE_WIDTH });
1210
+ return shot && shot.data ? Buffer.from(shot.data, 'base64') : null;
1211
+ } catch (error) {
1212
+ if (error instanceof DriverRpcError) return null;
1213
+ throw error;
1214
+ }
1215
+ }
1216
+
1217
+ /** A small PNG of the screen as block averages, or null. Never fails a step. */
1218
+ async _probe() {
1219
+ if (this.headless) return null;
1220
+ try {
1221
+ const shot = await this.rpc.call('screenshot', { max_width: PROBE_WIDTH });
1222
+ return shot && shot.data ? pngFingerprint(Buffer.from(shot.data, 'base64')) : null;
1223
+ } catch (error) {
1224
+ if (error instanceof DriverRpcError) return null;
1225
+ throw error;
1226
+ }
1227
+ }
1228
+
1229
+ /**
1230
+ * Whether the screen changed since the last observation: the outline did,
1231
+ * or, on a screen the persona plays from a picture, the picture did by more
1232
+ * than a blinking cursor. A canvas drawn game keeps one outline while
1233
+ * everything a player sees moves.
1234
+ */
1235
+ async _changedSinceObserved() {
1236
+ const { hash } = await this._snapshot();
1237
+ let changed = this._lastHash !== null && hash !== this._lastHash;
1238
+ this._lastHash = hash;
1239
+ if (!changed && this._lastUsedVision && this._lastProbe) {
1240
+ const probe = await this._probe();
1241
+ if (probe && significant(screenDelta(this._lastProbe, probe))) changed = true;
1242
+ }
1243
+ return changed;
1244
+ }
1245
+
1246
+ /**
1247
+ * A click target as the addon takes it: a node path. A path from /root goes
1248
+ * through as it is. Anything else is looked up in the last outline: a node
1249
+ * name, a path ending, or the text a node shows. Text on a label inside a
1250
+ * card names the card, the nearest thing above it a player can press.
1251
+ *
1252
+ * @param {string} target
1253
+ * @returns {{path: string}|{error: string}}
1254
+ */
1255
+ _resolveTarget(target) {
1256
+ const wanted = String(target ?? '').trim().replace(/^["'`]+|["'`]+$/g, '').trim();
1257
+ if (!wanted) return { error: 'the click named no target; name a node from the outline, or pass x and y' };
1258
+ if (wanted.startsWith('/')) return { path: wanted };
1259
+ const nodes = [];
1260
+ const walk = (node, pressAncestor) => {
1261
+ if (!node) return;
1262
+ const press = PRESSABLE_TYPE.test(node.type ?? '') && !node.disabled ? node : pressAncestor;
1263
+ nodes.push({ node, press });
1264
+ for (const child of node.children ?? []) walk(child, press);
1265
+ };
1266
+ walk(this._lastTree, null);
1267
+ const lower = wanted.toLowerCase();
1268
+ const byName = nodes.filter(({ node }) => node.name === wanted || String(node.path ?? '').endsWith(`/${wanted}`));
1269
+ // What a node reads as: the text it shows, else the label its author gave it.
1270
+ const reads = node => (typeof node.text === 'string' && node.text ? node.text : typeof node.label === 'string' ? node.label : null);
1271
+ const exactText = nodes.filter(({ node }) => reads(node) !== null && reads(node).trim().toLowerCase() === lower);
1272
+ const partText = nodes.filter(({ node }) => reads(node) !== null && reads(node).toLowerCase().includes(lower));
1273
+ for (const [found, viaText] of [[byName, false], [exactText, true], [partText, true]]) {
1274
+ if (found.length === 0) continue;
1275
+ const paths = [...new Set(found.map(({ node, press }) => String((viaText && press ? press : node).path ?? '')).filter(Boolean))];
1276
+ if (paths.length === 1) return { path: paths[0] };
1277
+ if (paths.length > 1) {
1278
+ return { error: `"${wanted}" matches ${paths.length} nodes on this screen (${paths.slice(0, MAX_MATCHES_NAMED).join(', ')}${paths.length > MAX_MATCHES_NAMED ? ', ...' : ''}); name one by its path, or pass the x and y of its centre` };
1279
+ }
1280
+ }
1281
+ return { error: `nothing on this screen is named or reads "${wanted}"; a click target is a node path from the outline, a node name or its visible text, or the x and y of a centre` };
1282
+ }
1283
+
1284
+ /**
1285
+ * The single keys of a key action: every chord taken apart (Shift+Tab is
1286
+ * Shift and Tab, the modifier first), at most MAX_HELD_KEYS.
1287
+ */
1288
+ _keysOf(action) {
1289
+ const out = [];
1290
+ for (const key of [action.key, ...(Array.isArray(action.keys) ? action.keys : [])]) {
1291
+ if (typeof key !== 'string' || key === '') continue;
1292
+ const parts = key.length > 1 ? key.split(/\+(?=.)/) : [key];
1293
+ for (const part of parts) if (part !== '' && !out.includes(part)) out.push(part);
1294
+ }
1295
+ return out.slice(0, MAX_HELD_KEYS);
1296
+ }
1297
+
1298
+ /**
1299
+ * A point in the window for a pointer input: coordinates as given, or the
1300
+ * centre of a node named the way a click target is.
1301
+ *
1302
+ * @param {string|{x: number, y: number}|undefined} target
1303
+ * @returns {{x: number, y: number}|{error: string}}
1304
+ */
1305
+ _pointOf(target) {
1306
+ if (target && typeof target === 'object') return { x: Number(target.x) || 0, y: Number(target.y) || 0 };
1307
+ const resolved = this._resolveTarget(target);
1308
+ if (resolved.error) return { error: resolved.error };
1309
+ let found = null;
1310
+ const walk = (node) => {
1311
+ if (!node || found) return;
1312
+ if (node.path === resolved.path) { found = node; return; }
1313
+ for (const child of node.children ?? []) walk(child);
1314
+ };
1315
+ walk(this._lastTree);
1316
+ const centre = found && Array.isArray(found.center) && found.center.length === 2
1317
+ ? found.center.map(Number)
1318
+ : found && Array.isArray(found.rect) && found.rect.length === 4
1319
+ ? [Number(found.rect[0]) + Number(found.rect[2]) / 2, Number(found.rect[1]) + Number(found.rect[3]) / 2]
1320
+ : null;
1321
+ if (!centre || !centre.every(Number.isFinite)) return { error: `"${String(target)}" has no place on the screen the pointer can go to; pass the x and y of a centre the outline prints` };
1322
+ return { x: Math.round(centre[0]), y: Math.round(centre[1]) };
1323
+ }
1324
+
1325
+ /**
1326
+ * A pointer action with every named end turned into a point, or the error
1327
+ * that says which end could not be found (the runner's failure, never the game's).
1328
+ */
1329
+ _withPoints(action) {
1330
+ if (action.kind === 'drag' || action.kind === 'swipe') {
1331
+ const from = this._pointOf(action.from);
1332
+ const to = this._pointOf(action.to);
1333
+ if (from.error || to.error) return { error: from.error || to.error };
1334
+ return { action: { ...action, kind: 'drag', from, to } };
1335
+ }
1336
+ if (action.kind === 'hover' || (action.kind === 'scroll' && action.target !== undefined)) {
1337
+ const at = this._pointOf(action.target);
1338
+ if (at.error) return { error: at.error };
1339
+ return { action: { ...action, target: at } };
1340
+ }
1341
+ if (action.kind === 'scroll') return { action: { ...action, target: { x: Math.round(this.viewport.w / 2), y: Math.round(this.viewport.h / 2) } } };
1342
+ return { action };
1343
+ }
1344
+
1345
+ /** The moves of a drag, and how long each stays, from the action's own numbers. */
1346
+ _dragPlan(action) {
1347
+ const path_ = dragPath(action.from, action.to, { steps: action.steps, via: action.via || [] });
1348
+ const duration = Math.min(Math.max(Number(action.durationMs) || DEFAULT_DRAG_MS, 0), MAX_DRAG_MS);
1349
+ return { path: path_, duration, hold: Math.min(Math.max(Number(action.holdMs) || 0, 0), INPUT_MAX_HOLD_MS), button: mouseButton(action.button) };
1350
+ }
1351
+
812
1352
  async act(action) {
813
1353
  if (!action || typeof action.kind !== 'string') {
814
1354
  return { ok: false, error: 'action needs a kind', changed: false };
@@ -818,19 +1358,50 @@ export class GodotDriver {
818
1358
  if (action.kind === 'type' && (action.replace || action.target)) {
819
1359
  return { ok: false, error: 'replace (empty a field, then type) and a typing target are only available on playwright_web; this driver can only type more text into what has focus', changed: false };
820
1360
  }
1361
+ if (action.kind === 'click' && typeof action.target === 'string') {
1362
+ // The runner could not tell which node was meant: its own failure, said
1363
+ // as one (driverError), so nothing downstream reads it as a broken game.
1364
+ const resolved = this._resolveTarget(action.target);
1365
+ if (resolved.error) return { ok: false, error: resolved.error, changed: false, driverError: true };
1366
+ action = { ...action, target: resolved.path };
1367
+ }
1368
+ if (action.kind === 'select') {
1369
+ if (!this.addonAtLeast(1, 5)) {
1370
+ return { ok: false, error: 'the driver addon in this project is older than 1.5.0 and has no select: click the dropdown to open it and click the option, or drag a slider handle', changed: false, driverError: true, unsupported: { input: 'select', reason: 'the Ravensight driver addon in this project predates select (1.5.0); a dropdown is opened and picked with clicks, a slider is dragged' } };
1371
+ }
1372
+ const resolved = this._resolveTarget(action.target);
1373
+ if (resolved.error) return { ok: false, error: resolved.error.replace('a click target', 'a select target'), changed: false, driverError: true };
1374
+ action = { ...action, target: resolved.path };
1375
+ }
1376
+ if (['drag', 'swipe', 'hover', 'scroll'].includes(action.kind)) {
1377
+ if (this.headless) return { ok: false, error: 'headless Godot routes no mouse input; run windowed', changed: false, driverError: true };
1378
+ const pointed = this._withPoints(action);
1379
+ if (pointed.error) return { ok: false, error: pointed.error, changed: false, driverError: true };
1380
+ action = pointed.action;
1381
+ }
1382
+ this._lastDetail = null;
1383
+ this._stripFacts = null;
1384
+ this._stripMoved = false;
1385
+ this._strip = null;
1386
+ // What a refused select says: the game's own list of options is the answer.
1387
+ const refusedSelect = (error) => (action.kind === 'select' && error.code === -32602 ? { driverError: true } : {});
1388
+ const done = async () => ({
1389
+ ok: true,
1390
+ // A screen that ended as it began after moving in between did change.
1391
+ changed: (await this._changedSinceObserved()) || this._stripMoved,
1392
+ ...(this._lastDetail ? { detail: this._lastDetail } : {}),
1393
+ ...(this._stripFacts ? { strip: this._stripFacts } : {}),
1394
+ });
821
1395
  if (this.lockstep && action.kind !== 'quit' && action.kind !== 'set_time_scale') {
822
1396
  try {
823
1397
  await this._performLockstep(action);
824
1398
  } catch (error) {
825
1399
  if (error instanceof DriverRpcError) {
826
- return { ok: false, error: error.rpcMessage, code: error.code, data: error.data, changed: false };
1400
+ return { ok: false, error: error.rpcMessage, code: error.code, data: error.data, changed: false, ...(isTargetMiss(error) ? { driverError: true } : {}), ...refusedSelect(error) };
827
1401
  }
828
1402
  throw error;
829
1403
  }
830
- const { hash } = await this._snapshot();
831
- const changed = this._lastHash !== null && hash !== this._lastHash;
832
- this._lastHash = hash;
833
- return { ok: true, changed };
1404
+ return done();
834
1405
  }
835
1406
  const pausing = this.pauseBetweenActions && this._paused && action.kind !== 'quit' && action.kind !== 'set_time_scale';
836
1407
  try {
@@ -839,7 +1410,7 @@ export class GodotDriver {
839
1410
  await this._perform(action);
840
1411
  } catch (error) {
841
1412
  if (error instanceof DriverRpcError) {
842
- return { ok: false, error: error.rpcMessage, code: error.code, data: error.data, changed: false };
1413
+ return { ok: false, error: error.rpcMessage, code: error.code, data: error.data, changed: false, ...(isTargetMiss(error) ? { driverError: true } : {}), ...refusedSelect(error) };
843
1414
  }
844
1415
  throw error;
845
1416
  }
@@ -854,36 +1425,40 @@ export class GodotDriver {
854
1425
  } finally {
855
1426
  if (pausing && this.rpc && !this.rpc.closed) await this._freeze().catch(() => {});
856
1427
  }
857
- const { hash } = await this._snapshot();
858
- const changed = this._lastHash !== null && hash !== this._lastHash;
859
- this._lastHash = hash;
860
- return { ok: true, changed };
1428
+ return done();
861
1429
  }
862
1430
 
863
1431
  async _perform(action) {
864
1432
  switch (action.kind) {
1433
+ case 'select': {
1434
+ const answer = await this.rpc.call('select', { node_path: action.target, ...(action.option !== undefined ? { option: action.option } : {}), ...(action.value !== undefined ? { value: action.value } : {}) });
1435
+ await this.rpc.call('wait_frames', { n: 2 });
1436
+ this._lastDetail = selectDetail(answer);
1437
+ return;
1438
+ }
865
1439
  case 'key': {
866
1440
  // Every key goes down, the game runs for the hold, then every key that
867
1441
  // went down comes back up, in reverse order, even when a later press
868
1442
  // was refused: a key left held would steer the rest of the run.
869
- const keys = [action.key, ...(Array.isArray(action.keys) ? action.keys : [])]
870
- .filter((key) => typeof key === 'string' && key !== '')
871
- .slice(0, MAX_HELD_KEYS);
1443
+ const keys = this._keysOf(action);
872
1444
  const holdMs = holdWallMs(action.holdMs, this._resumeScale);
1445
+ const repeats = holdMs >= KEY_REPEAT_DELAY_MS;
873
1446
  const down = [];
1447
+ let stripTimesTaken = null;
874
1448
  try {
875
- for (const key of keys) {
876
- await this.rpc.call('key', { keycode: key, pressed: true });
1449
+ for (const [index, key] of keys.entries()) {
1450
+ await this.rpc.call('key', { keycode: key, pressed: true, ...(repeats && index === keys.length - 1 ? { repeat: true } : {}) });
877
1451
  down.push(key);
878
1452
  }
879
1453
  // A tap is one frame, as it always was; a hold is game time.
880
- if (holdMs > 0) await this._sleep(holdMs);
1454
+ if (holdMs > 0) stripTimesTaken = await this._sleepWithStrip(holdMs);
881
1455
  else await this.rpc.call('wait_frames', { n: 1 });
882
1456
  } finally {
883
1457
  for (const key of down.reverse()) {
884
1458
  await this.rpc.call('key', { keycode: key, pressed: false }).catch(() => {});
885
1459
  }
886
1460
  }
1461
+ await this._settleStrip(stripTimesTaken);
887
1462
  return;
888
1463
  }
889
1464
  case 'type':
@@ -899,19 +1474,92 @@ export class GodotDriver {
899
1474
  return;
900
1475
  case 'click': {
901
1476
  const target = action.target;
902
- if (typeof target === 'string') {
903
- await this.rpc.call('click', { node_path: target, button: action.button, double: action.double });
1477
+ const where = typeof target === 'string' ? { node_path: target } : { x: target?.x ?? 0, y: target?.y ?? 0 };
1478
+ const extras = { ...(action.button ? { button: action.button } : {}), ...(action.double ? { double: true } : {}) };
1479
+ const hold = Math.min(Math.max(Number(action.holdMs) || 0, 0), INPUT_MAX_HOLD_MS);
1480
+ if (hold > 0) {
1481
+ await this.rpc.call('mouse', { kind: 'move', ...where });
1482
+ await this.rpc.call('mouse', { kind: 'down', ...where, ...extras });
1483
+ try {
1484
+ await this._sleep(holdWallMs(hold, this._resumeScale));
1485
+ } finally {
1486
+ await this.rpc.call('mouse', { kind: 'up', ...where, ...extras }).catch(() => {});
1487
+ }
904
1488
  } else {
905
- await this.rpc.call('click', {
906
- x: target?.x ?? 0,
907
- y: target?.y ?? 0,
908
- button: action.button,
909
- double: action.double,
910
- });
1489
+ await this.rpc.call('click', { ...where, ...extras });
911
1490
  }
912
1491
  await this.rpc.call('wait_frames', { n: 2 });
913
1492
  return;
914
1493
  }
1494
+ case 'drag': {
1495
+ const plan = this._dragPlan(action);
1496
+ const press = { button: plan.button };
1497
+ await this.rpc.call('mouse', { kind: 'move', ...action.from });
1498
+ await this.rpc.call('mouse', { kind: 'down', ...action.from, ...press });
1499
+ try {
1500
+ if (plan.hold > 0) await this._sleep(holdWallMs(plan.hold, this._resumeScale));
1501
+ const pause = holdWallMs(plan.duration, this._resumeScale) / plan.path.length;
1502
+ for (const point of plan.path) {
1503
+ await this.rpc.call('mouse', { kind: 'move', ...point });
1504
+ await this._sleep(pause);
1505
+ }
1506
+ } finally {
1507
+ await this.rpc.call('mouse', { kind: 'up', ...action.to, ...press }).catch(() => {});
1508
+ }
1509
+ await this.rpc.call('wait_frames', { n: 2 });
1510
+ this._lastDetail = `Dragged from (${action.from.x},${action.from.y}) to (${action.to.x},${action.to.y}) in ${plan.path.length} moves over ${Math.round(plan.duration)} ms.`;
1511
+ return;
1512
+ }
1513
+ case 'hover':
1514
+ await this.rpc.call('mouse', { kind: 'move', ...action.target });
1515
+ await this.rpc.call('wait_frames', { n: 2 });
1516
+ this._lastDetail = `The pointer rests at (${action.target.x},${action.target.y}).`;
1517
+ return;
1518
+ case 'scroll': {
1519
+ const modifier = String(action.modifier || '').toLowerCase();
1520
+ const held = { ...(/^(?:ctrl|control)$/.test(modifier) ? { ctrl: true } : {}), ...(modifier === 'shift' ? { shift: true } : {}), ...(/^(?:alt|option)$/.test(modifier) ? { alt: true } : {}) };
1521
+ const notches = wheelNotches(action.dx, action.dy);
1522
+ for (const notch of notches) await this.rpc.call('mouse', { kind: 'wheel', ...action.target, dx: notch.dx, dy: notch.dy, ...held });
1523
+ await this.rpc.call('wait_frames', { n: 2 });
1524
+ this._lastDetail = `Turned the wheel ${notches.length} notch(es) with the pointer at (${action.target.x},${action.target.y}).`;
1525
+ return;
1526
+ }
1527
+ case 'sequence': {
1528
+ // On the runner's clock, as the web driver plays it; lockstep is the
1529
+ // exact one.
1530
+ const keysDown = [];
1531
+ const buttonsDown = [];
1532
+ const started = this._now();
1533
+ let worst = 0;
1534
+ try {
1535
+ for (const event of sequenceEvents(action.steps)) {
1536
+ const due = started + holdWallMs(event.atMs, this._resumeScale);
1537
+ if (due > this._now()) await this._sleep(due - this._now());
1538
+ worst = Math.max(worst, this._now() - due);
1539
+ const stepOf = event.step;
1540
+ if (stepOf.key) {
1541
+ const parts = this._keysOf({ key: stepOf.key });
1542
+ for (const part of event.down ? parts : [...parts].reverse()) {
1543
+ await this.rpc.call('key', { keycode: part, pressed: event.down });
1544
+ if (event.down) keysDown.push(part); else keysDown.splice(keysDown.lastIndexOf(part), 1);
1545
+ }
1546
+ } else if (event.down) {
1547
+ await this.rpc.call('mouse', { kind: 'move', x: stepOf.x, y: stepOf.y });
1548
+ await this.rpc.call('mouse', { kind: 'down', x: stepOf.x, y: stepOf.y, button: stepOf.button });
1549
+ buttonsDown.push(stepOf);
1550
+ } else {
1551
+ await this.rpc.call('mouse', { kind: 'up', x: stepOf.x, y: stepOf.y, button: stepOf.button });
1552
+ buttonsDown.splice(buttonsDown.indexOf(stepOf), 1);
1553
+ }
1554
+ }
1555
+ } finally {
1556
+ for (const key of keysDown.reverse()) await this.rpc.call('key', { keycode: key, pressed: false }).catch(() => {});
1557
+ for (const held of buttonsDown.reverse()) await this.rpc.call('mouse', { kind: 'up', x: held.x, y: held.y, button: held.button }).catch(() => {});
1558
+ }
1559
+ await this.rpc.call('wait_frames', { n: 2 });
1560
+ this._lastDetail = `Played ${action.steps.length} timed input(s) while the game ran; the latest landed ${Math.round(worst)} ms after its time.`;
1561
+ return;
1562
+ }
915
1563
  case 'press_action':
916
1564
  await this.rpc.call(
917
1565
  'press_action',
@@ -947,15 +1595,49 @@ export class GodotDriver {
947
1595
  */
948
1596
  async _snapshot() {
949
1597
  const state = await this.rpc.call('get_state', { max_depth: this.treeDepth, visible_only: true });
1598
+ await this._expandCuts(state);
950
1599
  const outline = buildObservation({ state, step: this._step });
1600
+ this._lastTree = state?.tree ?? null;
951
1601
  return { state, hash: outline.hash };
952
1602
  }
953
1603
 
954
- async _rawScreenshot() {
1604
+ /**
1605
+ * Read the subtrees the depth cut left out, in place. Best effort: a node
1606
+ * that went away between the two reads keeps its `+N more`.
1607
+ */
1608
+ async _expandCuts(state) {
1609
+ const cut = [];
1610
+ const collect = (node) => {
1611
+ if (!node || cut.length >= MAX_CUT_EXPANSIONS) return;
1612
+ if (Number(node.child_count) > 0 && (node.children ?? []).length === 0 && node.path) cut.push(node);
1613
+ for (const child of node.children ?? []) collect(child);
1614
+ };
1615
+ collect(state?.tree);
1616
+ for (const node of cut) {
1617
+ try {
1618
+ const below = await this.rpc.call('get_state', { root: node.path, max_depth: CUT_EXPANSION_DEPTH, visible_only: true });
1619
+ if (below?.tree && Array.isArray(below.tree.children)) {
1620
+ node.children = below.tree.children;
1621
+ delete node.child_count;
1622
+ if (below.truncated) state.truncated = true;
1623
+ }
1624
+ } catch (error) {
1625
+ if (!(error instanceof DriverRpcError)) throw error;
1626
+ }
1627
+ }
1628
+ }
1629
+
1630
+ /**
1631
+ * @param {{format?: string, quality?: number}} [frame] leave out for the PNG
1632
+ * evidence is saved as
1633
+ */
1634
+ async _rawScreenshot(frame = null, { quiet = false, strip = false } = {}) {
955
1635
  if (this.headless) return null;
1636
+ const params = { max_width: this.viewport.w, ...(frame ? { format: frame.format, quality: frame.quality } : {}), ...(strip ? { strip: true } : {}) };
956
1637
  try {
957
- return await this.rpc.call('screenshot', { max_width: this.viewport.w });
1638
+ return await this.rpc.call('screenshot', params);
958
1639
  } catch (error) {
1640
+ if (error instanceof DriverRpcError && quiet) return null;
959
1641
  if (error instanceof DriverRpcError) {
960
1642
  this._consoleQueue.push({ kind: 'driver', text: `screenshot: ${error.rpcMessage}` });
961
1643
  return null;
@@ -1002,6 +1684,28 @@ export class GodotDriver {
1002
1684
 
1003
1685
  // Capture only this project's viewport. No screen/audio device is opened.
1004
1686
  async _startFrameCapture() {
1687
+ // A default recording that cannot be made here is skipped without a
1688
+ // word to the persona: the run summary says why there is no video.
1689
+ if (this._recordAuto) {
1690
+ if (this.headless || !this.runDir) { this.recordingSkipped = this.headless ? 'a headless game has no picture to record' : 'there is no run directory to record into'; return; }
1691
+ const encoder = await this._detectEncoder();
1692
+ if (!encoder?.path) { this.recordingSkipped = 'ffmpeg is not installed (install it, or set RAVENSIGHT_FFMPEG, to get a video of Godot runs)'; return; }
1693
+ try {
1694
+ this._framesDir = await recordingDirectory(this.runDir);
1695
+ } catch (error) {
1696
+ this.recordingSkipped = String(error && error.message);
1697
+ return;
1698
+ }
1699
+ this._encoder = encoder;
1700
+ this._recordingStartedAt = this._now();
1701
+ await this._captureFrame();
1702
+ if (this._captureEndedAt != null) return;
1703
+ this._videoTimer = setInterval(() => { void this._captureFrame(); }, Math.round(1000 / this._recordingLimits.fps));
1704
+ this._videoTimer.unref?.();
1705
+ this._videoDeadline = setTimeout(() => this._endCapture('duration_limit'), this._recordingLimits.durationMs);
1706
+ this._videoDeadline.unref?.();
1707
+ return;
1708
+ }
1005
1709
  this._recordingStartedAt = this._now();
1006
1710
  if (this.runDir) this._framesDir = await recordingDirectory(this.runDir);
1007
1711
  if (this.headless || !this.runDir) {
@@ -1032,6 +1736,13 @@ export class GodotDriver {
1032
1736
  this._videoTimer = null;
1033
1737
  }
1034
1738
 
1739
+ _endCaptureOnExit(reason) {
1740
+ if (this._captureReason === 'capture_failed' && this._now() - this._captureEndedAt <= EXIT_ATTRIBUTION_MS) {
1741
+ this._captureReason = reason;
1742
+ }
1743
+ this._endCapture(reason);
1744
+ }
1745
+
1035
1746
  async _captureFrame() {
1036
1747
  if (this._capturePromise || this._stopped || this._captureEndedAt != null) return;
1037
1748
  if (this._now() - this._recordingStartedAt >= this._recordingLimits.durationMs) {
@@ -1040,7 +1751,9 @@ export class GodotDriver {
1040
1751
  const at = this._now();
1041
1752
  this._capturePromise = (async () => {
1042
1753
  try {
1043
- const shot = await this._rawScreenshot();
1754
+ // JPEG frames: a tenth of a PNG's bytes, so the frame budget covers a
1755
+ // whole run and not its first minute.
1756
+ const shot = await this._rawScreenshot(VIDEO_FRAME, { quiet: true });
1044
1757
  if (!shot) return;
1045
1758
  const max = this._recordingLimits.singleFrameBytes;
1046
1759
  if (typeof shot.data !== 'string' || shot.data.length > Math.ceil(max / 3) * 4) {
@@ -1050,7 +1763,13 @@ export class GodotDriver {
1050
1763
  if (bytes.length > max || this._frameBytes + bytes.length > this._recordingLimits.frameBytes) {
1051
1764
  this._endCapture('frame_bytes_limit'); return;
1052
1765
  }
1053
- const name = `${String(this._frameIndex + 1).padStart(6, '0')}.png`;
1766
+ // The game stands still while a persona thinks: a frame the same as
1767
+ // the last one is not written again, and the last one is held on
1768
+ // screen until the next that differs.
1769
+ const digest = createHash('sha1').update(bytes).digest('hex');
1770
+ if (digest === this._lastFrameDigest) return;
1771
+ this._lastFrameDigest = digest;
1772
+ const name = `${String(this._frameIndex + 1).padStart(6, '0')}.${shot.format === 'jpeg' ? 'jpg' : 'png'}`;
1054
1773
  await fs.writeFile(path.join(this._framesDir, name), bytes, { flag: 'wx', mode: 0o600 });
1055
1774
  this._frames.push({ name, at });
1056
1775
  this._frameIndex += 1;
@@ -1107,7 +1826,10 @@ export class GodotDriver {
1107
1826
  this._stopped = true;
1108
1827
  this._signal?.removeEventListener('abort', this._onAbort);
1109
1828
  await this.trace?.end({ tick: this.tick, reason, deaths: this.deaths, errors: this.errorCount }).catch(() => {});
1110
- if (this._recordingStartedAt != null) this._endCapture(reason);
1829
+ if (this._recordingStartedAt != null) {
1830
+ if (reason === 'game_crashed' || reason === 'game_exited') this._endCaptureOnExit(reason);
1831
+ else this._endCapture(reason);
1832
+ }
1111
1833
  await this._capturePromise;
1112
1834
  if (this.rpc && !this.rpc.closed) {
1113
1835
  await this.rpc.call('quit', { code: 0 }, { timeoutMs: 2000 }).catch(() => {});
@@ -1127,6 +1849,7 @@ export class GodotDriver {
1127
1849
  this._untrack = null;
1128
1850
  return {
1129
1851
  videoPath: null, ...await this._finalizeRecording(),
1852
+ ...(this.recordingSkipped ? { recordingSkipped: this.recordingSkipped } : {}),
1130
1853
  frameCount: this._frameIndex, chapters: this.chapters,
1131
1854
  logPath: this.logPath, exitCode: this.exitCode,
1132
1855
  };