feat(beehive): checkpoint isolated TypeScript relay host and terminal slice

Signed-off-by: Logan Johnson <loganj@squareup.com>
This commit is contained in:
Logan Johnson
2026-09-09 22:26:24 -04:00
parent 051c3a270b
commit 94d1da0e81
14 changed files with 693 additions and 0 deletions

2
beehive/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
node_modules/
.state/

73
beehive/CHECKPOINT.md Normal file
View File

@@ -0,0 +1,73 @@
# Beehive implementation checkpoint
Scope: standalone TypeScript experimental package, no existing client changes.
Base origin/main 051c3a270be9c73da9ab06700bcab7d5552fceaa; branch beehive/cbfd9440.
First slice uses a dedicated, isolated loopback TypeScript WebSocket relay. It is
NOT a Buzz/Nostr relay extension: no kind allocations, production policy changes,
or promise of current Buzz relay admission. Ciphertext and signed envelopes are
stored/forwarded by relay, never direct-host HTTP. One locally provisioned owner
Nostr identity is shared by trusted, non-cloned controller/host installations.
Signatures cannot identify individual hosts sharing that key. Local admission
journal is safety state (necessary exception to only runtime/keys local); remote
configuration and receipts are also on relay. No controller service.
Implementation priorities: real network → validated contracts → durable host
admission/outbox → fixture runner lifecycle → line-oriented terminal UI.
Real Buzz Agent / Databricks v2 exact-model evidence is a separate gate; do not
claim fixture success proves authentication, model application or crash safety.
No owner credential stores may be accessed to remove that gate.
Pending parity: guided vendor setup, real ACP catalog/exact-model bridge,
Goose/Claude Code/Codex, ten presets/custom ACP, other Buzz Agent providers,
mesh transport, compute deployment, profiles/metadata, Restart/Move, key import
with saved-owner verification/revocation, service installation, reconnect UX.
No exclusion from requested parity is treated as owner-approved.
## Implemented milestone (2026-09-10)
Executable code: `src/protocol.ts` (runtime codecs, owner Schnorr signatures,
private AES-GCM envelopes), `storage.ts` (0600 atomic/fsynced writes), `relay.ts`
(real loopback WebSocket ciphertext persistence/fanout), `client.ts`, `host.ts`
(fixed local authority binding, exclusive lock, revisioned admission/fingerprints,
outbox, immutable fixture launch, owned process-group Stop), `cli.ts` (local
identity/guided setup, relay/host entry points, line-oriented TUI).
Validation: `npm test` passes 2 tests including actual external runner and
in-group descendant, actual TUI process close/reopen twice, relay client replay,
wrong-agent/revision/fingerprint rejection, exclusive host lock and changed
saved-agent binding rejection, clean host restart retaining stopped assignment.
Node 26.8.1. Fixture success is NOT real harness/model/OAuth success.
`node node_modules/typescript/bin/tsc --noEmit` was attempted and FAILS because
@types/node and @types/ws are unavailable. npm install from registry.npmjs.org
returned Block Cloudflare Dependency Confusion HTML; npm --offline ENOTCACHED.
Runtime tests use ignored symlinks to preinstalled public JS package dependencies
(documented in TESTING.md). No lockfile or clean-install claim. No policy bypass.
Repo-wide `just ci` was not run; no Rust/native/client files changed.
The existing relay explicitly rejects unknown kinds (`handlers/ingest.rs:436`)
and p-gated REQ authorization is kind-specific (`handlers/req.rs:1319`). This
prototype does not presume arbitrary private-kind admission or prove that no
future standard envelope can work; hosted/current-Buzz relay integration remains
an explicit unsolved boundary. Dedicated dev relay is intentionally distinct.
Real target: installed buzz-agent and buzz-acp found under /Applications/Buzz.app;
only an isolated-env auth-help attempt was made, returning DATABRICKS_HOST
required. No OAuth cache, owner key/profile or historical private store read.
Local option 2 records Databricks v2 target and displays blocked readiness;
Start fails closed. README gives the actual local OAuth command and gate.
Fresh-run next step: from `beehive/`, run `npm install && npm run check && npm test`
once approved npm access/types are available; fix all strict diagnostics and
create a lockfile before expanding the ACP bridge. If access remains blocked,
continue with cached-runtime tests and a targeted host-side catalog/exact-model
adapter, never weaken typing or claim model-ready based on spawn.
Known unfinished safety: no crash recovery beyond quarantine/exclusive lock,
no host reconnect, no relay ACK/TUI durable pending-intent store, no outbox
pruning, no OS containment against escaping descendants, no immutable executable
handle/script pinning, no hostile-local-journal validation/migration. No Move,
Restart, key import/revocation, real ACP bridge, multi-agent host, full profile
workflow or vendor parity. README has the concrete parity matrix. This is a
reviewable development checkpoint, not system completion or merge/release-ready.

138
beehive/README.md Normal file
View File

