Files
bzzz/mcp-server/node_modules/openai/index.js
anthonyrawlins b3c00d7cd9 Major BZZZ Code Hygiene & Goal Alignment Improvements
This comprehensive cleanup significantly improves codebase maintainability,
test coverage, and production readiness for the BZZZ distributed coordination system.

## 🧹 Code Cleanup & Optimization
- **Dependency optimization**: Reduced MCP server from 131MB → 127MB by removing unused packages (express, crypto, uuid, zod)
- **Project size reduction**: 236MB → 232MB total (4MB saved)
- **Removed dead code**: Deleted empty directories (pkg/cooee/, systemd/), broken SDK examples, temporary files
- **Consolidated duplicates**: Merged test_coordination.go + test_runner.go → unified test_bzzz.go (465 lines of duplicate code eliminated)

## 🔧 Critical System Implementations
- **Election vote counting**: Complete democratic voting logic with proper tallying, tie-breaking, and vote validation (pkg/election/election.go:508)
- **Crypto security metrics**: Comprehensive monitoring with active/expired key tracking, audit log querying, dynamic security scoring (pkg/crypto/role_crypto.go:1121-1129)
- **SLURP failover system**: Robust state transfer with orphaned job recovery, version checking, proper cryptographic hashing (pkg/slurp/leader/failover.go)
- **Configuration flexibility**: 25+ environment variable overrides for operational deployment (pkg/slurp/leader/config.go)

## 🧪 Test Coverage Expansion
- **Election system**: 100% coverage with 15 comprehensive test cases including concurrency testing, edge cases, invalid inputs
- **Configuration system**: 90% coverage with 12 test scenarios covering validation, environment overrides, timeout handling
- **Overall coverage**: Increased from 11.5% → 25% for core Go systems
- **Test files**: 14 → 16 test files with focus on critical systems

## 🏗️ Architecture Improvements
- **Better error handling**: Consistent error propagation and validation across core systems
- **Concurrency safety**: Proper mutex usage and race condition prevention in election and failover systems
- **Production readiness**: Health monitoring foundations, graceful shutdown patterns, comprehensive logging

## 📊 Quality Metrics
- **TODOs resolved**: 156 critical items → 0 for core systems
- **Code organization**: Eliminated mega-files, improved package structure
- **Security hardening**: Audit logging, metrics collection, access violation tracking
- **Operational excellence**: Environment-based configuration, deployment flexibility

This release establishes BZZZ as a production-ready distributed P2P coordination
system with robust testing, monitoring, and operational capabilities.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-16 12:14:57 +10:00

319 lines
18 KiB
JavaScript

