Open History to see the last commit
1import * as DateTime from "effect/DateTime";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Path from "effect/Path";
5import {
6 type ClientOrchestrationCommand,
7 type UserInputAttachments,
8 getProviderAttachmentLimitError,
9 type IsoDateTime,
10 type OrchestrationCommand,
11 OrchestrationDispatchCommandError,
12 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
13} from "@t3tools/contracts";
14
15import {
16 createAttachmentId,
17 planAttachmentClaim,
18 PENDING_ATTACHMENT_THREAD_SEGMENT,
19 parseThreadSegmentFromAttachmentId,
20 resolveAttachmentPath,
21} from "../attachmentStore.ts";
22import { ServerConfig } from "../config.ts";
23import { parseBase64DataUrl } from "../imageMime.ts";
24import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
25
26export const canonicalizeClientCommandTimestamps = (
27 command: ClientOrchestrationCommand,
28 receivedAt: IsoDateTime,
29): ClientOrchestrationCommand => {
30 const canonicalCommand =
31 "createdAt" in command
32 ? {
33 ...command,
34 createdAt: receivedAt,
35 }
36 : command;
37
38 if (canonicalCommand.type !== "thread.turn.start" || !canonicalCommand.bootstrap?.createThread) {
39 return canonicalCommand;
40 }
41
42 return {
43 ...canonicalCommand,
44 bootstrap: {
45 ...canonicalCommand.bootstrap,
46 createThread: {
47 ...canonicalCommand.bootstrap.createThread,
48 createdAt: receivedAt,
49 },
50 },
51 };
52};
53
54const removeClaimedAttachmentPaths = Effect.fn("Normalizer.removeClaimedAttachmentPaths")(
55 function* (attachmentPaths: ReadonlyArray<string>) {
56 if (attachmentPaths.length === 0) {
57 return;
58 }
59 const fileSystem = yield* FileSystem.FileSystem;
60 yield* Effect.forEach(
61 attachmentPaths,
62 (attachmentPath) =>
63 fileSystem.remove(attachmentPath, { force: true }).pipe(
64 Effect.tapError((cause) =>
65 Effect.logWarning("Failed to remove an unclaimed attachment copy.", {
66 attachmentPath,
67 cause,
68 }),
69 ),
70 Effect.orElseSucceed(() => undefined),
71 ),
72 { concurrency: 1 },
73 );
74 },
75);
76
77export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
78 Effect.gen(function* () {
79 const receivedAt = DateTime.formatIso(yield* DateTime.now);
80 const canonicalCommand = canonicalizeClientCommandTimestamps(command, receivedAt);
81 const fileSystem = yield* FileSystem.FileSystem;
82 const path = yield* Path.Path;
83 const serverConfig = yield* ServerConfig;
84 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
85
86 const normalizeProjectWorkspaceRoot = (workspaceRoot: string) =>
87 workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(
88 Effect.mapError(
89 (cause) =>
90 new OrchestrationDispatchCommandError({
91 message: cause.message,
92 }),
93 ),
94 );
95
96 const normalizeProjectWorkspaceRootForCreate = (
97 workspaceRoot: string,
98 createIfMissing: boolean | undefined,
99 ) =>
100 workspacePaths
101 .normalizeWorkspaceRoot(workspaceRoot, {
102 createIfMissing: createIfMissing === true,
103 })
104 .pipe(
105 Effect.mapError(
106 (cause) =>
107 new OrchestrationDispatchCommandError({
108 message: cause.message,
109 }),
110 ),
111 );
112
113 if (canonicalCommand.type === "project.create") {
114 return {
115 ...canonicalCommand,
116 workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate(
117 canonicalCommand.workspaceRoot,
118 canonicalCommand.createWorkspaceRootIfMissing,
119 ),
120 createWorkspaceRootIfMissing: canonicalCommand.createWorkspaceRootIfMissing === true,
121 } satisfies OrchestrationCommand;
122 }
123
124 if (
125 canonicalCommand.type === "project.meta.update" &&
126 canonicalCommand.workspaceRoot !== undefined
127 ) {
128 return {
129 ...canonicalCommand,
130 workspaceRoot: yield* normalizeProjectWorkspaceRoot(canonicalCommand.workspaceRoot),
131 } satisfies OrchestrationCommand;
132 }
133
134 if (
135 canonicalCommand.type !== "thread.turn.start" &&
136 canonicalCommand.type !== "thread.user-input.respond"
137 ) {
138 return canonicalCommand as OrchestrationCommand;
139 }
140
141 const attachments =
142 canonicalCommand.type === "thread.turn.start"
143 ? canonicalCommand.message.attachments
144 : Object.values(canonicalCommand.attachmentsByQuestionId ?? {}).flat();
145 const attachmentLimitError = getProviderAttachmentLimitError(attachments);
146 if (attachmentLimitError) {
147 return yield* new OrchestrationDispatchCommandError({ message: attachmentLimitError });
148 }
149 if (canonicalCommand.type === "thread.turn.start") {
150 const clientAttachmentIds = new Set<string>();
151 for (const attachment of attachments) {
152 if (attachment.id === undefined) continue;
153 if (clientAttachmentIds.has(attachment.id)) {
154 return yield* new OrchestrationDispatchCommandError({
155 message: `Attachment '${attachment.name}' cannot be sent: duplicate attachment id.`,
156 });
157 }
158 clientAttachmentIds.add(attachment.id);
159 }
160 }
161 const claimedAttachmentPaths: string[] = [];
162 const attachmentsWithDecodedSizes = [...attachments];
163 // Context records bind to attachments by the id the client knew; they follow the rename.
164 const finalAttachmentIdByClientId = new Map<string, string>();
165 const normalizedAttachments = yield* Effect.forEach(
166 attachments,
167 (attachment, index) =>
168 Effect.gen(function* () {
169 if (!("dataUrl" in attachment)) {
170 const claim = planAttachmentClaim({
171 attachmentsDir: serverConfig.attachmentsDir,
172 threadId: canonicalCommand.threadId,
173 attachmentId: attachment.id,
174 });
175 if (!claim.ok) {
176 return yield* new OrchestrationDispatchCommandError({
177 message: `Attachment '${attachment.name}' cannot be sent: ${claim.reason}.`,
178 });
179 }
180
181 const info = yield* fileSystem.stat(claim.currentPath).pipe(
182 Effect.mapError(
183 (cause) =>
184 new OrchestrationDispatchCommandError({
185 message: `Attachment '${attachment.name}' cannot be sent: attachment not found.`,
186 cause,
187 }),
188 ),
189 );
190 if (Number(info.size) !== attachment.sizeBytes) {
191 return yield* new OrchestrationDispatchCommandError({
192 message: `Attachment '${attachment.name}' cannot be sent: stored size does not match.`,
193 });
194 }
195
196 const normalizedAttachment = {
197 ...attachment,
198 id: claim.finalId,
199 mimeType: attachment.mimeType.toLowerCase(),
200 };
201 const expectedPath = resolveAttachmentPath({
202 attachmentsDir: serverConfig.attachmentsDir,
203 attachment: normalizedAttachment,
204 });
205 if (expectedPath !== claim.finalPath) {
206 return yield* new OrchestrationDispatchCommandError({
207 message: `Attachment '${attachment.name}' cannot be sent: attachment type does not match the upload.`,
208 });
209 }
210
211 // Keep the pending copy until the turn succeeds. A failed thread
212 // bootstrap can then retry with a fresh thread id. A copy, not a
213 // hard link: an agent editing the delivered file in place must not
214 // mutate the retry source.
215 yield* fileSystem.copyFile(claim.currentPath, claim.finalPath).pipe(
216 Effect.mapError(
217 (cause) =>
218 new OrchestrationDispatchCommandError({
219 message: `Failed to claim attachment '${attachment.name}' for this thread.`,
220 cause,
221 }),
222 ),
223 );
224 claimedAttachmentPaths.push(claim.finalPath);
225 finalAttachmentIdByClientId.set(attachment.id, claim.finalId);
226
227 return normalizedAttachment;
228 }
229
230 const parsed = parseBase64DataUrl(attachment.dataUrl);
231 if (!parsed || !parsed.mimeType.startsWith("image/")) {
232 return yield* new OrchestrationDispatchCommandError({
233 message: `Invalid image attachment payload for '${attachment.name}'.`,
234 });
235 }
236
237 const bytes = Buffer.from(parsed.base64, "base64");
238 if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
239 return yield* new OrchestrationDispatchCommandError({
240 message: `Image attachment '${attachment.name}' is empty or too large.`,
241 });
242 }
243
244 const attachmentId = createAttachmentId(canonicalCommand.threadId);
245 if (!attachmentId) {
246 return yield* new OrchestrationDispatchCommandError({
247 message: "Failed to create a safe attachment id.",
248 });
249 }
250
251 const persistedAttachment = {
252 type: "image" as const,
253 id: attachmentId,
254 name: attachment.name,
255 mimeType: parsed.mimeType.toLowerCase(),
256 sizeBytes: bytes.byteLength,
257 ...(attachment.source ? { source: attachment.source } : {}),
258 };
259 attachmentsWithDecodedSizes[index] = persistedAttachment;
260 const decodedLimitError = getProviderAttachmentLimitError(attachmentsWithDecodedSizes);
261 if (decodedLimitError) {
262 return yield* new OrchestrationDispatchCommandError({ message: decodedLimitError });
263 }
264
265 const attachmentPath = resolveAttachmentPath({
266 attachmentsDir: serverConfig.attachmentsDir,
267 attachment: persistedAttachment,
268 });
269 if (!attachmentPath) {
270 return yield* new OrchestrationDispatchCommandError({
271 message: `Failed to resolve persisted path for '${attachment.name}'.`,
272 });
273 }
274
275 yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
276 Effect.mapError(
277 () =>
278 new OrchestrationDispatchCommandError({
279 message: `Failed to create attachment directory for '${attachment.name}'.`,
280 }),
281 ),
282 );
283 yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
284 Effect.mapError(
285 () =>
286 new OrchestrationDispatchCommandError({
287 message: `Failed to persist attachment '${attachment.name}'.`,
288 }),
289 ),
290 );
291 claimedAttachmentPaths.push(attachmentPath);
292 if (attachment.id !== undefined) {
293 finalAttachmentIdByClientId.set(attachment.id, attachmentId);
294 }
295
296 return persistedAttachment;
297 }),
298 { concurrency: 1 },
299 ).pipe(Effect.tapError(() => removeClaimedAttachmentPaths(claimedAttachmentPaths)));
300
301 if (canonicalCommand.type === "thread.user-input.respond") {
302 let index = 0;
303 const attachmentsByQuestionId = Object.fromEntries(
304 Object.entries(canonicalCommand.attachmentsByQuestionId ?? {}).map(
305 ([questionId, original]) => {
306 const claimed = normalizedAttachments.slice(
307 index,
308 index + original.length,
309 ) as UserInputAttachments[string];
310 index += original.length;
311 return [questionId, claimed];
312 },
313 ),
314 );
315 return {
316 ...canonicalCommand,
317 ...(attachments.length > 0 ? { attachmentsByQuestionId } : {}),
318 };
319 }
320 const context = canonicalCommand.message.context;
321 const normalizedContext =
322 context === undefined
323 ? undefined
324 : {
325 ...context,
326 records: context.records.map((record) =>
327 (record.kind === "image" || record.kind === "file") && "attachmentId" in record
328 ? {
329 ...record,
330 attachmentId:
331 finalAttachmentIdByClientId.get(record.attachmentId) ?? record.attachmentId,
332 }
333 : record,
334 ),
335 };
336 return {
337 ...canonicalCommand,
338 message: {
339 ...canonicalCommand.message,
340 attachments: normalizedAttachments,
341 ...(normalizedContext !== undefined ? { context: normalizedContext } : {}),
342 },
343 } satisfies OrchestrationCommand;
344 });
345
346export const cleanupFailedUploadedAttachments = Effect.fn(
347 "Normalizer.cleanupFailedUploadedAttachments",
348)(function* (command: ClientOrchestrationCommand, normalizedCommand: OrchestrationCommand) {
349 const originalAttachments =
350 command.type === "thread.turn.start"
351 ? command.message.attachments
352 : command.type === "thread.user-input.respond"
353 ? Object.values(command.attachmentsByQuestionId ?? {}).flat()
354 : [];
355 const normalizedAttachments =
356 normalizedCommand.type === "thread.turn.start"
357 ? normalizedCommand.message.attachments
358 : normalizedCommand.type === "thread.user-input.respond"
359 ? Object.values(normalizedCommand.attachmentsByQuestionId ?? {}).flat()
360 : [];
361 if (normalizedAttachments.length === 0) return;
362
363 const serverConfig = yield* ServerConfig;
364 const claimedPaths: string[] = [];
365 for (const [index, attachment] of normalizedAttachments.entries()) {
366 const original = originalAttachments[index];
367 if (
368 !original ||
369 "dataUrl" in original ||
370 parseThreadSegmentFromAttachmentId(original.id) !== PENDING_ATTACHMENT_THREAD_SEGMENT
371 ) {
372 continue;
373 }
374
375 const claimedPath = resolveAttachmentPath({
376 attachmentsDir: serverConfig.attachmentsDir,
377 attachment,
378 });
379 if (claimedPath) {
380 claimedPaths.push(claimedPath);
381 }
382 }
383 yield* removeClaimedAttachmentPaths(claimedPaths);
384});