ravensight-playtest 0.8.0 → 0.8.2

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 CHANGED
@@ -27,9 +27,14 @@ question, and nothing is charged.
27
27
  | `--build <id>` | Use this build instead of the newest ready one. |
28
28
  | `--persona <slug>` | The persona for both runs. Default `curious-kid`. |
29
29
  | `--video`, `--transcript` | Save video or transcripts of both sessions in their reports. Priced in the quote. |
30
- | `--wait` | Stay until the run finishes, printing each phase change, then each mode's outcome. |
30
+ | `--wait` | Stay until the run finishes, printing each phase change and the queue place while it waits, then each mode's outcome. Works with a saved quote file too. |
31
31
  | `--game <id>` | Override the linked game. |
32
32
 
33
+ `hosted run` prints the hosted run id and job id as soon as the run is admitted.
34
+ A run waiting for a hosted machine shows its place, such as "Queued, position 2,
35
+ expected to start in about 14 minutes" or "Queued, starting now", and `--wait`
36
+ prints it again whenever it moves.
37
+
33
38
  The phases are the dashboard's: queued, provisioning, running, capturing,
34
39
  analyzing, then report ready, failed or canceled. `hosted status <id>` prints
35
40
  the current one (`--wait` to follow it) with each mode's state and findings and
@@ -41,16 +46,26 @@ is refunded during settlement.
41
46
  To review a quote before paying, save it and confirm it later:
42
47
 
43
48
  ```sh
44
- ravensight-playtest hosted quote --game GAME --build BUILD --persona curious-kid --video --output hosted-quote.json
45
- ravensight-playtest hosted run hosted-quote.json
49
+ ravensight-playtest hosted quote --game GAME --build BUILD --video --output hosted-quote.json
50
+ ravensight-playtest hosted run hosted-quote.json --wait
46
51
  ```
47
52
 
53
+ `hosted quote` uses the same default persona as `hosted run`, `curious-kid`, and
54
+ says so; `--persona` names another.
55
+
48
56
  `--profile` is needed only when the server advertises more than one build
49
57
  profile; the error lists them. The quote names the full Geri then Freki price, prepaid amount, evidence
50
58
  options, expiry and refund rules. It charges nothing. `hosted run` confirms
51
59
  that saved quote before one admission request. Its durable journal blocks an
52
60
  automatic second POST after an uncertain outcome; preserve it for reconciliation.
53
61
  Both forms of `hosted run` keep that journal under `.ravensight/hosted-runs/`.
62
+ When the server refuses the run with its own reason (busy capacity, funding,
63
+ an expired quote), no run was started, nothing was charged and the journal is
64
+ cleared, so the same command can be run again; it sends the same idempotency
65
+ key, so the server can never admit it twice. Only an answer that never arrived
66
+ leaves the outcome unknown. Then `hosted status`, with no run id, asks the
67
+ server what happened once the quote has expired (so asking cannot start the
68
+ run), records the run if it was admitted, and clears the journal if it was not.
54
69
  A charged-blocked acknowledgement does not prove gameplay or a report. This
55
70
  command does not top up funds, change local run/report files or ask for model
56
71
  proxy permission on the CLI credential.
@@ -68,11 +83,16 @@ continues to use its local runner and original API contract.
68
83
  The hosted build command source adds a local check before a paid upload:
69
84
 
70
85
  ```sh
71
- ravensight-playtest build preflight ./game.zip --format web --entrypoint index.html
72
- ravensight-playtest build upload ./game.zip --game GAME --entrypoint index.html --dry-run
86
+ ravensight-playtest build preflight ./game.zip --format web
87
+ ravensight-playtest build upload ./game.zip --game GAME --dry-run
73
88
  ravensight-playtest build status --game GAME
74
89
  ```
75
90
 
91
+ `--entrypoint` names the file the game starts from. Without it, an `index.html`
92
+ at the root of the archive (or inside the one folder that holds everything) is
93
+ used, or else the only HTML file, and the command says which. When several
94
+ files could be the entry, it lists them and asks you to choose one.
95
+
76
96
  `preflight` seeks through bounded ZIP metadata; it does not load a multi-GB
77
97
  archive into memory. A saved server profile can be supplied with `--capacity`
78
98
  for its declared limits. Upload uses the server's build profile when it
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ravensight-playtest",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "description": "Local AI playtests and seeded game simulations with reports in Ravensight.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://ravensight.io/docs/#playtest",
package/src/cli.js CHANGED
@@ -161,7 +161,7 @@ export function buildProgram() {
161
161
  .description('save a full hosted quote without charging or admitting a run')
162
162
  .requiredOption('--build <id>', 'an existing validated hosted build')
163
163
  .option('--profile <version>', 'hosted profile to quote; optional when the server advertises exactly one, otherwise the error lists the choices')
164
- .requiredOption('--persona <slug>', 'one available persona for both separate playthroughs')
164
+ .option('--persona <slug>', 'the persona that plays both runs (default: curious-kid, the same as hosted run)')
165
165
  .requiredOption('--output <file>', 'save the original quote and immutable consent here')
166
166
  .option('--game <id>', 'game id, overriding this repo’s configuration')
167
167
  .addOption(new Option('--geri-provider <name>', "Geri's model provider: primary or alternate (ravensight.io/legal/subprocessors names both); unavailable choices are refused").choices(['primary', 'alternate']).conflicts('standardProvider'))
@@ -180,19 +180,22 @@ export function buildProgram() {
180
180
  .option('--persona <slug>', 'the persona that plays both runs (default: curious-kid)')
181
181
  .option('--game <id>', 'game id, overriding this repo’s configuration')
182
182
  .option('--video', 'save video of both game sessions in their reports')
183
- .option('--wait', 'stay until the report is ready, printing each phase change')
183
+ .option('--wait', 'stay until the report is ready, printing each phase change (with or without a saved quote)')
184
+ // Hidden: the server now queues a funded run instead of refusing it for
185
+ // capacity. Kept so an older server's busy answer can still be waited out.
186
+ .addOption(new Option('--wait-for-capacity [minutes]', 'when hosted capacity is busy, ask again about once a minute and start when there is room, for up to this many minutes (default 60)').hideHelp())
184
187
  .action(capture(slot, async (filename, options, command) => {
185
188
  const { hostedRun, hostedRunDirect } = await import('./commands/hosted.js');
186
189
  if (filename) {
187
- const extra = ['build', 'persona', 'game', 'video', 'wait'].filter(name => options[name] !== undefined);
190
+ const extra = ['build', 'persona', 'game', 'video'].filter(name => options[name] !== undefined);
188
191
  if (extra.length) throw new CliError(`A saved quote already fixes its build, persona and options. Drop --${extra.join(', --')}, or run "hosted run" without a quote file.`);
189
- return hostedRun(filename, flagsFrom(command.optsWithGlobals()));
192
+ return hostedRun(filename, flagsFrom(command.optsWithGlobals(), { wait: options.wait, waitForCapacity: options.waitForCapacity }));
190
193
  }
191
194
  return hostedRunDirect(flagsFrom(command.optsWithGlobals(), { build: options.build, persona: options.persona, game: options.game,
192
- video: options.video, wait: options.wait }));
195
+ video: options.video, wait: options.wait, waitForCapacity: options.waitForCapacity }));
193
196
  }));
194
- common(hosted.command('status <run-id>'))
195
- .description('show the phase of one hosted run (queued, provisioning, running, capturing, analyzing, report ready, failed or canceled), each mode and the report link')
197
+ common(hosted.command('status [run-id]'))
198
+ .description('show the phase of one hosted run (queued, provisioning, running, capturing, analyzing, report ready, failed or canceled), each mode and the report link; with no run id, ask the server about any admission whose outcome is not known yet')
196
199
  .option('--game <id>', 'game id, overriding this repo’s configuration')
197
200
  .option('--wait', 'stay until the run finishes, printing each phase change')
