retouche-dev 0.1.0 → 0.1.1

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.
package/PROMPT.md CHANGED
@@ -72,10 +72,10 @@ An `allow` entry is `{ component?: "Text", classes?: ["text-muted-*"], propertie
72
72
 
73
73
  The overlay talks to its dev route at `/api/retouche` on the app's own origin: the code behind each override, the config entries it writes and voice sessions all go through it. Read the app's config for anything that stands between the two, and change it for development only:
74
74
 
75
- - **Hostname.** The route answers on `localhost`, `*.localhost`, `127.0.0.1` and `[::1]`. If the developer opens the dev server under another name (a domain mapped in `/etc/hosts`, a LAN address, a container or tunnel host: look at `server.host` and `server.allowedHosts` in the Vite config, `allowedDevOrigins` in the Next config, the dev script and the README), add each name, comma-separated, to `RETOUCHE_HOSTS` in the app's `.env.local`, or to the `allowedHosts` option when the whole team uses it: `retouche({ allowedHosts: [...] })`, or for Next.js a route file reading `export const { GET, POST } = createRoute({ allowedHosts: [...] });` with `createRoute` from `retouche-dev/next`.
75
+ - **Hostname.** The route answers on `localhost`, `*.localhost`, `127.0.0.1` and `[::1]`, and only to a browser on the machine running the dev server. If the developer opens the dev server under another name (a domain mapped in `/etc/hosts`, a LAN address, a container or tunnel host: look at `server.host` and `server.allowedHosts` in the Vite config, `allowedDevOrigins` in the Next config, the dev script and the README), add each name, comma-separated, to `RETOUCHE_HOSTS` in the app's `.env.local`, or to the `allowedHosts` option when the whole team uses it: `retouche({ allowedHosts: [...] })`, or for Next.js a route file reading `export const { GET, POST } = createRoute({ allowedHosts: [...] });` with `createRoute` from `retouche-dev/next`.
76
76
  - **Next.js `basePath`.** The overlay calls `/api/retouche` from the site's root, so with a `basePath` set: stop and tell me.
77
77
  - **Requests in front of the route.** A Next.js `proxy.ts` or `middleware.ts` whose matcher covers `/api/retouche` and that can redirect, rewrite or reject it (auth, locale prefixes, rate limits): exclude `/api/retouche` from its matcher. Vite runs Retouche's middleware before its own `server.proxy`, so a proxied `/api` is fine; when the app's own server sits in front of Vite (Vite in middleware mode under Express, Hono, Fastify…), it must hand `/api/retouche` to `vite.middlewares` before its own routes.
78
- - **Security headers in development.** A `Content-Security-Policy` or `Permissions-Policy` sent in development (headers in the Next config, `proxy.ts` or `middleware.ts`, a `<meta http-equiv>` tag, Vite's `server.headers`, the app's own server) must let the overlay run. Its styles are `<style>` elements: `style-src 'unsafe-inline'`, and since browsers ignore `'unsafe-inline'` next to a nonce or hash, leave those out of `style-src` in development. Screenshots are `blob:` and `data:` images (`img-src`). Listening through a speech-to-text key loads an audio worklet from a `blob:` URL (`script-src`). Voice sessions need the microphone (`microphone=(self)`). Leave production headers as they are.
78
+ - **Security headers in development.** A `Content-Security-Policy` or `Permissions-Policy` sent in development (headers in the Next config, `proxy.ts` or `middleware.ts`, a `<meta http-equiv>` tag, Vite's `server.headers`, the app's own server) must let the overlay run. Its styles are `<style>` elements: `style-src 'unsafe-inline'`, and since browsers ignore `'unsafe-inline'` next to a nonce or hash, leave those out of `style-src` in development. The overlay pairs with the dev server through `http://127.0.0.1` on a port the server picks (`connect-src http://127.0.0.1:*`). Screenshots are `blob:` and `data:` images (`img-src`). Listening through a speech-to-text key loads an audio worklet from a `blob:` URL (`script-src`). Voice sessions need the microphone (`microphone=(self)`). Leave production headers as they are.
79
79
  - **Editor.** Code opens in VS Code unless `RETOUCHE_EDITOR` names another: `cursor`, `webstorm`, `windsurf` or `zed`. When you know the developer works in one of those, set it in the app's `.env.local`.
80
80
  - Before writing to `.env.local`, check that git ignores it, and add it to `.gitignore` when it doesn't.
