@buffcore/cli 0.8.43 → 0.8.44

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 (49) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/commands/ui/chat/approval-folders.d.ts +20 -0
  3. package/dist/commands/ui/chat/approval-folders.js +134 -0
  4. package/dist/commands/ui/chat/approval-text.d.ts +11 -0
  5. package/dist/commands/ui/chat/approval-text.js +69 -0
  6. package/dist/commands/ui/chat/approval-writes.d.ts +32 -0
  7. package/dist/commands/ui/chat/approval-writes.js +179 -0
  8. package/dist/commands/ui/chat/claude-permissions.d.ts +4 -4
  9. package/dist/commands/ui/chat/claude-permissions.js +32 -4
  10. package/dist/commands/ui/chat/codex-idle.d.ts +1 -1
  11. package/dist/commands/ui/chat/commit-limits.d.ts +36 -0
  12. package/dist/commands/ui/chat/commit-limits.js +164 -0
  13. package/dist/commands/ui/chat/fresh-critique.js +3 -1
  14. package/dist/commands/ui/chat/fresh-launch.d.ts +5 -0
  15. package/dist/commands/ui/chat/fresh-launch.js +7 -4
  16. package/dist/commands/ui/chat/fresh.js +7 -1
  17. package/dist/commands/ui/chat/gh-api-limits.d.ts +14 -0
  18. package/dist/commands/ui/chat/gh-api-limits.js +74 -0
  19. package/dist/commands/ui/chat/git-words.d.ts +10 -0
  20. package/dist/commands/ui/chat/git-words.js +26 -0
  21. package/dist/commands/ui/chat/host-launched.d.ts +11 -0
  22. package/dist/commands/ui/chat/host-launched.js +35 -0
  23. package/dist/commands/ui/chat/limit-mentions.js +16 -2
  24. package/dist/commands/ui/chat/limit-text.d.ts +15 -0
  25. package/dist/commands/ui/chat/limit-text.js +36 -0
  26. package/dist/commands/ui/chat/limits-hook.js +2 -2
  27. package/dist/commands/ui/chat/limits.d.ts +7 -12
  28. package/dist/commands/ui/chat/limits.en.d.ts +2 -0
  29. package/dist/commands/ui/chat/limits.en.js +2 -0
  30. package/dist/commands/ui/chat/limits.es.js +2 -0
  31. package/dist/commands/ui/chat/limits.js +63 -59
  32. package/dist/commands/ui/chat/planning-limits.js +11 -0
  33. package/dist/commands/ui/chat/publish-limits.js +23 -7
  34. package/dist/commands/ui/chat/turn-guard.d.ts +8 -2
  35. package/dist/commands/ui/chat/turn-guard.js +8 -3
  36. package/dist/commands/ui/index.d.ts +42 -0
  37. package/dist/commands/ui/index.js +14 -2
  38. package/dist/commands/ui/routes.d.ts +2 -0
  39. package/dist/commands/ui/server-options.js +1 -0
  40. package/dist/commands/ui/server-request.js +5 -0
  41. package/dist/commands/ui/server.d.ts +7 -0
  42. package/dist/commands/ui/server.js +3 -0
  43. package/dist/commands/ui/studio-routes.d.ts +1 -0
  44. package/dist/commands/ui/studio-routes.js +3 -1
  45. package/dist/commands/ui/studio-state.d.ts +1 -0
  46. package/dist/ui/page.js +78 -69
  47. package/docs/PROTOTYPE.md +11 -0
  48. package/docs/WORKBENCH.md +11 -2
  49. package/package.json +11 -11
@@ -1,20 +1,27 @@
1
1
  /**
2
2
  * The limits every turn keeps at every level, "Never ask" included: no reading folders of sign-ins
3
3
  * or keys, no deploy, no production settings, no `git push`, and no network download without a
4
- * person's click, and no publishing a package or a release. The studio's hook (limits-hook.ts) runs this before each tool call; the
5
- * permission mode never decides them. Plain Node only: the hook runs it without the CLI.
4
+ * person's click, no publishing a package or a release, and no shell write into the approval
5
+ * records (`prototype/versions/`); a design turn on Autopilot makes no commit either. The
6
+ * studio's hook (limits-hook.ts) runs this before each tool call; the permission mode never
7
+ * decides them. Plain Node only: the hook runs it without the CLI.
6
8
  */
7
9
  import { relative, resolve } from 'node:path';
10
+ import { folderWrite } from './approval-folders.js';
11
+ import { approvalText } from './approval-text.js';
12
+ import { approvalWrite } from './approval-writes.js';
8
13
  import { commandParts, ESCAPE, partWords, programName, } from './command-parts.js';
