Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

project.ts

562 lines18.9 KB

1import * as Schema from "effect/Schema";
2import * as SchemaTransformation from "effect/SchemaTransformation";
3import { RepositoryIdentity, ThreadEnvMode } from "./environment.ts";
4import { ModelSelection } from "./modelSelection.ts";
5import {
6 CommandId,
7 ForwardCompatibleUnion,
8 isUnknownUnionMember,
9 IsoDateTime,
10 NonNegativeInt,
11 PositiveInt,
12 ProjectId,
13 TrimmedNonEmptyString,
14 TrimmedString,
15 type UnknownUnionMember,
16} from "./baseSchemas.ts";
17​
18const PROJECT_SEARCH_ENTRIES_MAX_LIMIT = 200;
19const PROJECT_SEARCH_CONTENTS_MAX_LIMIT = 500;
20const PROJECT_WRITE_FILE_PATH_MAX_LENGTH = 512;
21const PROJECT_READ_FILE_PATH_MAX_LENGTH = 512;
22​
23export const ProjectScriptIcon = Schema.Literals([
24 "play",
25 "test",
26 "lint",
27 "configure",
28 "build",
29 "debug",
30]);
31export type ProjectScriptIcon = typeof ProjectScriptIcon.Type;
32​
33export const ProjectScript = Schema.Struct({
34 id: TrimmedNonEmptyString,
35 name: TrimmedNonEmptyString,
36 command: TrimmedNonEmptyString,
37 icon: ProjectScriptIcon,
38 runOnWorktreeCreate: Schema.Boolean,
39 /** Start the agent while setup runs unless explicitly disabled. */
40 async: Schema.optional(Schema.Boolean),
41 previewUrl: Schema.optional(TrimmedNonEmptyString),
42 autoOpenPreview: Schema.optional(Schema.Boolean),
43});
44export type ProjectScript = typeof ProjectScript.Type;
45​
46export const ProjectIconColor = Schema.Literals([
47 "gray",
48 "red",
49 "orange",
50 "amber",
51 "yellow",
52 "lime",
53 "green",
54 "emerald",
55 "teal",
56 "cyan",
57 "sky",
58 "blue",
59 "indigo",
60 "violet",
61 "purple",
62 "fuchsia",
63 "pink",
64 "rose",
65]);
66export type ProjectIconColor = typeof ProjectIconColor.Type;
67​
68const ProjectLucideIconName = TrimmedNonEmptyString.check(
69 Schema.isMaxLength(64),
70 Schema.isPattern(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
71);
72​
73const ProjectEmoji = TrimmedNonEmptyString.check(Schema.isMaxLength(32));
74​
75// Grapheme-count validation belongs to the server command boundary, not snapshot decoding.
76export const ProjectMonogramText = TrimmedNonEmptyString.check(
77 Schema.isMaxLength(32),
78 Schema.isPattern(/^[\p{L}\p{N}][\p{L}\p{N}\p{M}\u200c\u200d]*$/u),
79);
80​
81const ProjectLucideIcon = Schema.Struct({
82 kind: Schema.Literal("lucide"),
83 name: ProjectLucideIconName,
84 color: ProjectIconColor,
85});
86const ProjectEmojiIcon = Schema.Struct({
87 kind: Schema.Literal("emoji"),
88 emoji: ProjectEmoji,
89});
90const ProjectMonogramIcon = Schema.Struct({
91 kind: Schema.Literal("monogram"),
92 text: ProjectMonogramText,
93 color: ProjectIconColor,
94});
95/** A workspace-relative image a project may use as its favicon. */
96export const ProjectFaviconPath = TrimmedNonEmptyString.check(
97 Schema.isMaxLength(1024),
98 Schema.isPattern(/\.(?:avif|gif|ico|jpe?g|png|svg|webp)$/i),
99);
100export type ProjectFaviconPath = typeof ProjectFaviconPath.Type;
101​
102/** A project's chosen icon, as clients set it. */
103export const ProjectIconOverride = Schema.Union([
104 ProjectLucideIcon,
105 ProjectEmojiIcon,
106 ProjectMonogramIcon,
107]);
108export type ProjectIconOverride = typeof ProjectIconOverride.Type;
109​
110/**
111 * Before v2, servers sent a monogram as a lucide icon carrying its text, so
112 * older clients showed a folder. Icons stored then, and v2 servers released
113 * before this change, still use that shape; it is read here, never written.
114 */
115const ProjectLucideIconWithLegacyMonogram = Schema.Struct({
116 ...ProjectLucideIcon.fields,
117 monogramText: Schema.optional(ProjectMonogramText),
118 monogram: Schema.optional(ProjectMonogramText),
119});
120const projectIconMembers = [
121 ProjectLucideIconWithLegacyMonogram,
122 ProjectEmojiIcon,
123 ProjectMonogramIcon,
124] as const;
125type ProjectIconMember = (typeof projectIconMembers)[number]["Type"];
126​
127const fromLegacyMonogram = (icon: ProjectIconMember): ProjectIconOverride => {
128 if (icon.kind !== "lucide") return icon;
129 const text = icon.monogramText ?? icon.monogram;
130 return text === undefined
131 ? { kind: "lucide", name: icon.name, color: icon.color }
132 : { kind: "monogram", text, color: icon.color };
133};
134​
135/** An icon the server stores; it reads legacy monograms and writes the plain shape. */
136export const StoredProjectIcon = Schema.Union(projectIconMembers).pipe(
137 Schema.decodeTo(
138 Schema.toType(ProjectIconOverride),
139 SchemaTransformation.transform<ProjectIconOverride, ProjectIconMember>({
140 decode: fromLegacyMonogram,
141 encode: (icon) => icon,
142 }),
143 ),
144);
145​
146/**
147 * An icon as clients receive it. A kind from a newer server decodes as no
148 * override, so the client shows the project's default icon.
149 */
150export const ReceivedProjectIcon = ForwardCompatibleUnion(projectIconMembers, "kind").pipe(
151 Schema.decodeTo(
152 Schema.NullOr(Schema.toType(ProjectIconOverride)),
153 SchemaTransformation.transform<
154 ProjectIconOverride | null,
155 ProjectIconMember | UnknownUnionMember<"kind">
156 >({
157 decode: (icon) => (isUnknownUnionMember(icon) ? null : fromLegacyMonogram(icon)),
158 encode: (icon) => icon as ProjectIconMember,
159 }),
160 ),
161);
162​
163export const Project = Schema.Struct({
164 id: ProjectId,
165 title: TrimmedNonEmptyString,
166 workspaceRoot: TrimmedNonEmptyString,
167 repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
168 faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
169 projectIcon: Schema.optional(Schema.NullOr(ReceivedProjectIcon)),
170 defaultModelSelection: Schema.NullOr(ModelSelection),
171 defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
172 // Opt-in because background sync performs network I/O and may move the checkout.
173 autoPull: Schema.optional(Schema.Boolean),
174 scripts: Schema.Array(ProjectScript),
175 createdAt: IsoDateTime,
176 updatedAt: IsoDateTime,
177 deletedAt: Schema.NullOr(IsoDateTime),
178});
179export type Project = typeof Project.Type;
180​
181export const ProjectSnapshot = Schema.Struct({
182 projects: Schema.Array(Project),
183 updatedAt: IsoDateTime,
184});
185export type ProjectSnapshot = typeof ProjectSnapshot.Type;
186​
187export const ProjectChange = Schema.Union([
188 Schema.Struct({ type: Schema.Literal("project.upserted"), project: Project }),
189 Schema.Struct({
190 type: Schema.Literal("project.deleted"),
191 projectId: ProjectId,
192 deletedAt: IsoDateTime,
193 }),
194]);
195export type ProjectChange = typeof ProjectChange.Type;
196​
197export const ProjectCreatePayload = Schema.Struct({
198 title: TrimmedNonEmptyString,
199 workspaceRoot: TrimmedNonEmptyString,
200 createWorkspaceRootIfMissing: Schema.optional(Schema.Boolean),
201 defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
202 scripts: Schema.optional(Schema.Array(ProjectScript)),
203});
204export type ProjectCreatePayload = typeof ProjectCreatePayload.Type;
205​
206export const ProjectUpdatePayload = Schema.Struct({
207 title: Schema.optional(TrimmedNonEmptyString),
208 workspaceRoot: Schema.optional(TrimmedNonEmptyString),
209 defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
210 autoPull: Schema.optional(Schema.Boolean),
211 projectIcon: Schema.optional(Schema.NullOr(ProjectIconOverride)),
212 faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
213 defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
214 scripts: Schema.optional(Schema.Array(ProjectScript)),
215});
216export type ProjectUpdatePayload = typeof ProjectUpdatePayload.Type;
217​
218export const ProjectMutation = Schema.Union([
219 Schema.Struct({
220 type: Schema.Literal("project.create"),
221 commandId: CommandId,
222 projectId: ProjectId,
223 ...ProjectCreatePayload.fields,
224 }),
225 Schema.Struct({
226 type: Schema.Literal("project.update"),
227 commandId: CommandId,
228 projectId: ProjectId,
229 ...ProjectUpdatePayload.fields,
230 }),
231 Schema.Struct({
232 type: Schema.Literal("project.delete"),
233 commandId: CommandId,
234 projectId: ProjectId,
235 force: Schema.optional(Schema.Boolean),
236 }),
237]);
238export type ProjectMutation = typeof ProjectMutation.Type;
239​
240export class ProjectMutationError extends Schema.TaggedError<ProjectMutationError>()(
241 "ProjectMutationError",
242 {
243 commandId: CommandId,
244 message: Schema.String,
245 cause: Schema.optional(Schema.Defect()),
246 },
247) {}
248​
249export const ProjectEntryKind = Schema.Literals(["file", "directory"]);
250export type ProjectEntryKind = typeof ProjectEntryKind.Type;
251​
252export const ProjectSearchEntriesInput = Schema.Struct({
253 cwd: TrimmedNonEmptyString,
254 // An empty query is a bounded browse: the index returns frecency-ordered
255 // entries, which the file picker uses for its initial results.
256 query: TrimmedString.check(Schema.isMaxLength(256)),
257 limit: PositiveInt.check(Schema.isLessThanOrEqualTo(PROJECT_SEARCH_ENTRIES_MAX_LIMIT)),
258 kind: Schema.optional(ProjectEntryKind),
259 imageOnly: Schema.optional(Schema.Boolean),
260});
261export type ProjectSearchEntriesInput = typeof ProjectSearchEntriesInput.Type;
262​
263export const ProjectEntry = Schema.Struct({
264 path: TrimmedNonEmptyString,
265 kind: ProjectEntryKind,
266 ignored: Schema.optional(Schema.Boolean),
267});
268export type ProjectEntry = typeof ProjectEntry.Type;
269​
270export const ProjectSearchEntriesResult = Schema.Struct({
271 entries: Schema.Array(ProjectEntry),
272 truncated: Schema.Boolean,
273});
274export type ProjectSearchEntriesResult = typeof ProjectSearchEntriesResult.Type;
275​
276export const ProjectSearchContentsInput = Schema.Struct({
277 cwd: TrimmedNonEmptyString,
278 // Whitespace is significant in content queries (" foo", regex trailing
279 // spaces), so the query is deliberately not trimmed on the wire.
280 query: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(256)),
281 limit: PositiveInt.check(Schema.isLessThanOrEqualTo(PROJECT_SEARCH_CONTENTS_MAX_LIMIT)),
282 caseSensitive: Schema.Boolean,
283 wholeWord: Schema.Boolean,
284 useRegex: Schema.Boolean,
285});
286export type ProjectSearchContentsInput = typeof ProjectSearchContentsInput.Type;
287​
288export const ProjectContentMatchRange = Schema.Struct({
289 start: NonNegativeInt,
290 end: NonNegativeInt,
291});
292export type ProjectContentMatchRange = typeof ProjectContentMatchRange.Type;
293​
294export const ProjectContentMatch = Schema.Struct({
295 path: TrimmedNonEmptyString,
296 lineNumber: PositiveInt,
297 lineContent: Schema.String,
298 matchRanges: Schema.Array(ProjectContentMatchRange),
299});
300export type ProjectContentMatch = typeof ProjectContentMatch.Type;
301​
302export const ProjectSearchContentsResult = Schema.Struct({
303 matches: Schema.Array(ProjectContentMatch),
304 truncated: Schema.Boolean,
305 regexFallbackError: Schema.optional(Schema.String),
306});
307export type ProjectSearchContentsResult = typeof ProjectSearchContentsResult.Type;
308​
309export const ProjectListEntriesInput = Schema.Struct({
310 cwd: TrimmedNonEmptyString,
311 // Present for immediate filesystem children, including ignored entries; empty means root.
312 // Omitted preserves the indexed recursive listing used by older clients.
313 directoryPath: Schema.optional(TrimmedString),
314});
315export type ProjectListEntriesInput = typeof ProjectListEntriesInput.Type;
316​
317export const ProjectListEntriesResult = Schema.Struct({
318 entries: Schema.Array(ProjectEntry),
319 truncated: Schema.Boolean,
320});
321export type ProjectListEntriesResult = typeof ProjectListEntriesResult.Type;
322​
323export const ProjectEntriesFailure = Schema.Literals([
324 "workspace_root_not_found",
325 "workspace_root_create_failed",
326 "workspace_root_stat_failed",
327 "workspace_root_not_directory",
328 "search_index_create_failed",
329 "search_index_scan_timed_out",
330 "search_index_search_failed",
331 "directory_list_failed",
332]);
333export type ProjectEntriesFailure = typeof ProjectEntriesFailure.Type;
334​
335type ProjectEntriesFailureContext = {
336 readonly failure: ProjectEntriesFailure;
337 readonly normalizedCwd?: string;
338 readonly timeout?: string;
339 readonly detail?: string;
340 readonly cause?: unknown;
341};
342​
343function decodedProjectErrorMessage(props: object): string | undefined {
344 if (!("message" in props)) return undefined;
345 return typeof props.message === "string" ? props.message : undefined;
347​
348export class ProjectSearchEntriesError extends Schema.TaggedError<ProjectSearchEntriesError>()(
349 "ProjectSearchEntriesError",
350 {
351 cwd: Schema.optional(TrimmedNonEmptyString),
352 queryLength: Schema.optional(NonNegativeInt),
353 limit: Schema.optional(PositiveInt),
354 failure: Schema.optional(ProjectEntriesFailure),
355 normalizedCwd: Schema.optional(TrimmedNonEmptyString),
356 timeout: Schema.optional(TrimmedNonEmptyString),
357 detail: Schema.optional(TrimmedNonEmptyString),
358 message: TrimmedNonEmptyString,
359 cause: Schema.optional(Schema.Defect()),
360 },
361) {
362 // The structured fields are optional on the wire so newer peers can decode legacy message-only
363 // failures. New application code must provide them through this constructor.
364 // @effect-diagnostics-next-line overriddenSchemaConstructor:off
365 constructor(
366 props: ProjectEntriesFailureContext & {
367 readonly cwd: string;
368 readonly queryLength: number;
369 readonly limit: number;
370 },
371 ) {
372 super({
373 ...props,
374 message:
375 decodedProjectErrorMessage(props) ??
376 `Failed to search workspace entries in '${props.cwd}'.`,
377 } as any);
378 }
380​
381export class ProjectSearchContentsError extends Schema.TaggedError<ProjectSearchContentsError>()(
382 "ProjectSearchContentsError",
383 {
384 cwd: Schema.optional(TrimmedNonEmptyString),
385 queryLength: Schema.optional(NonNegativeInt),
386 limit: Schema.optional(PositiveInt),
387 failure: Schema.optional(ProjectEntriesFailure),
388 normalizedCwd: Schema.optional(TrimmedNonEmptyString),
389 timeout: Schema.optional(TrimmedNonEmptyString),
390 detail: Schema.optional(TrimmedNonEmptyString),
391 message: TrimmedNonEmptyString,
392 cause: Schema.optional(Schema.Defect()),
393 },
394) {
395 // @effect-diagnostics-next-line overriddenSchemaConstructor:off
396 constructor(
397 props: ProjectEntriesFailureContext & {
398 readonly cwd: string;
399 readonly queryLength: number;
400 readonly limit: number;
401 },
402 ) {
403 super({
404 ...props,
405 message:
406 decodedProjectErrorMessage(props) ??
407 `Failed to search workspace contents in '${props.cwd}'.`,
408 } as any);
409 }
411​
412export class ProjectListEntriesError extends Schema.TaggedError<ProjectListEntriesError>()(
413 "ProjectListEntriesError",
414 {
415 cwd: Schema.optional(TrimmedNonEmptyString),
416 failure: Schema.optional(ProjectEntriesFailure),
417 normalizedCwd: Schema.optional(TrimmedNonEmptyString),
418 timeout: Schema.optional(TrimmedNonEmptyString),
419 detail: Schema.optional(TrimmedNonEmptyString),
420 message: TrimmedNonEmptyString,
421 cause: Schema.optional(Schema.Defect()),
422 },
423) {
424 // @effect-diagnostics-next-line overriddenSchemaConstructor:off
425 constructor(props: ProjectEntriesFailureContext & { readonly cwd: string }) {
426 super({
427 ...props,
428 message:
429 decodedProjectErrorMessage(props) ?? `Failed to list workspace entries in '${props.cwd}'.`,
430 } as any);
431 }
433​
434export const ProjectReadFileInput = Schema.Struct({
435 cwd: TrimmedNonEmptyString,
436 // Workspace-relative, or an absolute host path for a file outside the
437 // workspace. Only workspace-relative paths can be written back.
438 relativePath: TrimmedNonEmptyString.check(Schema.isMaxLength(PROJECT_READ_FILE_PATH_MAX_LENGTH)),
439});
440export type ProjectReadFileInput = typeof ProjectReadFileInput.Type;
441​
442export const ProjectReadFileResult = Schema.Struct({
443 relativePath: TrimmedNonEmptyString,
444 contents: Schema.String,
445 byteLength: NonNegativeInt,
446 truncated: Schema.Boolean,
447});
448export type ProjectReadFileResult = typeof ProjectReadFileResult.Type;
449​
450export const ProjectFileFailure = Schema.Literals([
451 "workspace_path_outside_root",
452 "resolved_path_outside_root",
453 "path_not_file",
454 "binary_file",
455 "operation_failed",
456]);
457export type ProjectFileFailure = typeof ProjectFileFailure.Type;
458​
459export const ProjectFileOperation = Schema.Literals([
460 "realpath-workspace-root",
461 "realpath-target",
462 "open",
463 "stat",
464 "read",
465 "close",
466 "make-directory",
467 "write-file",
468]);
469export type ProjectFileOperation = typeof ProjectFileOperation.Type;
470​
471type ProjectFileFailureContext = {
472 readonly cwd: string;
473 readonly relativePath: string;
474 readonly failure: ProjectFileFailure;
475 readonly resolvedPath?: string;
476 readonly resolvedWorkspaceRoot?: string;
477 readonly operation?: ProjectFileOperation;
478 readonly operationPath?: string;
479 readonly cause?: unknown;
480};
481​
482export class ProjectReadFileError extends Schema.TaggedError<ProjectReadFileError>()(
483 "ProjectReadFileError",
484 {
485 cwd: Schema.optional(TrimmedNonEmptyString),
486 relativePath: Schema.optional(TrimmedNonEmptyString),
487 failure: Schema.optional(ProjectFileFailure),
488 resolvedPath: Schema.optional(TrimmedNonEmptyString),
489 resolvedWorkspaceRoot: Schema.optional(TrimmedNonEmptyString),
490 operation: Schema.optional(ProjectFileOperation),
491 operationPath: Schema.optional(TrimmedNonEmptyString),
492 message: TrimmedNonEmptyString,
493 cause: Schema.optional(Schema.Defect()),
494 },
495) {
496 // @effect-diagnostics-next-line overriddenSchemaConstructor:off
497 constructor(props: ProjectFileFailureContext) {
498 super({
499 ...props,
500 message:
501 decodedProjectErrorMessage(props) ??
502 `Failed to read workspace file '${props.relativePath}' in '${props.cwd}'.`,
503 } as any);
504 }
506​
507export const ProjectWriteFileInput = Schema.Struct({
508 cwd: TrimmedNonEmptyString,
509 relativePath: TrimmedNonEmptyString.check(Schema.isMaxLength(PROJECT_WRITE_FILE_PATH_MAX_LENGTH)),
510 contents: Schema.String,
511});
512export type ProjectWriteFileInput = typeof ProjectWriteFileInput.Type;
513​
514export const ProjectWriteFileResult = Schema.Struct({
515 relativePath: TrimmedNonEmptyString,
516});
517export type ProjectWriteFileResult = typeof ProjectWriteFileResult.Type;
518​
519/** The environment's Scratch project, created on first request. */
520export const ProjectEnsureScratchResult = Schema.Struct({
521 projectId: ProjectId,
522});
523export type ProjectEnsureScratchResult = typeof ProjectEnsureScratchResult.Type;
524​
525/** A project started from just a name, in a new folder the server makes. */
526export const ProjectCreateNewInput = Schema.Struct({
527 name: TrimmedNonEmptyString.check(Schema.isMaxLength(200)),
528});
529export type ProjectCreateNewInput = typeof ProjectCreateNewInput.Type;
530​
531export const ProjectCreateNewResult = Schema.Struct({
532 projectId: ProjectId,
533 workspaceRoot: TrimmedNonEmptyString,
534 /** Why the first commit failed. The project and its files exist either way. */
535 commitError: Schema.optionalKey(TrimmedNonEmptyString),
536});
537export type ProjectCreateNewResult = typeof ProjectCreateNewResult.Type;
538​
539export class ProjectWriteFileError extends Schema.TaggedError<ProjectWriteFileError>()(
540 "ProjectWriteFileError",
541 {
542 cwd: Schema.optional(TrimmedNonEmptyString),
543 relativePath: Schema.optional(TrimmedNonEmptyString),
544 failure: Schema.optional(ProjectFileFailure),
545 resolvedPath: Schema.optional(TrimmedNonEmptyString),
546 resolvedWorkspaceRoot: Schema.optional(TrimmedNonEmptyString),
547 operation: Schema.optional(ProjectFileOperation),
548 operationPath: Schema.optional(TrimmedNonEmptyString),
549 message: TrimmedNonEmptyString,
550 cause: Schema.optional(Schema.Defect()),
551 },
552) {
553 // @effect-diagnostics-next-line overriddenSchemaConstructor:off
554 constructor(props: ProjectFileFailureContext) {
555 super({
556 ...props,
557 message:
558 decodedProjectErrorMessage(props) ??
559 `Failed to write workspace file '${props.relativePath}' in '${props.cwd}'.`,
560 } as any);
561 }