81
81
  - **Voice sessions** (Session on the bar) turn what the developer says while pointing at the page into feedback through their own Claude Code, Codex or Mastra Code CLI, whichever is installed and signed in; Retouche runs it in the background. Sessions are saved in the user's data folder, outside the repo. A Groq, Mistral or OpenAI speech-to-text key is added from the voice start screen, or picked up from `GROQ_API_KEY`, `MISTRAL_API_KEY` or `OPENAI_API_KEY` in the environment or the app's `.env` files, and kept outside the repo. Other writers, ACP agents or OpenAI-compatible endpoints, and any other transcriber go in the `voice` option of `retouche()` or `createRoute()`, typed in the package; add them only when the developer asks, and never write a key into a file. None is required for the rest of Retouche.
package/dist/cli.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { t as WATCHED_GROUPS } from "./class-groups-DKpPgmHx.js";
3
- import { O as voiceIdSchema, i as FOLLOW_OUTCOMES } from "./clock-DPQ0w5RJ.js";
4
- import { d as FOLLOW_TOOL, l as reviewItems, p as mcpFollowPrompt, t as cardMarkdown, u as FOLLOW_PROMPT } from "./voice-markdown-DhG3jnuj.js";
5
- import { a as writeFollow, g as failure, i as readFollower, l as readSessionFile, n as followedSession, o as writeFollower, r as readFollow, s as NO_FOLDER, t as EMPTY_FOLLOW, u as projectFolder } from "./follow-files-VmBxVLp-.js";
3
+ import { A as voiceIdSchema, i as FOLLOW_OUTCOMES } from "./clock-BJi08VJS.js";
4
+ import { d as FOLLOW_TOOL, l as reviewItems, p as mcpFollowPrompt, t as cardMarkdown, u as FOLLOW_PROMPT } from "./voice-markdown-BiOKT1SX.js";
5
+ import { a as writeFollow, g as failure, i as readFollower, l as readSessionFile, n as followedSession, o as writeFollower, r as readFollow, s as NO_FOLDER, t as EMPTY_FOLLOW, u as projectFolder } from "./follow-files-CfuW6Ah5.js";
6
6
  import { existsSync, readFileSync } from "node:fs";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { z } from "zod";
@@ -577,7 +577,7 @@ function localTarball() {
577
577
  return null;
578
578
  }
