@aeolus-fleet/trierarch-plugin 0.32.0 → 0.34.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.
Files changed (84) hide show
  1. package/dist/adapters/fleet/operator-fleet.d.ts +2 -0
  2. package/dist/adapters/fleet/operator-fleet.js +50 -0
  3. package/dist/adapters/fleet/operator-fleet.js.map +1 -0
  4. package/dist/adapters/fleet/rest-fleet-door.js +2 -1
  5. package/dist/adapters/fleet/rest-fleet-door.js.map +1 -1
  6. package/dist/adapters/prisma/fleet-forgetter.d.ts +1 -1
  7. package/dist/adapters/prisma/fleet-forgetter.js +2 -2
  8. package/dist/adapters/prisma/fleet-forgetter.js.map +1 -1
  9. package/dist/adapters/prisma/generated/browser.d.ts +23 -0
  10. package/dist/adapters/prisma/generated/client.d.ts +23 -0
  11. package/dist/adapters/prisma/generated/commonInputTypes.d.ts +201 -0
  12. package/dist/adapters/prisma/generated/internal/class.d.ts +33 -0
  13. package/dist/adapters/prisma/generated/internal/class.js +4 -4
  14. package/dist/adapters/prisma/generated/internal/class.js.map +1 -1
  15. package/dist/adapters/prisma/generated/internal/prismaNamespace.d.ts +306 -1
  16. package/dist/adapters/prisma/generated/internal/prismaNamespace.js +54 -1
  17. package/dist/adapters/prisma/generated/internal/prismaNamespace.js.map +1 -1
  18. package/dist/adapters/prisma/generated/internal/prismaNamespaceBrowser.d.ts +56 -0
  19. package/dist/adapters/prisma/generated/internal/prismaNamespaceBrowser.js +54 -1
  20. package/dist/adapters/prisma/generated/internal/prismaNamespaceBrowser.js.map +1 -1
  21. package/dist/adapters/prisma/generated/models/SubscriptionReading.d.ts +1113 -0
  22. package/dist/adapters/prisma/generated/models/SubscriptionReading.js +2 -0
  23. package/dist/adapters/prisma/generated/models/SubscriptionReading.js.map +1 -0
  24. package/dist/adapters/prisma/generated/models/UsageDay.d.ts +1554 -0
  25. package/dist/adapters/prisma/generated/models/UsageDay.js +2 -0
  26. package/dist/adapters/prisma/generated/models/UsageDay.js.map +1 -0
  27. package/dist/adapters/prisma/generated/models/UsageHour.d.ts +1445 -0
  28. package/dist/adapters/prisma/generated/models/UsageHour.js +2 -0
  29. package/dist/adapters/prisma/generated/models/UsageHour.js.map +1 -0
  30. package/dist/adapters/prisma/generated/models.d.ts +3 -0
  31. package/dist/adapters/prisma/usage-history.d.ts +3 -0
  32. package/dist/adapters/prisma/usage-history.js +316 -0
  33. package/dist/adapters/prisma/usage-history.js.map +1 -0
  34. package/dist/adapters/trpc/router.d.ts +225 -1
  35. package/dist/adapters/trpc/router.js +185 -1
  36. package/dist/adapters/trpc/router.js.map +1 -1
  37. package/dist/app.js +16 -0
  38. package/dist/app.js.map +1 -1
  39. package/dist/core/connection/ports.d.ts +1 -0
  40. package/dist/core/machines/join-machine.js +2 -4
  41. package/dist/core/machines/join-machine.js.map +1 -1
  42. package/dist/core/machines/new-setup-line.d.ts +32 -0
  43. package/dist/core/machines/new-setup-line.js +45 -0
  44. package/dist/core/machines/new-setup-line.js.map +1 -0
  45. package/dist/core/machines/setup-line.d.ts +14 -0
  46. package/dist/core/machines/setup-line.js +13 -0
  47. package/dist/core/machines/setup-line.js.map +1 -0
  48. package/dist/core/operator/ports.d.ts +27 -2
  49. package/dist/core/shared/errors.d.ts +1 -1
  50. package/dist/core/shared/errors.js.map +1 -1
  51. package/dist/core/usage/ports.d.ts +19 -0
  52. package/dist/core/usage/ports.js +2 -0
  53. package/dist/core/usage/ports.js.map +1 -0
  54. package/dist/core/usage/read-subscription-windows.d.ts +35 -0
  55. package/dist/core/usage/read-subscription-windows.js +32 -0
  56. package/dist/core/usage/read-subscription-windows.js.map +1 -0
  57. package/dist/core/usage/read-token-usage.d.ts +61 -0
  58. package/dist/core/usage/read-token-usage.js +79 -0
  59. package/dist/core/usage/read-token-usage.js.map +1 -0
  60. package/dist/core/usage/read-usage-values.d.ts +36 -0
  61. package/dist/core/usage/read-usage-values.js +31 -0
  62. package/dist/core/usage/read-usage-values.js.map +1 -0
  63. package/dist/core/usage/ship-names.d.ts +19 -0
  64. package/dist/core/usage/ship-names.js +29 -0
  65. package/dist/core/usage/ship-names.js.map +1 -0
  66. package/dist/core/usage/subscription-windows.d.ts +28 -0
  67. package/dist/core/usage/subscription-windows.js +2 -0
  68. package/dist/core/usage/subscription-windows.js.map +1 -0
  69. package/dist/core/usage/token-usage.d.ts +61 -0
  70. package/dist/core/usage/token-usage.js +5 -0
  71. package/dist/core/usage/token-usage.js.map +1 -0
  72. package/dist/core/usage/usage-range.d.ts +12 -0
  73. package/dist/core/usage/usage-range.js +24 -0
  74. package/dist/core/usage/usage-range.js.map +1 -0
  75. package/dist/core/usage/usage-reading.d.ts +53 -0
  76. package/dist/core/usage/usage-reading.js +2 -0
  77. package/dist/core/usage/usage-reading.js.map +1 -0
  78. package/dist/core/usage/usage-values.d.ts +15 -0
  79. package/dist/core/usage/usage-values.js +2 -0
  80. package/dist/core/usage/usage-values.js.map +1 -0
  81. package/package.json +1 -1
  82. package/src/adapters/prisma/migrations/20261028120000_usage_history/migration.sql +57 -0
  83. package/src/adapters/prisma/migrations/20261028150000_usage_cost_per_kind/migration.sql +21 -0
  84. package/src/adapters/prisma/schema.prisma +79 -2
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=UsageHour.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"UsageHour.js","sourceRoot":"","sources":["../../../../../src/adapters/prisma/generated/models/UsageHour.ts"],"names":[],"mappings":""}
@@ -2,4 +2,7 @@ export type * from './models/Connection.js';
2
2
  export type * from './models/FleetSwitch.js';
