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

TextGenerationUtils.ts

123 lines3.9 KB

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.toType(schema));
13 if (document.definitions && Object.keys(document.definitions).length > 0) {
14 return { ...document.schema, $defs: document.definitions };
15 }
16 return document.schema;
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]`;
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();
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";
48​
49// Prompts ask for under 40 characters. This cap only stops a runaway model
50// from pushing a paragraph into the sidebar, header, and window title.
51const MAX_THREAD_TITLE_CHARS = 120;
52​
53/** Normalise a raw thread title to a single line. Clients truncate for display. */
54export function sanitizeThreadTitle(raw: string): string {
55 // Unwrap a JSON-formatted title before truncation can cut off the closing brace.
56 const decoded = decodeJsonThreadTitle(raw);
57 const title = Option.isSome(decoded) ? decoded.value.title : raw;
58 const normalized = title
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 <= MAX_THREAD_TITLE_CHARS) {
71 return normalized;
72 }
73​
74 return `${normalized.slice(0, MAX_THREAD_TITLE_CHARS - 3).trimEnd()}...`;
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}\`)`;
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 (isTextGenerationError(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,
114 cause: error,
115 });
116 }
117​
118 return new TextGenerationError({
119 operation,
120 detail: fallback,
121 cause: error,
122 });