Open History to see the last commit
1/**
2 * Shared utilities for text generation layers (Codex, Claude, etc.).
3 *
4 * @module textGenerationUtils
5 */
6import { Schema } from "effect";
7
8import { TextGenerationError } from "@t3tools/contracts";
9
10import { existsSync } from "node:fs";
11import { join } from "node:path";
12
13export function isGitRepository(cwd: string): boolean {
14 return existsSync(join(cwd, ".git"));
15}
16
17/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
18export function toJsonSchemaObject(schema: Schema.Top): unknown {
19 const document = Schema.toJsonSchemaDocument(schema);
20 if (document.definitions && Object.keys(document.definitions).length > 0) {
21 return { ...document.schema, $defs: document.definitions };
22 }
23 return document.schema;
24}
25
26/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
27export function limitSection(value: string, maxChars: number): string {
28 if (value.length <= maxChars) return value;
29 const truncated = value.slice(0, maxChars);
30 return `${truncated}\n\n[truncated]`;
31}
32
33/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
34export function sanitizeCommitSubject(raw: string): string {
35 const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
36 const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
37 if (withoutTrailingPeriod.length === 0) {
38 return "Update project files";
39 }
40
41 if (withoutTrailingPeriod.length <= 72) {
42 return withoutTrailingPeriod;
43 }
44 return withoutTrailingPeriod.slice(0, 72).trimEnd();
45}
46
47/** Normalise a raw PR title to a single line with a sensible fallback. */
48export function sanitizePrTitle(raw: string): string {
49 const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
50 if (singleLine.length > 0) {
51 return singleLine;
52 }
53 return "Update project changes";
54}
55
56/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
57export function sanitizeThreadTitle(raw: string): string {
58 const normalized = raw
59 .trim()
60 .split(/\r?\n/g)[0]
61 ?.trim()
62 .replace(/^['"`]+|['"`]+$/g, "")
63 .trim()
64 .replace(/\s+/g, " ");
65
66 if (!normalized || normalized.trim().length === 0) {
67 return "New thread";
68 }
69
70 if (normalized.length <= 50) {
71 return normalized;
72 }
73
74 return `${normalized.slice(0, 47).trimEnd()}...`;
75}
76
77/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
78function cliLabel(cliName: string): string {
79 const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
80 return `${capitalized} CLI (\`${cliName}\`)`;
81}
82
83/**
84 * Normalize an unknown error from a CLI text generation process into a
85 * typed `TextGenerationError`. Parameterized by CLI name so both Codex
86 * and Claude (and future providers) can share the same logic.
87 */
88export function normalizeCliError(
89 cliName: string,
90 operation: string,
91 error: unknown,
92 fallback: string,
93): TextGenerationError {
94 if (Schema.is(TextGenerationError)(error)) {
95 return error;
96 }
97
98 if (error instanceof Error) {
99 const lower = error.message.toLowerCase();
100 if (
101 error.message.includes(`Command not found: ${cliName}`) ||
102 lower.includes(`spawn ${cliName}`) ||
103 lower.includes("enoent")
104 ) {
105 return new TextGenerationError({
106 operation,
107 detail: `${cliLabel(cliName)} is required but not available on PATH.`,
108 cause: error,
109 });
110 }
111 return new TextGenerationError({
112 operation,
113 detail: `${fallback}: ${error.message}`,
114 cause: error,
115 });
116 }
117
118 return new TextGenerationError({
119 operation,
120 detail: fallback,
121 cause: error,
122 });
123}