agentlane 0.0.0 → 0.4.0-rc.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.
Files changed (146) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/LICENSE +27 -0
  3. package/README.md +167 -2
  4. package/dist/agents/claude-plugin.js +79 -0
  5. package/dist/agents/cli.js +258 -0
  6. package/dist/agents/detect.js +88 -0
  7. package/dist/agents/init.js +251 -0
  8. package/dist/agents/launcher.js +32 -0
  9. package/dist/agents/package.js +119 -0
  10. package/dist/agents/skills.js +59 -0
  11. package/dist/agents/toml.js +325 -0
  12. package/dist/agents/wiring-check.js +117 -0
  13. package/dist/agents/wiring.js +374 -0
  14. package/dist/bench/host.js +104 -0
  15. package/dist/bench/live.js +511 -0
  16. package/dist/bench/mcp-client.js +91 -0
  17. package/dist/bench/model.js +15 -0
  18. package/dist/bench/report.js +162 -0
  19. package/dist/bench/run.js +121 -0
  20. package/dist/bench/schedule.js +140 -0
  21. package/dist/bench/stats.js +59 -0
  22. package/dist/bench-cli.js +167 -0
  23. package/dist/browser/aria.js +184 -0
  24. package/dist/browser/control.js +203 -0
  25. package/dist/browser/env.js +118 -0
  26. package/dist/browser/evidence.js +44 -0
  27. package/dist/browser/install.js +361 -0
  28. package/dist/browser/kinds.js +10 -0
  29. package/dist/browser/lane-browser.js +224 -0
  30. package/dist/browser/libraries.js +56 -0
  31. package/dist/browser/paths.js +29 -0
  32. package/dist/browser/release.js +121 -0
  33. package/dist/browser/screen.js +19 -0
  34. package/dist/browser/signin.js +154 -0
  35. package/dist/browser/stop.js +163 -0
  36. package/dist/browser/tools.js +25 -0
  37. package/dist/cache/build.js +154 -0
  38. package/dist/cache/config.js +186 -0
  39. package/dist/cache/index.js +4 -0
  40. package/dist/cache/key.js +196 -0
  41. package/dist/cache/store.js +303 -0
  42. package/dist/cli.js +178 -0
  43. package/dist/clock.js +4 -0
  44. package/dist/devices/adb.js +160 -0
  45. package/dist/devices/android.js +214 -0
  46. package/dist/devices/backend.js +7 -0
  47. package/dist/devices/bundler.js +46 -0
  48. package/dist/devices/common.js +51 -0
  49. package/dist/devices/controls.js +65 -0
  50. package/dist/devices/dial.js +56 -0
  51. package/dist/devices/emulator.js +396 -0
  52. package/dist/devices/hygiene.js +202 -0
  53. package/dist/devices/index.js +5 -0
  54. package/dist/devices/launch.js +76 -0
  55. package/dist/devices/simctl.js +119 -0
  56. package/dist/devices/tools.js +1 -0
  57. package/dist/devices/variant.js +99 -0
  58. package/dist/devices/xcrun.js +265 -0
  59. package/dist/driver/absence.js +54 -0
  60. package/dist/driver/caller.js +51 -0
  61. package/dist/driver/client.js +312 -0
  62. package/dist/driver/diff.js +180 -0
  63. package/dist/driver/elements.js +70 -0
  64. package/dist/driver/engine-main.js +13 -0
  65. package/dist/driver/engine.js +499 -0
  66. package/dist/driver/errors.js +11 -0
  67. package/dist/driver/exec.js +66 -0
  68. package/dist/driver/failure.js +156 -0
  69. package/dist/driver/flow.js +94 -0
  70. package/dist/driver/idle.js +100 -0
  71. package/dist/driver/images.js +68 -0
  72. package/dist/driver/install.js +272 -0
  73. package/dist/driver/lock.js +101 -0
  74. package/dist/driver/look.js +223 -0
  75. package/dist/driver/maestro-child.js +194 -0
  76. package/dist/driver/maestro-runs.js +46 -0
  77. package/dist/driver/paths.js +105 -0
  78. package/dist/driver/pixels.js +144 -0
  79. package/dist/driver/plan.js +108 -0
  80. package/dist/driver/release.js +7 -0
  81. package/dist/driver/runner.js +42 -0
  82. package/dist/driver/selector.js +91 -0
  83. package/dist/driver/session.js +474 -0
  84. package/dist/driver/suggest.js +86 -0
  85. package/dist/driver/supervisor.js +251 -0
  86. package/dist/driver/tree.js +426 -0
  87. package/dist/driver-cli.js +865 -0
  88. package/dist/evidence/device.js +177 -0
  89. package/dist/evidence/evidence.js +304 -0
  90. package/dist/evidence/files.js +92 -0
  91. package/dist/hooks/env.js +81 -0
  92. package/dist/hooks/run.js +101 -0
  93. package/dist/mcp/server.js +69 -0
  94. package/dist/mcp/tools.js +246 -0
  95. package/dist/name.js +22 -0
  96. package/dist/plugin/aims.js +465 -0
  97. package/dist/plugin/conventions.js +73 -0
  98. package/dist/plugin/guard.js +163 -0
  99. package/dist/plugin/hook-cli.js +216 -0
  100. package/dist/plugin/session-name.js +28 -0
  101. package/dist/plugin/shell.js +254 -0
  102. package/dist/processes.js +77 -0
  103. package/dist/project/config.js +316 -0
  104. package/dist/project/schema.js +335 -0
  105. package/dist/project/validate.js +224 -0
  106. package/dist/registry/config.js +142 -0
  107. package/dist/registry/format.js +22 -0
  108. package/dist/registry/owner.js +265 -0
  109. package/dist/registry/paths.js +50 -0
  110. package/dist/registry/ports.js +26 -0
  111. package/dist/registry/prune.js +160 -0
  112. package/dist/registry/refusal.js +53 -0
  113. package/dist/registry/registry.js +1027 -0
  114. package/dist/registry/resources.js +117 -0
  115. package/dist/registry/rows.js +115 -0
  116. package/dist/registry/status.js +85 -0
  117. package/dist/registry/store.js +274 -0
  118. package/dist/registry/types.js +1 -0
  119. package/dist/registry-cli.js +544 -0
  120. package/dist/services/services.js +268 -0
  121. package/dist/services/system.js +189 -0
  122. package/dist/up/deps.js +1 -0
  123. package/dist/up/doctor.js +424 -0
  124. package/dist/up/exec.js +133 -0
  125. package/dist/up/lane-files.js +75 -0
  126. package/dist/up/lane-services.js +38 -0
  127. package/dist/up/maestro-env.js +172 -0
  128. package/dist/up/preflight.js +232 -0
  129. package/dist/up/release.js +148 -0
  130. package/dist/up/resources.js +178 -0
  131. package/dist/up/restart.js +87 -0
  132. package/dist/up/setup.js +28 -0
  133. package/dist/up/up.js +610 -0
  134. package/dist/up-cli.js +258 -0
  135. package/dist/usage.js +16 -0
  136. package/package.json +58 -3
  137. package/schema/agentlane.schema.json +675 -0
  138. package/skills/create-verification-skill/LICENSE +21 -0
  139. package/skills/create-verification-skill/SKILL.md +88 -0
  140. package/skills/dev-loop/LICENSE +21 -0
  141. package/skills/dev-loop/SKILL.md +61 -0
  142. package/skills/device/SKILL.md +8 -0
  143. package/skills/drive/SKILL.md +64 -0
  144. package/skills/maintain-verification-skill/LICENSE +21 -0
  145. package/skills/maintain-verification-skill/SKILL.md +42 -0
  146. package/skills/setup/SKILL.md +80 -0
