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

ProviderFailure.ts

147 lines4.8 KB

1import type {
2 NodeId,
3 OrchestrationV2ProviderFailure,
4 OrchestrationV2ProviderFailureClass,
5 OrchestrationV2TurnItem,
6 ProviderDriverKind,
7 ProviderThreadId,
8 ProviderTurnId,
9 RunId,
10 ThreadId,
11} from "@t3tools/contracts";
12import type * as DateTime from "effect/DateTime";
13​
14import type { IdAllocatorV2Shape } from "./IdAllocator.ts";
15​
16export const MAX_PROVIDER_FAILURE_MESSAGE_LENGTH = 4_096;
17export const MAX_PROVIDER_FAILURE_CODE_LENGTH = 128;
18​
19const DEFAULT_PROVIDER_FAILURE_MESSAGE = "Provider turn failed.";
20​
21function stringField(value: unknown, key: "message" | "code"): string | undefined {
22 if (typeof value !== "object" || value === null) return undefined;
23 try {
24 const candidate = (value as Record<string, unknown>)[key];
25 return typeof candidate === "string" ? candidate : undefined;
26 } catch {
27 return undefined;
28 }
30​
31function redactUrl(match: string): string {
32 const trailing = /[),.;!?]+$/u.exec(match)?.[0] ?? "";
33 const candidate = trailing.length === 0 ? match : match.slice(0, -trailing.length);
34 try {
35 const url = new URL(candidate);
36 url.username = "";
37 url.password = "";
38 url.search = "";
39 url.hash = "";
40 return `${url.toString()}${trailing}`;
41 } catch {
42 return "[REDACTED_URL]";
43 }
45​
46function replaceUnsafeControlCharacters(value: string): string {
47 const sanitized: Array<string> = [];
48 for (const character of value) {
49 const codePoint = character.codePointAt(0) ?? 0;
50 sanitized.push(
51 codePoint <= 0x08 ||
52 (codePoint >= 0x0b && codePoint <= 0x0c) ||
53 (codePoint >= 0x0e && codePoint <= 0x1f) ||
54 codePoint === 0x7f
55 ? " "
56 : character,
57 );
58 }
59 return sanitized.join("");
61​
62/** Removes common credential forms before provider text crosses a transport boundary. */
63export function redactProviderFailureText(value: string): string {
64 return replaceUnsafeControlCharacters(value)
65 .replace(/\bhttps?:\/\/[^\s<>"']+/giu, redactUrl)
66 .replace(/\b(Bearer|Basic)\s+[^\s,;]+/giu, "$1 [REDACTED]")
67 .replace(
68 /(["'](?:access[_-]?token|api[_-]?key|authorization|credential|password|secret|token)["']\s*:\s*["'])[^"']*(["'])/giu,
69 "$1[REDACTED]$2",
70 )
71 .replace(
72 /(\b(?:access[_-]?token|api[_-]?key|authorization|credential|password|secret|token)\b\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/giu,
73 "$1[REDACTED]",
74 )
75 .replace(/\bsk-[A-Za-z0-9_-]{16,}\b/gu, "[REDACTED]")
76 .trim();
78​
79function boundedText(value: string, maxLength: number): string {
80 const redacted = redactProviderFailureText(value);
81 if (redacted.length <= maxLength) return redacted;
82 let end = Math.max(0, maxLength - 1);
83 const finalCodeUnit = redacted.charCodeAt(end - 1);
84 if (finalCodeUnit >= 0xd800 && finalCodeUnit <= 0xdbff) {
85 end -= 1;
86 }
87 return `${redacted.slice(0, end)}…`;
89​
90export function makeProviderFailure(input: {
91 readonly cause?: unknown;
92 readonly message?: string | undefined;
93 readonly code?: string | null | undefined;
94 readonly class?: OrchestrationV2ProviderFailureClass;
95 readonly retryable?: boolean | null;
96}): OrchestrationV2ProviderFailure {
97 const rawMessage =
98 input.message ??
99 (input.cause instanceof Error ? input.cause.message : stringField(input.cause, "message")) ??
100 DEFAULT_PROVIDER_FAILURE_MESSAGE;
101 const message = boundedText(rawMessage, MAX_PROVIDER_FAILURE_MESSAGE_LENGTH);
102 const rawCode = input.code ?? stringField(input.cause, "code") ?? null;
103 const code =
104 rawCode === null ? null : boundedText(rawCode, MAX_PROVIDER_FAILURE_CODE_LENGTH) || null;
105​
106 return {
107 class: input.class ?? "unknown",
108 message: message || DEFAULT_PROVIDER_FAILURE_MESSAGE,
109 code,
110 retryable: input.retryable ?? null,
111 };
113​
114export function makeProviderFailureTurnItem(input: {
115 readonly idAllocator: IdAllocatorV2Shape;
116 readonly driver: ProviderDriverKind;
117 readonly threadId: ThreadId;
118 readonly runId: RunId | null;
119 readonly nodeId: NodeId | null;
120 readonly providerThreadId: ProviderThreadId;
121 readonly providerTurnId: ProviderTurnId;
122 readonly itemOrdinal: number;
123 readonly failure: OrchestrationV2ProviderFailure;
124 readonly occurredAt: DateTime.Utc;
125}): Extract<OrchestrationV2TurnItem, { readonly type: "error" }> {
126 return {
127 id: input.idAllocator.derive.turnItemFromProviderItem({
128 driver: input.driver,
129 nativeItemId: `terminal-failure:${input.providerTurnId}`,
130 }),
131 threadId: input.threadId,
132 runId: input.runId,
133 nodeId: input.nodeId,
134 providerThreadId: input.providerThreadId,
135 providerTurnId: input.providerTurnId,
136 nativeItemRef: null,
137 parentItemId: null,
138 ordinal: input.itemOrdinal,
139 status: "failed",
140 title: "Provider error",
141 startedAt: input.occurredAt,
142 completedAt: input.occurredAt,
143 updatedAt: input.occurredAt,
144 type: "error",
145 failure: input.failure,
146 };