@buffcore/cli 0.8.39 → 0.8.41

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 (34) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/commands/create-steps.en.js +1 -1
  3. package/dist/commands/create-steps.js +1 -1
  4. package/dist/commands/extension/steps.js +6 -2
  5. package/dist/commands/prototype/snapshot-themes.js +3 -1
  6. package/dist/commands/ui/autopilot-records.d.ts +3 -0
  7. package/dist/commands/ui/chat/allow-folder-route.d.ts +9 -0
  8. package/dist/commands/ui/chat/allow-folder-route.js +56 -0
  9. package/dist/commands/ui/chat/allow-folder.d.ts +18 -0
  10. package/dist/commands/ui/chat/allow-folder.js +130 -0
  11. package/dist/commands/ui/chat/ask-person.d.ts +17 -0
  12. package/dist/commands/ui/chat/ask-person.en.d.ts +4 -0
  13. package/dist/commands/ui/chat/ask-person.en.js +4 -0
  14. package/dist/commands/ui/chat/ask-person.es.d.ts +4 -0
  15. package/dist/commands/ui/chat/ask-person.es.js +4 -0
  16. package/dist/commands/ui/chat/ask-person.js +60 -0
  17. package/dist/commands/ui/chat/recorded-turn.js +2 -0
  18. package/dist/commands/ui/chat/routes.js +2 -0
  19. package/dist/commands/ui/chat/store.d.ts +2 -0
  20. package/dist/commands/ui/chat/store.js +14 -1
  21. package/dist/commands/ui/chat/stream.en.d.ts +11 -0
  22. package/dist/commands/ui/chat/stream.en.js +12 -1
  23. package/dist/commands/ui/chat/stream.es.d.ts +11 -0
  24. package/dist/commands/ui/chat/stream.es.js +12 -1
  25. package/dist/commands/ui/chat/turn-reserve.js +2 -0
  26. package/dist/commands/ui/chat/turn-selection.d.ts +3 -0
  27. package/dist/commands/ui/chat/turn-selection.js +9 -3
  28. package/dist/commands/ui/studio-state.d.ts +1 -1
  29. package/dist/ui/page.js +93 -93
  30. package/docs/WORKBENCH.md +14 -4
  31. package/package.json +11 -11
  32. package/skills/ape-design-system/SKILL.md +14 -3
  33. package/skills/ape-plan-change/SKILL.md +2 -2
  34. package/templates/product/README.md +1 -1
package/CHANGELOG.md CHANGED
@@ -4,6 +4,25 @@ One section per release (a git tag). **Upgrade notes** list anything that breaks
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## v0.8.41 (2026-12-01)
8
+
9
+ - Three new starter themes, `themes.clear`, `themes.warm` and `themes.bold`, each with its own ground, main color, type, corners and one-line voice, in light, dark and high contrast. The Brand step offers these three first, so its cards look clearly different; a product's current starter still shows beside them. `themes.neutral` and `themes.soft` stay. No upgrade notes: nothing changes for an existing product.
10
+ - The studio says what it is doing while it reads the development level: "Reading…" on the level button, "Reading who approves…" and "the studio checks again in a moment", in place of "not confirmed" with no next step (English and Spanish).
11
+ - The Brand step says its looks are shown on a screen from your app: the starter's sample screen until you make your own.
12
+ - The `ape-design-system` skill starts with a reference study: pictures of what buyers use and admire, captured politely (robots.txt, no bot checks worked around, cookie banners hidden, pictures kept out of the repository), and `design/study.md` before a direction is chosen.
13
+ - The studio's agent panel asks once for a folder outside the product: after a refused read, "Allow this folder" adds that folder to the product's `.claude/settings.local.json` and the agent tries again; "Not now" goes on without it. Only a person on the studio page, with the `settings` right on a hosted studio, can allow it, and only the folder the refusal named. No upgrade notes.
14
+ - In the Plan chat, a refused `ape enable` or `ape disable` of a platform shows the platforms as switches and "Change in Setup", which opens Setup's platforms with the chosen changes ready to confirm. No upgrade notes.
15
+ - The studio's page no longer grows past the window as a chat gets long. Each message's hidden label for screen readers was placed outside the agent panel's scrolling list, so a long conversation added an empty scroll below the studio. No upgrade notes.
16
+ - When the studio's agent needs the person's decision, it asks one short question on its turn's ask line (`ape-ask: turn=<launch id> <question>`, the same private per-launch proof as an Auto choice), then stops. The chat records it as `waiting` (`{ question, at, turn }`, a new optional field of the workbench chat contract), and every step's page shows "Waiting for your direction" with the question and an Answer button that puts the cursor in the agent panel's box (on a phone it opens the Agent tab first). The question clears when the person sends, stops the turn or starts a new chat for the step, and when a later turn ends without asking. Only the turn the studio launched for that chat can raise it. No upgrade notes.
17
+
18
+ ## v0.8.40 (2026-12-01)
19
+
20
+ - **What 0.8.40 holds:** `ape add` and `ape remove` work in CI. No upgrade notes: nothing changes for an existing product.
21
+
22
+ - **Known issues:** those of 0.8.38.
23
+
24
+ - `ape add` and `ape remove` run `pnpm install --no-frozen-lockfile`. Both change `package.json`, so the lockfile must change too; where `CI` is set, pnpm refused with `ERR_PNPM_OUTDATED_LOCKFILE` and the add was put back.
25
+
7
26
  ## v0.8.39 (2026-11-30)
