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 T3ProjectFileLoader from "../project/T3ProjectFileLoader.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(
202 ProjectFaviconResolver.layer.pipe(
203 Layer.provide(WorkspacePaths.layer),
204 Layer.provide(T3ProjectFileLoader.layer),
205 ),
206 ),
207 Layer.provideMerge(WorkspacePaths.layer),
208 Layer.provideMerge(SqlitePersistenceLayerLive),
209);
210
211const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
212const withProjectCliSessionToken = <A, E, R>(
213 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
214 run: (token: string) => Effect.Effect<A, E, R>,
215) =>
216 Effect.acquireUseRelease(
217 environmentAuth.issueSession({
218 scopes: AuthAdministrativeScopes,
219 label: "t3 project cli",
220 }),
221 (issued) => run(issued.token),
222 (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
223 );
224
225const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
226 effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
227
228const makeLiveServerClient = (origin: string) =>
229 HttpApiClient.make(EnvironmentHttpApi, {
230 baseUrl: origin,
231 });
232
233const normalizeWorkspaceRootForProjectCommand = Effect.fn(
234 "normalizeWorkspaceRootForProjectCommand",
235)(function* (workspaceRoot: string) {
236 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
237 return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
238});
239
240const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
241 workspaceRoot: string,
242 explicitTitle?: string,
243) {
244 if (explicitTitle !== undefined) {
245 const trimmed = explicitTitle.trim();
246 if (trimmed.length > 0) {
247 return trimmed;
248 }
249 return yield* new ProjectTitleEmptyError({
250 operation: "validateProjectTitle",
251 title: explicitTitle,
252 });
253 }
254
255 const path = yield* Path.Path;
256 const basename = path.basename(workspaceRoot).trim();
257 return basename.length > 0 ? basename : "project";
258});
259
260const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
261 readonly snapshot: ProjectSnapshot;
262 readonly identifier: string;
263}) {
264 const trimmedIdentifier = input.identifier.trim();
265 if (trimmedIdentifier.length === 0) {
266 return yield* new ProjectIdentifierEmptyError({
267 operation: "resolveProjectTarget",
268 identifier: input.identifier,
269 });
270 }
271
272 const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
273 const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
274 if (exactIdMatch) {
275 return {
276 id: exactIdMatch.id,
277 title: exactIdMatch.title,
278 workspaceRoot: exactIdMatch.workspaceRoot,
279 } satisfies ProjectMutationTarget;
280 }
281
282 const normalizedWorkspaceRootResult = yield* Effect.result(
283 normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
284 );
285 const normalizedWorkspaceRoot =
286 normalizedWorkspaceRootResult._tag === "Success" ? normalizedWorkspaceRootResult.success : null;
287
288 // A stored workspace path still identifies its project after the directory is gone.
289 const exactWorkspaceMatch = activeProjects.find(
290 (project) => project.workspaceRoot === (normalizedWorkspaceRoot ?? trimmedIdentifier),
291 );
292
293 const resolved = exactWorkspaceMatch;
294 if (!resolved) {
295 return yield* new ProjectNotFoundError({
296 operation: "resolveProjectTarget",
297 identifier: trimmedIdentifier,
298 activeProjectCount: activeProjects.length,
299 ...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),
300 ...(normalizedWorkspaceRootResult._tag === "Failure"
301 ? { cause: normalizedWorkspaceRootResult.failure }
302 : {}),
303 });
304 }
305
306 return {
307 id: resolved.id,
308 title: resolved.title,
309 workspaceRoot: resolved.workspaceRoot,
310 } satisfies ProjectMutationTarget;
311});
312
313const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
314 Effect.gen(function* () {
315 const client = yield* makeLiveServerClient(origin);
316 return yield* client.projects.snapshot({
317 headers: { authorization: `Bearer ${bearerToken}` },
318 });
319 }).pipe(
320 withProjectCliLiveServerTimeout,
321 Effect.mapError(projectCommandErrorFromLiveServerRequest),
322 );
323
324const dispatchLiveOrchestrationCommand = (
325 origin: string,
326 bearerToken: string,
327 command: ProjectCliDispatchCommand,
328) =>
329 Effect.gen(function* () {
330 const client = yield* makeLiveServerClient(origin);
331 yield* client.projects.mutate({
332 headers: { authorization: `Bearer ${bearerToken}` },
333 payload: command,
334 } as Parameters<typeof client.projects.mutate>[0]);
335 }).pipe(
336 withProjectCliLiveServerTimeout,
337 Effect.mapError(projectCommandErrorFromLiveServerRequest),
338 );
339
340const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
341 const projects = yield* ProjectService.ProjectService;
342 return yield* projects.snapshot;
343});
344
345const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
346 function* (
347 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
348 config: ServerConfig.ServerConfig["Service"],
349 ) {
350 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
351 if (Option.isNone(runtimeState)) {
352 return Option.none<{ readonly origin: string }>();
353 }
354
355 const attempt = withProjectCliSessionToken(environmentAuth, (token) =>
356 fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
357 Effect.as({
358 origin: runtimeState.value.origin,
359 }),
360 ),
361 );
362
363 const attempted = yield* Effect.result(attempt);
364 if (attempted._tag === "Success") {
365 return Option.some(attempted.success);
366 }
367
368 yield* Effect.logDebug("Failed to connect to the persisted project CLI server.", {
369 origin: runtimeState.value.origin,
370 cause: attempted.failure,
371 });
372 yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
373 return Option.none<{ readonly origin: string }>();
374 },
375);
376
377const runProjectMutation = Effect.fn("runProjectMutation")(function* (
378 flags: CliAuthLocationFlags,
379 run: (input: {
380 readonly snapshot: ProjectSnapshot;
381 readonly dispatch: (
382 command: ProjectCliDispatchCommand,
383 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
384 readonly mode: ProjectCommandExecutionMode;
385 }) => Effect.Effect<
386 string,
387 Error,
388 | Crypto.Crypto
389 | FileSystem.FileSystem
390 | HttpClient.HttpClient
391 | Path.Path
392 | WorkspacePaths.WorkspacePaths
393 >,
394) {
395 const logLevel = yield* GlobalFlag.LogLevel;
396 const config = yield* resolveCliAuthConfig(flags, logLevel);
397 const minimumLogLevel = config.logLevel;
398
399 return yield* Effect.gen(function* () {
400 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
401 const liveMode = yield* tryResolveLiveProjectExecutionMode(environmentAuth, config);
402
403 if (Option.isSome(liveMode)) {
404 return yield* withProjectCliSessionToken(environmentAuth, (token) =>
405 Effect.gen(function* () {
406 const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
407 const output = yield* run({
408 snapshot,
409 dispatch: (command) =>
410 dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
411 mode: "live",
412 });
413 yield* Console.log(output);
414 }),
415 );
416 }
417
418 const offlineRuntimeLayer = ProjectCliRuntimeLive.pipe(
419 Layer.provide(ServerConfig.layer(config)),
420 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
421 );
422
423 return yield* Effect.gen(function* () {
424 const snapshot = yield* getOfflineSnapshot();
425 const projects = yield* ProjectService.ProjectService;
426 const output = yield* run({
427 snapshot,
428 dispatch: (command) =>
429 command.type === "project.create"
430 ? projects
431 .create({
432 commandId: command.commandId,
433 projectId: command.projectId,
434 title: command.title,
435 workspaceRoot: command.workspaceRoot,
436 ...(command.defaultModelSelection === undefined
437 ? {}
438 : { defaultModelSelection: command.defaultModelSelection }),
439 ...(command.scripts === undefined ? {} : { scripts: command.scripts }),
440 })
441 .pipe(Effect.asVoid)
442 : command.type === "project.update"
443 ? projects
444 .update({
445 commandId: command.commandId,
446 projectId: command.projectId,
447 ...(command.title === undefined ? {} : { title: command.title }),
448 ...(command.workspaceRoot === undefined
449 ? {}
450 : { workspaceRoot: command.workspaceRoot }),
451 ...(command.defaultModelSelection === undefined
452 ? {}
453 : { defaultModelSelection: command.defaultModelSelection }),
454 ...(command.scripts === undefined ? {} : { scripts: command.scripts }),
455 })
456 .pipe(Effect.asVoid)
457 : projects
458 .delete({
459 commandId: command.commandId,
460 projectId: command.projectId,
461 ...(command.force === undefined ? {} : { force: command.force }),
462 })
463 .pipe(Effect.asVoid),
464 mode: "offline",
465 });
466 yield* Console.log(output);
467 }).pipe(Effect.provide(offlineRuntimeLayer));
468 }).pipe(
469 Effect.provide(
470 Layer.mergeAll(EnvironmentAuth.runtimeLayer, WorkspacePaths.layer).pipe(
471 Layer.provideMerge(FetchHttpClient.layer),
472 Layer.provide(ServerConfig.layer(config)),
473 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
474 ),
475 ),
476 );
477});
478
479const projectAddCommand = Command.make("add", {
480 ...projectLocationFlags,
481 workspaceRoot: Argument.string("path").pipe(
482 Argument.withDescription("Workspace root to add as a project."),
483 ),
484 title: Flag.string("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
485}).pipe(
486 Command.withDescription("Add a project."),
487 Command.withHandler((flags) =>
488 runProjectMutation(
489 flags,
490 Effect.fn("projectAddMutation")(function* ({
491 snapshot,
492 dispatch,
493 }: {
494 readonly snapshot: ProjectSnapshot;
495 readonly dispatch: (
496 command: ProjectCliDispatchCommand,
497 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
498 }) {
499 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
500 const existingProject = snapshot.projects.find(
501 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
502 );
503 if (existingProject) {
504 return yield* new ProjectAlreadyExistsError({
505 operation: "addProject",
506 projectId: existingProject.id,
507 workspaceRoot,
508 });
509 }
510
511 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
512 const projectId = ProjectId.make(yield* projectCommandUuid);
513 yield* dispatch({
514 type: "project.create",
515 commandId: CommandId.make(yield* projectCommandUuid),
516 projectId,
517 title,
518 workspaceRoot,
519 });
520 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
521 }),
522 ),
523 ),
524);
525
526const projectRemoveCommand = Command.make("remove", {
527 ...projectLocationFlags,
528 project: Argument.string("project").pipe(
529 Argument.withDescription("Project id or workspace root to remove."),
530 ),
531 force: Flag.boolean("force").pipe(
532 Flag.withDescription("Delete the project and all of its threads."),
533 Flag.withDefault(false),
534 ),
535}).pipe(
536 Command.withDescription("Remove a project."),
537 Command.withHandler((flags) =>
538 runProjectMutation(
539 flags,
540 Effect.fn("projectRemoveMutation")(function* ({
541 snapshot,
542 dispatch,
543 }: {
544 readonly snapshot: ProjectSnapshot;
545 readonly dispatch: (
546 command: ProjectCliDispatchCommand,
547 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
548 }) {
549 const project = yield* findActiveProjectTarget({
550 snapshot,
551 identifier: flags.project,
552 });
553 yield* dispatch({
554 type: "project.delete",
555 commandId: CommandId.make(yield* projectCommandUuid),
556 projectId: project.id,
557 force: flags.force,
558 });
559 return `Removed project ${project.id} (${project.title}).`;
560 }),
561 ),
562 ),
563);
564
565const projectRenameCommand = Command.make("rename", {
566 ...projectLocationFlags,
567 project: Argument.string("project").pipe(
568 Argument.withDescription("Project id or workspace root to rename."),
569 ),
570 title: Argument.string("title").pipe(Argument.withDescription("New project title.")),
571}).pipe(
572 Command.withDescription("Rename a project."),
573 Command.withHandler((flags) =>
574 runProjectMutation(
575 flags,
576 Effect.fn("projectRenameMutation")(function* ({
577 snapshot,
578 dispatch,
579 }: {
580 readonly snapshot: ProjectSnapshot;
581 readonly dispatch: (
582 command: ProjectCliDispatchCommand,
583 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
584 }) {
585 const project = yield* findActiveProjectTarget({
586 snapshot,
587 identifier: flags.project,
588 });
589 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
590 if (nextTitle === project.title) {
591 return `Project ${project.id} is already named ${nextTitle}.`;
592 }
593
594 yield* dispatch({
595 type: "project.update",
596 commandId: CommandId.make(yield* projectCommandUuid),
597 projectId: project.id,
598 title: nextTitle,
599 });
600 return `Renamed project ${project.id} to ${nextTitle}.`;
601 }),
602 ),
603 ),
604);
605
606export const projectCommand = Command.make("project").pipe(
607 Command.withDescription("Manage projects."),
608 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
609);