579
579
  function installSource(argument) {
580
- if (argument === void 0) return packageName();
580
+ if (argument === void 0) return `${packageName()}@latest`;
581
581
  if (argument === "--local") return localTarball();
582
582
  const url = tarballUrl.safeParse(argument);
583
583
  if (url.success) return url.data;
@@ -269,6 +269,8 @@ const sourceFileSchema = z.object({
269
269
  path: z.string()
270
270
  });
271
271
  const errorBodySchema = z.object({ error: z.string() });
272
+ const unpairedBodySchema = errorBodySchema.extend({ pair: z.number().int().min(1).max(65535) });
273
+ const pairTokenSchema = z.object({ token: z.string().min(1) });
272
274
  const SERVER_FRAME_ORIGIN = "(?:about|rsc)://React/[^/\\s)]+/";
273
275
  const SERVER_FRAME_PREFIX = new RegExp(`^${SERVER_FRAME_ORIGIN}`);
274
276
  function isServerFrame(fileName) {
@@ -302,4 +304,4 @@ function clock(ms) {
302
304
  function recordedMs(session) {
303
305
  return Math.max(0, ...session.passages.map(({ endMs }) => endMs), ...session.moments.map(({ atMs, durationMs }) => atMs + durationMs), ...session.shots.map(({ atMs }) => atMs));
304
306
  }
305
- export { voiceKeyRequestSchema as A, statusSchema as C, voiceHistorySchema as D, voiceHistoryRequestSchema as E, voiceStreamSchema as F, voiceTranscriptRequestSchema as I, voiceTranscriptSchema as L, voiceSessionSchema as M, voiceShotUploadSchema as N, voiceIdSchema as O, voiceStreamRequestSchema as P, sourceFileSchema as S, voiceFigureUploadSchema as T, TRANSCRIBER_PROVIDER_NAMES as _, followCardSchema as a, isServerFrame as b, EDITORS as c, ROUTE_BASE as d, SERVER_FRAME_ORIGIN as f, TRANSCRIBER_PROVIDERS as g, STREAMED_TRANSCRIBERS as h, FOLLOW_OUTCOMES as i, voiceSessionRequestSchema as j, voiceKeyAnswerSchema as k, ENDPOINTS as l, STATUS_MARKER as m, recordedMs as n, voiceFollowSchema as o, SERVER_FRAME_PREFIX as p, pendingPassages as r, BUILT_IN_AGENTS as s, clock as t, REQUEST_HEADER as u, VOICE_ID as v, voiceAnalysisRequestSchema as w, routeMarkerSchema as x, errorBodySchema as y };
307
+ export { voiceIdSchema as A, sourceFileSchema as C, voiceFigureUploadSchema as D, voiceAnalysisRequestSchema as E, voiceShotUploadSchema as F, voiceStreamRequestSchema as I, voiceStreamSchema as L, voiceKeyRequestSchema as M, voiceSessionRequestSchema as N, voiceHistoryRequestSchema as O, voiceSessionSchema as P, voiceTranscriptRequestSchema as R, routeMarkerSchema as S, unpairedBodySchema as T, TRANSCRIBER_PROVIDER_NAMES as _, followCardSchema as a, isServerFrame as b, EDITORS as c, ROUTE_BASE as d, SERVER_FRAME_ORIGIN as f, TRANSCRIBER_PROVIDERS as g, STREAMED_TRANSCRIBERS as h, FOLLOW_OUTCOMES as i, voiceKeyAnswerSchema as j, voiceHistorySchema as k, ENDPOINTS as l, STATUS_MARKER as m, recordedMs as n, voiceFollowSchema as o, SERVER_FRAME_PREFIX as p, pendingPassages as r, BUILT_IN_AGENTS as s, clock as t, REQUEST_HEADER as u, VOICE_ID as v, statusSchema as w, pairTokenSchema as x, errorBodySchema as y, voiceTranscriptSchema as z };
@@ -1,4 +1,4 @@
1
- import { M as voiceSessionSchema, O as voiceIdSchema, a as followCardSchema, v as VOICE_ID } from "./clock-DPQ0w5RJ.js";
1
+ import { A as voiceIdSchema, P as voiceSessionSchema, a as followCardSchema, v as VOICE_ID } from "./clock-BJi08VJS.js";
2
2
  import { z } from "zod";
3
3
  import { basename, dirname, join } from "node:path";
4
4
  import { createHash, randomBytes } from "node:crypto";
@@ -1,17 +1,134 @@
1
- import { A as voiceKeyRequestSchema, E as voiceHistoryRequestSchema, I as voiceTranscriptRequestSchema, N as voiceShotUploadSchema, P as voiceStreamRequestSchema, T as voiceFigureUploadSchema, _ as TRANSCRIBER_PROVIDER_NAMES, b as isServerFrame, c as EDITORS, d as ROUTE_BASE, g as TRANSCRIBER_PROVIDERS, h as STREAMED_TRANSCRIBERS, j as voiceSessionRequestSchema, l as ENDPOINTS, m as STATUS_MARKER, n as recordedMs, p as SERVER_FRAME_PREFIX, r as pendingPassages, s as BUILT_IN_AGENTS, t as clock, u as REQUEST_HEADER, v as VOICE_ID, w as voiceAnalysisRequestSchema } from "./clock-DPQ0w5RJ.js";
2
- import { _ as imageResponse, c as SessionFiles, d as projectId, f as userConfigFolder, g as failure$1, h as errorResponse, i as readFollower, m as createKeyedQueue, p as writePrivateFile, r as readFollow, u as projectFolder, v as jsonResponse, y as outcomeResponse } from "./follow-files-VmBxVLp-.js";
1
+ import { D as voiceFigureUploadSchema, E as voiceAnalysisRequestSchema, F as voiceShotUploadSchema, I as voiceStreamRequestSchema, M as voiceKeyRequestSchema, N as voiceSessionRequestSchema, O as voiceHistoryRequestSchema, R as voiceTranscriptRequestSchema, _ as TRANSCRIBER_PROVIDER_NAMES, b as isServerFrame, c as EDITORS, d as ROUTE_BASE, g as TRANSCRIBER_PROVIDERS, h as STREAMED_TRANSCRIBERS, l as ENDPOINTS, m as STATUS_MARKER, n as recordedMs, p as SERVER_FRAME_PREFIX, r as pendingPassages, s as BUILT_IN_AGENTS, t as clock, u as REQUEST_HEADER, v as VOICE_ID } from "./clock-BJi08VJS.js";
2
+ import { _ as imageResponse, c as SessionFiles, d as projectId, f as userConfigFolder, g as failure$1, h as errorResponse, i as readFollower, m as createKeyedQueue, p as writePrivateFile, r as readFollow, u as projectFolder, v as jsonResponse, y as outcomeResponse } from "./follow-files-CfuW6Ah5.js";
3
3
  import { n as passageRuns, r as spokenWords } from "./spoken-timeline-1xtFghWv.js";
4
- import { constants, existsSync, realpathSync } from "node:fs";
4
+ import { constants, existsSync, readFileSync, realpathSync } from "node:fs";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { z } from "zod";
7
+ import { once } from "node:events";
7
8
  import { basename, delimiter, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
8
- import { randomUUID } from "node:crypto";
9
+ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
9
10
  import { access, copyFile, mkdtemp, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
11
+ import { createServer } from "node:http";
12
+ import { homedir, tmpdir } from "node:os";
10
13
  import { SourceMap, createRequire } from "node:module";
11
14
  import { PROTOCOL_VERSION, RequestError, client, methods, ndJsonStream } from "@agentclientprotocol/sdk";
12
15
  import { spawn } from "node:child_process";
13
16
  import { Writable } from "node:stream";
14
- import { homedir, tmpdir } from "node:os";
17
+ // src/server/guard/request-guard.ts
18
+ const LOOPBACK_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "[::1]"]);
19
+ const LOOPBACK_IPV4 = /^127(?:\.\d{1,3}){3}$/;
20
+ const IPV4_MAPPED_PREFIX = "::ffff:";
21
+ const TRUSTED_FETCH_SITES = /* @__PURE__ */ new Set(["same-origin", "none"]);
22
+ function hostnameOf(request) {
23
+ const host = request.headers.get("host") ?? new URL(request.url).host;
24
+ try {
25
+ return new URL(`http://${host}`).hostname.toLowerCase();
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+ function isLoopbackHostname(hostname) {
31
+ return LOOPBACK_HOSTNAMES.has(hostname) || hostname.endsWith(".localhost") || LOOPBACK_IPV4.test(hostname);
32
+ }
33
+ function isLoopbackAddress(address) {
34
+ if (address === void 0) return false;
35
+ const ipv4 = address.startsWith(IPV4_MAPPED_PREFIX) ? address.slice(7) : address;
36
+ return address === "::1" || LOOPBACK_IPV4.test(ipv4);
37
+ }
38
+ function rejectUntrustedHost(request, allowedHosts) {
39
+ const hostname = hostnameOf(request);
40
+ if (!(hostname !== null && (isLoopbackHostname(hostname) || allowedHosts.includes(hostname)))) return errorResponse("Retouche only answers on localhost. Add other dev hostnames to allowedHosts or RETOUCHE_HOSTS.", 403);
41
+ return null;
42
+ }
43
+ function rejectUntrustedCaller(request, allowedHosts) {
44
+ const sent = request.headers.get(REQUEST_HEADER);
45
+ if (sent === null || sent === "") return errorResponse(`Retouche requests must send the ${REQUEST_HEADER} header.`, 403);
46
+ const fetchSite = request.headers.get("sec-fetch-site");
47
+ const hostname = hostnameOf(request);
48
+ const mayOmitFetchSite = hostname !== null && allowedHosts.includes(hostname) && !isLoopbackHostname(hostname);
49
+ if (!(fetchSite === null ? mayOmitFetchSite : TRUSTED_FETCH_SITES.has(fetchSite))) return errorResponse("Retouche only answers requests from the app's own origin.", 403);
50
+ return null;
51
+ }
52
+ // src/server/guard/pair-listener.ts
53
+ const LISTEN_HOST = "127.0.0.1";
54
+ const listeningSchema = z.object({ port: z.number() });
55
+ const shared = globalThis;
56
+ function portOf(server) {
57
+ const listening = listeningSchema.safeParse(server.address());
58
+ return listening.success ? listening.data.port : 0;
59
+ }
60
+ function originHostname(origin) {
61
+ if (origin === void 0) return null;
62
+ try {
63
+ return new URL(origin).hostname.toLowerCase();
64
+ } catch {
65
+ return null;
66
+ }
67
+ }
68
+ function answerPair(answer, request, response) {
69
+ const { origin } = request.headers;
70
+ const hostname = originHostname(origin);
71
+ const isAppPage = hostname !== null && (isLoopbackHostname(hostname) || answer.allowedHosts.has(hostname));
72
+ const isOwnHost = request.headers.host === `${LISTEN_HOST}:${answer.port}`;
73
+ if (request.method !== "GET" || !isOwnHost || !isAppPage) {
74
+ response.writeHead(403).end();
75
+ return;
76
+ }
77
+ const body = { token: answer.token };
78
+ response.writeHead(200, {
79
+ "access-control-allow-origin": origin,
80
+ "cache-control": "no-store",
81
+ "content-type": "application/json; charset=utf-8",
82
+ vary: "origin"
83
+ }).end(JSON.stringify(body));
84
+ }
85
+ async function listen(allowedHosts) {
86
+ const token = randomBytes(32).toString("base64url");
87
+ const server = createServer((request, response) => {
88
+ answerPair({
89
+ allowedHosts,
90
+ port: portOf(server),
91
+ token
92
+ }, request, response);
93
+ });
94
+ server.listen(0, LISTEN_HOST);
95
+ await once(server, "listening");
96
+ server.unref();
97
+ return {
98
+ port: portOf(server),
99
+ token
100
+ };
101
+ }
102
+ async function startListening(listener) {
103
+ try {
104
+ return await listen(listener.allowedHosts);
105
+ } catch (error) {
106
+ listener.pairing = null;
107
+ throw error;
108
+ }
109
+ }
110
+ async function pairListener(allowedHosts) {
111
+ shared.retouchePairListener ??= {
112
+ allowedHosts: /* @__PURE__ */ new Set(),
113
+ pairing: null
114
+ };
115
+ const listener = shared.retouchePairListener;
116
+ for (const host of allowedHosts) listener.allowedHosts.add(host);
117
+ listener.pairing ??= startListening(listener);
118
+ return await listener.pairing;
119
+ }
120
+ function isToken(sent, token) {
121
+ const sentBytes = Buffer.from(sent ?? "");
122
+ const tokenBytes = Buffer.from(token);
123
+ return sentBytes.length === tokenBytes.length && timingSafeEqual(sentBytes, tokenBytes);
124
+ }
125
+ async function unpairedBody(request, allowedHosts) {
126
+ const { port, token } = await pairListener(allowedHosts);
127
+ return isToken(request.headers.get("x-retouche"), token) ? null : {
128
+ error: "Retouche only answers a page open on the machine running the dev server.",
129
+ pair: port
130
+ };
131
+ }
15
132
  // src/server/voice/agents/agent-backend.ts
16
133
  const AGENT_TIMEOUT_MS = 18e4;
17
134
  const CANCELLED = "Analysis was cancelled.";
@@ -305,14 +422,36 @@ function optionKeyEnvs(voice) {
305
422
  const { agents, transcriber } = parsed.data;
306
423
  return [...agents, transcriber].flatMap((each) => each !== null && "apiKeyEnv" in each && each.apiKeyEnv !== void 0 ? [each.apiKeyEnv] : []);
307
424
  }
308
- function withEnvFiles(files, options) {
425
+ function readsEnv(options) {
309
426
  const read = /* @__PURE__ */ new Set([...PRESET_KEY_ENVS, ...optionKeyEnvs(options.voice)]);
310
- const picked = Object.entries(files).filter(([name]) => name.startsWith(OWN_PREFIX) || read.has(name));
427
+ return (name) => name.startsWith(OWN_PREFIX) || read.has(name);
428
+ }
429
+ function withEnvFiles(files, options) {
430
+ const isRead = readsEnv(options);
431
+ const picked = Object.entries(files).filter(([name]) => isRead(name));
311
432
  return {
312
433
  ...process.env,
313
434
  ...Object.fromEntries(picked)
314
435
  };
315
436
  }
437
+ const APP_ENV_FILES = [
438
+ ".env",
439
+ ".env.local",
440
+ ".env.development",
441
+ ".env.development.local"
442
+ ];
443
+ const ENV_FILE_NAME = /^\s*(?:export\s+)?(?<name>[\w.-]+)\s*=/gmu;
444
+ function envFileNames(root) {
445
+ return new Set(APP_ENV_FILES.flatMap((file) => {
446
+ const path = join(root, file);
447
+ return existsSync(path) ? [...readFileSync(path, "utf-8").matchAll(ENV_FILE_NAME)].flatMap((match) => match.groups?.name ?? []) : [];
448
+ }));
449
+ }
450
+ function withoutEnvFiles(env, options) {
451
+ const isRead = readsEnv(options);
452
+ const fromFiles = envFileNames(resolve(presentValue(options.root) ?? process.cwd()));
453
+ return Object.fromEntries(Object.entries(env).filter(([name]) => !fromFiles.has(name) || isRead(name)));
454
+ }
316
455
  function resolveServerOptions(options, env) {
317
456
  return {
318
457
  allowedHosts: (options.allowedHosts ?? presentValue(env.RETOUCHE_HOSTS)?.split(",") ?? []).map((host) => host.trim().toLowerCase()).filter(Boolean),
@@ -321,45 +460,24 @@ function resolveServerOptions(options, env) {
321
460
  voice: resolveVoice(options.voice)
322
461
  };
323
462
  }
324
- // src/server/request-guard.ts
325
- const LOOPBACK_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "[::1]"]);
326
- const LOOPBACK_IPV4 = /^127(?:\.\d{1,3}){3}$/;
327
- const IPV4_MAPPED_PREFIX = "::ffff:";
328
- const TRUSTED_FETCH_SITES = /* @__PURE__ */ new Set(["same-origin", "none"]);
329
- function hostnameOf(request) {
330
- const host = request.headers.get("host") ?? new URL(request.url).host;
331
- try {
332
- return new URL(`http://${host}`).hostname.toLowerCase();
333
- } catch {
334
- return null;
335
- }
336
- }
337
- function isLoopbackHostname(hostname) {
338
- return LOOPBACK_HOSTNAMES.has(hostname) || hostname.endsWith(".localhost") || LOOPBACK_IPV4.test(hostname);
339
- }
340
- function isLoopbackAddress(address) {
341
- if (address === void 0) return false;
342
- const ipv4 = address.startsWith(IPV4_MAPPED_PREFIX) ? address.slice(7) : address;
343
- return address === "::1" || LOOPBACK_IPV4.test(ipv4);
344
- }
345
- function rejectUntrustedHost(request, allowedHosts) {
346
- const hostname = hostnameOf(request);
347
- if (!(hostname !== null && (isLoopbackHostname(hostname) || allowedHosts.includes(hostname)))) return errorResponse("Retouche only answers on localhost. Add other dev hostnames to allowedHosts or RETOUCHE_HOSTS.", 403);
348
- return null;
349
- }
350
- function rejectUntrustedCaller(request, allowedHosts) {
351
- if (request.headers.get("x-retouche") !== "1") return errorResponse(`Retouche requests must send the ${REQUEST_HEADER} header.`, 403);
352
- const fetchSite = request.headers.get("sec-fetch-site");
353
- const hostname = hostnameOf(request);
354
- const mayOmitFetchSite = hostname !== null && allowedHosts.includes(hostname) && !isLoopbackHostname(hostname);
355
- if (!(fetchSite === null ? mayOmitFetchSite : TRUSTED_FETCH_SITES.has(fetchSite))) return errorResponse("Retouche only answers requests from the app's own origin.", 403);
356
- return null;
463
+ // src/server/source/workspace-path.ts
464
+ function workspaceRelativePath(realPath, workspaceRoot) {
465
+ const relativePath = relative(workspaceRoot, realPath);
466
+ return relativePath === "" || relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath) ? null : relativePath.split(sep).join("/");
357
467
  }
358
468
  // src/server/source/project-roots.ts
469
+ function realPath(path) {
470
+ const resolved = resolve(path);
471
+ return existsSync(resolved) ? realpathSync(resolved) : resolved;
472
+ }
359
473
  function resolveProjectRoots(appRoot) {
360
- const resolvedRoot = resolve(appRoot);
361
- const root = existsSync(resolvedRoot) ? realpathSync(resolvedRoot) : resolvedRoot;
474
+ const root = realPath(appRoot);
475
+ const home = realPath(homedir());
362
476
  for (let directory = root;; directory = dirname(directory)) {
477
+ if (directory === home || workspaceRelativePath(home, directory) !== null) return {
478
+ root,
479
+ workspaceRoot: root
480
+ };
363
481
  if (existsSync(join(directory, ".git"))) return {
364
482
  root,
365
483
  workspaceRoot: directory
@@ -572,11 +690,6 @@ function jsxElementLines(code, line, column) {
572
690
  start: line
573
691
  };
574
692
  }
575
- // src/server/source/workspace-path.ts
576
- function workspaceRelativePath(realPath, workspaceRoot) {
577
- const relativePath = relative(workspaceRoot, realPath);
578
- return relativePath === "" || relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath) ? null : relativePath.split(sep).join("/");
579
- }
580
693
  // src/server/source/server-frame.ts
581
694
  const QUERY_OR_HASH = /[?#].*$/;
582
695
  const SOURCE_MAPPING_URL = /\/\/# sourceMappingURL=(?<url>\S+)\s*$/;
@@ -897,23 +1010,57 @@ function createEndpointBackend(config) {
897
1010
  const READ_ONLY_KINDS = /* @__PURE__ */ new Set(["read", "search"]);
898
1011
  const ALLOW = ["allow_once"];
899
1012
  const REFUSE = ["reject_once", "reject_always"];
900
- function rememberToolKind(toolKinds, update) {
901
- if ((update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") && update.kind) toolKinds.set(update.toolCallId, update.kind);
1013
+ const INPUT_PATH_KEYS = [
1014
+ "path",
1015
+ "file_path",
1016
+ "filePath",
1017
+ "abs_path"
1018
+ ];
1019
+ const rawInputSchema = z.record(z.string(), z.unknown());
1020
+ const pathSchema = z.string();
1021
+ function namedPaths(fields) {
1022
+ const input = rawInputSchema.safeParse(fields.rawInput);
1023
+ const inputPaths = input.success ? INPUT_PATH_KEYS.flatMap((key) => {
1024
+ const path = pathSchema.safeParse(input.data[key]);
1025
+ return path.success ? [path.data] : [];
1026
+ }) : [];
1027
+ return [...(fields.locations ?? []).map((location) => location.path), ...inputPaths];
1028
+ }
1029
+ function seenWith(seen, fields) {
1030
+ return {
1031
+ kind: fields.kind ?? seen?.kind,
1032
+ paths: [...seen?.paths ?? [], ...namedPaths(fields)]
1033
+ };
1034
+ }
1035
+ function rememberToolCall(toolCalls, update) {
1036
+ if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
1037
+ const { toolCallId } = update;
1038
+ toolCalls.set(toolCallId, seenWith(toolCalls.get(toolCallId), update));
1039
+ }
1040
+ }
1041
+ async function insideWorkdir(workdir, path) {
1042
+ const [root, real] = await Promise.all([realpath(workdir), realpath(resolve(workdir, path)).catch(() => null)]);
1043
+ return real !== null && (real === root || workspaceRelativePath(real, root) !== null);
902
1044
  }
903
- function permissionOutcome(request, toolKinds) {
904
- const { kind, toolCallId } = request.toolCall;
905
- const toolKind = kind ?? toolKinds.get(toolCallId);
906
- const option = (toolKind !== void 0 && READ_ONLY_KINDS.has(toolKind) ? ALLOW : REFUSE).map((optionKind) => request.options.find((candidate) => candidate.kind === optionKind)).find((candidate) => candidate !== void 0);
1045
+ async function mayRead(workdir, seen) {
1046
+ if (seen.kind === null || seen.kind === void 0 || !READ_ONLY_KINDS.has(seen.kind) || seen.paths.length === 0) return false;
1047
+ return (await Promise.all(seen.paths.map(async (path) => await insideWorkdir(workdir, path)))).every(Boolean);
1048
+ }
1049
+ function choose(request, wanted) {
1050
+ const option = wanted.map((optionKind) => request.options.find((candidate) => candidate.kind === optionKind)).find((candidate) => candidate !== void 0);
907
1051
  return option === void 0 ? { outcome: "cancelled" } : {
908
1052
  optionId: option.optionId,
909
1053
  outcome: "selected"
910
1054
  };
911
1055
  }
912
- function connectAgent(stream) {
913
- const toolKinds = /* @__PURE__ */ new Map();
1056
+ function connectAgent(stream, workdir) {
1057
+ const toolCalls = /* @__PURE__ */ new Map();
914
1058
  return client({ name: "retouche" }).onNotification(methods.client.session.update, ({ params }) => {
915
- rememberToolKind(toolKinds, params.update);
916
- }).onRequest(methods.client.session.requestPermission, ({ params }) => ({ outcome: permissionOutcome(params, toolKinds) })).connect(stream);
1059
+ rememberToolCall(toolCalls, params.update);
1060
+ }).onRequest(methods.client.session.requestPermission, async ({ params }) => {
1061
+ const { toolCall } = params;
1062
+ return { outcome: choose(params, await mayRead(workdir, seenWith(toolCalls.get(toolCall.toolCallId), toolCall)) ? ALLOW : REFUSE) };
1063
+ }).connect(stream);
917
1064
  }
918
1065
  const KILL_GRACE_MS = 3e3;
919
1066
  function lastLine(text) {
@@ -1246,7 +1393,7 @@ function stopReply(config, stop) {
1246
1393
  }
1247
1394
  async function runAcp(config, call) {
1248
1395
  const agentProcess = startAgentProcess(config, call);
1249
- const connection = connectAgent(agentProcess.stream);
1396
+ const connection = connectAgent(agentProcess.stream, call.workdir);
1250
1397
  const limit = deadline(call.signal);
1251
1398
  const running = {
1252
1399
  config,
@@ -1466,6 +1613,14 @@ function createCliBackend({ agent, cli, command }) {
1466
1613
  } };
1467
1614
  }
1468
1615
  // src/server/voice/agents/cli/codex-cli.ts
1616
+ const CONFIG = [
1617
+ "model_reasoning_effort=\"low\"",
1618
+ "features.shell_tool=false",
1619
+ "features.view_image=false",
1620
+ "features.multi_agent=false",
1621
+ "features.apps=false",
1622
+ "web_search=\"disabled\""
1623
+ ];
1469
1624
  const eventSchema$1 = z.union([
1470
1625
  z.object({
1471
1626
  item: z.object({
@@ -1503,19 +1658,20 @@ const codexCli = {
1503
1658
  prepare: async (prompt, workdir) => {
1504
1659
  const schemaFile = join(workdir, "feedback.schema.json");
1505
1660
  await writeFile(schemaFile, prompt.schemaJson);
1661
+ const imageFiles = await copyImagesInto(workdir, prompt.images);
1506
1662
  return {
1507
1663
  args: [
1508
1664
  "exec",
1509
1665
  "--skip-git-repo-check",
1510
1666
  "--ephemeral",
1667
+ "--ignore-user-config",
1511
1668
  "--sandbox",
1512
1669
  "read-only",
1513
1670
  "--output-schema",
1514
1671
  schemaFile,
1515
1672
  "--json",
1516
- "-c",
1517
- "model_reasoning_effort=\"low\"",
1518
- ...(await copyImagesInto(workdir, prompt.images)).map((file) => `--image=${file}`),
1673
+ ...CONFIG.flatMap((setting) => ["-c", setting]),
1674
+ ...imageFiles.map((file) => `--image=${file}`),
1519
1675
  "-C",
1520
1676
  workdir,
1521
1677
  "-"
@@ -1570,7 +1726,12 @@ const mastracodeCli = {
1570
1726
  "--title",
1571
1727
  "Retouche voice session"
1572
1728
  ],
1573
- env: { MASTRACODE_DISABLE_MCP: "1" },
1729
+ env: {
1730
+ MASTRACODE_DISABLE_MCP: "1",
1731
+ TEMP: workdir,
1732
+ TMP: workdir,
1733
+ TMPDIR: workdir
1734
+ },
1574
1735
  stdin: `${prompt.system}\n\n${prompt.material}\n\n${instructions(prompt)}`
1575
1736
  };
1576
1737
  },
@@ -2728,6 +2889,12 @@ async function routeRequest(request, routes) {
2728
2889
  const route = Object.entries(methods).find(([method]) => method === request.method)?.[1];
2729
2890
  return route ? await route(request) : errorResponse(`${endpoint} only answers ${Object.keys(methods).join(" and ")} requests.`, 405);
2730
2891
  }
2892
+ async function rejectUnpaired(request, allowedHosts) {
2893
+ const unpaired = await unpairedBody(request, allowedHosts);
2894
+ if (unpaired === null) return null;
2895
+ const isStatus = endpointOf(new URL(request.url).pathname) === ENDPOINTS.status;
2896
+ return jsonResponse(unpaired, isStatus ? 200 : 401);
2897
+ }
2731
2898
  function createRouteHandler(options = {}, env = process.env) {
2732
2899
  const settings = resolveServerOptions(options, env);
2733
2900
  let roots = null;
@@ -2749,7 +2916,7 @@ function createRouteHandler(options = {}, env = process.env) {
2749
2916
  ...voice.routes
2750
2917
  };
2751
2918
  return async (request) => {
2752
- const rejection = rejectUntrustedHost(request, settings.allowedHosts) ?? rejectUntrustedCaller(request, settings.allowedHosts);
2919
+ const rejection = rejectUntrustedHost(request, settings.allowedHosts) ?? rejectUntrustedCaller(request, settings.allowedHosts) ?? await rejectUnpaired(request, settings.allowedHosts);
2753
2920
  if (rejection) return rejection;
2754
2921
  try {
2755
2922
  return await routeRequest(request, routes);
@@ -2759,4 +2926,4 @@ function createRouteHandler(options = {}, env = process.env) {
2759
2926
  }
2760
2927
  };
2761
2928
  }
2762
- export { withEnvFiles as a, isLoopbackAddress as i, BODY_LIMIT_ERROR as n, MAX_BODY_BYTES as r, createRouteHandler as t };
2929
+ export { withoutEnvFiles as a, withEnvFiles as i, BODY_LIMIT_ERROR as n, isLoopbackAddress as o, MAX_BODY_BYTES as r, createRouteHandler as t };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  interface LayerProps {
2
2
  config: unknown;
3
3
  rememberDotVisibility?: boolean;
4
+ voice?: boolean;
4
5
  }
5
6
  export declare function Retouche(props: LayerProps): import("react").JSX.Element | null;
6
7
  export {};
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import { c } from "react/compiler-runtime";
3
3
  import { Suspense, lazy, useSyncExternalStore } from "react";
4
4
  import { jsx } from "react/jsx-runtime";
5
5
  // src/retouche.tsx
6
- const Layer = process.env.NODE_ENV === "production" ? null : lazy(async () => await import("./layer-DVJN6vRD.js"));
6
+ const Layer = process.env.NODE_ENV === "production" ? null : lazy(async () => await import("./layer-Ce6QQdAy.js"));
7
7
  function subscribeToNothing() {
8
8
  return () => {};
9
9
  }