gemini

package
v0.186.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package gemini talks to Google's Gemini API on a key the user supplies through the environment.

Caprock never stores that key. It is read from GEMINI_API_KEY at the moment of the call, never written to config.json, never accepted by PUT /v1/settings and never returned by GET /v1/settings — see ADR-023. The objection this answers is recorded in .ai/17-teams.md: a bug in a tool that holds no credential cannot leak one.

This is the second outbound call in the product, after the release check, and the first that carries user content. Nothing here runs on a timer or in the background: a request leaves only when a person asked a question in that turn.

Index

Constants

View Source
const Agent = "gemini"

Agent is the value the sessions table carries for Gemini work, alongside "claude" and "opencode".

View Source
const DefaultModel = "gemini-3.5-flash-lite"

DefaultModel is what a request without a model uses: the cheapest current Flash tier, because the common use is a question about the user's own sessions rather than deep reasoning, and it is their money.

View Source
const Endpoint = "https://generativelanguage.googleapis.com/v1beta"

Endpoint is the only host this package ever contacts.

View Source
const EnvKey = "GEMINI_API_KEY"

EnvKey is the variable the key is read from. The name matches what Google's own tooling uses, so a machine already set up for Gemini needs no new setup.

View Source
const MaxBody = 8 << 20

MaxBody bounds what is read back. A runaway response must not become a runaway allocation in a daemon that is meant to sit quietly.

Variables

View Source
var ErrNoKey = errors.New("no " + EnvKey + " in the environment")

ErrNoKey means the environment holds no key, which is also how the feature stays off: with nothing set there is no default-on path to disable.

Functions

func Available

func Available(stored string) bool

Available reports whether a key is present at all.

func EnvKeyValue added in v0.43.0

func EnvKeyValue() string

EnvKeyValue returns the key from the environment, trimmed.

The environment still wins over the stored one: a machine already set up that way keeps working untouched, and a CI runner can inject a key without writing a file (ADR-025).

func Key

func Key(stored string) string

Key resolves the key to use: the environment first, then whatever the user entered in the dashboard. Empty means absent — callers must treat that as "the feature is not set up here", not as an error to report.

Types

type Client

type Client struct {
	// Stored is the key the user entered in the dashboard, used when the
	// environment does not carry one.
	Stored string
	HTTP   *http.Client
	// Base overrides the endpoint in tests. Empty means Endpoint.
	Base string
	// Now is injectable so timings are deterministic under test.
	Now func() time.Time
}

Client calls the API. The zero value is usable.

func (*Client) Ask

func (c *Client) Ask(ctx context.Context, model, system, prompt string) (*Reply, error)

Ask sends one prompt and returns the answer. system may be empty.

func (*Client) Check

func (c *Client) Check(ctx context.Context) ([]string, error)

Check verifies the key by listing models. It is the cheapest call that proves the key works, and it sends no user content.

type Ingester added in v0.44.4

type Ingester struct {
	// contains filtered or unexported fields
}

Ingester turns Gemini's telemetry files into Caprock events.

It tails rather than polls-and-rereads: each file belongs to one session, grows only at the end, and is never rewritten — so remembering a byte offset per file is both correct and the difference between reading a few hundred bytes a tick and re-parsing megabytes.

Every write is idempotent anyway. Events carry a key derived from the session, the event kind and its timestamp, and `(session_id, key)` is unique in the store, so a re-read after a restart is a no-op rather than a session whose cost has doubled.

func NewIngester added in v0.44.4

func NewIngester(dir string, rec *rollup.Recorder, log *slog.Logger) *Ingester

NewIngester builds one. dir is where spawned sessions write their telemetry.

func (*Ingester) Forget added in v0.44.4

func (g *Ingester) Forget(sessionID string)

Forget drops the offset for a finished session's file, so a restart does not hold state for sessions that will never grow again.

func (*Ingester) Kick added in v0.117.2

func (g *Ingester) Kick()

Kick asks for a sweep now instead of at the next tick: input was just typed into a Gemini session Caprock holds. Never blocks.

func (*Ingester) Run added in v0.44.4

func (g *Ingester) Run(ctx context.Context)

Run tails every telemetry file until the context ends.

func (*Ingester) Sweep added in v0.44.4

func (g *Ingester) Sweep(ctx context.Context) (int, error)

Sweep reads whatever is new in every file and records it. Returns how many events were stored.

func (*Ingester) Track added in v0.44.4

func (g *Ingester) Track(sessionID, cwd string)

Track records where a session runs, so its events land in the right project.

type Reply

type Reply struct {
	Text    string        `json:"text"`
	Model   string        `json:"model"`
	Usage   Usage         `json:"usage"`
	Elapsed time.Duration `json:"-"`
}

Reply is one answer plus what it cost.

type TelemetryEvent added in v0.44.4

type TelemetryEvent struct {
	Kind      event.Kind
	SessionID string
	TS        time.Time
	// Model is set on api_response and config.
	Model string
	// Tokens, all zero unless this is an api_response.
	TokensIn   int
	TokensOut  int
	CacheRead  int
	Thoughts   int
	ToolTokens int
	// Tool is set on tool_call.
	Tool    string
	Success bool
	// DurationMS is how long the call took, 0 when not applicable.
	DurationMS int
	// Text is the user's prompt on user_prompt. Kept out of every other event
	// so a caller that does not want prose never accidentally holds any.
	Text string
	// Raw is the attributes map, stored as the event payload so a field this
	// parser does not yet read is still there to be read later.
	Raw map[string]any
	// Offset is where this record began, in bytes from the start of the file.
	// Stable across re-reads, which is what makes it usable in a dedupe key —
	// unlike a position within one sweep's batch, which moves when the sweep
	// starts from a different place.
	Offset int64
}

TelemetryEvent is one decoded log record, in Caprock's own terms.

func ParseTelemetry added in v0.44.4

func ParseTelemetry(r io.Reader) ([]TelemetryEvent, error)

ParseTelemetry decodes a telemetry stream into events, in file order.

A record that cannot be decoded is skipped rather than failing the read: this file is written by another program while Caprock is reading it, so a torn final record is the normal case and not an error worth propagating.

func ParseTelemetryAt added in v0.49.1

func ParseTelemetryAt(r io.Reader) ([]TelemetryEvent, int64, error)

ParseTelemetryAt is ParseTelemetry, and also reports how many bytes were consumed by whole records.

The caller tails a file Gemini is still writing, so the tail is routinely a half-written record. Advancing past it loses it: when the writer finishes, those bytes are below the stored offset and nothing reads them again. The count returned here is the offset just after the last balanced `}` at depth zero — everything after it is an incomplete record and will be re-read, which costs nothing because the store deduplicates.

type Usage

type Usage struct {
	PromptTokens   int64 `json:"prompt_tokens"`
	OutputTokens   int64 `json:"output_tokens"`
	CachedTokens   int64 `json:"cached_tokens"`
	ThoughtsTokens int64 `json:"thoughts_tokens"`
	TotalTokens    int64 `json:"total_tokens"`
}

Usage is what the response says it cost, in tokens. These are the figures Caprock prices; there is no per-key billing API to reconcile them against (Google reports per project), so the total is what Caprock sent rather than what Google billed, and the UI says so.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL