diff --git a/beehive/README.md b/beehive/README.md index bdd14cdca1..8725400779 100644 --- a/beehive/README.md +++ b/beehive/README.md @@ -887,3 +887,34 @@ To reuse a local definition, explicitly copy its JSON into the Beehive directory and choose **Refresh harnesses**. Only detection fields are read: launch arguments, environment variables, credentials, and Desktop agent state are not imported. Refresh replaces the saved inventory; saved runtime configurations are unchanged. + +### Providers in the OpenTUI manager + +Providers is available while signed out. Add provider supports OpenAI, Anthropic, +OpenAI-compatible (endpoint and wire mode), OpenRouter, and Databricks v2. +Select a saved row, then use Tab or `a` to focus its actions. Arrows select an +action; Enter runs it. PgUp/PgDn scroll details, model IDs, and the full result. +Forms use Tab/Shift-Tab, Left/Right choices, Enter to advance/submit, Ctrl-U to +clear a field, and Esc to cancel. API-key input is masked; its value stays in the +Node controller and credential helper, not renderer state or settings. + +Edit preserves provider identity and affects future launches. A replacement API +key gets a fresh exact OS entry; old entries remain for active launch snapshots. +Blank key input keeps the saved key. Test checks access to the provider model +catalog, not generation or every model. Load models displays exact model IDs. +Codex/Pi setup checks installed adapters and supported provider combinations, +then saves an exact model configuration without starting an agent. + +Databricks reads the HTTPS workspace origin from `DATABRICKS_HOST`; unset or +mismatched origins produce an actionable unavailable state. Browser sign-in is +explicit and uses the packaged native helper. Reload providers refreshes durable +state and projects the environment workspace without reading credentials. +Esc stops waiting, not committed storage: inspect/reload before retrying. Quit +closes the provider controller and cancels its bounded helpers. + +For safe real-terminal acceptance without vendor or OS access, the explicit +`test/provider-tui-fixture.ts` entrypoint uses the real renderer, IPC, controller, +and settings with synthetic external adapters. It requires a temporary +`BEEHIVE_HOME` whose name contains `provider-tui-fixture-`. It is not reachable +from the production launcher. API key `deny` exercises provider denial. The +fixture is not proof of live vendor authentication. diff --git a/beehive/src/manager-credential-child.ts b/beehive/src/manager-credential-child.ts index c9e93790bc..a52c6d41c1 100644 --- a/beehive/src/manager-credential-child.ts +++ b/beehive/src/manager-credential-child.ts @@ -7,7 +7,7 @@ import { object } from './protocol.ts'; import { readHostIdentity, bootstrapHostIdentity } from './host-identity.ts'; import { createCredential, credentialReference, readCredential, systemCredentials } from './credential-store.ts'; import { publicKey } from './protocol.ts'; -import { registerAgent, agentNsec, addOpenAI, addProvider, providerCredentials } from './settings-credentials.ts'; +import { registerAgent, agentNsec, addOpenAI, addProvider, editProvider, providerCredentials } from './settings-credentials.ts'; import { readSettings } from './settings.ts'; import { providerModelOptions } from './settings-models.ts'; @@ -36,8 +36,11 @@ process.once('message', async (input: any) => { addOpenAI(input.directory,input.name,input.secret,providerCredentials()); process.send?.({ ok: true }); } else if (input.action === 'add-provider') { - addProvider(input.directory,input.name,input.secret,providerCredentials(),input.type,input.endpoint,input.wire); + addProvider(input.directory,input.name,input.secret,providerCredentials(),input.type,input.endpoint,input.wire,input.revision); process.send?.({ok:true}); + } else if (input.action === 'edit-provider') { + editProvider(input.directory, input.provider, input.revision, input.name, input.endpoint, input.wire, input.secret ?? '', providerCredentials()); + process.send?.({ ok: true }); } else if (input.action === 'provider-read') { const secret = providerCredentials().read(input.key); if (!secret) throw Error('Missing provider credential'); diff --git a/beehive/src/manager-view.ts b/beehive/src/manager-view.ts index e21168b9a6..1867c22452 100644 --- a/beehive/src/manager-view.ts +++ b/beehive/src/manager-view.ts @@ -1,5 +1,6 @@ import { createCliRenderer } from '@opentui/core'; import { OpenTuiShell } from './opentui-shell.ts'; +import { localProviders } from './provider-client.ts'; import { localHarnessInventory } from './harness-inventory.ts'; const renderer = await createCliRenderer({ @@ -9,7 +10,7 @@ const renderer = await createCliRenderer({ openConsoleOnError: false, }); const inventory = localHarnessInventory(); -const shell = new OpenTuiShell(renderer, inventory); +const shell = new OpenTuiShell(renderer, inventory, undefined, localProviders()); void inventory.refresh(); const stop = () => shell.close(); process.once('SIGINT', stop); diff --git a/beehive/src/opentui-shell.ts b/beehive/src/opentui-shell.ts index e2e519acde..bdb762268e 100644 --- a/beehive/src/opentui-shell.ts +++ b/beehive/src/opentui-shell.ts @@ -1,4 +1,6 @@ import { BoxRenderable, ScrollBoxRenderable, TextRenderable, type CliRenderer, type KeyEvent } from '@opentui/core'; +import { ProviderPanel } from './provider-panel.ts'; +import type { ProviderClient } from './provider-protocol.ts'; import { brand, destinations, listWidth, ownerLabel, ShellState, type FocusRegion } from './shell-state.ts'; import { HarnessInventoryController, type HarnessInventorySnapshot } from './harness-inventory.ts'; @@ -9,7 +11,7 @@ export const palette = { const wideFooter = '←→ move Enter open Tab panes Esc return ? help q quit'; const minimumFooter = 'Ctrl-Q quit'; -const helpBody = 'Header: ←→ destination; Enter / ↓ opens\nList: ↑ header; → / Enter Details\nDetails: ↑ header; ← List\nTab / Shift-Tab visible regions\nEsc active header\n? / Enter / Esc close help\nq quit Beehive'; +const helpBody = 'Header: ←→ destination; Enter / ↓ opens\nList: ↑ header; → / Enter Details\nDetails: ↑ header; ← List\nTab / Shift-Tab visible regions\nEsc active header\n? / Enter / Esc close help\nq quit Beehive\nProviders: a / Tab actions; ↑↓ selects\nPgUp / PgDn scroll details and results\nForms: Tab next; ←→ choice; Ctrl-U clear'; const helpTitleRows = 2; const helpActionRows = 2; const helpVerticalChrome = 4; // one-cell border and one-row inset at both edges @@ -69,6 +71,7 @@ export class OpenTuiShell { private inventorySnapshot: HarnessInventorySnapshot; private unsubscribeInventory: () => void; private screenGeneration = 0; + private providers?: ProviderPanel; private readonly footerRule: TextRenderable; private readonly footer: TextRenderable; private helpScrim?: BoxRenderable; @@ -78,7 +81,7 @@ export class OpenTuiShell { private helpTitle?: TextRenderable; private helpActions?: TextRenderable; - constructor(readonly renderer: CliRenderer, private readonly inventory: HarnessInventoryController, private readonly helpContent = helpBody) { + constructor(readonly renderer: CliRenderer, private readonly inventory: HarnessInventoryController, private readonly helpContent = helpBody, providers?: ProviderClient) { this.inventorySnapshot = inventory.snapshot(); this.done = new Promise(resolve => { this.finish = resolve; }); this.root = new BoxRenderable(renderer, { width: '100%', height: '100%', flexDirection: 'column', backgroundColor: palette.surface }); @@ -106,10 +109,12 @@ export class OpenTuiShell { this.divider = new TextRenderable(renderer, { width: 1, height: '100%', fg: palette.divider, content: '│' }); this.focusPerimeter = new BoxRenderable(renderer, { position: 'absolute', visible: false, border: true, borderColor: palette.focus, backgroundColor: 'transparent', onMouseDown: event => { - if (this.state.focus === 'list') this.clickListSlot(Math.floor((event.y - 6) / 2)); + if (this.state.activeSection === 3) { this.providers?.pointer(event.y); return; } + if (this.state.focus === 'list') this.clickListSlot(event.y - 6); else if (this.state.focus === 'detail' && event.y === 15) this.activateSelectedRow(); }, onMouseScroll: event => { + if (this.state.activeSection === 3) { this.providers?.scroll(event.scroll?.direction ?? ''); return; } if (this.state.focus !== 'list') return; if (event.scroll?.direction === 'up') this.state.key('up'); else if (event.scroll?.direction === 'down') this.state.key('down'); @@ -131,6 +136,8 @@ export class OpenTuiShell { this.footerRule = new TextRenderable(renderer, { height: 1, fg: palette.divider }); this.root.add(this.footerRule); this.footer = new TextRenderable(renderer, { height: 1, fg: palette.muted, content: wideFooter }); this.root.add(this.footer); + if (providers) this.providers = new ProviderPanel(renderer, this.listPane, this.detailPane, this.state, providers, () => this.paint()); + renderer.keyInput.on('paste', event => { if (this.providers?.paste(new TextDecoder().decode(event.bytes))) event.preventDefault(); }); renderer.keyInput.on('keypress', key => this.key(key)); renderer.on('resize', () => this.resize()); renderer.on('destroy', () => this.close(false)); @@ -145,6 +152,7 @@ export class OpenTuiShell { private pane(region: Exclude) { return new BoxRenderable(this.renderer, { height: '100%', backgroundColor: palette.surface, onMouseScroll: event => { + if (this.state.activeSection === 3) { this.providers?.scroll(event.scroll?.direction ?? ''); return; } if (region !== 'list' || this.state.activeSection !== 2 || !this.visible(region)) return; if (event.scroll?.direction === 'up') this.state.key('up'); else if (event.scroll?.direction === 'down') this.state.key('down'); @@ -159,6 +167,7 @@ export class OpenTuiShell { } private key(key: KeyEvent) { + if (!(key.ctrl && ['q', 'c'].includes(key.name)) && !this.state.belowMinimum && !this.state.helpOpen && this.providers?.key(key)) { key.preventDefault(); return; } const wasHarnesses = this.state.mode === 'section' && this.state.activeSection === 2; const effect = this.state.key(key.name, { ctrl: key.ctrl, shift: key.shift }); if (wasHarnesses && !(this.state.mode === 'section' && this.state.activeSection === 2)) { this.screenGeneration++; this.inventory.cancel(); } @@ -225,6 +234,7 @@ export class OpenTuiShell { this.listPane.width = '100%'; this.detailPane.width = '100%'; this.detailPane.flexGrow = 1; this.divider.visible = false; } this.paintHarnesses(); + this.providers?.setActive(!this.state.belowMinimum && this.state.mode === 'section' && this.state.activeSection === 3); const focusedPane = this.state.focus === 'list' || this.state.focus === 'detail' ? this.state.focus : undefined; this.focusPerimeter.visible = Boolean(focusedPane); if (focusedPane) { @@ -325,6 +335,7 @@ export class OpenTuiShell { this.closed = true; this.unsubscribeInventory(); this.inventory.dispose(); + this.providers?.dispose(); if (destroy) this.renderer.destroy(); this.finish(); } diff --git a/beehive/src/provider-child.ts b/beehive/src/provider-child.ts new file mode 100644 index 0000000000..41e04c3d8c --- /dev/null +++ b/beehive/src/provider-child.ts @@ -0,0 +1,20 @@ +import { ProviderService } from './provider-service.ts'; +const service = new ProviderService(process.env.BEEHIVE_HOME); +service.subscribe(snapshot => { if (process.connected) process.send?.({ type: 'snapshot', snapshot }); }); +let pending: Promise | undefined; +let exiting = false; +process.on('message', async (message: any) => { + if (message.type === 'secret') service.secret(message.action, message.value); + else if (message.type === 'cancel') service.cancel(); + else if (message.type === 'request') { + pending = service.request(message.request); + const ok = await pending; + if (process.connected && !exiting) process.send?.({ type: 'result', id: message.id, ok }); + } +}); +const stop = () => { + if (exiting) return; exiting = true; service.dispose(); + void Promise.resolve(pending).finally(() => process.exit()); +}; +process.on('disconnect', stop); +process.on('SIGTERM', stop); diff --git a/beehive/src/provider-client.ts b/beehive/src/provider-client.ts new file mode 100644 index 0000000000..256248ef34 --- /dev/null +++ b/beehive/src/provider-client.ts @@ -0,0 +1,40 @@ +import { fork } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { existsSync } from 'node:fs'; +import type { ProviderClient, ProviderRequest, ProviderSnapshot } from './provider-protocol.ts'; + +/** Renderer transport: only public projections return from the Node authority. */ +export function localProviders(options: { helper?: URL; environment?: NodeJS.ProcessEnv } = {}): ProviderClient { + const environment = options.environment ?? process.env; + const packagedNode = fileURLToPath(new URL('../runtime/node', import.meta.url)); + const child = fork(fileURLToPath(options.helper ?? new URL('./provider-child.ts', import.meta.url)), [], { + execPath: existsSync(packagedNode) ? packagedNode : process.env.BEEHIVE_NODE || 'node', + execArgv: ['--experimental-transform-types'], silent: true, + env: { PATH: environment.PATH ?? '/usr/bin:/bin', ...(environment.HOME ? { HOME: environment.HOME } : {}), ...(environment.BEEHIVE_HOME ? { BEEHIVE_HOME: environment.BEEHIVE_HOME } : {}), ...(environment.DATABRICKS_HOST ? { DATABRICKS_HOST: environment.DATABRICKS_HOST } : {}) }, + }); + let snapshot: ProviderSnapshot = { revision: 0, rows: [], phase: 'busy', message: 'Loading local providers…', secretLength: 0, models: [] }; + let serial = 0, disposed = false; + const listeners = new Set<(snapshot: ProviderSnapshot) => void>(); + const pending = new Map void>(); + const emit = () => { for (const listener of listeners) listener(structuredClone(snapshot)); }; + const unavailable = () => { + for (const resolve of pending.values()) resolve(false); pending.clear(); + if (disposed) return; + snapshot = { ...snapshot, phase: 'error', secretLength: 0, message: 'Provider controller stopped. Reopen Beehive. Saved data was not reset.' }; emit(); + }; + child.stdout?.resume(); child.stderr?.resume(); child.on('error', unavailable); child.on('close', unavailable); + child.on('message', (message: any) => { + if (disposed) return; + if (message.type === 'snapshot') { snapshot = message.snapshot; emit(); } + else if (message.type === 'result') { pending.get(message.id)?.(message.ok === true); pending.delete(message.id); } + }); + const send = (message: object) => { if (!disposed && child.connected) child.send(message, error => { if (error) unavailable(); }); else unavailable(); }; + return { + snapshot: () => structuredClone(snapshot), + subscribe(listener) { listeners.add(listener); listener(structuredClone(snapshot)); return () => { listeners.delete(listener); }; }, + request(request: ProviderRequest) { return new Promise(resolve => { const id = ++serial; pending.set(id, resolve); send({ type: 'request', id, request }); }); }, + secret(action, value) { send({ type: 'secret', action, value }); }, + cancel() { send({ type: 'cancel' }); }, + dispose() { if (disposed) return; disposed = true; for (const resolve of pending.values()) resolve(false); pending.clear(); listeners.clear(); if (child.connected) child.disconnect(); else child.kill('SIGTERM'); }, + }; +} diff --git a/beehive/src/provider-dialog.ts b/beehive/src/provider-dialog.ts new file mode 100644 index 0000000000..f5882ca6d2 --- /dev/null +++ b/beehive/src/provider-dialog.ts @@ -0,0 +1,97 @@ +import { BoxRenderable, TextRenderable, type CliRenderer, type KeyEvent } from '@opentui/core'; +import { palette } from './opentui-shell.ts'; + +export type DialogField = { label: string; value?: string; secret?: boolean; choices?: string[] }; +export type DialogResult = Record; + +/** Public form state only. Secret keystrokes go straight to the controller. */ +export class ProviderDialog { + private scrim: BoxRenderable; + private surface: BoxRenderable; + private title: TextRenderable; + private rows: TextRenderable[] = []; + private actions: TextRenderable; + private index = 0; + private offset = 0; + private secretLength = 0; + private closed = false; + readonly done: Promise; + private finish!: (value: DialogResult | undefined) => void; + constructor(private renderer: CliRenderer, private heading: string, readonly fields: DialogField[], private secret: (action: 'append' | 'backspace' | 'clear', value?: string) => void, private submitLabel = 'Save') { + this.done = new Promise(resolve => this.finish = resolve); + this.scrim = new BoxRenderable(renderer, { position: 'absolute', width: '100%', height: '100%', backgroundColor: palette.scrim }); + this.surface = new BoxRenderable(renderer, { position: 'absolute', border: true, borderColor: palette.dialog, backgroundColor: palette.surface }); + renderer.root.add(this.scrim); renderer.root.add(this.surface); + this.title = new TextRenderable(renderer, { position: 'absolute', top: 1, left: 2, height: 1, fg: palette.focus }); + this.surface.add(this.title); + for (let i = 0; i < fields.length; i++) { + const row = new TextRenderable(renderer, { position: 'absolute', left: 2, height: 2, fg: palette.text, onMouseDown: () => { this.index = i; this.paint(); } }); + this.surface.add(row); this.rows.push(row); + } + this.actions = new TextRenderable(renderer, { position: 'absolute', left: 2, height: 2, fg: palette.text, onMouseDown: () => this.complete() }); + this.surface.add(this.actions); this.paint(); + } + updateSecretLength(length: number) { this.secretLength = length; this.paint(); } + paste(value: string) { + const field = this.fields[this.index]; + if (!field || field.choices) return; + const text = value.replace(/[\x00-\x1f\x7f]/g, ''); + if (field.secret) this.secret('append', text); + else field.value = ((field.value ?? '') + text).slice(0, 4096); + this.paint(); + } + key(key: Pick) { + if (key.name === 'escape') { this.cancel(); return; } + if (key.name === 'tab' || key.name === 'down' || key.name === 'up') { + const delta = key.name === 'up' || key.shift ? -1 : 1; + this.index = (this.index + delta + this.fields.length + 1) % (this.fields.length + 1); this.paint(); return; + } + const field = this.fields[this.index]; + if (key.name === 'return') { + if (!field) this.complete(); + else { this.index++; this.paint(); } + return; + } + if (!field) return; + if (field.choices) { + if (key.name === 'left' || key.name === 'right') { + const current = Math.max(0, field.choices.indexOf(field.value ?? '')); + field.value = field.choices[(current + (key.name === 'left' ? -1 : 1) + field.choices.length) % field.choices.length]; + } + } else if (key.ctrl && key.name === 'u') { + if (field.secret) this.secret('clear'); else field.value = ''; + } else if (key.name === 'backspace') { + if (field.secret) this.secret('backspace'); else field.value = [...(field.value ?? '')].slice(0, -1).join(''); + } else if (!key.ctrl && !key.meta && key.sequence && !/[\x00-\x1f\x7f]/.test(key.sequence)) this.paste(key.sequence); + this.paint(); + } + paint() { + if (this.closed) return; + const width = Math.min(68, this.renderer.width - 4), height = Math.min(this.renderer.height - 4, 7 + this.fields.length * 3); + this.surface.width = width; this.surface.height = height; + this.surface.left = Math.floor((this.renderer.width - width) / 2); this.surface.top = Math.floor((this.renderer.height - height) / 2); + this.title.content = this.heading; this.title.width = width - 6; + const capacity = Math.max(1, Math.floor((height - 7) / 3)); + const selected = Math.min(this.index, this.fields.length - 1); + if (selected < this.offset) this.offset = selected; + if (selected >= this.offset + capacity) this.offset = selected - capacity + 1; + this.rows.forEach((row, i) => { + const field = this.fields[i]!; row.visible = i >= this.offset && i < this.offset + capacity; + row.top = 3 + (i - this.offset) * 3; row.width = width - 6; + const value = field.secret ? '•'.repeat(Math.min(this.secretLength, width - 10)) : field.value ?? ''; + row.content = `${field.label}${field.choices ? ' ← →' : ''}\n${value.slice(-(width - 6)) || ' '}`; + row.bg = this.index === i ? palette.selected : palette.surface; + row.fg = this.index === i ? palette.selectedText : palette.text; + }); + this.actions.top = height - 4; this.actions.width = width - 6; + this.actions.content = ` ${this.submitLabel} \nTab next · Esc cancel · Ctrl-U clear`; + this.actions.bg = this.index === this.fields.length ? palette.selected : palette.surface; + this.actions.fg = this.index === this.fields.length ? palette.selectedText : palette.text; + } + private complete() { + const values = Object.fromEntries(this.fields.filter(field => !field.secret).map(field => [field.label, field.value ?? field.choices?.[0] ?? ''])); + this.destroy(); this.finish(values); + } + cancel() { if (this.closed) return; this.secret('clear'); this.destroy(); this.finish(undefined); } + private destroy() { this.closed = true; this.surface.destroyRecursively(); this.scrim.destroyRecursively(); } +} diff --git a/beehive/src/provider-panel.ts b/beehive/src/provider-panel.ts new file mode 100644 index 0000000000..cffc97adb9 --- /dev/null +++ b/beehive/src/provider-panel.ts @@ -0,0 +1,191 @@ +import { BoxRenderable, TextRenderable, type CliRenderer, type KeyEvent } from '@opentui/core'; +import { palette } from './opentui-shell.ts'; +import { ProviderDialog, type DialogField } from './provider-dialog.ts'; +import type { ProviderClient, ProviderRow, ProviderSnapshot } from './provider-protocol.ts'; +import type { ShellState } from './shell-state.ts'; +import { listWidth } from './shell-state.ts'; + +const types = ['openai', 'anthropic', 'openai-compat', 'openrouter', 'databricks_v2']; +/** Providers presentation. All durable changes and secret state live in Node. */ +export class ProviderPanel { + private snapshot: ProviderSnapshot; + private unsubscribe: () => void; + private selected = 'add'; + private actionIndex = 0; + private actionOffset = 0; + private offset = 0; + private detailOffset = 0; + private list: BoxRenderable; + private detail: BoxRenderable; + private listTitle: TextRenderable; + private detailTitle: TextRenderable; + private details: TextRenderable; + private rows: TextRenderable[] = []; + private actions: TextRenderable[] = []; + private status: TextRenderable; + private actionTitle: TextRenderable; + private dialog?: ProviderDialog; + private active = false; + private generation = 0; + constructor(private renderer: CliRenderer, listPane: BoxRenderable, detailPane: BoxRenderable, private state: ShellState, private client: ProviderClient, private repaint: () => void) { + this.snapshot = client.snapshot(); + this.list = new BoxRenderable(renderer, { width: '100%', height: '100%', backgroundColor: palette.surface }); + this.detail = new BoxRenderable(renderer, { width: '100%', height: '100%', backgroundColor: palette.surface }); + listPane.add(this.list); detailPane.add(this.detail); + this.listTitle = new TextRenderable(renderer, { left: 2, top: 1, position: 'absolute', height: 1, fg: palette.muted, content: 'PROVIDERS' }); this.list.add(this.listTitle); + this.detailTitle = new TextRenderable(renderer, { left: 2, top: 1, position: 'absolute', height: 1, fg: palette.muted }); this.detail.add(this.detailTitle); + this.details = new TextRenderable(renderer, { left: 2, top: 3, position: 'absolute', fg: palette.text, wrapMode: 'word' }); this.detail.add(this.details); + this.actionTitle = new TextRenderable(renderer, { left: 2, position: 'absolute', height: 1, fg: palette.muted, content: 'AVAILABLE ACTIONS' }); this.detail.add(this.actionTitle); + this.status = new TextRenderable(renderer, { left: 2, position: 'absolute', fg: palette.muted, wrapMode: 'word' }); this.detail.add(this.status); + for (let i = 0; i < 40; i++) { + const row = new TextRenderable(renderer, { left: 2, position: 'absolute', height: 1, fg: palette.text, onMouseDown: () => this.select(i + this.offset) }); this.list.add(row); this.rows.push(row); + } + for (let i = 0; i < 7; i++) { + const action = new TextRenderable(renderer, { left: 2, position: 'absolute', height: 1, fg: palette.text, onMouseDown: () => { if (!this.active || this.dialog) return; this.actionIndex = this.actionOffset + i; this.state.focus = 'detail'; void this.run(); } }); this.detail.add(action); this.actions.push(action); + } + this.unsubscribe = client.subscribe(snapshot => { this.snapshot = snapshot; this.dialog?.updateSecretLength(snapshot.secretLength); this.paint(); }); + } + private items() { return [...this.snapshot.rows.map(row => row.id), 'add', 'reload']; } + private row() { return this.snapshot.rows.find(row => row.id === this.selected); } + private commands() { + if (this.selected === 'add') return ['Add provider']; + if (this.selected === 'reload') return ['Reload providers']; + return ['Edit provider', 'Test provider', 'Load models', ...(this.row()?.type === 'databricks_v2' ? ['Sign in to Databricks'] : []), 'Set up Codex', 'Set up Pi']; + } + private select(index: number) { + if (!this.active || this.dialog) return; + const id = this.items()[index]; if (!id) return; + this.selected = id; this.actionIndex = 0; this.actionOffset = 0; this.detailOffset = 0; this.state.focus = 'list'; this.repaint(); + } + setActive(active: boolean) { + if (this.active && !active) { this.generation++; this.dialog?.cancel(); this.dialog = undefined; this.client.cancel(); } + const entered = active && !this.active; + this.active = active; this.list.visible = active; this.detail.visible = active; + if (entered) void this.client.request({ action: 'reload' }); + this.paint(); + } + paste(value: string) { if (this.dialog) { this.dialog.paste(value); return true; } return false; } + key(key: KeyEvent): boolean { + if (!this.active) return false; + if (this.dialog) { this.dialog.key(key); return true; } + if (this.snapshot.phase === 'busy' && key.name === 'escape') { this.client.cancel(); return true; } + if (key.name === 'a') { this.state.focus = 'detail'; this.repaint(); return true; } + if (key.name === 'tab') { this.state.focus = this.state.focus === 'list' ? 'detail' : this.state.focus === 'detail' ? 'list' : 'list'; this.repaint(); return true; } + if (this.state.focus === 'list' && ['up', 'down'].includes(key.name)) { + const index = this.items().indexOf(this.selected), next = index + (key.name === 'up' ? -1 : 1); + if (next < 0) { this.state.focus = 'header'; this.state.headerIndex = 3; this.repaint(); } + else this.select(Math.min(this.items().length - 1, next)); + return true; + } + if (this.state.focus === 'detail') { + if (['up', 'down'].includes(key.name)) { this.actionIndex = Math.max(0, Math.min(this.commands().length - 1, this.actionIndex + (key.name === 'up' ? -1 : 1))); this.paint(); return true; } + if (['pageup', 'pagedown'].includes(key.name)) { this.detailOffset = Math.max(0, this.detailOffset + (key.name === 'pageup' ? -3 : 3)); this.paint(); return true; } + if (key.name === 'return') { void this.run(); return true; } + } + return false; + } + private async form(title: string, fields: DialogField[], submit = 'Save') { + this.client.secret('clear'); + const dialog = new ProviderDialog(this.renderer, title, fields, (action, value) => this.client.secret(action, value), submit); + this.dialog = dialog; + const result = await dialog.done; + if (this.dialog === dialog) this.dialog = undefined; + this.repaint(); return result; + } + private async edit(row?: ProviderRow) { + const generation = this.generation, revision = this.snapshot.revision; + let type = row?.type; + if (!type) { + const result = await this.form('ADD PROVIDER', [{ label: 'Type', value: 'openai', choices: types }], 'Continue'); + if (!result || generation !== this.generation) return; + type = result.Type as ProviderRow['type']; + } + const fields: DialogField[] = [{ label: 'Name', value: row?.name ?? (type === 'databricks_v2' ? 'Databricks' : type) }]; + if (type === 'databricks_v2') fields.push({ label: 'Workspace (DATABRICKS_HOST)', value: this.snapshot.databricksHost ?? 'Set DATABRICKS_HOST and reopen Beehive', choices: [this.snapshot.databricksHost ?? 'Set DATABRICKS_HOST and reopen Beehive'] }); + else { + if (type === 'openai-compat') fields.push({ label: 'Endpoint', value: row?.endpoint ?? 'https://' }, { label: 'Wire', value: row?.wire ?? 'auto', choices: ['auto', 'chat', 'responses'] }); + fields.push({ label: row ? 'API key (blank keeps saved)' : 'API key', secret: true }); + } + const result = await this.form(row ? 'EDIT PROVIDER' : 'ADD PROVIDER', fields); + if (!result || generation !== this.generation) return; + await this.client.request({ action: 'save', provider: row?.id, revision, values: { type, name: result.Name!, endpoint: result.Endpoint ?? '', wire: result.Wire ?? 'auto' } }); + } + private async setup(row: ProviderRow, harness: string) { + const generation = this.generation; + if (!await this.client.request({ action: 'discover', provider: row.id, revision: this.snapshot.revision }) || generation !== this.generation) return; + const available = this.snapshot.setup?.find(value => value.id === harness); + if (!available || available.state !== 'available' || !available.providers.includes(row.type)) { + await this.form('SETUP UNAVAILABLE', [{ label: 'Reason', value: available?.reason ?? 'Harness not installed', choices: [available?.reason ?? 'Harness not installed'] }], 'Close'); return; + } + const revision = this.snapshot.revision; + const fields: DialogField[] = [{ label: 'Name', value: `${available.label} configuration` }, { label: 'Model', value: this.snapshot.modelProvider === row.id ? this.snapshot.models[0] : '' }]; + if (harness === 'pi') fields.push({ label: 'Effort', value: 'Inherit', choices: ['Inherit', 'minimal', 'low', 'medium', 'high', 'xhigh'] }); + const result = await this.form(`SET UP ${available.label.toUpperCase()}`, fields); + if (!result || generation !== this.generation) return; + await this.client.request({ action: 'setup', provider: row.id, revision, values: { harness, name: result.Name!, model: result.Model!, effort: result.Effort ?? 'Inherit' } }); + } + pointer(y: number) { + if (!this.active || this.dialog) return; + if (this.state.focus === 'list') this.select(y - 6 + this.offset); + else { + const count = Math.min(this.commands().length, this.renderer.height < 28 ? 3 : 7); + const first = this.renderer.height - 5 - count - 4; + const index = y - 3 - first + this.actionOffset; + if (index >= 0 && index < this.commands().length) { this.actionIndex = index; void this.run(); } + } + } + scroll(direction: string) { + if (!this.active || this.dialog) return; + if (this.state.focus === 'list') this.select(Math.max(0, Math.min(this.items().length - 1, this.items().indexOf(this.selected) + (direction === 'up' ? -1 : 1)))); + else { this.detailOffset = Math.max(0, this.detailOffset + (direction === 'up' ? -1 : 1)); this.paint(); } + } + private async run() { + if (this.snapshot.phase === 'busy' || this.dialog || !this.active) return; + const command = this.commands()[this.actionIndex], row = this.row(); + if (command === 'Add provider') await this.edit(); + else if (command === 'Reload providers') await this.client.request({ action: 'reload' }); + else if (row) { + if (command === 'Edit provider') await this.edit(row); + else if (command === 'Set up Codex' || command === 'Set up Pi') await this.setup(row, command === 'Set up Codex' ? 'codex' : 'pi'); + else await this.client.request({ action: command === 'Test provider' ? 'test' : command === 'Load models' ? 'models' : 'login', provider: row.id, revision: this.snapshot.revision }); + } + } + paint() { + if (!this.active) return; + const height = this.renderer.height - 5, leftWidth = listWidth(this.renderer.width) - 4, width = this.renderer.width - listWidth(this.renderer.width) - 5; + const items = this.items(); if (!items.includes(this.selected)) this.selected = 'add'; + const selectedIndex = items.indexOf(this.selected), capacity = Math.min(this.rows.length, Math.max(1, height - 4)); + if (selectedIndex < this.offset) this.offset = selectedIndex; + if (selectedIndex >= this.offset + capacity) this.offset = selectedIndex - capacity + 1; + this.rows.forEach((renderable, slot) => { + const id = items[this.offset + slot], row = this.snapshot.rows.find(row => row.id === id); + renderable.visible = slot < capacity && !!id; renderable.top = slot + 3; renderable.width = leftWidth; + renderable.content = (id === 'add' ? '+ Add provider' : id === 'reload' ? '↻ Reload providers' : `◇ ${row?.name ?? ''}`).slice(0, leftWidth); + renderable.bg = id === this.selected ? palette.selected : palette.surface; renderable.fg = id === this.selected ? palette.selectedText : palette.text; + }); + const row = this.row(); + this.detailTitle.content = row ? row.name.toUpperCase() : this.selected === 'add' ? 'ADD PROVIDER' : 'RELOAD PROVIDERS'; this.detailTitle.width = width; + const commands = this.commands(); + const actionCapacity = Math.min(commands.length, this.renderer.height < 28 ? 3 : 7); + if (this.actionIndex < this.actionOffset) this.actionOffset = this.actionIndex; + if (this.actionIndex >= this.actionOffset + actionCapacity) this.actionOffset = this.actionIndex - actionCapacity + 1; + const actionStart = height - actionCapacity - 4; + const info = row ? [`State ${row.state}`, `Type ${row.type}`, `Connects to ${row.endpoint}`, '', row.detail, ...(this.snapshot.modelProvider === row.id ? ['', 'MODELS', ...this.snapshot.models] : [])] : this.selected === 'add' ? ['Choose OpenAI, Anthropic, OpenAI-compatible, OpenRouter, or Databricks v2.', '', 'Credentials stay in the OS credential store.'] : ['Reload saved providers and the DATABRICKS_HOST workspace. No owner sign-in is required.']; + info.push('', 'RESULT', this.snapshot.message); + const wrapped = info.flatMap(line => { const result: string[] = []; for (let start = 0; start < Math.max(1, line.length); start += width) result.push(line.slice(start, start + width)); return result; }); + this.detailOffset = Math.min(this.detailOffset, Math.max(0, wrapped.length - (actionStart - 4))); + this.details.width = width; this.details.height = Math.max(1, actionStart - 4); this.details.content = wrapped.slice(this.detailOffset, this.detailOffset + Math.max(1, actionStart - 4)).join('\n'); + this.actionTitle.top = actionStart - 1; this.actionTitle.width = width; + this.actions.forEach((action, index) => { + const commandIndex = this.actionOffset + index; + action.visible = index < actionCapacity; action.top = actionStart + index; action.width = width; + action.content = commands[commandIndex] ?? ''; action.fg = this.state.focus === 'detail' && this.actionIndex === commandIndex ? palette.selectedText : palette.text; + action.bg = this.state.focus === 'detail' && this.actionIndex === commandIndex ? palette.selected : palette.surface; + }); + this.status.top = height - 3; this.status.width = width; this.status.height = 2; + this.status.content = this.snapshot.phase === 'busy' ? 'Working… Esc stops waiting' : `${this.snapshot.phase === 'error' ? 'FAILED · ' : ''}PgUp/PgDn details\n↑↓ actions · Enter run`; + this.status.fg = this.snapshot.phase === 'error' ? palette.failure : palette.muted; + this.dialog?.paint(); + } + dispose() { this.generation++; this.dialog?.cancel(); this.unsubscribe(); this.client.dispose(); } +} diff --git a/beehive/src/provider-protocol.ts b/beehive/src/provider-protocol.ts new file mode 100644 index 0000000000..8172ef10fe --- /dev/null +++ b/beehive/src/provider-protocol.ts @@ -0,0 +1,13 @@ +/** Public renderer/controller protocol. Snapshots contain no credential references or secrets. */ +export type ProviderType = 'openai' | 'anthropic' | 'openai-compat' | 'openrouter' | 'databricks_v2'; +export type ProviderRow = { id: string; name: string; type: ProviderType; endpoint: string; wire?: string; state: string; detail: string }; +export type ProviderSnapshot = { revision: number; rows: ProviderRow[]; phase: 'idle' | 'busy' | 'error'; message: string; secretLength: number; models: string[]; modelProvider?: string; databricksHost?: string; setup?: { id: string; label: string; state: string; reason: string; providers: string[] }[] }; +export type ProviderRequest = { action: 'reload' | 'save' | 'test' | 'models' | 'login' | 'discover' | 'setup'; provider?: string; revision?: number; values?: Record }; +export interface ProviderClient { + snapshot(): ProviderSnapshot; + subscribe(listener: (snapshot: ProviderSnapshot) => void): () => void; + request(request: ProviderRequest): Promise; + secret(action: 'append' | 'backspace' | 'clear', value?: string): void; + cancel(): void; + dispose(): void; +} diff --git a/beehive/src/provider-service.ts b/beehive/src/provider-service.ts new file mode 100644 index 0000000000..98c90b890f --- /dev/null +++ b/beehive/src/provider-service.ts @@ -0,0 +1,106 @@ +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import { readSettings, saveSettings, settingsId, replaceProvider } from './settings.ts'; +import { managerCredential } from './manager-credential.ts'; +import { databricksHost, databricksNative, rememberEnvironmentDatabricks } from './databricks.ts'; +import { discoverHarnesses } from './harness-discovery.ts'; +import { retainCredentialAttempt } from './settings-credentials.ts'; +import type { ProviderClient, ProviderRequest, ProviderSnapshot } from './provider-protocol.ts'; + +export const providerEndpoints: Record = { openai: 'https://api.openai.com/v1', anthropic: 'https://api.anthropic.com', openrouter: 'https://openrouter.ai/api/v1' }; +export type ProviderDependencies = { credential: typeof managerCredential; native: typeof databricksNative; discover: typeof discoverHarnesses }; + +/** Node-only local authority. No owner credentials, relay client, or Host service. */ +export class ProviderService implements ProviderClient { + private current: ProviderSnapshot = { revision: 0, rows: [], phase: 'idle', message: 'Select a provider or add one.', secretLength: 0, models: [] }; + private listeners = new Set<(snapshot: ProviderSnapshot) => void>(); + private secretValue = ''; + private active?: AbortController; + private generation = 0; + private disposed = false; + private readonly directory: string; + constructor(private readonly home = homedir(), private readonly environment: NodeJS.ProcessEnv = process.env, private readonly deps: ProviderDependencies = { credential: managerCredential, native: databricksNative, discover: discoverHarnesses }) { + this.directory = join(home, '.beehive', 'host'); + this.reload(); + } + snapshot() { return structuredClone(this.current); } + subscribe(listener: (snapshot: ProviderSnapshot) => void) { this.listeners.add(listener); listener(this.snapshot()); return () => { this.listeners.delete(listener); }; } + private publish() { if (!this.disposed) for (const listener of this.listeners) listener(this.snapshot()); } + private reload() { + try { + const settings = readSettings(this.directory); + let workspace: string | undefined; + try { if (this.environment.DATABRICKS_HOST) workspace = databricksHost(this.environment.DATABRICKS_HOST); } catch { /* Expose actionable public status, never raw input. */ } + this.current = { ...this.current, revision: settings.revision, databricksHost: workspace, rows: settings.providers.map(p => ({ id: p.id, name: p.name, type: p.type, endpoint: p.endpoint, ...(p.wire ? { wire: p.wire } : {}), state: p.type === 'databricks_v2' && p.endpoint !== workspace ? 'ENV MISSING' : 'SAVED', detail: p.type === 'databricks_v2' ? p.endpoint === workspace ? 'Sign in explicitly, then test or load models.' : 'Set DATABRICKS_HOST to this workspace HTTPS origin.' : 'Credential stored securely. Access has not been tested in this session.' })) }; + } catch { this.current.phase = 'error'; this.current.message = 'Saved providers could not be read. Existing data was not changed.'; } + this.publish(); + } + secret(action: 'append' | 'backspace' | 'clear', value = '') { + if (this.disposed || this.active) return; + if (action === 'clear') this.secretValue = ''; + else if (action === 'backspace') this.secretValue = [...this.secretValue].slice(0, -1).join(''); + else this.secretValue = (this.secretValue + value.replace(/[\x00-\x1f\x7f]/g, '')).slice(0, 16384); + this.current.secretLength = [...this.secretValue].length; this.publish(); + } + async request(request: ProviderRequest) { + if (this.active || this.disposed) return false; + const abort = new AbortController(), generation = ++this.generation; + this.active = abort; this.current.phase = 'busy'; this.current.message = 'Working… Esc stops waiting; changes may already be saved.'; this.publish(); + const check = () => { abort.signal.throwIfAborted(); if (generation !== this.generation || this.disposed) throw Error('Cancelled'); }; + try { + const before = readSettings(this.directory), values = request.values ?? {}; + if (request.revision !== undefined && before.revision !== request.revision) throw Error('Settings changed'); + const provider = before.providers.find(row => row.id === request.provider); + if (['test', 'models', 'login', 'setup'].includes(request.action) && !provider) throw Error('Select provider'); + if (provider?.type === 'databricks_v2' && request.action !== 'save' && this.current.databricksHost !== provider.endpoint) throw Error('Databricks workspace environment missing'); + let message = ''; + if (request.action === 'reload') { + rememberEnvironmentDatabricks(this.directory, this.environment.DATABRICKS_HOST); + message = this.environment.DATABRICKS_HOST ? 'Local providers loaded.' : 'Local providers loaded. Set DATABRICKS_HOST to add a Databricks workspace.'; + } else if (request.action === 'save') { + if (values.type === 'databricks_v2' || provider?.type === 'databricks_v2') { + const endpoint = databricksHost(this.environment.DATABRICKS_HOST ?? ''); + if (provider) replaceProvider(this.directory, { ...provider, name: values.name || provider.name, endpoint, key: endpoint === provider.endpoint ? provider.key : { service: 'beehive', account: `provider:${settingsId()}` } }, before.revision); + else rememberEnvironmentDatabricks(this.directory, endpoint); + } else { + const type = provider?.type ?? values.type; + await this.deps.credential({ action: provider ? 'edit-provider' : 'add-provider', directory: this.directory, provider: provider?.id, revision: before.revision, name: values.name, type, endpoint: providerEndpoints[type ?? ''] ?? values.endpoint, ...(type === 'openai-compat' ? { wire: values.wire || 'auto' } : {}), secret: this.secretValue }, abort.signal); + } + check(); readSettings(this.directory); message = 'Provider saved. Existing runs are unchanged.'; + } else if (request.action === 'login') { + if (provider!.type !== 'databricks_v2') throw Error('Not Databricks'); + retainCredentialAttempt(this.directory, provider!.key); + await this.deps.native({ action: 'login', host: provider!.endpoint, key: provider!.key }, abort.signal); check(); message = 'Databricks sign-in completed. Test access or load models.'; + } else if (request.action === 'test' || request.action === 'models') { + this.current.models = []; this.current.modelProvider = undefined; + const result = provider!.type === 'databricks_v2' + ? await this.deps.native({ action: 'models', host: provider!.endpoint, key: provider!.key }, abort.signal) + : await this.deps.credential({ action: 'models', directory: this.directory, provider: provider!.id }, abort.signal); + check(); this.current.models = result.models ?? []; this.current.modelProvider = provider!.id; + message = request.action === 'test' ? 'Provider model catalog is reachable. Model execution has not been tested.' : `${this.current.models.length} models loaded. Custom model IDs are also supported.`; + } else if (request.action === 'discover') { + const rows = await this.deps.discover(abort.signal, { home: this.home }); check(); + this.current.setup = rows.filter(row => ['codex', 'pi'].includes(row.id)).map(({ id, label, state, reason, providers }) => ({ id, label, state, reason, providers })); + message = 'Choose an available harness and exact model ID. Saving does not start an agent.'; + } else if (request.action === 'setup') { + const rows = await this.deps.discover(abort.signal, { home: this.home }); check(); + const row = rows.find(row => row.id === values.harness); + if (!row || !['codex', 'pi'].includes(row.id) || row.state !== 'available' || !row.executable || !row.cli || !row.providers.includes(provider!.type)) throw Error('Harness unavailable or unsupported provider'); + const current = readSettings(this.directory); + if (current.revision !== before.revision) throw Error('Settings changed'); + saveSettings(this.directory, { ...current, runtimes: [...current.runtimes, { id: settingsId(), name: values.name || `${row.label} configuration`, harness: row.id as 'codex' | 'pi', executable: row.executable, cli: row.cli, providerId: provider!.id, model: values.model ?? '', ...(values.effort && values.effort !== 'Inherit' ? { effort: values.effort } : {}) }] }, current.revision); + message = 'Runtime configuration saved for future use. No agent was started.'; + } + check(); this.current.phase = 'idle'; this.current.message = message; this.reload(); return true; + } catch { + if (generation === this.generation && !this.disposed) { this.current.phase = 'error'; this.current.message = 'Could not complete the operation. Check fields, provider access, and DATABRICKS_HOST if needed. Changes may already be saved; reload before retrying.'; this.reload(); } + return false; + } finally { + this.secretValue = ''; this.current.secretLength = 0; + if (this.active === abort) this.active = undefined; + this.publish(); + } + } + cancel() { this.generation++; this.active?.abort(); this.secretValue = ''; this.current.secretLength = 0; this.current.phase = 'idle'; this.current.message = 'Stopped waiting. Changes or OS credentials may already be saved. Reload providers before retrying.'; this.publish(); } + dispose() { this.cancel(); this.disposed = true; this.listeners.clear(); } +} diff --git a/beehive/src/settings-credentials.ts b/beehive/src/settings-credentials.ts index d1a1397c88..f0713d754d 100644 --- a/beehive/src/settings-credentials.ts +++ b/beehive/src/settings-credentials.ts @@ -6,7 +6,7 @@ import { loadNativeEntry, type NativeEntry } from './native-credentials.ts'; import { type CredentialBackend, credentialReference, createCredential, readCredential } from './credential-store.ts'; import { nip19 } from 'nostr-tools'; import { publicKey } from './protocol.ts'; -import { readSettings, saveSettings, settingsId, settingsLock, type ProviderReference, type RegisteredAgent, type SavedProvider, validateSettings } from './settings.ts'; +import { readSettings, saveSettings, settingsId, settingsLock, type ProviderReference, type RegisteredAgent, type SavedProvider, validateSettings, replaceProvider } from './settings.ts'; /** Decode hidden nsec input on Node, never in the renderer's display state. */ export function agentNsec(input: string): string { @@ -49,10 +49,11 @@ export function addOpenAI(directory: string, name: string, secret: string, backe return addProvider(directory,name,secret,backend,'openai','https://api.openai.com/v1'); } /** Verified immutable OS entry for each supported API-key provider. */ -export function addProvider(directory: string, name: string, secret: string, backend: ProviderCredentials, type: SavedProvider['type'], endpoint: string, wire?: SavedProvider['wire']) { +export function addProvider(directory: string, name: string, secret: string, backend: ProviderCredentials, type: SavedProvider['type'], endpoint: string, wire?: SavedProvider['wire'], expected?: number) { if (!name || name.length > 128 || /[\x00-\x1f\x7f]/.test(name)) throw Error('Enter a provider name'); if (!secret || secret.length > 16384 || /\s/.test(secret)) throw Error('Enter an API key'); const previous = readSettings(directory), id = settingsId(); + if (expected !== undefined && previous.revision !== expected) throw Error('Settings changed. Open the form again.'); const key: ProviderReference = { service: 'beehive', account: `provider:${id}` }; const candidate = validateSettings({ ...previous, providers: [...previous.providers, { id, name, type, endpoint, key, ...(wire ? {wire} : {}) }] }); settingsLock(directory, () => { retainCredentialAttempt(directory,key); backend.create(key, secret); }); @@ -68,3 +69,21 @@ export function retainCredentialAttempt(directory: string, key: object) { if (!Array.isArray(rows) || rows.length >= 100) throw Error('Credential recovery log needs attention'); if (!rows.some(row => JSON.stringify(row) === JSON.stringify(key))) writePrivate(path,[...rows,key]); } + +/** Verified credential rotation uses a fresh exact entry; active runs keep the old + * reference. Empty secret preserves the existing credential without reading it. */ +export function editProvider(directory: string, id: string, expected: number, name: string, endpoint: string, wire: SavedProvider['wire'], secret: string, backend: ProviderCredentials) { + const previous = readSettings(directory); + if (previous.revision !== expected) throw Error('Settings changed. Open the form again.'); + const current = previous.providers.find(row => row.id === id); + if (!current || current.type === 'databricks_v2') throw Error('Select an API-key provider'); + if (secret && (secret.length > 16384 || /\s/.test(secret))) throw Error('Enter an API key'); + const key: ProviderReference = secret ? { service: 'beehive', account: `provider:${settingsId()}` } : current.key; + const provider: SavedProvider = { ...current, name, endpoint, key, ...(current.type === 'openai-compat' ? { wire } : {}) }; + validateSettings({ ...previous, providers: previous.providers.map(row => row.id === id ? provider : row) }); + if (secret) { + settingsLock(directory, () => { retainCredentialAttempt(directory, key); backend.create(key, secret); }); + if (backend.read(key) !== secret) throw Error('Provider credential verification failed'); + } + return replaceProvider(directory, provider, expected); +} diff --git a/beehive/src/settings.ts b/beehive/src/settings.ts index 27451fc166..e629cbb62e 100644 --- a/beehive/src/settings.ts +++ b/beehive/src/settings.ts @@ -88,3 +88,16 @@ export function retainedSettingsRow(previous: object, next: object, collection: const { runtimeId: _, ...identity } = next as RegisteredAgent; return JSON.stringify(previous) === JSON.stringify(identity); } + +/** Provider edits affect future launches only. Existing launch snapshots retain + * their endpoint and credential reference; old OS entries are never overwritten. */ +export function replaceProvider(directory: string, provider: SavedProvider, expected: number): Settings { + return settingsLock(directory, () => { + const previous = readSettings(directory); + if (previous.revision !== expected) throw Error('Settings changed. Open the form again.'); + if (!previous.providers.some(row => row.id === provider.id)) throw Error('Provider no longer exists'); + const next = validateSettings({ ...previous, revision: expected + 1, providers: previous.providers.map(row => row.id === provider.id ? provider : row) }); + writePrivate(path(directory), next); + return readSettings(directory); + }); +} diff --git a/beehive/test/provider-service.test.ts b/beehive/test/provider-service.test.ts new file mode 100644 index 0000000000..5bf94f7bcc --- /dev/null +++ b/beehive/test/provider-service.test.ts @@ -0,0 +1,94 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, rmSync, readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ProviderService, type ProviderDependencies } from '../src/provider-service.ts'; +import { addProvider, editProvider, type ProviderCredentials } from '../src/settings-credentials.ts'; +import { readSettings } from '../src/settings.ts'; + +function fixture() { + const home = mkdtempSync(join(tmpdir(), 'providers-')), directory = join(home, '.beehive', 'host'); + const keys = new Map(); + const backend: ProviderCredentials = { read: ref => keys.get(ref.account) ?? null, create: (ref, secret) => { assert.equal(keys.has(ref.account), false); keys.set(ref.account, secret); } }; + const deps: ProviderDependencies = { + credential: async (input: any) => { + if (input.action === 'add-provider') addProvider(directory, input.name, input.secret, backend, input.type, input.endpoint, input.wire); + else if (input.action === 'edit-provider') editProvider(directory, input.provider, input.revision, input.name, input.endpoint, input.wire, input.secret, backend); + else if (input.action === 'models') return { models: ['gpt-fixture'] }; + else throw Error('Unexpected credential action'); + return { ok: true }; + }, + native: async () => ({ ok: true, models: ['fixture-model'] }), + discover: async () => [{ id: 'codex', label: 'Codex', executable: '/fixture/codex-acp', cli: '/fixture/codex', state: 'available', providers: ['openai'], reason: 'Fixture' }], + }; + const service = new ProviderService(home, {}, deps); + return { home, directory, keys, backend, deps, service, close() { service.dispose(); rmSync(home, { recursive: true, force: true }); } }; +} +test('signed-out add, edit, models and Codex setup retain active credential references and durable data', async () => { + const f = fixture(); + try { + f.service.secret('append', 'first-private-key'); + assert.doesNotMatch(JSON.stringify(f.service.snapshot()), /first-private-key/); + assert.equal(await f.service.request({ action: 'save', revision: 0, values: { type: 'openai', name: 'Fixture' } }), true); + let settings = readSettings(f.directory), provider = settings.providers[0]!; + const oldKey = provider.key; + assert.equal(await f.service.request({ action: 'models', provider: provider.id, revision: settings.revision }), true); + assert.deepEqual(f.service.snapshot().models, ['gpt-fixture']); + assert.equal(await f.service.request({ action: 'setup', provider: provider.id, revision: settings.revision, values: { harness: 'codex', model: 'gpt-fixture' } }), true); + settings = readSettings(f.directory); + f.service.secret('append', 'second-private-key'); + assert.equal(await f.service.request({ action: 'save', provider: provider.id, revision: settings.revision, values: { name: 'Renamed' } }), true); + settings = readSettings(f.directory); provider = settings.providers[0]!; + assert.equal(provider.name, 'Renamed'); assert.notDeepEqual(provider.key, oldKey); + assert.equal(f.keys.get(oldKey.account), 'first-private-key', 'active launch reference remains valid'); + assert.equal(f.keys.get(provider.key.account), 'second-private-key'); + assert.equal(settings.runtimes.length, 1); + assert.doesNotMatch(readFileSync(join(f.directory, 'settings.json'), 'utf8'), /private-key/); + assert.equal(f.service.snapshot().secretLength, 0); + const reopened = new ProviderService(f.home, {}, f.deps); + assert.equal(reopened.snapshot().rows[0]?.name, 'Renamed'); reopened.dispose(); + } finally { f.close(); } +}); +test('stale revision and denied credential read-back leave public provider unchanged', async () => { + const f = fixture(); + try { + f.service.secret('append', 'secret'); + assert.equal(await f.service.request({ action: 'save', revision: 9, values: { type: 'openai', name: 'No' } }), false); + assert.equal(readSettings(f.directory).providers.length, 0); + assert.throws(() => addProvider(f.directory, 'No', 'secret', { create() {}, read() { return null; } }, 'openai', 'https://api.openai.com/v1'), /verification/); + assert.equal(readSettings(f.directory).providers.length, 0); + assert.doesNotMatch(JSON.stringify(f.service.snapshot()), /"secret"/); + } finally { f.close(); } +}); +test('Databricks environment adds origin without credentials; missing environment blocks network', async () => { + const f = fixture(); let calls = 0; + f.deps.native = async () => { calls++; return { ok: true }; }; + const service = new ProviderService(f.home, { DATABRICKS_HOST: 'https://fixture.cloud.databricks.com' }, f.deps); + try { + assert.equal(await service.request({ action: 'reload' }), true); + assert.equal(calls, 0); assert.equal(f.keys.size, 0); + const row = service.snapshot().rows[0]!; + assert.equal(await service.request({ action: 'login', provider: row.id }), true); + assert.equal(calls, 1); + const without = new ProviderService(f.home, {}, f.deps); + assert.equal(without.snapshot().rows[0]?.state, 'ENV MISSING'); + assert.equal(await without.request({ action: 'models', provider: row.id }), false); + assert.equal(calls, 1); without.dispose(); + } finally { service.dispose(); f.close(); } +}); +test('cancel fences late model result and duplicate operation; secrets clear', async () => { + const f = fixture(); + try { + addProvider(f.directory, 'Fixture', 'secret', f.backend, 'openai', 'https://api.openai.com/v1'); + await f.service.request({ action: 'reload' }); + let finish!: (value: any) => void; + f.deps.credential = () => new Promise(resolve => finish = resolve); + const id = f.service.snapshot().rows[0]!.id; + const pending = f.service.request({ action: 'models', provider: id }); + assert.equal(await f.service.request({ action: 'models', provider: id }), false); + f.service.cancel(); finish({ models: ['late'] }); + assert.equal(await pending, false); assert.deepEqual(f.service.snapshot().models, []); + assert.match(f.service.snapshot().message, /may already be saved/); + } finally { f.close(); } +}); diff --git a/beehive/test/provider-tui-fixture-child.ts b/beehive/test/provider-tui-fixture-child.ts new file mode 100644 index 0000000000..e67ab52dc9 --- /dev/null +++ b/beehive/test/provider-tui-fixture-child.ts @@ -0,0 +1,31 @@ +// Explicit test executable only. No native credential or network operations. +import { ProviderService } from '../src/provider-service.ts'; +import { addProvider, editProvider, type ProviderCredentials } from '../src/settings-credentials.ts'; +import { join } from 'node:path'; +const home = process.env.BEEHIVE_HOME; +if (!home || !home.includes('provider-tui-fixture-')) throw Error('Explicit fixture root required'); +const directory = join(home, '.beehive', 'host'); +const keys = new Map(); +const backend: ProviderCredentials = { read: ref => keys.get(ref.account) ?? null, create: (ref, value) => { keys.set(ref.account, value); } }; +const service = new ProviderService(home, process.env, { + credential: async (input: any, signal) => { + if (input.action === 'add-provider') addProvider(directory, input.name, input.secret, backend, input.type, input.endpoint, input.wire); + else if (input.action === 'edit-provider') editProvider(directory, input.provider, input.revision, input.name, input.endpoint, input.wire, input.secret ?? '', backend); + else if (input.action === 'models') { + await new Promise(resolve => setTimeout(resolve, 400)); signal.throwIfAborted(); + // A deterministic failure enables real TUI retry/correction exercise. + if ([...keys.values()].includes('deny')) throw Error('Fixture denial'); + return { models: ['gpt-fixture', 'gpt-other'] }; + } else throw Error('Unexpected fixture operation'); + return { ok: true }; + }, + native: async (_input, signal) => { signal.throwIfAborted(); return { ok: true, models: ['databricks-fixture'] }; }, + discover: async () => ['codex', 'pi'].map(id => ({ id, label: id === 'pi' ? 'Pi' : 'Codex', executable: `/fixture/${id}-acp`, cli: `/fixture/${id}`, state: 'available' as const, providers: id === 'pi' ? ['openai', 'databricks_v2'] : ['openai'], reason: 'Synthetic installed adapter' })), +}); +service.subscribe(snapshot => process.send?.({ type: 'snapshot', snapshot })); +process.on('message', async (message: any) => { + if (message.type === 'secret') service.secret(message.action, message.value); + else if (message.type === 'cancel') service.cancel(); + else if (message.type === 'request') process.send?.({ type: 'result', id: message.id, ok: await service.request(message.request) }); +}); +process.on('disconnect', () => { service.dispose(); process.exit(); }); diff --git a/beehive/test/provider-tui-fixture.ts b/beehive/test/provider-tui-fixture.ts new file mode 100644 index 0000000000..d86ab277f0 --- /dev/null +++ b/beehive/test/provider-tui-fixture.ts @@ -0,0 +1,9 @@ +// Real OpenTUI + real Node IPC/controller; synthetic external authorization only. +import { createCliRenderer } from '@opentui/core'; +import { OpenTuiShell } from '../src/opentui-shell.ts'; +import { localHarnessInventory } from '../src/harness-inventory.ts'; +import { localProviders } from '../src/provider-client.ts'; +if (!process.env.BEEHIVE_HOME?.includes('provider-tui-fixture-')) throw Error('Explicit fixture root required'); +const renderer = await createCliRenderer({ exitOnCtrlC: false, screenMode: 'alternate-screen', consoleMode: 'disabled', openConsoleOnError: false }); +const shell = new OpenTuiShell(renderer, localHarnessInventory(), undefined, localProviders({ helper: new URL('./provider-tui-fixture-child.ts', import.meta.url) })); +try { await shell.done; } finally { shell.close(); } diff --git a/beehive/test/shell-opentui.test.ts b/beehive/test/shell-opentui.test.ts index bcb46d8c9e..ab2295cf5c 100644 --- a/beehive/test/shell-opentui.test.ts +++ b/beehive/test/shell-opentui.test.ts @@ -89,14 +89,14 @@ test('memory renderer layers a full scrim and naturally sized help surface with try { ui.mockInput.pressKey('?'); await ui.renderOnce(); const geometry = helpDialogGeometry(120, 40); - assert.deepEqual(geometry, { width: 62, maxHeight: 36, naturalHeight: 15, height: 15, bodyHeight: 7, bodyWidth: 56, scrollbar: false }); + assert.deepEqual(geometry, { width: 62, maxHeight: 36, naturalHeight: 18, height: 18, bodyHeight: 10, bodyWidth: 56, scrollbar: false }); assert.equal(rgb(cell(ui, 0, 0).bg), '7,9,7'); // scrim covers cells outside the dialog assert.equal(rgb(cell(ui, 30, 14).bg), '13,16,14'); // surface is above the scrim assert.equal(rgb(cell(ui, 29, 13).fg), '156,164,155'); // centered dialog boundary // A longer body is constrained to H - 4 while title/actions retain their fixed rows. const overflowing = Array.from({ length: 12 }, (_, row) => `overflow row ${row}`).join('\n'); assert.deepEqual(helpDialogGeometry(50, 20, overflowing), { width: 46, maxHeight: 16, naturalHeight: 20, height: 16, bodyHeight: 8, bodyWidth: 39, scrollbar: true }); - assert.equal(helpDialogGeometry(50, 20).height, 15); // short help stays natural, below its max of 16 + assert.equal(helpDialogGeometry(60, 20).height, 16); // added provider controls scroll at the supported minimum } finally { shell.close(); } }); diff --git a/beehive/test/shell-providers.test.ts b/beehive/test/shell-providers.test.ts new file mode 100644 index 0000000000..bd2d0e3530 --- /dev/null +++ b/beehive/test/shell-providers.test.ts @@ -0,0 +1,57 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createTestRenderer } from '@opentui/core/testing'; +import { OpenTuiShell } from '../src/opentui-shell.ts'; +import { HarnessInventoryController } from '../src/harness-inventory.ts'; +import type { ProviderClient, ProviderRequest, ProviderSnapshot } from '../src/provider-protocol.ts'; +import { ProviderDialog } from '../src/provider-dialog.ts'; + +function fixture() { + const requests: ProviderRequest[] = []; + const secrets: string[] = []; + const snapshot: ProviderSnapshot = { revision: 1, rows: [{ id: 'p', name: 'Fixture', type: 'openai', endpoint: 'https://api.openai.com/v1', state: 'SAVED', detail: 'Access untested' }], phase: 'idle', message: 'Select a provider.', secretLength: 0, models: [] }; + const listeners = new Set<(s: ProviderSnapshot) => void>(); + const client: ProviderClient = { + snapshot: () => structuredClone(snapshot), + subscribe(fn) { listeners.add(fn); fn(structuredClone(snapshot)); return () => { listeners.delete(fn); }; }, + async request(request) { requests.push(request); return true; }, + secret(action, value) { if (value) secrets.push(value); snapshot.secretLength = action === 'clear' ? 0 : action === 'backspace' ? Math.max(0, snapshot.secretLength - 1) : snapshot.secretLength + (value?.length ?? 0); for (const fn of listeners) fn(structuredClone(snapshot)); }, + cancel() {}, dispose() {}, + }; + const inventory = new HarnessInventoryController({ read: () => ({ version: 1, revision: 0, agents: [], providers: [], runtimes: [] }), save: candidate => candidate }, async () => []); + return { client, inventory, requests, secrets }; +} +for (const [width, height] of [[120, 40], [60, 20]]) test(`Providers signed-out keyboard actions and modal at ${width}x${height}`, async () => { + const ui = await createTestRenderer({ width, height, exitOnCtrlC: false }), f = fixture(); + const shell = new OpenTuiShell(ui.renderer, f.inventory, undefined, f.client); + try { + for (let i = 0; i < 3; i++) ui.mockInput.pressArrow('right'); + ui.mockInput.pressEnter(); await ui.renderOnce(); + assert.match(ui.captureCharFrame(), /Add provider/); + ui.mockInput.pressArrow('up'); ui.mockInput.pressTab(); await ui.renderOnce(); + assert.equal(shell.state.focus, 'detail'); + assert.match(ui.captureCharFrame(), /Test provider/); + ui.mockInput.pressArrow('down'); ui.mockInput.pressEnter(); await ui.renderOnce(); + assert.deepEqual(f.requests.at(-1), { action: 'test', provider: 'p', revision: 1 }); + ui.mockInput.pressArrow('up'); ui.mockInput.pressEnter(); await ui.renderOnce(); + assert.match(ui.captureCharFrame(), /EDIT PROVIDER/); + ui.mockInput.pressTab(); await ui.renderOnce(); + ui.mockInput.typeText('never-render-this-key'); await ui.renderOnce(); + assert.doesNotMatch(ui.captureCharFrame(), /never-render-this-key/); + assert.ok(f.secrets.length > 0); + ui.mockInput.pressEnter(); ui.mockInput.pressEnter(); await ui.renderOnce(); + await new Promise(resolve => setTimeout(resolve, 10)); + assert.equal(f.requests.at(-1)?.action, 'save'); + assert.doesNotMatch(JSON.stringify(f.requests), /never-render-this-key/); + } finally { shell.close(); } +}); +test('form input preserves q as text and cancellation clears secret without save', async () => { + const ui = await createTestRenderer({ width: 60, height: 20, exitOnCtrlC: false }); + const calls: string[] = []; + const dialog = new ProviderDialog(ui.renderer, 'ADD PROVIDER', [{ label: 'Name', value: '' }, { label: 'API key', secret: true }], action => calls.push(action)); + try { + dialog.key({ name: 'q', sequence: 'q', ctrl: false, shift: false, meta: false }); + assert.equal(dialog.fields[0]?.value, 'q'); + dialog.cancel(); assert.equal(await dialog.done, undefined); assert.deepEqual(calls, ['clear']); + } finally { ui.renderer.destroy(); } +});