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

ProviderFailure.ts

251 lines8.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 type { IdAllocatorV2Shape } from "./IdAllocator.ts";
17import { ContextHandoffBudgetError } from "./ContextHandoffDelivery.ts";
18​
19export const MAX_PROVIDER_FAILURE_MESSAGE_LENGTH = 4_096;
20export const MAX_PROVIDER_FAILURE_CODE_LENGTH = 128;
21​
22const DEFAULT_PROVIDER_FAILURE_MESSAGE = "Provider turn failed.";
23​
24/** Translate known categories without exposing arbitrary provider defect text. */
25function causeMessage(cause: unknown): string | undefined {
26 const seen = new Set<unknown>();
27 let message: string | undefined;
28 for (let depth = 0; depth < 16 && cause != null && !seen.has(cause); depth++) {
29 seen.add(cause);
30 try {
31 if (Cause.isCause(cause)) {
32 cause = Cause.squash(cause);
33 continue;
34 }
35 if (typeof cause !== "object") break;
36 switch ((cause as Record<string, unknown>)._tag) {
37 case "ContextHandoffBudgetError":
38 return new ContextHandoffBudgetError().message;
39 case "ClaudeBackgroundWorkBlocksQueryReplacementError":
40 return stringField(cause, "message");
41 case "ContextHandoffDeliveryUncertainError":
42 return "T3 could not confirm whether conversation history reached the provider. Retry the turn to recover the session.";
43 case "ProviderAdapterTurnStartError":
44 message =
45 "The provider could not start this turn. Retry the turn; if it keeps failing, check the provider setup and server logs.";
46 break;
47 case "ProviderAdapterEventStreamError":
48 message =
49 "The provider event stream closed unexpectedly. Retry the turn; if it keeps failing, check the provider and server logs.";
50 break;
51 case "ProviderAdapterOpenSessionError":
52 message =
53 "The provider session could not be opened. Check that the provider is installed and signed in, then retry the turn.";
54 break;
55 case "ProviderAdapterResumeThreadError":
56 message =
57 "The provider conversation could not be resumed. Retry the turn; if it keeps failing, check the provider and server logs.";
58 break;
59 }
60 cause = (cause as Record<string, unknown>).cause;
61 } catch {
62 break;
63 }
64 }
65 return message;
67​
68function stringField(value: unknown, key: "message" | "code"): string | undefined {
69 if (typeof value !== "object" || value === null) return undefined;
70 try {
71 const candidate = (value as Record<string, unknown>)[key];
72 return typeof candidate === "string" ? candidate : undefined;
73 } catch {
74 return undefined;
75 }
77​
78function redactUrl(match: string): string {
79 const trailing = /[),.;!?]+$/u.exec(match)?.[0] ?? "";
80 const candidate = trailing.length === 0 ? match : match.slice(0, -trailing.length);
81 try {
82 const url = new URL(candidate);
83 url.username = "";
84 url.password = "";
85 url.search = "";
86 url.hash = "";
87 return `${url.toString()}${trailing}`;
88 } catch {
89 return "[REDACTED_URL]";
90 }
92​
93function replaceUnsafeControlCharacters(value: string): string {
94 const sanitized: Array<string> = [];
95 for (const character of value) {
96 const codePoint = character.codePointAt(0) ?? 0;
97 sanitized.push(
98 codePoint <= 0x08 ||
99 (codePoint >= 0x0b && codePoint <= 0x0c) ||
100 (codePoint >= 0x0e && codePoint <= 0x1f) ||
101 codePoint === 0x7f
102 ? " "
103 : character,
104 );
105 }
106 return sanitized.join("");
108​
109/** Removes common credential forms before provider text crosses a transport boundary. */
110function redactProviderFailureText(value: string): string {
111 return replaceUnsafeControlCharacters(value)
112 .replace(/\bhttps?:\/\/[^\s<>"']+/giu, redactUrl)
113 .replace(/\b(Bearer|Basic)\s+[^\s,;]+/giu, "$1 [REDACTED]")
114 .replace(
115 /(["'](?:access[_-]?token|api[_-]?key|authorization|credential|password|secret|token)["']\s*:\s*["'])[^"']*(["'])/giu,
116 "$1[REDACTED]$2",
117 )
118 .replace(
119 /(\b(?:access[_-]?token|api[_-]?key|authorization|credential|password|secret|token)\b\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/giu,
120 "$1[REDACTED]",
121 )
122 .replace(/\bsk-[A-Za-z0-9_-]{16,}\b/gu, "[REDACTED]")
123 .trim();
125​
126function boundedText(value: string, maxLength: number): string {
127 const redacted = redactProviderFailureText(value);
128 if (redacted.length <= maxLength) return redacted;
129 let end = Math.max(0, maxLength - 1);
130 const finalCodeUnit = redacted.charCodeAt(end - 1);
131 if (finalCodeUnit >= 0xd800 && finalCodeUnit <= 0xdbff) {
132 end -= 1;
133 }
134 return `${redacted.slice(0, end)}…`;
136​
137export function makeProviderFailure(input: {
138 readonly cause?: unknown;
139 readonly message?: string | undefined;
140 readonly code?: string | null | undefined;
141 readonly class?: OrchestrationV2ProviderFailureClass;
142 readonly retryable?: boolean | null;
143 readonly resetAt?: string | null;
144}): OrchestrationV2ProviderFailure {
145 const rawMessage = input.message ?? causeMessage(input.cause) ?? DEFAULT_PROVIDER_FAILURE_MESSAGE;
146 const message = boundedText(rawMessage, MAX_PROVIDER_FAILURE_MESSAGE_LENGTH);
147 const rawCode = input.code ?? stringField(input.cause, "code") ?? null;
148 const code =
149 rawCode === null ? null : boundedText(rawCode, MAX_PROVIDER_FAILURE_CODE_LENGTH) || null;
150​
151 return {
152 class: input.class ?? "unknown",
153 message: message || DEFAULT_PROVIDER_FAILURE_MESSAGE,
154 code,
155 retryable: input.retryable ?? null,
156 ...(input.class === "usage_limit" &&
157 input.resetAt != null &&
158 Number.isFinite(Date.parse(input.resetAt))
159 ? { resetAt: DateTime.formatIso(DateTime.makeUnsafe(input.resetAt)) }
160 : {}),
161 };
163​
164export function makeProviderFailureTurnItem(input: {
165 readonly idAllocator: IdAllocatorV2Shape;
166 readonly driver: ProviderDriverKind;
167 readonly threadId: ThreadId;
168 readonly runId: RunId | null;
169 readonly nodeId: NodeId | null;
170 readonly providerThreadId: ProviderThreadId;
171 readonly providerTurnId: ProviderTurnId;
172 readonly itemOrdinal: number;
173 readonly failure: OrchestrationV2ProviderFailure;
174 readonly retry?: OrchestrationV2ProviderRetry;
175 readonly retryStartedAt?: DateTime.Utc;
176 readonly occurredAt: DateTime.Utc;
177}): Extract<OrchestrationV2TurnItem, { readonly type: "error" }> {
178 return {
179 id: input.idAllocator.derive.turnItemFromProviderItem({
180 driver: input.driver,
181 nativeItemId: `terminal-failure:${input.providerTurnId}`,
182 }),
183 threadId: input.threadId,
184 runId: input.runId,
185 nodeId: input.nodeId,
186 providerThreadId: input.providerThreadId,
187 providerTurnId: input.providerTurnId,
188 nativeItemRef: null,
189 parentItemId: null,
190 ordinal: input.itemOrdinal,
191 status: "failed",
192 title: input.failure.class === "usage_limit" ? "Usage limit reached" : "Provider error",
193 startedAt: input.retryStartedAt ?? input.occurredAt,
194 completedAt: input.occurredAt,
195 updatedAt: input.occurredAt,
196 type: "error",
197 failure: input.failure,
198 ...(input.retry === undefined ? {} : { retry: input.retry }),
199 };
201​
202export function makeProviderRetryTurnItem(input: {
203 readonly idAllocator: IdAllocatorV2Shape;
204 readonly driver: ProviderDriverKind;
205 readonly threadId: ThreadId;
206 readonly runId: RunId | null;
207 readonly nodeId: NodeId | null;
208 readonly providerThreadId: ProviderThreadId;
209 readonly providerTurnId: ProviderTurnId;
210 readonly itemOrdinal: number;
211 readonly failure: OrchestrationV2ProviderFailure;
212 readonly retry: OrchestrationV2ProviderRetry;
213 readonly status: Extract<
214 OrchestrationV2TurnItem["status"],
215 "running" | "completed" | "failed" | "interrupted" | "cancelled"
216 >;
217 readonly startedAt: DateTime.Utc;
218 readonly updatedAt: DateTime.Utc;
219}): Extract<OrchestrationV2TurnItem, { readonly type: "error" }> {
220 const completed = input.status !== "running";
221 let title = "Provider retry";
222 if (input.status === "completed") {
223 title = "Provider recovered";
224 } else if (input.status === "failed") {
225 title = input.failure.class === "usage_limit" ? "Usage limit reached" : "Provider error";
226 } else if (input.status === "interrupted" || input.status === "cancelled") {
227 title = "Provider retry stopped";
228 }
229 return {
230 id: input.idAllocator.derive.turnItemFromProviderItem({
231 driver: input.driver,
232 nativeItemId: `terminal-failure:${input.providerTurnId}`,
233 }),
234 threadId: input.threadId,
235 runId: input.runId,
236 nodeId: input.nodeId,
237 providerThreadId: input.providerThreadId,
238 providerTurnId: input.providerTurnId,
239 nativeItemRef: null,
240 parentItemId: null,
241 ordinal: input.itemOrdinal,
242 status: input.status,
243 title,
244 startedAt: input.startedAt,
245 completedAt: completed ? input.updatedAt : null,
246 updatedAt: input.updatedAt,
247 type: "error",
248 failure: input.failure,
249 retry: input.retry,
250 };