@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
|
@@ -6,17 +6,12 @@ import { decodeUntrustedProviderContinuationState } from "../../interaction/prov
|
|
|
6
6
|
import { decodeUntrustedPortableReasoningState } from "../../interaction/portable_reasoning_state.js";
|
|
7
7
|
import { toolsByWireName } from "../../interaction/tool_identity.js";
|
|
8
8
|
import { explicitModelId, isAnthropicRouterModel, unsupportedModelMessage } from "./router_model.js";
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
"
|
|
14
|
-
|
|
15
|
-
"tool_search_tool_regex_20251119",
|
|
16
|
-
"tool_search_tool_bm25",
|
|
17
|
-
"tool_search_tool_bm25_20251119",
|
|
18
|
-
];
|
|
19
|
-
const isServerToolType = (type) => SUPPORTED_SERVER_TOOL_TYPES.includes(type) || isAnthropicWebSearchToolType(type);
|
|
9
|
+
import { ANTHROPIC_TOOL_TYPE_KINDS } from "../../interaction/types.js";
|
|
10
|
+
const anthropicToolKind = (type) => {
|
|
11
|
+
if (Object.hasOwn(ANTHROPIC_TOOL_TYPE_KINDS, type))
|
|
12
|
+
return ANTHROPIC_TOOL_TYPE_KINDS[type];
|
|
13
|
+
return isAnthropicWebSearchToolType(type) ? "server_tool" : undefined;
|
|
14
|
+
};
|
|
20
15
|
export function anthropicMessagesToInteraction(payload) {
|
|
21
16
|
const model = requiredString(payload.model, "model");
|
|
22
17
|
if (!isAnthropicRouterModel(model) && explicitModelId(model) === null) {
|
|
@@ -81,11 +76,19 @@ function appendAnthropicMessage(items, role, value, messageIndex) {
|
|
|
81
76
|
throw invalidRequest(`messages[${messageIndex}].content must be a string or an array.`, `messages.${messageIndex}.content`);
|
|
82
77
|
}
|
|
83
78
|
let buffered = [];
|
|
79
|
+
let toolsAdded = [];
|
|
84
80
|
const flushMessage = () => {
|
|
85
|
-
if (buffered.length === 0)
|
|
81
|
+
if (buffered.length === 0 && toolsAdded.length === 0)
|
|
86
82
|
return;
|
|
87
|
-
items.push({
|
|
83
|
+
items.push({
|
|
84
|
+
type: "message",
|
|
85
|
+
role,
|
|
86
|
+
content: buffered,
|
|
87
|
+
contentShape: "parts",
|
|
88
|
+
...(toolsAdded.length === 0 ? {} : { toolsAdded }),
|
|
89
|
+
});
|
|
88
90
|
buffered = [];
|
|
91
|
+
toolsAdded = [];
|
|
89
92
|
};
|
|
90
93
|
let pendingServerToolUse = null;
|
|
91
94
|
for (const [contentIndex, rawBlock] of value.entries()) {
|
|
@@ -236,6 +239,16 @@ function appendAnthropicMessage(items, role, value, messageIndex) {
|
|
|
236
239
|
});
|
|
237
240
|
continue;
|
|
238
241
|
}
|
|
242
|
+
if (type === "tool_addition") {
|
|
243
|
+
if (role !== "system")
|
|
244
|
+
throw invalidRequest("tool_addition blocks require the system role.", param);
|
|
245
|
+
const tool = isRecord(rawBlock.tool) ? rawBlock.tool : undefined;
|
|
246
|
+
if (tool?.type !== "tool_definition") {
|
|
247
|
+
throw invalidRequest(`${param}.tool must be a tool_definition.`, `${param}.tool`);
|
|
248
|
+
}
|
|
249
|
+
toolsAdded.push(anthropicTool(tool.definition, `${param}.tool.definition`));
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
239
252
|
throw new HttpError(400, `Anthropic content block type '${type}' is not supported.`, "unsupported_content_block", param);
|
|
240
253
|
}
|
|
241
254
|
flushMessage();
|
|
@@ -392,42 +405,44 @@ function anthropicTools(value) {
|
|
|
392
405
|
return [];
|
|
393
406
|
if (!Array.isArray(value))
|
|
394
407
|
throw invalidRequest("tools must be an array.", "tools");
|
|
395
|
-
return value.map((rawTool, index) => {
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
kind: "server_tool",
|
|
411
|
-
name: requiredString(rawTool.name, `tools.${index}.name`),
|
|
412
|
-
type,
|
|
413
|
-
description: optionalString(rawTool.description, `tools.${index}.description`),
|
|
414
|
-
...(isAnthropicWebSearchToolType(type) ? { definition: rawTool } : {}),
|
|
415
|
-
};
|
|
416
|
-
}
|
|
417
|
-
throw new HttpError(400, `Anthropic tool type '${String(type)}' is not supported by this router.`, "unsupported_tool", `tools.${index}.type`);
|
|
408
|
+
return value.map((rawTool, index) => anthropicTool(rawTool, `tools.${index}`));
|
|
409
|
+
}
|
|
410
|
+
function anthropicTool(rawTool, param) {
|
|
411
|
+
if (!isRecord(rawTool))
|
|
412
|
+
throw invalidRequest(`${param} must be an object.`, param);
|
|
413
|
+
const type = rawTool.type;
|
|
414
|
+
if (type !== undefined && type !== "custom") {
|
|
415
|
+
const kind = typeof type === "string" ? anthropicToolKind(type) : undefined;
|
|
416
|
+
if (kind === "client_tool") {
|
|
417
|
+
return {
|
|
418
|
+
kind,
|
|
419
|
+
name: requiredString(rawTool.name, `${param}.name`),
|
|
420
|
+
type: type,
|
|
421
|
+
description: optionalString(rawTool.description, `${param}.description`),
|
|
422
|
+
};
|
|
418
423
|
}
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
424
|
+
if (kind === "server_tool") {
|
|
425
|
+
return {
|
|
426
|
+
kind,
|
|
427
|
+
name: requiredString(rawTool.name, `${param}.name`),
|
|
428
|
+
type: type,
|
|
429
|
+
description: optionalString(rawTool.description, `${param}.description`),
|
|
430
|
+
...(isAnthropicWebSearchToolType(type) ? { definition: rawTool } : {}),
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
throw new HttpError(400, `Anthropic tool type '${String(type)}' is not supported by this router.`, "unsupported_tool", `${param}.type`);
|
|
434
|
+
}
|
|
435
|
+
const schema = rawTool.input_schema;
|
|
436
|
+
if (!isRecord(schema))
|
|
437
|
+
throw invalidRequest(`${param}.input_schema must be an object.`, `${param}.input_schema`);
|
|
438
|
+
return {
|
|
439
|
+
kind: "function",
|
|
440
|
+
name: requiredString(rawTool.name, `${param}.name`),
|
|
441
|
+
description: optionalString(rawTool.description, `${param}.description`),
|
|
442
|
+
parameters: schema,
|
|
443
|
+
strict: optionalBoolean(rawTool.strict, `${param}.strict`),
|
|
444
|
+
deferLoading: optionalBoolean(rawTool.defer_loading, `${param}.defer_loading`),
|
|
445
|
+
};
|
|
431
446
|
}
|
|
432
447
|
function anthropicToolChoice(value) {
|
|
433
448
|
if (value === undefined || value === null)
|
package/dist/providers/pi.js
CHANGED
|
@@ -222,7 +222,7 @@ export function buildModel(pi, modelId, pricing, config) {
|
|
|
222
222
|
throw new HttpError(502, `No base URL is configured for provider ${provider}.`, "provider_configuration_error");
|
|
223
223
|
}
|
|
224
224
|
const contextWindow = contextWindowForModel(modelId, registered, config) ?? 128000;
|
|
225
|
-
const compat = gatewayRuntimeCompat(api, runtimeCompat(provider, registered, modelId));
|
|
225
|
+
const compat = gatewayRuntimeCompat(api, runtimeCompat(provider, registered, modelId), provider, nativeId);
|
|
226
226
|
return {
|
|
227
227
|
...(registered ?? {}),
|
|
228
228
|
...(compat !== undefined ? { compat } : {}),
|
|
@@ -298,12 +298,19 @@ function contextWindowForModel(modelId, registered, config) {
|
|
|
298
298
|
// `tools` field, when a model supports mid-conversation system messages. The gateway
|
|
299
299
|
// keeps tools at the request level until that native tool-change path is validated.
|
|
300
300
|
const RESPONSES_APIS = new Set(["openai-responses", "azure-openai-responses", "openai-codex-responses"]);
|
|
301
|
-
|
|
301
|
+
// Compat the gateway adds where Pi's own table has no entry. A rule applies when
|
|
302
|
+
// its provider and model match, and a value Pi already set wins. Remove a rule
|
|
303
|
+
// once the pinned pi-ai sets the same value.
|
|
304
|
+
const COMPAT_RULES = [
|
|
305
|
+
{ provider: "anthropic", model: /^claude-haiku-(4-5|5-5)(-|$)/, compat: { supportsToolReferences: true } },
|
|
306
|
+
];
|
|
307
|
+
function gatewayRuntimeCompat(api, compat, provider, modelId) {
|
|
302
308
|
// Pi 1.5 enables server-side message threads whenever sessionId is set.
|
|
303
309
|
// Gateway sessions serve affinity, not permission to retain a conversation
|
|
304
310
|
// remotely; keep full-history requests, including on ZDR routes.
|
|
305
311
|
if (api === "anthropic-messages") {
|
|
306
|
-
|
|
312
|
+
const base = isRecord(compat) ? compat : {};
|
|
313
|
+
return { ...base, ...gatewayCompatDefaults(provider, modelId, base), supportsMessageThreads: false };
|
|
307
314
|
}
|
|
308
315
|
if (typeof api !== "string" || !RESPONSES_APIS.has(api))
|
|
309
316
|
return compat;
|
|
@@ -311,6 +318,18 @@ function gatewayRuntimeCompat(api, compat) {
|
|
|
311
318
|
return compat;
|
|
312
319
|
return { ...compat, supportsMidConvoSystemMessages: false };
|
|
313
320
|
}
|
|
321
|
+
function gatewayCompatDefaults(provider, modelId, base) {
|
|
322
|
+
const defaults = {};
|
|
323
|
+
for (const rule of COMPAT_RULES) {
|
|
324
|
+
if (rule.provider !== provider || !rule.model.test(modelId))
|
|
325
|
+
continue;
|
|
326
|
+
for (const [key, value] of Object.entries(rule.compat)) {
|
|
327
|
+
if (base[key] === undefined)
|
|
328
|
+
defaults[key] = value;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return defaults;
|
|
332
|
+
}
|
|
314
333
|
function modelPricingFromConfig(config) {
|
|
315
334
|
const configuredCost = config?.fast_mode && config.provider === "anthropic" && config.fast_mode_cost
|
|
316
335
|
? config.fast_mode_cost
|
|
@@ -13,6 +13,7 @@ const UNKNOWN_SOURCE = {
|
|
|
13
13
|
};
|
|
14
14
|
export function buildContext(request, target) {
|
|
15
15
|
const systemParts = request.instructions ? [request.instructions] : [];
|
|
16
|
+
const leadingTools = [];
|
|
16
17
|
const messages = [];
|
|
17
18
|
const toolCalls = new Map();
|
|
18
19
|
const timestamp = Date.now();
|
|
@@ -54,12 +55,13 @@ export function buildContext(request, target) {
|
|
|
54
55
|
if (item.type === "message" && (item.role === "system" || item.role === "developer")) {
|
|
55
56
|
flushAssistant();
|
|
56
57
|
const text = readableContent(item.content);
|
|
57
|
-
|
|
58
|
-
continue;
|
|
58
|
+
const added = (item.toolsAdded ?? []).filter((tool) => isSentTool(tool, target));
|
|
59
59
|
if (!sawConversationItem) {
|
|
60
60
|
// Leading preamble is identical on every request, so folding it into
|
|
61
61
|
// the system prompt keeps the provider payload prefix stable.
|
|
62
|
-
|
|
62
|
+
if (text)
|
|
63
|
+
systemParts.push(text);
|
|
64
|
+
leadingTools.push(...added);
|
|
63
65
|
continue;
|
|
64
66
|
}
|
|
65
67
|
// Mid-conversation system/developer notes arrive between turns (Claude
|
|
@@ -67,7 +69,12 @@ export function buildContext(request, target) {
|
|
|
67
69
|
// Folding them into the system prompt mutates the front of the provider
|
|
68
70
|
// payload, so prefix-matching prompt caches miss and re-write the whole
|
|
69
71
|
// conversation at cache-write prices. Keep them positional instead.
|
|
70
|
-
|
|
72
|
+
if (text)
|
|
73
|
+
appendPositionalNote(messages, text, timestamp);
|
|
74
|
+
// Tools added mid-conversation stay in place, as Claude Code's `tool_addition` blocks do.
|
|
75
|
+
if (added.length > 0) {
|
|
76
|
+
messages.push({ role: "system", content: "", toolsAdded: added.map((tool) => toolToPi(tool, target.api)), timestamp });
|
|
77
|
+
}
|
|
71
78
|
continue;
|
|
72
79
|
}
|
|
73
80
|
sawConversationItem = true;
|
|
@@ -236,11 +243,14 @@ export function buildContext(request, target) {
|
|
|
236
243
|
const context = { messages };
|
|
237
244
|
if (systemParts.length > 0)
|
|
238
245
|
context.systemPrompt = systemParts.join("\n\n");
|
|
239
|
-
const clientTools = request.tools.filter((tool) =>
|
|
246
|
+
const clientTools = [...request.tools.filter((tool) => isSentTool(tool, target)), ...leadingTools];
|
|
240
247
|
if (clientTools.length > 0)
|
|
241
248
|
context.tools = clientTools.map((tool) => toolToPi(tool, target.api));
|
|
242
249
|
return context;
|
|
243
250
|
}
|
|
251
|
+
function isSentTool(tool, target) {
|
|
252
|
+
return tool.kind !== "hosted" && (tool.kind !== "server_tool" || target.api === "anthropic-messages");
|
|
253
|
+
}
|
|
244
254
|
function thinkingContent(item, continuation) {
|
|
245
255
|
if (continuation.kind === "openai_reasoning") {
|
|
246
256
|
const providerItemId = continuation.providerItemId ?? item.id;
|
|
@@ -1,14 +1,27 @@
|
|
|
1
|
-
import { routingCandidateKey, } from "@mupt-ai/dari-router/policy-engine";
|
|
1
|
+
import { previousDecisionFromHit, routingCandidateKey, } from "@mupt-ai/dari-router/policy-engine";
|
|
2
2
|
import { isBackgroundRequest } from "../../interaction/types.js";
|
|
3
3
|
import { HttpError } from "../../http/errors.js";
|
|
4
4
|
import { assertCreditAvailableBeforeRouting } from "../../telemetry/usage.js";
|
|
5
|
-
// Explicit background classes bypass the selector and every lease path.
|
|
6
|
-
//
|
|
5
|
+
// Explicit background classes bypass the selector and every lease path. As
|
|
6
|
+
// Claude Code does against Anthropic, work for an agent (compaction, side
|
|
7
|
+
// questions, prompt suggestions) runs on the model that agent is on. Claude
|
|
8
|
+
// Code names its small model itself, so the rest that reaches routing (a
|
|
9
|
+
// safety check, a web search) runs on the cheapest model.
|
|
7
10
|
export function auxiliaryDecision(prepared) {
|
|
8
11
|
if (!isBackgroundRequest(prepared.interaction))
|
|
9
12
|
return null;
|
|
10
13
|
assertCreditAvailableBeforeRouting(prepared.billable, prepared.credentials);
|
|
11
14
|
const requestClass = prepared.interaction.agentContext.requestClass;
|
|
15
|
+
const agent = agentCandidate(prepared);
|
|
16
|
+
if (agent) {
|
|
17
|
+
return {
|
|
18
|
+
decision: {
|
|
19
|
+
selectedModel: agent.model,
|
|
20
|
+
reasoningEffort: agent.reasoningEffort,
|
|
21
|
+
reason: `${requestClass} request served on its agent's model without selection.`,
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
}
|
|
12
25
|
const cheapest = cheapestCandidate(prepared);
|
|
13
26
|
if (!cheapest) {
|
|
14
27
|
throw new HttpError(503, "Background requests require a routable model with known pricing.", "background_model_unavailable");
|
|
@@ -20,6 +33,24 @@ export function auxiliaryDecision(prepared) {
|
|
|
20
33
|
};
|
|
21
34
|
return { decision };
|
|
22
35
|
}
|
|
36
|
+
/* The pair the agent is on (its lease target, else what it was last served)
|
|
37
|
+
or, when this request cannot take that pair (a forced tool rules out
|
|
38
|
+
thinking), one of those models at a level it can. */
|
|
39
|
+
function agentCandidate(prepared) {
|
|
40
|
+
const row = prepared.agentRow;
|
|
41
|
+
if (row === undefined)
|
|
42
|
+
return null;
|
|
43
|
+
const candidates = prepared.routing.candidateResolution.candidates;
|
|
44
|
+
const pair = previousDecisionFromHit(row, candidates);
|
|
45
|
+
if (pair)
|
|
46
|
+
return { model: pair.model, reasoningEffort: pair.reasoningEffort };
|
|
47
|
+
for (const model of [row.next_model, row.model]) {
|
|
48
|
+
const candidate = candidates.find((candidate) => candidate.model === model);
|
|
49
|
+
if (candidate)
|
|
50
|
+
return candidate;
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
23
54
|
/* Ranked on estimated input cost: these requests carry a whole transcript in
|
|
24
55
|
and a sentence out, so the prompt dominates. Estimates cover the configured
|
|
25
56
|
roster, so they are narrowed to the candidates pruning actually left
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type RouterPrefixHit } from "@mupt-ai/dari-router/policy-engine";
|
|
1
2
|
import { type RoutingContext } from "../context/routing_context.js";
|
|
2
3
|
import { type InteractionRequest } from "../interaction/types.js";
|
|
3
4
|
import { type RequestTags, type SessionPin } from "../platform/platform.js";
|
|
@@ -22,6 +23,7 @@ export type PreparedRoutedCompletion = {
|
|
|
22
23
|
};
|
|
23
24
|
role?: RouterRole;
|
|
24
25
|
rolePrompt?: string;
|
|
26
|
+
agentRow?: RouterPrefixHit;
|
|
25
27
|
reporter: RoutedRuntimeReporter;
|
|
26
28
|
};
|
|
27
29
|
export declare function prepareRoutedCompletion(args: {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { newestConversationHit, } from "@mupt-ai/dari-router/policy-engine";
|
|
1
2
|
import { interactionConversationPrefix } from "../context/interaction_fingerprint.js";
|
|
2
3
|
import { clampRequestedEffort } from "../context/routing_context.js";
|
|
3
4
|
import { modelMetadataLookup } from "../providers/pi.js";
|
|
@@ -6,7 +7,7 @@ import { isBackgroundRequest } from "../interaction/types.js";
|
|
|
6
7
|
import { executionProviderForModel } from "../models/execution_provider.js";
|
|
7
8
|
import { codexModelConfig, subscriptionServes } from "../models/subscriptions.js";
|
|
8
9
|
import { explicitModelId } from "../protocol/input/router_model.js";
|
|
9
|
-
import { gatewayPlatform } from "../platform/platform.js";
|
|
10
|
+
import { gatewayPlatform, } from "../platform/platform.js";
|
|
10
11
|
import { resolveRouter } from "../strategies/routing.js";
|
|
11
12
|
import { RequestReporter } from "../telemetry/report.js";
|
|
12
13
|
import { RoutingBillingFinalization } from "../telemetry/billing_finalization.js";
|
|
@@ -88,6 +89,20 @@ export async function prepareRoutedCompletion(args) {
|
|
|
88
89
|
}
|
|
89
90
|
credentials = conversationCredentials;
|
|
90
91
|
}
|
|
92
|
+
// Claude Code runs compaction, side questions and its other forked work on
|
|
93
|
+
// the model of the agent they serve. On routing, that is the model the
|
|
94
|
+
// agent's conversation is on, read from its latest row.
|
|
95
|
+
const agentRow = background
|
|
96
|
+
&& args.harnessConversationIdentity !== undefined
|
|
97
|
+
&& credentials.strict !== true
|
|
98
|
+
&& explicitModelId(args.interaction.model) === null
|
|
99
|
+
? await agentConversationRow({
|
|
100
|
+
resolveRequest: { routerId: args.routerId, apiKey: args.apiKey, clientHarness: args.clientHarness },
|
|
101
|
+
identity: args.harnessConversationIdentity,
|
|
102
|
+
interaction: args.interaction,
|
|
103
|
+
scope: harnessScope,
|
|
104
|
+
})
|
|
105
|
+
: undefined;
|
|
91
106
|
const roleModel = withRoleModel(credentials, args.interaction);
|
|
92
107
|
const prompt = rolePrompt(credentials, args.interaction);
|
|
93
108
|
const strictAccess = strictProviderAccess(credentials, roleModel.interaction);
|
|
@@ -176,9 +191,35 @@ export async function prepareRoutedCompletion(args) {
|
|
|
176
191
|
...(sessionPin === undefined ? {} : { sessionPin }),
|
|
177
192
|
...(roleModel.role === undefined ? {} : { role: roleModel.role }),
|
|
178
193
|
...(prompt === undefined ? {} : { rolePrompt: prompt }),
|
|
194
|
+
...(agentRow === undefined ? {} : { agentRow }),
|
|
179
195
|
reporter,
|
|
180
196
|
};
|
|
181
197
|
}
|
|
198
|
+
/* The latest row of the conversation a background request works for. Forked
|
|
199
|
+
work carries that agent's transcript, so it names the same conversation
|
|
200
|
+
under the agent's own request class. An agent with an id is usually a
|
|
201
|
+
subagent, which Claude Code may have run as a workflow agent, but may be a
|
|
202
|
+
main agent (an Agent Teams teammate). Other background work
|
|
203
|
+
(a web search, a safety check) carries its own transcript and finds none. */
|
|
204
|
+
async function agentConversationRow(args) {
|
|
205
|
+
const namedAgent = (args.identity.qualifiers?.length ?? 0) > 0
|
|
206
|
+
|| (args.identity.kind === "codex_thread" && args.identity.parentThreadId !== undefined);
|
|
207
|
+
const prefix = interactionConversationPrefix(args.interaction);
|
|
208
|
+
for (const requestClass of namedAgent ? ["subagent", "workflow", "main"] : ["main"]) {
|
|
209
|
+
const conversationId = scopedHarnessConversationId({
|
|
210
|
+
identity: args.identity,
|
|
211
|
+
sourceProtocol: args.interaction.sourceProtocol,
|
|
212
|
+
scope: args.scope,
|
|
213
|
+
conversationPrefix: JSON.stringify([requestClass, prefix]),
|
|
214
|
+
});
|
|
215
|
+
// Read-only: none of this resolve's credentials serve the request.
|
|
216
|
+
const resolved = await resolveRouter({ ...args.resolveRequest, conversationId, provisional: true });
|
|
217
|
+
const row = newestConversationHit(resolved.prefix_hits, conversationId)?.entry;
|
|
218
|
+
if (row !== undefined)
|
|
219
|
+
return row;
|
|
220
|
+
}
|
|
221
|
+
return undefined;
|
|
222
|
+
}
|
|
182
223
|
// Ask the platform for each enabled model's credential up front, so provider
|
|
183
224
|
// execution stays synchronous.
|
|
184
225
|
async function withProviderCredentials(credentials, apiKey, clientHarness) {
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The self-hosted gateway's Activity: each served request's log row in the
|
|
3
|
+
* gateway's SQLite database, in the same tables and columns hosted Dari keeps
|
|
4
|
+
* in Postgres, so the gateway's Activity reads (`../activity/`) serve both.
|
|
5
|
+
*
|
|
6
|
+
* Routers come from the config file and API keys are the gateway keys; both
|
|
7
|
+
* are mirrored into the tables Activity joins for their names. There are no
|
|
8
|
+
* people. Retained request and response bodies live in their own table, and
|
|
9
|
+
* nothing is retained for a ZDR router.
|
|
10
|
+
*/
|
|
11
|
+
import type { Database } from "bun:sqlite";
|
|
12
|
+
import { type ActivityDb } from "../activity/sql.js";
|
|
13
|
+
export declare const SELF_HOSTED_BLOB_BUCKET = "gateway";
|
|
14
|
+
type Row = Record<string, unknown>;
|
|
15
|
+
export declare class ActivityStore {
|
|
16
|
+
private readonly db;
|
|
17
|
+
/** The database the gateway's Activity reads query. */
|
|
18
|
+
readonly reads: ActivityDb;
|
|
19
|
+
constructor(db: Database);
|
|
20
|
+
/**
|
|
21
|
+
* Mirror the configured routers and the gateway keys into the tables
|
|
22
|
+
* Activity reads names from. Routers removed from the config keep their
|
|
23
|
+
* name, marked deleted, so their past traffic still reads well.
|
|
24
|
+
*/
|
|
25
|
+
syncDirectory(organizationId: string, routers: ReadonlyArray<{
|
|
26
|
+
id: string;
|
|
27
|
+
zdr: boolean;
|
|
28
|
+
}>, gatewayKeyCount: number): void;
|
|
29
|
+
/** Store one served request's report: its row, tool events, and bodies. */
|
|
30
|
+
record(report: Row): void;
|
|
31
|
+
/** A retained body, or null. */
|
|
32
|
+
readBlob(key: string): string | null;
|
|
33
|
+
private modelSwitched;
|
|
34
|
+
}
|
|
35
|
+
export {};
|