retouche-dev 0.1.0 → 0.1.2

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 { _ as failure, a as writeFollow, 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-Dcya6bMQ.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";
@@ -36,12 +36,26 @@ function failure(error, status) {
36
36
  function outcomeResponse(outcome) {
37
37
  return outcome.ok ? jsonResponse(outcome.value) : errorResponse(outcome.error, outcome.status);
38
38
  }
39
+ // src/server/deferred.ts
40
+ const unsettled = () => {};
41
+ function deferred() {
42
+ let settle = unsettled;
43
+ let fail = unsettled;
44
+ return {
45
+ promise: new Promise((resolve, reject) => {
46
+ settle = resolve;
47
+ fail = reject;
48
+ }),
49
+ reject: fail,
50
+ resolve: settle
51
+ };
52
+ }
39
53
  // src/server/voice/keyed-queue.ts
40
54
  function createKeyedQueue() {
41
55
  const tails = /* @__PURE__ */ new Map();
42
56
  return async (key, task) => {
43
57
  const previous = tails.get(key);
44
- const { promise: done, resolve } = Promise.withResolvers();
58
+ const { promise: done, resolve } = deferred();
45
59
  tails.set(key, done);
46
60
  try {
47
61
  await previous;
@@ -268,4 +282,4 @@ async function followedSession(projectFolder) {
268
282
  const follow = await readFollow(newest.folder);
269
283
  return follow !== null && follow.closedAt === null ? newest : null;
270
284
  }
271
- export { imageResponse as _, writeFollow as a, SessionFiles as c, projectId as d, userConfigFolder as f, failure as g, errorResponse as h, readFollower as i, readSessionFile as l, createKeyedQueue as m, followedSession as n, writeFollower as o, writePrivateFile as p, readFollow as r, NO_FOLDER as s, EMPTY_FOLLOW as t, projectFolder as u, jsonResponse as v, outcomeResponse as y };
285
+ export { failure as _, writeFollow as a, outcomeResponse as b, SessionFiles as c, projectId as d, userConfigFolder as f, errorResponse as g, deferred as h, readFollower as i, readSessionFile as l, createKeyedQueue as m, followedSession as n, writeFollower as o, writePrivateFile as p, readFollow as r, NO_FOLDER as s, EMPTY_FOLLOW as t, projectFolder as u, imageResponse as v, jsonResponse as y };
@@ -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 failure$1, b as outcomeResponse, c as SessionFiles, d as projectId, f as userConfigFolder, g as errorResponse, h as deferred, i as readFollower, m as createKeyedQueue, p as writePrivateFile, r as readFollow, u as projectFolder, v as imageResponse, y as jsonResponse } from "./follow-files-Dcya6bMQ.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,37 @@ 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
+ const ENV_FILE_NAME = /^\s*(?:export\s+)?(?<name>[\w.-]+)(?:\s*=|:\s)/gmu;
430
+ function envFileNames({ folders, mode }) {
431
+ const files = [
432
+ ".env",
433
+ ".env.local",
434
+ `.env.${mode}`,
435
+ `.env.${mode}.local`
436
+ ];
437
+ const paths = folders.flatMap((folder) => files.map((file) => join(folder, file)));
438
+ return new Set(paths.flatMap((path) => existsSync(path) ? [...readFileSync(path, "utf-8").matchAll(ENV_FILE_NAME)].flatMap((match) => match.groups?.name ?? []) : []));
439
+ }
440
+ function withoutNames(env, drop) {
441
+ return Object.fromEntries(Object.entries(env).filter(([name]) => !drop(name)));
442
+ }
443
+ function appEnvs(loaded, files, options) {
444
+ const isRead = readsEnv(options);
445
+ const fromFiles = envFileNames(files);
446
+ const env = withoutNames(loaded, (name) => fromFiles.has(name) && !isRead(name));
311
447
  return {
312
- ...process.env,
313
- ...Object.fromEntries(picked)
448
+ env,
449
+ spawnEnv: withoutNames(env, (name) => fromFiles.has(name) && !name.startsWith(OWN_PREFIX))
314
450
  };
315
451
  }
452
+ function appEnvFolders(options) {
453
+ const root = resolve(presentValue(options.root) ?? process.cwd());
454
+ return [.../* @__PURE__ */ new Set([process.cwd(), root])];
455
+ }
316
456
  function resolveServerOptions(options, env) {
317
457
  return {
318
458
  allowedHosts: (options.allowedHosts ?? presentValue(env.RETOUCHE_HOSTS)?.split(",") ?? []).map((host) => host.trim().toLowerCase()).filter(Boolean),
@@ -321,45 +461,24 @@ function resolveServerOptions(options, env) {
321
461
  voice: resolveVoice(options.voice)
322
462
  };
323
463
  }
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;
464
+ // src/server/source/workspace-path.ts
465
+ function workspaceRelativePath(realPath, workspaceRoot) {
466
+ const relativePath = relative(workspaceRoot, realPath);
467
+ return relativePath === "" || relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath) ? null : relativePath.split(sep).join("/");
357
468
  }
358
469
  // src/server/source/project-roots.ts
470
+ function realPath(path) {
471
+ const resolved = resolve(path);
472
+ return existsSync(resolved) ? realpathSync(resolved) : resolved;
473
+ }
359
474
  function resolveProjectRoots(appRoot) {
360
- const resolvedRoot = resolve(appRoot);
361
- const root = existsSync(resolvedRoot) ? realpathSync(resolvedRoot) : resolvedRoot;
475
+ const root = realPath(appRoot);
476
+ const home = realPath(homedir());
362
477
  for (let directory = root;; directory = dirname(directory)) {
478
+ if (directory === home || workspaceRelativePath(home, directory) !== null) return {
479
+ root,
480
+ workspaceRoot: root
481
+ };
363
482
  if (existsSync(join(directory, ".git"))) return {
364
483
  root,
365
484
  workspaceRoot: directory
@@ -572,11 +691,6 @@ function jsxElementLines(code, line, column) {
572
691
  start: line
573
692
  };
574
693
  }
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
694
  // src/server/source/server-frame.ts
581
695
  const QUERY_OR_HASH = /[?#].*$/;
582
696
  const SOURCE_MAPPING_URL = /\/\/# sourceMappingURL=(?<url>\S+)\s*$/;
@@ -879,8 +993,8 @@ async function chatRequest(config, prompt) {
879
993
  }
880
994
  });
881
995
  }
882
- function createEndpointBackend(config) {
883
- return { run: async ({ env, prompt, signal }) => {
996
+ function createEndpointBackend(config, env) {
997
+ return { run: async ({ prompt, signal }) => {
884
998
  const reply = await callEndpoint({
885
999
  answer: chatCompletionSchema,
886
1000
  body: await chatRequest(config, prompt),
@@ -897,23 +1011,57 @@ function createEndpointBackend(config) {
897
1011
  const READ_ONLY_KINDS = /* @__PURE__ */ new Set(["read", "search"]);
898
1012
  const ALLOW = ["allow_once"];
899
1013
  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);
1014
+ const INPUT_PATH_KEYS = [
1015
+ "path",
1016
+ "file_path",
1017
+ "filePath",
1018
+ "abs_path"
1019
+ ];
1020
+ const rawInputSchema = z.record(z.string(), z.unknown());
1021
+ const pathSchema = z.string();
1022
+ function namedPaths(fields) {
1023
+ const input = rawInputSchema.safeParse(fields.rawInput);
1024
+ const inputPaths = input.success ? INPUT_PATH_KEYS.flatMap((key) => {
1025
+ const path = pathSchema.safeParse(input.data[key]);
1026
+ return path.success ? [path.data] : [];
1027
+ }) : [];
1028
+ return [...(fields.locations ?? []).map((location) => location.path), ...inputPaths];
1029
+ }
1030
+ function seenWith(seen, fields) {
1031
+ return {
1032
+ kind: fields.kind ?? seen?.kind,
1033
+ paths: [...seen?.paths ?? [], ...namedPaths(fields)]
1034
+ };
1035
+ }
1036
+ function rememberToolCall(toolCalls, update) {
1037
+ if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
1038
+ const { toolCallId } = update;
1039
+ toolCalls.set(toolCallId, seenWith(toolCalls.get(toolCallId), update));
1040
+ }
1041
+ }
1042
+ async function insideWorkdir(workdir, path) {
1043
+ const [root, real] = await Promise.all([realpath(workdir), realpath(resolve(workdir, path)).catch(() => null)]);
1044
+ return real !== null && (real === root || workspaceRelativePath(real, root) !== null);
1045
+ }
1046
+ async function mayRead(workdir, seen) {
1047
+ if (seen.kind === null || seen.kind === void 0 || !READ_ONLY_KINDS.has(seen.kind) || seen.paths.length === 0) return false;
1048
+ return (await Promise.all(seen.paths.map(async (path) => await insideWorkdir(workdir, path)))).every(Boolean);
902
1049
  }
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);
1050
+ function choose(request, wanted) {
1051
+ const option = wanted.map((optionKind) => request.options.find((candidate) => candidate.kind === optionKind)).find((candidate) => candidate !== void 0);
907
1052
  return option === void 0 ? { outcome: "cancelled" } : {
908
1053
  optionId: option.optionId,
909
1054
  outcome: "selected"
910
1055
  };
911
1056
  }
912
- function connectAgent(stream) {
913
- const toolKinds = /* @__PURE__ */ new Map();
1057
+ function connectAgent(stream, workdir) {
1058
+ const toolCalls = /* @__PURE__ */ new Map();
914
1059
  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);
1060
+ rememberToolCall(toolCalls, params.update);
1061
+ }).onRequest(methods.client.session.requestPermission, async ({ params }) => {
1062
+ const { toolCall } = params;
1063
+ return { outcome: choose(params, await mayRead(workdir, seenWith(toolCalls.get(toolCall.toolCallId), toolCall)) ? ALLOW : REFUSE) };
1064
+ }).connect(stream);
917
1065
  }
918
1066
  const KILL_GRACE_MS = 3e3;
919
1067
  function lastLine(text) {
@@ -953,7 +1101,7 @@ function createStopper(child) {
953
1101
  };
954
1102
  }
955
1103
  async function runProcess(call) {
956
- const { promise, resolve } = Promise.withResolvers();
1104
+ const { promise, resolve } = deferred();
957
1105
  const child = spawn(call.command, call.args, {
958
1106
  cwd: call.cwd,
959
1107
  env: agentEnv(call.env),
@@ -1032,8 +1180,8 @@ function watchExit(child) {
1032
1180
  child.stderr.setEncoding("utf-8").on("data", (chunk) => {
1033
1181
  stderr = (stderr + chunk).slice(-4096);
1034
1182
  });
1035
- const exit = Promise.withResolvers();
1036
- const ended = Promise.withResolvers();
1183
+ const exit = deferred();
1184
+ const ended = deferred();
1037
1185
  child.once("error", (error) => {
1038
1186
  ended.resolve(null);
1039
1187
  exit.resolve({
@@ -1192,7 +1340,7 @@ function failure(error) {
1192
1340
  };
1193
1341
  }
1194
1342
  function deadline(signal) {
1195
- const { promise, resolve } = Promise.withResolvers();
1343
+ const { promise, resolve } = deferred();
1196
1344
  const onAbort = () => {
1197
1345
  resolve("aborted");
1198
1346
  };
@@ -1236,7 +1384,7 @@ async function cancelTurn(running) {
1236
1384
  const { connection, sessionId } = running;
1237
1385
  if (sessionId === null || connection.signal.aborted) return;
1238
1386
  await connection.agent.notify(methods.agent.session.cancel, { sessionId }).catch(() => null);
1239
- const { promise, resolve } = Promise.withResolvers();
1387
+ const { promise, resolve } = deferred();
1240
1388
  const timer = setTimeout(resolve, CANCEL_GRACE_MS, null);
1241
1389
  await Promise.race([running.turn.catch(() => null), promise]);
1242
1390
  clearTimeout(timer);
@@ -1246,7 +1394,7 @@ function stopReply(config, stop) {
1246
1394
  }
1247
1395
  async function runAcp(config, call) {
1248
1396
  const agentProcess = startAgentProcess(config, call);
1249
- const connection = connectAgent(agentProcess.stream);
1397
+ const connection = connectAgent(agentProcess.stream, call.workdir);
1250
1398
  const limit = deadline(call.signal);
1251
1399
  const running = {
1252
1400
  config,
@@ -1466,6 +1614,14 @@ function createCliBackend({ agent, cli, command }) {
1466
1614
  } };
1467
1615
  }
1468
1616
  // src/server/voice/agents/cli/codex-cli.ts
1617
+ const CONFIG = [
1618
+ "model_reasoning_effort=\"low\"",
1619
+ "features.shell_tool=false",
1620
+ "features.view_image=false",
1621
+ "features.multi_agent=false",
1622
+ "features.apps=false",
1623
+ "web_search=\"disabled\""
1624
+ ];
1469
1625
  const eventSchema$1 = z.union([
1470
1626
  z.object({
1471
1627
  item: z.object({
@@ -1503,19 +1659,20 @@ const codexCli = {
1503
1659
  prepare: async (prompt, workdir) => {
1504
1660
  const schemaFile = join(workdir, "feedback.schema.json");
1505
1661
  await writeFile(schemaFile, prompt.schemaJson);
1662
+ const imageFiles = await copyImagesInto(workdir, prompt.images);
1506
1663
  return {
1507
1664
  args: [
1508
1665
  "exec",
1509
1666
  "--skip-git-repo-check",
1510
1667
  "--ephemeral",
1668
+ "--ignore-user-config",
1511
1669
  "--sandbox",
1512
1670
  "read-only",
1513
1671
  "--output-schema",
1514
1672
  schemaFile,
1515
1673
  "--json",
1516
- "-c",
1517
- "model_reasoning_effort=\"low\"",
1518
- ...(await copyImagesInto(workdir, prompt.images)).map((file) => `--image=${file}`),
1674
+ ...CONFIG.flatMap((setting) => ["-c", setting]),
1675
+ ...imageFiles.map((file) => `--image=${file}`),
1519
1676
  "-C",
1520
1677
  workdir,
1521
1678
  "-"
@@ -1570,7 +1727,12 @@ const mastracodeCli = {
1570
1727
  "--title",
1571
1728
  "Retouche voice session"
1572
1729
  ],
1573
- env: { MASTRACODE_DISABLE_MCP: "1" },
1730
+ env: {
1731
+ MASTRACODE_DISABLE_MCP: "1",
1732
+ TEMP: workdir,
1733
+ TMP: workdir,
1734
+ TMPDIR: workdir
1735
+ },
1574
1736
  stdin: `${prompt.system}\n\n${prompt.material}\n\n${instructions(prompt)}`
1575
1737
  };
1576
1738
  },
@@ -1619,18 +1781,18 @@ async function builtInAgent({ id, name }, env) {
1619
1781
  kind: "command"
1620
1782
  };
1621
1783
  }
1622
- async function configuredAgent(config, env) {
1784
+ async function configuredAgent(config, { env, spawnEnv }) {
1623
1785
  const agent = {
1624
1786
  id: agentIdOf(config.name),
1625
1787
  name: config.name
1626
1788
  };
1627
1789
  if (config.kind === "endpoint") return isEndpointReady(config, env) ? {
1628
1790
  agent,
1629
- backend: createEndpointBackend(config),
1791
+ backend: createEndpointBackend(config, env),
1630
1792
  checkSignIn: null,
1631
1793
  kind: "endpoint"
1632
1794
  } : null;
1633
- const command = await findCommand(config.command, env);
1795
+ const command = await findCommand(config.command, spawnEnv);
1634
1796
  return command === null ? null : {
1635
1797
  agent,
1636
1798
  backend: createAcpBackend({
@@ -1641,8 +1803,11 @@ async function configuredAgent(config, env) {
1641
1803
  kind: "command"
1642
1804
  };
1643
1805
  }
1644
- async function findAvailable({ agents, env }) {
1645
- return (await Promise.all([...BUILT_IN_AGENTS.map(async (agent) => await builtInAgent(agent, env)), ...agents.map(async (config) => await configuredAgent(config, env))])).filter((entry) => entry !== null);
1806
+ async function findAvailable({ agents, env, spawnEnv }) {
1807
+ return (await Promise.all([...BUILT_IN_AGENTS.map(async (agent) => await builtInAgent(agent, spawnEnv)), ...agents.map(async (config) => await configuredAgent(config, {
1808
+ env,
1809
+ spawnEnv
1810
+ }))])).filter((entry) => entry !== null);
1646
1811
  }
1647
1812
  async function listAgents(registered) {
1648
1813
  return await Promise.all(registered.map(async ({ agent, checkSignIn, kind }) => ({
@@ -2390,7 +2555,7 @@ var MistralStream = class {
2390
2555
  #keyOrigin;
2391
2556
  #chunkBytes;
2392
2557
  #session;
2393
- #done = Promise.withResolvers();
2558
+ #done = deferred();
2394
2559
  #queued = [];
2395
2560
  #text = "";
2396
2561
  #failure = null;
@@ -2644,15 +2809,16 @@ function transcriptionRoutes(transcription) {
2644
2809
  };
2645
2810
  }
2646
2811
  function createVoiceRoutes(context) {
2647
- const { env, voice } = context;
2812
+ const { env, spawnEnv, voice } = context;
2648
2813
  const store = new SessionFiles(() => projectFolder(env, projectId(context.root())));
2649
2814
  const agents = createAgentRegistry({
2650
2815
  agents: voice.agents,
2651
- env
2816
+ env,
2817
+ spawnEnv
2652
2818
  });
2653
2819
  const analyze = createAnalyzer({
2654
2820
  agents,
2655
- env,
2821
+ env: spawnEnv,
2656
2822
  store
2657
2823
  });
2658
2824
  const transcription = {
@@ -2728,7 +2894,13 @@ async function routeRequest(request, routes) {
2728
2894
  const route = Object.entries(methods).find(([method]) => method === request.method)?.[1];
2729
2895
  return route ? await route(request) : errorResponse(`${endpoint} only answers ${Object.keys(methods).join(" and ")} requests.`, 405);
2730
2896
  }
2731
- function createRouteHandler(options = {}, env = process.env) {
2897
+ async function rejectUnpaired(request, allowedHosts) {
2898
+ const unpaired = await unpairedBody(request, allowedHosts);
2899
+ if (unpaired === null) return null;
2900
+ const isStatus = endpointOf(new URL(request.url).pathname) === ENDPOINTS.status;
2901
+ return jsonResponse(unpaired, isStatus ? 200 : 401);
2902
+ }
2903
+ function createRouteHandler(options = {}, env = process.env, spawnEnv = env) {
2732
2904
  const settings = resolveServerOptions(options, env);
2733
2905
  let roots = null;
2734
2906
  const projectRoots = () => {
@@ -2738,6 +2910,7 @@ function createRouteHandler(options = {}, env = process.env) {
2738
2910
  const voice = createVoiceRoutes({
2739
2911
  env,
2740
2912
  root: () => projectRoots().root,
2913
+ spawnEnv,
2741
2914
  voice: settings.voice
2742
2915
  });
2743
2916
  const routes = {
@@ -2749,7 +2922,7 @@ function createRouteHandler(options = {}, env = process.env) {
2749
2922
  ...voice.routes
2750
2923
  };
2751
2924
  return async (request) => {
2752
- const rejection = rejectUntrustedHost(request, settings.allowedHosts) ?? rejectUntrustedCaller(request, settings.allowedHosts);
2925
+ const rejection = rejectUntrustedHost(request, settings.allowedHosts) ?? rejectUntrustedCaller(request, settings.allowedHosts) ?? await rejectUnpaired(request, settings.allowedHosts);
2753
2926
  if (rejection) return rejection;
2754
2927
  try {
2755
2928
  return await routeRequest(request, routes);
@@ -2759,4 +2932,4 @@ function createRouteHandler(options = {}, env = process.env) {
2759
2932
  }
2760
2933
  };
2761
2934
  }
2762
- export { withEnvFiles as a, isLoopbackAddress as i, BODY_LIMIT_ERROR as n, MAX_BODY_BYTES as r, createRouteHandler as t };
2935
+ export { appEnvs as a, appEnvFolders 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-Bw5Xt2p7.js"));
7
7
  function subscribeToNothing() {
8
8
  return () => {};
9
9
  }