@aria-framework/ai 0.1.0 → 0.3.0

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.
package/index.js CHANGED
@@ -170,6 +170,13 @@ function createAiClient(deps = {}) {
170
170
  }
171
171
 
172
172
  module.exports = {
173
+ // The usage counter behind every ceiling. LAZY: it needs the db-worker driver contract, which
174
+ // is an OPTIONAL peer — a consumer using only createAiClient/polish/facts must not be made to
175
+ // install a database package to require this one.
176
+ get createUsageStore() { return require('./usageStore').createUsageStore; },
177
+ get createProviderStore() { return require('./providerStore').createProviderStore; },
178
+ get providerSchemaFor() { return require('./providerStore').schemaFor; },
179
+ get usageSchemaFor() { return require('./usageStore').schemaFor; },
173
180
  createAiClient,
174
181
  PROVIDERS, DEFAULTS,
175
182
  AiError, fromFetchFailure, redact,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aria-framework/ai",
3
3
  "description": "Aria App Framework — AI module. A dependency-injected model seam (createAiClient) over several providers (LM Studio / OpenAI-compatible / Anthropic), with a fact-preservation guard, generic Polish and Generate writing engines, and a browser polish widget. Prompts and config stay in the consuming app.",
4
- "version": "0.1.0",
4
+ "version": "0.3.0",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
7
7
  "publishConfig": {
@@ -16,9 +16,15 @@
16
16
  "generate.js",
17
17
  "providers/openai-compatible.js",
18
18
  "providers/anthropic.js",
19
- "browser/ai-polish.js"
19
+ "browser/ai-polish.js", "usageStore.js", "providerStore.js"
20
20
  ],
21
+ "peerDependencies": {
22
+ "@aria-framework/db-worker": ">=0.7.0"
23
+ },
24
+ "peerDependenciesMeta": {
25
+ "@aria-framework/db-worker": { "optional": true }
26
+ },
21
27
  "scripts": {
22
- "test": "node test/smoke.js"
28
+ "test": "node test/smoke.js && node test/usageStore.js && node test/providerStore.js"
23
29
  }
24
30
  }