3
3
  export type * from './models/InstallationRequest.js';
4
4
  export type * from './models/EnabledModel.js';
5
+ export type * from './models/UsageHour.js';
6
+ export type * from './models/UsageDay.js';
7
+ export type * from './models/SubscriptionReading.js';
5
8
  export type * from './commonInputTypes.js';
@@ -0,0 +1,3 @@
1
+ import type { UsageHistory } from '../../core/usage/ports.js';
2
+ import type { PrismaClient } from './client.js';
3
+ export declare function createPrismaUsageHistory(db: PrismaClient): UsageHistory;
@@ -0,0 +1,316 @@
1
+ import { Prisma } from './generated/client.js';
2
+ export function createPrismaUsageHistory(db) {
3
+ return {
4
+ record: async (fleetId, reading) => {
5
+ await db.$transaction(async (tx) => {
6
+ const changes = [];
7
+ const scope = { tx, fleetId, reading };
8
+ for (const hour of [...reading.hours].sort(byHourKey)) {
9
+ changes.push(...(await setHour(scope, hour)));
10
+ }
11
+ for (const change of changes.sort(byDayKey)) {
12
+ await addToDay(scope, change);
13
+ }
14
+ await addSubscriptionReadings(scope);
15
+ });
16
+ },
17
+ readTokens: async (fleetId, query) => {
18
+ const source = sourceOf(fleetId, query);
19
+ const [rows, unpriced] = await Promise.all([db.$queryRaw(bucketsQuery(source, query)), db.$queryRaw(unpricedModelsQuery(source))]);
20
+ return toTokenUsage(rows, { splitBy: query.splitBy, unpricedModels: unpriced.map((row) => row.model) });
21
+ },
22
+ readValues: (fleetId, query) => db.$queryRaw(valuesQuery(fleetId, query)),
23
+ readWindows: async (fleetId, query) => toWindows(await db.$queryRaw(windowsQuery(fleetId, query))),
24
+ };
25
+ }
26
+ /** Sets one hour row to the reading, unless the stored one is as new; answers what its day gains and loses. */
27
+ async function setHour({ tx, fleetId, reading }, hour) {
28
+ const values = {
29
+ harness: hour.harness,
30
+ login: hour.login,
31
+ input: String(hour.tokens.input),
32
+ output: String(hour.tokens.output),
33
+ cache_read: String(hour.tokens.cacheRead),
34
+ cache_write: String(hour.tokens.cacheWrite),
35
+ estimated_cost_input_usd: costText(hour.estimatedCostUsd?.input),
36
+ estimated_cost_output_usd: costText(hour.estimatedCostUsd?.output),
37
+ estimated_cost_cache_read_usd: costText(hour.estimatedCostUsd?.cacheRead),
38
+ estimated_cost_cache_write_usd: costText(hour.estimatedCostUsd?.cacheWrite),
39
+ };
40
+ const change = (dayValues, isTakenAway) => ({ shipId: hour.shipId, day: utcDay(hour.hour), model: hour.model, values: dayValues, isTakenAway });
41
+ // A row another reading is inserting makes this wait for it, then do nothing.
42
+ const inserted = await tx.$queryRaw `
43
+ INSERT INTO usage_hours (fleet_id, hour, machine_ship_id, ship_id, folder_made_at, model, harness, login, input, output, cache_read, cache_write,
44
+ estimated_cost_input_usd, estimated_cost_output_usd, estimated_cost_cache_read_usd, estimated_cost_cache_write_usd, read_at)
45
+ VALUES (${fleetId}, ${hour.hour}, ${reading.machineShipId}, ${hour.shipId}, ${hour.folderMadeAt}, ${hour.model}, ${hour.harness}, ${hour.login},
46
+ ${values.input}::bigint, ${values.output}::bigint, ${values.cache_read}::bigint, ${values.cache_write}::bigint,
47
+ ${values.estimated_cost_input_usd}::numeric, ${values.estimated_cost_output_usd}::numeric, ${values.estimated_cost_cache_read_usd}::numeric,
48
+ ${values.estimated_cost_cache_write_usd}::numeric, ${reading.readAt})
49
+ ON CONFLICT DO NOTHING
50
+ RETURNING 1`;
51
+ if (inserted.length > 0) {
52
+ return [change(values, false)];
53
+ }
54
+ const [stored] = await tx.$queryRaw `
55
+ SELECT harness, login, input::text, output::text, cache_read::text, cache_write::text, estimated_cost_input_usd::text, estimated_cost_output_usd::text,
56
+ estimated_cost_cache_read_usd::text, estimated_cost_cache_write_usd::text, read_at
57
+ FROM usage_hours
58
+ WHERE fleet_id = ${fleetId} AND hour = ${hour.hour} AND machine_ship_id = ${reading.machineShipId} AND ship_id = ${hour.shipId} AND folder_made_at = ${hour.folderMadeAt} AND model = ${hour.model}
59
+ FOR UPDATE`;
60
+ if (stored === undefined || stored.read_at.getTime() >= reading.readAt.getTime()) {
61
+ return [];
62
+ }
63
+ await tx.$executeRaw `
64
+ UPDATE usage_hours
65
+ SET harness = ${hour.harness}, login = ${hour.login}, input = ${values.input}::bigint, output = ${values.output}::bigint, cache_read = ${values.cache_read}::bigint,
66
+ cache_write = ${values.cache_write}::bigint, estimated_cost_input_usd = ${values.estimated_cost_input_usd}::numeric,
67
+ estimated_cost_output_usd = ${values.estimated_cost_output_usd}::numeric, estimated_cost_cache_read_usd = ${values.estimated_cost_cache_read_usd}::numeric,
68
+ estimated_cost_cache_write_usd = ${values.estimated_cost_cache_write_usd}::numeric, read_at = ${reading.readAt}
69
+ WHERE fleet_id = ${fleetId} AND hour = ${hour.hour} AND machine_ship_id = ${reading.machineShipId} AND ship_id = ${hour.shipId} AND folder_made_at = ${hour.folderMadeAt} AND model = ${hour.model}`;
70
+ return [change(stored, true), change(values, false)];
71
+ }
72
+ /**
73
+ * Adds an hour row's values to its day row, or takes them away: each kind's
74
+ * cost, or, when the trierarch does not price the model, each kind's tokens as
75
+ * not priced.
76
+ */
77
+ async function addToDay({ tx, fleetId, reading }, change) {
78
+ const sign = change.isTakenAway ? -1 : 1;
79
+ const { values } = change;
80
+ await tx.$executeRaw `
81
+ INSERT INTO usage_days (fleet_id, day, machine_ship_id, ship_id, model, harness, login, input, output, cache_read, cache_write,
82
+ estimated_cost_input_usd, estimated_cost_output_usd, estimated_cost_cache_read_usd, estimated_cost_cache_write_usd,
83
+ unpriced_input, unpriced_output, unpriced_cache_read, unpriced_cache_write)
84
+ SELECT ${fleetId}, ${change.day}::date, ${reading.machineShipId}, ${change.shipId}, ${change.model}, ${values.harness}, ${values.login},
85
+ ${sign} * t.input, ${sign} * t.output, ${sign} * t.cache_read, ${sign} * t.cache_write,
86
+ ${sign} * coalesce(t.cost_input, 0), ${sign} * coalesce(t.cost_output, 0), ${sign} * coalesce(t.cost_cache_read, 0), ${sign} * coalesce(t.cost_cache_write, 0),
87
+ ${sign} * CASE WHEN t.cost_input IS NULL THEN t.input ELSE 0 END, ${sign} * CASE WHEN t.cost_input IS NULL THEN t.output ELSE 0 END,
88
+ ${sign} * CASE WHEN t.cost_input IS NULL THEN t.cache_read ELSE 0 END, ${sign} * CASE WHEN t.cost_input IS NULL THEN t.cache_write ELSE 0 END
89
+ FROM (SELECT ${values.input}::bigint AS input, ${values.output}::bigint AS output, ${values.cache_read}::bigint AS cache_read,
90
+ ${values.cache_write}::bigint AS cache_write, ${values.estimated_cost_input_usd}::numeric AS cost_input, ${values.estimated_cost_output_usd}::numeric AS cost_output,
91
+ ${values.estimated_cost_cache_read_usd}::numeric AS cost_cache_read, ${values.estimated_cost_cache_write_usd}::numeric AS cost_cache_write) AS t
92
+ ON CONFLICT (fleet_id, day, machine_ship_id, ship_id, model, harness, login) DO UPDATE
93
+ SET input = usage_days.input + EXCLUDED.input, output = usage_days.output + EXCLUDED.output, cache_read = usage_days.cache_read + EXCLUDED.cache_read,
94
+ cache_write = usage_days.cache_write + EXCLUDED.cache_write,
95
+ estimated_cost_input_usd = usage_days.estimated_cost_input_usd + EXCLUDED.estimated_cost_input_usd,
96
+ estimated_cost_output_usd = usage_days.estimated_cost_output_usd + EXCLUDED.estimated_cost_output_usd,
97
+ estimated_cost_cache_read_usd = usage_days.estimated_cost_cache_read_usd + EXCLUDED.estimated_cost_cache_read_usd,
98
+ estimated_cost_cache_write_usd = usage_days.estimated_cost_cache_write_usd + EXCLUDED.estimated_cost_cache_write_usd,
99
+ unpriced_input = usage_days.unpriced_input + EXCLUDED.unpriced_input, unpriced_output = usage_days.unpriced_output + EXCLUDED.unpriced_output,
100
+ unpriced_cache_read = usage_days.unpriced_cache_read + EXCLUDED.unpriced_cache_read, unpriced_cache_write = usage_days.unpriced_cache_write + EXCLUDED.unpriced_cache_write`;
101
+ }
102
+ /** A cost as Postgres numeric reads it exactly; none when the model is not priced. */
103
+ function costText(usd) {
104
+ return usd === undefined ? null : String(usd);
105
+ }
106
+ async function addSubscriptionReadings({ tx, fleetId, reading }) {
107
+ const rows = reading.subscriptions.flatMap((subscription) => subscription.windows.map((window) => ({
108
+ fleetId,
109
+ machineShipId: reading.machineShipId,
110
+ harness: subscription.harness,
111
+ windowMinutes: window.windowMinutes,
112
+ readAt: subscription.readAt,
113
+ usedPercent: window.usedPercent,
114
+ resetsAt: window.resetsAt,
115
+ })));
116
+ await tx.subscriptionReading.createMany({ data: rows, skipDuplicates: true });
117
+ }
118
+ /** The UTC day an hour starts in, as Postgres reads a date. */
119
+ function utcDay(hour) {
120
+ return hour.toISOString().slice(0, 'yyyy-mm-dd'.length);
121
+ }
122
+ function byHourKey(a, b) {
123
+ return a.hour.getTime() - b.hour.getTime() || a.shipId.localeCompare(b.shipId) || a.folderMadeAt.getTime() - b.folderMadeAt.getTime() || a.model.localeCompare(b.model);
124
+ }
125
+ function byDayKey(a, b) {
126
+ return (a.day.localeCompare(b.day) ||
127
+ a.shipId.localeCompare(b.shipId) ||
128
+ a.model.localeCompare(b.model) ||
129
+ a.values.harness.localeCompare(b.values.harness) ||
130
+ (a.values.login ?? '').localeCompare(b.values.login ?? ''));
131
+ }
132
+ /** The series past which the rest are added up as other. */
133
+ const MOST_SERIES = 7;
134
+ /** The column each breakdown splits by, in both tables. */
135
+ const SPLIT_COLUMNS = {
136
+ machine: Prisma.sql `machine_ship_id`,
137
+ harness: Prisma.sql `harness`,
138
+ model: Prisma.sql `model`,
139
+ ship: Prisma.sql `ship_id`,
140
+ login: Prisma.sql `login`,
141
+ };
142
+ /** The amounts every read row carries and the buckets add up, each kind apart. */
143
+ const AMOUNT_COLUMNS = [
144
+ 'input',
145
+ 'output',
146
+ 'cache_read',
147
+ 'cache_write',
148
+ 'cost_input',
149
+ 'cost_output',
150
+ 'cost_cache_read',
151
+ 'cost_cache_write',
152
+ 'unpriced_input',
153
+ 'unpriced_output',
154
+ 'unpriced_cache_read',
155
+ 'unpriced_cache_write',
156
+ ];
157
+ function sourceOf(fleetId, query) {
158
+ const key = query.splitBy === null ? Prisma.sql `NULL::text` : SPLIT_COLUMNS[query.splitBy];
159
+ const filters = filtersOf(query.filters);
160
+ if (query.grain === 'hour') {
161
+ const where = Prisma.sql `fleet_id = ${fleetId} AND hour >= ${query.from} AND hour < ${query.to} AND ${filters}`;
162
+ return {
163
+ // A model not priced has all four costs null: its tokens of each kind count as not priced.
164
+ rows: Prisma.sql `SELECT hour AS at, ${key} AS key, input, output, cache_read, cache_write,
165
+ coalesce(estimated_cost_input_usd, 0) AS cost_input, coalesce(estimated_cost_output_usd, 0) AS cost_output,
166
+ coalesce(estimated_cost_cache_read_usd, 0) AS cost_cache_read, coalesce(estimated_cost_cache_write_usd, 0) AS cost_cache_write,
167
+ CASE WHEN estimated_cost_input_usd IS NULL THEN input ELSE 0 END AS unpriced_input,
168
+ CASE WHEN estimated_cost_input_usd IS NULL THEN output ELSE 0 END AS unpriced_output,
169
+ CASE WHEN estimated_cost_input_usd IS NULL THEN cache_read ELSE 0 END AS unpriced_cache_read,
170
+ CASE WHEN estimated_cost_input_usd IS NULL THEN cache_write ELSE 0 END AS unpriced_cache_write
171
+ FROM usage_hours WHERE ${where}`,
172
+ unpricedRows: Prisma.sql `SELECT model FROM usage_hours WHERE ${where} AND estimated_cost_input_usd IS NULL`,
173
+ };
174
+ }
175
+ const where = Prisma.sql `fleet_id = ${fleetId} AND day >= (${query.from}::timestamptz AT TIME ZONE 'UTC')::date AND day < (${query.to}::timestamptz AT TIME ZONE 'UTC')::date AND ${filters}`;
176
+ return {
177
+ rows: Prisma.sql `SELECT day::timestamp AT TIME ZONE 'UTC' AS at, ${key} AS key, input, output, cache_read, cache_write,
178
+ estimated_cost_input_usd AS cost_input, estimated_cost_output_usd AS cost_output, estimated_cost_cache_read_usd AS cost_cache_read,
179
+ estimated_cost_cache_write_usd AS cost_cache_write, unpriced_input, unpriced_output, unpriced_cache_read, unpriced_cache_write
180
+ FROM usage_days WHERE ${where}`,
181
+ unpricedRows: Prisma.sql `SELECT model FROM usage_days WHERE ${where} AND unpriced_input + unpriced_output + unpriced_cache_read + unpriced_cache_write > 0`,
182
+ };
183
+ }
184
+ /** Each filtered breakdown as one condition; a null login is "not reported". */
185
+ function filtersOf(filters) {
186
+ const conditions = [];
187
+ const anyOf = (column, values) => {
188
+ if (values !== undefined) {
189
+ conditions.push(Prisma.sql `${column} = ANY(${[...values]}::text[])`);
190
+ }
191
+ };
192
+ anyOf(SPLIT_COLUMNS.machine, filters.machineShipIds);
193
+ anyOf(SPLIT_COLUMNS.harness, filters.harnesses);
194
+ anyOf(SPLIT_COLUMNS.model, filters.models);
195
+ anyOf(SPLIT_COLUMNS.ship, filters.shipIds);
196
+ if (filters.logins !== undefined) {
197
+ const named = filters.logins.filter((login) => login !== null);
198
+ const notReported = filters.logins.includes(null) ? Prisma.sql `OR login IS NULL` : Prisma.empty;
199
+ conditions.push(Prisma.sql `(login = ANY(${named}::text[]) ${notReported})`);
200
+ }
201
+ return conditions.length === 0 ? Prisma.sql `TRUE` : Prisma.join(conditions, ' AND ');
202
+ }
203
+ /** The series ranked by their total of the measure, largest first (then by key), the ones past MOST_SERIES as other, added up per bucket. */
204
+ function bucketsQuery(source, query) {
205
+ const measure = query.measure === 'tokens' ? Prisma.sql `input + output + cache_read + cache_write` : Prisma.sql `cost_input + cost_output + cost_cache_read + cost_cache_write`;
206
+ // Raw only over AMOUNT_COLUMNS, this file's own constants: no input reaches it.
207
+ const sums = Prisma.raw(AMOUNT_COLUMNS.map((column) => `sum(p.${column}) AS ${column}`).join(', '));
208
+ const amounts = Prisma.raw(AMOUNT_COLUMNS.map((column) => `${column}::float8 AS ${column}`).join(', '));
209
+ return Prisma.sql `
210
+ WITH picked AS (${source.rows}),
211
+ ranked AS (
212
+ SELECT key, row_number() OVER (ORDER BY sum(${measure}) DESC, key ASC NULLS LAST) AS rank, count(*) OVER () AS keys
213
+ FROM picked GROUP BY key
214
+ ),
215
+ grouped AS (
216
+ SELECT p.at,
217
+ CASE WHEN r.keys > ${MOST_SERIES} AND r.rank > ${MOST_SERIES} THEN ${MOST_SERIES + 1} ELSE r.rank END AS rank,
218
+ CASE WHEN r.keys > ${MOST_SERIES} AND r.rank > ${MOST_SERIES} THEN NULL ELSE p.key END AS key,
219
+ ${sums}
220
+ FROM picked p JOIN ranked r ON r.key IS NOT DISTINCT FROM p.key
221
+ GROUP BY 1, 2, 3
222
+ )
223
+ SELECT at, rank::int AS rank, key, ${amounts}
224
+ FROM grouped ORDER BY at, rank`;
225
+ }
226
+ /** One page of a breakdown's values by their tokens, largest first, then by value with a login not reported last: after the cursor, up to the limit. */
227
+ function valuesQuery(fleetId, query) {
228
+ const source = sourceOf(fleetId, { from: query.from, to: query.to, grain: query.grain, splitBy: query.breakdown, measure: 'tokens', filters: {} });
229
+ const { after } = query;
230
+ let afterCursor = Prisma.sql `TRUE`;
231
+ if (after?.value === null) {
232
+ afterCursor = Prisma.sql `tokens < ${after.tokens}::numeric`;
233
+ }
234
+ else if (after) {
235
+ afterCursor = Prisma.sql `(tokens < ${after.tokens}::numeric OR (tokens = ${after.tokens}::numeric AND (value > ${after.value} OR value IS NULL)))`;
236
+ }
237
+ return Prisma.sql `
238
+ WITH totals AS (SELECT key AS value, sum(input + output + cache_read + cache_write) AS tokens FROM (${source.rows}) AS picked GROUP BY key)
239
+ SELECT value, tokens::float8 AS tokens FROM totals
240
+ WHERE ${afterCursor}
241
+ ORDER BY tokens DESC, value ASC NULLS LAST
242
+ LIMIT ${query.limit}`;
243
+ }
244
+ /** Every reading in the range of a page of machine and harness pairs, after the cursor, ordered by machine, harness, window and time; the pairs carry the filters. */
245
+ function windowsQuery(fleetId, query) {
246
+ const conditions = [Prisma.sql `fleet_id = ${fleetId}`, Prisma.sql `read_at >= ${query.from}`, Prisma.sql `read_at < ${query.to}`];
247
+ if (query.filters.machineShipIds !== undefined) {
248
+ conditions.push(Prisma.sql `machine_ship_id = ANY(${[...query.filters.machineShipIds]}::text[])`);
249
+ }
250
+ if (query.filters.harnesses !== undefined) {
251
+ conditions.push(Prisma.sql `harness = ANY(${[...query.filters.harnesses]}::text[])`);
252
+ }
253
+ const where = Prisma.join(conditions, ' AND ');
254
+ const after = query.after === null ? Prisma.sql `TRUE` : Prisma.sql `(machine_ship_id, harness) > (${query.after.machineShipId}, ${query.after.harness})`;
255
+ return Prisma.sql `
256
+ WITH pairs AS (
257
+ SELECT DISTINCT machine_ship_id, harness FROM subscription_readings
258
+ WHERE ${where} AND ${after}
259
+ ORDER BY machine_ship_id, harness LIMIT ${query.limit}
260
+ )
261
+ SELECT r.machine_ship_id, r.harness, r.window_minutes, r.read_at, r.used_percent::float8 AS used_percent, r.resets_at
262
+ FROM subscription_readings r JOIN pairs p ON p.machine_ship_id = r.machine_ship_id AND p.harness = r.harness
263
+ WHERE r.fleet_id = ${fleetId} AND r.read_at >= ${query.from} AND r.read_at < ${query.to}
264
+ ORDER BY r.machine_ship_id, r.harness, r.window_minutes, r.read_at`;
265
+ }
266
+ /** The readings as charts: one per machine and harness, one window each per window length. */
267
+ function toWindows(rows) {
268
+ const charts = [];
269
+ for (const row of rows) {
270
+ let chart = charts.at(-1);
271
+ if (chart?.machineShipId !== row.machine_ship_id || chart.harness !== row.harness) {
272
+ chart = { machineShipId: row.machine_ship_id, harness: row.harness, windows: [] };
273
+ charts.push(chart);
274
+ }
275
+ let window = chart.windows.at(-1);
276
+ if (window?.windowMinutes !== row.window_minutes) {
277
+ window = { windowMinutes: row.window_minutes, readings: [] };
278
+ chart.windows.push(window);
279
+ }
280
+ window.readings.push({ readAt: row.read_at, usedPercent: row.used_percent, resetsAt: row.resets_at });
281
+ }
282
+ return charts;
283
+ }
284
+ function unpricedModelsQuery(source) {
285
+ return Prisma.sql `SELECT DISTINCT model FROM (${source.unpricedRows}) AS unpriced ORDER BY model`;
286
+ }
287
+ /** The rows as the port answers them: the series by rank, and per bucket the amounts of each series by its index. */
288
+ function toTokenUsage(rows, read) {
289
+ const keys = new Map(rows.map((row) => [row.rank, row.key]));
290
+ const series = [...keys.keys()]
291
+ .toSorted((a, b) => a - b)
292
+ .map((rank) => {
293
+ if (read.splitBy === null) {
294
+ return { kind: 'all' };
295
+ }
296
+ return rank > MOST_SERIES ? { kind: 'other' } : { kind: 'value', value: keys.get(rank) ?? null };
297
+ });
298
+ const buckets = [];
299
+ for (const row of rows) {
300
+ const amount = {
301
+ series: row.rank - 1,
302
+ tokens: { input: row.input, output: row.output, cacheRead: row.cache_read, cacheWrite: row.cache_write },
303
+ estimatedCostUsd: { input: row.cost_input, output: row.cost_output, cacheRead: row.cost_cache_read, cacheWrite: row.cost_cache_write },
304
+ unpricedTokens: { input: row.unpriced_input, output: row.unpriced_output, cacheRead: row.unpriced_cache_read, cacheWrite: row.unpriced_cache_write },
305
+ };
306
+ const last = buckets.at(-1);
307
+ if (last?.at.getTime() === row.at.getTime()) {
308
+ last.amounts.push(amount);
309
+ }
310
+ else {
311
+ buckets.push({ at: row.at, amounts: [amount] });
312
+ }
313
+ }
314
+ return { series, buckets, unpricedModels: read.unpricedModels };
315
+ }
316
+ //# sourceMappingURL=usage-history.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-history.js","sourceRoot":"","sources":["../../../src/adapters/prisma/usage-history.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAiC/C,MAAM,UAAU,wBAAwB,CAAC,EAAgB;IACvD,OAAO;QACL,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE;YACjC,MAAM,EAAE,CAAC,YAAY,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;gBACjC,MAAM,OAAO,GAAgB,EAAE,CAAC;gBAChC,MAAM,KAAK,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;gBACvC,KAAK,MAAM,IAAI,IAAI,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;oBACtD,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;gBAChD,CAAC;gBACD,KAAK,MAAM,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;oBAC5C,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;gBAChC,CAAC;gBACD,MAAM,uBAAuB,CAAC,KAAK,CAAC,CAAC;YACvC,CAAC,CAAC,CAAC;QACL,CAAC;QACD,UAAU,EAAE,KAAK,EAAE,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AAC,CAAC;QAClD,CAAC;IACH,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,CAAC;AAClE,CAAC"}
@@ -9,13 +9,19 @@ import type { IsServed } from '../../core/installation/served.js';
9
9
  import type { SetFleetEnabled } from '../../core/installation/set-fleet-enabled.js';
