Open History to see the last commit
1import {
2 CommandId,
3 OrchestrationReadModel,
4 ProjectId,
5 type ClientOrchestrationCommand,
6} from "@t3tools/contracts";
7import * as Console from "effect/Console";
8import * as Crypto from "effect/Crypto";
9import * as Data from "effect/Data";
10import * as DateTime from "effect/DateTime";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Path from "effect/Path";
18import * as References from "effect/References";
19import * as Schema from "effect/Schema";
20import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
21import {
22 FetchHttpClient,
23 HttpClient,
24 HttpClientRequest,
25 HttpClientResponse,
26} from "effect/unstable/http";
27
28import { AuthControlPlaneRuntimeLive } from "../auth/Layers/AuthControlPlane.ts";
29import { AuthControlPlane } from "../auth/Services/AuthControlPlane.ts";
30import type { AuthControlPlaneShape } from "../auth/Services/AuthControlPlane.ts";
31import { ServerConfig, type ServerConfigShape } from "../config.ts";
32import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
33import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
34import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts";
35import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts";
36import { RepositoryIdentityResolverLive } from "../project/Layers/RepositoryIdentityResolver.ts";
37import { getAutoBootstrapDefaultModelSelection } from "../serverRuntimeStartup.ts";
38import {
39 clearPersistedServerRuntimeState,
40 readPersistedServerRuntimeState,
41} from "../serverRuntimeState.ts";
42import { WorkspacePathsLive } from "../workspace/Layers/WorkspacePaths.ts";
43import { WorkspacePaths } from "../workspace/Services/WorkspacePaths.ts";
44import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
45
46type ProjectMutationTarget = {
47 readonly id: ProjectId;
48 readonly title: string;
49 readonly workspaceRoot: string;
50};
51
52type ProjectCommandExecutionMode = "live" | "offline";
53type ProjectCliDispatchCommand = Extract<
54 ClientOrchestrationCommand,
55 { type: "project.create" | "project.meta.update" | "project.delete" }
56>;
57
58class ProjectCommandError extends Data.TaggedError("ProjectCommandError")<{
59 readonly message: string;
60}> {}
61
62const projectCommandUuid = Crypto.Crypto.pipe(
63 Effect.flatMap((crypto) => crypto.randomUUIDv4),
64 Effect.mapError(
65 () =>
66 new ProjectCommandError({
67 message: "Failed to generate a project command identifier.",
68 }),
69 ),
70);
71
72const ProjectCliRuntimeLive = Layer.mergeAll(
73 WorkspacePathsLive,
74 OrchestrationLayerLive.pipe(
75 Layer.provideMerge(RepositoryIdentityResolverLive),
76 Layer.provideMerge(SqlitePersistenceLayerLive),
77 ),
78);
79
80const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
81const OrchestrationHttpErrorResponse = Schema.Struct({
82 error: Schema.String,
83});
84
85const withProjectCliSessionToken = <A, E, R>(
86 authControlPlane: AuthControlPlaneShape,
87 run: (token: string) => Effect.Effect<A, E, R>,
88) =>
89 Effect.acquireUseRelease(
90 authControlPlane.issueSession({
91 role: "owner",
92 label: "t3 project cli",
93 }),
94 (issued) => run(issued.token),
95 (issued) => authControlPlane.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
96 );
97
98const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
99 effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
100
101const runLiveServerRequest = <A, E extends Error, R>(
102 request: HttpClientRequest.HttpClientRequest,
103 handle: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, E, R>,
104) =>
105 Effect.gen(function* () {
106 const httpClient = yield* HttpClient.HttpClient;
107 const response = yield* httpClient.execute(request);
108 return yield* handle(response);
109 }).pipe(withProjectCliLiveServerTimeout);
110
111const decodeOrchestrationReadModelResponse = (response: HttpClientResponse.HttpClientResponse) =>
112 HttpClientResponse.schemaBodyJson(OrchestrationReadModel)(response);
113
114const readErrorMessageFromResponse = (response: HttpClientResponse.HttpClientResponse) =>
115 HttpClientResponse.schemaBodyJson(OrchestrationHttpErrorResponse)(response).pipe(
116 Effect.map((body) => body.error),
117 Effect.catch(() => Effect.succeed(null)),
118 Effect.map((body) => {
119 if (typeof body === "string" && body.trim().length > 0) {
120 return body;
121 }
122 return `Server request failed with status ${response.status}.`;
123 }),
124 );
125
126const normalizeWorkspaceRootForProjectCommand = Effect.fn(
127 "normalizeWorkspaceRootForProjectCommand",
128)(function* (workspaceRoot: string) {
129 const workspacePaths = yield* WorkspacePaths;
130 return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
131});
132
133const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
134 workspaceRoot: string,
135 explicitTitle?: string,
136) {
137 if (explicitTitle !== undefined) {
138 const trimmed = explicitTitle.trim();
139 if (trimmed.length > 0) {
140 return trimmed;
141 }
142 return yield* new ProjectCommandError({ message: "Project title cannot be empty." });
143 }
144
145 const path = yield* Path.Path;
146 const basename = path.basename(workspaceRoot).trim();
147 return basename.length > 0 ? basename : "project";
148});
149
150const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
151 readonly snapshot: OrchestrationReadModel;
152 readonly identifier: string;
153}) {
154 const trimmedIdentifier = input.identifier.trim();
155 if (trimmedIdentifier.length === 0) {
156 return yield* new ProjectCommandError({ message: "Project identifier cannot be empty." });
157 }
158
159 const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
160 const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
161 if (exactIdMatch) {
162 return {
163 id: exactIdMatch.id,
164 title: exactIdMatch.title,
165 workspaceRoot: exactIdMatch.workspaceRoot,
166 } satisfies ProjectMutationTarget;
167 }
168
169 const normalizedWorkspaceRootResult = yield* Effect.exit(
170 normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
171 );
172 const normalizedWorkspaceRoot = Exit.isSuccess(normalizedWorkspaceRootResult)
173 ? normalizedWorkspaceRootResult.value
174 : null;
175
176 const exactWorkspaceMatch =
177 normalizedWorkspaceRoot === null
178 ? undefined
179 : activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot);
180
181 const resolved = exactWorkspaceMatch;
182 if (!resolved) {
183 return yield* new ProjectCommandError({
184 message: `No active project found for '${trimmedIdentifier}'.`,
185 });
186 }
187
188 return {
189 id: resolved.id,
190 title: resolved.title,
191 workspaceRoot: resolved.workspaceRoot,
192 } satisfies ProjectMutationTarget;
193});
194
195const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
196 runLiveServerRequest(
197 HttpClientRequest.get(`${origin}/api/orchestration/snapshot`).pipe(
198 HttpClientRequest.acceptJson,
199 HttpClientRequest.bearerToken(bearerToken),
200 ),
201 HttpClientResponse.matchStatus({
202 "2xx": decodeOrchestrationReadModelResponse,
203 orElse: (response) =>
204 readErrorMessageFromResponse(response).pipe(
205 Effect.flatMap((message) => Effect.fail(new ProjectCommandError({ message }))),
206 ),
207 }),
208 );
209
210const dispatchLiveOrchestrationCommand = (
211 origin: string,
212 bearerToken: string,
213 command: ProjectCliDispatchCommand,
214) =>
215 HttpClientRequest.post(`${origin}/api/orchestration/dispatch`).pipe(
216 HttpClientRequest.acceptJson,
217 HttpClientRequest.bearerToken(bearerToken),
218 HttpClientRequest.bodyJson(command),
219 Effect.flatMap((request) =>
220 runLiveServerRequest(
221 request,
222 HttpClientResponse.matchStatus({
223 "2xx": () => Effect.void,
224 orElse: (response) =>
225 readErrorMessageFromResponse(response).pipe(
226 Effect.flatMap((message) => Effect.fail(new ProjectCommandError({ message }))),
227 ),
228 }),
229 ),
230 ),
231 );
232
233const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
234 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
235 return yield* projectionSnapshotQuery.getSnapshot();
236});
237
238const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
239 function* (authControlPlane: AuthControlPlaneShape, config: ServerConfigShape) {
240 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
241 if (Option.isNone(runtimeState)) {
242 return Option.none<{ readonly origin: string }>();
243 }
244
245 const attempt = withProjectCliSessionToken(authControlPlane, (token) =>
246 fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
247 Effect.as({
248 origin: runtimeState.value.origin,
249 }),
250 ),
251 );
252
253 const attempted = yield* Effect.exit(attempt);
254 if (Exit.isSuccess(attempted)) {
255 return Option.some(attempted.value);
256 }
257
258 yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
259 return Option.none<{ readonly origin: string }>();
260 },
261);
262
263const runProjectMutation = Effect.fn("runProjectMutation")(function* (
264 flags: CliAuthLocationFlags,
265 run: (input: {
266 readonly snapshot: OrchestrationReadModel;
267 readonly dispatch: (
268 command: ProjectCliDispatchCommand,
269 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
270 readonly mode: ProjectCommandExecutionMode;
271 }) => Effect.Effect<
272 string,
273 Error,
274 Crypto.Crypto | FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
275 >,
276) {
277 const logLevel = yield* GlobalFlag.LogLevel;
278 const config = yield* resolveCliAuthConfig(flags, logLevel);
279 const minimumLogLevel = config.logLevel;
280
281 return yield* Effect.gen(function* () {
282 const authControlPlane = yield* AuthControlPlane;
283 const liveMode = yield* tryResolveLiveProjectExecutionMode(authControlPlane, config);
284
285 if (Option.isSome(liveMode)) {
286 return yield* withProjectCliSessionToken(authControlPlane, (token) =>
287 Effect.gen(function* () {
288 const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
289 const output = yield* run({
290 snapshot,
291 dispatch: (command) =>
292 dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
293 mode: "live",
294 });
295 yield* Console.log(output);
296 }),
297 );
298 }
299
300 const offlineRuntimeLayer = ProjectCliRuntimeLive.pipe(
301 Layer.provide(Layer.succeed(ServerConfig, config)),
302 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
303 );
304
305 return yield* Effect.gen(function* () {
306 const snapshot = yield* getOfflineSnapshot();
307 const orchestrationEngine = yield* OrchestrationEngineService;
308 const output = yield* run({
309 snapshot,
310 dispatch: (command) => orchestrationEngine.dispatch(command),
311 mode: "offline",
312 });
313 yield* Console.log(output);
314 }).pipe(Effect.provide(offlineRuntimeLayer));
315 }).pipe(
316 Effect.provide(
317 Layer.mergeAll(AuthControlPlaneRuntimeLive, WorkspacePathsLive).pipe(
318 Layer.provideMerge(FetchHttpClient.layer),
319 Layer.provide(Layer.succeed(ServerConfig, config)),
320 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
321 ),
322 ),
323 );
324});
325
326const projectAddCommand = Command.make("add", {
327 ...projectLocationFlags,
328 workspaceRoot: Argument.string("path").pipe(
329 Argument.withDescription("Workspace root to add as a project."),
330 ),
331 title: Flag.string("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
332}).pipe(
333 Command.withDescription("Add a project."),
334 Command.withHandler((flags) =>
335 runProjectMutation(
336 flags,
337 Effect.fn("projectAddMutation")(function* ({
338 snapshot,
339 dispatch,
340 }: {
341 readonly snapshot: OrchestrationReadModel;
342 readonly dispatch: (
343 command: ProjectCliDispatchCommand,
344 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
345 }) {
346 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
347 const existingProject = snapshot.projects.find(
348 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
349 );
350 if (existingProject) {
351 return yield* new ProjectCommandError({
352 message: `An active project already exists for '${workspaceRoot}'.`,
353 });
354 }
355
356 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
357 const projectId = ProjectId.make(yield* projectCommandUuid);
358 yield* dispatch({
359 type: "project.create",
360 commandId: CommandId.make(yield* projectCommandUuid),
361 projectId,
362 title,
363 workspaceRoot,
364 defaultModelSelection: getAutoBootstrapDefaultModelSelection(),
365 createdAt: DateTime.formatIso(yield* DateTime.now),
366 });
367 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
368 }),
369 ),
370 ),
371);
372
373const projectRemoveCommand = Command.make("remove", {
374 ...projectLocationFlags,
375 project: Argument.string("project").pipe(
376 Argument.withDescription("Project id or workspace root to remove."),
377 ),
378}).pipe(
379 Command.withDescription("Remove a project."),
380 Command.withHandler((flags) =>
381 runProjectMutation(
382 flags,
383 Effect.fn("projectRemoveMutation")(function* ({
384 snapshot,
385 dispatch,
386 }: {
387 readonly snapshot: OrchestrationReadModel;
388 readonly dispatch: (
389 command: ProjectCliDispatchCommand,
390 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
391 }) {
392 const project = yield* findActiveProjectTarget({
393 snapshot,
394 identifier: flags.project,
395 });
396 yield* dispatch({
397 type: "project.delete",
398 commandId: CommandId.make(yield* projectCommandUuid),
399 projectId: project.id,
400 });
401 return `Removed project ${project.id} (${project.title}).`;
402 }),
403 ),
404 ),
405);
406
407const projectRenameCommand = Command.make("rename", {
408 ...projectLocationFlags,
409 project: Argument.string("project").pipe(
410 Argument.withDescription("Project id or workspace root to rename."),
411 ),
412 title: Argument.string("title").pipe(Argument.withDescription("New project title.")),
413}).pipe(
414 Command.withDescription("Rename a project."),
415 Command.withHandler((flags) =>
416 runProjectMutation(
417 flags,
418 Effect.fn("projectRenameMutation")(function* ({
419 snapshot,
420 dispatch,
421 }: {
422 readonly snapshot: OrchestrationReadModel;
423 readonly dispatch: (
424 command: ProjectCliDispatchCommand,
425 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
426 }) {
427 const project = yield* findActiveProjectTarget({
428 snapshot,
429 identifier: flags.project,
430 });
431 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
432 if (nextTitle === project.title) {
433 return `Project ${project.id} is already named ${nextTitle}.`;
434 }
435
436 yield* dispatch({
437 type: "project.meta.update",
438 commandId: CommandId.make(yield* projectCommandUuid),
439 projectId: project.id,
440 title: nextTitle,
441 });
442 return `Renamed project ${project.id} to ${nextTitle}.`;
443 }),
444 ),
445 ),
446);
447
448export const projectCommand = Command.make("project").pipe(
449 Command.withDescription("Manage projects."),
450 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
451);