@buffcore/cli 0.8.42 → 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 (119) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/commands/design/references.d.ts +9 -0
  3. package/dist/commands/design/references.js +20 -1
  4. package/dist/commands/extension/places-approval.d.ts +1 -1
  5. package/dist/commands/prototype/comp-record.d.ts +27 -0
  6. package/dist/commands/prototype/comp-record.js +85 -0
  7. package/dist/commands/prototype/comp-words.d.ts +12 -0
  8. package/dist/commands/prototype/comp-words.js +24 -0
  9. package/dist/commands/prototype/comp.d.ts +26 -0
  10. package/dist/commands/prototype/comp.js +71 -0
  11. package/dist/commands/prototype/milestone-versions.d.ts +1 -1
  12. package/dist/commands/prototype/record-look-child.js +4 -1
  13. package/dist/commands/prototype/snapshot-command.js +1 -1
  14. package/dist/commands/prototype/snapshot-setup.d.ts +11 -0
  15. package/dist/commands/prototype/snapshot-setup.js +29 -5
  16. package/dist/commands/prototype/versions.d.ts +3 -3
  17. package/dist/commands/ui/agents-route.d.ts +2 -0
  18. package/dist/commands/ui/agents-route.js +8 -5
  19. package/dist/commands/ui/approval-authority.d.ts +1 -1
  20. package/dist/commands/ui/approve.js +7 -1
  21. package/dist/commands/ui/chat/approval-folders.d.ts +20 -0
  22. package/dist/commands/ui/chat/approval-folders.js +134 -0
  23. package/dist/commands/ui/chat/approval-text.d.ts +11 -0
  24. package/dist/commands/ui/chat/approval-text.js +69 -0
  25. package/dist/commands/ui/chat/approval-writes.d.ts +32 -0
  26. package/dist/commands/ui/chat/approval-writes.js +179 -0
  27. package/dist/commands/ui/chat/claude-permissions.d.ts +4 -4
  28. package/dist/commands/ui/chat/claude-permissions.js +32 -4
  29. package/dist/commands/ui/chat/codex-idle.d.ts +1 -0
  30. package/dist/commands/ui/chat/commit-limits.d.ts +36 -0
  31. package/dist/commands/ui/chat/commit-limits.js +164 -0
  32. package/dist/commands/ui/chat/fresh-critique.d.ts +28 -0
  33. package/dist/commands/ui/chat/fresh-critique.js +123 -0
  34. package/dist/commands/ui/chat/fresh-launch.d.ts +36 -0
  35. package/dist/commands/ui/chat/fresh-launch.js +125 -0
  36. package/dist/commands/ui/chat/fresh-prompts.d.ts +17 -0
  37. package/dist/commands/ui/chat/fresh-prompts.js +76 -0
  38. package/dist/commands/ui/chat/fresh-report.d.ts +8 -0
  39. package/dist/commands/ui/chat/fresh-report.js +36 -0
  40. package/dist/commands/ui/chat/fresh-routes.d.ts +3 -0
  41. package/dist/commands/ui/chat/fresh-routes.js +64 -0
  42. package/dist/commands/ui/chat/fresh-settings.d.ts +12 -0
  43. package/dist/commands/ui/chat/fresh-settings.js +66 -0
  44. package/dist/commands/ui/chat/fresh-store.d.ts +17 -0
  45. package/dist/commands/ui/chat/fresh-store.js +67 -0
  46. package/dist/commands/ui/chat/fresh.d.ts +31 -0
  47. package/dist/commands/ui/chat/fresh.en.d.ts +7 -0
  48. package/dist/commands/ui/chat/fresh.en.js +7 -0
  49. package/dist/commands/ui/chat/fresh.es.d.ts +7 -0
  50. package/dist/commands/ui/chat/fresh.es.js +7 -0
  51. package/dist/commands/ui/chat/fresh.js +118 -0
  52. package/dist/commands/ui/chat/gh-api-limits.d.ts +14 -0
  53. package/dist/commands/ui/chat/gh-api-limits.js +74 -0
  54. package/dist/commands/ui/chat/git-words.d.ts +10 -0
  55. package/dist/commands/ui/chat/git-words.js +26 -0
  56. package/dist/commands/ui/chat/host-launched.d.ts +11 -0
  57. package/dist/commands/ui/chat/host-launched.js +35 -0
  58. package/dist/commands/ui/chat/limit-mentions.d.ts +2 -2
  59. package/dist/commands/ui/chat/limit-mentions.js +36 -2
  60. package/dist/commands/ui/chat/limit-text.d.ts +15 -0
  61. package/dist/commands/ui/chat/limit-text.js +36 -0
  62. package/dist/commands/ui/chat/limits-hook.js +2 -2
  63. package/dist/commands/ui/chat/limits.d.ts +11 -9
  64. package/dist/commands/ui/chat/limits.en.d.ts +4 -0
  65. package/dist/commands/ui/chat/limits.en.js +4 -0
  66. package/dist/commands/ui/chat/limits.es.js +4 -0
  67. package/dist/commands/ui/chat/limits.js +67 -51
  68. package/dist/commands/ui/chat/parse-claude.js +7 -3
  69. package/dist/commands/ui/chat/permission-ask.js +3 -0
  70. package/dist/commands/ui/chat/planning-limits.js +26 -0
  71. package/dist/commands/ui/chat/publish-limits.d.ts +4 -0
  72. package/dist/commands/ui/chat/publish-limits.js +113 -0
  73. package/dist/commands/ui/chat/recorded-turn.js +3 -0
  74. package/dist/commands/ui/chat/stream.js +4 -1
  75. package/dist/commands/ui/chat/turn-guard.d.ts +10 -2
  76. package/dist/commands/ui/chat/turn-guard.js +20 -3
  77. package/dist/commands/ui/chat/turn-state.d.ts +5 -0
  78. package/dist/commands/ui/chat/turn.js +1 -0
  79. package/dist/commands/ui/comp-approval.d.ts +6 -0
  80. package/dist/commands/ui/comp-approval.js +42 -0
  81. package/dist/commands/ui/host.js +3 -0
  82. package/dist/commands/ui/index.d.ts +42 -0
  83. package/dist/commands/ui/index.js +32 -8
  84. package/dist/commands/ui/loop-approve.d.ts +4 -4
  85. package/dist/commands/ui/places-change.d.ts +1 -1
  86. package/dist/commands/ui/plan-structure.d.ts +3 -0
  87. package/dist/commands/ui/plan-structure.en.d.ts +3 -0
  88. package/dist/commands/ui/plan-structure.en.js +3 -0
  89. package/dist/commands/ui/plan-structure.es.d.ts +3 -0
  90. package/dist/commands/ui/plan-structure.es.js +3 -0
  91. package/dist/commands/ui/plan-structure.js +12 -4
  92. package/dist/commands/ui/prototype-comp-route.d.ts +7 -0
  93. package/dist/commands/ui/prototype-comp-route.js +109 -0
  94. package/dist/commands/ui/prototype-main.d.ts +2 -1
  95. package/dist/commands/ui/prototype-scenes-child.js +4 -1
  96. package/dist/commands/ui/prototype-snapshot-session.d.ts +1 -1
  97. package/dist/commands/ui/prototype-snapshot-session.js +3 -0
  98. package/dist/commands/ui/prototype-snapshot.d.ts +1 -1
  99. package/dist/commands/ui/routes.d.ts +8 -3
  100. package/dist/commands/ui/routes.js +3 -3
  101. package/dist/commands/ui/save-publish.js +3 -0
  102. package/dist/commands/ui/server-options.js +1 -0
  103. package/dist/commands/ui/server-request.js +5 -0
  104. package/dist/commands/ui/server.d.ts +14 -0
  105. package/dist/commands/ui/server.js +10 -3
  106. package/dist/commands/ui/structure-surface.d.ts +6 -0
  107. package/dist/commands/ui/structure-surface.js +94 -0
  108. package/dist/commands/ui/studio-routes.d.ts +1 -0
  109. package/dist/commands/ui/studio-routes.js +7 -1
  110. package/dist/commands/ui/studio-state.d.ts +7 -4
  111. package/dist/commands/ui/studio-versions.d.ts +3 -3
  112. package/dist/ui/page.js +98 -89
  113. package/docs/PROCESS.md +5 -0
  114. package/docs/PROTOTYPE.md +31 -0
  115. package/docs/WORKBENCH.md +11 -2
  116. package/package.json +11 -11
  117. package/skills/ape-critique/SKILL.md +9 -3
  118. package/skills/ape-design-system/SKILL.md +2 -1
  119. package/skills/ape-prototype/SKILL.md +5 -1
