Open History to see the last commit
1import { PROVIDER_DISPLAY_NAMES, type ProviderDriverKind } from "@t3tools/contracts";
2import * as Predicate from "effect/Predicate";
3import * as SqlError from "effect/sql/SqlError";
4
5const GENERIC_ERROR_PREFIXES = [
6 "Failed to dispatch orchestration V2 command",
7 "Failed to dispatch orchestration command ",
8 "Provider adapter failed while dispatching orchestration command ",
9];
10
11const SQLITE_RECOVERY_MESSAGES: Readonly<Record<number, string>> = {
12 5: "The T3 Code server database is busy (SQLITE_BUSY). Wait a moment, then retry. If this keeps happening, check for another T3 Code process using the same data directory on the server.",
13 6: "The T3 Code server database is locked (SQLITE_LOCKED). Wait a moment, then retry. If this keeps happening, check the server logs for the process holding the database lock.",
14 8: "The T3 Code server database is read-only (SQLITE_READONLY). On the machine running the server, check that its data directory is writable and its disk is mounted read-write, then retry.",
15 10: "The T3 Code server could not read or write its database (SQLITE_IOERR). On the machine running the server, check free disk space and disk health, then retry. If it still fails, check the server logs.",
16 11: "The T3 Code server database appears damaged (SQLITE_CORRUPT). Preserve the server data directory and check the server logs before restoring a database backup.",
17 13: "The T3 Code server could not save this change because its database or disk is full (SQLITE_FULL). Free space on the machine running the server, then retry. If space is available, check the server logs for a database size limit.",
18 14: "The T3 Code server could not open a database file (SQLITE_CANTOPEN). On the machine running the server, check free disk space and that its data and temporary directories exist and are writable, then retry. If it still fails, check the server logs.",
19 26: "The T3 Code server could not read its database file (SQLITE_NOTADB). Preserve the server data directory and check the configured database path and server logs before restoring a database backup.",
20};
21
22function databaseErrorMessage(value: unknown): string | undefined {
23 if (!SqlError.isSqlError(value)) return undefined;
24
25 let cause: unknown = value.cause;
26 const seen = new Set<unknown>();
27 while (Predicate.isObject(cause) && !seen.has(cause)) {
28 seen.add(cause);
29 // node:sqlite uses extended result codes; their low byte is the primary code.
30 if (typeof cause.errcode === "number" && Number.isInteger(cause.errcode) && cause.errcode > 0) {
31 const message = SQLITE_RECOVERY_MESSAGES[cause.errcode & 0xff];
32 if (message !== undefined) return message;
33 }
34 cause = cause.cause;
35 }
36
37 return "The T3 Code server could not complete this database request. Retry once; if it still fails, check the server logs for the database error.";
38}
39
40const CAPABILITY_REJECTION_MESSAGES: Record<string, (provider: string) => string> = {
41 queued_messages: (p) => `${p} cannot queue messages behind an active run.`,
42 active_steering: (p) =>
43 `${p} cannot redirect an active run. Stop it first, then send the message.`,
44 interrupt_restart_steering: (p) =>
45 `${p} cannot redirect an active run. Stop it first, then send the message.`,
46 interrupt: (p) => `${p} cannot stop a run once it has started.`,
47 native_fork: (p) => `${p} cannot fork this thread natively.`,
48 fork_from_turn: (p) => `${p} cannot fork from an earlier point in this thread.`,
49 rollback: (p) =>
50 `${p} cannot rewind its conversation, so this checkpoint cannot be restored on this thread.`,
51 rollback_snapshot: (p) =>
52 `${p} did not report its rewound conversation state, so the checkpoint was not restored.`,
53 context_handoff: (p) => `${p} cannot receive the context handoff needed for this switch.`,
54 strong_terminal_status: (p) =>
55 `${p} cannot confirm when its runs finish reliably enough for this.`,
56};
57
58function providerDisplayName(instanceId: string): string {
59 const known = PROVIDER_DISPLAY_NAMES[instanceId as ProviderDriverKind];
60 if (known !== undefined) return known;
61 const trimmed = instanceId.replace(/Agent$/i, "").trim();
62 if (trimmed.length === 0) return instanceId;
63 return trimmed.charAt(0).toUpperCase() + trimmed.slice(1);
64}
65
66function policyRejectionMessage(value: unknown): string | undefined {
67 if (!Predicate.isObject(value) || typeof value.providerInstanceId !== "string") return undefined;
68 const provider = providerDisplayName(value.providerInstanceId);
69 if (value._tag === "CommandPolicyCapabilityUnsupportedError") {
70 const capability = typeof value.capability === "string" ? value.capability : "";
71 return CAPABILITY_REJECTION_MESSAGES[capability]?.(provider);
72 }
73 if (value._tag === "CommandPolicyUnsupportedError") {
74 return `${provider} cannot deliver a message that way right now.`;
75 }
76 return undefined;
77}
78
79function textValue(value: unknown): string | undefined {
80 return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
81}
82
83function messageFrom(value: unknown): string | undefined {
84 if (typeof value === "string") {
85 return textValue(value);
86 }
87 const friendly = policyRejectionMessage(value);
88 if (friendly !== undefined) {
89 return friendly;
90 }
91 if (value instanceof Error) {
92 return textValue(value.message);
93 }
94 if (!Predicate.isObject(value)) {
95 return undefined;
96 }
97 return textValue(value.detail) ?? textValue(value.message);
98}
99
100function isGenericErrorMessage(message: string): boolean {
101 return GENERIC_ERROR_PREFIXES.some((prefix) => message.startsWith(prefix));
102}
103
104function collectErrorMessages(value: unknown, seen: Set<unknown>): ReadonlyArray<string> {
105 if (value === undefined || value === null || seen.has(value)) {
106 return [];
107 }
108 seen.add(value);
109
110 if (Array.isArray(value)) {
111 return value.flatMap((item) => collectErrorMessages(item, seen));
112 }
113
114 const databaseMessage = databaseErrorMessage(value);
115 if (databaseMessage !== undefined) return [databaseMessage];
116
117 const message = messageFrom(value);
118 if (!Predicate.isObject(value)) {
119 return message === undefined ? [] : [message];
120 }
121
122 const nested = [
123 ...collectErrorMessages(value.cause, seen),
124 ...collectErrorMessages(value.error, seen),
125 ...collectErrorMessages(value.errors, seen),
126 ];
127
128 return message === undefined ? nested : [message, ...nested];
129}
130
131export function userFacingDispatchErrorMessage(cause: unknown): string | undefined {
132 const messages = collectErrorMessages(cause, new Set()).filter(
133 (message, index, allMessages) =>
134 !isGenericErrorMessage(message) && allMessages.indexOf(message) === index,
135 );
136 return messages.at(-1);
137}