@kosuke-ai/kosuke 1.0.81 → 1.0.82

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.
@@ -0,0 +1,342 @@
1
+ /**
2
+ * Scopes a Tailwind build to a prototype's canvas: the page root becomes `.pt-canvas`, the dark
3
+ * theme `.pt-canvas.dark`, every other selector a descendant of the canvas, and `@media` width
4
+ * rules `@container canvas` rules, so the Device control applies them. What could load, leak out
5
+ * of the canvas or the server refuses is dropped, as are the entry's plain rules for classes the
6
+ * prototype never names. The result passes the server's `generatedStyleIssues`
7
+ * (src/lib/prototypes/content-checks.ts).
8
+ */
9
+ const CANVAS = '.pt-canvas';
10
+ /** At-rules whose body is a list of rules, kept and scoped. */
11
+ const GROUPS = new Set(['layer', 'media', 'supports', 'container', 'starting-style']);
12
+ /** At-rules whose body holds descriptors or keyframe steps, kept as written. */
13
+ const OPAQUE = new Set(['keyframes', '-webkit-keyframes', 'property', 'font-face']);
14
+ const EXTERNAL_URL = /url\(\s*(?!["']?\s*data:)/i;
15
+ const REFUSED_TEXT = /<\/style|--pt-/i;
16
+ /** The `@media` features the server refuses: the canvas, not the window, sets them. */
17
+ const SIZE_FEATURE = /\b(?:min-|max-)?(?:width|height|aspect-ratio|orientation)\b/i;
18
+ /** Splits `css` into its top-level statements and blocks, strings and brackets kept whole. */
19
+ function parse(css) {
20
+ const nodes = [];
21
+ let index = 0;
22
+ while (index < css.length) {
23
+ let cursor = index;
24
+ let quote = null;
25
+ let parens = 0;
26
+ for (; cursor < css.length; cursor++) {
27
+ const char = css[cursor];
28
+ if (quote) {
29
+ if (char === '\\')
30
+ cursor++;
31
+ else if (char === quote)
32
+ quote = null;
33
+ }
34
+ else if (char === '"' || char === "'")
35
+ quote = char;
36
+ else if (char === '(')
37
+ parens++;
38
+ else if (char === ')')
39
+ parens--;
40
+ else if (char === '{' || char === '}' || (char === ';' && parens <= 0))
41
+ break;
42
+ }
43
+ const prelude = css.slice(index, cursor).trim();
44
+ if (cursor >= css.length || css[cursor] === '}') {
45
+ // A rule's last declaration may go without its semicolon; past a stray close nothing more
46
+ // can be read safely.
47
+ if (cursor >= css.length && prelude)
48
+ nodes.push({ kind: 'statement', text: prelude });
49
+ return nodes;
50
+ }
51
+ if (css[cursor] === ';') {
52
+ if (prelude)
53
+ nodes.push({ kind: 'statement', text: prelude });
54
+ index = cursor + 1;
55
+ continue;
56
+ }
57
+ let depth = 1;
58
+ let end = cursor + 1;
59
+ quote = null;
60
+ for (; end < css.length && depth > 0; end++) {
61
+ const char = css[end];
62
+ if (quote) {
63
+ if (char === '\\')
64
+ end++;
65
+ else if (char === quote)
66
+ quote = null;
67
+ }
68
+ else if (char === '"' || char === "'")
69
+ quote = char;
70
+ else if (char === '{')
71
+ depth++;
72
+ else if (char === '}')
73
+ depth--;
74
+ }
75
+ if (depth > 0)
76
+ return nodes;
77
+ nodes.push({ kind: 'rule', prelude, body: css.slice(cursor + 1, end - 1) });
78
+ index = end;
79
+ }
80
+ return nodes;
81
+ }
82
+ /** Splits at the top-level occurrences of `separator`, outside strings, brackets and parens. */
83
+ function splitTop(text, separator) {
84
+ const parts = [];
85
+ let depth = 0;
86
+ let quote = null;
87
+ let start = 0;
88
+ for (let index = 0; index < text.length; index++) {
89
+ const char = text[index];
90
+ if (quote) {
91
+ if (char === '\\')
92
+ index++;
93
+ else if (char === quote)
94
+ quote = null;
95
+ }
96
+ else if (char === '"' || char === "'")
97
+ quote = char;
98
+ else if (char === '(' || char === '[')
99
+ depth++;
100
+ else if (char === ')' || char === ']')
101
+ depth--;
102
+ else if (char === separator && depth === 0) {
103
+ parts.push(text.slice(start, index));
104
+ start = index + 1;
105
+ }
106
+ }
107
+ parts.push(text.slice(start));
108
+ return parts.map((part) => part.trim()).filter(Boolean);
109
+ }
110
+ function stripComments(css) {
111
+ let out = '';
112
+ let quote = null;
113
+ for (let index = 0; index < css.length; index++) {
114
+ const char = css[index];
115
+ if (quote) {
116
+ out += char;
117
+ if (char === '\\')
118
+ out += css[++index] ?? '';
119
+ else if (char === quote)
120
+ quote = null;
121
+ }
122
+ else if (char === '/' && css[index + 1] === '*') {
123
+ const close = css.indexOf('*/', index + 2);
124
+ if (close < 0)
125
+ break;
126
+ index = close + 1;
127
+ }
128
+ else {
129
+ if (char === '"' || char === "'")
130
+ quote = char;
131
+ out += char;
132
+ }
133
+ }
134
+ return out;
135
+ }
136
+ const squash = (text) => text.replace(/\s+/g, ' ').trim();
137
+ /** The compound selectors of `selector` at its top level, with the combinators between them. */
138
+ function compounds(selector) {
139
+ const parts = [];
140
+ let depth = 0;
141
+ let quote = null;
142
+ let current = '';
143
+ for (let index = 0; index < selector.length; index++) {
144
+ const char = selector[index];
145
+ if (quote) {
146
+ current += char;
147
+ if (char === '\\')
148
+ current += selector[++index] ?? '';
149
+ else if (char === quote)
150
+ quote = null;
151
+ continue;
152
+ }
153
+ if (char === '\\') {
154
+ current += char + (selector[++index] ?? '');
155
+ continue;
156
+ }
157
+ if (char === '"' || char === "'")
158
+ quote = char;
159
+ else if (char === '(' || char === '[')
160
+ depth++;
161
+ else if (char === ')' || char === ']')
162
+ depth--;
163
+ else if (depth === 0 && /[\s>+~]/.test(char)) {
164
+ if (current)
165
+ parts.push(current);
166
+ current = '';
167
+ continue;
168
+ }
169
+ current += char;
170
+ }
171
+ if (current)
172
+ parts.push(current);
173
+ return parts;
174
+ }
175
+ const unescapeIdent = (ident) => ident.replace(/\\([0-9a-f]{1,6}\s?|[\s\S])/gi, (_, escaped) => /^[0-9a-f]{1,6}\s?$/i.test(escaped)
176
+ ? String.fromCodePoint(parseInt(escaped.trim(), 16))
177
+ : escaped);
178
+ /** The class names a selector names, anywhere in it, unescaped. */
179
+ function classNames(selector) {
180
+ const withoutStrings = selector.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/g, '""');
181
+ return [
182
+ ...withoutStrings.matchAll(/\.((?:[\w-]|\\[0-9a-f]{1,6}\s?|\\[\s\S]|[^\x00-\x7f])+)/gi),
183
+ ].map((match) => unescapeIdent(match[1]));
184
+ }
185
+ const ROOT_COMPOUND = /^(?::root|:host|html|body)(?![\w-]|\()/i;
186
+ const ROOT_PSEUDO = /:(?:root|host)(?![\w-])/i;
187
+ const DARK_COMPOUND = /^\.dark(?![\w-]|\\)/;
188
+ /** Whether the server reads `selector` as inside the canvas (content-checks.ts `styleIssues`). */
189
+ const staysInCanvas = (selector) => /^\.pt-canvas(?![\w-])/.test(selector) &&
190
+ !/^\.pt-canvas(?:[.:#[][^\s>~+]*)?\s*[~+]/.test(selector);
191
+ /** `selector` on the canvas: none when it cannot be, two for a leading `.dark` theme class. */
192
+ function scopeSelector(selector) {
193
+ if (/^\.pt-canvas(?![\w-])/.test(selector))
194
+ return [selector];
195
+ const [first, ...rest] = compounds(selector);
196
+ if (!first)
197
+ return [];
198
+ const restText = selector.slice(selector.indexOf(first) + first.length);
199
+ // The page root, later in a selector (`html body`, `[dir] :root`), has no place in the canvas.
200
+ if (rest.some((part) => /^(?:html|body)(?![\w-])/i.test(part) || ROOT_PSEUDO.test(part)))
201
+ return [];
202
+ const root = first.match(ROOT_COMPOUND);
203
+ if (root)
204
+ return [`${CANVAS}${first.slice(root[0].length)}${restText}`];
205
+ // The dark theme is a class on the canvas (`pt-canvas dark`), or on a part inside it.
206
+ if (DARK_COMPOUND.test(first))
207
+ return [`${CANVAS}${selector}`, `${CANVAS} ${selector}`];
208
+ return [`${CANVAS} ${selector}`];
209
+ }
210
+ /** A rule's declarations without those that load, set the shell tokens or close the style. */
211
+ function cleanDeclarations(body) {
212
+ const kept = splitTop(body, ';')
213
+ .filter((declaration) => !EXTERNAL_URL.test(declaration) && !REFUSED_TEXT.test(declaration))
214
+ .map((declaration) => declaration.replace(/\s*\n\s*/g, ' '));
215
+ return kept.length ? kept.join(';') : null;
216
+ }
217
+ /** `@media` queries on the window's width as `@container canvas` ones; null when they cannot be. */
218
+ function mediaToContainer(query) {
219
+ const parts = splitTop(query, ',').map((part) => part.replace(/^(?:only\s+)?(?:screen|all)\s+and\s+/i, '').trim());
220
+ const conditions = [];
221
+ for (const part of parts) {
222
+ const features = part.split(/\s+and\s+/i);
223
+ const widthOnly = features.every((feature) => /^\(\s*(?:(?:min-|max-)?width\s*:[^()]*|[^()]*\bwidth\s*[<>=][^()]*)\)$/i.test(feature));
224
+ if (!widthOnly)
225
+ return null;
226
+ conditions.push(features.length > 1 && parts.length > 1 ? `(${part})` : part);
227
+ }
228
+ return conditions.length ? `canvas ${conditions.join(' or ')}` : null;
229
+ }
230
+ /**
231
+ * A style rule with nested blocks, flat: its own declarations, then each nested at-rule around
232
+ * the rule's selector and each nested rule with its selector resolved, in order, so the
233
+ * cascade is unchanged. Tailwind nests its `@supports` colour fallbacks this way.
234
+ */
235
+ function flattenRule(prelude, body) {
236
+ const items = parse(body);
237
+ const declarations = items.flatMap((item) => (item.kind === 'statement' ? [item.text] : []));
238
+ const parents = splitTop(prelude, ',');
239
+ const nodes = declarations.length
240
+ ? [{ kind: 'rule', prelude, body: declarations.join(';') }]
241
+ : [];
242
+ for (const item of items) {
243
+ if (item.kind !== 'rule')
244
+ continue;
245
+ if (item.prelude.startsWith('@'))
246
+ nodes.push({ kind: 'rule', prelude: item.prelude, body: `${prelude}{${item.body}}` });
247
+ else {
248
+ const selectors = splitTop(item.prelude, ',').flatMap((child) => parents.map((parent) => child.includes('&') ? child.replaceAll('&', `:is(${parent})`) : `${parent} ${child}`));
249
+ nodes.push(...flattenRule(selectors.join(','), item.body));
250
+ }
251
+ }
252
+ return nodes;
253
+ }
254
+ function scopeNodes(nodes, scope) {
255
+ const out = [];
256
+ for (const node of nodes) {
257
+ if (node.kind === 'statement') {
258
+ // Only the layer order statement stays; @import, @charset, @source and the like go.
259
+ if (/^@layer\s+[\w-]+(?:\s*,\s*[\w-]+)*$/i.test(node.text))
260
+ out.push(`${squash(node.text)};`);
261
+ continue;
262
+ }
263
+ const { prelude, body } = node;
264
+ if (prelude.startsWith('@')) {
265
+ const name = prelude
266
+ .slice(1)
267
+ .split(/[\s({]/)[0]
268
+ .toLowerCase();
269
+ const params = prelude.slice(name.length + 1).trim();
270
+ if (OPAQUE.has(name)) {
271
+ if (EXTERNAL_URL.test(prelude + body) || REFUSED_TEXT.test(prelude + body))
272
+ continue;
273
+ out.push(`${squash(prelude)}{${squash(body)}}`);
274
+ continue;
275
+ }
276
+ if (!GROUPS.has(name))
277
+ continue;
278
+ let head = squash(prelude);
279
+ if (name === 'media') {
280
+ if (/^(?:only\s+)?print\b/i.test(params))
281
+ continue;
282
+ if (SIZE_FEATURE.test(params)) {
283
+ const container = mediaToContainer(params);
284
+ if (!container)
285
+ continue;
286
+ head = `@container ${container}`;
287
+ }
288
+ }
289
+ if (EXTERNAL_URL.test(head) || REFUSED_TEXT.test(head))
290
+ continue;
291
+ const inner = scopeNodes(parse(body), {
292
+ ...scope,
293
+ utilities: scope.utilities || (name === 'layer' && params === 'utilities'),
294
+ });
295
+ if (inner.length)
296
+ out.push(`${head}{${inner.join('')}}`);
297
+ continue;
298
+ }
299
+ if (body.includes('{')) {
300
+ out.push(...scopeNodes(flattenRule(prelude, body), scope));
301
+ continue;
302
+ }
303
+ const declarations = cleanDeclarations(body);
304
+ if (!declarations)
305
+ continue;
306
+ const selectors = new Set();
307
+ for (const selector of splitTop(squash(prelude), ',')) {
308
+ if (REFUSED_TEXT.test(selector))
309
+ continue;
310
+ if (!scope.utilities &&
311
+ classNames(selector).some((name) => name !== 'dark' && !scope.known.has(name)))
312
+ continue;
313
+ for (const scoped of scopeSelector(selector))
314
+ if (staysInCanvas(scoped))
315
+ selectors.add(scoped);
316
+ }
317
+ if (selectors.size)
318
+ out.push(`${[...selectors].join(',')}{${declarations}}`);
319
+ }
320
+ return out;
321
+ }
322
+ /** Drops the top-level `@keyframes` that nothing kept names. */
323
+ function dropUnusedKeyframes(blocks) {
324
+ const keyframes = /^@(?:-webkit-)?keyframes\s+([^\s{]+)/i;
325
+ const used = blocks.filter((block) => !keyframes.test(block)).join('\n');
326
+ return blocks.filter((block) => {
327
+ const name = block.match(keyframes)?.[1]?.replace(/^["']|["']$/g, '');
328
+ if (!name)
329
+ return true;
330
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
331
+ return new RegExp(`(?:^|[^\\w-])${escaped}(?![\\w-])`).test(used);
332
+ });
333
+ }
334
+ /**
335
+ * The CSS of a Tailwind build, scoped to the canvas, with only the entry's plain rules whose
336
+ * classes are all among `candidates` (the class-like tokens of content.js).
337
+ */
338
+ export function scopeToCanvas(css, candidates) {
339
+ const known = new Set(candidates);
340
+ const blocks = scopeNodes(parse(stripComments(css)), { known, utilities: false });
341
+ return dropUnusedKeyframes(blocks).join('\n') + '\n';
342
+ }
@@ -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
+ }