mirror of
https://github.com/block/buzz.git
synced 2026-11-30 05:02:57 +00:00
feat(beehive): connect saved OpenAI providers to Codex runtime bindings
Signed-off-by: Logan Johnson <loganj@squareup.com>
This commit is contained in:
@@ -17,7 +17,7 @@ This is an **incomplete candidate**, not the complete authorized prototype. No i
|
||||
|
||||
1. **Databricks v2 setup, native PKCE, OS custody and model catalog implemented.** Explicit provider open still prefills the URL; browser sign-in now calls the shared Rust owner through a built macOS arm64 helper. Verified OS storage precedes public CAS; cancellation cannot publish. Headless catalog/launch-preflight refresh uses Beehive-only entries. See `native/README.md` for the export recipe and the remaining static-token lifetime limit of an already-running stock harness. No Desktop credentials or JS OAuth engine.
|
||||
2. **Desktop-equivalent harness discovery/capability rules and effort are NOT implemented.** Only Buzz Agent PATH resolution is offered. No Codex version probe, adapter/CLI discovery contract, current Pi `buzz-pi-acp`, Goose/Claude/Codex provider combinations or model-specific effort propagation is claimed. Effort is explicitly unavailable, never guessed.
|
||||
3. Optional relay display name is not captured yet; URL-only footer is truthful. There is no fabricated relay name.
|
||||
3. Optional relay display name is now captured by bounded NIP-11 metadata (relay integration dfa54c7b8). Exact URL and actual state remain authoritative; failure/stale/cancel yields URL-only.
|
||||
4. Catalogs are deliberately append-only. There is no edit/delete/migration UI. Credential-attempt references are retained for explicit recovery; a public save failure can leave an OS entry. Do not delete retained attempts automatically.
|
||||
5. Local service currently requires a Unix socket path of at most 100 bytes and an owner-only host directory. Windows transport is not implemented. The intended desktop/laptop target is macOS.
|
||||
6. Large catalogs still need an explicit management-wire headroom gate before adoption. The catalog permits up to 100 rows while a management message is bounded at 32 KiB; verify/restrict the projected inventory against that limit before release. The small integrated flow does not establish large-inventory behavior.
|
||||
@@ -56,7 +56,7 @@ Recovered 78f0c373 without restarting its implementation. This continuation adds
|
||||
2. **Databricks v2 continuation a7e21caa:** `PkceOAuthTokenSource::new_with_custody` bypasses all token-file reads/writes; the default Desktop/CLI cache behavior is unchanged. New `beehive-databricks` binary uses native Beehive OS entries, verified writes, exact-account cross-process locking, shared PKCE and the canonical v2 model union/filter implementation. Built release Mach-O arm64 and helper package at `/Users/loganj/.buzz/artifacts/beehive-databricks-a7e21caa/`; reproducible scoped recipe in `native/README.md`. Future exports must merge the helper into their Beehive `bin/`; no installed package was changed. Start obtains a refreshed access token, but a running stock harness does not yet have continuous OAuth refresh.
|
||||
3. **Harness discovery:** still Buzz Agent PATH-only; Desktop-equivalent adapter/CLI/version rules remain required. Prior-art plan has exact source owners and current Pi correction. No discovery rewrite made.
|
||||
4. **Models/effort:** existing OpenAI listing/custom model retained; Databricks now uses the shared native authenticated catalog and custom-model path. Supported harness-specific effort selection/launch propagation remains required. Synthetic Databricks native auth/store/refresh/catalog and host Save/Start/ACP evidence is recorded in the a7e21caa artifact; no live-provider or effort evidence is claimed.
|
||||
5. **Relay:** URL/actual connection state retained; optional metadata name capture still missing. No network fetch added.
|
||||
5. **Relay:** integrated bounded optional NIP-11 name; exact URL/actual state retained. Fetch is unauthenticated, size/deadline bounded, cancellation/stale fenced; failures remain nameless.
|
||||
6. **Wire:** pre-adoption actual representation gate and shared producer/consumer ceiling added and tested. Residual: 8 KiB reserve is conservative headroom, NOT proof that arbitrarily growing assignment/run history fits forever. It also applies to legacy startup inventories; unusually large existing inventories can now refuse startup even if below 32 KiB. Assess this compatibility boundary before release. Existing send failure handling does not constitute a future-lifecycle fit proof.
|
||||
7. **Lifecycle/failures:** new service teardown/unauthorized-stop coverage passes. Broader credential helper late-completion/cancellation/failure matrix remains incomplete. Existing active-run immutability fixture still passes.
|
||||
|
||||
@@ -139,3 +139,26 @@ never enter the new proxy. Shared launch/ownership remains touched; Larry must
|
||||
assess the final combined suite after relay integration, not waive older failures.
|
||||
No push/install/publication. Capability-specific non-Buzz provider integration and
|
||||
live-account readiness are not claimed by this component.
|
||||
|
||||
|
||||
## Adapter continuation 9b0f8958 (incomplete assignment)
|
||||
|
||||
Relay-name commit is integrated (dfa54c7b8). Codex × saved OpenAI now uses the
|
||||
existing Codex launch schema: detected >=1.10.0 adapter and separate CLI, saved
|
||||
exact custom model, OS-only immutable credential reference, host admission read,
|
||||
OPENAI_API_KEY and JSON CODEX_CONFIG model override, separate HOME/CODEX_HOME,
|
||||
ACP protocol 2 exact-model evidence, existing owned Stop. No generic effort is
|
||||
offered (Desktop agentConfigCore owns it via model ID). No new native code or
|
||||
proxy routes. Legacy explicit Codex key-file bindings remain separate; an OS
|
||||
binding cannot fall back to a file.
|
||||
|
||||
This does NOT complete the requested non-Buzz matrix. Pi execution/provider
|
||||
integration and non-Buzz Databricks integration are still absent. Claude remains
|
||||
provider-locked in the cited Desktop catalog; Claude × OpenAI is not offered.
|
||||
Do not publish this as BUILD IT ALL complete. Current source inspection did not
|
||||
establish a Desktop-owned Pi/Codex/Claude Databricks launch adapter; implementing
|
||||
such transport still requires the actual adapter protocol/config contract, not
|
||||
merely sending BUZZ_AGENT_PROVIDER to an unrelated process.
|
||||
|
||||
Evidence for this continuation, final suite and remaining work:
|
||||
`/Users/loganj/.buzz/artifacts/beehive-adapter-integration-9b0f8958/INTEGRATION_RESULT.md`.
|
||||
|
||||
@@ -39,7 +39,7 @@ export function prepareAgent(input: AgentLaunch) {
|
||||
if (plan.harness === 'codex') {
|
||||
identifier(plan.model);
|
||||
if (plan.args.length || !plan.codex || !plan.codex.models.includes(plan.model) || plan.home === plan.configDirectory) throw Error('Codex requires zero-argument adapter, approved model and distinct HOME/CODEX_HOME');
|
||||
return Object.freeze({ plan, executableHash: hash(readFileSync(plan.executable)), env: Object.freeze(codexEnvironment(plan.codex, plan.home, plan.configDirectory, plan.model)), cliExecutableHash: hash(readFileSync(plan.codex.cli)) });
|
||||
return Object.freeze({ plan, executableHash: hash(readFileSync(plan.executable)), env: Object.freeze(codexEnvironment(plan.codex, plan.home, plan.configDirectory, plan.model, plan.resolvedProviderKey)), cliExecutableHash: hash(readFileSync(plan.codex.cli)) });
|
||||
}
|
||||
if (plan.harness === 'claude') {
|
||||
identifier(plan.model);
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import { accessSync, constants, readFileSync, realpathSync, statSync } from 'node:fs';
|
||||
import type { ProviderReference } from './settings.ts';
|
||||
import { dirname, isAbsolute } from 'node:path';
|
||||
|
||||
/** Pinned Buzz 051c3a2 pool.rs:295–320: Codex native systemPrompt requires protocol 2. */
|
||||
export const CODEX_ADAPTER = 'codex-acp';
|
||||
/** Local-only Codex API-key binding. ChatGPT subscription login caches and custom providers are not inferred. */
|
||||
export type CodexSetup = { cli: string; apiKeyFile: string; models: string[] };
|
||||
export type CodexSetup = { cli: string; apiKeyFile?: string; credential?: ProviderReference; models: string[] };
|
||||
/** Validate private inputs without reading a credential during offline setup. */
|
||||
export function validateCodex(value: CodexSetup): void {
|
||||
if (!value || !isAbsolute(value.cli) || !isAbsolute(value.apiKeyFile) || !Array.isArray(value.models) || !value.models.length || value.models.length > 100 || value.models.some(m => typeof m !== 'string' || !/^[a-zA-Z0-9_.:/-]{1,200}$/.test(m))) throw Error('Invalid local Codex CLI/key-file/models binding');
|
||||
if (!value || !isAbsolute(value.cli) || (value.credential ? value.apiKeyFile !== undefined || value.credential.service !== 'beehive' || !/^provider:[0-9a-f-]{36}$/.test(value.credential.account) : typeof value.apiKeyFile !== 'string' || !isAbsolute(value.apiKeyFile)) || !Array.isArray(value.models) || !value.models.length || value.models.length > 100 || value.models.some(m => typeof m !== 'string' || !/^[a-zA-Z0-9_.:/-]{1,200}$/.test(m))) throw Error('Invalid local Codex CLI/key-file/models binding');
|
||||
}
|
||||
/** Build a closed service-user env. A local key is a prerequisite, NOT authentication proof. */
|
||||
export function codexEnvironment(value: CodexSetup, home: string, configDirectory: string, model: string): Record<string, string> {
|
||||
export function codexEnvironment(value: CodexSetup, home: string, configDirectory: string, model: string, resolvedKey?: string): Record<string, string> {
|
||||
validateCodex(value);
|
||||
try {
|
||||
if (realpathSync(value.cli) !== value.cli) throw Error();
|
||||
@@ -18,11 +19,16 @@ export function codexEnvironment(value: CodexSetup, home: string, configDirector
|
||||
} catch { throw Error('Codex CLI missing/noncanonical; install Codex locally as the service user. No install initiated'); }
|
||||
let key: string;
|
||||
try {
|
||||
const st = statSync(value.apiKeyFile);
|
||||
if (realpathSync(value.apiKeyFile) !== value.apiKeyFile || !st.isFile() || st.size > 16384 || (st.mode & 0o077) !== 0 || st.uid !== process.getuid?.()) throw Error();
|
||||
key = readFileSync(value.apiKeyFile, 'utf8').trim();
|
||||
if (!key || /[\s\0]/.test(key)) throw Error();
|
||||
} catch { throw Error('Codex API key prerequisite missing/unsafe locally; provision an owner-only key file as the service user. No login initiated'); }
|
||||
if (value.credential) {
|
||||
if (!resolvedKey || resolvedKey.length > 16384 || /[\s\0]/.test(resolvedKey)) throw Error();
|
||||
key = resolvedKey;
|
||||
} else {
|
||||
const st = statSync(value.apiKeyFile!);
|
||||
if (realpathSync(value.apiKeyFile!) !== value.apiKeyFile || !st.isFile() || st.size > 16384 || (st.mode & 0o077) !== 0 || st.uid !== process.getuid?.()) throw Error();
|
||||
key = readFileSync(value.apiKeyFile!, 'utf8').trim();
|
||||
if (!key || /[\s\0]/.test(key)) throw Error();
|
||||
}
|
||||
} catch { throw Error(value.credential ? 'Codex OS provider credential unavailable; repair the saved OpenAI provider. No file fallback or login initiated' : 'Codex API key prerequisite missing/unsafe locally; provision an owner-only key file as the service user. No login initiated'); }
|
||||
return { PATH: `${dirname(value.cli)}:${dirname(process.execPath)}:/usr/bin:/bin`, HOME: home, CODEX_HOME: configDirectory, OPENAI_API_KEY: key, CODEX_CONFIG: JSON.stringify({ model }) };
|
||||
}
|
||||
/** Positive same-session startup model report, never a fabricated set_model RPC ACK. */
|
||||
|
||||
@@ -78,7 +78,7 @@ export async function discoverHarnesses(signal: AbortSignal, options: { home?: s
|
||||
let state: DetectedHarness['state'] = !binary ? 'not-installed' : row.underlyingCli && !cli ? 'cli-missing' : 'available';
|
||||
if (state === 'available' && row.id === 'codex' && !compatibleCodex(await probe(binary!, ['--version'], [...managed, path].join(delimiter), home, signal) ?? '')) state = 'incompatible';
|
||||
signal.throwIfAborted();
|
||||
const providers = state === 'available' && row.id === 'buzz-agent' ? ['openai', 'databricks_v2'] : [];
|
||||
const providers = state === 'available' && row.id === 'buzz-agent' ? ['openai', 'databricks_v2'] : state === 'available' && row.id === 'codex' ? ['openai'] : [];
|
||||
const reason = state === 'not-installed' ? 'Not installed' : state === 'cli-missing' ? `Underlying ${row.underlyingCli} CLI not installed` : state === 'incompatible' ? 'Codex ACP 1.10.0 or newer required; version unknown/outdated' : providers.length ? 'Detected; provider/model access unverified' : 'Detected; this catalog’s OS-backed providers are not supported by this adapter. Use existing local setup for native authentication.';
|
||||
result.push({ id: row.id, label: row.label!, executable: binary, cli, state, providers, reason });
|
||||
}
|
||||
|
||||
@@ -241,10 +241,11 @@ function slot(setup: Setup, path: string, agent: string, currentSetup: (id: stri
|
||||
accessSync(setup.runner, constants.X_OK);
|
||||
if (realpathSync(selected.workspace) !== selected.workspace || !statSync(selected.workspace).isDirectory()) throw Error('Workspace changed');
|
||||
let resolvedProviderKey: string | undefined;
|
||||
if (setup.buzzProvider?.credential) {
|
||||
const providerCredential = setup.buzzProvider?.credential ?? (setup.mode === 'codex' ? setup.codex?.credential : undefined);
|
||||
if (providerCredential) {
|
||||
const controller = new AbortController(); credentialRead = controller;
|
||||
try {
|
||||
const result = await providerRead({ action: 'provider-read', provider:setup.buzzProvider.provider, host:setup.buzzProvider.baseUrl, key: setup.buzzProvider.credential }, controller.signal);
|
||||
const result = await providerRead({ action: 'provider-read', provider:setup.buzzProvider?.provider ?? 'openai-compat', host:setup.buzzProvider?.baseUrl ?? 'https://api.openai.com/v1', key: providerCredential }, controller.signal);
|
||||
controller.signal.throwIfAborted();
|
||||
if (closing || retracting(revision) || state.revision !== revision || hash(state.assignment) !== assignment || hash(state.selected) !== selectionBefore) throw Error('Provider admission invalidated');
|
||||
resolvedProviderKey = result.secret; result.secret = undefined;
|
||||
|
||||
@@ -273,9 +273,11 @@ A Stop result is not a recent host report that confirms the agent is stopped.` }
|
||||
const provider = readSettings(this.hostDirectory).providers.find(p => p.id === v.provider);
|
||||
const result = provider?.type === 'databricks_v2' ? await databricksNative({ action: 'models',host:provider.endpoint,key:provider.key },abort.signal) : await this.credential({ action: 'models', directory: this.hostDirectory, provider: v.provider },abort.signal); check(); this.models = result.models; this.status = 'Model list loaded. Custom model is also available.';
|
||||
} else if (request.action === 'add-runtime') {
|
||||
if (!this.runtimeExecutable || (v.harness ?? 'buzz-agent') !== 'buzz-agent') throw plain('No supported executable found.');
|
||||
const selected = this.harnesses?.find(h => h.id === (v.harness ?? 'buzz-agent'));
|
||||
const previous = readSettings(this.hostDirectory);
|
||||
saveSettings(this.hostDirectory,{ ...previous, runtimes: [...previous.runtimes,{ id: settingsId(), name: v.name ?? '', harness: 'buzz-agent', executable: this.runtimeExecutable, providerId: v.provider ?? '', model: v.model ?? '', ...(v.effort ? { effort: v.effort } : {}) }] },previous.revision);
|
||||
const provider = previous.providers.find(p => p.id === v.provider);
|
||||
if (!selected?.executable || !provider || !selected.providers.includes(provider.type) || !['buzz-agent','codex'].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', executable: selected.executable, ...(selected.id === 'codex' ? { cli: selected.cli } : {}), providerId: v.provider ?? '', model: v.model ?? '', ...(v.effort ? { effort: v.effort } : {}) }] },previous.revision);
|
||||
this.status = 'Runtime saved for new runs. Running agents did not change. Host loading is reported separately.';
|
||||
} else if (request.action === 'host-start') {
|
||||
this.service = await startService(this.hostDirectory); check(); this.status = 'Host running. Registration and settings do not start agents.';
|
||||
|
||||
@@ -23,7 +23,7 @@ export async function runtimeForm(screen: {
|
||||
const models = snapshot().models;
|
||||
const choiceModel = await screen.choose(models ? 'Model' : 'Model listing unavailable · Custom model allowed', [...(models ?? []), 'Custom model']); if (!choiceModel) return;
|
||||
const model = choiceModel === 'Custom model' ? await screen.input('Exact model ID. Custom does not verify provider access.') : choiceModel; if (!model) return;
|
||||
const efforts = runtimeEfforts(provider.type, model);
|
||||
const efforts = selected.id === 'buzz-agent' ? runtimeEfforts(provider.type, model) : [];
|
||||
const effort = efforts.length ? await screen.choose('Effort · new runs only', ['Inherit', ...efforts]) : 'Inherit'; if (!effort) return;
|
||||
const name = await screen.input('Runtime name', model); if (!name) return;
|
||||
if (await screen.confirm(`Save ${name}?\n${selected.label} · ${provider.name} · ${model}\n${efforts.length ? `Effort: ${effort}` : 'No supported effort control for this model.'}\nSaved for new runs. Running agents do not change.`)) await request('add-runtime', { name, model, provider: provider.id, harness: selected.id, ...(effort !== 'Inherit' ? { effort } : {}) });
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { readSettings, type Settings } from './settings.ts';
|
||||
import { readSettings, validateSettings, type Settings } from './settings.ts';
|
||||
import { validateSetup, type Setup } from './host.ts';
|
||||
|
||||
/** Materialize reusable runtimes into an existing authorized slot's inventory.
|
||||
* Workspace, conversation authority and identity remain owned by that slot.
|
||||
* Catalog registration alone cannot create a slot or authorize execution. */
|
||||
export function runtimeBindings(base: Setup, settings: Settings): Record<string, Setup> {
|
||||
validateSettings(settings);
|
||||
if (!base.serviceHome || !base.configDirectory) return {};
|
||||
return Object.fromEntries(settings.runtimes.map(runtime => {
|
||||
const provider = settings.providers.find(p => p.id === runtime.providerId);
|
||||
@@ -13,8 +14,8 @@ export function runtimeBindings(base: Setup, settings: Settings): Record<string,
|
||||
host: base.host, ownerPublic: base.ownerPublic, ...(base.ownerSecret ? { ownerSecret: base.ownerSecret } : {}), ...(base.agentSecret ? { agentSecret: base.agentSecret } : {}),
|
||||
runner: runtime.executable, args: [], workspace: base.workspace, allowedWorkspaces: base.allowedWorkspaces,
|
||||
serviceHome: base.serviceHome, configDirectory: base.configDirectory,
|
||||
...(base.conversation ? { conversation: base.conversation } : {}), mode: 'buzz-agent-api-key',
|
||||
buzzProvider: provider.type === 'databricks_v2' ? { provider:'databricks_v2',auth:'token',baseUrl:provider.endpoint,credential:provider.key,models:[runtime.model],...(runtime.effort ? { effort:runtime.effort } : {}) } : { provider: 'openai-compat', baseUrl: provider.endpoint, credential: provider.key, wire: 'auto', models: [runtime.model], ...(runtime.effort ? { effort:runtime.effort } : {}) },
|
||||
...(base.conversation ? { conversation: base.conversation } : {}), ...(runtime.harness === 'codex' ? { mode: 'codex', codex: { cli: runtime.cli!, credential: provider.key, models: [runtime.model] } } : { mode: 'buzz-agent-api-key',
|
||||
buzzProvider: provider.type === 'databricks_v2' ? { provider:'databricks_v2',auth:'token',baseUrl:provider.endpoint,credential:provider.key,models:[runtime.model],...(runtime.effort ? { effort:runtime.effort } : {}) } : { provider: 'openai-compat', baseUrl: provider.endpoint, credential: provider.key, wire: 'auto', models: [runtime.model], ...(runtime.effort ? { effort:runtime.effort } : {}) } }),
|
||||
})];
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ export type RegisteredAgent = { publicKey: string; key: CredentialReference; pro
|
||||
/** Each provider version owns an exact immutable OS credential entry. */
|
||||
export type ProviderReference = { service: 'beehive'; account: string };
|
||||
export type SavedProvider = { id: string; name: string; type: 'openai' | 'databricks_v2'; endpoint: string; key: ProviderReference };
|
||||
export type SavedRuntime = { id: string; name: string; harness: 'buzz-agent'; executable: string; providerId: string; model: string; effort?: string };
|
||||
export type SavedRuntime = { id: string; name: string; harness: 'buzz-agent' | 'codex'; cli?: string; executable: string; providerId: string; model: string; effort?: string };
|
||||
export type Settings = { 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);
|
||||
@@ -26,14 +26,17 @@ export function validateSettings(value: Settings): Settings {
|
||||
if (a.profile && (typeof a.profile.relay !== 'string' || Object.values(a.profile).some(v => typeof v !== 'string' || v.length > 2048 || /[\x00-\x1f\x7f]/.test(v)))) throw Error('Invalid public profile');
|
||||
}
|
||||
for (const p of value.providers) if (!label(p.name) || !label(p.id) || !['openai','databricks_v2'].includes(p.type) || (p.type === 'openai' ? p.endpoint !== 'https://api.openai.com/v1' : databricksHost(p.endpoint) !== p.endpoint) || p.key?.service !== 'beehive' || !/^provider:[0-9a-f-]{36}$/.test(p.key.account)) throw Error('Invalid saved provider');
|
||||
for (const r of value.runtimes) if (!label(r.id) || !label(r.name) || r.harness !== 'buzz-agent' || !isAbsolute(r.executable) || !/^[a-zA-Z0-9_.:/-]{1,200}$/.test(r.model) || !value.providers.some(p => p.id === r.providerId)) throw Error('Invalid saved runtime');
|
||||
for (const r of value.runtimes) if (!label(r.id) || !label(r.name) || !['buzz-agent','codex'].includes(r.harness) || !isAbsolute(r.executable) || !/^[a-zA-Z0-9_.:/-]{1,200}$/.test(r.model) || !value.providers.some(p => p.id === r.providerId)) throw Error('Invalid saved runtime');
|
||||
for (const r of value.runtimes) {
|
||||
if (r.harness === 'codex' ? !r.cli || !isAbsolute(r.cli) || r.effort !== undefined || value.providers.find(p => p.id === r.providerId)?.type !== 'openai' : 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);
|
||||
// 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']);
|
||||
for (const a of value.agents) { fields(a, ['publicKey','key','profile','profileState']); if (a.profile) fields(a.profile, ['relay','name','picture','about']); }
|
||||
for (const p of value.providers) { fields(p, ['id','name','type','endpoint','key']); fields(p.key, ['service','account']); }
|
||||
for (const r of value.runtimes) fields(r, ['id','name','harness','executable','providerId','model','effort']);
|
||||
for (const r of value.runtimes) fields(r, ['id','name','harness','executable','providerId','model','effort','cli']);
|
||||
return structuredClone(value);
|
||||
}
|
||||
/** Absent settings means an empty catalog, never reconstructed credentials. */
|
||||
|
||||
@@ -68,3 +68,18 @@ for (const mode of ['ok', 'wrong-model', 'missing-native', 'wrong-protocol', 'mi
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
test('Codex OS provider binding requires the resolved exact-reference key and forbids file fallback', () => {
|
||||
const { dir, launch } = fixture();
|
||||
try {
|
||||
const codex = { cli: launch.codex!.cli, models: [launch.model], credential: { service: 'beehive' as const, account: 'provider:00000000-0000-0000-0000-000000000000' } };
|
||||
assert.throws(() => prepareAgent({...launch,codex}),/OS provider credential unavailable/);
|
||||
assert.throws(() => prepareAgent({...launch,codex,resolvedProviderKey:'bad key'}),/OS provider credential unavailable/);
|
||||
assert.throws(() => prepareAgent({...launch,codex:{...codex,apiKeyFile:launch.codex!.apiKeyFile},resolvedProviderKey:'synthetic'}),/Invalid local Codex/);
|
||||
const prepared = prepareAgent({...launch,codex,resolvedProviderKey:'synthetic-os-only'});
|
||||
assert.equal(prepared.env.OPENAI_API_KEY,'synthetic-os-only');
|
||||
assert.deepEqual(JSON.parse(prepared.env.CODEX_CONFIG!),{model:launch.model});
|
||||
assert.ok(!JSON.stringify(codex).includes('synthetic-os-only'));
|
||||
} finally { rmSync(dir,{recursive:true,force:true}); }
|
||||
});
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { createServer } from 'node:http';
|
||||
import { once } from 'node:events';
|
||||
import { addDatabricks } from '../src/databricks.ts';
|
||||
import { wrapManagement, unwrapManagement } from '../src/nostr-codec.ts';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, rmSync, existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
|
||||
import { mkdtempSync, mkdirSync, rmSync, existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { tmpdir } from 'node:os';
|
||||
@@ -72,26 +74,48 @@ test('OpenAI verifies store before public commit; listing is bounded and custom
|
||||
assert.throws(() => saveSettings(root,catalog,catalog.revision),/changed/);
|
||||
});
|
||||
|
||||
for (const providerType of ['openai','databricks_v2'] as const) test(`${providerType} saved runtime reaches host Save/new Start while the prior active run remains immutable`, async t => {
|
||||
for (const providerType of ['openai','databricks_v2','codex-openai'] as const) test(`${providerType} saved runtime reaches host Save/new Start while the prior active run remains immutable`, async t => {
|
||||
const root = fixture(t), owner = newKey(), agent = newKey(), hostKey = publicKey(newKey());
|
||||
const setup: Setup = { host: hostKey, ownerSecret: owner, agentSecret: agent, runner: realpathSync(process.execPath), args: ['-e','setInterval(()=>{},1000)'], workspace: root, serviceHome: root, configDirectory: root, mode: 'fixture' };
|
||||
const codex = providerType === 'codex-openai';
|
||||
const home = codex ? join(root,'service-home') : root, config = codex ? join(root,'agent-config') : root;
|
||||
if (codex) { mkdirSync(home); mkdirSync(config); }
|
||||
const setup: Setup = { host: hostKey, ownerSecret: owner, agentSecret: agent, runner: realpathSync(process.execPath), args: ['-e','setInterval(()=>{},1000)'], workspace: root, serviceHome: home, configDirectory: config, mode: 'fixture' };
|
||||
provision(root,setup,createGenesis(publicKey(owner),publicKey(agent),hostKey));
|
||||
let receive: (m: Message) => void = () => {}; const reports: Message[] = [];
|
||||
const transport = { binding: { host: hostKey, owner: publicKey(owner) }, validate() {}, connect(_url: string,_secret: string,handle: (m: Message) => void) { receive = handle; return { ready: Promise.resolve(), send(m: Message) { reports.push(m); }, close() {} }; } };
|
||||
let providerReads = 0;
|
||||
const running = await host(root,'ws://127.0.0.1',undefined,transport,undefined,async (input,signal) => { signal.throwIfAborted(); assert.equal((input as any).provider,providerType === 'openai' ? 'openai-compat' : 'databricks_v2'); if (providerType === 'databricks_v2') assert.equal((input as any).host,'https://fixture.example'); providerReads++; return {ok:true,secret:'synthetic-provider-key'}; });
|
||||
const running = await host(root,'ws://127.0.0.1',undefined,transport,undefined,async (input,signal) => { signal.throwIfAborted(); assert.equal((input as any).provider,providerType !== 'databricks_v2' ? 'openai-compat' : 'databricks_v2'); if (providerType === 'databricks_v2') assert.equal((input as any).host,'https://fixture.example'); providerReads++; return {ok:true,secret:codex ? 'fixture-codex-private-key' : 'synthetic-provider-key'}; });
|
||||
t.after(() => running.close());
|
||||
const start = message('start',hostKey,publicKey(agent),0); receive(start);
|
||||
await wait(() => reports.some(m => m.type === 'inventory' && m.body.phase === 'running'));
|
||||
const active = reports.filter(m => m.type === 'inventory').at(-1)!.body.actualRun;
|
||||
let stored: string | null = null;
|
||||
if (providerType === 'openai') addOpenAI(root,'Fixture','synthetic',{ read: () => stored, create(_r,v) { stored = v; } });
|
||||
if (providerType !== 'databricks_v2') addOpenAI(root,'Fixture','synthetic',{ read: () => stored, create(_r,v) { stored = v; } });
|
||||
else await addDatabricks(root,'Fixture','https://fixture.example',new AbortController().signal,async () => ({ok:true}));
|
||||
const prior = readSettings(root), id = settingsId();
|
||||
const model = providerType === 'openai' ? 'gpt-5' : 'databricks-gpt-5-4';
|
||||
const model = codex ? 'custom-codex-model' : providerType === 'openai' ? 'gpt-5' : 'databricks-gpt-5-4';
|
||||
const executable = join(root,'fixture-buzz-agent');
|
||||
writeFileSync(executable,`#!/bin/sh\n[ \"$BUZZ_AGENT_THINKING_EFFORT\" = high ] || exit 9\nexec '${process.execPath}' '${fileURLToPath(new URL('./acp-fixture.ts',import.meta.url))}' ${providerType === 'openai' ? 'openai' : 'databricks-os'}\n`,{mode:0o700});
|
||||
saveSettings(root,{ ...prior, runtimes: [{ id, name: 'Future', harness: 'buzz-agent', executable, providerId: prior.providers[0]!.id, model, effort: 'high' }] },prior.revision);
|
||||
let requests = 0;
|
||||
if (codex) {
|
||||
const server = createServer(async (req,res) => {
|
||||
assert.equal(req.method,'POST'); assert.equal(req.url,'/v1/responses');
|
||||
assert.equal(req.headers.authorization,'Bearer fixture-codex-private-key');
|
||||
let body = ''; for await (const chunk of req) body += chunk;
|
||||
assert.equal(JSON.parse(body).model,model); requests++;
|
||||
res.end('{"output":[]}');
|
||||
});
|
||||
server.listen(0,'127.0.0.1'); await once(server,'listening');
|
||||
t.after(() => new Promise<void>(resolve => server.close(() => resolve())));
|
||||
const endpoint = `http://127.0.0.1:${(server.address() as any).port}/v1/responses`;
|
||||
writeFileSync(join(root,'mode'),'ok');
|
||||
writeFileSync(executable,`#!${process.execPath}
|
||||
const response = await fetch(${JSON.stringify(endpoint)}, {method:'POST',headers:{authorization:'Bearer '+process.env.OPENAI_API_KEY},body:JSON.stringify({model:JSON.parse(process.env.CODEX_CONFIG).model})});
|
||||
if (!response.ok) throw Error('Synthetic provider rejected');
|
||||
await import(${JSON.stringify(new URL('./conversation-harness-fixture.ts',import.meta.url).href)});
|
||||
`,{mode:0o700});
|
||||
}
|
||||
saveSettings(root,{ ...prior, runtimes: [{ id, name: 'Future', harness: codex ? 'codex' : 'buzz-agent', executable, providerId: prior.providers[0]!.id, model, ...(codex ? {cli:realpathSync(process.execPath)} : {effort:'high'}) }] },prior.revision);
|
||||
await wait(() => running.settingsRevision === 2);
|
||||
await wait(() => reports.some(m => m.type === 'inventory' && (m.body.harnessSetups as any[]).some(r => r.id === `runtime:${id}`)));
|
||||
const inventory = reports.filter(m => m.type === 'inventory').at(-1)!;
|
||||
@@ -109,6 +133,7 @@ for (const providerType of ['openai','databricks_v2'] as const) test(`${provider
|
||||
assert.equal(reports.find(m => m.body.operation === nextStart.id)?.body.result,'accepted');
|
||||
assert.equal((reports.filter(m => m.type === 'inventory').at(-1)!.body.actualRun as any).selection.model,model);
|
||||
assert.equal(providerReads,1);
|
||||
if (codex) { assert.equal(requests,1); assert.ok(!readFileSync(join(root,'journal.json'),'utf8').includes('fixture-codex-private-key')); }
|
||||
assert.ok(!JSON.stringify(reports).includes('synthetic-provider-key'));
|
||||
assert.ok(!readFileSync(join(root,'journal.json'),'utf8').includes('synthetic-provider-key'));
|
||||
const invalid = { ...readSettings(root), revision: 3, runtimes: [] }; writePrivate(join(root,'settings.json'),invalid);
|
||||
|
||||
@@ -104,7 +104,7 @@ test('Desktop contract detects fake adapter/CLI independently, strict Codex vers
|
||||
assert.equal(rows.find(r => r.id === 'codex')?.state,'available');
|
||||
assert.equal(rows.find(r => r.id === 'claude')?.state,'cli-missing');
|
||||
assert.equal(rows.find(r => r.id === 'goose')?.state,'not-installed');
|
||||
assert.deepEqual(rows.filter(r => r.providers.length).map(r => r.id),['buzz-agent']);
|
||||
assert.deepEqual(rows.filter(r => r.providers.length).map(r => r.id),['codex','buzz-agent']);
|
||||
for (const value of ['1.9.99','1.10','1.10.0-rc1','not-version']) assert.equal(compatibleCodex(value),false);
|
||||
for (const value of ['1.10.0','pkg 2.0.0']) assert.equal(compatibleCodex(value),true);
|
||||
const slow = join(root,'slow'); writeFileSync(slow,'#!/bin/sh\nexec /bin/sleep 60\n',{mode:0o700});
|
||||
@@ -178,3 +178,12 @@ test('relay runtime never receives the OS-backed Databricks bearer', t => {
|
||||
assert.equal(plan.env.DATABRICKS_TOKEN,undefined);
|
||||
assert.ok(!JSON.stringify(plan.env).includes('synthetic-provider-token'));
|
||||
});
|
||||
|
||||
|
||||
test('Codex saved-provider matrix rejects Databricks, missing CLI and invented generic effort', () => {
|
||||
const settings: Settings = {version:1,revision:0,agents:[],providers:[{id:'p',name:'OpenAI',type:'openai',endpoint:'https://api.openai.com/v1',key}],runtimes:[{id:'r',name:'Custom Codex',harness:'codex',cli:process.execPath,executable:process.execPath,providerId:'p',model:'custom-codex-model'}]};
|
||||
assert.equal(validateSettings(settings).runtimes[0]!.model,'custom-codex-model');
|
||||
assert.throws(() => validateSettings({...settings,runtimes:[{...settings.runtimes[0]!,cli:undefined}]}),/combination/);
|
||||
assert.throws(() => validateSettings({...settings,runtimes:[{...settings.runtimes[0]!,effort:'high'}]}),/combination/);
|
||||
assert.throws(() => validateSettings({...settings,providers:[{...settings.providers[0]!,type:'databricks_v2',endpoint:'https://fixture.example'}]}),/combination/);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user