@mupt-ai/dari-gateway 1.0.374 → 1.0.375
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/dist/activity/filters.d.ts +1 -1
- package/dist/activity/filters.js +1 -1
- package/dist/harnesses/antigravity.d.ts +11 -0
- package/dist/harnesses/antigravity.js +47 -0
- package/dist/harnesses/index.d.ts +3 -0
- package/dist/harnesses/index.js +2 -1
- package/dist/http/auth.d.ts +1 -0
- package/dist/http/auth.js +11 -0
- package/dist/http/handler.d.ts +1 -1
- package/dist/http/handler.js +16 -1
- package/dist/ingress/gemini.d.ts +18 -0
- package/dist/ingress/gemini.js +181 -0
- package/dist/ingress/harness_request.js +6 -2
- package/dist/interaction/types.d.ts +1 -1
- package/dist/protocol/gemini_thought_signature.d.ts +2 -0
- package/dist/protocol/gemini_thought_signature.js +23 -0
- package/dist/protocol/input/gemini_generate_content.d.ts +4 -0
- package/dist/protocol/input/gemini_generate_content.js +293 -0
- package/dist/protocol/input/router_model.d.ts +1 -0
- package/dist/protocol/input/router_model.js +7 -0
- package/dist/protocol/output/gemini_generate_content.d.ts +17 -0
- package/dist/protocol/output/gemini_generate_content.js +102 -0
- package/dist/protocol/output/gemini_generate_content_stream.d.ts +17 -0
- package/dist/protocol/output/gemini_generate_content_stream.js +86 -0
- package/dist/runtime/harness_identity/conversation.d.ts +4 -0
- package/dist/self_host/connected.js +14 -7
- package/package.json +2 -2
- package/src/activity/filters.ts +1 -1
- package/src/harnesses/antigravity.ts +50 -0
- package/src/harnesses/index.ts +2 -1
- package/src/http/auth.ts +11 -0
- package/src/http/handler.ts +20 -1
- package/src/ingress/gemini.ts +206 -0
- package/src/ingress/harness_request.ts +5 -1
- package/src/interaction/types.ts +1 -1
- package/src/protocol/gemini_thought_signature.ts +23 -0
- package/src/protocol/input/gemini_generate_content.ts +297 -0
- package/src/protocol/input/router_model.ts +8 -0
- package/src/protocol/output/gemini_generate_content.ts +108 -0
- package/src/protocol/output/gemini_generate_content_stream.ts +101 -0
- package/src/runtime/harness_identity/conversation.ts +5 -0
- package/src/self_host/connected.ts +14 -7
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import { isRecord, type ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
|
|
2
|
+
|
|
3
|
+
import { HttpError } from "../../http/errors.js";
|
|
4
|
+
import { decodeUntrustedPortableReasoningState } from "../../interaction/portable_reasoning_state.js";
|
|
5
|
+
import { decodeUntrustedProviderContinuationState } from "../../interaction/provider_continuation_state.js";
|
|
6
|
+
import type {
|
|
7
|
+
InteractionContent,
|
|
8
|
+
InteractionItem,
|
|
9
|
+
InteractionReasoning,
|
|
10
|
+
InteractionRequest,
|
|
11
|
+
InteractionResponseFormat,
|
|
12
|
+
InteractionTool,
|
|
13
|
+
InteractionToolChoice,
|
|
14
|
+
ReasoningControls,
|
|
15
|
+
} from "../../interaction/types.js";
|
|
16
|
+
import { decodeGeminiThoughtSignature } from "../gemini_thought_signature.js";
|
|
17
|
+
import { geminiRouterModel } from "./router_model.js";
|
|
18
|
+
|
|
19
|
+
/* Gemini API generateContent, as Gemini CLI sends it. The model comes from the
|
|
20
|
+
request path, so the caller sets `payload.model`; `stream` comes from the
|
|
21
|
+
method (`streamGenerateContent`). */
|
|
22
|
+
export function geminiGenerateContentToInteraction(
|
|
23
|
+
payload: Record<string, unknown>,
|
|
24
|
+
args: { stream: boolean },
|
|
25
|
+
): InteractionRequest {
|
|
26
|
+
const config = optionalRecord(payload.generationConfig, "generationConfig") ?? {};
|
|
27
|
+
return {
|
|
28
|
+
sourceProtocol: "gemini_generate_content",
|
|
29
|
+
model: geminiRouterModel(requiredString(payload.model, "model")),
|
|
30
|
+
instructions: systemInstruction(payload.systemInstruction),
|
|
31
|
+
items: geminiItems(payload.contents),
|
|
32
|
+
tools: geminiTools(payload.tools),
|
|
33
|
+
toolChoice: geminiToolChoice(payload.toolConfig),
|
|
34
|
+
generation: {
|
|
35
|
+
temperature: optionalNumber(config.temperature, "generationConfig.temperature"),
|
|
36
|
+
topP: optionalNumber(config.topP, "generationConfig.topP"),
|
|
37
|
+
maxOutputTokens: optionalNumber(config.maxOutputTokens, "generationConfig.maxOutputTokens"),
|
|
38
|
+
stop: stopSequences(config.stopSequences),
|
|
39
|
+
},
|
|
40
|
+
reasoning: geminiReasoning(config.thinkingConfig),
|
|
41
|
+
responseFormat: geminiResponseFormat(config),
|
|
42
|
+
stream: args.stream,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function systemInstruction(value: unknown): string | undefined {
|
|
47
|
+
if (value === undefined || value === null) return undefined;
|
|
48
|
+
if (typeof value === "string") return value;
|
|
49
|
+
if (!isRecord(value) || !Array.isArray(value.parts)) {
|
|
50
|
+
throw invalidRequest("systemInstruction must be a Content object.", "systemInstruction");
|
|
51
|
+
}
|
|
52
|
+
const text = value.parts
|
|
53
|
+
.flatMap((part) => (isRecord(part) && typeof part.text === "string" && part.thought !== true ? [part.text] : []))
|
|
54
|
+
.join("\n");
|
|
55
|
+
return text.length > 0 ? text : undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/* Gemini function calls may come without ids (Gemini CLI strips its own), so a
|
|
59
|
+
missing id is synthesized per turn and position, and each functionResponse
|
|
60
|
+
without one pairs with the oldest open call of the same name. */
|
|
61
|
+
function geminiItems(value: unknown): InteractionItem[] {
|
|
62
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
63
|
+
throw invalidRequest("contents must be a non-empty array.", "contents");
|
|
64
|
+
}
|
|
65
|
+
const items: InteractionItem[] = [];
|
|
66
|
+
const openCalls: Array<{ callId: string; name: string }> = [];
|
|
67
|
+
for (const [turnIndex, rawContent] of value.entries()) {
|
|
68
|
+
const param = `contents.${turnIndex}`;
|
|
69
|
+
if (!isRecord(rawContent) || !Array.isArray(rawContent.parts)) {
|
|
70
|
+
throw invalidRequest(`${param} must be a Content object with parts.`, param);
|
|
71
|
+
}
|
|
72
|
+
const role = rawContent.role === "model" ? "assistant" : "user";
|
|
73
|
+
let buffered: InteractionContent[] = [];
|
|
74
|
+
const flush = () => {
|
|
75
|
+
if (buffered.length === 0) return;
|
|
76
|
+
items.push({ type: "message", role, content: buffered, contentShape: "parts" });
|
|
77
|
+
buffered = [];
|
|
78
|
+
};
|
|
79
|
+
let reasoningRestored = false;
|
|
80
|
+
for (const [partIndex, rawPart] of rawContent.parts.entries()) {
|
|
81
|
+
const partParam = `${param}.parts.${partIndex}`;
|
|
82
|
+
if (!isRecord(rawPart)) throw invalidRequest(`${partParam} must be an object.`, partParam);
|
|
83
|
+
// Dari's reasoning state rides on a part's signature; it precedes the turn's content.
|
|
84
|
+
if (role === "assistant" && !reasoningRestored && typeof rawPart.thoughtSignature === "string") {
|
|
85
|
+
const reasoning = signatureReasoning(rawPart.thoughtSignature, `${partParam}.thoughtSignature`);
|
|
86
|
+
if (reasoning !== null) {
|
|
87
|
+
flush();
|
|
88
|
+
items.push(...reasoning);
|
|
89
|
+
reasoningRestored = true;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
// Thought text is display-only; its state travels in the signature.
|
|
93
|
+
if (rawPart.thought === true) continue;
|
|
94
|
+
if (typeof rawPart.text === "string") {
|
|
95
|
+
if (rawPart.text.length > 0) buffered.push({ type: "text", text: rawPart.text });
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (isRecord(rawPart.inlineData)) {
|
|
99
|
+
buffered.push(inlineData(rawPart.inlineData, `${partParam}.inlineData`));
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (isRecord(rawPart.functionCall)) {
|
|
103
|
+
flush();
|
|
104
|
+
const call = rawPart.functionCall;
|
|
105
|
+
const name = requiredString(call.name, `${partParam}.functionCall.name`);
|
|
106
|
+
const callId = typeof call.id === "string" && call.id.length > 0 ? call.id : `call_${turnIndex}_${partIndex}`;
|
|
107
|
+
openCalls.push({ callId, name });
|
|
108
|
+
items.push({
|
|
109
|
+
type: "tool_call",
|
|
110
|
+
callId,
|
|
111
|
+
kind: "function",
|
|
112
|
+
name,
|
|
113
|
+
input: isRecord(call.args) ? call.args : {},
|
|
114
|
+
});
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (isRecord(rawPart.functionResponse)) {
|
|
118
|
+
flush();
|
|
119
|
+
const response = rawPart.functionResponse;
|
|
120
|
+
const name = requiredString(response.name, `${partParam}.functionResponse.name`);
|
|
121
|
+
const callId = pairedCallId(openCalls, response.id, name, turnIndex, partIndex);
|
|
122
|
+
items.push({
|
|
123
|
+
type: "tool_result",
|
|
124
|
+
callId,
|
|
125
|
+
kind: "function",
|
|
126
|
+
name,
|
|
127
|
+
output: JSON.stringify(response.response ?? {}),
|
|
128
|
+
outputShape: "string",
|
|
129
|
+
});
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (isRecord(rawPart.fileData)) {
|
|
133
|
+
throw new HttpError(400, "fileData parts are not supported; send the file as inlineData.", "unsupported_content", partParam);
|
|
134
|
+
}
|
|
135
|
+
// executableCode, codeExecutionResult, and other parts have no interaction form.
|
|
136
|
+
throw new HttpError(400, `${partParam} is not a supported Gemini part.`, "unsupported_content", partParam);
|
|
137
|
+
}
|
|
138
|
+
flush();
|
|
139
|
+
}
|
|
140
|
+
return items;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function pairedCallId(
|
|
144
|
+
openCalls: Array<{ callId: string; name: string }>,
|
|
145
|
+
id: unknown,
|
|
146
|
+
name: string,
|
|
147
|
+
turnIndex: number,
|
|
148
|
+
partIndex: number,
|
|
149
|
+
): string {
|
|
150
|
+
const index = typeof id === "string" && id.length > 0
|
|
151
|
+
? openCalls.findIndex((call) => call.callId === id)
|
|
152
|
+
: openCalls.findIndex((call) => call.name === name);
|
|
153
|
+
if (index >= 0) return openCalls.splice(index, 1)[0]!.callId;
|
|
154
|
+
return typeof id === "string" && id.length > 0 ? id : `call_${turnIndex}_${partIndex}`;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function signatureReasoning(signature: string, param: string): InteractionReasoning[] | null {
|
|
158
|
+
const states = decodeGeminiThoughtSignature(signature);
|
|
159
|
+
if (states === null) return null;
|
|
160
|
+
return states.map((state) => {
|
|
161
|
+
const continuation = decodeUntrustedProviderContinuationState(state);
|
|
162
|
+
if (continuation) return { type: "reasoning", summary: [], content: [], source: continuation.source, continuation };
|
|
163
|
+
const portable = decodeUntrustedPortableReasoningState(state);
|
|
164
|
+
if (!portable) {
|
|
165
|
+
throw new HttpError(400, `${param} carries an invalid Dari reasoning state.`, "invalid_provider_continuation_state", param);
|
|
166
|
+
}
|
|
167
|
+
return { type: "reasoning", summary: [], content: [], ...(portable.source ? { source: portable.source } : {}) };
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function inlineData(value: Record<string, unknown>, param: string): InteractionContent {
|
|
172
|
+
const mimeType = requiredString(value.mimeType, `${param}.mimeType`);
|
|
173
|
+
const data = requiredString(value.data, `${param}.data`);
|
|
174
|
+
if (mimeType === "application/pdf") return { type: "document", mimeType, data };
|
|
175
|
+
if (mimeType.startsWith("image/")) return { type: "image", url: `data:${mimeType};base64,${data}` };
|
|
176
|
+
throw new HttpError(400, `inlineData of type '${mimeType}' is not supported.`, "unsupported_content", `${param}.mimeType`);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function geminiTools(value: unknown): InteractionTool[] {
|
|
180
|
+
if (value === undefined || value === null) return [];
|
|
181
|
+
if (!Array.isArray(value)) throw invalidRequest("tools must be an array.", "tools");
|
|
182
|
+
const tools: InteractionTool[] = [];
|
|
183
|
+
for (const [toolIndex, rawTool] of value.entries()) {
|
|
184
|
+
const param = `tools.${toolIndex}`;
|
|
185
|
+
if (!isRecord(rawTool)) throw invalidRequest(`${param} must be an object.`, param);
|
|
186
|
+
if (rawTool.googleSearch !== undefined || rawTool.googleSearchRetrieval !== undefined) {
|
|
187
|
+
tools.push({ kind: "hosted", type: "web_search", config: {} });
|
|
188
|
+
}
|
|
189
|
+
// urlContext has no interaction form; Gemini CLI falls back to fetching the URL itself.
|
|
190
|
+
if (rawTool.functionDeclarations === undefined) continue;
|
|
191
|
+
if (!Array.isArray(rawTool.functionDeclarations)) {
|
|
192
|
+
throw invalidRequest(`${param}.functionDeclarations must be an array.`, `${param}.functionDeclarations`);
|
|
193
|
+
}
|
|
194
|
+
for (const [index, declaration] of rawTool.functionDeclarations.entries()) {
|
|
195
|
+
const declarationParam = `${param}.functionDeclarations.${index}`;
|
|
196
|
+
if (!isRecord(declaration)) throw invalidRequest(`${declarationParam} must be an object.`, declarationParam);
|
|
197
|
+
const parameters = isRecord(declaration.parametersJsonSchema)
|
|
198
|
+
? declaration.parametersJsonSchema
|
|
199
|
+
: isRecord(declaration.parameters) ? jsonSchema(declaration.parameters) as Record<string, unknown> : undefined;
|
|
200
|
+
tools.push({
|
|
201
|
+
kind: "function",
|
|
202
|
+
name: requiredString(declaration.name, `${declarationParam}.name`),
|
|
203
|
+
...(typeof declaration.description === "string" ? { description: declaration.description } : {}),
|
|
204
|
+
parameters: parameters ?? { type: "object", properties: {} },
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return tools;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Counts the Gemini API types as int64, which its JSON form writes as a string.
|
|
212
|
+
const SCHEMA_COUNTS = new Set(["minItems", "maxItems", "minLength", "maxLength", "minProperties", "maxProperties"]);
|
|
213
|
+
|
|
214
|
+
// The `parameters` form is OpenAPI with upper-case type names (`OBJECT`) and
|
|
215
|
+
// string counts (`"maxItems": "12"`).
|
|
216
|
+
function jsonSchema(value: unknown): unknown {
|
|
217
|
+
if (Array.isArray(value)) return value.map(jsonSchema);
|
|
218
|
+
if (!isRecord(value)) return value;
|
|
219
|
+
return Object.fromEntries(Object.entries(value).map(([key, entry]) => {
|
|
220
|
+
if (key === "type" && typeof entry === "string") return [key, entry.toLowerCase()];
|
|
221
|
+
if (SCHEMA_COUNTS.has(key) && typeof entry === "string" && /^\d+$/.test(entry)) return [key, Number(entry)];
|
|
222
|
+
return [key, jsonSchema(entry)];
|
|
223
|
+
}));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function geminiToolChoice(value: unknown): InteractionToolChoice | undefined {
|
|
227
|
+
if (!isRecord(value) || !isRecord(value.functionCallingConfig)) return undefined;
|
|
228
|
+
const { mode, allowedFunctionNames } = value.functionCallingConfig;
|
|
229
|
+
if (mode === "NONE") return "none";
|
|
230
|
+
if (mode === "ANY") {
|
|
231
|
+
return Array.isArray(allowedFunctionNames) && allowedFunctionNames.length === 1
|
|
232
|
+
&& typeof allowedFunctionNames[0] === "string"
|
|
233
|
+
? { kind: "function", name: allowedFunctionNames[0] }
|
|
234
|
+
: "required";
|
|
235
|
+
}
|
|
236
|
+
return mode === "AUTO" || mode === "VALIDATED" ? "auto" : undefined;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const THINKING_LEVELS: Record<string, ReasoningEffort> = {
|
|
240
|
+
MINIMAL: "minimal",
|
|
241
|
+
LOW: "low",
|
|
242
|
+
MEDIUM: "medium",
|
|
243
|
+
HIGH: "high",
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
function geminiReasoning(value: unknown): ReasoningControls | undefined {
|
|
247
|
+
if (value === undefined || value === null) return undefined;
|
|
248
|
+
if (!isRecord(value)) throw invalidRequest("thinkingConfig must be an object.", "generationConfig.thinkingConfig");
|
|
249
|
+
const level = typeof value.thinkingLevel === "string" ? THINKING_LEVELS[value.thinkingLevel.toUpperCase()] : undefined;
|
|
250
|
+
if (level !== undefined) return { effort: level, enabled: true };
|
|
251
|
+
const budget = value.thinkingBudget;
|
|
252
|
+
if (typeof budget !== "number") return undefined;
|
|
253
|
+
// Antigravity CLI sends a zero budget for any model it was not told thinks,
|
|
254
|
+
// so this asks for the "off" level, which a model without one does not take.
|
|
255
|
+
if (budget === 0) return { effort: "off" };
|
|
256
|
+
// -1 asks the model to pick its own budget. A token budget is Gemini's
|
|
257
|
+
// own unit, and the model served may be another maker's, so it only asks
|
|
258
|
+
// for thinking.
|
|
259
|
+
return { enabled: true };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function geminiResponseFormat(config: Record<string, unknown>): InteractionResponseFormat | undefined {
|
|
263
|
+
if (config.responseMimeType !== "application/json") return undefined;
|
|
264
|
+
const schema = isRecord(config.responseJsonSchema)
|
|
265
|
+
? config.responseJsonSchema
|
|
266
|
+
: isRecord(config.responseSchema) ? jsonSchema(config.responseSchema) as Record<string, unknown> : undefined;
|
|
267
|
+
return schema ? { type: "json_schema", name: "response", schema } : { type: "json_object" };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function stopSequences(value: unknown): string[] | undefined {
|
|
271
|
+
if (value === undefined || value === null) return undefined;
|
|
272
|
+
if (!Array.isArray(value) || !value.every((entry) => typeof entry === "string")) {
|
|
273
|
+
throw invalidRequest("stopSequences must be an array of strings.", "generationConfig.stopSequences");
|
|
274
|
+
}
|
|
275
|
+
return value;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function optionalRecord(value: unknown, param: string): Record<string, unknown> | undefined {
|
|
279
|
+
if (value === undefined || value === null) return undefined;
|
|
280
|
+
if (!isRecord(value)) throw invalidRequest(`${param} must be an object.`, param);
|
|
281
|
+
return value;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function optionalNumber(value: unknown, param: string): number | undefined {
|
|
285
|
+
if (value === undefined || value === null) return undefined;
|
|
286
|
+
if (typeof value !== "number" || !Number.isFinite(value)) throw invalidRequest(`${param} must be a number.`, param);
|
|
287
|
+
return value;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function requiredString(value: unknown, param: string): string {
|
|
291
|
+
if (typeof value !== "string" || value.length === 0) throw invalidRequest(`${param} must be a non-empty string.`, param);
|
|
292
|
+
return value;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function invalidRequest(message: string, param?: string): HttpError {
|
|
296
|
+
return new HttpError(400, message, "invalid_request_error", param);
|
|
297
|
+
}
|
|
@@ -91,3 +91,11 @@ const UNSUPPORTED_MODEL_MESSAGE =
|
|
|
91
91
|
export function unsupportedModelMessage(): string {
|
|
92
92
|
return UNSUPPORTED_MODEL_MESSAGE;
|
|
93
93
|
}
|
|
94
|
+
|
|
95
|
+
/* Gemini API clients (Antigravity CLI, Gemini CLI) name a Gemini model in
|
|
96
|
+
the request path (`gemini-3.1-pro-preview`, and their flash-lite helpers).
|
|
97
|
+
Every name routes except `dari/model/<id>`, which serves that catalog
|
|
98
|
+
model, so a client's model fallbacks and helper calls all reach the router. */
|
|
99
|
+
export function geminiRouterModel(model: string): string {
|
|
100
|
+
return explicitModelId(model) === null ? CANONICAL_ROUTER_MODEL : model;
|
|
101
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import type { RoutingDecision } from "@mupt-ai/dari-router/policy-engine";
|
|
2
|
+
|
|
3
|
+
import { parseDataImageUrl } from "../../interaction/image.js";
|
|
4
|
+
import { encodePortableReasoningState } from "../../interaction/portable_reasoning_state.js";
|
|
5
|
+
import { encodeProviderContinuationState } from "../../interaction/provider_continuation_state.js";
|
|
6
|
+
import type { InteractionOutput, InteractionRequest } from "../../interaction/types.js";
|
|
7
|
+
import type { ServedDecision } from "../../types.js";
|
|
8
|
+
import { encodeGeminiThoughtSignature } from "../gemini_thought_signature.js";
|
|
9
|
+
|
|
10
|
+
export function geminiGenerateContentResponse(args: {
|
|
11
|
+
id: string;
|
|
12
|
+
model: string;
|
|
13
|
+
output: InteractionOutput;
|
|
14
|
+
modelCost?: number | null;
|
|
15
|
+
request: InteractionRequest;
|
|
16
|
+
routing: RoutingDecision;
|
|
17
|
+
conversationId?: string;
|
|
18
|
+
}): Record<string, unknown> {
|
|
19
|
+
return {
|
|
20
|
+
candidates: [{
|
|
21
|
+
content: { role: "model", parts: geminiParts(args.output) },
|
|
22
|
+
finishReason: geminiFinishReason(args.output),
|
|
23
|
+
index: 0,
|
|
24
|
+
}],
|
|
25
|
+
usageMetadata: { ...geminiUsage(args.output), cost: args.modelCost ?? null },
|
|
26
|
+
modelVersion: args.model,
|
|
27
|
+
responseId: args.id,
|
|
28
|
+
dari_routing: geminiRouting(args.routing, args.id, args.conversationId),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/* Thought text shows as thought parts; the turn's reasoning state rides on the
|
|
33
|
+
first part Gemini CLI keeps in history, as a Dari thought signature. */
|
|
34
|
+
export function geminiParts(output: InteractionOutput): Array<Record<string, unknown>> {
|
|
35
|
+
const thoughts: Array<Record<string, unknown>> = [];
|
|
36
|
+
const parts: Array<Record<string, unknown>> = [];
|
|
37
|
+
for (const item of output.items) {
|
|
38
|
+
if (item.type === "reasoning") {
|
|
39
|
+
const text = [...item.summary, ...item.content].join("\n");
|
|
40
|
+
if (text) thoughts.push({ text, thought: true });
|
|
41
|
+
} else if (item.type === "tool_call") {
|
|
42
|
+
parts.push({ functionCall: { id: item.callId, name: item.name, args: toolArgs(item.input) } });
|
|
43
|
+
} else if (item.type === "message") {
|
|
44
|
+
for (const part of item.content) {
|
|
45
|
+
if (part.type === "text") parts.push({ text: part.text });
|
|
46
|
+
else if (part.type === "document") parts.push({ inlineData: { mimeType: part.mimeType, data: part.data } });
|
|
47
|
+
else if (part.type === "image") {
|
|
48
|
+
const image = parseDataImageUrl(part.url);
|
|
49
|
+
if (image) parts.push({ inlineData: { mimeType: image.mimeType, data: image.data } });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const signature = geminiThoughtSignature(output);
|
|
55
|
+
if (signature !== undefined) {
|
|
56
|
+
if (parts.length > 0) parts[0] = { ...parts[0], thoughtSignature: signature };
|
|
57
|
+
else parts.push({ text: "", thoughtSignature: signature });
|
|
58
|
+
}
|
|
59
|
+
return [...thoughts, ...(parts.length > 0 ? parts : [{ text: "" }])];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function geminiThoughtSignature(output: InteractionOutput): string | undefined {
|
|
63
|
+
const states = output.items.flatMap((item) => item.type !== "reasoning" ? [] : [
|
|
64
|
+
item.continuation
|
|
65
|
+
? encodeProviderContinuationState(item.continuation)
|
|
66
|
+
: encodePortableReasoningState({ source: item.source, itemId: item.id }),
|
|
67
|
+
]);
|
|
68
|
+
return states.length > 0 ? encodeGeminiThoughtSignature(states) : undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function geminiFinishReason(output: Pick<InteractionOutput, "stopReason">): string {
|
|
72
|
+
if (output.stopReason === "length") return "MAX_TOKENS";
|
|
73
|
+
if (output.stopReason === "error" || output.stopReason === "aborted") return "OTHER";
|
|
74
|
+
return "STOP";
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function geminiUsage(output: Pick<InteractionOutput, "usage">): Record<string, number> {
|
|
78
|
+
const { input, output: candidates, cacheRead, cacheWrite } = output.usage;
|
|
79
|
+
const prompt = input + cacheRead + cacheWrite;
|
|
80
|
+
return {
|
|
81
|
+
promptTokenCount: prompt,
|
|
82
|
+
candidatesTokenCount: candidates,
|
|
83
|
+
cachedContentTokenCount: cacheRead,
|
|
84
|
+
totalTokenCount: prompt + candidates,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function geminiRouting(decision: ServedDecision, requestId: string, conversationId?: string): Record<string, unknown> {
|
|
89
|
+
return {
|
|
90
|
+
requested_model: "dari/routing",
|
|
91
|
+
selected_model: decision.selectedModel,
|
|
92
|
+
reasoning_effort: decision.reasoningEffort,
|
|
93
|
+
reason: decision.reason,
|
|
94
|
+
request_id: requestId,
|
|
95
|
+
...(conversationId ? { conversation_id: conversationId } : {}),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function toolArgs(value: string | Record<string, unknown> | undefined): Record<string, unknown> {
|
|
100
|
+
if (value && typeof value === "object") return value;
|
|
101
|
+
if (!value) return {};
|
|
102
|
+
try {
|
|
103
|
+
const parsed: unknown = JSON.parse(value);
|
|
104
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Record<string, unknown> : {};
|
|
105
|
+
} catch {
|
|
106
|
+
return {};
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { isRecord, type RoutingDecision } from "@mupt-ai/dari-router/policy-engine";
|
|
2
|
+
|
|
3
|
+
import { piMessageToInteractionOutput } from "../../providers/pi_output.js";
|
|
4
|
+
import type { InteractionOutputItem, InteractionRequest, ProviderIdentity } from "../../interaction/types.js";
|
|
5
|
+
import {
|
|
6
|
+
isProviderFailureMessage,
|
|
7
|
+
providerFailureFromEvent,
|
|
8
|
+
providerFailureMessage,
|
|
9
|
+
type ProviderStreamOutcome,
|
|
10
|
+
} from "../../runtime/provider_stream_outcome.js";
|
|
11
|
+
import { sseStream } from "./sse_stream.js";
|
|
12
|
+
import { geminiFinishReason, geminiParts, geminiRouting, geminiUsage } from "./gemini_generate_content.js";
|
|
13
|
+
|
|
14
|
+
/* Text and thought text stream as they arrive. Function calls go out whole in
|
|
15
|
+
the final chunk, with the turn's thought signature on the first, since a
|
|
16
|
+
Gemini client takes each functionCall part as complete. */
|
|
17
|
+
export function geminiGenerateContentSseStream(args: {
|
|
18
|
+
id: string;
|
|
19
|
+
model: string;
|
|
20
|
+
routing: RoutingDecision;
|
|
21
|
+
events: AsyncIterable<Record<string, unknown>>;
|
|
22
|
+
source: ProviderIdentity;
|
|
23
|
+
request: InteractionRequest;
|
|
24
|
+
conversationId?: string;
|
|
25
|
+
onFinal?: (outcome: ProviderStreamOutcome) => void;
|
|
26
|
+
modelCost?: (message: Record<string, unknown>, failed: boolean) => number | null;
|
|
27
|
+
beforeClose?: (outcome: ProviderStreamOutcome) => Promise<void> | void;
|
|
28
|
+
clientSignal?: AbortSignal;
|
|
29
|
+
onAbort?: () => void;
|
|
30
|
+
}): ReadableStream<Uint8Array> {
|
|
31
|
+
const encoder = new TextEncoder();
|
|
32
|
+
return sseStream({
|
|
33
|
+
protocol: "gemini_generate_content",
|
|
34
|
+
lifecycle: args,
|
|
35
|
+
start: ({ controller, snapshot, lifecycle, settle, observeTerminal }) => {
|
|
36
|
+
const send = (payload: Record<string, unknown>) => {
|
|
37
|
+
if (!lifecycle.canWrite) return;
|
|
38
|
+
snapshot.record({ data: payload });
|
|
39
|
+
controller.enqueue(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`));
|
|
40
|
+
};
|
|
41
|
+
const chunk = (parts: Array<Record<string, unknown>>, extra: Record<string, unknown> = {}) => send({
|
|
42
|
+
candidates: [{ content: { role: "model", parts }, index: 0, ...extra }],
|
|
43
|
+
modelVersion: args.model,
|
|
44
|
+
responseId: args.id,
|
|
45
|
+
});
|
|
46
|
+
const sendProviderError = (message: Record<string, unknown>) => {
|
|
47
|
+
send({ error: { code: 502, message: providerFailureMessage(message), status: "UNAVAILABLE" } });
|
|
48
|
+
};
|
|
49
|
+
return {
|
|
50
|
+
consume: async () => {
|
|
51
|
+
for await (const event of args.events) {
|
|
52
|
+
if (lifecycle.shouldStopConsuming) break;
|
|
53
|
+
if (event.type === "text_delta" && typeof event.delta === "string" && event.delta) {
|
|
54
|
+
chunk([{ text: event.delta }]);
|
|
55
|
+
} else if (event.type === "thinking_delta" && typeof event.delta === "string" && event.delta) {
|
|
56
|
+
chunk([{ text: event.delta, thought: true }]);
|
|
57
|
+
} else if (event.type === "done") {
|
|
58
|
+
if (!isRecord(event.message)) throw new Error("Provider stream ended without a terminal message.");
|
|
59
|
+
observeTerminal(event.message);
|
|
60
|
+
if (isProviderFailureMessage(event.message)) {
|
|
61
|
+
settle({ status: "provider_error", message: event.message });
|
|
62
|
+
sendProviderError(event.message);
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
const output = piMessageToInteractionOutput(event.message, args.source, args.request);
|
|
66
|
+
settle({ status: "completed", message: event.message, output });
|
|
67
|
+
// Text already streamed; the final chunk carries the calls and the signature.
|
|
68
|
+
const parts = geminiParts({
|
|
69
|
+
...output,
|
|
70
|
+
items: output.items.flatMap((item): InteractionOutputItem[] => {
|
|
71
|
+
if (item.type === "reasoning") return [{ ...item, summary: [], content: [] }];
|
|
72
|
+
return item.type === "tool_call" ? [item] : [];
|
|
73
|
+
}),
|
|
74
|
+
}).filter((part) => !(part.text === "" && part.thoughtSignature === undefined));
|
|
75
|
+
send({
|
|
76
|
+
candidates: [{
|
|
77
|
+
content: { role: "model", parts },
|
|
78
|
+
finishReason: geminiFinishReason(output),
|
|
79
|
+
index: 0,
|
|
80
|
+
}],
|
|
81
|
+
usageMetadata: { ...geminiUsage(output), cost: args.modelCost?.(event.message, false) ?? null },
|
|
82
|
+
modelVersion: args.model,
|
|
83
|
+
responseId: args.id,
|
|
84
|
+
dari_routing: geminiRouting(args.routing, args.id, args.conversationId),
|
|
85
|
+
});
|
|
86
|
+
break;
|
|
87
|
+
} else if (event.type === "error") {
|
|
88
|
+
const message = providerFailureFromEvent(event);
|
|
89
|
+
settle({ status: "provider_error", message });
|
|
90
|
+
sendProviderError(message);
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
emitProviderError: sendProviderError,
|
|
96
|
+
close: () => controller.close(),
|
|
97
|
+
};
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
@@ -24,6 +24,11 @@ export type HarnessConversationIdentity =
|
|
|
24
24
|
kind: "muse_code_thread";
|
|
25
25
|
value: string;
|
|
26
26
|
qualifiers?: string[];
|
|
27
|
+
}
|
|
28
|
+
| {
|
|
29
|
+
kind: "antigravity_conversation";
|
|
30
|
+
value: string;
|
|
31
|
+
qualifiers?: string[];
|
|
27
32
|
};
|
|
28
33
|
|
|
29
34
|
export type HarnessConversationScope = {
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { hostname } from "node:os";
|
|
2
2
|
|
|
3
3
|
import type { ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
|
|
4
|
-
import { anthropicToken, bearerToken } from "../http/auth.js";
|
|
4
|
+
import { anthropicToken, bearerToken, geminiToken } from "../http/auth.js";
|
|
5
5
|
import { errorResponse, HttpError } from "../http/errors.js";
|
|
6
6
|
import { anthropicErrorResponse } from "../ingress/anthropic_messages.js";
|
|
7
|
+
import { geminiErrorResponse } from "../ingress/gemini.js";
|
|
7
8
|
import type { GatewayPlatform } from "../platform/platform.js";
|
|
8
9
|
import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER, PRIVATE_HEADER } from "../platform/routing_contract.js";
|
|
9
10
|
import type { Source } from "../models/sources.js";
|
|
@@ -171,6 +172,9 @@ async function readHostedRouter(hosted: HostedConnection, fetchImpl: typeof fetc
|
|
|
171
172
|
// The calls this gateway serves itself: routed calls and model lists. Every
|
|
172
173
|
// other path goes to hosted.
|
|
173
174
|
const LOCAL_CALL = /^(?:\/[^/]+)?(?:\/v1)?\/(?:chat\/completions|responses|messages|models)$/;
|
|
175
|
+
// Gemini API calls (Antigravity CLI): the model list at `{base}/v1beta/models`
|
|
176
|
+
// and a model's calls at `{base}/v1beta/models/{model}:{method}`.
|
|
177
|
+
const GEMINI_CALL = /^(?:\/[^/]+)?\/v1beta\/models(?:\/.+:(?:generateContent|streamGenerateContent|countTokens))?$/;
|
|
174
178
|
|
|
175
179
|
/**
|
|
176
180
|
* Serve a connected gateway: routed calls and model lists on `gateway` (the
|
|
@@ -196,18 +200,21 @@ export function connectedHandler(deps: {
|
|
|
196
200
|
if (pathname === "/healthz" || pathname === "/health" || pathname === "/api/hello") {
|
|
197
201
|
return await deps.gateway(request);
|
|
198
202
|
}
|
|
199
|
-
|
|
200
|
-
|
|
203
|
+
const gemini = GEMINI_CALL.test(pathname);
|
|
204
|
+
// Claude Code and Gemini API clients read errors in their own APIs'
|
|
205
|
+
// shapes, as the gateway answers them.
|
|
206
|
+
const fail = MESSAGES_CALL.test(pathname) ? anthropicErrorResponse : gemini ? geminiErrorResponse : errorResponse;
|
|
201
207
|
try {
|
|
202
208
|
const anthropic = !request.headers.has("authorization") && request.headers.has("x-api-key");
|
|
203
|
-
const key =
|
|
209
|
+
const key = gemini ? geminiToken(request.headers)
|
|
210
|
+
: anthropic ? anthropicToken(request.headers) : bearerToken(request.headers);
|
|
204
211
|
if (gatewayKeyIndex(deps.gatewayKeys, key) === null) {
|
|
205
212
|
throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
|
|
206
213
|
}
|
|
207
214
|
} catch (error) {
|
|
208
215
|
return fail(error);
|
|
209
216
|
}
|
|
210
|
-
if (!LOCAL_CALL.test(pathname)) return await forward(request, deps, fail);
|
|
217
|
+
if (!LOCAL_CALL.test(pathname) && !gemini) return await forward(request, deps, fail);
|
|
211
218
|
// Custom routing rules run only on hosted Dari: it serves those routers'
|
|
212
219
|
// calls whole.
|
|
213
220
|
if (request.method === "POST" && await usesCustomRules(deps.hostedRouter, pathname)) {
|
|
@@ -225,7 +232,7 @@ const MESSAGES_CALL = /\/messages(?:\/count_tokens)?$/;
|
|
|
225
232
|
async function usesCustomRules(hostedRouter: HostedRouters, pathname: string): Promise<boolean> {
|
|
226
233
|
let routerId = DEFAULT_ROUTER_ALIAS;
|
|
227
234
|
const first = pathname.split("/")[1];
|
|
228
|
-
if (first !== undefined && first !== "v1" && !LOCAL_CALL.test(`/${first}`)) routerId = first;
|
|
235
|
+
if (first !== undefined && first !== "v1" && first !== "v1beta" && !LOCAL_CALL.test(`/${first}`)) routerId = first;
|
|
229
236
|
try {
|
|
230
237
|
return (await hostedRouter(routerId)).customRules;
|
|
231
238
|
} catch {
|
|
@@ -241,7 +248,7 @@ async function forward(
|
|
|
241
248
|
): Promise<Response> {
|
|
242
249
|
const url = new URL(request.url);
|
|
243
250
|
const headers = new Headers(request.headers);
|
|
244
|
-
for (const name of ["host", "authorization", "x-api-key", "content-length", "connection", "accept-encoding"]) {
|
|
251
|
+
for (const name of ["host", "authorization", "x-api-key", "x-goog-api-key", "content-length", "connection", "accept-encoding"]) {
|
|
245
252
|
headers.delete(name);
|
|
246
253
|
}
|
|
247
254
|
headers.set("authorization", `Bearer ${deps.hosted.apiKey}`);
|