briyah 2.0.9 → 2.0.11

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 (55) hide show
  1. package/data/common/config/image_models.json +85 -6
  2. package/data/common/config/model_prices.json +30170 -32794
  3. package/dist-sdk/server/src/ai/LLM/anthropic.service.d.ts +7 -0
  4. package/dist-sdk/server/src/ai/LLM/anthropic.service.js +27 -24
  5. package/dist-sdk/server/src/ai/LLM/attachment-type.d.ts +21 -0
  6. package/dist-sdk/server/src/ai/LLM/attachment-type.js +76 -0
  7. package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +6 -0
  8. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +22 -17
  9. package/dist-sdk/server/src/ai/LLM/comfyui.service.js +1 -1
  10. package/dist-sdk/server/src/ai/LLM/deepseek.service.d.ts +1 -1
  11. package/dist-sdk/server/src/ai/LLM/deepseek.service.js +3 -2
  12. package/dist-sdk/server/src/ai/LLM/fal.service.d.ts +1 -1
  13. package/dist-sdk/server/src/ai/LLM/fal.service.js +4 -3
  14. package/dist-sdk/server/src/ai/LLM/googleai.service.d.ts +1 -1
  15. package/dist-sdk/server/src/ai/LLM/googleai.service.js +5 -4
  16. package/dist-sdk/server/src/ai/LLM/grok.service.d.ts +1 -1
  17. package/dist-sdk/server/src/ai/LLM/grok.service.js +3 -2
  18. package/dist-sdk/server/src/ai/LLM/mock.service.d.ts +1 -1
  19. package/dist-sdk/server/src/ai/LLM/mock.service.js +3 -2
  20. package/dist-sdk/server/src/ai/LLM/openai.service.d.ts +7 -1
  21. package/dist-sdk/server/src/ai/LLM/openai.service.js +30 -12
  22. package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +1 -1
  23. package/dist-sdk/server/src/ai/LLM/together.service.d.ts +1 -1
  24. package/dist-sdk/server/src/ai/LLM/together.service.js +5 -4
  25. package/dist-sdk/server/src/ai/agent-config.d.ts +4 -0
  26. package/dist-sdk/server/src/ai/agent-store.service.js +3 -0
  27. package/dist-sdk/server/src/ai/agent.d.ts +7 -0
  28. package/dist-sdk/server/src/ai/agent.js +6 -0
  29. package/dist-sdk/server/src/app/balance.service.d.ts +155 -27
  30. package/dist-sdk/server/src/app/balance.service.js +290 -97
  31. package/dist-sdk/server/src/app/usage-context.d.ts +24 -0
  32. package/dist-sdk/server/src/app/usage-context.js +35 -0
  33. package/dist-sdk/server/src/app.controller.d.ts +5 -0
  34. package/dist-sdk/server/src/app.controller.js +13 -2
  35. package/dist-sdk/server/src/app.service.d.ts +39 -4
  36. package/dist-sdk/server/src/app.service.js +40 -3
  37. package/dist-sdk/server/src/common/errors.d.ts +13 -1
  38. package/dist-sdk/server/src/common/errors.js +21 -1
  39. package/dist-sdk/server/src/packs/pack-instantiation.service.js +1 -0
  40. package/dist-sdk/server/src/packs/pack-manifest.d.ts +3 -1
  41. package/dist-sdk/server/src/packs/pack-manifest.js +2 -0
  42. package/dist-sdk/server/src/room/illustration/illustration.service.d.ts +17 -2
  43. package/dist-sdk/server/src/room/illustration/illustration.service.js +35 -9
  44. package/dist-sdk/server/src/room/illustration/illustration.types.d.ts +6 -0
  45. package/dist-sdk/server/src/room/room-config.d.ts +11 -1
  46. package/dist-sdk/server/src/room/room-store.service.js +4 -0
  47. package/dist-sdk/server/src/room/room.d.ts +9 -1
  48. package/dist-sdk/server/src/room/room.js +16 -1
  49. package/dist-sdk/server/src/sdk/index.d.ts +7 -1
  50. package/dist-sdk/server/src/sdk/index.js +19 -1
  51. package/dist-sdk/server/src/tools/core/illustrate.tool.js +10 -1
  52. package/dist-sdk/server/src/tools/native-tool.types.d.ts +3 -2
  53. package/dist-sdk/shared/types/app.types.d.ts +27 -0
  54. package/dist-sdk/shared/types/app.types.js +6 -1
  55. package/package.json +1 -1
