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

Normalizer.ts

179 lines5.9 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 IsoDateTime,
8 type OrchestrationCommand,
9 OrchestrationDispatchCommandError,
10 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
11} from "@t3tools/contracts";
12​
13import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts";
14import { ServerConfig } from "../config.ts";
15import { parseBase64DataUrl } from "../imageMime.ts";
16import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
17​
18export const canonicalizeClientCommandTimestamps = (
19 command: ClientOrchestrationCommand,
20 receivedAt: IsoDateTime,
21): ClientOrchestrationCommand => {
22 const canonicalCommand =
23 "createdAt" in command
24 ? {
25 ...command,
26 createdAt: receivedAt,
27 }
28 : command;
29​
30 if (canonicalCommand.type !== "thread.turn.start" || !canonicalCommand.bootstrap?.createThread) {
31 return canonicalCommand;
32 }
33​
34 return {
35 ...canonicalCommand,
36 bootstrap: {
37 ...canonicalCommand.bootstrap,
38 createThread: {
39 ...canonicalCommand.bootstrap.createThread,
40 createdAt: receivedAt,
41 },
42 },
43 };
44};
45​
46export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
47 Effect.gen(function* () {
48 const receivedAt = DateTime.formatIso(yield* DateTime.now);
49 const canonicalCommand = canonicalizeClientCommandTimestamps(command, receivedAt);
50 const fileSystem = yield* FileSystem.FileSystem;
51 const path = yield* Path.Path;
52 const serverConfig = yield* ServerConfig;
53 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
54​
55 const normalizeProjectWorkspaceRoot = (workspaceRoot: string) =>
56 workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(
57 Effect.mapError(
58 (cause) =>
59 new OrchestrationDispatchCommandError({
60 message: cause.message,
61 }),
62 ),
63 );
64​
65 const normalizeProjectWorkspaceRootForCreate = (
66 workspaceRoot: string,
67 createIfMissing: boolean | undefined,
68 ) =>
69 workspacePaths
70 .normalizeWorkspaceRoot(workspaceRoot, {
71 createIfMissing: createIfMissing === true,
72 })
73 .pipe(
74 Effect.mapError(
75 (cause) =>
76 new OrchestrationDispatchCommandError({
77 message: cause.message,
78 }),
79 ),
80 );
81​
82 if (canonicalCommand.type === "project.create") {
83 return {
84 ...canonicalCommand,
85 workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate(
86 canonicalCommand.workspaceRoot,
87 canonicalCommand.createWorkspaceRootIfMissing,
88 ),
89 createWorkspaceRootIfMissing: canonicalCommand.createWorkspaceRootIfMissing === true,
90 } satisfies OrchestrationCommand;
91 }
92​
93 if (
94 canonicalCommand.type === "project.meta.update" &&
95 canonicalCommand.workspaceRoot !== undefined
96 ) {
97 return {
98 ...canonicalCommand,
99 workspaceRoot: yield* normalizeProjectWorkspaceRoot(canonicalCommand.workspaceRoot),
100 } satisfies OrchestrationCommand;
101 }
102​
103 if (canonicalCommand.type !== "thread.turn.start") {
104 return canonicalCommand as OrchestrationCommand;
105 }
106​
107 const normalizedAttachments = yield* Effect.forEach(
108 canonicalCommand.message.attachments,
109 (attachment) =>
110 Effect.gen(function* () {
111 const parsed = parseBase64DataUrl(attachment.dataUrl);
112 if (!parsed || !parsed.mimeType.startsWith("image/")) {
113 return yield* new OrchestrationDispatchCommandError({
114 message: `Invalid image attachment payload for '${attachment.name}'.`,
115 });
116 }
117​
118 const bytes = Buffer.from(parsed.base64, "base64");
119 if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
120 return yield* new OrchestrationDispatchCommandError({
121 message: `Image attachment '${attachment.name}' is empty or too large.`,
122 });
123 }
124​
125 const attachmentId = createAttachmentId(canonicalCommand.threadId);
126 if (!attachmentId) {
127 return yield* new OrchestrationDispatchCommandError({
128 message: "Failed to create a safe attachment id.",
129 });
130 }
131​
132 const persistedAttachment = {
133 type: "image" as const,
134 id: attachmentId,
135 name: attachment.name,
136 mimeType: parsed.mimeType.toLowerCase(),
137 sizeBytes: bytes.byteLength,
138 };
139​
140 const attachmentPath = resolveAttachmentPath({
141 attachmentsDir: serverConfig.attachmentsDir,
142 attachment: persistedAttachment,
143 });
144 if (!attachmentPath) {
145 return yield* new OrchestrationDispatchCommandError({
146 message: `Failed to resolve persisted path for '${attachment.name}'.`,
147 });
148 }
149​
150 yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
151 Effect.mapError(
152 () =>
153 new OrchestrationDispatchCommandError({
154 message: `Failed to create attachment directory for '${attachment.name}'.`,
155 }),
156 ),
157 );
158 yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
159 Effect.mapError(
160 () =>
161 new OrchestrationDispatchCommandError({
162 message: `Failed to persist attachment '${attachment.name}'.`,
163 }),
164 ),
165 );
166​
167 return persistedAttachment;
168 }),
169 { concurrency: 1 },
170 );
171​
172 return {
173 ...canonicalCommand,
174 message: {
175 ...canonicalCommand.message,
176 attachments: normalizedAttachments,
177 },
178 } satisfies OrchestrationCommand;
179 });