@buffcore/cli 0.8.41 → 0.8.43

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 (219) hide show
  1. package/CHANGELOG.md +36 -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 +12 -0
  17. package/dist/commands/design/references.js +44 -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/extension/places-approval.d.ts +1 -1
  26. package/dist/commands/port-claims.d.ts +23 -0
  27. package/dist/commands/port-claims.js +95 -0
  28. package/dist/commands/prototype/browser.d.ts +9 -4
  29. package/dist/commands/prototype/browser.js +26 -18
  30. package/dist/commands/prototype/comp-record.d.ts +27 -0
  31. package/dist/commands/prototype/comp-record.js +85 -0
  32. package/dist/commands/prototype/comp-words.d.ts +12 -0
  33. package/dist/commands/prototype/comp-words.js +24 -0
  34. package/dist/commands/prototype/comp.d.ts +26 -0
  35. package/dist/commands/prototype/comp.js +71 -0
  36. package/dist/commands/prototype/export-base.d.ts +27 -0
  37. package/dist/commands/prototype/export-base.js +80 -0
  38. package/dist/commands/prototype/export.d.ts +3 -2
  39. package/dist/commands/prototype/export.js +13 -6
  40. package/dist/commands/prototype/index.js +1 -0
  41. package/dist/commands/prototype/media-ready.d.ts +8 -0
  42. package/dist/commands/prototype/media-ready.js +36 -0
  43. package/dist/commands/prototype/messages.en.d.ts +6 -0
  44. package/dist/commands/prototype/messages.en.js +6 -0
  45. package/dist/commands/prototype/messages.js +6 -0
  46. package/dist/commands/prototype/milestone-versions.d.ts +1 -1
  47. package/dist/commands/prototype/record-look-child.js +4 -1
  48. package/dist/commands/prototype/scene.d.ts +3 -1
  49. package/dist/commands/prototype/scene.js +22 -6
  50. package/dist/commands/prototype/snapshot-command.js +1 -1
  51. package/dist/commands/prototype/snapshot-inputs.js +35 -7
  52. package/dist/commands/prototype/snapshot-setup.d.ts +12 -1
  53. package/dist/commands/prototype/snapshot-setup.js +31 -6
  54. package/dist/commands/prototype/snapshot.d.ts +2 -0
  55. package/dist/commands/prototype/snapshot.js +2 -1
  56. package/dist/commands/prototype/versions.d.ts +3 -3
  57. package/dist/commands/ui/agents-route.d.ts +2 -0
  58. package/dist/commands/ui/agents-route.js +8 -5
  59. package/dist/commands/ui/approval-authority.d.ts +1 -1
  60. package/dist/commands/ui/approve.js +7 -1
  61. package/dist/commands/ui/chat/allow-folder.js +23 -77
  62. package/dist/commands/ui/chat/claude-permissions.d.ts +21 -0
  63. package/dist/commands/ui/chat/claude-permissions.js +69 -0
  64. package/dist/commands/ui/chat/codex-idle.d.ts +2 -0
  65. package/dist/commands/ui/chat/codex-overrides.js +2 -1
  66. package/dist/commands/ui/chat/codex-permissions.d.ts +12 -0
  67. package/dist/commands/ui/chat/codex-permissions.js +97 -0
  68. package/dist/commands/ui/chat/command-parts.d.ts +33 -0
  69. package/dist/commands/ui/chat/command-parts.js +219 -0
  70. package/dist/commands/ui/chat/command-wrappers.d.ts +21 -0
  71. package/dist/commands/ui/chat/command-wrappers.js +100 -0
  72. package/dist/commands/ui/chat/design-deletes.d.ts +1 -0
  73. package/dist/commands/ui/chat/design-deletes.js +39 -0
  74. package/dist/commands/ui/chat/fresh-critique.d.ts +28 -0
  75. package/dist/commands/ui/chat/fresh-critique.js +121 -0
  76. package/dist/commands/ui/chat/fresh-launch.d.ts +31 -0
  77. package/dist/commands/ui/chat/fresh-launch.js +122 -0
  78. package/dist/commands/ui/chat/fresh-prompts.d.ts +17 -0
  79. package/dist/commands/ui/chat/fresh-prompts.js +76 -0
  80. package/dist/commands/ui/chat/fresh-report.d.ts +8 -0
  81. package/dist/commands/ui/chat/fresh-report.js +36 -0
  82. package/dist/commands/ui/chat/fresh-routes.d.ts +3 -0
  83. package/dist/commands/ui/chat/fresh-routes.js +64 -0
  84. package/dist/commands/ui/chat/fresh-settings.d.ts +12 -0
  85. package/dist/commands/ui/chat/fresh-settings.js +66 -0
  86. package/dist/commands/ui/chat/fresh-store.d.ts +17 -0
  87. package/dist/commands/ui/chat/fresh-store.js +67 -0
  88. package/dist/commands/ui/chat/fresh.d.ts +31 -0
  89. package/dist/commands/ui/chat/fresh.en.d.ts +7 -0
  90. package/dist/commands/ui/chat/fresh.en.js +7 -0
  91. package/dist/commands/ui/chat/fresh.es.d.ts +7 -0
  92. package/dist/commands/ui/chat/fresh.es.js +7 -0
  93. package/dist/commands/ui/chat/fresh.js +112 -0
  94. package/dist/commands/ui/chat/launch-input.d.ts +4 -2
  95. package/dist/commands/ui/chat/launch-input.js +16 -3
  96. package/dist/commands/ui/chat/limit-mentions.d.ts +5 -0
  97. package/dist/commands/ui/chat/limit-mentions.js +94 -0
  98. package/dist/commands/ui/chat/limit-patterns.d.ts +15 -0
  99. package/dist/commands/ui/chat/limit-patterns.js +182 -0
  100. package/dist/commands/ui/chat/limits-hook.d.ts +1 -0
  101. package/dist/commands/ui/chat/limits-hook.js +30 -0
  102. package/dist/commands/ui/chat/limits.d.ts +44 -0
  103. package/dist/commands/ui/chat/limits.en.d.ts +20 -0
  104. package/dist/commands/ui/chat/limits.en.js +20 -0
  105. package/dist/commands/ui/chat/limits.es.d.ts +2 -0
  106. package/dist/commands/ui/chat/limits.es.js +19 -0
  107. package/dist/commands/ui/chat/limits.js +236 -0
  108. package/dist/commands/ui/chat/local-settings.d.ts +17 -0
  109. package/dist/commands/ui/chat/local-settings.js +73 -0
  110. package/dist/commands/ui/chat/opencode-config.d.ts +22 -0
  111. package/dist/commands/ui/chat/opencode-config.js +83 -0
  112. package/dist/commands/ui/chat/parse-claude.js +25 -5
  113. package/dist/commands/ui/chat/permission-ask.d.ts +44 -0
  114. package/dist/commands/ui/chat/permission-ask.js +145 -0
  115. package/dist/commands/ui/chat/permission-channel.d.ts +18 -0
  116. package/dist/commands/ui/chat/permission-channel.js +67 -0
  117. package/dist/commands/ui/chat/permission-route.d.ts +10 -0
  118. package/dist/commands/ui/chat/permission-route.js +47 -0
  119. package/dist/commands/ui/chat/permission-tool.d.ts +1 -0
  120. package/dist/commands/ui/chat/permission-tool.js +86 -0
  121. package/dist/commands/ui/chat/permissions.d.ts +11 -12
  122. package/dist/commands/ui/chat/permissions.js +20 -102
  123. package/dist/commands/ui/chat/planning-limits.d.ts +12 -0
  124. package/dist/commands/ui/chat/planning-limits.js +46 -0
  125. package/dist/commands/ui/chat/process.js +4 -1
  126. package/dist/commands/ui/chat/prompt.d.ts +8 -1
  127. package/dist/commands/ui/chat/prompt.en.d.ts +4 -0
  128. package/dist/commands/ui/chat/prompt.en.js +4 -0
  129. package/dist/commands/ui/chat/prompt.es.d.ts +4 -0
  130. package/dist/commands/ui/chat/prompt.es.js +4 -0
  131. package/dist/commands/ui/chat/prompt.js +18 -50
  132. package/dist/commands/ui/chat/publish-limits.d.ts +4 -0
  133. package/dist/commands/ui/chat/publish-limits.js +97 -0
  134. package/dist/commands/ui/chat/recorded-turn.js +6 -0
  135. package/dist/commands/ui/chat/routes.js +2 -0
  136. package/dist/commands/ui/chat/secret-folders.d.ts +16 -0
  137. package/dist/commands/ui/chat/secret-folders.js +35 -0
  138. package/dist/commands/ui/chat/stdin-shells.d.ts +8 -0
  139. package/dist/commands/ui/chat/stdin-shells.js +102 -0
  140. package/dist/commands/ui/chat/step-rules.d.ts +13 -0
  141. package/dist/commands/ui/chat/step-rules.js +47 -0
  142. package/dist/commands/ui/chat/store.js +11 -2
  143. package/dist/commands/ui/chat/stream.en.d.ts +6 -0
  144. package/dist/commands/ui/chat/stream.en.js +6 -0
  145. package/dist/commands/ui/chat/stream.es.d.ts +6 -0
  146. package/dist/commands/ui/chat/stream.es.js +6 -0
  147. package/dist/commands/ui/chat/stream.js +8 -2
  148. package/dist/commands/ui/chat/turn-guard.d.ts +27 -0
  149. package/dist/commands/ui/chat/turn-guard.js +86 -0
  150. package/dist/commands/ui/chat/turn-input.d.ts +3 -2
  151. package/dist/commands/ui/chat/turn-input.js +3 -1
  152. package/dist/commands/ui/chat/turn-scenes.d.ts +19 -0
  153. package/dist/commands/ui/chat/turn-scenes.js +44 -0
  154. package/dist/commands/ui/chat/turn-state.d.ts +11 -0
  155. package/dist/commands/ui/chat/turn.js +9 -3
  156. package/dist/commands/ui/comp-approval.d.ts +6 -0
  157. package/dist/commands/ui/comp-approval.js +42 -0
  158. package/dist/commands/ui/host.js +3 -0
  159. package/dist/commands/ui/index.js +18 -6
  160. package/dist/commands/ui/level-route.js +8 -3
  161. package/dist/commands/ui/loop-approve.d.ts +4 -4
  162. package/dist/commands/ui/page.d.ts +19 -1
  163. package/dist/commands/ui/page.js +9 -6
  164. package/dist/commands/ui/places-change.d.ts +1 -1
  165. package/dist/commands/ui/plan-structure.d.ts +12 -2
  166. package/dist/commands/ui/plan-structure.en.d.ts +4 -0
  167. package/dist/commands/ui/plan-structure.en.js +4 -0
  168. package/dist/commands/ui/plan-structure.es.d.ts +4 -0
  169. package/dist/commands/ui/plan-structure.es.js +4 -0
  170. package/dist/commands/ui/plan-structure.js +48 -14
  171. package/dist/commands/ui/prototype-comp-route.d.ts +7 -0
  172. package/dist/commands/ui/prototype-comp-route.js +109 -0
  173. package/dist/commands/ui/prototype-main.d.ts +3 -1
  174. package/dist/commands/ui/prototype-scenes-child.js +6 -1
  175. package/dist/commands/ui/prototype-scenes-read.d.ts +1 -0
  176. package/dist/commands/ui/prototype-scenes-route.js +7 -1
  177. package/dist/commands/ui/prototype-snapshot-session.d.ts +1 -1
  178. package/dist/commands/ui/prototype-snapshot-session.js +3 -0
  179. package/dist/commands/ui/prototype-snapshot.d.ts +1 -1
  180. package/dist/commands/ui/routes.d.ts +6 -3
  181. package/dist/commands/ui/routes.js +3 -3
  182. package/dist/commands/ui/save-commit.js +6 -2
  183. package/dist/commands/ui/save-publish.js +3 -0
  184. package/dist/commands/ui/server-options.js +2 -0
  185. package/dist/commands/ui/server.d.ts +12 -22
  186. package/dist/commands/ui/server.js +10 -48
  187. package/dist/commands/ui/snapshot-runners.d.ts +22 -0
  188. package/dist/commands/ui/snapshot-runners.js +45 -0
  189. package/dist/commands/ui/structure-surface.d.ts +6 -0
  190. package/dist/commands/ui/structure-surface.js +94 -0
  191. package/dist/commands/ui/studio-routes.d.ts +1 -0
  192. package/dist/commands/ui/studio-routes.js +5 -0
  193. package/dist/commands/ui/studio-state.d.ts +9 -4
  194. package/dist/commands/ui/studio-state.js +1 -0
  195. package/dist/commands/ui/studio-versions.d.ts +3 -3
  196. package/dist/commands/ui/studio.en.d.ts +13 -0
  197. package/dist/commands/ui/studio.en.js +13 -0
  198. package/dist/commands/ui/studio.es.d.ts +13 -0
  199. package/dist/commands/ui/studio.es.js +13 -0
  200. package/dist/commands/ui/theme-option.d.ts +8 -0
  201. package/dist/commands/ui/theme-option.js +40 -0
  202. package/dist/commands/ui/theme-values.d.ts +5 -0
  203. package/dist/commands/ui/theme-values.js +113 -0
  204. package/dist/ui/page.js +94 -94
  205. package/docs/PROCESS.md +5 -0
  206. package/docs/PROTOTYPE.md +24 -1
  207. package/docs/WORKBENCH.md +76 -22
  208. package/package.json +11 -11
  209. package/skills/ape-critique/SKILL.md +16 -6
  210. package/skills/ape-design-system/SKILL.md +4 -3
  211. package/skills/ape-plan-change/SKILL.md +7 -3
  212. package/skills/ape-prototype/SKILL.md +12 -1
  213. package/templates/example/apps/app/src/i18n/en.ts +2 -0
  214. package/templates/example/apps/app/src/i18n/es.json +2 -0
  215. package/templates/product/apps/admin/src/fonts.ts +2 -1
  216. package/templates/product/apps/app/src/fonts.ts +5 -1
  217. package/templates/product/apps/app/src/i18n/en.ts +2 -0
  218. package/templates/product/apps/app/src/i18n/es.json +2 -0
  219. package/templates/product/prototype/journeys.ts +3 -0
