ravensight-playtest 0.13.2 → 0.16.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 (40) hide show
  1. package/README.md +99 -4
  2. package/addons/ravensight_driver/driver.gd +472 -28
  3. package/docs/godot-driver.md +66 -2
  4. package/package.json +7 -5
  5. package/src/api/README.md +8 -1
  6. package/src/api/client.js +24 -1
  7. package/src/cli.js +14 -0
  8. package/src/commands/check.js +5 -2
  9. package/src/commands/fix.js +1 -1
  10. package/src/commands/run.js +26 -4
  11. package/src/commands/setup.js +176 -0
  12. package/src/packs/index.js +37 -5
  13. package/src/packs/keys.json +11 -0
  14. package/src/packs/pack-signing-hashes.json +7 -0
  15. package/src/packs/pack-signing-vectors.json +119 -0
  16. package/src/packs/signature.js +186 -0
  17. package/src/run/anygame/gamenotes.js +74 -12
  18. package/src/run/anygame/index.js +97 -34
  19. package/src/run/anygame/language.js +100 -10
  20. package/src/run/anygame/memory.js +70 -13
  21. package/src/run/anygame/shared-hashes.json +7 -7
  22. package/src/run/anygame/sound.js +59 -16
  23. package/src/run/args.js +2 -0
  24. package/src/run/claimwords.js +43 -7
  25. package/src/run/drivers/godot-cursor.js +96 -0
  26. package/src/run/drivers/godot-observation.js +29 -5
  27. package/src/run/drivers/godot.js +60 -5
  28. package/src/run/drivers/web.js +124 -14
  29. package/src/run/eventclaims.js +102 -6
  30. package/src/run/events.js +64 -6
  31. package/src/run/gameMemory.js +14 -5
  32. package/src/run/honesty.js +49 -2
  33. package/src/run/judge.js +22 -10
  34. package/src/run/liveFeed.js +254 -0
  35. package/src/run/personaLoop.js +103 -25
  36. package/src/run/pixels.js +491 -2
  37. package/src/run/replay.js +11 -0
  38. package/src/run/sdkSession.js +279 -16
  39. package/src/run/synthetic.js +12 -8
  40. package/src/run/tools.js +2 -2
@@ -515,8 +515,37 @@ export const EVIDENCE_HEADING = '## Where to look (added by the runner)';
515
515
  * @param {Map<string, Object>} [context.anchors] the runner's own findings, by id
516
516
  * @returns {{report: Object, index: Array<{id: string, action: number|null, screenshot: string|null, video: string|null}>}}
517
517
  */
