1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package main

// live.go is a minimal Gemini Live (BidiGenerateContent) WebSocket client for
// the Developer API (generativelanguage.googleapis.com), speaking the raw wire
// protocol directly (no SDK). Message shapes were derived from the python-genai
// SDK's _live_converters.py; the wire format is camelCase.
//
// Endpoint:
//   wss://generativelanguage.googleapis.com/ws/
//     google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent
// Auth: x-goog-api-key handshake header.
//
// Flow: dial -> send {"setup":{...}} -> recv {"setupComplete":{}} -> then a
// full-duplex exchange of realtimeInput/toolResponse (client->server) and
// serverContent/toolCall (server->client).

import (
	"context"
	"crypto/tls"
	"encoding/json"
	"flag"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"strings"
	"sync"
	"time"

	"golang.org/x/net/websocket"
)

const (
	// pass entry holding a Gemini API key (same location hans uses).
	geminiPassPath = "internet/ai.google.dev/gemini/api-keys/gemini-2.5-flash"
)

// audioInMIME / audioOutMIME are derived from the active model's sample rates.
var (
	audioInMIME  = fmt.Sprintf("audio/pcm;rate=%d", activeModel.AudioInSampleRate)
	audioOutMIME = fmt.Sprintf("audio/pcm;rate=%d", activeModel.AudioOutSampleRate)
)

// liveDebug reports whether to dump Live API wire traffic to stderr.
func liveDebug() bool { return os.Getenv("INVENTORY_LIVE_DEBUG") != "" }

// dbg logs a timestamped debug line to stderr when INVENTORY_LIVE_DEBUG is set.
func dbg(format string, args ...any) {
	if !liveDebug() {
		return
	}
	fmt.Fprintf(os.Stderr, "[dbg %s] "+format+"\n",
		append([]any{time.Now().Format("15:04:05.000")}, args...)...)
}

// geminiAPIKey returns the API key, in order of preference:
//   - GEMINI_API_KEY (env), for quick local use;
//   - GEMINI_API_KEY_FILE (env): a path to read the key from (first line). This
//     is how the systemd deployment feeds it a credential — the service sets
//     GEMINI_API_KEY_FILE=$CREDENTIALS_DIRECTORY/gemini-key (LoadCredential), so
//     the key never enters the environment or the nix store;
//   - `pass` (like hans), for the interactive workstation with a GPG keyring.
func geminiAPIKey() (string, error) {
	if key := os.Getenv("GEMINI_API_KEY"); key != "" {
		return key, nil
	}
	if path := os.Getenv("GEMINI_API_KEY_FILE"); path != "" {
		b, err := os.ReadFile(path)
		if err != nil {
			return "", fmt.Errorf("read GEMINI_API_KEY_FILE %q: %w", path, err)
		}
		key := strings.SplitN(strings.TrimSpace(string(b)), "\n", 2)[0]
		if key == "" {
			return "", fmt.Errorf("GEMINI_API_KEY_FILE %q is empty", path)
		}
		return key, nil
	}
	out, err := exec.Command("pass", geminiPassPath).Output()
	if err != nil {
		return "", fmt.Errorf("GEMINI_API_KEY / GEMINI_API_KEY_FILE not set and pass failed: %w", err)
	}
	key := strings.SplitN(strings.TrimSpace(string(out)), "\n", 2)[0]
	if key == "" {
		return "", fmt.Errorf("empty API key")
	}
	return key, nil
}

// ---- wire types (client -> server) ----

type blob struct {
	Data     string `json:"data"` // base64
	MimeType string `json:"mimeType"`
}

type setupMsg struct {
	Setup setup `json:"setup"`
}

