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

ProviderFailure.ts

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