ravensight-playtest 0.11.0 → 0.12.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 (63) hide show
  1. package/README.md +89 -21
  2. package/addons/mobile/Host/AppDelegate.swift +11 -0
  3. package/addons/mobile/RavensightMobile.xcodeproj/project.pbxproj +398 -0
  4. package/addons/mobile/RavensightMobile.xcodeproj/project.xcworkspace/contents.xcworkspacedata +7 -0
  5. package/addons/mobile/RavensightMobile.xcodeproj/xcshareddata/xcschemes/RavensightMobile.xcscheme +116 -0
  6. package/addons/mobile/UITests/MobileInputTests.swift +152 -0
  7. package/addons/mobile/project.yml +45 -0
  8. package/docs/ADAPTERS.md +5 -4
  9. package/docs/MOBILE.md +107 -0
  10. package/docs/NATIVE_RUNNER.md +7 -3
  11. package/docs/godot-driver.md +1 -1
  12. package/package.json +7 -5
  13. package/src/api/README.md +3 -3
  14. package/src/cli.js +36 -6
  15. package/src/commands/check.js +17 -3
  16. package/src/commands/device.js +64 -0
  17. package/src/commands/fakeCore.js +1 -1
  18. package/src/commands/hosted.js +16 -13
  19. package/src/commands/login.js +1 -1
  20. package/src/commands/run.js +39 -11
  21. package/src/dashboard.js +2 -3
  22. package/src/detect.js +17 -0
  23. package/src/fsutil.js +1 -1
  24. package/src/hosted/archivePreflight.js +3 -3
  25. package/src/hosted/buildUpload.js +8 -7
  26. package/src/hosted/recordedRun.js +19 -3
  27. package/src/run/anygame/index.js +9 -3
  28. package/src/run/args.js +6 -0
  29. package/src/run/budgetReserve.js +29 -9
  30. package/src/run/claimProtocol.js +27 -0
  31. package/src/run/completion.js +86 -0
  32. package/src/run/context.js +2 -2
  33. package/src/run/drivers/android.js +3 -0
  34. package/src/run/drivers/godot.js +1 -1
  35. package/src/run/drivers/index.js +4 -0
  36. package/src/run/drivers/ios.js +3 -0
  37. package/src/run/drivers/mobile/adb.js +91 -0
  38. package/src/run/drivers/mobile/attempt.js +18 -0
  39. package/src/run/drivers/mobile/crash.js +115 -0
  40. package/src/run/drivers/mobile/frame.js +64 -0
  41. package/src/run/drivers/mobile/ios-helper.js +102 -0
  42. package/src/run/drivers/mobile/lock.js +32 -0
  43. package/src/run/drivers/mobile/native.js +227 -0
  44. package/src/run/drivers/mobile/preflight.js +80 -0
  45. package/src/run/drivers/mobile/process.js +57 -0
  46. package/src/run/drivers/mobile/recording.js +88 -0
  47. package/src/run/drivers/mobile/screenshot.js +34 -0
  48. package/src/run/drivers/mobile/simctl.js +60 -0
  49. package/src/run/drivers/mobile/target.js +53 -0
  50. package/src/run/honesty.js +66 -26
  51. package/src/run/inputMeasurement.js +49 -0
  52. package/src/run/model.js +24 -31
  53. package/src/run/paths.js +1 -1
  54. package/src/run/personaLoop.js +282 -74
  55. package/src/run/proxyClient.js +173 -0
  56. package/src/run/repoTools.js +1 -1
  57. package/src/run/report.js +19 -0
  58. package/src/run/resume.js +33 -4
  59. package/src/run/screenshots.js +3 -1
  60. package/src/run/tools.js +31 -5
  61. package/src/run/usage.js +2 -2
  62. package/src/upload/allowlist.js +2 -2
  63. package/src/upload/index.js +9 -9
