@abhishek944/pi-web-access 0.0.0-stage → 0.1.0
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/ASTACK.md +23 -0
- package/CHANGELOG.md +1289 -0
- package/LICENSE +21 -0
- package/README.md +1215 -2
- package/SECURITY.md +5 -0
- package/abortable.ts +17 -0
- package/activity.ts +101 -0
- package/anysearch.ts +188 -0
- package/auth-fetch.ts +152 -0
- package/baizhi.ts +124 -0
- package/banner.png +0 -0
- package/bocha.ts +203 -0
- package/brave-rate-limit.ts +176 -0
- package/brave.ts +247 -0
- package/brightdata-unlocker.ts +272 -0
- package/ceramic.ts +220 -0
- package/chrome-cookies.ts +752 -0
- package/cloudflare-search.ts +237 -0
- package/content-find.ts +255 -0
- package/crawl4ai.ts +196 -0
- package/credential-source.ts +242 -0
- package/curator-page.ts +3607 -0
- package/curator-run.ts +45 -0
- package/curator-server.ts +761 -0
- package/custom-search.ts +226 -0
- package/data-uri-sanitize.ts +406 -0
- package/datalab-pdf-extract.ts +568 -0
- package/declared-web-links.ts +173 -0
- package/deepseek.ts +377 -0
- package/degoog.ts +323 -0
- package/dist/index.js +28286 -0
- package/dist/mcp-cli.js +29186 -0
- package/dist/pi-mcp.js +20855 -0
- package/dist/types/abortable.d.ts +2 -0
- package/dist/types/activity.d.ts +33 -0
- package/dist/types/anysearch.d.ts +7 -0
- package/dist/types/auth-fetch.d.ts +14 -0
- package/dist/types/baizhi.d.ts +3 -0
- package/dist/types/bocha.d.ts +3 -0
- package/dist/types/brave-rate-limit.d.ts +35 -0
- package/dist/types/brave.d.ts +3 -0
- package/dist/types/brightdata-unlocker.d.ts +11 -0
- package/dist/types/ceramic.d.ts +3 -0
- package/dist/types/chrome-cookies.d.ts +44 -0
- package/dist/types/cloudflare-search.d.ts +4 -0
- package/dist/types/content-find.d.ts +10 -0
- package/dist/types/crawl4ai.d.ts +8 -0
- package/dist/types/credential-source.d.ts +29 -0
- package/dist/types/curator-page.d.ts +5 -0
- package/dist/types/curator-run.d.ts +10 -0
- package/dist/types/curator-server.d.ts +72 -0
- package/dist/types/custom-search.d.ts +22 -0
- package/dist/types/data-uri-sanitize.d.ts +20 -0
- package/dist/types/datalab-pdf-extract.d.ts +59 -0
- package/dist/types/declared-web-links.d.ts +7 -0
- package/dist/types/deepseek.d.ts +13 -0
- package/dist/types/degoog.d.ts +3 -0
- package/dist/types/domain-filter-normalization.d.ts +9 -0
- package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
- package/dist/types/duckduckgo.d.ts +6 -0
- package/dist/types/endpoint-pdf-extract.d.ts +22 -0
- package/dist/types/exa.d.ts +17 -0
- package/dist/types/extract.d.ts +70 -0
- package/dist/types/feature-config.d.ts +2 -0
- package/dist/types/fetch-params.d.ts +39 -0
- package/dist/types/field-extract.d.ts +37 -0
- package/dist/types/firecrawl.d.ts +18 -0
- package/dist/types/gemini-adc.d.ts +9 -0
- package/dist/types/gemini-api.d.ts +37 -0
- package/dist/types/gemini-pdf-extract.d.ts +8 -0
- package/dist/types/gemini-search.d.ts +76 -0
- package/dist/types/gemini-url-context.d.ts +3 -0
- package/dist/types/gemini-web-config.d.ts +25 -0
- package/dist/types/gemini-web.d.ts +31 -0
- package/dist/types/github-api.d.ts +6 -0
- package/dist/types/github-extract.d.ts +19 -0
- package/dist/types/github-issue-pr.d.ts +28 -0
- package/dist/types/index.d.ts +53 -0
- package/dist/types/jina-search.d.ts +7 -0
- package/dist/types/kagi.d.ts +14 -0
- package/dist/types/keenable.d.ts +3 -0
- package/dist/types/kimi-search.d.ts +4 -0
- package/dist/types/linkup.d.ts +5 -0
- package/dist/types/mcp-cli.d.ts +2 -0
- package/dist/types/mcp-server.d.ts +10 -0
- package/dist/types/mcp-tool-definitions.d.ts +16 -0
- package/dist/types/mistral-search.d.ts +3 -0
- package/dist/types/ninerouter.d.ts +3 -0
- package/dist/types/offtopic-judge.d.ts +26 -0
- package/dist/types/ollama.d.ts +14 -0
- package/dist/types/openai-search.d.ts +23 -0
- package/dist/types/page-query.d.ts +22 -0
- package/dist/types/parallel-mcp.d.ts +10 -0
- package/dist/types/parallel.d.ts +13 -0
- package/dist/types/pdf-extract.d.ts +44 -0
- package/dist/types/perplexity.d.ts +26 -0
- package/dist/types/pi-mcp.d.ts +56 -0
- package/dist/types/pi-session-results.d.ts +8 -0
- package/dist/types/querit.d.ts +9 -0
- package/dist/types/query-rewrite.d.ts +2 -0
- package/dist/types/render-search-error.d.ts +56 -0
- package/dist/types/retrieval-only.d.ts +78 -0
- package/dist/types/rsc-extract.d.ts +11 -0
- package/dist/types/search-answer-formatting.d.ts +7 -0
- package/dist/types/search-result-count-normalization.d.ts +1 -0
- package/dist/types/searchinfinity.d.ts +7 -0
- package/dist/types/searxng.d.ts +3 -0
- package/dist/types/source-check.d.ts +102 -0
- package/dist/types/ssrf-protection.d.ts +66 -0
- package/dist/types/storage.d.ts +69 -0
- package/dist/types/summary-model-scope.d.ts +33 -0
- package/dist/types/summary-review.d.ts +30 -0
- package/dist/types/tabstack.d.ts +5 -0
- package/dist/types/tavily.d.ts +7 -0
- package/dist/types/tinyfish.d.ts +10 -0
- package/dist/types/tool-activation.d.ts +7 -0
- package/dist/types/tool-arguments.d.ts +1 -0
- package/dist/types/upgrade-notice.d.ts +6 -0
- package/dist/types/utils.d.ts +55 -0
- package/dist/types/valyu.d.ts +5 -0
- package/dist/types/video-extract.d.ts +15 -0
- package/dist/types/web-tool-contract.d.ts +98 -0
- package/dist/types/web-tool-core.d.ts +227 -0
- package/dist/types/xai-search.d.ts +12 -0
- package/dist/types/you.d.ts +3 -0
- package/dist/types/youtube-extract.d.ts +29 -0
- package/dist/types/zai.d.ts +3 -0
- package/docs/pi-mcp.md +41 -0
- package/domain-filter-normalization.ts +44 -0
- package/duckduckgo-rate-limit.ts +205 -0
- package/duckduckgo.ts +123 -0
- package/endpoint-pdf-extract.ts +225 -0
- package/exa.ts +620 -0
- package/extract.ts +1721 -0
- package/feature-config.ts +29 -0
- package/fetch-params.ts +147 -0
- package/field-extract.ts +347 -0
- package/firecrawl.ts +476 -0
- package/gemini-adc.ts +345 -0
- package/gemini-api.ts +368 -0
- package/gemini-pdf-extract.ts +108 -0
- package/gemini-search.ts +1162 -0
- package/gemini-url-context.ts +128 -0
- package/gemini-web-config.ts +131 -0
- package/gemini-web.ts +527 -0
- package/github-api.ts +197 -0
- package/github-extract.ts +1064 -0
- package/github-issue-pr.ts +717 -0
- package/index.ts +2819 -0
- package/jina-search.ts +275 -0
- package/kagi.ts +257 -0
- package/keenable.ts +222 -0
- package/kimi-search.ts +209 -0
- package/linkup.ts +170 -0
- package/mcp-cli.ts +40 -0
- package/mcp-server.ts +84 -0
- package/mcp-tool-definitions.ts +143 -0
- package/mistral-search.ts +268 -0
- package/ninerouter.ts +92 -0
- package/offtopic-judge.ts +72 -0
- package/ollama.ts +237 -0
- package/openai-search.ts +855 -0
- package/package.json +108 -4
- package/page-query.ts +185 -0
- package/parallel-mcp.ts +255 -0
- package/parallel.ts +373 -0
- package/pdf-extract.ts +447 -0
- package/perplexity.ts +245 -0
- package/pi-mcp.ts +139 -0
- package/pi-session-results.ts +40 -0
- package/pi-web-fetch-demo.mp4 +0 -0
- package/promise-try.d.ts +7 -0
- package/querit.ts +394 -0
- package/query-rewrite.ts +84 -0
- package/render-search-error.ts +170 -0
- package/retrieval-only.ts +102 -0
- package/rsc-extract.ts +338 -0
- package/search-answer-formatting.ts +11 -0
- package/search-result-count-normalization.ts +4 -0
- package/searchinfinity.ts +246 -0
- package/searxng.ts +236 -0
- package/source-check.ts +269 -0
- package/ssrf-protection.ts +602 -0
- package/storage.ts +547 -0
- package/summary-model-scope.ts +72 -0
- package/summary-review.ts +476 -0
- package/tabstack.ts +289 -0
- package/tavily.ts +257 -0
- package/tinyfish.ts +373 -0
- package/tool-activation.ts +169 -0
- package/tool-arguments.ts +23 -0
- package/upgrade-notice.ts +47 -0
- package/utils.ts +693 -0
- package/valyu.ts +177 -0
- package/video-extract.ts +398 -0
- package/web-tool-contract.ts +93 -0
- package/web-tool-core.ts +1810 -0
- package/xai-search.ts +443 -0
- package/you.ts +165 -0
- package/youtube-extract.ts +336 -0
- package/zai.ts +161 -0
package/gemini-adc.ts
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { createSign } from "node:crypto";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { getWebSearchConfigPath } from "./utils.ts";
|
|
6
|
+
import { redactCredential, CredentialResolutionError } from "./credential-source.ts";
|
|
7
|
+
|
|
8
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
9
|
+
const DEFAULT_ADC_PATH = join(homedir(), ".config", "gcloud", "application_default_credentials.json");
|
|
10
|
+
const TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
|
|
11
|
+
const DEFAULT_METADATA_HOST = "metadata.google.internal";
|
|
12
|
+
const VERTEX_HOST = "https://aiplatform.googleapis.com";
|
|
13
|
+
const VERTEX_API_VERSION = "v1";
|
|
14
|
+
const REFRESH_SKEW_MS = 60_000;
|
|
15
|
+
|
|
16
|
+
interface GeminiAdcConfig {
|
|
17
|
+
geminiAuth?: unknown;
|
|
18
|
+
geminiProject?: unknown;
|
|
19
|
+
geminiLocation?: unknown;
|
|
20
|
+
geminiApiKey?: unknown;
|
|
21
|
+
geminiBaseUrl?: unknown;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
let cachedConfig: GeminiAdcConfig | null = null;
|
|
25
|
+
|
|
26
|
+
function loadConfig(): GeminiAdcConfig {
|
|
27
|
+
if (cachedConfig) return cachedConfig;
|
|
28
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
29
|
+
cachedConfig = {};
|
|
30
|
+
return cachedConfig;
|
|
31
|
+
}
|
|
32
|
+
const raw = readFileSync(CONFIG_PATH, "utf-8");
|
|
33
|
+
try {
|
|
34
|
+
const parsed = JSON.parse(raw);
|
|
35
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
36
|
+
throw new Error("config root must be an object");
|
|
37
|
+
}
|
|
38
|
+
cachedConfig = parsed as GeminiAdcConfig;
|
|
39
|
+
} catch (err) {
|
|
40
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
41
|
+
throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
|
|
42
|
+
}
|
|
43
|
+
return cachedConfig;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function normalizeIdentifier(value: unknown, envName: string): string | null {
|
|
47
|
+
if (typeof value === "string") {
|
|
48
|
+
const trimmed = value.trim();
|
|
49
|
+
if (trimmed) return trimmed;
|
|
50
|
+
}
|
|
51
|
+
const fromEnv = process.env[envName]?.trim();
|
|
52
|
+
return fromEnv ? fromEnv : null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function isAdcAuthSelected(): boolean {
|
|
56
|
+
return (loadConfig().geminiAuth ?? "").toString().trim().toLowerCase() === "adc";
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function getAdcProject(): string | null {
|
|
60
|
+
return (
|
|
61
|
+
normalizeIdentifier(loadConfig().geminiProject, "GOOGLE_CLOUD_PROJECT") ??
|
|
62
|
+
normalizeIdentifier(null, "GCLOUD_PROJECT")
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function getAdcLocation(): string | null {
|
|
67
|
+
return normalizeIdentifier(loadConfig().geminiLocation, "GOOGLE_CLOUD_LOCATION");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function getAdcPath(): string {
|
|
71
|
+
return process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim() || DEFAULT_ADC_PATH;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function hasExplicitAdcPath(): boolean {
|
|
75
|
+
return !!process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function getMetadataHost(): string {
|
|
79
|
+
return (process.env.GCE_METADATA_HOST?.trim() || DEFAULT_METADATA_HOST).replace(/^https?:\/\//i, "").replace(/\/+$/, "");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function isOnGcp(): boolean {
|
|
83
|
+
if (process.env.METADATA_SERVER_DETECTION?.trim().toLowerCase() === "none") return false;
|
|
84
|
+
if (process.env.GCE_METADATA_HOST?.trim()) return true;
|
|
85
|
+
try {
|
|
86
|
+
return /Google/.test(readFileSync("/sys/class/dmi/id/bios_vendor", "utf8"));
|
|
87
|
+
} catch {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function getVertexApiBase(project: string, location: string): string {
|
|
93
|
+
return `${VERTEX_HOST}/${VERTEX_API_VERSION}/projects/${encodeURIComponent(project)}/locations/${encodeURIComponent(location)}/publishers/google`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function isVertexHost(origin: string): boolean {
|
|
97
|
+
return origin === VERTEX_HOST;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
interface AdcFile {
|
|
101
|
+
type?: string;
|
|
102
|
+
client_id?: string;
|
|
103
|
+
client_secret?: string;
|
|
104
|
+
refresh_token?: string;
|
|
105
|
+
client_email?: string;
|
|
106
|
+
private_key?: string;
|
|
107
|
+
private_key_id?: string;
|
|
108
|
+
token_uri?: string;
|
|
109
|
+
universe_domain?: string;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function objectRecord(value: unknown): Record<string, unknown> | null {
|
|
113
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function stringField(record: Record<string, unknown>, name: string): string | undefined {
|
|
117
|
+
const value = record[name];
|
|
118
|
+
return typeof value === "string" ? value : undefined;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function requiredString(record: Record<string, unknown>, name: string, context: string): string {
|
|
122
|
+
const value = stringField(record, name)?.trim();
|
|
123
|
+
if (!value) throw new Error(`${context} is missing ${name}`);
|
|
124
|
+
return value;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function parseAdcFile(raw: string): AdcFile {
|
|
128
|
+
const parsed = objectRecord(JSON.parse(raw));
|
|
129
|
+
if (!parsed) throw new Error("credential root must be an object");
|
|
130
|
+
const type = stringField(parsed, "type") ?? "authorized_user";
|
|
131
|
+
if (type === "authorized_user") {
|
|
132
|
+
return {
|
|
133
|
+
type,
|
|
134
|
+
client_id: requiredString(parsed, "client_id", "Gemini ADC authorized_user file"),
|
|
135
|
+
client_secret: requiredString(parsed, "client_secret", "Gemini ADC authorized_user file"),
|
|
136
|
+
refresh_token: requiredString(parsed, "refresh_token", "Gemini ADC authorized_user file"),
|
|
137
|
+
universe_domain: stringField(parsed, "universe_domain"),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
if (type === "service_account") {
|
|
141
|
+
return {
|
|
142
|
+
type,
|
|
143
|
+
client_email: requiredString(parsed, "client_email", "Gemini ADC service_account file"),
|
|
144
|
+
private_key: requiredString(parsed, "private_key", "Gemini ADC service_account file"),
|
|
145
|
+
private_key_id: stringField(parsed, "private_key_id"),
|
|
146
|
+
token_uri: stringField(parsed, "token_uri"),
|
|
147
|
+
universe_domain: stringField(parsed, "universe_domain"),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
return { type };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function parseTokenExchangeResponse(text: string, context: string): CachedToken {
|
|
154
|
+
let raw: unknown;
|
|
155
|
+
try {
|
|
156
|
+
raw = JSON.parse(text);
|
|
157
|
+
} catch (err) {
|
|
158
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
159
|
+
throw new Error(`${context} returned invalid JSON: ${message}`);
|
|
160
|
+
}
|
|
161
|
+
const parsed = objectRecord(raw);
|
|
162
|
+
if (!parsed) throw new Error(`${context} returned a non-object response`);
|
|
163
|
+
const token = stringField(parsed, "access_token")?.trim();
|
|
164
|
+
if (!token) throw new Error(`${context} returned no access_token`);
|
|
165
|
+
const expiresIn = parsed.expires_in ?? 3600;
|
|
166
|
+
if (typeof expiresIn !== "number" || !Number.isFinite(expiresIn)) {
|
|
167
|
+
throw new Error(`${context} returned invalid expires_in`);
|
|
168
|
+
}
|
|
169
|
+
return { token, expiresAt: Date.now() + Math.max((expiresIn * 1000) - REFRESH_SKEW_MS, 60_000) };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function loadAdcFile(): Promise<AdcFile> {
|
|
173
|
+
const path = getAdcPath();
|
|
174
|
+
if (!path || !existsSync(path)) {
|
|
175
|
+
throw new Error(`Google Application Default Credentials file not found at ${path}`);
|
|
176
|
+
}
|
|
177
|
+
const raw = readFileSync(path, "utf-8");
|
|
178
|
+
try {
|
|
179
|
+
return parseAdcFile(raw);
|
|
180
|
+
} catch (err) {
|
|
181
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
182
|
+
throw new Error(`Failed to parse Google Application Default Credentials file at ${path}: ${message}`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
interface CachedToken {
|
|
187
|
+
token: string;
|
|
188
|
+
expiresAt: number;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
let cachedToken: CachedToken | null = null;
|
|
192
|
+
|
|
193
|
+
export function clearAdcTokenCache(): void {
|
|
194
|
+
cachedToken = null;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Classifies a failed OAuth token exchange. Only explicit credential/authorization
|
|
199
|
+
* rejections (400 invalid_client/invalid_grant/invalid_scope, 401, 403 denied)
|
|
200
|
+
* mean the configured credentials themselves were refused — a hard credential
|
|
201
|
+
* problem callers should surface rather than silently fall back. Everything else
|
|
202
|
+
* (429 rate limit, 404, 5xx, network failures, timeouts) is transient, so it is
|
|
203
|
+
* left as a plain Error and existing per-provider fallbacks keep working.
|
|
204
|
+
*/
|
|
205
|
+
const OAUTH_CREDENTIAL_REJECTION_STATUSES = new Set([400, 401, 403]);
|
|
206
|
+
|
|
207
|
+
function throwOnTokenExchangeFailure(res: Response, detail: string, status: number): never {
|
|
208
|
+
if (OAUTH_CREDENTIAL_REJECTION_STATUSES.has(status)) {
|
|
209
|
+
throw new CredentialResolutionError("Gemini ADC", "oauth-credential-rejected");
|
|
210
|
+
}
|
|
211
|
+
throw new Error(`Gemini ADC token exchange failed (${status}): ${detail.slice(0, 300)}`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function exchangeRefreshToken(cfg: AdcFile, signal?: AbortSignal): Promise<CachedToken> {
|
|
215
|
+
const body = new URLSearchParams({
|
|
216
|
+
client_id: cfg.client_id ?? "",
|
|
217
|
+
client_secret: cfg.client_secret ?? "",
|
|
218
|
+
refresh_token: cfg.refresh_token ?? "",
|
|
219
|
+
grant_type: "refresh_token",
|
|
220
|
+
});
|
|
221
|
+
const res = await fetch(TOKEN_ENDPOINT, {
|
|
222
|
+
method: "POST",
|
|
223
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
224
|
+
body,
|
|
225
|
+
signal,
|
|
226
|
+
});
|
|
227
|
+
const text = await res.text();
|
|
228
|
+
if (!res.ok) {
|
|
229
|
+
throwOnTokenExchangeFailure(res, text, res.status);
|
|
230
|
+
}
|
|
231
|
+
return parseTokenExchangeResponse(text, "Gemini ADC token exchange");
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async function exchangeServiceAccountJwt(cfg: AdcFile, signal?: AbortSignal): Promise<CachedToken> {
|
|
235
|
+
if (!cfg.client_email || !cfg.private_key) {
|
|
236
|
+
throw new Error("Gemini ADC service_account file is missing client_email or private_key");
|
|
237
|
+
}
|
|
238
|
+
const now = Math.floor(Date.now() / 1000);
|
|
239
|
+
const header = { alg: "RS256", typ: "JWT" };
|
|
240
|
+
const claims = {
|
|
241
|
+
iss: cfg.client_email,
|
|
242
|
+
scope: "https://www.googleapis.com/auth/cloud-platform",
|
|
243
|
+
aud: TOKEN_ENDPOINT,
|
|
244
|
+
iat: now,
|
|
245
|
+
exp: now + 3600,
|
|
246
|
+
};
|
|
247
|
+
const encodePart = (obj: object): string =>
|
|
248
|
+
Buffer.from(JSON.stringify(obj)).toString("base64url");
|
|
249
|
+
const assertion = `${encodePart(header)}.${encodePart(claims)}`;
|
|
250
|
+
const signer = createSign("RSA-SHA256");
|
|
251
|
+
signer.update(assertion);
|
|
252
|
+
signer.end();
|
|
253
|
+
const signature = signer.sign(cfg.private_key, "base64url");
|
|
254
|
+
const jwt = `${assertion}.${signature}`;
|
|
255
|
+
|
|
256
|
+
const body = new URLSearchParams({
|
|
257
|
+
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
|
258
|
+
assertion: jwt,
|
|
259
|
+
});
|
|
260
|
+
const res = await fetch(cfg.token_uri || TOKEN_ENDPOINT, {
|
|
261
|
+
method: "POST",
|
|
262
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
263
|
+
body,
|
|
264
|
+
signal,
|
|
265
|
+
});
|
|
266
|
+
const text = await res.text();
|
|
267
|
+
if (!res.ok) {
|
|
268
|
+
throwOnTokenExchangeFailure(res, text, res.status);
|
|
269
|
+
}
|
|
270
|
+
return parseTokenExchangeResponse(text, "Gemini ADC service account token exchange");
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async function fetchMetadataToken(signal?: AbortSignal): Promise<CachedToken> {
|
|
274
|
+
const url = `http://${getMetadataHost()}/computeMetadata/v1/instance/service-accounts/default/token`;
|
|
275
|
+
let res: Response;
|
|
276
|
+
try {
|
|
277
|
+
res = await fetch(url, {
|
|
278
|
+
headers: { "Metadata-Flavor": "Google" },
|
|
279
|
+
redirect: "error",
|
|
280
|
+
signal,
|
|
281
|
+
});
|
|
282
|
+
} catch (err) {
|
|
283
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
284
|
+
throw new Error(`Gemini ADC metadata server token request failed: ${message}`);
|
|
285
|
+
}
|
|
286
|
+
const text = await res.text();
|
|
287
|
+
if (!res.ok) {
|
|
288
|
+
if (res.status === 401 || res.status === 403) {
|
|
289
|
+
throw new CredentialResolutionError("Gemini ADC", "oauth-credential-rejected");
|
|
290
|
+
}
|
|
291
|
+
throw new Error(`Gemini ADC metadata server token request failed (HTTP ${res.status}): ${text.slice(0, 300)}`);
|
|
292
|
+
}
|
|
293
|
+
return parseTokenExchangeResponse(text, "Gemini ADC metadata server token");
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export async function getAdcAccessToken(signal?: AbortSignal): Promise<string> {
|
|
297
|
+
if (cachedToken && cachedToken.expiresAt > Date.now()) {
|
|
298
|
+
return cachedToken.token;
|
|
299
|
+
}
|
|
300
|
+
if (!hasExplicitAdcPath() && !existsSync(DEFAULT_ADC_PATH) && isOnGcp()) {
|
|
301
|
+
cachedToken = await fetchMetadataToken(signal);
|
|
302
|
+
return cachedToken.token;
|
|
303
|
+
}
|
|
304
|
+
const cfg = await loadAdcFile();
|
|
305
|
+
const type = cfg.type ?? "authorized_user";
|
|
306
|
+
if (type === "authorized_user") {
|
|
307
|
+
cachedToken = await exchangeRefreshToken(cfg, signal);
|
|
308
|
+
} else if (type === "service_account") {
|
|
309
|
+
cachedToken = await exchangeServiceAccountJwt(cfg, signal);
|
|
310
|
+
} else {
|
|
311
|
+
throw new Error(`Gemini ADC unsupported credential type "${type}" (expected authorized_user or service_account)`);
|
|
312
|
+
}
|
|
313
|
+
return cachedToken.token;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export function isGeminiAdcAvailable(): boolean {
|
|
317
|
+
if (!isAdcAuthSelected()) return false;
|
|
318
|
+
// An explicitly configured Gemini API key takes precedence over ADC, so
|
|
319
|
+
// existing key-based setups and their unit tests keep working unchanged.
|
|
320
|
+
if (hasGeminiApiKeySource()) return false;
|
|
321
|
+
// An explicit base URL (gateway/relay/proxy) also wins over ADC: if the
|
|
322
|
+
// user deliberately routed Gemini somewhere, honor that routing.
|
|
323
|
+
if (hasExplicitApiBase()) return false;
|
|
324
|
+
if (!getAdcProject() || !getAdcLocation()) return false;
|
|
325
|
+
if (existsSync(getAdcPath())) return true;
|
|
326
|
+
return !hasExplicitAdcPath() && isOnGcp();
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function hasGeminiApiKeySource(): boolean {
|
|
330
|
+
const configured = loadConfig().geminiApiKey;
|
|
331
|
+
if (typeof configured === "string" && configured.trim()) return true;
|
|
332
|
+
const fromEnv = process.env.GEMINI_API_KEY?.trim();
|
|
333
|
+
return !!fromEnv;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function hasExplicitApiBase(): boolean {
|
|
337
|
+
const fromEnv = process.env.GOOGLE_GEMINI_BASE_URL?.trim();
|
|
338
|
+
if (fromEnv) return true;
|
|
339
|
+
const configured = loadConfig().geminiBaseUrl;
|
|
340
|
+
return typeof configured === "string" && configured.trim().length > 0;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export function redactAdcToken(text: string): string {
|
|
344
|
+
return cachedToken ? redactCredential(text, cachedToken.token) : text;
|
|
345
|
+
}
|
package/gemini-api.ts
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
|
|
3
|
+
import { getWebSearchConfigPath } from "./utils.ts";
|
|
4
|
+
import {
|
|
5
|
+
isGeminiAdcAvailable,
|
|
6
|
+
getAdcAccessToken,
|
|
7
|
+
getAdcProject,
|
|
8
|
+
getAdcLocation,
|
|
9
|
+
getVertexApiBase,
|
|
10
|
+
isVertexHost,
|
|
11
|
+
} from "./gemini-adc.ts";
|
|
12
|
+
|
|
13
|
+
const DEFAULT_API_HOST = "https://generativelanguage.googleapis.com";
|
|
14
|
+
const API_VERSION = "v1beta";
|
|
15
|
+
export const API_BASE = `${DEFAULT_API_HOST}/${API_VERSION}`;
|
|
16
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
17
|
+
export const DEFAULT_MODEL = "gemini-3.6-flash";
|
|
18
|
+
|
|
19
|
+
interface GeminiApiConfig {
|
|
20
|
+
geminiApiKey?: unknown;
|
|
21
|
+
geminiBaseUrl?: unknown;
|
|
22
|
+
cloudflareApiKey?: unknown;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
let cachedConfig: GeminiApiConfig | null = null;
|
|
26
|
+
|
|
27
|
+
function loadConfig(): GeminiApiConfig {
|
|
28
|
+
if (cachedConfig) return cachedConfig;
|
|
29
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
30
|
+
cachedConfig = {};
|
|
31
|
+
return cachedConfig;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const raw = readFileSync(CONFIG_PATH, "utf-8");
|
|
35
|
+
try {
|
|
36
|
+
cachedConfig = JSON.parse(raw) as GeminiApiConfig;
|
|
37
|
+
return cachedConfig;
|
|
38
|
+
} catch (err) {
|
|
39
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
40
|
+
throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function withTimeout(signal: AbortSignal | undefined, timeoutMs: number): AbortSignal {
|
|
45
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
46
|
+
return signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function normalizeApiKey(value: unknown): string | null {
|
|
50
|
+
if (typeof value !== "string") return null;
|
|
51
|
+
const normalized = value.trim();
|
|
52
|
+
return normalized.length > 0 ? normalized : null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function normalizeBaseUrl(value: unknown): string | null {
|
|
56
|
+
if (typeof value !== "string") return null;
|
|
57
|
+
const normalized = value.trim().replace(/\/+$/, "");
|
|
58
|
+
return normalized.length > 0 ? normalized : null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isCloudflareGateway(): boolean {
|
|
62
|
+
return getApiHost().includes("gateway.ai.cloudflare.com");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function getApiKey(signal?: AbortSignal): Promise<string | null> {
|
|
66
|
+
return resolveCredential({
|
|
67
|
+
provider: "Gemini",
|
|
68
|
+
configuredValue: loadConfig().geminiApiKey,
|
|
69
|
+
environmentValue: process.env.GEMINI_API_KEY,
|
|
70
|
+
signal,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function getApiHost(): string {
|
|
75
|
+
return (
|
|
76
|
+
normalizeBaseUrl(process.env.GOOGLE_GEMINI_BASE_URL) ??
|
|
77
|
+
normalizeBaseUrl(loadConfig().geminiBaseUrl) ??
|
|
78
|
+
DEFAULT_API_HOST
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function getVersionedApiBase(): string {
|
|
83
|
+
const project = getAdcProject();
|
|
84
|
+
const location = getAdcLocation();
|
|
85
|
+
if (isGeminiAdcAvailable() && project && location) {
|
|
86
|
+
return getVertexApiBase(project, location);
|
|
87
|
+
}
|
|
88
|
+
return `${getApiHost()}/${API_VERSION}`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function getUploadBase(): string {
|
|
92
|
+
return `${getApiHost()}/upload/${API_VERSION}`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Re-point a provider-returned URL at the configured API host (gateway), keeping
|
|
97
|
+
* path and query. No-op when host is unset (already the Google origin).
|
|
98
|
+
*/
|
|
99
|
+
export function rewriteUploadUrlOrigin(url: string): string {
|
|
100
|
+
try {
|
|
101
|
+
const parsed = new URL(url);
|
|
102
|
+
const base = getApiHost(); // may carry a path prefix (gateway passthrough route)
|
|
103
|
+
if (parsed.origin === new URL(base).origin) return url;
|
|
104
|
+
return `${base}${parsed.pathname}${parsed.search}`;
|
|
105
|
+
} catch {
|
|
106
|
+
return url;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function getLegacyCloudflareApiKey(): string | null {
|
|
111
|
+
return normalizeApiKey(process.env.CLOUDFLARE_API_KEY) ?? normalizeApiKey(loadConfig().cloudflareApiKey);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function resolveCloudflareApiKey(signal?: AbortSignal): Promise<string | null> {
|
|
115
|
+
return resolveCredential({
|
|
116
|
+
provider: "Cloudflare",
|
|
117
|
+
configuredValue: loadConfig().cloudflareApiKey,
|
|
118
|
+
environmentValue: process.env.CLOUDFLARE_API_KEY,
|
|
119
|
+
signal,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function getCloudflareApiKey(): string | null {
|
|
124
|
+
return getLegacyCloudflareApiKey();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function isGatewayConfigured(): boolean {
|
|
128
|
+
return isCloudflareGateway() && hasCredentialSource({
|
|
129
|
+
provider: "Cloudflare",
|
|
130
|
+
configuredValue: loadConfig().cloudflareApiKey,
|
|
131
|
+
environmentValue: process.env.CLOUDFLARE_API_KEY,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function buildAuthHeaders(apiKey: string | null = null, cloudflareApiKey: string | null = getLegacyCloudflareApiKey()): Record<string, string> {
|
|
136
|
+
if (!isCloudflareGateway()) return apiKey ? { "x-goog-api-key": apiKey } : {};
|
|
137
|
+
return cloudflareApiKey ? { "cf-aig-authorization": `Bearer ${cloudflareApiKey}` } : {};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function redactGeminiCredentials(text: string, apiKey: string | null | undefined, cloudflareApiKey: string | null | undefined, adcToken?: string | null): string {
|
|
141
|
+
let out = redactCredential(redactCredential(text, apiKey), cloudflareApiKey);
|
|
142
|
+
if (adcToken) out = redactCredential(out, adcToken);
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const responseCredentials = new WeakMap<Response, {
|
|
147
|
+
apiKey: string | null | undefined;
|
|
148
|
+
cloudflareApiKey: string | null | undefined;
|
|
149
|
+
adcToken?: string | null;
|
|
150
|
+
}>();
|
|
151
|
+
|
|
152
|
+
export function redactGeminiApiResponse(response: Response, text: string, apiKey?: string | null, adcToken?: string | null): string {
|
|
153
|
+
const credentials = responseCredentials.get(response);
|
|
154
|
+
return redactGeminiCredentials(text, credentials?.apiKey ?? apiKey, credentials?.cloudflareApiKey, credentials?.adcToken ?? adcToken);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export async function fetchGeminiApi(
|
|
158
|
+
url: string | URL,
|
|
159
|
+
init: RequestInit = {},
|
|
160
|
+
apiKey?: string | null,
|
|
161
|
+
): Promise<Response> {
|
|
162
|
+
const parsedUrl = new URL(url);
|
|
163
|
+
for (const name of parsedUrl.searchParams.keys()) {
|
|
164
|
+
if (["key", "api_key"].includes(name.toLowerCase())) {
|
|
165
|
+
throw new Error("Gemini API credential query parameters are not allowed");
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const project = getAdcProject();
|
|
169
|
+
const location = getAdcLocation();
|
|
170
|
+
const adcMode = isGeminiAdcAvailable() && !!project && !!location && isVertexHost(parsedUrl.origin);
|
|
171
|
+
let adcToken: string | null = null;
|
|
172
|
+
if (adcMode) {
|
|
173
|
+
adcToken = await getAdcAccessToken(init.signal ?? undefined);
|
|
174
|
+
}
|
|
175
|
+
const resolvedApiKey = adcMode ? null : (apiKey === undefined ? await getApiKey(init.signal ?? undefined) : apiKey);
|
|
176
|
+
const cloudflareApiKey = isCloudflareGateway() ? await resolveCloudflareApiKey(init.signal ?? undefined) : null;
|
|
177
|
+
const allowedOrigins = new Set([
|
|
178
|
+
new URL(getApiHost()).origin,
|
|
179
|
+
new URL(DEFAULT_API_HOST).origin,
|
|
180
|
+
...(adcMode ? [parsedUrl.origin] : []),
|
|
181
|
+
]);
|
|
182
|
+
const needsAuth = resolvedApiKey || isGatewayConfigured() || adcMode;
|
|
183
|
+
if (needsAuth && !allowedOrigins.has(parsedUrl.origin)) {
|
|
184
|
+
throw new Error("Gemini API request host is not allowed");
|
|
185
|
+
}
|
|
186
|
+
const headers = new Headers(init.headers);
|
|
187
|
+
headers.delete("x-goog-api-key");
|
|
188
|
+
headers.delete("cf-aig-authorization");
|
|
189
|
+
headers.delete("authorization");
|
|
190
|
+
if (adcMode && adcToken) {
|
|
191
|
+
headers.set("Authorization", `Bearer ${adcToken}`);
|
|
192
|
+
} else {
|
|
193
|
+
for (const [name, value] of Object.entries(buildAuthHeaders(resolvedApiKey, cloudflareApiKey))) {
|
|
194
|
+
headers.set(name, value);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
try {
|
|
198
|
+
const response = await fetch(parsedUrl, { ...init, headers });
|
|
199
|
+
responseCredentials.set(response, { apiKey: resolvedApiKey, cloudflareApiKey, adcToken });
|
|
200
|
+
return response;
|
|
201
|
+
} catch (error) {
|
|
202
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
203
|
+
const redactedMessage = redactGeminiCredentials(message, resolvedApiKey, cloudflareApiKey, adcToken);
|
|
204
|
+
if (redactedMessage === message) throw error;
|
|
205
|
+
const redactedError = new Error(redactedMessage);
|
|
206
|
+
if (error instanceof Error) redactedError.name = error.name;
|
|
207
|
+
throw redactedError;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function hasGeminiApiKeySource(): boolean {
|
|
212
|
+
return hasCredentialSource({
|
|
213
|
+
provider: "Gemini",
|
|
214
|
+
configuredValue: loadConfig().geminiApiKey,
|
|
215
|
+
environmentValue: process.env.GEMINI_API_KEY,
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export function isGeminiApiAvailable(): boolean {
|
|
220
|
+
return isGeminiAdcAvailable() || hasGeminiApiKeySource() || isGatewayConfigured();
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Whether the Gemini Files-API paths (YouTube and local video analysis) can
|
|
225
|
+
* authenticate. These use the Gemini Files API and metadata endpoints, which do
|
|
226
|
+
* not support ADC, so they still require an API key or a Cloudflare gateway.
|
|
227
|
+
*/
|
|
228
|
+
export function isGeminiApiAvailableWithVideo(): boolean {
|
|
229
|
+
return hasGeminiApiKeySource() || isGatewayConfigured();
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export interface GeminiApiOptions {
|
|
233
|
+
apiKey?: string;
|
|
234
|
+
model?: string;
|
|
235
|
+
mimeType?: string;
|
|
236
|
+
signal?: AbortSignal;
|
|
237
|
+
timeoutMs?: number;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export interface GeminiGenerateContentResult {
|
|
241
|
+
text: string;
|
|
242
|
+
finishReason?: string;
|
|
243
|
+
blockReason?: string;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export async function queryGeminiApiWithInlineData(
|
|
247
|
+
prompt: string,
|
|
248
|
+
data: string,
|
|
249
|
+
mimeType: string,
|
|
250
|
+
options: GeminiApiOptions = {},
|
|
251
|
+
): Promise<GeminiGenerateContentResult> {
|
|
252
|
+
const signal = withTimeout(options.signal, options.timeoutMs ?? 120000);
|
|
253
|
+
const apiKey = isGeminiAdcAvailable() ? null : (options.apiKey ?? await getApiKey(signal));
|
|
254
|
+
if (!apiKey && !isGatewayConfigured() && !isGeminiAdcAvailable()) {
|
|
255
|
+
throw new Error(
|
|
256
|
+
"Gemini API not configured. Either:\n" +
|
|
257
|
+
` 1. Configure geminiApiKey in ${CONFIG_PATH} or set GEMINI_API_KEY\n` +
|
|
258
|
+
" 2. Set GOOGLE_GEMINI_BASE_URL + CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing\n" +
|
|
259
|
+
" 3. Set geminiAuth to \"adc\" with a Google Cloud ADC (GOOGLE_APPLICATION_CREDENTIALS) + project/location"
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const model = options.model ?? DEFAULT_MODEL;
|
|
264
|
+
const url = `${getVersionedApiBase()}/models/${model}:generateContent`;
|
|
265
|
+
const body = {
|
|
266
|
+
contents: [
|
|
267
|
+
{
|
|
268
|
+
role: "user",
|
|
269
|
+
parts: [
|
|
270
|
+
{ inlineData: { mimeType, data } },
|
|
271
|
+
{ text: prompt },
|
|
272
|
+
],
|
|
273
|
+
},
|
|
274
|
+
],
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
const res = await fetchGeminiApi(url, {
|
|
278
|
+
method: "POST",
|
|
279
|
+
headers: { "Content-Type": "application/json" },
|
|
280
|
+
body: JSON.stringify(body),
|
|
281
|
+
signal,
|
|
282
|
+
}, apiKey);
|
|
283
|
+
|
|
284
|
+
if (!res.ok) {
|
|
285
|
+
const errorText = redactGeminiApiResponse(res, await res.text(), apiKey);
|
|
286
|
+
throw new Error(`Gemini API error ${res.status}: ${errorText.slice(0, 300)}`);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const response = (await res.json()) as GenerateContentResponse;
|
|
290
|
+
const candidate = response.candidates?.[0];
|
|
291
|
+
const text = candidate?.content?.parts
|
|
292
|
+
?.map((part) => part.text)
|
|
293
|
+
.filter((part): part is string => typeof part === "string" && part.length > 0)
|
|
294
|
+
.join("\n") ?? "";
|
|
295
|
+
|
|
296
|
+
return {
|
|
297
|
+
text,
|
|
298
|
+
...(candidate?.finishReason ? { finishReason: candidate.finishReason } : {}),
|
|
299
|
+
...(response.promptFeedback?.blockReason ? { blockReason: response.promptFeedback.blockReason } : {}),
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export async function queryGeminiApiWithVideo(
|
|
304
|
+
prompt: string,
|
|
305
|
+
videoUri: string,
|
|
306
|
+
options: GeminiApiOptions = {},
|
|
307
|
+
): Promise<string> {
|
|
308
|
+
const signal = withTimeout(options.signal, options.timeoutMs ?? 120000);
|
|
309
|
+
const apiKey = options.apiKey ?? await getApiKey(signal);
|
|
310
|
+
if (!apiKey && !isGatewayConfigured()) {
|
|
311
|
+
throw new Error(
|
|
312
|
+
"Gemini API not configured. Either:\n" +
|
|
313
|
+
` 1. Configure geminiApiKey in ${CONFIG_PATH} or set GEMINI_API_KEY\n` +
|
|
314
|
+
" 2. Set GOOGLE_GEMINI_BASE_URL + CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing"
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const model = options.model ?? DEFAULT_MODEL;
|
|
319
|
+
const url = `${getVersionedApiBase()}/models/${model}:generateContent`;
|
|
320
|
+
|
|
321
|
+
const fileData: Record<string, string> = { fileUri: videoUri };
|
|
322
|
+
if (options.mimeType) fileData.mimeType = options.mimeType;
|
|
323
|
+
|
|
324
|
+
const body = {
|
|
325
|
+
contents: [
|
|
326
|
+
{
|
|
327
|
+
role: "user",
|
|
328
|
+
parts: [
|
|
329
|
+
{ fileData },
|
|
330
|
+
{ text: prompt },
|
|
331
|
+
],
|
|
332
|
+
},
|
|
333
|
+
],
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
const res = await fetchGeminiApi(url, {
|
|
337
|
+
method: "POST",
|
|
338
|
+
headers: { "Content-Type": "application/json" },
|
|
339
|
+
body: JSON.stringify(body),
|
|
340
|
+
signal,
|
|
341
|
+
}, apiKey);
|
|
342
|
+
|
|
343
|
+
if (!res.ok) {
|
|
344
|
+
const errorText = redactGeminiApiResponse(res, await res.text(), apiKey);
|
|
345
|
+
throw new Error(`Gemini API error ${res.status}: ${errorText.slice(0, 300)}`);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const data = (await res.json()) as GenerateContentResponse;
|
|
349
|
+
const text = data.candidates?.[0]?.content?.parts
|
|
350
|
+
?.map((p) => p.text)
|
|
351
|
+
.filter(Boolean)
|
|
352
|
+
.join("\n");
|
|
353
|
+
|
|
354
|
+
if (!text) throw new Error("Gemini API returned empty response");
|
|
355
|
+
return text;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
interface GenerateContentResponse {
|
|
359
|
+
candidates?: Array<{
|
|
360
|
+
content?: {
|
|
361
|
+
parts?: Array<{ text?: string }>;
|
|
362
|
+
};
|
|
363
|
+
finishReason?: string;
|
|
364
|
+
}>;
|
|
365
|
+
promptFeedback?: {
|
|
366
|
+
blockReason?: string;
|
|
367
|
+
};
|
|
368
|
+
}
|