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