@namzu/google 0.2.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/dist/wire.js ADDED
@@ -0,0 +1,183 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { toToolResultBlocks } from '@namzu/sdk';
3
+ export function effortLevels(model) {
4
+ if (model === 'gemini-3-flash-preview')
5
+ return ['minimal', 'low', 'medium', 'high'];
6
+ if (model === 'gemini-3-pro-preview')
7
+ return ['low', 'high'];
8
+ if (/^gemini-2\.5-/.test(model))
9
+ return [];
10
+ return undefined;
11
+ }
12
+ export function routeFor(p) {
13
+ return p.providerRoute ?? { providerId: 'google', model: p.model, chainIndex: 0 };
14
+ }
15
+ export function partDigest(parts) {
16
+ return createHash('sha256').update(JSON.stringify(parts)).digest('hex');
17
+ }
18
+ export function buildRequest(p, scope = 'api-key') {
19
+ for (const key of ['parallelToolCalls', 'repetitionPenalty'])
20
+ if (p[key] !== undefined)
21
+ throw new Error(`Gemini does not support explicit ${key}.`);
22
+ if (p.cacheControl?.type === 'ephemeral')
23
+ throw new Error('Gemini does not support explicit ephemeral cache control.');
24
+ // enforceToolInputSchema is an optional optimization hint. Native tool schemas
25
+ // are sent below; unsupported strict generation is not claimed.
26
+ const generationConfig = {};
27
+ for (const [from, to] of [
28
+ ['maxTokens', 'maxOutputTokens'],
29
+ ['temperature', 'temperature'],
30
+ ['topP', 'topP'],
31
+ ['topK', 'topK'],
32
+ ['stop', 'stopSequences'],
33
+ ['frequencyPenalty', 'frequencyPenalty'],
34
+ ['presencePenalty', 'presencePenalty'],
35
+ ])
36
+ if (p[from] !== undefined)
37
+ generationConfig[to] = p[from];
38
+ if (p.responseFormat) {
39
+ generationConfig.responseMimeType = 'application/json';
40
+ if (p.responseFormat.type === 'json_schema')
41
+ generationConfig.responseJsonSchema = p.responseFormat.json_schema.schema;
42
+ }
43
+ if (p.effort || p.thinking) {
44
+ const t = {};
45
+ if (p.effort) {
46
+ if (!effortLevels(p.model)?.includes(p.effort))
47
+ throw new Error(`Gemini does not publish effort ${p.effort} for ${p.model}.`);
48
+ t.thinkingLevel = p.effort.toUpperCase();
49
+ }
50
+ if (p.thinking) {
51
+ const cfg = p.thinking;
52
+ if (cfg.type === 'disabled') {
53
+ if (!/^gemini-2\.5-flash/.test(p.model))
54
+ throw new Error(`Thinking cannot be disabled for ${p.model}.`);
55
+ t.thinkingBudget = 0;
56
+ }
57
+ else if (cfg.type === 'enabled') {
58
+ if (!/^gemini-2\.5-/.test(p.model) ||
59
+ !Number.isInteger(cfg.budgetTokens) ||
60
+ (cfg.budgetTokens ?? 0) <= 0)
61
+ throw new Error('Manual Gemini thinking requires a Gemini 2.5 model and positive integer budgetTokens.');
62
+ t.thinkingBudget = cfg.budgetTokens;
63
+ }
64
+ else if (/^gemini-2\.5-/.test(p.model))
65
+ t.thinkingBudget = -1;
66
+ else if (!effortLevels(p.model)?.length)
67
+ throw new Error(`Unknown adaptive thinking support for ${p.model}.`);
68
+ if (cfg.type !== 'enabled' && cfg.budgetTokens !== undefined)
69
+ throw new Error('budgetTokens requires enabled thinking.');
70
+ t.includeThoughts = cfg.display === 'summarized';
71
+ }
72
+ generationConfig.thinkingConfig = t;
73
+ }
74
+ const contents = [];
75
+ const system = [];
76
+ const names = new Map();
77
+ const nativeIds = new Map();
78
+ for (const m of p.messages) {
79
+ if (m.role === 'system') {
80
+ system.push({ text: m.content });
81
+ continue;
82
+ }
83
+ let parts = [];
84
+ if (m.role === 'assistant') {
85
+ for (const call of m.toolCalls ?? [])
86
+ names.set(call.id, call.function.name);
87
+ const r = m.source?.replayState;
88
+ if (r?.kind === 'namzu-google' &&
89
+ r.version === 1 &&
90
+ r.scope === scope &&
91
+ Array.isArray(r.parts) &&
92
+ r.digest === partDigest(r.parts) &&
93
+ JSON.stringify(r.route) === JSON.stringify(routeFor(p)) &&
94
+ m.source?.providerId === routeFor(p).providerId &&
95
+ m.source?.model === p.model &&
96
+ m.source?.chainIndex === routeFor(p).chainIndex &&
97
+ r.text === (m.content ?? '') &&
98
+ JSON.stringify(r.calls) === JSON.stringify(m.toolCalls ?? []) &&
99
+ Array.isArray(r.parts))
100
+ parts = r.parts;
101
+ else {
102
+ if (m.content)
103
+ parts.push({ text: m.content });
104
+ for (const call of m.toolCalls ?? [])
105
+ parts.push({
106
+ functionCall: {
107
+ name: call.function.name,
108
+ args: JSON.parse(call.function.arguments),
109
+ id: call.id,
110
+ },
111
+ });
112
+ }
113
+ const nativeCalls = parts.filter((part) => part.functionCall).map((part) => part.functionCall);
114
+ for (const [index, call] of (m.toolCalls ?? []).entries())
115
+ nativeIds.set(call.id, nativeCalls[index]?.id);
116
+ }
117
+ else if (m.role === 'tool') {
118
+ const name = names.get(m.toolCallId);
119
+ if (!name)
120
+ throw new Error('Gemini tool result has no matching function call.');
121
+ const blocks = toToolResultBlocks(m.content);
122
+ parts.push({
123
+ functionResponse: {
124
+ name,
125
+ ...(nativeIds.get(m.toolCallId) !== undefined ? { id: nativeIds.get(m.toolCallId) } : {}),
126
+ response: {
127
+ [m.isError ? 'error' : 'output']: blocks
128
+ .filter((b) => b.type === 'text')
129
+ .map((b) => b.text)
130
+ .join('\n'),
131
+ },
132
+ },
133
+ });
134
+ for (const b of blocks)
135
+ if (b.type !== 'text') {
136
+ if ('modelOmission' in b && b.modelOmission)
137
+ parts.push({ text: '[Attachment omitted from model context]' });
138
+ else
139
+ parts.push({ inlineData: { mimeType: b.mediaType, data: b.data } });
140
+ }
141
+ }
142
+ else {
143
+ if (m.content)
144
+ parts.push({ text: m.content });
145
+ for (const a of m.attachments ?? []) {
146
+ if (a.type === 'stored')
147
+ throw new Error('Resolve stored attachments before calling Gemini.');
148
+ if ('modelOmission' in a && a.modelOmission)
149
+ parts.push({ text: '[Attachment omitted from model context]' });
150
+ else {
151
+ if (a.type === 'document' && a.citations)
152
+ throw new Error('Gemini document citations are not supported by this driver.');
153
+ parts.push({ inlineData: { mimeType: a.mediaType, data: a.data } });
154
+ }
155
+ }
156
+ }
157
+ if (parts.length)
158
+ contents.push({ role: m.role === 'assistant' ? 'model' : 'user', parts });
159
+ }
160
+ const req = { contents, generationConfig };
161
+ if (system.length)
162
+ req.systemInstruction = { parts: system };
163
+ if (p.tools?.length)
164
+ req.tools = [
165
+ {
166
+ functionDeclarations: p.tools.map((t) => ({
167
+ name: t.function.name,
168
+ description: t.function.description,
169
+ parametersJsonSchema: t.function.parameters,
170
+ })),
171
+ },
172
+ ];
173
+ if (p.toolChoice)
174
+ req.toolConfig = {
175
+ functionCallingConfig: typeof p.toolChoice === 'string'
176
+ ? {
177
+ mode: { auto: 'AUTO', none: 'NONE', required: 'ANY' }[p.toolChoice],
178
+ }
179
+ : { mode: 'ANY', allowedFunctionNames: [p.toolChoice.function.name] },
180
+ };
181
+ return req;
182
+ }
183
+ //# sourceMappingURL=wire.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire.js","sourceRoot":"","sources":["../src/wire.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAExC,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAsB/C,MAAM,UAAU,YAAY,CAAC,KAAa;IACzC,IAAI,KAAK,KAAK,wBAAwB;QAAE,OAAO,CAAC,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;IACnF,IAAI,KAAK,KAAK,sBAAsB;QAAE,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA;IAC5D,IAAI,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,EAAE,CAAA;IAC1C,OAAO,SAAS,CAAA;AACjB,CAAC;AACD,MAAM,UAAU,QAAQ,CAAC,CAAuB;IAC/C,OAAO,CAAC,CAAC,aAAa,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,UAAU,EAAE,CAAC,EAAE,CAAA;AAClF,CAAC;AACD,MAAM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"version": "0.2.0",
4
+ "description": "Native Gemini API and Gemini CLI OAuth provider for the Namzu agent kernel.",
5
+ "license": "FSL-1.1-MIT",
6
+ "engines": {
7
+ "node": ">=20.0.0"
8
+ },
9
+ "type": "module",
10
+ "homepage": "https://github.com/cogitave/namzu#readme",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/cogitave/namzu.git",
14
+ "directory": "packages/providers/google"
15
+ },
16
+ "bugs": {
17
+ "url": "https://github.com/cogitave/namzu/issues"
18
+ },
19
+ "main": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.js"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "!dist/**/*.test.*",
30
+ "!dist/**/*.proc-test.*",
31
+ "!dist/**/__tests__",
32
+ "!dist/**/__fixtures__",
33
+ "!dist/**/test-setup.*",
34
+ "src",
35
+ "!src/**/*.test.*",
36
+ "!src/**/*.proc-test.*",
37
+ "!src/**/__tests__",
38
+ "!src/**/__fixtures__",
39
+ "!src/**/test-setup.*",
40
+ "LICENSE.md",
41
+ "README.md",
42
+ "CHANGELOG.md"
43
+ ],
44
+ "sideEffects": false,
45
+ "publishConfig": {
46
+ "access": "public",
47
+ "provenance": false
48
+ },
49
+ "peerDependencies": {
50
+ "@namzu/sdk": ">=37.0.0"
51
+ },
52
+ "devDependencies": {
53
+ "@biomejs/biome": "^1.9.4",
54
+ "@types/node": "^22.19.17",
55
+ "typescript": "^5.5.0",
56
+ "vitest": "^3.2.6",
57
+ "zod": "^3.23.0",
58
+ "@namzu/sdk": "^38.0.0"
59
+ },
60
+ "scripts": {
61
+ "build": "tsc --build",
62
+ "dev": "tsc --build --watch",
63
+ "lint": "biome check src/",
64
+ "lint:fix": "biome check --write src/",
65
+ "format": "biome format --write src/",
66
+ "test": "vitest run --passWithNoTests",
67
+ "typecheck": "tsc --noEmit"
68
+ }
69
+ }
package/src/client.ts ADDED
@@ -0,0 +1,349 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { attributionHeaders, providerHttpError } from '@namzu/sdk'
3
+ import type {
4
+ ChatCompletionParams,
5
+ LLMProvider,
6
+ ModelInfo,
7
+ ProviderCapabilities,
8
+ StreamChunk,
9
+ ToolCall,
10
+ } from '@namzu/sdk'
11
+ import type { GoogleConfig } from './types.js'
12
+ import { type Part, buildRequest, effortLevels, partDigest, routeFor } from './wire.js'
13
+ export const DEFAULT_GEMINI_MODEL = 'gemini-2.5-flash'
14
+ // Standard text/image API reference prices, USD per million; not subscription billing.
15
+ const PRICES: Record<string, readonly [number, number]> = {
16
+ 'gemini-2.5-flash': [0.3, 2.5],
17
+ 'gemini-2.5-pro': [1.25, 10],
18
+ }
19
+ export const GOOGLE_CAPABILITIES: ProviderCapabilities = {
20
+ supportsTools: true,
21
+ supportsStreaming: true,
22
+ supportsFunctionCalling: true,
23
+ supportsVision: true,
24
+ supportsDocuments: true,
25
+ supportsToolResultImages: true,
26
+ supportsToolResultDocuments: true,
27
+ supportsNativeStructuredOutput: true,
28
+ }
29
+ const API = 'https://generativelanguage.googleapis.com/v1beta'
30
+ const ASSIST = 'https://cloudcode-pa.googleapis.com/v1internal'
31
+ interface ResponseBody {
32
+ response?: ResponseBody
33
+ candidates?: Array<{ content?: { parts?: Part[] }; finishReason?: string }>
34
+ promptFeedback?: { blockReason?: string }
35
+ usageMetadata?: {
36
+ promptTokenCount?: number
37
+ candidatesTokenCount?: number
38
+ thoughtsTokenCount?: number
39
+ totalTokenCount?: number
40
+ cachedContentTokenCount?: number
41
+ }
42
+ }
43
+ /** Native GenerateContent transport; credential ownership remains with the host. */
44
+ export class GoogleProvider implements LLMProvider {
45
+ readonly id = 'google'
46
+ readonly name = 'Google Gemini'
47
+ readonly capabilities = GOOGLE_CAPABILITIES
48
+ private readonly fetcher: typeof globalThis.fetch
49
+ private readonly projectId?: string
50
+ constructor(private readonly config: GoogleConfig) {
51
+ if (Boolean(config.apiKey) === Boolean(config.getAccessToken))
52
+ throw new Error('Configure exactly one of Gemini apiKey or getAccessToken.')
53
+ if (
54
+ config.timeoutMs !== undefined &&
55
+ (!Number.isFinite(config.timeoutMs) || config.timeoutMs <= 0)
56
+ )
57
+ throw new Error('Gemini timeoutMs must be positive.')
58
+ this.fetcher = config.fetch ?? globalThis.fetch
59
+ this.projectId = config.projectId
60
+ }
61
+ reasoningEffortLevelsFor(model: string) {
62
+ return effortLevels(model)
63
+ }
64
+ private signal(signal?: AbortSignal) {
65
+ const timeout = AbortSignal.timeout(this.config.timeoutMs ?? 120_000)
66
+ return signal ? AbortSignal.any([signal, timeout]) : timeout
67
+ }
68
+ private async request(
69
+ url: string,
70
+ signal: AbortSignal,
71
+ body?: unknown,
72
+ accessToken?: string,
73
+ ): Promise<Response> {
74
+ signal.throwIfAborted()
75
+ const headers: Record<string, string> = {
76
+ ...attributionHeaders(),
77
+ 'Content-Type': 'application/json',
78
+ }
79
+ if (this.config.getAccessToken)
80
+ headers.Authorization = `Bearer ${accessToken ?? (await this.config.getAccessToken(signal))}`
81
+ else headers['x-goog-api-key'] = this.config.apiKey as string
82
+ signal.throwIfAborted()
83
+ const res = await this.fetcher(url, {
84
+ redirect: 'error',
85
+ method: body === undefined ? 'GET' : 'POST',
86
+ headers,
87
+ body: body === undefined ? undefined : JSON.stringify(body),
88
+ signal,
89
+ })
90
+ if (!res.ok) {
91
+ await res.body?.cancel()
92
+ throw providerHttpError({
93
+ providerId: this.id,
94
+ status: res.status,
95
+ retryAfter: res.headers.get('retry-after'),
96
+ })
97
+ }
98
+ return res
99
+ }
100
+ private async project(
101
+ signal: AbortSignal,
102
+ verify = false,
103
+ accessToken?: string,
104
+ ): Promise<string> {
105
+ if (this.projectId && !verify) return this.projectId
106
+ const res = await this.request(
107
+ `${ASSIST}:loadCodeAssist`,
108
+ signal,
109
+ {
110
+ cloudaicompanionProject: this.projectId,
111
+ metadata: {
112
+ ideType: 'IDE_UNSPECIFIED',
113
+ platform: 'PLATFORM_UNSPECIFIED',
114
+ pluginType: 'GEMINI',
115
+ },
116
+ },
117
+ accessToken,
118
+ )
119
+ const data = (await res.json()) as {
120
+ currentTier?: unknown
121
+ cloudaicompanionProject?: string | { id?: string }
122
+ }
123
+ const project =
124
+ typeof data.cloudaicompanionProject === 'string'
125
+ ? data.cloudaicompanionProject
126
+ : (data.cloudaicompanionProject?.id ?? this.projectId)
127
+ if (!data.currentTier || !project)
128
+ throw new Error(
129
+ 'Complete Gemini CLI login and Code Assist setup before using this account in Namzu; automatic onboarding is not performed.',
130
+ )
131
+ return project
132
+ }
133
+ async probeCredential(signal?: AbortSignal): Promise<void> {
134
+ const bounded = this.signal(signal)
135
+ if (this.config.getAccessToken) await this.project(bounded, true)
136
+ else await this.request(`${API}/models?pageSize=1`, bounded).then((r) => r.body?.cancel())
137
+ }
138
+ async listModels(signal?: AbortSignal): Promise<ModelInfo[]> {
139
+ signal?.throwIfAborted()
140
+ if (this.config.getAccessToken)
141
+ return Object.keys(PRICES).map((id) => ({
142
+ id,
143
+ name: id,
144
+ inputPrice: PRICES[id]?.[0] ?? 0,
145
+ outputPrice: PRICES[id]?.[1] ?? 0,
146
+ supportsToolUse: true,
147
+ supportsStreaming: true,
148
+ reasoningEffortLevels: effortLevels(id),
149
+ }))
150
+ const models: ModelInfo[] = []
151
+ let pageToken: string | undefined
152
+ const bounded = this.signal(signal)
153
+ do {
154
+ const res = await this.request(
155
+ `${API}/models?pageSize=100${pageToken ? `&pageToken=${encodeURIComponent(pageToken)}` : ''}`,
156
+ bounded,
157
+ )
158
+ const data = (await res.json()) as {
159
+ models?: Array<{
160
+ name: string
161
+ displayName?: string
162
+ inputTokenLimit?: number
163
+ outputTokenLimit?: number
164
+ supportedGenerationMethods?: string[]
165
+ }>
166
+ nextPageToken?: string
167
+ }
168
+ for (const m of data.models ?? [])
169
+ if (m.supportedGenerationMethods?.includes('generateContent')) {
170
+ const id = m.name.replace(/^models\//, '')
171
+ models.push({
172
+ id,
173
+ name: m.displayName ?? id,
174
+ contextWindow: m.inputTokenLimit,
175
+ maxOutputTokens: m.outputTokenLimit,
176
+ inputPrice: PRICES[id]?.[0] ?? 0,
177
+ outputPrice: PRICES[id]?.[1] ?? 0,
178
+ supportsToolUse: true,
179
+ supportsStreaming: true,
180
+ reasoningEffortLevels: effortLevels(id),
181
+ })
182
+ }
183
+ pageToken = data.nextPageToken
184
+ } while (pageToken)
185
+ return models
186
+ }
187
+ async *chatStream(p: ChatCompletionParams): AsyncIterable<StreamChunk> {
188
+ const scope = this.config.getAccessToken ? 'code-assist' : 'api-key'
189
+ const body = buildRequest(p, scope)
190
+ const signal = this.signal(p.signal)
191
+ const id = randomUUID()
192
+ const oauth = Boolean(this.config.getAccessToken)
193
+ const accessToken = await this.config.getAccessToken?.(signal)
194
+ const url = oauth
195
+ ? `${ASSIST}:streamGenerateContent?alt=sse`
196
+ : `${API}/models/${encodeURIComponent(p.model)}:streamGenerateContent?alt=sse`
197
+ const payload = oauth
198
+ ? {
199
+ model: p.model,
200
+ project: await this.project(signal, false, accessToken),
201
+ user_prompt_id: id,
202
+ request: body,
203
+ }
204
+ : body
205
+ const res = await this.request(url, signal, payload, accessToken)
206
+ if (!res.body) throw new Error('Gemini returned an empty streaming body.')
207
+ const reader = res.body.getReader()
208
+ const decoder = new TextDecoder()
209
+ let buffer = ''
210
+ let terminal = false
211
+ let text = ''
212
+ let toolIndex = 0
213
+ let reasoningIndex = 0
214
+ const parts: Part[] = []
215
+ const calls: ToolCall[] = []
216
+ let usage: StreamChunk['usage']
217
+ let finish: StreamChunk['finishReason']
218
+ const parse = (event: string): ResponseBody | undefined => {
219
+ const data = event
220
+ .split('\n')
221
+ .filter((l) => l.startsWith('data:'))
222
+ .map((l) => l.slice(5).trimStart())
223
+ .join('\n')
224
+ return data && data !== '[DONE]' ? JSON.parse(data) : undefined
225
+ }
226
+ try {
227
+ while (true) {
228
+ signal.throwIfAborted()
229
+ const next = await reader.read()
230
+ buffer += decoder.decode(next.value, { stream: !next.done })
231
+ buffer = buffer.replace(/\r\n/g, '\n')
232
+ if (buffer.length > 16 * 1024 * 1024) throw new Error('Gemini SSE event exceeds 16 MiB.')
233
+ let boundary = buffer.indexOf('\n\n')
234
+ while (boundary >= 0 || (next.done && buffer.trim())) {
235
+ const event = boundary >= 0 ? buffer.slice(0, boundary) : buffer
236
+ buffer = boundary >= 0 ? buffer.slice(boundary + 2) : ''
237
+ boundary = buffer.indexOf('\n\n')
238
+ const envelope = parse(event)
239
+ if (!envelope) continue
240
+ const chunk = envelope.response ?? envelope
241
+ if (chunk.promptFeedback?.blockReason) {
242
+ terminal = true
243
+ finish = 'content_filter'
244
+ }
245
+ const candidate = chunk.candidates?.[0]
246
+ for (const part of candidate?.content?.parts ?? []) {
247
+ parts.push(part)
248
+ if (part.functionCall) {
249
+ const f = part.functionCall
250
+ const callId = f.id ?? randomUUID()
251
+ const args = JSON.stringify(f.args ?? {})
252
+ calls.push({
253
+ id: callId,
254
+ type: 'function',
255
+ function: { name: f.name, arguments: args },
256
+ })
257
+ yield {
258
+ id,
259
+ delta: {
260
+ toolCalls: [
261
+ {
262
+ index: toolIndex,
263
+ id: callId,
264
+ type: 'function',
265
+ function: { name: f.name, arguments: args },
266
+ },
267
+ ],
268
+ },
269
+ }
270
+ yield {
271
+ id,
272
+ delta: { toolCallEnd: { index: toolIndex++, id: callId } },
273
+ }
274
+ } else if (part.thought) {
275
+ yield {
276
+ id,
277
+ delta: {
278
+ reasoning: {
279
+ index: reasoningIndex++,
280
+ type: 'thinking',
281
+ text: part.text ?? '',
282
+ signature: part.thoughtSignature,
283
+ done: true,
284
+ },
285
+ },
286
+ }
287
+ } else if (part.text) {
288
+ text += part.text
289
+ yield { id, delta: { content: part.text } }
290
+ }
291
+ }
292
+ if (candidate?.finishReason) {
293
+ terminal = true
294
+ if (candidate.finishReason === 'MAX_TOKENS') finish = 'length'
295
+ else if (candidate.finishReason === 'STOP')
296
+ finish = calls.length ? 'tool_calls' : 'stop'
297
+ else if (
298
+ [
299
+ 'SAFETY',
300
+ 'RECITATION',
301
+ 'BLOCKLIST',
302
+ 'PROHIBITED_CONTENT',
303
+ 'SPII',
304
+ 'IMAGE_SAFETY',
305
+ ].includes(candidate.finishReason)
306
+ )
307
+ finish = 'content_filter'
308
+ else throw new Error(`Gemini generation stopped with ${candidate.finishReason}.`)
309
+ }
310
+ const u = chunk.usageMetadata
311
+ if (u)
312
+ usage = {
313
+ cachedTokens: u.cachedContentTokenCount ?? 0,
314
+ cacheWriteTokens: 0,
315
+ reasoningTokens: u.thoughtsTokenCount,
316
+ promptTokens: u.promptTokenCount ?? 0,
317
+ completionTokens: (u.candidatesTokenCount ?? 0) + (u.thoughtsTokenCount ?? 0),
318
+ totalTokens:
319
+ u.totalTokenCount ??
320
+ (u.promptTokenCount ?? 0) +
321
+ (u.candidatesTokenCount ?? 0) +
322
+ (u.thoughtsTokenCount ?? 0),
323
+ }
324
+ }
325
+ if (next.done) break
326
+ }
327
+ if (!terminal) throw new Error('Gemini stream ended without a terminal finish reason.')
328
+ yield {
329
+ id,
330
+ delta: {},
331
+ finishReason: finish,
332
+ usage,
333
+ replayState: {
334
+ kind: 'namzu-google',
335
+ version: 1,
336
+ scope,
337
+ digest: partDigest(parts),
338
+ route: routeFor(p),
339
+ parts,
340
+ text,
341
+ calls,
342
+ },
343
+ }
344
+ } finally {
345
+ await reader.cancel().catch(() => {})
346
+ reader.releaseLock()
347
+ }
348
+ }
349
+ }
package/src/index.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { ProviderRegistry, type RegisterOptions } from '@namzu/sdk'
2
+ import { GOOGLE_CAPABILITIES, GoogleProvider } from './client.js'
3
+ import type { GoogleProviderConfig } from './types.js'
4
+ declare module '@namzu/sdk' {
5
+ interface ProviderConfigRegistry {
6
+ google: GoogleProviderConfig
7
+ }
8
+ }
9
+ export function registerGoogle(options?: RegisterOptions): void {
10
+ ProviderRegistry.register('google', GoogleProvider, GOOGLE_CAPABILITIES, options)
11
+ }
12
+ export {
13
+ GoogleProvider,
14
+ GOOGLE_CAPABILITIES,
15
+ DEFAULT_GEMINI_MODEL,
16
+ } from './client.js'
17
+ export type { GoogleConfig, GoogleProviderConfig } from './types.js'
package/src/types.ts ADDED
@@ -0,0 +1,12 @@
1
+ /** Gemini API credentials or a host-owned Gemini CLI OAuth token refresher. */
2
+ export interface GoogleConfig {
3
+ apiKey?: string
4
+ getAccessToken?: (signal?: AbortSignal) => Promise<string>
5
+ projectId?: string
6
+ model?: string
7
+ timeoutMs?: number
8
+ fetch?: typeof globalThis.fetch
9
+ }
10
+ export interface GoogleProviderConfig extends GoogleConfig {
11
+ type: 'google'
12
+ }