10
10
  import type { CheckCrewSettings } from '../../core/assignment/check-crew-settings.js';
11
11
  import type { JoinMachine } from '../../core/machines/join-machine.js';
12
+ import type { MakeNewSetupLine } from '../../core/machines/new-setup-line.js';
12
13
  import type { ListMachines } from '../../core/machines/list-machines.js';
13
14
  import type { ListEnabledModels } from '../../core/models/list-enabled-models.js';
14
15
  import type { SetModelEnabled } from '../../core/models/set-model-enabled.js';
15
16
  import type { AuthenticateOperator } from '../../core/operator/authenticate-operator.js';
17
+ import { type ReadTokenUsage } from '../../core/usage/read-token-usage.js';
18
+ import type { ReadSubscriptionWindows } from '../../core/usage/read-subscription-windows.js';
19
+ import type { ReadUsageValues } from '../../core/usage/read-usage-values.js';
16
20
  export interface Context {
17
21
  /** The Cookie header the console's server forwarded. */
18
22
  cookie: string | undefined;
23
+ /** The Origin header the console's server forwarded: the browser's, which the fleet checks on a change made with the cookie. */
24
+ origin: string | undefined;
19
25
  authenticateOperator: AuthenticateOperator;
20
26
  /** Whether the trierarch plugin is connected to the fleet. */
21
27
  isConnected: (fleetId: FleetId) => Promise<boolean>;
@@ -34,10 +40,14 @@ export interface Context {
34
40
  readConnection: ReadConnection;
35
41
  connect: Connect;
36
42
  joinMachine: JoinMachine;
43
+ newSetupLine: MakeNewSetupLine;
37
44
  listMachines: ListMachines;
38
45
  checkCrewSettings: CheckCrewSettings;
39
46
  listEnabledModels: ListEnabledModels;
40
47
  setModelEnabled: SetModelEnabled;
48
+ readTokenUsage: ReadTokenUsage;
49
+ readUsageValues: ReadUsageValues;
50
+ readSubscriptionWindows: ReadSubscriptionWindows;
41
51
  }
42
52
  /** What a caller reads of a failure: nothing of it, so no crew token, secret or query ever leaves; the log holds it whole. */
43
53
  export declare const INTERNAL_ERROR_MESSAGE = "Internal error";
@@ -168,6 +178,67 @@ export declare const machineOutputSchema: z.ZodObject<{
168
178
  version: z.ZodString;
169
179
  }, z.core.$strict>>;
170
180
  }, z.core.$strip>;
