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: attachment 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. A copy, not a
185 // hard link: an agent editing the delivered file in place must not
186 // mutate the retry source.
187 yield* fileSystem.copyFile(claim.currentPath, claim.finalPath).pipe(
188 Effect.mapError(
189 (cause) =>
190 new OrchestrationDispatchCommandError({
191 message: `Failed to claim attachment '${attachment.name}' for this thread.`,
192 cause,
193 }),
194 ),
195 );
196 claimedAttachmentPaths.push(claim.finalPath);
197
198 return normalizedAttachment;
199 }
200
201 const parsed = parseBase64DataUrl(attachment.dataUrl);
202 if (!parsed || !parsed.mimeType.startsWith("image/")) {
203 return yield* new OrchestrationDispatchCommandError({
204 message: `Invalid image attachment payload for '${attachment.name}'.`,
205 });
206 }
207
208 const bytes = Buffer.from(parsed.base64, "base64");
209 if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
210 return yield* new OrchestrationDispatchCommandError({
211 message: `Image attachment '${attachment.name}' is empty or too large.`,
212 });
213 }
214
215 const attachmentId = createAttachmentId(canonicalCommand.threadId);
216 if (!attachmentId) {
217 return yield* new OrchestrationDispatchCommandError({
218 message: "Failed to create a safe attachment id.",
219 });
220 }
221
222 const persistedAttachment = {
223 type: "image" as const,
224 id: attachmentId,
225 name: attachment.name,
226 mimeType: parsed.mimeType.toLowerCase(),
227 sizeBytes: bytes.byteLength,
228 };
229
230 const attachmentPath = resolveAttachmentPath({
231 attachmentsDir: serverConfig.attachmentsDir,
232 attachment: persistedAttachment,
233 });
234 if (!attachmentPath) {
235 return yield* new OrchestrationDispatchCommandError({
236 message: `Failed to resolve persisted path for '${attachment.name}'.`,
237 });
238 }
239
240 yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
241 Effect.mapError(
242 () =>
243 new OrchestrationDispatchCommandError({
244 message: `Failed to create attachment directory for '${attachment.name}'.`,
245 }),
246 ),
247 );
248 yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
249 Effect.mapError(
250 () =>
251 new OrchestrationDispatchCommandError({
252 message: `Failed to persist attachment '${attachment.name}'.`,
253 }),
254 ),
255 );
256
257 return persistedAttachment;
258 }),
259 { concurrency: 1 },
260 ).pipe(Effect.tapError(() => removeClaimedAttachmentPaths(claimedAttachmentPaths)));
261
262 return {
263 ...canonicalCommand,
264 message: {
265 ...canonicalCommand.message,
266 attachments: normalizedAttachments,
267 },
268 } satisfies OrchestrationCommand;
269 });
270
271export const cleanupFailedUploadedAttachments = Effect.fn(
272 "Normalizer.cleanupFailedUploadedAttachments",
273)(function* (command: ClientOrchestrationCommand, normalizedCommand: OrchestrationCommand) {
274 if (command.type !== "thread.turn.start" || normalizedCommand.type !== "thread.turn.start") {
275 return;
276 }
277
278 const serverConfig = yield* ServerConfig;
279 const claimedPaths: string[] = [];
280 for (const [index, attachment] of normalizedCommand.message.attachments.entries()) {
281 const original = command.message.attachments[index];
282 if (
283 !original ||
284 "dataUrl" in original ||
285 parseThreadSegmentFromAttachmentId(original.id) !== PENDING_ATTACHMENT_THREAD_SEGMENT
286 ) {
287 continue;
288 }
289
290 const claimedPath = resolveAttachmentPath({
291 attachmentsDir: serverConfig.attachmentsDir,
292 attachment,
293 });
294 if (claimedPath) {
295 claimedPaths.push(claimedPath);
296 }
297 }
298 yield* removeClaimedAttachmentPaths(claimedPaths);
299});