retouche-dev 0.0.0-stage → 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.
@@ -0,0 +1,307 @@
1
+ import { z } from "zod";
2
+ // src/protocol.ts
3
+ const ROUTE_BASE = "/api/retouche";
4
+ const REQUEST_HEADER = "x-retouche";
5
+ const ENDPOINTS = {
6
+ source: "/source",
7
+ status: "/status",
8
+ voiceAnalysis: "/voice/analysis",
9
+ voiceFigure: "/voice/figure",
10
+ voiceFollow: "/voice/follow",
11
+ voiceHistory: "/voice/history",
12
+ voiceSession: "/voice/session",
13
+ voiceShot: "/voice/shot",
14
+ voiceKey: "/voice/key",
15
+ voiceStream: "/voice/stream",
16
+ voiceTranscript: "/voice/transcript"
17
+ };
18
+ const EDITORS = [
19
+ "cursor",
20
+ "vscode",
21
+ "webstorm",
22
+ "windsurf",
23
+ "zed"
24
+ ];
25
+ const STATUS_MARKER = "retouche";
26
+ const BUILT_IN_AGENTS = [
27
+ {
28
+ id: "claude",
29
+ name: "Claude Code"
30
+ },
31
+ {
32
+ id: "codex",
33
+ name: "Codex"
34
+ },
35
+ {
36
+ id: "mastracode",
37
+ name: "Mastra Code"
38
+ }
39
+ ];
40
+ const VOICE_ID = /^[\w-]{1,64}$/;
41
+ const voiceIdSchema = z.string().regex(VOICE_ID);
42
+ const voiceAgentSchema = z.object({
43
+ id: voiceIdSchema,
44
+ name: z.string().min(1)
45
+ });
46
+ const listedAgentSchema = voiceAgentSchema.extend({
47
+ kind: z.enum(["command", "endpoint"]),
48
+ state: z.enum([
49
+ "ready",
50
+ "signed-out",
51
+ "unchecked"
52
+ ])
53
+ });
54
+ const TRANSCRIBER_PROVIDERS = [
55
+ "groq",
56
+ "mistral",
57
+ "openai"
58
+ ];
59
+ const TRANSCRIBER_PROVIDER_NAMES = {
60
+ groq: "Groq",
61
+ mistral: "Mistral",
62
+ openai: "OpenAI"
63
+ };
64
+ const STREAMED_TRANSCRIBERS = ["mistral"];
65
+ const transcriberProviderSchema = z.enum(TRANSCRIBER_PROVIDERS);
66
+ const listedTranscriberSchema = z.discriminatedUnion("source", [
67
+ z.object({
68
+ id: voiceIdSchema,
69
+ name: z.string().min(1),
70
+ source: z.literal("config")
71
+ }),
72
+ z.object({
73
+ id: transcriberProviderSchema,
74
+ name: z.string().min(1),
75
+ source: z.literal("saved")
76
+ }),
77
+ z.object({
78
+ id: transcriberProviderSchema,
79
+ keyEnv: z.string().min(1),
80
+ name: z.string().min(1),
81
+ source: z.literal("env")
82
+ })
83
+ ]);
84
+ const routeMarkerSchema = z.object({ marker: z.literal(STATUS_MARKER) });
85
+ const followSetupSchema = z.object({
86
+ command: z.string(),
87
+ project: voiceIdSchema
88
+ });
89
+ const statusSchema = routeMarkerSchema.extend({
90
+ agents: z.array(listedAgentSchema).default([]),
91
+ editor: z.enum(EDITORS),
92
+ follow: followSetupSchema.nullable().default(null),
93
+ transcribers: z.array(listedTranscriberSchema).default([])
94
+ });
95
+ const voiceRectSchema = z.object({
96
+ height: z.number(),
97
+ width: z.number(),
98
+ x: z.number(),
99
+ y: z.number()
100
+ });
101
+ const voiceSiteSchema = z.object({
102
+ absolutePath: z.string().nullable(),
103
+ line: z.number().int().nullable(),
104
+ path: z.string()
105
+ });
106
+ const voiceElementSchema = z.object({
107
+ callSite: voiceSiteSchema.nullable(),
108
+ component: z.string().nullable(),
109
+ componentSite: voiceSiteSchema.nullable(),
110
+ role: z.string().nullable(),
111
+ tag: z.string(),
112
+ text: z.string()
113
+ });
114
+ const voiceMomentSchema = z.object({
115
+ atMs: z.number().nonnegative(),
116
+ durationMs: z.number().nonnegative(),
117
+ element: voiceElementSchema,
118
+ id: voiceIdSchema,
119
+ kind: z.enum(["click", "point"]),
120
+ page: z.string(),
121
+ rect: voiceRectSchema,
122
+ shotId: voiceIdSchema.nullable()
123
+ });
124
+ const wordTimesSchema = z.array(z.number().nonnegative()).max(2e3);
125
+ const voicePassageSchema = z.object({
126
+ endMs: z.number().nonnegative(),
127
+ id: voiceIdSchema,
128
+ momentIds: z.array(voiceIdSchema),
129
+ page: z.string(),
130
+ startMs: z.number().nonnegative(),
131
+ text: z.string(),
132
+ wordMs: wordTimesSchema.optional()
133
+ });
134
+ const voiceShotSchema = z.object({
135
+ atMs: z.number().nonnegative(),
136
+ height: z.number().positive(),
137
+ id: voiceIdSchema,
138
+ page: z.string(),
139
+ width: z.number().positive()
140
+ });
141
+ const voiceStoredShotSchema = voiceShotSchema.extend({ path: z.string() });
142
+ const voiceFeedbackSchema = z.object({
143
+ detail: z.string(),
144
+ figure: z.string().nullable(),
145
+ id: voiceIdSchema,
146
+ momentId: voiceIdSchema.nullable(),
147
+ passageIds: z.array(voiceIdSchema),
148
+ quote: z.string(),
149
+ title: z.string()
150
+ });
151
+ const voiceAnalysisSchema = z.object({
152
+ agent: voiceAgentSchema.nullable(),
153
+ at: z.number().nullable(),
154
+ error: z.string().nullable(),
155
+ passageCount: z.number().int().nonnegative()
156
+ });
157
+ const voiceSessionSchema = z.object({
158
+ analysis: voiceAnalysisSchema,
159
+ dismissed: z.array(voiceFeedbackSchema),
160
+ endedAt: z.number().nullable(),
161
+ feedback: z.array(voiceFeedbackSchema),
162
+ folder: z.string(),
163
+ id: voiceIdSchema,
164
+ language: z.string(),
165
+ moments: z.array(voiceMomentSchema),
166
+ origin: z.string(),
167
+ passages: z.array(voicePassageSchema),
168
+ shots: z.array(voiceStoredShotSchema),
169
+ startedAt: z.number(),
170
+ undoAsked: z.array(voiceIdSchema).default([])
171
+ });
172
+ const voiceSessionRequestSchema = z.discriminatedUnion("kind", [
173
+ z.object({
174
+ kind: z.literal("create"),
175
+ language: z.string().min(1),
176
+ origin: z.string(),
177
+ startedAt: z.number()
178
+ }),
179
+ z.object({
180
+ id: voiceIdSchema,
181
+ kind: z.literal("record"),
182
+ moments: z.array(voiceMomentSchema),
183
+ passages: z.array(voicePassageSchema)
184
+ }),
185
+ z.object({
186
+ endedAt: z.number().nullable(),
187
+ id: voiceIdSchema,
188
+ kind: z.literal("end")
189
+ }),
190
+ z.object({
191
+ feedbackId: voiceIdSchema,
192
+ id: voiceIdSchema,
193
+ kind: z.literal(["dismiss", "undo"])
194
+ })
195
+ ]);
196
+ const voiceSessionSummarySchema = z.object({
197
+ id: voiceIdSchema,
198
+ itemCount: z.number().int().nonnegative(),
199
+ label: z.string(),
200
+ page: z.string().nullable(),
201
+ recordedMs: z.number().nonnegative(),
202
+ startedAt: z.number()
203
+ });
204
+ const voiceHistorySchema = z.object({ sessions: z.array(voiceSessionSummarySchema) });
205
+ const voiceHistoryRequestSchema = z.object({ delete: voiceIdSchema });
206
+ const voiceShotUploadSchema = z.object({
207
+ image: z.string().startsWith("data:image/"),
208
+ session: voiceIdSchema,
209
+ shot: voiceShotSchema
210
+ });
211
+ const voiceFigureUploadSchema = z.object({
212
+ feedback: voiceIdSchema,
213
+ image: z.string().startsWith("data:image/png"),
214
+ moment: voiceIdSchema,
215
+ session: voiceIdSchema
216
+ });
217
+ const voiceAnalysisRequestSchema = z.object({
218
+ agent: voiceIdSchema,
219
+ session: voiceIdSchema
220
+ });
221
+ const voiceTranscriptRequestSchema = z.object({
222
+ audio: z.string().startsWith("data:audio/"),
223
+ transcriber: voiceIdSchema
224
+ });
225
+ const voiceTranscriptSchema = z.object({
226
+ text: z.string(),
227
+ wordOffsetMs: wordTimesSchema.optional()
228
+ });
229
+ const pcmSchema = z.base64().max(2e6);
230
+ const voiceStreamRequestSchema = z.discriminatedUnion("action", [
231
+ z.object({
232
+ action: z.literal("open"),
233
+ audio: pcmSchema,
234
+ language: z.string().max(35),
235
+ phrases: z.array(z.string().max(100)).max(100),
236
+ sampleRate: z.number().int().min(8e3).max(96e3),
237
+ transcriber: voiceIdSchema
238
+ }),
239
+ z.object({
240
+ action: z.literal("append"),
241
+ audio: pcmSchema,
242
+ stream: voiceIdSchema
243
+ }),
244
+ z.object({
245
+ action: z.literal("end"),
246
+ audio: pcmSchema,
247
+ stream: voiceIdSchema
248
+ })
249
+ ]);
250
+ const voiceStreamSchema = z.object({
251
+ stream: voiceIdSchema,
252
+ text: z.string()
253
+ });
254
+ const voiceKeyRequestSchema = z.object({
255
+ key: z.string().trim().min(1).nullable(),
256
+ provider: transcriberProviderSchema
257
+ });
258
+ const voiceKeyAnswerSchema = z.object({ transcribers: z.array(listedTranscriberSchema) });
259
+ const lineRangeSchema = z.object({
260
+ end: z.number().int(),
261
+ start: z.number().int()
262
+ });
263
+ const sourceFileSchema = z.object({
264
+ absolutePath: z.string(),
265
+ code: z.string(),
266
+ column: z.number().int().nullable(),
267
+ elementLines: lineRangeSchema.nullable(),
268
+ line: z.number().int().nullable(),
269
+ path: z.string()
270
+ });
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) });
274
+ const SERVER_FRAME_ORIGIN = "(?:about|rsc)://React/[^/\\s)]+/";
275
+ const SERVER_FRAME_PREFIX = new RegExp(`^${SERVER_FRAME_ORIGIN}`);
276
+ function isServerFrame(fileName) {
277
+ return SERVER_FRAME_PREFIX.test(fileName);
278
+ }
279
+ // src/voice/follow-cards.ts
280
+ const FOLLOW_OUTCOMES = [
281
+ "applied",
282
+ "skipped",
283
+ "reverted"
284
+ ];
285
+ const FOLLOW_STATES = ["working", ...FOLLOW_OUTCOMES];
286
+ const followCardSchema = z.object({
287
+ note: z.string().nullable(),
288
+ state: z.enum(FOLLOW_STATES)
289
+ });
290
+ const voiceFollowSchema = z.object({
291
+ cards: z.record(voiceIdSchema, followCardSchema),
292
+ seenAt: z.number().nullable()
293
+ });
294
+ // src/voice/session-items.ts
295
+ function pendingPassages(session) {
296
+ const covered = new Set(session.feedback.flatMap((item) => item.passageIds));
297
+ return session.passages.filter((passage, index) => index >= session.analysis.passageCount && !covered.has(passage.id));
298
+ }
299
+ // src/clock.ts
300
+ function clock(ms) {
301
+ const seconds = Math.max(0, Math.floor(ms / 1e3));
302
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
303
+ }
304
+ function recordedMs(session) {
305
+ return Math.max(0, ...session.passages.map(({ endMs }) => endMs), ...session.moments.map(({ atMs, durationMs }) => atMs + durationMs), ...session.shots.map(({ atMs }) => atMs));
306
+ }
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 };
@@ -0,0 +1,44 @@
1
+ import { z } from "zod";
2
+ declare const allowEntrySchema: z.ZodObject<{
3
+ classes: z.ZodOptional<z.ZodArray<z.ZodString>>;
4
+ component: z.ZodOptional<z.ZodString>;
5
+ corners: z.ZodOptional<z.ZodLiteral<true>>;
6
+ properties: z.ZodOptional<z.ZodArray<z.ZodEnum<{
7
+ "font-family": "font-family";
8
+ "font-size": "font-size";
9
+ "font-smoothing": "font-smoothing";
10
+ "font-style": "font-style";
11
+ "font-variant-numeric": "font-variant-numeric";
12
+ "font-weight": "font-weight";
13
+ "letter-spacing": "letter-spacing";
14
+ "line-height": "line-height";
15
+ "text-color": "text-color";
16
+ "text-decoration": "text-decoration";
17
+ "text-transform": "text-transform";
18
+ }>>>;
19
+ }, z.core.$strip>;
20
+ export declare const retoucheConfigSchema: z.ZodObject<{
21
+ allow: z.ZodOptional<z.ZodArray<z.ZodObject<{
22
+ classes: z.ZodOptional<z.ZodArray<z.ZodString>>;
23
+ component: z.ZodOptional<z.ZodString>;
24
+ corners: z.ZodOptional<z.ZodLiteral<true>>;
25
+ properties: z.ZodOptional<z.ZodArray<z.ZodEnum<{
26
+ "font-family": "font-family";
27
+ "font-size": "font-size";
28
+ "font-smoothing": "font-smoothing";
29
+ "font-style": "font-style";
30
+ "font-variant-numeric": "font-variant-numeric";
31
+ "font-weight": "font-weight";
32
+ "letter-spacing": "letter-spacing";
33
+ "line-height": "line-height";
34
+ "text-color": "text-color";
35
+ "text-decoration": "text-decoration";
36
+ "text-transform": "text-transform";
37
+ }>>>;
38
+ }, z.core.$strip>>>;
39
+ components: z.ZodArray<z.ZodString>;
40
+ }, z.core.$strip>;
41
+ export type RetoucheConfig = z.infer<typeof retoucheConfigSchema>;
42
+ export type AllowEntry = z.infer<typeof allowEntrySchema>;
43
+ export declare function defineConfig(config: RetoucheConfig): RetoucheConfig;
44
+ export {};
package/dist/config.js ADDED
@@ -0,0 +1 @@
1
+ export { t as defineConfig, n as retoucheConfigSchema } from "./define-config-CepEvVVV.js";
@@ -0,0 +1,17 @@
1
+ import { t as WATCHED_GROUPS } from "./class-groups-DKpPgmHx.js";
2
+ import { z } from "zod";
3
+ // src/rules/define-config.ts
4
+ const allowEntrySchema = z.object({
5
+ classes: z.array(z.string().min(1)).optional(),
6
+ component: z.string().min(1).optional(),
7
+ corners: z.literal(true).optional(),
8
+ properties: z.array(z.enum(WATCHED_GROUPS)).optional()
9
+ }).refine((entry) => (entry.classes ?? []).length > 0 || (entry.properties ?? []).length > 0 || entry.corners === true, { message: "An allow entry needs `classes`, `properties` or `corners` to let anything through." });
10
+ const retoucheConfigSchema = z.object({
11
+ allow: z.array(allowEntrySchema).optional(),
12
+ components: z.array(z.string().min(1)).min(1)
13
+ });
14
+ function defineConfig(config) {
15
+ return config;
16
+ }
17
+ export { retoucheConfigSchema as n, defineConfig as t };
@@ -0,0 +1,271 @@
1
+ import { A as voiceIdSchema, P as voiceSessionSchema, a as followCardSchema, v as VOICE_ID } from "./clock-BJi08VJS.js";
2
+ import { z } from "zod";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { createHash, randomBytes } from "node:crypto";
5
+ import { chmod, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
6
+ // src/server/json-response.ts
7
+ const SAFE_HEADERS = {
8
+ "cache-control": "no-store",
9
+ "x-content-type-options": "nosniff"
10
+ };
11
+ function jsonResponse(body, status = 200) {
12
+ return Response.json(body, {
13
+ headers: {
14
+ ...SAFE_HEADERS,
15
+ "content-type": "application/json; charset=utf-8"
16
+ },
17
+ status
18
+ });
19
+ }
20
+ function imageResponse(bytes, contentType) {
21
+ return new Response(bytes, { headers: {
22
+ ...SAFE_HEADERS,
23
+ "content-type": contentType
24
+ } });
25
+ }
26
+ function errorResponse(error, status) {
27
+ return jsonResponse({ error }, status);
28
+ }
29
+ function failure(error, status) {
30
+ return {
31
+ error,
32
+ ok: false,
33
+ status
34
+ };
35
+ }
36
+ function outcomeResponse(outcome) {
37
+ return outcome.ok ? jsonResponse(outcome.value) : errorResponse(outcome.error, outcome.status);
38
+ }
39
+ // src/server/voice/keyed-queue.ts
40
+ function createKeyedQueue() {
41
+ const tails = /* @__PURE__ */ new Map();
42
+ return async (key, task) => {
43
+ const previous = tails.get(key);
44
+ const { promise: done, resolve } = Promise.withResolvers();
45
+ tails.set(key, done);
46
+ try {
47
+ await previous;
48
+ return await task();
49
+ } finally {
50
+ resolve(null);
51
+ if (tails.get(key) === done) tails.delete(key);
52
+ }
53
+ };
54
+ }
55
+ // src/server/voice/user-folders.ts
56
+ const OWN_FOLDER = "retouche";
57
+ const NON_WORD = /[^\w-]+/g;
58
+ const PLATFORM_DATA = { darwin: join("Library", "Application Support") };
59
+ function isSet(value) {
60
+ return value !== void 0 && value !== "";
61
+ }
62
+ function ownFolder(bases) {
63
+ const base = bases.find(isSet);
64
+ return base === void 0 ? null : join(base, OWN_FOLDER);
65
+ }
66
+ function userConfigFolder(env) {
67
+ const home = isSet(env.HOME) ? join(env.HOME, ".config") : void 0;
68
+ return ownFolder([
69
+ env.XDG_CONFIG_HOME,
70
+ env.APPDATA,
71
+ home
72
+ ]);
73
+ }
74
+ function userDataFolder(env) {
75
+ const data = PLATFORM_DATA[process.platform] ?? join(".local", "share");
76
+ const home = isSet(env.HOME) ? join(env.HOME, data) : void 0;
77
+ return ownFolder([
78
+ env.XDG_DATA_HOME,
79
+ env.LOCALAPPDATA,
80
+ home
81
+ ]);
82
+ }
83
+ function projectId(root) {
84
+ const name = basename(root).replaceAll(NON_WORD, "-").slice(0, 48);
85
+ const hash = createHash("sha256").update(root).digest("hex").slice(0, 8);
86
+ return `${name || "project"}-${hash}`;
87
+ }
88
+ function projectFolder(env, project) {
89
+ const folder = userDataFolder(env);
90
+ return folder === null ? null : join(folder, project);
91
+ }
92
+ async function writePrivateFile(path, data) {
93
+ await mkdir(dirname(path), {
94
+ mode: 448,
95
+ recursive: true
96
+ });
97
+ await writeFile(path, data, { mode: 384 });
98
+ await chmod(path, 384);
99
+ }
100
+ async function replacePrivateFile(path, data) {
101
+ const draft = `${path}.${randomBytes(4).toString("hex")}.tmp`;
102
+ await writePrivateFile(draft, data);
103
+ await rename(draft, path);
104
+ }
105
+ // src/server/voice/session-store.ts
106
+ const SESSION_FILE = "session.json";
107
+ function twoDigits(value) {
108
+ return String(value).padStart(2, "0");
109
+ }
110
+ function sessionId(now) {
111
+ return `${`${now.getFullYear()}${twoDigits(now.getMonth() + 1)}${twoDigits(now.getDate())}`}-${`${twoDigits(now.getHours())}${twoDigits(now.getMinutes())}${twoDigits(now.getSeconds())}`}-${randomBytes(2).toString("hex")}`;
112
+ }
113
+ function blankSession(fields, place) {
114
+ return {
115
+ ...fields,
116
+ ...place,
117
+ analysis: {
118
+ agent: null,
119
+ at: null,
120
+ error: null,
121
+ passageCount: 0
122
+ },
123
+ dismissed: [],
124
+ endedAt: null,
125
+ feedback: [],
126
+ moments: [],
127
+ passages: [],
128
+ shots: [],
129
+ undoAsked: []
130
+ };
131
+ }
132
+ async function readSessionFile(folder) {
133
+ try {
134
+ const text = await readFile(join(folder, SESSION_FILE), "utf-8");
135
+ const parsed = voiceSessionSchema.safeParse(JSON.parse(text));
136
+ return parsed.success ? {
137
+ ...parsed.data,
138
+ folder
139
+ } : null;
140
+ } catch {
141
+ return null;
142
+ }
143
+ }
144
+ async function sessionsIn(base) {
145
+ const names = await readdir(base).catch(() => []);
146
+ return (await Promise.all(names.filter((name) => VOICE_ID.test(name)).map(async (name) => await readSessionFile(join(base, name))))).filter((session) => session !== null).toSorted((first, second) => second.startedAt - first.startedAt);
147
+ }
148
+ const NO_FOLDER = "Retouche found no home folder to keep voice sessions in.";
149
+ var SessionFiles = class {
150
+ #sessions = /* @__PURE__ */ new Map();
151
+ #serialize = createKeyedQueue();
152
+ #baseFolder;
153
+ constructor(baseFolder) {
154
+ this.#baseFolder = baseFolder;
155
+ }
156
+ async read(id) {
157
+ const base = this.#baseFolder();
158
+ if (base === null || !VOICE_ID.test(id)) return null;
159
+ const known = this.#sessions.get(id);
160
+ if (known) return known;
161
+ const loaded = await readSessionFile(join(base, id));
162
+ if (loaded) this.#sessions.set(id, loaded);
163
+ return loaded;
164
+ }
165
+ async create(fields) {
166
+ const base = this.#baseFolder();
167
+ if (base === null) return failure(NO_FOLDER, 500);
168
+ let id = sessionId(/* @__PURE__ */ new Date());
169
+ while (await this.read(id)) id = sessionId(/* @__PURE__ */ new Date());
170
+ const session = blankSession(fields, {
171
+ folder: join(base, id),
172
+ id
173
+ });
174
+ this.#sessions.set(id, session);
175
+ await replacePrivateFile(join(session.folder, SESSION_FILE), JSON.stringify(session));
176
+ return {
177
+ ok: true,
178
+ value: session
179
+ };
180
+ }
181
+ async list() {
182
+ const base = this.#baseFolder();
183
+ const sessions = base === null ? [] : await sessionsIn(base);
184
+ const kept = new Set(sessions.map(({ id }) => id));
185
+ for (const id of this.#sessions.keys()) if (!kept.has(id)) this.#sessions.delete(id);
186
+ return sessions;
187
+ }
188
+ async remove(id) {
189
+ return await this.#serialize(id, async () => {
190
+ const session = await this.read(id);
191
+ if (!session) return failure(`No voice session ${id}.`, 404);
192
+ this.#sessions.delete(id);
193
+ await rm(session.folder, {
194
+ force: true,
195
+ recursive: true
196
+ });
197
+ return {
198
+ ok: true,
199
+ value: null
200
+ };
201
+ });
202
+ }
203
+ async update(id, change) {
204
+ return await this.#serialize(id, async () => {
205
+ const session = await this.read(id);
206
+ if (!session) return failure(`No voice session ${id}.`, 404);
207
+ const outcome = await change(session);
208
+ if (outcome.ok && outcome.value !== session) {
209
+ await replacePrivateFile(join(session.folder, SESSION_FILE), JSON.stringify(outcome.value));
210
+ this.#sessions.set(id, outcome.value);
211
+ }
212
+ return outcome;
213
+ });
214
+ }
215
+ };
216
+ // src/server/voice/follow/follow-files.ts
217
+ const FOLLOW_FILE = "follow.json";
218
+ const FOLLOWER_FILE = "follower.json";
219
+ const sentCardSchema = z.object({
220
+ detail: z.string(),
221
+ quote: z.string(),
222
+ title: z.string()
223
+ });
224
+ const followedCardSchema = followCardSchema.extend({
225
+ at: z.number(),
226
+ sent: sentCardSchema,
227
+ undoSent: z.boolean()
228
+ });
229
+ const followFileSchema = z.object({
230
+ cards: z.record(voiceIdSchema, followedCardSchema),
231
+ closedAt: z.number().nullable()
232
+ });
233
+ const followerSchema = z.object({
234
+ seenAt: z.number(),
235
+ session: voiceIdSchema.nullable()
236
+ });
237
+ const EMPTY_FOLLOW = {
238
+ cards: {},
239
+ closedAt: null
240
+ };
241
+ async function readJsonFile(path, schema) {
242
+ try {
243
+ const parsed = schema.safeParse(JSON.parse(await readFile(path, "utf-8")));
244
+ return parsed.success ? parsed.data : null;
245
+ } catch {
246
+ return null;
247
+ }
248
+ }
249
+ async function readFollow(sessionFolder) {
250
+ return await readJsonFile(join(sessionFolder, FOLLOW_FILE), followFileSchema);
251
+ }
252
+ async function writeFollow(sessionFolder, follow) {
253
+ await replacePrivateFile(join(sessionFolder, FOLLOW_FILE), JSON.stringify(follow));
254
+ }
255
+ async function readFollower(projectFolder) {
256
+ return await readJsonFile(join(projectFolder, FOLLOWER_FILE), followerSchema);
257
+ }
258
+ async function writeFollower(projectFolder, follower) {
259
+ await replacePrivateFile(join(projectFolder, FOLLOWER_FILE), JSON.stringify(follower));
260
+ }
261
+ async function newestSession(projectFolder) {
262
+ const [newest] = (await readdir(projectFolder).catch(() => [])).filter((name) => VOICE_ID.test(name)).toSorted().toReversed();
263
+ return newest === void 0 ? null : await readSessionFile(join(projectFolder, newest));
264
+ }
265
+ async function followedSession(projectFolder) {
266
+ const newest = await newestSession(projectFolder);
267
+ if (newest === null || newest.endedAt === null) return newest;
268
+ const follow = await readFollow(newest.folder);
269
+ return follow !== null && follow.closedAt === null ? newest : null;
270
+ }
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 };