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 IsoDateTime,
8 type OrchestrationCommand,
9 OrchestrationDispatchCommandError,
10 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
11} from "@t3tools/contracts";
12
13import {
14 createAttachmentId,
15 planAttachmentClaim,
16 PENDING_ATTACHMENT_THREAD_SEGMENT,
17 parseThreadSegmentFromAttachmentId,
18 resolveAttachmentPath,
19} from "../attachmentStore.ts";
20import { ServerConfig } from "../config.ts";
21import { parseBase64DataUrl } from "../imageMime.ts";
22import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
23
24export const canonicalizeClientCommandTimestamps = (
25 command: ClientOrchestrationCommand,
26 receivedAt: IsoDateTime,
27): ClientOrchestrationCommand => {
28 const canonicalCommand =
29 "createdAt" in command
30 ? {
31 ...command,
32 createdAt: receivedAt,
33 }
34 : command;
35
36 if (canonicalCommand.type !== "thread.turn.start" || !canonicalCommand.bootstrap?.createThread) {
37 return canonicalCommand;
38 }
39
40 return {
41 ...canonicalCommand,
42 bootstrap: {
43 ...canonicalCommand.bootstrap,
44 createThread: {
45 ...canonicalCommand.bootstrap.createThread,
46 createdAt: receivedAt,
47 },
48 },
49 };
50};
51
52const removeClaimedAttachmentPaths = Effect.fn("Normalizer.removeClaimedAttachmentPaths")(
53 function* (attachmentPaths: ReadonlyArray<string>) {
54 if (attachmentPaths.length === 0) {
55 return;
56 }
57 const fileSystem = yield* FileSystem.FileSystem;
58 yield* Effect.forEach(
59 attachmentPaths,
60 (attachmentPath) =>
61 fileSystem.remove(attachmentPath, { force: true }).pipe(
62 Effect.tapError((cause) =>
63 Effect.logWarning("Failed to remove an unclaimed attachment copy.", {
64 attachmentPath,
65 cause,
66 }),
67 ),
68 Effect.orElseSucceed(() => undefined),
69 ),
70 { concurrency: 1 },
71 );
72 },
73);
74
75export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
76 Effect.gen(function* () {
77 const receivedAt = DateTime.formatIso(yield* DateTime.now);
78 const canonicalCommand = canonicalizeClientCommandTimestamps(command, receivedAt);
79 const fileSystem = yield* FileSystem.FileSystem;
80 const path = yield* Path.Path;
81 const serverConfig = yield* ServerConfig;
82 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
83
84 const normalizeProjectWorkspaceRoot = (workspaceRoot: string) =>
85 workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(
86 Effect.mapError(
87 (cause) =>
88 new OrchestrationDispatchCommandError({
89 message: cause.message,
90 }),
91 ),
92 );
93
94 const normalizeProjectWorkspaceRootForCreate = (
95 workspaceRoot: string,
96 createIfMissing: boolean | undefined,
97 ) =>
98 workspacePaths
99 .normalizeWorkspaceRoot(workspaceRoot, {
100 createIfMissing: createIfMissing === true,
101 })
102 .pipe(
103 Effect.mapError(
104 (cause) =>
105 new OrchestrationDispatchCommandError({
106 message: cause.message,
107 }),
108 ),
109 );
110
111 if (canonicalCommand.type === "project.create") {
112 return {
113 ...canonicalCommand,
114 workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate(
115 canonicalCommand.workspaceRoot,
116 canonicalCommand.createWorkspaceRootIfMissing,
117 ),
118 createWorkspaceRootIfMissing: canonicalCommand.createWorkspaceRootIfMissing === true,
119 } satisfies OrchestrationCommand;
120 }
121
122 if (
123 canonicalCommand.type === "project.meta.update" &&
124 canonicalCommand.workspaceRoot !== undefined
125 ) {
126 return {
127 ...canonicalCommand,
128 workspaceRoot: yield* normalizeProjectWorkspaceRoot(canonicalCommand.workspaceRoot),
129 } satisfies OrchestrationCommand;
130 }
131
132 if (canonicalCommand.type !== "thread.turn.start") {
133 return canonicalCommand as OrchestrationCommand;
134 }
135
136 const claimedAttachmentPaths: string[] = [];
137 const normalizedAttachments = yield* Effect.forEach(
138 canonicalCommand.message.attachments,
139 (attachment) =>
140 Effect.gen(function* () {
141 if (!("dataUrl" in attachment)) {
142 const claim = planAttachmentClaim({
143 attachmentsDir: serverConfig.attachmentsDir,
144 threadId: canonicalCommand.threadId,
145 attachmentId: attachment.id,
146 });
147 if (!claim.ok) {
148 return yield* new OrchestrationDispatchCommandError({
149 message: `Attachment '${attachment.name}' cannot be sent: ${claim.reason}.`,
150 });
151 }
152
153 const info = yield* fileSystem.stat(claim.currentPath).pipe(
154 Effect.mapError(
155 (cause) =>
156 new OrchestrationDispatchCommandError({
157 message: `Attachment '${attachment.name}' cannot be sent: attachment not found.`,
158 cause,
159 }),
160 ),
161 );
162 if (Number(info.size) !== attachment.sizeBytes) {
163 return yield* new OrchestrationDispatchCommandError({
164 message: `Attachment '${attachment.name}' cannot be sent: stored size does not match.`,
165 });
166 }
167
168 const normalizedAttachment = {
169 ...attachment,
170 id: claim.finalId,
171 mimeType: attachment.mimeType.toLowerCase(),
172 };
173 const expectedPath = resolveAttachmentPath({
174 attachmentsDir: serverConfig.attachmentsDir,
175 attachment: normalizedAttachment,
176 });
177 if (expectedPath !== claim.finalPath) {
178 return yield* new OrchestrationDispatchCommandError({
179 message: `Attachment '${attachment.name}' cannot be sent: image type does not match the upload.`,
180 });
181 }
182
183 // Keep the pending copy until the turn succeeds. A failed thread
184 // bootstrap can then retry with a fresh thread id.
185 yield* fileSystem.copyFile(claim.currentPath, claim.finalPath).pipe(
186 Effect.mapError(
187 (cause) =>
188 new OrchestrationDispatchCommandError({
189 message: `Failed to claim attachment '${attachment.name}' for this thread.`,
190 cause,
191 }),
192 ),
193 );
194 claimedAttachmentPaths.push(claim.finalPath);
195
196 return normalizedAttachment;
197 }
198
199 const parsed = parseBase64DataUrl(attachment.dataUrl);
200 if (!parsed || !parsed.mimeType.startsWith("image/")) {
201 return yield* new OrchestrationDispatchCommandError({
202 message: `Invalid image attachment payload for '${attachment.name}'.`,
203 });
204 }
205
206 const bytes = Buffer.from(parsed.base64, "base64");
207 if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
208 return yield* new OrchestrationDispatchCommandError({
209 message: `Image attachment '${attachment.name}' is empty or too large.`,
210 });
211 }
212
213 const attachmentId = createAttachmentId(canonicalCommand.threadId);
214 if (!attachmentId) {
215 return yield* new OrchestrationDispatchCommandError({
216 message: "Failed to create a safe attachment id.",
217 });
218 }
219
220 const persistedAttachment = {
221 type: "image" as const,
222 id: attachmentId,
223 name: attachment.name,
224 mimeType: parsed.mimeType.toLowerCase(),
225 sizeBytes: bytes.byteLength,
226 };
227
228 const attachmentPath = resolveAttachmentPath({
229 attachmentsDir: serverConfig.attachmentsDir,
230 attachment: persistedAttachment,
231 });
232 if (!attachmentPath) {
233 return yield* new OrchestrationDispatchCommandError({
234 message: `Failed to resolve persisted path for '${attachment.name}'.`,
235 });
236 }
237
238 yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
239 Effect.mapError(
240 () =>
241 new OrchestrationDispatchCommandError({
242 message: `Failed to create attachment directory for '${attachment.name}'.`,
243 }),
244 ),
245 );
246 yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
247 Effect.mapError(
248 () =>
249 new OrchestrationDispatchCommandError({
250 message: `Failed to persist attachment '${attachment.name}'.`,
251 }),
252 ),
253 );
254
255 return persistedAttachment;
256 }),
257 { concurrency: 1 },
258 ).pipe(Effect.tapError(() => removeClaimedAttachmentPaths(claimedAttachmentPaths)));
259
260 return {
261 ...canonicalCommand,
262 message: {
263 ...canonicalCommand.message,
264 attachments: normalizedAttachments,
265 },
266 } satisfies OrchestrationCommand;
267 });
268
269export const cleanupFailedUploadedAttachments = Effect.fn(
270 "Normalizer.cleanupFailedUploadedAttachments",
271)(function* (command: ClientOrchestrationCommand, normalizedCommand: OrchestrationCommand) {
272 if (command.type !== "thread.turn.start" || normalizedCommand.type !== "thread.turn.start") {
273 return;
274 }
275
276 const serverConfig = yield* ServerConfig;
277 const claimedPaths: string[] = [];
278 for (const [index, attachment] of normalizedCommand.message.attachments.entries()) {
279 const original = command.message.attachments[index];
280 if (
281 !original ||
282 "dataUrl" in original ||
283 parseThreadSegmentFromAttachmentId(original.id) !== PENDING_ATTACHMENT_THREAD_SEGMENT
284 ) {
285 continue;
286 }
287
288 const claimedPath = resolveAttachmentPath({
289 attachmentsDir: serverConfig.attachmentsDir,
290 attachment,
291 });
292 if (claimedPath) {
293 claimedPaths.push(claimedPath);
294 }
295 }
296 yield* removeClaimedAttachmentPaths(claimedPaths);
297});