GeezerVison is showing github.com — feat: add Zero Gemini provider by gnanam1990 · Pull Request #18 · Twigpine/zero
Conversation
Summary
Adds the M1 Gnanam Gemini provider slice for Zero. This implements a Zero-native Google Gemini streaming adapter and wires registry-backed google models into the existing provider runtime resolver.
What Changed
- Added
src/providers/gemini.ts with REST/SSE streaming through Gemini streamGenerateContent.
- Maps Zero system/user/assistant/tool history into Gemini
systemInstruction, contents, functionCall, and functionResponse parts.
- Maps Zero tools into Gemini
functionDeclarations.
- Normalizes Gemini streamed text, candidate function calls, top-level
functionCalls, prompt-block feedback, HTTP auth/rate-limit errors, and usageMetadata into the shared Zero provider event schema.
- Wires
google runtime provider creation so registry Gemini models are implemented instead of pending.
- Passes registry
maxOutputTokens into the Gemini provider.
- Adds provider and runtime tests for mapping, streaming text, usage including thinking tokens, tool calls, prompt blocks, malformed tool history, API key requirement, and max token validation.
Drac Reference
Used Drac only as behavioral reference, rewritten cleanly in TypeScript for Zero:
by-function/llm-api/gemini-api.js for Gemini usage metadata, prompt block handling, and function call extraction.
by-function/llm-api/openai-api-6.js for Gemini parts and function response mapping.
by-function/llm-api/claude-api-50.js for normalized usage/tool-call behavior.
Validation
npx --yes bun install --frozen-lockfile
npx --yes bun run typecheck
npx --yes bun test tests/gemini-provider.test.ts tests/zero-provider-runtime.test.ts --timeout 15000 — 24 pass, 0 fail
npx --yes bun test ./tests --timeout 15000 — 132 pass, 0 fail
npx --yes bun run build
npx --yes bun run smoke:build
./zero --help
./zero providers current
git diff --check origin/main..HEAD
Review requested from @Vasanthdev2004 and @anandh8x.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review: PR #18 — feat: add Zero Gemini provider
Author: @gnanam1990 → main
Scope: 4 files, +833/-2. New src/providers/gemini.ts (441 lines) with REST/SSE streaming through Gemini streamGenerateContent. Wires google runtime provider into the resolver so registry Gemini models are implemented instead of pending. Maps Zero messages/tools/usage into Gemini's systemInstruction, contents, functionDeclarations, functionCall/functionResponse. Handles candidate parts and top-level functionCalls arrays, promptFeedback blocks, usageMetadata with thinking tokens, auth/rate-limit errors. 10 new provider tests + runtime tests.
PRD alignment: Per v2 PRD line, Gnanam owns M1 Gemini provider. Scope matches exactly. Cross-owner resolver change is additive. Owner is correct.
Verdict: Request changes — one correctness bug in message mapping that will produce 400s from the Gemini API.
Requires changes
1. Consecutive user entries produced when tool result precedes user text
src/providers/gemini.ts:342 pushes user text as a new { role: 'user' } entry directly:
if (content) {
contents.push({ role: 'user', parts: [{ text: content }] });
}
But tool results use appendUserParts (line 312), which also produces { role: 'user' } entries (via appendUserParts line 360). If a conversation history has:
user: "read file" → contents.push({ role: 'user', parts: [...] })
assistant: [tool_calls] → contents.push({ role: 'model', parts: [...] })
tool: [result] → appendUserParts → { role: 'user', parts: [functionResponse] }
user: "also grep" → contents.push({ role: 'user', parts: [{ text: ... }] })
The Gemini contents array ends up as [user, model, user, user] — two consecutive user entries. Gemini's API requires strictly alternating user/model roles in contents and will reject this with a validation error.
Fix: Use appendUserParts for user text, matching the tool-result path:
if (content) {
appendUserParts(contents, [{ text: content }]);
}
This merges the text into the preceding user entry when one exists, producing [user, model, user] — correct.
Suggestions (non-blocking)
2. appendUserParts merges functionResponse and text into one user message
This is actually desired behavior (Gemini allows mixed functionResponse and text parts in a single user message), but worth verifying the API accepts it. Gemini's docs confirm a single user message can contain multiple parts. ✅
3. toolNamesById fallback on line 316 uses the toolCallId as the function name
name: toolNamesById.get(message.toolCallId) ?? message.toolCallId,
If the ID isn't in the map (e.g., restored from a persisted conversation), Gemini sees a function name that's an opaque ID string and will 400 because no matching functionDeclaration exists. Not a realistic scenario for M1 since the provider always constructs full history, but a silent footgun for any persistence layer.
4. No AbortSignal/timeout support
Same pattern as Anthropic and OpenAI providers — FetchLike accepts signal via Parameters<typeof fetch>, but createStream never passes one. Non-blocking for M1.
5. No test for user-after-tool conversation scenario
The test suite exercises single-turn and multi-turn patterns but doesn't test a conversation with:
user → assistant(toolCalls) → tool(result) → user(text)
This would have caught issue #1 above. Consider adding in the next iteration.
6. DEFAULT_MAX_TOKENS = 8192 (line 4)
Reasonable for Gemini. No floor in resolveGoogleMaxTokens (src/zero-provider-runtime/resolver.ts:29-31), which passes through the registry value directly — correct behavior since Gemini models have varying ceilings and 8192 is already a good default.
What I like
-
Gemini-specific quirks handled correctly:
- Both
candidates[].content.parts[].functionCall and top-level functionCalls[] arrays (lines 183-199). Gemini can emit either — the code handles both.
usageMetadata.thoughtsTokenCount added to completionTokens (line 179) — correctly includes thinking tokens in usage accounting.
promptFeedback.blockReason surfaced as a clear error (lines 162-166).
models/ prefix stripping in normalizeModel (line 411 — Gemini returns model names with the prefix sometimes).
- Both
args and arguments in function call objects (line 223 — different in candidate parts vs top-level).
- Synthetic tool call IDs for candidate parts that lack IDs (line 221 —
gemini_tool_N).
-
emitGeminiToolCall as a generator — clean separation of tool-call event sequencing into a reusable function.
-
x-goog-api-key header (line 124) — correct for Google AI Studio API key auth.
-
SSE parsing reuses the same findSSEBoundary pattern from the Anthropic provider. But notice Gemini's stream uses untyped data: events (no event: prefix) — the parseGeminiSSEPayload function correctly handles this by looking only for data: lines. Correct for Gemini's protocol.
-
resolveGoogleMaxTokens is a one-liner passthrough (no artificial floor) — appropriate since Gemini's registry entries already have correct maxOutputTokens values.
-
Test coverage is thorough — 10 tests covering mapping, streaming text, function calls, top-level functionCalls, auth errors, rate limits, prompt blocks, empty messages, malformed tool history, and maxToken validation.
-
No dead code — every Gemini-specific path is exercised in at least one test.
Cross-owner / merge notes
src/zero-provider-runtime/resolver.ts change is purely additive: imports GeminiProvider, adds google branch before the throw ZeroPendingProviderError. No conflict with PR #15 (which added anthropic branch) or PR #17 (which modified resolver for exec). All additive — merge-safe.
tests/zero-provider-runtime.test.ts change is also additive (new tests at end of file). Merge-safe.
src/providers/gemini.ts is an entirely new file — no merge concerns.
Validation noted from PR body
bun run typecheck, bun test tests/gemini-provider.test.ts tests/zero-provider-runtime.test.ts (24 pass), bun test ./tests (132 pass), bun run build, bun run smoke:build — all green per author.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
Fixed the requested Gemini message-mapping blocker in daa72e5.
- User text after a tool result now uses
appendUserParts, so Gemini contents merge into [user, model, user] instead of producing consecutive user turns.
- Added regression coverage for
user -> assistant(toolCalls) -> tool(result) -> user(text).
Validation after fix:
npx --yes bun test tests/gemini-provider.test.ts tests/zero-provider-runtime.test.ts --timeout 15000 — 25 pass, 0 fail
npx --yes bun test ./tests --timeout 15000 — 133 pass, 0 fail
npx --yes bun run typecheck
npx --yes bun run build
npx --yes bun run smoke:build
./zero --help
./zero providers current
git diff --check
@anandh8x @Vasanthdev2004 ready for re-review.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Re-review: PR #18 v2 — feat: add Zero Gemini provider
Author: @gnanam1990 → main
Head: daa72e5f (was 1e3793ab)
Delta: Single fix + one new test.
Review items disposition
| Issue |
Status |
Consecutive user entries when tool result precedes user text (400 from Gemini API) |
FIXED — contents.push({ role: 'user', ... }) replaced with appendUserParts(contents, [...]). Now merges user text into the preceding user entry instead of creating a duplicate. |
| No test for user-after-tool conversation scenario |
FIXED — new test "merges user text after a tool result into the same Gemini user turn" asserts [user, model, user] shape with merged functionResponse + text parts. |
Test uses the exact scenario from the review: user(Read) → model(read_file) → user(functionResponse + text). Verifies 3 entries with merged parts in the last user entry.
Verdict
Approve. The only correctness issue from v1 is properly fixed and tested. The rest of the code (SSE parsing, tool call mapping, usage with thinking tokens, error handling) is unchanged and solid from v1 review.
Remaining non-blocking follow-ups from v1 (unchanged):
AbortSignal/timeout (same pattern as all other providers, fine for M1)
toolNamesById fallback using ID as function name (only triggers on persisted conversations without full history)
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Blockers
None found.
Non-Blocking
None.
Looks Good
- Gemini dispatch now routes through the official
https://generativelanguage.googleapis.com base URL with x-goog-api-key, requires an API key, and rejects unknown official Google models instead of silently dispatching custom strings.
- Message/tool mapping looks correct after the fix: tool responses and follow-up user text stay in the same Gemini user turn, function calls preserve names/ids/JSON object args, and usage includes thinking tokens.
- PR-branch validation passed:
bun run typecheck, bun test ./tests --timeout 15000 with 133 pass / 0 fail / 481 expect calls, bun run build, bun run smoke:build, and git diff --check.
- Latest-main test merge also passed after [codex] add m1 headless exec surface #17 landed: 141 pass / 0 fail / 514 expect calls, plus typecheck/build/smoke.
Verdict: Approve — Clean Gemini provider slice; the prior message-mapping blocker is fixed and runtime dispatch fails closed where it should.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Approve — validated in isolated branch and latest-main merge-check worktrees.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Reviewers
anandh8x
anandh8x approved these changes
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
Milestone
No milestone
Development
Successfully merging this pull request may close these issues.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
|