@@ -0,0 +1,22 @@
1
+ import type { TurnOptions } from './prompt.ts';
2
+ /** What every OpenCode turn denies for the limits: commands, and files for read and edit alike. */
3
+ export declare const OPENCODE_LIMITS: {
4
+ bash: {
5
+ [k: string]: string;
6
+ };
7
+ files: {
8
+ [k: string]: string;
9
+ };
10
+ };
11
+ /**
12
+ * The file limits for one turn's folder. A secret folder's name the folder lies in (a product
13
+ * kept under `secrets/`) is denied inside the product (by its path from the disk's root, or at
14
+ * the product's top from the project) and in the person's home, not around the product.
15
+ */
16
+ export declare function openCodeLimitFiles(folder: string): Record<string, string>;
17
+ /**
18
+ * OpenCode's runtime overlay (`OPENCODE_CONFIG_CONTENT`): the turn's own permission rules.
19
+ * On Autopilot (with `--auto`) a design turn has no command list, so nothing outside it is
20
+ * refused; the limits and the file denies hold at every level.
21
+ */
22
+ export declare function openCodeConfig(options: TurnOptions): string;
@@ -0,0 +1,83 @@
1
+ import { openCodeWildcard } from '../../agents/patterns.js';
2
+ import { claudeRules, holdFiles, turnWriteDenials } from './permissions.js';
3
+ import { LIMIT_COMMANDS, PRODUCTION_FILES } from './planning-limits.js';
4
+ import { enclosingSecrets, homeSecret, SECRET_FOLDERS } from './secret-folders.js';
5
+ import { verificationCommands, verifiesProduct } from './verification.js';
6
+ const deny = (patterns) => Object.fromEntries(patterns.map((path) => [path, 'deny']));
7
+ /**
8
+ * The limits as OpenCode rules, at every level: OpenCode has no hook, so its own deny rules are
9
+ * what holds them, and `--auto` keeps explicit denies. Commands match by their text (a prefix,
10
+ * then anything), secret folders and production settings by path; its web fetch tool is off.
11
+ */
12
+ const LIMIT_SHELL = deny(LIMIT_COMMANDS.flatMap((command) => [command, `${command} *`]));
13
+ const LIMIT_FILES = deny([
14
+ ...[...SECRET_FOLDERS].map((folder) => openCodeWildcard(`${folder}/`)),
15
+ ...PRODUCTION_FILES.map((file) => `*${file}`),
16
+ ]);
17
+ /** What every OpenCode turn denies for the limits: commands, and files for read and edit alike. */
18
+ export const OPENCODE_LIMITS = { bash: LIMIT_SHELL, files: LIMIT_FILES };
19
+ /**
20
+ * The file limits for one turn's folder. A secret folder's name the folder lies in (a product
21
+ * kept under `secrets/`) is denied inside the product (by its path from the disk's root, or at
22
+ * the product's top from the project) and in the person's home, not around the product.
23
+ */
24
+ export function openCodeLimitFiles(folder) {
25
+ const enclosing = enclosingSecrets(folder);
26
+ if (!enclosing.length)
27
+ return LIMIT_FILES;
28
+ const root = folder.replaceAll('\\', '/');
29
+ return deny([
30
+ ...[...SECRET_FOLDERS].flatMap((name) => {
31
+ if (!enclosing.includes(name))
32
+ return [openCodeWildcard(`${name}/`)];
33
+ const home = homeSecret(name, folder)?.replaceAll('\\', '/');
34
+ return [`${root}/*${name}/*`, `${name}/*`, ...(home ? [`${home}/*`] : [])];
35
+ }),
36
+ ...PRODUCTION_FILES.map((file) => `*${file}`),
37
+ ]);
38
+ }
39
+ /**
40
+ * OpenCode's runtime overlay (`OPENCODE_CONFIG_CONTENT`): the turn's own permission rules.
41
+ * On Autopilot (with `--auto`) a design turn has no command list, so nothing outside it is
42
+ * refused; the limits and the file denies hold at every level.
43
+ */
44
+ export function openCodeConfig(options) {
45
+ const { contained = false, work = 'loop', folder = process.cwd(), root = folder } = options;
46
+ const verification = verificationCommands(root, options);
47
+ const files = openCodeLimitFiles(folder);
48
+ const commands = claudeRules(work, folder)
49
+ .filter((rule) => rule.startsWith('Bash('))
50
+ .flatMap((rule) => {
51
+ const command = rule.slice(5, -1);
52
+ return command.endsWith(':*')
53
+ ? [command.slice(0, -2), command.replace(/:\*$/, ' *')]
54
+ : [command];
55
+ });
56
+ const listed = verifiesProduct(options) && options.level !== 'auto';
57
+ const comments = { [openCodeWildcard('.ape/comments/')]: 'deny' };
58
+ return JSON.stringify({
59
+ ...(contained ? { mcp: { ape: { enabled: false } } } : {}),
60
+ permission: {
61
+ // The last matching rule wins, so the limits come after the list.
62
+ bash: {
63
+ ...(listed
64
+ ? {
65
+ '*': 'deny',
66
+ ...Object.fromEntries([...commands, ...verification].map((command) => [command, 'allow'])),
67
+ }
68
+ : {}),
69
+ ...LIMIT_SHELL,
70
+ },
71
+ read: { ...comments, ...files },
72
+ edit: {
73
+ ...comments,
74
+ [openCodeWildcard('plan/agents.md')]: 'deny',
75
+ [openCodeWildcard('plan/places.json')]: 'deny',
76
+ ...Object.fromEntries(holdFiles.map((path) => [openCodeWildcard(path), 'deny'])),
77
+ ...Object.fromEntries(turnWriteDenials(work).map((path) => [openCodeWildcard(`${path}/`), 'deny'])),
78
+ ...files,
79
+ },
80
+ webfetch: 'deny',
81
+ },
82
+ });
83
+ }
@@ -1,6 +1,8 @@
1
1
  import { choiceReply } from './choice-reply.js';
