* Bill a stream that exited before a usage-bearing chunk arrived by looking up * the generation cost from OpenRouter's /generation endpoint. Mutates * `state.billed` on success so callers can tell the gap was filled. * * Never throws — failures are logged and swallowed. The worst case is that we
(params: {
generationId: string
openrouterApiKey: string | null
userId: string
stripeCustomerId?: string | null
agentId: string
clientId: string | null
clientRequestId: string | null
costMode: string | undefined
byok: boolean
startTime: Date
state: StreamState
request: unknown
fetch: typeof globalThis.fetch
logger: Logger
insertMessage: InsertMessageBigqueryFn
})
| 932 | * miss this one request, which is still strictly better than the old behavior. |
| 933 | */ |
| 934 | async function fallbackBillFromGeneration(params: { |
| 935 | generationId: string |
| 936 | openrouterApiKey: string | null |
| 937 | userId: string |
| 938 | stripeCustomerId?: string | null |
| 939 | agentId: string |
| 940 | clientId: string | null |
| 941 | clientRequestId: string | null |
| 942 | costMode: string | undefined |
| 943 | byok: boolean |
| 944 | startTime: Date |
| 945 | state: StreamState |
| 946 | request: unknown |
| 947 | fetch: typeof globalThis.fetch |
| 948 | logger: Logger |
| 949 | insertMessage: InsertMessageBigqueryFn |
| 950 | }): Promise<void> { |
| 951 | const { |
| 952 | generationId, |
| 953 | openrouterApiKey, |
| 954 | userId, |
| 955 | stripeCustomerId, |
| 956 | agentId, |
| 957 | clientId, |
| 958 | clientRequestId, |
| 959 | costMode, |
| 960 | byok, |
| 961 | startTime, |
| 962 | state, |
| 963 | request, |
| 964 | fetch, |
| 965 | logger, |
| 966 | insertMessage, |
| 967 | } = params |
| 968 | |
| 969 | try { |
| 970 | const response = await fetch( |
| 971 | `https://openrouter.ai/api/v1/generation?id=${encodeURIComponent(generationId)}`, |
| 972 | { |
| 973 | method: 'GET', |
| 974 | headers: { |
| 975 | Authorization: `Bearer ${openrouterApiKey ?? env.OPEN_ROUTER_API_KEY}`, |
| 976 | }, |
| 977 | }, |
| 978 | ) |
| 979 | |
| 980 | if (!response.ok) { |
| 981 | logger.error( |
| 982 | { |
| 983 | generationId, |
| 984 | status: response.status, |
| 985 | statusText: response.statusText, |
| 986 | userId, |
| 987 | agentId, |
| 988 | model: state.model, |
| 989 | responseTextLength: state.responseText.length, |
| 990 | }, |
| 991 | 'fallbackBillFromGeneration: generation lookup failed', |
no test coverage detected