briyah 2.0.8 → 2.0.10

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.
@@ -13,6 +13,13 @@ export declare class AnthropicAiService extends BaseAiService {
13
13
  createAgent(userPaths: UserPathsService, configService: IConfigService, agentStoreService: AgentStoreService, balanceService: BalanceService, artifactService: ArtifactService, agentName: string, agentNickname: string, description: string, promptFolder: string, modelName: string, storageDir?: string): Agent;
14
14
  getServiceName(): string;
15
15
  supportsImageGeneration(): boolean;
16
+ supportsImageAttachments(): boolean;
17
+ /**
18
+ * An attached file as Anthropic content: a PDF as a document block, an image
19
+ * as an image block (named in a text block before it, so the model can tell
20
+ * several apart), anything else as its text.
21
+ */
22
+ private static attachedFileContent;
16
23
  supportsPromptCaching(): boolean;
17
24
  getCacheConfig(agent: Agent, cacheMessage: boolean): {
18
25
  type: string;
@@ -18,6 +18,7 @@ const model_prices_1 = require("../model_prices");
18
18
  const errors_1 = require("../../common/errors");
19
19
  const logger_1 = require("../../common/logger");
20
20
  const ai_debug_logger_1 = require("../ai-debug-logger");
21
+ const attachment_type_1 = require("./attachment-type");
21
22
  let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.BaseAiService {
22
23
  static { AnthropicAiService_1 = this; }
23
24
  anthropic;
@@ -53,6 +54,30 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
53
54
  supportsImageGeneration() {
54
55
  return false;
55
56
  }
57
+ supportsImageAttachments() {
58
+ return true;
59
+ }
60
+ /**
61
+ * An attached file as Anthropic content: a PDF as a document block, an image
62
+ * as an image block (named in a text block before it, so the model can tell
63
+ * several apart), anything else as its text.
64
+ */
65
+ static attachedFileContent(file) {
66
+ const fileData = new Uint8Array(file.serviceMetadata.fileData);
67
+ if (file.mimeType === 'application/pdf') {
68
+ return [{
69
+ type: 'document',
70
+ source: { type: 'base64', media_type: 'application/pdf', data: Buffer.from(fileData).toString('base64') },
71
+ }];
72
+ }
73
+ if ((0, attachment_type_1.isAttachmentImage)(file.mimeType)) {
74
+ return [
75
+ { type: 'text', text: `Attached image "${file.fileName}":` },
76
+ { type: 'image', source: { type: 'base64', media_type: file.mimeType, data: Buffer.from(fileData).toString('base64') } },
77
+ ];
78
+ }
79
+ return [{ type: 'text', text: `Attached file "${file.fileName}":\n\n${Buffer.from(fileData).toString('utf-8')}` }];
80
+ }
56
81
  supportsPromptCaching() {
57
82
  return true;
58
83
  }
@@ -158,30 +183,8 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
158
183
  // Build a separate message for each attached file
159
184
  for (const file of attachedFiles) {
160
185
  if (file.serviceMetadata?.fileData) {
161
- const fileData = new Uint8Array(file.serviceMetadata.fileData);
162
- let fileContent;
163
- // Anthropic only supports PDFs as documents, text files need to be converted to text
164
- if (file.mimeType === 'application/pdf') {
165
- const base64Data = Buffer.from(fileData).toString('base64');
166
- fileContent = {
167
- type: 'document',
168
- source: {
169
- type: 'base64',
170
- media_type: 'application/pdf',
171
- data: base64Data,
172
- },
173
- };
174
- }
175
- else {
176
- // For text-based files (md, txt, etc.), convert to text
177
- const textContent = Buffer.from(fileData).toString('utf-8');
178
- fileContent = {
179
- type: 'text',
180
- text: `Attached file "${file.fileName}":\n\n${textContent}`,
181
- };
182
- }
183
186
  // Each document becomes its own message
184
- documentMessages.push({ role: 'user', content: [fileContent] });
187
+ documentMessages.push({ role: 'user', content: AnthropicAiService_1.attachedFileContent(file) });
185
188
  }
186
189
  }
187
190
  // Handle attached artifacts
@@ -0,0 +1,21 @@
1
+ /**
2
+ * What kind of file an agent is being handed, so each AI service can send it
3
+ * the way its API expects: a PDF as a document, a photo as an image, and
4
+ * anything else as text.
5
+ *
6
+ * The bytes decide first (a phone photo called "receipt.pdf" is still a JPEG),
7
+ * then the extension. HEIC (an iPhone's own photo format) is recognised so it
8
+ * can be refused with a message saying what to send instead; no AI service
9
+ * here reads it.
10
+ */
11
+ /** The image types the services that read images accept. */
12
+ export declare const ATTACHMENT_IMAGE_TYPES: readonly ["image/jpeg", "image/png", "image/gif", "image/webp"];
13
+ export type AttachmentImageType = (typeof ATTACHMENT_IMAGE_TYPES)[number];
14
+ /** Anthropic refuses an image over 5 MB (base64 makes it a third bigger again). */
15
+ export declare const MAX_ATTACHED_IMAGE_BYTES: number;
16
+ /** The MIME type of an image or PDF from its first bytes, or null when they say nothing. */
17
+ export declare function sniffAttachmentType(data: Uint8Array): string | null;
18
+ /** The MIME type an attachment is sent as: its bytes' if they identify it, else its extension's. */
19
+ export declare function detectAttachmentMimeType(fileName: string, data: Uint8Array): string;
20
+ /** True for the image types a service that reads images can be sent. */
21
+ export declare function isAttachmentImage(mimeType: string | null | undefined): mimeType is AttachmentImageType;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ /**
3
+ * What kind of file an agent is being handed, so each AI service can send it
4
+ * the way its API expects: a PDF as a document, a photo as an image, and
5
+ * anything else as text.
6
+ *
7
+ * The bytes decide first (a phone photo called "receipt.pdf" is still a JPEG),
8
+ * then the extension. HEIC (an iPhone's own photo format) is recognised so it
9
+ * can be refused with a message saying what to send instead; no AI service
10
+ * here reads it.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.MAX_ATTACHED_IMAGE_BYTES = exports.ATTACHMENT_IMAGE_TYPES = void 0;
14
+ exports.sniffAttachmentType = sniffAttachmentType;
15
+ exports.detectAttachmentMimeType = detectAttachmentMimeType;
16
+ exports.isAttachmentImage = isAttachmentImage;
17
+ /** The image types the services that read images accept. */
18
+ exports.ATTACHMENT_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
19
+ /** Anthropic refuses an image over 5 MB (base64 makes it a third bigger again). */
20
+ exports.MAX_ATTACHED_IMAGE_BYTES = 5 * 1024 * 1024;
21
+ const BY_EXTENSION = {
22
+ pdf: 'application/pdf',
23
+ txt: 'text/plain',
24
+ md: 'text/plain',
25
+ doc: 'application/msword',
26
+ docx: 'application/msword',
27
+ xls: 'application/vnd.ms-excel',
28
+ xlsx: 'application/vnd.ms-excel',
29
+ jpg: 'image/jpeg',
30
+ jpeg: 'image/jpeg',
31
+ png: 'image/png',
32
+ gif: 'image/gif',
33
+ webp: 'image/webp',
34
+ heic: 'image/heic',
35
+ heif: 'image/heic',
36
+ };
37
+ function startsWith(data, bytes, offset = 0) {
38
+ if (data.length < offset + bytes.length)
39
+ return false;
40
+ return bytes.every((b, i) => data[offset + i] === b);
41
+ }
42
+ function ascii(text) {
43
+ return [...text].map((c) => c.charCodeAt(0));
44
+ }
45
+ /** The MIME type of an image or PDF from its first bytes, or null when they say nothing. */
46
+ function sniffAttachmentType(data) {
47
+ if (startsWith(data, [0xff, 0xd8, 0xff]))
48
+ return 'image/jpeg';
49
+ if (startsWith(data, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
50
+ return 'image/png';
51
+ if (startsWith(data, ascii('GIF87a')) || startsWith(data, ascii('GIF89a')))
52
+ return 'image/gif';
53
+ if (startsWith(data, ascii('RIFF')) && startsWith(data, ascii('WEBP'), 8))
54
+ return 'image/webp';
55
+ if (startsWith(data, ascii('%PDF-')))
56
+ return 'application/pdf';
57
+ // ISO media: "ftyp" at offset 4, then a brand. These brands are HEIC/HEIF stills.
58
+ if (startsWith(data, ascii('ftyp'), 4)) {
59
+ const brand = String.fromCharCode(...data.slice(8, 12));
60
+ if (['heic', 'heix', 'hevc', 'heim', 'heis', 'mif1', 'msf1'].includes(brand))
61
+ return 'image/heic';
62
+ }
63
+ return null;
64
+ }
65
+ /** The MIME type an attachment is sent as: its bytes' if they identify it, else its extension's. */
66
+ function detectAttachmentMimeType(fileName, data) {
67
+ const sniffed = sniffAttachmentType(data);
68
+ if (sniffed)
69
+ return sniffed;
70
+ const ext = (fileName.split('.').pop() ?? '').toLowerCase();
71
+ return BY_EXTENSION[ext] ?? 'application/octet-stream';
72
+ }
73
+ /** True for the image types a service that reads images can be sent. */
74
+ function isAttachmentImage(mimeType) {
75
+ return !!mimeType && exports.ATTACHMENT_IMAGE_TYPES.includes(mimeType);
76
+ }
@@ -27,6 +27,12 @@ export declare class BaseAiService {
27
27
  */
28
28
  getModelPricePrefix(): string | null;
29
29
  supportsImageGeneration(): boolean;
30
+ /**
31
+ * Whether attachDocument() accepts images (JPEG, PNG, GIF, WebP) for the
32
+ * model to look at. A service that says no refuses them rather than sending
33
+ * the bytes on as text.
34
+ */
35
+ supportsImageAttachments(): boolean;
30
36
  /**
31
37
  * Whether createAgent() must find the model in model_prices.json /
32
38
  * image_models.json before an agent can be created. Services whose model
@@ -103,6 +109,24 @@ export declare class BaseAiService {
103
109
  * @returns Promise with model information
104
110
  */
105
111
  listModels(): Promise<ModelInfo[]>;
112
+ /**
113
+ * Drops the models {@link createAgent} would refuse, so the picker only offers
114
+ * models that can actually be used.
115
+ *
116
+ * A provider API lists everything it hosts — embeddings, speech, video, music,
117
+ * retired preview ids — but an agent can only be built for a model that has a
118
+ * pricing entry, because cost tracking and balance gating have nothing to charge
119
+ * without one. Sharing {@link isKnownModel} with the creation gate is what keeps
120
+ * the two from drifting apart; filtering on any other rule would reopen the gap.
121
+ *
122
+ * Services exempt from that gate (`requiresKnownModel() === false`) are returned
123
+ * unchanged, since their models are self-hosted or free and never appear in
124
+ * model_prices.json.
125
+ *
126
+ * @param models The models the provider API returned
127
+ * @returns The usable subset, or `models` unchanged for an exempt service
128
+ */
129
+ protected withoutUnpricedModels(models: ModelInfo[]): ModelInfo[];
106
130
  /**
107
131
  * Actual implementation to fetch models from the API
108
132
  * This should be overridden by subclasses
@@ -51,6 +51,7 @@ const prompt_resolver_1 = require("../../config/prompt-resolver");
51
51
  const handlebars_1 = require("handlebars");
52
52
  const ai_1 = require("ai");
53
53
  const errors_1 = require("../../common/errors");
54
+ const attachment_type_1 = require("./attachment-type");
54
55
  const logger_1 = require("../../common/logger");
55
56
  const jsonrepair_1 = require("jsonrepair");
56
57
  const model_prices_1 = require("../model_prices");
@@ -88,6 +89,14 @@ let BaseAiService = class BaseAiService {
88
89
  supportsImageGeneration() {
89
90
  return false;
90
91
  }
92
+ /**
93
+ * Whether attachDocument() accepts images (JPEG, PNG, GIF, WebP) for the
94
+ * model to look at. A service that says no refuses them rather than sending
95
+ * the bytes on as text.
96
+ */
97
+ supportsImageAttachments() {
98
+ return false;
99
+ }
91
100
  /**
92
101
  * Whether createAgent() must find the model in model_prices.json /
93
102
  * image_models.json before an agent can be created. Services whose model
@@ -251,14 +260,47 @@ let BaseAiService = class BaseAiService {
251
260
  try {
252
261
  const models = await this.fetchModelsFromApi();
253
262
  // Cache the result for future calls
254
- this.modelsCache = models;
255
- return models;
263
+ this.modelsCache = this.withoutUnpricedModels(models);
264
+ return this.modelsCache;
256
265
  }
257
266
  catch (error) {
258
267
  logger_1.logger.error(`Error fetching models for ${this.getServiceName()}:`, error);
259
268
  throw error;
260
269
  }
261
270
  }
271
+ /**
272
+ * Drops the models {@link createAgent} would refuse, so the picker only offers
273
+ * models that can actually be used.
274
+ *
275
+ * A provider API lists everything it hosts — embeddings, speech, video, music,
276
+ * retired preview ids — but an agent can only be built for a model that has a
277
+ * pricing entry, because cost tracking and balance gating have nothing to charge
278
+ * without one. Sharing {@link isKnownModel} with the creation gate is what keeps
279
+ * the two from drifting apart; filtering on any other rule would reopen the gap.
280
+ *
281
+ * Services exempt from that gate (`requiresKnownModel() === false`) are returned
282
+ * unchanged, since their models are self-hosted or free and never appear in
283
+ * model_prices.json.
284
+ *
285
+ * @param models The models the provider API returned
286
+ * @returns The usable subset, or `models` unchanged for an exempt service
287
+ */
288
+ withoutUnpricedModels(models) {
289
+ if (!this.requiresKnownModel() || !Array.isArray(models))
290
+ return models;
291
+ const prefix = this.getModelPricePrefix();
292
+ const usable = models.filter((model) => (0, model_prices_1.isKnownModel)(model.model, prefix));
293
+ const hidden = models.length - usable.length;
294
+ if (hidden > 0) {
295
+ logger_1.logger.debug(`${this.getServiceName()}: hiding ${hidden} of ${models.length} models with no model_prices.json entry`);
296
+ }
297
+ // An empty picker looks the same as a dead provider in the UI, so name the
298
+ // cause while the pricing table is still the thing to go and look at.
299
+ if (models.length > 0 && usable.length === 0) {
300
+ logger_1.logger.warn(`${this.getServiceName()}: none of its ${models.length} models have a model_prices.json entry; the model picker will be empty`);
301
+ }
302
+ return usable;
303
+ }
262
304
  /**
263
305
  * Actual implementation to fetch models from the API
264
306
  * This should be overridden by subclasses
@@ -323,7 +365,8 @@ let BaseAiService = class BaseAiService {
323
365
  _saveResponse = true, // eslint-disable-line @typescript-eslint/no-unused-vars
324
366
  _promptInstructions = null, // eslint-disable-line @typescript-eslint/no-unused-vars
325
367
  _cacheConfig = null, // eslint-disable-line @typescript-eslint/no-unused-vars
326
- _maxOutputChars = 0) {
368
+ _maxOutputChars = 0 // eslint-disable-line @typescript-eslint/no-unused-vars
369
+ ) {
327
370
  // Check if service is available
328
371
  if (!this.isAvailable) {
329
372
  return Promise.reject(new Error(`${this.getServiceName()} service is not available. Check API key configuration.`));
@@ -464,23 +507,18 @@ let BaseAiService = class BaseAiService {
464
507
  throw new Error('Shared document attachment not supported by this service');
465
508
  }
466
509
  try {
467
- let ext = fileName.split('.').pop();
468
- let mimeType = 'application/octet-stream';
469
- // Determine MIME type based on extension
470
- if (ext.toLowerCase() === 'pdf') {
471
- mimeType = 'application/pdf';
472
- }
473
- else if (ext.toLowerCase() === 'txt') {
474
- mimeType = 'text/plain';
475
- }
476
- else if (ext.toLowerCase() === 'md') {
477
- mimeType = 'text/plain';
478
- }
479
- else if (['doc', 'docx'].includes(ext.toLowerCase())) {
480
- mimeType = 'application/msword';
510
+ // The bytes decide first (a photo named .pdf is still a photo), then the extension.
511
+ const mimeType = (0, attachment_type_1.detectAttachmentMimeType)(fileName, fileData);
512
+ if (mimeType === 'image/heic') {
513
+ throw new Error(`${fileName} is a HEIC photo, which AI services cannot read; send it as a JPEG or PNG`);
481
514
  }
482
- else if (['xls', 'xlsx'].includes(ext.toLowerCase())) {
483
- mimeType = 'application/vnd.ms-excel';
515
+ if ((0, attachment_type_1.isAttachmentImage)(mimeType)) {
516
+ if (!this.supportsImageAttachments()) {
517
+ throw new Error(`The ${this.getServiceName()} service does not read images; ${fileName} cannot be attached`);
518
+ }
519
+ if (fileData.length > attachment_type_1.MAX_ATTACHED_IMAGE_BYTES) {
520
+ throw new Error(`${fileName} is ${(fileData.length / 1048576).toFixed(1)} MB; images must be ${attachment_type_1.MAX_ATTACHED_IMAGE_BYTES / 1048576} MB or less`);
521
+ }
484
522
  }
485
523
  // Create metadata for this file and store the file data with it
486
524
  const fileMetadata = {
@@ -18,10 +18,16 @@ export declare class OpenAiService extends BaseAiService {
18
18
  constructor();
19
19
  getServiceName(): string;
20
20
  supportsImageGeneration(): boolean;
21
+ supportsImageAttachments(): boolean;
22
+ /**
23
+ * An attached file sent with the request (not through a vector store): an
24
+ * image as a Responses API input_image, anything else as its text.
25
+ */
26
+ private static attachedFileMessage;
21
27
  supportsPromptCaching(): boolean;
22
28
  fetchModelsFromApi(): Promise<ModelInfo[]>;
23
29
  finishAgent(agent: Agent): Promise<void>;
24
- textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, maxOutputChars?: number): Promise<any>;
30
+ textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, _maxOutputChars?: number): Promise<any>;
25
31
  attachDocument(agent: Agent, fileName: string, fileData: Uint8Array): Promise<string>;
26
32
  /**
27
33
  * Adds a message to the agent history in the appropriate format for this service
@@ -8,6 +8,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
+ var OpenAiService_1;
11
12
  Object.defineProperty(exports, "__esModule", { value: true });
12
13
  exports.OpenAiService = void 0;
13
14
  const common_1 = require("@nestjs/common");
@@ -16,6 +17,7 @@ const base_ai_service_1 = require("./base-ai.service");
16
17
  const openai_2 = require("openai");
17
18
  const model_prices_1 = require("../model_prices");
18
19
  const errors_1 = require("../../common/errors");
20
+ const attachment_type_1 = require("./attachment-type");
19
21
  const logger_1 = require("../../common/logger");
20
22
  // Effort levels in ascending intensity. Used to pick the nearest supported
21
23
  // effort when an agent's configured value isn't allowed by a given model.
@@ -27,7 +29,7 @@ const EFFORT_ORDER = ['low', 'medium', 'high'];
27
29
  const MODEL_EFFORT_ALLOWLIST = {
28
30
  'gpt-5-pro': ['high'],
29
31
  };
30
- let OpenAiService = class OpenAiService extends base_ai_service_1.BaseAiService {
32
+ let OpenAiService = OpenAiService_1 = class OpenAiService extends base_ai_service_1.BaseAiService {
31
33
  openai;
32
34
  /**
33
35
  * Returns the effort levels the given model accepts, or `null` if the
@@ -100,6 +102,26 @@ let OpenAiService = class OpenAiService extends base_ai_service_1.BaseAiService
100
102
  supportsImageGeneration() {
101
103
  return true;
102
104
  }
105
+ supportsImageAttachments() {
106
+ return true;
107
+ }
108
+ /**
109
+ * An attached file sent with the request (not through a vector store): an
110
+ * image as a Responses API input_image, anything else as its text.
111
+ */
112
+ static attachedFileMessage(file) {
113
+ const fileData = new Uint8Array(file.serviceMetadata.fileData);
114
+ if ((0, attachment_type_1.isAttachmentImage)(file.mimeType)) {
115
+ return {
116
+ role: 'user',
117
+ content: [
118
+ { type: 'input_text', text: `Attached image "${file.fileName}":` },
119
+ { type: 'input_image', image_url: `data:${file.mimeType};base64,${Buffer.from(fileData).toString('base64')}` },
120
+ ],
121
+ };
122
+ }
123
+ return { role: 'user', content: `File "${file.fileName}":\n\n${Buffer.from(fileData).toString('utf-8')}` };
124
+ }
103
125
  supportsPromptCaching() {
104
126
  return false;
105
127
  }
@@ -144,7 +166,9 @@ let OpenAiService = class OpenAiService extends base_ai_service_1.BaseAiService
144
166
  }
145
167
  async textPrompt(agent, prompt, jsonSchema = null, saveResponse = true, promptInstructions = null,
146
168
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
147
- _cacheConfig = null, maxOutputChars = 0) {
169
+ _cacheConfig = null,
170
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
171
+ _maxOutputChars = 0) {
148
172
  // CHECK BALANCE BEFORE AI CALL (unless disabled)
149
173
  if (agent.balanceService && !agent.disableBalanceCheck) {
150
174
  const hasSufficientBalance = agent.balanceService.hasSufficientBalance();
@@ -167,13 +191,7 @@ let OpenAiService = class OpenAiService extends base_ai_service_1.BaseAiService
167
191
  hasVectorStoreFiles = true;
168
192
  }
169
193
  else if (file.serviceMetadata?.fileData) {
170
- // File has direct data - include it in the message
171
- const fileData = new Uint8Array(file.serviceMetadata.fileData);
172
- const textContent = Buffer.from(fileData).toString('utf-8');
173
- messages.push({
174
- role: 'user',
175
- content: `File "${file.fileName}":\n\n${textContent}`,
176
- });
194
+ messages.push(OpenAiService_1.attachedFileMessage(file));
177
195
  }
178
196
  }
179
197
  // Add message about vector store files if any exist
@@ -512,7 +530,7 @@ let OpenAiService = class OpenAiService extends base_ai_service_1.BaseAiService
512
530
  }
513
531
  };
514
532
  exports.OpenAiService = OpenAiService;
515
- exports.OpenAiService = OpenAiService = __decorate([
533
+ exports.OpenAiService = OpenAiService = OpenAiService_1 = __decorate([
516
534
  (0, common_1.Injectable)(),
517
535
  __metadata("design:paramtypes", [])
518
536
  ], OpenAiService);
@@ -1,6 +1,7 @@
1
1
  /**
2
- * The pricing table: the bundled one, with the host's {@link LOCAL_PRICES_FILE}
3
- * merged over it.
2
+ * The pricing table, in three layers: the vendored one, our own
3
+ * {@link ANNOTATIONS_FILE} fields merged into the entries they name, and the
4
+ * host's {@link LOCAL_PRICES_FILE} merged over both.
4
5
  *
5
6
  * A shallow merge keyed by model name, so an overlay entry replaces a bundled one
6
7
  * outright rather than being merged field by field. Half an entry is worse than
@@ -56,6 +56,23 @@ const logger_1 = require("../common/logger");
56
56
  * accident to guard against — negotiated pricing has nowhere else to live.
57
57
  */
58
58
  const LOCAL_PRICES_FILE = 'model_prices.local.json';
59
+ /**
60
+ * Briyah's own capability facts about models in the bundled table.
61
+ *
62
+ * Some things we need to know are not in litellm's table and never will be --
63
+ * `supports_web_search_filtering` says whether Anthropic accepts the newer
64
+ * `web_search_20260209` server tool, which only our own request builder cares
65
+ * about. Annotating `model_prices.json` in place was the obvious home and the
66
+ * wrong one: `update-model-prices.js` writes the fetched bytes verbatim, so every
67
+ * refresh wipes the annotation and nothing says so.
68
+ *
69
+ * Kept here, the vendored table stays a byte-for-byte copy and these survive by
70
+ * construction. Merged **field by field** over the entry they name, unlike
71
+ * {@link LOCAL_PRICES_FILE}, which replaces an entry whole: an annotation adds a
72
+ * fact to a vendored entry rather than restating it, so merging any other way
73
+ * would mean copying prices here to keep them.
74
+ */
75
+ const ANNOTATIONS_FILE = 'model_prices.annotations.json';
59
76
  // Lazy-loaded so that BRIYAH_DATA_PATH is read at first use, not at import time.
60
77
  let _modelPrices = null;
61
78
  let _imageModels = null;
@@ -105,8 +122,38 @@ function getImageModels() {
105
122
  return _imageModels;
106
123
  }
107
124
  /**
108
- * The pricing table: the bundled one, with the host's {@link LOCAL_PRICES_FILE}
109
- * merged over it.
125
+ * Adds {@link ANNOTATIONS_FILE} fields to the bundled entries they name.
126
+ *
127
+ * An annotation only ever decorates an entry that already exists. A name the
128
+ * table does not have is skipped rather than created, because an entry holding a
129
+ * capability flag and no prices would read as a known model to `isKnownModel` and
130
+ * let an agent be built for it -- costing every call at zero, which is the exact
131
+ * thing the pricing gate exists to prevent. It warns, since the usual cause is a
132
+ * model retired upstream and the annotation outliving it.
133
+ *
134
+ * @param bundled The vendored table
135
+ * @param annotations The annotations file contents
136
+ * @returns A copy of `bundled` with the annotated fields applied
137
+ */
138
+ function applyAnnotations(bundled, annotations) {
139
+ const merged = { ...bundled };
140
+ for (const [modelName, fields] of Object.entries(annotations)) {
141
+ if (!fields || typeof fields !== 'object' || Array.isArray(fields)) {
142
+ logger_1.logger.warn(`Ignoring ${ANNOTATIONS_FILE} entry "${modelName}": expected an object of fields`);
143
+ continue;
144
+ }
145
+ if (!merged[modelName]) {
146
+ logger_1.logger.warn(`${ANNOTATIONS_FILE} annotates "${modelName}", which is not in model_prices.json`);
147
+ continue;
148
+ }
149
+ merged[modelName] = { ...merged[modelName], ...fields };
150
+ }
151
+ return merged;
152
+ }
153
+ /**
154
+ * The pricing table, in three layers: the vendored one, our own
155
+ * {@link ANNOTATIONS_FILE} fields merged into the entries they name, and the
156
+ * host's {@link LOCAL_PRICES_FILE} merged over both.
110
157
  *
111
158
  * A shallow merge keyed by model name, so an overlay entry replaces a bundled one
112
159
  * outright rather than being merged field by field. Half an entry is worse than
@@ -140,7 +187,10 @@ function getModelPrices() {
140
187
  if (localCount > 0) {
141
188
  logger_1.logger.log(`Applied ${localCount} model price entr${localCount === 1 ? 'y' : 'ies'} from ${LOCAL_PRICES_FILE}`);
142
189
  }
143
- _modelPrices = { ...bundled, ...local };
190
+ const annotated = applyAnnotations(bundled, readOptionalJsonObject(path.join(configDir, ANNOTATIONS_FILE)));
191
+ // The host overlay goes on last so it still wins: it replaces an entry whole,
192
+ // annotations and all, which is what makes it an override rather than a layer.
193
+ _modelPrices = { ...annotated, ...local };
144
194
  return _modelPrices;
145
195
  }
146
196
  /**
@@ -25,6 +25,23 @@ function buildDataGuideMarkdown() {
25
25
  '',
26
26
  'A query with no `groupBy` and no `metrics` lists rows. With either, it',
27
27
  'aggregates: `groupBy` gives the dimensions, `metrics` the numbers.',
28
+ '`count` counts rows (with a field, the rows where it is present);',
29
+ '`countDistinct` counts a field\'s different values.',
30
+ '',
31
+ 'To keep only some groups, add `having`: conditions on your own metrics,',
32
+ 'applied after grouping, each naming a metric by its `as`. Groups with more',
33
+ 'than five rows:',
34
+ '',
35
+ '```json',
36
+ '{"dataset": "markets", "groupBy": ["mga"],',
37
+ ' "metrics": [{"fn": "count", "as": "markets"}],',
38
+ ' "having": [{"field": "markets", "op": "gt", "value": 5}]}',
39
+ '```',
40
+ '',
41
+ 'A **list** field holds several values on one row. Filter it with `has`',
42
+ '(holds this value), `hasAny` (holds one of these), `contains` (a member',
43
+ 'contains this text), `isEmpty` or `notEmpty`. A list cannot be grouped or',
44
+ 'aggregated.',
28
45
  '',
29
46
  '**Only what is listed here exists.** A field that is not on a dataset cannot',
30
47
  'be filtered, grouped or summed, and two datasets can only be related if a',
@@ -69,7 +86,7 @@ function describeDataset(set, heading) {
69
86
  /** One field line: what it is, and what may be done with it. */
70
87
  function describeField(field) {
71
88
  const parts = [`\`${field.name}\` (${field.type}`];
72
- if (field.type === 'enum' && field.enumValues?.length) {
89
+ if ((field.type === 'enum' || field.type === 'list') && field.enumValues?.length) {
73
90
  parts.push(`: ${field.enumValues.join(' | ')}`);
74
91
  }
75
92
  parts.push(')');