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

failure.ts

334 lines11.9 KB

1import type {
2 NodeId,
3 OrchestrationV2ProviderFailure,
4 OrchestrationV2ProviderFailureClass,
5 OrchestrationV2ProviderRetry,
6 OrchestrationV2TurnItem,
7 ProviderDriverKind,
8 ProviderThreadId,
9 ProviderTurnId,
10 RunId,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as DateTime from "effect/DateTime";
14import * as Cause from "effect/Cause";
15​
16import * as IdAllocator from "./IdAllocator.ts";
17import type { ProviderAdapterFailureReason } from "./ProviderAdapter.ts";
18import * as Schema from "effect/Schema";
19​
20export class ContextHandoffBudgetError extends Schema.TaggedError<ContextHandoffBudgetError>()(
21 "ContextHandoffBudgetError",
22 {},
23) {
24 override get message() {
25 return "The request leaves too little context for a provider handoff. Shorten the request or use a larger-context model; the current request has not been truncated.";
26 }
28​
29export class ContextHandoffBackgroundWorkError extends Schema.TaggedError<ContextHandoffBackgroundWorkError>()(
30 "ContextHandoffBackgroundWorkError",
31 {},
32) {
33 override get message() {
34 return "The target provider still has background work running. Wait for it to finish or stop it before retrying the handoff.";
35 }
37​
38export const MAX_PROVIDER_FAILURE_MESSAGE_LENGTH = 4_096;
39const MAX_PROVIDER_FAILURE_CODE_LENGTH = 128;
40​
41const DEFAULT_PROVIDER_FAILURE_MESSAGE = "Provider turn failed.";
42​
43const PROVIDER_FAILURE_CATEGORIES: Partial<
44 Record<string, { readonly summary: string; readonly guidance: string }>
45> = {
46 ProviderAdapterTurnStartError: {
47 summary: "The provider could not start this turn",
48 guidance: "Retry the turn; if it keeps failing, check the provider setup and server logs.",
49 },
50 ProviderAdapterEventStreamError: {
51 summary: "The provider event stream closed unexpectedly",
52 guidance: "Retry the turn; if it keeps failing, check the provider and server logs.",
53 },
54 ProviderAdapterOpenSessionError: {
55 summary: "The provider session could not be opened",
56 guidance: "Check that the provider is installed and signed in, then retry the turn.",
57 },
58 ProviderAdapterResumeThreadError: {
59 summary: "The provider conversation could not be resumed",
60 guidance: "Retry the turn; if it keeps failing, check the provider and server logs.",
61 },
62};
63​
64const PROVIDER_FAILURE_REASONS: Record<ProviderAdapterFailureReason, string> = {
65 previous_turn_active: "the previous turn is still running",
66 attachment_unreadable: "an attachment could not be read",
67};
68​
69/**
70 * Walks a cause chain for curated text without reading arbitrary provider
71 * defect text. `known` is the message of a domain error T3 raised itself;
72 * `category` is the generic message of the innermost provider wrapper seen.
73 */
74function curatedCauseMessages(cause: unknown): {
75 readonly known: string | undefined;
76 readonly category: string | undefined;
77} {
78 const seen = new Set<unknown>();
79 let category: (typeof PROVIDER_FAILURE_CATEGORIES)[string];
80 let reason: string | undefined;
81 const categoryMessage = () => {
82 if (category === undefined) return undefined;
83 return reason
84 ? `${category.summary}: ${reason}. ${category.guidance}`
85 : `${category.summary}. ${category.guidance}`;
86 };
87 for (let depth = 0; depth < 16 && cause != null && !seen.has(cause); depth++) {
88 seen.add(cause);
89 try {
90 if (Cause.isCause(cause)) {
91 cause = Cause.squash(cause);
92 continue;
93 }
94 if (typeof cause !== "object") break;
95 const tag = (cause as Record<string, unknown>)._tag;
96 switch (tag) {
97 case "ContextHandoffBudgetError":
98 return { known: new ContextHandoffBudgetError().message, category: categoryMessage() };
99 case "ContextHandoffBackgroundWorkError":
100 return {
101 known: new ContextHandoffBackgroundWorkError().message,
102 category: categoryMessage(),
103 };
104 case "AcpModelSelectionError":
105 case "ClaudeBackgroundWorkBlocksQueryReplacementError":
106 case "ClaudeAppendSystemPromptFileError":
107 case "ClaudeAppendSystemPromptMissingValueError":
108 case "ClaudeSettingsLaunchArgError":
109 case "ClaudeMcpRegistrationTimeoutError":
110 case "CursorModelUnavailableError":
111 case "ProviderSetupError":
112 return { known: stringField(cause, "message"), category: categoryMessage() };
113 case "ContextHandoffDeliveryUncertainError":
114 return {
115 known:
116 "T3 could not confirm whether conversation history reached the provider. Retry the turn to recover the session.",
117 category: categoryMessage(),
118 };
119 case "ProviderAdapterProtocolError": {
120 const typedReason = (cause as Record<string, unknown>).reason;
121 if (
122 category !== undefined &&
123 typeof typedReason === "string" &&
124 Object.hasOwn(PROVIDER_FAILURE_REASONS, typedReason)
125 ) {
126 reason ??= PROVIDER_FAILURE_REASONS[typedReason as ProviderAdapterFailureReason];
127 }
128 break;
129 }
130 }
131 if (typeof tag === "string" && Object.hasOwn(PROVIDER_FAILURE_CATEGORIES, tag)) {
132 category = PROVIDER_FAILURE_CATEGORIES[tag];
133 reason = undefined;
134 }
135 cause = (cause as Record<string, unknown>).cause;
136 } catch {
137 break;
138 }
139 }
140 return { known: undefined, category: categoryMessage() };
142​
143/**
144 * The curated message of a domain error in a failure's cause chain, if any.
145 * Callers that pass their own `message` to `makeProviderFailure` check it
146 * first, so a known reason is not hidden behind a wrapper's text.
147 */
148export function knownProviderFailureMessage(cause: unknown): string | undefined {
149 return curatedCauseMessages(cause).known;
151​
152function stringField(value: unknown, key: "message" | "code"): string | undefined {
153 if (typeof value !== "object" || value === null) return undefined;
154 try {
155 const candidate = (value as Record<string, unknown>)[key];
156 return typeof candidate === "string" ? candidate : undefined;
157 } catch {
158 return undefined;
159 }
161​
162function redactUrl(match: string): string {
163 const trailing = /[),.;!?]+$/u.exec(match)?.[0] ?? "";
164 const candidate = trailing.length === 0 ? match : match.slice(0, -trailing.length);
165 try {
166 const url = new URL(candidate);
167 url.username = "";
168 url.password = "";
169 url.search = "";
170 url.hash = "";
171 return `${url.toString()}${trailing}`;
172 } catch {
173 return "[REDACTED_URL]";
174 }
176​
177function replaceUnsafeControlCharacters(value: string): string {
178 const sanitized: Array<string> = [];
179 for (const character of value) {
180 const codePoint = character.codePointAt(0) ?? 0;
181 sanitized.push(
182 codePoint <= 0x08 ||
183 (codePoint >= 0x0b && codePoint <= 0x0c) ||
184 (codePoint >= 0x0e && codePoint <= 0x1f) ||
185 codePoint === 0x7f
186 ? " "
187 : character,
188 );
189 }
190 return sanitized.join("");
192​
193function redactProviderFailureText(value: string): string {
194 return replaceUnsafeControlCharacters(value)
195 .replace(/\bhttps?:\/\/[^\s<>"']+/giu, redactUrl)
196 .replace(/\b(Bearer|Basic)\s+[^\s,;]+/giu, "$1 [REDACTED]")
197 .replace(
198 /(["'][\w-]*(?:access[_-]?token|api[_-]?key|authorization|credential|password|secret|token)["']\s*:\s*["'])[^"']*(["'])/giu,
199 "$1[REDACTED]$2",
200 )
201 .replace(
202 /((?<![\w-])[\w-]*(?:access[_-]?token|api[_-]?key|authorization|credential|password|secret|token)\b\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/giu,
203 "$1[REDACTED]",
204 )
205 .replace(/\bsk-[A-Za-z0-9_-]{16,}\b/gu, "[REDACTED]")
206 .trim();
208​
209function boundedText(value: string, maxLength: number): string {
210 const redacted = redactProviderFailureText(value);
211 if (redacted.length <= maxLength) return redacted;
212 let end = Math.max(0, maxLength - 1);
213 const finalCodeUnit = redacted.charCodeAt(end - 1);
214 if (finalCodeUnit >= 0xd800 && finalCodeUnit <= 0xdbff) {
215 end -= 1;
216 }
217 return `${redacted.slice(0, end)}…`;
219​
220export function makeProviderFailure(input: {
221 readonly cause?: unknown;
222 readonly message?: string | undefined;
223 readonly code?: string | null | undefined;
224 readonly class?: OrchestrationV2ProviderFailureClass;
225 readonly retryable?: boolean | null;
226 readonly resetAt?: string | null;
227}): OrchestrationV2ProviderFailure {
228 const curated = curatedCauseMessages(input.cause);
229 const rawMessage =
230 input.message ?? curated.known ?? curated.category ?? DEFAULT_PROVIDER_FAILURE_MESSAGE;
231 const message = boundedText(rawMessage, MAX_PROVIDER_FAILURE_MESSAGE_LENGTH);
232 const rawCode = input.code ?? stringField(input.cause, "code") ?? null;
233 const code =
234 rawCode === null ? null : boundedText(rawCode, MAX_PROVIDER_FAILURE_CODE_LENGTH) || null;
235​
236 return {
237 class: input.class ?? "unknown",
238 message: message || DEFAULT_PROVIDER_FAILURE_MESSAGE,
239 code,
240 retryable: input.retryable ?? null,
241 ...(input.class === "usage_limit" &&
242 input.resetAt != null &&
243 Number.isFinite(Date.parse(input.resetAt))
244 ? { resetAt: DateTime.formatIso(DateTime.makeUnsafe(input.resetAt)) }
245 : {}),
246 };
248​
249export function makeProviderFailureTurnItem(input: {
250 readonly driver: ProviderDriverKind;
251 readonly threadId: ThreadId;
252 readonly runId: RunId | null;
253 readonly nodeId: NodeId | null;
254 readonly providerThreadId: ProviderThreadId;
255 readonly providerTurnId: ProviderTurnId;
256 readonly itemOrdinal: number;
257 readonly failure: OrchestrationV2ProviderFailure;
258 readonly retry?: OrchestrationV2ProviderRetry;
259 readonly retryStartedAt?: DateTime.Utc;
260 readonly occurredAt: DateTime.Utc;
261}): Extract<OrchestrationV2TurnItem, { readonly type: "error" }> {
262 return {
263 id: IdAllocator.derive.turnItemFromProviderItem({
264 driver: input.driver,
265 nativeItemId: `terminal-failure:${input.providerTurnId}`,
266 }),
267 threadId: input.threadId,
268 runId: input.runId,
269 nodeId: input.nodeId,
270 providerThreadId: input.providerThreadId,
271 providerTurnId: input.providerTurnId,
272 nativeItemRef: null,
273 parentItemId: null,
274 ordinal: input.itemOrdinal,
275 status: "failed",
276 title: input.failure.class === "usage_limit" ? "Usage limit reached" : "Provider error",
277 startedAt: input.retryStartedAt ?? input.occurredAt,
278 completedAt: input.occurredAt,
279 updatedAt: input.occurredAt,
280 type: "error",
281 failure: input.failure,
282 ...(input.retry === undefined ? {} : { retry: input.retry }),
283 };
285​
286export function makeProviderRetryTurnItem(input: {
287 readonly driver: ProviderDriverKind;
288 readonly threadId: ThreadId;
289 readonly runId: RunId | null;
290 readonly nodeId: NodeId | null;
291 readonly providerThreadId: ProviderThreadId;
292 readonly providerTurnId: ProviderTurnId;
293 readonly itemOrdinal: number;
294 readonly failure: OrchestrationV2ProviderFailure;
295 readonly retry: OrchestrationV2ProviderRetry;
296 readonly status: Extract<
297 OrchestrationV2TurnItem["status"],
298 "running" | "completed" | "failed" | "interrupted" | "cancelled"
299 >;
300 readonly startedAt: DateTime.Utc;
301 readonly updatedAt: DateTime.Utc;
302}): Extract<OrchestrationV2TurnItem, { readonly type: "error" }> {
303 const completed = input.status !== "running";
304 let title = "Provider retry";
305 if (input.status === "completed") {
306 title = "Provider recovered";
307 } else if (input.status === "failed") {
308 title = input.failure.class === "usage_limit" ? "Usage limit reached" : "Provider error";
309 } else if (input.status === "interrupted" || input.status === "cancelled") {
310 title = "Provider retry stopped";
311 }
312 return {
313 id: IdAllocator.derive.turnItemFromProviderItem({
314 driver: input.driver,
315 nativeItemId: `terminal-failure:${input.providerTurnId}`,
316 }),
317 threadId: input.threadId,
318 runId: input.runId,
319 nodeId: input.nodeId,
320 providerThreadId: input.providerThreadId,
321 providerTurnId: input.providerTurnId,
322 nativeItemRef: null,
323 parentItemId: null,
324 ordinal: input.itemOrdinal,
325 status: input.status,
326 title,
327 startedAt: input.startedAt,
328 completedAt: completed ? input.updatedAt : null,
329 updatedAt: input.updatedAt,
330 type: "error",
331 failure: input.failure,
332 retry: input.retry,
333 };