181
+ /** Token usage as the Usage page reads it (ISO 8601 in UTC): its series named and largest first, each bucket holding usage, and the range's totals. */
182
+ export declare const tokenUsageOutputSchema: z.ZodObject<{
183
+ grain: z.ZodEnum<{
184
+ hour: "hour";
185
+ day: "day";
186
+ }>;
187
+ series: z.ZodArray<z.ZodObject<{
188
+ key: z.ZodDiscriminatedUnion<[z.ZodObject<{
189
+ kind: z.ZodLiteral<"value">;
190
+ value: z.ZodNullable<z.ZodString>;
191
+ }, z.core.$strip>, z.ZodObject<{
192
+ kind: z.ZodLiteral<"other">;
193
+ }, z.core.$strip>, z.ZodObject<{
194
+ kind: z.ZodLiteral<"all">;
195
+ }, z.core.$strip>, z.ZodObject<{
196
+ kind: z.ZodLiteral<"tokenKind">;
197
+ tokenKind: z.ZodEnum<{
198
+ output: "output";
199
+ input: "input";
200
+ cacheRead: "cacheRead";
201
+ cacheWrite: "cacheWrite";
202
+ }>;
203
+ }, z.core.$strip>], "kind">;
204
+ name: z.ZodNullable<z.ZodString>;
205
+ amounts: z.ZodObject<{
206
+ tokens: z.ZodObject<{
207
+ input: z.ZodNumber;
208
+ output: z.ZodNumber;
209
+ cacheRead: z.ZodNumber;
210
+ cacheWrite: z.ZodNumber;
211
+ }, z.core.$strip>;
212
+ estimatedCostUsd: z.ZodNumber;
213
+ unpricedTokens: z.ZodNumber;
214
+ }, z.core.$strip>;
215
+ }, z.core.$strip>>;
216
+ buckets: z.ZodArray<z.ZodObject<{
217
+ at: z.ZodISODateTime;
218
+ amounts: z.ZodArray<z.ZodObject<{
219
+ tokens: z.ZodObject<{
220
+ input: z.ZodNumber;
221
+ output: z.ZodNumber;
222
+ cacheRead: z.ZodNumber;
223
+ cacheWrite: z.ZodNumber;
224
+ }, z.core.$strip>;
225
+ estimatedCostUsd: z.ZodNumber;
226
+ unpricedTokens: z.ZodNumber;
227
+ series: z.ZodInt;
228
+ }, z.core.$strip>>;
229
+ }, z.core.$strip>>;
230
+ totals: z.ZodObject<{
231
+ tokens: z.ZodObject<{
232
+ input: z.ZodNumber;
233
+ output: z.ZodNumber;
234
+ cacheRead: z.ZodNumber;
235
+ cacheWrite: z.ZodNumber;
236
+ }, z.core.$strip>;
237
+ estimatedCostUsd: z.ZodNumber;
238
+ unpricedTokens: z.ZodNumber;
239
+ }, z.core.$strip>;
240
+ unpricedModels: z.ZodArray<z.ZodString>;
241
+ }, z.core.$strip>;
171
242
  export declare const trierarchPluginRouter: import("@trpc/server").TRPCBuiltRouter<{
172
243
  ctx: Context;
173
244
  meta: object;
@@ -241,6 +312,22 @@ export declare const trierarchPluginRouter: import("@trpc/server").TRPCBuiltRout
241
312
  };
