@buffcore/cli 0.8.44 → 0.8.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,19 @@ One section per release (a git tag). **Upgrade notes** list anything that breaks
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## v0.8.45 (2026-12-03)
8
+
9
+ - The studio's Prototype is a workspace: along the top, the change and its version (Compare, Approve), **Customer app | Console**, **Mobile | Tablet | Desktop** (Rotate for a tablet) and the tools **Select | Comment | Draw | Area**; on the left, **Journeys** (from `plan/journeys.md`, by who does them and in which app, joined to the journeys the running app plays; the open one lists its steps to jump to) and **Screens**, with the sample data at the foot; in the middle, the app in its device, zoomed to fit, with a line saying what you see and the step bar (Back, the step, Play, Next) under it. The console is a second frame at the stack's admin address: switching keeps each one's step and never reloads the other. The rail folds to its icons on this page. At phone width a phone's app takes the page (a tablet or a desktop is drawn in its bezel, zoomed to fit), the device choice shows as icons, and a bar sits at the app's foot (Journeys, Back, the step, Next, Changes); on a touch screen the Comment hint says tap. The preview's Try a journey and Preview options menus, the canvas's Full screen button and the drawn-only full-screen scenes are gone.
10
+
11
+ **Upgrade notes** (hosts that build on `@buffcore/admin-shell/workbench`): the drawn-only full screen is removed from the public types: `LOOP_MOMENTS` (and so `LoopMoment`) no longer has `fs-tablet`, `fs-overview` or `fs-change`, `LoopSample` no longer has `fs`, and `FsSample` and `FsMark` are gone; delete them from your own sample data. The studio catalog's `studio.loop.proto.fullScreen` and `studio.loop.fs.*` messages are gone too, so drop any override of them. `ProtoSample` gains an optional `consoleOthers` (the console's scenes for the workspace's Screens).
12
+ - Marking in the Prototype workspace, with the bar's tools (or the keys V, C, P and R; Escape for Select) and their hint in the line above the device: Comment pins a numbered note on the part clicked (the running app names it, "Comment on Price", by its accessible label or test id, else "this spot"), Area drags a dashed box and Draw marks freehand. The marks are kept per change and version until sent and listed above the chat's box, each with its number, kind, screen and device (a mark records the app, the device, a turned tablet, and the journey step or sample data shown; a click shows them again), its note and Remove, with Clear all and a box for anything else. One **Send N changes** sends one message with every mark, its note and its place, and a picture of each marked screen, shot by the snapshot's browser at that device with the marks drawn (`POST /api/prototype/shot`); while the agent works it waits in the chat as one card (Edit, Back to the box) and goes when the turn ends. The bridge's new `ape:prototype:part` ask goes only on the private port of the current hello and its answer is read strictly: only a name and a box, never the app's data. At phone width the foot bar's Changes counts the marks. `TextArea` gains `labelHidden`; the icon set gains `tablet`. Known limits: marks go on the customer app only, so on the Console the marking tools are off and the line above the device says why (a picture of the console would need a signed-in browser); and the picture's browser refuses requests and WebSockets to other hosts and a page that ends on another address, but a redirect the app's own server answers is followed before that check (the app's server could fetch that address anyway).
13
+
14
+ **Upgrade notes** (every product): keep `@buffcore/app-shell` and `@buffcore/admin-shell` on the same release (`ape upgrade` does); an older prototype home does not answer the part ask, so a comment is on "this spot".
15
+ - The Brief reads short first: What it is; Who uses it as a table (role, where, what we know); Kind; How it earns with the money seal; Must have and Not now side by side, the first few of each with "N more"; Not this project, each line with Edit and Add a line (both a message to the agent, as adding was); the agent's questions. Each section's Read more opens its whole text from `plan/brief.md` in a reading sheet (headings, real lists, about 68 characters a line, the product's Markdown shown as text only), and the brief's other sections open from one Read the whole brief. The short form is the `> Summary:` line the agent writes under each heading (one per role in Who it is for, one per item in Must do and Later); a section without one shows its first sentence, and a section the brief does not have is not shown. The studio state's brief gains `parts` (each section's summaries and Markdown); `Markdown` reads numbered lists and takes `size="read"`, and `Sheet` takes `size="read"` and a `sub` line.
16
+
17
+ **Upgrade notes** (every product): the brief template and the `ape-plan-change` skill now ask for a `> Summary:` line under each heading of `plan/brief.md`; `ape upgrade` refreshes the skill. An existing brief works as it is (each section shows its first sentence); to read it short, ask the agent to add the summary lines.
18
+ - The studio's scroll bars are a little easier to find: the thumb is a little stronger than a border.
19
+
7
20
  ## v0.8.44 (2026-12-02)
8
21
 
9
22
  - A host whose own trusted launcher starts the agent's turns can say so: `createUiServer({ hostLaunched: true })`, or `APE_HOST_LAUNCHED=1` in the environment of `ape ui` (exactly `1`). Every Claude Code turn (coding, Build, design, validation, tests, fixes, planning on Autopilot) then launches exactly as a 0.8.41 turn did: no per-turn `--settings` file with the limits hook, no `--mcp-config` with the permission tool, no `--permission-prompt-tool` and no per-turn socket; `acceptEdits`, or `dontAsk` with hooks off for planning, at every level (never `auto` or `bypassPermissions`, Autopilot and Never ask included), with 0.8.41's allow and deny lists. Fresh turns (the review before Save and the critique) follow it: hooks off through the inline `--settings` JSON, no settings file and no `--setting-sources=`. Settings says once that the host starts the agents and applies their limits (English and Spanish), and the studio state gains an optional `hostLaunched`. Off by default: nothing changes for a host that passes nothing.
@@ -0,0 +1,31 @@
1
+ import type { MarkShotBody } from '@buffcore/contracts/workbench';
2
+ import type { Browser } from 'playwright-core';
3
+ /** The running app's prototype home at the marked step or data, as the studio frames it. */
4
+ export declare function shotAddress(app: string, body: MarkShotBody, navigation: string): URL;
5
+ /**
6
+ * Runs inside the page (Playwright sends its source): one layer over the screen with each mark,
7
+ * an area dashed, a drawing as its line, and every mark's number in a dot. Only numbers are drawn:
8
+ * a note never reaches the page. The colors are fixed, not the app's: they must read on any app.
9
+ */
10
+ export declare function drawMarks(marks: MarkShotBody['marks']): void;
11
+ /** The whole picture (load, fonts, marks and the shot itself) is done within this, or refused (ms). */
12
+ export declare const SHOT_LIMIT = 30000;
13
+ /** The shot took longer than its limit: its context was closed. */
14
+ export declare class ShotTimeout extends Error {
15
+ }
16
+ /** A WebSocket address on the app's own origin: ws for http, wss for https, the same host. */
17
+ export declare function sameHost(socket: URL, app: URL): boolean;
18
+ /** The page left the app's own address before the shot. */
19
+ export declare class ShotMoved extends Error {
20
+ }
21
+ /**
22
+ * Runs inside the page: scrolls the page, and its tallest scroller, as the app was scrolled when
23
+ * marked (the same rule finds the scroller as the app's own answer does).
24
+ */
25
+ export declare function scrollTo(scroll: NonNullable<MarkShotBody['scroll']>): void;
26
+ /**
27
+ * Opens `url` at the marked size in a fresh context, scrolled as marked, draws the marks and returns
28
+ * the PNG, all within `limit` ms. The context reaches only the app's own origin: any request to
29
+ * another host is refused, and a page that left the address (a redirect) is not shot.
30
+ */
31
+ export declare function shootMarks(browser: Browser, url: URL, body: MarkShotBody, limit?: number): Promise<Buffer>;
@@ -0,0 +1,149 @@
1
+ /** How long the page's own requests get to settle before the picture is taken (ms). */
2
+ const SETTLE = 5_000;
3
+ /** The running app's prototype home at the marked step or data, as the studio frames it. */
4
+ export function shotAddress(app, body, navigation) {
5
+ const url = new URL(app);
6
+ url.pathname = `${url.pathname.replace(/\/+$/, '')}/prototype`;
7
+ url.search = new URLSearchParams({
8
+ embed: '1',
9
+ apeNav: navigation,
10
+ studioPreview: '1',
11
+ locale: body.locale,
12
+ mode: body.mode,
13
+ ...(body.journey ? { journey: body.journey, step: String(body.step ?? 0) } : {}),
14
+ ...(body.data ? { data: body.data } : {}),
15
+ }).toString();
16
+ url.hash = '';
17
+ return url;
18
+ }
19
+ /**
20
+ * Runs inside the page (Playwright sends its source): one layer over the screen with each mark,
21
+ * an area dashed, a drawing as its line, and every mark's number in a dot. Only numbers are drawn:
22
+ * a note never reaches the page. The colors are fixed, not the app's: they must read on any app.
23
+ */
24
+ export function drawMarks(marks) {
25
+ const svg = 'http://www.w3.org/2000/svg';
26
+ const layer = document.createElementNS(svg, 'svg');
27
+ layer.setAttribute('width', String(window.innerWidth));
28
+ layer.setAttribute('height', String(window.innerHeight));
29
+ layer.setAttribute('style', 'position:fixed;inset:0;z-index:2147483647;pointer-events:none;overflow:visible');
30
+ const add = (name, attributes) => {
31
+ const node = document.createElementNS(svg, name);
32
+ for (const [key, value] of Object.entries(attributes))
33
+ node.setAttribute(key, String(value));
34
+ layer.appendChild(node);
35
+ return node;
36
+ };
37
+ const line = { fill: 'none', stroke: '#2563eb', 'stroke-linecap': 'round' };
38
+ for (const mark of marks) {
39
+ if (mark.kind === 'area' && mark.box)
40
+ add('rect', {
41
+ ...line,
42
+ x: mark.box.x,
43
+ y: mark.box.y,
44
+ width: mark.box.w,
45
+ height: mark.box.h,
46
+ rx: 4,
47
+ 'stroke-width': 2,
48
+ 'stroke-dasharray': '6 4',
49
+ });
50
+ if (mark.kind === 'draw' && mark.points)
51
+ add('polyline', {
52
+ ...line,
53
+ points: mark.points.map(([x, y]) => `${x},${y}`).join(' '),
54
+ 'stroke-width': 3,
55
+ 'stroke-linejoin': 'round',
56
+ });
57
+ const [x, y] = mark.box ? [mark.box.x, mark.box.y] : (mark.points?.[0] ?? [0, 0]);
58
+ add('circle', { cx: x, cy: y, r: 12, fill: '#2563eb', stroke: '#ffffff', 'stroke-width': 2 });
59
+ const label = add('text', {
60
+ x,
61
+ y,
62
+ fill: '#ffffff',
63
+ 'font-family': 'system-ui, sans-serif',
64
+ 'font-size': 12,
65
+ 'font-weight': 700,
66
+ 'text-anchor': 'middle',
67
+ 'dominant-baseline': 'central',
68
+ });
69
+ label.textContent = String(mark.n);
70
+ }
71
+ document.body.appendChild(layer);
72
+ }
73
+ /** The whole picture (load, fonts, marks and the shot itself) is done within this, or refused (ms). */
74
+ export const SHOT_LIMIT = 30_000;
75
+ /** The shot took longer than its limit: its context was closed. */
76
+ export class ShotTimeout extends Error {
77
+ }
78
+ /** A WebSocket address on the app's own origin: ws for http, wss for https, the same host. */
79
+ export function sameHost(socket, app) {
80
+ const scheme = { 'ws:': 'http:', 'wss:': 'https:' }[socket.protocol];
81
+ return scheme === app.protocol && socket.host === app.host;
82
+ }
83
+ /** The page left the app's own address before the shot. */
84
+ export class ShotMoved extends Error {
85
+ }
86
+ /**
87
+ * Runs inside the page: scrolls the page, and its tallest scroller, as the app was scrolled when
88
+ * marked (the same rule finds the scroller as the app's own answer does).
89
+ */
90
+ export function scrollTo(scroll) {
91
+ window.scrollTo(scroll.page.x, scroll.page.y);
92
+ let tallest;
93
+ let most = 0;
94
+ const all = document.body?.querySelectorAll('*') ?? [];
95
+ for (let i = 0; i < all.length && i < 20_000; i++) {
96
+ const el = all[i];
97
+ const room = el.scrollHeight - el.clientHeight;
98
+ if (room > most && /auto|scroll|overlay/.test(getComputedStyle(el).overflowY)) {
99
+ most = room;
100
+ tallest = el;
101
+ }
102
+ }
103
+ tallest?.scrollTo(scroll.inner.x, scroll.inner.y);
104
+ }
105
+ /**
106
+ * Opens `url` at the marked size in a fresh context, scrolled as marked, draws the marks and returns
107
+ * the PNG, all within `limit` ms. The context reaches only the app's own origin: any request to
108
+ * another host is refused, and a page that left the address (a redirect) is not shot.
109
+ */
110
+ export async function shootMarks(browser, url, body, limit = SHOT_LIMIT) {
111
+ const context = await browser.newContext({
112
+ viewport: body.view,
113
+ deviceScaleFactor: 1,
114
+ colorScheme: body.mode,
115
+ locale: body.locale,
116
+ serviceWorkers: 'block',
117
+ });
118
+ let timer;
119
+ const expired = new Promise((_, reject) => {
120
+ timer = setTimeout(() => reject(new ShotTimeout(`no picture within ${limit} ms`)), limit);
121
+ });
122
+ const shot = async () => {
123
+ // tsx names functions with `__name`; functions sent to the page need it there too.
124
+ await context.addInitScript({ content: 'globalThis.__name = (fn) => fn;' });
125
+ await context.route('**/*', (route) => new URL(route.request().url()).origin === url.origin ? route.continue() : route.abort());
126
+ // A WebSocket to another host is closed before it connects; the app's own goes through.
127
+ await context.routeWebSocket((socket) => !sameHost(socket, url), (socket) => socket.close());
128
+ const page = await context.newPage();
129
+ await page.goto(url.href, { waitUntil: 'load', timeout: limit });
130
+ await page.waitForLoadState('networkidle', { timeout: SETTLE }).catch(() => undefined);
131
+ await page.evaluate(() => document.fonts?.ready.then(() => true));
132
+ if (body.scroll)
133
+ await page.evaluate(scrollTo, body.scroll);
134
+ await page.evaluate(drawMarks, body.marks);
135
+ if (new URL(page.url()).origin !== url.origin)
136
+ throw new ShotMoved(`the page left ${url.origin}`);
137
+ return await page.screenshot({ animations: 'disabled', type: 'png' });
138
+ };
139
+ const running = shot();
140
+ running.catch(() => undefined);
141
+ try {
142
+ return await Promise.race([running, expired]);
143
+ }
144
+ finally {
145
+ clearTimeout(timer);
146
+ // Closing the context ends whatever the shot was still waiting for.
147
+ await context.close().catch(() => undefined);
148
+ }
149
+ }
@@ -25,6 +25,9 @@ export declare const en: {
25
25
  'ui.compare.noGit': string;
26
26
  'ui.compare.unexpected': string;
27
27
  'ui.snapshot.noChange': string;
28
+ 'ui.shot.invalid': string;
29
+ 'ui.shot.notRunning': string;
30
+ 'ui.shot.failed': string;
28
31
  'ui.snapshot.readFailed': string;
29
32
  'ui.snapshot.proof': string;
30
33
  'ui.snapshot.linked': string;
@@ -25,6 +25,9 @@ export const en = {
25
25
  'ui.compare.noGit': 'Git could not read the repository history. Check the checkout and make sure the commits for the comparison are available.',
26
26
  'ui.compare.unexpected': 'The comparison failed unexpectedly. Run pnpm ape prototype versions --json. If that fails, check the change’s file in prototype/versions/. If the versions look right, report the comparison failure.',
27
27
  'ui.snapshot.noChange': 'There is no change selected for a snapshot.',
28
+ 'ui.shot.invalid': 'The studio asked for a picture it cannot take.',
29
+ 'ui.shot.notRunning': 'The app is not running, so its marked screen cannot be shot.',
30
+ 'ui.shot.failed': 'The marked screen could not be shot: {reason}',
28
31
  'ui.snapshot.readFailed': 'Git could not read the saved source.',
29
32
  'ui.snapshot.proof': 'Record version needs unchanged passing snapshot proof for this change, saved source and checkout. Save the review files and take a new snapshot if needed.',
30
33
  'ui.snapshot.linked': '{coding, select, yes {{here, select, yes {This studio is open in the checkout where {change} is being built} other {{change} is being built in its own checkout}}. Its approved prototype is on main, so there is nothing to record from that checkout. Take snapshot draws it there with its own servers, and Save keeps its snapshot files on the change’s branch.} other {{here, select, yes {This studio is open in {change}’s own checkout} other {{change} is checked out in {path}}}. Take snapshot draws it there with its own servers, and Save keeps its snapshot files on the change’s branch. The studio records only on main, so in a terminal in {here, select, yes {this folder} other {that folder}}: commit all its changes and the new prototype/snapshots folder, then run pnpm ape prototype version {change} --why "what changed".}}',
@@ -25,6 +25,9 @@ export declare const es: {
25
25
  'ui.compare.noGit': string;
26
26
  'ui.compare.unexpected': string;
27
27
  'ui.snapshot.noChange': string;
28
+ 'ui.shot.invalid': string;
29
+ 'ui.shot.notRunning': string;
30
+ 'ui.shot.failed': string;
28
31
  'ui.snapshot.readFailed': string;
29
32
  'ui.snapshot.proof': string;
30
33
  'ui.snapshot.linked': string;
@@ -25,6 +25,9 @@ export const es = {
25
25
  'ui.compare.noGit': 'Git no pudo leer el historial del repositorio. Revisa la copia de trabajo y comprueba que los commits de la comparación estén disponibles.',
26
26
  'ui.compare.unexpected': 'La comparación falló de forma inesperada. Ejecuta pnpm ape prototype versions --json. Si ese comando falla, revisa el archivo del cambio en prototype/versions/. Si las versiones son correctas, informa del fallo de la comparación.',
27
27
  'ui.snapshot.noChange': 'No hay ningún cambio seleccionado para una instantánea.',
28
+ 'ui.shot.invalid': 'El estudio pidió una imagen que no se puede tomar.',
29
+ 'ui.shot.notRunning': 'La app no está en marcha, así que no se puede capturar la pantalla marcada.',
30
+ 'ui.shot.failed': 'No se pudo capturar la pantalla marcada: {reason}',
28
31
  'ui.snapshot.readFailed': 'Git no pudo leer el código guardado.',
29
32
  'ui.snapshot.proof': 'Registrar versión necesita una prueba de captura válida y sin cambios para este cambio, código guardado y copia de trabajo. Guarda los archivos de revisión y toma una nueva captura si es necesario.',
30
33
  'ui.snapshot.linked': '{coding, select, yes {{here, select, yes {Este estudio está abierto en la copia de trabajo donde se está construyendo {change}} other {{change} se está construyendo en su propia copia de trabajo}}. Su prototipo aprobado está en main, así que no hay nada que registrar desde esa copia de trabajo. Tomar instantánea la dibuja allí con sus propios servidores, y Guardar conserva los archivos de su instantánea en la rama del cambio.} other {{here, select, yes {Este estudio está abierto en la copia de trabajo propia de {change}} other {{change} está en la copia de trabajo {path}}}. Tomar instantánea la dibuja allí con sus propios servidores, y Guardar conserva los archivos de su instantánea en la rama del cambio. El estudio registra solo en main, así que en una terminal en {here, select, yes {esta carpeta} other {esa carpeta}}: haz commit de todos sus cambios y de la nueva carpeta prototype/snapshots, y luego ejecuta pnpm ape prototype version {change} --why "qué cambió".}}',
@@ -0,0 +1,13 @@
1
+ import type { PlanFacts } from '@buffcore/contracts/workbench';
2
+ export declare const withoutComments: (text: string) => string;
3
+ export declare const answer: (text: string) => string;
4
+ export declare const plain: (text: string) => string;
5
+ /** A newline wraps a paragraph or list item; only a new marker starts another item. */
6
+ export declare function briefSection(text: string, words?: (text: string) => string): string;
7
+ /** Section spelling, fences and closing hashes follow the original Brief reader. */
8
+ export declare function planSections(text: string): {
9
+ heading: string;
10
+ body: string;
11
+ }[];
12
+ /** Section headings stay as written; the template's prompts are not answers. */
13
+ export declare function parseBrief(text: string | null): PlanFacts['brief'];
@@ -0,0 +1,91 @@
1
+ export const withoutComments = (text) => text.replace(/<!--[\s\S]*?(?:-->|$)/g, '');
2
+ // The base readers' grammar, shared by bounded plan previews as well as Brief and Roadmap.
3
+ export const answer = (text) => text
4
+ // Without a closing > the tag alternative cannot match. Keep the original code grammar.
5
+ .replace(text.includes('>') ? /`+([^`]*)`+|<[^>]*>/g : /`+([^`]*)`+/g, (_match, code) => code ?? '')
6
+ .replace(/^\s*(?:[-*+]|\d+[.)])\s*$/gm, '')
7
+ .trim();
8
+ export const plain = (text) => {
9
+ const words = answer(text);
10
+ // The original link expression cannot match without ](. This guard changes no output.
11
+ return (words.includes('](') ? words.replace(/!?\[([^\]]*)\]\((?:[^()]|\([^()]*\))*\)/g, '$1') : words).replace(/\*\*|__|`/g, '');
12
+ };
13
+ /** A newline wraps a paragraph or list item; only a new marker starts another item. */
14
+ export function briefSection(text, words = plain) {
15
+ const lines = [];
16
+ for (const raw of words(text).split(/\r?\n/)) {
17
+ const line = raw.trim();
18
+ const marker = /^(?:[-*+]|\d+[.)])\s+/;
19
+ if (marker.test(line))
20
+ lines.push(line.replace(marker, '- '));
21
+ else if (line && lines.at(-1))
22
+ lines[lines.length - 1] += ` ${line}`;
23
+ else
24
+ lines.push(line);
25
+ }
26
+ return lines.join('\n').trim();
27
+ }
28
+ /** Section spelling, fences and closing hashes follow the original Brief reader. */
29
+ export function planSections(text) {
30
+ return text
31
+ .split(/^##\s+/m)
32
+ .slice(1)
33
+ .map((part) => {
34
+ const [heading = '', ...body] = part.split(/\r?\n/);
35
+ return { heading: heading.trim(), body: body.join('\n') };
36
+ });
37
+ }
38
+ /**
39
+ * A section's short form: `> Summary: one line`, as many as the section needs (one per role). Also
40
+ * `> Resumen:`, and the word in bold.
41
+ */
42
+ const SUMMARY = /^\s*>\s*(?:\*\*|__)?(?:summary|resumen)(?:\*\*|__)?\s*:\s*(?:\*\*|__)?\s*(.*)$/i;
43
+ /**
44
+ * The template's prompts, in their own form: a line (or a list item) that is all `<Words...>`, the
45
+ * first a capital, wrapping onto the next lines with no blank line between, and never holding an
46
+ * address (`://`, `@`) or another `<` or `>`. Nothing else is taken for a tag: `age < 18`,
47
+ * `<https://...>` and `<help@...>` are the person's words, and the studio shows them as text.
48
+ */
49
+ const PROMPT = /^[ \t]*(?:(?:[-*+]|\d+[.)])[ \t]+)?<(?=[A-Z])(?![^>]*:\/\/)[^<>@\n]*(?:\n[ \t]*[^<>@\s][^<>@\n]*)*>[ \t]*$/gm;
50
+ /** The brief's words: the base grammar, without reading `<` and `>` as tags. */
51
+ const briefWords = (text) => text
52
+ .replace(/`+([^`]*)`+/g, '$1')
53
+ .replace(/!?\[([^\]]*)\]\((?:[^()]|\([^()]*\))*\)/g, '$1')
54
+ .replace(/\*\*|__/g, '')
55
+ .replace(/^\s*(?:[-*+]|\d+[.)])\s*$/gm, '')
56
+ .trim();
57
+ /**
58
+ * One section: its summary lines (template prompts and Markdown removed), and the rest as written,
59
+ * without the template's `<prompts>`, for reading.
60
+ */
61
+ function briefPart(heading, body) {
62
+ const lines = body.split(/\r?\n/);
63
+ const summary = lines.flatMap((line) => {
64
+ const words = plain(SUMMARY.exec(line)?.[1] ?? '');
65
+ return words ? [words] : [];
66
+ });
67
+ const rest = lines
68
+ .filter((line) => !SUMMARY.test(line))
69
+ .join('\n')
70
+ .replace(PROMPT, '');
71
+ const text = rest.replace(/\n{3,}/g, '\n\n').trim();
72
+ return { part: { heading, summary, text }, rest };
73
+ }
74
+ /** Section headings stay as written; the template's prompts are not answers. */
75
+ export function parseBrief(text) {
76
+ if (text === null)
77
+ return null;
78
+ const sections = {};
79
+ const parts = [];
80
+ for (const { heading, body } of planSections(withoutComments(text))) {
81
+ const { part, rest } = briefPart(heading, body);
82
+ // A section with only its summary is answered: the summary is its words.
83
+ sections[heading] = briefSection(rest, briefWords) || part.summary.join('\n');
84
+ if (part.text || part.summary.length)
85
+ parts.push(part);
86
+ }
87
+ const kindPart = parts.find((part) => /b2b|b2c|kind/i.test(part.heading));
88
+ const kindWords = kindPart ? `${kindPart.summary.join('\n')}\n${kindPart.text}` : '';
89
+ const kind = /\bb2([bc])\b/i.exec(kindWords)?.[1]?.toLowerCase();
90
+ return { sections, parts, ...(kind ? { kind: kind === 'b' ? 'b2b' : 'b2c' } : {}) };
91
+ }
@@ -1,23 +1,13 @@
1
1
  import type { PlanFacts } from '@buffcore/contracts/workbench';
2
2
  import { type Change } from '../change-file.ts';
3
+ export { answer, briefSection, parseBrief, plain, planSections, withoutComments, } from './plan-brief.ts';
3
4
  export { parseJourneys } from './plan-journeys.ts';
4
- export declare const withoutComments: (text: string) => string;
5
5
  export declare function textAt(root: string, file: string): Promise<string | null>;
6
- export declare const answer: (text: string) => string;
7
- export declare const plain: (text: string) => string;
8
- /** A newline wraps a paragraph or list item; only a new marker starts another item. */
9
- export declare function briefSection(text: string): string;
10
- /** Section spelling, fences and closing hashes follow the original Brief reader. */
11
- export declare function planSections(text: string): {
12
- heading: string;
13
- body: string;
14
- }[];
15
6
  /** The base change reader's list grammar; prose never becomes an inferred step. */
16
7
  export declare function stepItems(text: string, read?: (text: string, index: number) => string): string[];
17
8
  export declare const journeyStepItems: (text: string) => string[];
18
9
  /** Section headings stay as written; the template's prompts are not answers. */
19
10
  export declare function readBrief(root: string): Promise<PlanFacts['brief']>;
20
- export declare function parseBrief(text: string | null): PlanFacts['brief'];
21
11
  /** Only actual milestone headings and their change ids; commented examples stay unanswered. */
22
12
  export declare function readRoadmap(root: string): Promise<PlanFacts['milestones']>;
23
13
  export declare function parseRoadmap(text: string): PlanFacts['milestones'];
@@ -5,14 +5,15 @@ import { readChange } from '../change-file.js';
5
5
  import { fourAtATime, needsPrototype, readTree } from '../change-screens.js';
6
6
  import { resolveMode } from '../design/state.js';
7
7
  import { brandMatches, brandPreview } from './brand-approval.js';
8
+ import { answer, parseBrief, plain, withoutComments } from './plan-brief.js';
8
9
  import { changeDetail } from './plan-details.js';
9
10
  import { planHistory } from './plan-history.js';
10
11
  import { parseJourneys } from './plan-journeys.js';
11
12
  import { readNotThis } from './plan-not.js';
12
13
  import { structureFacts } from './plan-structure.js';
13
14
  import { stepFiles } from './save-ownership.js';
15
+ export { answer, briefSection, parseBrief, plain, planSections, withoutComments, } from './plan-brief.js';
14
16
  export { parseJourneys } from './plan-journeys.js';
15
- export const withoutComments = (text) => text.replace(/<!--[\s\S]*?(?:-->|$)/g, '');
16
17
  async function rawTextAt(root, file) {
17
18
  try {
18
19
  return await readFile(join(root, file), 'utf8');
@@ -25,42 +26,6 @@ export async function textAt(root, file) {
25
26
  const text = await rawTextAt(root, file);
26
27
  return text === null ? null : withoutComments(text);
27
28
  }
28
- // The base readers' grammar, shared by bounded plan previews as well as Brief and Roadmap.
29
- export const answer = (text) => text
30
- // Without a closing > the tag alternative cannot match. Keep the original code grammar.
31
- .replace(text.includes('>') ? /`+([^`]*)`+|<[^>]*>/g : /`+([^`]*)`+/g, (_match, code) => code ?? '')
32
- .replace(/^\s*(?:[-*+]|\d+[.)])\s*$/gm, '')
33
- .trim();
34
- export const plain = (text) => {
35
- const words = answer(text);
36
- // The original link expression cannot match without ](. This guard changes no output.
37
- return (words.includes('](') ? words.replace(/!?\[([^\]]*)\]\((?:[^()]|\([^()]*\))*\)/g, '$1') : words).replace(/\*\*|__|`/g, '');
38
- };
39
- /** A newline wraps a paragraph or list item; only a new marker starts another item. */
40
- export function briefSection(text) {
41
- const lines = [];
42
- for (const raw of plain(text).split(/\r?\n/)) {
43
- const line = raw.trim();
44
- const marker = /^(?:[-*+]|\d+[.)])\s+/;
45
- if (marker.test(line))
46
- lines.push(line.replace(marker, '- '));
47
- else if (line && lines.at(-1))
48
- lines[lines.length - 1] += ` ${line}`;
49
- else
50
- lines.push(line);
51
- }
52
- return lines.join('\n').trim();
53
- }
54
- /** Section spelling, fences and closing hashes follow the original Brief reader. */
55
- export function planSections(text) {
56
- return text
57
- .split(/^##\s+/m)
58
- .slice(1)
59
- .map((part) => {
60
- const [heading = '', ...body] = part.split(/\r?\n/);
61
- return { heading: heading.trim(), body: body.join('\n') };
62
- });
63
- }
64
29
  /** The base change reader's list grammar; prose never becomes an inferred step. */
65
30
  export function stepItems(text, read = plain) {
66
31
  const items = [];
@@ -80,17 +45,6 @@ export const journeyStepItems = (text) => plain(text)
80
45
  export async function readBrief(root) {
81
46
  return parseBrief(await rawTextAt(root, stepFiles.brief[0]));
82
47
  }
83
- export function parseBrief(text) {
84
- if (text === null)
85
- return null;
86
- const sections = {};
87
- for (const { heading, body } of planSections(withoutComments(text))) {
88
- sections[heading] = briefSection(body);
89
- }
90
- const kindSection = Object.entries(sections).find(([heading]) => /b2b|b2c|kind/i.test(heading));
91
- const kind = /\bb2([bc])\b/i.exec(kindSection?.[1] ?? '')?.[1]?.toLowerCase();
92
- return { sections, ...(kind ? { kind: kind === 'b' ? 'b2b' : 'b2c' } : {}) };
93
- }
94
48
  /** Only actual milestone headings and their change ids; commented examples stay unanswered. */
95
49
  export async function readRoadmap(root) {
96
50
  return parseRoadmap((await rawTextAt(root, stepFiles.plan[0])) ?? '');
@@ -6,6 +6,11 @@ export declare function planPrototypeOnMain(root: string, plan: PlanFacts | unde
6
6
  brief: {
7
7
  sections: Record<string, string>;
8
8
  kind?: "b2b" | "b2c" | undefined;
9
+ parts?: {
10
+ heading: string;
11
+ summary: string[];
12
+ text: string;
13
+ }[] | undefined;
9
14
  } | null;
10
15
  milestones: {
11
16
  name: string;
@@ -0,0 +1,16 @@
1
+ import { type MarkShotBody } from '@buffcore/contracts/workbench';
2
+ import { launchBrowser } from '../prototype/browser.ts';
3
+ import { shootMarks } from '../prototype/mark-shot.ts';
4
+ import type { UiRoute } from './routes.ts';
5
+ import type { UiServerOptions } from './server.ts';
6
+ export type Shooter = (url: URL, body: MarkShotBody) => Promise<Buffer>;
7
+ /** At most this many pictures are taken at once; the others wait their turn. */
8
+ export declare const SHOTS_AT_ONCE = 2;
9
+ /**
10
+ * One browser for the studio's pictures, launched once however many ask at the same moment, with
11
+ * at most SHOTS_AT_ONCE pictures taken at a time, and closed when no picture was asked for a while.
12
+ */
13
+ export declare function browserShooter(launch?: typeof launchBrowser, shot?: typeof shootMarks): Shooter & {
14
+ close: () => Promise<void>;
15
+ };
16
+ export declare function prototypeShotRoute(options: Pick<UiServerOptions, 'stack'>, shutdown?: AbortSignal, shoot?: Shooter): UiRoute;
@@ -0,0 +1,98 @@
1
+ // `POST /api/prototype/shot`: a picture of the running app at one marked screen and device, with the
2
+ // marks drawn, for the one message that sends them. The snapshot's own browser (Playwright's
3
+ // headless Chromium) opens only this studio's app address; nothing from the request names a host.
4
+ import { randomUUID } from 'node:crypto';
5
+ import { markShotBody, workbenchApi } from '@buffcore/contracts/workbench';
6
+ import { launchBrowser } from '../prototype/browser.js';
7
+ import { shootMarks, shotAddress } from '../prototype/mark-shot.js';
8
+ import { commandT as t } from './commands.js';
9
+ /** The body: a few marks of numbers; a drawing's points are the largest part. */
10
+ const BODY_LIMIT = 200_000;
11
+ /** A picture past this is not sent (a chat image's limit, in base64 characters). */
12
+ const PICTURE_LIMIT = 5 * 1024 * 1024;
13
+ /** The browser closes when no picture was asked for this long (ms). */
14
+ const IDLE = 60_000;
15
+ /** At most this many pictures are taken at once; the others wait their turn. */
16
+ export const SHOTS_AT_ONCE = 2;
17
+ /**
18
+ * One browser for the studio's pictures, launched once however many ask at the same moment, with
19
+ * at most SHOTS_AT_ONCE pictures taken at a time, and closed when no picture was asked for a while.
20
+ */
21
+ export function browserShooter(launch = launchBrowser, shot = shootMarks) {
22
+ let browser;
23
+ let timer;
24
+ let running = 0;
25
+ const waiting = [];
26
+ const close = async () => {
27
+ const open = browser;
28
+ browser = undefined;
29
+ await (await open?.catch(() => undefined))?.close();
30
+ };
31
+ const opened = async () => {
32
+ const current = browser ?? launch();
33
+ browser = current;
34
+ const ready = await current.catch((error) => {
35
+ if (browser === current)
36
+ browser = undefined;
37
+ throw error;
38
+ });
39
+ if (ready.isConnected())
40
+ return ready;
41
+ // Gone (a crash): the first to see it launches again, the others share that launch.
42
+ if (browser === current)
43
+ browser = launch();
44
+ return opened();
45
+ };
46
+ const shoot = async (url, body) => {
47
+ clearTimeout(timer);
48
+ // A finished shot hands its place straight to the next in line.
49
+ if (running < SHOTS_AT_ONCE)
50
+ running += 1;
51
+ else
52
+ await new Promise((turn) => waiting.push(turn));
53
+ try {
54
+ return await shot(await opened(), url, body);
55
+ }
56
+ finally {
57
+ const next = waiting.shift();
58
+ if (next)
59
+ next();
60
+ else
61
+ running -= 1;
62
+ if (!running) {
63
+ timer = setTimeout(() => void close(), IDLE);
64
+ timer.unref?.();
65
+ }
66
+ }
67
+ };
68
+ return Object.assign(shoot, { close });
69
+ }
70
+ export function prototypeShotRoute(options, shutdown, shoot = browserShooter()) {
71
+ const closable = shoot;
72
+ shutdown?.addEventListener('abort', () => void closable.close?.(), { once: true });
73
+ return {
74
+ method: 'POST',
75
+ path: workbenchApi.prototypeShot,
76
+ right: 'build',
77
+ origin: true,
78
+ handle: async ({ body }) => {
79
+ const request = markShotBody.safeParse(await body(BODY_LIMIT).catch(() => undefined));
80
+ if (!request.success)
81
+ return { status: 400, body: { error: t('ui.shot.invalid') } };
82
+ const stack = options.stack.info();
83
+ if (!stack.answers?.app)
84
+ return { status: 409, body: { error: t('ui.shot.notRunning') } };
85
+ try {
86
+ const png = await shoot(shotAddress(stack.app, request.data, randomUUID()), request.data);
87
+ const data = png.toString('base64');
88
+ if (data.length > PICTURE_LIMIT)
89
+ throw new Error('too large');
90
+ return { status: 200, body: { type: 'image/png', data } };
91
+ }
92
+ catch (error) {
93
+ const reason = (error instanceof Error ? error.message : String(error)).split('\n')[0];
94
+ return { status: 503, body: { error: t('ui.shot.failed', { reason }) } };
95
+ }
96
+ },
97
+ };
98
+ }
@@ -1,6 +1,7 @@
1
1
  import { workbenchApi } from '@buffcore/contracts/workbench';
2
2
  import { z } from 'zod';
3
3
  import { readableFields } from './access.js';
4
+ import { prototypeShotRoute } from './prototype-shot-route.js';
4
5
  import { prototypeSnapshotRoute } from './prototype-snapshot.js';
5
6
  import { runRoute } from './run-route.js';
6
7
  import { visibleRuns } from './snapshot-view.js';
@@ -45,6 +46,7 @@ export function coreRoutes(options, shutdown) {
45
46
  },
46
47
  runRoute(options, snapshot.record),
47
48
  snapshot,
49
+ prototypeShotRoute(options, shutdown),
48
50
  {
49
51
  method: 'POST',
50
52
  path: workbenchApi.stack,
@@ -66,10 +66,22 @@ export function createUiServer(input) {
66
66
  });
67
67
  const key = options.runner.cwd ? runnerKey(options.runner.cwd) : undefined;
68
68
  server.on('listening', () => localListener(options, server.address().port));
69
+ // A browser opens spare connections it may never send a request on. close() ends those at once
70
+ // (Node ends only the idle ones), so it never waits on them, and a server started again on the
71
+ // same port answers the tab's next load.
72
+ const unused = new Set();
73
+ server.on('connection', (socket) => {
74
+ unused.add(socket);
75
+ socket.once('close', () => unused.delete(socket));
76
+ });
77
+ server.on('request', (req) => unused.delete(req.socket));
69
78
  const close = server.close;
70
79
  server.close = function (callback) {
71
80
  shutdown.abort();
72
- return close.call(this, callback);
81
+ const closing = close.call(this, callback);
82
+ for (const socket of unused)
83
+ socket.destroy();
84
+ return closing;
73
85
  };
74
86
  if (key)
75
87
  snapshotRunners.set(key, options.runner);
@@ -171,6 +171,11 @@ export declare function studioState(root: string, options: Pick<UiServerOptions,
171
171
  brief: {
172
172
  sections: Record<string, string>;
173
173
  kind?: "b2b" | "b2c" | undefined;
174
+ parts?: {
175
+ heading: string;
176
+ summary: string[];
177
+ text: string;
178
+ }[] | undefined;
174
179
  } | null;
175
180
  milestones: {
176
181
  name: string;