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 in-flight uploads; a stored "archive.part" would
47 // look stale to sweepStalePendingAttachments and get deleted.
48 if (extension === ".part" || !/^\.[a-z0-9]{1,10}$/.test(extension)) {
49 return ".bin";
50 }
51 return extension;
52}
53
54function attachmentIdExtensionSuffix(extension: string | undefined): string {
55 if (!extension) {
56 return "";
57 }
58 const normalized = extension.replace(/^\./, "").toLowerCase();
59 return new RegExp(`^${ATTACHMENT_ID_FILE_EXTENSION_PATTERN}$`).test(normalized)
60 ? `-${normalized}`
61 : "-bin";
62}
63
64export function createPendingAttachmentId(extension?: string): string {
65 return `${PENDING_ATTACHMENT_THREAD_SEGMENT}-${NodeCrypto.randomUUID()}${attachmentIdExtensionSuffix(extension)}`;
66}
67
68export function parseAttachmentUuid(attachmentId: string): string | null {
69 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
70 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
71 return null;
72 }
73 return normalizedId.match(ATTACHMENT_ID_PATTERN)?.[2]?.toLowerCase() ?? null;
74}
75
76export function parseAttachmentFileExtension(attachmentId: string): string | null {
77 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
78 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
79 return null;
80 }
81 return normalizedId.match(ATTACHMENT_ID_PATTERN)?.[3]?.toLowerCase() ?? null;
82}
83
84export function createAttachmentId(threadId: string, extension?: string): string | null {
85 const threadSegment = toSafeThreadAttachmentSegment(threadId);
86 if (!threadSegment) {
87 return null;
88 }
89 return `${threadSegment}-${NodeCrypto.randomUUID()}${attachmentIdExtensionSuffix(extension)}`;
90}
91
92export function createDeterministicAttachmentId(
93 threadId: string,
94 stableKey: string,
95): string | null {
96 const threadSegment = toSafeThreadAttachmentSegment(threadId);
97 if (!threadSegment) return null;
98 const hash = NodeCrypto.createHash("sha256")
99 .update(JSON.stringify([threadId, stableKey]))
100 .digest("hex")
101 .slice(0, 32);
102 const uuid = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20)}`;
103 return `${threadSegment}-${uuid}`;
104}
105
106/**
107 * Stable key for an inline chat attachment. A retry resends the same bytes and
108 * keeps its id. Editing a queued message reuses the message id, so the bytes
109 * also stop a new image from taking an earlier image's id and file. Clients
110 * cache attachment images by id, which relies on ids never changing bytes.
111 */
112export function chatAttachmentStableKey(
113 messageId: string,
114 index: number,
115 bytes: Uint8Array,
116): string {
117 const digest = NodeCrypto.createHash("sha256").update(bytes).digest("hex");
118 return `${messageId}:${index}:${digest}`;
119}
120
121export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
122 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
123 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
124 return null;
125 }
126 const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
127 if (!match) {
128 return null;
129 }
130 return match[1]?.toLowerCase() ?? null;
131}
132
133/**
134 * Attachments a thread's tool calls published: `html_render` pages and
135 * captured MCP App documents. Only ids minted for this thread count, so
136 * deleting a fork never removes its source's pages.
137 */
138export function threadHtmlRenderAttachmentIds(
139 threadId: string,
140 items: Iterable<{ readonly toolName: string | null | undefined; readonly output?: unknown }>,
141) {
142 const segment = toSafeThreadAttachmentSegment(threadId);
143 if (segment === null) return [];
144 return Array.from(items).flatMap((item) => {
145 const attachmentId =
146 htmlRenderFromToolItem(item)?.attachmentId ?? mcpAppFromToolItem(item)?.attachmentId;
147 return attachmentId !== undefined &&
148 parseThreadSegmentFromAttachmentId(attachmentId) === segment
149 ? [attachmentId]
150 : [];
151 });
152}
153
154/** Null for attachment types this build does not know; callers skip those. */
155export function attachmentRelativePath(attachment: ChatAttachment): string | null {
156 switch (attachment.type) {
157 case "image": {
158 const extension = inferImageExtension({
159 mimeType: attachment.mimeType,
160 fileName: attachment.name,
161 });
162 return `${attachment.id}${extension}`;
163 }
164 case "file":
165 return `${attachment.id}${attachmentFileExtension(attachment.name)}`;
166 default:
167 return null;
168 }
169}
170
171export function resolveAttachmentPath(input: {
172 readonly attachmentsDir: string;
173 readonly attachment: ChatAttachment;
174}): string | null {
175 const relativePath = attachmentRelativePath(input.attachment);
176 if (!relativePath) {
177 return null;
178 }
179 return resolveAttachmentRelativePath({
180 attachmentsDir: input.attachmentsDir,
181 relativePath,
182 });
183}
184
185export function resolveAttachmentPathById(input: {
186 readonly attachmentsDir: string;
187 readonly attachmentId: string;
188}): string | null {
189 const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
190 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
191 return null;
192 }
193 const fileExtension = parseAttachmentFileExtension(normalizedId);
194 if (fileExtension) {
195 const filePath = resolveAttachmentRelativePath({
196 attachmentsDir: input.attachmentsDir,
197 relativePath: `${normalizedId}.${fileExtension.toLowerCase()}`,
198 });
199 return filePath && NodeFS.existsSync(filePath) ? filePath : null;
200 }
201 for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
202 const maybePath = resolveAttachmentRelativePath({
203 attachmentsDir: input.attachmentsDir,
204 relativePath: `${normalizedId}${extension}`,
205 });
206 if (maybePath && NodeFS.existsSync(maybePath)) {
207 return maybePath;
208 }
209 }
210 return null;
211}
212
213export type AttachmentClaimPlan =
214 | {
215 readonly ok: true;
216 readonly finalId: string;
217 readonly currentPath: string;
218 readonly finalPath: string;
219 }
220 | { readonly ok: false; readonly reason: string };
221
222export function planAttachmentClaim(input: {
223 readonly attachmentsDir: string;
224 readonly threadId: string;
225 readonly attachmentId: string;
226}): AttachmentClaimPlan {
227 const uuid = parseAttachmentUuid(input.attachmentId);
228 const requestedSegment = parseThreadSegmentFromAttachmentId(input.attachmentId);
229 if (!uuid || !requestedSegment) {
230 return { ok: false, reason: "invalid attachment id" };
231 }
232
233 if (!toSafeThreadAttachmentSegment(input.threadId)) {
234 return { ok: false, reason: "invalid thread id" };
235 }
236 if (requestedSegment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
237 return { ok: false, reason: "attachment must be a pending upload" };
238 }
239
240 const currentPath = resolveAttachmentPathById({
241 attachmentsDir: input.attachmentsDir,
242 attachmentId: input.attachmentId,
243 });
244 if (!currentPath) {
245 return { ok: false, reason: "attachment not found (removed or expired)" };
246 }
247 const fileExtension = parseAttachmentFileExtension(input.attachmentId) ?? undefined;
248 const finalId = createAttachmentId(input.threadId, fileExtension);
249 if (!finalId) {
250 return { ok: false, reason: "failed to create attachment id" };
251 }
252
253 const expectedFinalPath = resolveAttachmentRelativePath({
254 attachmentsDir: input.attachmentsDir,
255 relativePath: `${finalId}${NodePath.extname(currentPath)}`,
256 });
257 if (!expectedFinalPath) {
258 return { ok: false, reason: "failed to resolve attachment path" };
259 }
260 return {
261 ok: true,
262 finalId,
263 currentPath,
264 finalPath: expectedFinalPath,
265 };
266}
267
268export function sweepStalePendingAttachments(input: {
269 readonly attachmentsDir: string;
270 readonly nowMs: number;
271}): { readonly deleted: number } {
272 let entries: string[];
273 try {
274 entries = NodeFS.readdirSync(input.attachmentsDir);
275 } catch {
276 return { deleted: 0 };
277 }
278
279 let deleted = 0;
280 for (const entry of entries) {
281 const isPartial = entry.endsWith(".part");
282 if (!isPartial) {
283 const attachmentId = parseAttachmentIdFromRelativePath(entry);
284 if (
285 !attachmentId ||
286 parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT
287 ) {
288 continue;
289 }
290 }
291
292 const resolved = resolveAttachmentRelativePath({
293 attachmentsDir: input.attachmentsDir,
294 relativePath: entry,
295 });
296 if (!resolved) {
297 continue;
298 }
299 try {
300 const maxAgeMs = isPartial ? PARTIAL_UPLOAD_MAX_AGE_MS : PENDING_ATTACHMENT_MAX_AGE_MS;
301 if (input.nowMs - NodeFS.statSync(resolved).mtimeMs > maxAgeMs) {
302 NodeFS.unlinkSync(resolved);
303 deleted += 1;
304 }
305 } catch {
306 continue;
307 }
308 }
309
310 return { deleted };
311}
312
313function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
314 const normalized = normalizeAttachmentRelativePath(relativePath);
315 if (!normalized || normalized.includes("/")) {
316 return null;
317 }
318 const extensionIndex = normalized.lastIndexOf(".");
319 if (extensionIndex <= 0) {
320 return null;
321 }
322 const id = normalized.slice(0, extensionIndex);
323 return id.length > 0 && !id.includes(".") ? id : null;
324}