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