@mupt-ai/dari-gateway 1.0.324 → 1.0.326

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 (88) hide show
  1. package/README.md +4 -3
  2. package/dist/activity/conversation_detail.d.ts +2 -0
  3. package/dist/activity/conversation_detail.js +259 -0
  4. package/dist/activity/conversation_records.d.ts +129 -0
  5. package/dist/activity/conversation_records.js +318 -0
  6. package/dist/activity/conversations.d.ts +11 -0
  7. package/dist/activity/conversations.js +198 -0
  8. package/dist/activity/core.d.ts +13 -0
  9. package/dist/activity/core.js +613 -0
  10. package/dist/activity/filters.d.ts +71 -0
  11. package/dist/activity/filters.js +169 -0
  12. package/dist/activity/http.d.ts +37 -0
  13. package/dist/activity/http.js +109 -0
  14. package/dist/activity/params.d.ts +40 -0
  15. package/dist/activity/params.js +130 -0
  16. package/dist/activity/people.d.ts +3 -0
  17. package/dist/activity/people.js +413 -0
  18. package/dist/activity/routes.d.ts +2 -0
  19. package/dist/activity/routes.js +23 -0
  20. package/dist/activity/savings.d.ts +12 -0
  21. package/dist/activity/savings.js +102 -0
  22. package/dist/activity/shared.d.ts +15 -0
  23. package/dist/activity/shared.js +26 -0
  24. package/dist/activity/sql.d.ts +52 -0
  25. package/dist/activity/sql.js +124 -0
  26. package/dist/activity/tool_exchanges.d.ts +21 -0
  27. package/dist/activity/tool_exchanges.js +309 -0
  28. package/dist/activity/tool_skill_activity.d.ts +128 -0
  29. package/dist/activity/tool_skill_activity.js +280 -0
  30. package/dist/activity/tool_skill_identities.d.ts +25 -0
  31. package/dist/activity/tool_skill_identities.js +162 -0
  32. package/dist/activity/tools.d.ts +4 -0
  33. package/dist/activity/tools.js +68 -0
  34. package/dist/activity/values.d.ts +45 -0
  35. package/dist/activity/values.js +178 -0
  36. package/dist/context/interaction_fingerprint.js +11 -3
  37. package/dist/context/interaction_fingerprint_format.d.ts +2 -1
  38. package/dist/context/interaction_fingerprint_format.js +2 -0
  39. package/dist/http/handler.d.ts +2 -1
  40. package/dist/http/handler.js +6 -1
  41. package/dist/interaction/types.d.ts +17 -2
  42. package/dist/interaction/types.js +11 -0
  43. package/dist/link/endpoints.js +44 -53
  44. package/dist/platform/platform.d.ts +12 -0
  45. package/dist/protocol/input/anthropic_messages.js +63 -48
  46. package/dist/providers/pi.js +22 -3
  47. package/dist/providers/pi_context.js +15 -5
  48. package/dist/runtime/claude_code/auxiliary_routing.js +34 -3
  49. package/dist/runtime/prepare_routed_completion.d.ts +2 -0
  50. package/dist/runtime/prepare_routed_completion.js +42 -1
  51. package/dist/self_host/activity_store.d.ts +35 -0
  52. package/dist/self_host/activity_store.js +373 -0
  53. package/dist/self_host/main.d.ts +3 -2
  54. package/dist/self_host/main.js +8 -3
  55. package/dist/self_host/platform.d.ts +4 -2
  56. package/dist/self_host/platform.js +35 -3
  57. package/package.json +2 -2
  58. package/src/activity/conversation_detail.ts +283 -0
  59. package/src/activity/conversation_records.ts +403 -0
  60. package/src/activity/conversations.ts +218 -0
  61. package/src/activity/core.ts +678 -0
  62. package/src/activity/filters.ts +206 -0
  63. package/src/activity/http.ts +140 -0
  64. package/src/activity/params.ts +138 -0
  65. package/src/activity/people.ts +471 -0
  66. package/src/activity/routes.ts +26 -0
  67. package/src/activity/savings.ts +121 -0
  68. package/src/activity/shared.ts +36 -0
  69. package/src/activity/sql.ts +139 -0
  70. package/src/activity/tool_exchanges.ts +340 -0
  71. package/src/activity/tool_skill_activity.ts +314 -0
  72. package/src/activity/tool_skill_identities.ts +196 -0
  73. package/src/activity/tools.ts +76 -0
  74. package/src/activity/values.ts +197 -0
  75. package/src/context/interaction_fingerprint.ts +9 -3
  76. package/src/context/interaction_fingerprint_format.ts +6 -1
  77. package/src/http/handler.ts +5 -1
  78. package/src/interaction/types.ts +21 -11
  79. package/src/link/endpoints.ts +44 -54
  80. package/src/platform/platform.ts +12 -0
  81. package/src/protocol/input/anthropic_messages.ts +66 -53
  82. package/src/providers/pi.ts +22 -3
  83. package/src/providers/pi_context.ts +14 -7
  84. package/src/runtime/claude_code/auxiliary_routing.ts +33 -2
  85. package/src/runtime/prepare_routed_completion.ts +60 -2
  86. package/src/self_host/activity_store.ts +423 -0
  87. package/src/self_host/main.ts +17 -3
  88. package/src/self_host/platform.ts +38 -3
