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