@@ -0,0 +1,138 @@
# Beehive (experimental first slice)
Standalone TypeScript host + relay + terminal UI. **Not Desktop parity, not
production-ready, not compatible with the current Buzz relay.** No existing
client, relay policy, credential store, or native service is changed.
A locally created owner secp256k1 identity signs encrypted commands/receipts.
Hosts retain fixed agent authority and supervise external processes. The TUI
can close while the host/runner continues. No direct-host HTTP API or controller
service exists. This package intentionally lives alongside, not inside, the
native clients: it is a separately authorized product experiment.
## Run an isolated fixture
Requires Node >=22.18 (tested with 26.8.1), POSIX process groups, npm dependencies.
```sh
cd beehive
npm install
npm test
npm run check
node src/cli.ts identity /tmp/my-beehive-owner
# Prints public key; never prints the private key.
node src/cli.ts setup /tmp/my-beehive-host /tmp/my-beehive-owner/identity.json
# Choose fixture, absolute Node executable, an allowed real workspace directory,
# and this package's absolute test/runner.ts path. Confirm NEW agent key creation.
node src/cli.ts relay 19481 <printed-owner-public-key> /tmp/my-beehive-relay.json
# Separate terminal:
node src/cli.ts host /tmp/my-beehive-host ws://127.0.0.1:19481
# Separate terminal:
node src/cli.ts tui /tmp/my-beehive-owner/identity.json ws://127.0.0.1:19481
```
TUI: `hosts`, `select <host-name>`, `show`, `start`, `save`, `stop`, `quit`.
Save asks for advertised model, workspace and independent behavior profile.
Only one fixture model and the `default` profile are currently supported;
profile authoring/versioning and useful multi-setup selection remain to build.
`show` separates selected-next and immutable actual-run snapshot. Save does not
restart. `quit` leaves the host running. Reopen TUI to inspect it; `stop` confirms
the owned process group is absent and leaves the agent assigned to this host.
Ctrl-C on **host** stops its owned fixture runner before exiting.
**Do not point fixture mode at real agents.** This seam deliberately passes no
agent key, OAuth context, model, or instructions to the fixture. Executable trust
is a local operator decision; remote messages cannot supply executable/args/env.
The runner must remain within its process group. Escaping descendants require
stronger OS containment before arbitrary harness support.
## Relay boundary and trust
Dedicated loopback-only WebSocket relay, not a Nostr relay, and no reserved kind
numbers. All application traffic is runtime-validated, Schnorr-signed and
AES-256-GCM-encrypted using a domain-separated owner-secret-derived key. The
relay is provisioned with only the owner public key, verifies publications and
stores ciphertext atomically before fanout. Local unauthenticated readers can
receive ciphertext and traffic metadata; this is NOT hosted private admission.
The protocol must receive independent cryptographic review before deployment.
Existing Buzz clients cannot consume these messages. Hosted compatibility needs
an independently validated private relay route/protocol decision; adding an
arbitrary Nostr kind is not an admission solution.
One dedicated owner shares signing/decryption authority with fully trusted host
installations. Host IDs route messages; they are NOT cryptographic host proof.
Agent identities are generated separately and only locally. Key import and
Move are disabled. Setup refuses an existing host directory; saved journal
bindings prevent owner/agent/host replacement from resetting admission.
An owner can still bypass software by cloning/recreating installations: safety
assumes non-cloned, non-rollback, exclusively supervised installations.
## Lifecycle claims and deliberate limits
- Exact operation ID/fingerprint and revision preconditions; durable admission
before effects, persistent replies/outbox, idempotent replay. No exactly-once
claim. Successful Start means process spawned, **not model/conversation ready**.
- Immutable captured selection/executable digest; executable and workspace
prerequisites checked immediately before fixture launch. Executable replacement
between check and spawn is outside this trusted-operator preview; full prepared
launch must pin all setup/credential/script generations and close that gap.
- Stop uses an in-lifetime child handle plus process group exit confirmation.
PID alone is never used for recovery. Failed/unexpected exit quarantines.
- Interrupted operation replies report reconciliation required. Abrupt host death
leaves an exclusive lock: restart is blocked, not an automatic PID-based
takeover. Local recovery tooling and crash-injection coverage remain pending.
**Do not remove locks just because a PID seems absent.**
- Local journals are necessary admission/safety/outbox records, not a second
remote authoring authority. Commands, configurations, receipts and inventory
cross the relay. Journal schema validation/migration and transactional scaling
remain pending; current journal is operator-trusted local state.
- Relay history max 10,000 envelopes, per-envelope limit, slow-reader disconnect.
Log full closes publisher; no compaction. Outbox retained without ACK pruning;
host auto-reconnect, relay ACKs and durable TUI pending intents are not yet
implemented. Lost connection means unknown, not stopped or success.
- Inventory has freshness, not liveness proof. Host starts no action based on peer
agent presence. Only its locally bound agent is manageable.
## Real target: Buzz Agent + Databricks v2
Local setup option 2 captures installed adapter path and HTTPS workspace URL,
creates a separate local agent identity, and advertises the target selection
`databricks-claude-haiku-4-5` as **blocked**, not discovered/model-ready. Start
fails closed because exact-model application evidence is not implemented.
Under the intended dedicated host-service OS user (not your Desktop context),
use an isolated configuration directory and the installed executable:
```sh
BUZZ_AGENT_CONFIG_DIR=<isolated-service-config-dir> \
DATABRICKS_HOST=https://<your-workspace> buzz-agent auth databricks
```
Buzz Agent owns its normal browser OAuth ceremony, workspace/client/scopes cache
and refresh. No static token is required. The actual workspace/account is a
human input; no login URL or successful authentication was observed in this
milestone. `buzz-acp models --json` is the next external catalog seam, but it
spawns an ACP session and does not prove exact-model application. Current main
has no strict `BUZZ_ACP_REQUIRED_MODEL` capability to assume. Neither owner nor
historical credential files were read/copied. An installed `buzz-agent auth
databricks --help` invocation in a scrubbed environment returned
`DATABRICKS_HOST required`; it was not a login/authentication test.
## Supported / remaining parity
| Surface | This slice | Required next work |
|---|---|---|
| Local owner/key setup | New owner + separately generated agent key | nsec import, saved-owner verification, revocation/key removal UX |
| Host inventory | Real relay, fixed authority, freshness | multiple setups/agents, service install, reconnect/reconciliation |
| Remote configuration | CAS model/workspace/default profile selection | reusable profiles, metadata, config history, setup revision pinning |
| Lifecycle | fixture Start/Stop, UI-independent host | strict real launch, Restart, host-owned irreversible Move |
| Buzz Agent Databricks v2 | Local setup + explicit blocked target | normal OAuth/capability/catalog bridge, exact-model evidence |
| Other Buzz Agent providers | Not implemented | Anthropic, OpenAI-compatible, Databricks legacy, OpenRouter |
| Goose / Claude Code / Codex | Not implemented | harness-specific local auth and adapters/catalog/launch |
| Ten presets / custom ACP | Not implemented | explicit executable/env trust, preset-specific capability grounding |
| OpenClaw Gateway | Not implemented | external containment/environment boundary |
| Relay mesh LLM mode | Not implemented | separate transport integration, not generic provider alias |
| Compute deployment providers | Not implemented | assess `buzz-backend-*` separately from LLM providers |
None of the remaining rows is an owner-approved exclusion from the requested
full parity. Review actual executable UX/security/lifecycle before expanding.

