@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 495 lines 16.7 KB
Raw
1 import {
2 AuthStandardClientScopes,
3 CommandId,
4 EnvironmentHttpCommonError,
5 type ProjectMutation,
6 type ProjectSnapshot,
7 ProjectId,
8 } from "@t3tools/contracts";
9 import * as Console from "effect/Console";
10 import * as SecureRandom from "effect/crypto/SecureRandom";
11 import * as Effect from "effect/Effect";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Layer from "effect/Layer";
14 import * as Option from "effect/Option";
15 import * as Path from "effect/Path";
16 import * as References from "effect/References";
17 import * as Schema from "effect/Schema";
18 import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
19 import { FetchHttpClient, HttpClient, HttpClientError } from "effect/http";
20
21 import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
22 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
23
24 import * as ServerConfig from "../config.ts";
25 import * as SqlitePersistence from "../persistence/Sqlite.ts";
26 import type * as RuntimeLayer from "../orchestration-v2/runtimeLayer.ts";
27 import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
28 import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
29 import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
30 import * as ProjectService from "../project/ProjectService.ts";
31 import { projectMutationOperation } from "../project/ProjectMutation.ts";
32 import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
33 import * as ServerSettings from "../serverSettings.ts";
34 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
35 import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
36 import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
37 import * as RunningServer from "./runningServer.ts";
38
39 type ProjectMutationTarget = {
40 readonly id: ProjectId;
41 readonly title: string;
42 readonly workspaceRoot: string;
43 };
44
45 type ProjectCliDispatchCommand = ProjectMutation;
46
47 const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
48
49 export class ProjectCommandIdGenerationError extends Schema.TaggedError<ProjectCommandIdGenerationError>()(
50 "ProjectCommandIdGenerationError",
51 {
52 operation: Schema.Literal("generateProjectCommandId"),
53 cause: Schema.Defect(),
54 },
55 ) {
56 override get message(): string {
57 return "Failed to generate a project command identifier.";
58 }
59 }
60
61 export class ProjectLiveServerDeclaredResponseError extends Schema.TaggedError<ProjectLiveServerDeclaredResponseError>()(
62 "ProjectLiveServerDeclaredResponseError",
63 {
64 operation: Schema.Literal("callLiveServer"),
65 code: Schema.String,
66 traceId: Schema.String,
67 cause: Schema.Defect(),
68 },
69 ) {
70 override get message(): string {
71 return `Server request failed (${this.code}, trace ${this.traceId}).`;
72 }
73 }
74
75 export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedError<ProjectLiveServerUndeclaredStatusError>()(
76 "ProjectLiveServerUndeclaredStatusError",
77 {
78 operation: Schema.Literal("callLiveServer"),
79 status: Schema.Int,
80 cause: Schema.Defect(),
81 },
82 ) {
83 override get message(): string {
84 return `Server request failed with undeclared status ${this.status}.`;
85 }
86 }
87
88 export class ProjectTitleEmptyError extends Schema.TaggedError<ProjectTitleEmptyError>()(
89 "ProjectTitleEmptyError",
90 {
91 operation: Schema.Literal("validateProjectTitle"),
92 title: Schema.String,
93 },
94 ) {
95 override get message(): string {
96 return "Project title cannot be empty.";
97 }
98 }
99
100 export class ProjectIdentifierEmptyError extends Schema.TaggedError<ProjectIdentifierEmptyError>()(
101 "ProjectIdentifierEmptyError",
102 {
103 operation: Schema.Literal("resolveProjectTarget"),
104 identifier: Schema.String,
105 },
106 ) {
107 override get message(): string {
108 return "Project identifier cannot be empty.";
109 }
110 }
111
112 export class ProjectNotFoundError extends Schema.TaggedError<ProjectNotFoundError>()(
113 "ProjectNotFoundError",
114 {
115 operation: Schema.Literal("resolveProjectTarget"),
116 identifier: Schema.String,
117 normalizedWorkspaceRoot: Schema.optional(Schema.String),
118 activeProjectCount: Schema.Number,
119 cause: Schema.optional(Schema.Defect()),
120 },
121 ) {
122 override get message(): string {
123 return `No active project found for '${this.identifier}'.`;
124 }
125 }
126
127 export class ProjectAlreadyExistsError extends Schema.TaggedError<ProjectAlreadyExistsError>()(
128 "ProjectAlreadyExistsError",
129 {
130 operation: Schema.Literal("addProject"),
131 projectId: ProjectId,
132 workspaceRoot: Schema.String,
133 },
134 ) {
135 override get message(): string {
136 return `An active project already exists for '${this.workspaceRoot}'.`;
137 }
138 }
139
140 export const ProjectCommandError = Schema.Union([
141 ProjectCommandIdGenerationError,
142 ProjectLiveServerDeclaredResponseError,
143 ProjectLiveServerUndeclaredStatusError,
144 ProjectTitleEmptyError,
145 ProjectIdentifierEmptyError,
146 ProjectNotFoundError,
147 ProjectAlreadyExistsError,
148 ]);
149 export type ProjectCommandError = typeof ProjectCommandError.Type;
150
151 /** Names a server's error answer; unanswered requests pass through for `changeState`. */
152 function projectCommandErrorFromServerAnswer<E>(cause: E) {
153 if (isEnvironmentHttpCommonError(cause)) {
154 return new ProjectLiveServerDeclaredResponseError({
155 operation: "callLiveServer",
156 code: cause.code,
157 traceId: cause.traceId,
158 cause,
159 });
160 }
161 if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
162 return new ProjectLiveServerUndeclaredStatusError({
163 operation: "callLiveServer",
164 status: cause.response.status,
165 cause,
166 });
167 }
168 return cause;
169 }
170
171 const projectCommandUuid = SecureRandom.SecureRandom.pipe(
172 Effect.flatMap((random) => random.uuidV4()),
173 Effect.mapError(
174 (cause) =>
175 new ProjectCommandIdGenerationError({
176 operation: "generateProjectCommandId",
177 cause,
178 }),
179 ),
180 );
181
182 const makeProjectCliRuntimeLayer = (layerProjectService: typeof RuntimeLayer.layerProjectService) =>
183 layerProjectService.pipe(
184 Layer.provideMerge(ProjectEnrichmentService.layer),
185 Layer.provideMerge(RepositoryIdentityResolver.layer),
186 Layer.provideMerge(
187 ProjectFaviconResolver.layer.pipe(
188 Layer.provide(WorkspacePaths.layer),
189 Layer.provide(T3ProjectFileLoader.layer),
190 ),
191 ),
192 Layer.provideMerge(WorkspacePaths.layer),
193 Layer.provideMerge(
194 ServerSettings.layer.pipe(
195 Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layer)),
196 ),
197 ),
198 // Built after acquireServerOwnership; layerCliConfig would contend with this process's own lock.
199 Layer.provideMerge(SqlitePersistence.layerConfig),
200 );
201
202 const normalizeWorkspaceRootForProjectCommand = Effect.fn(
203 "normalizeWorkspaceRootForProjectCommand",
204 )(function* (workspaceRoot: string) {
205 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
206 return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
207 });
208
209 const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
210 workspaceRoot: string,
211 explicitTitle?: string,
212 ) {
213 if (explicitTitle !== undefined) {
214 const trimmed = explicitTitle.trim();
215 if (trimmed.length > 0) {
216 return trimmed;
217 }
218 return yield* new ProjectTitleEmptyError({
219 operation: "validateProjectTitle",
220 title: explicitTitle,
221 });
222 }
223
224 const path = yield* Path.Path;
225 const basename = path.basename(workspaceRoot).trim();
226 return basename.length > 0 ? basename : "project";
227 });
228
229 const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
230 readonly snapshot: ProjectSnapshot;
231 readonly identifier: string;
232 }) {
233 const trimmedIdentifier = input.identifier.trim();
234 if (trimmedIdentifier.length === 0) {
235 return yield* new ProjectIdentifierEmptyError({
236 operation: "resolveProjectTarget",
237 identifier: input.identifier,
238 });
239 }
240
241 const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
242 const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
243 if (exactIdMatch) {
244 return {
245 id: exactIdMatch.id,
246 title: exactIdMatch.title,
247 workspaceRoot: exactIdMatch.workspaceRoot,
248 } satisfies ProjectMutationTarget;
249 }
250
251 const normalizedWorkspaceRootResult = yield* Effect.result(
252 normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
253 );
254 // A stored workspace path still identifies its project after the directory is gone, so a
255 // relative or trailing-slash path resolves the same way it would while the directory exists.
256 const normalizedWorkspaceRoot =
257 normalizedWorkspaceRootResult._tag === "Success"
258 ? normalizedWorkspaceRootResult.success
259 : normalizedWorkspaceRootResult.failure.normalizedWorkspaceRoot;
260
261 const exactWorkspaceMatch = activeProjects.find(
262 (project) => project.workspaceRoot === normalizedWorkspaceRoot,
263 );
264
265 const resolved = exactWorkspaceMatch;
266 if (!resolved) {
267 return yield* new ProjectNotFoundError({
268 operation: "resolveProjectTarget",
269 identifier: trimmedIdentifier,
270 activeProjectCount: activeProjects.length,
271 normalizedWorkspaceRoot,
272 ...(normalizedWorkspaceRootResult._tag === "Failure"
273 ? { cause: normalizedWorkspaceRootResult.failure }
274 : {}),
275 });
276 }
277
278 return {
279 id: resolved.id,
280 title: resolved.title,
281 workspaceRoot: resolved.workspaceRoot,
282 } satisfies ProjectMutationTarget;
283 });
284
285 const runProjectMutation = Effect.fn("runProjectMutation")(function* (
286 flags: CliAuthLocationFlags,
287 run: (input: {
288 readonly snapshot: ProjectSnapshot;
289 readonly dispatch: (
290 command: ProjectCliDispatchCommand,
291 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
292 }) => Effect.Effect<
293 string,
294 Error,
295 | SecureRandom.SecureRandom
296 | FileSystem.FileSystem
297 | HttpClient.HttpClient
298 | Path.Path
299 | WorkspacePaths.WorkspacePaths
300 >,
301 ) {
302 const logLevel = yield* GlobalFlag.LogLevel;
303 const config = yield* resolveCliAuthConfig(flags, logLevel);
304 const minimumLogLevel = config.logLevel;
305
306 return yield* Effect.gen(function* () {
307 const output = yield* RunningServer.changeState({
308 scopes: AuthStandardClientScopes,
309 viaServer: Effect.fn("project.viaServer")(function* (client) {
310 return yield* run({
311 snapshot: yield* client.projects.snapshot({ headers: {} }),
312 dispatch: (command) =>
313 client.projects.mutate({ headers: {}, payload: command } as Parameters<
314 typeof client.projects.mutate
315 >[0]),
316 });
317 }, Effect.mapError(projectCommandErrorFromServerAnswer)),
318 locally: Effect.promise(() => import("../orchestration-v2/runtimeLayer.ts")).pipe(
319 Effect.flatMap(({ layerProjectService }) =>
320 Effect.gen(function* () {
321 const projects = yield* ProjectService.ProjectService;
322 return yield* run({
323 snapshot: yield* projects.snapshot,
324 dispatch: (command) =>
325 projectMutationOperation(projects, command).pipe(Effect.asVoid),
326 });
327 }).pipe(
328 Effect.provide(
329 makeProjectCliRuntimeLayer(layerProjectService).pipe(
330 Layer.provide(ServerConfig.layer(config)),
331 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
332 ),
333 ),
334 ),
335 ),
336 ),
337 });
338 yield* Console.log(output);
339 }).pipe(
340 Effect.scoped,
341 Effect.provide(
342 Layer.mergeAll(EnvironmentAuth.layerRuntime, WorkspacePaths.layer).pipe(
343 Layer.provideMerge(FetchHttpClient.layer),
344 Layer.provideMerge(ServerConfig.layer(config)),
345 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
346 ),
347 ),
348 );
349 });
350
351 const projectAddCommand = Command.make("add", {
352 ...projectLocationFlags,
353 workspaceRoot: Argument.String("path").pipe(
354 Argument.withDescription("Workspace root to add as a project."),
355 ),
356 title: Flag.String("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
357 }).pipe(
358 Command.withDescription("Add a project."),
359 Command.withHandler((flags) =>
360 runProjectMutation(
361 flags,
362 Effect.fn("projectAddMutation")(function* ({
363 snapshot,
364 dispatch,
365 }: {
366 readonly snapshot: ProjectSnapshot;
367 readonly dispatch: (
368 command: ProjectCliDispatchCommand,
369 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
370 }) {
371 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
372 const existingProject = snapshot.projects.find(
373 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
374 );
375 // Re-adding an archived project's folder restores it, matching the clients.
376 if (existingProject?.archivedAt != null) {
377 const title = Option.isSome(flags.title)
378 ? yield* resolveProjectTitle(workspaceRoot, flags.title.value)
379 : undefined;
380 yield* dispatch({
381 type: "project.update",
382 commandId: CommandId.make(yield* projectCommandUuid),
383 projectId: existingProject.id,
384 archived: false,
385 ...(title === undefined ? {} : { title }),
386 });
387 return `Unarchived project ${existingProject.id} (${title ?? existingProject.title}) at ${workspaceRoot}.`;
388 }
389 if (existingProject) {
390 return yield* new ProjectAlreadyExistsError({
391 operation: "addProject",
392 projectId: existingProject.id,
393 workspaceRoot,
394 });
395 }
396
397 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
398 const projectId = ProjectId.make(yield* projectCommandUuid);
399 yield* dispatch({
400 type: "project.create",
401 commandId: CommandId.make(yield* projectCommandUuid),
402 projectId,
403 title,
404 workspaceRoot,
405 });
406 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
407 }),
408 ),
409 ),
410 );
411
412 const projectRemoveCommand = Command.make("remove", {
413 ...projectLocationFlags,
414 project: Argument.String("project").pipe(
415 Argument.withDescription("Project id or workspace root to remove."),
416 ),
417 force: Flag.Boolean("force").pipe(
418 Flag.withDescription("Delete the project and all of its threads."),
419 Flag.withDefault(false),
420 ),
421 }).pipe(
422 Command.withDescription("Remove a project."),
423 Command.withHandler((flags) =>
424 runProjectMutation(
425 flags,
426 Effect.fn("projectRemoveMutation")(function* ({
427 snapshot,
428 dispatch,
429 }: {
430 readonly snapshot: ProjectSnapshot;
431 readonly dispatch: (
432 command: ProjectCliDispatchCommand,
433 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
434 }) {
435 const project = yield* findActiveProjectTarget({
436 snapshot,
437 identifier: flags.project,
438 });
439 yield* dispatch({
440 type: "project.delete",
441 commandId: CommandId.make(yield* projectCommandUuid),
442 projectId: project.id,
443 force: flags.force,
444 });
445 return `Removed project ${project.id} (${project.title}).`;
446 }),
447 ),
448 ),
449 );
450
451 const projectRenameCommand = Command.make("rename", {
452 ...projectLocationFlags,
453 project: Argument.String("project").pipe(
454 Argument.withDescription("Project id or workspace root to rename."),
455 ),
456 title: Argument.String("title").pipe(Argument.withDescription("New project title.")),
457 }).pipe(
458 Command.withDescription("Rename a project."),
459 Command.withHandler((flags) =>
460 runProjectMutation(
461 flags,
462 Effect.fn("projectRenameMutation")(function* ({
463 snapshot,
464 dispatch,
465 }: {
466 readonly snapshot: ProjectSnapshot;
467 readonly dispatch: (
468 command: ProjectCliDispatchCommand,
469 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
470 }) {
471 const project = yield* findActiveProjectTarget({
472 snapshot,
473 identifier: flags.project,
474 });
475 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
476 if (nextTitle === project.title) {
477 return `Project ${project.id} is already named ${nextTitle}.`;
478 }
479
480 yield* dispatch({
481 type: "project.update",
482 commandId: CommandId.make(yield* projectCommandUuid),
483 projectId: project.id,
484 title: nextTitle,
485 });
486 return `Renamed project ${project.id} to ${nextTitle}.`;
487 }),
488 ),
489 ),
490 );
491
492 export const projectCommand = Command.make("project").pipe(
493 Command.withDescription("Manage projects."),
494 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
495 );