@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.
- package/README.md +4 -3
- package/dist/activity/conversation_detail.d.ts +2 -0
- package/dist/activity/conversation_detail.js +259 -0
- package/dist/activity/conversation_records.d.ts +129 -0
- package/dist/activity/conversation_records.js +318 -0
- package/dist/activity/conversations.d.ts +11 -0
- package/dist/activity/conversations.js +198 -0
- package/dist/activity/core.d.ts +13 -0
- package/dist/activity/core.js +613 -0
- package/dist/activity/filters.d.ts +71 -0
- package/dist/activity/filters.js +169 -0
- package/dist/activity/http.d.ts +37 -0
- package/dist/activity/http.js +109 -0
- package/dist/activity/params.d.ts +40 -0
- package/dist/activity/params.js +130 -0
- package/dist/activity/people.d.ts +3 -0
- package/dist/activity/people.js +413 -0
- package/dist/activity/routes.d.ts +2 -0
- package/dist/activity/routes.js +23 -0
- package/dist/activity/savings.d.ts +12 -0
- package/dist/activity/savings.js +102 -0
- package/dist/activity/shared.d.ts +15 -0
- package/dist/activity/shared.js +26 -0
- package/dist/activity/sql.d.ts +52 -0
- package/dist/activity/sql.js +124 -0
- package/dist/activity/tool_exchanges.d.ts +21 -0
- package/dist/activity/tool_exchanges.js +309 -0
- package/dist/activity/tool_skill_activity.d.ts +128 -0
- package/dist/activity/tool_skill_activity.js +280 -0
- package/dist/activity/tool_skill_identities.d.ts +25 -0
- package/dist/activity/tool_skill_identities.js +162 -0
- package/dist/activity/tools.d.ts +4 -0
- package/dist/activity/tools.js +68 -0
- package/dist/activity/values.d.ts +45 -0
- package/dist/activity/values.js +178 -0
- package/dist/context/interaction_fingerprint.js +11 -3
- package/dist/context/interaction_fingerprint_format.d.ts +2 -1
- package/dist/context/interaction_fingerprint_format.js +2 -0
- package/dist/http/handler.d.ts +2 -1
- package/dist/http/handler.js +6 -1
- package/dist/interaction/types.d.ts +17 -2
- package/dist/interaction/types.js +11 -0
- package/dist/link/endpoints.js +44 -53
- package/dist/platform/platform.d.ts +12 -0
- package/dist/protocol/input/anthropic_messages.js +63 -48
- package/dist/providers/pi.js +22 -3
- package/dist/providers/pi_context.js +15 -5
- package/dist/runtime/claude_code/auxiliary_routing.js +34 -3
- package/dist/runtime/prepare_routed_completion.d.ts +2 -0
- package/dist/runtime/prepare_routed_completion.js +42 -1
- package/dist/self_host/activity_store.d.ts +35 -0
- package/dist/self_host/activity_store.js +373 -0
- package/dist/self_host/main.d.ts +3 -2
- package/dist/self_host/main.js +8 -3
- package/dist/self_host/platform.d.ts +4 -2
- package/dist/self_host/platform.js +35 -3
- package/package.json +2 -2
- package/src/activity/conversation_detail.ts +283 -0
- package/src/activity/conversation_records.ts +403 -0
- package/src/activity/conversations.ts +218 -0
- package/src/activity/core.ts +678 -0
- package/src/activity/filters.ts +206 -0
- package/src/activity/http.ts +140 -0
- package/src/activity/params.ts +138 -0
- package/src/activity/people.ts +471 -0
- package/src/activity/routes.ts +26 -0
- package/src/activity/savings.ts +121 -0
- package/src/activity/shared.ts +36 -0
- package/src/activity/sql.ts +139 -0
- package/src/activity/tool_exchanges.ts +340 -0
- package/src/activity/tool_skill_activity.ts +314 -0
- package/src/activity/tool_skill_identities.ts +196 -0
- package/src/activity/tools.ts +76 -0
- package/src/activity/values.ts +197 -0
- package/src/context/interaction_fingerprint.ts +9 -3
- package/src/context/interaction_fingerprint_format.ts +6 -1
- package/src/http/handler.ts +5 -1
- package/src/interaction/types.ts +21 -11
- package/src/link/endpoints.ts +44 -54
- package/src/platform/platform.ts +12 -0
- package/src/protocol/input/anthropic_messages.ts +66 -53
- package/src/providers/pi.ts +22 -3
- package/src/providers/pi_context.ts +14 -7
- package/src/runtime/claude_code/auxiliary_routing.ts +33 -2
- package/src/runtime/prepare_routed_completion.ts +60 -2
- package/src/self_host/activity_store.ts +423 -0
- package/src/self_host/main.ts +17 -3
- package/src/self_host/platform.ts +38 -3
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
/* Tool and skill Activity: aggregates over `routing_tool_skill_events`, the
|
|
2
|
+
named tool calls, skill uses, and skill file reads found in routed
|
|
3
|
+
requests. Tools group by capability ID, skills by observed name. */
|
|
4
|
+
import { bucketIndex, bucketStart, criteria } from "./filters.js";
|
|
5
|
+
import { likePattern, raw, sql } from "./sql.js";
|
|
6
|
+
import { formatInstant, readInstant, readInt } from "./values.js";
|
|
7
|
+
import { loadDetailIdentities, loadItemIdentities, topIdentity, } from "./tool_skill_identities.js";
|
|
8
|
+
const MAX_ACTIVITY_ITEMS = 1000;
|
|
9
|
+
const DEFAULT_SERIES_COUNT = 5;
|
|
10
|
+
export const MAX_SELECTED_SERIES = 10;
|
|
11
|
+
const DEFAULT_SERIES_COVERAGE_PERCENT = 90;
|
|
12
|
+
/* Every query here reads `routing_tool_skill_events e` joined to its request
|
|
13
|
+
`routing_requests r`, filtered by `scopeCriteria`. */
|
|
14
|
+
/** What an event counts toward: a tool's capability ID, a skill's observed name. */
|
|
15
|
+
export function itemColumn(mode) {
|
|
16
|
+
return mode === "tools" ? sql `e.capability_id` : sql `e.observed_name`;
|
|
17
|
+
}
|
|
18
|
+
export function usesCount(mode) {
|
|
19
|
+
return mode === "tools"
|
|
20
|
+
? sql `count(*) filter (where e.event_type = 'tool_call')`
|
|
21
|
+
: sql `count(*) filter (where e.event_type = 'skill_use')`;
|
|
22
|
+
}
|
|
23
|
+
export const FILE_READS = sql `count(*) filter (where e.event_type = 'skill_load')`;
|
|
24
|
+
/** The scope's events: its mode's event types, on requests passing the filters. */
|
|
25
|
+
export function scopeCriteria(scope) {
|
|
26
|
+
const types = scope.mode === "tools"
|
|
27
|
+
? sql `e.event_type = 'tool_call'`
|
|
28
|
+
: sql `e.event_type in ('skill_use', 'skill_load')`;
|
|
29
|
+
return sql `${criteria(scope.db, scope.organizationId, scope.filters)} and ${types}`;
|
|
30
|
+
}
|
|
31
|
+
/** One row per item among the events matching `where`. */
|
|
32
|
+
function itemRows(mode, where) {
|
|
33
|
+
return sql `
|
|
34
|
+
select
|
|
35
|
+
${itemColumn(mode)} as capability_id,
|
|
36
|
+
max(e.observed_name) as observed_name,
|
|
37
|
+
${usesCount(mode)} as uses,
|
|
38
|
+
${FILE_READS} as file_reads,
|
|
39
|
+
cast(max(r.received_at) as text) as latest_at
|
|
40
|
+
from routing_tool_skill_events e
|
|
41
|
+
join routing_requests r on r.id = e.routing_request_id
|
|
42
|
+
where ${where}
|
|
43
|
+
group by ${itemColumn(mode)}`;
|
|
44
|
+
}
|
|
45
|
+
function readItemRow(row) {
|
|
46
|
+
return {
|
|
47
|
+
capability_id: String(row.capability_id),
|
|
48
|
+
observed_name: String(row.observed_name),
|
|
49
|
+
uses: readInt(row.uses),
|
|
50
|
+
file_reads: readInt(row.file_reads),
|
|
51
|
+
latest_at: readInstant(row.latest_at),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function itemBody(row, identities) {
|
|
55
|
+
return {
|
|
56
|
+
capability_id: row.capability_id,
|
|
57
|
+
observed_name: row.observed_name,
|
|
58
|
+
uses: row.uses,
|
|
59
|
+
file_reads: row.file_reads,
|
|
60
|
+
identity_count: identities.length,
|
|
61
|
+
top_identity: identities[0] ?? null,
|
|
62
|
+
latest_at: formatInstant(row.latest_at),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
async function items(scope, rows) {
|
|
66
|
+
const identities = await loadItemIdentities(scope, rows.map((row) => row.capability_id));
|
|
67
|
+
return rows.map((row) => itemBody(row, identities.get(row.capability_id) ?? []));
|
|
68
|
+
}
|
|
69
|
+
function metricValue(item, metric) {
|
|
70
|
+
if (metric === "uses")
|
|
71
|
+
return item.uses;
|
|
72
|
+
if (metric === "file_reads")
|
|
73
|
+
return item.file_reads;
|
|
74
|
+
return item.uses + item.file_reads;
|
|
75
|
+
}
|
|
76
|
+
export async function toolSkillActivity(scope, metric, seriesIds) {
|
|
77
|
+
const { db, filters, mode } = scope;
|
|
78
|
+
const where = scopeCriteria(scope);
|
|
79
|
+
const item = itemColumn(mode);
|
|
80
|
+
const uses = usesCount(mode);
|
|
81
|
+
const [totals] = await db.all(sql `
|
|
82
|
+
select
|
|
83
|
+
${uses} as total_uses,
|
|
84
|
+
${FILE_READS} as total_file_reads,
|
|
85
|
+
count(distinct ${item}) as total_items
|
|
86
|
+
from routing_tool_skill_events e
|
|
87
|
+
join routing_requests r on r.id = e.routing_request_id
|
|
88
|
+
where ${where}`);
|
|
89
|
+
const totalUses = readInt(totals?.total_uses);
|
|
90
|
+
const totalFileReads = readInt(totals?.total_file_reads);
|
|
91
|
+
const totalItems = readInt(totals?.total_items);
|
|
92
|
+
const [primary, secondary] = metric === "uses"
|
|
93
|
+
? [uses, FILE_READS]
|
|
94
|
+
: metric === "file_reads" ? [FILE_READS, uses] : [sql `(${uses} + ${FILE_READS})`, uses];
|
|
95
|
+
const rows = (await db.all(sql `
|
|
96
|
+
${itemRows(mode, where)}
|
|
97
|
+
order by ${primary} desc, ${secondary} desc, max(e.observed_name), ${item}
|
|
98
|
+
limit ${MAX_ACTIVITY_ITEMS}`)).map(readItemRow);
|
|
99
|
+
const itemBodies = await items(scope, rows);
|
|
100
|
+
let selected;
|
|
101
|
+
if (seriesIds.length > 0) {
|
|
102
|
+
const known = new Set(rows.map((row) => row.capability_id));
|
|
103
|
+
selected = seriesIds.filter((id) => known.has(id));
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
// The top items until they cover 90% of the metric: at least five, at most ten.
|
|
107
|
+
const total = metric === "uses" ? totalUses : metric === "file_reads" ? totalFileReads : totalUses + totalFileReads;
|
|
108
|
+
const minimum = Math.min(DEFAULT_SERIES_COUNT, rows.length);
|
|
109
|
+
selected = [];
|
|
110
|
+
let covered = 0;
|
|
111
|
+
for (const row of rows.slice(0, MAX_SELECTED_SERIES)) {
|
|
112
|
+
selected.push(row.capability_id);
|
|
113
|
+
covered += metricValue(row, metric);
|
|
114
|
+
if (selected.length < minimum)
|
|
115
|
+
continue;
|
|
116
|
+
if (covered * 100 >= total * DEFAULT_SERIES_COVERAGE_PERCENT)
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const names = new Map(rows.map((row) => [row.capability_id, row.observed_name]));
|
|
121
|
+
// Positional grouping: the bucket expression binds a value, and Postgres
|
|
122
|
+
// does not match two bound copies of it.
|
|
123
|
+
const aggregate = await db.all(sql `
|
|
124
|
+
select
|
|
125
|
+
${bucketIndex(db, filters)} as bucket_index,
|
|
126
|
+
${uses} as uses,
|
|
127
|
+
${FILE_READS} as file_reads
|
|
128
|
+
from routing_tool_skill_events e
|
|
129
|
+
join routing_requests r on r.id = e.routing_request_id
|
|
130
|
+
where ${where}
|
|
131
|
+
group by 1
|
|
132
|
+
order by 1`);
|
|
133
|
+
return {
|
|
134
|
+
from_at: formatInstant(filters.start),
|
|
135
|
+
to_at: formatInstant(filters.end),
|
|
136
|
+
bucket_seconds: filters.bucketSeconds,
|
|
137
|
+
mode,
|
|
138
|
+
total_uses: totalUses,
|
|
139
|
+
total_file_reads: totalFileReads,
|
|
140
|
+
total_items: totalItems,
|
|
141
|
+
items_truncated: totalItems > rows.length,
|
|
142
|
+
items: itemBodies,
|
|
143
|
+
series: await loadSeries(scope, selected, names),
|
|
144
|
+
aggregate_series: aggregate.map((row) => ({
|
|
145
|
+
bucket_start: bucketStart(filters, row.bucket_index),
|
|
146
|
+
uses: readInt(row.uses),
|
|
147
|
+
file_reads: readInt(row.file_reads),
|
|
148
|
+
})),
|
|
149
|
+
selected_series_ids: selected,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
async function loadSeries(scope, ids, names) {
|
|
153
|
+
if (ids.length === 0)
|
|
154
|
+
return [];
|
|
155
|
+
const item = itemColumn(scope.mode);
|
|
156
|
+
const rows = await scope.db.all(sql `
|
|
157
|
+
select
|
|
158
|
+
${bucketIndex(scope.db, scope.filters)} as bucket_index,
|
|
159
|
+
${item} as capability_id,
|
|
160
|
+
${usesCount(scope.mode)} as uses,
|
|
161
|
+
${FILE_READS} as file_reads
|
|
162
|
+
from routing_tool_skill_events e
|
|
163
|
+
join routing_requests r on r.id = e.routing_request_id
|
|
164
|
+
where ${scopeCriteria(scope)}
|
|
165
|
+
and ${item} in (${ids})
|
|
166
|
+
group by 1, 2
|
|
167
|
+
order by 1, 2`);
|
|
168
|
+
return rows.map((row) => {
|
|
169
|
+
const id = String(row.capability_id);
|
|
170
|
+
return {
|
|
171
|
+
bucket_start: bucketStart(scope.filters, row.bucket_index),
|
|
172
|
+
capability_id: id,
|
|
173
|
+
observed_name: names.get(id) ?? id,
|
|
174
|
+
uses: readInt(row.uses),
|
|
175
|
+
file_reads: readInt(row.file_reads),
|
|
176
|
+
};
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
/** One item's detail; null when it has no activity under the filters. */
|
|
180
|
+
export async function toolSkillDetail(scope, capabilityId) {
|
|
181
|
+
const { db, filters, mode } = scope;
|
|
182
|
+
const where = sql `${scopeCriteria(scope)} and ${itemColumn(mode)} = ${capabilityId}`;
|
|
183
|
+
const [found] = await db.all(itemRows(mode, where));
|
|
184
|
+
if (found === undefined)
|
|
185
|
+
return null;
|
|
186
|
+
const row = { ...readItemRow(found), capability_id: capabilityId };
|
|
187
|
+
const identities = await loadDetailIdentities(scope, capabilityId);
|
|
188
|
+
const uses = usesCount(mode);
|
|
189
|
+
const versionRows = mode !== "skills" ? [] : await db.all(sql `
|
|
190
|
+
select
|
|
191
|
+
e.skill_version,
|
|
192
|
+
${uses} as uses,
|
|
193
|
+
${FILE_READS} as file_reads,
|
|
194
|
+
cast(max(r.received_at) as text) as latest_at
|
|
195
|
+
from routing_tool_skill_events e
|
|
196
|
+
join routing_requests r on r.id = e.routing_request_id
|
|
197
|
+
where ${where}
|
|
198
|
+
group by e.skill_version
|
|
199
|
+
order by max(r.received_at) desc`);
|
|
200
|
+
const sourceRows = await db.all(sql `
|
|
201
|
+
select
|
|
202
|
+
e.evidence_source,
|
|
203
|
+
${uses} as uses,
|
|
204
|
+
${FILE_READS} as file_reads
|
|
205
|
+
from routing_tool_skill_events e
|
|
206
|
+
join routing_requests r on r.id = e.routing_request_id
|
|
207
|
+
where ${where}
|
|
208
|
+
group by e.evidence_source
|
|
209
|
+
order by count(*) desc, e.evidence_source`);
|
|
210
|
+
const originRows = mode !== "skills" ? [] : await db.all(sql `
|
|
211
|
+
select
|
|
212
|
+
e.capability_id,
|
|
213
|
+
r.source_protocol,
|
|
214
|
+
e.evidence_source,
|
|
215
|
+
${uses} as uses,
|
|
216
|
+
${FILE_READS} as file_reads
|
|
217
|
+
from routing_tool_skill_events e
|
|
218
|
+
join routing_requests r on r.id = e.routing_request_id
|
|
219
|
+
where ${where}
|
|
220
|
+
group by e.capability_id, r.source_protocol, e.evidence_source
|
|
221
|
+
order by count(*) desc, e.capability_id, r.source_protocol, e.evidence_source`);
|
|
222
|
+
const versions = versionRows.map((v) => ({
|
|
223
|
+
version: v.skill_version ?? null,
|
|
224
|
+
uses: readInt(v.uses),
|
|
225
|
+
file_reads: readInt(v.file_reads),
|
|
226
|
+
latest_at: formatInstant(readInstant(v.latest_at)),
|
|
227
|
+
}));
|
|
228
|
+
const sources = sourceRows.map((s) => ({
|
|
229
|
+
source: String(s.evidence_source),
|
|
230
|
+
uses: readInt(s.uses),
|
|
231
|
+
file_reads: readInt(s.file_reads),
|
|
232
|
+
}));
|
|
233
|
+
const origins = originRows.map((o) => ({
|
|
234
|
+
capability_id: String(o.capability_id),
|
|
235
|
+
source_protocol: String(o.source_protocol),
|
|
236
|
+
evidence_source: String(o.evidence_source),
|
|
237
|
+
uses: readInt(o.uses),
|
|
238
|
+
file_reads: readInt(o.file_reads),
|
|
239
|
+
}));
|
|
240
|
+
return {
|
|
241
|
+
from_at: formatInstant(filters.start),
|
|
242
|
+
to_at: formatInstant(filters.end),
|
|
243
|
+
bucket_seconds: filters.bucketSeconds,
|
|
244
|
+
mode,
|
|
245
|
+
item: itemBody(row, identities.map(topIdentity)),
|
|
246
|
+
series: await loadSeries(scope, [capabilityId], new Map([[capabilityId, row.observed_name]])),
|
|
247
|
+
identities: identities.map((identity) => ({ ...identity, latest_at: formatInstant(identity.latest_at) })),
|
|
248
|
+
versions,
|
|
249
|
+
sources,
|
|
250
|
+
origins,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
const INVENTORY_SORTS = {
|
|
254
|
+
name: sql `lower(observed_name)`,
|
|
255
|
+
uses: sql `uses`,
|
|
256
|
+
file_reads: sql `file_reads`,
|
|
257
|
+
latest: sql `latest_at`,
|
|
258
|
+
};
|
|
259
|
+
export async function toolSkillInventory(scope, query) {
|
|
260
|
+
const pattern = likePattern(query.search);
|
|
261
|
+
const matches = query.search
|
|
262
|
+
? sql `lower(capability_id) like ${pattern} escape '/' or lower(observed_name) like ${pattern} escape '/'`
|
|
263
|
+
: sql `true`;
|
|
264
|
+
const filtered = sql `
|
|
265
|
+
select *
|
|
266
|
+
from (${itemRows(scope.mode, scopeCriteria(scope))}) aggregate_rows
|
|
267
|
+
where ${matches}`;
|
|
268
|
+
const [count] = await scope.db.all(sql `select count(*) as total from (${filtered}) filtered_rows`);
|
|
269
|
+
const rows = (await scope.db.all(sql `
|
|
270
|
+
select *
|
|
271
|
+
from (${filtered}) filtered_rows
|
|
272
|
+
order by ${INVENTORY_SORTS[query.sortBy]} ${raw(query.sortDirection)}, capability_id
|
|
273
|
+
limit ${query.limit + 1} offset ${query.offset}`)).map(readItemRow);
|
|
274
|
+
const page = rows.slice(0, query.limit);
|
|
275
|
+
return {
|
|
276
|
+
total_items: readInt(count?.total),
|
|
277
|
+
items: await items(scope, page),
|
|
278
|
+
next_offset: rows.length > query.limit ? query.offset + query.limit : null,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type Instant } from "./values.js";
|
|
2
|
+
import { type Scope } from "./tool_skill_activity.js";
|
|
3
|
+
export type TopIdentity = {
|
|
4
|
+
id: string;
|
|
5
|
+
identity_type: "person" | "api_key";
|
|
6
|
+
name: string;
|
|
7
|
+
detail: string;
|
|
8
|
+
uses: number;
|
|
9
|
+
file_reads: number;
|
|
10
|
+
};
|
|
11
|
+
export type Identity = TopIdentity & {
|
|
12
|
+
latest_at: Instant;
|
|
13
|
+
api_keys: Array<{
|
|
14
|
+
id: string;
|
|
15
|
+
label: string;
|
|
16
|
+
key_prefix: string;
|
|
17
|
+
uses: number;
|
|
18
|
+
file_reads: number;
|
|
19
|
+
}>;
|
|
20
|
+
};
|
|
21
|
+
/** Each item's identities, most active first. */
|
|
22
|
+
export declare function loadItemIdentities(scope: Scope, capabilityIds: string[]): Promise<Map<string, TopIdentity[]>>;
|
|
23
|
+
/** One item's identities with each one's API keys, most active first. */
|
|
24
|
+
export declare function loadDetailIdentities(scope: Scope, capabilityId: string): Promise<Identity[]>;
|
|
25
|
+
export declare function topIdentity(identity: Identity): TopIdentity;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/* Who used a tool or skill: people, or the API key for unassigned traffic. */
|
|
2
|
+
import { IDENTITY_API_KEY, identityKey } from "./shared.js";
|
|
3
|
+
import { sql } from "./sql.js";
|
|
4
|
+
import { readInstant, readInt, readOptionalString } from "./values.js";
|
|
5
|
+
import { FILE_READS, itemColumn, scopeCriteria, usesCount } from "./tool_skill_activity.js";
|
|
6
|
+
/** Python's tuple sort: compare keys in order; strings by code point. */
|
|
7
|
+
function compareKeys(left, right) {
|
|
8
|
+
for (let i = 0; i < left.length; i += 1) {
|
|
9
|
+
const a = left[i];
|
|
10
|
+
const b = right[i];
|
|
11
|
+
if (a < b)
|
|
12
|
+
return -1;
|
|
13
|
+
if (a > b)
|
|
14
|
+
return 1;
|
|
15
|
+
}
|
|
16
|
+
return 0;
|
|
17
|
+
}
|
|
18
|
+
function readIdentityRow(row) {
|
|
19
|
+
return {
|
|
20
|
+
capabilityId: readOptionalString(row.capability_id),
|
|
21
|
+
userId: readOptionalString(row.attributed_user_id),
|
|
22
|
+
identityApiKeyId: readOptionalString(row.identity_api_key_id),
|
|
23
|
+
apiKeyId: readOptionalString(row.api_key_id),
|
|
24
|
+
uses: readInt(row.uses),
|
|
25
|
+
fileReads: readInt(row.file_reads),
|
|
26
|
+
latestAt: readInstant(row.latest_at),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/** Each item's identities, most active first. */
|
|
30
|
+
export async function loadItemIdentities(scope, capabilityIds) {
|
|
31
|
+
const grouped = new Map();
|
|
32
|
+
if (capabilityIds.length === 0)
|
|
33
|
+
return new Map();
|
|
34
|
+
const item = itemColumn(scope.mode);
|
|
35
|
+
const rows = (await scope.db.all(sql `
|
|
36
|
+
select
|
|
37
|
+
${item} as capability_id,
|
|
38
|
+
r.attributed_user_id,
|
|
39
|
+
${IDENTITY_API_KEY} as identity_api_key_id,
|
|
40
|
+
${usesCount(scope.mode)} as uses,
|
|
41
|
+
${FILE_READS} as file_reads,
|
|
42
|
+
cast(max(r.received_at) as text) as latest_at
|
|
43
|
+
from routing_tool_skill_events e
|
|
44
|
+
join routing_requests r on r.id = e.routing_request_id
|
|
45
|
+
where ${scopeCriteria(scope)}
|
|
46
|
+
and ${item} in (${capabilityIds})
|
|
47
|
+
group by ${item}, r.attributed_user_id, ${IDENTITY_API_KEY}`)).map(readIdentityRow);
|
|
48
|
+
const records = await identityRecords(scope, rows);
|
|
49
|
+
for (const row of rows) {
|
|
50
|
+
if (row.capabilityId === null)
|
|
51
|
+
throw new Error("Tool or skill identity query returned a missing capability ID.");
|
|
52
|
+
const list = grouped.get(row.capabilityId) ?? [];
|
|
53
|
+
list.push([summaryIdentity(row, records), row.latestAt]);
|
|
54
|
+
grouped.set(row.capabilityId, list);
|
|
55
|
+
}
|
|
56
|
+
const result = new Map();
|
|
57
|
+
for (const [capabilityId, values] of grouped) {
|
|
58
|
+
const sortKey = ([identity, latest]) => [-(identity.uses + identity.file_reads), -identity.uses, -latest, identity.name.toLowerCase(), identity.id];
|
|
59
|
+
values.sort((a, b) => compareKeys(sortKey(a), sortKey(b)));
|
|
60
|
+
result.set(capabilityId, values.map(([identity]) => identity));
|
|
61
|
+
}
|
|
62
|
+
return result;
|
|
63
|
+
}
|
|
64
|
+
/** One item's identities with each one's API keys, most active first. */
|
|
65
|
+
export async function loadDetailIdentities(scope, capabilityId) {
|
|
66
|
+
const rows = (await scope.db.all(sql `
|
|
67
|
+
select
|
|
68
|
+
r.attributed_user_id,
|
|
69
|
+
${IDENTITY_API_KEY} as identity_api_key_id,
|
|
70
|
+
r.api_key_id,
|
|
71
|
+
${usesCount(scope.mode)} as uses,
|
|
72
|
+
${FILE_READS} as file_reads,
|
|
73
|
+
cast(max(r.received_at) as text) as latest_at
|
|
74
|
+
from routing_tool_skill_events e
|
|
75
|
+
join routing_requests r on r.id = e.routing_request_id
|
|
76
|
+
where ${scopeCriteria(scope)}
|
|
77
|
+
and ${itemColumn(scope.mode)} = ${capabilityId}
|
|
78
|
+
group by r.attributed_user_id, ${IDENTITY_API_KEY}, r.api_key_id`)).map(readIdentityRow);
|
|
79
|
+
const records = await identityRecords(scope, rows);
|
|
80
|
+
const grouped = new Map();
|
|
81
|
+
for (const row of rows) {
|
|
82
|
+
const key = JSON.stringify(identityKey(row.userId, row.identityApiKeyId));
|
|
83
|
+
grouped.set(key, [...(grouped.get(key) ?? []), row]);
|
|
84
|
+
}
|
|
85
|
+
const identities = [];
|
|
86
|
+
for (const identityRows of grouped.values()) {
|
|
87
|
+
const summary = summaryIdentity(identityRows[0], records);
|
|
88
|
+
const keyed = identityRows.filter((row) => row.apiKeyId !== null && records.apiKeys.has(row.apiKeyId));
|
|
89
|
+
const keySort = (row) => [-(row.uses + row.fileReads), -row.uses, records.apiKeys.get(row.apiKeyId).label.toLowerCase(), row.apiKeyId];
|
|
90
|
+
keyed.sort((a, b) => compareKeys(keySort(a), keySort(b)));
|
|
91
|
+
identities.push({
|
|
92
|
+
id: summary.id,
|
|
93
|
+
identity_type: summary.identity_type,
|
|
94
|
+
name: summary.name,
|
|
95
|
+
detail: summary.detail,
|
|
96
|
+
uses: identityRows.reduce((total, row) => total + row.uses, 0),
|
|
97
|
+
file_reads: identityRows.reduce((total, row) => total + row.fileReads, 0),
|
|
98
|
+
latest_at: Math.max(...identityRows.map((row) => row.latestAt)),
|
|
99
|
+
api_keys: keyed.map((row) => {
|
|
100
|
+
const key = records.apiKeys.get(row.apiKeyId);
|
|
101
|
+
return { id: row.apiKeyId, label: key.label, key_prefix: key.key_prefix, uses: row.uses, file_reads: row.fileReads };
|
|
102
|
+
}),
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
const sortKey = (identity) => [-(identity.uses + identity.file_reads), -identity.uses, -identity.latest_at, identity.name.toLowerCase(), identity.id];
|
|
106
|
+
return identities.sort((a, b) => compareKeys(sortKey(a), sortKey(b)));
|
|
107
|
+
}
|
|
108
|
+
export function topIdentity(identity) {
|
|
109
|
+
return {
|
|
110
|
+
id: identity.id,
|
|
111
|
+
identity_type: identity.identity_type,
|
|
112
|
+
name: identity.name,
|
|
113
|
+
detail: identity.detail,
|
|
114
|
+
uses: identity.uses,
|
|
115
|
+
file_reads: identity.file_reads,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
async function identityRecords(scope, rows) {
|
|
119
|
+
const userIds = [...new Set(rows.flatMap((row) => (row.userId === null ? [] : [row.userId])))];
|
|
120
|
+
const apiKeyIds = [...new Set(rows.flatMap((row) => [row.identityApiKeyId, row.apiKeyId].filter((id) => id !== null)))];
|
|
121
|
+
const users = new Map();
|
|
122
|
+
const apiKeys = new Map();
|
|
123
|
+
if (userIds.length > 0) {
|
|
124
|
+
for (const user of await scope.db.all(sql `select id, display_name, email from users where id in (${userIds})`)) {
|
|
125
|
+
users.set(String(user.id), { display_name: readOptionalString(user.display_name), email: String(user.email) });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (apiKeyIds.length > 0) {
|
|
129
|
+
const keys = await scope.db.all(sql `
|
|
130
|
+
select id, label, key_prefix
|
|
131
|
+
from organization_api_keys
|
|
132
|
+
where organization_id = ${scope.organizationId}
|
|
133
|
+
and id in (${apiKeyIds})`);
|
|
134
|
+
for (const key of keys)
|
|
135
|
+
apiKeys.set(String(key.id), { label: String(key.label), key_prefix: String(key.key_prefix) });
|
|
136
|
+
}
|
|
137
|
+
return { users, apiKeys };
|
|
138
|
+
}
|
|
139
|
+
function summaryIdentity(row, records) {
|
|
140
|
+
const counts = { uses: row.uses, file_reads: row.fileReads };
|
|
141
|
+
if (row.userId !== null) {
|
|
142
|
+
const user = records.users.get(row.userId);
|
|
143
|
+
return {
|
|
144
|
+
id: `person:${row.userId}`,
|
|
145
|
+
identity_type: "person",
|
|
146
|
+
name: user ? user.display_name || user.email : "Deleted User",
|
|
147
|
+
detail: user ? user.email : "User No Longer Available",
|
|
148
|
+
...counts,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
if (row.identityApiKeyId !== null) {
|
|
152
|
+
const key = records.apiKeys.get(row.identityApiKeyId);
|
|
153
|
+
return {
|
|
154
|
+
id: `key:${row.identityApiKeyId}`,
|
|
155
|
+
identity_type: "api_key",
|
|
156
|
+
name: key ? key.label : "Deleted API Key",
|
|
157
|
+
detail: key ? `${key.key_prefix}… · Shared / Unassigned` : "API Key No Longer Available",
|
|
158
|
+
...counts,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
return { id: "unattributed", identity_type: "api_key", name: "Unattributed", detail: "No API Key Attribution", ...counts };
|
|
162
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/* Tool and skill Activity routes: `tools-skills`, its inventory, and one
|
|
2
|
+
item's detail. */
|
|
3
|
+
import { readActivityQuery, readSourceScope, sourceProtocols, validatedBucketFilters, validatedFilters } from "./filters.js";
|
|
4
|
+
import { badRequest, notFound } from "./params.js";
|
|
5
|
+
import { MAX_SELECTED_SERIES, toolSkillActivity, toolSkillDetail as loadDetail, toolSkillInventory as loadInventory, } from "./tool_skill_activity.js";
|
|
6
|
+
const MODES = ["tools", "skills"];
|
|
7
|
+
const INVENTORY_MAX_LIMIT = 100;
|
|
8
|
+
export const toolSkills = async ({ db, params, admitted }) => {
|
|
9
|
+
params.requirePresent("mode");
|
|
10
|
+
const mode = params.literal("mode", MODES) ?? "tools";
|
|
11
|
+
const bucketSeconds = params.int("bucket_seconds", { ge: 60 });
|
|
12
|
+
const scope = readSourceScope(params);
|
|
13
|
+
const metric = params.literal("series_metric", ["uses", "file_reads", "activity"], "uses");
|
|
14
|
+
const seriesIds = params.strings("series_id");
|
|
15
|
+
const query = readActivityQuery(params);
|
|
16
|
+
params.done();
|
|
17
|
+
const protocols = sourceProtocols(scope);
|
|
18
|
+
const organizationId = admitted();
|
|
19
|
+
const filters = validatedBucketFilters(query, protocols, bucketSeconds);
|
|
20
|
+
if (mode === "tools" && metric !== "uses")
|
|
21
|
+
throw badRequest("Tool series can only be ranked by uses.");
|
|
22
|
+
const ids = [...new Set(seriesIds)];
|
|
23
|
+
if (ids.length > MAX_SELECTED_SERIES)
|
|
24
|
+
throw badRequest(`Select at most ${MAX_SELECTED_SERIES} tool or skill series.`);
|
|
25
|
+
if (ids.some((id) => !id || id.length > 512))
|
|
26
|
+
throw badRequest("Tool or skill series IDs must contain 1 to 512 characters.");
|
|
27
|
+
return toolSkillActivity({ db, organizationId, filters, mode }, metric, ids);
|
|
28
|
+
};
|
|
29
|
+
export const toolSkillInventory = async ({ db, params, admitted }) => {
|
|
30
|
+
params.requirePresent("mode");
|
|
31
|
+
const mode = params.literal("mode", MODES) ?? "tools";
|
|
32
|
+
const scope = readSourceScope(params);
|
|
33
|
+
const search = params.string("search", { maxLength: 200 }) ?? "";
|
|
34
|
+
const sortBy = params.literal("sort_by", ["name", "uses", "file_reads", "latest"], "uses");
|
|
35
|
+
const sortDirection = params.literal("sort_direction", ["asc", "desc"], "desc");
|
|
36
|
+
const limit = params.int("limit", { default: 20, ge: 1, le: INVENTORY_MAX_LIMIT });
|
|
37
|
+
const offset = params.int("offset", { default: 0, ge: 0 });
|
|
38
|
+
const query = readActivityQuery(params);
|
|
39
|
+
params.done();
|
|
40
|
+
const protocols = sourceProtocols(scope);
|
|
41
|
+
const organizationId = admitted();
|
|
42
|
+
const filters = validatedFilters(query, protocols);
|
|
43
|
+
return loadInventory({ db, organizationId, filters, mode }, {
|
|
44
|
+
// Python's str.strip(): Unicode whitespace, like JavaScript's trim().
|
|
45
|
+
search: search.trim(),
|
|
46
|
+
sortBy,
|
|
47
|
+
sortDirection,
|
|
48
|
+
limit,
|
|
49
|
+
offset,
|
|
50
|
+
});
|
|
51
|
+
};
|
|
52
|
+
export const toolSkillDetail = async ({ db, params, admitted }) => {
|
|
53
|
+
params.requirePresent("mode");
|
|
54
|
+
const mode = params.literal("mode", MODES) ?? "tools";
|
|
55
|
+
params.requirePresent("capability_id");
|
|
56
|
+
const capabilityId = params.string("capability_id", { minLength: 1, maxLength: 512 }) ?? "";
|
|
57
|
+
const bucketSeconds = params.int("bucket_seconds", { ge: 60 });
|
|
58
|
+
const scope = readSourceScope(params);
|
|
59
|
+
const query = readActivityQuery(params);
|
|
60
|
+
params.done();
|
|
61
|
+
const protocols = sourceProtocols(scope);
|
|
62
|
+
const organizationId = admitted();
|
|
63
|
+
const filters = validatedBucketFilters(query, protocols, bucketSeconds);
|
|
64
|
+
const detail = await loadDetail({ db, organizationId, filters, mode }, capabilityId);
|
|
65
|
+
if (detail === null)
|
|
66
|
+
throw notFound("Tool or skill activity not found.");
|
|
67
|
+
return detail;
|
|
68
|
+
};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ActivityDb } from "./sql.js";
|
|
2
|
+
/** Microseconds since the Unix epoch, UTC. */
|
|
3
|
+
export type Instant = number;
|
|
4
|
+
export declare function instantFromDate(date: Date): Instant;
|
|
5
|
+
/**
|
|
6
|
+
* Canonical text for an instant: `YYYY-MM-DDTHH:MM:SS.ffffffZ`. Instants are
|
|
7
|
+
* bound and stored in this form, so stored text sorts in time order.
|
|
8
|
+
*/
|
|
9
|
+
export declare function canonicalInstant(instant: Instant): string;
|
|
10
|
+
/** An instant as Dari's API writes one: fractional seconds only when nonzero. */
|
|
11
|
+
export declare function formatInstant(instant: Instant): string;
|
|
12
|
+
/** A timestamp column as either database returns it. */
|
|
13
|
+
export declare function readInstant(value: unknown): Instant;
|
|
14
|
+
export declare function readOptionalInstant(value: unknown): Instant | null;
|
|
15
|
+
/**
|
|
16
|
+
* Parse a datetime as Dari's API accepts one in a query: ISO 8601 (a date
|
|
17
|
+
* alone is midnight), or Unix seconds (milliseconds above 2e10). `naive` is a
|
|
18
|
+
* value without a UTC offset; its instant reads it as UTC. Null when it is
|
|
19
|
+
* not a datetime.
|
|
20
|
+
*/
|
|
21
|
+
export declare function parseInstantText(text: string): {
|
|
22
|
+
instant: Instant;
|
|
23
|
+
naive: boolean;
|
|
24
|
+
} | null;
|
|
25
|
+
export type Decimal = {
|
|
26
|
+
coefficient: bigint;
|
|
27
|
+
exponent: number;
|
|
28
|
+
};
|
|
29
|
+
export declare function parseDecimal(value: string | number): Decimal;
|
|
30
|
+
export declare function addDecimals(left: Decimal, right: Decimal): Decimal;
|
|
31
|
+
export declare function subtractDecimals(left: Decimal, right: Decimal): Decimal;
|
|
32
|
+
export declare function compareDecimals(left: Decimal, right: Decimal): number;
|
|
33
|
+
/** Python's `str(Decimal)`. */
|
|
34
|
+
export declare function formatDecimal(value: Decimal): string;
|
|
35
|
+
/** Python's `decimal_text`: a numeric column's value as API text, or null. */
|
|
36
|
+
export declare function decimalText(value: unknown): string | null;
|
|
37
|
+
/** Add the present values to zero; null when none is present. */
|
|
38
|
+
export declare function sumDecimalText(values: readonly unknown[]): string | null;
|
|
39
|
+
export declare function readInt(value: unknown): number;
|
|
40
|
+
export declare function readOptionalInt(value: unknown): number | null;
|
|
41
|
+
export declare function readOptionalBool(value: unknown): boolean | null;
|
|
42
|
+
export declare function readBool(value: unknown): boolean;
|
|
43
|
+
/** A JSON column: Postgres returns it parsed, SQLite as its text. */
|
|
44
|
+
export declare function readJson(db: ActivityDb, value: unknown): unknown;
|
|
45
|
+
export declare function readOptionalString(value: unknown): string | null;
|