33
beehive/TESTING.md Normal file
View File

@@ -0,0 +1,33 @@
# Package validation
`npm test` runs Node's real TypeScript test runner. Test identities and stores
are fresh temporary owner-only resources. No production services or provider
credentials are required. `npm run check` performs strict TypeScript checking.
Automated evidence in `test/slice.test.ts`:
- malformed/wrong-owner/tampered envelope rejection;
- actual loopback WebSocket relay persistence and encrypted payload checks;
- external deterministic TypeScript runner Start/Stop;
- wrong-agent authority denial, operation fingerprint conflict, stale revision;
- selected-next Save while a run continues;
- two actual CLI TUI subprocess sessions, each showing running actual state and
quitting while the host survives;
- relay client close/reopen, duplicate retry, clean host close/restart with
assignment/revision retained.
Fixture is not an ACP agent or OAuth/model test. Crash-safe multi-host Move,
unknown descendant containment, relay outages/full log, host SIGKILL, hostile
local journal modifications and production private admission are not proven.
Current environment: registry.npmjs.org requests are redirected to Block's
Cloudflare Dependency Confusion block page (HTML rather than JSON). Offline npm
has no package metadata cache. Local tests use symlinks to already-installed
public JS packages from
`~/.local/lib/janet/a8d6cdb-darwin-arm64/package/candidate/node_modules/`
(`@noble/curves` 1.2.0, `ws` 8.21.0, TypeScript 5.9.3); no private Janet data is
used and nothing there was modified. Symlinks are ignored, not committed.
`@types/node` / `@types/ws` are not installed locally; typecheck currently fails
with missing declaration diagnostics. This is not a passing typecheck or a
reproducible clean install. Restore approved dependency access, generate a lock
file, run strict check and package tests before proposing merge/production use.
No policy bypass or alternate registry workaround was attempted.

1
beehive/package.json Normal file
View File

@@ -0,0 +1 @@
{"name":"@buzz/beehive","version":"0.0.1","private":true,"type":"module","engines":{"node":">=22.18"},"scripts":{"check":"tsc --noEmit","test":"node --test test/*.test.ts","start":"node src/cli.ts"},"dependencies":{"@noble/curves":"1.2.0","ws":"8.21.0"},"devDependencies":{"@types/node":"22.18.0","@types/ws":"8.18.1","typescript":"5.9.3"}}

93
beehive/src/cli.ts Normal file
View File

