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