198
201
  .action(capture(slot, async (runId, options, command) => {
@@ -209,7 +212,7 @@ export function buildProgram() {
209
212
  const build = common(program.command('build').description('check or upload a self-contained hosted game archive'));
210
213
  build.command('preflight <archive>')
211
214
  .description('check bounded ZIP metadata locally before any paid upload')
212
- .requiredOption('--entrypoint <path>', 'entry file inside the ZIP')
215
+ .option('--entrypoint <path>', 'entry file inside the ZIP (default: index.html at the root, or the only HTML file; several are listed to choose from)')
213
216
  .option('--format <name>', 'web or godot-project without a selected capacity profile', 'web')
214
217
  .option('--capacity <file>', 'saved profile JSON for a local capacity check; does not establish server readiness')
215
218
  .action(capture(slot, async (archive, options, command) => {
@@ -226,7 +229,7 @@ export function buildProgram() {
226
229
  build.command('upload <archive>')
227
230
  .description('preflight and stream one private build upload after validation-hold consent')
228
231
  .option('--profile <version>', 'server build profile to upload under; optional when the server advertises exactly one, otherwise the error lists the choices')
229
- .requiredOption('--entrypoint <path>', 'entry file inside the ZIP')
232
+ .option('--entrypoint <path>', 'entry file inside the ZIP (default: index.html at the root, or the only HTML file; several are listed to choose from)')
230
233
  .option('--game <id>', 'game id, overriding this repo’s configuration')
231
234
  .option('--journal <file>', 'preserve this original upload intent at the specified path')
232
235
  .option('--dry-run', 'inspect and hash the archive without requesting a reservation')
@@ -2,7 +2,7 @@ import { readFile, stat } from 'node:fs/promises';
2
2
  import { createContext } from '../api/index.js';
3
3
  import { resolveGameId } from '../config.js';
4
4
  import { withAuthHandling } from '../auth/session.js';
5
- import { preflightBuildArchive, limitsFromProfile } from '../hosted/archivePreflight.js';
5
+ import { preflightBuildArchive, limitsFromProfile, entrypointChoiceLine } from '../hosted/archivePreflight.js';
6
6
  import { uploadHostedBuild } from '../hosted/buildUpload.js';
7
7
  import { buildStatusLines, readHostedBuilds } from '../hosted/buildStatus.js';
8
8
  import { CliError, ExitCode } from '../errors.js';
@@ -43,6 +43,7 @@ export async function buildPreflight(filename, flags = {}) {
43
43
  requirements: profile?.capacity?.requirements });
44
44
  if (flags.json) ui.json(result);
45
45
  else {
46
+ if (result.entrypointChosen) ui.info(entrypointChoiceLine({ entrypoint: result.entrypoint, reason: result.entrypointChosen }));
46
47
  ui.ok(`ZIP metadata passed: ${result.entries} entries; ${ui.bytes(result.archiveBytes)} uploaded, ${ui.bytes(result.expandedBytes)} expanded.`);
47
48
  ui.info('No wallet charge or upload was requested. Server validation and runtime compatibility checks are still required.');
48
49
  }
@@ -62,6 +63,7 @@ export async function buildUpload(filename, flags = {}, deps = {}) {
62
63
  onPrepared: prepared => {
63
64
  progress.stop();
64
65
  if (flags.json) return;
66
+ if (prepared.entrypointChosen) ui.info(entrypointChoiceLine({ entrypoint: prepared.entrypoint, reason: prepared.entrypointChosen }));
65
67
  ui.info(`Build profile: ${prepared.profileVersion}${flags.profile ? '' : ', the only one the server advertises'}.`);
66
68
  ui.info(`ZIP metadata checked: ${prepared.entries} entries; ${ui.bytes(prepared.archiveBytes)} archive, ${ui.bytes(prepared.expandedBytes)} expanded.`);
67
69
  const limit = prepared.limits;
@@ -4,21 +4,26 @@ import { withAuthHandling } from '../auth/session.js';
4
4
  import { CliError, ExitCode } from '../errors.js';
5
5
  import { ui } from '../ui/index.js';
6
6
  import { quoteHostedRun, runHostedQuote, hostedQuoteLines, prepareHostedRun, admitHostedOffer, confirmQuestion,
7
- hostedConsentLines, fundingShortfall, readHostedRun, cancelHostedRun, GERI_PROVIDERS } from '../hosted/recordedRun.js';
8
- import { hostedPlaytestStatus, modeOutcomes, modeLine, TERMINAL_PHASES } from '../hosted/status.js';
7
+ hostedConsentLines, fundingShortfall, readHostedRun, cancelHostedRun, GERI_PROVIDERS, admitWithCapacityWait,
8
+ resolveHostedIntents } from '../hosted/recordedRun.js';
9
+ import { hostedPlaytestStatus, modeOutcomes, modeLine, TERMINAL_PHASES, queueInfo, queueLine } from '../hosted/status.js';
9
10
  import { jobLink } from '../dashboard.js';
10
11
  import { DEFAULT_PERSONAS } from '../runDefaults.js';
11
12
 
12
13
  export async function hostedQuote(flags = {}, deps = {}) {
13
14
  const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot: flags.repoRoot, requireAuth: true });
15
+ // The same default as "hosted run", so a quote and a run of the same build
16
+ // match unless a persona is named.
17
+ const persona = flags.persona || DEFAULT_PERSONAS[0];
14
18
  return withAuthHandling(context, async () => {
15
19
  const result = await quoteHostedRun({ api: context.api, apiUrl: context.api.apiUrl,
16
20
  gameId: resolveGameId(flags, context.config), buildId: flags.build, profileVersion: flags.profile,
17
- persona: flags.persona,
21
+ persona,
18
22
  standardProvider: flags.geriProvider ? GERI_PROVIDERS[flags.geriProvider] : flags.standardProvider, includeVideo: Boolean(flags.video),
19
23
  output: flags.output });
20
- if (flags.json) ui.json(result);
24
+ if (flags.json) ui.json({ ...result, persona, personaDefaulted: !flags.persona });
21
25
  else {
26
+ if (!flags.persona) ui.info(`Persona: ${persona}, the default. Choose another with --persona.`);
22
27
  hostedQuoteLines(result).forEach(line => ui.info(line));
23
28
  ui.ok(`Saved ${result.quoteFile}. No admission or charge was requested.`);
24
29
  }
@@ -28,21 +33,65 @@ export async function hostedQuote(flags = {}, deps = {}) {
28
33
 
29
34
  export async function hostedRun(filename, flags = {}, deps = {}) {
30
35
  if (flags.json && !flags.yes && !deps.confirm) throw new CliError('Inspect the saved quote, then use --yes with --json. No admission was requested.');
36
+ const maxWaitMs = capacityWaitMs(flags.waitForCapacity);
31
37
  const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot: flags.repoRoot, requireAuth: true });
38
+ const now = deps.now || Date.now, sleep = deps.sleep || (() => sleepFor(POLL_MS));
32
39
  return withAuthHandling(context, async () => {
33
- const result = await runHostedQuote({ filename, api: context.api, apiUrl: context.api.apiUrl, repoRoot: context.repoRoot,
40
+ const api = context.api, apiUrl = api.apiUrl;
41
+ const result = await runHostedQuote({ filename, api, apiUrl, repoRoot: context.repoRoot, now,
34
42
  confirm: deps.confirm || (question => ui.confirm(question, { yes: Boolean(flags.yes) })),
35
- onPrepared: offer => { if (!flags.json) hostedQuoteLines(offer).forEach(line => ui.info(line)); } });
36
- if (flags.json) ui.json(result);
37
- else if (result.state === 'declined') ui.info('Hosted quote declined. No admission was requested.');
38
- else {
39
- ui.ok(`Admission ${result.admissionId}; job ${result.jobId}. Saved ${result.journal}.`);
40
- ui.info('The server acknowledged charged_blocked. This does not prove a worker started or produced gameplay or reports.');
43
+ onPrepared: offer => { if (!flags.json) hostedQuoteLines(offer).forEach(line => ui.info(line)); },
44
+ admit: admitter(flags, deps, maxWaitMs) });
45
+ if (result.state === 'declined') {
46
+ if (flags.json) ui.json(result); else ui.info('Hosted quote declined. No admission was requested.');
47
+ return ExitCode.CANCELED;
48
+ }
49
+ const { offer: admittedOffer, ...admitted } = result, gameId = admittedOffer.gameId;
50
+ if (!flags.json) {
51
+ ui.ok(`Admission ${admitted.admissionId}; job ${admitted.jobId}. Saved ${admitted.journal}.`);
52
+ admittedLines(admitted, now());
53
+ ui.info(`Check on it with: ravensight-playtest hosted status ${admitted.admissionId}`);
54
+ }
55
+ if (!flags.wait) {
56
+ if (flags.json) ui.json(admitted);
57
+ else ui.info(`The server acknowledged the paid admission (${admitted.state}). This does not prove a worker started or produced gameplay or reports.`);
58
+ return ExitCode.OK;
41
59
  }
42
- return result.state === 'declined' ? ExitCode.CANCELED : ExitCode.OK;
60
+ const view = await waitForRun({ api, gameId, admissionId: admitted.admissionId, apiUrl, sleep, now, onPhase: phaseLine(flags) });
61
+ if (flags.json) ui.json({ ...admitted, gameId, status: view });
62
+ else printOutcome(view);
63
+ return exitFor(view);
43
64
  });
44
65
  }
45
66
 
67
+ const CAPACITY_WAIT_DEFAULT_MINUTES = 60;
68
+ const CAPACITY_WAIT_MAX_MINUTES = 720;
69
+
70
+ /** --wait-for-capacity [minutes]: true for the default, or whole minutes up to 12 hours. */
71
+ export function capacityWaitMs(value) {
72
+ if (value === undefined || value === false) return null;
73
+ const minutes = value === true ? CAPACITY_WAIT_DEFAULT_MINUTES : Number(value);
74
+ if (!Number.isInteger(minutes) || minutes < 1 || minutes > CAPACITY_WAIT_MAX_MINUTES) {
75
+ throw new CliError(`--wait-for-capacity takes whole minutes from 1 to ${CAPACITY_WAIT_MAX_MINUTES} (default ${CAPACITY_WAIT_DEFAULT_MINUTES}); put a saved quote file before it. Nothing was charged.`);
76
+ }
77
+ return minutes * 60000;
78
+ }
79
+
80
+ const minutesText = ms => { const m = Math.round(ms / 60000); return m < 1 ? 'under a minute' : `${m} minute${m === 1 ? '' : 's'}`; };
81
+ const delayText = ms => { const s = Math.round(ms / 1000), m = Math.floor(s / 60); return m ? `${m} m ${s % 60} s` : `${s} s`; };
82
+
83
+ /** How an accepted offer is admitted: once, or waiting for capacity when asked. */
84
+ function admitter(flags, deps, maxWaitMs) {
85
+ return async args => {
86
+ if (maxWaitMs === null) return { ...await admitHostedOffer(args), offer: args.offer };
87
+ return admitWithCapacityWait({ ...args, maxWaitMs, sleep: deps.capacitySleep, random: deps.random,
88
+ onBusy: ({ delayMs, waitedMs }) => {
89
+ if (!flags.json) ui.info(`Hosted capacity is busy. No run was started and nothing was charged. Asking again in ${delayText(delayMs)} (waited ${minutesText(waitedMs)} of ${minutesText(maxWaitMs)}).`);
90
+ },
91
+ onRequote: offer => { if (!flags.json) ui.info(`Fresh quote ${offer.quote.quoteId} at the same price, ${dollars(offer.quote.totalPriceCents)}. The earlier attempt charged nothing.`); } });
92
+ };
93
+ }
94
+
46
95
  const POLL_MS = 15000;
47
96
  const dollars = cents => `$${(cents / 100).toFixed(2)}`;
48
97
  const sleepFor = ms => new Promise(resolve => { const timer = setTimeout(resolve, ms); if (timer.unref) timer.unref(); });
@@ -66,12 +115,13 @@ function statusView(gameId, apiUrl, { admission, job, runs }, now = Date.now())
66
115
  totalPriceCents: Number.isSafeInteger(admission.totalPriceCents) ? admission.totalPriceCents : null,
67
116
  modes: modeOutcomes(runs, Array.isArray(admission.controllers) ? admission.controllers : ['standard', 'jev']),
68
117
  summaryReport: job?.summary_report ?? null,
69
- reportUrl: admission.jobId ? jobLink(gameId, admission.jobId, apiUrl) : null
118
+ reportUrl: admission.jobId ? jobLink(gameId, admission.jobId, apiUrl) : null,
119
+ queue: status.phase === 'queued' ? queueInfo(admission) : null
70
120
  };
71
121
  }
72
122
 
73
- function printOutcome(view) {
74
- ui.info(`${view.label}. ${view.detail}`);
123
+ function printOutcome(view, now = Date.now()) {
124
+ ui.info(view.queue ? queueLine(view.queue, now) : `${view.label}. ${view.detail}`);
75
125
  if (view.failure) ui.info(`Reason: ${view.failure}`);
76
126
  if (view.cancelRequested && view.phase !== 'canceled') ui.info('Cancellation was requested.');
77
127
  if (TERMINAL_PHASES.includes(view.phase) || view.modes.some(row => row.state !== 'not_started')) view.modes.forEach(row => ui.info(modeLine(row)));
@@ -85,14 +135,22 @@ const exitFor = view => view.phase === 'canceled' ? ExitCode.CANCELED : view.pha
85
135
  async function waitForRun({ api, gameId, admissionId, apiUrl, sleep, now, onPhase }) {
86
136
  let last = null;
87
137
  for (;;) {
88
- const view = statusView(gameId, apiUrl, await readHostedRun({ api, gameId, admissionId }), now());
89
- if (view.phase !== last) { last = view.phase; onPhase(view); }
138
+ const at = now(), view = statusView(gameId, apiUrl, await readHostedRun({ api, gameId, admissionId }), at);
139
+ // In the queue, a new position or estimate is printed too, so the wait is visible.
140
+ const key = view.queue ? queueLine(view.queue, at) : view.phase;
141
+ if (key !== last) { last = key; onPhase(view, at); }
90
142
  if (TERMINAL_PHASES.includes(view.phase)) return view;
91
143
  await sleep();
92
144
  }
93
145
  }
94
146
 
95
- const phaseLine = flags => row => { if (!flags.json) ui.info(`${row.label}: ${row.detail}`); };
147
+ const phaseLine = flags => (row, at = Date.now()) => { if (!flags.json) ui.info(row.queue ? queueLine(row.queue, at) : `${row.label}: ${row.detail}`); };
148
+
149
+ /** The job id at once, then the queue place when the server gave one. */
150
+ function admittedLines(admitted, now) {
151
+ const line = queueLine(admitted.queue, now);
152
+ if (line) ui.info(line);
153
+ }
96
154
 
97
155
  /**
98
156
  * `hosted run` with no saved quote: the newest eligible build (or --build), a
@@ -101,6 +159,7 @@ const phaseLine = flags => row => { if (!flags.json) ui.info(`${row.label}: ${ro
101
159
  */
102
160
  export async function hostedRunDirect(flags = {}, deps = {}) {
103
161
  if (flags.json && !flags.yes && !deps.confirm) throw new CliError('A hosted run charges prepaid funds. Use --yes with --json. Nothing was charged.');
162
+ const maxWaitMs = capacityWaitMs(flags.waitForCapacity);
104
163
  const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot: flags.repoRoot, requireAuth: true });
105
164
  const now = deps.now || Date.now, sleep = deps.sleep || (() => sleepFor(POLL_MS));
106
165
  return withAuthHandling(context, async () => {
@@ -123,13 +182,14 @@ export async function hostedRunDirect(flags = {}, deps = {}) {
123
182
  else ui.info('Declined. Nothing was charged.');
124
183
  return ExitCode.CANCELED;
125
184
  }
126
- const admitted = await admitHostedOffer({ offer, api, apiUrl, repoRoot: context.repoRoot, now });
185
+ const { offer: admittedOffer, ...admitted } = await admitter(flags, deps, maxWaitMs)({ offer, api, apiUrl, repoRoot: context.repoRoot, now });
127
186
  const reportUrl = jobLink(gameId, admitted.jobId, apiUrl);
128
187
  const result = { state: admitted.state, admissionId: admitted.admissionId, jobId: admitted.jobId, gameId, buildId: build.buildId,
129
- persona: offer.request.personas[0], totalPriceCents: admitted.totalPriceCents, dueNowCents: offer.quote.dueNowCents,
130
- journal: admitted.journal, reportUrl };
188
+ persona: offer.request.personas[0], totalPriceCents: admitted.totalPriceCents, dueNowCents: admittedOffer.quote.dueNowCents,
189
+ journal: admitted.journal, reportUrl, queue: admitted.queue || null };
131
190
  if (!flags.json) {
132
- ui.ok(`Paid ${dollars(offer.quote.dueNowCents)}. Hosted run ${admitted.admissionId}, job ${admitted.jobId}.`);
191
+ ui.ok(`Paid ${dollars(admittedOffer.quote.dueNowCents)}. Hosted run ${admitted.admissionId}, job ${admitted.jobId}.`);
192
+ admittedLines(admitted, now());
133
193
  ui.info(`Check on it with: ravensight-playtest hosted status ${admitted.admissionId}`);
134
194
  }
135
195
  if (!flags.wait) {
@@ -147,16 +207,32 @@ export async function hostedRunDirect(flags = {}, deps = {}) {
147
207
  export async function hostedStatus(admissionId, flags = {}, deps = {}) {
148
208
  const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot: flags.repoRoot, requireAuth: true });
149
209
  const now = deps.now || Date.now, sleep = deps.sleep || (() => sleepFor(POLL_MS));
210
+ if (!admissionId) {
211
+ if (flags.wait) throw new CliError('Name the hosted run to wait for: hosted status <run-id> --wait.');
212
+ return withAuthHandling(context, () => resolvePending(context, flags, now));
213
+ }
150
214
  return withAuthHandling(context, async () => {
151
215
  const api = context.api, apiUrl = api.apiUrl, gameId = resolveGameId(flags, context.config);
152
216
  const view = flags.wait
153
217
  ? await waitForRun({ api, gameId, admissionId, apiUrl, sleep, now, onPhase: phaseLine(flags) })
154
218
  : statusView(gameId, apiUrl, await readHostedRun({ api, gameId, admissionId }), now());
155
- if (flags.json) ui.json(view); else printOutcome(view);
219
+ if (flags.json) ui.json(view); else printOutcome(view, now());
156
220
  return flags.wait ? exitFor(view) : ExitCode.OK;
157
221
  });
158
222
  }
159
223
 
224
+ /** "hosted status" with no run id: ask the server about every admission whose outcome is not known locally. */
225
+ async function resolvePending(context, flags, now) {
226
+ const results = await resolveHostedIntents({ api: context.api, apiUrl: context.api.apiUrl, repoRoot: context.repoRoot, now });
227
+ if (flags.json) { ui.json({ intents: results.map(({ message, ...row }) => row) }); }
228
+ else if (!results.length) ui.info('No hosted admission is waiting for an answer. Name a run to see it: ravensight-playtest hosted status <run-id>');
229
+ else for (const row of results) {
230
+ ui.info(row.message);
231
+ if (row.state === 'admitted') ui.info(`Check on it with: ravensight-playtest hosted status ${row.admissionId}`);
232
+ }
233
+ return results.some(row => ['unknown', 'unreadable', 'wait', 'other_api'].includes(row.state)) ? ExitCode.ENVIRONMENT : ExitCode.OK;
234
+ }
235
+
160
236
  export async function hostedCancel(admissionId, flags = {}, deps = {}) {
161
237
  if (flags.json && !flags.yes && !deps.confirm) throw new CliError('Use --yes with --json to cancel a hosted run. Nothing was canceled.');
162
238
  const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot: flags.repoRoot, requireAuth: true });
@@ -279,7 +279,70 @@ export async function inspectBuildArchive(archive, { limits: supplied, format, e
279
279
  zip64: dir.zip64, metadataVerified: true, nativeBinaryMetadata, contentsVerified: false, serverValidationRequired: true, runtimeCompatibilityProven: false };
280
280
  }
281
281
 
282
- export async function preflightBuildArchive(filename, options) {
282
+ // The file names in the central directory, read with the same bounded
283
+ // metadata reads as the full inspection. Only names: inspectBuildArchive still
284
+ // checks every entry once the entry file is chosen.
285
+ async function archiveFileNames(archive, limits) {
286
+ const dir = await directory(archive, limits), names = [];
287
+ let cursor = dir.offset;
288
+ for (let index = 0; index < dir.count; index++) {
289
+ const h = await archive.read(cursor, 46);
290
+ if (h.readUInt32LE(0) !== 0x02014b50) reject('a ZIP directory entry is invalid');
291
+ const nameBytes = h.readUInt16LE(28), extraBytes = h.readUInt16LE(30), commentBytes = h.readUInt16LE(32);
292
+ if (!nameBytes || nameBytes > MAX_PATH_BYTES || cursor + 46 + nameBytes + extraBytes + commentBytes > dir.offset + dir.size) reject('a ZIP directory entry is oversized');
293
+ const name = (await archive.read(cursor + 46, nameBytes)).toString('utf8');
294
+ if (!name.endsWith('/')) names.push(name);
295
+ cursor += 46 + nameBytes + extraBytes + commentBytes;
296
+ }
297
+ return names;
298
+ }
299
+
300
+ const ENTRY_KINDS = Object.freeze({
301
+ web: { noun: 'HTML file', preferred: 'index.html', match: name => name.endsWith('.html') },
302
+ 'godot-project': { noun: 'project.godot file', preferred: 'project.godot', match: name => name.split('/').at(-1) === 'project.godot' },
303
+ 'windows-executable': { noun: '.exe file', preferred: null, match: name => name.toLowerCase().endsWith('.exe') }
304
+ });
305
+ const MAX_LISTED = 10;
306
+
307
+ /**
308
+ * The entry file to use when --entrypoint is not given. An index.html (or
309
+ * project.godot) at the top wins; otherwise the only candidate at the top,
310
+ * looking inside one wrapping folder when everything sits in one; otherwise
311
+ * the only candidate anywhere. With several, the error lists them so the
312
+ * person can choose: nothing is guessed.
313
+ * @returns {Promise<{entrypoint: string, reason: 'root'|'only-top-level'|'wrapped-folder'|'only-one'}>}
314
+ */
315
+ export async function chooseEntrypoint(archive, { limits: supplied, format } = {}) {
316
+ const kind = ENTRY_KINDS[format];
317
+ if (!kind) throw new CliError('Choose the entry file inside the ZIP with --entrypoint. No upload reservation was requested.');
318
+ const names = await archiveFileNames(archive, buildLimits(supplied));
319
+ const tops = new Set(names.map(name => name.split('/')[0]));
320
+ const wrapped = names.length > 0 && names.every(name => name.includes('/')) && tops.size === 1;
321
+ const base = wrapped ? `${[...tops][0]}/` : '';
322
+ const level = names.filter(name => name.startsWith(base) && !name.slice(base.length).includes('/'));
323
+ if (kind.preferred && level.includes(base + kind.preferred)) return { entrypoint: base + kind.preferred, reason: wrapped ? 'wrapped-folder' : 'root' };
324
+ const top = level.filter(kind.match);
325
+ if (top.length === 1) return { entrypoint: top[0], reason: wrapped ? 'wrapped-folder' : 'only-top-level' };
326
+ const every = top.length ? top : names.filter(kind.match).sort((a, b) => a.split('/').length - b.split('/').length || a.localeCompare(b));
327
+ if (every.length === 1) return { entrypoint: every[0], reason: 'only-one' };
328
+ if (!every.length && format === 'web' && nativeBuildKind(names)) reject(NATIVE_ADVICE[nativeBuildKind(names)]);
329
+ if (!every.length) throw new CliError(`No ${kind.noun} was found in the archive to start the game from. Check the ZIP holds the exported build, or name the entry file with --entrypoint. No upload reservation was requested.`);
330
+ const listed = every.slice(0, MAX_LISTED).join(', ') + (every.length > MAX_LISTED ? `, and ${every.length - MAX_LISTED} more` : '');
331
+ throw new CliError(`Several files could be the entry file: ${listed}. Choose one with --entrypoint. No upload reservation was requested.`);
332
+ }
333
+
334
+ /** One plain sentence saying which entry file was chosen and why. */
335
+ export function entrypointChoiceLine({ entrypoint, reason }) {
336
+ const why = { root: 'found at the root of the archive', 'only-top-level': 'the only one at the top of the archive',
337
+ 'wrapped-folder': 'inside the one folder that holds the build', 'only-one': 'the only one in the archive' }[reason];
338
+ return `Entry file: ${entrypoint}, ${why}. Pass --entrypoint to choose another.`;
339
+ }
340
+
341
+ export async function preflightBuildArchive(filename, options = {}) {
283
342
  const archive = await openBuildArchive(filename, options);
284
- try { return await inspectBuildArchive(archive, options); } finally { await archive.close(); }
343
+ try {
344
+ if (options.entrypoint) return await inspectBuildArchive(archive, options);
345
+ const chosen = await chooseEntrypoint(archive, options);
346
+ return { ...await inspectBuildArchive(archive, { ...options, entrypoint: chosen.entrypoint }), entrypointChosen: chosen.reason };
347
+ } finally { await archive.close(); }
285
348
  }
@@ -6,7 +6,7 @@ import { CliError } from '../errors.js';
6
6
  import { ApiError } from '../api/errors.js';
7
7
  import { writeJson } from '../fsutil.js';
8
8
  import { printable } from '../ui/index.js';
9
- import { openBuildArchive, inspectBuildArchive, buildLimits, limitsFromProfile } from './archivePreflight.js';
9
+ import { openBuildArchive, inspectBuildArchive, buildLimits, limitsFromProfile, chooseEntrypoint } from './archivePreflight.js';
10
10
 
11
11
  const fail = message => { throw new CliError(message); };
12
12
  const base = game => `/api/v1/games/${encodeURIComponent(game)}/playtest/hosted`;
@@ -102,11 +102,16 @@ export async function uploadHostedBuild({ filename, gameId, profileVersion, entr
102
102
  const archive = await openBuildArchive(filename, { signal });
103
103
  try {
104
104
  onProgress({ phase: 'preflight' });
105
+ // No --entrypoint: an index.html at the root, or the only candidate, is
106
+ // used and said so; several candidates are listed, never guessed.
107
+ const chosen = entrypoint ? null : await chooseEntrypoint(archive, { limits, format: profile.format });
108
+ if (chosen) entrypoint = chosen.entrypoint;
105
109
  const measurement = await inspectBuildArchive(archive, { limits, format: profile.format, entrypoint, requirements: profile.capacity?.requirements });
106
110
  onProgress({ phase: 'hash', completedBytes: 0, totalBytes: archive.size });
107
111
  const sha256 = await archive.sha256({ onProgress: (completedBytes, totalBytes) => onProgress({ phase: 'hash', completedBytes, totalBytes }) });
108
112
  const prepared = { ...measurement, sha256, profileVersion, limits, capacity: profile.capacity || null,
109
- validationHoldCents: offer.amountCents, funding: caps.funding || null, gameplayQuoteRequired: true };
113
+ validationHoldCents: offer.amountCents, funding: caps.funding || null, gameplayQuoteRequired: true,
114
+ ...(chosen ? { entrypointChosen: chosen.reason } : {}) };
110
115
  await onPrepared(prepared);
111
116
  if (dryRun) return { state: 'preflight_only', ...prepared, walletMutationRequested: false };
112
117
  if (!await confirm(`Reserve ${money(offer.amountCents)} from prepaid funds for this build’s static validation? It is returned after safe cleanup and is separate from the gameplay quote.`)) {
@@ -1,5 +1,5 @@
1
- import { createHash } from 'node:crypto';
2
- import { mkdir, open, access, rename } from 'node:fs/promises';
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdir, open, access, rename, readFile, readdir, rm } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { CliError, ExitCode } from '../errors.js';
5
5
  import { ApiError } from '../api/errors.js';
@@ -7,6 +7,7 @@ import { stableStringify } from '../fsutil.js';
7
7
  import { printable } from '../ui/index.js';
8
8
  import { chooseProfile } from './buildUpload.js';
9
9
  import { displayName } from '../run/controllers.js';
10
+ import { queueInfo } from './status.js';
10
11
 
11
12
  const MAX_QUOTE_BYTES = 1024 * 1024;
12
13
  const CONSENT_KEYS = ['quoteId', 'planHash', 'profileVersion', 'controllers', 'includeVideo', 'includeTranscript',
@@ -155,85 +156,314 @@ export function hostedQuoteLines(offer) {
155
156
  `Quote expires ${new Date(q.expiresAt).toISOString()}.`];
156
157
  }
157
158
 
158
- // A saved durable intent is never retried, even with the same quote or a new
159
- // capability response. The server also receives a stable key for this plan.
160
- export async function runHostedQuote({ filename, api, apiUrl, repoRoot, confirm, onPrepared = () => {}, now = Date.now }) {
159
+ const journalDir = repoRoot => path.join(repoRoot, '.ravensight', 'hosted-runs');
160
+ const journalFor = (repoRoot, { apiUrl, gameId, planHash }) => path.join(journalDir(repoRoot), `${digest({ apiUrl, gameId, planHash })}.json`);
161
+ const offerJournal = (repoRoot, offer) => journalFor(repoRoot, { apiUrl: offer.apiUrl, gameId: offer.gameId, planHash: offer.quote.planHash });
162
+ // The longest a server quote lives (recordedPlan QUOTE_MS). An older journal
163
+ // without the quote's own expiry is resolved after this much time.
164
+ const QUOTE_LIFETIME_MS = 300000;
165
+ const SERVER_CLOCK_MARGIN_MS = 15000;
166
+
167
+ async function readJournal(filename) {
168
+ try { return JSON.parse(await readFile(filename, 'utf8')); }
169
+ catch (error) { if (error.code === 'ENOENT') return null; return { unreadable: true }; }
170
+ }
171
+
172
+ // Removes the intent and every response captured for it. Only called when the
173
+ // server said for certain that nothing was admitted. The idempotency key is
174
+ // derived from the plan, so a later attempt with the same quote sends the same
175
+ // key and the server still deduplicates it.
176
+ async function clearIntent(journal) {
177
+ const dir = path.dirname(journal), name = path.basename(journal);
178
+ let names = [];
179
+ try { names = await readdir(dir); } catch (error) { if (error.code !== 'ENOENT') throw error; }
180
+ await Promise.all(names.filter(row => row === name || row.startsWith(name + '.')).map(row => rm(path.join(dir, row), { force: true })));
181
+ }
182
+
183
+ // A saved durable intent whose outcome is unknown is never retried here; only
184
+ // "hosted status" asks the server about it. The server receives a stable key.
185
+ export async function runHostedQuote({ filename, api, apiUrl, repoRoot, confirm, onPrepared = () => {}, now = Date.now, admit = admitHostedOffer }) {
161
186
  const offer = validateHostedOffer(await readHostedQuote(filename), apiUrl, now());
162
- const identity = digest({ apiUrl: offer.apiUrl, gameId: offer.gameId, planHash: offer.quote.planHash });
163
- const journal = path.join(repoRoot, '.ravensight', 'hosted-runs', `${identity}.json`);
164
- try { await access(journal); fail(`This hosted quote already has an admission intent at ${journal}. Reconcile the original outcome; no POST was repeated.`); }
165
- catch (error) { if (error.code !== 'ENOENT') throw error; }
187
+ const journal = offerJournal(repoRoot, offer), prior = await readJournal(journal);
188
+ if (prior?.phase === 'charged_blocked' && admissionPattern.test(prior.admission?.admissionId || '')) {
189
+ fail(`This quote already started hosted run ${prior.admission.admissionId}. Check it with: ravensight-playtest hosted status ${prior.admission.admissionId}`);
190
+ }
191
+ if (prior) fail(`This quote's earlier admission has no known outcome yet (${journal}). Ask the server what happened with: ravensight-playtest hosted status. No request was repeated.`);
166
192
  const { profile, funding } = await available(api, offer.gameId, offer.request.profileVersion, offer.request.standardProvider);
167
193
  if (profile.driver !== offer.request.driver || funding?.eligible === false || offer.quote.funding?.eligible === false) fail('The server no longer advertises this profile or sufficient prepaid funding. Nothing was charged.');
168
194
  await onPrepared(offer);
169
195
  if (typeof confirm !== 'function') fail('The full hosted quote must be confirmed before admission.');
170
196
  if (!await confirm(confirmQuestion(offer))) return { state: 'declined', walletMutationRequested: false };
171
- return admitHostedOffer({ offer, api, apiUrl, repoRoot, now });
197
+ return admit({ offer, api, apiUrl, repoRoot, now });
172
198
  }
173
199
 
174
200
  export const confirmQuestion = offer => `Pay ${money(offer.quote.dueNowCents)} now (${money(offer.quote.totalPriceCents)} total) for the quoted Geri then Freki runs and the evidence options shown?`;
175
201
 
176
- // Refusals the server makes before any charge: the quote or consent was not
177
- // accepted, funding or capacity said no, or the quote is gone. The original
178
- // intent is kept on disk all the same; only the message differs.
179
- const DEFINITE_REFUSALS = new Set(['hosted_funding_required', 'quote_not_accepted', 'not_found', 'recorded_unavailable',
202
+ // Refusals the server makes with its own code, before any charge: the request
203
+ // failed inside the admission's transaction, which rolled back, or before it.
204
+ // These are certain, so the local intent is cleared and the same quote can be
205
+ // tried again. A 5xx or a status the server did not explain is not certain.
206
+ const CERTAIN_REFUSALS = new Set(['hosted_funding_required', 'quote_not_accepted', 'not_found',
180
207
  'recorded_setup_required', 'hosted_global_capacity', 'too_many_active_hosted_runs', 'hosted_daily_capacity',
181
- 'hosted_build_too_large', 'hosted_build_safety_hold']);
208
+ 'hosted_build_too_large', 'hosted_build_safety_hold', 'quote_expired', 'recorded_quote_changed',
209
+ 'hosted_game_unavailable', 'hosted_studio_unavailable']);
210
+ // Refused by the server with its own code, but a 5xx: reported plainly, intent kept for "hosted status".
211
+ const EXPLAINED_UNAVAILABLE = new Set(['recorded_unavailable', 'hosted_execution_budget_unconfigured']);
212
+ export const CAPACITY_CODES = Object.freeze(['hosted_global_capacity', 'too_many_active_hosted_runs']);
213
+ // The server keeps an attempt it refused under the plan's key and answers a
214
+ // repeat with this, so that quote cannot start a run. Nothing was charged.
215
+ export const REFUSED_EARLIER = 'hosted_quote_refused_earlier';
216
+
217
+ export const certainRefusal = error => error instanceof ApiError
218
+ && (error.status === 401 || error.status >= 400 && error.status < 500 && CERTAIN_REFUSALS.has(error.code));
182
219
 
183
220
  export function hostedRefusalMessage(error) {
184
221
  const code = error?.code;
185
222
  if (code === 'hosted_funding_required') {
186
223
  const f = error.body?.funding;
187
224
  const topUp = Number.isSafeInteger(f?.requiredTopUpCents) && f.requiredTopUpCents > 0 ? ` Add at least ${money(f.requiredTopUpCents)} of prepaid funds, then request a new quote.` : ' Add prepaid funds, then request a new quote.';
188
- return `The server refused the run for funding. Nothing was charged.${topUp}`;
225
+ return `The server refused the run for funding. No run was started and nothing was charged.${topUp}`;
189
226
  }
190
227
  if (code === 'quote_not_accepted') return 'The server did not accept this consent for the quote. Nothing was charged; request a new quote.';
191
- if (['hosted_global_capacity', 'too_many_active_hosted_runs'].includes(code)) return 'Hosted capacity is busy. Nothing was charged. Wait for an existing run to finish, then retry. Adding funds does not increase capacity.';
192
- if (code === 'hosted_daily_capacity') return 'Today\'s hosted run allowance is used up. Nothing was charged. Try again after the daily limit resets.';
228
+ if (CAPACITY_CODES.includes(code)) return 'Hosted capacity is busy, so no run was started and nothing was charged. Run the same command again with --wait-for-capacity to wait for room and start then; it never charges twice. Adding funds does not increase capacity.';
229
+ if (code === 'hosted_daily_capacity') return 'Today\'s hosted run allowance is used up. No run was started and nothing was charged. Try again after the daily limit resets at 00:00 UTC.';
193
230
  if (code === 'recorded_setup_required') return `${error.message || 'Complete the playtest brief and choose an available persona.'} Nothing was charged.`;
194
231
  if (code === 'not_found') return 'The quote is no longer available. Nothing was charged; request a new quote.';
232
+ if (code === 'quote_expired' || code === 'recorded_quote_changed') return 'The quote expired before the run was admitted. No run was started and nothing was charged; request a new quote.';
195
233
  if (code === 'hosted_build_too_large') return 'This build is too large to play on a hosted machine: hosted playtests play builds up to 300 MiB unpacked. Make the build smaller and upload it again. Nothing was charged.';
196
234
  if (code === 'hosted_build_safety_hold') return 'This build was stopped for safety during a hosted playtest and cannot run again until an admin reviews and clears it in the dashboard. Nothing was charged.';
235
+ if (code === REFUSED_EARLIER) return 'The server already refused an earlier attempt with this quote, so it will not start a run from it. No run was started and nothing was charged; request a new quote, or use "hosted run" without a quote file.';
197
236
  return 'Hosted playtests are not available right now. Nothing was charged.';
198
237
  }
199
238
 
200
- // A saved durable intent is never retried. The journal is fsynced before the
201
- // only wallet-mutating POST and the server receives a stable key for the plan.
239
+ const refusalError = (code, error = { code }) => Object.assign(new CliError(hostedRefusalMessage(error), ExitCode.ENVIRONMENT),
240
+ { refusal: { code, certain: true, retryAfter: Number.isFinite(error.retryAfter) ? error.retryAfter : null } });
241
+
242
+ // The states a replayed key can report for an admission it made. The first
243
+ // answer is charged_blocked; a replay after the direct queue moved the run on
244
+ // reports where it is now (game_tracker recordedAdmission REPLAY_STATE). Every
245
+ // one of them means the run was admitted and charged once.
246
+ export const ADMITTED_STATES = Object.freeze(['charged_blocked', 'dispatched', 'running', 'review', 'closed', 'settled', 'canceled']);
247
+ const ACK_KEYS = ['admissionId', 'dispatchAllowed', 'jobId', 'state', 'totalPriceCents'];
248
+ const wholeOrNull = value => value === null || value === undefined || Number.isSafeInteger(value) && value >= 0;
249
+ const timeOrNull = value => value === null || value === undefined || typeof value === 'string' && value.length <= 64 && Number.isFinite(Date.parse(value));
250
+ // The queue place (directQueue.forAdmission). It is information only, never
251
+ // money, but each field it names must still have its own type.
252
+ export function validQueue(q) {
253
+ return Boolean(q) && typeof q === 'object' && !Array.isArray(q) && Number.isSafeInteger(q.position) && q.position >= 0
254
+ && ['ahead', 'running', 'ceiling', 'expectedStartMinutes', 'latestStartMinutes'].every(key => wholeOrNull(q[key]))
255
+ && ['estimatedStartAt', 'expectedStartAt', 'latestStartAt'].every(key => timeOrNull(q[key]))
256
+ && (q.startsNow === undefined || typeof q.startsNow === 'boolean')
257
+ && (q.message === undefined || typeof q.message === 'string' && q.message.length <= 500);
258
+ }
259
+
260
+ // What a 202 from POST /runs says: the acknowledgement of a new or replayed
261
+ // admission, the server's record that this key's attempt was refused, or an
262
+ // outcome the server itself cannot yet state. The keys are checked exactly,
263
+ // because this answer is the record of money taken: a queued admission adds
264
+ // `queued: true` with its `queue` place, and nothing else is accepted.
265
+ function readAdmissionAnswer(answer, totalPriceCents) {
266
+ if (answer.status !== 202 || answer.headers.get('content-type')?.split(';')[0].trim().toLowerCase() !== 'application/json'
267
+ || typeof answer.body !== 'string' || Buffer.byteLength(answer.body) > MAX_QUOTE_BYTES) return { kind: 'unknown' };
268
+ let ack;
269
+ try { ack = JSON.parse(answer.body); } catch { return { kind: 'unknown' }; }
270
+ if (!ack || typeof ack !== 'object' || Array.isArray(ack)) return { kind: 'unknown' };
271
+ if (same(ack, { state: 'failed', dispatchAllowed: false })) return { kind: 'refused_earlier' };
272
+ // Whatever else is wrong, an admission id the server named is kept so the person can find the run.
273
+ const named = { admissionId: admissionPattern.test(ack.admissionId || '') ? ack.admissionId : null,
274
+ jobId: /^pt_job_[a-f0-9]{20}$/.test(ack.jobId || '') ? ack.jobId : null };
275
+ const unknown = { kind: 'unknown', ...named };
276
+ const keys = Object.keys(ack).filter(key => key !== 'queue' && key !== 'queued').sort();
277
+ if (Object.hasOwn(ack, 'queue') && !validQueue(ack.queue)) return unknown;
278
+ if (Object.hasOwn(ack, 'queued') && (ack.queued !== true || !Object.hasOwn(ack, 'queue'))) return unknown;
279
+ if (!same(keys, ACK_KEYS) || !ADMITTED_STATES.includes(ack.state) || ack.dispatchAllowed !== false
280
+ || ack.totalPriceCents !== totalPriceCents || !named.admissionId || !named.jobId) return unknown;
281
+ const { queued, ...rest } = ack;
282
+ return { kind: 'admitted', ack: rest };
283
+ }
284
+
285
+ const namedRun = read => read.admissionId ? ` The server named hosted run ${read.admissionId}${read.jobId ? ` (job ${read.jobId})` : ''}; check it with: ravensight-playtest hosted status ${read.admissionId}` : '';
286
+
287
+ async function postAdmission(api, { gameId, consent, idempotencyKey }, captureFile) {
288
+ let responseCaptured = false;
289
+ const answer = await api.request('POST', `${base(gameId)}/runs`, { body: consent,
290
+ headers: { 'Idempotency-Key': idempotencyKey }, idempotent: false, raw: true,
291
+ onResponseRaw: async ({ status, contentType, bytes, bodyComplete }) => {
292
+ await exclusiveJson(captureFile, { status, contentType, bodyComplete,
293
+ bodyBase64: bytes.toString('base64'), bodyBytes: bytes.length,
294
+ bodySha256: createHash('sha256').update(bytes).digest('hex') });
295
+ responseCaptured = true;
296
+ } });
297
+ return responseCaptured ? answer : null;
298
+ }
299
+
300
+ async function recordAdmitted(journal, state, ack) {
301
+ state.phase = 'charged_blocked'; state.admission = ack; state.resolvedAt = new Date().toISOString();
302
+ await rm(journal + '.acknowledged.json', { force: true });
303
+ await exclusiveJson(journal + '.acknowledged.json', state);
304
+ await rename(journal + '.acknowledged.json', journal);
305
+ }
306
+
307
+ // The journal is fsynced before the only wallet-mutating POST and the server
308
+ // receives a stable key for the plan. A certain refusal clears the journal;
309
+ // anything else keeps it as admission_unknown for "hosted status" to resolve.
202
310
  export async function admitHostedOffer({ offer, api, apiUrl, repoRoot, now = Date.now }) {
203
311
  validateHostedOffer(offer, apiUrl, now());
204
- const identity = digest({ apiUrl: offer.apiUrl, gameId: offer.gameId, planHash: offer.quote.planHash });
205
- const journal = path.join(repoRoot, '.ravensight', 'hosted-runs', `${identity}.json`);
312
+ const journal = offerJournal(repoRoot, offer);
206
313
  const state = { schema: 'ravensight-hosted-admission-journal/v1', apiUrl: offer.apiUrl, gameId: offer.gameId,
207
314
  quoteId: offer.quote.quoteId, planHash: offer.quote.planHash, consent: offer.consent,
208
- idempotencyKey: `hosted-${offer.quote.planHash}`, phase: 'admission_unknown', createdAt: new Date(now()).toISOString() };
315
+ idempotencyKey: `hosted-${offer.quote.planHash}`, quoteExpiresAt: offer.quote.expiresAt,
316
+ phase: 'admission_unknown', createdAt: new Date(now()).toISOString() };
209
317
  await exclusiveJson(journal, state); // fsync BEFORE the only wallet-mutating POST
210
- try {
211
- let responseCaptured = false;
212
- const answer = await api.request('POST', `${base(offer.gameId)}/runs`, { body: offer.consent,
213
- headers: { 'Idempotency-Key': state.idempotencyKey }, idempotent: false, raw: true,
214
- onResponseRaw: async ({ status, contentType, bytes, bodyComplete }) => {
215
- await exclusiveJson(journal + '.response.json', { status, contentType, bodyComplete,
216
- bodyBase64: bytes.toString('base64'), bodyBytes: bytes.length,
217
- bodySha256: createHash('sha256').update(bytes).digest('hex') });
218
- responseCaptured = true;
219
- } });
220
- if (!responseCaptured) fail('The admission response was not captured. Preserve the original intent.');
221
- if (answer.status !== 202 || answer.headers.get('content-type')?.split(';')[0].trim().toLowerCase() !== 'application/json'
222
- || typeof answer.body !== 'string' || Buffer.byteLength(answer.body) > MAX_QUOTE_BYTES) fail('The admission acknowledgement needs reconciliation.');
223
- const ack = JSON.parse(answer.body);
224
- if (!same(Object.keys(ack).sort(), ['admissionId', 'dispatchAllowed', 'jobId', 'state', 'totalPriceCents'])
225
- || ack.state !== 'charged_blocked' || ack.dispatchAllowed !== false || ack.totalPriceCents !== offer.quote.totalPriceCents
226
- || !/^ha_[a-f0-9-]{36}$/.test(ack.admissionId || '') || !/^pt_job_[a-f0-9]{20}$/.test(ack.jobId || '')) fail('The admission acknowledgement needs reconciliation.');
227
- state.phase = 'charged_blocked'; state.admission = ack;
228
- await exclusiveJson(journal + '.acknowledged.json', state);
229
- await rename(journal + '.acknowledged.json', journal);
230
- return { state: 'charged_blocked', ...ack, journal, replayAuthorized: false, gameplayProven: false };
231
- } catch (error) {
232
- if (error instanceof ApiError && error.status === 401) throw error;
233
- if (error instanceof ApiError && DEFINITE_REFUSALS.has(error.code) && error.status >= 400 && error.status < 600) {
234
- throw new CliError(hostedRefusalMessage(error), ExitCode.ENVIRONMENT);
318
+ let answer;
319
+ try { answer = await postAdmission(api, state, journal + '.response.json'); }
320
+ catch (error) {
321
+ if (certainRefusal(error)) {
322
+ await clearIntent(journal);
323
+ if (error.status === 401) throw error;
324
+ throw refusalError(error.code, error);
325
+ }
326
+ if (error instanceof ApiError && EXPLAINED_UNAVAILABLE.has(error.code)) {
327
+ throw new CliError(`${hostedRefusalMessage(error)} To confirm and free this quote, run: ravensight-playtest hosted status`, ExitCode.ENVIRONMENT);
328
+ }
329
+ fail(`The admission's outcome is not known: ${unknownAdvice(journal)}`);
330
+ }
331
+ const read = answer ? readAdmissionAnswer(answer, offer.quote.totalPriceCents) : { kind: 'unknown' };
332
+ if (read.kind === 'refused_earlier') { await clearIntent(journal); throw refusalError(REFUSED_EARLIER); }
333
+ if (read.kind !== 'admitted') fail(`The admission acknowledgement needs reconciliation: ${unknownAdvice(journal)}.${namedRun(read)}`);
334
+ await recordAdmitted(journal, state, read.ack);
335
+ return { state: 'charged_blocked', ...read.ack, queue: queueInfo(read.ack), journal, replayAuthorized: false, gameplayProven: false };
336
+ }
337
+
338
+ const unknownAdvice = journal => `the run may or may not have started. Preserve ${journal}; nothing was retried. Ask the server what happened with: ravensight-playtest hosted status`;
339
+
340
+ /**
341
+ * Settle every saved admission intent whose outcome is unknown by asking the
342
+ * server, which answers from its own record under the same idempotency key.
343
+ * The question is only sent once the quote has expired, so it can report an
344
+ * admission but never start one. A certain answer that nothing was admitted
345
+ * clears the intent; an admission is recorded; anything else is kept.
346
+ */
347
+ export async function resolveHostedIntents({ api, apiUrl, repoRoot, now = Date.now }) {
348
+ const dir = journalDir(repoRoot), here = origin(apiUrl), results = [];
349
+ let names = [];
350
+ try { names = (await readdir(dir)).filter(name => /^[a-f0-9]{64}\.json$/.test(name)).sort(); }
351
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
352
+ for (const name of names) {
353
+ const journal = path.join(dir, name), state = await readJournal(journal);
354
+ if (!state || state.phase !== 'admission_unknown') continue;
355
+ if (state.unreadable || state.schema !== 'ravensight-hosted-admission-journal/v1' || !id(state.gameId) || !hex(state.planHash)
356
+ || state.idempotencyKey !== `hosted-${state.planHash}` || !state.consent || typeof state.consent !== 'object'
357
+ || journalFor(repoRoot, state) !== journal) {
358
+ results.push({ journal, state: 'unreadable', message: `${journal} is not a hosted admission record this version can read. Nothing was sent.` });
359
+ continue;
360
+ }
361
+ if (state.apiUrl !== here) {
362
+ results.push({ journal, gameId: state.gameId, state: 'other_api', message: `${journal} belongs to ${state.apiUrl}. Run this with --api-url ${state.apiUrl} to resolve it.` });
363
+ continue;
364
+ }
365
+ const created = Date.parse(state.createdAt);
366
+ const expiresAt = Number.isSafeInteger(state.quoteExpiresAt) ? state.quoteExpiresAt : (Number.isFinite(created) ? created + QUOTE_LIFETIME_MS : null);
367
+ const askAt = expiresAt === null ? null : expiresAt + SERVER_CLOCK_MARGIN_MS;
368
+ if (askAt === null || now() < askAt) {
369
+ results.push({ journal, gameId: state.gameId, state: 'wait', askAt,
370
+ message: askAt === null ? `${journal} has no readable time. Nothing was sent.`
371
+ : `Game ${state.gameId}: asking before ${new Date(askAt).toISOString()} could still start the run, so nothing was sent. Run "hosted status" again after that time.` });
372
+ continue;
373
+ }
374
+ let answer;
375
+ try { answer = await postAdmission(api, state, `${journal}.reconcile-${now()}-${randomUUID().slice(0, 8)}.json`); }
376
+ catch (error) {
377
+ if (certainRefusal(error) && error.status !== 401) {
378
+ await clearIntent(journal);
379
+ results.push({ journal, gameId: state.gameId, state: 'not_admitted', code: error.code,
380
+ message: `Game ${state.gameId}: the server has no run for this quote. No run was started and nothing was charged. The record is cleared.` });
381
+ continue;
382
+ }
383
+ if (error instanceof ApiError && error.status === 401) throw error;
384
+ results.push({ journal, gameId: state.gameId, state: 'unknown', message: `Game ${state.gameId}: the server did not answer clearly (${error.code || error.message}). The record is kept; try again later.` });
385
+ continue;
386
+ }
387
+ const read = answer ? readAdmissionAnswer(answer, state.consent.totalPriceCents) : { kind: 'unknown' };
388
+ if (read.kind === 'refused_earlier') {
389
+ await clearIntent(journal);
390
+ results.push({ journal, gameId: state.gameId, state: 'not_admitted', code: REFUSED_EARLIER,
391
+ message: `Game ${state.gameId}: the server refused that attempt. No run was started and nothing was charged. The record is cleared.` });
392
+ } else if (read.kind === 'admitted') {
393
+ await recordAdmitted(journal, state, read.ack);
394
+ results.push({ journal, gameId: state.gameId, state: 'admitted', admissionId: read.ack.admissionId, jobId: read.ack.jobId,
395
+ totalPriceCents: read.ack.totalPriceCents, runState: read.ack.state,
396
+ message: `Game ${state.gameId}: the run was admitted as ${read.ack.admissionId} (job ${read.ack.jobId}) and charged ${money(read.ack.totalPriceCents)}.` });
397
+ } else {
398
+ results.push({ journal, gameId: state.gameId, state: 'unknown', ...(read.admissionId ? { admissionId: read.admissionId } : {}), ...(read.jobId ? { jobId: read.jobId } : {}),
399
+ message: `Game ${state.gameId}: the server cannot state the outcome yet. The record is kept; nothing was retried.${namedRun(read)} If this persists, write to support@realityse.com with ${path.basename(journal)}.` });
400
+ }
401
+ }
402
+ return results;
403
+ }
404
+
405
+ // The terms a person accepted. A fresh quote taken while waiting for capacity
406
+ // must match them exactly, or nothing is admitted without asking again.
407
+ const TERMS = ['buildId', 'profileVersion', 'driver', 'controllers', 'includeVideo', 'includeTranscript', 'currency',
408
+ 'localPriceCents', 'computePriceCents', 'totalPriceCents', 'dueNowCents', 'alreadyReservedCents', 'localBreakdown',
409
+ 'computeBreakdown', 'priceVersion', 'policyVersion', 'customerFailure', 'cancelAfterStart', 'standardProvider',
410
+ 'standardProviderPolicyHash'];
411
+ const sameTerms = (a, b) => TERMS.every(key => same(a[key] ?? null, b[key] ?? null));
412
+
413
+ /** A fresh quote for exactly the request of an accepted offer. Charges nothing. */
414
+ export async function requoteOffer({ api, apiUrl, offer, now = Date.now }) {
415
+ const { profile, funding } = await available(api, offer.gameId, offer.request.profileVersion, offer.request.standardProvider);
416
+ if (profile.driver !== offer.request.driver) fail('The server no longer advertises this build profile. No run was started and nothing was charged.');
417
+ const response = await api.request('POST', `${base(offer.gameId)}/quotes`, { body: offer.request, idempotent: false });
418
+ if (response.status !== 200) fail('The server did not return a hosted quote. No run was started and nothing was charged.');
419
+ const quote = response.body, consent = hostedConsent(quote, offer.request, now());
420
+ if (fundingShortfall(quote, funding)) fail('The balance no longer meets this hosted run\'s funding requirement. No run was started and nothing was charged. Add prepaid funds, then run the command again.');
421
+ if (!sameTerms(offer.quote, quote)) fail(`The price or terms changed while waiting for capacity, so no run was started and nothing was charged. Run the command again to see the new quote (it was ${money(offer.quote.totalPriceCents)}, now ${money(quote.totalPriceCents)}).`);
422
+ const value = { apiUrl: origin(apiUrl), gameId: offer.gameId, request: offer.request, quote, consent };
423
+ return { schema: 'ravensight-hosted-recorded-quote/v1', ...value, integrity: digest(value) };
424
+ }
425
+
426
+ export const CAPACITY_POLL_MS = 60000;
427
+ export const CAPACITY_JITTER_MS = 30000;
428
+ const CAPACITY_RETRY_AFTER_MAX_MS = 15 * 60000;
429
+
430
+ /** The wait before asking again: at least a minute, longer if the server says so, plus jitter. */
431
+ export function capacityDelay(error, random = Math.random) {
432
+ const server = Number.isFinite(error?.retryAfter) && error.retryAfter > 0 ? Math.min(error.retryAfter * 1000, CAPACITY_RETRY_AFTER_MAX_MS) : 0;
433
+ return Math.max(CAPACITY_POLL_MS, server) + Math.floor(random() * CAPACITY_JITTER_MS);
434
+ }
435
+
436
+ /**
437
+ * Admit an accepted offer, and while the server answers that hosted capacity
438
+ * is busy, ask again about once a minute until there is room or maxWaitMs
439
+ * passes. Every busy answer is a certain refusal that charged nothing and
440
+ * cleared its intent; any other outcome ends the wait, so an unknown outcome
441
+ * is never retried. Quotes last minutes, so each new attempt takes a fresh
442
+ * quote and refuses unless its terms equal the accepted ones exactly.
443
+ */
444
+ export async function admitWithCapacityWait({ offer, api, apiUrl, repoRoot, maxWaitMs, now = Date.now,
445
+ sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), random = Math.random, onBusy = () => {}, onRequote = () => {} }) {
446
+ if (!Number.isSafeInteger(maxWaitMs) || maxWaitMs < 1) fail('Choose how long to wait for capacity.');
447
+ const started = now(), deadline = started + maxWaitMs;
448
+ let current = offer, requoteNext = false, busy = 0;
449
+ for (;;) {
450
+ if (requoteNext) { current = await requoteOffer({ api, apiUrl, offer, now }); onRequote(current); }
451
+ try { return { ...await admitHostedOffer({ offer: current, api, apiUrl, repoRoot, now }), offer: current, busyAnswers: busy }; }
452
+ catch (error) {
453
+ const code = error?.refusal?.code;
454
+ // The server will not admit this quote again: take a fresh one straight away, once.
455
+ if (!requoteNext && [REFUSED_EARLIER, 'quote_expired', 'recorded_quote_changed'].includes(code)) { requoteNext = true; continue; }
456
+ if (!CAPACITY_CODES.includes(code)) throw error;
457
+ busy += 1;
458
+ const delay = capacityDelay(error.refusal, random);
459
+ if (now() + delay > deadline) {
460
+ const waited = Math.max(1, Math.round((now() - started) / 60000));
461
+ throw Object.assign(new CliError(`Hosted capacity stayed busy for ${waited} minute${waited === 1 ? '' : 's'}, so no run was started and nothing was charged. Run the command again later, or with a longer --wait-for-capacity.`, ExitCode.ENVIRONMENT), { refusal: error.refusal });
462
+ }
463
+ onBusy({ attempt: busy, delayMs: delay, waitedMs: now() - started, maxWaitMs });
464
+ await sleep(delay);
465
+ requoteNext = true;
235
466
  }
236
- fail(`The original admission outcome needs reconciliation. Preserve ${journal}; no retry or replacement admission was requested.`);
237
467
  }
238
468
  }
239
469
 
@@ -107,3 +107,24 @@ export function modeLine(row) {
107
107
  if (row.reason) parts.push(row.reason);
108
108
  return `${row.name}: ${parts.join(', ')}.`;
109
109
  }
110
+
111
+ // The server's FIFO queue for hosted runs (game_tracker fix/hosted-capacity-and-reaper).
112
+ // ASSUMED field names, read in this one place until that branch's contract lands:
113
+ // `queue: { position: <whole number, 1 is next>, estimatedStartAt: <ISO time or null> }`
114
+ // on the admission acknowledgement and on GET /hosted/runs/:admissionId.
115
+ // Position 0, or an estimate already past, reads as starting now.
116
+ export function queueInfo(source) {
117
+ const q = source?.queue;
118
+ if (!q || typeof q !== 'object' || !Number.isSafeInteger(q.position) || q.position < 0) return null;
119
+ const at = typeof q.estimatedStartAt === 'string' ? Date.parse(q.estimatedStartAt) : NaN;
120
+ return { position: q.position, estimatedStartAt: Number.isFinite(at) ? new Date(at).toISOString() : null };
121
+ }
122
+
123
+ /** "Queued, position 2, expected to start in about 14 minutes." or "Queued, starting now." */
124
+ export function queueLine(queue, now = Date.now()) {
125
+ if (!queue) return null;
126
+ const minutes = queue.estimatedStartAt === null ? null : Math.ceil((Date.parse(queue.estimatedStartAt) - Number(now)) / 60000);
127
+ if (queue.position === 0 || minutes !== null && minutes <= 0) return 'Queued, starting now.';
128
+ const eta = minutes === null ? '' : `, expected to start in about ${minutes} minute${minutes === 1 ? '' : 's'}`;
129
+ return `Queued, position ${queue.position}${eta}.`;
130
+ }