@@ -0,0 +1,93 @@
import { createInterface } from 'node:readline/promises';
import { stdin, stdout } from 'node:process';
import { existsSync, mkdirSync, realpathSync } from 'node:fs';
import { resolve, join } from 'node:path';
import { relay } from './relay.ts';
import { host } from './host.ts';
import { connect } from './client.ts';
import { message, newKey, publicKey, object, text, type Message } from './protocol.ts';
import { readPrivate, writePrivate } from './storage.ts';
const [command, ...args] = process.argv.slice(2);
const help = `Beehive — isolated development preview (loopback relay only)
identity <new-directory> Create a NEW local owner identity
setup <new-host-directory> <identity-file> Guided local harness + key setup
relay <port> <owner-public-key> <log-file> Dedicated ciphertext relay
host <host-directory> <ws://127.0.0.1:port> Persistent foreground host
tui <identity-file> <ws://127.0.0.1:port> Relay-connected terminal UI
No import, Move, provider login RPC or production relay support yet.`;
async function main() {
if (command === 'identity') {
const dir = resolve(text(args[0]));
mkdirSync(dir,{ mode: 0o700 });
const secret = newKey();
writePrivate(join(dir,'identity.json'),{ secret });
console.log(`Owner public key: ${publicKey(secret)}\nIdentity file: ${join(dir,'identity.json')}`);
} else if (command === 'setup') {
const dir = resolve(text(args[0]));
if (existsSync(dir)) throw Error('Use a new host directory; setup cannot reset authority');
const secret = text(object(readPrivate(resolve(text(args[1])))).secret);
const ui = createInterface({ input: stdin, output: stdout });
try {
const name = text(await ui.question('Host name: '));
const mode = await ui.question('Setup [1 deterministic fixture / 2 Buzz Agent + Databricks v2]: ');
if (!['1','2'].includes(mode)) throw Error('Choose 1 or 2');
const runner = realpathSync(text(await ui.question(mode === '1' ? 'Absolute fixture runner executable: ' : 'Absolute installed buzz-acp executable: ')));
const workspace = realpathSync(text(await ui.question('Allowed workspace (absolute directory): ')));
const extra = mode === '1' ? text(await ui.question('Absolute fixture TypeScript script: ')) : '';
const databricksHost = mode === '2' ? text(await ui.question('Databricks workspace HTTPS URL: ')) : undefined;
if (databricksHost && new URL(databricksHost).protocol !== 'https:') throw Error('HTTPS workspace required');
if ((await ui.question('Create a NEW agent identity assigned exclusively to this host? [yes/no]: ')) !== 'yes') return;
mkdirSync(dir,{ mode: 0o700 });
writePrivate(join(dir,'setup.json'),{ host: name, ownerSecret: secret, agentSecret: newKey(), runner, args: mode === '1' ? [resolve(extra)] : [], workspace, mode: mode === '1' ? 'fixture' : 'buzz-agent-databricks-v2', ...(databricksHost ? { databricksHost } : {}) });
console.log('Local setup saved. Start the host separately; the TUI never owns its lifetime.');
if (mode === '2') console.log(`Not authenticated or model-ready. Under the dedicated service OS user, with an isolated BUZZ_AGENT_CONFIG_DIR, run:\nDATABRICKS_HOST=${JSON.stringify(databricksHost)} buzz-agent auth databricks\nBuzz Agent owns browser OAuth/cache/refresh. Start is blocked until exact-model evidence is implemented.`);
} finally { ui.close(); }
} else if (command === 'relay') {
const server = await relay(Number(args[0]),text(args[1]),resolve(text(args[2])));
console.log(`Development relay listening ${JSON.stringify(server.address())}`);
process.once('SIGINT',() => { for (const c of server.clients) c.close(); server.close(); });
} else if (command === 'host') {
const running = await host(resolve(text(args[0])),text(args[1]));
console.log(`Host online; agent ${running.agent}. Ctrl-C stops owned runner before host exits.`);
process.once('SIGINT',() => { void running.close(); });
process.once('SIGTERM',() => { void running.close(); });
} else if (command === 'tui') {
const secret = text(object(readPrivate(resolve(text(args[0])))).secret);
const inventory = new Map<string,Message>();
const client = connect(text(args[1]),secret,m => {
if (m.type === 'inventory') {
const prior = inventory.get(m.host);
if (!prior || Number(m.body.observedAt) > Number(prior.body.observedAt)) inventory.set(m.host,m);
}
if (m.type === 'receipt') console.log(`\nHost receipt (may be replayed) ${m.body.operation}: ${JSON.stringify(m.body)}`);
});
await client.ready;
client.socket.on('close',() => console.log('\nRelay disconnected: live status and command outcomes UNKNOWN. Reopen TUI.'));
const ui = createInterface({ input: stdin, output: stdout });
console.log('Beehive | Hosts → assigned agent → selected-next / actual run\nCommands: hosts, select <host>, show, save, start, stop, quit. Closing this UI does not stop hosts.');
let selected = '';
try {
for (;;) {
const line = (await ui.question('beehive> ')).trim();
if (line === 'quit') break;
if (line === 'hosts') { for (const [name,m] of inventory) console.log(`${name}: ${m.body.phase} | ${m.body.readiness} | ${Date.now()-Number(m.body.observedAt) > 6000 ? 'STALE/UNKNOWN' : 'recent host report'}`); continue; }
if (line.startsWith('select ')) { selected = line.slice(7); continue; }
const current = inventory.get(selected);
if (!current) { console.log('Select an advertised host first.'); continue; }
if (line === 'show') { console.log(JSON.stringify(current,null,2)); continue; }
if (!['save','start','stop'].includes(line)) { console.log('Use hosts/select/show/save/start/stop/quit.'); continue; }
if (Date.now()-Number(current.body.observedAt) > 6000) { console.log('Host stale: status unknown; no action sent.'); continue; }
let body: Record<string, unknown> = {};
if (line === 'save') {
console.log(`Allowed models: ${JSON.stringify(current.body.models)}; workspaces: ${JSON.stringify(current.body.workspaces)}; behavior profiles: ${JSON.stringify(current.body.profiles)}`);
body = { model: await ui.question('Model: '), workspace: await ui.question('Workspace: '), profile: await ui.question('Behavior profile: ') };
}
const request = message(line as 'save' | 'start' | 'stop',selected,current.agent,current.revision,body);
client.send(request);
console.log(`Requested ${line} (${request.id}); publication is NOT host acceptance.`);
}
} finally { ui.close(); client.close(); }
} else console.log(help);
}
main().catch(error => { console.error(error instanceof Error ? error.message : 'Beehive failed'); process.exitCode = 1; });

18
beehive/src/client.ts Normal file
View File