@@ -115,8 +115,11 @@ class TurnStream {
115
115
  const { chat, folder } = this.options;
116
116
  if (event.kind === 'refused') {
117
117
  const call = this.calls.get(event.id);
118
+ // The limits refused a command: the chat shows the limit's card in place of its line.
119
+ if (event.limit && call?.tool?.verb === 'ran')
120
+ call.tool.limit = event.limit;
118
121
  if (call)
119
- this.refuse(call, inTree(chat.work) ? event.reason : undefined);
122
+ this.refuse(call, inTree(chat.work) && !event.limit ? event.reason : undefined);
120
123
  return;
121
124
  }
122
125
  const existing = event.id ? this.calls.get(event.id) : undefined;
@@ -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. */
@@ -16,10 +21,13 @@ export interface TurnGuard {
16
21
  }
17
22
  /** A value only an open launch's own guard wrote into its arguments. */
18
23
  export declare const guardArgument: (arg: string) => boolean;
24
+ /** A launch outside a chat (a fresh read) may quote its own code-owned values while it runs. */
25
+ export declare function launchArguments(args: readonly string[]): () => void;
19
26
  /**
20
27
  * Opens a Claude launch's guard: the level and "Never ask" read now, and the limits hook in a
21
28
  * settings file and the permission tool's channel, in a folder of the launch's own that closes
22
29
  * 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).
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).
24
32
  */
25
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';
@@ -10,6 +11,18 @@ import { chatError } from './prompt.js';
10
11
  const live = new Set();
11
12
  /** A value only an open launch's own guard wrote into its arguments. */
12
13
  export const guardArgument = (arg) => [...live].some((guard) => guard.args.has(arg));
14
+ /** A launch outside a chat (a fresh read) may quote its own code-owned values while it runs. */
15
+ export function launchArguments(args) {
16
+ const guard = {
17
+ level: 'lead',
18
+ neverAsk: false,
19
+ allowed: [],
20
+ args: new Set(args),
21
+ close: () => live.delete(guard),
22
+ };
23
+ live.add(guard);
24
+ return guard.close;
25
+ }
13
26
  const script = (name) => {
14
27
  const suffix = import.meta.url.endsWith('.ts') ? 'ts' : 'js';
15
28
  return fileURLToPath(new URL(`./${name}.${suffix}`, import.meta.url)).replaceAll('\\', '/');
@@ -18,7 +31,8 @@ const script = (name) => {
18
31
  * Opens a Claude launch's guard: the level and "Never ask" read now, and the limits hook in a
19
32
  * settings file and the permission tool's channel, in a folder of the launch's own that closes
20
33
  * 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).
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).
22
36
  */
23
37
  export function openTurnGuard(run, root, save) {
24
38
  const guard = {
@@ -29,7 +43,9 @@ export function openTurnGuard(run, root, save) {
29
43
  close: () => { },
30
44
  };
31
45
  live.add(guard);
32
- 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')) {
33
49
  guard.close = () => live.delete(guard);
34
50
  return guard;
35
51
  }
@@ -52,7 +68,8 @@ export function openTurnGuard(run, root, save) {
52
68
  const channel = openPermissionChannel((call) => askPerson(turn, call, closed.signal));
53
69
  guard.settings = join(folder, 'settings.json');
54
70
  guard.mcp = join(folder, 'mcp.json');
55
- 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}`;
56
73
  writeFileSync(guard.settings, JSON.stringify({
57
74
  // Flag settings outrank the product's own, so a product file cannot switch the hook off.
58
75
  disableAllHooks: false,
@@ -5,6 +5,7 @@ import type { MergeConfiguration } from '../merge-authority.ts';
5
5
  import type { AgentTurn, Start, stopTree } from '../runner.ts';
6
6
  import type { ChatImage } from './defs.ts';
7
7
  import type { findAgents } from './find.ts';
8
+ import type { FreshLooks } from './fresh.ts';
8
9
  import type { Install } from './install.ts';
9
10
  import type { TurnMigrations } from './migration-turn.ts';
10
11
  import type { AskTurn } from './permission-ask.ts';
@@ -36,6 +37,8 @@ export interface Active {
36
37
  scenes?: TurnScene[];
37
38
  /** The launch's permission card, while its permission tool can ask; private, never saved. */
38
39
  asks?: AskTurn;
40
+ /** Told when the turn ends, to start a fresh agent's review of the step. */
41
+ fresh?: Pick<FreshLooks, 'afterTurn'>;
39
42
  }
40
43
  export interface ChatEngineOptions extends MergeConfiguration {
41
44
  start?: Start;
@@ -45,6 +48,8 @@ export interface ChatEngineOptions extends MergeConfiguration {
45
48
  install?: Install;
46
49
  environment?: NodeJS.ProcessEnv;
47
50
  migrations?: TurnMigrations;
51
+ /** The studio's fresh turns: a review after a planning step's turn writes its files. */
52
+ fresh?: FreshLooks;
48
53
  }
49
54
  /** Permission answers are ordinary sends; a notice belongs only to the agent that asked. */
50
55
  export declare function turnContext({ chat, person, firstMessage, retryNotice }: Active): AgentTurn;
@@ -88,6 +88,7 @@ export class ChatEngine {
88
88
  this.heldMerges.supersede(run);
89
89
  if (actor)
90
90
  run.person = actor;
91
+ run.fresh = this.options.fresh;
91
92
  run.startedAt = startedAt;
92
93
  run.firstMessage = run.chat.messages.length;
93
94
  if (run.stopped) {
@@ -0,0 +1,6 @@
1
+ import type { ApprovalArtifact } from './approval-authority.ts';
2
+ import { type SaveSource } from './host-save.ts';
3
+ import type { UiAnswer } from './routes.ts';
4
+ export declare function compApproval(root: string, fingerprint: string, signer?: string, role?: string, agent?: string, source?: SaveSource): Promise<UiAnswer>;
5
+ /** What a host's authority judges: the comp the page showed, at the commit checked out. */
6
+ export declare function compResolver(root: string, fingerprint: string): Promise<() => ApprovalArtifact>;
@@ -0,0 +1,42 @@
1
+ // Approve the look: the guarded approval route's door for the comp. A person's only, at every level;
2
+ // there is no agent, MCP or Autopilot door, and `approveComp` refuses an agent's name. The record is
3
+ // saved as its own isolated commit, as a version approval is (`saveApprovalRecord`).
4
+ import { ApprovalRefusal } from '../approval-rules.js';
5
+ import { newestComp } from '../prototype/comp.js';
6
+ import { approveComp, COMP_FILE } from '../prototype/comp-record.js';
7
+ import { compT } from '../prototype/comp-words.js';
8
+ import { VersionRefusal } from '../prototype/versions.js';
9
+ import { hostGit } from '../safe-git.js';
10
+ import { HostSaveRefusal } from './host-save.js';
11
+ import { saveApprovalRecord } from './save-route.js';
12
+ const git = async (root, args) => (await hostGit(root, args)).trim();
13
+ export async function compApproval(root, fingerprint, signer, role, agent, source) {
14
+ if (agent !== undefined)
15
+ return { status: 409, body: { error: compT('comp.person') } };
16
+ const by = signer ?? (await git(root, ['config', 'user.email']).catch(() => ''));
17
+ if (!by)
18
+ return { status: 400, body: { error: compT('comp.identity') } };
19
+ const commit = await git(root, ['rev-parse', '--verify', 'HEAD']).catch(() => null);
20
+ if (!commit)
21
+ return { status: 409, body: { error: compT('comp.commitFirst') } };
22
+ try {
23
+ const record = await saveApprovalRecord(root, COMP_FILE, (write = true) => approveComp(root, { by, commit, fingerprint, role }, write), by, undefined, source);
24
+ return { status: 201, body: record.approval };
25
+ }
26
+ catch (error) {
27
+ if (error instanceof HostSaveRefusal)
28
+ return { status: 409, body: error.result() };
29
+ if (error instanceof ApprovalRefusal || error instanceof VersionRefusal)
30
+ return { status: 409, body: { error: error.message } };
31
+ throw error;
32
+ }
33
+ }
34
+ /** What a host's authority judges: the comp the page showed, at the commit checked out. */
35
+ export async function compResolver(root, fingerprint) {
36
+ const commit = await git(root, ['rev-parse', '--verify', 'HEAD']);
37
+ return () => {
38
+ if (newestComp(root)?.fingerprint !== fingerprint)
39
+ throw new Error();
40
+ return { kind: 'comp', version: null, commit, fingerprint };
41
+ };
42
+ }
@@ -54,6 +54,9 @@ export async function routeRight(route, request) {
54
54
  return route.right;
55
55
  if (route.path === '/api/approve') {
56
56
  const { kind } = approvalKind.parse(await request.body());
57
+ // The comp is the prototype's look: whoever approves prototypes approves it.
58
+ if (kind === 'comp')
59
+ return 'approve:prototype';
57
60
  return kind === 'places' ? 'approve:data' : `approve:${kind}`;
58
61
  }
59
62
  if (route.path === '/api/run') {
@@ -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;
@@ -5,7 +5,11 @@ import { spawn } from 'node:child_process';
5
5
  import { createI18n } from '@buffcore/i18n';
6
6
  import { InvalidArgumentError } from 'commander';
7
7
  import { findRoot, loadEnv, loadProduct } from '../../project.js';
8
+ import { FreshLooks } from './chat/fresh.js';
9
+ import { freshRoutes } from './chat/fresh-routes.js';
10
+ import { hostLaunchedEnv } from './chat/host-launched.js';
8
11
  import { TurnMigrations } from './chat/migration-turn.js';
12
+ import { agentStart } from './chat/process.js';
9
13
  import { chatRoutes } from './chat/routes.js';
10
14
  import { installShutdown } from './chat/shutdown.js';
11
15
  import { ChatEngine } from './chat/turn.js';
@@ -40,19 +44,29 @@ function openBrowser(url) {
40
44
  .on('error', () => { })
41
45
  .unref();
42
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
+ }
43
57
  export async function ui(options) {
44
58
  const locale = options.lang === undefined ? undefined : uiLocale(options.lang);
45
59
  if (options.studio)
46
60
  console.log(t('ui.studio.noop', undefined, locale));
47
61
  const root = findRoot();
48
- const agentEnvironment = { ...process.env };
49
- const env = loadEnv(root);
62
+ const { agentEnvironment, env, hostLaunched } = uiEnvironment(root);
50
63
  const { name } = await loadProduct(root);
51
64
  const port = options.port ? Number(options.port) : defaultStudioPort(env.APE_API_PORT);
52
65
  const token = newToken();
53
66
  const code = localCode((event) => console.log(t(`ui.code.${event}`, undefined, locale)));
54
67
  const migrations = new TurnMigrations(root, env, locale);
55
- const chats = new ChatEngine(root, { environment: agentEnvironment, migrations });
68
+ const fresh = new FreshLooks(root, agentStart(root, agentEnvironment));
69
+ const chats = new ChatEngine(root, { environment: agentEnvironment, migrations, fresh });
56
70
  await chats.ready;
57
71
  const stack = new Stack(root, {
58
72
  app: env.APE_APP_URL,
@@ -68,6 +82,8 @@ export async function ui(options) {
68
82
  const server = createUiServer({
69
83
  turnMigrations: migrations,
70
84
  contained: false,
85
+ // A host that starts `ape ui` under its own trusted launcher sets APE_HOST_LAUNCHED=1.
86
+ hostLaunched,
71
87
  token,
72
88
  code,
73
89
  product: name,
@@ -76,13 +92,17 @@ export async function ui(options) {
76
92
  runner,
77
93
  plan: () => plan,
78
94
  refreshPlan,
79
- routes: [...routes, ...chatRoutes(chats)],
95
+ routes: [...routes, ...chatRoutes(chats), ...freshRoutes(fresh, root)],
96
+ onFullSnapshot: (source, report) => void fresh.afterSnapshot(source, report),
80
97
  });
81
98
  await openStudio(server, port, token, code, options, locale);
82
- keepStudio(server, stack, chats, migrations);
99
+ keepStudio(server, stack, chats, migrations, fresh);
83
100
  }
84
- function keepStudio(server, stack, chats, migrations) {
85
- server.once('close', () => chats.stopAll());
101
+ function keepStudio(server, stack, chats, migrations, fresh) {
102
+ server.once('close', () => {
103
+ fresh.close();
104
+ void chats.stopAll();
105
+ });
86
106
  void stack.check();
87
107
  setInterval(() => void stack.check(), 2000).unref();
88
108
  installShutdown({
@@ -91,9 +111,13 @@ function keepStudio(server, stack, chats, migrations) {
91
111
  },
92
112
  release: () => stack.release(),
93
113
  stop: async () => {
114
+ fresh.close();
94
115
  await Promise.all([chats.shutdown(), migrations.idle()]);
95
116
  },
96
- force: () => chats.stopAll(true),
117
+ force: () => {
118
+ fresh.close();
119
+ return chats.stopAll(true);
120
+ },
97
121
  });
98
122
  }
99
123
  async function openStudio(server, port, token, code, options, locale) {
@@ -9,7 +9,7 @@ export declare function brandApproval(root: string, direction: keyof typeof them
9
9
  } | {
10
10
  status: number;
11
11
  body: {
12
- kind: "brand" | "money" | "places" | "plan" | "prototype" | "release";
12
+ kind: "brand" | "comp" | "money" | "places" | "plan" | "prototype" | "release";
13
13
  signatures: {
14
14
  by: string;
15
15
  at: string;
@@ -75,7 +75,7 @@ export declare function prototypeApproval(root: string, request: {
75
75
  approved?: {
76
76
  version: number;
77
77
  approval: {
78
- kind: "brand" | "money" | "places" | "plan" | "prototype" | "release";
78
+ kind: "brand" | "comp" | "money" | "places" | "plan" | "prototype" | "release";
79
79
  signatures: {
80
80
  by: string;
81
81
  at: string;
@@ -100,7 +100,7 @@ export declare function prototypeApproval(root: string, request: {
100
100
  pending?: {
101
101
  version: number;
102
102
  approval: {
103
- kind: "brand" | "money" | "places" | "plan" | "prototype" | "release";
103
+ kind: "brand" | "comp" | "money" | "places" | "plan" | "prototype" | "release";
104
104
  signatures: {
105
105
  by: string;
106
106
  at: string;
@@ -125,7 +125,7 @@ export declare function prototypeApproval(root: string, request: {
125
125
  superseded?: {
126
126
  version: number;
127
127
  approval: {
128
- kind: "brand" | "money" | "places" | "plan" | "prototype" | "release";
128
+ kind: "brand" | "comp" | "money" | "places" | "plan" | "prototype" | "release";
129
129
  signatures: {
130
130
  by: string;
131
131
  at: string;
@@ -42,7 +42,7 @@ export declare function plannedPlaceApproval(root: string, change: string): Prom
42
42
  revision: string;
43
43
  record: {
44
44
  approvals: {
45
- kind: "brand" | "money" | "places" | "plan" | "prototype" | "release";
45
+ kind: "brand" | "comp" | "money" | "places" | "plan" | "prototype" | "release";
46
46
  signatures: {
47
47
  by: string;
48
48
  at: string;
@@ -16,16 +16,19 @@ export type ChangeScreens = ReadonlyMap<string, readonly string[]>;
16
16
  export declare function parseStructure(text: string, screens?: readonly string[], changes?: ChangeScreens): {
17
17
  rows: StructureRow[];
18
18
  notes: string[];
19
+ surface: "desktop" | "phone";
19
20
  };
20
21
  /** Reuse the inventory's discovery; no product code is loaded and no navigation is inferred. */
21
22
  export declare function readStructure(root: string): Promise<{
22
23
  rows: StructureRow[];
23
24
  notes: string[];
25
+ surface: "desktop" | "phone";
24
26
  } | null>;
25
27
  /** A malformed structure must not hide the rest of an older product's plan. */
26
28
  export declare function structureFacts(root: string): Promise<{
27
29
  rows: StructureRow[];
28
30
  notes: string[];
31
+ surface: "desktop" | "phone";
29
32
  } | {
30
33
  rows: never[];
31
34
  notes: never[];
@@ -18,4 +18,7 @@ export declare const en: {
18
18
  'structure.main': string;
19
19
  'structure.empty': string;
20
20
  'structure.notes': string;
21
+ 'structure.surfaceMissing': string;
22
+ 'structure.surfaceFailed': string;
23
+ 'structure.surface': string;
21
24
  };
@@ -18,4 +18,7 @@ export const en = {
18
18
  'structure.main': '{row}: Main must be yes or no. File order ranks the main sections.',
19
19
  'structure.empty': 'Name at least one section and its first screen.',
20
20
  'structure.notes': 'Add short notes for nested screens and their return targets, phone and wide screens.',
21
+ 'structure.surfaceMissing': 'Draft the structure first; then choose which surface comes first.',
22
+ 'structure.surfaceFailed': 'The surface could not be written. Try again.',
23
+ 'structure.surface': '{row}: write the Surface line once, before the table, as Surface: desktop or Surface: phone.',
21
24
  };
@@ -18,4 +18,7 @@ export declare const es: {
18
18
  'structure.main': string;
19
19
  'structure.empty': string;
20
20
  'structure.notes': string;
21
+ 'structure.surfaceMissing': string;
22
+ 'structure.surfaceFailed': string;
23
+ 'structure.surface': string;
21
24
  };
@@ -18,4 +18,7 @@ export const es = {
18
18
  'structure.main': '{row}: Main debe ser yes o no. El orden del archivo ordena las secciones principales.',
19
19
  'structure.empty': 'Nombra al menos una sección y su primera pantalla.',
20
20
  'structure.notes': 'Añade notas breves para las pantallas anidadas y su regreso, teléfonos y pantallas anchas.',
21
+ 'structure.surfaceMissing': 'Primero haz el borrador de la estructura; luego elige qué superficie va primero.',
22
+ 'structure.surfaceFailed': 'No se pudo escribir la superficie. Inténtalo de nuevo.',
23
+ 'structure.surface': '{row}: escribe la línea Surface una vez, antes de la tabla, como Surface: desktop o Surface: phone.',
21
24
  };
@@ -3,6 +3,7 @@ import { join } from 'node:path';
3
3
  import { createI18n } from '@buffcore/i18n';
4
4
  import { readChanges } from '../change-file.js';
5
5
  import { adminScreens, appScreens } from '../inventory-screens.js';
6
+ import { SURFACE_FIELD, SURFACE_LINE } from '../prototype/comp.js';
6
7
  import { en } from './plan-structure.en.js';
7
8
  import { es } from './plan-structure.es.js';
8
9
  /** `/billing (planned, C-020)`: a first screen a change adds, before its route exists. */
@@ -28,6 +29,7 @@ function sourceName(line, t) {
28
29
  function structureLines(text, t, numbers) {
29
30
  const table = [];
30
31
  const notes = [];
32
+ let surface;
31
33
  let state = 'before';
32
34
  for (const [index, line] of text
33
35
  .replace(/^\uFEFF/, '')
@@ -42,7 +44,13 @@ function structureLines(text, t, numbers) {
42
44
  state = 'after';
43
45
  }
44
46
  else if (state === 'before' && /^# [\p{L}\p{N}][^<>|]*$/u.test(line)) {
45
- // Only titles and empty lines may precede the table.
47
+ // Only titles, the surface and empty lines may precede the table.
48
+ }
49
+ else if (state === 'before' && SURFACE_FIELD.test(line)) {
50
+ const found = SURFACE_LINE.exec(line);
51
+ if (surface || !found)
52
+ throw new Error(t('structure.surface', { row }));
53
+ surface = found[1]?.toLowerCase();
46
54
  }
47
55
  else if (/^\|.*(?<!\\)\|$/.test(line)) {
48
56
  if (state === 'after')
@@ -58,7 +66,7 @@ function structureLines(text, t, numbers) {
58
66
  throw new Error(t(state === 'before' ? 'structure.before' : 'structure.noteShape', { row }));
59
67
  }
60
68
  }
61
- return { table, notes };
69
+ return { table, notes, surface: surface ?? 'desktop' };
62
70
  }
63
71
  const cells = (line) => line
64
72
  .split(/(?<!\\)\|/)
@@ -145,12 +153,12 @@ export function parseStructure(text, screens, changes) {
145
153
  const locale = /^es(?:[-_.]|$)/i.test(process.env.LC_ALL || process.env.LANG || '') ? 'es' : 'en';
146
154
  const t = (key, values) => messages.t(locale, key, values);
147
155
  const numbers = new Intl.NumberFormat(locale);
148
- const { table, notes } = structureLines(text, t, numbers);
156
+ const { table, notes, surface } = structureLines(text, t, numbers);
149
157
  checkColumns(table, t, numbers);
150
158
  const rows = structureRows(table, t, screens, changes);
151
159
  if (!notes.length)
152
160
  throw new Error(t('structure.notes'));
153
- return { rows, notes };
161
+ return { rows, notes, surface };
154
162
  }
155
163
  /** Reuse the inventory's discovery; no product code is loaded and no navigation is inferred. */
156
164
  export async function readStructure(root) {
@@ -0,0 +1,7 @@
1
+ import { type PrototypeCompReply } from '@buffcore/contracts/workbench';
2
+ import type { ImageType, UiRoute } from './routes.ts';
3
+ export declare const pictureType: (file: string) => ImageType | undefined;
4
+ export declare function compReply(root: string, hosted?: boolean): Promise<PrototypeCompReply>;
5
+ /** The file a picture name stands for, or undefined: only the comp's own shots and the references. */
6
+ export declare function compPicture(root: string, name: string, hosted?: boolean): Promise<string | undefined>;
7
+ export declare function prototypeCompRoutes(root: string): UiRoute[];
@@ -0,0 +1,109 @@
1
+ // The comp page's reads: the newest comp snapshot's screens, the references beside them and the
2
+ // approval; and each picture by its name (never by a path from the request).
3
+ import { readFile } from 'node:fs/promises';
4
+ import { extname, join } from 'node:path';
5
+ import { frameSizes } from '@buffcore/config';
6
+ import { workbenchApi } from '@buffcore/contracts/workbench';
7
+ import { loadProduct } from '../../project.js';
8
+ import { referencePictures } from '../design/references.js';
9
+ import { compDir, firstSurface, newestComp } from '../prototype/comp.js';
10
+ import { compApproved, readCompApproval } from '../prototype/comp-record.js';
11
+ import { snapshotsDir } from '../prototype/report.js';
12
+ const MAX = 12;
13
+ /** The picture types the page shows, by extension; any other file is never served. */
14
+ const TYPES = {
15
+ '.png': 'image/png',
16
+ '.jpg': 'image/jpeg',
17
+ '.jpeg': 'image/jpeg',
18
+ '.webp': 'image/webp',
19
+ '.gif': 'image/gif',
20
+ '.avif': 'image/avif',
21
+ };
22
+ export const pictureType = (file) => TYPES[extname(file).toLowerCase()];
23
+ const SHOT = /^[0-9a-f]{7,64}\/[^/\\]+\.png$/;
24
+ /** A comp screen's light and dark pictures: the product's theme, as the snapshot shot them. */
25
+ function screenShots(scene) {
26
+ const looks = Object.keys(scene.screenshots ?? {});
27
+ const dark = looks.find((look) => look.endsWith('.dark'));
28
+ const light = dark && looks.includes(dark.slice(0, -5)) ? dark.slice(0, -5) : looks[0];
29
+ return { light, dark };
30
+ }
31
+ async function desktopWidth(root) {
32
+ try {
33
+ return frameSizes(await loadProduct(root)).desktop.width;
34
+ }
35
+ catch {
36
+ return frameSizes().desktop.width;
37
+ }
38
+ }
39
+ /**
40
+ * The reference files the page may show, in their places: on the person's own computer (the local
41
+ * studio) any listed picture; under a host only those inside the product's folder.
42
+ */
43
+ async function shownReferences(root, hosted) {
44
+ return (await referencePictures(root))
45
+ .slice(0, MAX)
46
+ .map(({ file, inside }) => file && (inside || !hosted) && pictureType(file) ? file : undefined);
47
+ }
48
+ export async function compReply(root, hosted = false) {
49
+ const surface = firstSurface(root);
50
+ const comp = newestComp(root);
51
+ const record = readCompApproval(root);
52
+ const references = await shownReferences(root, hosted);
53
+ const screens = (comp?.report.scenes ?? []).slice(0, MAX).map((scene, index) => {
54
+ const { light, dark } = screenShots(scene);
55
+ return {
56
+ key: scene.key.slice(0, 100),
57
+ title: String(scene.title ?? scene.key).slice(0, 200),
58
+ ...(light ? { light: `screen-${index}-light` } : {}),
59
+ ...(dark ? { dark: `screen-${index}-dark` } : {}),
60
+ };
61
+ });
62
+ return {
63
+ surface,
64
+ width: surface === 'phone' ? frameSizes().phone.width : await desktopWidth(root),
65
+ screens,
66
+ references: references.map((file, index) => (file ? `reference-${index}` : null)),
67
+ ...(comp ? { fingerprint: comp.fingerprint } : {}),
68
+ approved: compApproved(record, comp),
69
+ approval: record?.approval ?? null,
70
+ };
71
+ }
72
+ /** The file a picture name stands for, or undefined: only the comp's own shots and the references. */
73
+ export async function compPicture(root, name, hosted = false) {
74
+ const screen = /^screen-(\d{1,2})-(light|dark)$/.exec(name);
75
+ if (screen) {
76
+ const scene = newestComp(root)?.report.scenes[Number(screen[1])];
77
+ if (!scene)
78
+ return;
79
+ const look = screenShots(scene)[screen[2]];
80
+ const path = look ? scene.screenshots[look] : undefined;
81
+ return path && SHOT.test(path) ? join(compDir(snapshotsDir(root)), path) : undefined;
82
+ }
83
+ const reference = /^reference-(\d{1,2})$/.exec(name);
84
+ if (reference)
85
+ return (await shownReferences(root, hosted))[Number(reference[1])];
86
+ }
87
+ export function prototypeCompRoutes(root) {
88
+ return [
89
+ {
90
+ method: 'GET',
91
+ path: workbenchApi.prototypeComp,
92
+ right: 'read:runs',
93
+ handle: async ({ hosted }) => ({ status: 200, body: await compReply(root, !!hosted) }),
94
+ },
95
+ {
96
+ method: 'GET',
97
+ path: `${workbenchApi.prototypeComp}/picture/:name`,
98
+ right: 'read:runs',
99
+ handle: async ({ params, hosted }) => {
100
+ const file = await compPicture(root, params.name ?? '', !!hosted);
101
+ const type = file ? pictureType(file) : undefined;
102
+ const bytes = file && type ? await readFile(file).catch(() => undefined) : undefined;
103
+ return bytes && type
104
+ ? { status: 200, body: bytes, type }
105
+ : { status: 404, body: { error: 'missing' } };
106
+ },
107
+ },
108
+ ];
109
+ }
@@ -72,12 +72,13 @@ export declare function planPrototypeOnMain(root: string, plan: PlanFacts | unde
72
72
  planned?: string | undefined;
73
73
  }[];
74
74
  notes: string[];
75
+ surface?: "desktop" | "phone" | undefined;
75
76
  problem?: string | undefined;
76
77
  } | null | undefined;
77
78
  themeDirection?: string | undefined;
78
79
  themeVoice?: string | undefined;
79
80
  brand: {
80
- kind: "brand" | "money" | "places" | "plan" | "prototype" | "release";
81
+ kind: "brand" | "comp" | "money" | "places" | "plan" | "prototype" | "release";
81
82
  signatures: {
82
83
  by: string;
83
84
  at: string;
@@ -11,7 +11,10 @@ import { writeSync } from 'node:fs';
11
11
  import { pathToFileURL } from 'node:url';
12
12
  try {
13
13
  const prototype = (await import(__rewriteRelativeImportExtension(pathToFileURL(process.argv[2] ?? '').href))).default;
14
- const scenes = prototype.scenes.map(({ key, title, surface, view }) => ({
14
+ // The comp's scenes (`comp/`) are snapshotted apart and never listed among the scenes.
15
+ const scenes = prototype.scenes
16
+ .filter(({ key }) => !(typeof key === 'string' && key.startsWith('comp/')))
17
+ .map(({ key, title, surface, view }) => ({
15
18
  key,
16
19
  title,
17
20
  surface,