@@ -0,0 +1,200 @@
1
+ /**
2
+ * The provider registry — every endpoint the app can talk to, configured once.
3
+ *
4
+ * WHY THIS EXISTS. Support101's AI settings page is one flat form with eleven fields describing a
5
+ * single provider, and nine of those eleven are really per-endpoint. That shape collapses the
6
+ * moment a second endpoint exists, which is what a backup provider is. The fix is not a
7
+ * `backup_base_url` beside every field — that is the same form doubled, and it caps at two.
8
+ *
9
+ * A PROVIDER IS AN ENDPOINT, not a job. It has a connection, a model or two, capability limits and
10
+ * its own spend guard, and it can be health-checked. Routes reference providers by id, so one
11
+ * endpoint can be one route's primary and another's fallback without being configured twice.
12
+ *
13
+ * ── THE ID IS THE OPERATOR'S ────────────────────────────────────────────────────────────────────
14
+ * `local-fast`, `gpu-box-1`, whatever they like. NO CALL SITE EVER NAMES A PROVIDER — code names a
15
+ * route, the operator decides what serves it. That is the whole reason failover is possible, and
16
+ * it means renaming a provider must break nothing.
17
+ *
18
+ * ── ONE ENDPOINT CAN SERVE CHAT AND EMBEDDINGS ──────────────────────────────────────────────────
19
+ * `model` and `embedding_model` are separate columns on the SAME row because that is how the
20
+ * servers actually work: one LM Studio instance answers both. Splitting them into two provider
21
+ * rows would duplicate the connection, and then its health twice. A chat route reads `model`, an
22
+ * embedding route reads `embedding_model`.
23
+ *
24
+ * ── THE API KEY IS NOT IN THIS TABLE ────────────────────────────────────────────────────────────
25
+ * It lives in whatever secret store the app already has — Support101 keeps it in an encrypted
26
+ * credentials database beside its Entra secret. So `secrets` is INJECTED, the package never sees a
27
+ * credential at rest, and `resolve()` is the only thing that pulls one. Keys are write-only from
28
+ * the UI's point of view: there is no read-back, because a lost LLM key is rotated at the
29
+ * provider, not recovered.
30
+ */
31
+
32
+ 'use strict';
33
+
34
+ /** Columns the caller may set. `id` is separate — it is the key and is never updated in place. */
35
+ const FIELDS = [
36
+ 'label', 'kind', 'base_url', 'model', 'embedding_model',
37
+ 'context_tokens', 'max_tokens', 'timeout_ms', 'daily_token_cap', 'enabled', 'sort_order'
38
+ ];
39
+
40
+ const NUMERIC = new Set(['context_tokens', 'max_tokens', 'timeout_ms', 'daily_token_cap', 'enabled', 'sort_order']);
41
+
42
+ /** An id an operator typed, constrained so it can appear in a URL and a log line unescaped. */
43
+ function assertId(id) {
44
+ if (typeof id !== 'string' || !/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(id)) {
45
+ throw new Error(
46
+ `provider id ${JSON.stringify(id)} is not usable: 3-40 characters, lowercase letters, ` +
47
+ 'digits and hyphens, not starting or ending with a hyphen.'
48
+ );
49
+ }
50
+ return id;
51
+ }
52
+
53
+ /**
54
+ * @param {object} opts
55
+ * driver @aria-framework/db-worker driver contract (required)
56
+ * table default 'ai_providers'
57
+ * secrets { get(id) => Promise<string> } — the app's credential store. Optional; without it
58
+ * resolve() returns an empty apiKey, which is correct for local endpoints.
59
+ * defaults { [kind]: { baseUrl, model, label } } — the package's PROVIDER DEFAULTS, so a row
60
+ * may leave base_url or model blank and still resolve to something usable.
61
+ */
62
+ function createProviderStore(opts = {}) {
63
+ const driver = opts.driver;
64
+ if (!driver || typeof driver.run !== 'function') {
65
+ throw new Error('createProviderStore({ driver }): the db-worker driver contract is required');
66
+ }
67
+ const table = opts.table || 'ai_providers';
68
+ const secrets = opts.secrets || null;
69
+ const defaults = opts.defaults || {};
70
+
71
+ const clean = (p) => {
72
+ const out = {};
73
+ for (const f of FIELDS) {
74
+ if (p[f] === undefined) continue;
75
+ out[f] = NUMERIC.has(f) ? (Number(p[f]) || 0) : (p[f] == null ? null : String(p[f]));
76
+ }
77
+ return out;
78
+ };
79
+
80
+ return {
81
+ table,
82
+
83
+ /** Every provider, in the operator's chosen order. */
84
+ async all() {
85
+ return driver.all(`SELECT * FROM ${table} ORDER BY sort_order, id`);
86
+ },
87
+
88
+ /** Only the ones that may be used. A disabled provider stays configured but is never called. */
89
+ async enabled() {
90
+ return driver.all(`SELECT * FROM ${table} WHERE enabled = 1 ORDER BY sort_order, id`);
91
+ },
92
+
93
+ async byId(id) {
94
+ return driver.get(`SELECT * FROM ${table} WHERE id = ?`, [String(id)]);
95
+ },
96
+
97
+ async create(p = {}) {
98
+ const id = assertId(p.id);
99
+ if (await this.byId(id)) throw new Error(`a provider called ${JSON.stringify(id)} already exists`);
100
+ if (!p.kind) throw new Error('a provider needs a kind (the adapter that talks to it)');
101
+ const fields = clean(p);
102
+ const cols = ['id'].concat(Object.keys(fields));
103
+ const vals = [id].concat(Object.values(fields));
104
+ await driver.run(
105
+ `INSERT INTO ${table} (${cols.join(', ')}) VALUES (${cols.map(() => '?').join(', ')})`, vals);
106
+ return { id };
107
+ },
108
+
109
+ /**
110
+ * Update in place. The ID IS NOT UPDATABLE here on purpose: routes reference providers by id,
111
+ * so renaming one would silently orphan every chain that points at it. A rename is a create
112
+ * plus a repoint plus a delete, which is a deliberate act rather than a typo in a text field.
113
+ */
114
+ async update(id, p = {}) {
115
+ const existing = await this.byId(id);
116
+ if (!existing) throw new Error(`no provider called ${JSON.stringify(id)}`);
117
+ const fields = clean(p);
118
+ const keys = Object.keys(fields);
119
+ if (!keys.length) return { changes: 0 };
120
+ const r = await driver.run(
121
+ `UPDATE ${table} SET ${keys.map((k) => `${k} = ?`).join(', ')} WHERE id = ?`,
122
+ Object.values(fields).concat([String(id)]));
123
+ return { changes: r.changes };
124
+ },
125
+
126
+ async remove(id) {
127
+ const r = await driver.run(`DELETE FROM ${table} WHERE id = ?`, [String(id)]);
128
+ return { changes: r.changes };
129
+ },
130
+
131
+ /**
132
+ * Everything needed to make a call, in the shape createAiClient's `resolveConfig` returns.
133
+ *
134
+ * This is the seam that makes adoption a swap rather than a rewrite: an app whose getConfig()
135
+ * read eleven settings keys can point at this instead and change nothing else.
136
+ *
137
+ * @param {string} id
138
+ * @param {{embedding?: boolean}} o resolve the EMBEDDING model rather than the chat one
139
+ */
140
+ async resolve(id, o = {}) {
141
+ const row = await this.byId(id);
142
+ if (!row) return { provider: 'off', enabled: false, missing: String(id) };
143
+ if (!row.enabled) return { provider: 'off', enabled: false, disabled: String(id) };
144
+
145
+ const d = defaults[row.kind] || {};
146
+ let apiKey = '';
147
+ if (secrets && typeof secrets.get === 'function') {
148
+ // A credential store that is locked or unavailable must not take the whole call down with
149
+ // an exception — a local endpoint needs no key at all, and the adapter's own auth failure
150
+ // is a better error than "the keychain was busy".
151
+ try { apiKey = (await secrets.get(row.id)) || ''; } catch (_) { apiKey = ''; }
152
+ }
153
+
154
+ return {
155
+ enabled: true,
156
+ id: row.id,
157
+ provider: row.kind,
158
+ label: row.label || d.label || row.id,
159
+ baseUrl: row.base_url || d.baseUrl || '',
160
+ model: (o.embedding ? row.embedding_model : row.model) || (o.embedding ? '' : d.model) || '',
161
+ embeddingModel: row.embedding_model || '',
162
+ apiKey,
163
+ timeoutMs: Number(row.timeout_ms) || 60000,
164
+ maxTokens: Number(row.max_tokens) || 1024,
165
+ contextTokens: Number(row.context_tokens) || 8192,
166
+ dailyTokenCap: Number(row.daily_token_cap) || 0
167
+ };
168
+ }
169
+ };
170
+ }
171
+
172
+ /**
173
+ * The DDL, in the caller's dialect.
174
+ *
175
+ * `id` is TEXT and the primary key rather than an autoincrement integer, because it is the name an
176
+ * operator types and the thing routes reference. A surrogate key would mean routes pointed at
177
+ * numbers nobody recognises in a config screen.
178
+ */
179
+ function schemaFor(dialect) {
180
+ const t = dialect || { now: () => "datetime('now')" };
181
+ return `
182
+ id TEXT PRIMARY KEY,
183
+ label TEXT,
184
+ kind TEXT NOT NULL,
185
+ base_url TEXT,
186
+ model TEXT,
187
+ embedding_model TEXT,
188
+ context_tokens INTEGER NOT NULL DEFAULT 0,
189
+ max_tokens INTEGER NOT NULL DEFAULT 0,
190
+ timeout_ms INTEGER NOT NULL DEFAULT 0,
191
+ -- Per PROVIDER, not global: a ceiling is meaningless on a GPU you already own, and the whole
192
+ -- point of a cheap cloud fallback is capping what it may spend while the primary is down.
193
+ daily_token_cap INTEGER NOT NULL DEFAULT 0,
194
+ enabled INTEGER NOT NULL DEFAULT 1,
195
+ sort_order INTEGER NOT NULL DEFAULT 0,
196
+ created_at TEXT NOT NULL DEFAULT (${t.now()})
197
+ `;
198
+ }
199
+
200
+ module.exports = { createProviderStore, schemaFor, _assertId: assertId };
package/usageStore.js ADDED
@@ -0,0 +1,273 @@
1
+ /**
2
+ * What the model has cost — the counter behind every ceiling.
3
+ *
4
+ * EXTRACTED FROM SUPPORT101 (models/AiUsage.js + lib/ai/budget.js), which has run this in
5
+ * production since its migration 014. The design decisions below are its, kept because they were
6
+ * right and the reasoning was written down; what changed is that the app-specific parts became
7
+ * parameters.
8
+ *
9
+ * ── APPEND-ONLY, ONE ROW PER CALL ───────────────────────────────────────────────────────────────
10
+ * Not a per-day counter that gets incremented. Two reasons, both from the original:
11
+ * 1. A counter update is a read-modify-write, and two concurrent calls lose one of them. A
12
+ * ceiling backed by a lossy counter is a report, not a limit.
13
+ * 2. A row per call is what makes "which ticket ate the budget" answerable at all.
14
+ *
15
+ * The cost is volume, and it is NOT negligible at every scale. Support101's own comment says "the
16
+ * table is small — a busy day is hundreds of rows", which is true for a helpdesk (~110k rows/year)
17
+ * and false for log triage (~14.6M rows/year at 40k calls/day). So `rollup()` exists: detail rows
18
+ * are short-lived, and a daily aggregate is what survives. Append-only is preserved; only the
19
+ * retention of the detail changes.
20
+ *
21
+ * ── CHECKED BEFORE, RECORDED AFTER ──────────────────────────────────────────────────────────────
22
+ * There is no way to know what a call will cost until it returns, so a ceiling is "you are already
23
+ * over", never "this would take you over". The last call may overshoot by its own size. The
24
+ * alternative — estimate and refuse in advance — is a guess about a number that cannot be
25
+ * computed, and being wrong in the confident direction blocks work that would have fit. A bounded
26
+ * overshoot is explainable; a wrong estimate is not.
27
+ *
28
+ * ── A CEILING OF 0 IS OFF ───────────────────────────────────────────────────────────────────────
29
+ * Not "no tokens allowed". An install that has never opened the budget screen is unlimited rather
30
+ * than silently broken — the opposite default presents as "the AI stopped working" on a fresh
31
+ * install with no clue why.
32
+ *
33
+ * ── THE DAY IS THE APP'S DAY ────────────────────────────────────────────────────────────────────
34
+ * A ceiling is an allowance a person set, so it resets when their day does. Computing it in UTC
35
+ * rolls the budget over mid-afternoon in +02:00, which gets diagnosed as "the AI randomly stopped
36
+ * working". The clock is therefore injected, and defaults to the host's local date.
37
+ *
38
+ * ── WHAT STAYS IN THE APP ───────────────────────────────────────────────────────────────────────
39
+ * The SCOPE column and its foreign key. Support101 scopes by `ticket_id REFERENCES tickets(id)
40
+ * ON DELETE SET NULL` — deleting a ticket KEEPS the usage row and forgets which ticket it belonged
41
+ * to, so the spend history survives the thing it was spent on. (An earlier draft of this comment
42
+ * said CASCADE, which would have been the opposite and wrong: erasing a ticket would erase the
43
+ * record that its budget was ever consumed.) That is real behaviour a generic column could not
44
+ * carry, and app 3 will scope by incident instead. So the package is told the column NAME and the
45
+ * app owns the column, its type and its constraints.
46
+ */
47
+
48
+ 'use strict';
49
+
50
+ /** YYYY-MM-DD in whatever zone the supplied clock is in. */
51
+ function dayOf(date) {
52
+ const pad = (n) => String(n).padStart(2, '0');
53
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
54
+ }
55
+
56
+ /**
57
+ * @param {object} opts
58
+ * driver @aria-framework/db-worker driver contract (required)
59
+ * table detail table, default 'ai_usage'
60
+ * rollupTable daily aggregate, default 'ai_usage_daily'
61
+ * scopeColumn the app's scope column, e.g. 'ticket_id'. Omitted = no scope dimension.
62
+ * routeColumn the route column, e.g. 'route'. Omitted = no route dimension.
63
+ * now () => Date, the APP'S clock. Default: host local time.
64
+ */
65
+ function createUsageStore(opts = {}) {
66
+ const driver = opts.driver;
67
+ if (!driver || typeof driver.run !== 'function') {
68
+ throw new Error('createUsageStore({ driver }): the db-worker driver contract is required');
69
+ }
70
+ const table = opts.table || 'ai_usage';
71
+ const rollupTable = opts.rollupTable || 'ai_usage_daily';
72
+ const scopeCol = opts.scopeColumn || null;
73
+ const routeCol = opts.routeColumn || null;
74
+ const now = typeof opts.now === 'function' ? opts.now : () => new Date();
75
+
76
+ /** Column list and placeholders, built once from what the app actually has. */
77
+ const cols = ['day', 'provider', 'model', 'calls', 'prompt_tokens', 'completion_tokens', 'total_tokens'];
78
+ if (scopeCol) cols.splice(3, 0, scopeCol);
79
+ if (routeCol) cols.splice(3, 0, routeCol);
80
+
81
+ return {
82
+ table,
83
+ rollupTable,
84
+
85
+ /** The current day string, exposed because callers compare against it. */
86
+ today: () => dayOf(now()),
87
+
88
+ /**
89
+ * Record one provider call. NEVER THROWS — see the wrapper in `budget` below; a lost counter
90
+ * row is a bookkeeping problem, not a reason to fail work that succeeded.
91
+ */
92
+ async record(entry = {}) {
93
+ const prompt = Number(entry.promptTokens) || 0;
94
+ const completion = Number(entry.completionTokens) || 0;
95
+ const total = Number(entry.totalTokens) || (prompt + completion);
96
+
97
+ const values = [dayOf(now()), String(entry.provider || ''), String(entry.model || '')];
98
+ if (routeCol) values.push(entry.route == null ? null : String(entry.route));
99
+ if (scopeCol) values.push(entry.scope == null ? null : entry.scope);
100
+ values.push(1, prompt, completion, total);
101
+
102
+ const placeholders = cols.map(() => '?').join(', ');
103
+ const r = await driver.run(
104
+ `INSERT INTO ${table} (${cols.join(', ')}) VALUES (${placeholders})`, values);
105
+ return { id: r.lastId };
106
+ },
107
+
108
+ /** Tokens spent today, across every path — background jobs and button presses alike. */
109
+ async tokensToday() {
110
+ const r = await driver.get(
111
+ `SELECT COALESCE(SUM(total_tokens), 0) n FROM ${table} WHERE day = ?`, [dayOf(now())]);
112
+ return Number(r.n) || 0;
113
+ },
114
+
115
+ /**
116
+ * Tokens ever spent against one scope.
117
+ *
118
+ * NOT PER DAY, deliberately, and this is load-bearing: the scope cap exists to stop one
119
+ * pathological thread — a hundred-message argument, or a retry loop against something the
120
+ * model keeps failing on — from eating the budget. A cap that reset at midnight would let
121
+ * exactly that happen, one day at a time, which is the failure it was written to prevent.
122
+ */
123
+ async tokensForScope(scope) {
124
+ if (!scopeCol) throw new Error('createUsageStore: no scopeColumn was configured');
125
+ const r = await driver.get(
126
+ `SELECT COALESCE(SUM(total_tokens), 0) n FROM ${table} WHERE ${scopeCol} = ?`, [scope]);
127
+ return Number(r.n) || 0;
128
+ },
129
+
130
+ /** For the admin screen: recent days, newest first. */
131
+ async byDay(days = 14) {
132
+ const limit = Math.min(200, Math.max(1, Number(days) * 4));
133
+ const group = ['day', 'provider', 'model'].concat(routeCol ? [routeCol] : []);
134
+ return driver.all(
135
+ `SELECT ${group.join(', ')},
136
+ SUM(calls) calls, SUM(prompt_tokens) prompt_tokens,
137
+ SUM(completion_tokens) completion_tokens, SUM(total_tokens) total_tokens
138
+ FROM ${table}
139
+ GROUP BY ${group.join(', ')}
140
+ ORDER BY day DESC, total_tokens DESC
141
+ LIMIT ?`, [limit]);
142
+ },
143
+
144
+ /** Totals per provider over a window, for the usage screen's per-provider table. */
145
+ async byProvider(sinceDay) {
146
+ return driver.all(
147
+ `SELECT provider, model,
148
+ SUM(calls) calls, SUM(prompt_tokens) prompt_tokens,
149
+ SUM(completion_tokens) completion_tokens, SUM(total_tokens) total_tokens
150
+ FROM ${table}
151
+ WHERE day >= ?
152
+ GROUP BY provider, model
153
+ ORDER BY total_tokens DESC`, [String(sinceDay)]);
154
+ },
155
+
156
+ /**
157
+ * Fold completed days of detail into the daily aggregate, then drop the folded detail.
158
+ *
159
+ * THIS IS WHAT MAKES APPEND-ONLY SURVIVABLE AT VOLUME. Deliberately NOT a trigger or an upsert
160
+ * on the write path: keeping the hot path a plain INSERT is the entire reason two concurrent
161
+ * calls cannot lose each other's counts.
162
+ *
163
+ * GRANULARITY MATCHES THE DATA. The detail table carries `day`, not an hour, so this rolls up
164
+ * by day — an earlier draft grouped by day and wrote the result into an `hour` column, which
165
+ * was incoherent. A consumer that needs finer buckets (log triage, where a day is far too
166
+ * coarse) adds an hour column to its own detail table and configures it; inventing one here
167
+ * from a date would be inventing precision that was never recorded.
168
+ *
169
+ * ONLY COMPLETED DAYS are folded. Folding today would race with calls still arriving into it,
170
+ * and the aggregate would disagree with the detail for as long as the day lasted.
171
+ *
172
+ * IDEMPOTENT via a watermark read from the aggregate's own MAX(day) — see below. Re-running is
173
+ * a no-op rather than a doubling, which matters because retention can leave folded detail in
174
+ * place for days.
175
+ *
176
+ * @param {{keepDetailDays?: number}} o how many completed days of DETAIL to keep after
177
+ * folding. 0 = keep none; the aggregate is the record from then on.
178
+ * @returns {{folded: number, deleted: number}}
179
+ */
180
+ async rollup(o = {}) {
181
+ const keepDays = Math.max(0, Number(o.keepDetailDays) || 0);
182
+ const group = ['provider', 'model'].concat(routeCol ? [routeCol] : []);
183
+ const todayStr = dayOf(now());
184
+ // Detail older than this is safe to delete: it has been folded AND is past retention.
185
+ const deleteBefore = dayOf(new Date(now().getTime() - keepDays * 86400000));
186
+
187
+ let folded = 0;
188
+ let deleted = 0;
189
+ await driver.transaction(async (tx) => {
190
+ // THE WATERMARK, and it is what makes this idempotent. Without it, any run with
191
+ // keepDetailDays > 0 re-folds detail that survived the last run and DOUBLES the aggregate
192
+ // — the ON CONFLICT accumulates, which is correct for new rows and catastrophic for
193
+ // repeats. Derived from the aggregate itself rather than stored separately: the highest
194
+ // day already folded is exactly `MAX(day)` there, so there is no second piece of state to
195
+ // keep in step.
196
+ const mark = await tx.get(`SELECT MAX(day) m FROM ${rollupTable}`);
197
+ const after = (mark && mark.m) || '';
198
+
199
+ const rows = await tx.all(
200
+ `SELECT day, ${group.join(', ')},
201
+ SUM(calls) calls, SUM(prompt_tokens) p, SUM(completion_tokens) c,
202
+ SUM(total_tokens) t
203
+ FROM ${table}
204
+ WHERE day < ? AND day > ?
205
+ GROUP BY day, ${group.join(', ')}`, [todayStr, after]);
206
+
207
+ const key = ['day', 'provider', 'model'].concat(routeCol ? [routeCol] : []);
208
+ for (const row of rows) {
209
+ const vals = [row.day, row.provider, row.model];
210
+ if (routeCol) vals.push(row[routeCol]);
211
+ await tx.run(
212
+ `INSERT INTO ${rollupTable} (${key.join(', ')}, calls, prompt_tokens, completion_tokens, total_tokens)
213
+ VALUES (${key.map(() => '?').join(', ')}, ?, ?, ?, ?)
214
+ ON CONFLICT(${key.join(', ')}) DO UPDATE SET
215
+ calls = ${rollupTable}.calls + excluded.calls,
216
+ prompt_tokens = ${rollupTable}.prompt_tokens + excluded.prompt_tokens,
217
+ completion_tokens = ${rollupTable}.completion_tokens + excluded.completion_tokens,
218
+ total_tokens = ${rollupTable}.total_tokens + excluded.total_tokens`,
219
+ vals.concat([row.calls, row.p, row.c, row.t]));
220
+ folded++;
221
+ }
222
+
223
+ if (folded && deleteBefore < todayStr) {
224
+ const res = await tx.run(`DELETE FROM ${table} WHERE day < ?`, [deleteBefore]);
225
+ deleted = Number(res.changes) || 0;
226
+ }
227
+ });
228
+ return { folded, deleted };
229
+ }
230
+ };
231
+ }
232
+
233
+ /**
234
+ * The DDL for both tables, in the caller's dialect.
235
+ *
236
+ * The app owns its SCOPE column and any foreign key on it — Support101's `ticket_id` cascades from
237
+ * `tickets`, which a generic column could not do — so this emits everything EXCEPT that, and the
238
+ * app adds it in its own migration.
239
+ */
240
+ function schemaFor(dialect, o = {}) {
241
+ const t = dialect || {
242
+ autoIncrementPk: () => 'INTEGER PRIMARY KEY AUTOINCREMENT',
243
+ now: () => "datetime('now')"
244
+ };
245
+ const route = o.routeColumn ? `\n ${o.routeColumn}${' '.repeat(Math.max(1, 14 - o.routeColumn.length))}TEXT,` : '';
246
+ return {
247
+ detail: `
248
+ id ${t.autoIncrementPk()},
249
+ day TEXT NOT NULL,
250
+ provider TEXT NOT NULL,
251
+ model TEXT NOT NULL,${route}
252
+ calls INTEGER NOT NULL DEFAULT 1,
253
+ prompt_tokens INTEGER NOT NULL DEFAULT 0,
254
+ completion_tokens INTEGER NOT NULL DEFAULT 0,
255
+ total_tokens INTEGER NOT NULL DEFAULT 0,
256
+ created_at TEXT NOT NULL DEFAULT (${t.now()})
257
+ `,
258
+ // The UNIQUE key is what ON CONFLICT targets — without it the rollup silently inserts
259
+ // duplicates instead of accumulating, and every re-run doubles the totals.
260
+ rollup: `
261
+ day TEXT NOT NULL,
262
+ provider TEXT NOT NULL,
263
+ model TEXT NOT NULL,${route}
264
+ calls INTEGER NOT NULL DEFAULT 0,
265
+ prompt_tokens INTEGER NOT NULL DEFAULT 0,
266
+ completion_tokens INTEGER NOT NULL DEFAULT 0,
267
+ total_tokens INTEGER NOT NULL DEFAULT 0,
268
+ UNIQUE(day, provider, model${o.routeColumn ? ', ' + o.routeColumn : ''})
269
+ `
270
+ };
271
+ }
272
+
273
+ module.exports = { createUsageStore, schemaFor, _dayOf: dayOf };