@@ -0,0 +1,156 @@
1
+ import { parseFlow, stepAtLine } from "./flow.js";
2
+ import { look } from "./look.js";
3
+ import { selectorsOfStep, selectorYaml } from "./selector.js";
4
+ import { suggestSelectors } from "./suggest.js";
5
+ const PREFIXES = [/^Failed to run flow:\s*/, /^kotlin\.Unit\s+/, /^java\.lang\.IllegalStateException:\s*/];
6
+ export function cleanMessage(error) {
7
+ let message = error.trim();
8
+ for (const prefix of PREFIXES)
9
+ message = message.replace(prefix, '');
10
+ return message;
11
+ }
12
+ const FILE_POSITION = /\.ya?ml:(\d+):(\d+)/;
13
+ const INVALID_FLOW = /^(Parsing Failed|Invalid Command|Config Section Required|Incorrect Format|Unknown Property|Missing required)/;
14
+ const DEVICE_ERROR = /An error was encountered processing the command|Simulator device failed to/;
15
+ function kindOf(message) {
16
+ if (INVALID_FLOW.test(message) || (FILE_POSITION.test(message) && !message.startsWith('Element not found')))
17
+ return 'invalid-flow';
18
+ if (message.startsWith('Element not found:'))
19
+ return 'selector-miss';
20
+ if (message.startsWith('Assertion is false:'))
21
+ return 'assertion';
22
+ if (DEVICE_ERROR.test(message))
23
+ return 'device-error';
24
+ return 'unknown';
25
+ }
26
+ function selectorFromMessage(message) {
27
+ const notFound = /^Element not found: (.*)$/s.exec(message)?.[1];
28
+ if (notFound !== undefined) {
29
+ const selector = {};
30
+ const index = /, Index: (\d+)$/.exec(notFound);
31
+ const body = index ? notFound.slice(0, index.index) : notFound;
32
+ if (index?.[1] !== undefined)
33
+ selector.index = Number(index[1]);
34
+ const id = /(?:^|, )Id matching regex: (.*?)(?=, Text matching regex: |$)/s.exec(body)?.[1];
35
+ const text = /(?:^|, )Text matching regex: (.*?)(?=, Id matching regex: |$)/s.exec(body)?.[1];
36
+ if (id !== undefined)
37
+ selector.id = id;
38
+ if (text !== undefined)
39
+ selector.text = text;
40
+ return selector.id !== undefined || selector.text !== undefined ? selector : undefined;
41
+ }
42
+ const asserted = /^Assertion is false: "(.*?)"(?:, id: (.*?))? is (?:not )?visible$/s.exec(message);
43
+ if (asserted) {
44
+ const selector = { text: asserted[1] ?? '' };
45
+ if (asserted[2] !== undefined)
46
+ selector.id = asserted[2];
47
+ return selector;
48
+ }
49
+ const idOnly = /^Assertion is false: id: (.*?) is (?:not )?visible$/s.exec(message)?.[1];
50
+ return idOnly === undefined ? undefined : { id: idOnly };
51
+ }
52
+ function sameSelector(a, b) {
53
+ return a.id === b.id && a.text === b.text;
54
+ }
55
+ function locateStep(steps, kind, message, selector) {
56
+ const position = FILE_POSITION.exec(message);
57
+ if (kind === 'invalid-flow')
58
+ return undefined;
59
+ if (position)
60
+ return undefined;
61
+ let candidates = [];
62
+ if (selector) {
63
+ candidates = steps.filter(step => selectorsOfStep(step).some(entry => sameSelector(entry.selector, selector)));
64
+ if (kind === 'assertion') {
65
+ const absent = message.endsWith(' is not visible');
66
+ candidates = candidates.filter(step => selectorsOfStep(step).some(entry => sameSelector(entry.selector, selector) && (entry.expect === 'absent') === absent));
67
+ }
68
+ }
69
+ else if (message.startsWith('Assertion is false:')) {
70
+ candidates = steps.filter(step => step.command === 'assertTrue');
71
+ }
72
+ else if (kind === 'device-error') {
73
+ const launch = message.includes('failed to launch') ? ['launchApp'] : message.includes('failed to open') ? ['openLink'] : [];
74
+ candidates = steps.filter(step => launch.includes(step.command));
75
+ }
76
+ return candidates.length === 1 ? candidates[0] : undefined;
77
+ }
78
+ const REACHED = {
79
+ 'invalid-flow': ['no', 'Maestro rejects a flow it cannot parse before running any step.'],
80
+ 'selector-miss': ['no', 'Maestro looks the element up before acting, and it never found one.'],
81
+ assertion: ['no', 'An assertion only reads the screen.'],
82
+ timeout: ['no', 'A wait only reads the screen.'],
83
+ 'device-error': ['yes', 'The simulator received the command and refused it.'],
84
+ unknown: ['unknown', "Maestro's error doesn't say how far the step got."],
85
+ };
86
+ /** Turns a failed `run` into a structured failure: kind, failing step, reached-device, fresh screen, suggestions. */
87
+ export function buildFailure(input) {
88
+ const message = cleanMessage(input.error);
89
+ const flow = parseFlow(input.flow);
90
+ let kind = kindOf(message);
91
+ if (kind === 'unknown' && flow.error !== undefined)
92
+ kind = 'invalid-flow';
93
+ let selector = selectorFromMessage(message);
94
+ let step;
95
+ if (input.failedStep !== undefined) {
96
+ step = flow.steps[input.failedStep];
97
+ }
98
+ else if (kind === 'invalid-flow') {
99
+ const line = FILE_POSITION.exec(message)?.[1];
100
+ if (line !== undefined && Number(line) > 0) {
101
+ const found = stepAtLine(flow, Number(line));
102
+ if (found && Number(line) >= found.startLine)
103
+ step = found;
104
+ }
105
+ }
106
+ else {
107
+ step = locateStep(flow.steps, kind, message, selector);
108
+ }
109
+ if (!step && flow.steps.length === 1 && input.failedStep === undefined)
110
+ step = flow.steps[0];
111
+ if (kind === 'assertion' && step?.command === 'extendedWaitUntil')
112
+ kind = 'timeout';
113
+ if (step && !selector && kind !== 'invalid-flow') {
114
+ selector = selectorsOfStep(step)[0]?.selector;
115
+ }
116
+ const [reachedDevice, reachedDeviceBecause] = REACHED[kind];
117
+ const missed = (kind === 'selector-miss' || kind === 'timeout' || (kind === 'assertion' && !message.endsWith(' is not visible'))) &&
118
+ selector;
119
+ const screen = input.screen ? look(input.screen, input.look) : undefined;
120
+ return {
121
+ kind,
122
+ message,
123
+ step: step && {
124
+ index: step.index,
125
+ total: flow.steps.length,
126
+ command: step.command,
127
+ yaml: step.source,
128
+ },
129
+ completedSteps: kind === 'invalid-flow' ? 0 : step?.index,
130
+ reachedDevice,
131
+ reachedDeviceBecause,
132
+ selector,
133
+ screen,
134
+ suggestions: missed && input.screen ? suggestSelectors(input.screen, missed) : [],
135
+ };
136
+ }
137
+ export function renderFailure(failure) {
138
+ const lines = [];
139
+ const where = failure.step
140
+ ? `step ${String(failure.step.index + 1)} of ${String(failure.step.total)} (${failure.step.yaml.replace(/^- /, '').replaceAll('\n', ' ').replace(/\s+/g, ' ')})`
141
+ : 'an unknown step';
142
+ lines.push(`Run failed (${failure.kind}) at ${where}: ${failure.message}`);
143
+ const ran = failure.completedSteps === undefined
144
+ ? 'Earlier steps may have run.'
145
+ : `${String(failure.completedSteps)} earlier step${failure.completedSteps === 1 ? '' : 's'} ran.`;
146
+ lines.push(`Reached the device: ${failure.reachedDevice}. ${failure.reachedDeviceBecause} ${ran}`);
147
+ if (failure.suggestions.length > 0) {
148
+ lines.push(`Selectors on screen like ${failure.selector ? selectorYaml(failure.selector) : 'the missed one'}:`);
149
+ for (const suggestion of failure.suggestions) {
150
+ lines.push(` ${suggestion.yaml} ${suggestion.element} (${suggestion.basis})`);
151
+ }
152
+ }
153
+ if (failure.screen)
154
+ lines.push('Screen now:', failure.screen.text);
155
+ return lines.join('\n');
156
+ }
@@ -0,0 +1,94 @@
1
+ import { isMap, isScalar, isSeq, LineCounter, parseAllDocuments, stringify } from 'yaml';
2
+ function isRecord(value) {
3
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
4
+ }
5
+ function commandName(body) {
6
+ if (typeof body === 'string')
7
+ return body;
8
+ if (isRecord(body))
9
+ return Object.keys(body)[0] ?? '';
10
+ return '';
11
+ }
12
+ function stepsByLine(source) {
13
+ const lines = source.split('\n');
14
+ const separator = lines.findLastIndex(line => /^---\s*$/.test(line));
15
+ const steps = [];
16
+ for (let i = separator + 1; i < lines.length; i++) {
17
+ const line = lines[i] ?? '';
18
+ if (!/^-(\s|$)/.test(line))
19
+ continue;
20
+ const previous = steps.at(-1);
21
+ if (previous)
22
+ previous.endLine = i;
23
+ const command = /^-\s*([A-Za-z]+)/.exec(line)?.[1] ?? '';
24
+ steps.push({ index: steps.length, command, body: undefined, source: line, startLine: i + 1, endLine: i + 1 });
25
+ }
26
+ const last = steps.at(-1);
27
+ if (last)
28
+ last.endLine = lines.length;
29
+ for (const step of steps)
30
+ step.source = lines
31
+ .slice(step.startLine - 1, step.endLine)
32
+ .join('\n')
33
+ .trimEnd();
34
+ return steps;
35
+ }
36
+ /**
37
+ * Splits Maestro flow YAML into its config header and its steps, with each step's line range in the source.
38
+ * A flow with only a command list (no `---`) has no config. YAML that doesn't parse still yields steps, found by
39
+ * their top-level `-` lines, so an error's line number can name the step.
40
+ */
41
+ export function parseFlow(source) {
42
+ const lineCounter = new LineCounter();
43
+ const docs = parseAllDocuments(source, { lineCounter });
44
+ const list = Array.isArray(docs) ? docs : [docs];
45
+ const commandsDoc = list.at(-1);
46
+ const configDoc = list.length > 1 ? list[0] : undefined;
47
+ const config = configDoc?.toJS();
48
+ const appId = isRecord(config) && typeof config.appId === 'string' ? config.appId : undefined;
49
+ const errors = list.flatMap(doc => doc.errors.map(error => error.message));
50
+ if (errors.length > 0 || !commandsDoc || !isSeq(commandsDoc.contents)) {
51
+ return {
52
+ appId,
53
+ config: isRecord(config) ? config : undefined,
54
+ steps: stepsByLine(source),
55
+ error: errors[0] ?? 'The flow has no list of commands.',
56
+ };
57
+ }
58
+ const steps = commandsDoc.contents.items.map((item, index) => {
59
+ const range = isScalar(item) || isMap(item) || isSeq(item) ? item.range : undefined;
60
+ const body = isScalar(item) || isMap(item) || isSeq(item) ? item.toJSON() : item;
61
+ const startLine = range ? lineCounter.linePos(range[0]).line : 0;
62
+ const endLine = range ? lineCounter.linePos(Math.max(range[0], range[1] - 1)).line : 0;
63
+ return { index, command: commandName(body), body, source: stringify([body]).trimEnd(), startLine, endLine };
64
+ });
65
+ return { appId, config: isRecord(config) ? config : undefined, steps, error: undefined };
66
+ }
67
+ export function stepAtLine(flow, line) {
68
+ return (flow.steps.find(step => step.startLine <= line && line <= step.endLine) ?? flow.steps.findLast(step => step.startLine <= line));
69
+ }
70
+ /** Writes the passing steps of a session's runs as one Maestro flow file that runs under `maestro test`. */
71
+ export function writeFlow(runs, appId) {
72
+ const steps = [];
73
+ let flowAppId = appId;
74
+ let config;
75
+ for (const run of runs) {
76
+ const flow = parseFlow(run.yaml);
77
+ if (flow.error !== undefined)
78
+ throw new Error(`A recorded run is not valid flow YAML: ${flow.error}`);
79
+ if (flow.appId !== undefined) {
80
+ if (flowAppId !== undefined && flowAppId !== flow.appId) {
81
+ throw new Error(`Recorded runs name two apps, ${flowAppId} and ${flow.appId}; a flow file has one appId.`);
82
+ }
83
+ flowAppId = flow.appId;
84
+ config ??= flow.config;
85
+ }
86
+ steps.push(...flow.steps.slice(0, run.passed ?? flow.steps.length).map(step => step.body));
87
+ }
88
+ if (flowAppId === undefined)
89
+ throw new Error('No recorded run names an appId, and none was given.');
90
+ if (steps.length === 0)
91
+ throw new Error('There are no passing steps to record.');
92
+ const header = { appId: flowAppId, ...config };
93
+ return { appId: flowAppId, steps, flow: `${stringify(header)}---\n${stringify(steps)}` };
94
+ }
@@ -0,0 +1,100 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { UsageError } from "../registry/refusal.js";
4
+ export const DEFAULT_IDLE_MS = 30 * 60_000;
5
+ export const SETTINGS_FILE = 'driver.json';
6
+ /**
7
+ * The driver's per-Mac settings, `<state dir>/driver.json`: `{"idleMinutes": 30}`. `idleMinutes: 0` keeps an
8
+ * engine running for as long as its lane lasts.
9
+ */
10
+ export function readDriverSettings(stateDir) {
11
+ const file = path.join(stateDir, SETTINGS_FILE);
12
+ let text;
13
+ try {
14
+ text = fs.readFileSync(file, 'utf8');
15
+ }
16
+ catch (error) {
17
+ if (error.code === 'ENOENT')
18
+ return { idleMs: DEFAULT_IDLE_MS };
19
+ throw error;
20
+ }
21
+ const fix = 'write {"idleMinutes": 30} (the default), or {"idleMinutes": 0} to keep engines running';
22
+ let raw;
23
+ try {
24
+ raw = JSON.parse(text);
25
+ }
26
+ catch (error) {
27
+ throw new UsageError(`${file} is not JSON: ${error.message}`, fix);
28
+ }
29
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
30
+ throw new UsageError(`${file} is not a JSON object`, fix);
31
+ const record = raw;
32
+ for (const key of Object.keys(record)) {
33
+ if (key !== 'idleMinutes')
34
+ throw new UsageError(`${file}: unknown setting '${key}'`, `use only idleMinutes; ${fix}`);
35
+ }
36
+ const minutes = record.idleMinutes;
37
+ if (minutes === undefined)
38
+ return { idleMs: DEFAULT_IDLE_MS };
39
+ if (typeof minutes !== 'number' || !Number.isFinite(minutes) || minutes < 0) {
40
+ throw new UsageError(`${file}: idleMinutes must be a number of minutes, 0 or more`, fix);
41
+ }
42
+ return { idleMs: Math.round(minutes * 60_000) };
43
+ }
44
+ /** Tracks an engine's tool calls, to tell when it has gone a whole idle period without one. */
45
+ export class IdleWatch {
46
+ idleMs;
47
+ clock;
48
+ last;
49
+ busy = 0;
50
+ constructor(idleMs, clock) {
51
+ this.idleMs = idleMs;
52
+ this.clock = clock;
53
+ this.last = clock.now();
54
+ }
55
+ begin() {
56
+ this.busy += 1;
57
+ this.last = this.clock.now();
58
+ }
59
+ end() {
60
+ this.busy = Math.max(0, this.busy - 1);
61
+ this.last = this.clock.now();
62
+ }
63
+ /** How long until the engine counts as idle; 0 when it already does, undefined when it never will. */
64
+ remainingMs() {
65
+ if (this.idleMs <= 0)
66
+ return undefined;
67
+ if (this.busy > 0)
68
+ return this.idleMs;
69
+ return Math.max(0, this.idleMs - (this.clock.now() - this.last));
70
+ }
71
+ }
72
+ export function writeIdleStop(file, stop) {
73
+ fs.writeFileSync(file, `${JSON.stringify(stop)}\n`, { mode: 0o600 });
74
+ }
75
+ /** Reads and removes the note an engine left when it stopped for lack of calls. */
76
+ export function takeIdleStop(file) {
77
+ let text;
78
+ try {
79
+ text = fs.readFileSync(file, 'utf8');
80
+ }
81
+ catch {
82
+ return undefined;
83
+ }
84
+ fs.rmSync(file, { force: true });
85
+ try {
86
+ const parsed = JSON.parse(text);
87
+ return parsed.version === 1 && typeof parsed.stoppedAt === 'number' && typeof parsed.idleMs === 'number'
88
+ ? parsed
89
+ : undefined;
90
+ }
91
+ catch {
92
+ return undefined;
93
+ }
94
+ }
95
+ export function describeIdle(ms) {
96
+ if (ms < 60_000)
97
+ return `${(ms / 1000).toFixed(1)} s`;
98
+ const minutes = ms / 60_000;
99
+ return `${Number.isInteger(minutes) ? String(minutes) : minutes.toFixed(1)} min`;
100
+ }
@@ -0,0 +1,68 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { DriverError } from "./errors.js";
4
+ import { runCommand, tail } from "./exec.js";
5
+ import { decodePng } from "./pixels.js";
6
+ /** Reads a JPEG's pixel size from its start-of-frame marker. */
7
+ export function jpegSize(jpeg) {
8
+ if (jpeg[0] !== 0xff || jpeg[1] !== 0xd8)
9
+ return undefined;
10
+ let offset = 2;
11
+ while (offset + 9 < jpeg.length) {
12
+ if (jpeg[offset] !== 0xff)
13
+ return undefined;
14
+ const marker = jpeg[offset + 1] ?? 0;
15
+ const length = jpeg.readUInt16BE(offset + 2);
16
+ const isFrame = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
17
+ if (isFrame)
18
+ return { height: jpeg.readUInt16BE(offset + 5), width: jpeg.readUInt16BE(offset + 7) };
19
+ offset += 2 + length;
20
+ }
21
+ return undefined;
22
+ }
23
+ /** Image edits with macOS's `sips`, through files in a scratch folder. */
24
+ export function sipsImages(scratch) {
25
+ let counter = 0;
26
+ const files = (extension) => {
27
+ fs.mkdirSync(scratch, { recursive: true, mode: 0o700 });
28
+ counter += 1;
29
+ const stem = path.join(scratch, `image-${String(process.pid)}-${String(counter)}`);
30
+ return { input: `${stem}.jpg`, output: `${stem}.${extension}` };
31
+ };
32
+ const sips = async (args, input, output) => {
33
+ const ran = await runCommand('sips', [...args, input, '--out', output], { timeoutMs: 30_000 });
34
+ try {
35
+ if (ran.code !== 0 || !fs.existsSync(output)) {
36
+ throw new DriverError(`sips failed (${ran.error ?? `exit ${String(ran.code)}`}): ${tail(ran.stderr || ran.stdout, 4)}`, 'sips ships with macOS; image edits need it');
37
+ }
38
+ return fs.readFileSync(output);
39
+ }
40
+ finally {
41
+ fs.rmSync(input, { force: true });
42
+ fs.rmSync(output, { force: true });
43
+ }
44
+ };
45
+ return {
46
+ async pixels(jpeg, width) {
47
+ const { input, output } = files('png');
48
+ fs.writeFileSync(input, jpeg);
49
+ return decodePng(await sips(['-s', 'format', 'png', '--resampleWidth', String(width)], input, output));
50
+ },
51
+ async transform(jpeg, edit) {
52
+ const { input, output } = files('jpg');
53
+ fs.writeFileSync(input, jpeg);
54
+ const size = jpegSize(jpeg);
55
+ const args = ['-s', 'format', 'jpeg'];
56
+ let width = size?.width;
57
+ if (edit.crop) {
58
+ const crop = edit.crop;
59
+ args.push('--cropToHeightWidth', String(crop.height), String(crop.width), '--cropOffset', String(crop.y), String(crop.x));
60
+ width = crop.width;
61
+ }
62
+ if (edit.scale !== undefined && width !== undefined) {
63
+ args.push('--resampleWidth', String(Math.max(1, Math.round(width * edit.scale))));
64
+ }
65
+ return sips(args, input, output);
66
+ },
67
+ };
68
+ }