@buffcore/cli 0.8.41 → 0.8.42

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 (164) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/commands/agents-file.d.ts +5 -0
  3. package/dist/commands/agents-file.js +30 -7
  4. package/dist/commands/change.d.ts +4 -0
  5. package/dist/commands/change.js +12 -5
  6. package/dist/commands/create-block.d.ts +2 -1
  7. package/dist/commands/create-block.js +7 -5
  8. package/dist/commands/create.d.ts +3 -2
  9. package/dist/commands/create.en.js +1 -1
  10. package/dist/commands/create.es.js +1 -1
  11. package/dist/commands/create.js +8 -6
  12. package/dist/commands/design/check.d.ts +2 -0
  13. package/dist/commands/design/check.js +6 -0
  14. package/dist/commands/design/journey-roles.d.ts +6 -0
  15. package/dist/commands/design/journey-roles.js +60 -0
  16. package/dist/commands/design/references.d.ts +3 -0
  17. package/dist/commands/design/references.js +25 -0
  18. package/dist/commands/design/tells-text.js +2 -2
  19. package/dist/commands/design/tells.d.ts +3 -1
  20. package/dist/commands/design/tells.en.d.ts +2 -0
  21. package/dist/commands/design/tells.en.js +2 -0
  22. package/dist/commands/design/tells.es.js +2 -0
  23. package/dist/commands/design/tells.js +10 -7
  24. package/dist/commands/dev.js +3 -0
  25. package/dist/commands/port-claims.d.ts +23 -0
  26. package/dist/commands/port-claims.js +95 -0
  27. package/dist/commands/prototype/browser.d.ts +9 -4
  28. package/dist/commands/prototype/browser.js +26 -18
  29. package/dist/commands/prototype/export-base.d.ts +27 -0
  30. package/dist/commands/prototype/export-base.js +80 -0
  31. package/dist/commands/prototype/export.d.ts +3 -2
  32. package/dist/commands/prototype/export.js +13 -6
  33. package/dist/commands/prototype/index.js +1 -0
  34. package/dist/commands/prototype/media-ready.d.ts +8 -0
  35. package/dist/commands/prototype/media-ready.js +36 -0
  36. package/dist/commands/prototype/messages.en.d.ts +6 -0
  37. package/dist/commands/prototype/messages.en.js +6 -0
  38. package/dist/commands/prototype/messages.js +6 -0
  39. package/dist/commands/prototype/scene.d.ts +3 -1
  40. package/dist/commands/prototype/scene.js +22 -6
  41. package/dist/commands/prototype/snapshot-inputs.js +35 -7
  42. package/dist/commands/prototype/snapshot-setup.d.ts +1 -1
  43. package/dist/commands/prototype/snapshot-setup.js +2 -1
  44. package/dist/commands/prototype/snapshot.d.ts +2 -0
  45. package/dist/commands/prototype/snapshot.js +2 -1
  46. package/dist/commands/ui/chat/allow-folder.js +23 -77
  47. package/dist/commands/ui/chat/claude-permissions.d.ts +21 -0
  48. package/dist/commands/ui/chat/claude-permissions.js +69 -0
  49. package/dist/commands/ui/chat/codex-idle.d.ts +1 -0
  50. package/dist/commands/ui/chat/codex-overrides.js +2 -1
  51. package/dist/commands/ui/chat/codex-permissions.d.ts +12 -0
  52. package/dist/commands/ui/chat/codex-permissions.js +97 -0
  53. package/dist/commands/ui/chat/command-parts.d.ts +33 -0
  54. package/dist/commands/ui/chat/command-parts.js +219 -0
  55. package/dist/commands/ui/chat/command-wrappers.d.ts +21 -0
  56. package/dist/commands/ui/chat/command-wrappers.js +100 -0
  57. package/dist/commands/ui/chat/design-deletes.d.ts +1 -0
  58. package/dist/commands/ui/chat/design-deletes.js +39 -0
  59. package/dist/commands/ui/chat/launch-input.d.ts +4 -2
  60. package/dist/commands/ui/chat/launch-input.js +16 -3
  61. package/dist/commands/ui/chat/limit-mentions.d.ts +5 -0
  62. package/dist/commands/ui/chat/limit-mentions.js +74 -0
  63. package/dist/commands/ui/chat/limit-patterns.d.ts +15 -0
  64. package/dist/commands/ui/chat/limit-patterns.js +182 -0
  65. package/dist/commands/ui/chat/limits-hook.d.ts +1 -0
  66. package/dist/commands/ui/chat/limits-hook.js +30 -0
  67. package/dist/commands/ui/chat/limits.d.ts +37 -0
  68. package/dist/commands/ui/chat/limits.en.d.ts +18 -0
  69. package/dist/commands/ui/chat/limits.en.js +18 -0
  70. package/dist/commands/ui/chat/limits.es.d.ts +2 -0
  71. package/dist/commands/ui/chat/limits.es.js +17 -0
  72. package/dist/commands/ui/chat/limits.js +224 -0
  73. package/dist/commands/ui/chat/local-settings.d.ts +17 -0
  74. package/dist/commands/ui/chat/local-settings.js +73 -0
  75. package/dist/commands/ui/chat/opencode-config.d.ts +22 -0
  76. package/dist/commands/ui/chat/opencode-config.js +83 -0
  77. package/dist/commands/ui/chat/parse-claude.js +18 -2
  78. package/dist/commands/ui/chat/permission-ask.d.ts +44 -0
  79. package/dist/commands/ui/chat/permission-ask.js +142 -0
  80. package/dist/commands/ui/chat/permission-channel.d.ts +18 -0
  81. package/dist/commands/ui/chat/permission-channel.js +67 -0
  82. package/dist/commands/ui/chat/permission-route.d.ts +10 -0
  83. package/dist/commands/ui/chat/permission-route.js +47 -0
  84. package/dist/commands/ui/chat/permission-tool.d.ts +1 -0
  85. package/dist/commands/ui/chat/permission-tool.js +86 -0
  86. package/dist/commands/ui/chat/permissions.d.ts +11 -12
  87. package/dist/commands/ui/chat/permissions.js +20 -102
  88. package/dist/commands/ui/chat/planning-limits.d.ts +12 -0
  89. package/dist/commands/ui/chat/planning-limits.js +31 -0
  90. package/dist/commands/ui/chat/process.js +4 -1
  91. package/dist/commands/ui/chat/prompt.d.ts +8 -1
  92. package/dist/commands/ui/chat/prompt.en.d.ts +4 -0
  93. package/dist/commands/ui/chat/prompt.en.js +4 -0
  94. package/dist/commands/ui/chat/prompt.es.d.ts +4 -0
  95. package/dist/commands/ui/chat/prompt.es.js +4 -0
  96. package/dist/commands/ui/chat/prompt.js +18 -50
  97. package/dist/commands/ui/chat/recorded-turn.js +3 -0
  98. package/dist/commands/ui/chat/routes.js +2 -0
  99. package/dist/commands/ui/chat/secret-folders.d.ts +16 -0
  100. package/dist/commands/ui/chat/secret-folders.js +35 -0
  101. package/dist/commands/ui/chat/stdin-shells.d.ts +8 -0
  102. package/dist/commands/ui/chat/stdin-shells.js +102 -0
  103. package/dist/commands/ui/chat/step-rules.d.ts +13 -0
  104. package/dist/commands/ui/chat/step-rules.js +47 -0
  105. package/dist/commands/ui/chat/store.js +11 -2
  106. package/dist/commands/ui/chat/stream.en.d.ts +6 -0
  107. package/dist/commands/ui/chat/stream.en.js +6 -0
  108. package/dist/commands/ui/chat/stream.es.d.ts +6 -0
  109. package/dist/commands/ui/chat/stream.es.js +6 -0
  110. package/dist/commands/ui/chat/stream.js +4 -1
  111. package/dist/commands/ui/chat/turn-guard.d.ts +25 -0
  112. package/dist/commands/ui/chat/turn-guard.js +74 -0
  113. package/dist/commands/ui/chat/turn-input.d.ts +3 -2
  114. package/dist/commands/ui/chat/turn-input.js +3 -1
  115. package/dist/commands/ui/chat/turn-scenes.d.ts +19 -0
  116. package/dist/commands/ui/chat/turn-scenes.js +44 -0
  117. package/dist/commands/ui/chat/turn-state.d.ts +6 -0
  118. package/dist/commands/ui/chat/turn.js +8 -3
  119. package/dist/commands/ui/level-route.js +8 -3
  120. package/dist/commands/ui/page.d.ts +19 -1
  121. package/dist/commands/ui/page.js +9 -6
  122. package/dist/commands/ui/plan-structure.d.ts +9 -2
  123. package/dist/commands/ui/plan-structure.en.d.ts +1 -0
  124. package/dist/commands/ui/plan-structure.en.js +1 -0
  125. package/dist/commands/ui/plan-structure.es.d.ts +1 -0
  126. package/dist/commands/ui/plan-structure.es.js +1 -0
  127. package/dist/commands/ui/plan-structure.js +36 -10
  128. package/dist/commands/ui/prototype-main.d.ts +1 -0
  129. package/dist/commands/ui/prototype-scenes-child.js +3 -1
  130. package/dist/commands/ui/prototype-scenes-read.d.ts +1 -0
  131. package/dist/commands/ui/prototype-scenes-route.js +7 -1
  132. package/dist/commands/ui/save-commit.js +6 -2
  133. package/dist/commands/ui/server-options.js +2 -0
  134. package/dist/commands/ui/server.d.ts +5 -22
  135. package/dist/commands/ui/server.js +3 -45
  136. package/dist/commands/ui/snapshot-runners.d.ts +22 -0
  137. package/dist/commands/ui/snapshot-runners.js +45 -0
  138. package/dist/commands/ui/studio-routes.d.ts +1 -0
  139. package/dist/commands/ui/studio-routes.js +1 -0
  140. package/dist/commands/ui/studio-state.d.ts +3 -0
  141. package/dist/commands/ui/studio-state.js +1 -0
  142. package/dist/commands/ui/studio.en.d.ts +13 -0
  143. package/dist/commands/ui/studio.en.js +13 -0
  144. package/dist/commands/ui/studio.es.d.ts +13 -0
  145. package/dist/commands/ui/studio.es.js +13 -0
  146. package/dist/commands/ui/theme-option.d.ts +8 -0
  147. package/dist/commands/ui/theme-option.js +40 -0
  148. package/dist/commands/ui/theme-values.d.ts +5 -0
  149. package/dist/commands/ui/theme-values.js +113 -0
  150. package/dist/ui/page.js +93 -93
  151. package/docs/PROTOTYPE.md +4 -1
  152. package/docs/WORKBENCH.md +76 -22
  153. package/package.json +11 -11
  154. package/skills/ape-critique/SKILL.md +8 -4
  155. package/skills/ape-design-system/SKILL.md +3 -3
  156. package/skills/ape-plan-change/SKILL.md +7 -3
  157. package/skills/ape-prototype/SKILL.md +8 -1
  158. package/templates/example/apps/app/src/i18n/en.ts +2 -0
  159. package/templates/example/apps/app/src/i18n/es.json +2 -0
  160. package/templates/product/apps/admin/src/fonts.ts +2 -1
  161. package/templates/product/apps/app/src/fonts.ts +5 -1
  162. package/templates/product/apps/app/src/i18n/en.ts +2 -0
  163. package/templates/product/apps/app/src/i18n/es.json +2 -0
  164. package/templates/product/prototype/journeys.ts +3 -0
