@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,124 @@
1
+ /* SQL for Activity, written once for both databases it reads: the self-hosted
2
+ gateway's SQLite and hosted Dari's Postgres. A query is a template of SQL
3
+ text and bound values; `ActivityDb` compiles it for its dialect and runs
4
+ it. Queries are written out in full, in SQL both databases accept.
5
+
6
+ Select timestamps and money as text (`cast(x as text)`): Bun reads a
7
+ Postgres timestamp as a `Date`, which drops microseconds, and a numeric
8
+ as a string that can drop its scale. Read them with `readInstant` and
9
+ `decimalText`. */
10
+ /** A query or a piece of one: SQL text and the values bound into it. */
11
+ export class Sql {
12
+ strings;
13
+ values;
14
+ constructor(strings, values) {
15
+ this.strings = strings;
16
+ this.values = values;
17
+ }
18
+ }
19
+ /**
20
+ * Build SQL from a template. An interpolation becomes:
21
+ * - another `Sql`: its text, inlined;
22
+ * - a string, boolean, or null: a bound value;
23
+ * - an integer: its digits (`limit ${n}`), so the planner sees the number;
24
+ * - an array: its values, comma-separated, for `in (${ids})`. An empty array
25
+ * is `null`, which `in` never matches.
26
+ */
27
+ export function sql(strings, ...args) {
28
+ const parts = [strings[0]];
29
+ const values = [];
30
+ const write = (text) => {
31
+ parts[parts.length - 1] += text;
32
+ };
33
+ const add = (arg) => {
34
+ if (arg instanceof Sql) {
35
+ write(arg.strings[0]);
36
+ arg.values.forEach((value, index) => {
37
+ values.push(value);
38
+ parts.push(arg.strings[index + 1]);
39
+ });
40
+ }
41
+ else if (Array.isArray(arg)) {
42
+ if (arg.length === 0)
43
+ write("null");
44
+ arg.forEach((item, index) => {
45
+ if (index > 0)
46
+ write(", ");
47
+ add(item);
48
+ });
49
+ }
50
+ else if (typeof arg === "number") {
51
+ if (!Number.isSafeInteger(arg))
52
+ throw new Error(`Not an integer: ${arg}.`);
53
+ write(String(arg));
54
+ }
55
+ else {
56
+ values.push(arg);
57
+ parts.push("");
58
+ }
59
+ };
60
+ args.forEach((arg, index) => {
61
+ add(arg);
62
+ write(strings[index + 1]);
63
+ });
64
+ return new Sql(parts, values);
65
+ }
66
+ /**
67
+ * SQL text built at run time, such as a table alias or `asc`. Never pass it
68
+ * anything a caller sent.
69
+ */
70
+ export function raw(text) {
71
+ return new Sql([text], []);
72
+ }
73
+ export function join(parts, separator) {
74
+ if (parts.length === 0)
75
+ return raw("");
76
+ return parts.reduce((joined, part) => sql `${joined}${raw(separator)}${part}`);
77
+ }
78
+ /** Every condition, as one parenthesized condition; true when there are none. */
79
+ export function and(conditions) {
80
+ return conditions.length === 0 ? sql `true` : sql `((${join(conditions, ") and (")}))`;
81
+ }
82
+ /** Any condition, as one parenthesized condition; false when there are none. */
83
+ export function or(conditions) {
84
+ return conditions.length === 0 ? sql `false` : sql `((${join(conditions, ") or (")}))`;
85
+ }
86
+ /**
87
+ * The pattern matching text that contains `query`, ignoring case, with `%`,
88
+ * `_`, and `/` in the query matched literally. Use it as
89
+ * `lower(x) like ${pattern} escape '/'`.
90
+ */
91
+ export function likePattern(query) {
92
+ const escaped = query.replace(/[/%_]/g, (character) => `/${character}`);
93
+ return sql `'%' || lower(${escaped}) || '%'`;
94
+ }
95
+ export function compile(query, dialect) {
96
+ let text = query.strings[0];
97
+ for (let i = 1; i < query.strings.length; i += 1) {
98
+ text += (dialect === "postgres" ? `$${i}` : "?") + query.strings[i];
99
+ }
100
+ const values = dialect === "sqlite"
101
+ ? query.values.map((value) => (typeof value === "boolean" ? Number(value) : value))
102
+ : [...query.values];
103
+ return { text, values };
104
+ }
105
+ /** Postgres through Bun's client, which must be able to run `unsafe` queries. */
106
+ export function postgresActivityDb(client) {
107
+ return {
108
+ dialect: "postgres",
109
+ async all(query) {
110
+ const { text, values } = compile(query, "postgres");
111
+ return [...(await client.unsafe(text, values))];
112
+ },
113
+ };
114
+ }
115
+ /** SQLite through `bun:sqlite`. */
116
+ export function sqliteActivityDb(database) {
117
+ return {
118
+ dialect: "sqlite",
119
+ async all(query) {
120
+ const { text, values } = compile(query, "sqlite");
121
+ return database.query(text).all(...values);
122
+ },
123
+ };
124
+ }
@@ -0,0 +1,21 @@
1
+ import { type ActivityFilters } from "./filters.js";
2
+ import type { ActivityRoute } from "./http.js";
3
+ import { type ActivityDb } from "./sql.js";
4
+ export declare const EXCHANGE_STATES: readonly ["matched", "unmatched_call", "orphan_result"];
5
+ export type ExchangeState = (typeof EXCHANGE_STATES)[number];
6
+ export declare const EXCHANGE_MAX_LIMIT = 200;
7
+ export type ExchangeQuery = {
8
+ states: readonly string[];
9
+ capabilityId: string | null;
10
+ requestIds: readonly string[];
11
+ includeTotal: boolean;
12
+ limit: number;
13
+ offset: number;
14
+ };
15
+ export type ExchangePage = {
16
+ total_items: number | null;
17
+ items: object[];
18
+ next_offset: number | null;
19
+ };
20
+ export declare const toolExchanges: ActivityRoute;
21
+ export declare function loadToolExchanges(db: ActivityDb, organizationId: string, filters: ActivityFilters, rawQuery: ExchangeQuery): Promise<ExchangePage>;
@@ -0,0 +1,309 @@
1
+ /* Tool exchanges: emitted tool calls matched at read time with the results
2
+ later requests submitted. A result matches the latest earlier completed,
3
+ non-ZDR call with the same exchange context and call ID on the same router,
4
+ key, and protocol. */
5
+ import { dimensionCriteria, readActivityQuery, readSourceScope, sourceProtocols, timeRange, validatedFilters, } from "./filters.js";
6
+ import { badRequest } from "./params.js";
7
+ import { join, raw, sql } from "./sql.js";
8
+ import { formatInstant, readInt, readOptionalInstant, readOptionalString } from "./values.js";
9
+ export const EXCHANGE_STATES = ["matched", "unmatched_call", "orphan_result"];
10
+ export const EXCHANGE_MAX_LIMIT = 200;
11
+ const EXCHANGE_MAX_REQUEST_IDS = 100;
12
+ export const toolExchanges = async (request) => {
13
+ const { params } = request;
14
+ const scope = readSourceScope(params);
15
+ const states = params.literals("exchange_state", EXCHANGE_STATES);
16
+ const capabilityId = params.string("capability_id", { maxLength: 512 }) ?? null;
17
+ const requestIds = params.strings("request_id");
18
+ const includeTotal = params.bool("include_total", true);
19
+ const limit = params.int("limit", { default: 50, ge: 1, le: EXCHANGE_MAX_LIMIT });
20
+ const offset = params.int("offset", { default: 0, ge: 0 });
21
+ const query = readActivityQuery(params);
22
+ params.done();
23
+ const protocols = sourceProtocols(scope);
24
+ if (requestIds.length > EXCHANGE_MAX_REQUEST_IDS) {
25
+ throw badRequest(`Select at most ${EXCHANGE_MAX_REQUEST_IDS} routing request IDs.`);
26
+ }
27
+ const organizationId = request.admitted();
28
+ const filters = validatedFilters(query, protocols);
29
+ return loadToolExchanges(request.db, organizationId, filters, {
30
+ states: states ?? (capabilityId !== null ? ["matched", "unmatched_call"] : EXCHANGE_STATES),
31
+ capabilityId,
32
+ requestIds,
33
+ includeTotal,
34
+ limit,
35
+ offset,
36
+ });
37
+ };
38
+ function validatedQuery(query) {
39
+ const states = [...new Set(query.states)];
40
+ const unsupported = states.filter((state) => !EXCHANGE_STATES.includes(state));
41
+ if (unsupported.length > 0)
42
+ throw badRequest(`Unsupported tool exchange state: ${unsupported.sort().join(", ")}.`);
43
+ if (states.length === 0)
44
+ throw badRequest("Select at least one tool exchange state.");
45
+ if (query.limit < 1 || query.limit > EXCHANGE_MAX_LIMIT) {
46
+ throw badRequest(`Tool exchange page limit must be between 1 and ${EXCHANGE_MAX_LIMIT}.`);
47
+ }
48
+ if (query.offset < 0)
49
+ throw badRequest("Tool exchange page offset must be non-negative.");
50
+ const capabilityId = query.capabilityId ? query.capabilityId.trim() : null;
51
+ if (capabilityId !== null && [...capabilityId].length > 512) {
52
+ throw badRequest("Tool exchange capability IDs cannot exceed 512 characters.");
53
+ }
54
+ if (capabilityId !== null && states.includes("orphan_result")) {
55
+ throw badRequest("Capability-scoped tool exchanges cannot include orphan results.");
56
+ }
57
+ const requestIds = [...new Set(query.requestIds)];
58
+ if (requestIds.length > EXCHANGE_MAX_REQUEST_IDS) {
59
+ throw badRequest(`Select at most ${EXCHANGE_MAX_REQUEST_IDS} routing request IDs.`);
60
+ }
61
+ if (requestIds.some((id) => id === "" || [...id].length > 128)) {
62
+ throw badRequest("Routing request IDs must contain 1 to 128 characters.");
63
+ }
64
+ return { ...query, states, capabilityId, requestIds };
65
+ }
66
+ export async function loadToolExchanges(db, organizationId, filters, rawQuery) {
67
+ const query = validatedQuery(rawQuery);
68
+ // Named requests scope the read to themselves and the other side of their
69
+ // exchanges, in any time range.
70
+ const ids = query.requestIds;
71
+ const named = ids.length > 0;
72
+ const yes = sql `true`;
73
+ const ofCapability = (alias) => query.capabilityId === null ? yes : sql `${raw(alias)}.capability_id = ${query.capabilityId}`;
74
+ /** The named requests, or the requests in the time range. */
75
+ const inScope = (alias) => (named ? sql `${raw(alias)}.id in (${ids})` : timeRange(db, filters, alias));
76
+ // The results the named requests observed, and the results of the calls they made.
77
+ const requested = !named ? sql `` : sql `
78
+ requested_tool_call_pairs as (
79
+ select distinct
80
+ ce.exchange_context_hash,
81
+ ce.tool_call_id
82
+ from routing_tool_skill_events ce
83
+ join routing_requests cr on cr.id = ce.routing_request_id
84
+ where cr.id in (${ids})
85
+ and cr.organization_id = ${organizationId}
86
+ and ce.event_type = 'tool_call'
87
+ and ce.exchange_context_hash is not null
88
+ and ce.tool_call_id is not null
89
+ ),
90
+ request_scoped_tool_result_ids as (
91
+ select o.id as result_observation_id
92
+ from routing_tool_result_observations o
93
+ join routing_requests dr on dr.id = o.routing_request_id
94
+ where dr.organization_id = ${organizationId}
95
+ and dr.id in (${ids})
96
+ union
97
+ select o.id
98
+ from requested_tool_call_pairs p
99
+ join routing_tool_result_observations o
100
+ on o.exchange_context_hash = p.exchange_context_hash and o.tool_call_id = p.tool_call_id
101
+ join routing_requests xr on xr.id = o.routing_request_id
102
+ where xr.organization_id = ${organizationId}
103
+ ),`;
104
+ // Each result with the call it answers: the latest earlier completed call
105
+ // with its exchange context and call ID, on its router, key, and protocol.
106
+ const matches = sql `
107
+ select
108
+ o.id as result_observation_id,
109
+ (
110
+ select ce.id
111
+ from routing_tool_skill_events ce
112
+ join routing_requests cr on cr.id = ce.routing_request_id
113
+ where ce.event_type = 'tool_call'
114
+ and ${ofCapability("ce")}
115
+ and ce.exchange_context_hash is not null
116
+ and ce.tool_call_id is not null
117
+ and ce.exchange_context_hash = o.exchange_context_hash
118
+ and ce.tool_call_id = o.tool_call_id
119
+ and cr.organization_id = rr.organization_id
120
+ and cr.router_id = rr.router_id
121
+ and (cr.api_key_id = rr.api_key_id or (cr.api_key_id is null and rr.api_key_id is null))
122
+ and cr.source_protocol = rr.source_protocol
123
+ and cr.zdr is false
124
+ and cr.completed_at is not null
125
+ and cr.completed_at <= rr.received_at
126
+ order by cr.completed_at desc, cr.id desc, ce.id desc
127
+ limit 1
128
+ ) as call_event_id
129
+ from routing_tool_result_observations o
130
+ join routing_requests rr on rr.id = o.routing_request_id
131
+ ${named ? sql `join request_scoped_tool_result_ids scoped on scoped.result_observation_id = o.id` : sql ``}
132
+ where rr.organization_id = ${organizationId}
133
+ and ${named ? yes : timeRange(db, filters, "rr")}
134
+ and rr.source_protocol in (${filters.protocols})
135
+ and rr.zdr is false`;
136
+ // One select per state, with the same columns: `e` and `cr` are the call
137
+ // and its request, `o` and `rr` the result and its request.
138
+ const matched = sql `
139
+ select
140
+ cast('matched' as text) as state,
141
+ e.tool_call_id,
142
+ e.capability_id,
143
+ e.observed_name,
144
+ cr.source_protocol,
145
+ cr.router_id,
146
+ cr.api_key_id,
147
+ e.id as call_event_id,
148
+ cr.id as call_request_id,
149
+ cr.received_at as call_received_at,
150
+ cr.completed_at as call_completed_at,
151
+ o.id as result_observation_id,
152
+ rr.id as result_request_id,
153
+ rr.received_at as result_observed_at,
154
+ rr.received_at as activity_at
155
+ from selected_tool_result_matches s
156
+ join routing_tool_result_observations o on o.id = s.result_observation_id
157
+ join routing_requests rr on rr.id = o.routing_request_id
158
+ join routing_tool_skill_events e on e.id = s.call_event_id
159
+ join routing_requests cr on cr.id = e.routing_request_id
160
+ where ${dimensionCriteria(filters, "cr")}
161
+ and ${ofCapability("e")}
162
+ and ${named ? sql `(cr.id in (${ids}) or rr.id in (${ids}))` : yes}`;
163
+ const unmatchedCalls = sql `
164
+ select
165
+ cast('unmatched_call' as text) as state,
166
+ e.tool_call_id,
167
+ e.capability_id,
168
+ e.observed_name,
169
+ cr.source_protocol,
170
+ cr.router_id,
171
+ cr.api_key_id,
172
+ e.id as call_event_id,
173
+ cr.id as call_request_id,
174
+ cr.received_at as call_received_at,
175
+ cr.completed_at as call_completed_at,
176
+ cast(null as text) as result_observation_id,
177
+ cast(null as text) as result_request_id,
178
+ cast(null as timestamptz) as result_observed_at,
179
+ cr.received_at as activity_at
180
+ from routing_tool_skill_events e
181
+ join routing_requests cr on cr.id = e.routing_request_id
182
+ where e.event_type = 'tool_call'
183
+ and cr.organization_id = ${organizationId}
184
+ and ${inScope("cr")}
185
+ and cr.source_protocol in (${filters.protocols})
186
+ and cr.zdr is false
187
+ and ${ofCapability("e")}
188
+ and not exists (select 1 from selected_tool_result_matches s where s.call_event_id = e.id)
189
+ and ${dimensionCriteria(filters, "cr")}`;
190
+ const orphanResults = sql `
191
+ select
192
+ cast('orphan_result' as text) as state,
193
+ o.tool_call_id,
194
+ cast(null as text) as capability_id,
195
+ cast(null as text) as observed_name,
196
+ rr.source_protocol,
197
+ rr.router_id,
198
+ rr.api_key_id,
199
+ cast(null as text) as call_event_id,
200
+ cast(null as text) as call_request_id,
201
+ cast(null as timestamptz) as call_received_at,
202
+ cast(null as timestamptz) as call_completed_at,
203
+ o.id as result_observation_id,
204
+ rr.id as result_request_id,
205
+ rr.received_at as result_observed_at,
206
+ rr.received_at as activity_at
207
+ from routing_tool_result_observations o
208
+ join routing_requests rr on rr.id = o.routing_request_id
209
+ where rr.organization_id = ${organizationId}
210
+ and ${inScope("rr")}
211
+ and rr.source_protocol in (${filters.protocols})
212
+ and rr.zdr is false
213
+ and not exists (
214
+ select 1
215
+ from selected_tool_result_matches s
216
+ where s.result_observation_id = o.id and s.call_event_id is not null
217
+ )
218
+ and ${dimensionCriteria(filters, "rr")}`;
219
+ const states = [];
220
+ if (query.states.includes("matched"))
221
+ states.push(matched);
222
+ if (query.states.includes("unmatched_call"))
223
+ states.push(unmatchedCalls);
224
+ if (query.states.includes("orphan_result"))
225
+ states.push(orphanResults);
226
+ // The page, with the total on each of its rows; the total alone when the
227
+ // page is empty.
228
+ const order = sql `
229
+ activity_at desc, state, tool_call_id nulls last, call_event_id nulls last, result_observation_id nulls last`;
230
+ const rows = await db.all(sql `
231
+ with ${requested}
232
+ selected_tool_result_matches as (${matches}),
233
+ tool_exchange_rows as (${join(states, " union all ")}),
234
+ tool_exchange_page as (
235
+ select *
236
+ from tool_exchange_rows
237
+ order by ${order}
238
+ limit ${query.limit + 1} offset ${query.offset}
239
+ ),
240
+ tool_exchange_totals as (
241
+ select count(*) as total_items
242
+ from tool_exchange_rows
243
+ )
244
+ select
245
+ p.state,
246
+ p.tool_call_id,
247
+ p.capability_id,
248
+ p.observed_name,
249
+ p.source_protocol,
250
+ p.router_id,
251
+ p.api_key_id,
252
+ p.call_event_id,
253
+ p.call_request_id,
254
+ cast(p.call_received_at as text) as call_received_at,
255
+ cast(p.call_completed_at as text) as call_completed_at,
256
+ p.result_observation_id,
257
+ p.result_request_id,
258
+ cast(p.result_observed_at as text) as result_observed_at,
259
+ ${query.includeTotal ? sql `t.total_items` : sql `null as total_items`}
260
+ from ${query.includeTotal
261
+ ? sql `tool_exchange_totals t left join tool_exchange_page p on true`
262
+ : sql `tool_exchange_page p`}
263
+ order by ${order}`);
264
+ let page = rows.filter((row) => row.state !== null && row.state !== undefined);
265
+ let nextOffset = null;
266
+ if (page.length > query.limit) {
267
+ page = page.slice(0, query.limit);
268
+ nextOffset = query.offset + query.limit;
269
+ }
270
+ const text = readOptionalString;
271
+ const time = (value) => {
272
+ const instant = readOptionalInstant(value);
273
+ return instant === null ? null : formatInstant(instant);
274
+ };
275
+ const items = page.map((row) => {
276
+ const state = String(row.state);
277
+ const item = { state, tool_call_id: text(row.tool_call_id) };
278
+ if (state !== "orphan_result") {
279
+ Object.assign(item, { capability_id: text(row.capability_id), observed_name: text(row.observed_name) });
280
+ }
281
+ Object.assign(item, { source_protocol: text(row.source_protocol), router_id: text(row.router_id), api_key_id: text(row.api_key_id) });
282
+ if (state !== "orphan_result") {
283
+ Object.assign(item, {
284
+ call_event_id: text(row.call_event_id),
285
+ call_request_id: text(row.call_request_id),
286
+ call_received_at: time(row.call_received_at),
287
+ call_completed_at: time(row.call_completed_at),
288
+ });
289
+ }
290
+ if (state !== "unmatched_call") {
291
+ Object.assign(item, {
292
+ result_observation_id: text(row.result_observation_id),
293
+ result_request_id: text(row.result_request_id),
294
+ result_observed_at: time(row.result_observed_at),
295
+ });
296
+ }
297
+ if (state === "matched") {
298
+ // Python: int(timedelta.total_seconds() * 1000), floored at 0.
299
+ const micros = readOptionalInstant(row.result_observed_at) - readOptionalInstant(row.call_completed_at);
300
+ item.result_turnaround_ms = Math.max(0, Math.trunc((micros / 1e6) * 1000));
301
+ }
302
+ return item;
303
+ });
304
+ return {
305
+ total_items: query.includeTotal ? readInt(rows[0].total_items) : null,
306
+ items,
307
+ next_offset: nextOffset,
308
+ };
309
+ }
@@ -0,0 +1,128 @@
1
+ import { type ActivityFilters } from "./filters.js";
2
+ import { type ActivityDb, type Sql } from "./sql.js";
3
+ import { type TopIdentity } from "./tool_skill_identities.js";
4
+ export type ToolSkillMode = "tools" | "skills";
5
+ export type SeriesMetric = "uses" | "file_reads" | "activity";
6
+ export declare const MAX_SELECTED_SERIES = 10;
7
+ /** The events, joined to their requests and filtered, for one mode. */
8
+ export type Scope = {
9
+ db: ActivityDb;
10
+ organizationId: string;
11
+ filters: ActivityFilters;
12
+ mode: ToolSkillMode;
13
+ };
14
+ /** What an event counts toward: a tool's capability ID, a skill's observed name. */
15
+ export declare function itemColumn(mode: ToolSkillMode): Sql;
16
+ export declare function usesCount(mode: ToolSkillMode): Sql;
17
+ export declare const FILE_READS: Sql;
18
+ /** The scope's events: its mode's event types, on requests passing the filters. */
19
+ export declare function scopeCriteria(scope: Scope): Sql;
20
+ export declare function toolSkillActivity(scope: Scope, metric: SeriesMetric, seriesIds: string[]): Promise<{
21
+ from_at: string;
22
+ to_at: string;
23
+ bucket_seconds: number;
24
+ mode: ToolSkillMode;
25
+ total_uses: number;
26
+ total_file_reads: number;
27
+ total_items: number;
28
+ items_truncated: boolean;
29
+ items: {
30
+ capability_id: string;
31
+ observed_name: string;
32
+ uses: number;
33
+ file_reads: number;
34
+ identity_count: number;
35
+ top_identity: TopIdentity;
36
+ latest_at: string;
37
+ }[];
38
+ series: {
39
+ bucket_start: string;
40
+ capability_id: string;
41
+ observed_name: string;
42
+ uses: number;
43
+ file_reads: number;
44
+ }[];
45
+ aggregate_series: {
46
+ bucket_start: string;
47
+ uses: number;
48
+ file_reads: number;
49
+ }[];
50
+ selected_series_ids: string[];
51
+ }>;
52
+ /** One item's detail; null when it has no activity under the filters. */
53
+ export declare function toolSkillDetail(scope: Scope, capabilityId: string): Promise<{
54
+ from_at: string;
55
+ to_at: string;
56
+ bucket_seconds: number;
57
+ mode: ToolSkillMode;
58
+ item: {
59
+ capability_id: string;
60
+ observed_name: string;
61
+ uses: number;
62
+ file_reads: number;
63
+ identity_count: number;
64
+ top_identity: TopIdentity;
65
+ latest_at: string;
66
+ };
67
+ series: {
68
+ bucket_start: string;
69
+ capability_id: string;
70
+ observed_name: string;
71
+ uses: number;
72
+ file_reads: number;
73
+ }[];
74
+ identities: {
75
+ latest_at: string;
76
+ id: string;
77
+ identity_type: "person" | "api_key";
78
+ name: string;
79
+ detail: string;
80
+ uses: number;
81
+ file_reads: number;
82
+ api_keys: Array<{
83
+ id: string;
84
+ label: string;
85
+ key_prefix: string;
86
+ uses: number;
87
+ file_reads: number;
88
+ }>;
89
+ }[];
90
+ versions: {
91
+ version: {} | null;
92
+ uses: number;
93
+ file_reads: number;
94
+ latest_at: string;
95
+ }[];
96
+ sources: {
97
+ source: string;
98
+ uses: number;
99
+ file_reads: number;
100
+ }[];
101
+ origins: {
102
+ capability_id: string;
103
+ source_protocol: string;
104
+ evidence_source: string;
105
+ uses: number;
106
+ file_reads: number;
107
+ }[];
108
+ } | null>;
109
+ export type InventoryQuery = {
110
+ search: string;
111
+ sortBy: "name" | "uses" | "file_reads" | "latest";
112
+ sortDirection: "asc" | "desc";
113
+ limit: number;
114
+ offset: number;
115
+ };
116
+ export declare function toolSkillInventory(scope: Scope, query: InventoryQuery): Promise<{
117
+ total_items: number;
118
+ items: {
119
+ capability_id: string;
120
+ observed_name: string;
121
+ uses: number;
122
+ file_reads: number;
123
+ identity_count: number;
124
+ top_identity: TopIdentity;
125
+ latest_at: string;
126
+ }[];
127
+ next_offset: number | null;
128
+ }>;