242
313
  meta: object;
243
314
  }>;
315
+ /**
316
+ * A machine's new setup line, once (aeolus-fleet#1239): a crewed machine's
317
+ * ship is released, then gets a new starting prompt, both as the operator
318
+ * with the forwarded session and Origin, so the operator's own rights
319
+ * decide. The old line stops working.
320
+ */
321
+ newSetupLine: import("@trpc/server").TRPCMutationProcedure<{
322
+ input: {
323
+ shipId: unknown;
324
+ };
325
+ output: {
326
+ shipId: `shp_${string}`;
327
+ setupLine: string;
328
+ };
329
+ meta: object;
330
+ }>;
244
331
  /** The fleet's machines, each with its trierarch's last report and details, read from the fleet. */
245
332
  list: import("@trpc/server").TRPCQueryProcedure<{
246
333
  input: void;
@@ -282,7 +369,7 @@ export declare const trierarchPluginRouter: import("@trpc/server").TRPCBuiltRout
282
369
  }[];
283
370
  version: string;
284
371
  machine?: {
285
- os?: "macos" | "linux" | "windows" | undefined;
372
+ os?: "windows" | "macos" | "linux" | undefined;
286
373
  arch?: "arm64" | "amd64" | undefined;
287
374
  } | undefined;
288
375
  runtime?: "host" | "container" | undefined;
