Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ Pass options with the object form of the plugin entry. Every option is optional.
| `voiceModel` | `"openai/gpt-6.1-sol"` | Model for the background agent that thinks for GPT-Live, as `provider/model`. |
| `voiceVariant` | `"medium"` | Thinking level for that model. |
| `log` | `true` | Keep a local log of each call (see [Privacy](#privacy)). |
| `visual` | automatic | Force the aura's drawing method: `kitty`, `herdr` or `blocks`. |
| `visual` | automatic | Force the aura's drawing method: `kitty`, `herdr` or `blocks`, or `none` to turn the aura off. |
| `fps` | `30` | Highest frame rate for the aura, panel and call strip. Lower it (for example `10`) to reduce terminal load. |

### Custom prompts

Expand Down
10 changes: 9 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ flowchart LR
| `src/server/context.ts` | Conversation history quoted as data, and agent text made speakable. |
| `src/server/auth.ts` | Reads OpenCode's ChatGPT OAuth sign-in. |
| `src/server/log.ts` | The per-call JSONL log. |
| `src/server/options.ts` | Picks the terminal plugin's options out of the `opencode.json` entry for the `options` RPC. |
| `src/tui/index.ts` | Terminal plugin: commands, keys, slots, starting calls. |
| `src/tui/controller.ts` | Call state machine in the terminal, helper lifecycle, RPC events, heartbeats. |
| `src/tui/helper.ts` | Finds, downloads (with checksum verification) and drives the native helper. |
Expand Down Expand Up @@ -142,8 +143,12 @@ constraints drive this:
- **No JSX.** For the same reason the UI does not use Solid; views are plain objects with `update(now)`,
`animating(now)` and optional `interval()`, `suspend()` and `dispose()`.

OpenCode passes the plugin's `opencode.json` options only to the server part. At setup the terminal part asks for them
with the `options` RPC (3 s timeout) and lays its own options on top, so `voice`, `panel`, `duck`, `visual`, `fps` and
`keybinds` work from `opencode.json`. Without an answer it runs on its own options and defaults.

The frame clock runs only while something animates, at the fastest interval any animating view asks for (33 ms for
the aura).
the aura), but never faster than the `fps` option allows.

### The aura

Expand All @@ -160,6 +165,9 @@ spinning the other way in violet. The level driving it is smoothed with a 40 ms
| `kitty` | The renderer reports kitty graphics | Kitty graphics commands over an empty slot, 30 fps (see below) |
| `blocks` | Everywhere else | Half-block characters, rendered at 3× and averaged down |

The `visual` option (or `GPT_LIVE_VISUAL`) forces a surface. `none` turns the aura off: the panel has no aura and the
sidebar aura slot is not registered.

The kitty surface (`src/tui/kitty.ts`) does not use OpenTUI's `ImageRenderable`, which clears the cells under an image
to the terminal's default background: with a translucent terminal, every late frame flashed a see-through square. It
reserves the cells with an empty box instead, so they keep the panel's background, and writes the kitty commands
Expand Down
2 changes: 1 addition & 1 deletion docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ Environment variables for testing. They are not user settings.
| `GPT_LIVE_OUTPUT` | `none` discards GPT-Live's audio; a path writes it to a WAV file. |
| `GPT_LIVE_AUTOSTART` | Start a call as soon as a session is open. |
| `GPT_LIVE_DEBUG` | Path to a JSONL file for UI diagnostics: which aura surface was picked, terminal capabilities, errors. |
| `GPT_LIVE_VISUAL` | Force the aura surface: `kitty`, `herdr` or `blocks`. |
| `GPT_LIVE_VISUAL` | Force the aura surface: `kitty`, `herdr`, `blocks` or `none`. |
| `GPT_LIVE_HOST` | Path to a `gpt-live-host` binary to use instead of the usual lookup. |

A hands-free test run: a recorded question as the microphone, no speaker, the call starting on its own:
Expand Down
3 changes: 3 additions & 0 deletions src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Bridge } from "./bridge"
import { background, historyFrom, type HistoryEntry } from "./context"
import { LiveError, MODEL, Sideband, createCall, requestIDs } from "./live"
import { CallLog } from "./log"
import { terminalOptions } from "./options"
import { loadPrompt } from "./prompt"

