@kosuke-ai/kosuke 1.0.81 → 1.0.83

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 (33) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/generated/commands/crons/create--personal.js +1 -1
  3. package/dist/generated/commands/crons/update--personal.js +1 -1
  4. package/dist/generated/commands/index.js +124 -118
  5. package/dist/generated/commands/projects/batch-merging-members-delete.js +7 -0
  6. package/dist/generated/commands/prototypes/create.js +32 -0
  7. package/dist/generated/commands/providers/default-model-set--personal.js +2 -9
  8. package/dist/generated/commands/providers/get--personal.js +1 -1
  9. package/dist/generated/commands/sensei/reels-activity-list.js +1 -1
  10. package/dist/generated/commands/sensei/reels-later-holds-create.js +43 -0
  11. package/dist/generated/commands/sensei/reels-later-holds-delete.js +29 -0
  12. package/dist/generated/commands/sensei/reels-later-holds-list.js +17 -0
  13. package/dist/generated/commands/sensei/widgets-get.js +1 -1
  14. package/dist/generated/commands/sessions/create.js +0 -14
  15. package/dist/generated/commands/sessions/prompt-update.js +0 -11
  16. package/dist/generated/commands/sessions/send.js +0 -18
  17. package/dist/generated/commands/sessions/update.js +3 -10
  18. package/dist/generated/commands/tasks/create--personal.js +0 -14
  19. package/dist/generated/commands/tasks/create.js +0 -14
  20. package/dist/generated/commands/tasks/update--personal.js +2 -9
  21. package/dist/generated/commands/tasks/update.js +2 -9
  22. package/dist/runtime/arguments.js +2 -0
  23. package/dist/runtime/attach.js +6 -12
  24. package/dist/runtime/option-parsers.js +14 -0
  25. package/dist/runtime/prototype-create.js +47 -0
  26. package/dist/runtime/prototype-styles-scope.js +342 -0
  27. package/dist/runtime/prototype-styles.js +166 -0
  28. package/dist/runtime/prototype-visual-browser.js +87 -0
  29. package/dist/runtime/prototype-visual-check.js +388 -0
  30. package/dist/runtime/prototype-visual-preview.js +159 -0
  31. package/dist/runtime/prototype-visual-scripts.js +174 -0
  32. package/openapi.json +237 -88
  33. package/package.json +5 -6
