plugin-ai-api 1.0.24 → 1.0.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/client/757.56952e321dc399b7.js +10 -0
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/757.db678ca1aa6c422c.js +10 -0
  4. package/dist/client-v2/index.js +1 -1
  5. package/dist/externalVersion.js +8 -8
  6. package/dist/locale/en-US.json +1 -0
  7. package/dist/locale/vi-VN.json +1 -0
  8. package/dist/locale/zh-CN.json +1 -0
  9. package/dist/server/billing.js +6 -1
  10. package/dist/server/collections/ai-api-config.js +6 -0
  11. package/dist/server/collections/ai-api-usage-records.js +1 -0
  12. package/dist/server/migrations/20260813000000-add-prompt-cache-tokens.js +69 -0
  13. package/dist/server/plugin.js +10 -0
  14. package/dist/server/resource/ai-api-config.js +5 -0
  15. package/dist/server/resource/ai-api-usage-monitor.js +3 -1
  16. package/dist/server/routes/chat-completions.js +89 -10
  17. package/dist/server/routes/completions.js +32 -10
  18. package/dist/server/services/file-processor.js +262 -0
  19. package/dist/server/usage.js +33 -3
  20. package/dist/server/utils/direct-llm-context.js +150 -15
  21. package/dist/server/utils/openai-format.js +21 -2
  22. package/dist/swagger.js +42 -3
  23. package/package.json +1 -1
  24. package/src/client-v2/pages/UsagePage.tsx +9 -0
  25. package/src/locale/en-US.json +1 -0
  26. package/src/locale/vi-VN.json +1 -0
  27. package/src/locale/zh-CN.json +1 -0
  28. package/src/server/__tests__/direct-llm-context.test.ts +87 -6
  29. package/src/server/__tests__/openai-format.test.ts +12 -2
  30. package/src/server/__tests__/request-body.test.ts +45 -2
  31. package/src/server/__tests__/usage-route.test.ts +120 -3
  32. package/src/server/__tests__/usage.test.ts +19 -0
  33. package/src/server/billing.ts +6 -1
  34. package/src/server/collections/ai-api-config.ts +8 -0
  35. package/src/server/collections/ai-api-role-permissions.ts +41 -41
  36. package/src/server/collections/ai-api-usage-records.ts +1 -0
  37. package/src/server/index.ts +10 -10
  38. package/src/server/middleware/rate-limit.ts +70 -70
  39. package/src/server/migrations/20260813000000-add-prompt-cache-tokens.ts +46 -0
  40. package/src/server/plugin.ts +20 -0
  41. package/src/server/resource/ai-api-config.ts +5 -0
  42. package/src/server/resource/ai-api-usage-monitor.ts +3 -0
  43. package/src/server/routes/chat-completions.ts +134 -11
  44. package/src/server/routes/completions.ts +33 -7
  45. package/src/server/services/__tests__/file-processor.test.ts +184 -0
  46. package/src/server/services/file-processor.ts +323 -0
  47. package/src/server/usage.ts +47 -1
  48. package/src/server/utils/direct-llm-context.ts +198 -20
  49. package/src/server/utils/openai-format.ts +25 -2
  50. package/src/server/utils/rate-limiter.ts +83 -83
  51. package/src/server/utils/resolve-service.ts +82 -82
  52. package/src/swagger.ts +45 -3
  53. package/dist/client/757.a01403fb7a1bea01.js +0 -10
  54. package/dist/client-v2/757.a117ce1cf7119cea.js +0 -10