type setup struct {
	Model                    string               `json:"model"`
	GenerationConfig         generationConfig     `json:"generationConfig"`
	SystemInstruction        *content             `json:"systemInstruction,omitempty"`
	Tools                    []geminiTool         `json:"tools,omitempty"`
	InputAudioTranscription  *struct{}            `json:"inputAudioTranscription,omitempty"`
	OutputAudioTranscription *struct{}            `json:"outputAudioTranscription,omitempty"`
	RealtimeInputConfig      *realtimeInputConfig `json:"realtimeInputConfig,omitempty"`
}

type generationConfig struct {
	ResponseModalities []string `json:"responseModalities,omitempty"`
}

// realtimeInputConfig controls how Gemini segments realtime audio into turns. We
// disable its automatic VAD and drive turn boundaries ourselves via
// activityStart/activityEnd (see the silence gate), so the two VADs don't stack.
type realtimeInputConfig struct {
	AutomaticActivityDetection automaticActivityDetection `json:"automaticActivityDetection"`
}

type automaticActivityDetection struct {
	Disabled bool `json:"disabled"`
}

type content struct {
	Role  string `json:"role,omitempty"`
	Parts []part `json:"parts"`
}

type part struct {
	Text       string `json:"text,omitempty"`
	InlineData *blob  `json:"inlineData,omitempty"`
}

type geminiTool struct {
	FunctionDeclarations []functionDeclaration `json:"functionDeclarations"`
}

type functionDeclaration struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Parameters  map[string]any `json:"parameters,omitempty"`
}

// realtimeInputMsg carries exactly one of audio/video/text/activity per message.
type realtimeInputMsg struct {
	RealtimeInput realtimeInput `json:"realtimeInput"`
}

type realtimeInput struct {
	Audio         *blob     `json:"audio,omitempty"`
	Video         *blob     `json:"video,omitempty"`
	Text          string    `json:"text,omitempty"`
	ActivityStart *struct{} `json:"activityStart,omitempty"`
	ActivityEnd   *struct{} `json:"activityEnd,omitempty"`
}

// clientContentMsg carries turn-based content that is appended to the model's
// context IN ORDER (unlike realtimeInput, which is optimized for responsiveness
// at the expense of ordering). We use it for the captured photo so its id
// persists in history rather than being overwritten by the next camera frame.
type clientContentMsg struct {
	ClientContent clientContent `json:"clientContent"`
}

type clientContent struct {
	Turns        []content `json:"turns"`
	TurnComplete bool      `json:"turnComplete"`
}

type toolResponseMsg struct {
	ToolResponse toolResponse `json:"toolResponse"`
}

type toolResponse struct {
	FunctionResponses []functionResponse `json:"functionResponses"`
}

type functionResponse struct {
	ID       string         `json:"id,omitempty"`
	Name     string         `json:"name"`
	Response map[string]any `json:"response"`
}

// ---- wire types (server -> client) ----

// serverMessage is the union of message kinds the server can send. Each arrives
// as a separate WS text frame; only one field is populated (usageMetadata may
// accompany serverContent).
type serverMessage struct {
	SetupComplete *json.RawMessage `json:"setupComplete,omitempty"`
	ServerContent *serverContent   `json:"serverContent,omitempty"`
	ToolCall      *serverToolCall  `json:"toolCall,omitempty"`
	GoAway        *json.RawMessage `json:"goAway,omitempty"`
	UsageMetadata *usageMetadata   `json:"usageMetadata,omitempty"`
}