@@ -0,0 +1,18 @@
import { WebSocket } from 'ws';
import { open, seal, type Message } from './protocol.ts';
/** All UI/host communication uses the real relay, never a host API. */
export function connect(url: string, secret: string, receive: (m: Message) => void) {
const endpoint = new URL(url);
if (endpoint.protocol !== 'ws:' || endpoint.hostname !== '127.0.0.1') throw Error('Development transport requires ws://127.0.0.1');
const socket = new WebSocket(url, { maxPayload: 70000 });
socket.on('message', data => {
try { receive(open(JSON.parse(data.toString()),secret)); } catch { /* Reject malformed/untrusted data, never print payloads. */ }
});
socket.on('error', () => {});
return {
socket,
ready: new Promise<void>((resolve,reject) => { socket.once('open',resolve); socket.once('error',reject); }),
send(m: Message) { if (socket.readyState !== WebSocket.OPEN) throw Error('Relay disconnected; result unknown'); socket.send(JSON.stringify(seal(m,secret))); },
close() { socket.close(); },
};
}

122
beehive/src/host.ts Normal file
View File

@@ -0,0 +1,122 @@
import { spawn, type ChildProcess } from 'node:child_process';
import { accessSync, constants, existsSync, mkdirSync, rmdirSync, realpathSync, statSync, readFileSync } from 'node:fs';
import { join, isAbsolute } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { connect } from './client.ts';
import { digest, fields, message, object, publicKey, text, type Message } from './protocol.ts';
import { readPrivate, writePrivate } from './storage.ts';
export type Setup = { host: string; ownerSecret: string; agentSecret: string; runner: string; args: string[]; workspace: string; mode: 'fixture' | 'buzz-agent-databricks-v2'; databricksHost?: string };
type Selection = { model: string; workspace: string; profile: string };
type State = { binding: { host: string; owner: string; agent: string }; revision: number; phase: 'stopped' | 'transitioning' | 'running' | 'quarantined'; selected: Selection; actual: null | { selection: Selection; executableHash: string; run: string }; operations: Record<string, { fingerprint: string; reply: Message }>; outbox: Message[] };
export function validateSetup(value: unknown): Setup {
const s = object(value);
for (const key of ['host','ownerSecret','agentSecret','runner','workspace']) text(s[key]);
publicKey(String(s.ownerSecret)); publicKey(String(s.agentSecret));
if (!isAbsolute(String(s.runner)) || !isAbsolute(String(s.workspace)) || !Array.isArray(s.args) || s.args.some(a => typeof a !== 'string') || !['fixture','buzz-agent-databricks-v2'].includes(String(s.mode))) throw Error('Invalid local setup');
return s as Setup;
}
/** Fixed-authority first slice. Keys never constitute a remote assignment grant. */
export async function host(directory: string, url: string) {
const setup = validateSetup(readPrivate(join(directory,'setup.json')));
const agent = publicKey(setup.agentSecret);
const lock = join(directory,'host.lock');
const path = join(directory,'journal.json');
let state: State = existsSync(path) ? readPrivate(path) as State : {
binding: { host: setup.host, owner: publicKey(setup.ownerSecret), agent }, revision: 0, phase: 'stopped', selected: { model: setup.mode === 'fixture' ? 'fixture-model' : 'databricks-claude-haiku-4-5', workspace: setup.workspace, profile: 'default' }, actual: null, operations: {}, outbox: [],
};
if (state.binding.host !== setup.host || state.binding.owner !== publicKey(setup.ownerSecret) || state.binding.agent !== agent) throw Error('Saved ownership/assignment mismatch');
mkdirSync(lock, { mode: 0o700 }); // No PID-only stale-lock recovery.
if (state.phase !== 'stopped') state.phase = 'quarantined';
const save = () => writePrivate(path,state);
save();
let child: ChildProcess | undefined;
function inventory() {
return message('inventory',setup.host,agent,state.revision, {
assignedHost: setup.host, phase: state.phase, selectedNext: state.selected, actualRun: state.actual,
setup: setup.mode, models: [setup.mode === 'fixture' ? 'fixture-model' : 'databricks-claude-haiku-4-5'],
workspaces: [setup.workspace], profiles: ['default'], readiness: setup.mode === 'fixture' ? 'fixture-only' : 'blocked: exact-model application evidence not implemented', observedAt: Date.now(),
});
}
let closing = false;
let queue = Promise.resolve();
const client = connect(url,setup.ownerSecret,m => { queue = queue.then(() => handle(m)).catch(() => { state.phase = 'quarantined'; save(); }); });
const publish = (m: Message) => { try { client.send(m); } catch { /* Durable outbox retained for reconnect/restart. */ } };
async function stopOwned() {
if (!child?.pid) throw Error('Unknown ownership; quarantined');
const pid = child.pid;
// Child handle from this host lifetime is required; never recover ownership from PID.
const exited = child.exitCode !== null || child.signalCode !== null;
if (!exited) process.kill(-pid,'SIGTERM');
for (let i = 0; i < 100; i++) {
try { process.kill(-pid,0); } catch (e) {
if ((e as NodeJS.ErrnoException).code === 'ESRCH') { child = undefined; return; }
throw e;
}
await delay(25);
}
throw Error('Owned process group did not exit; quarantined');
}
async function handle(m: Message) {
if (closing || m.host !== setup.host || !['inspect','save','start','stop'].includes(m.type)) return;
if (m.type === 'inspect') { publish(inventory()); return; }
const fingerprint = digest(JSON.stringify(m)).toString('hex');
const previous = Object.hasOwn(state.operations,m.id) ? state.operations[m.id] : undefined;
if (previous) {
publish(previous.fingerprint === fingerprint ? previous.reply : message('receipt',setup.host,m.agent,state.revision,{ operation: m.id, result: 'operation-id-conflict' })); return;
}
let result = 'accepted';
if (m.agent !== agent) result = 'not-authority';
else if (m.revision !== state.revision) result = 'revision-conflict';
else if (state.phase === 'quarantined' || state.phase === 'transitioning') result = 'quarantined';
else {
// Reserve operation before any spawn/kill; interrupted admission never retries effects.
const pending = message('receipt',setup.host,agent,state.revision,{ operation: m.id, result: 'interrupted-reconcile-locally' });
state.operations[m.id] = { fingerprint, reply: pending }; save();
try {
if (m.type === 'save') {
fields(m.body,['model','workspace','profile']);
const selected = { model: text(m.body.model), workspace: text(m.body.workspace), profile: text(m.body.profile) };
if (selected.model !== (setup.mode === 'fixture' ? 'fixture-model' : 'databricks-claude-haiku-4-5') || selected.workspace !== setup.workspace || selected.profile !== 'default') throw Error('Unsupported selection');
state.selected = selected; result = 'saved; running configuration unchanged';
} else if (m.type === 'start') {
fields(m.body,[]);
if (state.phase !== 'stopped') throw Error('Already running');
if (setup.mode !== 'fixture') throw Error('Exact-model application evidence unavailable');
accessSync(setup.runner,constants.X_OK);
if (realpathSync(setup.workspace) !== setup.workspace || !statSync(setup.workspace).isDirectory()) throw Error('Workspace changed');
state.actual = { selection: structuredClone(state.selected), executableHash: digest(readFileSync(setup.runner).toString('base64')).toString('hex'), run: m.id };
state.phase = 'transitioning'; save();
child = spawn(setup.runner,setup.args,{ cwd: state.selected.workspace, detached: true, stdio: 'ignore', env: { PATH: '/usr/bin:/bin', BEEHIVE_FIXTURE: '1' } });
await new Promise<void>((resolve,reject) => { child!.once('spawn',resolve); child!.once('error',reject); });
state.phase = 'running';
} else {
fields(m.body,[]);
if (state.phase !== 'stopped') {
state.phase = 'transitioning'; save(); await stopOwned(); state.phase = 'stopped'; state.actual = null;
}
}
state.revision++;
} catch (error) {
if (state.phase === 'transitioning') state.phase = 'quarantined';
result = error instanceof Error ? error.message : 'Operation failed';
}
}
const reply = message('receipt',setup.host,m.agent,state.revision,{ operation: m.id, result });
Object.defineProperty(state.operations,m.id,{ value: { fingerprint, reply }, enumerable: true, configurable: true, writable: true });
state.outbox.push(reply); save(); publish(reply); publish(inventory());
}
await client.ready;
for (const m of state.outbox) publish(m);
publish(inventory());
const heartbeat = setInterval(() => {
if (child && (child.exitCode !== null || child.signalCode !== null) && state.phase === 'running') { state.phase = 'quarantined'; save(); }
publish(inventory());
},2000);
return { agent, async close() {
if (closing) return; closing = true;
client.close(); clearInterval(heartbeat); await queue;
if (state.phase === 'running') { state.phase = 'transitioning'; save(); try { await stopOwned(); state.phase = 'stopped'; state.actual = null; } catch { state.phase = 'quarantined'; } }
save(); client.close(); rmdirSync(lock);
} };
}

