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