@@ -36,16 +36,37 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.BalanceService = void 0;
37
37
  const fs = __importStar(require("fs"));
38
38
  const path = __importStar(require("path"));
39
+ const usage_context_1 = require("./usage-context");
39
40
  const logger_1 = require("../common/logger");
41
+ const GRANTED_KEPT = 500;
40
42
  /**
41
- * Service for managing user balance
42
- * Tracks AI usage costs and enforces spending limits
43
+ * A user's AI credit: what they may spend, what they spent it on, and the
44
+ * limit that stops AI calls when it is gone.
45
+ *
46
+ * Credit sits in two pots, spent in this order:
47
+ * - **The allowance**, granted by the host for a period (for example, each
48
+ * month an invoice is paid). A new grant replaces it: unused allowance is not
49
+ * carried over. A user who is never granted one simply has none.
50
+ * - **Purchased credit**, added by payments ({@link addBalance}) and kept until
51
+ * used. New users start with `STARTING_BALANCE` here.
52
+ *
53
+ * The state is `userconfig/credits.json`; the single number Briyah kept before
54
+ * (`userconfig/balance`) is read once as purchased credit and then retired.
55
+ * Every charge, grant and purchase is also appended to the usage ledger,
56
+ * `usage/<yyyy-mm>.jsonl` in the user's data directory, with the agent and the
57
+ * usage tags it ran under (see usage-context.ts).
58
+ *
59
+ * A call is allowed while the total is not negative, as before: the last call
60
+ * may overdraw by its own cost, and the overdraft is taken out of the next
61
+ * allowance granted.
43
62
  */