@@ -0,0 +1,166 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, extname, join, resolve } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { promisify } from 'node:util';
7
+ import { scopeToCanvas } from './prototype-styles-scope.js';
8
+ /** The sandbox clone of a session, tried when nothing up from here depends on Tailwind. */
9
+ const SANDBOX_PROJECT = '/app/project';
10
+ /** The usual homes of a project's Tailwind entry, after components.json's `tailwind.css`. */
11
+ const ENTRY_PLACES = [
12
+ 'src/app/globals.css',
13
+ 'app/globals.css',
14
+ 'src/styles/globals.css',
15
+ 'styles/globals.css',
16
+ 'src/index.css',
17
+ 'src/global.css',
18
+ 'src/main.css',
19
+ ];
20
+ const TAILWIND_IMPORT = /@import\s+(?:url\(\s*)?["']tailwindcss(?:\/[^"']*)?["']|@tailwind\s+(?:base|components|utilities)\b/;
21
+ /** A class-like token: Tailwind ignores those it has no utility for. */
22
+ /** The project's own Tailwind v4 compiler, resolved from its clone: never the CLI's dependency. */
23
+ const TAILWIND_NODE = '@tailwindcss/node';
24
+ const CANDIDATE = /^[!-]?[a-z@[][\w\-:/.[\]()%#,'!&=*@<>+~]*$/i;
25
+ /** The generated block stays well under the page's 1 MB. */
26
+ const MAX_BYTES = 512 * 1024;
27
+ const V3_TIMEOUT_MS = 60_000;
28
+ const handWritten = (why) => ({
29
+ css: null,
30
+ notice: `Styles are hand written: ${why}.`,
31
+ });
32
+ function readJson(path) {
33
+ try {
34
+ const value = JSON.parse(readFileSync(path, 'utf8'));
35
+ return value && typeof value === 'object' ? value : null;
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ function dependsOnTailwind(dir) {
42
+ const pkg = readJson(join(dir, 'package.json'));
43
+ if (!pkg)
44
+ return false;
45
+ return ['dependencies', 'devDependencies'].some((field) => {
46
+ const deps = pkg[field];
47
+ return !!deps && typeof deps === 'object' && 'tailwindcss' in deps;
48
+ });
49
+ }
50
+ /** The flag's folder; else the nearest folder up from here that depends on tailwindcss; else the sandbox clone. */
51
+ function findProjectDir(flag) {
52
+ if (flag)
53
+ return resolve(flag);
54
+ for (let dir = process.cwd();; dir = dirname(dir)) {
55
+ if (dependsOnTailwind(dir))
56
+ return dir;
57
+ if (dirname(dir) === dir)
58
+ break;
59
+ }
60
+ return dependsOnTailwind(SANDBOX_PROJECT) ? SANDBOX_PROJECT : null;
61
+ }
62
+ /** The CSS file that imports tailwindcss: components.json's, else the first usual place that does. */
63
+ function findEntry(projectDir) {
64
+ const shadcn = readJson(join(projectDir, 'components.json'))?.tailwind;
65
+ const declared = shadcn && typeof shadcn === 'object' && 'css' in shadcn && typeof shadcn.css === 'string'
66
+ ? [shadcn.css]
67
+ : [];
68
+ for (const place of [...declared, ...ENTRY_PLACES]) {
69
+ const path = resolve(projectDir, place);
70
+ try {
71
+ if (TAILWIND_IMPORT.test(readFileSync(path, 'utf8')))
72
+ return path;
73
+ }
74
+ catch {
75
+ // Not there: try the next place.
76
+ }
77
+ }
78
+ return null;
79
+ }
80
+ /** The class-like tokens of content.js, the only class names the build is for. */
81
+ function contentCandidates(script) {
82
+ // `<`, `>` and `=` end a token, except inside brackets: `has-[>svg]:px-3` is one class.
83
+ const tokens = script
84
+ .replace(/\[[^\]\s"'`]*\]/g, (bracket) => bracket.replace(/[<>=]/g, (char) => `\u0000${char.charCodeAt(0)}\u0000`))
85
+ .split(/\$\{|[\s"'`<>=}]+/)
86
+ .map((token) => token.replace(/\u0000(\d+)\u0000/g, (_, code) => String.fromCharCode(Number(code))));
87
+ return [...new Set(tokens.filter((token) => CANDIDATE.test(token)))];
88
+ }
89
+ /**
90
+ * The entry with its own `@theme` blocks static, so every design token it declares is written,
91
+ * not only those the candidates use; Tailwind's default theme stays trimmed to what is used.
92
+ */
93
+ const staticTheme = (css) => css.replace(/@theme((?:\s+[\w-]+)*)\s*\{/g, (block, options) => /\b(?:static|reference)\b/.test(options) ? block : `@theme${options} static {`);
94
+ /** Tailwind v4: the project's own compiler, built for the candidates only, never its sources. */
95
+ async function buildV4(entry, modulePath, candidates) {
96
+ const loaded = (await import(pathToFileURL(modulePath).href));
97
+ const compile = loaded.compile ?? loaded.default?.compile;
98
+ if (typeof compile !== 'function')
99
+ throw new Error('@tailwindcss/node has no compile()');
100
+ const compiler = await compile(staticTheme(readFileSync(entry, 'utf8')), {
101
+ base: dirname(entry),
102
+ onDependency() { },
103
+ });
104
+ return compiler.build(candidates);
105
+ }
106
+ /** Tailwind v3: its own CLI, run in the project with its config, over content.js alone. */
107
+ async function buildV3(projectDir, entry, tailwindDir, script) {
108
+ const cli = join(tailwindDir, 'lib/cli.js');
109
+ if (!existsSync(cli))
110
+ throw new Error(`${cli} is missing`);
111
+ const { stdout } = await promisify(execFile)(process.execPath, [cli, '-i', entry, '--content', script], { cwd: projectDir, timeout: V3_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 });
112
+ return stdout;
113
+ }
114
+ const message = (error) => (error instanceof Error ? error.message : String(error)).split('\n')[0].replace(/\.$/, '');
115
+ /**
116
+ * The generated styles of a prototype: CSS built from the project's own Tailwind entry for
117
+ * only the class names content.js uses, scoped to the prototype's canvas. Never throws: with no
118
+ * Tailwind, or when anything fails, `css` is null and the notice says why.
119
+ */
120
+ export async function buildPrototypeStyles(input) {
121
+ try {
122
+ const script = input.attachments.find((path) => extname(path).toLowerCase() === '.js');
123
+ if (!script)
124
+ return handWritten('no content.js among the attached files');
125
+ const projectDir = findProjectDir(input.projectDir);
126
+ if (!projectDir)
127
+ return handWritten('no package.json that depends on tailwindcss here or above; pass --project-dir with the project clone');
128
+ if (!existsSync(join(projectDir, 'package.json')))
129
+ return handWritten(`${projectDir} has no package.json`);
130
+ const entry = findEntry(projectDir);
131
+ if (!entry)
132
+ return handWritten(`no CSS file in ${projectDir} imports tailwindcss`);
133
+ const require = createRequire(join(projectDir, 'package.json'));
134
+ let tailwindPackage;
135
+ try {
136
+ tailwindPackage = require.resolve('tailwindcss/package.json');
137
+ }
138
+ catch {
139
+ return handWritten(`tailwindcss is not installed in ${projectDir}; install its dependencies`);
140
+ }
141
+ const version = String(readJson(tailwindPackage)?.version ?? '');
142
+ const candidates = contentCandidates(readFileSync(resolve(script), 'utf8'));
143
+ let built;
144
+ if (/^3\./.test(version)) {
145
+ built = await buildV3(projectDir, entry, dirname(tailwindPackage), resolve(script));
146
+ }
147
+ else {
148
+ let modulePath;
149
+ try {
150
+ modulePath = require.resolve(TAILWIND_NODE);
151
+ }
152
+ catch {
153
+ return handWritten(`@tailwindcss/node is not installed in ${projectDir} (tailwindcss ${version || 'unknown'})`);
154
+ }
155
+ built = await buildV4(entry, modulePath, candidates);
156
+ }
157
+ const css = scopeToCanvas(built, candidates);
158
+ const bytes = Buffer.byteLength(css);
159
+ if (bytes > MAX_BYTES)
160
+ return handWritten(`the generated block is ${bytes} bytes, over ${MAX_BYTES}`);
161
+ return { css };
162
+ }
163
+ catch (error) {
164
+ return handWritten(`the Tailwind build failed (${message(error)})`);
165
+ }
166
+ }
@@ -0,0 +1,87 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { accessSync, constants } from 'node:fs';
3
+ import { delimiter, join } from 'node:path';
4
+ /**
5
+ * `agent-browser`, driven through child_process for the visual check. Every call to one session
6
+ * carries the same launch flags: agent-browser relaunches a session's browser, dropping its tabs
7
+ * and sign-in, when a call's flags differ from the ones it was launched with.
8
+ */
9
+ const BINARY = 'agent-browser';
10
+ /** Whether `agent-browser` is on PATH: session sandboxes have it, Sensei homes do not. */
11
+ export function hasBrowser(env = process.env) {
12
+ for (const dir of (env.PATH ?? '').split(delimiter)) {
13
+ if (!dir)
14
+ continue;
15
+ try {
16
+ accessSync(join(dir, BINARY), constants.X_OK);
17
+ return true;
18
+ }
19
+ catch {
20
+ // Not in this folder.
21
+ }
22
+ }
23
+ return false;
24
+ }
25
+ class BrowserError extends Error {
26
+ }
27
+ /** One call; answers the JSON `data`, or throws with agent-browser's error. */
28
+ export function browser(session, args, { timeoutMs, stdin }) {
29
+ return new Promise((resolve, reject) => {
30
+ const child = spawn(BINARY, ['--session', session.name, ...session.launch, '--json', ...args], {
31
+ stdio: ['pipe', 'pipe', 'pipe'],
32
+ });
33
+ const out = [];
34
+ const err = [];
35
+ const timer = setTimeout(() => {
36
+ child.kill('SIGKILL');
37
+ reject(new BrowserError(`agent-browser ${args[0]} took over ${Math.round(timeoutMs / 1000)} s`));
38
+ }, timeoutMs);
39
+ child.stdout.on('data', (chunk) => out.push(chunk));
40
+ child.stderr.on('data', (chunk) => err.push(chunk));
41
+ child.on('error', (error) => {
42
+ clearTimeout(timer);
43
+ reject(new BrowserError(error.message));
44
+ });
45
+ child.on('close', () => {
46
+ clearTimeout(timer);
47
+ const text = Buffer.concat(out).toString('utf8').trim();
48
+ let answer;
49
+ try {
50
+ answer = JSON.parse(text);
51
+ }
52
+ catch {
53
+ const why = (Buffer.concat(err).toString('utf8').trim() || text).split('\n')[0];
54
+ return reject(new BrowserError(`agent-browser ${args[0]}: ${why || 'no answer'}`));
55
+ }
56
+ const record = isRecord(answer) ? answer : {};
57
+ if (record.success !== true) {
58
+ return reject(new BrowserError(`agent-browser ${args[0]}: ${String(record.error ?? 'failed')}`));
59
+ }
60
+ resolve(isRecord(record.data) ? record.data : {});
61
+ });
62
+ child.stdin.end(stdin ?? '');
63
+ });
64
+ }
65
+ /** Runs a script in the session's active tab and answers its (awaited) value. */
66
+ export async function evaluate(session, script, timeoutMs) {
67
+ const data = await browser(session, ['eval', '--stdin'], { timeoutMs, stdin: script });
68
+ return data.result;
69
+ }
70
+ /** The sessions running now, by name. Reads the daemons only: no browser starts. */
71
+ export async function runningSessions(timeoutMs) {
72
+ const data = await browser({ name: 'default', launch: [] }, ['session', 'list'], { timeoutMs });
73
+ return new Set(Array.isArray(data.sessions) ? data.sessions.map(String) : []);
74
+ }
75
+ /**
76
+ * The hash of the flags a running session was launched with, or null. Reads the daemon only, so
77
+ * it relaunches nothing: two sessions with one hash take the same flags.
78
+ */
79
+ export async function launchHash(name, timeoutMs) {
80
+ const data = await browser({ name, launch: [] }, ['session', 'info'], { timeoutMs });
81
+ const runtime = isRecord(data.runtime) ? data.runtime : {};
82
+ const hash = runtime.launchHash ?? data.launchHash;
83
+ return hash === undefined || hash === null ? null : String(hash);
84
+ }
85
+ function isRecord(value) {
86
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
87
+ }
@@ -0,0 +1,388 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { extname, join } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { operations } from '../generated/commands/index.js';
7
+ import { buildRequest, execute } from './invoke.js';
8
+ import { browser, evaluate, hasBrowser, launchHash, runningSessions, } from './prototype-visual-browser.js';
9
+ import { findPreview, reachable } from './prototype-visual-preview.js';
10
+ import { compareScript, realThemeScript, settleScript, showStateScript, } from './prototype-visual-scripts.js';
11
+ /** Over this share of differing pixels the save needs a written reason (`src/lib/prototypes/record.ts`). */
12
+ const THRESHOLD = 3;
13
+ /** The whole check, both screenshots and the image's save included. */
14
+ const CHECK_TIMEOUT_MS = 90_000;
15
+ /** Where a session sandbox's agent writes artifacts: the Turn publishes each file at its slug. */
16
+ const SESSION_ARTIFACTS_DIR = '/tmp/kosuke-artifacts';
17
+ const ARTIFACT_SLUG_MAX = 64;
18
+ const SUFFIX = '-visual-check';
19
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
20
+ const notCompared = (why, notice) => ({
21
+ result: { status: 'not-compared', why },
22
+ ...(notice ? { notice: `Visual check: not compared: ${notice}` } : {}),
23
+ });
24
+ class CheckError extends Error {
25
+ why;
26
+ detail;
27
+ constructor(why, detail) {
28
+ super(detail);
29
+ this.why = why;
30
+ this.detail = detail;
31
+ }
32
+ }
33
+ /**
34
+ * The comparison of a prototype's baseline state with the real screen, as the save records it
35
+ * (`src/lib/prototypes/record.ts`, `PrototypeVisualCheck`), or null when none was attempted.
36
+ *
37
+ * 1. prototype.json declares no `baseline`: not compared.
38
+ * 2. No `agent-browser` on PATH (a Sensei home): not compared, no browser.
39
+ * 3. The preview: `--preview-url`, else this sandbox's app preview, else `kosuke preview get`;
40
+ * none, or no answer within 10 s: not compared.
41
+ * 4. Renders the page without saving it (`dryRun`) and opens it from a temp file in the check's
42
+ * own browser session.
43
+ * 5. At the prototype's main device width, for each theme it declares that the app has (light,
44
+ * then dark), screenshots the baseline state's canvas and the real screen.
45
+ * 6. Compares them in the browser and draws the side-by-side picture of the worst theme.
46
+ * 7. Saves the picture as the session's `<name>-visual-check` artifact, or the File
47
+ * `prototypes/<name>-visual-check.png`; a failed save keeps the result with no image.
48
+ * Any other failure is not compared, with a notice: the save itself goes on.
49
+ */
50
+ export async function runVisualCheck(input) {
51
+ const baseline = readBaseline(input.input.attachments);
52
+ if (!baseline)
53
+ return { result: { status: 'not-compared', why: 'no baseline declared' } };
54
+ if (!hasBrowser()) {
55
+ return notCompared('no browser', 'no browser here (agent-browser is not on PATH).');
56
+ }
57
+ const work = mkdtempSync(join(tmpdir(), 'kosuke-visual-check-'));
58
+ const opened = [];
59
+ let timer;
60
+ try {
61
+ const deadline = Date.now() + CHECK_TIMEOUT_MS;
62
+ const timeout = new Promise((_, reject) => {
63
+ timer = setTimeout(() => reject(new CheckError('timed out', 'the check took over 90 s.')), CHECK_TIMEOUT_MS);
64
+ });
65
+ return await Promise.race([check({ ...input, baseline, work, opened, deadline }), timeout]);
66
+ }
67
+ catch (error) {
68
+ if (error instanceof CheckError)
69
+ return notCompared(error.why, error.detail);
70
+ const message = error instanceof Error ? error.message : String(error);
71
+ return notCompared('the check failed', `${message.slice(0, 300)}.`);
72
+ }
73
+ finally {
74
+ clearTimeout(timer);
75
+ for (const session of opened) {
76
+ await browser(session, ['close'], { timeoutMs: 10_000 }).catch(() => undefined);
77
+ }
78
+ rmSync(work, { recursive: true, force: true });
79
+ }
80
+ }
81
+ async function check(input) {
82
+ const { runtime, baseline, work, deadline } = input;
83
+ const fields = input.input.fields;
84
+ const left = (most) => Math.max(1_000, Math.min(most, deadline - Date.now()));
85
+ const text = (value) => (typeof value === 'string' && value ? value : undefined);
86
+ const preview = await findPreview({
87
+ runtime,
88
+ flag: input.previewUrl,
89
+ projectId: text(fields.projectId),
90
+ sessionId: text(fields.sessionId),
91
+ }).catch(() => null);
92
+ if (!preview)
93
+ return notCompared('no preview reachable', 'no app preview is known here.');
94
+ if (!(await reachable(preview))) {
95
+ return notCompared('no preview reachable', `${preview.url} did not answer.`);
96
+ }
97
+ const page = await dryRun(input);
98
+ if (!page)
99
+ return { result: null };
100
+ const inventory = readInventory(page);
101
+ const device = mainDevice(inventory);
102
+ const themes = comparedThemes(inventory);
103
+ if (!device || !themes.length) {
104
+ throw new CheckError('the check failed', 'the page declares no device or no light or dark theme.');
105
+ }
106
+ const phone = device.kind === 'phone';
107
+ const width = device.px ?? (phone ? 390 : 1280);
108
+ const height = device.height ?? (phone ? 844 : 900);
109
+ const pagePath = join(work, 'prototype.html');
110
+ writeFileSync(pagePath, page);
111
+ // The check's own session, so the agent's browser is left as it is.
112
+ const own = {
113
+ name: `kosuke-prototype-check-${process.pid}-${randomBytes(3).toString('hex')}`,
114
+ launch: preview.launch,
115
+ };
116
+ input.opened.push(own);
117
+ await browser(own, ['open', pathToFileURL(pagePath).href], { timeoutMs: left(30_000) });
118
+ await browser(own, ['set', 'viewport', String(width), String(height)], {
119
+ timeoutMs: left(10_000),
120
+ });
121
+ const real = await realScreenSession(own, preview, left);
122
+ let worst = null;
123
+ for (const theme of themes) {
124
+ const protoShot = join(work, `prototype-${theme.id}.png`);
125
+ const realShot = join(work, `real-${theme.id}.png`);
126
+ await browser(own, ['open', pathToFileURL(pagePath).href], { timeoutMs: left(30_000) });
127
+ await browser(own, ['set', 'media', theme.scheme], { timeoutMs: left(10_000) });
128
+ const shown = (await evaluate(own, showStateScript({ ...baseline, theme: theme.id, width, height }), left(20_000)));
129
+ if (!shown?.reached) {
130
+ throw new CheckError('baseline state not reached', // The server refuses the save on these words (BASELINE_NOT_REACHED).
131
+ `the page could not show the baseline state "${baseline.state}"; it showed "${shown?.current ?? 'nothing'}".`);
132
+ }
133
+ await browser(own, ['screenshot', '--full', protoShot], { timeoutMs: left(20_000) });
134
+ await shootRealScreen(real.session, {
135
+ url: preview.url + baseline.path,
136
+ scheme: theme.scheme,
137
+ width,
138
+ height,
139
+ file: realShot,
140
+ left,
141
+ });
142
+ await browser(own, ['open', 'about:blank'], { timeoutMs: left(30_000) });
143
+ const comparison = (await evaluate(own, compareScript({
144
+ real: dataUrl(realShot),
145
+ prototype: dataUrl(protoShot),
146
+ box: shown.box,
147
+ maxHeight: height * 2 * Math.max(1, Math.round(shown.box.width / width)),
148
+ labels: [
149
+ `Real screen ${baseline.path}`,
150
+ `Prototype ${baseline.state}${baseline.variant ? ` (${baseline.variant})` : ''}`,
151
+ `Difference, ${theme.id}`,
152
+ ],
153
+ }), left(30_000)));
154
+ if (typeof comparison?.diffPercent !== 'number' || typeof comparison.png !== 'string') {
155
+ throw new CheckError('the check failed', 'the comparison gave no result.');
156
+ }
157
+ if (!worst || comparison.diffPercent > worst.comparison.diffPercent) {
158
+ worst = { theme, comparison };
159
+ }
160
+ }
161
+ if (!worst)
162
+ throw new CheckError('the check failed', 'nothing was compared.');
163
+ const image = join(work, 'side-by-side.png');
164
+ writeFileSync(image, Buffer.from(worst.comparison.png.replace(/^data:image\/png;base64,/, ''), 'base64'));
165
+ const saved = await saveImage({ runtime, fields, image }).catch((error) => ({
166
+ image: null,
167
+ notice: `the side-by-side image was not saved: ${error instanceof Error ? error.message : String(error)}.`,
168
+ }));
169
+ const diffPercent = worst.comparison.diffPercent;
170
+ const notices = [saved.notice, diffPercent > THRESHOLD ? real.signedOut : undefined]
171
+ .filter((line) => !!line)
172
+ .map((line) => line.charAt(0).toUpperCase() + line.slice(1));
173
+ return {
174
+ result: {
175
+ status: 'compared',
176
+ diffPercent,
177
+ threshold: THRESHOLD,
178
+ state: baseline.state,
179
+ variant: baseline.variant,
180
+ device: device.id,
181
+ width,
182
+ theme: worst.theme.id,
183
+ path: baseline.path,
184
+ image: saved.image,
185
+ },
186
+ ...(notices.length ? { notice: `Visual check: ${notices.join(' ')}` } : {}),
187
+ };
188
+ }
189
+ /**
190
+ * The real screen needs the agent's sign-in, so it is taken in the agent's own browser session
191
+ * (`$AGENT_BROWSER_SESSION`, else `default`), in a tab of its own that is closed after; the skill
192
+ * tells the agent to sign in to the preview there first. agent-browser relaunches a session
193
+ * whose launch flags differ from a call's, which would drop that sign-in, so the agent's session
194
+ * is used only when it runs with the flags the preview needs. Otherwise the real screen is taken
195
+ * signed out in the check's own session.
196
+ */
197
+ async function realScreenSession(own, preview, left) {
198
+ const name = process.env.AGENT_BROWSER_SESSION || 'default';
199
+ const agent = { name, launch: preview.launch };
200
+ const flags = preview.launch.length
201
+ ? ` opened with ${preview.launch.map((flag) => (flag.includes(' ') ? `"${flag}"` : flag)).join(' ')}`
202
+ : '';
203
+ const signedOut = {
204
+ session: own,
205
+ signedOut: `the real screen was taken signed out. To compare a signed-in screen, sign in to the preview in the agent-browser session "${name}"${flags}, then save again.`,
206
+ };
207
+ const running = await runningSessions(left(10_000)).catch(() => new Set());
208
+ if (!running.has(name))
209
+ return signedOut;
210
+ const [theirs, ours] = await Promise.all([
211
+ launchHash(name, left(10_000)).catch(() => null),
212
+ launchHash(own.name, left(10_000)).catch(() => null),
213
+ ]);
214
+ if (!theirs || theirs !== ours)
215
+ return signedOut;
216
+ return { session: agent };
217
+ }
218
+ /** Opens the real screen in a tab of its own, screenshots the viewport, and closes the tab. */
219
+ async function shootRealScreen(session, shot) {
220
+ const { left } = shot;
221
+ const before = await browser(session, ['tab', 'list'], { timeoutMs: left(10_000) });
222
+ const tabs = Array.isArray(before.tabs) ? before.tabs.filter(isRecord) : [];
223
+ const active = tabs.find((tab) => tab.active === true)?.tabId;
224
+ // A first compile of the page in a dev server can take a while.
225
+ const opened = await browser(session, ['tab', 'new', shot.url], { timeoutMs: left(45_000) });
226
+ const tab = typeof opened.tabId === 'string' ? opened.tabId : null;
227
+ try {
228
+ await browser(session, ['set', 'viewport', String(shot.width), String(shot.height)], {
229
+ timeoutMs: left(10_000),
230
+ });
231
+ await browser(session, ['set', 'media', shot.scheme], { timeoutMs: left(10_000) });
232
+ const href = await settled(session, left);
233
+ if (typeof href !== 'string' || href.startsWith('chrome-error:')) {
234
+ throw new CheckError('no preview reachable', `the browser could not open ${shot.url}.`);
235
+ }
236
+ await evaluate(session, realThemeScript(shot.scheme), left(15_000));
237
+ await browser(session, ['screenshot', shot.file], { timeoutMs: left(20_000) });
238
+ }
239
+ finally {
240
+ if (tab)
241
+ await browser(session, ['tab', 'close', tab], { timeoutMs: left(10_000) }).catch(() => undefined);
242
+ if (typeof active === 'string') {
243
+ await browser(session, ['tab', active], { timeoutMs: left(10_000) }).catch(() => undefined);
244
+ }
245
+ }
246
+ }
247
+ /**
248
+ * The page once it stops loading. A page that redirects as it loads (a sign-in cookie set on the
249
+ * first visit) destroys the context the wait ran in: wait again, at most three times.
250
+ */
251
+ async function settled(session, left) {
252
+ for (let attempt = 1;; attempt++) {
253
+ try {
254
+ return await evaluate(session, settleScript(10_000), left(20_000));
255
+ }
256
+ catch (error) {
257
+ const message = error instanceof Error ? error.message : String(error);
258
+ if (attempt >= 3 || !/context was destroyed|navigat/i.test(message))
259
+ throw error;
260
+ }
261
+ }
262
+ }
263
+ /** The page as the save would write it, rendered and checked but not saved; null when it fails its check. */
264
+ async function dryRun(input) {
265
+ const { visualCheck: _sent, visualCheckReason: _reason, ...fields } = input.input.fields;
266
+ const request = buildRequest(input.operation, {
267
+ ...input.input,
268
+ fields: { ...fields, dryRun: 'true' },
269
+ });
270
+ const outcome = await execute(input.runtime.client({ answerTimeoutMs: input.operation.answerTimeoutMs }), request);
271
+ // A page that fails its check fails the save the same way: the save reports it.
272
+ if (!outcome.ok)
273
+ return null;
274
+ const body = isRecord(outcome.body) ? outcome.body : {};
275
+ const data = isRecord(body.data) ? body.data : body;
276
+ const pages = Array.isArray(data.pages) ? data.pages.filter(isRecord) : [];
277
+ const html = pages[0]?.html;
278
+ if (typeof html !== 'string' || !html) {
279
+ throw new CheckError('the check failed', 'the dry run answered no page.');
280
+ }
281
+ return html;
282
+ }
283
+ /** prototype.json's `baseline`, from the attachment ending in .json; null when there is none. */
284
+ function readBaseline(attachments) {
285
+ const file = attachments.find((path) => extname(path).toLowerCase() === '.json');
286
+ if (!file)
287
+ return null;
288
+ let config;
289
+ try {
290
+ config = JSON.parse(readFileSync(file, 'utf8'));
291
+ }
292
+ catch {
293
+ return null;
294
+ }
295
+ const baseline = isRecord(config) ? config.baseline : undefined;
296
+ if (!isRecord(baseline))
297
+ return null;
298
+ const { state, path, variant } = baseline;
299
+ if (typeof state !== 'string' || !state || typeof path !== 'string' || !path.startsWith('/')) {
300
+ return null;
301
+ }
302
+ return { state, path, variant: typeof variant === 'string' && variant ? variant : null };
303
+ }
304
+ const INVENTORY = /<script\b[^>]*\bid\s*=\s*["']prototype-inventory["'][^>]*>([\s\S]*?)<\/script>/i;
305
+ /** The configuration as the renderer wrote it into the page: devices and themes normalized. */
306
+ function readInventory(page) {
307
+ try {
308
+ const value = JSON.parse(INVENTORY.exec(page)?.[1] ?? '');
309
+ return isRecord(value) ? value : {};
310
+ }
311
+ catch {
312
+ return {};
313
+ }
314
+ }
315
+ function mainDevice(inventory) {
316
+ const first = Array.isArray(inventory.devices) ? inventory.devices[0] : undefined;
317
+ if (!isRecord(first) || typeof first.id !== 'string')
318
+ return null;
319
+ return {
320
+ id: first.id,
321
+ kind: typeof first.kind === 'string' ? first.kind : 'desktop',
322
+ ...(typeof first.px === 'number' ? { px: first.px } : {}),
323
+ ...(typeof first.height === 'number' ? { height: first.height } : {}),
324
+ };
325
+ }
326
+ /** The first light and the first dark theme the prototype declares, light first. */
327
+ function comparedThemes(inventory) {
328
+ const themes = (Array.isArray(inventory.themes) ? inventory.themes : []).filter(isRecord);
329
+ return ['light', 'dark'].flatMap((scheme) => {
330
+ const theme = themes.find((item) => item.scheme === scheme && typeof item.id === 'string');
331
+ return theme ? [{ id: theme.id, scheme }] : [];
332
+ });
333
+ }
334
+ function dataUrl(path) {
335
+ return `data:image/png;base64,${readFileSync(path).toString('base64')}`;
336
+ }
337
+ /** `<name>-visual-check`, the name shortened at a hyphen to fit an artifact slug. */
338
+ function imageSlug(name) {
339
+ let base = name.toLowerCase();
340
+ while (base.length + SUFFIX.length > ARTIFACT_SLUG_MAX && base.includes('-')) {
341
+ base = base.slice(0, base.lastIndexOf('-'));
342
+ }
343
+ return `${base.slice(0, ARTIFACT_SLUG_MAX - SUFFIX.length)}${SUFFIX}`;
344
+ }
345
+ /**
346
+ * The side-by-side picture, next to the prototype. A session's artifacts are published by the
347
+ * Turn from the sandbox's artifacts folder (no route takes an image's bytes), so a session's
348
+ * picture is written there, which only its own sandbox can do. Files take it through
349
+ * `kosuke files set`.
350
+ */
351
+ async function saveImage(input) {
352
+ const { fields } = input;
353
+ const name = typeof fields.name === 'string' ? fields.name : 'prototype';
354
+ if (typeof fields.workspaceId === 'string' && fields.workspaceId) {
355
+ const path = `prototypes/${name}${SUFFIX}.png`;
356
+ const upload = join(input.image, '..', `${name}${SUFFIX}.png`);
357
+ copyFileSync(input.image, upload);
358
+ // The workspace form of `kosuke files set`, read from the registry like every command.
359
+ const filesSet = operations.find((operation) => operation.command.join(' ') === 'files set' && !operation.personalSpace);
360
+ if (!filesSet)
361
+ return { image: null, notice: 'the side-by-side image was not saved.' };
362
+ const outcome = await execute(input.runtime.client(), buildRequest(filesSet, {
363
+ pathParams: { workspaceId: fields.workspaceId },
364
+ fields: { path, mediaType: 'image/png' },
365
+ attachments: [upload],
366
+ }));
367
+ if (!outcome.ok) {
368
+ return {
369
+ image: null,
370
+ notice: `the side-by-side image was not saved (HTTP ${outcome.status}).`,
371
+ };
372
+ }
373
+ return { image: { kind: 'file', ref: path } };
374
+ }
375
+ const sessionId = fields.sessionId;
376
+ const ownSandbox = typeof sessionId === 'string' &&
377
+ sessionId === process.env.KOSUKE_SANDBOX_KEY &&
378
+ existsSync(SESSION_ARTIFACTS_DIR);
379
+ if (!ownSandbox) {
380
+ return {
381
+ image: null,
382
+ notice: "the side-by-side image is saved only from the session's own sandbox.",
383
+ };
384
+ }
385
+ const slug = imageSlug(name);
386
+ copyFileSync(input.image, join(SESSION_ARTIFACTS_DIR, `${slug}.png`));
387
+ return { image: { kind: 'artifact', ref: slug } };
388
+ }