63
beehive/src/protocol.ts Normal file
View File

@@ -0,0 +1,63 @@
import { createHash, createCipheriv, createDecipheriv, randomBytes, randomUUID } from 'node:crypto';
import { schnorr } from '@noble/curves/secp256k1';
/** Experimental private wire protocol; deliberately not a Nostr kind allocation. */
export type Message = { v: 1; id: string; host: string; agent: string; type: 'inspect' | 'save' | 'start' | 'stop' | 'inventory' | 'receipt'; revision: number; body: Record<string, unknown> };
export type Envelope = { v: 1; owner: string; nonce: string; ciphertext: string; tag: string; signature: string };
/** Reject unknown envelope/message fields, oversized values and ambiguous revisions. */
export function object(value: unknown): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) throw Error('Expected object');
return value as Record<string, unknown>;
}
export function text(value: unknown, max = 256): string {
if (typeof value !== 'string' || !value.length || value.length > max || /[\x00-\x1f\x7f]/.test(value)) throw Error('Invalid text');
return value;
}
export function fields(value: Record<string, unknown>, names: string[]) {
if (Object.keys(value).sort().join() !== names.sort().join()) throw Error('Unexpected fields');
}
export function parseMessage(value: unknown): Message {
const m = object(value);
fields(m, ['v','id','host','agent','type','revision','body']);
if (m.v !== 1 || !['inspect','save','start','stop','inventory','receipt'].includes(String(m.type)) || !Number.isSafeInteger(m.revision) || Number(m.revision) < 0) throw Error('Invalid message');
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(text(m.id))) throw Error('Invalid operation ID');
text(m.host); text(m.agent); object(m.body);
return m as Message;
}
export function digest(value: string): Buffer { return createHash('sha256').update(value).digest(); }
export function publicKey(secret: string): string { return Buffer.from(schnorr.getPublicKey(secret)).toString('hex'); }
export function newKey(): string { return Buffer.from(schnorr.utils.randomPrivateKey()).toString('hex'); }
function bytes(e: Omit<Envelope, 'signature'>): string { return JSON.stringify([e.v,e.owner,e.nonce,e.ciphertext,e.tag]); }
function encryptionKey(secret: string): Buffer { return digest(`beehive-private-v1:${secret}`); }
/** Encrypt before relay publication; the relay only receives the owner's public key. */
export function seal(message: Message, secret: string): Envelope {
parseMessage(message);
const nonce = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', encryptionKey(secret), nonce);
cipher.setAAD(Buffer.from('beehive-private-v1'));
const ciphertext = Buffer.concat([cipher.update(JSON.stringify(message)), cipher.final()]).toString('hex');
const e = { v: 1 as const, owner: publicKey(secret), nonce: nonce.toString('hex'), ciphertext, tag: cipher.getAuthTag().toString('hex') };
return { ...e, signature: Buffer.from(schnorr.sign(digest(bytes(e)), secret)).toString('hex') };
}
export function verifyEnvelope(value: unknown, owner: string): Envelope {
const e = object(value);
fields(e, ['v','owner','nonce','ciphertext','tag','signature']);
if (e.v !== 1 || e.owner !== owner) throw Error('Wrong owner/protocol');
for (const [key, length] of [['nonce',24],['tag',32],['signature',128]] as const) {
if (typeof e[key] !== 'string' || e[key].length !== length || !/^[0-9a-f]+$/.test(e[key])) throw Error('Invalid envelope');
}
if (typeof e.ciphertext !== 'string' || e.ciphertext.length > 65536 || !/^(?:[0-9a-f]{2})+$/.test(e.ciphertext)) throw Error('Invalid ciphertext');
const envelope = e as Envelope;
if (!schnorr.verify(envelope.signature, digest(bytes(envelope)), owner)) throw Error('Invalid signature');
return envelope;
}
export function open(value: unknown, secret: string): Message {
const e = verifyEnvelope(value, publicKey(secret));
const decipher = createDecipheriv('aes-256-gcm', encryptionKey(secret), Buffer.from(e.nonce,'hex'));
decipher.setAAD(Buffer.from('beehive-private-v1'));
decipher.setAuthTag(Buffer.from(e.tag,'hex'));
return parseMessage(JSON.parse(Buffer.concat([decipher.update(Buffer.from(e.ciphertext,'hex')),decipher.final()]).toString()));
}
export function message(type: Message['type'], host: string, agent: string, revision = 0, body: Record<string, unknown> = {}): Message {
return { v: 1, id: randomUUID(), type, host, agent, revision, body };
}

