Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Normalizer.ts

381 lines13.5 KB

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 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
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 if (
146 canonicalCommand.type === "thread.user-input.respond" &&
147 attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS
148 ) {
149 return yield* new OrchestrationDispatchCommandError({
150 message: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per question response.`,
151 });
152 }
153 if (canonicalCommand.type === "thread.turn.start") {
154 const clientAttachmentIds = new Set<string>();
155 for (const attachment of attachments) {
156 if (attachment.id === undefined) continue;
157 if (clientAttachmentIds.has(attachment.id)) {
158 return yield* new OrchestrationDispatchCommandError({
159 message: `Attachment '${attachment.name}' cannot be sent: duplicate attachment id.`,
160 });
161 }
162 clientAttachmentIds.add(attachment.id);
163 }
164 }
165 const claimedAttachmentPaths: string[] = [];
166 // Context records bind to attachments by the id the client knew; they follow the rename.
167 const finalAttachmentIdByClientId = new Map<string, string>();
168 const normalizedAttachments = yield* Effect.forEach(
169 attachments,
170 (attachment) =>
171 Effect.gen(function* () {
172 if (!("dataUrl" in attachment)) {
173 const claim = planAttachmentClaim({
174 attachmentsDir: serverConfig.attachmentsDir,
175 threadId: canonicalCommand.threadId,
176 attachmentId: attachment.id,
177 });
178 if (!claim.ok) {
179 return yield* new OrchestrationDispatchCommandError({
180 message: `Attachment '${attachment.name}' cannot be sent: ${claim.reason}.`,
181 });
182 }
183​
184 const info = yield* fileSystem.stat(claim.currentPath).pipe(
185 Effect.mapError(
186 (cause) =>
187 new OrchestrationDispatchCommandError({
188 message: `Attachment '${attachment.name}' cannot be sent: attachment not found.`,
189 cause,
190 }),
191 ),
192 );
193 if (Number(info.size) !== attachment.sizeBytes) {
194 return yield* new OrchestrationDispatchCommandError({
195 message: `Attachment '${attachment.name}' cannot be sent: stored size does not match.`,
196 });
197 }
198​
199 const normalizedAttachment = {
200 ...attachment,
201 id: claim.finalId,
202 mimeType: attachment.mimeType.toLowerCase(),
203 };
204 const expectedPath = resolveAttachmentPath({
205 attachmentsDir: serverConfig.attachmentsDir,
206 attachment: normalizedAttachment,
207 });
208 if (expectedPath !== claim.finalPath) {
209 return yield* new OrchestrationDispatchCommandError({
210 message: `Attachment '${attachment.name}' cannot be sent: attachment type does not match the upload.`,
211 });
212 }
213​
214 // Keep the pending copy until the turn succeeds. A failed thread
215 // bootstrap can then retry with a fresh thread id. A copy, not a
216 // hard link: an agent editing the delivered file in place must not
217 // mutate the retry source.
218 yield* fileSystem.copyFile(claim.currentPath, claim.finalPath).pipe(
219 Effect.mapError(
220 (cause) =>
221 new OrchestrationDispatchCommandError({
222 message: `Failed to claim attachment '${attachment.name}' for this thread.`,
223 cause,
224 }),
225 ),
226 );
227 claimedAttachmentPaths.push(claim.finalPath);
228 finalAttachmentIdByClientId.set(attachment.id, claim.finalId);
229​
230 return normalizedAttachment;
231 }
232​
233 const parsed = parseBase64DataUrl(attachment.dataUrl);
234 if (!parsed || !parsed.mimeType.startsWith("image/")) {
235 return yield* new OrchestrationDispatchCommandError({
236 message: `Invalid image attachment payload for '${attachment.name}'.`,
237 });
238 }
239​
240 const bytes = Buffer.from(parsed.base64, "base64");
241 if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
242 return yield* new OrchestrationDispatchCommandError({
243 message: `Image attachment '${attachment.name}' is empty or too large.`,
244 });
245 }
246​
247 const attachmentId = createAttachmentId(canonicalCommand.threadId);
248 if (!attachmentId) {
249 return yield* new OrchestrationDispatchCommandError({
250 message: "Failed to create a safe attachment id.",
251 });
252 }
253​
254 const persistedAttachment = {
255 type: "image" as const,
256 id: attachmentId,
257 name: attachment.name,
258 mimeType: parsed.mimeType.toLowerCase(),
259 sizeBytes: bytes.byteLength,
260 ...(attachment.source ? { source: attachment.source } : {}),
261 };
262​
263 const attachmentPath = resolveAttachmentPath({
264 attachmentsDir: serverConfig.attachmentsDir,
265 attachment: persistedAttachment,
266 });
267 if (!attachmentPath) {
268 return yield* new OrchestrationDispatchCommandError({
269 message: `Failed to resolve persisted path for '${attachment.name}'.`,
270 });
271 }
272​
273 yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
274 Effect.mapError(
275 () =>
276 new OrchestrationDispatchCommandError({
277 message: `Failed to create attachment directory for '${attachment.name}'.`,
278 }),
279 ),
280 );
281 yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
282 Effect.mapError(
283 () =>
284 new OrchestrationDispatchCommandError({
285 message: `Failed to persist attachment '${attachment.name}'.`,
286 }),
287 ),
288 );
289 if (attachment.id !== undefined) {
290 finalAttachmentIdByClientId.set(attachment.id, attachmentId);
291 }
292​
293 return persistedAttachment;
294 }),
295 { concurrency: 1 },
296 ).pipe(Effect.tapError(() => removeClaimedAttachmentPaths(claimedAttachmentPaths)));
297​
298 if (canonicalCommand.type === "thread.user-input.respond") {
299 let index = 0;
300 const attachmentsByQuestionId = Object.fromEntries(
301 Object.entries(canonicalCommand.attachmentsByQuestionId ?? {}).map(
302 ([questionId, original]) => {
303 const claimed = normalizedAttachments.slice(
304 index,
305 index + original.length,
306 ) as UserInputAttachments[string];
307 index += original.length;
308 return [questionId, claimed];
309 },
310 ),
311 );
312 return {
313 ...canonicalCommand,
314 ...(attachments.length > 0 ? { attachmentsByQuestionId } : {}),
315 };
316 }
317 const context = canonicalCommand.message.context;
318 const normalizedContext =
319 context === undefined
320 ? undefined
321 : {
322 ...context,
323 records: context.records.map((record) =>
324 (record.kind === "image" || record.kind === "file") && "attachmentId" in record
325 ? {
326 ...record,
327 attachmentId:
328 finalAttachmentIdByClientId.get(record.attachmentId) ?? record.attachmentId,
329 }
330 : record,
331 ),
332 };
333 return {
334 ...canonicalCommand,
335 message: {
336 ...canonicalCommand.message,
337 attachments: normalizedAttachments,
338 ...(normalizedContext !== undefined ? { context: normalizedContext } : {}),
339 },
340 } satisfies OrchestrationCommand;
341 });
342​
343export const cleanupFailedUploadedAttachments = Effect.fn(
344 "Normalizer.cleanupFailedUploadedAttachments",
345)(function* (command: ClientOrchestrationCommand, normalizedCommand: OrchestrationCommand) {
346 const originalAttachments =
347 command.type === "thread.turn.start"
348 ? command.message.attachments
349 : command.type === "thread.user-input.respond"
350 ? Object.values(command.attachmentsByQuestionId ?? {}).flat()
351 : [];
352 const normalizedAttachments =
353 normalizedCommand.type === "thread.turn.start"
354 ? normalizedCommand.message.attachments
355 : normalizedCommand.type === "thread.user-input.respond"
356 ? Object.values(normalizedCommand.attachmentsByQuestionId ?? {}).flat()
357 : [];
358 if (normalizedAttachments.length === 0) return;
359​
360 const serverConfig = yield* ServerConfig;
361 const claimedPaths: string[] = [];
362 for (const [index, attachment] of normalizedAttachments.entries()) {
363 const original = originalAttachments[index];
364 if (
365 !original ||
366 "dataUrl" in original ||
367 parseThreadSegmentFromAttachmentId(original.id) !== PENDING_ATTACHMENT_THREAD_SEGMENT
368 ) {
369 continue;
370 }
371​
372 const claimedPath = resolveAttachmentPath({
373 attachmentsDir: serverConfig.attachmentsDir,
374 attachment,
375 });
376 if (claimedPath) {
377 claimedPaths.push(claimedPath);
378 }
379 }
380 yield* removeClaimedAttachmentPaths(claimedPaths);
381});