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

Normalizer.ts

423 lines15.6 KB

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