32
beehive/src/relay.ts Normal file
View File

@@ -0,0 +1,32 @@
import { WebSocketServer, WebSocket } from 'ws';
import { existsSync } from 'node:fs';
import { verifyEnvelope, type Envelope } from './protocol.ts';
import { readPrivate, writePrivate } from './storage.ts';
/** Isolated dev relay: loopback-only, one admitted owner, bounded durable ciphertext log. */
export async function relay(port: number, owner: string, path: string) {
if (!/^[0-9a-f]{64}$/.test(owner)) throw Error('Invalid owner public key');
const history: Envelope[] = existsSync(path) ? (readPrivate(path) as unknown[]).map(e => verifyEnvelope(e,owner)) : [];
const known = new Set(history.map(e => e.signature));
const server = new WebSocketServer({ host: '127.0.0.1', port, maxPayload: 70000 });
server.on('connection', socket => {
// Ciphertext only. Authenticated writes; unauthenticated local readers learn traffic metadata.
for (const e of history) socket.send(JSON.stringify(e));
socket.on('error', () => {});
socket.on('message', data => {
try {
const e = verifyEnvelope(JSON.parse(data.toString()),owner);
if (known.has(e.signature)) return;
if (history.length >= 10000) throw Error('Development relay log full');
writePrivate(path,[...history,e]);
history.push(e); known.add(e.signature);
for (const client of server.clients) if (client.readyState === WebSocket.OPEN) {
if (client.bufferedAmount > 1000000) client.close(1008,'Slow reader');
else client.send(JSON.stringify(e));
}
} catch { socket.close(1008,'Invalid or unavailable publication'); }
});
});
await new Promise<void>((resolve,reject) => { server.once('listening',resolve); server.once('error',reject); });
return server;
}

18
beehive/src/storage.ts Normal file
View File

@@ -0,0 +1,18 @@
import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync, lstatSync } from 'node:fs';
import { dirname } from 'node:path';
import { randomUUID } from 'node:crypto';
/** Private atomic replacement, including file/directory fsync. Parent must be operator-owned. */
export function writePrivate(path: string, value: unknown): void {
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
const temp = `${path}.${randomUUID()}.tmp`;
const fd = openSync(temp, 'wx', 0o600);
try { writeFileSync(fd, JSON.stringify(value)); fsyncSync(fd); } finally { closeSync(fd); }
renameSync(temp,path);
const dir = openSync(dirname(path),'r');
try { fsyncSync(dir); } finally { closeSync(dir); }
}
export function readPrivate(path: string): unknown {
const stat = lstatSync(path);
if (!stat.isFile() || (stat.mode & 0o077)) throw Error('Local file must be regular and owner-only');
return JSON.parse(readFileSync(path,'utf8'));
}

8
beehive/test/runner.ts Normal file
View File

@@ -0,0 +1,8 @@
import { spawn } from 'node:child_process';
// Deterministic external fixture only: no AI, credentials, network or model claims.
if (process.env.BEEHIVE_FIXTURE !== '1') throw Error('Fixture must be explicitly enabled');
if (!process.argv.includes('--descendant')) {
spawn(process.execPath,[process.argv[1],'--descendant'], { stdio: 'ignore' });
}
setInterval(() => {},1000);
process.on('SIGTERM',() => process.exit(0));

View File

