Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeCrypto from "node:crypto";
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5
6import type { ChatAttachment } from "@t3tools/contracts";
7import { htmlRenderFromToolItem, mcpAppFromToolItem } from "@t3tools/shared/toolOutput";
8
9import {
10 normalizeAttachmentRelativePath,
11 resolveAttachmentRelativePath,
12} from "./attachmentPaths.ts";
13import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
14
15const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
16const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
17const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
18const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
19const ATTACHMENT_ID_FILE_EXTENSION_PATTERN = "[a-z0-9]{1,10}";
20const ATTACHMENT_ID_PATTERN = new RegExp(
21 `^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})(?:-(${ATTACHMENT_ID_FILE_EXTENSION_PATTERN}))?$`,
22 "i",
23);
24
25export const PENDING_ATTACHMENT_THREAD_SEGMENT = "pending";
26const PENDING_ATTACHMENT_MAX_AGE_MS = 24 * 60 * 60 * 1000;
27const PARTIAL_UPLOAD_MAX_AGE_MS = 60 * 60 * 1000;
28
29export function toSafeThreadAttachmentSegment(threadId: string): string | null {
30 const segment = threadId
31 .trim()
32 .toLowerCase()
33 .replace(/[^a-z0-9_-]+/gi, "-")
34 .replace(/-+/g, "-")
35 .replace(/^[-_]+|[-_]+$/g, "")
36 .slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)
37 .replace(/[-_]+$/g, "");
38 if (segment.length === 0) {
39 return null;
40 }
41 return segment === PENDING_ATTACHMENT_THREAD_SEGMENT ? "_pending" : segment;
42}
43
44export function attachmentFileExtension(fileName: string): string {
45 const extension = NodePath.extname(fileName).toLowerCase();
46 // .part is reserved for pending uploads; the stale-upload sweep would delete stored files.
47 if (extension === ".part" || !/^\.[a-z0-9]{1,10}$/.test(extension)) {
48 return ".bin";
49 }
50 return extension;
51}
52
53function attachmentIdExtensionSuffix(extension: string | undefined): string {
54 if (!extension) {
55 return "";
56 }
57 const normalized = extension.replace(/^\./, "").toLowerCase();
58 return new RegExp(`^${ATTACHMENT_ID_FILE_EXTENSION_PATTERN}$`).test(normalized)
59 ? `-${normalized}`
60 : "-bin";
61}
62
63export function createPendingAttachmentId(extension?: string): string {
64 return `${PENDING_ATTACHMENT_THREAD_SEGMENT}-${NodeCrypto.randomUUID()}${attachmentIdExtensionSuffix(extension)}`;
65}
66
67export function parseAttachmentUuid(attachmentId: string): string | null {
68 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
69 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
70 return null;
71 }
72 return normalizedId.match(ATTACHMENT_ID_PATTERN)?.[2]?.toLowerCase() ?? null;
73}
74
75export function parseAttachmentFileExtension(attachmentId: string): string | null {
76 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
77 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
78 return null;
79 }
80 return normalizedId.match(ATTACHMENT_ID_PATTERN)?.[3]?.toLowerCase() ?? null;
81}
82
83export function createAttachmentId(threadId: string, extension?: string): string | null {
84 const threadSegment = toSafeThreadAttachmentSegment(threadId);
85 if (!threadSegment) {
86 return null;
87 }
88 return `${threadSegment}-${NodeCrypto.randomUUID()}${attachmentIdExtensionSuffix(extension)}`;
89}
90
91export function createDeterministicAttachmentId(
92 threadId: string,
93 stableKey: string,
94): string | null {
95 const threadSegment = toSafeThreadAttachmentSegment(threadId);
96 if (!threadSegment) return null;
97 const hash = NodeCrypto.createHash("sha256")
98 .update(JSON.stringify([threadId, stableKey]))
99 .digest("hex")
100 .slice(0, 32);
101 const uuid = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20)}`;
102 return `${threadSegment}-${uuid}`;
103}
104
105/** Retries keep ids; changed bytes must get new ids because clients cache images by id. */
106export function chatAttachmentStableKey(
107 messageId: string,
108 index: number,
109 bytes: Uint8Array,
110): string {
111 const digest = NodeCrypto.createHash("sha256").update(bytes).digest("hex");
112 return `${messageId}:${index}:${digest}`;
113}
114
115export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
116 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
117 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
118 return null;
119 }
120 const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
121 if (!match) {
122 return null;
123 }
124 return match[1]?.toLowerCase() ?? null;
125}
126
127/** Only this thread's ids qualify, preserving source pages when deleting a fork. */
128export function threadHtmlRenderAttachmentIds(
129 threadId: string,
130 items: Iterable<{ readonly toolName: string | null | undefined; readonly output?: unknown }>,
131) {
132 const segment = toSafeThreadAttachmentSegment(threadId);
133 if (segment === null) return [];
134 return Array.from(items).flatMap((item) => {
135 const attachmentId =
136 htmlRenderFromToolItem(item)?.attachmentId ?? mcpAppFromToolItem(item)?.attachmentId;
137 return attachmentId !== undefined &&
138 parseThreadSegmentFromAttachmentId(attachmentId) === segment
139 ? [attachmentId]
140 : [];
141 });
142}
143
144export function attachmentRelativePath(attachment: ChatAttachment): string | null {
145 switch (attachment.type) {
146 case "image": {
147 const extension = inferImageExtension({
148 mimeType: attachment.mimeType,
149 fileName: attachment.name,
150 });
151 return `${attachment.id}${extension}`;
152 }
153 case "file":
154 return `${attachment.id}${attachmentFileExtension(attachment.name)}`;
155 default:
156 return null;
157 }
158}
159
160export function resolveAttachmentPath(input: {
161 readonly attachmentsDir: string;
162 readonly attachment: ChatAttachment;
163}): string | null {
164 const relativePath = attachmentRelativePath(input.attachment);
165 if (!relativePath) {
166 return null;
167 }
168 return resolveAttachmentRelativePath({
169 attachmentsDir: input.attachmentsDir,
170 relativePath,
171 });
172}
173
174export function resolveAttachmentPathById(input: {
175 readonly attachmentsDir: string;
176 readonly attachmentId: string;
177}): string | null {
178 const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
179 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
180 return null;
181 }
182 const fileExtension = parseAttachmentFileExtension(normalizedId);
183 if (fileExtension) {
184 const filePath = resolveAttachmentRelativePath({
185 attachmentsDir: input.attachmentsDir,
186 relativePath: `${normalizedId}.${fileExtension.toLowerCase()}`,
187 });
188 return filePath && NodeFS.existsSync(filePath) ? filePath : null;
189 }
190 for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
191 const maybePath = resolveAttachmentRelativePath({
192 attachmentsDir: input.attachmentsDir,
193 relativePath: `${normalizedId}${extension}`,
194 });
195 if (maybePath && NodeFS.existsSync(maybePath)) {
196 return maybePath;
197 }
198 }
199 return null;
200}
201
202export type AttachmentClaimPlan =
203 | {
204 readonly ok: true;
205 readonly finalId: string;
206 readonly currentPath: string;
207 readonly finalPath: string;
208 }
209 | { readonly ok: false; readonly reason: string };
210
211export function planAttachmentClaim(input: {
212 readonly attachmentsDir: string;
213 readonly threadId: string;
214 readonly attachmentId: string;
215}): AttachmentClaimPlan {
216 const uuid = parseAttachmentUuid(input.attachmentId);
217 const requestedSegment = parseThreadSegmentFromAttachmentId(input.attachmentId);
218 if (!uuid || !requestedSegment) {
219 return { ok: false, reason: "invalid attachment id" };
220 }
221
222 if (!toSafeThreadAttachmentSegment(input.threadId)) {
223 return { ok: false, reason: "invalid thread id" };
224 }
225 if (requestedSegment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
226 return { ok: false, reason: "attachment must be a pending upload" };
227 }
228
229 const currentPath = resolveAttachmentPathById({
230 attachmentsDir: input.attachmentsDir,
231 attachmentId: input.attachmentId,
232 });
233 if (!currentPath) {
234 return { ok: false, reason: "attachment not found (removed or expired)" };
235 }
236 const fileExtension = parseAttachmentFileExtension(input.attachmentId) ?? undefined;
237 const finalId = createAttachmentId(input.threadId, fileExtension);
238 if (!finalId) {
239 return { ok: false, reason: "failed to create attachment id" };
240 }
241
242 const expectedFinalPath = resolveAttachmentRelativePath({
243 attachmentsDir: input.attachmentsDir,
244 relativePath: `${finalId}${NodePath.extname(currentPath)}`,
245 });
246 if (!expectedFinalPath) {
247 return { ok: false, reason: "failed to resolve attachment path" };
248 }
249 return {
250 ok: true,
251 finalId,
252 currentPath,
253 finalPath: expectedFinalPath,
254 };
255}
256
257export function sweepStalePendingAttachments(input: {
258 readonly attachmentsDir: string;
259 readonly nowMs: number;
260}): { readonly deleted: number } {
261 let entries: string[];
262 try {
263 entries = NodeFS.readdirSync(input.attachmentsDir);
264 } catch {
265 return { deleted: 0 };
266 }
267
268 let deleted = 0;
269 for (const entry of entries) {
270 const isPartial = entry.endsWith(".part");
271 if (!isPartial) {
272 const attachmentId = parseAttachmentIdFromRelativePath(
273 entry.endsWith(".txt") && entry.slice(0, -4).includes(".") ? entry.slice(0, -4) : entry,
274 );
275 if (
276 !attachmentId ||
277 parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT
278 ) {
279 continue;
280 }
281 }
282
283 const resolved = resolveAttachmentRelativePath({
284 attachmentsDir: input.attachmentsDir,
285 relativePath: entry,
286 });
287 if (!resolved) {
288 continue;
289 }
290 try {
291 const maxAgeMs = isPartial ? PARTIAL_UPLOAD_MAX_AGE_MS : PENDING_ATTACHMENT_MAX_AGE_MS;
292 if (input.nowMs - NodeFS.statSync(resolved).mtimeMs > maxAgeMs) {
293 NodeFS.unlinkSync(resolved);
294 deleted += 1;
295 }
296 } catch {
297 continue;
298 }
299 }
300
301 return { deleted };
302}
303
304function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
305 const normalized = normalizeAttachmentRelativePath(relativePath);
306 if (!normalized || normalized.includes("/")) {
307 return null;
308 }
309 const extensionIndex = normalized.lastIndexOf(".");
310 if (extensionIndex <= 0) {
311 return null;
312 }
313 const id = normalized.slice(0, extensionIndex);
314 return id.length > 0 && !id.includes(".") ? id : null;
315}