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