Open History to see the last commit
1import {
2 AuthAdministrativeScopes,
3 CommandId,
4 EnvironmentHttpApi,
5 EnvironmentHttpCommonError,
6 type ProjectMutation,
7 type ProjectSnapshot,
8 ProjectId,
9} from "@t3tools/contracts";
10import * as Console from "effect/Console";
11import * as Crypto from "effect/Crypto";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
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 { FetchHttpClient, HttpClient, HttpClientError } from "effect/unstable/http";
22import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
23
24import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
25
26import * as ServerConfig from "../config.ts";
27import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts";
28import { ProjectServiceLayerLive } from "../orchestration-v2/runtimeLayer.ts";
29import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
30import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
31import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
32import * as ProjectService from "../project/ProjectService.ts";
33import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts";
34import {
35 clearPersistedServerRuntimeState,
36 readPersistedServerRuntimeState,
37} from "../serverRuntimeState.ts";
38import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
39import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
40
41type ProjectMutationTarget = {
42 readonly id: ProjectId;
43 readonly title: string;
44 readonly workspaceRoot: string;
45};
46
47type ProjectCommandExecutionMode = "live" | "offline";
48type ProjectCliDispatchCommand = ProjectMutation;
49
50const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
51
52export class ProjectCommandIdGenerationError extends Schema.TaggedErrorClass<ProjectCommandIdGenerationError>()(
53 "ProjectCommandIdGenerationError",
54 {
55 operation: Schema.Literal("generateProjectCommandId"),
56 cause: Schema.Defect(),
57 },
58) {
59 override get message(): string {
60 return "Failed to generate a project command identifier.";
61 }
62}
63
64export class ProjectLiveServerDeclaredResponseError extends Schema.TaggedErrorClass<ProjectLiveServerDeclaredResponseError>()(
65 "ProjectLiveServerDeclaredResponseError",
66 {
67 operation: Schema.Literal("callLiveServer"),
68 code: Schema.String,
69 traceId: Schema.String,
70 cause: Schema.Defect(),
71 },
72) {
73 override get message(): string {
74 return `Server request failed (${this.code}, trace ${this.traceId}).`;
75 }
76}
77
78export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedErrorClass<ProjectLiveServerUndeclaredStatusError>()(
79 "ProjectLiveServerUndeclaredStatusError",
80 {
81 operation: Schema.Literal("callLiveServer"),
82 status: Schema.Int,
83 cause: Schema.Defect(),
84 },
85) {
86 override get message(): string {
87 return `Server request failed with undeclared status ${this.status}.`;
88 }
89}
90
91export class ProjectLiveServerRequestError extends Schema.TaggedErrorClass<ProjectLiveServerRequestError>()(
92 "ProjectLiveServerRequestError",
93 {
94 operation: Schema.Literal("callLiveServer"),
95 cause: Schema.Defect(),
96 },
97) {
98 override get message(): string {
99 return "Failed to call the running server.";
100 }
101}
102
103export class ProjectTitleEmptyError extends Schema.TaggedErrorClass<ProjectTitleEmptyError>()(
104 "ProjectTitleEmptyError",
105 {
106 operation: Schema.Literal("validateProjectTitle"),
107 title: Schema.String,
108 },
109) {
110 override get message(): string {
111 return "Project title cannot be empty.";
112 }
113}
114
115export class ProjectIdentifierEmptyError extends Schema.TaggedErrorClass<ProjectIdentifierEmptyError>()(
116 "ProjectIdentifierEmptyError",
117 {
118 operation: Schema.Literal("resolveProjectTarget"),
119 identifier: Schema.String,
120 },
121) {
122 override get message(): string {
123 return "Project identifier cannot be empty.";
124 }
125}
126
127export class ProjectNotFoundError extends Schema.TaggedErrorClass<ProjectNotFoundError>()(
128 "ProjectNotFoundError",
129 {
130 operation: Schema.Literal("resolveProjectTarget"),
131 identifier: Schema.String,
132 normalizedWorkspaceRoot: Schema.optional(Schema.String),
133 activeProjectCount: Schema.Number,
134 cause: Schema.optional(Schema.Defect()),
135 },
136) {
137 override get message(): string {
138 return `No active project found for '${this.identifier}'.`;
139 }
140}
141
142export class ProjectAlreadyExistsError extends Schema.TaggedErrorClass<ProjectAlreadyExistsError>()(
143 "ProjectAlreadyExistsError",
144 {
145 operation: Schema.Literal("addProject"),
146 projectId: ProjectId,
147 workspaceRoot: Schema.String,
148 },
149) {
150 override get message(): string {
151 return `An active project already exists for '${this.workspaceRoot}'.`;
152 }
153}
154
155export const ProjectCommandError = Schema.Union([
156 ProjectCommandIdGenerationError,
157 ProjectLiveServerDeclaredResponseError,
158 ProjectLiveServerUndeclaredStatusError,
159 ProjectLiveServerRequestError,
160 ProjectTitleEmptyError,
161 ProjectIdentifierEmptyError,
162 ProjectNotFoundError,
163 ProjectAlreadyExistsError,
164]);
165export type ProjectCommandError = typeof ProjectCommandError.Type;
166
167export function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
168 if (isEnvironmentHttpCommonError(cause)) {
169 return new ProjectLiveServerDeclaredResponseError({
170 operation: "callLiveServer",
171 code: cause.code,
172 traceId: cause.traceId,
173 cause,
174 });
175 }
176 if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
177 return new ProjectLiveServerUndeclaredStatusError({
178 operation: "callLiveServer",
179 status: cause.response.status,
180 cause,
181 });
182 }
183
184 return new ProjectLiveServerRequestError({ operation: "callLiveServer", cause });
185}
186
187const projectCommandUuid = Crypto.Crypto.pipe(
188 Effect.flatMap((crypto) => crypto.randomUUIDv4),
189 Effect.mapError(
190 (cause) =>
191 new ProjectCommandIdGenerationError({
192 operation: "generateProjectCommandId",
193 cause,
194 }),
195 ),
196);
197
198const ProjectCliRuntimeLive = ProjectServiceLayerLive.pipe(
199 Layer.provideMerge(ProjectEnrichmentService.layer),
200 Layer.provideMerge(RepositoryIdentityResolver.layer),
201 Layer.provideMerge(ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer))),
202 Layer.provideMerge(WorkspacePaths.layer),
203 Layer.provideMerge(SqlitePersistenceLayerLive),
204);
205
206const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
207const withProjectCliSessionToken = <A, E, R>(
208 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
209 run: (token: string) => Effect.Effect<A, E, R>,
210) =>
211 Effect.acquireUseRelease(
212 environmentAuth.issueSession({
213 scopes: AuthAdministrativeScopes,
214 label: "t3 project cli",
215 }),
216 (issued) => run(issued.token),
217 (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
218 );
219
220const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
221 effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
222
223const makeLiveServerClient = (origin: string) =>
224 HttpApiClient.make(EnvironmentHttpApi, {
225 baseUrl: origin,
226 });
227
228const normalizeWorkspaceRootForProjectCommand = Effect.fn(
229 "normalizeWorkspaceRootForProjectCommand",
230)(function* (workspaceRoot: string) {
231 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
232 return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
233});
234
235const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
236 workspaceRoot: string,
237 explicitTitle?: string,
238) {
239 if (explicitTitle !== undefined) {
240 const trimmed = explicitTitle.trim();
241 if (trimmed.length > 0) {
242 return trimmed;
243 }
244 return yield* new ProjectTitleEmptyError({
245 operation: "validateProjectTitle",
246 title: explicitTitle,
247 });
248 }
249
250 const path = yield* Path.Path;
251 const basename = path.basename(workspaceRoot).trim();
252 return basename.length > 0 ? basename : "project";
253});
254
255const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
256 readonly snapshot: ProjectSnapshot;
257 readonly identifier: string;
258}) {
259 const trimmedIdentifier = input.identifier.trim();
260 if (trimmedIdentifier.length === 0) {
261 return yield* new ProjectIdentifierEmptyError({
262 operation: "resolveProjectTarget",
263 identifier: input.identifier,
264 });
265 }
266
267 const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
268 const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
269 if (exactIdMatch) {
270 return {
271 id: exactIdMatch.id,
272 title: exactIdMatch.title,
273 workspaceRoot: exactIdMatch.workspaceRoot,
274 } satisfies ProjectMutationTarget;
275 }
276
277 const normalizedWorkspaceRootResult = yield* Effect.result(
278 normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
279 );
280 const normalizedWorkspaceRoot =
281 normalizedWorkspaceRootResult._tag === "Success" ? normalizedWorkspaceRootResult.success : null;
282
283 const exactWorkspaceMatch =
284 normalizedWorkspaceRoot === null
285 ? undefined
286 : activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot);
287
288 const resolved = exactWorkspaceMatch;
289 if (!resolved) {
290 return yield* new ProjectNotFoundError({
291 operation: "resolveProjectTarget",
292 identifier: trimmedIdentifier,
293 activeProjectCount: activeProjects.length,
294 ...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),
295 ...(normalizedWorkspaceRootResult._tag === "Failure"
296 ? { cause: normalizedWorkspaceRootResult.failure }
297 : {}),
298 });
299 }
300
301 return {
302 id: resolved.id,
303 title: resolved.title,
304 workspaceRoot: resolved.workspaceRoot,
305 } satisfies ProjectMutationTarget;
306});
307
308const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
309 Effect.gen(function* () {
310 const client = yield* makeLiveServerClient(origin);
311 return yield* client.projects.snapshot({
312 headers: { authorization: `Bearer ${bearerToken}` },
313 });
314 }).pipe(
315 withProjectCliLiveServerTimeout,
316 Effect.mapError(projectCommandErrorFromLiveServerRequest),
317 );
318
319const dispatchLiveOrchestrationCommand = (
320 origin: string,
321 bearerToken: string,
322 command: ProjectCliDispatchCommand,
323) =>
324 Effect.gen(function* () {
325 const client = yield* makeLiveServerClient(origin);
326 yield* client.projects.mutate({
327 headers: { authorization: `Bearer ${bearerToken}` },
328 payload: command,
329 } as Parameters<typeof client.projects.mutate>[0]);
330 }).pipe(
331 withProjectCliLiveServerTimeout,
332 Effect.mapError(projectCommandErrorFromLiveServerRequest),
333 );
334
335const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
336 const projects = yield* ProjectService.ProjectService;
337 return yield* projects.snapshot;
338});
339
340const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
341 function* (
342 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
343 config: ServerConfig.ServerConfig["Service"],
344 ) {
345 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
346 if (Option.isNone(runtimeState)) {
347 return Option.none<{ readonly origin: string }>();
348 }
349
350 const attempt = withProjectCliSessionToken(environmentAuth, (token) =>
351 fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
352 Effect.as({
353 origin: runtimeState.value.origin,
354 }),
355 ),
356 );
357
358 const attempted = yield* Effect.result(attempt);
359 if (attempted._tag === "Success") {
360 return Option.some(attempted.success);
361 }
362
363 yield* Effect.logDebug("Failed to connect to the persisted project CLI server.", {
364 origin: runtimeState.value.origin,
365 cause: attempted.failure,
366 });
367 yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
368 return Option.none<{ readonly origin: string }>();
369 },
370);
371
372const runProjectMutation = Effect.fn("runProjectMutation")(function* (
373 flags: CliAuthLocationFlags,
374 run: (input: {
375 readonly snapshot: ProjectSnapshot;
376 readonly dispatch: (
377 command: ProjectCliDispatchCommand,
378 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
379 readonly mode: ProjectCommandExecutionMode;
380 }) => Effect.Effect<
381 string,
382 Error,
383 | Crypto.Crypto
384 | FileSystem.FileSystem
385 | HttpClient.HttpClient
386 | Path.Path
387 | WorkspacePaths.WorkspacePaths
388 >,
389) {
390 const logLevel = yield* GlobalFlag.LogLevel;
391 const config = yield* resolveCliAuthConfig(flags, logLevel);
392 const minimumLogLevel = config.logLevel;
393
394 return yield* Effect.gen(function* () {
395 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
396 const liveMode = yield* tryResolveLiveProjectExecutionMode(environmentAuth, config);
397
398 if (Option.isSome(liveMode)) {
399 return yield* withProjectCliSessionToken(environmentAuth, (token) =>
400 Effect.gen(function* () {
401 const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
402 const output = yield* run({
403 snapshot,
404 dispatch: (command) =>
405 dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
406 mode: "live",
407 });
408 yield* Console.log(output);
409 }),
410 );
411 }
412
413 const offlineRuntimeLayer = ProjectCliRuntimeLive.pipe(
414 Layer.provide(ServerConfig.layer(config)),
415 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
416 );
417
418 return yield* Effect.gen(function* () {
419 const snapshot = yield* getOfflineSnapshot();
420 const projects = yield* ProjectService.ProjectService;
421 const output = yield* run({
422 snapshot,
423 dispatch: (command) =>
424 command.type === "project.create"
425 ? projects
426 .create({
427 commandId: command.commandId,
428 projectId: command.projectId,
429 title: command.title,
430 workspaceRoot: command.workspaceRoot,
431 ...(command.defaultModelSelection === undefined
432 ? {}
433 : { defaultModelSelection: command.defaultModelSelection }),
434 ...(command.scripts === undefined ? {} : { scripts: command.scripts }),
435 })
436 .pipe(Effect.asVoid)
437 : command.type === "project.update"
438 ? projects
439 .update({
440 commandId: command.commandId,
441 projectId: command.projectId,
442 ...(command.title === undefined ? {} : { title: command.title }),
443 ...(command.workspaceRoot === undefined
444 ? {}
445 : { workspaceRoot: command.workspaceRoot }),
446 ...(command.defaultModelSelection === undefined
447 ? {}
448 : { defaultModelSelection: command.defaultModelSelection }),
449 ...(command.scripts === undefined ? {} : { scripts: command.scripts }),
450 })
451 .pipe(Effect.asVoid)
452 : projects
453 .delete({ commandId: command.commandId, projectId: command.projectId })
454 .pipe(Effect.asVoid),
455 mode: "offline",
456 });
457 yield* Console.log(output);
458 }).pipe(Effect.provide(offlineRuntimeLayer));
459 }).pipe(
460 Effect.provide(
461 Layer.mergeAll(EnvironmentAuth.runtimeLayer, WorkspacePaths.layer).pipe(
462 Layer.provideMerge(FetchHttpClient.layer),
463 Layer.provide(ServerConfig.layer(config)),
464 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
465 ),
466 ),
467 );
468});
469
470const projectAddCommand = Command.make("add", {
471 ...projectLocationFlags,
472 workspaceRoot: Argument.string("path").pipe(
473 Argument.withDescription("Workspace root to add as a project."),
474 ),
475 title: Flag.string("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
476}).pipe(
477 Command.withDescription("Add a project."),
478 Command.withHandler((flags) =>
479 runProjectMutation(
480 flags,
481 Effect.fn("projectAddMutation")(function* ({
482 snapshot,
483 dispatch,
484 }: {
485 readonly snapshot: ProjectSnapshot;
486 readonly dispatch: (
487 command: ProjectCliDispatchCommand,
488 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
489 }) {
490 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
491 const existingProject = snapshot.projects.find(
492 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
493 );
494 if (existingProject) {
495 return yield* new ProjectAlreadyExistsError({
496 operation: "addProject",
497 projectId: existingProject.id,
498 workspaceRoot,
499 });
500 }
501
502 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
503 const projectId = ProjectId.make(yield* projectCommandUuid);
504 yield* dispatch({
505 type: "project.create",
506 commandId: CommandId.make(yield* projectCommandUuid),
507 projectId,
508 title,
509 workspaceRoot,
510 defaultModelSelection: ServerRuntimeStartup.getAutoBootstrapDefaultModelSelection(),
511 });
512 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
513 }),
514 ),
515 ),
516);
517
518const projectRemoveCommand = Command.make("remove", {
519 ...projectLocationFlags,
520 project: Argument.string("project").pipe(
521 Argument.withDescription("Project id or workspace root to remove."),
522 ),
523}).pipe(
524 Command.withDescription("Remove a project."),
525 Command.withHandler((flags) =>
526 runProjectMutation(
527 flags,
528 Effect.fn("projectRemoveMutation")(function* ({
529 snapshot,
530 dispatch,
531 }: {
532 readonly snapshot: ProjectSnapshot;
533 readonly dispatch: (
534 command: ProjectCliDispatchCommand,
535 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
536 }) {
537 const project = yield* findActiveProjectTarget({
538 snapshot,
539 identifier: flags.project,
540 });
541 yield* dispatch({
542 type: "project.delete",
543 commandId: CommandId.make(yield* projectCommandUuid),
544 projectId: project.id,
545 });
546 return `Removed project ${project.id} (${project.title}).`;
547 }),
548 ),
549 ),
550);
551
552const projectRenameCommand = Command.make("rename", {
553 ...projectLocationFlags,
554 project: Argument.string("project").pipe(
555 Argument.withDescription("Project id or workspace root to rename."),
556 ),
557 title: Argument.string("title").pipe(Argument.withDescription("New project title.")),
558}).pipe(
559 Command.withDescription("Rename a project."),
560 Command.withHandler((flags) =>
561 runProjectMutation(
562 flags,
563 Effect.fn("projectRenameMutation")(function* ({
564 snapshot,
565 dispatch,
566 }: {
567 readonly snapshot: ProjectSnapshot;
568 readonly dispatch: (
569 command: ProjectCliDispatchCommand,
570 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
571 }) {
572 const project = yield* findActiveProjectTarget({
573 snapshot,
574 identifier: flags.project,
575 });
576 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
577 if (nextTitle === project.title) {
578 return `Project ${project.id} is already named ${nextTitle}.`;
579 }
580
581 yield* dispatch({
582 type: "project.update",
583 commandId: CommandId.make(yield* projectCommandUuid),
584 projectId: project.id,
585 title: nextTitle,
586 });
587 return `Renamed project ${project.id} to ${nextTitle}.`;
588 }),
589 ),
590 ),
591);
592
593export const projectCommand = Command.make("project").pipe(
594 Command.withDescription("Manage projects."),
595 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
596);