// usageMetadata is the authoritative token accounting from Gemini. The
// per-modality detail lists let us attribute tokens to audio vs image vs text.
// We capture every token kind the API reports (not just prompt/response) so
// cost accounting doesn't silently drop billable tokens: thoughts (billed at
// the output rate — "output price includes thinking tokens"), tool-use prompt
// tokens (tool results fed back as input, billed as input), and cached content
// tokens.
type usageMetadata struct {
	PromptTokenCount           int                  `json:"promptTokenCount,omitempty"`
	ResponseTokenCount         int                  `json:"responseTokenCount,omitempty"`
	CandidatesTokenCount       int                  `json:"candidatesTokenCount,omitempty"`
	TotalTokenCount            int                  `json:"totalTokenCount,omitempty"`
	ThoughtsTokenCount         int                  `json:"thoughtsTokenCount,omitempty"`
	ToolUsePromptTokenCount    int                  `json:"toolUsePromptTokenCount,omitempty"`
	CachedContentTokenCount    int                  `json:"cachedContentTokenCount,omitempty"`
	PromptTokensDetails        []modalityTokenCount `json:"promptTokensDetails,omitempty"`
	ResponseTokensDetails      []modalityTokenCount `json:"responseTokensDetails,omitempty"`
	ToolUsePromptTokensDetails []modalityTokenCount `json:"toolUsePromptTokensDetails,omitempty"`
	CacheTokensDetails         []modalityTokenCount `json:"cacheTokensDetails,omitempty"`
}

// modalityTokenCount is one {modality, tokenCount} breakdown entry. Modality is
// e.g. "AUDIO", "VIDEO", "IMAGE", "TEXT".
type modalityTokenCount struct {
	Modality   string `json:"modality,omitempty"`
	TokenCount int    `json:"tokenCount,omitempty"`
}

type serverContent struct {
	ModelTurn           *content       `json:"modelTurn,omitempty"`
	TurnComplete        bool           `json:"turnComplete,omitempty"`
	Interrupted         bool           `json:"interrupted,omitempty"`
	GenerationComplete  bool           `json:"generationComplete,omitempty"`
	InputTranscription  *transcription `json:"inputTranscription,omitempty"`
	OutputTranscription *transcription `json:"outputTranscription,omitempty"`
}

type transcription struct {
	Text string `json:"text,omitempty"`
}

type serverToolCall struct {
	FunctionCalls []functionCall `json:"functionCalls"`
}

type functionCall struct {
	ID   string         `json:"id,omitempty"`
	Name string         `json:"name"`
	Args map[string]any `json:"args"`
}

// ---- connection ----

// liveConn wraps a Live API websocket connection. Sends are serialized by a
// mutex so multiple goroutines (audio pump, video pump, tool responder) can
// share one connection safely.
type liveConn struct {
	ws     *websocket.Conn
	sendMu sync.Mutex
}

// dialLive opens a Live session, performs the setup handshake and waits for
// setupComplete. systemInstruction and tools are optional.
func dialLive(ctx context.Context, apiKey, model, systemInstruction string, tools []geminiTool) (*liveConn, error) {
	host := activeModel.WSHost
	u := url.URL{Scheme: "wss", Host: host, Path: activeModel.WSPath}
	cfg, err := websocket.NewConfig(u.String(), "https://"+host)
	if err != nil {
		return nil, fmt.Errorf("ws config: %w", err)
	}
	cfg.Header = http.Header{}
	cfg.Header.Set("x-goog-api-key", apiKey)
	cfg.TlsConfig = &tls.Config{ServerName: host}

	ws, err := cfg.DialContext(ctx)
	if err != nil {
		return nil, fmt.Errorf("ws dial: %w", err)
	}

	// developer API requires the models/ prefix.
	m := model
	if !strings.HasPrefix(m, "models/") && !strings.HasPrefix(m, "tunedModels/") {
		m = "models/" + m
	}
	su := setupMsg{Setup: setup{
		Model:                    m,
		GenerationConfig:         generationConfig{ResponseModalities: []string{"AUDIO"}},
		InputAudioTranscription:  &struct{}{},
		OutputAudioTranscription: &struct{}{},
		Tools:                    tools,
		// Disable Gemini's automatic VAD; our server-side silence gate detects
		// speech start/end and emits activityStart/activityEnd explicitly. To
		// fall back to Gemini auto-VAD, set Disabled:false (or drop this field).
		RealtimeInputConfig: &realtimeInputConfig{
			AutomaticActivityDetection: automaticActivityDetection{Disabled: true},
		},
	}}
	if systemInstruction != "" {
		su.Setup.SystemInstruction = &content{Parts: []part{{Text: systemInstruction}}}
	}
	if liveDebug() {
		if b, e := json.Marshal(su); e == nil {
			fmt.Fprintf(os.Stderr, "[live] setup payload: %s\n", b)
		}
	}
	if err := websocket.JSON.Send(ws, su); err != nil {
		ws.Close()
		return nil, fmt.Errorf("send setup: %w", err)
	}

	// Await setupComplete.
	var raw []byte
	if err := websocket.Message.Receive(ws, &raw); err != nil {
		ws.Close()
		return nil, fmt.Errorf("recv setup response: %w (the server closed the "+
			"connection after our setup message; usually a bad API key or an "+
			"invalid setup/model)", err)
	}
	if liveDebug() {
		fmt.Fprintf(os.Stderr, "[live] first server frame: %s\n", raw)
	}
	var first serverMessage
	if err := json.Unmarshal(raw, &first); err != nil {
		ws.Close()
		return nil, fmt.Errorf("decode setup response: %w (raw: %s)", err, raw)
	}
	if first.SetupComplete == nil {
		ws.Close()
		return nil, fmt.Errorf("expected setupComplete, got: %s", raw)
	}
	return &liveConn{ws: ws}, nil
}