44
63
  class BalanceService {
45
64
  userId;
46
65
  userPaths;
47
- balanceFilePath;
66
+ creditsFilePath;
67
+ legacyBalanceFilePath;
48
68
  markupFilePath;
69
+ usageDir;
49
70
  startingBalance;
50
71
  balanceMessageService;
51
72
  constructor(userId, userPaths, balanceMessageService) {
@@ -63,149 +84,321 @@ class BalanceService {
63
84
  if (this.startingBalance < 0) {
64
85
  throw new Error('STARTING_BALANCE must be non-negative');
65
86
  }
66
- // Set balance file path in user's userconfig directory
67
87
  const userconfigPath = this.userPaths.getUserConfigDir();
68
- this.balanceFilePath = path.join(userconfigPath, 'balance');
69
- const commonConfigPath = this.userPaths.getCommonConfigDir();
70
- this.markupFilePath = path.join(commonConfigPath, 'markup');
88
+ this.creditsFilePath = path.join(userconfigPath, 'credits.json');
89
+ this.legacyBalanceFilePath = path.join(userconfigPath, 'balance');
90
+ this.markupFilePath = path.join(this.userPaths.getCommonConfigDir(), 'markup');
91
+ this.usageDir = path.join(this.userPaths.getUserDataDir(), 'usage');
92
+ }
93
+ // ---- Balance (the total, as callers have always read it) -------------------
94
+ /** What the next call can draw on: allowance remaining plus purchased credit. */
95
+ getBalance() {
96
+ return this.summarize(this.readState()).total;
71
97
  }
72
98
  /**
73
- * Get current balance (loads from file)
74
- * @returns Current balance as number
75
- * @throws If balance file is corrupted
99
+ * Whether the user may make another AI call.
100
+ * @returns true while the total is not negative
76
101
  */
77
- getBalance() {
78
- try {
79
- // Check if balance file exists
80
- if (!fs.existsSync(this.balanceFilePath)) {
81
- // Create with starting balance for new users
82
- this.saveBalance(this.startingBalance);
83
- return this.startingBalance;
84
- }
85
- // Read balance file
86
- const balanceStr = fs.readFileSync(this.balanceFilePath, 'utf-8').trim();
87
- // Parse number
88
- const balance = parseFloat(balanceStr);
89
- if (isNaN(balance)) {
90
- logger_1.logger.error(`Balance file corrupted for user ${this.userId}, resetting to starting balance`);
91
- this.saveBalance(this.startingBalance);
92
- return this.startingBalance;
93
- }
94
- return balance;
102
+ hasSufficientBalance() {
103
+ return this.getBalance() >= 0;
104
+ }
105
+ /**
106
+ * Charges an AI call: out of the allowance first, the rest out of purchased
107
+ * credit (which the last call may overdraw), and records it in the ledger.
108
+ * @param amount What the call cost, markup included
109
+ * @param markup The markup part, also added to the platform's markup total
110
+ * @param source The agent the call was for, whose usage tags are recorded with it
111
+ * @throws If amount is negative
112
+ */
113
+ decrementBalance(amount, markup = 0, source) {
114
+ if (amount < 0) {
115
+ throw new Error('Amount must be positive');
95
116
  }
96
- catch (error) {
97
- logger_1.logger.error(`Error reading balance for user ${this.userId}:`, error);
98
- // Return starting balance as fallback
99
- return this.startingBalance;
117
+ const state = this.readState();
118
+ const allowanceLeft = Math.max(0, state.allowance.amount - state.allowance.used);
119
+ const fromAllowance = Math.min(amount, allowanceLeft);
120
+ const fromPurchased = amount - fromAllowance;
121
+ state.allowance.used += fromAllowance;
122
+ state.purchased -= fromPurchased;
123
+ this.writeState(state);
124
+ this.saveMarkup(this.getMarkup() + markup);
125
+ const tags = (0, usage_context_1.resolveUsageTags)(source?.usageTags);
126
+ this.appendUsage({
127
+ kind: 'charge',
128
+ at: new Date().toISOString(),
129
+ amount,
130
+ markup,
131
+ fromAllowance,
132
+ fromPurchased,
133
+ ...(source?.id ? { agentId: source.id } : {}),
134
+ ...(source?.agentName ? { agentName: source.agentName } : {}),
135
+ ...(source?.serviceName ? { serviceName: source.serviceName } : {}),
136
+ ...(source?.modelName ? { modelName: source.modelName } : {}),
137
+ ...(tags.user || tags.feature ? { tags } : {}),
138
+ });
139
+ }
140
+ /**
141
+ * Adds purchased credit (after a successful payment). It is kept until used,
142
+ * whatever happens to the allowance.
143
+ * @throws If amount is negative or zero
144
+ */
145
+ addBalance(amount) {
146
+ if (amount <= 0) {
147
+ throw new Error('Amount must be positive');
100
148
  }
149
+ const state = this.readState();
150
+ state.purchased += amount;
151
+ this.writeState(state);
152
+ this.appendUsage({ kind: 'purchase', at: new Date().toISOString(), amount });
153
+ }
154
+ // ---- The allowance -------------------------------------------------------
155
+ /**
156
+ * Starts a new allowance period: the allowance becomes `amount`, unspent, and
157
+ * whatever was left of the last one is gone. Purchased credit is untouched,
158
+ * except that an overdraft (purchased below zero) is paid out of the new
159
+ * allowance first.
160
+ *
161
+ * Applied once per reference: granting a reference already granted changes
162
+ * nothing, so a payment confirmed twice grants once.
163
+ *
164
+ * @param amount The new allowance in dollars (0 ends the allowance)
165
+ * @param options.reference The host's id for this grant, e.g. an invoice id
166
+ * @param options.periodStart When the period began; now when omitted
167
+ * @returns Whether it was applied, and the credit after it
168
+ */
169
+ grantAllowance(amount, options) {
170
+ if (!Number.isFinite(amount) || amount < 0) {
171
+ throw new Error('Allowance must be zero or more');
172
+ }
173
+ const reference = String(options?.reference ?? '').trim();
174
+ if (!reference) {
175
+ throw new Error('A grant needs a reference');
176
+ }
177
+ const state = this.readState();
178
+ if (state.granted.includes(reference)) {
179
+ return { granted: false, credits: this.summarize(state) };
180
+ }
181
+ const periodStart = options.periodStart
182
+ ? new Date(options.periodStart).toISOString()
183
+ : new Date().toISOString();
184
+ const overdraft = state.purchased < 0 ? -state.purchased : 0;
185
+ const repaid = Math.min(amount, overdraft);
186
+ state.allowance = { amount, used: repaid, periodStart, reference };
187
+ state.purchased += repaid;
188
+ state.granted = [...state.granted, reference].slice(-GRANTED_KEPT);
189
+ this.writeState(state);
190
+ this.appendUsage({ kind: 'grant', at: new Date().toISOString(), amount, reference });
191
+ return { granted: true, credits: this.summarize(state) };
192
+ }
193
+ /** The allowance, purchased credit and total, as of now. */
194
+ getCredits() {
195
+ return this.summarize(this.readState());
196
+ }
197
+ // ---- The ledger ----------------------------------------------------------
198
+ /**
199
+ * What was spent between two moments (inclusive), with totals by user, by
200
+ * feature and by day. Defaults: from the start of the current allowance
201
+ * period (or of this month, without one) to now.
202
+ *
203
+ * @param options.entries Also return the charges themselves
204
+ */
205
+ getUsage(options = {}) {
206
+ const state = this.readState();
207
+ const now = new Date();
208
+ const from = options.from
209
+ ? new Date(options.from)
210
+ : state.allowance.periodStart
211
+ ? new Date(state.allowance.periodStart)
212
+ : new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
213
+ const to = options.to ? new Date(options.to) : now;
214
+ const charges = this.readLedger(from, to).filter((e) => e.kind === 'charge');
215
+ const group = (keyOf) => {
216
+ const totals = new Map();
217
+ for (const e of charges) {
218
+ const key = keyOf(e);
219
+ const t = totals.get(key) ?? { key, amount: 0, calls: 0 };
220
+ t.amount += e.amount;
221
+ t.calls += 1;
222
+ totals.set(key, t);
223
+ }
224
+ return [...totals.values()].sort((a, b) => b.amount - a.amount);
225
+ };
226
+ return {
227
+ from: from.toISOString(),
228
+ to: to.toISOString(),
229
+ total: charges.reduce((s, e) => s + e.amount, 0),
230
+ calls: charges.length,
231
+ fromAllowance: charges.reduce((s, e) => s + (e.fromAllowance ?? 0), 0),
232
+ fromPurchased: charges.reduce((s, e) => s + (e.fromPurchased ?? e.amount), 0),
233
+ byUser: group((e) => e.tags?.user ?? ''),
234
+ byFeature: group((e) => e.tags?.feature ?? e.agentName ?? ''),
235
+ byDay: group((e) => e.at.slice(0, 10)).sort((a, b) => a.key.localeCompare(b.key)),
236
+ ...(options.entries ? { entries: charges } : {}),
237
+ };
238
+ }
239
+ /** Grants and purchases between two moments, oldest first. */
240
+ getCreditEvents(options = {}) {
241
+ const from = options.from ? new Date(options.from) : new Date(0);
242
+ const to = options.to ? new Date(options.to) : new Date();
243
+ return this.readLedger(from, to).filter((e) => e.kind !== 'charge');
101
244
  }
102
245
  /**
103
246
  * Get current markup (loads from file)
104
247
  * @returns Current markup total
105
- * @throws If markup file is corrupted
106
248
  */
107
249
  getMarkup() {
108
250
  try {
109
- // Check if balance file exists
110
251
  if (!fs.existsSync(this.markupFilePath)) {
111
- // Create with starting markup
112
252
  this.saveMarkup(0);
113
253
  return 0;
114
254
  }
115
- // Read balance file
116
- const markupStr = fs.readFileSync(this.markupFilePath, 'utf-8').trim();
117
- // Parse number
118
- const markup = parseFloat(markupStr);
255
+ const markup = parseFloat(fs.readFileSync(this.markupFilePath, 'utf-8').trim());
119
256
  if (isNaN(markup)) {
120
- logger_1.logger.error(`Markup file corrupted, resetting to 0`);
257
+ logger_1.logger.error('Markup file corrupted, resetting to 0');
121
258
  this.saveMarkup(0);
122
259
  return 0;
123
260
  }
124
261
  return markup;
125
262
  }
126
263
  catch (error) {
127
- logger_1.logger.error(`Error reading markup:`, error);
128
- // Return starting balance as fallback
264
+ logger_1.logger.error('Error reading markup:', error);
129
265
  return 0;
130
266
  }
131
267
  }
132
- /**
133
- * Check if user has sufficient balance to make AI calls
134
- * @returns true if balance >= 0, false otherwise
135
- */
136
- hasSufficientBalance() {
137
- const balance = this.getBalance();
138
- return balance >= 0;
268
+ // ---- Storage -------------------------------------------------------------
269
+ summarize(state) {
270
+ const remaining = Math.max(0, state.allowance.amount - state.allowance.used);
271
+ return {
272
+ allowance: { ...state.allowance, remaining },
273
+ purchased: state.purchased,
274
+ total: remaining + state.purchased,
275
+ };
139
276
  }
140
277
  /**
141
- * Decrement balance by specified amount
142
- * @param amount Amount to subtract from balance
143
- * @param markup Amount to add to markup total
144
- * @throws If amount is negative
278
+ * The credit state, created on first use: from the old single balance file
279
+ * when there is one (it was all purchased credit, as far as anyone knew),
280
+ * otherwise STARTING_BALANCE.
145
281
  */
146
- decrementBalance(amount, markup = 0) {
147
- if (amount < 0) {
148
- throw new Error('Amount must be positive');
282
+ readState() {
283
+ try {
284
+ if (fs.existsSync(this.creditsFilePath)) {
285
+ const parsed = JSON.parse(fs.readFileSync(this.creditsFilePath, 'utf-8'));
286
+ if (parsed && typeof parsed.purchased === 'number' && parsed.allowance) {
287
+ return {
288
+ version: 1,
289
+ allowance: {
290
+ amount: Number(parsed.allowance.amount) || 0,
291
+ used: Number(parsed.allowance.used) || 0,
292
+ periodStart: parsed.allowance.periodStart ?? null,
293
+ reference: parsed.allowance.reference ?? null,
294
+ },
295
+ purchased: parsed.purchased,
296
+ granted: Array.isArray(parsed.granted) ? parsed.granted : [],
297
+ };
298
+ }
299
+ logger_1.logger.error(`Credit file corrupted for user ${this.userId}; starting again from the legacy balance`);
300
+ }
301
+ }
302
+ catch (error) {
303
+ logger_1.logger.error(`Error reading credits for user ${this.userId}:`, error);
149
304
  }
150
- const currentBalance = this.getBalance();
151
- const newBalance = currentBalance - amount;
152
- this.saveBalance(newBalance);
153
- const currentMarkup = this.getMarkup();
154
- const newMarkup = currentMarkup + markup;
155
- this.saveMarkup(newMarkup);
305
+ const state = {
306
+ version: 1,
307
+ allowance: { amount: 0, used: 0, periodStart: null, reference: null },
308
+ purchased: this.readLegacyBalance() ?? this.startingBalance,
309
+ granted: [],
310
+ };
311
+ this.writeState(state);
312
+ if (fs.existsSync(this.legacyBalanceFilePath)) {
313
+ try {
314
+ fs.renameSync(this.legacyBalanceFilePath, `${this.legacyBalanceFilePath}.migrated`);
315
+ }
316
+ catch (error) {
317
+ logger_1.logger.error(`Could not retire the legacy balance file for user ${this.userId}:`, error);
318
+ }
319
+ }
320
+ return state;
156
321
  }
157
- /**
158
- * Add funds to balance
159
- * @param amount Amount to add to balance
160
- * @throws If amount is negative or zero
161
- */
162
- addBalance(amount) {
163
- if (amount <= 0) {
164
- throw new Error('Amount must be positive');
322
+ readLegacyBalance() {
323
+ try {
324
+ if (!fs.existsSync(this.legacyBalanceFilePath))
325
+ return null;
326
+ const balance = parseFloat(fs.readFileSync(this.legacyBalanceFilePath, 'utf-8').trim());
327
+ return isNaN(balance) ? null : balance;
328
+ }
329
+ catch {
330
+ return null;
165
331
  }
166
- const currentBalance = this.getBalance();
167
- const newBalance = currentBalance + amount;
168
- this.saveBalance(newBalance);
169
332
  }
170
- /**
171
- * Save balance to file
172
- * @param balance New balance value
173
- */
174
- saveBalance(balance) {
333
+ /** Writes the state through a temporary file, so a crash never leaves half a file. */
334
+ writeState(state) {
175
335
  try {
176
- // Ensure userconfig directory exists
177
- const userconfigPath = this.userPaths.getUserConfigDir();
178
- if (!fs.existsSync(userconfigPath)) {
179
- fs.mkdirSync(userconfigPath, { recursive: true });
180
- }
181
- // Write balance to file as plain text
182
- fs.writeFileSync(this.balanceFilePath, balance.toString(), 'utf-8');
183
- // Emit SSE update if service is available
184
- if (this.balanceMessageService) {
185
- this.balanceMessageService.emitUpdate(this.userId, balance);
186
- }
336
+ const dir = path.dirname(this.creditsFilePath);
337
+ if (!fs.existsSync(dir))
338
+ fs.mkdirSync(dir, { recursive: true });
339
+ const tmp = `${this.creditsFilePath}.tmp`;
340
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2), 'utf-8');
341
+ fs.renameSync(tmp, this.creditsFilePath);
187
342
  }
188
343
  catch (error) {
189
- logger_1.logger.error(`Error saving balance for user ${this.userId}:`, error);
344
+ logger_1.logger.error(`Error saving credits for user ${this.userId}:`, error);
190
345
  throw error;
191
346
  }
347
+ if (this.balanceMessageService) {
348
+ this.balanceMessageService.emitUpdate(this.userId, this.summarize(state).total);
349
+ }
350
+ }
351
+ appendUsage(entry) {
352
+ try {
353
+ if (!fs.existsSync(this.usageDir))
354
+ fs.mkdirSync(this.usageDir, { recursive: true });
355
+ const file = path.join(this.usageDir, `${entry.at.slice(0, 7)}.jsonl`);
356
+ fs.appendFileSync(file, `${JSON.stringify(entry)}\n`, 'utf-8');
357
+ }
358
+ catch (error) {
359
+ // The charge itself is already in the credit state; a lost ledger line
360
+ // must not fail the AI call that caused it.
361
+ logger_1.logger.error(`Error recording usage for user ${this.userId}:`, error);
362
+ }
363
+ }
364
+ /** Ledger lines from `from` to `to` inclusive, oldest first. */
365
+ readLedger(from, to) {
366
+ if (!fs.existsSync(this.usageDir))
367
+ return [];
368
+ const fromIso = from.toISOString();
369
+ const toIso = to.toISOString();
370
+ const firstMonth = fromIso.slice(0, 7);
371
+ const lastMonth = toIso.slice(0, 7);
372
+ const entries = [];
373
+ for (const file of fs.readdirSync(this.usageDir).filter((f) => /^\d{4}-\d{2}\.jsonl$/.test(f)).sort()) {
374
+ const month = file.slice(0, 7);
375
+ if (month < firstMonth || month > lastMonth)
376
+ continue;
377
+ for (const line of fs.readFileSync(path.join(this.usageDir, file), 'utf-8').split('\n')) {
378
+ if (!line.trim())
379
+ continue;
380
+ try {
381
+ const entry = JSON.parse(line);
382
+ if (entry.at >= fromIso && entry.at <= toIso)
383
+ entries.push(entry);
384
+ }
385
+ catch {
386
+ // A torn last line from a crash; skip it.
387
+ }
388
+ }
389
+ }
390
+ return entries.sort((a, b) => a.at.localeCompare(b.at));
192
391
  }
193
- /**
194
- * Save markup to file
195
- * @param markup
196
- */
197
392
  saveMarkup(markup) {
198
393
  try {
199
- // Ensure userconfig directory exists
200
394
  const commonConfigPath = this.userPaths.getCommonConfigDir();
201
395
  if (!fs.existsSync(commonConfigPath)) {
202
396
  fs.mkdirSync(commonConfigPath, { recursive: true });
203
397
  }
204
- // Write balance to file as plain text
205
398
  fs.writeFileSync(this.markupFilePath, markup.toString(), 'utf-8');
206
399
  }
207
400
  catch (error) {
208
- logger_1.logger.error(`Error saving markup:`, error);
401
+ logger_1.logger.error('Error saving markup:', error);
209
402
  throw error;
210
403
  }
211
404
  }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Who and what an AI charge is for, recorded with it in the user's usage ledger
3
+ * (see BalanceService). Both are the host's own labels: Briyah stores and
4
+ * groups by them but never interprets them.
5
+ */
6
+ export interface UsageTags {
7
+ /** The person the work was done for, e.g. an email address or a name. */
8
+ user?: string;
9
+ /** What the work was, e.g. "Loss run import" or "AI Assistant". */
10
+ feature?: string;
11
+ }
12
+ /**
13
+ * Runs `fn` with these usage tags in force: every AI charge made while it runs,
14
+ * including in work it starts and does not await, is recorded with them. Calls
15
+ * nest, the inner tags overriding the outer ones key by key, so a host can tag a
16
+ * whole request with its user and a single feature inside it with what it is.
17
+ *
18
+ * Tags set on an agent (`agent.usageTags`) win over these.
19
+ */
20
+ export declare function runWithUsageTags<T>(tags: UsageTags, fn: () => T): T;
21
+ /** The usage tags in force here, or an empty object. */
22
+ export declare function currentUsageTags(): UsageTags;
23
+ /** The tags a charge is recorded with: the context's, then the agent's own on top. */
24
+ export declare function resolveUsageTags(agentTags?: UsageTags | null): UsageTags;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runWithUsageTags = runWithUsageTags;
4
+ exports.currentUsageTags = currentUsageTags;
5
+ exports.resolveUsageTags = resolveUsageTags;
6
+ const async_hooks_1 = require("async_hooks");
7
+ const storage = new async_hooks_1.AsyncLocalStorage();
8
+ /**
9
+ * Runs `fn` with these usage tags in force: every AI charge made while it runs,
10
+ * including in work it starts and does not await, is recorded with them. Calls
11
+ * nest, the inner tags overriding the outer ones key by key, so a host can tag a
12
+ * whole request with its user and a single feature inside it with what it is.
13
+ *
14
+ * Tags set on an agent (`agent.usageTags`) win over these.
15
+ */
16
+ function runWithUsageTags(tags, fn) {
17
+ const outer = storage.getStore();
18
+ return storage.run({ ...outer, ...clean(tags) }, fn);
19
+ }
20
+ /** The usage tags in force here, or an empty object. */
21
+ function currentUsageTags() {
22
+ return { ...storage.getStore() };
23
+ }
24
+ /** The tags a charge is recorded with: the context's, then the agent's own on top. */
25
+ function resolveUsageTags(agentTags) {
26
+ return { ...currentUsageTags(), ...clean(agentTags ?? {}) };
27
+ }
28
+ function clean(tags) {
29
+ const out = {};
30
+ if (typeof tags.user === 'string' && tags.user.trim())
31
+ out.user = tags.user.trim();
32
+ if (typeof tags.feature === 'string' && tags.feature.trim())
33
+ out.feature = tags.feature.trim();
34
+ return out;
35
+ }
@@ -89,6 +89,7 @@ export declare class AppController {
89
89
  private static parseInstantiateModels;
90
90
  private static parseTurnMode;
91
91
  private static parseIllustrationMode;
92
+ private static parseImageAspect;
92
93
  createRoom(req: ExpressRequest, body: {
93
94
  roomName: string;
94
95
  roomGoal: string;
@@ -102,6 +103,8 @@ export declare class AppController {
102
103
  imageModel?: string;
103
104
  /** When the room illustrates itself. Absent means 'on-request'. */
104
105
  illustrationMode?: string;
106
+ /** The default shape of the room's pictures. Absent means 'square'. */
107
+ imageAspect?: string;
105
108
  }): Promise<CreateRoomResponse>;
106
109
  editRoom(req: ExpressRequest, roomId: string, body: {
107
110
  roomName: string;
@@ -119,6 +122,8 @@ export declare class AppController {
119
122
  imageModel?: string;
120
123
  /** When the room illustrates itself. */
121
124
  illustrationMode?: string;
125
+ /** The default shape of the room's pictures. */
126
+ imageAspect?: string;
122
127
  }): Promise<void>;
123
128
  /**
124
129
  * Creates an agent that belongs to this room and adds it to it.
@@ -59,6 +59,7 @@ const user_service_manager_1 = require("./app/user-service-manager");
59
59
  const published_agents_service_1 = require("./ai/published-agents.service");
60
60
  const published_rooms_service_1 = require("./room/published-rooms.service");
61
61
  const errors_1 = require("./common/errors");
62
+ const app_types_1 = require("../../shared/types/app.types");
62
63
  const path = __importStar(require("path"));
63
64
  const logger_1 = require("./common/logger");
64
65
  /**
@@ -874,6 +875,14 @@ let AppController = AppController_1 = class AppController {
874
875
  }
875
876
  return value;
876
877
  }
878
+ static parseImageAspect(value) {
879
+ if (value === undefined)
880
+ return undefined;
881
+ if (!app_types_1.IMAGE_ASPECTS.includes(value)) {
882
+ throw new common_1.BadRequestException(`imageAspect must be one of ${app_types_1.IMAGE_ASPECTS.map((a) => `'${a}'`).join(', ')}`);
883
+ }
884
+ return value;
885
+ }
877
886
  async createRoom(req, body) {
878
887
  // Validate required fields. A room may start empty: the agents that belong
879
888
  // to it are created through POST rooms/:roomId/agents once it exists.
@@ -890,9 +899,10 @@ let AppController = AppController_1 = class AppController {
890
899
  }
891
900
  const turnMode = AppController_1.parseTurnMode(body.turnMode);
892
901
  const illustrationMode = AppController_1.parseIllustrationMode(body.illustrationMode);
902
+ const imageAspect = AppController_1.parseImageAspect(body.imageAspect);
893
903
  try {
894
904
  const appService = this.getAppService(req);
895
- return await appService.createRoom(body.roomName, body.roomGoal, body.agentIds ?? [], body.roomLeader, turnMode, body.moderator, body.beginInstruction, body.imageModel, illustrationMode);
905
+ return await appService.createRoom(body.roomName, body.roomGoal, body.agentIds ?? [], body.roomLeader, turnMode, body.moderator, body.beginInstruction, body.imageModel, illustrationMode, imageAspect);
896
906
  }
897
907
  catch (error) {
898
908
  logger_1.logger.error(`[${req.user?.sub}] Error creating room ${body.roomName}:`, error);
@@ -908,9 +918,10 @@ let AppController = AppController_1 = class AppController {
908
918
  // and inside the try the catch below would turn it into a 500.
909
919
  const turnMode = AppController_1.parseTurnMode(body.turnMode);
910
920
  const illustrationMode = AppController_1.parseIllustrationMode(body.illustrationMode);
921
+ const imageAspect = AppController_1.parseImageAspect(body.imageAspect);
911
922
  try {
912
923
  const appService = this.getAppService(req);
913
- await appService.editRoom(roomId, body.roomName, body.roomGoal, body.baseRoomDir, body.agentIds, body.roomLeader, turnMode, body.moderator, body.pack, body.beginInstruction, body.imageModel, illustrationMode);
924
+ await appService.editRoom(roomId, body.roomName, body.roomGoal, body.baseRoomDir, body.agentIds, body.roomLeader, turnMode, body.moderator, body.pack, body.beginInstruction, body.imageModel, illustrationMode, imageAspect);
914
925
  }
915
926
  catch (error) {
916
927
  logger_1.logger.error(`[${req.user?.sub}] Error editing room ${roomId}:`, error);