@@ -0,0 +1,91 @@
import { spawn } from 'node:child_process';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, readFileSync, rmSync, realpathSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { newKey, publicKey, seal, open, message, parseMessage, type Message } from '../src/protocol.ts';
import { writePrivate } from '../src/storage.ts';
import { relay } from '../src/relay.ts';
import { host } from '../src/host.ts';
import { connect } from '../src/client.ts';
test('validated, encrypted, owner-authenticated envelopes',() => {
const key = newKey(); const m = message('start','host','agent');
const e = seal(m,key);
assert.deepEqual(open(e,key),m);
assert.throws(() => open(e,newKey()));
assert.throws(() => open({...e,ciphertext:'00'},key));
assert.throws(() => parseMessage({...m,revision:-1}));
assert.throws(() => parseMessage({...m,secret:'bad'}));
});
test('real websocket relay, external runner, durable retry, UI close/reopen, host restart',async () => {
const dir = realpathSync(mkdtempSync(join(tmpdir(),'beehive-test-')));
const secret = newKey(); const agentSecret = newKey(); const agent = publicKey(agentSecret);
const hostDir = join(dir,'host'); mkdirSync(hostDir);
writePrivate(join(hostDir,'setup.json'),{ host:'test-host',ownerSecret:secret,agentSecret,runner:process.execPath,args:[resolve('test/runner.ts')],workspace:dir,mode:'fixture' });
const log = join(dir,'relay.json');
const server = await relay(0,publicKey(secret),log);
const address = server.address(); assert.ok(address && typeof address !== 'string');
const url = `ws://127.0.0.1:${address.port}`;
const running = await host(hostDir,url);
await assert.rejects(host(hostDir,url),/EEXIST/);
let seen: Message[] = [];
let ui = connect(url,secret,m => seen.push(m)); await ui.ready;
async function wait(predicate: (m: Message) => boolean) {
for (let i=0;i<160;i++) { const m = seen.find(predicate); if (m) return m; await delay(25); }
throw Error('Timed out waiting for relay receipt');
}
async function request(m: Message) { ui.send(m); return wait(r => r.type === 'receipt' && r.body.operation === m.id); }
try {
await wait(m => m.type === 'inventory');
const wrong = await request(message('start','test-host',publicKey(newKey()),0)); assert.equal(wrong.body.result,'not-authority');
const start = message('start','test-host',agent,0);
assert.equal((await request(start)).body.result,'accepted');
await wait(m => m.type === 'inventory' && m.body.phase === 'running');
// Exercise the actual terminal executable twice, independently of the host.
const identity = join(dir,'identity.json'); writePrivate(identity,{secret});
for (let session = 0; session < 2; session++) {
const terminal = spawn(process.execPath,['src/cli.ts','tui',identity,url],{stdio:['pipe','pipe','pipe']});
let output = ''; let stage = 0;
terminal.stdout.on('data', chunk => {
output += chunk.toString();
if (output.endsWith('beehive> ')) {
const commands = ['hosts','select test-host','show','quit'];
const command = commands[stage++];
if (command) setTimeout(() => terminal.stdin.write(command+'\n'),100);
}
});
const code = await new Promise(resolve => terminal.once('exit',resolve));
assert.equal(code,0); assert.match(output,/actualRun/); assert.match(output,/running/);
}
ui.close(); seen = [];
ui = connect(url,secret,m => seen.push(m)); await ui.ready;
await wait(m => m.type === 'inventory' && m.body.phase === 'running');
assert.equal((await request(start)).revision,1);
assert.throws(() => parseMessage({...start,id:'__proto__'}));
const conflict = {...start,body:{unexpected:true}}; ui.send(conflict);
await wait(m => m.type === 'receipt' && m.body.result === 'operation-id-conflict');
assert.equal((await request(message('stop','test-host',agent,0))).body.result,'revision-conflict');
assert.equal((await request(message('save','test-host',agent,1,{model:'fixture-model',workspace:dir,profile:'default'}))).body.result,'saved; running configuration unchanged');
assert.equal((await request(message('stop','test-host',agent,2))).body.result,'accepted');
await wait(m => m.type === 'inventory' && m.body.phase === 'stopped' && m.revision === 3);
assert.ok(!readFileSync(log,'utf8').includes('fixture-model'));
assert.ok(!readFileSync(log,'utf8').includes(agentSecret));
await running.close();
const restarted = await host(hostDir,url);
try { seen = []; ui.send(message('inspect','test-host',agent)); await wait(m => m.type === 'inventory' && m.body.phase === 'stopped' && m.revision === 3); }
finally { await restarted.close(); }
const setupPath = join(hostDir,'setup.json');
const setup = JSON.parse(readFileSync(setupPath,'utf8'));
writePrivate(setupPath,{...setup,agentSecret:newKey()});
await assert.rejects(host(hostDir,url),/Saved ownership/);
} catch (e) { console.error(e); throw e; } finally {
try { await running.close(); } catch {}
ui.close(); for (const c of server.clients) c.terminate();
await new Promise<void>(resolve => server.close(() => resolve()));
rmSync(dir,{recursive:true,force:true});
}
});

1
beehive/tsconfig.json Normal file
View File

@@ -0,0 +1 @@
{"compilerOptions":{"target":"ES2023","module":"NodeNext","moduleResolution":"NodeNext","strict":true,"noEmit":true,"allowImportingTsExtensions":true,"esModuleInterop":true,"skipLibCheck":true},"include":["src/**/*.ts","test/**/*.ts"]}