@@ -0,0 +1,413 @@
1
+ /* People & Keys: Activity per person, and per API key for traffic no person
2
+ is attributed to (`people-keys`), and people over time (`people-series`). */
3
+ import { bucketIndex, bucketStart, criteria, MODEL, readActivityQuery, readSourceScope, sourceProtocols, validatedBucketFilters, validatedFilters, } from "./filters.js";
4
+ import { badRequest } from "./params.js";
5
+ import { and, likePattern, or, raw, sql } from "./sql.js";
6
+ import { AGENT_SESSION_KEY, IDENTITY_API_KEY, THINKING_LEVEL, thinkingLevelValue, } from "./shared.js";
7
+ import { decimalText, formatInstant, readInstant, readInt, readOptionalInstant, readOptionalString, } from "./values.js";
8
+ const PEOPLE_KEYS_DEFAULT_LIMIT = 20;
9
+ const PEOPLE_KEYS_MAX_LIMIT = 100;
10
+ const PEOPLE_COMPARISON_MAX_USERS = 10;
11
+ const DEFAULT_COMPARISON_USERS = 3;
12
+ const IDENTITY_SCOPES = ["all", "people", "keys"];
13
+ const IDENTITY_SORTS = ["identity", "keys", "conversations", "messages", "tokens", "spend", "last_active"];
14
+ const SORT_DIRECTIONS = ["asc", "desc"];
15
+ export const peopleKeys = async (request) => {
16
+ const { params, db } = request;
17
+ const search = params.string("search", { maxLength: 200 }) ?? "";
18
+ const scope = params.literal("identity_scope", IDENTITY_SCOPES, "all");
19
+ const sortBy = params.literal("sort_by", IDENTITY_SORTS, "last_active");
20
+ const direction = params.literal("sort_direction", SORT_DIRECTIONS, "desc");
21
+ const limit = params.int("limit", { default: PEOPLE_KEYS_DEFAULT_LIMIT, ge: 1, le: PEOPLE_KEYS_MAX_LIMIT });
22
+ const offset = params.int("offset", { default: 0, ge: 0 });
23
+ const sourceScope = readSourceScope(params);
24
+ const query = readActivityQuery(params);
25
+ params.done();
26
+ const protocols = sourceProtocols(sourceScope);
27
+ const organizationId = request.admitted();
28
+ const filters = validatedFilters(query, protocols);
29
+ const { identities, identityCount } = await loadIdentityPage(db, organizationId, filters, {
30
+ search: search.trim(),
31
+ scope,
32
+ sortBy,
33
+ direction,
34
+ limit,
35
+ offset,
36
+ });
37
+ const nextOffset = offset + identities.length;
38
+ return {
39
+ from_at: formatInstant(filters.start),
40
+ to_at: formatInstant(filters.end),
41
+ identities,
42
+ identity_count: identityCount,
43
+ limit,
44
+ offset,
45
+ next_offset: nextOffset < identityCount ? nextOffset : null,
46
+ };
47
+ };
48
+ export const peopleSeries = async (request) => {
49
+ const { params, db } = request;
50
+ const bucketSeconds = params.int("bucket_seconds", { ge: 60 });
51
+ const requested = params.strings("comparison_user_id");
52
+ const sourceScope = readSourceScope(params);
53
+ const query = readActivityQuery(params);
54
+ params.done();
55
+ const protocols = sourceProtocols(sourceScope);
56
+ const organizationId = request.admitted();
57
+ const filters = validatedBucketFilters(query, protocols, bucketSeconds);
58
+ const userIds = validatedComparisonUserIds(requested);
59
+ const where = criteria(db, organizationId, filters);
60
+ const bucket = bucketIndex(db, filters);
61
+ const activeRows = await db.all(sql `
62
+ select
63
+ ${bucket} as bucket_index,
64
+ count(distinct r.attributed_user_id) as active_people
65
+ from routing_requests r
66
+ where ${where}
67
+ and r.attributed_user_id is not null
68
+ group by 1
69
+ order by 1`);
70
+ if (userIds.length === 0) {
71
+ const busiest = await db.all(sql `
72
+ select r.attributed_user_id
73
+ from routing_requests r
74
+ where ${where}
75
+ and r.attributed_user_id is not null
76
+ group by r.attributed_user_id
77
+ order by count(*) desc, r.attributed_user_id
78
+ limit ${DEFAULT_COMPARISON_USERS}`);
79
+ userIds.push(...busiest.map((row) => String(row.attributed_user_id)));
80
+ }
81
+ const users = await loadComparisonUsers(db, userIds);
82
+ const compared = users.map((user) => user.id);
83
+ const peopleSeries = [];
84
+ if (compared.length > 0) {
85
+ const points = await db.all(sql `
86
+ select
87
+ ${bucket} as bucket_index,
88
+ r.attributed_user_id,
89
+ count(*) filter (where r.request_kind = 'user_message') as messages_sent,
90
+ count(*) as model_steps,
91
+ coalesce(sum(r.provider_total_tokens), 0) as total_tokens,
92
+ cast(sum(r.provider_total_cost_usd) as text) as provider_spend
93
+ from routing_requests r
94
+ where ${where}
95
+ and r.attributed_user_id in (${compared})
96
+ group by 1, 2
97
+ order by 1, 2`);
98
+ const counts = await db.all(sql `
99
+ select
100
+ d.bucket_index,
101
+ d.attributed_user_id,
102
+ count(*) as conversations
103
+ from (
104
+ select distinct
105
+ ${bucket} as bucket_index,
106
+ r.attributed_user_id,
107
+ r.router_id,
108
+ r.api_key_id,
109
+ r.source_protocol,
110
+ ${AGENT_SESSION_KEY} as conversation_marker
111
+ from routing_requests r
112
+ where ${where}
113
+ and r.attributed_user_id in (${compared})
114
+ ) d
115
+ group by d.bucket_index, d.attributed_user_id`);
116
+ const conversations = new Map(counts.map((row) => [`${readInt(row.bucket_index)}\0${row.attributed_user_id}`, readInt(row.conversations)]));
117
+ for (const row of points) {
118
+ peopleSeries.push({
119
+ bucket_start: bucketStart(filters, row.bucket_index),
120
+ user_id: String(row.attributed_user_id),
121
+ messages_sent: readInt(row.messages_sent),
122
+ model_steps: readInt(row.model_steps),
123
+ conversations: conversations.get(`${readInt(row.bucket_index)}\0${row.attributed_user_id}`) ?? 0,
124
+ provider_total_tokens: readInt(row.total_tokens),
125
+ provider_spend_usd: decimalText(row.provider_spend),
126
+ });
127
+ }
128
+ }
129
+ return {
130
+ from_at: formatInstant(filters.start),
131
+ to_at: formatInstant(filters.end),
132
+ bucket_seconds: filters.bucketSeconds,
133
+ active_people_series: activeRows.map((row) => ({
134
+ bucket_start: bucketStart(filters, row.bucket_index),
135
+ active_people: readInt(row.active_people),
136
+ })),
137
+ comparison_users: users,
138
+ people_series: peopleSeries,
139
+ };
140
+ };
141
+ function validatedComparisonUserIds(ids) {
142
+ const unique = [...new Set(ids)];
143
+ if (unique.length > PEOPLE_COMPARISON_MAX_USERS) {
144
+ throw badRequest(`Select at most ${PEOPLE_COMPARISON_MAX_USERS} people to compare.`);
145
+ }
146
+ if (unique.some((id) => id === "" || [...id].length > 200)) {
147
+ throw badRequest("Comparison user IDs must contain 1 to 200 characters.");
148
+ }
149
+ return unique;
150
+ }
151
+ /** The requested people who exist, in the requested order. */
152
+ async function loadComparisonUsers(db, userIds) {
153
+ if (userIds.length === 0)
154
+ return [];
155
+ const ids = [...new Set(userIds)].slice(0, PEOPLE_COMPARISON_MAX_USERS);
156
+ const rows = await db.all(sql `select id, display_name, email from users where id in (${ids})`);
157
+ const byId = new Map(rows.map((row) => [String(row.id), row]));
158
+ return ids.flatMap((id) => {
159
+ const user = byId.get(id);
160
+ if (user === undefined)
161
+ return [];
162
+ const email = String(user.email);
163
+ return [{ id, name: user.display_name || email, email }];
164
+ });
165
+ }
166
+ const IDENTITY_NAME = sql `coalesce(u.display_name, u.email, k.label, 'Unattributed')`;
167
+ const SORTS = {
168
+ identity: sql `lower(${IDENTITY_NAME})`,
169
+ keys: sql `s.api_key_count`,
170
+ conversations: sql `coalesce(c.conversations, 0)`,
171
+ messages: sql `s.messages_sent`,
172
+ tokens: sql `s.total_tokens`,
173
+ spend: sql `coalesce(s.provider_spend, 0)`,
174
+ last_active: sql `s.latest_at`,
175
+ };
176
+ /** The in-memory key of an identity: a person, an unassigned key, or neither. */
177
+ function identityKey(userId, apiKeyId) {
178
+ if (userId !== null)
179
+ return `person\0${userId}`;
180
+ if (apiKeyId !== null)
181
+ return `api_key\0${apiKeyId}`;
182
+ return "api_key";
183
+ }
184
+ async function loadIdentityPage(db, organizationId, filters, query) {
185
+ const where = criteria(db, organizationId, filters);
186
+ const conditions = [];
187
+ if (query.scope === "people")
188
+ conditions.push(sql `s.attributed_user_id is not null`);
189
+ if (query.scope === "keys")
190
+ conditions.push(sql `s.attributed_user_id is null`);
191
+ if (query.search)
192
+ conditions.push(searchCriterion(where, organizationId, query.search));
193
+ // `s`: each identity's totals. `c`: each identity's conversations.
194
+ const statement = sql `
195
+ with s as (
196
+ select
197
+ r.attributed_user_id,
198
+ ${IDENTITY_API_KEY} as identity_api_key_id,
199
+ count(*) filter (where r.request_kind = 'user_message') as messages_sent,
200
+ count(*) as model_steps,
201
+ count(distinct r.api_key_id) as api_key_count,
202
+ coalesce(sum(r.provider_total_tokens), 0) as total_tokens,
203
+ coalesce(sum(r.provider_cache_read_tokens), 0) as cache_read_tokens,
204
+ sum(r.provider_total_cost_usd) as provider_spend,
205
+ max(r.received_at) as latest_at
206
+ from routing_requests r
207
+ where ${where}
208
+ group by r.attributed_user_id, ${IDENTITY_API_KEY}
209
+ ),
210
+ c as (
211
+ select
212
+ d.attributed_user_id,
213
+ d.identity_api_key_id,
214
+ count(*) as conversations
215
+ from (
216
+ select distinct
217
+ r.attributed_user_id,
218
+ ${IDENTITY_API_KEY} as identity_api_key_id,
219
+ r.router_id,
220
+ r.api_key_id,
221
+ r.source_protocol,
222
+ ${AGENT_SESSION_KEY} as conversation_marker
223
+ from routing_requests r
224
+ where ${where}
225
+ ) d
226
+ group by d.attributed_user_id, d.identity_api_key_id
227
+ )
228
+ select
229
+ s.attributed_user_id,
230
+ s.identity_api_key_id,
231
+ s.messages_sent,
232
+ s.model_steps,
233
+ s.total_tokens,
234
+ s.cache_read_tokens,
235
+ cast(s.provider_spend as text) as provider_spend,
236
+ cast(s.latest_at as text) as latest_at,
237
+ coalesce(c.conversations, 0) as conversations,
238
+ ${IDENTITY_NAME} as identity_name,
239
+ u.email as user_email
240
+ from s
241
+ left join users u on u.id = s.attributed_user_id
242
+ left join organization_api_keys k on k.id = s.identity_api_key_id
243
+ left join c
244
+ on (s.attributed_user_id = c.attributed_user_id
245
+ or (s.attributed_user_id is null and c.attributed_user_id is null))
246
+ and (s.identity_api_key_id = c.identity_api_key_id
247
+ or (s.identity_api_key_id is null and c.identity_api_key_id is null))
248
+ where ${and(conditions)}`;
249
+ const [countRow] = await db.all(sql `select count(*) as count from (${statement}) page`);
250
+ const identityCount = readInt(countRow?.count);
251
+ const rows = await db.all(sql `
252
+ ${statement}
253
+ order by
254
+ ${SORTS[query.sortBy]} ${raw(query.direction)},
255
+ lower(${IDENTITY_NAME}),
256
+ coalesce(s.attributed_user_id, s.identity_api_key_id, '')
257
+ limit ${query.limit} offset ${query.offset}`);
258
+ if (rows.length === 0)
259
+ return { identities: [], identityCount };
260
+ const page = rows.map((row) => ({
261
+ row,
262
+ userId: readOptionalString(row.attributed_user_id),
263
+ apiKeyId: readOptionalString(row.identity_api_key_id),
264
+ }));
265
+ const pageWhere = sql `${where} and ${pageIdentityCriterion(page)}`;
266
+ const mix = await identityModelMix(db, pageWhere);
267
+ const usage = await identityKeyUsage(db, pageWhere);
268
+ const keys = await loadApiKeys(db, organizationId, new Set([...usage.values()].flatMap((used) => [...used.keys()])));
269
+ const identities = page.map(({ row, userId, apiKeyId }) => {
270
+ const key = identityKey(userId, apiKeyId);
271
+ const used = usage.get(key) ?? new Map();
272
+ const apiKeys = [...used.keys()]
273
+ .filter((id) => keys.has(id))
274
+ .map((id) => ({ ...keys.get(id), model_steps: used.get(id) }))
275
+ .sort((a, b) => compareText(a.label.toLowerCase(), b.label.toLowerCase()) || compareText(a.id, b.id));
276
+ return {
277
+ id: userId !== null ? `person:${userId}` : apiKeyId !== null ? `key:${apiKeyId}` : "unattributed",
278
+ identity_type: userId !== null ? "person" : "api_key",
279
+ user_id: userId,
280
+ api_key_id: apiKeyId,
281
+ name: String(row.identity_name),
282
+ email: readOptionalString(row.user_email),
283
+ api_keys: apiKeys,
284
+ conversations: readInt(row.conversations),
285
+ messages_sent: readInt(row.messages_sent),
286
+ model_steps: readInt(row.model_steps),
287
+ provider_total_tokens: readInt(row.total_tokens),
288
+ provider_cache_read_tokens: readInt(row.cache_read_tokens),
289
+ provider_spend_usd: decimalText(row.provider_spend),
290
+ latest_at: formatInstant(readInstant(row.latest_at)),
291
+ model_mix: mix.get(key) ?? [],
292
+ };
293
+ });
294
+ return { identities, identityCount };
295
+ }
296
+ /** Name, email, IDs, or any API key (ID, label, prefix) the identity used. */
297
+ function searchCriterion(where, organizationId, search) {
298
+ const pattern = likePattern(search);
299
+ const matchingKeys = sql `
300
+ select k2.id
301
+ from organization_api_keys k2
302
+ where k2.organization_id = ${organizationId}
303
+ and (
304
+ lower(k2.id) like ${pattern} escape '/'
305
+ or lower(k2.label) like ${pattern} escape '/'
306
+ or lower(k2.key_prefix) like ${pattern} escape '/'
307
+ )`;
308
+ return sql `
309
+ lower(${IDENTITY_NAME}) like ${pattern} escape '/'
310
+ or lower(u.email) like ${pattern} escape '/'
311
+ or lower(s.attributed_user_id) like ${pattern} escape '/'
312
+ or lower(s.identity_api_key_id) like ${pattern} escape '/'
313
+ or s.attributed_user_id in (
314
+ select distinct r.attributed_user_id
315
+ from routing_requests r
316
+ where ${where}
317
+ and r.attributed_user_id is not null
318
+ and r.api_key_id in (${matchingKeys})
319
+ )
320
+ or (s.attributed_user_id is null and s.identity_api_key_id in (${matchingKeys}))`;
321
+ }
322
+ /** The steps of the identities on the page. */
323
+ function pageIdentityCriterion(page) {
324
+ const people = page.flatMap(({ userId }) => (userId === null ? [] : [userId]));
325
+ const keys = page.flatMap(({ userId, apiKeyId }) => (userId === null && apiKeyId !== null ? [apiKeyId] : []));
326
+ const conditions = [];
327
+ if (people.length > 0)
328
+ conditions.push(sql `r.attributed_user_id in (${people})`);
329
+ if (keys.length > 0)
330
+ conditions.push(sql `r.attributed_user_id is null and r.api_key_id in (${keys})`);
331
+ if (page.some(({ userId, apiKeyId }) => userId === null && apiKeyId === null)) {
332
+ conditions.push(sql `r.attributed_user_id is null and r.api_key_id is null`);
333
+ }
334
+ return or(conditions);
335
+ }
336
+ async function identityModelMix(db, where) {
337
+ const rows = await db.all(sql `
338
+ select
339
+ r.attributed_user_id,
340
+ ${IDENTITY_API_KEY} as identity_api_key_id,
341
+ ${MODEL} as model,
342
+ ${THINKING_LEVEL} as thinking_level,
343
+ r.selected_provider,
344
+ count(*) as model_steps
345
+ from routing_requests r
346
+ where ${where}
347
+ group by 1, 2, 3, 4, 5`);
348
+ const grouped = new Map();
349
+ for (const row of rows) {
350
+ const key = identityKey(readOptionalString(row.attributed_user_id), readOptionalString(row.identity_api_key_id));
351
+ const mix = grouped.get(key) ?? [];
352
+ mix.push({
353
+ model: String(row.model),
354
+ thinking_level: thinkingLevelValue(row.thinking_level),
355
+ provider: readOptionalString(row.selected_provider),
356
+ model_steps: readInt(row.model_steps),
357
+ });
358
+ grouped.set(key, mix);
359
+ }
360
+ for (const mix of grouped.values()) {
361
+ mix.sort((a, b) => b.model_steps - a.model_steps
362
+ || compareText(a.model, b.model)
363
+ || compareText(a.thinking_level ?? "", b.thinking_level ?? "")
364
+ || compareText(a.provider ?? "", b.provider ?? ""));
365
+ }
366
+ return grouped;
367
+ }
368
+ /** Model steps per identity and the API key it used. */
369
+ async function identityKeyUsage(db, where) {
370
+ const rows = await db.all(sql `
371
+ select
372
+ r.attributed_user_id,
373
+ ${IDENTITY_API_KEY} as identity_api_key_id,
374
+ r.api_key_id,
375
+ count(*) as model_steps
376
+ from routing_requests r
377
+ where ${where}
378
+ and r.api_key_id is not null
379
+ group by 1, 2, 3`);
380
+ const usage = new Map();
381
+ for (const row of rows) {
382
+ const key = identityKey(readOptionalString(row.attributed_user_id), readOptionalString(row.identity_api_key_id));
383
+ const used = usage.get(key) ?? new Map();
384
+ used.set(String(row.api_key_id), readInt(row.model_steps));
385
+ usage.set(key, used);
386
+ }
387
+ return usage;
388
+ }
389
+ /** The organization's keys among `ids`, with their status now. */
390
+ async function loadApiKeys(db, organizationId, ids) {
391
+ const keys = new Map();
392
+ if (ids.size === 0)
393
+ return keys;
394
+ const rows = await db.all(sql `
395
+ select id, label, key_prefix, expires_at, revoked_at
396
+ from organization_api_keys
397
+ where organization_id = ${organizationId}
398
+ and id in (${[...ids]})`);
399
+ const now = Date.now() * 1000;
400
+ for (const row of rows) {
401
+ const expiresAt = readOptionalInstant(row.expires_at);
402
+ const status = row.revoked_at !== null && row.revoked_at !== undefined
403
+ ? "revoked"
404
+ : expiresAt !== null && expiresAt <= now ? "expired" : "active";
405
+ const id = String(row.id);
406
+ keys.set(id, { id, label: String(row.label), key_prefix: String(row.key_prefix), status });
407
+ }
408
+ return keys;
409
+ }
410
+ /** Python's string order, by code point. */
411
+ function compareText(a, b) {
412
+ return a < b ? -1 : a > b ? 1 : 0;
413
+ }
@@ -0,0 +1,2 @@
1
+ import type { ActivityRoute } from "./http.js";
2
+ export declare const ACTIVITY_ROUTES: ReadonlyArray<readonly [string, ActivityRoute]>;
@@ -0,0 +1,23 @@
1
+ /* Every Activity route, by its path under `/routing/activity/`. */
2
+ import { filterOptions, models, overview, routers, series } from "./core.js";
3
+ import { conversation, conversations, payload, toolExchanges } from "./conversations.js";
4
+ import { peopleKeys, peopleSeries } from "./people.js";
5
+ import { toolSkillDetail, toolSkillInventory, toolSkills } from "./tools.js";
6
+ export const ACTIVITY_ROUTES = [
7
+ ["filter-options", filterOptions],
8
+ ["overview", overview],
9
+ ["series", series],
10
+ ["routers", routers],
11
+ ["models", models],
12
+ ["people-keys", peopleKeys],
13
+ ["people-series", peopleSeries],
14
+ ["conversations", conversations],
15
+ ["conversations/:conversation_ref", conversation],
16
+ ["requests/:request_id/client-request", payload("client_request")],
17
+ ["requests/:request_id/selector-output", payload("selector_output")],
18
+ ["requests/:request_id/client-response", payload("client_response")],
19
+ ["tool-exchanges", toolExchanges],
20
+ ["tools-skills", toolSkills],
21
+ ["tools-skills/detail", toolSkillDetail],
22
+ ["tools-skills/inventory", toolSkillInventory],
23
+ ];
@@ -0,0 +1,12 @@
1
+ import { type ActivityDb, type Sql } from "./sql.js";
2
+ import { type ReasoningEffort } from "./shared.js";
3
+ export type ModelSavings = {
4
+ /** Keyed by `routeKey`. */
5
+ byModel: Map<string, string>;
6
+ total: string | null;
7
+ };
8
+ export declare function routeKey(model: string, thinkingLevel: ReasoningEffort | null, provider: string): string;
9
+ /** Savings per model, thinking level, and provider, and in total. */
10
+ export declare function loadSavings(db: ActivityDb, criteria: Sql): Promise<ModelSavings>;
11
+ /** Savings per router; null for a router with a step lacking a benchmark cost. */
12
+ export declare function loadRouterSavings(db: ActivityDb, criteria: Sql): Promise<Map<string, string | null>>;
@@ -0,0 +1,102 @@
1
+ /* Savings against each router's benchmark: the persisted per-step benchmark
2
+ replay cost minus the provider spend. Activity only sums what the routing
3
+ runtime stored; it never replays a conversation. A step without a stored
4
+ benchmark model has an unknown benchmark. */
5
+ import { sql } from "./sql.js";
6
+ import { THINKING_LEVEL, thinkingLevelValue } from "./shared.js";
7
+ import { addDecimals, formatDecimal, parseDecimal, readInt, readOptionalString, subtractDecimals } from "./values.js";
8
+ const ZERO = { coefficient: 0n, exponent: 0 };
9
+ /** What a group of steps cost and what its benchmark would have. Read with `groupSavings`. */
10
+ const TOTALS = sql `
11
+ count(*) as priced_rows,
12
+ count(r.benchmark_replay_cost_usd) as estimated_rows,
13
+ cast(sum(r.benchmark_replay_cost_usd) as text) as benchmark_total,
14
+ cast(sum(r.provider_total_cost_usd) as text) as provider_total,
15
+ cast(sum(case when r.model_switched is true and r.benchmark_replay_cost_usd - r.provider_total_cost_usd < 0
16
+ then r.benchmark_replay_cost_usd - r.provider_total_cost_usd else 0 end) as text) as nonpositive_total`;
17
+ /** The steps with a known price: the ones savings counts. */
18
+ const PRICED = sql `
19
+ r.selected_model is not null
20
+ and r.selected_provider is not null
21
+ and r.provider_pricing_known is true
22
+ and r.provider_total_cost_usd is not null`;
23
+ /** A group's savings, or null when some step has no benchmark cost. */
24
+ function groupSavings(row) {
25
+ if (readInt(row.estimated_rows) !== readInt(row.priced_rows) || row.benchmark_total === null)
26
+ return null;
27
+ // A benchmark-model step's counterfactual is the step itself: only the
28
+ // overspend of switching back onto it counts.
29
+ if (readOptionalString(row.benchmark_model) === String(row.model)) {
30
+ return parseDecimal(String(row.nonpositive_total ?? 0));
31
+ }
32
+ return subtractDecimals(parseDecimal(String(row.benchmark_total)), parseDecimal(String(row.provider_total)));
33
+ }
34
+ export function routeKey(model, thinkingLevel, provider) {
35
+ return JSON.stringify([model, thinkingLevel, provider]);
36
+ }
37
+ /** Savings per model, thinking level, and provider, and in total. */
38
+ export async function loadSavings(db, criteria) {
39
+ const rows = await db.all(sql `
40
+ select
41
+ r.router_id,
42
+ r.selected_model as model,
43
+ ${THINKING_LEVEL} as thinking_level,
44
+ r.selected_provider as provider,
45
+ r.benchmark_model_id as benchmark_model,
46
+ ${TOTALS}
47
+ from routing_requests r
48
+ where ${criteria}
49
+ and ${PRICED}
50
+ group by 1, 2, 3, 4, 5`);
51
+ const byModel = new Map();
52
+ const incomplete = new Set();
53
+ let total = ZERO;
54
+ let complete = rows.length > 0;
55
+ for (const row of rows) {
56
+ const key = routeKey(String(row.model), thinkingLevelValue(row.thinking_level), String(row.provider));
57
+ const value = groupSavings(row);
58
+ if (value === null) {
59
+ complete = false;
60
+ incomplete.add(key);
61
+ continue;
62
+ }
63
+ byModel.set(key, addDecimals(byModel.get(key) ?? ZERO, value));
64
+ total = addDecimals(total, value);
65
+ }
66
+ const result = new Map();
67
+ for (const [key, value] of byModel)
68
+ if (!incomplete.has(key))
69
+ result.set(key, formatDecimal(value));
70
+ return { byModel: result, total: complete ? formatDecimal(total) : null };
71
+ }
72
+ /** Savings per router; null for a router with a step lacking a benchmark cost. */
73
+ export async function loadRouterSavings(db, criteria) {
74
+ const rows = await db.all(sql `
75
+ select
76
+ r.router_id,
77
+ r.selected_model as model,
78
+ r.benchmark_model_id as benchmark_model,
79
+ ${TOTALS}
80
+ from routing_requests r
81
+ where ${criteria}
82
+ and ${PRICED}
83
+ and r.router_id is not null
84
+ group by 1, 2, 3`);
85
+ const totals = new Map();
86
+ const incomplete = new Set();
87
+ for (const row of rows) {
88
+ const routerId = String(row.router_id);
89
+ const value = groupSavings(row);
90
+ if (value === null) {
91
+ incomplete.add(routerId);
92
+ continue;
93
+ }
94
+ totals.set(routerId, addDecimals(totals.get(routerId) ?? ZERO, value));
95
+ }
96
+ const result = new Map();
97
+ for (const [routerId, value] of totals)
98
+ result.set(routerId, incomplete.has(routerId) ? null : formatDecimal(value));
99
+ for (const routerId of incomplete)
100
+ result.set(routerId, null);
101
+ return result;
102
+ }
@@ -0,0 +1,15 @@
1
+ export declare const REASONING_EFFORTS: readonly ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
2
+ export type ReasoningEffort = (typeof REASONING_EFFORTS)[number];
3
+ /** The thinking level of the model and thinking pair that served the step. */
4
+ export declare const THINKING_LEVEL: import("./sql.js").Sql;
5
+ /** The persisted conversation ID, with blank IDs as missing. */
6
+ export declare const CONVERSATION_ID: import("./sql.js").Sql;
7
+ /** The step's conversation: harness context runs grouped under their stable agent session. */
8
+ export declare const AGENT_SESSION_KEY: import("./sql.js").Sql;
9
+ /** Unassigned traffic is attributed to its API key; a person's to the person. */
10
+ export declare const IDENTITY_API_KEY: import("./sql.js").Sql;
11
+ /** A persisted thinking level; null for an unknown one. */
12
+ export declare function thinkingLevelValue(value: unknown): ReasoningEffort | null;
13
+ export type IdentityKey = readonly ["person" | "api_key", string | null];
14
+ /** The in-memory key of an attributed Activity identity. */
15
+ export declare function identityKey(attributedUserId: string | null, identityApiKeyId: string | null): IdentityKey;
@@ -0,0 +1,26 @@
1
+ /* SQL expressions and value rules every Activity read shares. */
2
+ import { sql } from "./sql.js";
3
+ export const REASONING_EFFORTS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
4
+ /* Expressions over a `routing_requests` row under the alias `r`. */
5
+ /** The thinking level of the model and thinking pair that served the step. */
6
+ export const THINKING_LEVEL = sql `(r.decision_details ->> 'selected_reasoning_effort')`;
7
+ /** The persisted conversation ID, with blank IDs as missing. */
8
+ export const CONVERSATION_ID = sql `nullif(r.conversation_id, '')`;
9
+ /** The step's conversation: harness context runs grouped under their stable agent session. */
10
+ export const AGENT_SESSION_KEY = sql `coalesce(nullif(r.agent_session_id, ''), nullif(r.conversation_id, ''), r.id)`;
11
+ /** Unassigned traffic is attributed to its API key; a person's to the person. */
12
+ export const IDENTITY_API_KEY = sql `case when r.attributed_user_id is null then r.api_key_id else null end`;
13
+ /** A persisted thinking level; null for an unknown one. */
14
+ export function thinkingLevelValue(value) {
15
+ return typeof value === "string" && REASONING_EFFORTS.includes(value)
16
+ ? value
17
+ : null;
18
+ }
19
+ /** The in-memory key of an attributed Activity identity. */
20
+ export function identityKey(attributedUserId, identityApiKeyId) {
21
+ if (attributedUserId !== null)
22
+ return ["person", attributedUserId];
23
+ if (identityApiKeyId !== null)
24
+ return ["api_key", identityApiKeyId];
25
+ return ["api_key", null];
26
+ }
@@ -0,0 +1,52 @@
1
+ export type Dialect = "postgres" | "sqlite";
2
+ export type SqlValue = string | number | boolean | null;
3
+ /** A query or a piece of one: SQL text and the values bound into it. */
4
+ export declare class Sql {
5
+ readonly strings: readonly string[];
6
+ readonly values: readonly SqlValue[];
7
+ constructor(strings: readonly string[], values: readonly SqlValue[]);
8
+ }
9
+ /**
10
+ * Build SQL from a template. An interpolation becomes:
11
+ * - another `Sql`: its text, inlined;
12
+ * - a string, boolean, or null: a bound value;
13
+ * - an integer: its digits (`limit ${n}`), so the planner sees the number;
14
+ * - an array: its values, comma-separated, for `in (${ids})`. An empty array
15
+ * is `null`, which `in` never matches.
16
+ */
17
+ export declare function sql(strings: TemplateStringsArray, ...args: Array<Sql | SqlValue | readonly SqlValue[]>): Sql;
18
+ /**
19
+ * SQL text built at run time, such as a table alias or `asc`. Never pass it
20
+ * anything a caller sent.
21
+ */
22
+ export declare function raw(text: string): Sql;
23
+ export declare function join(parts: readonly Sql[], separator: string): Sql;
24
+ /** Every condition, as one parenthesized condition; true when there are none. */
25
+ export declare function and(conditions: readonly Sql[]): Sql;
26
+ /** Any condition, as one parenthesized condition; false when there are none. */
27
+ export declare function or(conditions: readonly Sql[]): Sql;
28
+ /**
29
+ * The pattern matching text that contains `query`, ignoring case, with `%`,
30
+ * `_`, and `/` in the query matched literally. Use it as
31
+ * `lower(x) like ${pattern} escape '/'`.
32
+ */
33
+ export declare function likePattern(query: string): Sql;
34
+ /** A database that answers Activity's queries. */
35
+ export type ActivityDb = {
36
+ readonly dialect: Dialect;
37
+ all<Row = Record<string, unknown>>(query: Sql): Promise<Row[]>;
38
+ };
39
+ export declare function compile(query: Sql, dialect: Dialect): {
40
+ text: string;
41
+ values: SqlValue[];
42
+ };
43
+ /** Postgres through Bun's client, which must be able to run `unsafe` queries. */
44
+ export declare function postgresActivityDb(client: {
45
+ unsafe(text: string, values: SqlValue[]): Promise<unknown>;
46
+ }): ActivityDb;
47
+ /** SQLite through `bun:sqlite`. */
48
+ export declare function sqliteActivityDb(database: {
49
+ query(text: string): {
50
+ all(...values: SqlValue[]): unknown[];
51
+ };
52
+ }): ActivityDb;