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