@@ -393,6 +480,143 @@ export declare const trierarchPluginRouter: import("@trpc/server").TRPCBuiltRout
393
480
  meta: object;
394
481
  }>;
395
482
  }>>;
483
+ usage: import("@trpc/server").TRPCBuiltRouter<{
484
+ ctx: Context;
485
+ meta: object;
486
+ errorShape: import("@trpc/server").TRPCDefaultErrorShape;
487
+ transformer: false;
488
+ }, import("@trpc/server").TRPCDecorateCreateRouterOptions<{
489
+ /**
490
+ * The fleet's token usage in a range (the usage design): hours up to 7
491
+ * days, UTC days past that, split by one breakdown, by token kind or not
492
+ * at all, the 7 largest series by the measure and other for the rest.
493
+ * Every signed-in session's, viewer included.
494
+ */
495
+ tokens: import("@trpc/server").TRPCQueryProcedure<{
496
+ input: {
497
+ from: string;
498
+ to: string;
499
+ splitBy: "harness" | "ship" | "kind" | "model" | "machine" | "login" | null;
500
+ measure: "tokens" | "cost";
501
+ filters: {
502
+ machineShipIds?: unknown[] | undefined;
503
+ harnesses?: string[] | undefined;
504
+ models?: string[] | undefined;
505
+ shipIds?: unknown[] | undefined;
506
+ logins?: (string | null)[] | undefined;
507
+ };
508
+ };
509
+ output: {
510
+ grain: "hour" | "day";
511
+ series: {
512
+ key: {
513
+ kind: "value";
514
+ value: string | null;
515
+ } | {
516
+ kind: "other";
517
+ } | {
518
+ kind: "all";
519
+ } | {
520
+ kind: "tokenKind";
521
+ tokenKind: "output" | "input" | "cacheRead" | "cacheWrite";
522
+ };
523
+ name: string | null;
524
+ amounts: {
525
+ tokens: {
526
+ input: number;
527
+ output: number;
528
+ cacheRead: number;
529
+ cacheWrite: number;
530
+ };
531
+ estimatedCostUsd: number;
532
+ unpricedTokens: number;
533
+ };
534
+ }[];
535
+ buckets: {
536
+ at: string;
537
+ amounts: {
538
+ tokens: {
539
+ input: number;
540
+ output: number;
541
+ cacheRead: number;
542
+ cacheWrite: number;
543
+ };
544
+ estimatedCostUsd: number;
545
+ unpricedTokens: number;
546
+ series: number;
547
+ }[];
548
+ }[];
549
+ totals: {
550
+ tokens: {
551
+ input: number;
552
+ output: number;
553
+ cacheRead: number;
554
+ cacheWrite: number;
555
+ };
556
+ estimatedCostUsd: number;
557
+ unpricedTokens: number;
558
+ };
559
+ unpricedModels: string[];
560
+ };
561
+ meta: object;
562
+ }>;
563
+ /**
564
+ * The values of one breakdown in a range with their tokens, for the Usage
565
+ * page's filter menus: 20 a page, largest first, the next page after the
566
+ * cursor a page answered. Every signed-in session's, viewer included.
567
+ */
568
+ values: import("@trpc/server").TRPCQueryProcedure<{
569
+ input: {
570
+ from: string;
571
+ to: string;
572
+ breakdown: "harness" | "ship" | "model" | "machine" | "login";
573
+ cursor: string | null;
574
+ };
575
+ output: {
576
+ values: {
577
+ value: string | null;
578
+ name: string | null;
579
+ tokens: number;
580
+ }[];
581
+ nextCursor: string | null;
582
+ };
583
+ meta: object;
584
+ }>;
585
+ /**
586
+ * How full each harness's subscription windows were on each machine in a
587
+ * range: per machine and harness, 20 a page, each window's readings oldest
588
+ * first, the next page after the cursor a page answered. Every signed-in
589
+ * session's, viewer included.
590
+ */
591
+ windows: import("@trpc/server").TRPCQueryProcedure<{
592
+ input: {
593
+ from: string;
594
+ to: string;
595
+ filters: {
596
+ machineShipIds?: unknown[] | undefined;
597
+ harnesses?: string[] | undefined;
598
+ };
599
+ cursor: string | null;
600
+ };
601
+ output: {
602
+ charts: {
603
+ machineShipId: `shp_${string}`;
604
+ machineName: string | null;
605
+ harness: string;
606
+ windows: {
607
+ windowMinutes: number;
608
+ readings: {
609
+ readAt: string;
610
+ usedPercent: number;
611
+ resetsAt: string;
612
+ }[];
613
+ }[];
614
+ }[];
615
+ nextCursor: string | null;
616
+ };
617
+ meta: object;
618
+ }>;
619
+ }>>;
396
620
  installation: import("@trpc/server").TRPCBuiltRouter<{
397
621
  ctx: Context;
398
622
  meta: object;