9
14
  import { EXPRESSIONS, wrappedScripts } from './command-wrappers.js';
15
+ import { commitText, commitWords, designAutopilot, designWork, } from './commit-limits.js';
10
16
  import { designDelete } from './design-deletes.js';
17
+ import { subcommand, subcommandAt } from './git-words.js';
11
18
  import { mentionedLimit } from './limit-mentions.js';
12
19
  import { patternReach } from './limit-patterns.js';
13
- import { en } from './limits.en.js';
14
- import { es } from './limits.es.js';
20
+ import { limitReason, limitText } from './limit-text.js';
15
21
  import { publishLimit } from './publish-limits.js';
16
22
  import { holdsSecrets } from './secret-folders.js';
17
23
  import { readsStdin } from './stdin-shells.js';
24
+ export { limitReason, limitText, refusalLimit } from './limit-text.js';
18
25
  const SHELLS = new Map([
19
26
  ['Bash', 'bash'],
20
27
  ['PowerShell', 'powershell'],
@@ -52,28 +59,6 @@ export function secretPath(path, cwd) {
52
59
  }
53
60
  /** A word worth reading as a path: it has a separator, or starts like a hidden or home folder. */
54
61
  const pathLike = (word) => /[\\/]/.test(word) || /^[.~]/.test(word);
55
- // Git's options before the subcommand that take the next word as their value.
56
- const VALUED = new Set([
57
- '-C',
58
- '-c',
59
- '--git-dir',
60
- '--work-tree',
61
- '--namespace',
62
- '--super-prefix',
63
- '--config-env',
64
- '--attr-source',
65
- ]);
66
- /** The first word after `from` that is not an option (or an option's value), and its index. */
67
- function subcommandAt(words, from) {
68
- for (let index = from; index < words.length; index++) {
69
- const word = words[index];
70
- if (VALUED.has(word))
71
- index++;
72
- else if (!word.startsWith('-'))
73
- return { name: word.toLowerCase(), at: index };
74
- }
75
- }
76
- const subcommand = (words, from) => subcommandAt(words, from)?.name;
77
62
  /** A commit's or tag's message is words, not a command or a path: `git commit -m "…"`. */
78
63
  function withoutMessages(words) {
79
64
  const git = words.findIndex((word) => programName(word) === 'git');
@@ -83,7 +68,7 @@ function withoutMessages(words) {
83
68
  const at = sub.at;
84
69
  return words.filter((_, index) => index <= at || !/^(?:-[A-Za-z]*m|--message)$/.test(words[index - 1] ?? ''));
85
70
  }
86
- function wordsLimit(words, cwd) {
71
+ function wordsLimit(words, cwd, turn) {
87
72
  const names = words.map(programName);
88
73
  const checked = withoutMessages(words);
89
74
  if (checked.some((word) => pathLike(word) && secretPath(word, cwd)))
@@ -93,7 +78,9 @@ function wordsLimit(words, cwd) {
93
78
  const git = names.indexOf('git');
94
79
  // `git send-pack` is the plumbing under `git push`.
95
80
  const sub = git >= 0 ? subcommand(words, git + 1) : undefined;
96
- if (sub === 'push' || sub === 'send-pack')
81
+ // `git subtree push` pushes too.
82
+ const subtreePush = sub === 'subtree' && subcommand(words, words.indexOf('subtree', git) + 1) === 'push';
83
+ if (sub === 'push' || sub === 'send-pack' || subtreePush)
97
84
  return { decision: 'deny', kind: 'push' };
98
85
  const ape = names.indexOf('ape');
99
86
  if (ape >= 0) {
@@ -105,6 +92,10 @@ function wordsLimit(words, cwd) {
105
92
  const published = publishLimit(checked);
106
93
  if (published)
107
94
  return { decision: 'deny', kind: published };
95
+ if (approvalWrite(checked, cwd) || (designWork(turn) && folderWrite(checked, cwd)))
96
+ return { decision: 'deny', kind: 'approval' };
97
+ if (designAutopilot(turn) && commitWords(words))
98
+ return { decision: 'deny', kind: 'commit' };
108
99
  if (checked.some((word) => DOWNLOADS.test(word)))
109
100
  return { decision: 'ask', kind: 'download' };
110
101
  // `certutil -urlcache` fetches a URL; its other uses read local files.
@@ -118,7 +109,7 @@ function wordsLimit(words, cwd) {
118
109
  function partLimits(part, check, shell, depth) {
119
110
  const raw = partWords(part);
120
111
  const plain = partWords(part, ESCAPE[shell]);
121
- const own = wordsLimit(raw, check.cwd) ?? wordsLimit(plain, check.cwd);
112
+ const own = wordsLimit(raw, check.cwd, check.turn) ?? wordsLimit(plain, check.cwd, check.turn);
122
113
  if (readsStdin(plain))
123
114
  check.unsure ??= 'stdin';
124
115
  if (plain.some((word) => EXPRESSIONS.has(programName(word))))
@@ -132,7 +123,14 @@ function partLimits(part, check, shell, depth) {
132
123
  if (check.seen.has(key))
133
124
  return [];
134
125
  check.seen.add(key);
135
- return commandLimits(script, check, inside, depth + 1);
126
+ // A handed-on script's text is read too: an encoded one never showed it in the command.
127
+ const text = fallback(script, inside, check.cwd, check.turn);
128
+ if (text?.decision === 'deny')
129
+ return [{ ...text, part }];
130
+ return [
131
+ ...(text ? [{ ...text, part }] : []),
132
+ ...commandLimits(script, check, inside, depth + 1),
133
+ ];
136
134
  });
137
135
  return [...(own ? [{ ...own, part }] : []), ...inner];
138
136
  }
@@ -143,16 +141,40 @@ function commandLimits(command, check, shell, depth = 0) {
143
141
  }
144
142
  return commandParts(command, shell, check).flatMap((part) => partLimits(part, check, shell, depth));
145
143
  }
144
+ /**
145
+ * The text fallbacks for a write into the approval records (refused, or asked when every part
146
+ * only reads) and a design turn's commit on Autopilot (asked).
147
+ */
148
+ function fallback(command, shell, cwd, turn) {
149
+ const ask = (mention) => ({
150
+ decision: 'ask',
151
+ kind: 'unsure',
152
+ part: command,
153
+ unsure: 'mention',
154
+ mention,
155
+ });
156
+ const approval = approvalText(command, shell, cwd, designWork(turn));
157
+ if (approval === 'deny')
158
+ return { decision: 'deny', kind: 'approval', part: command };
159
+ if (approval)
160
+ return ask('prototype/versions');
161
+ const commit = designAutopilot(turn) ? commitText(command, shell) : undefined;
162
+ if (commit === 'deny')
163
+ return { decision: 'deny', kind: 'commit', part: command };
164
+ if (commit)
165
+ return ask('git commit');
166
+ }
146
167
  /**
147
168
  * A shell command's first limit: what the parse refuses, then what it asks; when it found
148
169
  * neither, a reading it could not follow, or a limit the text still mentions, asks the person.
149
170
  */
150
- function shellLimit(command, cwd, shell) {
151
- const check = { cwd, steps: 0, until: Date.now() + TIME_CAP, seen: new Set() };
171
+ function shellLimit(command, cwd, shell, turn) {
172
+ const check = { cwd, turn, steps: 0, until: Date.now() + TIME_CAP, seen: new Set() };
152
173
  if (command.length > TEXT_CAP)
153
174
  check.unsure = 'budget';
154
175
  else {
155
- const limits = commandLimits(command, check, shell);
176
+ const text = fallback(command, shell, cwd, turn);
177
+ const limits = [...commandLimits(command, check, shell), ...(text ? [text] : [])];
156
178
  const found = limits.find((limit) => limit.decision === 'deny') ?? limits[0];
157
179
  if (found)
158
180
  return found;
@@ -171,12 +193,15 @@ function shellLimit(command, cwd, shell) {
171
193
  ...(mention ? { mention } : {}),
172
194
  };
173
195
  }
174
- /** The first limit a tool call crosses, refusals before asks; nothing when it crosses none. */
175
- export function crossedLimit(tool, input, cwd) {
196
+ /**
197
+ * The first limit a tool call crosses, refusals before asks; nothing when it crosses none. The
198
+ * turn, when known, adds the limits only some turns keep (a design turn's commit on Autopilot).
199
+ */
200
+ export function crossedLimit(tool, input, cwd, turn) {
176
201
  const fields = (input ?? {});
177
202
  const shell = SHELLS.get(tool);
178
203
  if (shell) {
179
- return shellLimit(typeof fields.command === 'string' ? fields.command : '', cwd, shell);
204
+ return shellLimit(typeof fields.command === 'string' ? fields.command : '', cwd, shell, turn);
180
205
  }
181
206
  for (const field of fileFields(tool)) {
182
207
  const value = fields[field];
@@ -190,33 +215,12 @@ export function crossedLimit(tool, input, cwd) {
190
215
  if (tool === 'WebFetch' && typeof fields.url === 'string')
191
216
  return { decision: 'ask', kind: 'download', part: fields.url };
192
217
  }
193
- const catalogs = { en, es };
194
- const REFUSED = ['secrets', 'deploy', 'push', 'settings', 'publish', 'release'];
195
- /**
196
- * The limit a refused call's result names: the hook's own sentence for it, in either language,
197
- * came back as the result. Nothing when it names none.
198
- */
199
- export function refusalLimit(text) {
200
- return REFUSED.find((kind) => Object.values(catalogs).some((words) => text.includes(words[`limits.${kind}`].replace('`{part}`', ''))));
201
- }
202
- /** The agent's words in the turn's language (LANG), with `{name}` values filled in. */
203
- export function limitText(key, values = {}) {
204
- const locale = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || 'en')
205
- .slice(0, 2)
206
- .toLowerCase();
207
- const words = catalogs[locale === 'es' ? 'es' : 'en'];
208
- return words[key].replace(/\{(\w+)\}/g, (_, name) => values[name] ?? '');
209
- }
210
- /** The sentence the agent reads for a crossed limit: it names the refused part. */
211
- export const limitReason = (limit) => limit.kind === 'unsure'
212
- ? limitText(`limits.unsure.${limit.unsure ?? 'mention'}`, { mention: limit.mention ?? '' })
213
- : limitText(`limits.${limit.kind}`, { part: limit.part.slice(0, 200) });
214
218
  /**
215
219
  * The hook's answer to one call: a crossed limit, a design turn's delete inside `design/` or
216
220
  * `prototype/` (allowed), or nothing. A call it cannot read is refused, so a broken call never
217
221
  * slips past the limits.
218
222
  */
219
- export function hookAnswer(text, work) {
223
+ export function hookAnswer(text, work, level = '') {
220
224
  let call;
221
225
  try {
222
226
  call = JSON.parse(text);
@@ -226,7 +230,7 @@ export function hookAnswer(text, work) {
226
230
  }
227
231
  const tool = typeof call.tool_name === 'string' ? call.tool_name : '';
228
232
  const cwd = typeof call.cwd === 'string' && call.cwd ? call.cwd : process.cwd();
229
- const limit = crossedLimit(tool, call.tool_input, cwd);
233
+ const limit = crossedLimit(tool, call.tool_input, cwd, { work, level });
230
234
  if (limit)
231
235
  return { decision: limit.decision, reason: limitReason(limit) };
232
236
  const command = call.tool_input?.command;
@@ -24,6 +24,17 @@ export const LIMIT_COMMANDS = [
24
24
  'pnpm publish',
25
25
  'yarn publish',
26
26
  'yarn npm publish',
27
+ 'bun publish',
28
+ 'lerna publish',
29
+ 'changeset publish',
30
+ 'npx lerna publish',
31
+ 'npx changeset publish',
32
+ 'pnpm lerna publish',
33
+ 'pnpm changeset publish',
34
+ 'pnpm exec lerna publish',
35
+ 'pnpm exec changeset publish',
36
+ 'yarn lerna publish',
37
+ 'yarn changeset publish',
27
38
  'gh release create',
28
39
  'gh release new',
29
40
  'gh release upload',
@@ -1,15 +1,17 @@
1
1
  /**
2
2
  * The publishing commands the limits refuse: a package (`npm publish`, and npm's shortened names
3
- * down to `npm pu`; `pnpm publish`, `yarn publish`, `yarn npm publish`) and a release
4
- * (`gh release create|new|upload|edit|delete`, and `delete-asset`). Every package manager or `gh`
5
- * named in a part is read, so `npx npm publish`, `pnpm exec npm publish` and `env X=1 npm publish`
6
- * count too. Before the subcommand, the options each tool takes a value for skip that value
3
+ * down to `npm pu`; `pnpm publish`, `yarn publish`, `yarn npm publish`, `bun publish`,
4
+ * `lerna publish`, `changeset publish`) and a release (`gh release create|new|upload|edit|delete`,
5
+ * and `delete-asset`; `gh api` calls that create or change one, gh-api-limits.ts). Every package
6
+ * manager or `gh` named in a part is read, so `npx npm publish`, `pnpm exec changeset publish` and
7
+ * `env X=1 npm publish` count too. Before the subcommand, the options each tool takes a value for skip that value
7
8
  * (`npm --registry x publish`, `gh -R owner/repo release create`); after any other option the next
8
9
  * word is the subcommand, so `pnpm --filter publish build` runs (a shape the parse does not follow
9
10
  * still goes to the card through the text fallback). Asking only for help (`pnpm publish --help`)
10
11
  * runs. Plain Node only: the hook runs it.
11
12
  */
12
13
  import { programName } from './command-parts.js';
14
+ import { GH_API_VALUED, releaseCall } from './gh-api-limits.js';
13
15
  /** The options before the subcommand that take the next word as their value, per tool. */
14
16
  const VALUED = {
15
17
  npm: new Set([
@@ -47,11 +49,14 @@ const VALUED = {
47
49
  '--publish-branch',
48
50
  ]),
49
51
  yarn: new Set(['--cwd', '--registry', '--otp', '--tag', '--access', '--modules-folder']),
52
+ bun: new Set(['--cwd', '--registry', '--otp', '--tag', '--access', '--config', '-c']),
53
+ lerna: new Set(['--loglevel', '--concurrency']),
54
+ changeset: new Set(['--cwd']),
50
55
  gh: new Set(['-R', '--repo', '--hostname']),
51
56
  };
52
57
  /** Every option above, for the text fallback: their values are values, not a subcommand. */
53
58
  export const VALUED_OPTIONS = [
54
- ...new Set(Object.values(VALUED).flatMap((options) => [...options])),
59
+ ...new Set([...Object.values(VALUED).flatMap((options) => [...options]), ...GH_API_VALUED]),
55
60
  ];
56
61
  const RELEASE = new Set(['create', 'new', 'upload', 'edit', 'delete', 'delete-asset']);
57
62
  /** npm resolves a shortened command name: from `pu`, the only name it can mean is `publish`. */
@@ -59,10 +64,18 @@ const PUBLISHES = {
59
64
  npm: (word) => word.length >= 2 && 'publish'.startsWith(word),
60
65
  pnpm: (word) => word === 'publish',
61
66
  yarn: (word) => word === 'publish',
67
+ bun: (word) => word === 'publish',
68
+ lerna: (word) => word === 'publish',
69
+ changeset: (word) => word === 'publish',
62
70
  };
63
71
  const HELP = new Set(['--help', '-h']);
64
- /** The program a word names, without a pinned version (`npm@10`, `pnpm@latest`). */
65
- const toolName = (word) => programName(word).replace(/(?<=.)@[^@]*$/, '');
72
+ /**
73
+ * The program a word names, without a pinned version (`npm@10`, `pnpm@latest`); the changesets
74
+ * package run by its name (`npx @changesets/cli publish`) is its `changeset` command.
75
+ */
76
+ const toolName = (word) => /^@changesets\/cli(?:@[^@]*)?$/i.test(word)
77
+ ? 'changeset'
78
+ : programName(word).replace(/(?<=.)@[^@]*$/, '');
66
79
  /** The index of the subcommand after `from` when `wanted` accepts it; -1 otherwise. */
67
80
  function subcommandIs(words, from, valued, wanted) {
68
81
  for (let index = from; index < words.length; index++) {
@@ -89,6 +102,9 @@ export function publishLimit(words) {
89
102
  if (name !== 'gh')
90
103
  continue;
91
104
  const valued = VALUED.gh;
105
+ const api = subcommandIs(words, index + 1, valued, (word) => word === 'api');
106
+ if (api >= 0 && releaseCall(words, api + 1))
107
+ return 'release';
92
108
  const release = subcommandIs(words, index + 1, valued, (word) => word === 'release');
93
109
  const at = release < 0 ? -1 : subcommandIs(words, release + 1, valued, (w) => RELEASE.has(w));
94
110
  if (at >= 0 && !helpOnly(words, at))
@@ -4,8 +4,13 @@ import type { Active } from './turn-state.ts';
4
4
  export interface TurnGuard {
5
5
  level: Level;
6
6
  neverAsk: boolean;
7
- /** Settings with the limits hook; absent on planning below Autopilot, which disables every hook. */
7
+ /**
8
+ * Settings with the limits hook; absent on planning below Autopilot, which disables every hook,
9
+ * and when the host's launcher starts the turn (host-launched.ts): the host applies the limits.
10
+ */
8
11
  settings?: string;
12
+ /** The host's launcher starts this turn: no settings, MCP config or prompt tool, ever. */
13
+ host?: boolean;
9
14
  /** The MCP config that serves the permission prompt tool; absent where `settings` is. */
10
15
  mcp?: string;
11
16
  /** The rules this launch passed to `--allowedTools`, filled by the arguments. */
@@ -22,6 +27,7 @@ export declare function launchArguments(args: readonly string[]): () => void;
22
27
  * Opens a Claude launch's guard: the level and "Never ask" read now, and the limits hook in a
23
28
  * settings file and the permission tool's channel, in a folder of the launch's own that closes
24
29
  * with it. The hook runs before every call at every level, Never ask included; only planning below
25
- * Autopilot, which runs `dontAsk` with every hook off, gets neither (deny rules hold its limits).
30
+ * Autopilot, which runs `dontAsk` with every hook off, gets neither (deny rules hold its limits),
31
+ * and no turn of a product whose host launches its turns, as in 0.8.41 (the host applies them).
26
32
  */
27
33
  export declare function openTurnGuard(run: Active, root: string, save: () => void): TurnGuard;
@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os';
3
3
  import { join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { effectiveLevel, effectiveNeverAsk } from '../../agents-file.js';
6
+ import { hostLaunched } from './host-launched.js';
6
7
  import { askPerson } from './permission-ask.js';
7
8
  import { openPermissionChannel } from './permission-channel.js';
8
9
  import { isPlanning } from './permissions.js';
@@ -30,7 +31,8 @@ const script = (name) => {
30
31
  * Opens a Claude launch's guard: the level and "Never ask" read now, and the limits hook in a
31
32
  * settings file and the permission tool's channel, in a folder of the launch's own that closes
32
33
  * with it. The hook runs before every call at every level, Never ask included; only planning below
33
- * Autopilot, which runs `dontAsk` with every hook off, gets neither (deny rules hold its limits).
34
+ * Autopilot, which runs `dontAsk` with every hook off, gets neither (deny rules hold its limits),
35
+ * and no turn of a product whose host launches its turns, as in 0.8.41 (the host applies them).
34
36
  */
35
37
  export function openTurnGuard(run, root, save) {
36
38
  const guard = {
@@ -41,7 +43,9 @@ export function openTurnGuard(run, root, save) {
41
43
  close: () => { },
42
44
  };
43
45
  live.add(guard);
44
- if (isPlanning(run.chat.work) && guard.level !== 'auto') {
46
+ if (hostLaunched(root))
47
+ guard.host = true;
48
+ if (guard.host || (isPlanning(run.chat.work) && guard.level !== 'auto')) {
45
49
  guard.close = () => live.delete(guard);
46
50
  return guard;
47
51
  }
@@ -64,7 +68,8 @@ export function openTurnGuard(run, root, save) {
64
68
  const channel = openPermissionChannel((call) => askPerson(turn, call, closed.signal));
65
69
  guard.settings = join(folder, 'settings.json');
66
70
  guard.mcp = join(folder, 'mcp.json');
67
- const command = `"${node}" "${hook}" ${run.chat.work}`;
71
+ // The work and the level are code-owned words: the hook holds some limits only on some turns.
72
+ const command = `"${node}" "${hook}" ${run.chat.work} ${guard.level}`;
68
73
  writeFileSync(guard.settings, JSON.stringify({
69
74
  // Flag settings outrank the product's own, so a product file cannot switch the hook off.
70
75
  disableAllHooks: false,
@@ -5,6 +5,48 @@ export interface UiOptions {
5
5
  studio?: boolean;
6
6
  lang?: string;
7
7
  }
8
+ /**
9
+ * The environment `ape ui` was started with, copied before the product's `.env` is loaded (it is
10
+ * what agent turns get), then the product's settings. Only that copy can turn on the host-launched
11
+ * mode: a value an agent writes into the product's `.env` never counts.
12
+ */
13
+ export declare function uiEnvironment(root: string): {
14
+ agentEnvironment: {
15
+ [key: string]: string | undefined;
16
+ };
17
+ env: {
18
+ APE_ENV: "development" | "production" | "staging" | "test";
19
+ APE_RELEASE: string;
20
+ APE_LOG_LEVEL: "debug" | "error" | "fatal" | "info" | "trace" | "warn";
21
+ DATABASE_URL: string;
22
+ REDIS_URL: string;
23
+ APE_REDIS_PREFIX?: string | undefined;
24
+ APE_API_PORT: number;
25
+ APE_API_URL: string;
26
+ APE_WORKER_CONCURRENCY: number;
27
+ APE_ADMIN_URL: string;
28
+ APE_APP_URL: string;
29
+ APE_HOST: string;
30
+ APE_AUTH_SECRET: string;
31
+ APE_ENCRYPTION_KEY: string;
32
+ APE_S3_ENDPOINT?: string | undefined;
33
+ APE_S3_REGION: string;
34
+ APE_S3_BUCKET: string;
35
+ APE_S3_ACCESS_KEY?: string | undefined;
36
+ APE_S3_SECRET_KEY?: string | undefined;
37
+ APE_AI_MODE: "fixture" | "live" | "record";
38
+ APE_ALLOW_LIVE_AI: boolean;
39
+ ANTHROPIC_API_KEY?: string | undefined;
40
+ OPENAI_API_KEY?: string | undefined;
41
+ GOOGLE_VERTEX_API_KEY?: string | undefined;
42
+ GOOGLE_VERTEX_PROJECT?: string | undefined;
43
+ GOOGLE_VERTEX_LOCATION: string;
44
+ APE_BACKUP_KEY?: string | undefined;
45
+ TURNSTILE_SITE_KEY?: string | undefined;
46
+ TURNSTILE_SECRET_KEY?: string | undefined;
47
+ };
48
+ hostLaunched: boolean;
49
+ };
8
50
  export declare function ui(options: UiOptions): Promise<void>;
9
51
  /** `ape ui [--port <n>] [--no-open] [--lang <en|es>]` on the CLI's program. */
10
52
  export declare function addUiCommand(program: Command): void;
@@ -7,6 +7,7 @@ import { InvalidArgumentError } from 'commander';
7
7
  import { findRoot, loadEnv, loadProduct } from '../../project.js';
8
8
  import { FreshLooks } from './chat/fresh.js';
9
9
  import { freshRoutes } from './chat/fresh-routes.js';
10
+ import { hostLaunchedEnv } from './chat/host-launched.js';
10
11
  import { TurnMigrations } from './chat/migration-turn.js';
11
12
  import { agentStart } from './chat/process.js';
12
13
  import { chatRoutes } from './chat/routes.js';
@@ -43,13 +44,22 @@ function openBrowser(url) {
43
44
  .on('error', () => { })
44
45
  .unref();
45
46
  }
47
+ /**
48
+ * The environment `ape ui` was started with, copied before the product's `.env` is loaded (it is
49
+ * what agent turns get), then the product's settings. Only that copy can turn on the host-launched
50
+ * mode: a value an agent writes into the product's `.env` never counts.
51
+ */
52
+ export function uiEnvironment(root) {
53
+ const agentEnvironment = { ...process.env };
54
+ const env = loadEnv(root);
55
+ return { agentEnvironment, env, hostLaunched: hostLaunchedEnv(agentEnvironment) };
56
+ }
46
57
  export async function ui(options) {
47
58
  const locale = options.lang === undefined ? undefined : uiLocale(options.lang);
48
59
  if (options.studio)
49
60
  console.log(t('ui.studio.noop', undefined, locale));
50
61
  const root = findRoot();
51
- const agentEnvironment = { ...process.env };
52
- const env = loadEnv(root);
62
+ const { agentEnvironment, env, hostLaunched } = uiEnvironment(root);
53
63
  const { name } = await loadProduct(root);
54
64
  const port = options.port ? Number(options.port) : defaultStudioPort(env.APE_API_PORT);
55
65
  const token = newToken();
@@ -72,6 +82,8 @@ export async function ui(options) {
72
82
  const server = createUiServer({
73
83
  turnMigrations: migrations,
74
84
  contained: false,
85
+ // A host that starts `ape ui` under its own trusted launcher sets APE_HOST_LAUNCHED=1.
86
+ hostLaunched,
75
87
  token,
76
88
  code,
77
89
  product: name,
@@ -18,6 +18,8 @@ export interface UiRequest extends MergeConfiguration, SaveConfiguration, Outsid
18
18
  readonly stop?: AbortSignal;
19
19
  /** Supplied only by createUiServer, never by the request body or product. */
20
20
  readonly contained?: boolean;
21
+ /** The host's launcher starts the turns; supplied only by createUiServer. */
22
+ readonly hostLaunched?: boolean;
21
23
  req: IncomingMessage;
22
24
  /**
23
25
  * The path's `:name` segments, decoded: one may hold a `/` (from `%2F`), so a handler checks it
@@ -20,6 +20,7 @@ export function checkedUiOptions(input) {
20
20
  return {
21
21
  ...input,
22
22
  contained: input.contained === true,
23
+ hostLaunched: input.hostLaunched === true,
23
24
  hostParts: checkedHostParts(input.hostParts, signedIn),
24
25
  outside: checkedOutside(input.outside, signedIn),
25
26
  theme: checkedTheme(input.theme),
@@ -1,3 +1,4 @@
1
+ import { hostLaunched as isHostLaunched } from './chat/host-launched.js';
1
2
  import { localStudioOrigin } from './prototype-origin.js';
2
3
  import { bodyOf } from './routes.js';
3
4
  /** Local pages and coding turns use the bound address, including when port 0 was requested. */
@@ -16,11 +17,15 @@ export function requestContext(options, req, params, identity, shutdown) {
16
17
  let body;
17
18
  const disconnected = new AbortController();
18
19
  req.once('aborted', () => disconnected.abort());
20
+ // A host may pass a runner without a folder (or none): no folder is in the mode then.
21
+ const folder = options.runner?.cwd;
19
22
  return {
20
23
  req,
21
24
  identity,
22
25
  hosted: Boolean(options.signIn),
23
26
  contained: options.contained === true,
27
+ // On only while this server's product folder is in the mode (an empty runner folder never is).
28
+ hostLaunched: folder ? isHostLaunched(folder) : false,
24
29
  ...(options.approval ? { approval: options.approval } : {}),
25
30
  ...(options.level?.where.trim() ? { level: options.level } : {}),
26
31
  save: options.save,
@@ -60,6 +60,13 @@ export interface UiServerOptions extends SaveConfiguration, OutsideConfiguration
60
60
  mergeTimeoutMs?: number;
61
61
  /** Host-owned isolation boundary; never inferred from product inputs. */
62
62
  contained?: boolean;
63
+ /**
64
+ * The host's own trusted launcher starts the agent's turns: they launch as in 0.8.41, with no
65
+ * per-turn settings, MCP config, permission prompt tool or socket, and the host applies the
66
+ * limits (chat/host-launched.ts). For the product folder of `runner.cwd`, which it needs; one
67
+ * mode per folder, so the last server created for a folder decides it. Off by default.
68
+ */
69
+ hostLaunched?: boolean;
63
70
  product: string;
64
71
  script: () => Promise<string>;
65
72
  stack: Stack;
@@ -3,6 +3,7 @@ import { createServer } from 'node:http';
3
3
  import { workbenchApi } from '@buffcore/contracts/workbench';
4
4
  import { migrationRoute } from '../migrate-create-protocol.js';
5
5
  import { MilestoneVersionsPending } from '../prototype/milestone-key.js';
6
+ import { registerHostLaunched } from './chat/host-launched.js';
6
7
  import { scrubLaunchIds } from './chat/launch-ids.js';
7
8
  import { exchangeCode } from './code.js';
8
9
  import { studioFont } from './fonts.js';
@@ -72,8 +73,10 @@ export function createUiServer(input) {
72
73
  };
73
74
  if (key)
74
75
  snapshotRunners.set(key, options.runner);
76
+ const launcher = key ? registerHostLaunched(key, options.hostLaunched === true) : () => { };
75
77
  server.once('close', () => {
76
78
  shutdown.abort();
79
+ launcher();
77
80
  if (key && snapshotRunners.get(key) === options.runner)
78
81
  snapshotRunners.delete(key);
79
82
  });
@@ -4,6 +4,7 @@ export declare const studioAccess: {
4
4
  viewer: true;
5
5
  machine: true;
6
6
  contained: true;
7
+ hostLaunched: true;
7
8
  product: true;
8
9
  appUrl: true;
9
10
  plan: true;
@@ -22,6 +22,7 @@ export const studioAccess = {
22
22
  viewer: true,
23
23
  machine: true,
24
24
  contained: true,
25
+ hostLaunched: true,
25
26
  product: true,
26
27
  appUrl: true,
27
28
  plan: true,
@@ -93,7 +94,7 @@ cached = false) {
93
94
  path: '/api/studio',
94
95
  readable: true,
95
96
  handle: async (request) => {
96
- const { identity, hosted, approval, level, contained = false } = request;
97
+ const { identity, hosted, approval, level, contained = false, hostLaunched } = request;
97
98
  const current = await merged(await state({ identity, hosted, approval, level }), request);
98
99
  const context = authorityFor({ identity, approval });
99
100
  const checked = context
@@ -107,6 +108,7 @@ cached = false) {
107
108
  viewer: identity?.viewer,
108
109
  machine: identity?.machine,
109
110
  contained,
111
+ hostLaunched: hostLaunched === true,
110
112
  level,
111
113
  outside: outsideState(request.outside),
112
114
  }, identity?.viewer, studioAccess),
@@ -11,6 +11,7 @@ export declare function prototypeChange(root: string, context?: ApprovalContext)
11
11
  */
12
12
  export declare function studioState(root: string, options: Pick<UiServerOptions, 'product' | 'stack' | 'runner' | 'plan'>, detect?: () => Promise<FoundAgent[]>, held?: (id: string) => boolean, cached?: boolean): (request?: Request) => Promise<{
13
13
  contained?: boolean | undefined;
14
+ hostLaunched?: boolean | undefined;
14
15
  viewer?: {
15
16
  name: string;
16
17
  email?: string | undefined;