interface Options {
Expand Down Expand Up @@ -213,6 +214,8 @@ export default Plugin.define({
await ctx.session.hook("compaction", (event) => shapeRequest(event as never))

const registration = await ctx.rpc.register(GptLive, {
options: async () => terminalOptions(ctx.options as Record<string, unknown>),

status: async () => {
const auth = await resolveAuth(ctx)
return defined({
Expand Down
28 changes: 28 additions & 0 deletions src/server/options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const isString = (value: unknown): value is string => typeof value === "string"
const isKey = (value: unknown) => value === false || isString(value) || (Array.isArray(value) && value.every(isString))

/**
* The options the terminal plugin uses. Only well-typed values are kept, so the RPC reply
* always passes its schema and one bad value cannot hide the others.
*/
export function terminalOptions(raw: Record<string, unknown>) {
const result: {
voice?: string
panel?: boolean
duck?: boolean
visual?: string
fps?: number
keybinds?: Record<string, string | string[] | false>
} = {}
if (isString(raw.voice)) result.voice = raw.voice
if (typeof raw.panel === "boolean") result.panel = raw.panel
if (typeof raw.duck === "boolean") result.duck = raw.duck
if (isString(raw.visual)) result.visual = raw.visual
if (typeof raw.fps === "number" && Number.isFinite(raw.fps)) result.fps = raw.fps
if (raw.keybinds && typeof raw.keybinds === "object" && !Array.isArray(raw.keybinds))
result.keybinds = Object.fromEntries(Object.entries(raw.keybinds).filter(([, value]) => isKey(value))) as Record<
string,
string | string[] | false
>
return result
}
15 changes: 15 additions & 0 deletions src/shared/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,21 @@ export const GptLive = define({
voiceSessionID: z.string().optional(),
}),
},
/**
* The terminal plugin's options. OpenCode passes `opencode.json` plugin options only to the
* server part, so the terminal part reads its settings from here.
*/
options: {
input: z.object({}),
output: z.object({
voice: z.string().optional(),
panel: z.boolean().optional(),
duck: z.boolean().optional(),
visual: z.string().optional(),
fps: z.number().optional(),
keybinds: z.record(z.string(), z.union([z.string(), z.array(z.string()), z.literal(false)])).optional(),
}),
},
/** Heartbeat from the window that owns the call; calls whose window goes quiet are ended. */
alive: {
input: z.object({ callID: z.string() }),
Expand Down
51 changes: 42 additions & 9 deletions src/tui/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { Plugin as PluginNamespace } from "@opencode/plugin/tui"

import { VOICES, type Voice } from "../shared/rpc"
import { GptLive, VOICES, type Voice } from "../shared/rpc"
import { VoiceController, describeError } from "./controller"
import { callModel, type CallModel } from "./model"
import { auraEnabled, configureVisual, debug } from "./surface"
import { Frames, footerBadge, transcriptPanel, useCore, voiceAura, voiceStrip, type Core, type View } from "./ui"

const PANEL = "gptlive.transcript"
Expand Down Expand Up @@ -47,26 +48,54 @@ export function resolveKey(value: unknown, fallback: KeyOption): false | string
return typeof chosen === "string" ? chosen : resolveKey(undefined, fallback)
}

/**
* Options from the plugin's `opencode.json` entry. OpenCode hands those only to the server part,
* so ask it; without an answer the terminal part runs on `cli.json` options and defaults.
*/
async function serverOptions(context: Context): Promise<Record<string, unknown>> {
const location = context.location ?? context.data.location.default()
let timer: ReturnType<typeof setTimeout> | undefined
const timeout = new Promise<undefined>((resolve) => {
timer = setTimeout(() => resolve(undefined), 3000)
})
try {
const reply = await Promise.race([context.client.rpc(GptLive).options({}, { location }), timeout])
return reply ?? {}
} catch (error) {
debug({ event: "options-error", error: String(error) })
return {}
} finally {
clearTimeout(timer)
}
}

/** Builds the terminal plugin; `core` must be imported by the entry file (see tui.ts). */
export function createTuiPlugin(module: Core): PluginNamespace.Definition {
useCore(module)
return {
id: "opencode-gpt-live.tui",
setup(context: Context) {
const options = context.options as {
async setup(context: Context) {
const options = {
...(await serverOptions(context)),
...(context.options as Record<string, unknown>),
} as {
voice?: string
panel?: boolean
duck?: boolean
visual?: string
fps?: number
keybinds?: Partial<Record<KeyAction, KeyOption>>
}
configureVisual(options.visual)
const key = (action: KeyAction) => resolveKey(options.keybinds?.[action], DEFAULT_KEYS[action])
const voice = new VoiceController(context, {
voice: VOICES.includes(options.voice as Voice) ? (options.voice as Voice) : undefined,
// Other apps' audio is turned down during calls and restored afterwards.
duck: options.duck !== false,
})
const frames = new Frames(voice)
const frames = new Frames(voice, options.fps)
const autoPanel = options.panel !== false
debug({ event: "setup", root: import.meta.dir, options, aura: auraEnabled() })
let preparing: number | undefined
let generation = 0
let disposed = false
Expand Down Expand Up @@ -276,11 +305,15 @@ export function createTuiPlugin(module: Core): PluginNamespace.Definition {
return frames.mount(gated)
},
}),
context.ui.slot({
prepend: "sidebar.content",
render: (input) =>
frames.mount(voiceAura(context, voice, () => voice.owns(input.sessionID), "gptlive-aura-sidebar")),
}),
...(auraEnabled()
? [
context.ui.slot({
prepend: "sidebar.content",
render: (input) =>
frames.mount(voiceAura(context, voice, () => voice.owns(input.sessionID), "gptlive-aura-sidebar")),
}),
]
: []),
context.ui.slot({
append: "prompt.footer.status",
render: () => frames.mount(footerBadge(context, voice)),
Expand Down
21 changes: 19 additions & 2 deletions src/tui/surface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import type { Plugin } from "@opencode/plugin/tui"
* - herdr: frames streamed through herdr's pane graphics API (herdr does not display kitty
* images printed by programs)
* - blocks: half-block characters with true color, for every other terminal
* The choice is automatic; GPT_LIVE_VISUAL or the `visual` option can force one.
* The choice is automatic; GPT_LIVE_VISUAL or the `visual` option can force one, or turn the
* aura off with "none".
*/
import type { RGBA, Renderable, TextRenderable } from "@opentui/core"

Expand Down Expand Up @@ -43,9 +44,25 @@ export function debug(entry: Record<string, unknown>) {
}
}

/** The `visual` option; set once the plugin's options are known. */
let configuredVisual: string | undefined

export function configureVisual(visual: string | undefined) {
configuredVisual = visual
}

function forcedVisual() {
return configuredVisual ?? process.env.GPT_LIVE_VISUAL
}

/** False when the `visual` option (or GPT_LIVE_VISUAL) is "none": no aura is drawn anywhere. */
export function auraEnabled() {
return forcedVisual() !== "none"
}

export function pickSurface(context: Context, layer: string, rows: number): Surface {
const renderer = context.renderer
const forced = (context.options as { visual?: string }).visual ?? process.env.GPT_LIVE_VISUAL
const forced = forcedVisual()
// A multiplexer nested inside herdr inherits herdr's environment, but herdr's pane
// coordinates no longer match what is on screen.
const nested = !!(process.env.TMUX || process.env.STY || process.env.ZELLIJ)
Expand Down
28 changes: 18 additions & 10 deletions src/tui/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { RGBA, Renderable, TextRenderable } from "@opentui/core"
import { AuraCanvas, type AuraPalette, type Rgb } from "./aura"
import type { Entry, VoiceController } from "./controller"
import { type Core, useCore as provideCore } from "./core"
import { debug, fallbackSurface, pickSurface, type Surface } from "./surface"
import { auraEnabled, debug, fallbackSurface, pickSurface, type Surface } from "./surface"
import { duration, flap, pulse, shimmer, spinner } from "./visuals"

type Context = Plugin.Context
Expand Down Expand Up @@ -423,8 +423,8 @@ export function transcriptPanel(context: Context, voice: VoiceController, visibl
stickyStart: "bottom",
marginTop: 1,
})
const aura = voiceAura(context, voice, visible, "gptlive-aura-panel")
root.add(aura.root)
const aura = auraEnabled() ? voiceAura(context, voice, visible, "gptlive-aura-panel") : undefined
if (aura) root.add(aura.root)
root.add(header)
root.add(devices)
root.add(scroll)
Expand All @@ -434,11 +434,11 @@ export function transcriptPanel(context: Context, voice: VoiceController, visibl
return {
root,
animating: (now) => voice.active || voice.state.entries.some((entry) => entryAnimating(entry, now)),
interval: () => (aura.animating(Date.now()) ? aura.interval!() : 33),
suspend: () => aura.suspend!(),
dispose: () => aura.dispose!(),
interval: () => (aura?.animating(Date.now()) ? aura.interval!() : 33),
suspend: () => aura?.suspend!(),
dispose: () => aura?.dispose!(),
update(now) {
aura.update(now)
aura?.update(now)
const state = voice.state
const p = palette(context.theme)
const phase =
Expand Down Expand Up @@ -529,7 +529,8 @@ export function footerBadge(context: Context, voice: VoiceController): View {

/**
* Drives every mounted view: redraws on state changes, and while anything is animating at
* the fastest rate an animating view asks for (60 fps for the image aura, else 30). Views whose renderables were removed by the host are dropped automatically.
* the fastest rate an animating view asks for (30 fps by default), capped by
* the `fps` option. Views whose renderables were removed by the host are dropped automatically.
*/
export class Frames {
private readonly views = new Set<View>()
Expand All @@ -538,8 +539,14 @@ export class Frames {
private timer: ReturnType<typeof setInterval> | undefined
private period = 0
private readonly stopListening: () => void

constructor(private readonly voice: VoiceController) {
/** Shortest frame interval allowed, in milliseconds. */
private readonly minPeriod: number

constructor(
private readonly voice: VoiceController,
fps?: number,
) {
this.minPeriod = typeof fps === "number" && fps > 0 ? 1000 / fps : 0
this.stopListening = voice.onChange(() => this.tick())
}

Expand Down Expand Up @@ -576,6 +583,7 @@ export class Frames {
}
}
}
period = Math.max(period, this.minPeriod)
if (this.timer && (!animating || period !== this.period)) {
clearInterval(this.timer)
this.timer = undefined
Expand Down
20 changes: 20 additions & 0 deletions test/frames.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,24 @@ describe("frame clock", () => {
// Still mounted: every frame reached the view, including the ones after it failed.
expect(updates).toBe(9)
})

test("the fps option caps the frame rate of animating views", () => {
const voice = { onChange: () => () => {} }
const period = (fps?: number) => {
const frames = new Frames(voice as unknown as VoiceController, fps)
frames.mount({
root: { isDestroyed: false, destroyRecursively() {} } as unknown as View["root"],
animating: () => true,
interval: () => 33,
update() {},
})
const result = (frames as unknown as { period: number }).period
frames.dispose()
return result
}
expect(period()).toBe(33)
expect(period(10)).toBe(100)
expect(period(1000)).toBe(33)
expect(period(0)).toBe(33)
})
})
32 changes: 32 additions & 0 deletions test/options.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { describe, expect, test } from "bun:test"

import { terminalOptions } from "../src/server/options"

describe("terminal options", () => {
test("passes the terminal settings through", () => {
expect(
terminalOptions({
voice: "maple",
visual: "none",
fps: 10,
panel: false,
duck: true,
keybinds: { toggle: "<leader>v", mute: ["ctrl+y", "f9"], panel: false },
instructions: "server only",
}),
).toEqual({
voice: "maple",
visual: "none",
fps: 10,
panel: false,
duck: true,
keybinds: { toggle: "<leader>v", mute: ["ctrl+y", "f9"], panel: false },
})
})

test("drops values of the wrong type instead of failing", () => {
expect(terminalOptions({ fps: "10", panel: "no", keybinds: { toggle: 3, mute: "f9" } })).toEqual({
keybinds: { mute: "f9" },
})
})
})