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

Utils.ts

171 lines4.5 KB

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"));
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;
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]`;
32​
33export function extractJsonObject(raw: string): string {
34 const trimmed = raw.trim();
35 if (trimmed.length === 0) {
36 return trimmed;
37 }
38​
39 const start = trimmed.indexOf("{");
40 if (start < 0) {
41 return trimmed;
42 }
43​
44 let depth = 0;
45 let inString = false;
46 let escaping = false;
47 for (let index = start; index < trimmed.length; index += 1) {
48 const char = trimmed[index];
49 if (inString) {
50 if (escaping) {
51 escaping = false;
52 } else if (char === "\\") {
53 escaping = true;
54 } else if (char === '"') {
55 inString = false;
56 }
57 continue;
58 }
59​
60 if (char === '"') {
61 inString = true;
62 continue;
63 }
64​
65 if (char === "{") {
66 depth += 1;
67 continue;
68 }
69​
70 if (char === "}") {
71 depth -= 1;
72 if (depth === 0) {
73 return trimmed.slice(start, index + 1);
74 }
75 }
76 }
77​
78 return trimmed.slice(start);
80​
81/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
82export function sanitizeCommitSubject(raw: string): string {
83 const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
84 const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
85 if (withoutTrailingPeriod.length === 0) {
86 return "Update project files";
87 }
88​
89 if (withoutTrailingPeriod.length <= 72) {
90 return withoutTrailingPeriod;
91 }
92 return withoutTrailingPeriod.slice(0, 72).trimEnd();
94​
95/** Normalise a raw PR title to a single line with a sensible fallback. */
96export function sanitizePrTitle(raw: string): string {
97 const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
98 if (singleLine.length > 0) {
99 return singleLine;
100 }
101 return "Update project changes";
103​
104/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
105export function sanitizeThreadTitle(raw: string): string {
106 const normalized = raw
107 .trim()
108 .split(/\r?\n/g)[0]
109 ?.trim()
110 .replace(/^['"`]+|['"`]+$/g, "")
111 .trim()
112 .replace(/\s+/g, " ");
113​
114 if (!normalized || normalized.trim().length === 0) {
115 return "New thread";
116 }
117​
118 if (normalized.length <= 50) {
119 return normalized;
120 }
121​
122 return `${normalized.slice(0, 47).trimEnd()}...`;
124​
125/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
126function cliLabel(cliName: string): string {
127 const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
128 return `${capitalized} CLI (\`${cliName}\`)`;
130​
131/**
132 * Normalize an unknown error from a CLI text generation process into a
133 * typed `TextGenerationError`. Parameterized by CLI name so both Codex
134 * and Claude (and future providers) can share the same logic.
135 */
136export function normalizeCliError(
137 cliName: string,
138 operation: string,
139 error: unknown,
140 fallback: string,
141): TextGenerationError {
142 if (Schema.is(TextGenerationError)(error)) {
143 return error;
144 }
145​
146 if (error instanceof Error) {
147 const lower = error.message.toLowerCase();
148 if (
149 error.message.includes(`Command not found: ${cliName}`) ||
150 lower.includes(`spawn ${cliName}`) ||
151 lower.includes("enoent")
152 ) {
153 return new TextGenerationError({
154 operation,
155 detail: `${cliLabel(cliName)} is required but not available on PATH.`,
156 cause: error,
157 });
158 }
159 return new TextGenerationError({
160 operation,
161 detail: `${fallback}: ${error.message}`,
162 cause: error,
163 });
164 }
165​
166 return new TextGenerationError({
167 operation,
168 detail: fallback,
169 cause: error,
170 });