func (c *liveConn) sendJSON(v any) error {
	c.sendMu.Lock()
	defer c.sendMu.Unlock()
	return websocket.JSON.Send(c.ws, v)
}

// sendAudio sends a PCM16 16kHz chunk (base64) as realtime audio input.
func (c *liveConn) sendAudio(b64 string) error {
	return c.sendJSON(realtimeInputMsg{RealtimeInput: realtimeInput{
		Audio: &blob{Data: b64, MimeType: audioInMIME},
	}})
}

// sendVideoFrame sends a JPEG frame (base64) as realtime video input.
func (c *liveConn) sendVideoFrame(b64 string) error {
	return c.sendJSON(realtimeInputMsg{RealtimeInput: realtimeInput{
		Video: &blob{Data: b64, MimeType: "image/jpeg"},
	}})
}

// sendText sends a realtime text input.
func (c *liveConn) sendText(text string) error {
	return c.sendJSON(realtimeInputMsg{RealtimeInput: realtimeInput{Text: text}})
}

// sendActivityStart marks the start of a user speech turn (manual VAD). Must be
// sent BEFORE the audio buffers of that utterance.
func (c *liveConn) sendActivityStart() error {
	return c.sendJSON(realtimeInputMsg{RealtimeInput: realtimeInput{ActivityStart: &struct{}{}}})
}

// sendActivityEnd marks the end of a user speech turn (manual VAD). Must be sent
// AFTER the last audio buffer of that utterance; it lets the model begin its
// reply. With manual VAD there is no server silence tolerance, so the caller
// should only end after a sensible hangover (see the silence gate).
func (c *liveConn) sendActivityEnd() error {
	return c.sendJSON(realtimeInputMsg{RealtimeInput: realtimeInput{ActivityEnd: &struct{}{}}})
}

// sendClientContent appends a turn to the model context in order. Used for the
// captured photo so its id persists in history. turnComplete=false adds the
// content without forcing the model to generate a reply.
func (c *liveConn) sendClientContent(parts []part, turnComplete bool) error {
	return c.sendJSON(clientContentMsg{ClientContent: clientContent{
		Turns:        []content{{Role: "user", Parts: parts}},
		TurnComplete: turnComplete,
	}})
}

// sendToolResponses replies to a toolCall with function results.
func (c *liveConn) sendToolResponses(resps []functionResponse) error {
	return c.sendJSON(toolResponseMsg{ToolResponse: toolResponse{FunctionResponses: resps}})
}