@@ -0,0 +1,102 @@
1
+ /**
2
+ * A shell or interpreter that reads its script from standard input: `echo … | sh`, `bash <<'EOF'`,
3
+ * `sh <<< '…'`, `python -`, `pwsh -Command -`, `cmd` with no `/c`. What it runs is data the limits
4
+ * never see as a command, so the limits ask the person instead (limits.ts). Plain Node only: the
5
+ * hook runs it.
6
+ */
7
+ import { programName } from './command-parts.js';
8
+ import { POSIX, POWERSHELL, posixScript, powershellScript } from './command-wrappers.js';
9
+ const INTERPRETERS = new Set([
10
+ ...POSIX,
11
+ ...POWERSHELL,
12
+ 'cmd',
13
+ 'node',
14
+ 'deno',
15
+ 'bun',
16
+ 'python',
17
+ 'python3',
18
+ 'py',
19
+ 'perl',
20
+ 'ruby',
21
+ 'php',
22
+ 'lua',
23
+ ]);
24
+ /** Words that run the next one as a program: `sudo sh`, `env X=1 bash`, `pnpm exec node`. */
25
+ const LEADERS = new Set([
26
+ 'sudo',
27
+ 'doas',
28
+ 'env',
29
+ 'nohup',
30
+ 'exec',
31
+ 'command',
32
+ 'builtin',
33
+ 'time',
34
+ 'nice',
35
+ 'ionice',
36
+ 'timeout',
37
+ 'stdbuf',
38
+ 'xargs',
39
+ 'npx',
40
+ 'pnpx',
41
+ 'bunx',
42
+ 'dlx',
43
+ 'pnpm',
44
+ 'npm',
45
+ 'yarn',
46
+ '&',
47
+ '.',
48
+ 'call',
49
+ ]);
50
+ /** Each word may only lead the program: a setting, a leader, an option or a number. */
51
+ const leading = (word) => /^[A-Za-z_][A-Za-z0-9_]*=/.test(word) ||
52
+ LEADERS.has(programName(word)) ||
53
+ word.startsWith('-') ||
54
+ /^\d+$/.test(word);
55
+ /** The words after the program that are operands: no options, no redirections or their targets. */
56
+ function operands(rest) {
57
+ const found = [];
58
+ for (let index = 0; index < rest.length; index++) {
59
+ const word = rest[index];
60
+ if (/^\d*[<>]/.test(word) || /^&>/.test(word)) {
61
+ if (/^\d*(?:[<>]{1,2}|>[&|]|&>{1,2})$/.test(word))
62
+ index++;
63
+ }
64
+ else if (!/^[-+]/.test(word) || word === '-')
65
+ found.push(word);
66
+ }
67
+ return found;
68
+ }
69
+ function readsStdinFrom(name, rest) {
70
+ // A here-document, a here-string or `<`: its input is the script.
71
+ if (rest.some((word) => word.startsWith('<')))
72
+ return true;
73
+ // Asking for its version or help reads no script.
74
+ if (rest.some((word) => /^(?:--version|--help|-[vVh?])$/.test(word)))
75
+ return false;
76
+ const given = operands(rest);
77
+ if (given.includes('-'))
78
+ return true;
79
+ if (POSIX.has(name))
80
+ return (rest.some((word) => /^-[A-Za-z]*s[A-Za-z]*$/.test(word)) ||
81
+ (posixScript(rest, 0) === undefined && !given.length));
82
+ if (POWERSHELL.has(name)) {
83
+ const script = powershellScript(rest, 0);
84
+ if (script !== undefined)
85
+ return !script.trim() || script.trim() === '-';
86
+ return !rest.some((word) => /^[-/]f(?:i|il|ile)?$/i.test(word));
87
+ }
88
+ if (name === 'cmd')
89
+ return !rest.some((word) => /^\/[ck]$/i.test(word));
90
+ return !given.length;
91
+ }
92
+ /** Whether the part runs a shell or interpreter, as its program, that reads standard input. */
93
+ export function readsStdin(words) {
94
+ for (let index = 0; index < words.length; index++) {
95
+ const name = programName(words[index]);
96
+ if (INTERPRETERS.has(name) && readsStdinFrom(name, words.slice(index + 1)))
97
+ return true;
98
+ if (!leading(words[index]))
99
+ return false;
100
+ }
101
+ return false;
102
+ }
@@ -0,0 +1,13 @@
1
+ import type { Chat } from '@buffcore/contracts/workbench';
2
+ /**
3
+ * "Always allow in this step": exact commands a person allowed for one kind of work, kept in the
4
+ * product's `.claude/settings.local.json` under `apeStepAllow`, beside Allow this folder. Claude
5
+ * Code keeps an unknown key and ignores it (the spike proved it); the studio adds a step's rules to
6
+ * that step's `--allowedTools` only, so they never reach another step.
7
+ */
8
+ export declare const STEP_KEY = "apeStepAllow";
9
+ export declare const storableRule: (rule: string) => boolean;
10
+ /** The step's kept rules, read for a launch; anything unreadable or malformed is left out. */
11
+ export declare function stepRules(product: string, work: Chat['work']): string[];
12
+ /** Adds the rules to the step's list: never twice, every other setting kept, written whole. */
13
+ export declare function keepStepRules(product: string, work: Chat['work'], rules: readonly string[]): Promise<boolean>;
@@ -0,0 +1,47 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { isObject, localSettingsFile, updateLocalSettings } from './local-settings.js';
3
+ /**
4
+ * "Always allow in this step": exact commands a person allowed for one kind of work, kept in the
5
+ * product's `.claude/settings.local.json` under `apeStepAllow`, beside Allow this folder. Claude
6
+ * Code keeps an unknown key and ignores it (the spike proved it); the studio adds a step's rules to
7
+ * that step's `--allowedTools` only, so they never reach another step.
8
+ */
9
+ export const STEP_KEY = 'apeStepAllow';
10
+ /**
11
+ * One exact shell command a rule can name and a Windows launch can quote. `*` is Claude Code's
12
+ * wildcard (`Bash(node *)`, and `:*` for any arguments), so a kept rule never holds one: it would
13
+ * allow more than the person saw.
14
+ */
15
+ const RULE = /^(?:Bash|PowerShell)\([^%!"\r\n()*]{1,300}\)$/;
16
+ export const storableRule = (rule) => RULE.test(rule);
17
+ /** The step's kept rules, read for a launch; anything unreadable or malformed is left out. */
18
+ export function stepRules(product, work) {
19
+ try {
20
+ const settings = JSON.parse(readFileSync(localSettingsFile(product), 'utf8'));
21
+ const steps = isObject(settings) ? settings[STEP_KEY] : undefined;
22
+ const list = isObject(steps) ? steps[work] : undefined;
23
+ return Array.isArray(list)
24
+ ? list.filter((rule) => typeof rule === 'string' && storableRule(rule))
25
+ : [];
26
+ }
27
+ catch {
28
+ return [];
29
+ }
30
+ }
31
+ /** Adds the rules to the step's list: never twice, every other setting kept, written whole. */
32
+ export function keepStepRules(product, work, rules) {
33
+ if (!rules.length || !rules.every(storableRule))
34
+ return Promise.reject(new Error('rule'));
35
+ return updateLocalSettings(product, (settings) => {
36
+ const steps = settings[STEP_KEY] ?? {};
37
+ if (!isObject(steps))
38
+ throw new Error('settings');
39
+ const list = steps[work] ?? [];
40
+ if (!Array.isArray(list))
41
+ throw new Error('settings');
42
+ const added = rules.filter((rule) => !list.includes(rule));
43
+ if (!added.length)
44
+ return undefined;
45
+ return { ...settings, [STEP_KEY]: { ...steps, [work]: [...list, ...added] } };
46
+ });
47
+ }
@@ -86,13 +86,22 @@ export class ChatStore {
86
86
  }
87
87
  /** A stored chat's text as the chat it holds; a record that is not that chat is invalid. */
88
88
  parse(id, text) {
89
- let chat;
89
+ let record;
90
90
  try {
91
- chat = persistedChatSchema.parse(JSON.parse(scrubLaunchIds(text)));
91
+ record = JSON.parse(scrubLaunchIds(text));
92
92
  }
93
93
  catch {
94
94
  throw new InvalidChat(t('chat.invalid'));
95
95
  }
96
+ let parsed = persistedChatSchema.safeParse(record);
97
+ // A card that no longer fits the contract is stale: the chat stays, without it.
98
+ if (!parsed.success && record && typeof record === 'object' && 'asking' in record) {
99
+ const { asking: _stale, ...rest } = record;
100
+ parsed = persistedChatSchema.safeParse(rest);
101
+ }
102
+ if (!parsed.success)
103
+ throw new InvalidChat(t('chat.invalid'));
104
+ const chat = parsed.data;
96
105
  if (chat.id !== id)
97
106
  throw new InvalidChat(t('chat.invalid'));
98
107
  return chat;
@@ -13,6 +13,12 @@ export declare const en: {
13
13
  'chat.lines.refusal.permission': string;
14
14
  'chat.lines.permission': string;
15
15
  'chat.lines.allowed': string;
16
+ 'chat.lines.askOnce': string;
17
+ 'chat.lines.askAlways': string;
18
+ 'chat.lines.askRefused': string;
19
+ 'chat.lines.askEnded': string;
20
+ 'chat.ask.none': string;
21
+ 'chat.ask.onceOnly': string;
16
22
  'chat.allow.none': string;
17
23
  'chat.allow.notAbsolute': string;
18
24
  'chat.allow.missing': string;
@@ -13,6 +13,12 @@ export const en = {
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
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
15
  'chat.lines.allowed': '{by} allowed the agent to read {path}.',
16
+ 'chat.lines.askOnce': 'Allowed once: {command}',
17
+ 'chat.lines.askAlways': 'Always allowed in this step: {command}',
18
+ 'chat.lines.askRefused': 'Not allowed: {command}',
19
+ 'chat.lines.askEnded': 'Nobody answered, so this did not run: {command}',
20
+ 'chat.ask.none': 'The agent isn’t waiting for this answer any more.',
21
+ 'chat.ask.onceOnly': 'This one can only be allowed once.',
16
22
  'chat.allow.none': 'This message asks for no folder.',
17
23
  'chat.allow.notAbsolute': 'The studio allows only a folder named by its full path.',
18
24
  'chat.allow.missing': 'That folder isn’t there any more.',
@@ -15,6 +15,12 @@ export declare const es: {
15
15
  'chat.lines.refusal.permission': string;
16
16
  'chat.lines.permission': string;
17
17
  'chat.lines.allowed': string;
18
+ 'chat.lines.askOnce': string;
19
+ 'chat.lines.askAlways': string;
20
+ 'chat.lines.askRefused': string;
21
+ 'chat.lines.askEnded': string;
22
+ 'chat.ask.none': string;
23
+ 'chat.ask.onceOnly': string;
18
24
  'chat.allow.none': string;
19
25
  'chat.allow.notAbsolute': string;
20
26
  'chat.allow.missing': string;
@@ -15,6 +15,12 @@ export const es = {
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
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
17
  'chat.lines.allowed': '{by} permitió al agente leer {path}.',
18
+ 'chat.lines.askOnce': 'Permitido una vez: {command}',
19
+ 'chat.lines.askAlways': 'Siempre permitido en este paso: {command}',
20
+ 'chat.lines.askRefused': 'No permitido: {command}',
21
+ 'chat.lines.askEnded': 'Nadie respondió, así que esto no se ejecutó: {command}',
22
+ 'chat.ask.none': 'El agente ya no espera esta respuesta.',
23
+ 'chat.ask.onceOnly': 'Esto solo se puede permitir una vez.',
18
24
  'chat.allow.none': 'Este mensaje no pide ninguna carpeta.',
19
25
  'chat.allow.notAbsolute': 'El estudio solo permite una carpeta indicada con su ruta completa.',
20
26
  'chat.allow.missing': 'Esa carpeta ya no está.',
@@ -65,6 +65,9 @@ class TurnStream {
65
65
  const reply = this.options.reported ? adapter.reply?.(text) : undefined;
66
66
  if (reply !== undefined)
67
67
  this.options.reported?.(reply);
68
+ const notice = adapter.notice?.(text);
69
+ if (notice)
70
+ message(chat, 'system', notice);
68
71
  if (!events.length && !/^\s*[[{]/.test(text)) {
69
72
  this.appendDiagnostic(text);
70
73
  }
@@ -95,7 +98,7 @@ class TurnStream {
95
98
  this.file(event);
96
99
  }
97
100
  chat.state = 'running';
98
- if (events.length)
101
+ if (events.length || notice)
99
102
  store.checkpoint(chat);
100
103
  }
101
104
  catch {
@@ -0,0 +1,25 @@
1
+ import type { Level } from '@buffcore/contracts/workbench';
2
+ import type { Active } from './turn-state.ts';
3
+ /** What one Claude launch needs from the studio beyond its step's rules. */
4
+ export interface TurnGuard {
5
+ level: Level;
6
+ neverAsk: boolean;
7
+ /** Settings with the limits hook; absent on planning below Autopilot, which disables every hook. */
8
+ settings?: string;
9
+ /** The MCP config that serves the permission prompt tool; absent where `settings` is. */
10
+ mcp?: string;
11
+ /** The rules this launch passed to `--allowedTools`, filled by the arguments. */
12
+ allowed: string[];
13
+ /** Values a Windows launch may quote for this launch only. */
14
+ args: Set<string>;
15
+ close: () => void;
16
+ }
17
+ /** A value only an open launch's own guard wrote into its arguments. */
18
+ export declare const guardArgument: (arg: string) => boolean;
19
+ /**
20
+ * Opens a Claude launch's guard: the level and "Never ask" read now, and the limits hook in a
21
+ * settings file and the permission tool's channel, in a folder of the launch's own that closes
22
+ * with it. The hook runs before every call at every level, Never ask included; only planning below
23
+ * Autopilot, which runs `dontAsk` with every hook off, gets neither (deny rules hold its limits).
24
+ */
25
+ export declare function openTurnGuard(run: Active, root: string, save: () => void): TurnGuard;
@@ -0,0 +1,74 @@
1
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { effectiveLevel, effectiveNeverAsk } from '../../agents-file.js';
6
+ import { askPerson } from './permission-ask.js';
7
+ import { openPermissionChannel } from './permission-channel.js';
8
+ import { isPlanning } from './permissions.js';
9
+ import { chatError } from './prompt.js';
10
+ const live = new Set();
11
+ /** A value only an open launch's own guard wrote into its arguments. */
12
+ export const guardArgument = (arg) => [...live].some((guard) => guard.args.has(arg));
13
+ const script = (name) => {
14
+ const suffix = import.meta.url.endsWith('.ts') ? 'ts' : 'js';
15
+ return fileURLToPath(new URL(`./${name}.${suffix}`, import.meta.url)).replaceAll('\\', '/');
16
+ };
17
+ /**
18
+ * Opens a Claude launch's guard: the level and "Never ask" read now, and the limits hook in a
19
+ * settings file and the permission tool's channel, in a folder of the launch's own that closes
20
+ * with it. The hook runs before every call at every level, Never ask included; only planning below
21
+ * Autopilot, which runs `dontAsk` with every hook off, gets neither (deny rules hold its limits).
22
+ */
23
+ export function openTurnGuard(run, root, save) {
24
+ const guard = {
25
+ level: effectiveLevel(root),
26
+ neverAsk: effectiveNeverAsk(root),
27
+ allowed: [],
28
+ args: new Set(),
29
+ close: () => { },
30
+ };
31
+ live.add(guard);
32
+ if (isPlanning(run.chat.work) && guard.level !== 'auto') {
33
+ guard.close = () => live.delete(guard);
34
+ return guard;
35
+ }
36
+ const node = process.execPath.replaceAll('\\', '/');
37
+ const hook = script('limits-hook');
38
+ const tool = script('permission-tool');
39
+ if ([node, hook, tool].some((path) => /["%!\r\n]/.test(path))) {
40
+ live.delete(guard);
41
+ throw chatError('chat.invalid');
42
+ }
43
+ const folder = mkdtempSync(join(tmpdir(), 'ape-turn-'));
44
+ const closed = new AbortController();
45
+ const turn = {
46
+ chat: run.chat,
47
+ folder: run.tree,
48
+ allowed: guard.allowed,
49
+ product: root,
50
+ save,
51
+ };
52
+ const channel = openPermissionChannel((call) => askPerson(turn, call, closed.signal));
53
+ guard.settings = join(folder, 'settings.json');
54
+ guard.mcp = join(folder, 'mcp.json');
55
+ const command = `"${node}" "${hook}" ${run.chat.work}`;
56
+ writeFileSync(guard.settings, JSON.stringify({
57
+ // Flag settings outrank the product's own, so a product file cannot switch the hook off.
58
+ disableAllHooks: false,
59
+ hooks: { PreToolUse: [{ matcher: '*', hooks: [{ type: 'command', command, timeout: 30 }] }] },
60
+ }));
61
+ writeFileSync(guard.mcp, JSON.stringify({
62
+ mcpServers: { ape_permission: { type: 'stdio', command: node, args: [tool, channel.path] } },
63
+ }));
64
+ run.asks = turn;
65
+ guard.close = () => {
66
+ live.delete(guard);
67
+ closed.abort();
68
+ channel.close();
69
+ if (run.asks === turn)
70
+ delete run.asks;
71
+ rmSync(folder, { recursive: true, force: true });
72
+ };
73
+ return guard;
74
+ }
@@ -1,7 +1,8 @@
1
- import type { Chat, FoundAgent } from '@buffcore/contracts/workbench';
1
+ import type { Chat, FoundAgent, Level } from '@buffcore/contracts/workbench';
2
2
  import { type AgentSettings } from '../../agents-file.ts';
3
3
  import type { ChatImage } from './defs.ts';
4
4
  import { type ChatAdapter } from './prompt.ts';
5
+ import type { TurnGuard } from './turn-guard.ts';
5
6
  import type { Active } from './turn-state.ts';
6
7
  export declare const adapterFor: (id: Chat['agent']) => ChatAdapter | null;
7
8
  /** Codex splits image values on commas, including commas in a product's folder name. */
@@ -17,4 +18,4 @@ export declare function turnChoices(root: string, detect: () => Promise<FoundAge
17
18
  export declare function selectTurnAgent(run: Active, root: string, detect: () => Promise<FoundAgent[]>): Promise<void>;
18
19
  export declare function selectTakeover(run: Active): boolean;
19
20
  /** The same per-work choice supplies every launch, including resumes and a default takeover. */
20
- export declare function turnArgs(run: Active, root: string, adapter: ChatAdapter, examples?: string): string[];
21
+ export declare function turnArgs(run: Active, root: string, adapter: ChatAdapter, examples?: string, guard?: TurnGuard, level?: Level): string[];
@@ -62,7 +62,7 @@ export function selectTakeover(run) {
62
62
  return true;
63
63
  }
64
64
  /** The same per-work choice supplies every launch, including resumes and a default takeover. */
65
- export function turnArgs(run, root, adapter, examples) {
65
+ export function turnArgs(run, root, adapter, examples, guard, level) {
66
66
  const choice = run.settings && agentFor(run.chat.work, run.settings, run.found ?? [], adapter.id);
67
67
  prepareSelection(run, adapter.id, choice);
68
68
  if (choice?.notice)
@@ -79,5 +79,7 @@ export function turnArgs(run, root, adapter, examples) {
79
79
  page: run.chat.page,
80
80
  change: run.chat.change,
81
81
  examples,
82
+ guard,
83
+ level,
82
84
  });
83
85
  }
@@ -0,0 +1,19 @@
1
+ import type { Chat, PrototypeScenesReply } from '@buffcore/contracts/workbench';
2
+ import { viewSources } from '../../design/reach.ts';
3
+ export type TurnScene = NonNullable<NonNullable<Chat['messages'][number]['end']>['scenes']>[number];
4
+ export declare const SCENE_LINKS = 8;
5
+ interface Readers {
6
+ scenes: (root: string) => Promise<PrototypeScenesReply>;
7
+ views: typeof viewSources;
8
+ }
9
+ /** The files a turn wrote, as its own edit and write calls name them (paths from the product). */
10
+ export declare function writtenFiles(chat: Chat, firstMessage: number): ReadonlySet<string>;
11
+ /** Only a Prototype turn that wrote files can change scenes; any other turn ends without a wait. */
12
+ export declare function mayChangeScenes(chat: Chat, firstMessage: number): boolean;
13
+ /**
14
+ * The prototype scenes a Prototype turn changed: each scene whose named view reaches a file the
15
+ * turn wrote (the files it imports, as `design/reach.ts` follows them, like `own-scenes.ts`). The
16
+ * reply links to them in the preview. Anything unreadable gives no links, never an error.
17
+ */
18
+ export declare function turnScenes(root: string, chat: Chat, firstMessage: number, read?: Readers): Promise<TurnScene[]>;
19
+ export {};
@@ -0,0 +1,44 @@
1
+ import { viewSources } from '../../design/reach.js';
2
+ import { prototypeSceneReader } from '../prototype-scenes-read.js';
3
+ export const SCENE_LINKS = 8;
4
+ const readers = { scenes: (root) => prototypeSceneReader(root)(), views: viewSources };
5
+ /** The files a turn wrote, as its own edit and write calls name them (paths from the product). */
6
+ export function writtenFiles(chat, firstMessage) {
7
+ return new Set(chat.messages
8
+ .slice(firstMessage)
9
+ .flatMap((m) => m.tool && !m.tool.refused && ['edit', 'write'].includes(m.tool.verb) ? m.tool.targets : [])
10
+ .map((path) => path.replace(/\\/g, '/').replace(/^\.\//, '')));
11
+ }
12
+ /** Only a Prototype turn that wrote files can change scenes; any other turn ends without a wait. */
13
+ export function mayChangeScenes(chat, firstMessage) {
14
+ return (chat.work === 'design' &&
15
+ chat.title === 'prototype' &&
16
+ writtenFiles(chat, firstMessage).size > 0);
17
+ }
18
+ /**
19
+ * The prototype scenes a Prototype turn changed: each scene whose named view reaches a file the
20
+ * turn wrote (the files it imports, as `design/reach.ts` follows them, like `own-scenes.ts`). The
21
+ * reply links to them in the preview. Anything unreadable gives no links, never an error.
22
+ */
23
+ export async function turnScenes(root, chat, firstMessage, read = readers) {
24
+ if (!mayChangeScenes(chat, firstMessage))
25
+ return [];
26
+ try {
27
+ const written = writtenFiles(chat, firstMessage);
28
+ const reply = await read.scenes(root);
29
+ if (!reply.ok)
30
+ return [];
31
+ const views = await read.views(root);
32
+ return reply.scenes
33
+ .filter((scene) => {
34
+ const files = scene.view ? views[scene.surface]?.get(scene.view) : undefined;
35
+ return !!files && [...files.keys()].some((file) => written.has(file));
36
+ })
37
+ .filter((scene) => scene.key.length <= 100)
38
+ .slice(0, SCENE_LINKS)
39
+ .map(({ key, title }) => ({ key, title: title.slice(0, 200) }));
40
+ }
41
+ catch {
42
+ return [];
43
+ }
44
+ }
@@ -7,8 +7,10 @@ import type { ChatImage } from './defs.ts';
7
7
  import type { findAgents } from './find.ts';
8
8
  import type { Install } from './install.ts';
9
9
  import type { TurnMigrations } from './migration-turn.ts';
10
+ import type { AskTurn } from './permission-ask.ts';
10
11
  import type { TurnPerson } from './person.ts';
11
12
  import type { TurnResult } from './stream.ts';
13
+ import type { TurnScene } from './turn-scenes.ts';
12
14
  import type { TurnSelection } from './turn-selection.ts';
13
15
  import type { ensureWorktree } from './worktree.ts';
14
16
  export interface Active {
@@ -30,6 +32,10 @@ export interface Active {
30
32
  settings?: AgentSettings;
31
33
  found?: readonly FoundAgent[];
32
34
  selection?: TurnSelection;
35
+ /** The prototype scenes this turn changed, linked from its end. */
36
+ scenes?: TurnScene[];
37
+ /** The launch's permission card, while its permission tool can ask; private, never saved. */
38
+ asks?: AskTurn;
33
39
  }
34
40
  export interface ChatEngineOptions extends MergeConfiguration {
35
41
  start?: Start;
@@ -5,11 +5,11 @@ import { stopTree } from '../runner.js';
5
5
  import { finishChild, stopChild } from './agent-process.js';
6
6
  import { withTranscripts } from './attachments.js';
7
7
  import { finishChangeSave, readUnsavedTurn } from './change-save-turn.js';
8
+ import { withLinkedPermissions } from './codex-permissions.js';
8
9
  import { CodingApprovalRefusal, requireCodingApproval } from './coding-approval.js';
9
10
  import { HeldMerges } from './held-merges.js';
10
11
  import { launchInput, startCodingTurn } from './launch-input.js';
11
12
  import * as orphans from './orphans.js';
12
- import { withLinkedPermissions } from './permissions.js';
13
13
  import { turnOptions, turnPerson } from './person.js';
14
14
  import { agentStart } from './process.js';
15
15
  import { chatError, chatErrorMessage, t } from './prompt.js';
@@ -21,6 +21,7 @@ import { ChatStore, message } from './store.js';
21
21
  import { StudioSession } from './studio-session.js';
22
22
  import { selectTakeover, selectTurnAgent, turnChoices } from './turn-input.js';
23
23
  import { reserveTurn } from './turn-reserve.js';
24
+ import { mayChangeScenes, turnScenes } from './turn-scenes.js';
24
25
  import { startSelection } from './turn-selection.js';
25
26
  import { LOST_TURN } from './turn-state.js';
26
27
  import { noteFailure } from './unsent.js';
@@ -139,8 +140,9 @@ export class ChatEngine {
139
140
  if (run.stopped || this.closing)
140
141
  return this.finish(run, false);
141
142
  this.store.saveRetry(run.chat);
142
- const { adapter, input, spec, examples } = launchInput(run, this.root, context);
143
- const child = startCodingTurn(this.start, spec, run, this.options.migrations, examples);
143
+ const save = () => this.store.checkpoint(run.chat);
144
+ const { adapter, input, spec, examples, guard } = launchInput(run, this.root, context, save);
145
+ const child = startCodingTurn(this.start, spec, run, this.options.migrations, examples, guard);
144
146
  run.child = child;
145
147
  run.launched = true;
146
148
  const reported = startSelection(run);
@@ -179,6 +181,9 @@ export class ChatEngine {
179
181
  if (result.signedOut && (await this.takeover(run)))
180
182
  return;
181
183
  }
184
+ const first = run.firstMessage ?? 0;
185
+ if (!failed && !run.stopped && mayChangeScenes(run.chat, first))
186
+ run.scenes = await turnScenes(run.tree, run.chat, first);
182
187
  const saved = writesInChange(run.chat)
183
188
  ? await finishChangeSave(this.root, run, failed, this.attemptedTips.get(run.tree))
184
189
  : undefined;
@@ -15,7 +15,7 @@ export function levelRoute(root) {
15
15
  const { body, identity, hosted, level: control } = request;
16
16
  if (control)
17
17
  return { status: 409, body: levelElsewhere(control) };
18
- const { level } = levelBody.parse(await body());
18
+ const { level, neverAsk } = levelBody.parse(await body());
19
19
  const person = personForTurn({ identity, hosted });
20
20
  if (!person)
21
21
  return { status: 403, body: { error: hostT('ui.host.private') } };
@@ -25,9 +25,14 @@ export function levelRoute(root) {
25
25
  work: {},
26
26
  level: 'guide',
27
27
  };
28
- const content = await agentsFileText(target, { ...file, level });
28
+ // Never ask lives only with Autopilot: another level clears it, so coming back starts off.
29
+ const { neverAsk: saved, ...rest } = file;
30
+ const next = level === 'auto' && (neverAsk ?? saved)
31
+ ? { ...rest, level, neverAsk: true }
32
+ : { ...rest, level };
33
+ const content = await agentsFileText(target, next);
29
34
  if (!request.save) {
30
- await writeAgentsFile(target, { ...file, level });
35
+ await writeAgentsFile(target, next);
31
36
  factsChanged('levels', 'unsaved');
32
37
  if (level !== 'auto')
33
38
  mergeEvent('level', target);
@@ -1,4 +1,12 @@
1
1
  import { type HostPartSources } from '@buffcore/contracts/workbench';
2
+ import type { Theme } from '@buffcore/tokens';
3
+ /** What a host adds to the studio's page: its modules and its theme, both checked at start. */
4
+ export interface HostPageOptions {
5
+ /** Trusted modules served by the host, at the places `HostPartSources` names. Requires signIn. */
6
+ hostParts?: HostPartSources;
7
+ /** A host's theme, the same `Theme` as `studioTheme`; refused at start with every problem listed. */
8
+ theme?: Theme;
9
+ }
2
10
  /** The page's script, bundled from the admin shell's source (esbuild, a build-time tool). */
3
11
  export declare function bundlePage(cli?: string): Promise<string>;
4
12
  /** Where a built CLI keeps the page's script. */
@@ -6,7 +14,7 @@ export declare const builtPage: (cli: string) => string;
6
14
  /** The page's script: bundled now from source in a checkout, else the one the build made. */
7
15
  export declare function pageScript(cli?: string, locale?: 'en' | 'es'): Promise<string>;
8
16
  /** The page itself; mounting localizes the title to the studio's chosen language. */
9
- export declare const pageHtml: (product: string, hostParts?: HostPartSources, local?: boolean) => string;
17
+ export declare const pageHtml: (product: string, hostParts?: HostPartSources, local?: boolean, theme?: Theme) => string;
10
18
  /** Programmatic host setup only; reject unsafe maps before creating the server. */
11
19
  export declare function checkedHostParts(sources: HostPartSources | undefined, signedIn: boolean): {
12
20
  'top.end'?: string | undefined;
@@ -14,4 +22,14 @@ export declare function checkedHostParts(sources: HostPartSources | undefined, s
14
22
  'top.below'?: string | undefined;
15
23
  'setup.end'?: string | undefined;
16
24
  'issues.top'?: string | undefined;
25
+ 'side:prototype'?: string | undefined;
26
+ 'approve:release'?: string | undefined;
27
+ 'card:server'?: string | undefined;
28
+ rail?: {
29
+ id: string;
30
+ label: string;
31
+ source: string;
32
+ icon?: string | undefined;
33
+ }[] | undefined;
34
+ label?: string | undefined;
17
35
  } | undefined;
@@ -18,7 +18,9 @@ const token = root.hasAttribute('data-local-studio')
18
18
  : new URLSearchParams(location.search).get('token') ?? '';
19
19
  const data = document.getElementById('studio-host-parts');
20
20
  const hostParts = data ? JSON.parse(data.textContent) : undefined;
21
- mountStudio(root, { token, hostParts, locale: document.documentElement.lang || undefined });
21
+ const look = document.getElementById('studio-theme');
22
+ const theme = look ? JSON.parse(look.textContent) : undefined;
23
+ mountStudio(root, { token, hostParts, theme, locale: document.documentElement.lang || undefined });
22
24
  `;
23
25
  /** The page's script, bundled from the admin shell's source (esbuild, a build-time tool). */
24
26
  export async function bundlePage(cli = runningCli()) {
@@ -47,14 +49,15 @@ export async function pageScript(cli = runningCli(), locale) {
47
49
  }
48
50
  const escapeHtml = (s) => s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] ?? c);
49
51
  /** The page itself; mounting localizes the title to the studio's chosen language. */
50
- export const pageHtml = (product, hostParts, local = false) => `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(studioT('ui.title', { name: product }))}</title><link rel="stylesheet" href="${FONT_SHEET}" referrerpolicy="no-referrer"></head><body><div id="root"${local ? ' data-local-studio' : ''}></div>${hostPartsData(hostParts)}<script type="module" src="/page.js"></script></body></html>`;
52
+ export const pageHtml = (product, hostParts, local = false, theme) => `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(studioT('ui.title', { name: product }))}</title><link rel="stylesheet" href="${FONT_SHEET}" referrerpolicy="no-referrer"></head><body><div id="root"${local ? ' data-local-studio' : ''}></div>${hostPartsData(hostParts)}${jsonData('studio-theme', theme)}<script type="module" src="/page.js"></script></body></html>`;
51
53
  /** JSON data only; HTML delimiters cannot close this element or become executable markup. */
52
- function hostPartsData(sources) {
53
- if (!sources)
54
+ function jsonData(id, value) {
55
+ if (value === undefined)
54
56
  return '';
55
- const data = JSON.stringify(hostPartSourcesSchema.parse(sources)).replace(/[<>&\u2028\u2029]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
56
- return `<script id="studio-host-parts" type="application/json">${data}</script>`;
57
+ const data = JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
58
+ return `<script id="${id}" type="application/json">${data}</script>`;
57
59
  }
60
+ const hostPartsData = (sources) => sources ? jsonData('studio-host-parts', hostPartSourcesSchema.parse(sources)) : '';
58
61
  /** Programmatic host setup only; reject unsafe maps before creating the server. */
59
62
  export function checkedHostParts(sources, signedIn) {
60
63
  if (sources === undefined)