feat(beehive): configure agents directly and resume contextual sign-in

Signed-off-by: Logan Johnson <loganj@squareup.com>
This commit is contained in:
Logan Johnson
2026-09-16 15:19:28 -04:00
parent d216bbed7e
commit 4d87740f8f
18 changed files with 499 additions and 190 deletions

View File

@@ -1,74 +1,108 @@
# Revised manager UX — partial implementation checkpoint
# Revised manager UX — direct agent configuration
Delegation 5b89d3b2; base 9aef40a3f626200ef1a702c64e315cad5339f2d3.
**Not a delivery candidate. Do not install this checkpoint.**
Completes the manager continuation from d216bbe (previously a local checkpoint).
No installation is performed by this continuation.
Implemented:
- Removed the separate Controls frame altogether. The right-hand Details border
now encloses the report scroll and bounded, borderless action viewport. Tab/a,
focused `[Actions]`, keyboard selection and pointer activation remain real.
- Production Agents row generation groups directory rows under Registered agents
and Other agents using saved registration custody, with a Register agent row at
the top of Registered agents. Other-agent details offer Register agent.
- Both profile preview and registration reject a key differing from the selected
Other agent even without a Start continuation. Generic registration still permits
deliberate selection of a new identity.
- Removed the selectable Quit action; retained quit keys. Named Refresh harnesses.
## Data flow and compatibility
No settings schema, retained configuration, credential custody, transport, provider
or native implementation changed. Existing runtime workflows are still present.
- Registered-agent Details exposes Configure. Registration first verifies the
selected agent's canonical matching nsec, then collects harness, provider,
model, effort and environment. There is no configuration name or runtime
chooser/setup/navigation. Start of an unregistered agent still registers first.
- Direct submissions create immutable backing definitions in the existing
append-only settings catalog. These are real saved host-loadable definitions,
not ephemeral display rows. Existing runtime records, credential references,
registrations, host bindings, instructions and history remain retained.
- On an existing local slot, Configure awaits the exact host-loaded binding and
submits authenticated revision-checked Save. Host selectedNext remains the
authority; an active run is not mutated. Registration-to-Start still waits for
enrollment/Save receipts and a matching report before Start. Cancellation,
late completion, unknown results and stale selection remain fenced.
- Configure is host-local, matching credential/binding custody. Move selects the
destination and uses that destination's saved future configuration; a destination
needing setup is configured there through the same direct registration flow.
No credentials or bindings are copied between hosts. Existing Move authorization,
source teardown, destination preparation and late-grant rules are unchanged.
- Discovered harness inventory is now optional durable metadata in settings.json;
historical catalogs without that field still load. Refresh harnesses invokes
real discovery and retains providers and immutable agent definitions. It never
silently selects a configuration or restarts a run.
- A valid process DATABRICKS_HOST is normalized into a durable public workspace
reference without credentials, browser or model calls. The normal secure native
path remains responsible for authentication when needed. Reopen reuses the
reference instead of creating another provider.
- Signed-out Agents directly contains sign-in choices. Protected controller
requests return a contextual sign-in requirement, and protected section
navigation resumes after successful sign-in. Cancellation restores the prior
section without Working. Signed-in Agents has no standing sign-in menu.
Buzz first use still derives owner/normal Host relay in one selection; manual
import accepts matching nsec and saved-owner sign-in uses the retained key.
- One Details border encloses report and actions; no third Controls frame or
selectable Quit. q remains. Registered/Other grouping includes saved identities
absent from the current directory. Pointer-opened inputs now retain focus after
mouse dispatch (a real walkthrough finding, with a renderer regression).
## Evidence
## Focused validation
Direct Node 24.15.0 package typecheck passes. Direct Bun 1.4.2 renderer: 8/8.
Focused Node registration/navigation: 15/15. Renderer includes 100x30 long report,
keyboard and pointer actions, unchanged-refresh report scroll AND selected action
focus retention, overflow, narrow layout and hidden-input/quit ownership. This is
renderer evidence, not the requested complete actual-launcher walkthrough.
Direct Node 24.15.0 typecheck; controller/navigation **18/18**; form boundaries
**3/3**; Buzz custody/first-use/late completion **4/4**; direct Bun 1.4.2 renderer
**9/9**. The controller flow checks direct registration, active snapshot
immutability across Configure, remembered providers/harnesses/definitions, next
Start, signed-out authority and environment Databricks. Existing focused Move,
registration cancellation and late receipt tests remain included.
Logs: `/Users/loganj/.buzz/artifacts/beehive-revised-5b89d3b2/`.
The first renderer run exposed old-coordinate expectations after removing borders;
the final action viewport retains the old usable row count (without a third frame)
and those existing coordinate assertions pass. One initial typecheck fixture lacked
required Settings fields; corrected the fixture rather than weakening its type.
No full-package run attempted; inherited timed-out/non-green baseline is unchanged.
Two actual **100×30 shell-launcher** workflows use the existing first-use PTY
and registration/manager loader fixtures, with fresh explicit
`beehive-pairing-cli-` homes and credential files:
Reproduce focused controller tests from repository root (fresh isolated fixture;
no production keychain/provider/service/relay operations):
1. Signed-out Agents choices; contextual Harnesses sign-in cancellation and
restoration; one Buzz selection resumes Harnesses; q/exit0/terminal restoration.
2. No controller owner or backing configuration initially; contextual Buzz sign-in;
environment Databricks visible; actual provider Save; Refresh harnesses;
separate Registered/Other; Start of known Other agent; matching nsec; direct
harness/provider/model/effort/environment; running; Configure; Stop; actual
launcher/controller reopen; remembered catalog and credentials; next Start;
Stop; q/exit0/terminal restoration. Detail actions are pointer-driven and fields
are keyboard-driven. Controller tests additionally verify old active snapshots
remain byte-identical and next Start selects the new saved binding.
Only synthetic loopback relay, credential backend and external ACP fixture are
used. The native OAuth, production service/discovery and provider boundaries are
fenced. No production Keychain, provider, relay, browser, harness or host operation;
no native rebuild. Shell-launcher staging is under artifacts, not an installation.
Evidence directory: `/Users/loganj/.buzz/artifacts/beehive-direct-28618049/`.
Includes typecheck/focused/form/renderer/Buzz logs and actual shell smoke logs.
Initial iterations retained there include stale old-navigation expectations,
using the manager loader for a form-only file with additional exports, and the
pointer-focus failure. The first successful first-use driver also found a cleanup
attempt against an already-exited process; cleanup now checks its owned child.
None is represented as a production credential failure or a green broad suite.
**The inherited 400-second incomplete/non-green full-suite result remains open.**
No broad rerun, inherited-failure triage or repository-wide CI claim.
## Portable laptop-first smoke after separately guarded installation
Larry dispatches laptop installation first. From the exact installed package
root (not a production HOME), run its committed synthetic driver against the
actual installed launcher:
```sh
NODE=/path/to/node-24.15.0/bin/node
ROOT=$PWD
FIXTURE=$(mktemp -d /tmp/beehive-pairing-cli-revised-XXXXXX)
BEEHIVE_TEST_CREDENTIAL_FILE="$FIXTURE/credentials.json" \
NODE_OPTIONS="--import=$ROOT/beehive/test/manager-installed-loader.ts" \
BEEHIVE_TEST_REGISTRATION_WALKTHROUGH=1 \
"$NODE" --test beehive/test/registration-start.test.ts beehive/test/manager-navigation.test.ts
"$NODE" beehive/node_modules/typescript/bin/tsc --noEmit -p beehive
(cd beehive && /path/to/bun-1.4.2 test ./test/opentui-screen.bun.ts)
cd /absolute/path/to/installed/beehive
export BEEHIVE_SMOKE_NODE="$PWD/runtime/node"
export BEEHIVE_BUN="$PWD/runtime/bun"
export BEEHIVE_SMOKE_LAUNCHER="$PWD/bin/beehive"
"$BEEHIVE_SMOKE_NODE" --version # v24.15.0
"$BEEHIVE_BUN" --version # 1.4.2
/usr/bin/python3 test/buzz-first-use-smoke.py
BEEHIVE_SMOKE_DIRECT=1 /usr/bin/python3 test/buzz-first-use-smoke.py
```
## Required next work before publishing/installing
1. Evolve selected-next configuration API to accept harness/provider/model/effort/
environment directly. Replace runtimeForm/name/chooser paths, registration's
saved-runtime prerequisite, and Move's runtime selection. Preserve immutable
saved records and active-run snapshots; do not implement UI-only fake runtimes.
2. Complete grouped Agents behavior for saved registrations absent from current
directory results. Group header rows currently use ordinary list navigation.
3. Contextual sign-in chooser at actual authority boundaries; signed-out sign-in
choices directly in Agents list. Verify Buzz first use without preconfigured
owner, preserving its single-selection flow.
4. Remember/discover harness state on reopen, and project env Databricks availability
using existing `databricksHost` URL validation and secure provider references.
Current addDatabricks only saves a workspace/reference (no immediate login);
do not accidentally add credential reads to passive render.
5. Extract/test actual production menu generation (existing renderer overflow test
is explicitly only a generic stress fixture), then one complete isolated 100x30
actual-launcher walkthrough using adapted existing loaders. Do not claim the
preconfigured-owner registration fixture proves Buzz first use.
6. Self-review full flow, ordinary signed-off commit/publish and exact remote-head
verification; then request separate laptop-first guarded installation. No native
rebuild needed unless subsequent code changes native sources.
This run does not push or install. Laptop/current remains the prior 9aef40a build.
The driver constructs a closed child environment, explicit credential fixture,
NODE_OPTIONS --import manager loader and fresh HOME itself. It prints each
surviving fixture root, with ANSI and reconstructed frames. The direct workflow
reopens that same synthetic home to verify saved configuration. Do not substitute
production credentials, loosen loader fences, or interpret fixture readiness as
real provider/relay approval. Install/publish provenance and exact head belong in
the delivery post, not a moving hash embedded in this document.

View File

@@ -53,3 +53,12 @@ export async function addDatabricks(directory: string, name: string, endpoint: s
signal.throwIfAborted();
return saveSettings(directory,{ ...previous,providers:[...previous.providers,{ id,name,type:'databricks_v2',endpoint,key }] },previous.revision);
}
/** Project an environment workspace into the durable public provider catalog without authentication. */
export function rememberEnvironmentDatabricks(directory: string, value: string | undefined) {
if (!value) return;
const endpoint = databricksHost(value), previous = readSettings(directory);
if (previous.providers.some(p => p.type === 'databricks_v2' && p.endpoint === endpoint)) return;
const id = settingsId();
saveSettings(directory, { ...previous, providers: [...previous.providers, { id, name: 'Databricks', type: 'databricks_v2', endpoint, key: { service: 'beehive', account: `provider:${id}` } }] }, previous.revision);
}

View File