518
+ /**
519
+ * Every finding with its own id. A report that repeats an id (the model wrote
520
+ * two F001s) keeps the first and gives each repeat the next free id after the
521
+ * report's highest (`F007`, in the schema's F and three digits form), so every
522
+ * consumer that looks a finding up by id, first match or last, reaches the
523
+ * same one. Run once, as soon as the report is settled; running it again
524
+ * changes nothing.
525
+ */
526
+ export function uniqueFindingIds(report) {
527
+ if (!report || !Array.isArray(report.findings)) return report;
528
+ const taken = new Set(report.findings.map(finding => finding && typeof finding === 'object' ? finding.id : undefined).filter(id => id !== undefined && id !== null && id !== ''));
529
+ const seen = new Set();
530
+ let changed = false;
531
+ const findings = report.findings.map(finding => {
532
+ if (!finding || typeof finding !== 'object' || finding.id === undefined || finding.id === null || finding.id === '') return finding;
533
+ if (!seen.has(finding.id)) { seen.add(finding.id); return finding; }
534
+ let n = Math.max(0, ...[...taken].map(id => Number((String(id).match(/^F(\d+)$/) || [])[1]) || 0)) + 1;
535
+ while (taken.has(`F${String(n).padStart(3, '0')}`)) n += 1;
536
+ const id = `F${String(n).padStart(3, '0')}`;
537
+ taken.add(id);
538
+ seen.add(id);
539
+ changed = true;
540
+ return { ...finding, id };
541
+ });
542
+ return changed ? { ...report, findings } : report;
543
+ }
544
+
518
545
  export function attachWhereToLook(report, { observations = [], notes = [], screenshots = [], video = null, anchors = new Map(), bindings = new Map() } = {}) {
519
546
  if (!report || !Array.isArray(report.findings)) return { report, index: [] };
547
+ // One finding per id, so the index has one entry per id and a binding one owner.
548
+ report = uniqueFindingIds(report);
520
549
  const byIndex = new Map(observations.map(entry => [entry.index, entry]));
521
550
  const every = (screenshots || []).filter(shot => shot && typeof shot.relativePath === 'string' && shot.relativePath);
522
551
  const shotByPath = new Map(every.map(shot => [String(shot.relativePath).replace(/\\/g, '/'), shot]));
@@ -525,11 +554,29 @@ export function attachWhereToLook(report, { observations = [], notes = [], scree
525
554
  // it, never for something the persona saw.
526
555
  const shots = every.filter(shot => !shot.edge && !shot.derived);
527
556
  const index = [];
557
+ const unbound = new Map(bindings);
528
558
  const findings = report.findings.map(finding => {
529
559
  if (!finding || typeof finding !== 'object') return finding;
530
560
  // Later report formatting may append evidence; it cannot redefine the
531
561
  // provenance of the picture already sent to the claim check.
532
- if (bindings.has(finding.id)) { index.push(bindings.get(finding.id)); return finding; }
562
+ // The step and the video time it was placed at still land in its evidence,
563
+ // said once; a time the finding cites itself stands.
564
+ // Each binding is used once: a later finding that repeats an id is placed
565
+ // on its own evidence and inherits nothing from the first.
566
+ if (unbound.has(finding.id)) {
567
+ const bound = unbound.get(finding.id);
568
+ unbound.delete(finding.id);
569
+ index.push(bound);
570
+ const original = Array.isArray(finding.evidence) ? finding.evidence : null;
571
+ const kept = original ? [...original] : [];
572
+ const has = (type, test) => kept.some(item => item && item.type === type && test(String(item.ref)));
573
+ if (Number.isInteger(bound.action) && !has('transcript_step', ref => new RegExp(`^\\s*action\\s*#?\\s*${bound.action}\\s*$`, 'i').test(ref))) {
574
+ kept.push({ type: 'transcript_step', ref: `action ${bound.action}` });
575
+ }
576
+ if (typeof bound.video === 'string' && bound.video && !has('video_ts', () => true)) kept.push({ type: 'video_ts', ref: bound.video });
577
+ // Evidence that was not a list is always replaced by the list.
578
+ return original && kept.length === original.length ? finding : { ...finding, evidence: kept };
579
+ }
533
580
  const evidence = Array.isArray(finding.evidence) ? [...finding.evidence] : [];
534
581
  let at = null;
535
582
  let action = null;
@@ -704,5 +751,5 @@ export function playOnText(actions, maxActions) {
704
751
 
705
752
  export default {
706
753
  createCapabilityLedger, capabilityLines, writeCapabilitySection, capabilityPrompt, flatShare, isBlankScreen, createBlankWatch,
707
- describeInput, stepsBefore, runnerFinding, addRunnerFindings, runnerFindingsMarkdown, dialogNote, videoTime, attachWhereToLook, whereToLookMarkdown, playOnText
754
+ describeInput, stepsBefore, runnerFinding, addRunnerFindings, runnerFindingsMarkdown, dialogNote, videoTime, attachWhereToLook, uniqueFindingIds, whereToLookMarkdown, playOnText
708
755
  };
package/src/run/judge.js CHANGED
@@ -36,7 +36,8 @@
36
36
  // as an ended-empty or thin run, and never charged for a falsehood. Local money follows the honesty bar exactly
37
37
  // as hosted money does. With the switch off, both would be kept as `opinion` impressions instead.
38
38
  import { claimClass, claimBasis, checkSaid, praiseClaim } from './claimwords.js';
39
- import { eventsVerdict, eventsConfirmed, contradictedReason } from './eventclaims.js';
39
+ // A report written in another language: its claims are sorted by their fixed fields, never by English words (./claimwords.js readsEnglish).
40
+ import { eventsVerdict, eventsConfirmed, contradictedReason, eventsDecided } from './eventclaims.js';
40
41
  import { STILL_MIN_GAME_MS } from './stillWatch.js';
41
42
 
42
43
  /** Turn away unsettled taste and own-play difficulty, as the hosted judge does. See MONEY above: the owner's call. */
@@ -54,10 +55,11 @@ const text = x => String(x ?? '').replace(/[\u2013\u2014]/g, ',').replace(/\s+/g
54
55
  * `plain` for taste, and null when no check is asked (praise, difficulty).
55
56
  *
56
57
  * @param {{title?: string, description?: string, severity?: string, category?: string}} finding
57
- * @param {{marked?: boolean}} [opts] marked: the picture the playtester judged from carried the runner's marks and grid
58
+ * @param {{marked?: boolean, english?: boolean}} [opts] marked: the picture the playtester judged from carried the runner's marks and grid;
59
+ * english: the report is written in English, so its words are read (false: praise, stuck, absence and layout are not told by words)
58
60
  */
59
- export function claimShape(finding, { marked = false } = {}) {
60
- const claim = { title: finding?.title || '', detail: finding?.description || '', severity: finding?.severity || null, category: finding?.category || null, marked };
61
+ export function claimShape(finding, { marked = false, english = true } = {}) {
62
+ const claim = { title: finding?.title || '', detail: finding?.description || '', severity: finding?.severity || null, category: finding?.category || null, marked, english };
61
63
  // Praise filed as a problem is the playtester's liking; a blocker or a major is never read as praise, so its grade stands.
62
64
  if (claim.severity === 'praise' || (!['blocker', 'major'].includes(claim.severity) && praiseClaim(claim))) return { cls: 'praise', basis: null, question: null };
63
65
  const cls = claimClass(claim);
@@ -97,8 +99,8 @@ const designedWords = check => {
97
99
  * @param {{measured: Object|null, replay: Object|null}|null} [opts.still] for a claim that nothing happens: what the run measured of its input (./stillWatch.js noEffectTries) and the replay that watched it (./reportChecks.js replayWebFindings)
98
100
  * @returns {{route: string, outcome: string|null, reason: string|null, cls: string, basis: string|null, impression?: {kind: string, check: string|null, note: string}, evidence?: string, events?: Array}}
99
101
  */
100
- export function judgeIssue(finding, { check = null, run = null, step = null, marked = false, turnAwayUnsettled = TURN_AWAY_UNSETTLED, still = null } = {}) {
101
- const { cls, basis } = claimShape(finding, { marked });
102
+ export function judgeIssue(finding, { check = null, run = null, step = null, marked = false, turnAwayUnsettled = TURN_AWAY_UNSETTLED, still = null, english = true } = {}) {
103
+ const { cls, basis } = claimShape(finding, { marked, english });
102
104
  const base = { cls, basis };
103
105
  const finding_ = extra => ({ ...base, route: 'finding', outcome: null, reason: null, ...extra });
104
106
  const away = (outcome, reason, extra = {}) => ({ ...base, route: 'turned_away', outcome, reason: text(reason), ...extra });
@@ -113,7 +115,11 @@ export function judgeIssue(finding, { check = null, run = null, step = null, mar
113
115
  return impression('opinion', saidOf === null ? 'not_made' : saidOf === 'not_contradicted' ? 'not_contradicted' : 'cannot_tell', { ownPlay: true });
114
116
  }
115
117
  const claim = { title: finding?.title || '', step: Number.isSafeInteger(step) ? step : null };
116
- const ev = run ? eventsVerdict(run, claim) : null;
118
+ // The game's own events are matched in every language (step, phase, the numbers they carry). In another language they may only turn a
119
+ // claim away: a confirmation rests on the claim's English words, so it is dropped here and from the verdicts the report reads.
120
+ const ev0 = run ? eventsVerdict(run, claim) : null;
121
+ const ev = english || ev0?.verdict === 'contradicted' ? ev0 : null;
122
+ if (ev0 && !ev) eventsDecided(run).delete(claim.title);
117
123
  if (ev?.verdict === 'contradicted') return away('contradicted', contradictedReason(ev), { evidence: 'events', events: ev.events });
118
124
 
119
125
  const said = checkSaid(check);
@@ -133,11 +139,17 @@ export function judgeIssue(finding, { check = null, run = null, step = null, mar
133
139
  if (cls === 'stuck') {
134
140
  if (said === 'opposite') return away('contradicted', 'the frame at its moment contradicts it');
135
141
  if (designed) return designed;
142
+ // In another language `stuck` is the class a claim gets when nothing settles which it is (./claimwords.js claimClass): it needs the
143
+ // watch, and its frame at fault too, so neither one answer of the frame nor the watch alone publishes it.
144
+ if (!english && (!still || !still.measured)) return away('unconfirmed', 'it is written in a language whose claims the runner does not sort by their words, so it may be a claim that nothing happens, which one frame cannot show, and no watch of the screen while game time ran confirmed it');
136
145
  if (!still || !still.measured) return away('unconfirmed', 'a claim that nothing happens is confirmed only by watching the screen while game time runs with no input, and the run did not press the same control again and again with nothing changing; one still frame cannot settle it');
137
146
  // The hosted gate's stuck rule, word for word: reproduced counts only from a watch, since the same screen following the same input says nothing about stillness.
138
147
  const replay = still.replay || null;
139
148
  const detail = replay && replay.detail ? ` (${text(replay.detail)})` : '';
140
- if (replay?.state === 'reproduced' && Number(replay.watched_ms) >= STILL_MIN_GAME_MS) return finding_({ evidence: 'still_watch' });
149
+ if (replay?.state === 'reproduced' && Number(replay.watched_ms) >= STILL_MIN_GAME_MS) {
150
+ if (english || said === 'at_fault') return finding_({ evidence: 'still_watch' });
151
+ return away('unconfirmed', `it is written in a language whose claims the runner does not sort by their words, so it is held to both a watch and its frame; the watch saw the screen still, and ${made ? 'its frame did not show the game at fault' : unasked}`);
152
+ }
141
153
  if (replay?.state === 'reproduced') return away('unconfirmed', 'the replay reached the same screen but did not watch it while game time ran, so it could not test a claim that nothing happens');
142
154
  if (replay?.state === 'not_reproduced') return away('not_reproduced', `it did not come back when the recorded inputs were played again${detail}`);
143
155
  return away('unconfirmed', `a claim that nothing happens is confirmed only by watching the screen while game time runs for ${STILL_MIN_GAME_MS / 1000} seconds with no input, and that could not be done${detail}; one still frame cannot settle it`);
@@ -177,8 +189,8 @@ export function judgeIssue(finding, { check = null, run = null, step = null, mar
177
189
  * A claim the picture contradicts is turned away; a claim of fact stands when the picture shows it (as designed or at
178
190
  * fault included) and is turned away otherwise; anything else stands.
179
191
  */
180
- export function legacyIssue(finding, { check = null, marked = false } = {}) {
181
- const { cls, basis, question } = claimShape(finding, { marked });
192
+ export function legacyIssue(finding, { check = null, marked = false, english = true } = {}) {
193
+ const { cls, basis, question } = claimShape(finding, { marked, english });
182
194
  const said = checkSaid(check);
183
195
  const base = { cls, basis };
184
196
  if (said === 'opposite') return { ...base, route: 'turned_away', outcome: 'contradicted', reason: 'the frame at its moment contradicts it' };
@@ -0,0 +1,254 @@
1
+ /**
2
+ * The job's live view in the dashboard, fed while a local persona run plays.
3
+ *
4
+ * The play loop hands each played input here; this posts the newest steps to
5
+ * `POST .../runs/:runId/live` every few seconds and, only while the server
6
+ * says someone is watching, one small JPEG of the latest changed screen. It is
7
+ * the same body the cloud runner sends, read by the same live view.
8
+ *
9
+ * Nothing here can slow or fail the run: `step()` returns at once and never
10
+ * throws, one post is in flight at a time, a post is never retried and has an
11
+ * 8 second limit, a failed post is dropped, and the feed gives up quietly for
12
+ * the rest of the run after a refusal that will not change (401, 403, 404,
13
+ * 409) or five failures in a row. It writes nothing in the run folder: a frame
14
+ * is made in a temporary folder of its own. The run's upload stays the record.
15
+ * Live posts are free; nothing here touches money.
16
+ */
17
+ import { execFile } from 'node:child_process';
18
+ import { mkdtemp, readFile, rm, writeFile, access } from 'node:fs/promises';
19
+ import os from 'node:os';
20
+ import path from 'node:path';
21
+ import { redactText } from './redaction.js';
22
+ import { scanForSecrets } from './secretScan.js';
23
+
24
+ export const LIVE_INTERVAL_MS = 5000;
25
+ export const LIVE_MIN_INTERVAL_MS = 2000;
26
+ export const LIVE_MAX_INTERVAL_MS = 30000;
27
+ export const LIVE_MAX_STEPS = 10;
28
+ export const LIVE_MAX_FRAME_BYTES = 64 * 1024;
29
+ export const LIVE_MAX_SIDE = 640;
30
+ export const LIVE_WIDTH = 480;
31
+ export const LIVE_TIMEOUT_MS = 8000;
32
+ export const LIVE_MAX_FAILURES = 5;
33
+ // Shared by every run this process plays at once, so the live view never takes
34
+ // the request budget the runs' own heartbeats and uploads need.
35
+ export const LIVE_BUDGET = Object.freeze({ posts: 120, windowMs: 15 * 60 * 1000 });
36
+ const FINAL = new Set([401, 403, 404, 409]);
37
+ const TEXT = { label: 100, intent: 240, screen: 60 };
38
+
39
+ /**
40
+ * Whether this run feeds the live view: on when the run uploads, off with
41
+ * --no-live, --dry-upload, or a step log kept on this machine (the live steps
42
+ * are the step log's own content).
43
+ * @returns {{on: boolean, reason: 'flag'|'dry_upload'|'step_log'|null}}
44
+ */
45
+ export function liveDecision(options = {}) {
46
+ if (options.noLive === true) return { on: false, reason: 'flag' };
47
+ if (options.dryUpload === true) return { on: false, reason: 'dry_upload' };
48
+ if (options.uploadTranscript === false || options.noUploadStepLog === true) return { on: false, reason: 'step_log' };
49
+ return { on: true, reason: null };
50
+ }
51
+
52
+ /** The one line a run prints about the live view. */
53
+ export function liveLine(decision) {
54
+ if (decision.on) return 'While it plays, the job\'s page shows the recent steps, and a small picture of the screen while someone watches (Watch live). It costs nothing; --no-live turns it off.';
55
+ const why = { flag: '--no-live', dry_upload: '--dry-upload', step_log: 'the step log is kept local' }[decision.reason] || 'it is off';
56
+ return `The job's page will not show this run live (${why}).`;
57
+ }
58
+
59
+ /** A sliding window of posts, shared by the feeds of one process. */
60
+ export function createPostBudget({ posts = LIVE_BUDGET.posts, windowMs = LIVE_BUDGET.windowMs, now = Date.now } = {}) {
61
+ let sent = [];
62
+ return {
63
+ take() {
64
+ const at = now();
65
+ sent = sent.filter(t => at - t < windowMs);
66
+ if (sent.length >= posts) return false;
67
+ sent.push(at);
68
+ return true;
69
+ }
70
+ };
71
+ }
72
+ const processBudget = createPostBudget();
73
+
74
+ function clip(value, max) {
75
+ if (typeof value !== 'string') return '';
76
+ const cut = redactText(value).replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, max);
77
+ return cut && scanForSecrets(cut).length ? '' : cut;
78
+ }
79
+
80
+ /** The few fields of a played step the studio sees, trimmed and redacted. */
81
+ export function liveStep(step = {}, startedAt = null, at = Date.now()) {
82
+ const n = Number.isSafeInteger(step.n) && step.n >= 0 ? step.n : 0;
83
+ return {
84
+ n,
85
+ label: clip(step.label, TEXT.label),
86
+ intent: clip(step.intent, TEXT.intent),
87
+ changed: typeof step.changed === 'boolean' ? step.changed : null,
88
+ screen: clip(step.screen, TEXT.screen),
89
+ atMs: Number.isFinite(startedAt) ? Math.max(0, Math.round(at - startedAt)) : null
90
+ };
91
+ }
92
+
93
+ /** Width and height of a baseline or progressive JPEG, or null. */
94
+ export function jpegSize(buf) {
95
+ if (!Buffer.isBuffer(buf) || buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) return null;
96
+ let off = 2;
97
+ while (off + 9 < buf.length) {
98
+ if (buf[off] !== 0xff) return null;
99
+ const marker = buf[off + 1];
100
+ const len = buf.readUInt16BE(off + 2);
101
+ if ([0xc0, 0xc1, 0xc2].includes(marker)) return { height: buf.readUInt16BE(off + 5), width: buf.readUInt16BE(off + 7) };
102
+ off += 2 + len;
103
+ }
104
+ return null;
105
+ }
106
+
107
+ const fits = bytes => {
108
+ const size = jpegSize(bytes);
109
+ return size && bytes.length <= LIVE_MAX_FRAME_BYTES && size.width >= 1 && size.height >= 1 && size.width <= LIVE_MAX_SIDE && size.height <= LIVE_MAX_SIDE ? size : null;
110
+ };
111
+
112
+ function run(file, args, timeoutMs) {
113
+ return new Promise(resolve => {
114
+ execFile(file, args, { timeout: timeoutMs, windowsHide: true, env: { PATH: process.env.PATH || '' } }, error => resolve(error ? (error.code === 'ENOENT' ? 'missing' : 'failed') : 'ok'));
115
+ });
116
+ }
117
+
118
+ let noFfmpeg = false;
119
+ /**
120
+ * Scale an image to a small JPEG with ffmpeg at the lowest CPU priority, so a
121
+ * viewer never takes time from the game. Answers the bytes, or null (no
122
+ * ffmpeg on this machine, a failed scale).
123
+ */
124
+ export async function scaleFrame({ input, dir, ffmpeg = 'ffmpeg', exec = run, nice = process.platform === 'win32' ? null : '/usr/bin/nice' }) {
125
+ if (noFfmpeg) return null;
126
+ const source = path.join(dir, 'screen.img');
127
+ const out = path.join(dir, 'frame.jpg');
128
+ await writeFile(source, input);
129
+ await rm(out, { force: true });
130
+ const args = ['-hide_banner', '-loglevel', 'error', '-nostdin', '-y', '-threads', '1', '-i', source, '-frames:v', '1',
131
+ '-vf', `scale=w=${LIVE_WIDTH}:h=${LIVE_MAX_SIDE}:force_original_aspect_ratio=decrease,scale=trunc(iw/2)*2:trunc(ih/2)*2`, '-q:v', '9', '-f', 'image2', out];
132
+ const niced = nice && await access(nice).then(() => true, () => false);
133
+ const result = niced ? await exec(nice, ['-n', '19', ffmpeg, ...args], 5000) : await exec(ffmpeg, args, 5000);
134
+ if (result === 'missing') { noFfmpeg = true; return null; }
135
+ if (result !== 'ok') return null;
136
+ return readFile(out).catch(() => null);
137
+ }
138
+
139
+ /** For tests: forget that ffmpeg was missing. */
140
+ export function _resetFfmpeg() { noFfmpeg = false; }
141
+
142
+ /**
143
+ * One feed per run. Start it only after the run's `playing` transition was
144
+ * accepted; nothing is sent before a step arrives.
145
+ */
146
+ export function createLiveFeed({
147
+ api, gameId, jobId, runId,
148
+ startedAt = Date.now(),
149
+ now = Date.now,
150
+ budget = processBudget,
151
+ scale = scaleFrame,
152
+ makeDir = () => mkdtemp(path.join(os.tmpdir(), 'ravensight-live-')),
153
+ setTimer = setTimeout,
154
+ clearTimer = clearTimeout
155
+ }) {
156
+ let seq = 0, pending = [], shot = null, sentStep = -1, watching = false, inFlight = false, stopped = false;
157
+ let nextAt = 0, interval = LIVE_INTERVAL_MS, timer = null, failures = 0, dir = null;
158
+ const stats = { posts: 0, frames: 0, dropped: 0, failures: 0, reason: null };
159
+
160
+ const stop = reason => {
161
+ if (stopped) return;
162
+ stopped = true;
163
+ stats.reason = reason;
164
+ if (timer) clearTimer(timer);
165
+ timer = null;
166
+ pending = [];
167
+ shot = null;
168
+ if (dir) { const gone = dir; dir = null; rm(gone, { recursive: true, force: true }).catch(() => {}); }
169
+ };
170
+
171
+ async function frame() {
172
+ if (!watching || !shot || shot.step === sentStep) return null;
173
+ const want = shot;
174
+ try {
175
+ // Every frame is made fresh by the scaler, never forwarded as the driver gave it: the
176
+ // header of an image this process did not encode is not trusted. No scaler, no frame.
177
+ const input = Buffer.from(want.data, 'base64');
178
+ if (!dir) dir = await makeDir();
179
+ const bytes = await scale({ input, dir });
180
+ const size = bytes && fits(bytes);
181
+ if (!size) return null;
182
+ return { step: want.step, body: { type: 'image/jpeg', data: bytes.toString('base64'), width: size.width, height: size.height, step: want.step } };
183
+ } catch {
184
+ return null;
185
+ }
186
+ }
187
+
188
+ async function flush() {
189
+ timer = null;
190
+ if (stopped || inFlight) return;
191
+ if (!budget.take()) { nextAt = now() + LIVE_MAX_INTERVAL_MS; schedule(); return; }
192
+ inFlight = true;
193
+ const steps = pending.slice(-LIVE_MAX_STEPS);
194
+ stats.dropped += pending.length - steps.length;
195
+ pending = [];
196
+ try {
197
+ const f = await frame();
198
+ if (stopped) return;
199
+ seq += 1;
200
+ const answer = await api.runs.live(gameId, jobId, runId, { seq, steps, ...(f ? { frame: f.body } : {}) }, { timeoutMs: LIVE_TIMEOUT_MS });
201
+ stats.posts += 1;
202
+ failures = 0;
203
+ watching = answer?.watching === true;
204
+ if (f && answer?.accepted) { sentStep = f.step; stats.frames += 1; }
205
+ if (Number.isFinite(answer?.intervalMs)) interval = Math.min(LIVE_MAX_INTERVAL_MS, Math.max(LIVE_MIN_INTERVAL_MS, answer.intervalMs));
206
+ } catch (error) {
207
+ stats.failures += 1;
208
+ stats.dropped += steps.length;
209
+ const status = error && error.status;
210
+ if (FINAL.has(status)) return stop(`http_${status}`);
211
+ failures += 1;
212
+ if (failures >= LIVE_MAX_FAILURES) return stop('failures');
213
+ const waitMs = Number.isFinite(error?.body?.retryAfterMs) ? error.body.retryAfterMs : Number.isFinite(error?.retryAfter) ? error.retryAfter * 1000 : null;
214
+ if (status === 429 && waitMs !== null) nextAt = now() + Math.min(LIVE_MAX_INTERVAL_MS, Math.max(LIVE_MIN_INTERVAL_MS, waitMs));
215
+ } finally {
216
+ inFlight = false;
217
+ if (!stopped) {
218
+ nextAt = Math.max(nextAt, now() + interval);
219
+ if (pending.length || (watching && shot && shot.step !== sentStep)) schedule();
220
+ }
221
+ }
222
+ return undefined;
223
+ }
224
+
225
+ function schedule() {
226
+ if (stopped || timer || inFlight) return;
227
+ timer = setTimer(() => { flush().catch(() => {}); }, Math.max(0, nextAt - now()));
228
+ if (timer && typeof timer.unref === 'function') timer.unref();
229
+ }
230
+
231
+ return {
232
+ /**
233
+ * A step was played. `image` is the screen after it, `{ data: base64 }`
234
+ * (a PNG or a JPEG), when the screen changed and the driver has one.
235
+ */
236
+ step(step, { image = null } = {}) {
237
+ if (stopped) return;
238
+ try {
239
+ const s = liveStep(step, startedAt, now());
240
+ pending.push(s);
241
+ if (pending.length > LIVE_MAX_STEPS * 3) { stats.dropped += pending.length - LIVE_MAX_STEPS; pending = pending.slice(-LIVE_MAX_STEPS); }
242
+ if (image && typeof image.data === 'string' && image.data && step.changed !== false) shot = { data: image.data, step: s.n };
243
+ schedule();
244
+ } catch {
245
+ // Never into play.
246
+ }
247
+ },
248
+ close() { stop(stats.reason || 'closed'); },
249
+ stats: () => ({ ...stats, seq, watching, stopped })
250
+ };
251
+ }
252
+
253
+ /** A feed that sends nothing, for a run with the live view off. */
254
+ export const NO_LIVE_FEED = Object.freeze({ step() {}, close() {}, stats: () => ({ posts: 0, frames: 0, dropped: 0, failures: 0, reason: 'off', seq: 0, watching: false, stopped: true }) });