@@ -0,0 +1,184 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import {
3
+ FileProcessorService,
4
+ base64FileForwarder,
5
+ httpFileUrlFetcher,
6
+ fetchFileAsBase64,
7
+ pdfFileProcessor,
8
+ type PdfToImageRenderer,
9
+ } from '../file-processor';
10
+
11
+ describe('FileProcessorService', () => {
12
+ it('forwards file blocks with base64 data unchanged', async () => {
13
+ const service = new FileProcessorService();
14
+ service.register(base64FileForwarder);
15
+
16
+ const block = { type: 'file', file: { file_data: 'data:application/pdf;base64,JVBERi0=' } };
17
+ const result = await service.process(block, { ctx: {} as any });
18
+
19
+ expect(result).toEqual(block);
20
+ });
21
+
22
+ it('returns the block unchanged when no processor can handle it', async () => {
23
+ const service = new FileProcessorService();
24
+ const block = { type: 'text', text: 'hello' };
25
+ const result = await service.process(block, { ctx: {} as any });
26
+
27
+ expect(result).toEqual(block);
28
+ });
29
+
30
+ it('allows custom processors to override default behavior', async () => {
31
+ const service = new FileProcessorService();
32
+ service.register(base64FileForwarder);
33
+
34
+ const customProcessor = {
35
+ name: 'customFileProcessor',
36
+ canHandle: (block: { type: string }) => block.type === 'file',
37
+ process: vi.fn().mockResolvedValue({ type: 'file', file: { file_data: 'data:text/plain;base64,SGVsbG8=' } }),
38
+ };
39
+ service.register(customProcessor);
40
+
41
+ const block = { type: 'file', file: { file_data: 'data:application/pdf;base64,JVBERi0=' } };
42
+ const result = await service.process(block, { ctx: {} as any });
43
+
44
+ expect(customProcessor.process).toHaveBeenCalledWith(block, { ctx: {} as any });
45
+ expect(result).toEqual({ type: 'file', file: { file_data: 'data:text/plain;base64,SGVsbG8=' } });
46
+ });
47
+
48
+ it('unregister removes a processor by name', () => {
49
+ const service = new FileProcessorService();
50
+ service.register(base64FileForwarder);
51
+ expect(service.list()).toHaveLength(1);
52
+
53
+ service.unregister(base64FileForwarder.name);
54
+ expect(service.list()).toHaveLength(0);
55
+ });
56
+ });
57
+
58
+ describe('httpFileUrlFetcher', () => {
59
+ it('fetches a file from an http(s) URL and converts it to a file block', async () => {
60
+ const originalFetch = globalThis.fetch;
61
+ const fileBuffer = Buffer.from('hello world');
62
+ globalThis.fetch = vi.fn().mockResolvedValue({
63
+ ok: true,
64
+ status: 200,
65
+ headers: new Headers({
66
+ 'content-type': 'text/plain',
67
+ 'content-length': String(fileBuffer.length),
68
+ }),
69
+ arrayBuffer: () =>
70
+ Promise.resolve(fileBuffer.buffer.slice(fileBuffer.byteOffset, fileBuffer.byteOffset + fileBuffer.length)),
71
+ } as unknown as Response);
72
+
73
+ const result = await httpFileUrlFetcher.process(
74
+ { type: 'file_url', file_url: { url: 'https://example.com/hello.txt' } },
75
+ { ctx: {} as any },
76
+ );
77
+
78
+ expect(result).toMatchObject({
79
+ type: 'file',
80
+ file: {
81
+ file_data: expect.stringContaining('data:text/plain;base64,'),
82
+ mime_type: 'text/plain',
83
+ filename: 'hello.txt',
84
+ },
85
+ });
86
+
87
+ globalThis.fetch = originalFetch;
88
+ });
89
+
90
+ it('rejects unsupported protocols', async () => {
91
+ await expect(
92
+ httpFileUrlFetcher.process(
93
+ { type: 'file_url', file_url: { url: 'ftp://example.com/file.txt' } },
94
+ { ctx: {} as any },
95
+ ),
96
+ ).rejects.toThrow('protocol');
97
+ });
98
+ });
99
+
100
+ describe('fetchFileAsBase64', () => {
101
+ it('validates URL protocols', async () => {
102
+ await expect(fetchFileAsBase64('ftp://example.com/file.txt')).rejects.toThrow('protocol');
103
+ });
104
+
105
+ it('rejects malformed URLs', async () => {
106
+ await expect(fetchFileAsBase64('not a url')).rejects.toThrow('valid URL');
107
+ });
108
+ });
109
+
110
+ describe('pdfFileProcessor', () => {
111
+ const pdfBuffer = Buffer.from('%PDF-1.4\n1 0 obj\n<<\n>>\nendobj\n', 'binary');
112
+ const pdfDataUrl = `data:application/pdf;base64,${pdfBuffer.toString('base64')}`;
113
+
114
+ function createContext(config: { pdfRenderPagesAsImages?: boolean }, renderer?: PdfToImageRenderer | null) {
115
+ const service = new FileProcessorService();
116
+ if (renderer) {
117
+ service.registerPdfRenderer(renderer);
118
+ }
119
+ return {
120
+ ctx: {
121
+ db: {
122
+ getRepository: vi.fn((name: string) => {
123
+ if (name === 'aiApiConfig') {
124
+ return {
125
+ findOne: vi.fn().mockResolvedValue({
126
+ get: (key: string) => (key === 'pdfRenderPagesAsImages' ? config.pdfRenderPagesAsImages : undefined),
127
+ pdfRenderPagesAsImages: config.pdfRenderPagesAsImages,
128
+ }),
129
+ };
130
+ }
131
+ return { findOne: vi.fn() };
132
+ }),
133
+ },
134
+ app: {
135
+ pm: {
136
+ get: vi.fn().mockReturnValue({
137
+ fileProcessorService: service,
138
+ }),
139
+ },
140
+ },
141
+ log: { warn: vi.fn() },
142
+ },
143
+ } as any;
144
+ }
145
+
146
+ it('forwards a PDF file block when pdfRenderPagesAsImages is disabled', async () => {
147
+ const block = { type: 'file', file: { file_data: pdfDataUrl } } as any;
148
+ const result = await pdfFileProcessor.process(block, createContext({ pdfRenderPagesAsImages: false }));
149
+ expect(result).toBe(block);
150
+ });
151
+
152
+ it('forwards a PDF and warns when rendering is enabled but no renderer is registered', async () => {
153
+ const block = { type: 'file', file: { file_data: pdfDataUrl } } as any;
154
+ const context = createContext({ pdfRenderPagesAsImages: true });
155
+ const result = await pdfFileProcessor.process(block, context);
156
+
157
+ expect(result).toBe(block);
158
+ expect(context.ctx.log.warn).toHaveBeenCalledWith(
159
+ expect.stringContaining('pdfRenderPagesAsImages is enabled but no PdfToImageRenderer is registered'),
160
+ );
161
+ });
162
+
163
+ it('converts a PDF file block into image_url blocks when a renderer is registered', async () => {
164
+ const renderer: PdfToImageRenderer = {
165
+ name: 'mockRenderer',
166
+ render: vi.fn().mockResolvedValue([Buffer.from('page1'), Buffer.from('page2')]),
167
+ };
168
+ const block = { type: 'file', file: { file_data: pdfDataUrl } } as any;
169
+ const result = await pdfFileProcessor.process(block, createContext({ pdfRenderPagesAsImages: true }, renderer));
170
+
171
+ expect(Array.isArray(result)).toBe(true);
172
+ expect(result).toHaveLength(2);
173
+ expect((result as any[])[0]).toMatchObject({ type: 'image_url' });
174
+ expect((result as any[])[0].image_url.url).toMatch(/^data:image\/png;base64,/);
175
+ });
176
+
177
+ it('does not convert non-PDF file blocks', async () => {
178
+ const block = {
179
+ type: 'file',
180
+ file: { file_data: 'data:text/plain;base64,SGVsbG8=', filename: 'hello.txt' },
181
+ } as any;
182
+ expect(pdfFileProcessor.canHandle(block)).toBe(false);
183
+ });
184
+ });
@@ -0,0 +1,323 @@
1
+ import type { Context } from '@nocobase/actions';
2
+ import { basename } from 'path';
3
+
4
+ export interface FileContentBlock {
5
+ type: string;
6
+ [key: string]: unknown;
7
+ }
8
+
9
+ export interface FileProcessorContext {
10
+ ctx: Context;
11
+ }
12
+
13
+ export interface FileProcessor {
14
+ name: string;
15
+ canHandle(block: FileContentBlock): boolean;
16
+ process(block: FileContentBlock, context: FileProcessorContext): Promise<FileContentBlock | FileContentBlock[]>;
17
+ }
18
+
19
+ export interface PdfToImageRenderer {
20
+ name: string;
21
+ /**
22
+ * Render each page of a PDF into a PNG image buffer.
23
+ * @param buffer Raw PDF bytes.
24
+ * @returns Array of PNG buffers, one per page.
25
+ */
26
+ render(buffer: Buffer): Promise<Buffer[]>;
27
+ }
28
+
29
+ export type FileProcessorErrorCode =
30
+ | 'invalid_url'
31
+ | 'unsupported_protocol'
32
+ | 'fetch_failed'
33
+ | 'file_too_large'
34
+ | 'content_type_not_allowed'
35
+ | 'missing_url';
36
+
37
+ export class FileProcessorError extends Error {
38
+ constructor(
39
+ readonly code: FileProcessorErrorCode,
40
+ message: string,
41
+ ) {
42
+ super(message);
43
+ this.name = 'FileProcessorError';
44
+ }
45
+ }
46
+
47
+ export interface FetchFileOptions {
48
+ maxSizeBytes?: number;
49
+ timeoutMs?: number;
50
+ allowedProtocols?: string[];
51
+ allowedContentTypes?: string[];
52
+ }
53
+
54
+ const DEFAULT_MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB
55
+ const DEFAULT_TIMEOUT_MS = 30_000;
56
+ const ALLOWED_PROTOCOLS = new Set(['http:', 'https:']);
57
+
58
+ export class FileProcessorService {
59
+ private processors: FileProcessor[] = [];
60
+ private pdfRenderer: PdfToImageRenderer | null = null;
61
+
62
+ register(processor: FileProcessor): void {
63
+ this.unregister(processor.name);
64
+ this.processors.push(processor);
65
+ }
66
+
67
+ unregister(name: string): void {
68
+ this.processors = this.processors.filter((p) => p.name !== name);
69
+ }
70
+
71
+ async process(
72
+ block: FileContentBlock,
73
+ context: FileProcessorContext,
74
+ ): Promise<FileContentBlock | FileContentBlock[]> {
75
+ // Search from the end so the most recently registered processor wins.
76
+ // This makes it easy for a custom plugin to override a default processor.
77
+ const processor = [...this.processors].reverse().find((p) => p.canHandle(block));
78
+ if (!processor) {
79
+ return block;
80
+ }
81
+ return processor.process(block, context);
82
+ }
83
+
84
+ list(): ReadonlyArray<FileProcessor> {
85
+ return [...this.processors];
86
+ }
87
+
88
+ /**
89
+ * Register a renderer used to convert PDF pages into PNG images when
90
+ * `pdfRenderPagesAsImages` is enabled in the AI API config.
91
+ */
92
+ registerPdfRenderer(renderer: PdfToImageRenderer): void {
93
+ this.pdfRenderer = renderer;
94
+ }
95
+
96
+ unregisterPdfRenderer(): void {
97
+ this.pdfRenderer = null;
98
+ }
99
+
100
+ getPdfRenderer(): PdfToImageRenderer | null {
101
+ return this.pdfRenderer;
102
+ }
103
+ }
104
+
105
+ function isRecord(value: unknown): value is Record<string, unknown> {
106
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
107
+ }
108
+
109
+ function getUrlString(value: unknown): string | undefined {
110
+ if (typeof value === 'string') return value;
111
+ if (isRecord(value) && typeof value.url === 'string') return value.url;
112
+ return undefined;
113
+ }
114
+
115
+ function extractFilename(url: string, contentDisposition: string | null): string | undefined {
116
+ if (contentDisposition) {
117
+ const match = contentDisposition.match(/filename="?([^"]+)"?/);
118
+ if (match) return match[1];
119
+ }
120
+ try {
121
+ const pathname = new URL(url).pathname;
122
+ if (pathname) return basename(pathname);
123
+ } catch {
124
+ // ignore malformed URL
125
+ }
126
+ return undefined;
127
+ }
128
+
129
+ export async function fetchFileAsBase64(
130
+ url: string,
131
+ options: FetchFileOptions = {},
132
+ ): Promise<{ fileData: string; mimeType: string | undefined; filename: string | undefined }> {
133
+ const maxSize = options.maxSizeBytes ?? DEFAULT_MAX_FILE_SIZE;
134
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
135
+ const allowedProtocols = options.allowedProtocols ? new Set(options.allowedProtocols) : ALLOWED_PROTOCOLS;
136
+
137
+ let protocol: string;
138
+ try {
139
+ protocol = new URL(url).protocol;
140
+ } catch {
141
+ throw new FileProcessorError('invalid_url', `File URL '${url}' is not a valid URL.`);
142
+ }
143
+
144
+ if (!allowedProtocols.has(protocol)) {
145
+ throw new FileProcessorError('unsupported_protocol', `File URL protocol '${protocol}' is not allowed.`);
146
+ }
147
+
148
+ const controller = new AbortController();
149
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
150
+
151
+ try {
152
+ const response = await fetch(url, {
153
+ signal: controller.signal,
154
+ redirect: 'follow',
155
+ });
156
+
157
+ if (!response.ok) {
158
+ throw new FileProcessorError(
159
+ 'fetch_failed',
160
+ `Failed to fetch file from '${url}': ${response.status} ${response.statusText}`,
161
+ );
162
+ }
163
+
164
+ const contentLength = response.headers.get('content-length');
165
+ if (contentLength && Number(contentLength) > maxSize) {
166
+ throw new FileProcessorError('file_too_large', `File at '${url}' exceeds maximum allowed size.`);
167
+ }
168
+
169
+ const contentType = response.headers.get('content-type') || undefined;
170
+ if (
171
+ options.allowedContentTypes &&
172
+ contentType &&
173
+ !options.allowedContentTypes.some((type) => contentType.includes(type))
174
+ ) {
175
+ throw new FileProcessorError('content_type_not_allowed', `File content type '${contentType}' is not allowed.`);
176
+ }
177
+
178
+ const buffer = Buffer.from(await response.arrayBuffer());
179
+ if (buffer.length > maxSize) {
180
+ throw new FileProcessorError('file_too_large', `File at '${url}' exceeds maximum allowed size.`);
181
+ }
182
+
183
+ const mimeType = contentType?.split(';')[0].trim() ?? 'application/octet-stream';
184
+ const contentDisposition = response.headers.get('content-disposition');
185
+ const filename = extractFilename(url, contentDisposition) ?? 'file';
186
+
187
+ return {
188
+ fileData: `data:${mimeType};base64,${buffer.toString('base64')}`,
189
+ mimeType,
190
+ filename,
191
+ };
192
+ } finally {
193
+ clearTimeout(timeout);
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Default processor: forwards base64 `file` blocks unchanged.
199
+ * Handles `{ type: 'file', file: { file_data: 'data:...;base64,...' } }`.
200
+ */
201
+ export const base64FileForwarder: FileProcessor = {
202
+ name: 'base64FileForwarder',
203
+ canHandle(block: FileContentBlock): boolean {
204
+ if (block.type !== 'file') return false;
205
+ const file = isRecord(block.file) ? block.file : undefined;
206
+ if (!file) return false;
207
+ const fileData = String(file.file_data ?? '');
208
+ return fileData.startsWith('data:') && fileData.includes(';base64,');
209
+ },
210
+ async process(block: FileContentBlock): Promise<FileContentBlock> {
211
+ return block;
212
+ },
213
+ };
214
+
215
+ /**
216
+ * Default processor: downloads an http(s) `file_url` and converts it into a `file` block.
217
+ * Handles `{ type: 'file_url', file_url: { url: 'https://...' } }`.
218
+ */
219
+ export const httpFileUrlFetcher: FileProcessor = {
220
+ name: 'httpFileUrlFetcher',
221
+ canHandle(block: FileContentBlock): boolean {
222
+ if (block.type !== 'file_url') return false;
223
+ const fileUrl = isRecord(block.file_url) ? block.file_url : undefined;
224
+ if (!fileUrl) return false;
225
+ const url = String(fileUrl.url ?? '');
226
+ return url.startsWith('http://') || url.startsWith('https://');
227
+ },
228
+ async process(block: FileContentBlock): Promise<FileContentBlock> {
229
+ const fileUrl = isRecord(block.file_url) ? block.file_url : undefined;
230
+ const url = String(fileUrl?.url ?? '');
231
+ if (!url) {
232
+ throw new FileProcessorError('missing_url', "file_url block requires a 'url' property.");
233
+ }
234
+ const { fileData, mimeType, filename } = await fetchFileAsBase64(url);
235
+ return {
236
+ type: 'file',
237
+ file: {
238
+ file_data: fileData,
239
+ mime_type: mimeType,
240
+ filename: filename || 'file',
241
+ },
242
+ };
243
+ },
244
+ };
245
+
246
+ function decodeBase64DataUrl(url: string): { mimeType: string; buffer: Buffer } | undefined {
247
+ const match = /^data:([^;]+);base64,([A-Za-z0-9+/]+=*)$/.exec(url);
248
+ if (!match) return undefined;
249
+ try {
250
+ const buffer = Buffer.from(match[2], 'base64');
251
+ return { mimeType: match[1].toLowerCase(), buffer };
252
+ } catch {
253
+ return undefined;
254
+ }
255
+ }
256
+
257
+ function isPdfBuffer(buffer: Buffer): boolean {
258
+ return buffer.length >= 4 && buffer.toString('binary', 0, 4) === '%PDF';
259
+ }
260
+
261
+ function isPdfFileBlock(block: FileContentBlock): boolean {
262
+ if (block.type !== 'file') return false;
263
+ const file = isRecord(block.file) ? block.file : undefined;
264
+ if (!file) return false;
265
+ const fileData = String(file.file_data ?? '');
266
+ if (!fileData.startsWith('data:')) return false;
267
+ const mimeType = String(file.mime_type ?? '').toLowerCase();
268
+ if (mimeType === 'application/pdf') return true;
269
+ if (fileData.startsWith('data:application/pdf')) return true;
270
+ const decoded = decodeBase64DataUrl(fileData);
271
+ if (decoded && isPdfBuffer(decoded.buffer)) return true;
272
+ return false;
273
+ }
274
+
275
+ function getPluginFromContext(context: FileProcessorContext): any | undefined {
276
+ // @ts-expect-error app may not be typed on Context in test mocks.
277
+ return context.ctx.app?.pm?.get?.('plugin-ai-api');
278
+ }
279
+
280
+ /**
281
+ * Optional processor: converts a PDF `file` block into a series of `image_url`
282
+ * blocks when `pdfRenderPagesAsImages` is enabled and a PdfToImageRenderer is
283
+ * registered. When disabled, unavailable, or the block is not a PDF, the block
284
+ * is forwarded unchanged.
285
+ */
286
+ export const pdfFileProcessor: FileProcessor = {
287
+ name: 'pdfFileProcessor',
288
+ canHandle(block: FileContentBlock): boolean {
289
+ return isPdfFileBlock(block);
290
+ },
291
+ async process(
292
+ block: FileContentBlock,
293
+ context: FileProcessorContext,
294
+ ): Promise<FileContentBlock | FileContentBlock[]> {
295
+ const config = await context.ctx.db.getRepository('aiApiConfig').findOne();
296
+ if (!config?.pdfRenderPagesAsImages) {
297
+ return block;
298
+ }
299
+
300
+ const plugin = getPluginFromContext(context);
301
+ const renderer = plugin?.fileProcessorService?.getPdfRenderer?.();
302
+ if (!renderer) {
303
+ context.ctx.log?.warn?.(
304
+ '[pdfFileProcessor] pdfRenderPagesAsImages is enabled but no PdfToImageRenderer is registered. ' +
305
+ 'Forwarding PDF as a file block.',
306
+ );
307
+ return block;
308
+ }
309
+
310
+ const file = isRecord(block.file) ? block.file : undefined;
311
+ const fileData = String(file?.file_data ?? '');
312
+ const decoded = decodeBase64DataUrl(fileData);
313
+ if (!decoded) {
314
+ return block;
315
+ }
316
+
317
+ const pages = await renderer.render(decoded.buffer);
318
+ return pages.map((buffer) => ({
319
+ type: 'image_url',
320
+ image_url: { url: `data:image/png;base64,${buffer.toString('base64')}` },
321
+ }));
322
+ },
323
+ };
@@ -6,6 +6,7 @@ export type Usage = {
6
6
  prompt_tokens: number | null;
7
7
  completion_tokens: number | null;
8
8
  total_tokens: number | null;
9
+ prompt_cache_tokens?: number | null;
9
10
  };
10
11
 
11
12
  export type AiApiAuthType = 'apiKey' | 'bearer' | 'oidc' | 'unknown';
@@ -48,6 +49,33 @@ function normalizeTokenCount(value: unknown): number | null {
48
49
  return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
49
50
  }
50
51
 
52
+ /**
53
+ * Extract cached prompt tokens from a provider usage or response metadata object.
54
+ * Tolerates both LangChain-style (`input_token_details.cache_read`) and raw
55
+ * OpenAI-style (`prompt_tokens_details.cached_tokens`) shapes.
56
+ */
57
+ function extractPromptCacheTokens(source: Record<string, unknown>): number | null {
58
+ const inputDetails = source.input_token_details;
59
+ if (inputDetails && typeof inputDetails === 'object') {
60
+ const cacheRead = (inputDetails as Record<string, unknown>).cache_read;
61
+ if (typeof cacheRead === 'number') return cacheRead;
62
+ const cachedTokens = (inputDetails as Record<string, unknown>).cached_tokens;
63
+ if (typeof cachedTokens === 'number') return cachedTokens;
64
+ }
65
+
66
+ const promptDetails = source.prompt_tokens_details;
67
+ if (promptDetails && typeof promptDetails === 'object') {
68
+ const cachedTokens = (promptDetails as Record<string, unknown>).cached_tokens;
69
+ if (typeof cachedTokens === 'number') return cachedTokens;
70
+ }
71
+
72
+ if (typeof source.cached_tokens === 'number') return source.cached_tokens;
73
+ if (typeof source.cache_read_tokens === 'number') return source.cache_read_tokens;
74
+ if (typeof source.cache_read === 'number') return source.cache_read;
75
+
76
+ return null;
77
+ }
78
+
51
79
  export function normalizeUsage(value: unknown): Usage | undefined {
52
80
  if (!value || typeof value !== 'object') return undefined;
53
81
  const source = value as Record<string, unknown>;
@@ -65,6 +93,7 @@ export function normalizeUsage(value: unknown): Usage | undefined {
65
93
  prompt_tokens: prompt,
66
94
  completion_tokens: completion,
67
95
  total_tokens: total,
96
+ prompt_cache_tokens: extractPromptCacheTokens(source),
68
97
  };
69
98
  }
70
99
 
@@ -72,8 +101,24 @@ export function setAiApiUsageResult(
72
101
  ctx: Context,
73
102
  value: unknown,
74
103
  metadata: Pick<AiApiUsageResult, 'gatewayResponseId' | 'providerRequestId'> = {},
104
+ responseMetadata?: unknown,
75
105
  ): Usage | undefined {
76
- const usage = normalizeUsage(value);
106
+ let usage = normalizeUsage(value);
107
+
108
+ // Some providers only surface cached token details on response_metadata; fall
109
+ // back there when the usage object itself does not carry them.
110
+ if (usage?.prompt_cache_tokens === null && responseMetadata && typeof responseMetadata === 'object') {
111
+ const responseMetaRecord = responseMetadata as Record<string, unknown>;
112
+ let cacheTokens = extractPromptCacheTokens(responseMetaRecord);
113
+ // Providers sometimes nest the raw provider usage under response_metadata.usage.
114
+ if (cacheTokens === null && responseMetaRecord.usage && typeof responseMetaRecord.usage === 'object') {
115
+ cacheTokens = extractPromptCacheTokens(responseMetaRecord.usage as Record<string, unknown>);
116
+ }
117
+ if (cacheTokens !== null) {
118
+ usage = { ...usage, prompt_cache_tokens: cacheTokens };
119
+ }
120
+ }
121
+
77
122
  getAiApiState(ctx).aiApiUsageResult = usage
78
123
  ? { source: 'provider', usage, ...metadata }
79
124
  : { source: 'unavailable', ...metadata };
@@ -174,6 +219,7 @@ export async function finishUsageRecord(ctx: Context, id: unknown, startedAt: nu
174
219
  inputTokens: usage?.prompt_tokens ?? null,
175
220
  outputTokens: usage?.completion_tokens ?? null,
176
221
  totalTokens: usage?.total_tokens ?? null,
222
+ promptCacheTokens: usage?.prompt_cache_tokens ?? null,
177
223
  resolvedService: state.aiApiLlmBilling?.resolution?.service ?? null,
178
224
  resolvedProvider: state.aiApiLlmBilling?.resolution?.provider ?? null,
179
225
  resolvedModel: state.aiApiLlmBilling?.resolution?.model ?? null,