8
27
 
9
28
  - **What 0.8.39 holds:** a new example app, the one the tutorial makes, passes its first full prototype snapshot. No upgrade notes: nothing changes for an existing product.
@@ -17,7 +17,7 @@ export const en = {
17
17
  'create.listed': 'Added the skills list to the existing AGENTS.md (between two marker lines).',
18
18
  'create.ports': 'Ports: API {api}, admin {admin}, app {app}, studio {studio}, Postgres {postgres}, Redis {redis}.',
19
19
  'create.next': 'Next:',
20
- 'create.referenceFolder': 'Before the first plan, if idea or journey notes are in one sibling folder, replace {folder} in {snippet} with that folder and merge it into the git-ignored .claude/settings.local.json yourself, keeping existing settings. This lets Claude Code read and change files in that folder. The studio writes nothing and grants nothing; after a refused read, press Try again.',
20
+ 'create.referenceFolder': 'Before the first plan, if idea or journey notes are in one sibling folder, replace {folder} in {snippet} with that folder and merge it into the git-ignored .claude/settings.local.json yourself, keeping existing settings. This lets Claude Code read and change files in that folder. Or wait: after a refused read, the agent panel offers Allow this folder.',
21
21
  'create.localSkills': 'Your product already has its agent skills in .claude/skills.',
22
22
  'create.mcp': 'Your product’s .mcp.json already runs ape mcp.',
23
23
  'create.plugin': 'In Claude Code, the buffcore plugin adds the product skills and ape mcp:\n/plugin marketplace add {repository}\n/plugin install {plugin}',
@@ -27,7 +27,7 @@ const es = {
27
27
  'create.listed': 'Se añadió la lista de habilidades al AGENTS.md existente (entre dos líneas de marcadores).',
28
28
  'create.ports': 'Puertos: API {api}, administración {admin}, aplicación {app}, estudio {studio}, Postgres {postgres}, Redis {redis}.',
29
29
  'create.next': 'Siguiente:',
30
- 'create.referenceFolder': 'Antes del primer plan, si las notas de la idea o los recorridos están en una carpeta hermana, sustituye {folder} en {snippet} por esa carpeta y combina el fragmento tú mismo con .claude/settings.local.json, ignorado por git, conservando los ajustes existentes. Esto permite a Claude Code leer y cambiar archivos en esa carpeta. El estudio no escribe nada ni concede permisos; tras una lectura rechazada, pulsa Volver a intentar.',
30
+ 'create.referenceFolder': 'Antes del primer plan, si las notas de la idea o los recorridos están en una carpeta hermana, sustituye {folder} en {snippet} por esa carpeta y combina el fragmento tú mismo con .claude/settings.local.json, ignorado por git, conservando los ajustes existentes. Esto permite a Claude Code leer y cambiar archivos en esa carpeta. O espera: tras una lectura rechazada, el panel del agente ofrece Permitir esta carpeta.',
31
31
  'create.localSkills': 'Tu producto ya tiene sus habilidades de agentes en .claude/skills.',
32
32
  'create.mcp': 'El archivo .mcp.json de tu producto ya ejecuta ape mcp.',
33
33
  'create.plugin': 'En Claude Code, el plugin buffcore añade las habilidades del producto y ape mcp:\n/plugin marketplace add {repository}\n/plugin install {plugin}',
@@ -73,11 +73,15 @@ async function tables(root, key, drop, owner) {
73
73
  await app.close();
74
74
  }
75
75
  }
76
- /** Keep the synchronous step shared with remove, while a child streams and captures pnpm's output. */
76
+ /**
77
+ * Keep the synchronous step shared with remove, while a child streams and captures pnpm's output.
78
+ * Add and remove change package.json, so the lockfile must change too, also where CI is set and pnpm
79
+ * would otherwise refuse (frozen lockfile).
80
+ */
77
81
  const INSTALL = `
78
82
  const { spawn } = require('node:child_process');
79
83
  const { writeSync } = require('node:fs');
80
- const child = spawn('pnpm install', { shell: true, stdio: ['inherit', 'pipe', 'pipe'] });
84
+ const child = spawn('pnpm install --no-frozen-lockfile', { shell: true, stdio: ['inherit', 'pipe', 'pipe'] });
81
85
  let tail = Buffer.alloc(0);
82
86
  const keep = (chunk) => { tail = Buffer.concat([tail, Buffer.from(chunk)]).subarray(-65536); };
83
87
  for (const [source, target] of [[child.stdout, process.stdout], [child.stderr, process.stderr]]) {
@@ -5,7 +5,9 @@ import { themes } from '@buffcore/tokens';
5
5
  * must work in each).
6
6
  */
7
7
  export function themesOf(product) {
8
- const starters = Object.values(themes);
8
+ // Neutral and Soft hold BuffCore's components to every check; Clear, Warm and Bold pass the same
9
+ // token checks in their own tests. Five looks per scene would not fit one scene's time budget.
10
+ const starters = [themes.neutral, themes.soft];
9
11
  const starter = starters.find((theme) => theme.key === product?.key);
10
12
  return product && JSON.stringify(product) !== JSON.stringify(starter) ? [product] : starters;
11
13
  }
@@ -59,8 +59,11 @@ declare const recordSchema: z.ZodObject<{
59
59
  commit: z.ZodString;
60
60
  change: z.ZodOptional<z.ZodString>;
61
61
  direction: z.ZodOptional<z.ZodEnum<{
62
+ bold: "bold";
63
+ clear: "clear";
62
64
  neutral: "neutral";
63
65
  soft: "soft";
66
+ warm: "warm";
64
67
  }>>;
65
68
  version: z.ZodOptional<z.ZodNumber>;
66
69
  screen: z.ZodOptional<z.ZodString>;
@@ -0,0 +1,9 @@
1
+ import type { UiRoute } from '../routes.ts';
2
+ import type { ChatEngine } from './turn.ts';
3
+ /**
4
+ * A person's "Allow this folder": the folder is the one the chat's own permission notice names,
5
+ * never one the request sends. Only the studio page reaches it (its token or the host's sign-in,
6
+ * Origin, the settings right); no MCP tool or agent command calls it. The chat records who allowed
7
+ * what, the studio's audit line for a settings change outside git.
8
+ */
9
+ export declare function allowFolderRoute(engine: ChatEngine): UiRoute;
@@ -0,0 +1,56 @@
1
+ import { allowFolderAnswer, allowFolderBody, chatIdSchema } from '@buffcore/contracts/workbench';
2
+ import { AllowRefusal, addAdditionalDirectory, allowableFolder } from './allow-folder.js';
3
+ import { t } from './prompt.js';
4
+ import { message } from './store.js';
5
+ import { lineText } from './stream-text.js';
6
+ const refused = (status, text) => ({ status, body: { error: text } });
7
+ /**
8
+ * A person's "Allow this folder": the folder is the one the chat's own permission notice names,
9
+ * never one the request sends. Only the studio page reaches it (its token or the host's sign-in,
10
+ * Origin, the settings right); no MCP tool or agent command calls it. The chat records who allowed
11
+ * what, the studio's audit line for a settings change outside git.
12
+ */
13
+ export function allowFolderRoute(engine) {
14
+ return {
15
+ method: 'POST',
16
+ path: '/api/chats/:id/allow-folder',
17
+ right: 'settings',
18
+ origin: true,
19
+ handle: async (request) => {
20
+ const id = request.params.id;
21
+ if (!chatIdSchema.safeParse(id).success)
22
+ return refused(400, t('chat.invalid'));
23
+ const body = allowFolderBody.safeParse(await request.body().catch(() => undefined));
24
+ if (!body.success)
25
+ return refused(400, t('chat.invalid'));
26
+ const chat = engine.get(id);
27
+ if (!chat)
28
+ return refused(404, t('chat.missing'));
29
+ const notice = chat.messages[body.data.at];
30
+ const permission = notice?.from === 'system' ? notice.permission : undefined;
31
+ if (permission?.setting !== 'permissions.additionalDirectories')
32
+ return refused(409, lineText('chat.allow.none'));
33
+ try {
34
+ const folder = await allowableFolder(engine.root, permission.path);
35
+ const added = await addAdditionalDirectory(engine.root, folder);
36
+ if (!permission.allowed) {
37
+ permission.allowed = true;
38
+ const by = request.identity?.viewer.name;
39
+ const line = message(chat, 'system', lineText('chat.lines.allowed', { by: by ?? '', path: folder }));
40
+ if (by)
41
+ line.by = by;
42
+ engine.store.saveRetry(chat);
43
+ }
44
+ return {
45
+ status: added ? 201 : 200,
46
+ body: allowFolderAnswer.parse({ ok: true, path: folder }),
47
+ };
48
+ }
49
+ catch (error) {
50
+ if (error instanceof AllowRefusal)
51
+ return refused(409, lineText(`chat.allow.${error.why}`));
52
+ return refused(500, t('chat.server'));
53
+ }
54
+ },
55
+ };
56
+ }
@@ -0,0 +1,18 @@
1
+ /** Why a folder may not be added; each has a sentence in stream.en.ts as `chat.allow.<why>`. */
2
+ export type FolderRefusal = 'notAbsolute' | 'missing' | 'notFolder' | 'root' | 'home' | 'inside' | 'linked' | 'secrets' | 'settings';
3
+ export declare class AllowRefusal extends Error {
4
+ readonly why: FolderRefusal;
5
+ constructor(why: FolderRefusal);
6
+ }
7
+ /**
8
+ * The folder the person may allow: absolute, there, a folder, itself (no link), not a whole disk,
9
+ * not the home folder or one that holds it, outside the product, and not a folder of sign-ins or
10
+ * keys (`.ssh`, `.aws`, `secrets` and the like). Returns its real path.
11
+ */
12
+ export declare function allowableFolder(product: string, path: string): Promise<string>;
13
+ /**
14
+ * Adds `folder` to `permissions.additionalDirectories` in `<product>/.claude/settings.local.json`:
15
+ * made when missing, every other setting kept, never twice, written whole or not at all.
16
+ * Returns false when the folder was there already.
17
+ */
18
+ export declare function addAdditionalDirectory(product: string, folder: string): Promise<boolean>;
@@ -0,0 +1,130 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { promises as fs } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { isAbsolute, join, parse, relative, resolve, sep } from 'node:path';
5
+ export class AllowRefusal extends Error {
6
+ why;
7
+ constructor(why) {
8
+ super(why);
9
+ this.why = why;
10
+ }
11
+ }
12
+ const windows = process.platform === 'win32';
13
+ /**
14
+ * Folders that hold sign-ins and keys. The folder an agent was refused comes from what the agent
15
+ * tried to read, so one click must never hand it these, at any depth.
16
+ */
17
+ const SECRET_FOLDERS = new Set([
18
+ '.ssh',
19
+ '.gnupg',
20
+ '.aws',
21
+ '.azure',
22
+ '.kube',
23
+ '.docker',
24
+ '.gcloud',
25
+ '.password-store',
26
+ 'secrets',
27
+ ]);
28
+ const holdsSecrets = (path) => path.split(/[\\/]+/).some((part) => SECRET_FOLDERS.has(part.toLowerCase()));
29
+ const same = (a, b) => (windows ? a.toLowerCase() === b.toLowerCase() : a === b);
30
+ /** `child` is `parent` or inside it. */
31
+ function within(parent, child) {
32
+ const path = relative(parent, child);
33
+ return path === '' || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path));
34
+ }
35
+ /**
36
+ * The folder the person may allow: absolute, there, a folder, itself (no link), not a whole disk,
37
+ * not the home folder or one that holds it, outside the product, and not a folder of sign-ins or
38
+ * keys (`.ssh`, `.aws`, `secrets` and the like). Returns its real path.
39
+ */
40
+ export async function allowableFolder(product, path) {
41
+ // On Windows `\notes` counts as absolute yet means the current drive: a drive or share is required.
42
+ if (!isAbsolute(path) || (windows && !/^(?:[a-z]:[\\/]|[\\/]{2})/i.test(path)))
43
+ throw new AllowRefusal('notAbsolute');
44
+ const entry = await fs.stat(path).catch(() => undefined);
45
+ if (!entry)
46
+ throw new AllowRefusal('missing');
47
+ if (!entry.isDirectory())
48
+ throw new AllowRefusal('notFolder');
49
+ const [real, home, root] = await Promise.all([
50
+ fs.realpath(path),
51
+ fs.realpath(homedir()),
52
+ fs.realpath(product),
53
+ ]);
54
+ if (parse(real).root === real)
55
+ throw new AllowRefusal('root');
56
+ if (within(real, home))
57
+ throw new AllowRefusal('home');
58
+ if (within(root, real))
59
+ throw new AllowRefusal('inside');
60
+ if (holdsSecrets(real) || holdsSecrets(resolve(path)))
61
+ throw new AllowRefusal('secrets');
62
+ if (!same(real, resolve(path)))
63
+ throw new AllowRefusal('linked');
64
+ return real;
65
+ }
66
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
67
+ async function readSettings(file) {
68
+ let text;
69
+ try {
70
+ text = await fs.readFile(file, 'utf8');
71
+ }
72
+ catch (error) {
73
+ if (error.code === 'ENOENT')
74
+ return {};
75
+ throw new AllowRefusal('settings');
76
+ }
77
+ try {
78
+ const value = JSON.parse(text);
79
+ if (object(value))
80
+ return value;
81
+ }
82
+ catch {
83
+ // Not JSON: never overwritten.
84
+ }
85
+ throw new AllowRefusal('settings');
86
+ }
87
+ /** A scanner or an editor can hold the file for a moment on Windows: a few short tries. */
88
+ async function replace(temporary, file) {
89
+ for (let n = 1;; n++) {
90
+ try {
91
+ return await fs.rename(temporary, file);
92
+ }
93
+ catch (error) {
94
+ const code = error.code;
95
+ if (n >= 5 || !['EPERM', 'EBUSY', 'EACCES'].includes(code ?? '')) {
96
+ await fs.rm(temporary, { force: true });
97
+ throw error;
98
+ }
99
+ await new Promise((done) => setTimeout(done, 20 * n));
100
+ }
101
+ }
102
+ }
103
+ let queue = Promise.resolve();
104
+ /**
105
+ * Adds `folder` to `permissions.additionalDirectories` in `<product>/.claude/settings.local.json`:
106
+ * made when missing, every other setting kept, never twice, written whole or not at all.
107
+ * Returns false when the folder was there already.
108
+ */
109
+ export function addAdditionalDirectory(product, folder) {
110
+ const next = queue.then(async () => {
111
+ const file = join(product, '.claude', 'settings.local.json');
112
+ const settings = await readSettings(file);
113
+ const permissions = settings.permissions ?? {};
114
+ if (!object(permissions))
115
+ throw new AllowRefusal('settings');
116
+ const list = permissions.additionalDirectories ?? [];
117
+ if (!Array.isArray(list))
118
+ throw new AllowRefusal('settings');
119
+ if (list.some((entry) => typeof entry === 'string' && same(resolve(product, entry), folder)))
120
+ return false;
121
+ const text = `${JSON.stringify({ ...settings, permissions: { ...permissions, additionalDirectories: [...list, folder] } }, null, 2)}\n`;
122
+ await fs.mkdir(join(product, '.claude'), { recursive: true });
123
+ const temporary = `${file}.${randomUUID()}.tmp`;
124
+ await fs.writeFile(temporary, text, { flag: 'wx' });
125
+ await replace(temporary, file);
126
+ return true;
127
+ });
128
+ queue = next.catch(() => undefined);
129
+ return next;
130
+ }
@@ -0,0 +1,17 @@
1
+ import type { Chat } from '@buffcore/contracts/workbench';
2
+ export type Waiting = NonNullable<Chat['waiting']>;
3
+ export declare function askInstructions(launchId: string): string;
4
+ /** The last valid ask line of this launch in the text, or nothing. */
5
+ export declare function askedQuestion(text: string, launchId: string): string | undefined;
6
+ /** Records the turn's question on the launch; the chat shows it once the turn ends. */
7
+ export declare function askReporter(selection: {
8
+ launchId: string;
9
+ record: {
10
+ id?: string;
11
+ };
12
+ asked?: Waiting;
13
+ }): (text: string) => void;
14
+ /** The panel shows the agent's question as plain words, without the line's marker. */
15
+ export declare function plainAsk(text: string): string;
16
+ /** A turn's end: waiting only when it ended well and asked; anything else clears the question. */
17
+ export declare function endWaiting(chat: Chat, asked: Waiting | undefined, failed: boolean): void;
@@ -0,0 +1,4 @@
1
+ export declare const en: {
2
+ 'ask.instructions': string;
3
+ 'ask.launchId': string;
4
+ };
@@ -0,0 +1,4 @@
1
+ export const en = {
2
+ 'ask.instructions': 'When you need the person’s decision, ask them in one short question (at most 500 characters): write it as the last line of your reply, on its own line, exactly as {line}, then stop and wait for their answer. The studio shows that question to the person.',
3
+ 'ask.launchId': 'Your launch id for that line is {id}; write it in place of {placeholder}. Do not copy it anywhere else.',
4
+ };
@@ -0,0 +1,4 @@
1
+ export declare const es: {
2
+ 'ask.instructions': string;
3
+ 'ask.launchId': string;
4
+ };
@@ -0,0 +1,4 @@
1
+ export const es = {
2
+ 'ask.instructions': 'Cuando necesites que la persona decida, pregúntale en una sola pregunta corta (500 caracteres como máximo): escríbela como la última línea de tu respuesta, en su propia línea, exactamente como {line}, y luego detente y espera su respuesta. El estudio le muestra esa pregunta a la persona.',
3
+ 'ask.launchId': 'Tu identificador de lanzamiento para esa línea es {id}; escríbelo en lugar de {placeholder}. No lo copies en ningún otro sitio.',
4
+ };
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The agent asks the person for a decision on the same private channel as an Auto choice: one line
3
+ * of its own top-level reply, carrying this launch's id. Only the turn the studio started for this
4
+ * chat knows the id, so no request from outside the turn can make the page wait.
5
+ */
6
+ import { randomUUID, timingSafeEqual } from 'node:crypto';
7
+ import { createI18n, matchLocale } from '@buffcore/i18n';
8
+ import { en } from './ask-person.en.js';
9
+ import { es } from './ask-person.es.js';
10
+ const words = createI18n({ catalogs: [{ en, es }] });
11
+ const askText = (key, values) => words.t(matchLocale((process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || 'en')
12
+ .replace('_', '-')
13
+ .split('.')[0], words.locales), key, values);
14
+ const PLACEHOLDER = '<launch-id>';
15
+ const LINE = /^[ \t]*(?:>[ \t]*)*ape-ask: turn=(ape-[a-f0-9]{32}) (.+)$/;
16
+ // After launch ids are scrubbed from stored text, the line reads as the question alone.
17
+ const SCRUBBED = /^([ \t]*(?:>[ \t]*)*)ape-ask: (?:launchid|turn=\S+) (.+)$/gm;
18
+ export function askInstructions(launchId) {
19
+ return `${askText('ask.instructions', { line: `ape-ask: turn=${PLACEHOLDER} <question>` })}\n${askText('ask.launchId', { id: launchId, placeholder: PLACEHOLDER })}\n`;
20
+ }
21
+ /** The last valid ask line of this launch in the text, or nothing. */
22
+ export function askedQuestion(text, launchId) {
23
+ if (!/^ape-[a-f0-9]{32}$/.test(launchId))
24
+ return;
25
+ let asked;
26
+ for (const line of text.split(/\r?\n/)) {
27
+ if (line.length > 600)
28
+ continue;
29
+ const match = LINE.exec(line);
30
+ if (!match || !timingSafeEqual(Buffer.from(match[1]), Buffer.from(launchId)))
31
+ continue;
32
+ const question = match[2].replace(/[\p{Cc}\p{Cf}]/gu, '').trim();
33
+ if (question && question.length <= 500 && !question.includes(PLACEHOLDER))
34
+ asked = question;
35
+ }
36
+ return asked;
37
+ }
38
+ /** Records the turn's question on the launch; the chat shows it once the turn ends. */
39
+ export function askReporter(selection) {
40
+ return (text) => {
41
+ const question = askedQuestion(text, selection.launchId);
42
+ if (question)
43
+ selection.asked = {
44
+ question,
45
+ at: new Date().toISOString(),
46
+ turn: selection.record.id ?? randomUUID(),
47
+ };
48
+ };
49
+ }
50
+ /** The panel shows the agent's question as plain words, without the line's marker. */
51
+ export function plainAsk(text) {
52
+ return text.includes('ape-ask: ') ? text.replace(SCRUBBED, '$1$2') : text;
53
+ }
54
+ /** A turn's end: waiting only when it ended well and asked; anything else clears the question. */
55
+ export function endWaiting(chat, asked, failed) {
56
+ if (asked && !failed)
57
+ chat.waiting = asked;
58
+ else
59
+ delete chat.waiting;
60
+ }
@@ -1,5 +1,6 @@
1
1
  import { factsChanged } from '../merge-events.js';
2
2
  import { stopTree } from '../runner.js';
3
+ import { endWaiting } from './ask-person.js';
3
4
  import { watchCodexIdle } from './codex-idle.js';
4
5
  import { recordTurn } from './orphans.js';
5
6
  import { message } from './store.js';
@@ -9,6 +10,7 @@ export function recordTurnEnd(run, failed, unsaved) {
9
10
  if (!run.launched || run.startedAt === undefined)
10
11
  return;
11
12
  endTurn(run.chat, run.startedAt, run.firstMessage ?? 0, failed, unsaved, run.stopped === true);
13
+ endWaiting(run.chat, run.selection?.asked, failed || run.stopped === true);
12
14
  // The turn may have edited files: the unsaved list the studio holds is from before it.
13
15
  factsChanged('unsaved');
14
16
  delete run.startedAt;
@@ -1,4 +1,5 @@
1
1
  import { chatIdSchema, newChatBody, sendBody, stopAnswer, stopBody, } from '@buffcore/contracts/workbench';
2
+ import { allowFolderRoute } from './allow-folder-route.js';
2
3
  import { readSendBody } from './attachments.js';
3
4
  import { CodingApprovalRefusal } from './coding-approval.js';
4
5
  import { t } from './prompt.js';
@@ -88,6 +89,7 @@ export function chatRoutes(engine) {
88
89
  return { status: 409, body: { error: busy.message } };
89
90
  }),
90
91
  stopRoute(engine),
92
+ allowFolderRoute(engine),
91
93
  ];
92
94
  }
93
95
  function commentsRoute(engine) {
@@ -12,6 +12,8 @@ export declare class ChatStore {
12
12
  constructor(root: string);
13
13
  folder(id?: string): string;
14
14
  create(body: NewChat, agent: AgentId): Chat;
15
+ /** A new chat for a step replaces its old one: an old question no longer waits there. */
16
+ private forgetWaiting;
15
17
  get(id: string): Chat | null;
16
18
  /** A stored chat's text as the chat it holds; a record that is not that chat is invalid. */
17
19
  parse(id: string, text: string): Chat;
@@ -3,6 +3,7 @@ import { appendFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFile
3
3
  import { join } from 'node:path';
4
4
  import { chatIdSchema, persistedChatSchema, turnChoiceSchema, } from '@buffcore/contracts/workbench';
5
5
  import { z } from 'zod';
6
+ import { plainAsk } from './ask-person.js';
6
7
  import { diagnosticDetail, diagnosticEvent } from './detail.js';
7
8
  import { failureSentence } from './failure.js';
8
9
  import { scrubLaunchIds } from './launch-ids.js';
@@ -56,8 +57,20 @@ export class ChatStore {
56
57
  };
57
58
  this.saveRetry(chat);
58
59
  writeFileSync(join(this.folder(chat.id), 'events.jsonl'), '', { mode: 0o600 });
60
+ this.forgetWaiting(chat);
59
61
  return chat;
60
62
  }
63
+ /** A new chat for a step replaces its old one: an old question no longer waits there. */
64
+ forgetWaiting(fresh) {
65
+ for (const old of this.all())
66
+ if (old.id !== fresh.id &&
67
+ old.page === fresh.page &&
68
+ old.change === fresh.change &&
69
+ old.waiting) {
70
+ delete old.waiting;
71
+ this.checkpoint(old);
72
+ }
73
+ }
61
74
  get(id) {
62
75
  chatIdSchema.parse(id);
63
76
  const pending = this.pending.get(id);
@@ -208,7 +221,7 @@ export function message(chat, from, text, agent, detail) {
208
221
  export function applyEvent(chat, event) {
209
222
  switch (event.kind) {
210
223
  case 'text':
211
- message(chat, 'agent', event.text, chat.agent);
224
+ message(chat, 'agent', plainAsk(event.text), chat.agent);
212
225
  break;
213
226
  case 'tool':
214
227
  message(chat, 'agent', t('chat.tool', { name: event.name, target: event.target ? ` (${event.target})` : '' }), chat.agent);
@@ -12,6 +12,17 @@ export declare const en: {
12
12
  'chat.lines.refusal.command': string;
13
13
  'chat.lines.refusal.permission': string;
14
14
  'chat.lines.permission': string;
15
+ 'chat.lines.allowed': string;
16
+ 'chat.allow.none': string;
17
+ 'chat.allow.notAbsolute': string;
18
+ 'chat.allow.missing': string;
19
+ 'chat.allow.notFolder': string;
20
+ 'chat.allow.root': string;
21
+ 'chat.allow.home': string;
22
+ 'chat.allow.secrets': string;
23
+ 'chat.allow.inside': string;
24
+ 'chat.allow.linked': string;
25
+ 'chat.allow.settings': string;
15
26
  'chat.lines.end': string;
16
27
  'chat.lines.failed': string;
17
28
  'chat.lines.codexPreparing': string;
@@ -11,7 +11,18 @@ export const en = {
11
11
  'chat.lines.refusal.taskOutput': 'Claude needs permission to read the task output ({target}), so run the check in the foreground.',
12
12
  'chat.lines.refusal.command': 'Claude needs permission to run {target} in this step, so use a listed command or ask the person to run it.',
13
13
  'chat.lines.refusal.permission': 'Claude needs permission {verb, select, read {to read {target}} edit {to edit {target}} write {to write {target}} search {to search for {target}} other {to use {target}}} in this step, so ask the person how to continue.',
14
- 'chat.lines.permission': 'Needs your OK outside the studio: {path}. Add the folder to permissions.additionalDirectories in .claude/settings.local.json yourself. The studio grants nothing.',
14
+ 'chat.lines.permission': 'Needs your OK to read a folder outside the product: {path}. Allow it in the studio, or go on without it.',
15
+ 'chat.lines.allowed': '{by} allowed the agent to read {path}.',
16
+ 'chat.allow.none': 'This message asks for no folder.',
17
+ 'chat.allow.notAbsolute': 'The studio allows only a folder named by its full path.',
18
+ 'chat.allow.missing': 'That folder isn’t there any more.',
19
+ 'chat.allow.notFolder': 'That path is a file, not a folder.',
20
+ 'chat.allow.root': 'The studio never allows a whole drive or disk.',
21
+ 'chat.allow.home': 'The studio never allows your home folder or a folder that holds it.',
22
+ 'chat.allow.secrets': 'The studio never allows a folder of sign-ins or keys, such as .ssh, .aws or secrets.',
23
+ 'chat.allow.inside': 'That folder is inside this product, so the agent may read it already.',
24
+ 'chat.allow.linked': 'That folder is a link to another place, so the studio doesn’t allow it. Add the real folder to .claude/settings.local.json yourself.',
25
+ 'chat.allow.settings': 'The product’s .claude/settings.local.json isn’t settings the studio can read, so it was left as it is.',
15
26
  'chat.lines.end': 'Done in {time}',
16
27
  'chat.lines.failed': 'Stopped after {time}',
17
28
  'chat.lines.codexPreparing': 'Waiting for Codex. The Windows sandbox may still be preparing.',
@@ -14,6 +14,17 @@ export declare const es: {
14
14
  'chat.lines.refusal.command': string;
15
15
  'chat.lines.refusal.permission': string;
16
16
  'chat.lines.permission': string;
17
+ 'chat.lines.allowed': string;
18
+ 'chat.allow.none': string;
19
+ 'chat.allow.notAbsolute': string;
20
+ 'chat.allow.missing': string;
21
+ 'chat.allow.notFolder': string;
22
+ 'chat.allow.root': string;
23
+ 'chat.allow.home': string;
24
+ 'chat.allow.secrets': string;
25
+ 'chat.allow.inside': string;
26
+ 'chat.allow.linked': string;
27
+ 'chat.allow.settings': string;
17
28
  'chat.lines.end': string;
18
29
  'chat.lines.failed': string;
19
30
  'chat.lines.count': string;
@@ -13,7 +13,18 @@ export const es = {
13
13
  'chat.lines.refusal.taskOutput': 'Claude necesita permiso para leer la salida de la tarea ({target}), así que ejecuta la comprobación en primer plano.',
14
14
  'chat.lines.refusal.command': 'Claude necesita permiso para ejecutar {target} en este paso, así que usa un comando de la lista o pide a la persona que lo ejecute.',
15
15
  'chat.lines.refusal.permission': 'Claude necesita permiso para {verb, select, read {leer {target}} edit {editar {target}} write {escribir en {target}} search {buscar {target}} other {usar {target}}} en este paso, así que pregunta a la persona cómo continuar.',
16
- 'chat.lines.permission': 'Necesita tu permiso fuera del estudio: {path}. Añade la carpeta a permissions.additionalDirectories en .claude/settings.local.json tú mismo. El estudio no concede permisos.',
16
+ 'chat.lines.permission': 'Necesita tu permiso para leer una carpeta fuera del producto: {path}. Permítela en el estudio o continúa sin ella.',
17
+ 'chat.lines.allowed': '{by} permitió al agente leer {path}.',
18
+ 'chat.allow.none': 'Este mensaje no pide ninguna carpeta.',
19
+ 'chat.allow.notAbsolute': 'El estudio solo permite una carpeta indicada con su ruta completa.',
20
+ 'chat.allow.missing': 'Esa carpeta ya no está.',
21
+ 'chat.allow.notFolder': 'Esa ruta es un archivo, no una carpeta.',
22
+ 'chat.allow.root': 'El estudio nunca permite una unidad o un disco entero.',
23
+ 'chat.allow.home': 'El estudio nunca permite tu carpeta personal ni una carpeta que la contenga.',
24
+ 'chat.allow.secrets': 'El estudio nunca permite una carpeta de accesos o claves, como .ssh, .aws o secrets.',
25
+ 'chat.allow.inside': 'Esa carpeta está dentro de este producto, así que el agente ya puede leerla.',
26
+ 'chat.allow.linked': 'Esa carpeta es un enlace a otro sitio, así que el estudio no la permite. Añade la carpeta real a .claude/settings.local.json tú mismo.',
27
+ 'chat.allow.settings': 'El archivo .claude/settings.local.json del producto no contiene ajustes que el estudio pueda leer, así que se dejó como estaba.',
17
28
  'chat.lines.end': 'Listo en {time}',
18
29
  'chat.lines.failed': 'Se detuvo tras {time}',
19
30
  'chat.lines.count': '{count, plural, one {# llamada denegada} other {# llamadas denegadas}}',
@@ -31,6 +31,8 @@ export async function reserveTurn(root, store, active, id, text, contained, clos
31
31
  }
32
32
  run.chat = store.get(id);
33
33
  run.accepted = message(run.chat, 'you', text);
34
+ // The person answered: the agent's question no longer waits.
35
+ delete run.chat.waiting;
34
36
  run.chat.state = 'running';
35
37
  store.saveRetry(run.chat);
36
38
  return run;
@@ -1,4 +1,5 @@
1
1
  import type { AgentChoice, AgentId } from '@buffcore/contracts/workbench';
2
+ import { type Waiting } from './ask-person.ts';
2
3
  import { newTurnChoice } from './auto-choice.ts';
3
4
  import { supportedChoices } from './supported-choices.ts';
4
5
  import { type AgentOverrides } from './turn-overrides.ts';
@@ -11,5 +12,7 @@ export type TurnSelection = {
11
12
  choice: AgentOverrides;
12
13
  supported: ReturnType<typeof supportedChoices>;
13
14
  instructions: string;
15
+ /** The question this launch's own reply asked the person, if any. */
16
+ asked?: Waiting;
14
17
  };
15
18
  export declare function startSelection(run: Active): ((text: string) => void) | undefined;
@@ -1,3 +1,4 @@
1
+ import { askInstructions, askReporter } from './ask-person.js';
1
2
  import { autoInstructions, choiceReporter, choiceText, newTurnChoice, startedChoice, } from './auto-choice.js';
2
3
  import { newLaunchId } from './launch-ids.js';
3
4
  import { TranslatedChatError } from './prompt.js';
@@ -31,7 +32,7 @@ export function prepareSelection(run, agent, effective) {
31
32
  record,
32
33
  choice,
33
34
  supported,
34
- instructions: autoInstructions(requested, supported, launchId),
35
+ instructions: autoInstructions(requested, supported, launchId) + askInstructions(launchId),
35
36
  };
36
37
  const accepted = acceptChoice(agent, version, choice, {});
37
38
  if (!accepted.ok)
@@ -46,7 +47,12 @@ export function startSelection(run) {
46
47
  if (!selection)
47
48
  return;
48
49
  startedChoice(selection.record, selection.choice, selection.supported);
50
+ const ask = askReporter(selection);
49
51
  if (selection.record.model.requested !== 'auto' && selection.record.effort.requested !== 'auto')
50
- return;
51
- return choiceReporter(selection.record, selection.supported, selection.launchId);
52
+ return ask;
53
+ const choice = choiceReporter(selection.record, selection.supported, selection.launchId);
54
+ return (text) => {
55
+ choice(text);
56
+ ask(text);
57
+ };
52
58
  }