"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnprocessableEntityError = exports.PermissionDeniedError = exports.InternalServerError = exports.AuthenticationError = exports.BadRequestError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.APIUserAbortError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIError = exports.OpenAIError = exports.fileFromPath = exports.toFile = exports.AzureOpenAI = exports.OpenAI = void 0;
const qs = __importStar(require("./internal/qs/index.js"));
const Core = __importStar(require("./core.js"));
const Errors = __importStar(require("./error.js"));
const Pagination = __importStar(require("./pagination.js"));
const Uploads = __importStar(require("./uploads.js"));
const API = __importStar(require("./resources/index.js"));
const batches_1 = require("./resources/batches.js");
const completions_1 = require("./resources/completions.js");
const embeddings_1 = require("./resources/embeddings.js");
const files_1 = require("./resources/files.js");
const images_1 = require("./resources/images.js");
const models_1 = require("./resources/models.js");
const moderations_1 = require("./resources/moderations.js");
const audio_1 = require("./resources/audio/audio.js");
const beta_1 = require("./resources/beta/beta.js");
const chat_1 = require("./resources/chat/chat.js");
const containers_1 = require("./resources/containers/containers.js");
const evals_1 = require("./resources/evals/evals.js");
const fine_tuning_1 = require("./resources/fine-tuning/fine-tuning.js");
const graders_1 = require("./resources/graders/graders.js");
const responses_1 = require("./resources/responses/responses.js");
const uploads_1 = require("./resources/uploads/uploads.js");
const vector_stores_1 = require("./resources/vector-stores/vector-stores.js");
const completions_2 = require("./resources/chat/completions/completions.js");
/**
* API Client for interfacing with the OpenAI API.
*/
class OpenAI extends Core.APIClient {
/**
* API Client for interfacing with the OpenAI API.
*
* @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined]
* @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]
* @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null]
* @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API.
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
* @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
*/
constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('OPENAI_API_KEY'), organization = Core.readEnv('OPENAI_ORG_ID') ?? null, project = Core.readEnv('OPENAI_PROJECT_ID') ?? null, ...opts } = {}) {
if (apiKey === undefined) {
throw new Errors.OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");
}
const options = {
apiKey,
organization,
project,
...opts,
baseURL: baseURL || `https://api.openai.com/v1`,
};
if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) {
throw new Errors.OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");
}
super({
baseURL: options.baseURL,
timeout: options.timeout ?? 600000 /* 10 minutes */,
httpAgent: options.httpAgent,
maxRetries: options.maxRetries,
fetch: options.fetch,
});
this.completions = new API.Completions(this);
this.chat = new API.Chat(this);
this.embeddings = new API.Embeddings(this);
this.files = new API.Files(this);
this.images = new API.Images(this);
this.audio = new API.Audio(this);
this.moderations = new API.Moderations(this);
this.models = new API.Models(this);
this.fineTuning = new API.FineTuning(this);
this.graders = new API.Graders(this);
this.vectorStores = new API.VectorStores(this);
this.beta = new API.Beta(this);
this.batches = new API.Batches(this);
this.uploads = new API.Uploads(this);
this.responses = new API.Responses(this);
this.evals = new API.Evals(this);
this.containers = new API.Containers(this);
this._options = options;
this.apiKey = apiKey;
this.organization = organization;
this.project = project;
}
defaultQuery() {
return this._options.defaultQuery;
}
defaultHeaders(opts) {
return {
...super.defaultHeaders(opts),
'OpenAI-Organization': this.organization,
'OpenAI-Project': this.project,
...this._options.defaultHeaders,
};
}
authHeaders(opts) {
return { Authorization: `Bearer ${this.apiKey}` };
}
stringifyQuery(query) {
return qs.stringify(query, { arrayFormat: 'brackets' });
}
}
exports.OpenAI = OpenAI;
_a = OpenAI;
OpenAI.OpenAI = _a;
OpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes
OpenAI.OpenAIError = Errors.OpenAIError;
OpenAI.APIError = Errors.APIError;
OpenAI.APIConnectionError = Errors.APIConnectionError;
OpenAI.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
OpenAI.APIUserAbortError = Errors.APIUserAbortError;
OpenAI.NotFoundError = Errors.NotFoundError;
OpenAI.ConflictError = Errors.ConflictError;
OpenAI.RateLimitError = Errors.RateLimitError;
OpenAI.BadRequestError = Errors.BadRequestError;
OpenAI.AuthenticationError = Errors.AuthenticationError;
OpenAI.InternalServerError = Errors.InternalServerError;
OpenAI.PermissionDeniedError = Errors.PermissionDeniedError;
OpenAI.UnprocessableEntityError = Errors.UnprocessableEntityError;
OpenAI.toFile = Uploads.toFile;
OpenAI.fileFromPath = Uploads.fileFromPath;
OpenAI.Completions = completions_1.Completions;
OpenAI.Chat = chat_1.Chat;
OpenAI.ChatCompletionsPage = completions_2.ChatCompletionsPage;
OpenAI.Embeddings = embeddings_1.Embeddings;
OpenAI.Files = files_1.Files;
OpenAI.FileObjectsPage = files_1.FileObjectsPage;
OpenAI.Images = images_1.Images;
OpenAI.Audio = audio_1.Audio;
OpenAI.Moderations = moderations_1.Moderations;
OpenAI.Models = models_1.Models;
OpenAI.ModelsPage = models_1.ModelsPage;
OpenAI.FineTuning = fine_tuning_1.FineTuning;
OpenAI.Graders = graders_1.Graders;
OpenAI.VectorStores = vector_stores_1.VectorStores;
OpenAI.VectorStoresPage = vector_stores_1.VectorStoresPage;
OpenAI.VectorStoreSearchResponsesPage = vector_stores_1.VectorStoreSearchResponsesPage;
OpenAI.Beta = beta_1.Beta;
OpenAI.Batches = batches_1.Batches;
OpenAI.BatchesPage = batches_1.BatchesPage;
OpenAI.Uploads = uploads_1.Uploads;
OpenAI.Responses = responses_1.Responses;
OpenAI.Evals = evals_1.Evals;
OpenAI.EvalListResponsesPage = evals_1.EvalListResponsesPage;
OpenAI.Containers = containers_1.Containers;
OpenAI.ContainerListResponsesPage = containers_1.ContainerListResponsesPage;
/** API Client for interfacing with the Azure OpenAI API. */
class AzureOpenAI extends OpenAI {
/**
* API Client for interfacing with the Azure OpenAI API.
*
* @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined]
* @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/`
* @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined]
* @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`.
* @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]
* @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`.
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
* @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
*/
constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('AZURE_OPENAI_API_KEY'), apiVersion = Core.readEnv('OPENAI_API_VERSION'), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) {
if (!apiVersion) {
throw new Errors.OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");
}
if (typeof azureADTokenProvider === 'function') {
dangerouslyAllowBrowser = true;
}
if (!azureADTokenProvider && !apiKey) {
throw new Errors.OpenAIError('Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.');
}
if (azureADTokenProvider && apiKey) {
throw new Errors.OpenAIError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.');
}
// define a sentinel value to avoid any typing issues
apiKey ?? (apiKey = API_KEY_SENTINEL);
opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion };
if (!baseURL) {
if (!endpoint) {
endpoint = process.env['AZURE_OPENAI_ENDPOINT'];
}
if (!endpoint) {
throw new Errors.OpenAIError('Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable');
}
baseURL = `${endpoint}/openai`;
}
else {
if (endpoint) {
throw new Errors.OpenAIError('baseURL and endpoint are mutually exclusive');
}
}
super({
apiKey,
baseURL,
...opts,
...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}),
});
this.apiVersion = '';
this._azureADTokenProvider = azureADTokenProvider;
this.apiVersion = apiVersion;
this.deploymentName = deployment;
}
buildRequest(options, props = {}) {
if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) {
if (!Core.isObj(options.body)) {
throw new Error('Expected request body to be an object');
}
const model = this.deploymentName || options.body['model'] || options.__metadata?.['model'];
if (model !== undefined && !this.baseURL.includes('/deployments')) {
options.path = `/deployments/${model}${options.path}`;
}
}
return super.buildRequest(options, props);
}
async _getAzureADToken() {
if (typeof this._azureADTokenProvider === 'function') {
const token = await this._azureADTokenProvider();
if (!token || typeof token !== 'string') {
throw new Errors.OpenAIError(`Expected 'azureADTokenProvider' argument to return a string but it returned ${token}`);
}
return token;
}
return undefined;
}
authHeaders(opts) {
return {};
}
async prepareOptions(opts) {
/**
* The user should provide a bearer token provider if they want
* to use Azure AD authentication. The user shouldn't set the
* Authorization header manually because the header is overwritten
* with the Azure AD token if a bearer token provider is provided.
*/
if (opts.headers?.['api-key']) {
return super.prepareOptions(opts);
}
const token = await this._getAzureADToken();
opts.headers ?? (opts.headers = {});
if (token) {
opts.headers['Authorization'] = `Bearer ${token}`;
}
else if (this.apiKey !== API_KEY_SENTINEL) {
opts.headers['api-key'] = this.apiKey;
}
else {
throw new Errors.OpenAIError('Unable to handle auth');
}
return super.prepareOptions(opts);
}
}
exports.AzureOpenAI = AzureOpenAI;
const _deployments_endpoints = new Set([
'/completions',
'/chat/completions',
'/embeddings',
'/audio/transcriptions',
'/audio/translations',
'/audio/speech',
'/images/generations',
'/images/edits',
]);
const API_KEY_SENTINEL = '<Missing Key>';
// ---------------------- End Azure ----------------------
var uploads_2 = require("./uploads.js");
Object.defineProperty(exports, "toFile", { enumerable: true, get: function () { return uploads_2.toFile; } });
Object.defineProperty(exports, "fileFromPath", { enumerable: true, get: function () { return uploads_2.fileFromPath; } });
var error_1 = require("./error.js");
Object.defineProperty(exports, "OpenAIError", { enumerable: true, get: function () { return error_1.OpenAIError; } });
Object.defineProperty(exports, "APIError", { enumerable: true, get: function () { return error_1.APIError; } });
Object.defineProperty(exports, "APIConnectionError", { enumerable: true, get: function () { return error_1.APIConnectionError; } });
Object.defineProperty(exports, "APIConnectionTimeoutError", { enumerable: true, get: function () { return error_1.APIConnectionTimeoutError; } });
Object.defineProperty(exports, "APIUserAbortError", { enumerable: true, get: function () { return error_1.APIUserAbortError; } });
Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return error_1.NotFoundError; } });
Object.defineProperty(exports, "ConflictError", { enumerable: true, get: function () { return error_1.ConflictError; } });
Object.defineProperty(exports, "RateLimitError", { enumerable: true, get: function () { return error_1.RateLimitError; } });
Object.defineProperty(exports, "BadRequestError", { enumerable: true, get: function () { return error_1.BadRequestError; } });
Object.defineProperty(exports, "AuthenticationError", { enumerable: true, get: function () { return error_1.AuthenticationError; } });
Object.defineProperty(exports, "InternalServerError", { enumerable: true, get: function () { return error_1.InternalServerError; } });
Object.defineProperty(exports, "PermissionDeniedError", { enumerable: true, get: function () { return error_1.PermissionDeniedError; } });
Object.defineProperty(exports, "UnprocessableEntityError", { enumerable: true, get: function () { return error_1.UnprocessableEntityError; } });
exports = module.exports = OpenAI;
module.exports.AzureOpenAI = AzureOpenAI;
exports.default = OpenAI;
//# sourceMappingURL=index.js.map