@mupt-ai/dari-gateway 1.0.325 → 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/platform/platform.d.ts +7 -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/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/platform/platform.ts +7 -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/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,318 @@
|
|
|
1
|
+
/* Conversations as Activity reads them: the `routing_requests` rows of one
|
|
2
|
+
inferred conversation, the names those rows point at, and the summary the
|
|
3
|
+
list and the detail both show. A conversation is the steps sharing a
|
|
4
|
+
protocol, agent session marker, router, API key, and attributed person. */
|
|
5
|
+
import { SUPPORTED_SOURCE_PROTOCOLS } from "./filters.js";
|
|
6
|
+
import { AGENT_SESSION_KEY, thinkingLevelValue } from "./shared.js";
|
|
7
|
+
import { or, sql } from "./sql.js";
|
|
8
|
+
import { addDecimals, formatInstant, parseDecimal, readBool, readInstant, readInt, readJson, readOptionalBool, readOptionalInstant, readOptionalInt, readOptionalString, } from "./values.js";
|
|
9
|
+
/** The columns `readRecord` reads. */
|
|
10
|
+
function recordColumns(db) {
|
|
11
|
+
// `selector_lease_turns` as text when it is a JSON integer, which a parsed
|
|
12
|
+
// JSON value cannot tell from a float such as `3.0`.
|
|
13
|
+
const leaseTurns = db.dialect === "postgres"
|
|
14
|
+
? sql `case when jsonb_typeof(r.decision_details -> 'selector_lease_turns') = 'number'
|
|
15
|
+
then r.decision_details ->> 'selector_lease_turns' end`
|
|
16
|
+
: sql `case when json_type(r.decision_details, '$.selector_lease_turns') = 'integer'
|
|
17
|
+
then cast(json_extract(r.decision_details, '$.selector_lease_turns') as text) end`;
|
|
18
|
+
return sql `
|
|
19
|
+
r.id, r.request_id, r.organization_id, r.source_protocol, r.router_id, r.api_key_id, r.attributed_user_id,
|
|
20
|
+
r.request_kind, r.conversation_id, r.agent_session_id, r.conversation_title,
|
|
21
|
+
r.zdr, r.status, r.error_code, r.error_message,
|
|
22
|
+
r.selected_model, r.selected_provider,
|
|
23
|
+
r.provider_input_tokens, r.provider_cache_read_tokens, r.provider_cache_write_tokens,
|
|
24
|
+
r.provider_output_tokens, r.provider_total_tokens,
|
|
25
|
+
cast(r.provider_total_cost_usd as text) as provider_total_cost_usd,
|
|
26
|
+
r.provider_pricing_known,
|
|
27
|
+
r.selector_latency_ms, r.provider_latency_ms, r.total_latency_ms,
|
|
28
|
+
r.message_count, r.has_tools,
|
|
29
|
+
cast(r.received_at as text) as received_at,
|
|
30
|
+
cast(r.completed_at as text) as completed_at,
|
|
31
|
+
r.decision_details, r.request_metadata, r.selector_reason,
|
|
32
|
+
r.blob_bucket, r.request_blob_key, r.response_blob_key, r.selector_output_blob_key, r.request_blob_format,
|
|
33
|
+
${leaseTurns} as lease_turns`;
|
|
34
|
+
}
|
|
35
|
+
function readRecord(db, row) {
|
|
36
|
+
const text = readOptionalString;
|
|
37
|
+
return {
|
|
38
|
+
id: String(row.id),
|
|
39
|
+
requestId: String(row.request_id),
|
|
40
|
+
organizationId: text(row.organization_id),
|
|
41
|
+
sourceProtocol: text(row.source_protocol),
|
|
42
|
+
routerId: text(row.router_id),
|
|
43
|
+
apiKeyId: text(row.api_key_id),
|
|
44
|
+
attributedUserId: text(row.attributed_user_id),
|
|
45
|
+
requestKind: text(row.request_kind),
|
|
46
|
+
conversationId: text(row.conversation_id),
|
|
47
|
+
agentSessionId: text(row.agent_session_id),
|
|
48
|
+
conversationTitle: text(row.conversation_title),
|
|
49
|
+
zdr: readBool(row.zdr),
|
|
50
|
+
status: String(row.status),
|
|
51
|
+
errorCode: text(row.error_code),
|
|
52
|
+
errorMessage: text(row.error_message),
|
|
53
|
+
selectedModel: text(row.selected_model),
|
|
54
|
+
selectedProvider: text(row.selected_provider),
|
|
55
|
+
providerInputTokens: readOptionalInt(row.provider_input_tokens),
|
|
56
|
+
providerCacheReadTokens: readOptionalInt(row.provider_cache_read_tokens),
|
|
57
|
+
providerCacheWriteTokens: readOptionalInt(row.provider_cache_write_tokens),
|
|
58
|
+
providerOutputTokens: readOptionalInt(row.provider_output_tokens),
|
|
59
|
+
providerTotalTokens: readOptionalInt(row.provider_total_tokens),
|
|
60
|
+
providerTotalCostUsd: (row.provider_total_cost_usd ?? null),
|
|
61
|
+
providerPricingKnown: readOptionalBool(row.provider_pricing_known),
|
|
62
|
+
selectorLatencyMs: readOptionalInt(row.selector_latency_ms),
|
|
63
|
+
providerLatencyMs: readOptionalInt(row.provider_latency_ms),
|
|
64
|
+
totalLatencyMs: readOptionalInt(row.total_latency_ms),
|
|
65
|
+
messageCount: readInt(row.message_count),
|
|
66
|
+
hasTools: readBool(row.has_tools),
|
|
67
|
+
receivedAt: readInstant(row.received_at),
|
|
68
|
+
completedAt: readOptionalInstant(row.completed_at),
|
|
69
|
+
decisionDetails: readJson(db, row.decision_details),
|
|
70
|
+
requestMetadata: readJson(db, row.request_metadata),
|
|
71
|
+
selectorReason: text(row.selector_reason),
|
|
72
|
+
blobBucket: text(row.blob_bucket),
|
|
73
|
+
requestBlobKey: text(row.request_blob_key),
|
|
74
|
+
responseBlobKey: text(row.response_blob_key),
|
|
75
|
+
selectorOutputBlobKey: text(row.selector_output_blob_key),
|
|
76
|
+
requestBlobFormat: text(row.request_blob_format),
|
|
77
|
+
leaseTurns: /^\d+$/.test(String(row.lease_turns)) && Number(row.lease_turns) > 0 ? Number(row.lease_turns) : null,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/** The rows matching a condition, oldest first. */
|
|
81
|
+
export async function loadRecords(db, condition) {
|
|
82
|
+
const rows = await db.all(sql `
|
|
83
|
+
select ${recordColumns(db)}
|
|
84
|
+
from routing_requests r
|
|
85
|
+
where ${condition}
|
|
86
|
+
order by r.received_at, r.id`);
|
|
87
|
+
return rows.map((row) => readRecord(db, row));
|
|
88
|
+
}
|
|
89
|
+
/** The row with this ID, or the organization's row with this gateway request ID. */
|
|
90
|
+
export async function findRecord(db, ref, organizationId) {
|
|
91
|
+
const byId = await db.all(sql `
|
|
92
|
+
select ${recordColumns(db)}
|
|
93
|
+
from routing_requests r
|
|
94
|
+
where r.id = ${ref}`);
|
|
95
|
+
if (byId.length > 0)
|
|
96
|
+
return readRecord(db, byId[0]);
|
|
97
|
+
if (organizationId === undefined)
|
|
98
|
+
return null;
|
|
99
|
+
const byRequest = await db.all(sql `
|
|
100
|
+
select ${recordColumns(db)}
|
|
101
|
+
from routing_requests r
|
|
102
|
+
where r.organization_id = ${organizationId}
|
|
103
|
+
and r.request_id = ${ref}
|
|
104
|
+
limit 1`);
|
|
105
|
+
return byRequest.length > 0 ? readRecord(db, byRequest[0]) : null;
|
|
106
|
+
}
|
|
107
|
+
/** A row of the organization with a protocol Activity reads. */
|
|
108
|
+
export function supported(record, organizationId) {
|
|
109
|
+
return record !== null && record.organizationId === organizationId && record.sourceProtocol !== null
|
|
110
|
+
&& SUPPORTED_SOURCE_PROTOCOLS.includes(record.sourceProtocol);
|
|
111
|
+
}
|
|
112
|
+
/** Python's `a or b or ...` over optional strings. */
|
|
113
|
+
export function firstTruthy(...values) {
|
|
114
|
+
return values.find((value) => value) ?? "";
|
|
115
|
+
}
|
|
116
|
+
export function groupKeyText(key) {
|
|
117
|
+
return JSON.stringify([key.sourceProtocol, key.conversationKey, key.routerId, key.apiKeyId, key.attributedUserId]);
|
|
118
|
+
}
|
|
119
|
+
export function recordKey(record) {
|
|
120
|
+
return {
|
|
121
|
+
sourceProtocol: record.sourceProtocol,
|
|
122
|
+
conversationKey: firstTruthy(record.agentSessionId, record.conversationId, record.id),
|
|
123
|
+
routerId: record.routerId,
|
|
124
|
+
apiKeyId: record.apiKeyId,
|
|
125
|
+
attributedUserId: record.attributedUserId,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
/** The record's context run: its conversation ID, or its own row ID. */
|
|
129
|
+
export function contextRun(record) {
|
|
130
|
+
return firstTruthy(record.conversationId, record.id);
|
|
131
|
+
}
|
|
132
|
+
/** The steps of any of the conversations, in any time range. */
|
|
133
|
+
export function groupsCondition(keys) {
|
|
134
|
+
const equal = (column, value) => value === null ? sql `${column} is null` : sql `${column} = ${value}`;
|
|
135
|
+
return or(keys.map((key) => sql `
|
|
136
|
+
r.source_protocol = ${key.sourceProtocol}
|
|
137
|
+
and ${AGENT_SESSION_KEY} = ${key.conversationKey}
|
|
138
|
+
and ${equal(sql `r.router_id`, key.routerId)}
|
|
139
|
+
and ${equal(sql `r.api_key_id`, key.apiKeyId)}
|
|
140
|
+
and ${equal(sql `r.attributed_user_id`, key.attributedUserId)}`));
|
|
141
|
+
}
|
|
142
|
+
/** Each conversation's latest non-empty title, from steps in any time range. */
|
|
143
|
+
export async function conversationTitles(db, organizationId, keys) {
|
|
144
|
+
const records = await loadRecords(db, sql `
|
|
145
|
+
r.organization_id = ${organizationId}
|
|
146
|
+
and r.conversation_title is not null
|
|
147
|
+
and ${groupsCondition(keys)}`);
|
|
148
|
+
const titles = new Map();
|
|
149
|
+
for (const record of records) {
|
|
150
|
+
if (record.conversationTitle)
|
|
151
|
+
titles.set(groupKeyText(recordKey(record)), record.conversationTitle);
|
|
152
|
+
}
|
|
153
|
+
return titles;
|
|
154
|
+
}
|
|
155
|
+
/** The routers, API keys, and people the steps name, deleted ones included. */
|
|
156
|
+
export async function loadEntities(db, records) {
|
|
157
|
+
const ids = (pick) => [...new Set(records.map(pick).filter((id) => Boolean(id)))];
|
|
158
|
+
const entities = { routers: new Map(), keys: new Map(), users: new Map() };
|
|
159
|
+
const routers = await db.all(sql `select id, name, zdr from model_routers where id in (${ids((r) => r.routerId)})`);
|
|
160
|
+
for (const row of routers) {
|
|
161
|
+
entities.routers.set(String(row.id), { name: String(row.name), zdr: readBool(row.zdr) });
|
|
162
|
+
}
|
|
163
|
+
const keys = await db.all(sql `
|
|
164
|
+
select id, label, key_prefix from organization_api_keys where id in (${ids((r) => r.apiKeyId)})`);
|
|
165
|
+
for (const row of keys) {
|
|
166
|
+
entities.keys.set(String(row.id), { label: String(row.label), keyPrefix: String(row.key_prefix) });
|
|
167
|
+
}
|
|
168
|
+
const users = await db.all(sql `
|
|
169
|
+
select id, display_name, email from users where id in (${ids((r) => r.attributedUserId)})`);
|
|
170
|
+
for (const row of users) {
|
|
171
|
+
entities.users.set(String(row.id), { displayName: readOptionalString(row.display_name), email: String(row.email) });
|
|
172
|
+
}
|
|
173
|
+
return entities;
|
|
174
|
+
}
|
|
175
|
+
/** Python's `format(Decimal, "f")`. */
|
|
176
|
+
export function fixedDecimal(value) {
|
|
177
|
+
if (value.exponent >= 0)
|
|
178
|
+
return (value.coefficient * 10n ** BigInt(value.exponent)).toString();
|
|
179
|
+
const negative = value.coefficient < 0n;
|
|
180
|
+
const digits = (negative ? -value.coefficient : value.coefficient).toString().padStart(-value.exponent + 1, "0");
|
|
181
|
+
const point = digits.length + value.exponent;
|
|
182
|
+
return `${negative ? "-" : ""}${digits.slice(0, point)}.${digits.slice(point)}`;
|
|
183
|
+
}
|
|
184
|
+
export function optionalFixed(value) {
|
|
185
|
+
return value === null ? null : fixedDecimal(parseDecimal(value));
|
|
186
|
+
}
|
|
187
|
+
/** The values without nulls or immediate repeats. */
|
|
188
|
+
export function consecutivePath(values) {
|
|
189
|
+
const path = [];
|
|
190
|
+
for (const value of values) {
|
|
191
|
+
if (value !== null && path.at(-1) !== value)
|
|
192
|
+
path.push(value);
|
|
193
|
+
}
|
|
194
|
+
return path;
|
|
195
|
+
}
|
|
196
|
+
export function decisionDetails(record) {
|
|
197
|
+
const details = record.decisionDetails;
|
|
198
|
+
return details !== null && typeof details === "object" && !Array.isArray(details)
|
|
199
|
+
? details
|
|
200
|
+
: null;
|
|
201
|
+
}
|
|
202
|
+
export function selectedEffort(record) {
|
|
203
|
+
return thinkingLevelValue(decisionDetails(record)?.selected_reasoning_effort);
|
|
204
|
+
}
|
|
205
|
+
/** The conversation summary over its steps, oldest first. */
|
|
206
|
+
export function conversationSummary(records, entities, title, switches) {
|
|
207
|
+
const first = records[0];
|
|
208
|
+
const last = records.at(-1);
|
|
209
|
+
const router = first.routerId === null ? undefined : entities.routers.get(first.routerId);
|
|
210
|
+
const key = first.apiKeyId === null ? undefined : entities.keys.get(first.apiKeyId);
|
|
211
|
+
const user = first.attributedUserId === null ? undefined : entities.users.get(first.attributedUserId);
|
|
212
|
+
const runs = new Set();
|
|
213
|
+
let messagesSent = 0;
|
|
214
|
+
let totalTokens = 0;
|
|
215
|
+
let spend = null;
|
|
216
|
+
let priced = 0;
|
|
217
|
+
let unpriced = 0;
|
|
218
|
+
let hasError = false;
|
|
219
|
+
let hasAborted = false;
|
|
220
|
+
let allZdr = true;
|
|
221
|
+
let anyZdr = false;
|
|
222
|
+
for (const record of records) {
|
|
223
|
+
runs.add(contextRun(record));
|
|
224
|
+
if (record.requestKind === "user_message")
|
|
225
|
+
messagesSent += 1;
|
|
226
|
+
totalTokens += record.providerTotalTokens ?? 0;
|
|
227
|
+
if (record.providerTotalCostUsd !== null) {
|
|
228
|
+
spend = addDecimals(spend ?? { coefficient: 0n, exponent: 0 }, parseDecimal(record.providerTotalCostUsd));
|
|
229
|
+
}
|
|
230
|
+
if (record.providerPricingKnown !== null && record.selectedModel !== null && record.selectedProvider !== null) {
|
|
231
|
+
if (record.providerPricingKnown)
|
|
232
|
+
priced += 1;
|
|
233
|
+
else
|
|
234
|
+
unpriced += 1;
|
|
235
|
+
}
|
|
236
|
+
if (record.status === "provider_error" || record.status === "selector_error")
|
|
237
|
+
hasError = true;
|
|
238
|
+
if (record.status === "aborted")
|
|
239
|
+
hasAborted = true;
|
|
240
|
+
allZdr &&= record.zdr;
|
|
241
|
+
anyZdr ||= record.zdr;
|
|
242
|
+
}
|
|
243
|
+
return {
|
|
244
|
+
conversation_ref: first.id,
|
|
245
|
+
conversation_id: first.conversationId || null,
|
|
246
|
+
agent_session_id: first.agentSessionId || null,
|
|
247
|
+
context_runs: runs.size,
|
|
248
|
+
source_protocol: first.sourceProtocol,
|
|
249
|
+
title: title || ([...records].reverse().find((record) => record.conversationTitle)?.conversationTitle ?? null),
|
|
250
|
+
router_id: first.routerId,
|
|
251
|
+
router_name: router?.name ?? null,
|
|
252
|
+
api_key_id: first.apiKeyId,
|
|
253
|
+
api_key_label: key?.label ?? null,
|
|
254
|
+
api_key_prefix: key?.keyPrefix ?? null,
|
|
255
|
+
attributed_user_id: first.attributedUserId,
|
|
256
|
+
attributed_user_name: user === undefined ? null : user.displayName || user.email,
|
|
257
|
+
attributed_user_email: user?.email ?? null,
|
|
258
|
+
first_at: formatInstant(first.receivedAt),
|
|
259
|
+
last_at: formatInstant(last.receivedAt),
|
|
260
|
+
messages_sent: messagesSent,
|
|
261
|
+
model_steps: records.length,
|
|
262
|
+
model_switches: switches ?? contextRunSwitches(records),
|
|
263
|
+
model_path: consecutivePath(records.map((record) => record.selectedModel)),
|
|
264
|
+
provider_path: consecutivePath(records.map((record) => record.selectedProvider)),
|
|
265
|
+
provider_total_tokens: totalTokens,
|
|
266
|
+
provider_spend_usd: spend === null ? null : fixedDecimal(spend),
|
|
267
|
+
priced_model_steps: priced,
|
|
268
|
+
unpriced_model_steps: unpriced,
|
|
269
|
+
has_error: hasError,
|
|
270
|
+
has_aborted: hasAborted,
|
|
271
|
+
terminal_status: last.status,
|
|
272
|
+
retention: router?.zdr || allZdr ? "zdr" : anyZdr ? "mixed" : "retained",
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
/** Model changes within each context run. */
|
|
276
|
+
function contextRunSwitches(records) {
|
|
277
|
+
const paths = new Map();
|
|
278
|
+
for (const record of records) {
|
|
279
|
+
const run = contextRun(record);
|
|
280
|
+
paths.set(run, [...(paths.get(run) ?? []), record.selectedModel]);
|
|
281
|
+
}
|
|
282
|
+
let switches = 0;
|
|
283
|
+
for (const models of paths.values())
|
|
284
|
+
switches += Math.max(0, consecutivePath(models).length - 1);
|
|
285
|
+
return switches;
|
|
286
|
+
}
|
|
287
|
+
/** Python's `repr` of a string. */
|
|
288
|
+
export function pyRepr(text) {
|
|
289
|
+
const quote = text.includes("'") && !text.includes('"') ? '"' : "'";
|
|
290
|
+
let out = quote;
|
|
291
|
+
for (const character of text) {
|
|
292
|
+
const code = character.codePointAt(0);
|
|
293
|
+
if (character === "\\" || character === quote)
|
|
294
|
+
out += `\\${character}`;
|
|
295
|
+
else if (character === "\n")
|
|
296
|
+
out += "\\n";
|
|
297
|
+
else if (character === "\r")
|
|
298
|
+
out += "\\r";
|
|
299
|
+
else if (character === "\t")
|
|
300
|
+
out += "\\t";
|
|
301
|
+
else if (code < 0x20 || (code >= 0x7f && code < 0xa0))
|
|
302
|
+
out += `\\x${code.toString(16).padStart(2, "0")}`;
|
|
303
|
+
else
|
|
304
|
+
out += character;
|
|
305
|
+
}
|
|
306
|
+
return out + quote;
|
|
307
|
+
}
|
|
308
|
+
const REQUEST_BLOB_FORMATS = ["chat_projection_v1", "interaction_request_v1"];
|
|
309
|
+
/** The stored request format; a row with an unknown one is inconsistent. */
|
|
310
|
+
export function requestBlobFormat(record) {
|
|
311
|
+
if (record.requestBlobKey === null)
|
|
312
|
+
return null;
|
|
313
|
+
const format = record.requestBlobFormat;
|
|
314
|
+
if (format === null || !REQUEST_BLOB_FORMATS.includes(format)) {
|
|
315
|
+
throw new Error(`Routing request ${pyRepr(record.id)} has unsupported request blob format ${format === null ? "None" : pyRepr(format)}.`);
|
|
316
|
+
}
|
|
317
|
+
return format;
|
|
318
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ActivityRoute } from "./http.js";
|
|
2
|
+
export { conversation } from "./conversation_detail.js";
|
|
3
|
+
export { toolExchanges } from "./tool_exchanges.js";
|
|
4
|
+
export declare const conversations: ActivityRoute;
|
|
5
|
+
declare const PAYLOAD_KEYS: {
|
|
6
|
+
readonly client_request: "requestBlobKey";
|
|
7
|
+
readonly client_response: "responseBlobKey";
|
|
8
|
+
readonly selector_output: "selectorOutputBlobKey";
|
|
9
|
+
};
|
|
10
|
+
/** A step's stored client request, client response, or selector output. */
|
|
11
|
+
export declare const payload: (kind: keyof typeof PAYLOAD_KEYS) => ActivityRoute;
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/* Conversation routes: the conversation list, one conversation's detail, and
|
|
2
|
+
the retained payloads of its steps. */
|
|
3
|
+
import { conversationSummary, conversationTitles, findRecord, groupKeyText, groupsCondition, loadEntities, loadRecords, pyRepr, recordKey, requestBlobFormat, supported, } from "./conversation_records.js";
|
|
4
|
+
import { criteria, readActivityQuery, readSourceScope, sourceProtocols, validatedFilters } from "./filters.js";
|
|
5
|
+
import { notFound } from "./params.js";
|
|
6
|
+
import { AGENT_SESSION_KEY } from "./shared.js";
|
|
7
|
+
import { likePattern, raw, sql } from "./sql.js";
|
|
8
|
+
import { readInt, readOptionalString } from "./values.js";
|
|
9
|
+
export { conversation } from "./conversation_detail.js";
|
|
10
|
+
export { toolExchanges } from "./tool_exchanges.js";
|
|
11
|
+
/** What the list sorts by, as columns of a conversation's row. */
|
|
12
|
+
const SORTS = {
|
|
13
|
+
last_active: sql `last_at`,
|
|
14
|
+
messages: sql `messages_sent`,
|
|
15
|
+
model_steps: sql `model_steps`,
|
|
16
|
+
model_switches: sql `model_switches`,
|
|
17
|
+
spend: sql `coalesce(provider_spend, 0)`,
|
|
18
|
+
tokens: sql `provider_tokens`,
|
|
19
|
+
};
|
|
20
|
+
export const conversations = async (request) => {
|
|
21
|
+
const { params, db } = request;
|
|
22
|
+
const scope = readSourceScope(params);
|
|
23
|
+
const search = params.string("search", { maxLength: 200 }) ?? "";
|
|
24
|
+
const sortBy = params.literal("sort_by", Object.keys(SORTS), "last_active");
|
|
25
|
+
const direction = params.literal("sort_direction", ["asc", "desc"], "desc");
|
|
26
|
+
const limit = params.int("limit", { default: 20, ge: 1, le: 100 });
|
|
27
|
+
const offset = params.int("offset", { default: 0, ge: 0 });
|
|
28
|
+
const query = readActivityQuery(params);
|
|
29
|
+
params.done();
|
|
30
|
+
const protocols = sourceProtocols(scope);
|
|
31
|
+
const organizationId = request.admitted();
|
|
32
|
+
const filters = validatedFilters(query, protocols);
|
|
33
|
+
const term = search.trim();
|
|
34
|
+
const where = criteria(db, organizationId, filters);
|
|
35
|
+
const pattern = likePattern(term);
|
|
36
|
+
// One row per conversation. With a search term, `correlation_match` is
|
|
37
|
+
// whether a correlation ID of any of its steps contains it.
|
|
38
|
+
const correlationMatch = term === "" ? sql `0` : sql `
|
|
39
|
+
max(case when lower(r.conversation_id) like ${pattern} escape '/'
|
|
40
|
+
or lower(r.request_id) like ${pattern} escape '/'
|
|
41
|
+
or lower(r.client_request_id) like ${pattern} escape '/'
|
|
42
|
+
then 1 else 0 end)`;
|
|
43
|
+
const groups = sql `
|
|
44
|
+
select
|
|
45
|
+
r.source_protocol,
|
|
46
|
+
${AGENT_SESSION_KEY} as conversation_key,
|
|
47
|
+
r.router_id,
|
|
48
|
+
r.api_key_id,
|
|
49
|
+
r.attributed_user_id,
|
|
50
|
+
min(r.received_at) as first_at,
|
|
51
|
+
max(r.received_at) as last_at,
|
|
52
|
+
count(*) filter (where r.request_kind = 'user_message') as messages_sent,
|
|
53
|
+
count(*) as model_steps,
|
|
54
|
+
sum(coalesce(r.provider_total_tokens, 0)) as provider_tokens,
|
|
55
|
+
sum(r.provider_total_cost_usd) as provider_spend,
|
|
56
|
+
count(*) filter (where r.model_switched is true) as model_switches,
|
|
57
|
+
${correlationMatch} as correlation_match
|
|
58
|
+
from routing_requests r
|
|
59
|
+
where ${where}
|
|
60
|
+
group by r.source_protocol, ${AGENT_SESSION_KEY}, r.router_id, r.api_key_id, r.attributed_user_id`;
|
|
61
|
+
// A search keeps the conversations matching on a correlation ID, the ID or
|
|
62
|
+
// name of their router, key, or person, or their latest title.
|
|
63
|
+
const rows = term === "" ? groups : sql `
|
|
64
|
+
select g.*
|
|
65
|
+
from (${groups}) g
|
|
66
|
+
left join model_routers mr on mr.id = g.router_id and mr.organization_id = ${organizationId}
|
|
67
|
+
left join organization_api_keys k on k.id = g.api_key_id and k.organization_id = ${organizationId}
|
|
68
|
+
left join users u on u.id = g.attributed_user_id
|
|
69
|
+
where g.correlation_match = 1
|
|
70
|
+
or lower(g.conversation_key) like ${pattern} escape '/'
|
|
71
|
+
or lower(g.router_id) like ${pattern} escape '/'
|
|
72
|
+
or lower(mr.name) like ${pattern} escape '/'
|
|
73
|
+
or lower(g.api_key_id) like ${pattern} escape '/'
|
|
74
|
+
or lower(k.label) like ${pattern} escape '/'
|
|
75
|
+
or lower(k.key_prefix) like ${pattern} escape '/'
|
|
76
|
+
or lower(g.attributed_user_id) like ${pattern} escape '/'
|
|
77
|
+
or lower(u.display_name) like ${pattern} escape '/'
|
|
78
|
+
or lower(u.email) like ${pattern} escape '/'
|
|
79
|
+
or lower((
|
|
80
|
+
select r.conversation_title
|
|
81
|
+
from routing_requests r
|
|
82
|
+
where r.organization_id = ${organizationId}
|
|
83
|
+
and r.source_protocol = g.source_protocol
|
|
84
|
+
and ${AGENT_SESSION_KEY} = g.conversation_key
|
|
85
|
+
and (r.router_id = g.router_id or (r.router_id is null and g.router_id is null))
|
|
86
|
+
and (r.api_key_id = g.api_key_id or (r.api_key_id is null and g.api_key_id is null))
|
|
87
|
+
and (r.attributed_user_id = g.attributed_user_id
|
|
88
|
+
or (r.attributed_user_id is null and g.attributed_user_id is null))
|
|
89
|
+
and r.conversation_title is not null
|
|
90
|
+
order by r.received_at desc, r.id desc
|
|
91
|
+
limit 1
|
|
92
|
+
)) like ${pattern} escape '/'`;
|
|
93
|
+
// The page, with the totals over every conversation on each of its rows;
|
|
94
|
+
// one row of totals alone when the page is empty.
|
|
95
|
+
const order = sql `${SORTS[sortBy]} ${raw(direction)}, last_at desc, source_protocol, conversation_key`;
|
|
96
|
+
const page = await db.all(sql `
|
|
97
|
+
with conversation_rows as (${rows}),
|
|
98
|
+
conversation_page as (
|
|
99
|
+
select *
|
|
100
|
+
from conversation_rows
|
|
101
|
+
order by ${order}
|
|
102
|
+
limit ${limit + 1} offset ${offset}
|
|
103
|
+
),
|
|
104
|
+
conversation_totals as (
|
|
105
|
+
select
|
|
106
|
+
count(*) as conversation_count,
|
|
107
|
+
coalesce(sum(model_switches), 0) as total_model_switches,
|
|
108
|
+
count(*) filter (where model_switches > 0) as conversations_with_model_switches
|
|
109
|
+
from conversation_rows
|
|
110
|
+
)
|
|
111
|
+
select
|
|
112
|
+
p.source_protocol,
|
|
113
|
+
p.conversation_key,
|
|
114
|
+
p.router_id,
|
|
115
|
+
p.api_key_id,
|
|
116
|
+
p.attributed_user_id,
|
|
117
|
+
p.model_switches,
|
|
118
|
+
t.conversation_count,
|
|
119
|
+
t.total_model_switches,
|
|
120
|
+
t.conversations_with_model_switches
|
|
121
|
+
from conversation_totals t
|
|
122
|
+
left join conversation_page p on true
|
|
123
|
+
order by ${order}`);
|
|
124
|
+
const totals = page[0];
|
|
125
|
+
const switches = new Map();
|
|
126
|
+
let keys = [];
|
|
127
|
+
for (const row of page) {
|
|
128
|
+
if (row.conversation_key === null || row.conversation_key === undefined)
|
|
129
|
+
continue;
|
|
130
|
+
const key = {
|
|
131
|
+
sourceProtocol: String(row.source_protocol),
|
|
132
|
+
conversationKey: String(row.conversation_key),
|
|
133
|
+
routerId: readOptionalString(row.router_id),
|
|
134
|
+
apiKeyId: readOptionalString(row.api_key_id),
|
|
135
|
+
attributedUserId: readOptionalString(row.attributed_user_id),
|
|
136
|
+
};
|
|
137
|
+
keys.push(key);
|
|
138
|
+
switches.set(groupKeyText(key), readInt(row.model_switches));
|
|
139
|
+
}
|
|
140
|
+
let nextOffset = null;
|
|
141
|
+
if (keys.length > limit) {
|
|
142
|
+
keys = keys.slice(0, limit);
|
|
143
|
+
nextOffset = offset + limit;
|
|
144
|
+
}
|
|
145
|
+
const items = [];
|
|
146
|
+
if (keys.length > 0) {
|
|
147
|
+
const records = await loadRecords(db, sql `${where} and ${groupsCondition(keys)}`);
|
|
148
|
+
const titles = await conversationTitles(db, organizationId, keys);
|
|
149
|
+
const entities = await loadEntities(db, records);
|
|
150
|
+
const byGroup = new Map();
|
|
151
|
+
for (const record of records) {
|
|
152
|
+
const text = groupKeyText(recordKey(record));
|
|
153
|
+
byGroup.set(text, [...(byGroup.get(text) ?? []), record]);
|
|
154
|
+
}
|
|
155
|
+
for (const key of keys) {
|
|
156
|
+
const text = groupKeyText(key);
|
|
157
|
+
items.push(conversationSummary(byGroup.get(text), entities, titles.get(text), switches.get(text)));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
conversations: items,
|
|
162
|
+
conversation_count: readInt(totals.conversation_count),
|
|
163
|
+
model_switches: readInt(totals.total_model_switches),
|
|
164
|
+
conversations_with_model_switches: readInt(totals.conversations_with_model_switches),
|
|
165
|
+
limit,
|
|
166
|
+
offset,
|
|
167
|
+
next_offset: nextOffset,
|
|
168
|
+
};
|
|
169
|
+
};
|
|
170
|
+
const PAYLOAD_KEYS = {
|
|
171
|
+
client_request: "requestBlobKey",
|
|
172
|
+
client_response: "responseBlobKey",
|
|
173
|
+
selector_output: "selectorOutputBlobKey",
|
|
174
|
+
};
|
|
175
|
+
/** A step's stored client request, client response, or selector output. */
|
|
176
|
+
export const payload = (kind) => async (request) => {
|
|
177
|
+
request.params.done();
|
|
178
|
+
const organizationId = request.admitted();
|
|
179
|
+
const requestId = request.path.request_id;
|
|
180
|
+
const record = await findRecord(request.db, requestId);
|
|
181
|
+
if (!supported(record, organizationId))
|
|
182
|
+
throw notFound(`Unknown routing request ${pyRepr(requestId)}.`);
|
|
183
|
+
const missing = notFound(`No ${kind.replace(/_/g, " ")} payload is stored for this routing request.`);
|
|
184
|
+
const key = record[PAYLOAD_KEYS[kind]];
|
|
185
|
+
if (record.blobBucket === null || key === null)
|
|
186
|
+
throw missing;
|
|
187
|
+
const body = await request.platform.readBlob(record.blobBucket, key);
|
|
188
|
+
if (body === null)
|
|
189
|
+
throw missing;
|
|
190
|
+
const format = kind === "client_request" ? requestBlobFormat(record) : null;
|
|
191
|
+
const headers = {
|
|
192
|
+
"Content-Type": kind === "selector_output" ? "text/plain; charset=utf-8" : "application/json",
|
|
193
|
+
"Cache-Control": "no-store",
|
|
194
|
+
};
|
|
195
|
+
if (format !== null)
|
|
196
|
+
headers["X-Dari-Request-Format"] = format;
|
|
197
|
+
return new Response(body, { headers });
|
|
198
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ActivityRoute } from "./http.js";
|
|
2
|
+
import { type Decimal } from "./values.js";
|
|
3
|
+
export declare const series: ActivityRoute;
|
|
4
|
+
export declare const overview: ActivityRoute;
|
|
5
|
+
export declare const routers: ActivityRoute;
|
|
6
|
+
export declare const models: ActivityRoute;
|
|
7
|
+
/**
|
|
8
|
+
* Python's `format(Decimal(value) / divisor, "f")` under the default context:
|
|
9
|
+
* 28 significant digits, rounded half-even, and an exact quotient kept as
|
|
10
|
+
* close to the dividend's exponent as it allows.
|
|
11
|
+
*/
|
|
12
|
+
export declare function divideFormat(value: Decimal, divisor: number): string;
|
|
13
|
+
export declare const filterOptions: ActivityRoute;
|