package/src/run/args.js CHANGED
@@ -15,6 +15,10 @@ const VALUED = new Map([
15
15
  ['--personas', 'personas'],
16
16
  ['--driver', 'driver'],
17
17
  ['--driver-config', 'driverConfig'],
18
+ ['--native-build', 'nativeBuild'],
19
+ ['--device', 'device'],
20
+ ['--package', 'package'],
21
+ ['--bundle-id', 'bundleId'],
18
22
  ['--controller', 'controller'],
19
23
  ['--compare-with', 'compareWith'],
20
24
  ['--build-url', 'buildUrl'],
@@ -54,6 +58,8 @@ const BOOLEAN = new Map([
54
58
  // playwright_web only: a phone sized screen played with touch (taps, finger
55
59
  // drags, a two finger pinch) and no mouse.
56
60
  ['--phone', 'phone'],
61
+ ['--portrait', 'portrait'],
62
+ ['--landscape', 'landscape'],
57
63
  // The older name for --upload-step-log; both send the step log whatever the project config says.
58
64
  ['--upload-transcript', 'uploadTranscript'],
59
65
  ['--upload-step-log', 'uploadTranscript'],
@@ -1,11 +1,11 @@
1
- import { OUTPUT_WEIGHT } from './usage.js';
1
+ import { CACHE_WRITE_WEIGHT, OUTPUT_WEIGHT } from './usage.js';
2
2
 
3
3
  /**
4
4
  * Keeping enough of a run's model budget back to write its report.
5
5
  *
6
6
  * The proxy reserves each call's pessimistic projection before sending it:
7
- * the whole request body at the full input rate (characters / 3.5) plus the
8
- * output ceiling at the output rate. A call whose projection does not fit
7
+ * measured text (characters / 3.5), each image's advertised reserve units, and the output
8
+ * ceiling at the output rate. A call whose projection does not fit
9
9
  * what is left of the run's budget is refused with 402 before anything is
10
10
  * sent. The server's own warning comes at 80 percent of the budget, counting
11
11
  * the call being made, and in the October 26 runs it never came: one act
@@ -39,12 +39,26 @@ export const FLAT_MARGIN_RATIO = 0.03;
39
39
  /**
40
40
  * The proxy's projection of a request, in input-token units.
41
41
  *
42
- * @param {number} bodyChars the request's JSON length
42
+ * The proxy reserves the whole input (text and images) as if it were all
43
+ * written to the prompt cache, at the cache write premium, because a cache
44
+ * miss bills it that way. A unit here is one input token at the plain rate
45
+ * (./usage.js), so the input side is weighted the same. Before 0.12.0 the
46
+ * client counted it at the plain rate; a screenshot's base64 length hid the
47
+ * gap, and an image counted at its reserve units no longer does.
48
+ *
49
+ * @param {number} bodyChars the request's UTF-8 JSON length
43
50
  * @param {number} maxTokens its output ceiling
51
+ * @param {number} imageUnits image reserve units from the advertised measurement rule
44
52
  * @returns {number}
45
53
  */
46
- export function projectionUnits(bodyChars, maxTokens) {
47
- return Math.max(0, Number(bodyChars) || 0) / CHARS_PER_INPUT_TOKEN + Math.max(0, Number(maxTokens) || 0) * OUTPUT_WEIGHT;
54
+ export function projectionUnits(bodyChars, maxTokens, imageUnits = 0) {
55
+ const input = Math.max(0, Number(bodyChars) || 0) / CHARS_PER_INPUT_TOKEN + Math.max(0, Number(imageUnits) || 0);
56
+ return input * CACHE_WRITE_WEIGHT + Math.max(0, Number(maxTokens) || 0) * OUTPUT_WEIGHT;
57
+ }
58
+
59
+ /** A request's JSON size in UTF-8 bytes, the unit the proxy measures text in. */
60
+ export function requestBytes(body) {
61
+ return Buffer.byteLength(JSON.stringify(body));
48
62
  }
49
63
 
50
64
  /**
@@ -56,18 +70,21 @@ export function projectionUnits(bodyChars, maxTokens) {
56
70
  * @param {number} args.actChars the next act request's JSON length
57
71
  * @param {number} args.actMaxTokens
58
72
  * @param {number} args.actCostUnits what an act turn has really cost, at most, lately
73
+ * @param {boolean} [args.actUncached] the next act turn cannot read the prompt cache
74
+ * (its tools differ), so it costs its whole projection, not a recent cached turn
59
75
  * @param {number} args.reportChars the report request's JSON length if it were sent now
60
76
  * @param {number} args.reportMaxTokens
61
77
  * @returns {{stop: boolean, known: boolean, figures: Object}}
62
78
  */
63
- export function reserveDecision({ usdMax, spend, actChars, actMaxTokens, actCostUnits, reportChars, reportMaxTokens }) {
79
+ export function reserveDecision({ usdMax, spend, actChars, actImageUnits = 0, actMaxTokens, actCostUnits, actUncached = false, reportChars, reportMaxTokens }) {
64
80
  const max = Number(usdMax);
65
81
  if (!Number.isFinite(max) || max <= 0 || !spend || !Number.isFinite(spend.usdPerUnit) || spend.usdPerUnit <= 0) {
66
82
  return { stop: false, known: false, figures: {} };
67
83
  }
68
84
  const price = spend.usdPerUnit;
69
- const actProjected = price * projectionUnits(actChars, actMaxTokens);
70
- const actCost = price * Math.max(0, Number(actCostUnits) || 0) * ACT_COST_MARGIN;
85
+ const actProjected = price * projectionUnits(actChars, actMaxTokens, actImageUnits);
86
+ const recentCost = price * Math.max(0, Number(actCostUnits) || 0) * ACT_COST_MARGIN;
87
+ const actCost = actUncached ? Math.max(recentCost, actProjected) : recentCost;
71
88
  const reportProjected = price * projectionUnits(reportChars, reportMaxTokens) * REPORT_RESERVE_MARGIN;
72
89
  const flat = max * FLAT_MARGIN_RATIO;
73
90
  // The act turn itself has to be admitted, and after it the report has to be.
@@ -78,6 +95,9 @@ export function reserveDecision({ usdMax, spend, actChars, actMaxTokens, actCost
78
95
  stop: !actFits || !reportFitsAfter,
79
96
  known: true,
80
97
  figures: {
98
+ stop_reason: !actFits && !reportFitsAfter ? 'act_projection_and_report_reserve' : !actFits ? 'act_projection' : !reportFitsAfter ? 'report_reserve' : null,
99
+ act_fits: actFits,
100
+ report_fits_after: reportFitsAfter,
81
101
  usd_max: round(max),
82
102
  usd_spent: round(spend.usd),
83
103
  act_projected_usd: round(actProjected),
@@ -0,0 +1,27 @@
1
+ // Local request formatting only. Shared claim words, truth rules and the judge
2
+ // stay unchanged; a protocol repair is never evidence that a claim is true.
3
+ import { CLAIM_SYSTEM, claimRead } from './claimwords.js';
4
+
5
+ const FAULT_ANSWERS = Object.freeze(['at_fault', 'as_designed', 'shows_opposite', 'cannot_tell']);
6
+ const PLAIN_ANSWERS = Object.freeze(['shows_it', 'shows_opposite', 'cannot_tell']);
7
+ const faultQuestion = question => ['fault', 'absence', 'layout'].includes(question);
8
+
9
+ export const CLAIM_FAULT_SYSTEM = 'You check playtest findings against their evidence. You are shown one frame from the session and one claim about the game at that moment. A red box, when there is one, marks where the input landed. Answer the question under the claim with exactly one of its answers: "game at fault", "as designed", "shows the opposite", or "cannot tell". Use the meanings and evidence requirements in that question. Seeing a fact described by a claim does not by itself establish that the game is at fault. A frame that merely does not contradict the claim is "cannot tell". After "as designed:" you may quote the game\'s message as that question permits. Give no other explanation.';
10
+
11
+ export const MAX_CLAIM_REPLY_TEXT = 1024;
12
+ export const claimCheckSystem = question => faultQuestion(question) ? CLAIM_FAULT_SYSTEM : CLAIM_SYSTEM;
13
+
14
+ /** A recognized answer must also belong to the question that was asked. */
15
+ export function claimReply(question, text, toolUses = []) {
16
+ const says = claimRead(text);
17
+ const allowed = faultQuestion(question) ? FAULT_ANSWERS : PLAIN_ANSWERS;
18
+ const reason = toolUses.length ? 'unexpected_tool_call' : !says ? 'unrecognized_answer' : !allowed.includes(says) ? 'answer_not_allowed_for_question' : null;
19
+ return { says, valid: reason === null, reason };
20
+ }
21
+
22
+ export function claimFormatRepair(question) {
23
+ const answers = faultQuestion(question)
24
+ ? '"game at fault", "as designed", "shows the opposite", or "cannot tell"'
25
+ : '"shows it", "shows the opposite", or "cannot tell"';
26
+ return `Your previous reply did not use the answer format allowed by this question. Answer the same question about the same image using exactly one of: ${answers}. Use the original question's definitions. Do not infer a fault merely from seeing the stated fact, add facts, or assume the claim is true. If the evidence does not settle the question, answer "cannot tell". Do not call tools. This is the only format repair.`;
27
+ }
@@ -0,0 +1,86 @@
1
+ /** A completion statement ends play; it never establishes a proof or a finding. */
2
+ export const COMPLETION_PREFIX = 'BRIEF_COMPLETE:';
3
+ export const MAX_COMPLETION_TEXT = 12000;
4
+
5
+ // A deliberate marker may follow prose or Markdown. A quoted screen label is
6
+ // not a completion attempt. Bound both the search and the JSON scan.
7
+ function completionObject(text) {
8
+ const marker = /(?:^|[\s*#>`_])BRIEF_COMPLETE:/.exec(text.slice(0, MAX_COMPLETION_TEXT));
9
+ if (!marker) return undefined;
10
+ if (text.length > MAX_COMPLETION_TEXT) return null;
11
+ const start = text.indexOf('{', marker.index + marker[0].length);
12
+ if (start < 0) return null;
13
+ let depth = 0;
14
+ let quoted = false;
15
+ let escaped = false;
16
+ for (let i = start; i < text.length; i += 1) {
17
+ const char = text[i];
18
+ if (quoted) {
19
+ if (escaped) escaped = false;
20
+ else if (char === '\\') escaped = true;
21
+ else if (char === '"') quoted = false;
22
+ } else if (char === '"') quoted = true;
23
+ else if (char === '{') depth += 1;
24
+ else if (char === '}' && --depth === 0) {
25
+ try { return JSON.parse(text.slice(start, i + 1)); } catch { return null; }
26
+ }
27
+ }
28
+ return null;
29
+ }
30
+
31
+ /** One line per criterion; remove list markers, never numeric requirements. */
32
+ export function completionCriteria(brief) {
33
+ const fields = brief?.fields || brief || {};
34
+ if (typeof fields.success_criteria !== 'string') return [];
35
+ return fields.success_criteria.split('\n').map(line => line.trim().replace(/^(?:[-*]\s+|\d+[.)]\s+)/, '').trim()).filter(Boolean)
36
+ .map((text, index) => ({ id: `sc_${index + 1}`, text }));
37
+ }
38
+
39
+ /** Fixed instructions, sent only when the user supplied concrete criteria. */
40
+ export function completionPrompt(criteria, minimumActions) {
41
+ if (!criteria.length) return '';
42
+ return [
43
+ 'Completing this brief:',
44
+ ...criteria.map(criterion => `${criterion.id}: ${criterion.text}`),
45
+ `After at least ${minimumActions} counted actions, when ALL of these criteria and their requested verification have been observed, stop with no tool call. Use ${COMPLETION_PREFIX} followed by JSON: {"criteria":[{"id":"sc_1","steps":[12],"observed":"what that screen showed"}]}. Include every listed criterion exactly once; steps are the actual step numbers printed on the observations, and observed is a concise account of the visible evidence. Do not invent steps or claim an unverified result.`,
46
+ 'Finishing one level or only part of the brief is not completion. Until the criteria are met, keep exploring in scope. Once the requested end state and verification are complete, preserve that state: do not deliberately lose, erase progress, start over or leave the task merely to use the remaining action budget. The report separately evaluates these claims; this stopping statement does not certify success.'
47
+ ].join('\n');
48
+ }
49
+
50
+ /**
51
+ * Recognize a deliberate completion claim with references the run really has.
52
+ * This checks shape and provenance, not whether an image proves the assertion.
53
+ * That judgement remains with the existing report/claim pipeline and review.
54
+ */
55
+ export function completionClaim({ text, criteria, observations, actions, minimumActions }) {
56
+ if (typeof text !== 'string') return null;
57
+ const value = completionObject(text);
58
+ if (value === undefined) return null;
59
+ const refuse = reason => ({ accepted: false, reason });
60
+ if (!criteria.length) return refuse('no_explicit_criteria');
61
+ if (actions < minimumActions) return refuse('session_minimum_not_met');
62
+ if (value === null) return refuse('invalid_completion_shape');
63
+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => key !== 'criteria')
64
+ || !Array.isArray(value.criteria) || value.criteria.length !== criteria.length) return refuse('criteria_incomplete');
65
+ const required = new Set(criteria.map(row => row.id));
66
+ const seen = new Set();
67
+ const knownSteps = new Set(observations.filter(row => !row.driver_error && Number.isSafeInteger(row.step) && row.step >= 0).map(row => row.step));
68
+ for (const row of value.criteria) {
69
+ if (!row || typeof row !== 'object' || Array.isArray(row) || Object.keys(row).some(key => !['id', 'steps', 'observed'].includes(key))
70
+ || !required.has(row.id) || seen.has(row.id)) return refuse('criteria_incomplete');
71
+ if (typeof row.observed !== 'string' || !row.observed.trim() || row.observed.length > 1000
72
+ || !Array.isArray(row.steps) || row.steps.length === 0 || row.steps.length > 20
73
+ || row.steps.some(step => !Number.isSafeInteger(step) || !knownSteps.has(step))) return refuse('evidence_not_observed');
74
+ seen.add(row.id);
75
+ }
76
+ return { accepted: true, criteria: value.criteria };
77
+ }
78
+
79
+ /** One formatting turn, without tools or new gameplay observations. */
80
+ export function completionRepairPrompt(criteria, reason) {
81
+ return [
82
+ `Your explicit completion statement could not be validated (${reason}). This is the one formatting repair, not a request to continue playing. Do not call tools or send gameplay input. Do not invent accomplishments, observations or step references.`,
83
+ `Reformat your existing account as ${COMPLETION_PREFIX} {"criteria":[{"id":"sc_1","steps":[12],"observed":"what the existing observation showed"}]}. Include every criterion exactly once, with its actual observed step references and a concise visible account. Required criteria: ${JSON.stringify(criteria)}.`,
84
+ 'If the existing observations do not support this account, say so. Play will end without further input even if the account remains invalid; the report and independent review decide what was actually verified. This repair never certifies success.'
85
+ ].join('\n');
86
+ }
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Two independent ceilings:
5
5
  *
6
- * 1. **Images.** `routing.json`'s `persona_playtest.act` sets
6
+ * 1. **Images.** The server routing table's `persona_playtest.act` sets
7
7
  * `max_images: 1`, and the proxy counts image blocks across the WHOLE
8
8
  * `messages` array and answers 400 `too_many_images` past that. So the
9
9
  * ceiling is on the context, not on the newest turn: exactly one image
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * The brief asked for at most two images per call. One is what the
16
16
  * server actually allows on this step, and a body with two comes back
17
- * 400 with nothing played, so this file follows routing.json. It is a
17
+ * 400 with nothing played, so this file follows the server routing table. It is a
18
18
  * constant rather than a literal so that a routing change is a one line
19
19
  * change here, and `shrinkImages` exists so a caller that meets
20
20
  * `too_many_images` anyway can retry smaller instead of failing the run.
@@ -0,0 +1,3 @@
1
+ import { createMobileDriver } from './mobile/native.js';
2
+ export function createAndroidDriver(options = {}) { return createMobileDriver({ ...options, name: 'android_driver' }); }
3
+ export default createAndroidDriver;
@@ -183,7 +183,7 @@ export function holdWallMs(holdMs, scale = 1) {
183
183
  *
184
184
  * Godot needs a real environment to start, but it is also running the
185
185
  * customer's game code, and that code has no business seeing the developer's
186
- * ANTHROPIC_API_KEY, RAVENSIGHT_TOKEN, cloud credentials or CI secrets. So the
186
+ * model provider API keys, RAVENSIGHT_TOKEN, cloud credentials or CI secrets. So the
187
187
  * environment is built from this list rather than inherited wholesale. Names are
188
188
  * matched case insensitively, because Windows environment blocks are.
189
189
  */
@@ -1,3 +1,5 @@
1
+ import { createAndroidDriver } from './android.js';
2
+ import { createIosDriver } from './ios.js';
1
3
  import { assertDriver, DriverError } from './driver.js';
2
4
  import { createWebDriver } from './web.js';
3
5
  import { createWebDriverAdapter, WEBDRIVER_NAMES } from './webdriver.js';
@@ -21,6 +23,8 @@ export const DRIVERS = Object.freeze(['playwright_web', 'godot_driver', 'cli_std
21
23
  * @returns {Promise<Object>} a driver satisfying ./driver.js
22
24
  */
23
25
  export async function createDriver(name, options = {}) {
26
+ if (name === 'android_driver' && options.mode !== 'webdriver') return assertDriver(createAndroidDriver(options), name);
27
+ if (name === 'ios_driver' && options.mode !== 'webdriver') return assertDriver(createIosDriver(options), name);
24
28
  if (WEBDRIVER_NAMES.includes(name)) return assertDriver(createWebDriverAdapter({...options,name}),name);
25
29
  const load = options.importer || (specifier => import(specifier));
26
30
  switch (name) {
@@ -0,0 +1,3 @@
1
+ import { createMobileDriver } from './mobile/native.js';
2
+ export function createIosDriver(options = {}) { return createMobileDriver({ ...options, name: 'ios_driver' }); }
3
+ export default createIosDriver;
@@ -0,0 +1,91 @@
1
+ import { readdir, stat } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { command, sdkTool, sdkRoot, sleep, startProcess } from './process.js';
4
+ import { validateNativeId } from './target.js';
5
+
6
+ export function parseAdbDevices(text) {
7
+ return text.split('\n').filter(line => !line.startsWith('List ') && line.trim()).map(line => {
8
+ const [id, state, ...details] = line.trim().split(/\s+/);
9
+ return { platform: 'android', id, state, name: details.find(x => x.startsWith('model:'))?.slice(6) || id, emulator: id.startsWith('emulator-') };
10
+ });
11
+ }
12
+ export function parseApkBadging(text) {
13
+ const packageId = /package: name='([^']+)'/.exec(text)?.[1];
14
+ const activity = /launchable-activity: name='([^']+)'/.exec(text)?.[1];
15
+ if (!packageId || !activity) throw new Error('The APK has no package or launchable activity. Build an installable debug APK.');
16
+ validateNativeId(packageId);
17
+ if (!/^[A-Za-z0-9_.$]+$/.test(activity)) throw new Error('The APK launch activity is invalid.');
18
+ const abi = /native-code:\s*(.*)/.exec(text)?.[1]?.match(/'[^']+'/g)?.map(x => x.slice(1, -1)) || [];
19
+ return { packageId, activity, abi };
20
+ }
21
+ export function createAdb({ run = command, env = process.env } = {}) {
22
+ const binary = () => sdkTool('adb', env);
23
+ const call = async (serial, args, options) => run(await binary(), [...(serial ? ['-s', serial] : []), ...args], options);
24
+ return {
25
+ binary, call,
26
+ async list() {
27
+ const devices = parseAdbDevices(await call(null, ['devices', '-l']));
28
+ for (const device of devices.filter(d => d.emulator && d.state === 'device')) {
29
+ device.avd = await call(device.id, ['emu', 'avd', 'name']).then(x => x.split('\n')[0].trim()).catch(() => null);
30
+ }
31
+ return devices;
32
+ },
33
+ async avds() { return (await run(await sdkTool('emulator', env), ['-list-avds'], { timeout: 10000 })).split('\n').filter(Boolean); },
34
+ async inspect(file) {
35
+ if (!file || path.extname(file).toLowerCase() !== '.apk' || !(await stat(file).catch(() => null))?.isFile()) throw new Error('Pass --native-build with an existing Android .apk file.');
36
+ let aapt = env.RAVENSIGHT_AAPT;
37
+ if (!aapt) {
38
+ const root = path.join(sdkRoot(env), 'build-tools');
39
+ const versions = await readdir(root).catch(() => []);
40
+ for (const version of versions.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))) {
41
+ const candidate = path.join(root, version, process.platform === 'win32' ? 'aapt.exe' : 'aapt');
42
+ if (await stat(candidate).catch(() => null)) { aapt = candidate; break; }
43
+ }
44
+ }
45
+ if (!aapt) throw new Error('Android build-tools (aapt) are missing. Install SDK build-tools or set RAVENSIGHT_AAPT.');
46
+ return parseApkBadging(await run(aapt, ['dump', 'badging', file], { timeout: 20000 }));
47
+ },
48
+ async boot(name, { signal } = {}) {
49
+ if (!(await this.avds()).includes(name)) throw new Error(`No Android virtual device named ${name}. Run device list.`);
50
+ const existing = (await this.list()).find(d => d.avd === name);
51
+ if (existing) { await this.waitBoot(existing.id, { signal }); return { ...existing, owned: false }; }
52
+ const process = startProcess(await sdkTool('emulator', env), ['-avd', name, '-no-snapshot-save']);
53
+ const until = Date.now() + 180000;
54
+ while (Date.now() < until) {
55
+ if (process.child.exitCode !== null) throw new Error(`Emulator failed to start: ${process.diagnostic()}`);
56
+ const device = (await this.list()).find(d => d.avd === name);
57
+ if (device) { await this.waitBoot(device.id, { signal }); return { ...device, owned: true }; }
58
+ await sleep(1000, signal);
59
+ }
60
+ process.child.kill('SIGTERM');
61
+ throw new Error('Android emulator boot timed out after 180 seconds.');
62
+ },
63
+ async waitBoot(serial, { signal, timeout = 120000 } = {}) {
64
+ const end = Date.now() + timeout;
65
+ while (Date.now() < end) {
66
+ if (await call(serial, ['shell', 'getprop', 'sys.boot_completed'], { signal, timeout: 5000 }).catch(() => '') === '1') return;
67
+ await sleep(500, signal);
68
+ }
69
+ throw new Error(`Android device ${serial} did not finish booting.`);
70
+ },
71
+ async select(wanted, { boot = false, signal } = {}) {
72
+ if (!wanted) throw new Error('Pass --device with an emulator serial or AVD name. Native play never takes over an unselected device.');
73
+ const all = await this.list();
74
+ let found = wanted ? all.filter(d => d.id === wanted || d.avd === wanted) : all.filter(d => d.state === 'device' && d.emulator);
75
+ if (!found.length && wanted && boot && (await this.avds()).includes(wanted)) found = [await this.boot(wanted, { signal })];
76
+ if (found.length !== 1) throw new Error(found.length ? 'Several Android devices match. Pass --device with an exact emulator serial or AVD name.' : 'No matching Android emulator is running. Run device boot <AVD> --platform android.');
77
+ if (!found[0].emulator) throw new Error('This native driver currently supports Android emulators only.');
78
+ if (found[0].state !== 'device') throw new Error(`Android device ${found[0].id} is ${found[0].state}.`);
79
+ await this.waitBoot(found[0].id, { signal });
80
+ return found[0];
81
+ },
82
+ async abi(serial) { return (await call(serial, ['shell', 'getprop', 'ro.product.cpu.abilist'])).split(','); },
83
+ async shutdown(serial) { await call(serial, ['emu', 'kill']); }
84
+ };
85
+ }
86
+
87
+ export function quoteAndroidText(value) {
88
+ const text = String(value);
89
+ if (!text || text.length > 2000 || /[^\x20-\x7e]|%/.test(text)) throw new Error('Android text entry currently accepts 1 to 2000 printable ASCII characters without percent signs.');
90
+ return `'${text.replace(/ /g, '%s').replace(/'/g, `'\\''`)}'`;
91
+ }
@@ -0,0 +1,18 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+
5
+ /** Preserve an interrupted native attempt whole, including relative evidence refs. */
6
+ export async function archiveNativeAttempt(directory) {
7
+ const info = await fs.lstat(directory).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
8
+ if (!info) return null;
9
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error('The native run evidence path must be a local directory.');
10
+ if (!(await fs.readdir(directory)).length) return null;
11
+ const job = path.dirname(path.dirname(directory));
12
+ const destination = path.join(job, 'native-attempts', path.basename(directory), `${Date.now()}-${randomUUID()}`);
13
+ await fs.mkdir(path.dirname(destination), { recursive: true });
14
+ // Rename preserves the complete attempt atomically. No previous media, report,
15
+ // transcript or screenshot is silently reused in the new playthrough.
16
+ await fs.rename(directory, destination);
17
+ return path.relative(job, destination).split(path.sep).join('/');
18
+ }
@@ -0,0 +1,115 @@
1
+ import fs from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { createHash } from 'node:crypto';
6
+
7
+ const REPORT_BYTES = 8 * 1024 * 1024;
8
+ const MAX_CANDIDATES = 20;
9
+ const FATAL_TYPES = new Set(['EXC_BAD_ACCESS', 'EXC_BAD_INSTRUCTION', 'EXC_ARITHMETIC', 'EXC_BREAKPOINT', 'EXC_CRASH', 'EXC_GUARD']);
10
+ const FATAL_SIGNALS = new Set(['SIGABRT', 'SIGSEGV', 'SIGBUS', 'SIGILL', 'SIGTRAP', 'SIGFPE']);
11
+ const truthy = value => value === true || value === 1 || /^(true|yes|1)$/i.test(String(value));
12
+
13
+ // Apple uses a space before the time and up to six fractional digits in .ips.
14
+ export function crashTime(value) {
15
+ if (typeof value !== 'string') return NaN;
16
+ const normalized = value.replace(/^(\d{4}-\d\d-\d\d) (\d\d:\d\d:\d\d)/, '$1T$2')
17
+ .replace(/(\.\d{3})\d+/, '$1').replace(/\s([+-]\d\d)(\d\d)$/, '$1:$2');
18
+ return Date.parse(normalized);
19
+ }
20
+
21
+ /** Fail closed: an exit alone, stale report or another simulator is not a crash. */
22
+ export function matchIosCrashReport(text, scope, exitObservedAt) {
23
+ if (typeof text !== 'string' || Buffer.byteLength(text) > REPORT_BYTES) return null;
24
+ try {
25
+ const newline = text.indexOf('\n');
26
+ if (newline < 1) return null;
27
+ const header = JSON.parse(text.slice(0, newline)), report = JSON.parse(text.slice(newline + 1));
28
+ if (String(header.bug_type) !== '309' || Number(header.platform) !== 7) return null;
29
+ if (header.bundleID !== scope.bundleId || report.bundleInfo?.CFBundleIdentifier !== scope.bundleId || report.procName !== scope.executable || report.pid !== scope.pid) return null;
30
+ const udid = scope.device.toUpperCase();
31
+ const coalition = report.coalitionName === `com.apple.CoreSimulator.SimDevice.${scope.device}`;
32
+ const simulatorPath = typeof report.procPath === 'string' && report.procPath.toUpperCase().includes(`/CORESIMULATOR/DEVICES/${udid}/`);
33
+ if (!coalition && !simulatorPath) return null;
34
+ // If either identity field names another device, do not accept the other one.
35
+ const pathDevice = typeof report.procPath === 'string' && /\/CoreSimulator\/Devices\/([A-Fa-f0-9-]{36})\//.exec(report.procPath)?.[1];
36
+ const coalitionDevice = typeof report.coalitionName === 'string' && /^com\.apple\.CoreSimulator\.SimDevice\.([A-Fa-f0-9-]{36})$/.exec(report.coalitionName)?.[1];
37
+ if (pathDevice && pathDevice.toUpperCase() !== udid || coalitionDevice && coalitionDevice.toUpperCase() !== udid) return null;
38
+ const launched = crashTime(report.procLaunch), captured = crashTime(report.captureTime);
39
+ // A second of tolerance accommodates timestamp precision, not an older instance.
40
+ if (!Number.isFinite(launched) || !Number.isFinite(captured) || launched < scope.launchStartedAt - 1000 || launched > scope.launchCompletedAt + 1000 || captured < launched || captured < scope.launchStartedAt || captured > exitObservedAt + 1000) return null;
41
+ if (truthy(report.isNonFatal) || truthy(report.isSimulated)) return null;
42
+ if (!FATAL_TYPES.has(report.exception?.type) || !FATAL_SIGNALS.has(report.exception?.signal)) return null;
43
+ const incident = report.incident || header.incident_id;
44
+ if (typeof incident !== 'string' || !/^[A-Fa-f0-9-]{36}$/.test(incident)) return null;
45
+ return {
46
+ schemaVersion: 1, platform: 'ios', kind: 'crashed', device: scope.device,
47
+ bundleId: scope.bundleId, executable: scope.executable, pid: scope.pid, incident,
48
+ launchStartedAt: scope.launchStartedAt, launchCompletedAt: scope.launchCompletedAt,
49
+ processLaunchAt: launched, crashAt: captured, exitObservedAt,
50
+ exception: { type: report.exception.type, signal: report.exception.signal },
51
+ reportSha256: createHash('sha256').update(text).digest('hex')
52
+ };
53
+ } catch { return null; }
54
+ }
55
+
56
+ /** Read only exact executable report candidates. Never emit unrelated host logs. */
57
+ export function createIosCrashTracker({ device, bundleId, executable, pid, launchStartedAt, launchCompletedAt, runDir, reportDirectory = path.join(os.homedir(), 'Library/Logs/DiagnosticReports'), now = Date.now } = {}) {
58
+ executable = path.basename(executable || '');
59
+ if (!/^[A-Fa-f0-9-]{36}$/.test(device || '') || !/^[A-Za-z][A-Za-z0-9_.-]+$/.test(bundleId || '') || !/^[A-Za-z0-9_. -]{1,128}$/.test(executable) || !Number.isSafeInteger(pid) || pid <= 0 || !Number.isFinite(launchStartedAt) || !Number.isFinite(launchCompletedAt) || launchCompletedAt < launchStartedAt || !runDir) throw new Error('The iOS crash tracker needs an exact launch identity.');
60
+ const scope = { device, bundleId, executable, pid, launchStartedAt, launchCompletedAt };
61
+ let pending = null, found = null;
62
+ async function scan(exitObservedAt) {
63
+ const candidates = [];
64
+ let directory;
65
+ try {
66
+ directory = await fs.opendir(reportDirectory);
67
+ let entries = 0;
68
+ for await (const entry of directory) {
69
+ if (++entries > 10000) break;
70
+ if (!entry.isFile() || !entry.name.startsWith(`${executable}-`) || !entry.name.endsWith('.ips')) continue;
71
+ const file = path.join(reportDirectory, entry.name), info = await fs.lstat(file).catch(() => null);
72
+ if (!info?.isFile() || info.isSymbolicLink() || info.size <= 0 || info.size > REPORT_BYTES || info.mtimeMs < launchStartedAt - 1000) continue;
73
+ candidates.push({ file, name: entry.name, modified: info.mtimeMs });
74
+ }
75
+ } catch { return null; }
76
+ for (const candidate of candidates.sort((a, b) => b.modified - a.modified).slice(0, MAX_CANDIDATES)) {
77
+ let handle;
78
+ try {
79
+ handle = await fs.open(candidate.file, constants.O_RDONLY | constants.O_NOFOLLOW);
80
+ const info = await handle.stat();
81
+ if (!info.isFile() || info.size > REPORT_BYTES) continue;
82
+ const buffer = Buffer.alloc(REPORT_BYTES + 1);
83
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
84
+ if (bytesRead > REPORT_BYTES) continue;
85
+ const bytes = buffer.subarray(0, bytesRead);
86
+ const result = matchIosCrashReport(bytes.toString('utf8'), scope, exitObservedAt);
87
+ if (!result) continue;
88
+ const evidencePath = path.join(runDir, 'native-crash.json');
89
+ await fs.mkdir(runDir, { recursive: true });
90
+ await fs.writeFile(evidencePath, JSON.stringify({ ...result, sourceFile: candidate.name }, null, 2) + '\n', { mode: 0o600 });
91
+ const message = `An iOS crash report confirms ${result.exception.type} (${result.exception.signal}) in ${bundleId}.`;
92
+ return { kind: 'crashed', message, log: message, evidencePath, incident: result.incident, pid, exception: result.exception };
93
+ } catch { /* Missing, still-writing, inaccessible or unrecognized reports remain unknown. */ }
94
+ finally { await handle?.close().catch(() => {}); }
95
+ }
96
+ return null;
97
+ }
98
+ return {
99
+ check({ exitObservedAt = now(), timeoutMs = 5000 } = {}) {
100
+ if (found) return Promise.resolve(found);
101
+ if (pending) return pending;
102
+ if (!Number.isFinite(exitObservedAt) || !Number.isFinite(timeoutMs) || timeoutMs < 0) return Promise.resolve(null);
103
+ pending = (async () => {
104
+ const deadline = now() + Math.min(5000, timeoutMs);
105
+ do {
106
+ found = await scan(exitObservedAt);
107
+ if (found || now() >= deadline) return found;
108
+ await new Promise(resolve => setTimeout(resolve, Math.min(200, Math.max(0, deadline - now()))));
109
+ } while (now() <= deadline);
110
+ return null;
111
+ })().finally(() => { pending = null; });
112
+ return pending;
113
+ }
114
+ };
115
+ }
@@ -0,0 +1,64 @@
1
+ import { deflateSync } from 'node:zlib';
2
+ import { decodePng } from '../../pixels.js';
3
+
4
+ const SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
5
+ // Node 22.0 is supported; zlib.crc32 was added in 22.2.
6
+ const CRC_TABLE = Uint32Array.from({ length: 256 }, (_, byte) => {
7
+ let value = byte;
8
+ for (let bit = 0; bit < 8; bit++) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
9
+ return value >>> 0;
10
+ });
11
+ function crc32(bytes) {
12
+ let value = 0xffffffff;
13
+ for (const byte of bytes) value = CRC_TABLE[(value ^ byte) & 255] ^ (value >>> 8);
14
+ return (value ^ 0xffffffff) >>> 0;
15
+ }
16
+ /** Only a fully written, checksum-valid PNG can end a screenshot capture. */
17
+ export function completePng(bytes) {
18
+ if (!Buffer.isBuffer(bytes) || bytes.length < 33 || !bytes.subarray(0, 8).equals(SIGNATURE)) return false;
19
+ let offset = 8;
20
+ while (offset + 12 <= bytes.length) {
21
+ const length = bytes.readUInt32BE(offset), end = offset + 12 + length;
22
+ if (end > bytes.length) return false;
23
+ const kind = bytes.toString('ascii', offset + 4, offset + 8);
24
+ if (bytes.readUInt32BE(offset + 8 + length) !== crc32(bytes.subarray(offset + 4, offset + 8 + length))) return false;
25
+ if (kind === 'IEND') return length === 0 && end === bytes.length && Boolean(decodePng(bytes));
26
+ offset = end;
27
+ }
28
+ return false;
29
+ }
30
+ function chunk(name, body) {
31
+ const type = Buffer.from(name), length = Buffer.alloc(4), crc = Buffer.alloc(4);
32
+ length.writeUInt32BE(body.length); crc.writeUInt32BE(crc32(Buffer.concat([type, body])) >>> 0);
33
+ return Buffer.concat([length, type, body, crc]);
34
+ }
35
+ export function encodeFrame(width, height, rgba) {
36
+ const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(width); ihdr.writeUInt32BE(height, 4); ihdr[8] = 8; ihdr[9] = 6;
37
+ const lines = Buffer.alloc(height * (width * 4 + 1));
38
+ for (let y = 0; y < height; y++) rgba.copy(lines, y * (width * 4 + 1) + 1, y * width * 4, (y + 1) * width * 4);
39
+ return Buffer.concat([SIGNATURE, chunk('IHDR', ihdr), chunk('IDAT', deflateSync(lines, { level: 3 })), chunk('IEND', Buffer.alloc(0))]);
40
+ }
41
+ export function mobileFrame(png, longEdge = 1280) {
42
+ const source = decodePng(png);
43
+ if (!source) throw new Error('The device did not return a supported 8-bit RGB or RGBA PNG screenshot.');
44
+ const scale = Math.min(1, longEdge / Math.max(source.width, source.height));
45
+ const width = Math.max(1, Math.floor(source.width * scale)), height = Math.max(1, Math.floor(source.height * scale));
46
+ if (scale === 1) return { png, width, height, nativeWidth: source.width, nativeHeight: source.height };
47
+ const rgba = Buffer.alloc(width * height * 4);
48
+ // Bilinear filtering preserves small text better than nearest-neighbour scaling.
49
+ for (let y = 0; y < height; y++) {
50
+ const fy = y * source.height / height, y0 = Math.floor(fy), y1 = Math.min(y0 + 1, source.height - 1), ty = fy - y0;
51
+ for (let x = 0; x < width; x++) {
52
+ const fx = x * source.width / width, x0 = Math.floor(fx), x1 = Math.min(x0 + 1, source.width - 1), tx = fx - x0;
53
+ for (let c = 0; c < 4; c++) {
54
+ const at = (xx, yy) => c >= source.channels ? 255 : source.data[(yy * source.width + xx) * source.channels + c];
55
+ rgba[(y * width + x) * 4 + c] = Math.round((at(x0, y0) * (1 - tx) + at(x1, y0) * tx) * (1 - ty) + (at(x0, y1) * (1 - tx) + at(x1, y1) * tx) * ty);
56
+ }
57
+ }
58
+ }
59
+ return { png: encodeFrame(width, height, rgba), width, height, nativeWidth: source.width, nativeHeight: source.height };
60
+ }
61
+ export function devicePoint(point, frame, size = { width: frame?.nativeWidth, height: frame?.nativeHeight }) {
62
+ if (!frame || !point || !Number.isFinite(point.x) || !Number.isFinite(point.y) || point.x < 0 || point.y < 0 || point.x >= frame.width || point.y >= frame.height) throw new Error('Use coordinates inside the most recent screenshot.');
63
+ return { x: Math.min(size.width - 1, Math.round(point.x * size.width / frame.width)), y: Math.min(size.height - 1, Math.round(point.y * size.height / frame.height)) };
64
+ }