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 type * as DateTime from "effect/DateTime";
14
15import type { IdAllocatorV2Shape } from "./IdAllocator.ts";
16
17export const MAX_PROVIDER_FAILURE_MESSAGE_LENGTH = 4_096;
18export const MAX_PROVIDER_FAILURE_CODE_LENGTH = 128;
19
20const DEFAULT_PROVIDER_FAILURE_MESSAGE = "Provider turn failed.";
21
22function stringField(value: unknown, key: "message" | "code"): string | undefined {
23 if (typeof value !== "object" || value === null) return undefined;
24 try {
25 const candidate = (value as Record<string, unknown>)[key];
26 return typeof candidate === "string" ? candidate : undefined;
27 } catch {
28 return undefined;
29 }
30}
31
32function redactUrl(match: string): string {
33 const trailing = /[),.;!?]+$/u.exec(match)?.[0] ?? "";
34 const candidate = trailing.length === 0 ? match : match.slice(0, -trailing.length);
35 try {
36 const url = new URL(candidate);
37 url.username = "";
38 url.password = "";
39 url.search = "";
40 url.hash = "";
41 return `${url.toString()}${trailing}`;
42 } catch {
43 return "[REDACTED_URL]";
44 }
45}
46
47function replaceUnsafeControlCharacters(value: string): string {
48 const sanitized: Array<string> = [];
49 for (const character of value) {
50 const codePoint = character.codePointAt(0) ?? 0;
51 sanitized.push(
52 codePoint <= 0x08 ||
53 (codePoint >= 0x0b && codePoint <= 0x0c) ||
54 (codePoint >= 0x0e && codePoint <= 0x1f) ||
55 codePoint === 0x7f
56 ? " "
57 : character,
58 );
59 }
60 return sanitized.join("");
61}
62
63/** Removes common credential forms before provider text crosses a transport boundary. */
64function redactProviderFailureText(value: string): string {
65 return replaceUnsafeControlCharacters(value)
66 .replace(/\bhttps?:\/\/[^\s<>"']+/giu, redactUrl)
67 .replace(/\b(Bearer|Basic)\s+[^\s,;]+/giu, "$1 [REDACTED]")
68 .replace(
69 /(["'](?:access[_-]?token|api[_-]?key|authorization|credential|password|secret|token)["']\s*:\s*["'])[^"']*(["'])/giu,
70 "$1[REDACTED]$2",
71 )
72 .replace(
73 /(\b(?:access[_-]?token|api[_-]?key|authorization|credential|password|secret|token)\b\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/giu,
74 "$1[REDACTED]",
75 )
76 .replace(/\bsk-[A-Za-z0-9_-]{16,}\b/gu, "[REDACTED]")
77 .trim();
78}
79
80function boundedText(value: string, maxLength: number): string {
81 const redacted = redactProviderFailureText(value);
82 if (redacted.length <= maxLength) return redacted;
83 let end = Math.max(0, maxLength - 1);
84 const finalCodeUnit = redacted.charCodeAt(end - 1);
85 if (finalCodeUnit >= 0xd800 && finalCodeUnit <= 0xdbff) {
86 end -= 1;
87 }
88 return `${redacted.slice(0, end)}…`;
89}
90
91export function makeProviderFailure(input: {
92 readonly cause?: unknown;
93 readonly message?: string | undefined;
94 readonly code?: string | null | undefined;
95 readonly class?: OrchestrationV2ProviderFailureClass;
96 readonly retryable?: boolean | null;
97}): OrchestrationV2ProviderFailure {
98 const rawMessage =
99 input.message ??
100 (input.cause instanceof Error ? input.cause.message : stringField(input.cause, "message")) ??
101 DEFAULT_PROVIDER_FAILURE_MESSAGE;
102 const message = boundedText(rawMessage, MAX_PROVIDER_FAILURE_MESSAGE_LENGTH);
103 const rawCode = input.code ?? stringField(input.cause, "code") ?? null;
104 const code =
105 rawCode === null ? null : boundedText(rawCode, MAX_PROVIDER_FAILURE_CODE_LENGTH) || null;
106
107 return {
108 class: input.class ?? "unknown",
109 message: message || DEFAULT_PROVIDER_FAILURE_MESSAGE,
110 code,
111 retryable: input.retryable ?? null,
112 };
113}
114
115export function makeProviderFailureTurnItem(input: {
116 readonly idAllocator: IdAllocatorV2Shape;
117 readonly driver: ProviderDriverKind;
118 readonly threadId: ThreadId;
119 readonly runId: RunId | null;
120 readonly nodeId: NodeId | null;
121 readonly providerThreadId: ProviderThreadId;
122 readonly providerTurnId: ProviderTurnId;
123 readonly itemOrdinal: number;
124 readonly failure: OrchestrationV2ProviderFailure;
125 readonly retry?: OrchestrationV2ProviderRetry;
126 readonly retryStartedAt?: DateTime.Utc;
127 readonly occurredAt: DateTime.Utc;
128}): Extract<OrchestrationV2TurnItem, { readonly type: "error" }> {
129 return {
130 id: input.idAllocator.derive.turnItemFromProviderItem({
131 driver: input.driver,
132 nativeItemId: `terminal-failure:${input.providerTurnId}`,
133 }),
134 threadId: input.threadId,
135 runId: input.runId,
136 nodeId: input.nodeId,
137 providerThreadId: input.providerThreadId,
138 providerTurnId: input.providerTurnId,
139 nativeItemRef: null,
140 parentItemId: null,
141 ordinal: input.itemOrdinal,
142 status: "failed",
143 title: "Provider error",
144 startedAt: input.retryStartedAt ?? input.occurredAt,
145 completedAt: input.occurredAt,
146 updatedAt: input.occurredAt,
147 type: "error",
148 failure: input.failure,
149 ...(input.retry === undefined ? {} : { retry: input.retry }),
150 };
151}
152
153export function makeProviderRetryTurnItem(input: {
154 readonly idAllocator: IdAllocatorV2Shape;
155 readonly driver: ProviderDriverKind;
156 readonly threadId: ThreadId;
157 readonly runId: RunId | null;
158 readonly nodeId: NodeId | null;
159 readonly providerThreadId: ProviderThreadId;
160 readonly providerTurnId: ProviderTurnId;
161 readonly itemOrdinal: number;
162 readonly failure: OrchestrationV2ProviderFailure;
163 readonly retry: OrchestrationV2ProviderRetry;
164 readonly status: Extract<
165 OrchestrationV2TurnItem["status"],
166 "running" | "completed" | "failed" | "interrupted" | "cancelled"
167 >;
168 readonly startedAt: DateTime.Utc;
169 readonly updatedAt: DateTime.Utc;
170}): Extract<OrchestrationV2TurnItem, { readonly type: "error" }> {
171 const completed = input.status !== "running";
172 let title = "Provider retry";
173 if (input.status === "completed") {
174 title = "Provider recovered";
175 } else if (input.status === "failed") {
176 title = "Provider error";
177 } else if (input.status === "interrupted" || input.status === "cancelled") {
178 title = "Provider retry stopped";
179 }
180 return {
181 id: input.idAllocator.derive.turnItemFromProviderItem({
182 driver: input.driver,
183 nativeItemId: `terminal-failure:${input.providerTurnId}`,
184 }),
185 threadId: input.threadId,
186 runId: input.runId,
187 nodeId: input.nodeId,
188 providerThreadId: input.providerThreadId,
189 providerTurnId: input.providerTurnId,
190 nativeItemRef: null,
191 parentItemId: null,
192 ordinal: input.itemOrdinal,
193 status: input.status,
194 title,
195 startedAt: input.startedAt,
196 completedAt: completed ? input.updatedAt : null,
197 updatedAt: input.updatedAt,
198 type: "error",
199 failure: input.failure,
200 retry: input.retry,
201 };
202}