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
106export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
107 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
108 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
109 return null;
110 }
111 const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
112 if (!match) {
113 return null;
114 }
115 return match[1]?.toLowerCase() ?? null;
116}
117
118/**
119 * Attachments a thread's tool calls published: `html_render` pages and
120 * captured MCP App documents. Only ids minted for this thread count, so
121 * deleting a fork never removes its source's pages.
122 */
123export function threadHtmlRenderAttachmentIds(
124 threadId: string,
125 items: Iterable<{ readonly toolName: string | null | undefined; readonly output?: unknown }>,
126) {
127 const segment = toSafeThreadAttachmentSegment(threadId);
128 if (segment === null) return [];
129 return Array.from(items).flatMap((item) => {
130 const attachmentId =
131 htmlRenderFromToolItem(item)?.attachmentId ?? mcpAppFromToolItem(item)?.attachmentId;
132 return attachmentId !== undefined &&
133 parseThreadSegmentFromAttachmentId(attachmentId) === segment
134 ? [attachmentId]
135 : [];
136 });
137}
138
139/** Null for attachment types this build does not know; callers skip those. */
140export function attachmentRelativePath(attachment: ChatAttachment): string | null {
141 switch (attachment.type) {
142 case "image": {
143 const extension = inferImageExtension({
144 mimeType: attachment.mimeType,
145 fileName: attachment.name,
146 });
147 return `${attachment.id}${extension}`;
148 }
149 case "file":
150 return `${attachment.id}${attachmentFileExtension(attachment.name)}`;
151 default:
152 return null;
153 }
154}
155
156export function resolveAttachmentPath(input: {
157 readonly attachmentsDir: string;
158 readonly attachment: ChatAttachment;
159}): string | null {
160 const relativePath = attachmentRelativePath(input.attachment);
161 if (!relativePath) {
162 return null;
163 }
164 return resolveAttachmentRelativePath({
165 attachmentsDir: input.attachmentsDir,
166 relativePath,
167 });
168}
169
170export function resolveAttachmentPathById(input: {
171 readonly attachmentsDir: string;
172 readonly attachmentId: string;
173}): string | null {
174 const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
175 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
176 return null;
177 }
178 const fileExtension = parseAttachmentFileExtension(normalizedId);
179 if (fileExtension) {
180 const filePath = resolveAttachmentRelativePath({
181 attachmentsDir: input.attachmentsDir,
182 relativePath: `${normalizedId}.${fileExtension.toLowerCase()}`,
183 });
184 return filePath && NodeFS.existsSync(filePath) ? filePath : null;
185 }
186 for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
187 const maybePath = resolveAttachmentRelativePath({
188 attachmentsDir: input.attachmentsDir,
189 relativePath: `${normalizedId}${extension}`,
190 });
191 if (maybePath && NodeFS.existsSync(maybePath)) {
192 return maybePath;
193 }
194 }
195 return null;
196}
197
198export type AttachmentClaimPlan =
199 | {
200 readonly ok: true;
201 readonly finalId: string;
202 readonly currentPath: string;
203 readonly finalPath: string;
204 }
205 | { readonly ok: false; readonly reason: string };
206
207export function planAttachmentClaim(input: {
208 readonly attachmentsDir: string;
209 readonly threadId: string;
210 readonly attachmentId: string;
211}): AttachmentClaimPlan {
212 const uuid = parseAttachmentUuid(input.attachmentId);
213 const requestedSegment = parseThreadSegmentFromAttachmentId(input.attachmentId);
214 if (!uuid || !requestedSegment) {
215 return { ok: false, reason: "invalid attachment id" };
216 }
217
218 if (!toSafeThreadAttachmentSegment(input.threadId)) {
219 return { ok: false, reason: "invalid thread id" };
220 }
221 if (requestedSegment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
222 return { ok: false, reason: "attachment must be a pending upload" };
223 }
224
225 const currentPath = resolveAttachmentPathById({
226 attachmentsDir: input.attachmentsDir,
227 attachmentId: input.attachmentId,
228 });
229 if (!currentPath) {
230 return { ok: false, reason: "attachment not found (removed or expired)" };
231 }
232 const fileExtension = parseAttachmentFileExtension(input.attachmentId) ?? undefined;
233 const finalId = createAttachmentId(input.threadId, fileExtension);
234 if (!finalId) {
235 return { ok: false, reason: "failed to create attachment id" };
236 }
237
238 const expectedFinalPath = resolveAttachmentRelativePath({
239 attachmentsDir: input.attachmentsDir,
240 relativePath: `${finalId}${NodePath.extname(currentPath)}`,
241 });
242 if (!expectedFinalPath) {
243 return { ok: false, reason: "failed to resolve attachment path" };
244 }
245 return {
246 ok: true,
247 finalId,
248 currentPath,
249 finalPath: expectedFinalPath,
250 };
251}
252
253export function sweepStalePendingAttachments(input: {
254 readonly attachmentsDir: string;
255 readonly nowMs: number;
256}): { readonly deleted: number } {
257 let entries: string[];
258 try {
259 entries = NodeFS.readdirSync(input.attachmentsDir);
260 } catch {
261 return { deleted: 0 };
262 }
263
264 let deleted = 0;
265 for (const entry of entries) {
266 const isPartial = entry.endsWith(".part");
267 if (!isPartial) {
268 const attachmentId = parseAttachmentIdFromRelativePath(entry);
269 if (
270 !attachmentId ||
271 parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT
272 ) {
273 continue;
274 }
275 }
276
277 const resolved = resolveAttachmentRelativePath({
278 attachmentsDir: input.attachmentsDir,
279 relativePath: entry,
280 });
281 if (!resolved) {
282 continue;
283 }
284 try {
285 const maxAgeMs = isPartial ? PARTIAL_UPLOAD_MAX_AGE_MS : PENDING_ATTACHMENT_MAX_AGE_MS;
286 if (input.nowMs - NodeFS.statSync(resolved).mtimeMs > maxAgeMs) {
287 NodeFS.unlinkSync(resolved);
288 deleted += 1;
289 }
290 } catch {
291 continue;
292 }
293 }
294
295 return { deleted };
296}
297
298function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
299 const normalized = normalizeAttachmentRelativePath(relativePath);
300 if (!normalized || normalized.includes("/")) {
301 return null;
302 }
303 const extensionIndex = normalized.lastIndexOf(".");
304 if (extensionIndex <= 0) {
305 return null;
306 }
307 const id = normalized.slice(0, extensionIndex);
308 return id.length > 0 && !id.includes(".") ? id : null;
309}