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

failure.ts

371 lines13.6 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​
64// codex_protocol::protocol::validate_thread_goal_objective
65const CODEX_GOAL_VALIDATION_MESSAGE =
66 /^goal objective must (?:not be empty|be at most \d{1,6} characters)$/u;
67​
68const PROVIDER_FAILURE_REASONS: Record<ProviderAdapterFailureReason, string> = {
69 previous_turn_active: "the previous turn is still running",
70 attachment_unreadable: "an attachment could not be read",
71};
72​
73/**
74 * Walks a cause chain for curated text without reading arbitrary provider
75 * defect text. `known` is the message of a domain error T3 raised itself;
76 * `category` is the generic message of the innermost provider wrapper seen.
77 */
78function curatedCauseMessages(cause: unknown): {
79 readonly known: string | undefined;
80 readonly category: string | undefined;
81} {
82 const seen = new Set<unknown>();
83 let category: (typeof PROVIDER_FAILURE_CATEGORIES)[string];
84 let reason: string | undefined;
85 const categoryMessage = () => {
86 if (category === undefined) return undefined;
87 return reason
88 ? `${category.summary}: ${reason}. ${category.guidance}`
89 : `${category.summary}. ${category.guidance}`;
90 };
91 for (let depth = 0; depth < 16 && cause != null && !seen.has(cause); depth++) {
92 seen.add(cause);
93 try {
94 if (Cause.isCause(cause)) {
95 cause = Cause.squash(cause);
96 continue;
97 }
98 if (typeof cause !== "object") break;
99 const tag = (cause as Record<string, unknown>)._tag;
100 switch (tag) {
101 case "ContextHandoffBudgetError":
102 return { known: new ContextHandoffBudgetError().message, category: categoryMessage() };
103 case "ContextHandoffBackgroundWorkError":
104 return {
105 known: new ContextHandoffBackgroundWorkError().message,
106 category: categoryMessage(),
107 };
108 case "AcpModelSelectionError":
109 case "ClaudeBackgroundWorkBlocksQueryReplacementError":
110 case "ClaudeAppendSystemPromptFileError":
111 case "ClaudeAppendSystemPromptMissingValueError":
112 case "ClaudeSettingsLaunchArgError":
113 case "ClaudeMcpRegistrationTimeoutError":
114 case "ClaudeCodeRootRefusalError":
115 case "CursorModelUnavailableError":
116 case "CodexGoalObjectiveTooLongError":
117 case "ProviderSetupError":
118 case "ProviderAdapterThreadInUseError":
119 return { known: stringField(cause, "message"), category: categoryMessage() };
120 case "CodexAppServerRequestError": {
121 // Only Codex's fixed-shape goal validation text is actionable and
122 // safe to show; other request error text stays hidden.
123 const rejection = stringField(cause, "message");
124 if (
125 (cause as Record<string, unknown>).method === "thread/goal/set" &&
126 rejection !== undefined &&
127 CODEX_GOAL_VALIDATION_MESSAGE.test(rejection)
128 ) {
129 return { known: `Codex rejected the goal: ${rejection}.`, category: categoryMessage() };
130 }
131 break;
132 }
133 case "AcpProcessExitedError": {
134 const exit = `provider process exited${processExitStatus(cause)}`;
135 const stage = category === undefined ? `The ${exit}` : `${category.summary}: the ${exit}`;
136 return {
137 known: `${stage}. Check the server logs for the provider's output, then retry the turn.`,
138 category: categoryMessage(),
139 };
140 }
141 case "ContextHandoffDeliveryUncertainError":
142 return {
143 known:
144 "T3 could not confirm whether conversation history reached the provider. Retry the turn to recover the session.",
145 category: categoryMessage(),
146 };
147 case "ProviderAdapterProtocolError": {
148 const typedReason = (cause as Record<string, unknown>).reason;
149 if (
150 category !== undefined &&
151 typeof typedReason === "string" &&
152 Object.hasOwn(PROVIDER_FAILURE_REASONS, typedReason)
153 ) {
154 reason ??= PROVIDER_FAILURE_REASONS[typedReason as ProviderAdapterFailureReason];
155 }
156 break;
157 }
158 }
159 if (typeof tag === "string" && Object.hasOwn(PROVIDER_FAILURE_CATEGORIES, tag)) {
160 category = PROVIDER_FAILURE_CATEGORIES[tag];
161 reason = undefined;
162 }
163 cause = (cause as Record<string, unknown>).cause;
164 } catch {
165 break;
166 }
167 }
168 return { known: undefined, category: categoryMessage() };
170​
171// Only the structured status; stderr and the spawner cause can carry provider output.
172function processExitStatus(exited: object): string {
173 const { signal, code } = exited as Record<string, unknown>;
174 if (typeof signal === "string" && /^SIG[A-Z0-9]{1,16}$/u.test(signal)) {
175 return ` after signal ${signal}`;
176 }
177 return typeof code === "number" && Number.isSafeInteger(code) ? ` with code ${code}` : "";
179​
180/**
181 * The curated message of a domain error in a failure's cause chain, if any.
182 * Callers that pass their own `message` to `makeProviderFailure` check it
183 * first, so a known reason is not hidden behind a wrapper's text.
184 */
185export function knownProviderFailureMessage(cause: unknown): string | undefined {
186 return curatedCauseMessages(cause).known;
188​
189function stringField(value: unknown, key: "message" | "code"): string | undefined {
190 if (typeof value !== "object" || value === null) return undefined;
191 try {
192 const candidate = (value as Record<string, unknown>)[key];
193 return typeof candidate === "string" ? candidate : undefined;
194 } catch {
195 return undefined;
196 }
198​
199function redactUrl(match: string): string {
200 const trailing = /[),.;!?]+$/u.exec(match)?.[0] ?? "";
201 const candidate = trailing.length === 0 ? match : match.slice(0, -trailing.length);
202 try {
203 const url = new URL(candidate);
204 url.username = "";
205 url.password = "";
206 url.search = "";
207 url.hash = "";
208 return `${url.toString()}${trailing}`;
209 } catch {
210 return "[REDACTED_URL]";
211 }
213​
214function replaceUnsafeControlCharacters(value: string): string {
215 const sanitized: Array<string> = [];
216 for (const character of value) {
217 const codePoint = character.codePointAt(0) ?? 0;
218 sanitized.push(
219 codePoint <= 0x08 ||
220 (codePoint >= 0x0b && codePoint <= 0x0c) ||
221 (codePoint >= 0x0e && codePoint <= 0x1f) ||
222 codePoint === 0x7f
223 ? " "
224 : character,
225 );
226 }
227 return sanitized.join("");
229​
230function redactProviderFailureText(value: string): string {
231 return replaceUnsafeControlCharacters(value)
232 .replace(/\bhttps?:\/\/[^\s<>"']+/giu, redactUrl)
233 .replace(/\b(Bearer|Basic)\s+[^\s,;]+/giu, "$1 [REDACTED]")
234 .replace(
235 /(["'][\w-]*(?:access[_-]?token|api[_-]?key|authorization|credential|password|secret|token)["']\s*:\s*["'])[^"']*(["'])/giu,
236 "$1[REDACTED]$2",
237 )
238 .replace(
239 /((?<![\w-])[\w-]*(?:access[_-]?token|api[_-]?key|authorization|credential|password|secret|token)\b\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/giu,
240 "$1[REDACTED]",
241 )
242 .replace(/\bsk-[A-Za-z0-9_-]{16,}\b/gu, "[REDACTED]")
243 .trim();
245​
246function boundedText(value: string, maxLength: number): string {
247 const redacted = redactProviderFailureText(value);
248 if (redacted.length <= maxLength) return redacted;
249 let end = Math.max(0, maxLength - 1);
250 const finalCodeUnit = redacted.charCodeAt(end - 1);
251 if (finalCodeUnit >= 0xd800 && finalCodeUnit <= 0xdbff) {
252 end -= 1;
253 }
254 return `${redacted.slice(0, end)}…`;
256​
257export function makeProviderFailure(input: {
258 readonly cause?: unknown;
259 readonly message?: string | undefined;
260 readonly code?: string | null | undefined;
261 readonly class?: OrchestrationV2ProviderFailureClass;
262 readonly retryable?: boolean | null;
263 readonly resetAt?: string | null;
264}): OrchestrationV2ProviderFailure {
265 const curated = curatedCauseMessages(input.cause);
266 const rawMessage =
267 input.message ?? curated.known ?? curated.category ?? DEFAULT_PROVIDER_FAILURE_MESSAGE;
268 const message = boundedText(rawMessage, MAX_PROVIDER_FAILURE_MESSAGE_LENGTH);
269 const rawCode = input.code ?? stringField(input.cause, "code") ?? null;
270 const code =
271 rawCode === null ? null : boundedText(rawCode, MAX_PROVIDER_FAILURE_CODE_LENGTH) || null;
272​
273 return {
274 class: input.class ?? "unknown",
275 message: message || DEFAULT_PROVIDER_FAILURE_MESSAGE,
276 code,
277 retryable: input.retryable ?? null,
278 ...(input.class === "usage_limit" &&
279 input.resetAt != null &&
280 Number.isFinite(Date.parse(input.resetAt))
281 ? { resetAt: DateTime.formatIso(DateTime.makeUnsafe(input.resetAt)) }
282 : {}),
283 };
285​
286export function makeProviderFailureTurnItem(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 retryStartedAt?: DateTime.Utc;
297 readonly occurredAt: DateTime.Utc;
298}): Extract<OrchestrationV2TurnItem, { readonly type: "error" }> {
299 return {
300 id: IdAllocator.derive.turnItemFromProviderItem({
301 driver: input.driver,
302 nativeItemId: `terminal-failure:${input.providerTurnId}`,
303 }),
304 threadId: input.threadId,
305 runId: input.runId,
306 nodeId: input.nodeId,
307 providerThreadId: input.providerThreadId,
308 providerTurnId: input.providerTurnId,
309 nativeItemRef: null,
310 parentItemId: null,
311 ordinal: input.itemOrdinal,
312 status: "failed",
313 title: input.failure.class === "usage_limit" ? "Usage limit reached" : "Provider error",
314 startedAt: input.retryStartedAt ?? input.occurredAt,
315 completedAt: input.occurredAt,
316 updatedAt: input.occurredAt,
317 type: "error",
318 failure: input.failure,
319 ...(input.retry === undefined ? {} : { retry: input.retry }),
320 };
322​
323export function makeProviderRetryTurnItem(input: {
324 readonly driver: ProviderDriverKind;
325 readonly threadId: ThreadId;
326 readonly runId: RunId | null;
327 readonly nodeId: NodeId | null;
328 readonly providerThreadId: ProviderThreadId;
329 readonly providerTurnId: ProviderTurnId;
330 readonly itemOrdinal: number;
331 readonly failure: OrchestrationV2ProviderFailure;
332 readonly retry: OrchestrationV2ProviderRetry;
333 readonly status: Extract<
334 OrchestrationV2TurnItem["status"],
335 "running" | "completed" | "failed" | "interrupted" | "cancelled"
336 >;
337 readonly startedAt: DateTime.Utc;
338 readonly updatedAt: DateTime.Utc;
339}): Extract<OrchestrationV2TurnItem, { readonly type: "error" }> {
340 const completed = input.status !== "running";
341 let title = "Provider retry";
342 if (input.status === "completed") {
343 title = "Provider recovered";
344 } else if (input.status === "failed") {
345 title = input.failure.class === "usage_limit" ? "Usage limit reached" : "Provider error";
346 } else if (input.status === "interrupted" || input.status === "cancelled") {
347 title = "Provider retry stopped";
348 }
349 return {
350 id: IdAllocator.derive.turnItemFromProviderItem({
351 driver: input.driver,
352 nativeItemId: `terminal-failure:${input.providerTurnId}`,
353 }),
354 threadId: input.threadId,
355 runId: input.runId,
356 nodeId: input.nodeId,
357 providerThreadId: input.providerThreadId,
358 providerTurnId: input.providerTurnId,
359 nativeItemRef: null,
360 parentItemId: null,
361 ordinal: input.itemOrdinal,
362 status: input.status,
363 title,
364 startedAt: input.startedAt,
365 completedAt: completed ? input.updatedAt : null,
366 updatedAt: input.updatedAt,
367 type: "error",
368 failure: input.failure,
369 retry: input.retry,
370 };