// liveReadIdleTimeout bounds how long receive() will block waiting for the next
// frame. A healthy Live session streams frames continuously, so a gap this long
// means the connection is silently dead (no FIN/goAway); the read deadline turns
// that into an error rather than an indefinite block. Cancellation of the owning
// context can't unblock a raw x/net/websocket read, so this deadline is our only
// backstop against a wedged reader (see session.go teardown).
const liveReadIdleTimeout = 30 * time.Second

// receive reads and decodes the next server message. Blocks until a frame
// arrives, the connection closes, or liveReadIdleTimeout elapses with no frame.
func (c *liveConn) receive() (*serverMessage, []byte, error) {
	_ = c.ws.SetReadDeadline(time.Now().Add(liveReadIdleTimeout))
	var raw []byte
	if err := websocket.Message.Receive(c.ws, &raw); err != nil {
		return nil, nil, err
	}
	var msg serverMessage
	if err := json.Unmarshal(raw, &msg); err != nil {
		return nil, raw, fmt.Errorf("decode server message: %w", err)
	}
	return &msg, raw, nil
}

func (c *liveConn) close() error {
	dbg("live: close() called on Gemini connection")
	return c.ws.Close()
}

// cmdLiveTest is a diagnostic: connect to Gemini Live, run the setup handshake,
// send one text turn ("say hello") and print server responses until turn
// complete. Enables INVENTORY_LIVE_DEBUG so the raw setup + first frame are
// dumped. Use this to isolate Live API issues from the browser/proxy plumbing.
//
//	inventory live-test [--model NAME] [--text "..."]
func cmdLiveTest(args []string) {
	fs := flag.NewFlagSet("live-test", flag.ExitOnError)
	model := fs.String("model", defaultModel, "Gemini Live model")
	text := fs.String("text", "Say hello in one short sentence.", "text turn to send")
	fs.Parse(args)

	os.Setenv("INVENTORY_LIVE_DEBUG", "1")

	key, err := geminiAPIKey()
	if err != nil {
		fmt.Fprintf(os.Stderr, "api key: %v\n", err)
		os.Exit(1)
	}
	fmt.Fprintf(os.Stderr, "[live-test] got API key (len %d), connecting model %q…\n", len(key), *model)

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	live, err := dialLive(ctx, key, *model, "You are a terse test assistant.", nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "dialLive: %v\n", err)
		os.Exit(1)
	}
	defer live.close()
	fmt.Fprintln(os.Stderr, "[live-test] setupComplete OK ✓")

	if err := live.sendText(*text); err != nil {
		fmt.Fprintf(os.Stderr, "sendText: %v\n", err)
		os.Exit(1)
	}
	fmt.Fprintf(os.Stderr, "[live-test] sent text: %q\n", *text)

	audioBytes := 0
	for {
		msg, raw, err := live.receive()
		if err != nil {
			fmt.Fprintf(os.Stderr, "[live-test] receive ended: %v\n", err)
			break
		}
		if liveDebug() && len(raw) < 400 {
			fmt.Fprintf(os.Stderr, "[live-test] frame: %s\n", raw)
		}
		if sc := msg.ServerContent; sc != nil {
			if sc.OutputTranscription != nil && sc.OutputTranscription.Text != "" {
				fmt.Fprintf(os.Stderr, "[live-test] model transcript: %s\n", sc.OutputTranscription.Text)
			}
			if sc.ModelTurn != nil {
				for _, p := range sc.ModelTurn.Parts {
					if p.InlineData != nil {
						audioBytes += len(p.InlineData.Data)
					}
					if p.Text != "" {
						fmt.Fprintf(os.Stderr, "[live-test] model text: %s\n", p.Text)
					}
				}
			}
			if sc.TurnComplete {
				fmt.Fprintf(os.Stderr, "[live-test] turn complete ✓ (received %d b64 audio bytes)\n", audioBytes)
				break
			}
		}
	}
}