@mupt-ai/dari-gateway 1.0.369 → 1.0.371
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 +1 -0
- package/dist/harnesses/claude_code.d.ts +11 -0
- package/dist/{ingress/claude_code/request_context.js → harnesses/claude_code.js} +40 -1
- package/dist/harnesses/codex.d.ts +9 -0
- package/dist/harnesses/codex.js +112 -0
- package/dist/harnesses/hermes.d.ts +4 -0
- package/dist/harnesses/hermes.js +6 -0
- package/dist/harnesses/index.d.ts +34 -0
- package/dist/harnesses/index.js +13 -0
- package/dist/harnesses/muse_code.d.ts +9 -0
- package/dist/harnesses/muse_code.js +22 -0
- package/dist/harnesses/openclaw.d.ts +4 -0
- package/dist/harnesses/openclaw.js +6 -0
- package/dist/harnesses/opencode.d.ts +7 -0
- package/dist/harnesses/opencode.js +40 -0
- package/dist/harnesses/pi.d.ts +6 -0
- package/dist/harnesses/pi.js +23 -0
- package/dist/ingress/client_harness.d.ts +1 -2
- package/dist/ingress/client_harness.js +4 -39
- package/dist/ingress/harness_request.js +6 -3
- package/dist/ingress/models.js +2 -1
- package/dist/link/endpoints.js +5 -5
- package/dist/providers/execution.d.ts +1 -0
- package/dist/providers/execution.js +27 -7
- package/dist/runtime/harness_identity/extract.d.ts +0 -8
- package/dist/runtime/harness_identity/extract.js +2 -201
- package/dist/runtime/harness_identity/ids.d.ts +2 -0
- package/dist/runtime/harness_identity/ids.js +26 -0
- package/dist/runtime/harness_identity/index.d.ts +1 -1
- package/dist/runtime/harness_identity/index.js +1 -1
- package/dist/runtime/routed_completion.js +2 -1
- package/dist/self_host/activity_store.d.ts +7 -0
- package/dist/self_host/activity_store.js +24 -0
- package/dist/self_host/config.js +1 -1
- package/dist/self_host/hosted_sync.d.ts +2 -0
- package/dist/self_host/hosted_sync.js +4 -0
- package/dist/self_host/main.d.ts +2 -0
- package/dist/self_host/main.js +38 -0
- package/dist/self_host/router_models.js +1 -1
- package/dist/types.d.ts +1 -1
- package/package.json +2 -2
- package/src/{ingress/claude_code/request_context.ts → harnesses/claude_code.ts} +56 -2
- package/src/harnesses/codex.ts +156 -0
- package/src/harnesses/hermes.ts +8 -0
- package/src/harnesses/index.ts +29 -0
- package/src/harnesses/muse_code.ts +30 -0
- package/src/harnesses/openclaw.ts +8 -0
- package/src/harnesses/opencode.ts +51 -0
- package/src/harnesses/pi.ts +28 -0
- package/src/ingress/client_harness.ts +4 -41
- package/src/ingress/harness_request.ts +9 -9
- package/src/ingress/models.ts +2 -1
- package/src/link/endpoints.ts +5 -5
- package/src/providers/execution.ts +34 -7
- package/src/runtime/harness_identity/extract.ts +2 -284
- package/src/runtime/harness_identity/ids.ts +41 -0
- package/src/runtime/harness_identity/index.ts +1 -10
- package/src/runtime/routed_completion.ts +2 -1
- package/src/self_host/activity_store.ts +28 -0
- package/src/self_host/config.ts +1 -1
- package/src/self_host/hosted_sync.ts +5 -0
- package/src/self_host/main.ts +37 -0
- package/src/self_host/router_models.ts +1 -1
- package/src/types.ts +2 -10
- package/dist/ingress/claude_code/request_context.d.ts +0 -4
- package/dist/ingress/muse_code.d.ts +0 -2
- package/dist/ingress/muse_code.js +0 -8
- package/src/ingress/muse_code.ts +0 -9
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
const MAX_ID_CHARS = 200;
|
|
1
|
+
import { openCodeSubagentId } from "../../harnesses/opencode.js";
|
|
2
|
+
import { boundedIdentity } from "./ids.js";
|
|
4
3
|
export function chatCompletionsConversationIdentity(headers, promptCacheKey) {
|
|
5
4
|
// Pi summaries use fresh cache/affinity IDs. Its explicit session header
|
|
6
5
|
// groups them with the main turns without changing provider cache affinity.
|
|
@@ -18,201 +17,3 @@ export function chatCompletionsConversationIdentity(headers, promptCacheKey) {
|
|
|
18
17
|
...(subagentId === undefined ? {} : { qualifiers: [subagentId] }),
|
|
19
18
|
};
|
|
20
19
|
}
|
|
21
|
-
export function piRequestContext(headers) {
|
|
22
|
-
if (boundedIdentity(headers.get("x-pi-session-id"), "x-pi-session-id") === undefined) {
|
|
23
|
-
return undefined;
|
|
24
|
-
}
|
|
25
|
-
const kind = headers.get("x-pi-request-kind")?.trim();
|
|
26
|
-
return {
|
|
27
|
-
requestClass: kind === "turn" ? "main"
|
|
28
|
-
: kind === "compaction" ? "compaction"
|
|
29
|
-
// The Dari extension's web search tool: one request beside the turn,
|
|
30
|
-
// served as background work like Claude Code's own search.
|
|
31
|
-
: kind === "search" ? "auxiliary"
|
|
32
|
-
: "unknown",
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
// OpenCode names the session behind every request, and a subagent's parent
|
|
36
|
-
// session too. The `dari opencode` plugin adds the request kind and agent,
|
|
37
|
-
// which OpenCode does not send itself. Like Claude Code's headers, these are
|
|
38
|
-
// client-supplied routing hints, never inferred from prompt text.
|
|
39
|
-
export function openCodeRequestContext(headers) {
|
|
40
|
-
if (boundedIdentity(headers.get("x-opencode-session-id"), "x-opencode-session-id") === undefined) {
|
|
41
|
-
return undefined;
|
|
42
|
-
}
|
|
43
|
-
const kind = headers.get("x-opencode-request-kind")?.trim();
|
|
44
|
-
const subagentId = openCodeSubagentId(headers);
|
|
45
|
-
const requestClass = kind === "compaction" ? "compaction"
|
|
46
|
-
: kind === "title" || kind === "generate" ? "auxiliary"
|
|
47
|
-
: subagentId === undefined ? "main" : "subagent";
|
|
48
|
-
return {
|
|
49
|
-
requestClass,
|
|
50
|
-
...(subagentId === undefined ? {} : {
|
|
51
|
-
agentId: subagentId,
|
|
52
|
-
parentAgentId: boundedIdentity(headers.get("x-opencode-parent-session-id"), "x-opencode-parent-session-id"),
|
|
53
|
-
}),
|
|
54
|
-
agentType: boundedIdentity(headers.get("x-opencode-agent"), "x-opencode-agent"),
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
function openCodeSubagentId(headers) {
|
|
58
|
-
const parent = boundedIdentity(headers.get("x-opencode-parent-session-id"), "x-opencode-parent-session-id");
|
|
59
|
-
return parent === undefined
|
|
60
|
-
? undefined
|
|
61
|
-
: boundedIdentity(headers.get("x-opencode-session-id"), "x-opencode-session-id");
|
|
62
|
-
}
|
|
63
|
-
export function codexConversationIdentity(headers, payload) {
|
|
64
|
-
const clientMetadata = isRecord(payload.client_metadata)
|
|
65
|
-
? payload.client_metadata
|
|
66
|
-
: undefined;
|
|
67
|
-
const turnMetadata = codexTurnMetadataCollection(headers, payload);
|
|
68
|
-
if (turnMetadata.length === 0) {
|
|
69
|
-
return undefined;
|
|
70
|
-
}
|
|
71
|
-
// Clients can carry a stale projection after a resume or fork. Conflicts
|
|
72
|
-
// must not fail the request, and fields must not mix across projections:
|
|
73
|
-
// take thread, turn, and parent from one turn metadata projection, header
|
|
74
|
-
// first, falling back to the standalone thread fields only for the thread.
|
|
75
|
-
const entry = turnMetadata.find((metadata) => metadata.thread_id !== undefined)
|
|
76
|
-
?? turnMetadata[0];
|
|
77
|
-
const threadId = uuidIdentity(entry.thread_id, "x-codex-turn-metadata.thread_id")
|
|
78
|
-
?? uuidIdentity(headers.get("thread-id"), "thread-id")
|
|
79
|
-
?? uuidIdentity(clientMetadata?.thread_id, "client_metadata.thread_id");
|
|
80
|
-
if (threadId === undefined) {
|
|
81
|
-
return undefined;
|
|
82
|
-
}
|
|
83
|
-
const userTurnId = uuidIdentity(entry.turn_id, "x-codex-turn-metadata.turn_id");
|
|
84
|
-
const parentThreadId = uuidIdentity(entry.parent_thread_id, "x-codex-turn-metadata.parent_thread_id");
|
|
85
|
-
return {
|
|
86
|
-
kind: "codex_thread",
|
|
87
|
-
value: threadId,
|
|
88
|
-
...(parentThreadId === undefined ? {} : { parentThreadId }),
|
|
89
|
-
...(userTurnId === undefined ? {} : { userTurnId }),
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
export function codexRequestPurpose(headers, payload) {
|
|
93
|
-
const turnMetadata = codexTurnMetadataCollection(headers, payload);
|
|
94
|
-
return turnMetadata.length > 0 && turnMetadata.every(isCodexMemoryExtraction)
|
|
95
|
-
? "memory_extraction"
|
|
96
|
-
: undefined;
|
|
97
|
-
}
|
|
98
|
-
export function codexRequestContext(headers, payload) {
|
|
99
|
-
const metadata = codexTurnMetadataCollection(headers, payload);
|
|
100
|
-
if (metadata.length === 0)
|
|
101
|
-
return undefined;
|
|
102
|
-
// Classify from one projection, header first, skipping one that omits the
|
|
103
|
-
// request kind so a partial header falls back to a complete body.
|
|
104
|
-
const entry = metadata.find((candidate) => candidate.request_kind !== undefined)
|
|
105
|
-
?? metadata[0];
|
|
106
|
-
const kind = entry.request_kind;
|
|
107
|
-
const agentKind = entry.subagent_kind;
|
|
108
|
-
const agentId = uuidIdentity(entry.thread_id, "x-codex-turn-metadata.thread_id");
|
|
109
|
-
const requestClass = kind === "compaction" ? "compaction"
|
|
110
|
-
: kind === "memory" || kind === "prewarm" ? "auxiliary"
|
|
111
|
-
: kind === "turn" && agentKind === "memory_consolidation" ? "auxiliary"
|
|
112
|
-
: kind === "turn" && agentKind === "compact" ? "compaction"
|
|
113
|
-
: kind === "turn" && agentKind !== undefined ? "subagent"
|
|
114
|
-
: kind === "turn" ? "main" : "unknown";
|
|
115
|
-
return {
|
|
116
|
-
requestClass,
|
|
117
|
-
...(requestClass === "subagent" && agentId !== undefined ? { agentId } : {}),
|
|
118
|
-
parentAgentId: uuidIdentity(entry.parent_thread_id, "x-codex-turn-metadata.parent_thread_id"),
|
|
119
|
-
agentType: boundedIdentity(agentKind, "x-codex-turn-metadata.subagent_kind"),
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
// Muse Code sends its thread on every Responses request. The main agent's
|
|
123
|
-
// thread is its session, and each subagent has its own thread, so each keeps
|
|
124
|
-
// its own conversation and lease.
|
|
125
|
-
export function museCodeConversationIdentity(headers) {
|
|
126
|
-
const threadId = boundedIdentity(headers.get("x-tbh-thread-id"), "x-tbh-thread-id");
|
|
127
|
-
return threadId === undefined ? undefined : { kind: "muse_code_thread", value: threadId };
|
|
128
|
-
}
|
|
129
|
-
export function claudeCodeConversationIdentity(headers, metadataSessionId) {
|
|
130
|
-
const candidates = [
|
|
131
|
-
uuidIdentity(headers.get("x-claude-code-session-id"), "x-claude-code-session-id"),
|
|
132
|
-
uuidIdentity(metadataSessionId, "metadata.user_id.session_id"),
|
|
133
|
-
].filter((value) => value !== undefined);
|
|
134
|
-
if (candidates.length === 0)
|
|
135
|
-
return undefined;
|
|
136
|
-
// Claude Code can carry a stale metadata session after a resume or fork.
|
|
137
|
-
// The header names the live session, so it wins over the metadata.
|
|
138
|
-
const [sessionId] = candidates;
|
|
139
|
-
// Claude Code reuses the parent session UUID for every subagent, but gives
|
|
140
|
-
// each subagent a stable agent header. Keep the parent thread on the bare
|
|
141
|
-
// session identity and scope each subagent to its own composite identity.
|
|
142
|
-
// Treat this as an opaque Claude identifier. Besides ordinary subagent IDs,
|
|
143
|
-
// Claude may send labeled agents or Agent Teams identities such as
|
|
144
|
-
// `reviewer@backend`; Dari only needs a stable, bounded value to hash.
|
|
145
|
-
const agentId = boundedIdentity(headers.get("x-claude-code-agent-id"), "x-claude-code-agent-id");
|
|
146
|
-
return {
|
|
147
|
-
kind: "claude_code_session",
|
|
148
|
-
value: sessionId,
|
|
149
|
-
...(agentId === undefined ? {} : { qualifiers: [agentId] }),
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
function isCodexMemoryExtraction(metadata) {
|
|
153
|
-
if (metadata.request_kind !== "memory" ||
|
|
154
|
-
metadata.thread_source !== "memory_consolidation") {
|
|
155
|
-
return false;
|
|
156
|
-
}
|
|
157
|
-
// Codex deliberately omits canonical turn identity for detached phase-1
|
|
158
|
-
// memory jobs, while compatibility projections still carry the live root
|
|
159
|
-
// thread UUID. Phase-2 consolidation agents use ordinary turn metadata and
|
|
160
|
-
// their own thread identities, so they do not match this shape.
|
|
161
|
-
return [
|
|
162
|
-
"session_id",
|
|
163
|
-
"thread_id",
|
|
164
|
-
"turn_id",
|
|
165
|
-
"root_turn_id",
|
|
166
|
-
"window_id",
|
|
167
|
-
"forked_from_thread_id",
|
|
168
|
-
].every((field) => metadata[field] === undefined);
|
|
169
|
-
}
|
|
170
|
-
function codexTurnMetadataCollection(headers, payload) {
|
|
171
|
-
const clientMetadata = isRecord(payload.client_metadata)
|
|
172
|
-
? payload.client_metadata
|
|
173
|
-
: undefined;
|
|
174
|
-
return [
|
|
175
|
-
codexTurnMetadata(headers.get("x-codex-turn-metadata"), "x-codex-turn-metadata"),
|
|
176
|
-
codexTurnMetadata(clientMetadata?.["x-codex-turn-metadata"], "client_metadata.x-codex-turn-metadata"),
|
|
177
|
-
].filter((value) => value !== undefined);
|
|
178
|
-
}
|
|
179
|
-
function boundedIdentity(value, field) {
|
|
180
|
-
if (value === undefined || value === null)
|
|
181
|
-
return undefined;
|
|
182
|
-
if (typeof value !== "string") {
|
|
183
|
-
throw new HttpError(400, `${field} must be a string.`, "invalid_request_error", field);
|
|
184
|
-
}
|
|
185
|
-
const normalized = value.trim();
|
|
186
|
-
if (!normalized)
|
|
187
|
-
return undefined;
|
|
188
|
-
if (normalized.length > MAX_ID_CHARS) {
|
|
189
|
-
throw new HttpError(400, `${field} must not exceed ${MAX_ID_CHARS} characters.`, "invalid_request_error", field);
|
|
190
|
-
}
|
|
191
|
-
return normalized;
|
|
192
|
-
}
|
|
193
|
-
function uuidIdentity(value, field) {
|
|
194
|
-
const normalized = boundedIdentity(value, field);
|
|
195
|
-
if (normalized === undefined)
|
|
196
|
-
return undefined;
|
|
197
|
-
const canonical = normalized.toLowerCase();
|
|
198
|
-
if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(canonical)) {
|
|
199
|
-
throw new HttpError(400, `${field} must be a UUID.`, "invalid_request_error", field);
|
|
200
|
-
}
|
|
201
|
-
return canonical;
|
|
202
|
-
}
|
|
203
|
-
function codexTurnMetadata(raw, field) {
|
|
204
|
-
if (raw === undefined || raw === null)
|
|
205
|
-
return undefined;
|
|
206
|
-
if (typeof raw !== "string") {
|
|
207
|
-
throw new HttpError(400, `${field} must be a JSON string.`, "invalid_request_error", field);
|
|
208
|
-
}
|
|
209
|
-
try {
|
|
210
|
-
const parsed = JSON.parse(raw);
|
|
211
|
-
if (!isRecord(parsed))
|
|
212
|
-
throw new Error("not an object");
|
|
213
|
-
return parsed;
|
|
214
|
-
}
|
|
215
|
-
catch {
|
|
216
|
-
throw new HttpError(400, `${field} must contain a JSON object.`, "invalid_request_error", field);
|
|
217
|
-
}
|
|
218
|
-
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { HttpError } from "../../http/errors.js";
|
|
2
|
+
const MAX_ID_CHARS = 200;
|
|
3
|
+
export function boundedIdentity(value, field) {
|
|
4
|
+
if (value === undefined || value === null)
|
|
5
|
+
return undefined;
|
|
6
|
+
if (typeof value !== "string") {
|
|
7
|
+
throw new HttpError(400, `${field} must be a string.`, "invalid_request_error", field);
|
|
8
|
+
}
|
|
9
|
+
const normalized = value.trim();
|
|
10
|
+
if (!normalized)
|
|
11
|
+
return undefined;
|
|
12
|
+
if (normalized.length > MAX_ID_CHARS) {
|
|
13
|
+
throw new HttpError(400, `${field} must not exceed ${MAX_ID_CHARS} characters.`, "invalid_request_error", field);
|
|
14
|
+
}
|
|
15
|
+
return normalized;
|
|
16
|
+
}
|
|
17
|
+
export function uuidIdentity(value, field) {
|
|
18
|
+
const normalized = boundedIdentity(value, field);
|
|
19
|
+
if (normalized === undefined)
|
|
20
|
+
return undefined;
|
|
21
|
+
const canonical = normalized.toLowerCase();
|
|
22
|
+
if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(canonical)) {
|
|
23
|
+
throw new HttpError(400, `${field} must be a UUID.`, "invalid_request_error", field);
|
|
24
|
+
}
|
|
25
|
+
return canonical;
|
|
26
|
+
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export { scopedHarnessAgentId, scopedHarnessConversationId, scopedHarnessSessionId, type HarnessConversationIdentity, type HarnessConversationScope, } from "./conversation.js";
|
|
2
|
-
export { chatCompletionsConversationIdentity
|
|
2
|
+
export { chatCompletionsConversationIdentity } from "./extract.js";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export { scopedHarnessAgentId, scopedHarnessConversationId, scopedHarnessSessionId, } from "./conversation.js";
|
|
2
|
-
export { chatCompletionsConversationIdentity
|
|
2
|
+
export { chatCompletionsConversationIdentity } from "./extract.js";
|
|
@@ -56,7 +56,8 @@ export async function handleRoutedCompletion(args) {
|
|
|
56
56
|
for (const [name, value] of Object.entries(args.responseHeaders?.(prepared.credentials) ?? {})) {
|
|
57
57
|
response.headers.set(name, value);
|
|
58
58
|
}
|
|
59
|
-
|
|
59
|
+
// Its X-Request-Id is the request the client is told it made.
|
|
60
|
+
return response;
|
|
60
61
|
}
|
|
61
62
|
catch (error) {
|
|
62
63
|
const terminal = prepared.reporter.freezeFailure(error);
|
|
@@ -41,6 +41,13 @@ export declare class ActivityStore {
|
|
|
41
41
|
saveSessionGitEvents(write: SessionGitEvents): Promise<void>;
|
|
42
42
|
/** Store a session's git events: what a step's tool output showed, or commits its git hook reported. */
|
|
43
43
|
private insertGitEvents;
|
|
44
|
+
/**
|
|
45
|
+
* Delete up to `limit` requests received before `cutoff`, with their bodies
|
|
46
|
+
* and (by cascade) their tool and git events, and up to `limit` git events
|
|
47
|
+
* reported apart from any request. Returns how many went, so a caller
|
|
48
|
+
* clears a large backlog a batch at a time without holding the database.
|
|
49
|
+
*/
|
|
50
|
+
prune(cutoff: Date, limit?: number): number;
|
|
44
51
|
/** A retained body, or null. */
|
|
45
52
|
readBlob(key: string): string | null;
|
|
46
53
|
private modelSwitched;
|
|
@@ -359,6 +359,30 @@ export class ActivityStore {
|
|
|
359
359
|
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(`rge_${randomUUID().replaceAll("-", "")}`, organizationId, routingRequestId, sourceProtocol ?? "", agentSessionId, occurredAt, int(event.ordinal), text(event.kind), text(event.repository), int(event.number), text(event.title), text(event.branch), text(event.commit_sha));
|
|
360
360
|
}
|
|
361
361
|
}
|
|
362
|
+
/**
|
|
363
|
+
* Delete up to `limit` requests received before `cutoff`, with their bodies
|
|
364
|
+
* and (by cascade) their tool and git events, and up to `limit` git events
|
|
365
|
+
* reported apart from any request. Returns how many went, so a caller
|
|
366
|
+
* clears a large backlog a batch at a time without holding the database.
|
|
367
|
+
*/
|
|
368
|
+
prune(cutoff, limit = 500) {
|
|
369
|
+
const before = canonicalInstant(instantFromDate(cutoff));
|
|
370
|
+
return this.db.transaction(() => {
|
|
371
|
+
const old = this.db.query(`select id, request_blob_key, response_blob_key, selector_prompt_blob_key, selector_output_blob_key
|
|
372
|
+
from routing_requests where received_at < ? limit ?`).all(before, limit);
|
|
373
|
+
for (const row of old) {
|
|
374
|
+
for (const key of [row.request_blob_key, row.response_blob_key, row.selector_prompt_blob_key, row.selector_output_blob_key]) {
|
|
375
|
+
if (key)
|
|
376
|
+
this.db.query("delete from routing_request_blobs where object_key = ?").run(key);
|
|
377
|
+
}
|
|
378
|
+
this.db.query("delete from routing_requests where id = ?").run(row.id);
|
|
379
|
+
}
|
|
380
|
+
const events = this.db.query(`delete from routing_git_events where id in (
|
|
381
|
+
select id from routing_git_events where routing_request_id is null and occurred_at < ? limit ?
|
|
382
|
+
)`).run(before, limit);
|
|
383
|
+
return old.length + events.changes;
|
|
384
|
+
})();
|
|
385
|
+
}
|
|
362
386
|
/** A retained body, or null. */
|
|
363
387
|
readBlob(key) {
|
|
364
388
|
const row = this.db.query("select body from routing_request_blobs where object_key = ?").get(key);
|
package/dist/self_host/config.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { isReasoningEffort, isRecord, providerForModel, } from "@mupt-ai/dari-router/policy-engine";
|
|
2
|
-
import { CLIENT_HARNESSES } from "../
|
|
2
|
+
import { CLIENT_HARNESSES } from "../harnesses/index.js";
|
|
3
3
|
import { checkSources, DEFAULT_RESET_MIN_HOURS } from "../models/sources.js";
|
|
4
4
|
import { modelKeyProviders, otherModelProviders, providerModel } from "../models/canonical.js";
|
|
5
5
|
const REDIRECT_HOST_PATTERN = /^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
|
|
@@ -27,6 +27,8 @@ export declare class HostedSync {
|
|
|
27
27
|
stop(): void;
|
|
28
28
|
/** Queue a served request's log row for hosted Activity. */
|
|
29
29
|
enqueue(row: Record<string, unknown>): void;
|
|
30
|
+
/** Drop rows queued before `cutoff` that hosted never took. */
|
|
31
|
+
prune(cutoff: Date): void;
|
|
30
32
|
private scheduleAccountsCheck;
|
|
31
33
|
private checkAccounts;
|
|
32
34
|
/** Send the queued request rows a batch at a time, unless hosted failed lately. */
|
|
@@ -69,6 +69,10 @@ export class HostedSync {
|
|
|
69
69
|
}
|
|
70
70
|
this.db.run("INSERT INTO hosted_request_outbox (row_json, queued_at) VALUES (?, ?)", [json, this.now()]);
|
|
71
71
|
}
|
|
72
|
+
/** Drop rows queued before `cutoff` that hosted never took. */
|
|
73
|
+
prune(cutoff) {
|
|
74
|
+
this.db.run("DELETE FROM hosted_request_outbox WHERE queued_at < ?", [cutoff.getTime()]);
|
|
75
|
+
}
|
|
72
76
|
scheduleAccountsCheck(delayMs) {
|
|
73
77
|
this.accountsTimer = setTimeout(() => void this.checkAccounts(), delayMs);
|
|
74
78
|
this.accountsTimer.unref?.();
|
package/dist/self_host/main.d.ts
CHANGED
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
* saved model lists and router specs, prefix-cache state, and Activity:
|
|
14
14
|
* each request's log row and, outside ZDR routers, its request and response
|
|
15
15
|
* bodies (default `dari-gateway.db`). It holds subscription tokens.
|
|
16
|
+
* - `DARI_GATEWAY_RETENTION_DAYS`: how many days of Activity, and of requests
|
|
17
|
+
* waiting to sync to hosted Dari, the database keeps (default 7).
|
|
16
18
|
* - `DARI_GATEWAY_ENCRYPTION_KEY`: encrypts the subscription tokens and API
|
|
17
19
|
* keys in the database (`openssl rand -base64 32`; see secret_box.ts for
|
|
18
20
|
* rotation). Unset, they are stored as they are, and the Dari Link approval
|
package/dist/self_host/main.js
CHANGED
|
@@ -32,6 +32,10 @@ const CANONICAL_MODELS_ROUTE = "/v1/canonical-models";
|
|
|
32
32
|
// How often a connected gateway reads idle plans' usage, so their meters move
|
|
33
33
|
// without a request here.
|
|
34
34
|
const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
|
|
35
|
+
// How long Activity and unsent outbox rows are kept, unless
|
|
36
|
+
// DARI_GATEWAY_RETENTION_DAYS says otherwise, and how often old ones go.
|
|
37
|
+
const DEFAULT_RETENTION_DAYS = 7;
|
|
38
|
+
const PRUNE_INTERVAL_MS = 60 * 60_000;
|
|
35
39
|
/**
|
|
36
40
|
* Start a self-hosted Dari Gateway from environment variables:
|
|
37
41
|
*
|
|
@@ -46,6 +50,8 @@ const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
|
|
|
46
50
|
* saved model lists and router specs, prefix-cache state, and Activity:
|
|
47
51
|
* each request's log row and, outside ZDR routers, its request and response
|
|
48
52
|
* bodies (default `dari-gateway.db`). It holds subscription tokens.
|
|
53
|
+
* - `DARI_GATEWAY_RETENTION_DAYS`: how many days of Activity, and of requests
|
|
54
|
+
* waiting to sync to hosted Dari, the database keeps (default 7).
|
|
49
55
|
* - `DARI_GATEWAY_ENCRYPTION_KEY`: encrypts the subscription tokens and API
|
|
50
56
|
* keys in the database (`openssl rand -base64 32`; see secret_box.ts for
|
|
51
57
|
* rotation). Unset, they are stored as they are, and the Dari Link approval
|
|
@@ -73,6 +79,7 @@ export async function startSelfHostedGateway(env = process.env) {
|
|
|
73
79
|
if (gatewayKeys.length === 0) {
|
|
74
80
|
throw new Error("Set DARI_GATEWAY_KEYS to the comma-separated keys clients authenticate with.");
|
|
75
81
|
}
|
|
82
|
+
const retentionDays = retentionDaysFromEnv(env.DARI_GATEWAY_RETENTION_DAYS);
|
|
76
83
|
const config = await loadGatewayConfig(env.DARI_GATEWAY_CONFIG?.trim() || undefined);
|
|
77
84
|
const routersDir = env.DARI_GATEWAY_ROUTERS_DIR?.trim();
|
|
78
85
|
const specFiles = routersDir ? await loadRouterSpecDirectory(routersDir) : undefined;
|
|
@@ -218,6 +225,24 @@ export async function startSelfHostedGateway(env = process.env) {
|
|
|
218
225
|
if (env.DARI_SESSION_PORT_FILE)
|
|
219
226
|
await Bun.write(env.DARI_SESSION_PORT_FILE, String(server.port));
|
|
220
227
|
sync?.start();
|
|
228
|
+
// A batch at a time, so a large backlog never holds up requests.
|
|
229
|
+
let closed = false;
|
|
230
|
+
let pruned = null;
|
|
231
|
+
const prune = () => {
|
|
232
|
+
pruned ??= (async () => {
|
|
233
|
+
const cutoff = new Date(Date.now() - retentionDays * 24 * 60 * 60_000);
|
|
234
|
+
sync?.prune(cutoff);
|
|
235
|
+
while (!closed && activity.prune(cutoff) > 0)
|
|
236
|
+
await Bun.sleep(0);
|
|
237
|
+
})().catch((error) => {
|
|
238
|
+
console.error("Activity retention failed", error instanceof Error ? error.message : String(error));
|
|
239
|
+
}).finally(() => {
|
|
240
|
+
pruned = null;
|
|
241
|
+
});
|
|
242
|
+
};
|
|
243
|
+
prune();
|
|
244
|
+
const pruning = setInterval(prune, PRUNE_INTERVAL_MS);
|
|
245
|
+
pruning.unref?.();
|
|
221
246
|
const idleUsage = sync === null ? null : setInterval(() => {
|
|
222
247
|
void refreshStaleUsage(subscriptions, { fetch, baseUrls });
|
|
223
248
|
}, IDLE_USAGE_INTERVAL_MS);
|
|
@@ -225,6 +250,8 @@ export async function startSelfHostedGateway(env = process.env) {
|
|
|
225
250
|
return {
|
|
226
251
|
server,
|
|
227
252
|
close: () => {
|
|
253
|
+
closed = true;
|
|
254
|
+
clearInterval(pruning);
|
|
228
255
|
if (idleUsage !== null)
|
|
229
256
|
clearInterval(idleUsage);
|
|
230
257
|
sync?.stop();
|
|
@@ -232,6 +259,17 @@ export async function startSelfHostedGateway(env = process.env) {
|
|
|
232
259
|
},
|
|
233
260
|
};
|
|
234
261
|
}
|
|
262
|
+
/** DARI_GATEWAY_RETENTION_DAYS as a whole number of days; unset, the default. */
|
|
263
|
+
function retentionDaysFromEnv(raw) {
|
|
264
|
+
const value = raw?.trim();
|
|
265
|
+
if (!value)
|
|
266
|
+
return DEFAULT_RETENTION_DAYS;
|
|
267
|
+
const days = Number(value);
|
|
268
|
+
if (!Number.isInteger(days) || days < 1) {
|
|
269
|
+
throw new Error(`DARI_GATEWAY_RETENTION_DAYS must be a whole number of days, at least 1; got ${JSON.stringify(raw)}.`);
|
|
270
|
+
}
|
|
271
|
+
return days;
|
|
272
|
+
}
|
|
235
273
|
/**
|
|
236
274
|
* Check each provider API key the routers use before serving: a key its
|
|
237
275
|
* provider rejects fails startup, and one no check could answer is reported.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { errorResponse, HttpError } from "../http/errors.js";
|
|
2
|
-
import { CLIENT_HARNESSES } from "../
|
|
2
|
+
import { CLIENT_HARNESSES } from "../harnesses/index.js";
|
|
3
3
|
import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
4
4
|
import { DEFAULT_GATEWAY_CONFIG, parseRouterModels, } from "./config.js";
|
|
5
5
|
// A router's own list is saved under no agent.
|
package/dist/types.d.ts
CHANGED
|
@@ -48,7 +48,7 @@ export type PublicEvalCatalogCard = Omit<RouterEval, "scores"> & {
|
|
|
48
48
|
export type ServedDecision = RoutingDecision & {
|
|
49
49
|
sessionPinned?: boolean;
|
|
50
50
|
};
|
|
51
|
-
export type ClientHarness
|
|
51
|
+
export type { ClientHarness } from "./harnesses/index.js";
|
|
52
52
|
export type ResolvedRouterModelConfig = {
|
|
53
53
|
provider: string;
|
|
54
54
|
native_model_id: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mupt-ai/dari-gateway",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.371",
|
|
4
4
|
"description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@aws-sdk/client-sts": "3.1063.0",
|
|
55
|
-
"@mupt-ai/dari-router": "1.0.
|
|
55
|
+
"@mupt-ai/dari-router": "1.0.371",
|
|
56
56
|
"@mupt-ai/pi-ai": "1.5.2-mupt.3"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
@@ -1,5 +1,24 @@
|
|
|
1
|
-
import { HttpError } from "
|
|
2
|
-
import type { AgentRequestContext, AgentRequestClass } from "
|
|
1
|
+
import { HttpError } from "../http/errors.js";
|
|
2
|
+
import type { AgentRequestContext, AgentRequestClass } from "../interaction/types.js";
|
|
3
|
+
import { boundedIdentity, uuidIdentity } from "../runtime/harness_identity/ids.js";
|
|
4
|
+
import type { HarnessConversationIdentity } from "../runtime/harness_identity/conversation.js";
|
|
5
|
+
import type { Harness } from "./index.js";
|
|
6
|
+
|
|
7
|
+
export const claudeCode = {
|
|
8
|
+
id: "claude_code",
|
|
9
|
+
headers: [
|
|
10
|
+
"user-agent",
|
|
11
|
+
"x-app",
|
|
12
|
+
"anthropic-beta",
|
|
13
|
+
"x-claude-code-session-id",
|
|
14
|
+
"x-claude-code-request-class",
|
|
15
|
+
"x-claude-code-agent-id",
|
|
16
|
+
"x-claude-code-parent-agent-id",
|
|
17
|
+
"x-claude-code-agent-type",
|
|
18
|
+
],
|
|
19
|
+
// A Claude Code plan serves only Claude Code.
|
|
20
|
+
ownPlanOnly: true,
|
|
21
|
+
} as const satisfies Harness;
|
|
3
22
|
|
|
4
23
|
const REQUEST_CLASSES = new Set<AgentRequestClass>([
|
|
5
24
|
"main", "subagent", "workflow", "auxiliary", "compaction", "side_reply",
|
|
@@ -51,3 +70,38 @@ function identifier(headers: Headers, name: string): string | undefined {
|
|
|
51
70
|
}
|
|
52
71
|
return value;
|
|
53
72
|
}
|
|
73
|
+
|
|
74
|
+
export function claudeCodeConversationIdentity(
|
|
75
|
+
headers: Headers,
|
|
76
|
+
metadataSessionId?: string,
|
|
77
|
+
): HarnessConversationIdentity | undefined {
|
|
78
|
+
const candidates = [
|
|
79
|
+
uuidIdentity(
|
|
80
|
+
headers.get("x-claude-code-session-id"),
|
|
81
|
+
"x-claude-code-session-id",
|
|
82
|
+
),
|
|
83
|
+
uuidIdentity(
|
|
84
|
+
metadataSessionId,
|
|
85
|
+
"metadata.user_id.session_id",
|
|
86
|
+
),
|
|
87
|
+
].filter((value): value is string => value !== undefined);
|
|
88
|
+
if (candidates.length === 0) return undefined;
|
|
89
|
+
// Claude Code can carry a stale metadata session after a resume or fork.
|
|
90
|
+
// The header names the live session, so it wins over the metadata.
|
|
91
|
+
const [sessionId] = candidates;
|
|
92
|
+
// Claude Code reuses the parent session UUID for every subagent, but gives
|
|
93
|
+
// each subagent a stable agent header. Keep the parent thread on the bare
|
|
94
|
+
// session identity and scope each subagent to its own composite identity.
|
|
95
|
+
// Treat this as an opaque Claude identifier. Besides ordinary subagent IDs,
|
|
96
|
+
// Claude may send labeled agents or Agent Teams identities such as
|
|
97
|
+
// `reviewer@backend`; Dari only needs a stable, bounded value to hash.
|
|
98
|
+
const agentId = boundedIdentity(
|
|
99
|
+
headers.get("x-claude-code-agent-id"),
|
|
100
|
+
"x-claude-code-agent-id",
|
|
101
|
+
);
|
|
102
|
+
return {
|
|
103
|
+
kind: "claude_code_session",
|
|
104
|
+
value: sessionId,
|
|
105
|
+
...(agentId === undefined ? {} : { qualifiers: [agentId] }),
|
|
106
|
+
};
|
|
107
|
+
}
|