@@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { fetchRelayDirectory, type DirectoryAgent } from './relay-directory.ts';
import { runtimeEnvironment } from './runtime-environment.ts';
import { addDatabricks, databricksNative } from './databricks.ts';
import { addDatabricks, databricksNative, databricksHost, rememberEnvironmentDatabricks } from './databricks.ts';
import { existsSync } from 'node:fs';
import { readSettings, saveSettings, settingsId, type Settings, type RegisteredAgent } from './settings.ts';
import { agentNsec } from './settings-credentials.ts';
@@ -26,12 +26,13 @@ import { profileDrafts, editProfileDraft } from './profile-drafts.ts';
/** Controller completion is not a host receipt: submitted work remains pending. */
export type ManagerResult =
| { state: 'completed' }
| { state: 'signin-required' }
| { state: 'submitted'; operationId: string }
| { state: 'registration-required'; continuation: string; agent: string }
| { state: 'failed' | 'cancelled' | 'ignored'; reason: string };
export type ManagerRequest = { id: number; action: string; values?: Record<string, string>; target?: string; revision?: number };
export type ManagerItem = { names?: { agent?: string; host?: string; startHost?: string }; startTarget?: string; startRevision?: number; target?: string; id: string; label: string; detail: string; evidence?: string; disabled?: Record<string, string> };
export type ManagerItem = { configuration?: Record<string,string>; names?: { agent?: string; host?: string; startHost?: string }; startTarget?: string; startRevision?: number; target?: string; id: string; label: string; detail: string; evidence?: string; disabled?: Record<string, string> };
export type MoveDestination = { target: string; revision: number; label: string; reason?: string };
export type ManagerSnapshot = { managementRelay?: 'connected' | 'disconnected'; diagnostics?: ManagerItem[]; local: ManagerItem[]; agents: (ManagerItem & { revision: number; configurations: string[]; destinations?: MoveDestination[] })[]; routing?: { owner: string; relay: string }; owner?: string; status: string; settings?: Settings; service?: ServiceStatus; hostRelay?: string; relayName?: string; profilePreview?: RegisteredAgent; models?: string[]; modelLabels?: Record<string,string>; runtimeExecutable?: string; harnesses?: DetectedHarness[]; databricksHost?: string };
const short = (s: string) => s.length > 22 ? `${s.slice(0,8)}…${s.slice(-6)}` : s;
@@ -127,7 +128,7 @@ const describe = (v: unknown, labels: Record<string, string> = {}, path = ''): s
return /^[0-9a-f]{32,}$/i.test(v) ? short(v) : v;
}
if (!Object.keys(v).length) return 'Not reported';
return Object.entries(v).map(([k, value]) => {
return Object.entries(v).filter(([k]) => k !== 'harnessSetup').map(([k, value]) => {
const child = path ? `${path}.${k}` : k;
const rendered = describe(value, labels, child);
if (labels !== availabilityLabels && inlineChoice.has(child) && value !== null && !Array.isArray(value) && typeof value === 'object') return rendered;
@@ -171,10 +172,26 @@ export class ManagerController {
private fetchName: typeof fetchRelayName;
constructor(home: string, changed: (snapshot: ManagerSnapshot) => void,
credential = managerCredential, connect = managementClient, fetchName = fetchRelayName, directoryRead = fetchRelayDirectory, profileRead = fetchAgentProfile) {
this.home = home; this.changed = changed; this.credential = credential; this.connect = connect; this.fetchName = fetchName; this.directoryRead = directoryRead; this.profileRead = profileRead;
this.home = home;
try { rememberEnvironmentDatabricks(this.hostDirectory, process.env.DATABRICKS_HOST); } catch { this.status = 'Databricks workspace configuration needs attention.'; }
try { this.harnesses = readSettings(this.hostDirectory).harnesses; } catch { /* Snapshot reports retained configuration errors. */ }
this.changed = changed; this.credential = credential; this.connect = connect; this.fetchName = fetchName; this.directoryRead = directoryRead; this.profileRead = profileRead;
}
private get hostDirectory() { return join(this.home, '.beehive', 'host'); }
private get ownerDirectory() { return join(this.home, '.beehive', 'owner'); }
private directConfiguration(value: unknown): Record<string,string> | undefined {
const selected = value as { harnessSetup?: { id?: string } } | undefined;
const settings = readSettings(this.hostDirectory);
const runtime = settings.runtimes.find(r => selected?.harnessSetup?.id === `runtime:${r.id}`);
if (!runtime) return;
return { harness: runtime.harness, provider: runtime.providerId, model: runtime.model, effort: runtime.effort ?? 'Inherit', environment: JSON.stringify(runtime.environment ?? {}) };
}
private configurationDescription(value: unknown) {
const fields = this.directConfiguration(value);
if (!fields) return describe(value, selectionLabels);
const provider = readSettings(this.hostDirectory).providers.find(p => p.id === fields.provider);
return `Harness: ${fields.harness}\nProvider: ${provider?.name ?? 'Unavailable'}\nModel: ${fields.model}\nEffort: ${fields.effort}\nEnvironment: ${Object.keys(JSON.parse(fields.environment!)).join(', ') || 'None'}`;
}
snapshot(): ManagerSnapshot {
const local: ManagerSnapshot['local'] = [];
try {
@@ -195,10 +212,10 @@ Reported status: ${m.body.phase}
Assigned host: ${m.body.assignedHost === m.host ? 'Assigned to this host' : 'Not assigned to this host'}
Current run (host report)
${m.body.actualRun ? describe(m.body.actualRun, runLabels) : 'No current run in this report'}
${m.body.actualRun ? this.configurationDescription((m.body.actualRun as {selection?:unknown}).selection ?? m.body.actualRun) : 'No current run in this report'}
Configuration for next start
${describe(m.body.selectedNext, selectionLabels)}
${this.configurationDescription(m.body.selectedNext)}
This choice does not change the current run.` };
});
const agents: ManagerSnapshot['agents'] = this.directory.map(agent => {
@@ -208,7 +225,7 @@ This choice does not change the current run.` };
try { registered = readSettings(this.hostDirectory).agents.some(a => a.publicKey === agent.publicKey); } catch { /* Configuration error is shown in Local Host. */ }
const local = this.localEnrollmentTarget(agent.publicKey);
const unavailable = 'No unique assigned host report. Execution authority is unknown.';
return { names: { agent: agent.name && agent.name !== agent.publicKey ? agent.name : short(agent.publicKey), host: report ? String((this.offers.get(report.host)?.body.configuration as {label?: string})?.label || short(report.host)) : undefined, startHost: local ? readHostIdentityPublic(this.hostDirectory).pairing.label : undefined }, startTarget: local, startRevision: local ? -1 : undefined, destinations: report ? this.moveDestinations(report) : [], id:agent.publicKey,target:shown?.id,label:`${agent.name} · ${shown ? this.fresh(report!) ? report!.body.phase : 'Unknown' : 'Unknown'}`,revision:shown?.revision ?? -1,configurations:shown?.configurations ?? [],disabled: { ...(shown?.disabled ?? { start:unavailable,stop:unavailable,restart:unavailable,move:unavailable,'select-config':unavailable }), ...(local ? {start:''} : {}) },evidence:JSON.stringify({ discovery:agent,report },null,2),detail:`${agent.name}
return { configuration: report ? this.directConfiguration(report.body.selectedNext) : undefined, names: { agent: agent.name && agent.name !== agent.publicKey ? agent.name : short(agent.publicKey), host: report ? String((this.offers.get(report.host)?.body.configuration as {label?: string})?.label || short(report.host)) : undefined, startHost: local ? readHostIdentityPublic(this.hostDirectory).pairing.label : undefined }, startTarget: local, startRevision: local ? -1 : undefined, destinations: report ? this.moveDestinations(report) : [], id:agent.publicKey,target:shown?.id,label:`${agent.name} · ${shown ? this.fresh(report!) ? report!.body.phase : 'Unknown' : 'Unknown'}`,revision:shown?.revision ?? -1,configurations:shown?.configurations ?? [],disabled: { ...(shown?.disabled ?? { start:unavailable,stop:unavailable,restart:unavailable,move:unavailable,'select-config':unavailable }), ...(local ? {start:''} : {}) },evidence:JSON.stringify({ discovery:agent,report },null,2),detail:`${agent.name}
Agent: ${agent.publicKey}
Registered here: ${registered ? 'Yes' : 'No'}
Relay presence: ${agent.status} (discovery only)
@@ -247,11 +264,11 @@ A Stop result is not a recent host report that confirms the agent is stopped.` }
const target = JSON.stringify([offer.host,source.agent]), report = this.inventory.get(target);
const label = String((offer.body.configuration as {label?:string})?.label ?? short(offer.host));
let reason: string | undefined;
if (!this.fresh(offer) || !report || !this.fresh(report)) reason = `On ${label}, register this agent with a local runtime, use local Start to enroll it, then Stop and Refresh. No credentials are transferred.`;
if (!this.fresh(offer) || !report || !this.fresh(report)) reason = `On ${label}, register this agent with a local configuration, use local Start to enroll it, then Stop and Refresh. No credentials are transferred.`;
else if (report.body.localKey !== 'present') reason = `On ${label}, stop its host service and run beehive import-agent-key <host-directory> ${source.agent}. Enter the matching key only there, restart that host and Refresh. Source will not stop.`;
else if (report.body.phase !== 'stopped' || report.body.actualRun) reason = 'Destination is not an eligible stopped standby.';
const selected = report?.body.selectedNext as {harnessSetup?:{id:string}; model?:string} | undefined;
return {target,revision:report?.revision ?? -1,label:`${label} · ${selected?.harnessSetup?.id ?? 'default runtime'} · ${selected?.model ?? 'setup required'}`,reason};
return {target,revision:report?.revision ?? -1,label:`${label} · ${selected?.model ?? 'setup required'}`,reason};
});
}
private operationStatus() { return this.client?.status() ?? []; }
@@ -291,6 +308,16 @@ A Stop result is not a recent host report that confirms the agent is stopped.` }
if (!this.closed) this.changed(this.snapshot());
});
}
/** Append an immutable backing configuration; host Save remains selected-next authority. */
private saveAgentConfiguration(values: Record<string,string>) {
const selected = this.harnesses?.find(h => h.id === values.harness);
const previous = readSettings(this.hostDirectory);
const provider = previous.providers.find(p => p.id === values.provider);
if (!selected?.executable || !provider || !selected.providers.includes(provider.type) || !['buzz-agent','codex','pi'].includes(selected.id)) throw plain('Select an available harness and provider.');
const runtime = { id: settingsId(), name: 'Agent configuration', harness: selected.id as 'buzz-agent' | 'codex' | 'pi', executable: selected.executable, ...(['codex','pi'].includes(selected.id) ? { cli: selected.cli } : {}), providerId: provider.id, model: values.model ?? '', ...(values.environment ? { environment: runtimeEnvironment(JSON.parse(values.environment)) } : {}), ...(values.effort ? { effort: values.effort } : {}) };
saveSettings(this.hostDirectory, { ...previous, runtimes: [...previous.runtimes, runtime] }, previous.revision);
return runtime;
}
refresh() {
if (this.closed) return;
this.changed(this.snapshot());
@@ -304,6 +331,7 @@ A Stop result is not a recent host report that confirms the agent is stopped.` }
async request(request: ManagerRequest): Promise<ManagerResult> {
if (this.closed || request.id <= this.lastId || this.active) return { state: 'ignored', reason: 'Request is closed, duplicate, or busy.' };
this.lastId = request.id;
if (!this.owner && !['refresh','configure','host-start','host-stop','signin','signin-buzz','signout','retire-continuation'].includes(request.action)) return { state: 'signin-required' };
const abort = new AbortController(); this.active = abort;
const generation = ++this.generation;
const check = () => { abort.signal.throwIfAborted(); if (this.closed || generation !== this.generation) throw plain('Stopped waiting. Changes may already be saved or submitted. Inspect before you try again.'); };
@@ -327,18 +355,19 @@ A Stop result is not a recent host report that confirms the agent is stopped.` }
const pending = this.continuation;
if ((pending || v.continuation) && (!pending || pending.token !== v.continuation || pending.agent !== key)) throw plain('Start selection changed. No operation was sent.');
if (this.profilePreview?.publicKey !== key) throw plain('Confirm the public key first.');
const settings = readSettings(this.hostDirectory), runtime = settings.runtimes.find(r => r.id === v.runtime);
if (!runtime) throw plain('Select a saved runtime.');
const settings = readSettings(this.hostDirectory);
let runtime = settings.runtimes.find(r => r.id === v.runtime);
if (pending?.enroll) {
if (settings.revision !== pending.settingsRevision || this.localEnrollmentTarget(key) !== pending.target) throw plain('Local enrollment selection changed. Start again.');
} else if (pending) {
const report = this.agentReport(key);
if (settings.revision !== pending.settingsRevision || !report || !this.fresh(report) || JSON.stringify([report.host,report.agent]) !== pending.target || report.revision !== pending.revision || report.body.phase !== 'stopped' || report.body.actualRun) throw plain('Settings or host selection changed. Start again.');
}
runtime ??= this.saveAgentConfiguration(v);
const { profile, profileState } = this.profilePreview;
await this.credential({ action: 'register-agent', directory: this.hostDirectory, secret: v.secret, profile: { profile, profileState }, runtimeId:runtime.id, expectedRevision:settings.revision },abort.signal); check();
await this.credential({ action: 'register-agent', directory: this.hostDirectory, secret: v.secret, profile: { profile, profileState }, runtimeId:runtime.id, expectedRevision:readSettings(this.hostDirectory).revision },abort.signal); check();
this.profilePreview = undefined;
if (!pending) this.status = 'Agent and runtime registered. Not assigned or started.';
if (!pending) this.status = 'Agent registered. Configuration saved.';
else {
const guard = () => {
check();
@@ -374,7 +403,7 @@ A Stop result is not a recent host report that confirms the agent is stopped.` }
if (binding) break;
await delay(100,undefined,{signal:abort.signal});
}
if (!binding) throw plain('Runtime is saved but not loaded by the host. No Start sent.');
if (!binding) throw plain('Configuration is saved but not loaded by the host. No Start sent.');
const noPending = () => { if (this.client!.status().some(o => o.request.host === report.host && o.request.agent === report.agent && !['completed','failed'].includes(o.state))) throw plain('Another operation has no confirmed result. No Start sent.'); };
noPending();
const selected = report.body.selectedNext as Record<string,unknown>;
@@ -385,34 +414,48 @@ A Stop result is not a recent host report that confirms the agent is stopped.` }
for (let n=0;n<100;n++) {
guard();
const operation = this.client!.status().find(o => o.request.id === save.id);
if (!operation || ['failed','unknown'].includes(operation.state)) throw plain('Runtime selection failed or is unknown. No Start sent. Inspect operations.');
if (!operation || ['failed','unknown'].includes(operation.state)) throw plain('Configuration selection failed or is unknown. No Start sent. Inspect operations.');
report = current();
if (operation.state === 'completed' && report.revision === pending.revision+1) {
const selection = report.body.selectedNext as {model?:string;harnessSetup?:{id?:string;fingerprint?:string}};
if (selection.model !== runtime.model || selection.harnessSetup?.id !== binding.id || selection.harnessSetup.fingerprint !== binding.fingerprint) throw plain('Selected runtime changed. No Start sent.');
if (selection.model !== runtime.model || selection.harnessSetup?.id !== binding.id || selection.harnessSetup.fingerprint !== binding.fingerprint) throw plain('Selected configuration changed. No Start sent.');
applied = true; break;
}
if (report.revision > pending.revision+1) throw plain('Host revision changed. No Start sent.');
await delay(100,undefined,{signal:abort.signal});
}
if (!applied) this.status = `Runtime selection submitted (${save.id}). Start was not sent. Inspect operations.`;
if (!applied) this.status = `Configuration selection submitted (${save.id}). Start was not sent. Inspect operations.`;
else {
guard(); report = current(); noPending();
if (report.revision !== pending.revision+1) throw plain('Host revision changed. No Start sent.');
const start = message('start',report.host,report.agent,report.revision);
this.client!.submit(start); result = {state:'submitted',operationId:start.id};
this.status = `Start submitted (${start.id}). Registration and runtime selection verified. Running state awaits a host report.`;
this.status = `Start submitted (${start.id}). Registration and configuration verified. Running state awaits a host report.`;
}
}
} else if (request.action === 'provider-form') {
this.databricksHost = process.env.DATABRICKS_HOST ?? ''; this.status = 'Provider credentials stay in Beehive’s OS store.';
} else if (request.action === 'add-databricks') {
await addDatabricks(this.hostDirectory,v.name,v.endpoint,abort.signal); check(); this.status = 'Databricks workspace saved. Authentication will be requested only when models or a runtime need it. No agent was started.';
await addDatabricks(this.hostDirectory,v.name,v.endpoint,abort.signal); check(); this.status = 'Databricks workspace saved. Authentication is requested when needed.';
} else if (request.action === 'add-openai' || request.action === 'add-provider') {
await this.credential({ action: request.action, directory: this.hostDirectory, name: v.name, secret: v.secret, type:v.type, endpoint:v.endpoint, wire:v.wire },abort.signal); check(); this.status = 'Provider saved. No agent was started.';
} else if (request.action === 'runtime-form') {
this.runtimeExecutable = undefined; this.harnesses = undefined; this.models = undefined; this.modelLabels = undefined;
const harnesses = await discoverHarnesses(abort.signal); check(); this.harnesses = harnesses;
} else if (request.action === 'runtime-form' || request.action === 'configuration-form') {
if (process.env.DATABRICKS_HOST) {
const endpoint = databricksHost(process.env.DATABRICKS_HOST);
const before = readSettings(this.hostDirectory);
if (!before.providers.some(p => p.type === 'databricks_v2' && p.endpoint === endpoint)) {
await addDatabricks(this.hostDirectory, 'Databricks', endpoint, abort.signal);
if (this.continuation?.settingsRevision === before.revision) this.continuation.settingsRevision = before.revision + 1;
}
check();
}
this.models = undefined; this.modelLabels = undefined;
const harnesses = await discoverHarnesses(abort.signal, { home: this.home }); check();
const previous = readSettings(this.hostDirectory);
saveSettings(this.hostDirectory, { ...previous, harnesses }, previous.revision);
// Discovery changes inventory, not the user's pending Start selection.
if (this.continuation && this.continuation.settingsRevision === previous.revision) this.continuation.settingsRevision = previous.revision + 1;
this.harnesses = harnesses;
this.runtimeExecutable = this.harnesses.find(h => h.id === 'buzz-agent' && h.providers.length)?.executable; this.models = undefined; this.modelLabels = undefined;
this.status = this.harnesses.map(h => `${h.label}: ${h.reason}`).join(' · ');
} else if (request.action === 'models') {
@@ -425,7 +468,7 @@ A Stop result is not a recent host report that confirms the agent is stopped.` }
const provider = previous.providers.find(p => p.id === v.provider);
if (!selected?.executable || !provider || !selected.providers.includes(provider.type) || !['buzz-agent','codex','pi'].includes(selected.id)) throw plain('No supported executable/provider combination found.');
saveSettings(this.hostDirectory,{ ...previous, runtimes: [...previous.runtimes,{ id: settingsId(), name: v.name ?? '', harness: selected.id as 'buzz-agent' | 'codex' | 'pi', executable: selected.executable, ...(['codex','pi'].includes(selected.id) ? { cli: selected.cli } : {}), providerId: v.provider ?? '', model: v.model ?? '', ...(v.environment ? { environment: runtimeEnvironment(JSON.parse(v.environment)) } : {}), ...(v.effort ? { effort: v.effort } : {}) }] },previous.revision);
this.status = 'Runtime saved for new runs. Running agents did not change. Host loading is reported separately.';
this.status = 'Configuration saved for next Start.';
} else if (request.action === 'host-start') {
this.service = await startService(this.hostDirectory); check(); this.status = 'Host running. Registration and settings do not start agents.';
} else if (request.action === 'host-stop') {
@@ -445,7 +488,7 @@ A Stop result is not a recent host report that confirms the agent is stopped.` }
const relay = retained?.relay ?? (request.action === 'signin-buzz'
? readHostIdentityPublic(this.hostDirectory).pairing.relay : v.relay ?? '');
if (!/^(wss|ws):\/\//.test(relay)) throw plain('Enter a relay URL that starts with ws:// or wss://.');
const result = await this.credential({ action: request.action, owner, ...(request.action === 'signin' && v.secret ? { secret: v.secret.toLowerCase() } : {}) }, abort.signal);
const result = await this.credential({ action: request.action, owner, ...(request.action === 'signin' && v.secret ? { secret: v.secret.startsWith('nsec1') ? agentNsec(v.secret) : v.secret.toLowerCase() } : {}) }, abort.signal);
delete v.secret; check();
if (request.action === 'signin-buzz') {
let matches = false;
@@ -506,7 +549,7 @@ A Stop result is not a recent host report that confirms the agent is stopped.` }
} else if (request.action === 'reconcile') { this.client?.reconcile(); this.status = 'Checking operation results. Operations blocked by relay policy will not be retried.';
} else if (request.action === 'operations') {
this.status = this.operationStatus().slice(-5).reverse().map(o => `${plainOperationType(o.request)} · ${plainStates[o.state] ?? o.state} · ${o.request.id.slice(0,8)}\n${operationText(o.result ?? o.publication)}`).join('\n') || 'No saved operations.';
} else if (['start', 'stop', 'restart', 'move', 'select-config', 'select-runtime'].includes(request.action)) {
} else if (['start', 'stop', 'restart', 'move', 'select-config', 'select-runtime', 'configure-agent'].includes(request.action)) {
if (!this.owner || !this.client) throw plain('Owner sign-in required');
if (request.action === 'start') {
const agent = this.directory.find(a => this.localEnrollmentTarget(a.publicKey) === request.target);
@@ -529,7 +572,7 @@ A Stop result is not a recent host report that confirms the agent is stopped.` }
const selected = current.body.selectedNext as {harnessSetup?:{id?:string}};
if (!registered || !settings.runtimes.some(r => selected?.harnessSetup?.id === `runtime:${r.id}`)) {
this.continuation = {token:randomUUID(),agent:current.agent,target:request.target!,revision:current.revision,settingsRevision:settings.revision,owner:this.owner};
this.status = 'Confirm registration and select a runtime before Start.';
this.status = 'Confirm registration and configure the agent before Start.';
return {state:'registration-required',continuation:this.continuation.token,agent:current.agent};
}
}
@@ -561,14 +604,22 @@ A Stop result is not a recent host report that confirms the agent is stopped.` }
this.status = `Move submitted (${operation.id}). Source remains assigned until preparation and verified Stop. Destination launch is reported separately.`;
return {state:'submitted',operationId:operation.id};
}
if (request.action === 'select-runtime') {
if (!existsSync(join(this.hostDirectory,'host-identity.json')) || readHostIdentityPublic(this.hostDirectory).pairing.host !== current.host) throw plain('Select a runtime on its local host.');
const runtime = readSettings(this.hostDirectory).runtimes.find(r => r.id === v.runtime);
const binding = (current.body.harnessSetups as {id:string;fingerprint:string}[] | undefined)?.find(b => b.id === `runtime:${runtime?.id}`);
if (!runtime || !binding) throw plain('Runtime is not loaded by this host. Refresh and try again.');
if (request.action === 'select-runtime' || request.action === 'configure-agent') {
if (!existsSync(join(this.hostDirectory,'host-identity.json')) || readHostIdentityPublic(this.hostDirectory).pairing.host !== current.host) throw plain('Configure on the agent’s local host.');
const runtime = request.action === 'configure-agent' ? this.saveAgentConfiguration(v) : readSettings(this.hostDirectory).runtimes.find(r => r.id === v.runtime);
let binding: {id:string;fingerprint:string} | undefined;
for (let n=0;n<100;n++) {
check();
const report = this.inventory.get(request.target!);
if (!report || !this.fresh(report) || report.revision !== current.revision) throw plain('Host selection changed. Configuration retained; no Save sent.');
binding = (report.body.harnessSetups as {id:string;fingerprint:string}[] | undefined)?.find(b => b.id === `runtime:${runtime?.id}`);
if (binding) break;
await delay(100,undefined,{signal:abort.signal});
}
if (!runtime || !binding) throw plain('Configuration is not loaded by this host. Refresh and try again.');
const save = message('save',current.host,current.agent,current.revision,{ ...(current.body.selectedNext as Record<string,unknown>),model:runtime.model,harnessSetup:{id:binding.id,fingerprint:binding.fingerprint} });
this.client.submit(save);
this.status = `Runtime Save submitted (${save.id}). Current run unchanged; inspect the host result before Start.`;
this.status = `Configuration Save submitted (${save.id}). Current run unchanged; inspect the host result before Start.`;
return {state:'submitted',operationId:save.id};
}
const operation = message(request.action === 'select-config' ? 'save' : request.action as 'start' | 'stop' | 'restart', current.host, current.agent, current.revision, request.action === 'select-config' ? { configurationAction: 'select', name: v.name } : {});

View File

@@ -8,18 +8,24 @@ export function sectionRows(snapshot: ManagerSnapshot, section: number): Manager
const settings = snapshot.settings;
if (section === 0) return snapshot.local.map(row => row.id !== 'host' ? row : ({ ...row, detail: `Host name: ${row.label}\nRelay URL: ${snapshot.hostRelay ?? snapshot.routing?.relay ?? '—'}\nState: ${snapshot.service?.state ?? 'unknown'}\nSaved revision: ${settings?.revision ?? 0}\nLoaded revision: ${snapshot.service?.revision ?? '—'}` }));
if (section === 1) {
if (!snapshot.owner) return [
{ id: 'signin-buzz', label: 'Sign in with Buzz key', detail: 'Sign in with Buzz key' },
{ id: 'signin-saved', label: 'Sign in with saved owner key', detail: 'Sign in with saved owner key' },
{ id: 'signin-import', label: 'Import matching owner key', detail: 'Import matching owner key' },
];
const registered = new Set(settings?.agents.map(agent => agent.publicKey) ?? []);
return [
{ id: 'registered-agents', label: 'Registered agents', detail: 'Registered agents' },
{ id: 'register-agent', label: ' Register agent', detail: 'Register agent' },
...snapshot.agents.filter(agent => registered.has(agent.id)),
...(settings?.agents ?? []).filter(agent => !snapshot.agents.some(row => row.id === agent.publicKey)).map(agent => ({ id: agent.publicKey, label: agent.profile?.name ?? agent.publicKey, detail: 'Registered here · Host unavailable' })),
{ id: 'other-agents', label: 'Other agents', detail: 'Other agents' },
...snapshot.agents.filter(agent => !registered.has(agent.id)),
];
}
if (section === 2) return [
...(snapshot.harnesses ?? []).map(h => ({ id: `harness:${h.id}`, label: `${h.label} · ${h.state}`, detail: `Harness: ${h.label}\nState: ${h.state}\nExecutable: ${h.executable ?? '—'}\nCLI: ${h.cli ?? '—'}` })),
...(settings?.runtimes ?? []).map(r => ({ id: `runtime:${r.id}`, label: r.name, detail: `Runtime: ${r.name}\nHarness: ${r.harness}\nProvider: ${settings?.providers.find(p => p.id === r.providerId)?.name ?? '—'}\nModel: ${r.model}\nEffort: ${r.effort ?? 'Inherit'}\nEnvironment: ${Object.keys(r.environment ?? {}).join(', ') || 'None'}` })),
];
if (section === 3) return (settings?.providers ?? []).map(p => ({ id: p.id, label: p.name, detail: `Provider: ${p.name}\nType: ${p.type}\nEndpoint: ${p.endpoint}` }));
return [];

View File

@@ -1,5 +1,5 @@
import { ManagerNavigation, sectionRows } from './manager-navigation.ts';
import { runtimeForm } from './runtime-form.ts';
import { configurationForm } from './runtime-form.ts';
import { createCliRenderer } from '@opentui/core';
import { createReadStream, createWriteStream } from 'node:fs';
import { createInterface } from 'node:readline';
@@ -17,7 +17,7 @@ let snapshot: ManagerSnapshot = { local: [], agents: [], status: 'Connecting to
const navigation = new ManagerNavigation();
let scope = 0, selected = '', sequence = 0, lastStatus = '';
let pending: { id: number; resolve: (result: ManagerResult) => void } | undefined;
function request(action: string, values?: Record<string,string>, target?: string, revision?: number) {
function rawRequest(action: string, values?: Record<string,string>, target?: string, revision?: number) {
if (pending) return Promise.resolve<ManagerResult>({ state: 'ignored', reason: 'An operation is pending.' });
const id = ++sequence;
const completion = new Promise<ManagerResult>(resolve => { pending = { id, resolve }; });
@@ -26,6 +26,20 @@ function request(action: string, values?: Record<string,string>, target?: string
output.write(JSON.stringify(message) + '\n');
return completion.finally(retire);
}
async function signin() {
if (snapshot.owner) return true;
const choice = await screen.choose('Sign in', ['Buzz key', 'Saved owner key', 'Import matching owner key']);
if (!choice) return false;
if (choice === 'Buzz key') await rawRequest('signin-buzz');
else await routing('signin', choice === 'Import matching owner key');
return !!snapshot.owner;
}
async function request(action: string, values?: Record<string,string>, target?: string, revision?: number): Promise<ManagerResult> {
const result = await rawRequest(action, values, target, revision);
if (result.state !== 'signin-required') return result;
if (!await signin()) return { state: 'cancelled', reason: 'Sign in cancelled.' };
return rawRequest(action, values, target, revision);
}
async function routing(action: string, secret = false) {
const retained = action !== 'configure' ? snapshot.routing : undefined;
let owner = retained?.owner ?? '', relay = retained?.relay ?? '';
@@ -42,7 +56,7 @@ async function routing(action: string, secret = false) {
}
const values: Record<string,string> = { owner, relay };
if (secret) {
const key = await screen.input('Import owner key\nMatching private key (64 hex characters) · OS credential store', '', true);
const key = await screen.input('Import owner key\nMatching nsec · OS credential store', '', true);
if (key === undefined) return;
values.secret = key;
}
@@ -53,18 +67,14 @@ async function routing(action: string, secret = false) {
async function registerForm(continuation?: string, agent?: string) {
let secret = '', settled = false;
try {
const runtimes = snapshot.settings?.runtimes ?? [];
if (!runtimes.length) { screen.notice('Add a provider and runtime in Harnesses, then Start again.'); return; }
const labels = runtimes.map(r => `${r.name} · ${r.model} · ${r.id}`);
const choice = await screen.choose('Runtime',labels); if (choice === undefined) return;
const runtime = runtimes[labels.indexOf(choice)]; if (!runtime) return;
const answer = await screen.input(`Register agent${agent ? `\n${agent}` : ''}\nMatching nsec. Hidden. Saved in Beehive’s OS credential store.`, '', true);
if (answer === undefined) return; secret = answer;
const result = await request('profile-preview',{secret,...(agent ? {agent} : {}),...(continuation ? {continuation} : {})});
if (result.state !== 'completed') { settled = true; return; }
const preview = snapshot.profilePreview; if (!preview) return;
if (!await screen.confirm(`Register agent\n${preview.profile?.name ?? 'Name unavailable'}\n${preview.publicKey}\n${preview.profileState === 'unavailable' ? 'Profile unavailable; public key verified locally.' : preview.profileState === 'none' ? 'No relay profile found.' : ''}\nRuntime: ${runtime.name}\nHarness: ${runtime.harness} · Model: ${runtime.model}\nProvider: ${snapshot.settings?.providers.find(p => p.id === runtime.providerId)?.name ?? 'Unknown'}\nEffort: ${runtime.effort ?? 'Inherit'} · Environment: ${Object.keys(runtime.environment ?? {}).join(', ') || 'None'}\n${continuation ? 'Register and continue Start on the selected host?' : 'Save registration?'}`)) return;
await request('register-agent',{secret,runtime:runtime.id,...(agent ? {agent} : {}),...(continuation ? {continuation} : {})}); settled = true;
const configuration = await configurationForm(screen, () => snapshot, request); if (!configuration) return;
if (!await screen.confirm(`Register agent\n${preview.profile?.name ?? 'Name unavailable'}\n${preview.publicKey}\n${continuation ? 'Register and Start?' : 'Save registration?'}`)) return;
await request('register-agent',{secret,...configuration,...(agent ? {agent} : {}),...(continuation ? {continuation} : {})}); settled = true;
} finally { secret = ''; if (continuation && !settled) await request('retire-continuation'); }
}
function eligibility(action: string) {
@@ -103,7 +113,6 @@ function render() {
if (await screen.confirm(`Save provider\n${name}`)) await request('add-provider',{ name, secret, type:providerType, endpoint, ...(wire ? {wire} : {}) });
secret = '';
} },
{ label: 'Add runtime', run: () => runtimeForm(screen, () => snapshot, request) },
{ label: 'Start', disabled: snapshot.service?.state === 'unknown' ? 'Host ownership is unknown. No process will be adopted.' : undefined, run: async () => {
if (!configured) { await routing('configure'); return; }
if (await screen.confirm('Start host\nLocal host service · Keeps running when you quit')) await request('host-start');
@@ -114,19 +123,10 @@ function render() {
} },
] : snapshot.owner ? [
{ label: 'Refresh agents', run: () => request('directory-refresh') },
{ label: 'Choose runtime…', disabled: eligibility('select-config'), run: async () => {
{ label: 'Configure', disabled: eligibility('select-config'), run: async () => {
const row = snapshot.agents.find(r => r.id === selected); if (!row) return;
const runtimes = snapshot.settings?.runtimes ?? [];
const labels = runtimes.map(r => `${r.name} · ${r.model} · ${r.id}`);
const choice = await screen.choose('Runtime for next start',labels); if (choice === undefined) return;
const runtime = runtimes[labels.indexOf(choice)]; if (!runtime) return;
if (await screen.confirm(`Save runtime\n${runtime.name} · Next Start\n${targetNames(row)}`)) await request('select-runtime',{runtime:runtime.id},row.target,row.revision);
} },
{ label: 'Choose configuration…', disabled: eligibility('select-config'), run: async () => {
const row = snapshot.agents.find(r => r.id === selected); if (!row) return;
const name = await screen.choose('Configuration for next start', row.configurations); if (name === undefined) return;
if (!await screen.confirm(`Save configuration\n${name} · Next Start\n${targetNames(row)}\nRevision: ${row.revision}`)) return;
await request('select-config', { name }, row.target, row.revision);
const configuration = await configurationForm(screen, () => snapshot, request, row.configuration); if (!configuration) return;
if (await screen.confirm(`Save configuration\n${targetNames(row)}\nFor next Start`)) await request('configure-agent',configuration,row.target,row.revision);
} },
...(['start','stop','restart'] as const).map(action => ({ label: action[0]!.toUpperCase() + action.slice(1), disabled: eligibility(action), run: async () => {
const row = snapshot.agents.find(r => r.id === selected); if (!row) return;
@@ -139,7 +139,7 @@ function render() {
const destinations = row.destinations ?? [];
if (!destinations.length) { screen.notice('No destination hosts. Configure and start another host for this owner and relay, then Refresh.'); return; }
const labels = destinations.map(d => `${d.label}${d.reason ? ' · Setup required' : ''}`);
const chosen = await screen.choose('Move · destination host / runtime',labels); if (chosen === undefined) return;
const chosen = await screen.choose('Move · destination host',labels); if (chosen === undefined) return;
const destination = destinations[labels.indexOf(chosen)]; if (!destination) return;
if (destination.reason) { screen.notice(destination.reason); return; }
if (!await screen.confirm(`Move agent\n${targetNames(row)}\nDestination: ${destination.label}
@@ -159,12 +159,11 @@ The source stops before destination launch. Workspace, session and credentials s
if (scope === 1) {
const isAgent = snapshot.agents.some(row => row.id === selected);
const registered = snapshot.settings?.agents.some(agent => agent.publicKey === selected);
if (snapshot.owner && !isAgent) actions = [registerAction, ...actions.filter(action => ['Refresh agents', 'Sign out'].includes(action.label))];
else if (snapshot.owner && !registered) actions.unshift(registerAction);
if (snapshot.owner && !isAgent) actions = [registered ? { label: 'Configure', disabled: 'Host unavailable.', run: () => {} } : registerAction, ...actions.filter(action => ['Refresh agents', 'Sign out'].includes(action.label))];
else if (snapshot.owner && !registered) { actions = actions.filter(a => a.label !== 'Configure'); actions.unshift(registerAction); }
}
if (scope === 2) actions = [
...actions.filter(a => a.label === 'Add runtime'),
{ label: 'Refresh harnesses', run: () => request('runtime-form') },
{ label: 'Refresh harnesses', run: () => request('configuration-form') },
];
if (scope === 3) actions = [
...actions.filter(a => a.label === 'Add provider'),
@@ -178,7 +177,16 @@ The source stops before destination launch. Workspace, session and credentials s
const notice = scope === 0 ? `Host: ${snapshot.service?.state ?? 'unknown'} · Saved: ${snapshot.settings?.revision ?? 0} · Loaded: ${snapshot.service?.revision ?? 'not confirmed'}\n${snapshot.status}` : snapshot.status;
if (lastStatus !== notice) { lastStatus = notice; screen.notice(notice); }
}
screen.onScope = value => { navigation.switch(value); scope = navigation.section; render(); if (scope === 2 && !snapshot.harnesses) void request('runtime-form'); };
screen.onScope = async value => {
if (value >= 2 && !snapshot.owner && !await signin()) { screen.setScope(scope); return; }
navigation.switch(value); scope = navigation.section; render();
if (scope === 2 && !snapshot.harnesses) await request('configuration-form');
};
screen.onActivate = async id => {
if (id === 'signin-buzz') await request('signin-buzz');
else if (id === 'signin-saved' || id === 'signin-import') await routing('signin', id === 'signin-import');
else if (id === 'register-agent') { if (await signin()) await registerForm(); }
};
screen.onSelect = id => { if (selected !== id) { navigation.select(id); selected = id; render(); } };
const input = createInterface({ input: createReadStream('', { fd: 3 }) });
input.on('line', line => {

View File

@@ -36,6 +36,7 @@ export class OpenTuiScreen {
private finish!: () => void;
readonly done = new Promise<void>(resolve => { this.finish = resolve; });
onScope: (index: number) => void = () => {};
onActivate: (id: string) => void | Promise<void> = () => {};
onSelect: (id: string) => void = () => {};
/** Persistent ordinary-key legend, separate from status. Never function-key first.
@@ -89,7 +90,11 @@ export class OpenTuiScreen {
const offset = Math.max(0, Math.min(this.actions.getSelectedIndex() - Math.floor(visible / 2), this.commands.length - visible));
const index = offset + delta;
if (index >= this.commands.length) return;
this.actions.setSelectedIndex(index); this.actions.selectCurrent();
this.actions.setSelectedIndex(index);
// Finish pointer focus dispatch before an action opens an input modal.
// Otherwise Select's mouse handler can steal focus back from that input.
const action = this.commands[index];
queueMicrotask(() => { void this.run(index, action); });
} });
this.pane.add(this.actions);
this.status = new TextRenderable(renderer, { fg, height: 2, onMouseDown: () => this.outcome() });
@@ -109,7 +114,7 @@ export class OpenTuiScreen {
this.focusStyle(); if (row) this.onSelect(row.id);
});
this.actions.on('itemSelected', (index: number) => { void this.run(index); });
this.list.on('itemSelected', () => { if (this.narrow) { this.drilled = true; this.resize(); this.focusIndex = 1; this.scroll.focus(); } });
this.list.on('itemSelected', () => { const row = this.rows[this.list.getSelectedIndex()]; if (row) void this.onActivate(row.id); if (this.narrow) { this.drilled = true; this.resize(); this.focusIndex = 1; this.scroll.focus(); } });
renderer.keyInput.on('keypress', key => this.key(key));
renderer.keyInput.on('paste', event => {
if (!this.modal) return;
@@ -154,6 +159,7 @@ export class OpenTuiScreen {
setRelay(url?: string, state = 'unknown', name?: string) { this.relayFooter = url ? `Relay: ${name ? `${clean(name)} · ` : ''}${clean(url)} · ${state}` : 'Relay: Not configured · disconnected'; this.resize(); }
private heading() { this.header.content = `${this.renderer.width < 56 ? '' : 'BEEHIVE '}${managerSections.map((name, index) => this.scope === index ? `[${name}]` : name).join(this.renderer.width < 56 ? ' ' : ' | ')}\n${clean(this.owner)}`; }
setOwner(publicSuffix?: string) { this.owner = publicSuffix ? `${publicSuffix} · signed in` : 'signed out'; this.heading(); }
setScope(scope: number) { this.scope = scope; this.drilled = false; this.selectedRow = -1; this.resize(); this.heading(); }
private switchScope(scope: number) {
if (this.modal || this.busy || this.small.visible || this.closed) return;
// A section change must present its own details from the top even when the

View File

@@ -4,36 +4,39 @@ import { runtimeEfforts } from './runtime-effort.ts';
import type { ManagerSnapshot, ManagerResult } from './manager-controller.ts';
/** Same short form used by the actual renderer and synthetic key/form fixtures. */
export async function runtimeForm(screen: {
export async function configurationForm(screen: {
choose(label: string, options: string[]): Promise<string | undefined>;
input(label: string, initial?: string): Promise<string | undefined>;
confirm(label: string): Promise<boolean>;
notice(text: string): void;
}, snapshot: () => ManagerSnapshot, request: (action: string, values?: Record<string,string>) => Promise<ManagerResult>) {
if ((await request('runtime-form')).state !== 'completed') return;
const harnesses = snapshot().harnesses ?? [];
}, snapshot: () => ManagerSnapshot, request: (action: string, values?: Record<string,string>) => Promise<ManagerResult>, initial: Record<string,string> = {}) {
if ((await request('configuration-form')).state !== 'completed') return;
const harnesses = [...(snapshot().harnesses ?? [])].sort((a,b) => Number(b.id === initial.harness) - Number(a.id === initial.harness));
if (!harnesses.length) { screen.notice(snapshot().status); return; }
const labels = harnesses.map(h => `${h.label} · ${h.providers.length ? 'Available' : h.state === 'available' ? 'Provider integration unavailable' : h.state}`);
const harness = await screen.choose('Harness', labels); if (!harness) return;
const selected = harnesses[labels.indexOf(harness)];
if (!selected?.providers.length) { screen.notice(selected?.reason ?? 'Unsupported harness'); return; }
const providers = (snapshot().settings?.providers ?? []).filter(p => selected.providers.includes(p.type));
const providers = (snapshot().settings?.providers ?? []).filter(p => selected.providers.includes(p.type)).sort((a,b) => Number(b.id === initial.provider) - Number(a.id === initial.provider));
if (!providers.length) { screen.notice('Add a supported provider first.'); return; }
const choice = await screen.choose('Provider', providers.map(p => `${p.name} · ${p.id}`)); if (!choice) return;
const provider = providers.find(p => choice === `${p.name} · ${p.id}`)!;
const providerLabels = providers.map((p,i) => providers.filter(other => other.name === p.name).length > 1 ? `${p.name} (${i + 1})` : p.name);
const choice = await screen.choose('Provider', providerLabels); if (!choice) return;
const provider = providers[providerLabels.indexOf(choice)]!;
const modelResult = await request('models', { provider: provider.id });
if (modelResult.state === 'cancelled' || modelResult.state === 'ignored') return;
const models = snapshot().models;
const models = snapshot().models ? [...new Set([...(initial.provider === provider.id && initial.model ? [initial.model] : []), ...snapshot().models!])] : undefined;
const labelsById = snapshot().modelLabels ?? {};
const modelLabels = (models ?? []).map(id=>labelsById[id] && labelsById[id] !== id ? `${labelsById[id]} · ${id}` : id);
const choiceModel = await screen.choose(models ? 'Model' : 'Model · Custom model', [...modelLabels, 'Custom model']); if (!choiceModel) return;
const model = choiceModel === 'Custom model' ? await screen.input('Custom model\nExact model ID') : models?.[modelLabels.indexOf(choiceModel)]; if (!model) return;
const model = choiceModel === 'Custom model' ? await screen.input('Custom model\nExact model ID', initial.provider === provider.id ? initial.model : undefined) : models?.[modelLabels.indexOf(choiceModel)]; if (!model) return;
const efforts = selected.id === 'buzz-agent' ? runtimeEfforts(provider.type, model) : selected.id === 'pi' ? piEfforts(provider.type, model) : [];
const effort = efforts.length ? await screen.choose('Effort · new runs only', ['Inherit', ...efforts]) : 'Inherit'; if (!effort) return;
const entry = await screen.input('Environment\nJSON name/value map · no secrets', '{}'); if (entry === undefined) return;
const effort = efforts.length ? await screen.choose('Effort · new runs only', ['Inherit', ...efforts].sort((a,b) => Number(b === initial.effort) - Number(a === initial.effort))) : 'Inherit'; if (!effort) return;
const entry = await screen.input('Environment\nJSON name/value map · no secrets', initial.environment ?? '{}'); if (entry === undefined) return;
let environment: string;
try { environment = JSON.stringify(runtimeEnvironment(JSON.parse(entry))); }
catch { screen.notice('Invalid environment. Use nonsecret name/value pairs; identity, provider and loader variables are reserved. Nothing saved.'); return; }
const name = await screen.input('Runtime name', model); if (!name) return;
if (await screen.confirm(`Save runtime\n${name}\n${selected.label} · ${provider.name} · ${model}\n${efforts.length ? `Effort: ${effort}` : ''}\nEnvironment: ${Object.keys(JSON.parse(environment)).join(', ') || 'None'}\nSaved for new runs.`)) await request('add-runtime', { name, model, environment, provider: provider.id, harness: selected.id, ...(effort !== 'Inherit' ? { effort } : {}) });
return { model, environment, provider: provider.id, harness: selected.id, ...(effort !== 'Inherit' ? { effort } : {}) };
}
/** Historical import compatibility; this now collects direct configuration only. */
export const runtimeForm = configurationForm;

View File

@@ -1,3 +1,4 @@
import type { DetectedHarness } from './harness-discovery.ts';
import { validateBuzzProvider } from './buzz-provider.ts';
import { runtimeEnvironment } from './runtime-environment.ts';
import { piEfforts } from './pi.ts';
@@ -17,7 +18,7 @@ export type RegisteredAgent = { runtimeId?: string; publicKey: string; key: Cred
export type ProviderReference = { service: 'beehive'; account: string };
export type SavedProvider = { id: string; name: string; type: 'openai' | 'anthropic' | 'openai-compat' | 'openrouter' | 'databricks_v2'; endpoint: string; wire?: 'auto' | 'chat' | 'responses'; key: ProviderReference };
export type SavedRuntime = { environment?: Record<string, string>; id: string; name: string; harness: 'buzz-agent' | 'codex' | 'pi'; cli?: string; executable: string; providerId: string; model: string; effort?: string };
export type Settings = { version: 1; revision: number; agents: RegisteredAgent[]; providers: SavedProvider[]; runtimes: SavedRuntime[] };
export type Settings = { harnesses?: DetectedHarness[]; version: 1; revision: number; agents: RegisteredAgent[]; providers: SavedProvider[]; runtimes: SavedRuntime[] };
const path = (directory: string) => join(directory, 'settings.json');
const label = (s: unknown) => typeof s === 'string' && s.length > 0 && s.length <= 128 && !/[\x00-\x1f\x7f]/.test(s);
/** Validate catalog references without touching an OS store or network. */
@@ -41,9 +42,10 @@ export function validateSettings(value: Settings): Settings {
if (r.harness === 'codex' ? !r.cli || !isAbsolute(r.cli) || r.effort !== undefined || value.providers.find(p => p.id === r.providerId)?.type !== 'openai' : r.harness === 'pi' ? !['openai','databricks_v2'].includes(value.providers.find(p => p.id === r.providerId)!.type) || !r.cli || !isAbsolute(r.cli) || r.effort !== undefined && !piEfforts(value.providers.find(p => p.id === r.providerId)!.type, r.model).includes(r.effort) : r.cli !== undefined) throw Error('Unsupported runtime provider/CLI/effort combination');
}
for (const r of value.runtimes) validateRuntimeEffort(value.providers.find(p => p.id === r.providerId)!.type, r.model, r.effort);
if (value.harnesses !== undefined && (!Array.isArray(value.harnesses) || value.harnesses.length > 32 || value.harnesses.some(h => typeof h.id !== 'string' || typeof h.label !== 'string' || typeof h.reason !== 'string' || !['available','not-installed','cli-missing','incompatible'].includes(h.state) || !Array.isArray(h.providers) || h.providers.some(p => typeof p !== 'string') || (h.executable !== undefined && !isAbsolute(h.executable)) || (h.cli !== undefined && !isAbsolute(h.cli))))) throw Error('Invalid harness inventory');
// Reject unknown fields, including accidental secret-bearing input.
const fields = (o: object, allowed: string[]) => { if (Object.keys(o).some(k => !allowed.includes(k))) throw Error('Unexpected settings field'); };
fields(value, ['version','revision','agents','providers','runtimes']);
fields(value, ['version','revision','agents','providers','runtimes','harnesses']);
for (const a of value.agents) { fields(a, ['publicKey','key','profile','profileState','runtimeId']); if (a.profile) fields(a.profile, ['relay','name','picture','about']); }
for (const p of value.providers) { fields(p, ['id','name','type','endpoint','key','wire']); fields(p.key, ['service','account']); }
for (const r of value.runtimes) fields(r, ['id','name','harness','executable','providerId','model','effort','cli','environment']);

View File

@@ -19,19 +19,31 @@ const key='1'.repeat(64), backend=isolatedFileCredentials(process.env.BEEHIVE_TE
createCredential('owner',key,backend);
bootstrapHostIdentity(process.env.HOME+'/.beehive/host','Fixture Host',publicKey(key),'wss://fixture.invalid',backend);
console.log(publicKey(key));"""
direct = os.environ.get('BEEHIVE_SMOKE_DIRECT') == '1'
if direct:
env.update(BEEHIVE_SMOKE_DIRECT='1', BEEHIVE_TEST_REGISTRATION_WALKTHROUGH='1', DATABRICKS_HOST='https://synthetic-workspace.example')
seed = "import {publicKey} from './src/protocol.ts'; console.log(publicKey('1'.repeat(64)));"
owner = subprocess.check_output([node, '--input-type=module', '-e', seed], env=env, text=True).strip()
env['BEEHIVE_TEST_BUZZ_OWNER'] = owner
config = Path(home+'/.beehive/owner/controller.json')
assert not config.exists(), 'Regression must start with NO configured owner'
before = Path(env['BEEHIVE_TEST_CREDENTIAL_FILE']).read_bytes()
pid, fd = pty.fork()
if pid == 0:
os.execve(node, [node, 'src/manager-entry.ts'], env)
fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack('HHHH', 36, 140, 0, 0))
before = Path(env['BEEHIVE_TEST_CREDENTIAL_FILE']).read_bytes() if not direct else b''
def launch():
pid, fd = pty.fork()
if pid == 0:
before_tty = termios.tcgetattr(0)
command = [os.environ['BEEHIVE_SMOKE_LAUNCHER']] if os.environ.get('BEEHIVE_SMOKE_LAUNCHER') else [node, 'bin/beehive.cjs']
result = subprocess.run(command, env=env)
restored = termios.tcgetattr(0) == before_tty
os.write(1, ('\nTERMINAL_RESTORED='+str(restored)+' EXIT='+str(result.returncode)+'\n').encode())
os._exit(0 if restored and result.returncode == 0 else 1)
fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack('HHHH', 30, 100, 0, 0))
return pid, fd
pid, fd = launch()
transcript = b''
frames = []
import re
ROWS, COLS = 36, 140
ROWS, COLS = 30, 100
def screen(buf):
cells={}; row=col=1; i=0; n=len(buf)
while i<n:
@@ -84,13 +96,97 @@ def send(data):
os.write(fd, data)
wait()
try:
def enter_text(value):
send(b'\x1b[200~'+value.encode()+b'\x1b[201~')
send(b'\r')
def click_action(label):
for y, line in enumerate(frames[-1].splitlines(),1):
x = line.find(label, 29)
if x >= 0:
send(('\x1b[<0;%d;%dM\x1b[<0;%d;%dm' % (x+1,y,x+1,y)).encode())
return
raise AssertionError('Missing detail action '+label+'\n'+frames[-1])
def select_agent():
for y, line in enumerate(frames[-1].splitlines(),1):
x = line.find('Review agent')
if 0 <= x < 28:
send(('\x1b[<0;%d;%dM\x1b[<0;%d;%dm' % (x+1,y,x+1,y)).encode())
return
raise AssertionError('Missing agent row\n'+frames[-1])
def direct_journey():
global pid, fd, transcript
wait(3)
send(b'\x1b[C')
assert 'Sign in with Buzz key' in frames[-1]
send(b'\x1b[C'); send(b'\r') # contextual Buzz signin, resume Harnesses
wait(2)
assert config.exists()
send(b'\x1b[C')
assert 'Databricks' in frames[-1]
click_action('Add provider')
send(b'\r'); send(b'\r') # OpenAI, default name
enter_text('synthetic-provider-key'); enter_text('yes')
send(b'\x1b[D'); click_action('Refresh harnesses')
send(b'\x1b[D')
assert 'Registered agents' in frames[-1] and 'Other agents' in frames[-1]
# Select the known Other agent using the real list, then Start -> registration.
select_agent()
click_action('Start')
enter_text('yes')
assert 'Matching nsec' in frames[-1]
nsec = subprocess.check_output([node,'--input-type=module','-e',"import {nsecEncode} from 'nostr-tools/nip19'; console.log(nsecEncode(Buffer.from('2'.repeat(64),'hex')));"],env=env,text=True).strip()
enter_text(nsec)
assert 'Harness' in frames[-1]
send(b'\r') # Buzz Agent
send(b'\x1b[B\r') # OpenAI, after environment Databricks
send(b'\r') # gpt-5
send(b'\x1b[B\x1b[B\x1b[B\r') # high effort
send(b'\x15'); enter_text('{"REVIEW_MODE":"synthetic"}')
enter_text('yes'); wait(5)
assert 'running' in frames[-1], frames[-1]
assert nsec.encode() not in transcript
settings = json.loads(Path(home+'/.beehive/host/settings.json').read_text())
assert len(settings['agents']) == 1 and len(settings['runtimes']) == 1
assert settings['runtimes'][0]['environment'] == {'REVIEW_MODE':'synthetic'}
click_action('Configure')
# Reopened form defaults to the actual saved selection, not a named chooser.
send(b'\r'); send(b'\r'); send(b'\r'); send(b'\r'); send(b'\r'); enter_text('yes'); wait(3)
click_action('Stop'); enter_text('yes'); wait(3)
assert 'stopped' in frames[-1]
remembered = json.loads(Path(home+'/.beehive/host/settings.json').read_text())
send(b'q'); wait(3)
assert b'TERMINAL_RESTORED=True EXIT=0' in transcript
os.waitpid(pid,0); os.close(fd)
Path(home+'/first-ui.ansi').write_bytes(transcript)
transcript = b''
pid, fd = launch(); wait(3)
# Actual launcher/controller reopen: retained provider, inventory, config and host journal.
send(b'\x1b[C'); send(b'\r'); wait(2) # direct Buzz row
select_agent()
click_action('Start'); enter_text('yes'); wait(5)
assert 'running' in frames[-1], frames[-1]
reopened = json.loads(Path(home+'/.beehive/host/settings.json').read_text())
for key in ['providers','runtimes','harnesses','agents']:
assert reopened[key] == remembered[key], key
click_action('Stop'); enter_text('yes'); wait(3)
send(b'q'); wait(2)
assert b'TERMINAL_RESTORED=True EXIT=0' in transcript
print('PASS 100x30 direct lifecycle: contextual Buzz; env Databricks; provider Save; refresh; Other matching nsec; harness/provider/model/effort/environment; Configure; Start/Stop; actual launcher reopen; next Start; q restored. HOME='+home)
def first_use():
wait(2)
send(b'\x1b[C') # Agents
send(b'a') # Actions
assert 'Sign in with Buzz key' in frames[-1]
send(b'\x1b[B') # Buzz action, not saved-key action
send(b'\r') # ONE selection; no more input
assert 'Sign in with saved' in frames[-1]
send(b'\x1b[C') # Protected Harnesses intent -> contextual chooser
assert 'Buzz key' in frames[-1]
send(b'\x1b')
assert '[Agents]' in frames[-1] and 'Working' not in frames[-1]
send(b'\x1b[C')
send(b'\r') # One Buzz selection resumes Harnesses
wait(2)
assert config.exists(), 'One selection did not initialize owner routing'
assert json.loads(config.read_text()) == {'version': 1, 'owner': owner, 'relay': 'wss://fixture.invalid'}
@@ -104,9 +200,18 @@ try:
assert b'1'*64 not in file.read_bytes(), 'Private key persisted'
assert b'nsec1' not in file.read_bytes(), 'nsec persisted'
assert b'1'*64 not in transcript and b'nsec1' not in transcript, 'Private key rendered'
print('PASS first use: Agents -> Buzz key once -> derived owner signed in; no prompts or private copy. HOME='+home)
assert '[Harnesses]' in frames[-1], 'Protected intent not resumed'
send(b'q')
wait(2)
assert b'TERMINAL_RESTORED=True EXIT=0' in transcript
print('PASS 100x30 actual launcher: signed-out Agents choices; contextual cancel/resume; Buzz once; q + terminal restored. HOME='+home)
try:
direct_journey() if direct else first_use()
finally:
Path(home+'/ui.ansi').write_bytes(transcript)
Path(home+'/ui-frames.txt').write_text('\n--- FRAME ---\n'.join(frames))
os.killpg(pid, 9)
os.waitpid(pid, 0)
done, _ = os.waitpid(pid, os.WNOHANG)
if not done:
os.killpg(pid, 9)
os.waitpid(pid, 0)

View File

@@ -6,9 +6,13 @@ const fixture = fileURLToPath(new URL('./manager-installed-fixture.ts', import.m
// Explicit test-only seam. No production environment switch or OS-store fallback.
registerHooks({ load(url, context, next) {
const result = next(url, context);
if (url.endsWith('/src/harness-discovery.ts')) return { ...result, source: "import {realpathSync} from 'node:fs'; export async function discoverHarnesses() { return [{id:'buzz-agent',label:'Buzz Agent',executable:process.env.BEEHIVE_TEST_REGISTRATION_WALKTHROUGH === '1' ? realpathSync(process.env.HOME + '/synthetic-acp') : process.execPath,state:'available',providers:['openai','anthropic','openai-compat','openrouter','databricks_v2'],reason:'Synthetic only'}]; }" };
if (url.endsWith('/src/harness-discovery.ts')) return { ...result, source: "import {realpathSync} from 'node:fs'; export async function discoverHarnesses(_signal, options = {}) { return [{id:'buzz-agent',label:'Buzz Agent',executable:process.env.BEEHIVE_TEST_REGISTRATION_WALKTHROUGH === '1' ? realpathSync((options.home ?? process.env.HOME) + '/synthetic-acp') : process.execPath,state:'available',providers:['openai','anthropic','openai-compat','openrouter','databricks_v2'],reason:'Synthetic only'}]; }" };
if (url.endsWith('/src/databricks-runtime.ts') || url.endsWith('/src/databricks-runtime-child.ts')) return { ...result, source: "throw Error('Runtime auth disabled by installed fixture');" };
if (url.endsWith('/src/databricks.ts')) return { ...result, source: "export function databricksHost(v) { return new URL(v).origin; } export async function databricksNative() { throw Error('Native OAuth disabled by installed fixture'); } export async function addDatabricks() { throw Error('Native OAuth disabled by installed fixture'); }" };
if (url.endsWith('/src/databricks.ts')) {
const source = String(result.source), start = source.indexOf('export async function databricksNative('), end = source.indexOf('/** Save the workspace',start);
if (start < 0 || end < 0) throw Error('Databricks fixture fence failed closed');
return { ...result, source: source.slice(0,start) + "export async function databricksNative() { throw Error('Native OAuth disabled by installed fixture'); }\n" + source.slice(end) };
}
if (!walkthrough && url.endsWith('/src/relay-directory.ts')) return { ...result, source: "export async function fetchRelayDirectory() { throw Error('Directory disabled by installed fixture'); }" };
if (url.endsWith('/src/agent-profile.ts')) return { ...result, source: "export async function fetchAgentProfile() { return {profileState:'none'}; }" };
if (url.endsWith('/src/host-service.ts')) return { ...result, source: "export async function serviceStatus() { return {state:'stopped',relay:'disconnected'}; } export async function startService() { throw Error('Service start disabled by installed fixture'); } export async function stopService() { throw Error('Service stop disabled by installed fixture'); }" };

View File

@@ -16,16 +16,23 @@ test('four sections retain exact selections without retargeting removed items',
});
test('section rows expose selected public fields, not credential references or other controls', () => {
const snapshot: ManagerSnapshot = { local: [{ id: 'host', label: 'This host', detail: '' }], agents: [], status: '', hostRelay: 'wss://fixture.invalid', service: { state: 'stopped' }, settings: { version: 1, revision: 1, agents: [], providers: [{ id: 'p', name: 'Provider A', type: 'openai', endpoint: 'https://api.openai.com/v1', key: { service: 'beehive', account: 'secret-reference' } }], runtimes: [{ id: 'r', name: 'Runtime A', harness: 'buzz-agent', providerId: 'p', model: 'gpt-5', effort: 'high', executable: '/fixture/harness' }] } };
const snapshot: ManagerSnapshot = { owner: 'owner', local: [{ id: 'host', label: 'This host', detail: '' }], agents: [], status: '', hostRelay: 'wss://fixture.invalid', service: { state: 'stopped' }, settings: { version: 1, revision: 1, agents: [], providers: [{ id: 'p', name: 'Provider A', type: 'openai', endpoint: 'https://api.openai.com/v1', key: { service: 'beehive', account: 'secret-reference' } }], runtimes: [{ id: 'r', name: 'Runtime A', harness: 'buzz-agent', providerId: 'p', model: 'gpt-5', effort: 'high', executable: '/fixture/harness' }] } };
assert.match(sectionRows(snapshot,0)[0]!.detail, /Host name: This host\nRelay URL: wss:\/\/fixture.invalid\nState: stopped/);
assert.deepEqual(sectionRows(snapshot,1).map(row => row.label), ['Registered agents', ' Register agent', 'Other agents']);
assert.match(sectionRows(snapshot,2)[0]!.detail, /Provider: Provider A\nModel: gpt-5\nEffort: high/);
assert.deepEqual(sectionRows(snapshot,2), []); // Legacy records stay internal, not a second setup surface.
assert.equal(sectionRows(snapshot,3)[0]!.id,'p');
assert.ok(!JSON.stringify(sectionRows(snapshot,3)).includes('secret-reference'));
});
test('Agents are separated by registered custody, retaining directory order within each group', () => {
const agent = (id: string) => ({ id, label: id, detail: id, revision: 0, configurations: [] });
const snapshot = { local: [], agents: [agent('other'), agent('registered')], status: '', settings: { version: 1, revision: 0, providers: [], runtimes: [], agents: [{ publicKey: 'registered', key: { service: 'beehive', role: 'agent', publicKey: 'registered' }, profileState: 'none' }] } } as ManagerSnapshot;
const snapshot = { owner: 'owner', local: [], agents: [agent('other'), agent('registered')], status: '', settings: { version: 1, revision: 0, providers: [], runtimes: [], agents: [{ publicKey: 'registered', key: { service: 'beehive', role: 'agent', publicKey: 'registered' }, profileState: 'none' }] } } as ManagerSnapshot;
assert.deepEqual(sectionRows(snapshot, 1).map(row => row.id), ['registered-agents', 'register-agent', 'registered', 'other-agents', 'other']);
});
test('signed-out Agents directly offer sign-in and no standing menu survives sign-in', () => {
const snapshot: ManagerSnapshot = { local: [], agents: [], status: '' };
assert.deepEqual(sectionRows(snapshot,1).map(row => row.id), ['signin-buzz','signin-saved','signin-import']);
snapshot.owner = 'owner';
assert.ok(sectionRows(snapshot,1).every(row => !row.id.startsWith('signin')));
});

View File

@@ -7,7 +7,7 @@ import { verifyEvent, type Event } from 'nostr-tools/pure';
* recipient-scoped REQ, timestamp/size and publication rules. Optional allowed
* identities model real server AUTH refusal, not a Beehive membership preflight.
*/
export async function nostrFixture(owner: string, allowedIdentities?: ReadonlySet<string>, access: { open?: boolean; denyAuth?: boolean; denyPublication?: boolean; denyReq?: boolean } = {}, publicHttp?: (req: IncomingMessage, res: ServerResponse) => boolean) {
export async function nostrFixture(owner: string, allowedIdentities?: ReadonlySet<string>, access: { open?: boolean; denyAuth?: boolean; denyPublication?: boolean; denyReq?: boolean; port?: number } = {}, publicHttp?: (req: IncomingMessage, res: ServerResponse) => boolean) {
const allowed = new Set(allowedIdentities ?? [owner]);
const httpRequests: string[] = [];
const http = createServer((req, res) => {
@@ -18,7 +18,7 @@ export async function nostrFixture(owner: string, allowedIdentities?: ReadonlySe
else res.writeHead(404).end('{}');
});
const server = new WebSocketServer({ server: http, maxPayload: 300000 });
await new Promise<void>(resolve => http.listen(0, '127.0.0.1', resolve));
await new Promise<void>((resolve,reject) => { http.once('error',reject); http.listen(access.port ?? 0, '127.0.0.1', resolve); });
const address = http.address();
if (!address || typeof address === 'string') throw Error('Missing fixture address');
const url = `ws://127.0.0.1:${address.port}`;

View File

@@ -8,7 +8,7 @@ test('host shows selected details and controls with hidden ordinary-key entry',
const view = new OpenTuiScreen(ui.renderer);
try {
let calls = 0;
view.show(['Agents','Providers','Runtimes'].map(label => ({ id: label,label,detail: 'Host name: Fixture' })),['Register agent','Add provider','Add runtime','Start','Stop'].map(label => ({ label,run: () => { calls++; } })));
view.show(['Agents','Providers','Harnesses'].map(label => ({ id: label,label,detail: 'Host name: Fixture' })),['Register agent','Add provider','Configure','Start','Stop'].map(label => ({ label,run: () => { calls++; } })));
view.setRelay('wss://fixture.invalid','disconnected'); await ui.renderOnce();
const frame = ui.captureCharFrame();
assert.match(frame,/\[Host\]/); assert.match(frame,/Register agent/); assert.match(frame,/wss:\/\/fixture.invalid.*disconnected/);
@@ -203,3 +203,18 @@ test('temporary notices retire nested work but retain newer results and errors',
await ui.renderOnce(); assert.ok(!ui.captureCharFrame().includes('Working'));
} finally { view.close(); }
});
test('pointer-opened confirmation retains ordinary input focus through mouse dispatch', async () => {
const ui = await createTestRenderer({ width: 100, height: 30, exitOnCtrlC: false });
const view = new OpenTuiScreen(ui.renderer);
try {
let result: boolean | undefined;
view.show([{id:'agent',label:'Agent',detail:'Selected agent'}],[{label:'Start',run:async()=>{result = await view.confirm('Start agent?');}}]);
await ui.renderOnce();
const lines = ui.captureCharFrame().split('\n'), row = lines.findIndex(line => line.includes('Start'));
await ui.mockMouse.click(40,row); await ui.renderOnce();
await ui.mockInput.typeText('yes'); await ui.renderOnce();
ui.mockInput.pressEnter(); await ui.renderOnce();
assert.equal(result,true,'pointer dispatch stole focus from confirmation input');
} finally { view.close(); }
});

View File

@@ -37,12 +37,13 @@ test('Pi model routes use the shared capability owner; UC tenant components neve
assert.ok(runtimeCapabilities('databricks_v2','gpt-5.schema.unknown')!.supported_efforts.includes('high'));
});
test('actual runtime form offers Pi both providers, retains custom names, submits only supported model effort',async()=>{
test('direct configuration form offers Pi both providers and returns only supported model effort',async()=>{
for(const type of ['openai','databricks_v2'] as const) {
const model=type==='openai'?'gpt-5':'databricks-gpt-5-4';
const snapshot:ManagerSnapshot={local:[],agents:[],status:'fixture',harnesses:[{id:'pi',label:'Pi',executable:'/fake',cli:'/fake-pi',state:'available',providers:['openai','databricks_v2'],reason:'synthetic'}],models:[model],settings:{version:1,revision:1,agents:[],runtimes:[],providers:[{id:'p',name:'Saved',type,endpoint:type==='openai'?'https://api.openai.com/v1':'https://pi-workspace.example',key}]}};
const choices=['Pi · Available','Saved · p',model,'high'];const calls:any[]=[];
await runtimeForm({async choose(_label,options){const value=choices.shift();assert.ok(options.includes(value!));return value;},async input(label){return label.startsWith('Environment') ? '{}' : 'My Pi';},async confirm(){return true;},notice(){throw Error('unexpected notice');}},()=>snapshot,async(action,values)=>{calls.push({action,values});return {state:"completed"};});
assert.deepEqual(calls.at(-1),{action:'add-runtime',values:{name:'My Pi',model,environment:'{}',provider:'p',harness:'pi',effort:'high'}});
const choices=['Pi · Available','Saved',model,'high'];const calls:any[]=[];
const configured = await runtimeForm({async choose(_label,options){const value=choices.shift();assert.ok(options.includes(value!));return value;},async input(label){return label.startsWith('Environment') ? '{}' : 'My Pi';},async confirm(){return true;},notice(){throw Error('unexpected notice');}},()=>snapshot,async(action,values)=>{calls.push({action,values});return {state:"completed"};});
assert.deepEqual(configured,{model,environment:'{}',provider:'p',harness:'pi',effort:'high'});
assert.deepEqual(calls.map(c => c.action),['configuration-form','models']);
}
});

View File

@@ -1,5 +1,5 @@
import { setTimeout as delay } from 'node:timers/promises';
import { mkdirSync, writeFileSync, realpathSync } from 'node:fs';
import { mkdirSync, writeFileSync, realpathSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { schnorr } from '@noble/curves/secp256k1';
@@ -9,12 +9,12 @@ import { message, newKey, publicKey, digest, type Message } from '../src/protoco
import { ManagerController, type ManagerSnapshot } from '../src/manager-controller.ts';
import { fetchRelayDirectory } from '../src/relay-directory.ts';
import { managementClient } from '../src/intents.ts';
import { bootstrapHostIdentity } from '../src/host-identity.ts';
import { bootstrapHostIdentity, readHostIdentity, readHostIdentityPublic } from '../src/host-identity.ts';
import { privateHostTransport } from '../src/host-transport.ts';
import { createControllerConfig } from '../src/controller-config.ts';
import { provisionCredentialSlot } from '../src/credential-slots.ts';
import { createGenesis } from '../src/assignment.ts';
import { createCredential } from '../src/credential-store.ts';
import { createCredential, type CredentialReference } from '../src/credential-store.ts';
import { registerAgent, agentNsec, addOpenAI, addProvider } from '../src/settings-credentials.ts';
import { readSettings, saveSettings } from '../src/settings.ts';
import { host } from '../src/host.ts';
@@ -24,7 +24,7 @@ import { nostrFixture } from './nostr-fixture.ts';
/** Product-shaped synthetic fixture. Real private relay, owner authentication,
* host and owned ACP process. Public assignment is pre-provisioned explicitly by
* this test, NOT derived by registration from directory metadata or nsec custody. */
export async function registrationFixture(home: string, changed: (s: ManagerSnapshot) => void, assigned = true, move = false) {
export async function registrationFixture(home: string, changed: (s: ManagerSnapshot) => void, assigned = true, move = false, direct = false) {
home = realpathSync(home);
if (!home.includes('beehive-pairing-cli-')) throw Error('Fresh explicit fixture HOME required');
const credentials = isolatedFileCredentials(join(home,'credentials.json'));
@@ -34,7 +34,8 @@ export async function registrationFixture(home: string, changed: (s: ManagerSnap
const profile = finalizeEvent({kind:0,created_at:now,tags:[['auth',owner,'',Buffer.from(schnorr.sign(digest(`nostr:agent-auth:${agent}:`),ownerSecret)).toString('hex')]],content:JSON.stringify({name:'Review agent'})},Buffer.from(agentSecret,'hex'));
const errors: unknown[] = [], ids = new Set<string>();
const members = new Set([owner]); let url = '';
const relay = await nostrFixture(owner,members,{open:true},(req,res) => {
const retained = direct && existsSync(join(home,'.beehive/host/host-identity.json')) ? readHostIdentityPublic(join(home,'.beehive/host')) : undefined;
const relay = await nostrFixture(owner,members,{open:true,...(retained ? {port:Number(new URL(retained.pairing.relay).port)} : {})},(req,res) => {
if (req.method === 'GET' && req.url === '/') { res.end(JSON.stringify({self:publicKey(relaySecret),name:'Synthetic relay'})); return true; }
if (req.method !== 'POST' || req.url !== '/query') return false;
let body = ''; req.on('data',chunk => { body += chunk; if (body.length > 65536) req.destroy(); });
@@ -52,18 +53,18 @@ export async function registrationFixture(home: string, changed: (s: ManagerSnap
url = relay.url;
const directory = join(home,'.beehive','host');
mkdirSync(directory,{recursive:true,mode:0o700});
const identity = bootstrapHostIdentity(directory,'Review host',owner,url,credentials);
createCredential('owner',ownerSecret,credentials);
createControllerConfig(join(home,'.beehive','owner'),owner,url);
const identity = retained ? readHostIdentity(directory,credentials) : bootstrapHostIdentity(directory,'Review host',owner,url,credentials);
if (!retained) createCredential('owner',ownerSecret,credentials);
if (!direct) createControllerConfig(join(home,'.beehive','owner'),owner,url);
const setup = {host:identity.pairing.host,ownerPublic:owner,runner:realpathSync(process.execPath),args:['-e','setInterval(()=>{},1000)'],workspace:home,mode:'fixture' as const,serviceHome:home,configDirectory:home};
const genesis = createGenesis(owner,agent,identity.pairing.host);
if (assigned) provisionCredentialSlot(directory,setup,agentSecret,genesis,credentials);
let providerKey: string | null = null;
addOpenAI(directory,'Review OpenAI','synthetic-provider-key',{read:()=>providerKey,create:(_r,v)=>{providerKey=v;}});
if (!direct) addOpenAI(directory,'Review OpenAI','synthetic-provider-key',{read:()=>providerKey,create:(_r,v)=>{providerKey=v;}});
const executable = join(home,'synthetic-acp');
writeFileSync(executable,`#!/bin/sh\n[ "$REVIEW_MODE" = synthetic ] || exit 9\nexec '${process.execPath}' '${fileURLToPath(new URL('./acp-fixture.ts',import.meta.url))}' saved-provider\n`,{mode:0o700});
const settings = readSettings(directory), runtimeId = 'review-runtime';
saveSettings(directory,{...settings,runtimes:[{id:runtimeId,name:'Review runtime',harness:'buzz-agent',executable,providerId:settings.providers[0]!.id,model:'gpt-5',effort:'high',environment:{REVIEW_MODE:'synthetic'}}]},settings.revision);
if (!direct) saveSettings(directory,{...settings,runtimes:[{id:runtimeId,name:'Review runtime',harness:'buzz-agent',executable,providerId:settings.providers[0]!.id,model:'gpt-5',effort:'high',environment:{REVIEW_MODE:'synthetic'}}]},settings.revision);
let providerFailure = false;
let holdPrepared = false, dropGrant = false, holdEnrollment = false;
const held: (()=>void)[] = [];
@@ -119,8 +120,8 @@ export async function registrationFixture(home: string, changed: (s: ManagerSnap
let credentialFailure = false, beforeCredential: (() => Promise<void>) | undefined, afterCredential: (() => Promise<void>) | undefined;
const credential = async (input: any, signal: AbortSignal) => {
signal.throwIfAborted();
if (input.action === 'signin') return {ok:true,secret:ownerSecret};
if (input.action === 'add-provider') { addProvider(directory,input.name,input.secret,{read:()=>providerKey,create:(_r,v)=>{providerKey=v;}},input.type,input.endpoint,input.wire); return {ok:true}; }
if (input.action === 'signin' || input.action === 'signin-buzz') return {ok:true,secret:ownerSecret};
if (input.action === 'add-provider') { addProvider(directory,input.name,input.secret,direct ? {read:r=>credentials.read(r as unknown as CredentialReference),create:(r,v)=>credentials.create(r as unknown as CredentialReference,v)} : {read:()=>providerKey,create:(_r,v)=>{providerKey=v;}},input.type,input.endpoint,input.wire); return {ok:true}; }
if (input.action === 'models') { const p=readSettings(directory).providers.find(p=>p.id===input.provider); const model=p?.type === 'anthropic' ? 'claude-sonnet-4-5' : p?.type === 'openrouter' ? 'vendor/custom-model' : 'gpt-5'; return {ok:true,models:[model],modelLabels:{[model]:p?.type === 'anthropic' ? 'Claude Sonnet 4.5' : model}}; }
if (input.action !== 'register-agent') throw Error('Fixture denies external credential operation');
await beforeCredential?.(); signal.throwIfAborted();
@@ -138,6 +139,7 @@ export async function registrationFixture(home: string, changed: (s: ManagerSnap
/** Installed walkthrough uses the same real synthetic lifecycle fixture as tests. */
export async function walkthroughController(home: string, changed: (s: ManagerSnapshot) => void) {
const fixture = await registrationFixture(home,changed,false,true);
const direct = process.env.BEEHIVE_SMOKE_DIRECT === '1';
const fixture = await registrationFixture(home,changed,false,!direct,direct);
return fixture.controller;
}

View File

@@ -138,7 +138,7 @@ test('explicit directory refresh reuses authenticated discovery without reconnec
assert.deepEqual(f.snapshot.agents.map(a=>a.id),before);
assert.deepEqual(f.errors,[]);
await f.request('signout');
assert.equal((await f.request('directory-refresh')).state,'failed');
assert.equal((await f.request('directory-refresh')).state,'signin-required');
assert.equal(f.snapshot.agents.length,0);
});
@@ -258,3 +258,59 @@ test('Other-agent registration requires that exact identity even without a Start
await f.request('operations');
assert.match(f.snapshot.status, /No saved operations/);
});
test('direct agent configuration registers, saves future selection without mutating actual, remembers discovery and preserves provider references', async t => {
const f = await fixture(t);
const begin = await f.start(); assert.equal(begin.state,'registration-required'); if (begin.state !== 'registration-required') return;
await f.request('profile-preview',{secret:f.nsec,agent:f.agent,continuation:begin.continuation});
assert.equal((await f.request('configuration-form')).state,'completed',f.snapshot.status);
const provider = readSettings(f.directory).providers[0]!;
const fields = {harness:'buzz-agent',provider:provider.id,model:'gpt-5',effort:'high',environment:'{"REVIEW_MODE":"synthetic"}'};
assert.equal((await f.request('register-agent',{...fields,secret:f.nsec,agent:f.agent,continuation:begin.continuation})).state,'submitted',f.snapshot.status);
await until(()=>f.snapshot.agents[0]?.label.includes('running') === true);
let row = f.snapshot.agents[0]!;
const actual = JSON.parse(row.evidence!).report.body.actualRun;
assert.notEqual(actual.selection.harnessSetup.id, `runtime:${f.runtimeId}`);
assert.equal((await f.request('configure-agent',{...fields,effort:'low'},row.target,row.revision)).state,'submitted',f.snapshot.status);
await until(()=>f.snapshot.agents[0]!.revision > row.revision);
row = f.snapshot.agents[0]!;
assert.deepEqual(JSON.parse(row.evidence!).report.body.actualRun,actual);
assert.equal(row.configuration?.effort,'low');
assert.ok(!row.detail.includes('runtime:'));
const saved = readSettings(f.directory);
assert.equal((await f.request('configuration-form')).state,'completed');
assert.deepEqual(readSettings(f.directory).providers,saved.providers);
assert.deepEqual(readSettings(f.directory).runtimes,saved.runtimes);
assert.deepEqual(readSettings(f.directory).harnesses,f.snapshot.harnesses);
const {ManagerController} = await import('../src/manager-controller.ts');
const reopened = new ManagerController(f.controller.home,()=>{});
assert.deepEqual(reopened.snapshot().harnesses,f.snapshot.harnesses);
assert.deepEqual(reopened.snapshot().settings?.providers,saved.providers);
assert.deepEqual(reopened.snapshot().settings?.runtimes,saved.runtimes);
assert.equal((await reopened.request({id:1,action:'configure-agent',values:fields})).state,'signin-required');
reopened.close();
await f.request('stop',undefined,row.target,row.revision);
await until(()=>f.snapshot.agents[0]?.label.includes('stopped') === true);
row=f.snapshot.agents[0]!;
await f.request('start',undefined,row.target,row.revision);
await until(()=>f.snapshot.agents[0]?.label.includes('running') === true);
assert.notEqual(JSON.parse(f.snapshot.agents[0]!.evidence!).report.body.actualRun.selection.harnessSetup.id,actual.selection.harnessSetup.id);
});
test('environment Databricks is normalized, visible and durable before any provider setup or credential read', async t => {
const home = realpathSync(mkdtempSync(join(tmpdir(),'beehive-pairing-cli-env-provider-')));
t.after(()=>rmSync(home,{recursive:true,force:true}));
const prior = process.env.DATABRICKS_HOST;
process.env.DATABRICKS_HOST = 'https://synthetic-workspace.example/';
const {ManagerController} = await import('../src/manager-controller.ts');
try {
const controller = new ManagerController(home,()=>{},async()=>{ throw Error('Passive availability cannot read credentials'); });
const providers = controller.snapshot().settings!.providers;
assert.equal(providers.length,1); assert.equal(providers[0]!.type,'databricks_v2');
assert.equal(providers[0]!.endpoint,'https://synthetic-workspace.example');
controller.close();
const reopened = new ManagerController(home,()=>{});
assert.deepEqual(reopened.snapshot().settings!.providers,providers); reopened.close();
assert.ok(!existsSync(join(home,'credentials.json')));
} finally { if (prior === undefined) delete process.env.DATABRICKS_HOST; else process.env.DATABRICKS_HOST = prior; }
});

View File

@@ -55,5 +55,5 @@ test('runtime form stops on failed discovery and cancelled models rather than co
const calls:string[]=[];
await runtimeForm(screen,()=>snapshot,async action=>{calls.push(action);return action === 'models' ? {state:'cancelled',reason:'fixture'} : {state:'completed'};});
assert.equal(choices,2);
assert.deepEqual(calls,['runtime-form','models']);
assert.deepEqual(calls,['configuration-form','models']);
});

View File

@@ -129,19 +129,19 @@ test('effort is manifest-backed, validates persisted settings and reaches actual
await session.catalog(); await session.verify();
});
test('short runtime form selects supported model-specific effort; unknown custom inherits provider capabilities and unsupported harness cannot save', async () => {
test('direct configuration form selects supported model-specific effort; unknown custom inherits provider capabilities and unsupported harness cannot save', async () => {
const snapshot: ManagerSnapshot = { local:[], agents:[], status:'synthetic', models:['gpt-5'], harnesses:[{id:'buzz-agent',label:'Buzz Agent',executable:'/fixture',state:'available',providers:['openai'],reason:'fixture'},{id:'pi',label:'Pi',state:'available',providers:[],reason:'Provider integration unavailable'}], settings:{version:1,revision:1,agents:[],runtimes:[],providers:[{id:'p',name:'OpenAI',type:'openai',endpoint:'https://api.openai.com/v1',key}]} };
const submitted: {action:string;values?:Record<string,string>}[] = [];
const run = async (choices: string[], inputs: string[]) => runtimeForm({choose:async (_label,options) => {const value=choices.shift(); assert.ok(value === undefined || options.includes(value)); return value;},input:async label => { assert.ok(label.split('\n')[0]!.length <= 30); if (label.startsWith('Custom model')) assert.equal(label, 'Custom model\nExact model ID'); if (label.startsWith('Environment')) { assert.equal(label, 'Environment\nJSON name/value map · no secrets'); return '{}'; } return inputs.shift(); },confirm:async label => {assert.match(label,/^Save runtime\n/);return true;},notice:() => {}}, () => snapshot, async (action,values) => {submitted.push({action,values});return {state:"completed"};});
await run(['Buzz Agent · Available','OpenAI · p','gpt-5','high'],['Reasoning']);
assert.equal(submitted.at(-1)?.values?.effort,'high');
assert.equal(submitted.at(-1)?.values?.model,'gpt-5');
const run = async (choices: string[], inputs: string[]) => runtimeForm({choose:async (_label,options) => {const value=choices.shift(); assert.ok(value === undefined || options.includes(value)); return value;},input:async label => { assert.ok(label.split('\n')[0]!.length <= 30); if (label.startsWith('Custom model')) assert.equal(label, 'Custom model\nExact model ID'); if (label.startsWith('Environment')) { assert.equal(label, 'Environment\nJSON name/value map · no secrets'); return '{}'; } return inputs.shift(); },confirm:async () => { throw Error('Direct form must not persist configuration implicitly'); },notice:() => {}}, () => snapshot, async (action,values) => {submitted.push({action,values});return {state:"completed"};});
const configured = await run(['Buzz Agent · Available','OpenAI','gpt-5','high'],[]);
assert.equal(configured?.effort,'high');
assert.equal(configured?.model,'gpt-5');
submitted.length=0;
await run(['Buzz Agent · Available','OpenAI · p','Custom model','Inherit'],['unrecognized-model','Custom']);
assert.equal(submitted.at(-1)?.action,'add-runtime'); assert.equal(submitted.at(-1)?.values?.effort,undefined);
const custom = await run(['Buzz Agent · Available','OpenAI','Custom model','Inherit'],['unrecognized-model']);
assert.equal(custom?.model,'unrecognized-model'); assert.equal(custom?.effort,undefined);
submitted.length=0;
await run(['Pi · Provider integration unavailable'],[]);
assert.deepEqual(submitted.map(s => s.action),['runtime-form']);
assert.deepEqual(submitted.map(s => s.action),['configuration-form']);
});
test('one actual wrapper/harness run makes requests before expiry, after refresh, and after revocation without restart', async t => {