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