2
+ import { permissionMode } from './claude-permissions.js';
2
3
  import { isClaudeTaskOutput } from './claude-task-output.js';
3
- import { buildArgs, failure, jsonLine, object } from './prompt.js';
4
+ import { refusalLimit } from './limits.js';
5
+ import { buildArgs, failure, jsonLine, object, t } from './prompt.js';
4
6
  const verbs = {
5
7
  read: 'read',
6
8
  read_file: 'read',
@@ -65,9 +67,12 @@ function refusalEvents(value) {
65
67
  block.is_error !== true ||
66
68
  typeof block.tool_use_id !== 'string')
67
69
  return [];
68
- return permissionRefused(JSON.stringify(block.content))
69
- ? [{ kind: 'refused', id: block.tool_use_id }]
70
- : [];
70
+ const text = JSON.stringify(block.content);
71
+ // The studio's limits hook refused it: its own sentence is the result.
72
+ const limit = refusalLimit(text);
73
+ if (limit)
74
+ return [{ kind: 'refused', id: block.tool_use_id, limit }];
75
+ return permissionRefused(text) ? [{ kind: 'refused', id: block.tool_use_id }] : [];
71
76
  }
72
77
  /** Claude's result lists the tool and input, with no structured permission decision. */
73
78
  function refusalReason(tool) {
@@ -130,10 +135,25 @@ function claudeEvents(event) {
130
135
  /** Documented stream-json messages, without partial-message duplication. */
131
136
  export function claudeAdapter() {
132
137
  const calls = new Map();
138
+ let asked;
133
139
  return {
134
140
  id: 'claude',
135
141
  reply: choiceReply('claude'),
136
- buildArgs: (options) => buildArgs('claude', options),
142
+ buildArgs: (options) => {
143
+ asked = permissionMode(options.work ?? 'loop', options.guard);
144
+ return buildArgs('claude', options);
145
+ },
146
+ // Claude Code runs `auto` only on models that support it and otherwise starts in `default`
147
+ // without a word; its init event names the mode it really runs, so the chat says so once.
148
+ notice(line) {
149
+ const event = jsonLine(line);
150
+ if (asked !== 'auto' || event.type !== 'system' || event.subtype !== 'init')
151
+ return;
152
+ if (typeof event.permissionMode !== 'string' || event.permissionMode === 'auto')
153
+ return;
154
+ asked = undefined;
155
+ return t('chat.autoUnavailable');
156
+ },
137
157
  parse(line) {
138
158
  return claudeEvents(jsonLine(line)).map((event) => {
139
159
  if (event.kind === 'tool' && event.id)
@@ -0,0 +1,44 @@
1
+ import type { Chat } from '@buffcore/contracts/workbench';
2
+ import { type Limit } from './limits.ts';
3
+ import type { PermissionAnswer, PermissionCall } from './permission-channel.ts';
4
+ export type AskAnswer = 'once' | 'always' | 'deny';
5
+ /** The card a paused turn shows, and how the route answers it. Private to the launch. */
6
+ export interface PendingAsk {
7
+ id: string;
8
+ /** The exact rules "Always allow in this step" keeps; empty when only Allow once is offered. */
9
+ rules: string[];
10
+ answer: (answer: AskAnswer) => void;
11
+ }
12
+ export interface AskTurn {
13
+ chat: Chat;
14
+ /** The turn's folder: where the agent's relative paths point. */
15
+ folder: string;
16
+ /** The step's rules this launch passed to `--allowedTools`. */
17
+ allowed: readonly string[];
18
+ /** The product whose step list Always allow writes: read again for each call. */
19
+ product?: string;
20
+ save: () => void;
21
+ asking?: PendingAsk;
22
+ queue?: Promise<unknown>;
23
+ }
24
+ export declare const ASK_WAIT: number;
25
+ /** A step rule (`Bash(cmd)` exact, `Bash(cmd:*)` the command and its arguments) allowing the part. */
26
+ export declare function ruleAllows(rules: readonly string[], tool: string, part: string): boolean;
27
+ /** Text the card stores, never longer than its cap and never empty. */
28
+ export declare const shortened: (text: string, cap: number) => string;
29
+ /** What the card says and what Always allow would keep, from the call alone. */
30
+ export declare function askCard(call: PermissionCall, turn: Pick<AskTurn, 'folder' | 'allowed'>): {
31
+ nameable: boolean;
32
+ command: string;
33
+ limit: Limit | undefined;
34
+ outside: string[];
35
+ inside: string[];
36
+ parts: string[];
37
+ rules: string[];
38
+ };
39
+ /**
40
+ * One call the permission tool hands over: the chat shows the card, the turn waits for the
41
+ * person's answer (or the turn's end, or half an hour), and the agent hears the outcome. Calls
42
+ * wait their turn, so a chat shows one card at a time.
43
+ */
44
+ export declare function askPerson(turn: AskTurn, call: PermissionCall, closed: AbortSignal, wait?: number): Promise<PermissionAnswer>;
@@ -0,0 +1,145 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { commandParts, partProgram } from './command-parts.js';
3
+ import { crossedLimit, limitReason, limitText } from './limits.js';
4
+ import { stepRules, storableRule } from './step-rules.js';
5
+ import { message } from './store.js';
6
+ import { lineText } from './stream-text.js';
7
+ const SHELLS = new Map([
8
+ ['Bash', 'bash'],
9
+ ['PowerShell', 'powershell'],
10
+ ]);
11
+ export const ASK_WAIT = 30 * 60_000;
12
+ /** The chat contract's caps on the card's stored text (workbench-chats.ts). */
13
+ const COMMAND_CAP = 2000;
14
+ const PART_CAP = 300;
15
+ /** A here-document's body follows its first line: a one-line rule can't name the whole call. */
16
+ const HEREDOC = /<<-?\s*['"\\]?[A-Za-z_]/;
17
+ /** A step rule (`Bash(cmd)` exact, `Bash(cmd:*)` the command and its arguments) allowing the part. */
18
+ export function ruleAllows(rules, tool, part) {
19
+ return rules.some((rule) => {
20
+ if (!rule.startsWith(`${tool}(`) || !rule.endsWith(')'))
21
+ return false;
22
+ const body = rule.slice(tool.length + 1, -1);
23
+ if (!body.endsWith(':*'))
24
+ return part === body;
25
+ const prefix = body.slice(0, -2);
26
+ return part === prefix || part.startsWith(`${prefix} `);
27
+ });
28
+ }
29
+ /** Text the card stores, never longer than its cap and never empty. */
30
+ export const shortened = (text, cap) => !text ? '?' : text.length > cap ? `${text.slice(0, cap - 1)}…` : text;
31
+ function describe(call) {
32
+ const input = (call.input ?? {});
33
+ const target = [input.command, input.file_path, input.path, input.url, input.pattern].find((value) => typeof value === 'string' && value.length > 0);
34
+ const text = SHELLS.has(call.tool) ? (target ?? '') : `${call.tool} ${target ?? ''}`.trim();
35
+ return text || call.tool;
36
+ }
37
+ /** What the card says and what Always allow would keep, from the call alone. */
38
+ export function askCard(call, turn) {
39
+ const whole = describe(call);
40
+ const shell = SHELLS.get(call.tool);
41
+ const parts = shell ? commandParts(whole, shell) : [];
42
+ const outside = parts.filter((part) => !ruleAllows(turn.allowed, call.tool, part));
43
+ const named = outside.length ? outside : parts;
44
+ const rules = outside.map((part) => `${call.tool}(${part})`);
45
+ const limit = crossedLimit(call.tool, call.input, turn.folder);
46
+ // A command a rule can name exactly: no limit, no here-document, not cut short.
47
+ const nameable = !!shell && !limit && whole.length <= COMMAND_CAP && !HEREDOC.test(whole);
48
+ const once = !nameable || !rules.length || !rules.every(storableRule);
49
+ return {
50
+ nameable,
51
+ command: shortened(whole, COMMAND_CAP),
52
+ limit,
53
+ outside,
54
+ inside: parts.filter((part) => !outside.includes(part)),
55
+ parts: [...new Set(named.map((part) => shortened(partProgram(part), PART_CAP)))].slice(0, 20),
56
+ rules: once ? [] : rules,
57
+ };
58
+ }
59
+ /** Why the card asks when the limits could not vouch for the command, as the chat stores it. */
60
+ const unsureOf = (limit) => limit?.kind === 'unsure' && limit.unsure
61
+ ? {
62
+ unsure: {
63
+ why: limit.unsure,
64
+ ...(limit.mention ? { mention: shortened(limit.mention, 80) } : {}),
65
+ },
66
+ }
67
+ : {};
68
+ /** The sentence the agent reads when the person says no, or nobody answers. */
69
+ function refusal(card, answer) {
70
+ const parts = (card.parts.length ? card.parts : [card.command]).join('`, `');
71
+ if (answer === 'ended')
72
+ return limitText('limits.ended', { parts });
73
+ if (card.limit)
74
+ return limitReason(card.limit);
75
+ return card.inside.length
76
+ ? limitText('limits.outside', { parts, allowed: card.inside.join('`, `') })
77
+ : limitText('limits.refused', { parts });
78
+ }
79
+ /**
80
+ * One call the permission tool hands over: the chat shows the card, the turn waits for the
81
+ * person's answer (or the turn's end, or half an hour), and the agent hears the outcome. Calls
82
+ * wait their turn, so a chat shows one card at a time.
83
+ */
84
+ export function askPerson(turn, call, closed, wait = ASK_WAIT) {
85
+ const next = (turn.queue ?? Promise.resolve()).then(() => ask(turn, call, closed, wait));
86
+ turn.queue = next.catch(() => undefined);
87
+ return next;
88
+ }
89
+ /**
90
+ * Always allow reaches the running launch too: the step's list is read again for each call, so a
91
+ * command kept a moment ago (here or in another chat of this step) does not ask twice. Only exact
92
+ * kept rules count, and only for a call a rule can name.
93
+ */
94
+ function keptSince(turn, call, card) {
95
+ if (!turn.product || !card.nameable || !card.outside.length)
96
+ return false;
97
+ const kept = stepRules(turn.product, turn.chat.work);
98
+ return card.outside.every((part) => ruleAllows(kept, call.tool, part));
99
+ }
100
+ async function ask(turn, call, closed, wait) {
101
+ if (closed.aborted)
102
+ return { allow: false, message: refusal(askCard(call, turn), 'ended') };
103
+ const card = askCard(call, turn);
104
+ // A limit is never the person's to allow: the hook refuses it first, and so does the card.
105
+ if (card.limit?.decision === 'deny')
106
+ return { allow: false, message: limitReason(card.limit) };
107
+ if (keptSince(turn, call, card))
108
+ return { allow: true };
109
+ const id = randomUUID();
110
+ const answer = await new Promise((resolve) => {
111
+ const timer = setTimeout(() => resolve('ended'), wait);
112
+ timer.unref?.();
113
+ const end = () => resolve('ended');
114
+ closed.addEventListener('abort', end, { once: true });
115
+ turn.asking = {
116
+ id,
117
+ rules: card.rules,
118
+ answer: (value) => {
119
+ clearTimeout(timer);
120
+ closed.removeEventListener('abort', end);
121
+ resolve(value);
122
+ },
123
+ };
124
+ turn.chat.asking = {
125
+ id,
126
+ tool: call.tool.slice(0, 80) || '?',
127
+ command: card.command,
128
+ parts: card.parts,
129
+ ...(card.rules.length ? {} : { once: true }),
130
+ ...unsureOf(card.limit),
131
+ at: new Date().toISOString(),
132
+ };
133
+ turn.save();
134
+ });
135
+ if (turn.asking?.id === id)
136
+ delete turn.asking;
137
+ if (turn.chat.asking?.id === id)
138
+ delete turn.chat.asking;
139
+ const line = { once: 'askOnce', always: 'askAlways', deny: 'askRefused', ended: 'askEnded' };
140
+ message(turn.chat, 'system', lineText(`chat.lines.${line[answer]}`, { command: card.command }));
141
+ turn.save();
142
+ return answer === 'once' || answer === 'always'
143
+ ? { allow: true }
144
+ : { allow: false, message: refusal(card, answer) };
145
+ }
@@ -0,0 +1,18 @@
1
+ export interface PermissionCall {
2
+ tool: string;
3
+ input: unknown;
4
+ }
5
+ export interface PermissionAnswer {
6
+ allow: boolean;
7
+ message?: string;
8
+ }
9
+ /**
10
+ * One launch's local channel for its permission tool: a named pipe (Windows) or a socket only its
11
+ * owner can open, at an unguessable name that only this launch's arguments carry. It is not an
12
+ * HTTP route, so nothing that reaches the studio's server can answer through it, and it closes
13
+ * with the turn. Each connection is one call; the answer is one JSON line.
14
+ */
15
+ export declare function openPermissionChannel(answer: (call: PermissionCall) => Promise<PermissionAnswer>): {
16
+ path: string;
17
+ close: () => void;
18
+ };
@@ -0,0 +1,67 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { chmodSync, rmSync } from 'node:fs';
3
+ import { createServer } from 'node:net';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ const LIMIT = 256 * 1024;
7
+ /**
8
+ * One launch's local channel for its permission tool: a named pipe (Windows) or a socket only its
9
+ * owner can open, at an unguessable name that only this launch's arguments carry. It is not an
10
+ * HTTP route, so nothing that reaches the studio's server can answer through it, and it closes
11
+ * with the turn. Each connection is one call; the answer is one JSON line.
12
+ */
13
+ export function openPermissionChannel(answer) {
14
+ const name = `ape-permission-${randomBytes(16).toString('hex')}`;
15
+ const path = process.platform === 'win32' ? `\\\\.\\pipe\\${name}` : join(tmpdir(), `${name}.sock`);
16
+ const sockets = new Set();
17
+ const server = createServer((socket) => {
18
+ sockets.add(socket);
19
+ socket.setEncoding('utf8');
20
+ let text = '';
21
+ let asked = false;
22
+ socket.on('close', () => sockets.delete(socket));
23
+ socket.on('error', () => socket.destroy());
24
+ socket.on('data', (chunk) => {
25
+ if (asked)
26
+ return;
27
+ text += chunk;
28
+ if (text.length > LIMIT)
29
+ return socket.destroy();
30
+ const end = text.indexOf('\n');
31
+ if (end < 0)
32
+ return;
33
+ asked = true;
34
+ let call;
35
+ try {
36
+ const value = JSON.parse(text.slice(0, end));
37
+ if (typeof value.tool !== 'string')
38
+ throw new Error('call');
39
+ call = { tool: value.tool, input: value.input ?? {} };
40
+ }
41
+ catch {
42
+ return socket.end(`${JSON.stringify({ allow: false })}\n`);
43
+ }
44
+ answer(call)
45
+ .catch(() => ({ allow: false }))
46
+ .then((reply) => {
47
+ if (!socket.destroyed)
48
+ socket.end(`${JSON.stringify(reply)}\n`);
49
+ });
50
+ });
51
+ });
52
+ server.on('error', () => server.close());
53
+ server.listen(path, () => {
54
+ if (process.platform !== 'win32')
55
+ chmodSync(path, 0o600);
56
+ });
57
+ return {
58
+ path,
59
+ close: () => {
60
+ for (const socket of sockets)
61
+ socket.destroy();
62
+ server.close();
63
+ if (process.platform !== 'win32')
64
+ rmSync(path, { force: true });
65
+ },
66
+ };
67
+ }
@@ -0,0 +1,10 @@
1
+ import type { UiRoute } from '../routes.ts';
2
+ import type { ChatEngine } from './turn.ts';
3
+ /**
4
+ * A person's answer to a paused turn's card: Allow once, Always allow in this step, or Don't
5
+ * allow. Only the studio page reaches it (its token or the host's sign-in, Origin, the settings
6
+ * right), and only for the card the running launch shows now: an answer naming another card, an
7
+ * ended launch or another chat is refused. "Always" keeps the card's own rules, never words from
8
+ * the request, before the turn goes on.
9
+ */
10
+ export declare function permissionRoute(engine: ChatEngine): UiRoute;
@@ -0,0 +1,47 @@
1
+ import { chatIdSchema, permissionAnswerBody, permissionAnswerReply, } from '@buffcore/contracts/workbench';
2
+ import { t } from './prompt.js';
3
+ import { keepStepRules } from './step-rules.js';
4
+ import { lineText } from './stream-text.js';
5
+ const refused = (status, text) => ({ status, body: { error: text } });
6
+ /**
7
+ * A person's answer to a paused turn's card: Allow once, Always allow in this step, or Don't
8
+ * allow. Only the studio page reaches it (its token or the host's sign-in, Origin, the settings
9
+ * right), and only for the card the running launch shows now: an answer naming another card, an
10
+ * ended launch or another chat is refused. "Always" keeps the card's own rules, never words from
11
+ * the request, before the turn goes on.
12
+ */
13
+ export function permissionRoute(engine) {
14
+ return {
15
+ method: 'POST',
16
+ path: '/api/chats/:id/permission',
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 = permissionAnswerBody.safeParse(await request.body().catch(() => undefined));
24
+ if (!body.success)
25
+ return refused(400, t('chat.invalid'));
26
+ const run = [...engine.active.values()].find((active) => active.chat.id === id);
27
+ const pending = run?.asks?.asking;
28
+ if (!pending || pending.id !== body.data.id)
29
+ return refused(409, lineText('chat.ask.none'));
30
+ if (body.data.answer === 'always') {
31
+ if (!pending.rules.length)
32
+ return refused(409, lineText('chat.ask.onceOnly'));
33
+ try {
34
+ await keepStepRules(engine.root, run.chat.work, pending.rules);
35
+ }
36
+ catch {
37
+ return refused(409, lineText('chat.allow.settings'));
38
+ }
39
+ // The card may have ended while the file was written; the rule is kept either way.
40
+ if (run.asks?.asking !== pending)
41
+ return refused(409, lineText('chat.ask.none'));
42
+ }
43
+ pending.answer(body.data.answer);
44
+ return { status: 200, body: permissionAnswerReply.parse({ ok: true }) };
45
+ },
46
+ };
47
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The permission prompt tool a Claude turn calls (`--permission-prompt-tool`) when a call needs an
3
+ * answer: a tiny stdio MCP server with one tool, `ask`. Run by plain Node, as
4
+ * `node permission-tool.ts <channel>`, it hands the call to the studio over the turn's own local
5
+ * channel and waits for the person. Only the studio answers; the tool never decides, and it always
6
+ * returns the agent's own input unchanged on an allow.
7
+ */
8
+ import { connect } from 'node:net';
9
+ import { createInterface } from 'node:readline';
10
+ import { limitText } from './limits.js';
11
+ const channel = process.argv[2] ?? '';
12
+ const send = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);
13
+ /** One call, one connection: the studio's first line back is the answer. */
14
+ function askStudio(tool, input) {
15
+ const unanswered = { allow: false, message: limitText('limits.ended', { parts: tool }) };
16
+ return new Promise((resolve) => {
17
+ let text = '';
18
+ const socket = connect(channel);
19
+ socket.setEncoding('utf8');
20
+ socket.on('connect', () => socket.write(`${JSON.stringify({ tool, input })}\n`));
21
+ socket.on('data', (chunk) => {
22
+ text += chunk;
23
+ if (!text.includes('\n'))
24
+ return;
25
+ socket.end();
26
+ try {
27
+ const answer = JSON.parse(text.slice(0, text.indexOf('\n')));
28
+ resolve(answer.allow === true ? { allow: true } : { ...unanswered, ...answer, allow: false });
29
+ }
30
+ catch {
31
+ resolve(unanswered);
32
+ }
33
+ });
34
+ socket.on('error', () => resolve(unanswered));
35
+ socket.on('close', () => resolve(unanswered));
36
+ });
37
+ }
38
+ const TOOL = {
39
+ name: 'ask',
40
+ description: "Asks the studio's person to allow a tool call.",
41
+ inputSchema: {
42
+ type: 'object',
43
+ properties: {
44
+ tool_name: { type: 'string' },
45
+ input: { type: 'object' },
46
+ tool_use_id: { type: 'string' },
47
+ },
48
+ required: ['tool_name', 'input'],
49
+ },
50
+ };
51
+ async function call(id, params) {
52
+ const tool = typeof params.arguments?.tool_name === 'string' ? params.arguments.tool_name : '';
53
+ const input = params.arguments?.input ?? {};
54
+ const answer = await askStudio(tool, input);
55
+ const body = answer.allow
56
+ ? { behavior: 'allow', updatedInput: input }
57
+ : { behavior: 'deny', message: answer.message };
58
+ send({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: JSON.stringify(body) }] } });
59
+ }
60
+ createInterface({ input: process.stdin }).on('line', (line) => {
61
+ let message;
62
+ try {
63
+ message = JSON.parse(line);
64
+ }
65
+ catch {
66
+ return;
67
+ }
68
+ const { id, method, params = {} } = message;
69
+ if (method === 'initialize')
70
+ return send({
71
+ jsonrpc: '2.0',
72
+ id,
73
+ result: {
74
+ protocolVersion: params.protocolVersion ?? '2025-06-18',
75
+ capabilities: { tools: {} },
76
+ serverInfo: { name: 'ape-permission', version: '1' },
77
+ },
78
+ });
79
+ if (method === 'tools/list')
80
+ return send({ jsonrpc: '2.0', id, result: { tools: [TOOL] } });
81
+ if (method === 'tools/call' && params.name === 'ask')
82
+ return void call(id, params);
83
+ // Anything else asked (a ping, an empty list) gets an empty answer, as the spike proved.
84
+ if (id !== undefined)
85
+ send({ jsonrpc: '2.0', id, result: {} });
86
+ });
@@ -5,28 +5,27 @@ export declare const codingCommands: (change: string) => string[];
5
5
  export declare function claudeRules(work?: Chat['work'], folder?: string): string[];
6
6
  export declare const inTree: (work: Chat['work']) => boolean;
7
7
  export declare const isPlanning: (work: Chat['work']) => work is "loop" | "planning";
8
+ export declare const COMMAND_PATHS: string[];
9
+ export declare const CHAT_PATH = ".ape/chats";
10
+ export declare const COMMENT_PATH = ".ape/comments";
11
+ export declare const APPROVAL_PATH = "prototype/versions";
8
12
  export declare const turnWriteDenials: (work: Chat['work']) => string[];
9
13
  export declare const holdFiles: string[];
14
+ export declare const LEVEL_PATHS: string[];
10
15
  /** Studio's coding commands cannot write into the folders guarded by the file tools. */
11
16
  export declare function codingWriteDenied(path: string): boolean;
12
17
  export declare const PLANNING_SETTINGS = "{\"disableAllHooks\":true}";
13
- export declare function claudeDenied(work?: Chat['work']): string[];
14
- /** JSON's string escaping is also valid for TOML basic keys, including quotes and backslashes. */
15
- export declare function codexTrust(folder: string): string;
18
+ /**
19
+ * A turn's edit denies. Planning below Autopilot may edit only plan/, so its own list is enough;
20
+ * planning on Autopilot (`open`) may edit anywhere, so it also keeps the chats, the commands'
21
+ * files and hooks (`.claude/**`, `.githooks/**`, `package.json` and the rest) as design turns do.
22
+ */
23
+ export declare function claudeDenied(work?: Chat['work'], open?: boolean): string[];
16
24
  /** Exact code-owned arguments only: never admit arbitrary path or permission text to cmd. */
17
25
  export declare function claudeLinked(product: string): {
18
26
  allowed: string[];
19
27
  denied: string[];
20
28
  };
21
- /** Share a scan between argument construction and shim validation, only for this launch. */
22
- export declare function withLinkedPermissions<T>(launch: () => T): T;
23
- /**
24
- * Every turn denies comments and the approval record; design and validation, which write the
25
- * product folder, also the change trees (planning writes plan/ only). Codex takes absolute
26
- * paths only (0.166 rejects read globs), so a nested product's prototype/versions is not
27
- * named here; Claude's rule covers it. Design/validation expand read paths.
28
- */
29
- export declare function codexFilesystem(work: Chat['work'], folder: string, product?: string, examples?: string): string[];
30
29
  /** Only these code-owned values can be quoted when launching a Windows CLI shim. */
31
30
  export declare const SHIM_PERMISSION_ARGS: Set<string>;
32
31
  /** A launch gets its own exact allow set; no linked rule survives unlinking. */