adapters
Classes
AdapterFactory
Defined in: packages/nexus-agents/src/adapters/factory.ts:79
Factory for creating and managing model adapters.
Implements the registry pattern to allow dynamic registration of adapter creators for different model providers. This enables a plugin-style architecture where new providers can be added without modifying core code.
Example
const factory = new AdapterFactory();
// Register a provider
factory.register('anthropic', (config) => new ClaudeAdapter(config));
// Create an adapter
const result = factory.create({
providerId: 'anthropic',
modelId: 'claude-sonnet-4'
});
if (result.ok) {
const adapter = result.value;
// Use adapter...
}
Constructors
Constructor
new AdapterFactory(): AdapterFactory;
Returns
Accessors
size
Get Signature
get size(): number;
Defined in: packages/nexus-agents/src/adapters/factory.ts:272
Returns the number of registered providers.
Returns
number
Count of registered providers
Methods
clear()
clear(): void;
Defined in: packages/nexus-agents/src/adapters/factory.ts:280
Clears all registered providers. Useful for testing or resetting the factory state.
Returns
void
create()
create(config): Result<IModelAdapter, ConfigError>;
Defined in: packages/nexus-agents/src/adapters/factory.ts:172
Creates an adapter instance for the specified configuration.
Validates the configuration against the schema, looks up the provider in the registry, and invokes the creator function to produce an adapter.
Parameters
config
Adapter configuration specifying provider and settings
apiKey?
string = ...
API key for authentication (optional, may come from environment)
baseUrl?
string = ...
Base URL for the API (optional, uses provider default)
maxRetries?
number = ...
Maximum number of retries for failed requests
modelId
string = ...
Model identifier (e.g., ‘claude-sonnet-4’, ‘gpt-4o’)
providerId
string = ...
Provider identifier (e.g., ‘anthropic’, ‘openai’)
timeout?
number = ...
Request timeout in milliseconds
Returns
Result<IModelAdapter, ConfigError>
Result containing the adapter or a ConfigError
Example
const result = factory.create({
providerId: 'anthropic',
modelId: 'claude-sonnet-4',
timeout: 30000,
maxRetries: 3
});
if (result.ok) {
const response = await result.value.complete(request);
} else {
console.error('Failed to create adapter:', result.error.message);
}
hasProvider()
hasProvider(providerId): boolean;
Defined in: packages/nexus-agents/src/adapters/factory.ts:254
Checks if a provider is registered.
Parameters
providerId
string
The provider ID to check
Returns
boolean
True if the provider is registered
listProviders()
listProviders(): string[];
Defined in: packages/nexus-agents/src/adapters/factory.ts:263
Returns a list of all registered provider IDs.
Returns
string[]
Array of provider identifiers
register()
register(
providerId,
creator,
options?
): Result<void, ConfigError>;
Defined in: packages/nexus-agents/src/adapters/factory.ts:101
Registers an adapter creator for a provider.
Parameters
providerId
string
Unique identifier for the provider (e.g., ‘anthropic’)
creator
Factory function that creates adapters for this provider
options?
Registration options
Returns
Result<void, ConfigError>
Result indicating success or failure
Example
const result = factory.register('anthropic', (config) => new ClaudeAdapter(config));
if (!result.ok) {
console.error('Registration failed:', result.error.message);
}
unregister()
unregister(providerId): Result<boolean, ConfigError>;
Defined in: packages/nexus-agents/src/adapters/factory.ts:134
Unregisters an adapter creator for a provider.
Parameters
providerId
string
The provider ID to unregister
Returns
Result<boolean, ConfigError>
Result indicating whether the provider was removed
AdapterModelError
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:68
Extended ModelError that supports specific error codes.
While ModelError from core uses MODEL_ERROR by default, this subclass allows adapters to specify more granular error codes like MODEL_RATE_LIMITED, MODEL_TIMEOUT, etc.
Extends ModelError so instanceof ModelError checks pass naturally
without requiring as unknown as ModelError casts.
Extends
Constructors
Constructor
new AdapterModelError(message, options): AdapterModelError;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:69
Parameters
message
string
options
Returns
Overrides
Properties
cause
readonly cause: Error | undefined;
Defined in: packages/nexus-agents/src/core/errors.ts:105
Inherited from
code
readonly code: ErrorCode;
Defined in: packages/nexus-agents/src/core/errors.ts:103
Inherited from
context
readonly context: Record<string, unknown> | undefined;
Defined in: packages/nexus-agents/src/core/errors.ts:104
Inherited from
message
message: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075
Inherited from
name
name: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074
Inherited from
stack?
optional stack?: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076
Inherited from
stackTraceLimit
static stackTraceLimit: number;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:67
The Error.stackTraceLimit property specifies the number of stack frames
collected by a stack trace (whether generated by new Error().stack or
Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes
will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will not capture any frames.
Inherited from
Methods
toJSON()
toJSON(): SerializedError;
Defined in: packages/nexus-agents/src/core/errors.ts:121
Serializes the error to a JSON-safe object.
Returns
Inherited from
captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:51
Creates a .stack property on targetObject, which when accessed returns
a string representing the location in the code at which
Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
The first line of the trace will be prefixed with
${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
above constructorOpt, including constructorOpt, will be omitted from the
generated stack trace.
The constructorOpt argument is useful for hiding implementation
details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
Parameters
targetObject
object
constructorOpt?
Function
Returns
void
Inherited from
prepareStackTrace()
static prepareStackTrace(err, stackTraces): any;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:55
Parameters
err
Error
stackTraces
CallSite[]
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
AdapterRateLimiter
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:72
Token bucket rate limiter for controlling request rates.
The token bucket algorithm works as follows:
- A bucket holds tokens up to a maximum capacity
- Tokens are added at a fixed rate (refillRate per second)
- Each request consumes one or more tokens
- If insufficient tokens, the request is rejected or waits
Example
const limiter = new RateLimiter({
capacity: 100, // Max 100 tokens
refillRate: 10, // 10 tokens per second
});
if (limiter.tryAcquire()) {
// Proceed with operation
} else {
// Rate limited
}
// Or wait for tokens
await limiter.waitForTokens();
Constructors
Constructor
new AdapterRateLimiter(config): AdapterRateLimiter;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:85
Creates a new RateLimiter instance.
Parameters
config
Configuration options
Returns
Throws
If configuration is invalid
Methods
acquire()
acquire(tokens?): Result<void, RateLimitExceeded>;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:177
Attempts to acquire tokens and returns a Result with detailed information.
Parameters
tokens?
number = 1
Number of tokens to acquire (default: 1)
Returns
Result<void, RateLimitExceeded>
Result containing void on success, or RateLimitExceeded on failure
Example
const result = limiter.acquire(5);
if (!result.ok) {
console.log(`Retry after ${result.error.retryAfterMs}ms`);
}
getAvailableTokens()
getAvailableTokens(): number;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:260
Returns the number of whole tokens available.
Returns
number
Integer number of available tokens
getCapacity()
getCapacity(): number;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:276
Returns the bucket’s maximum capacity.
Returns
number
getRefillRate()
getRefillRate(): number;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:283
Returns the refill rate in tokens per second.
Returns
number
getRemainingTokens()
getRemainingTokens(): number;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:250
Returns the current number of available tokens. Performs a refill before returning the count.
Returns
number
Number of available tokens (may be fractional)
getTimeUntilAvailable()
getTimeUntilAvailable(tokens?): number;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:293
Calculates the time in milliseconds until the specified tokens are available.
Parameters
tokens?
number = 1
Number of tokens needed (default: 1)
Returns
number
Time in milliseconds until tokens are available, 0 if already available
reset()
reset(): void;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:268
Resets the rate limiter to its initial state. The bucket is refilled to capacity.
Returns
void
tryAcquire()
tryAcquire(tokens?): boolean;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:145
Attempts to acquire the specified number of tokens.
Parameters
tokens?
number = 1
Number of tokens to acquire (default: 1)
Returns
boolean
true if tokens were acquired, false if rate limited
Example
if (limiter.tryAcquire(5)) {
// Acquired 5 tokens
}
waitForTokens()
waitForTokens(tokens?): Promise<void>;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:221
Waits until the specified number of tokens are available, then acquires them.
Parameters
tokens?
number = 1
Number of tokens to acquire (default: 1)
Returns
Promise<void>
Promise that resolves when tokens are acquired
Throws
If tokens exceed capacity (would wait forever)
Example
await limiter.waitForTokens(10);
// 10 tokens acquired
abstract BaseAdapter
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:152
Abstract base class for model adapters.
Provides default implementations for common adapter functionality while leaving the core API interaction methods abstract for provider-specific implementations.
Example
class ClaudeAdapter extends BaseAdapter {
constructor(config: ClaudeAdapterConfig) {
super({
providerId: 'anthropic',
modelId: config.modelId,
capabilities: [ModelCapability.COMPLETION, ModelCapability.STREAMING],
apiKey: config.apiKey,
});
}
async complete(request: CompletionRequest): Promise<Result<CompletionResponse, ModelError>> {
this.logRequest(request);
// Provider-specific implementation...
}
async *stream(request: CompletionRequest): AsyncIterable<StreamChunk> {
this.logRequest(request);
// Provider-specific streaming implementation...
}
}
Extended by
Implements
Constructors
Constructor
new BaseAdapter(config): BaseAdapter;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:168
Creates a new BaseAdapter instance.
Parameters
config
Adapter configuration
Returns
Properties
capabilities
readonly capabilities: readonly ModelCapability[];
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:155
Capabilities this model supports
Implementation of
config
protected readonly config: BaseAdapterConfig;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:161
Configuration for the adapter
logger
protected readonly logger: ILogger;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:158
Logger for request/response logging
modelId
readonly modelId: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:154
Model identifier (e.g., ‘claude-sonnet-4’, ‘gpt-4o’)
Implementation of
providerId
readonly providerId: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:153
Provider identifier (e.g., ‘anthropic’, ‘openai’)
Implementation of
Methods
complete()
abstract complete(request): Promise<Result<CompletionResponse, ModelError>>;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:188
Send a completion request to the model. Must be implemented by concrete adapter classes.
Parameters
request
The completion request
Returns
Promise<Result<CompletionResponse, ModelError>>
Result with response or ModelError
Implementation of
countTokens()
countTokens(text): Promise<number>;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:208
Count tokens in text using the unified TokenEstimator.
This provides a reasonable estimate for most use cases. Concrete adapters may override this with provider-specific tokenizers.
Parameters
text
string
Text to count tokens for
Returns
Promise<number>
Approximate token count
Implementation of
hasCapability()
hasCapability(capability): boolean;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:260
Check if this adapter supports a specific capability.
Parameters
capability
The capability to check for
Returns
boolean
True if the capability is supported
logRequest()
protected logRequest(request): void;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:270
Log details about an outgoing request. Sanitizes sensitive information before logging.
Parameters
request
The completion request to log
Returns
void
logResponse()
protected logResponse(response): void;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:292
Log details about a received response.
Parameters
response
The completion response to log
Returns
void
stream()
abstract stream(request): AsyncIterable<StreamChunk>;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:197
Stream a completion request from the model. Must be implemented by concrete adapter classes.
Parameters
request
The completion request
Returns
AsyncIterable<StreamChunk>
Yields
StreamChunk objects as they arrive
Implementation of
transformError()
protected transformError(error): ModelError;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:315
Transform a provider-specific error into a standardized ModelError.
Maps common error patterns to appropriate error codes:
- Rate limiting (429, quota exceeded)
- Timeouts (ETIMEDOUT, ESOCKETTIMEDOUT)
- Authentication (401, 403)
- Model unavailable (503, 502)
Parameters
error
unknown
The original error from the provider
Returns
A standardized ModelError
validateConfig()
validateConfig(): Result<void, ConfigError>;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:220
Validate adapter configuration.
Checks that required configuration fields are present and valid. Concrete adapters may override to add provider-specific validation.
Returns
Result<void, ConfigError>
Ok if valid, ConfigError if invalid
Implementation of
ClaudeAdapter
Defined in: packages/nexus-agents/src/adapters/claude-adapter.ts:75
Claude/Anthropic model adapter.
Provides a unified interface for interacting with Anthropic’s Claude models. Supports completion, streaming, tool use, and vision capabilities.
Example
const adapter = new ClaudeAdapter({
modelId: 'claude-sonnet-4',
apiKey: process.env.ANTHROPIC_API_KEY,
});
const result = await adapter.complete({
messages: [{ role: 'user', content: 'Hello!' }],
maxTokens: 1024,
});
if (result.ok) {
console.log(result.value.content);
}
Extends
Constructors
Constructor
new ClaudeAdapter(config): ClaudeAdapter;
Defined in: packages/nexus-agents/src/adapters/claude-adapter.ts:85
Creates a new ClaudeAdapter instance.
Parameters
config
Claude adapter configuration
Returns
Throws
If API key is missing
Overrides
Properties
capabilities
readonly capabilities: readonly ModelCapability[];
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:155
Capabilities this model supports
Inherited from
config
protected readonly config: BaseAdapterConfig;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:161
Configuration for the adapter
Inherited from
logger
protected readonly logger: ILogger;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:158
Logger for request/response logging
Inherited from
modelId
readonly modelId: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:154
Model identifier (e.g., ‘claude-sonnet-4’, ‘gpt-4o’)
Inherited from
providerId
readonly providerId: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:153
Provider identifier (e.g., ‘anthropic’, ‘openai’)
Inherited from
Methods
complete()
complete(request): Promise<Result<CompletionResponse, ModelError>>;
Defined in: packages/nexus-agents/src/adapters/claude-adapter.ts:146
Send a completion request to Claude.
Parameters
request
The completion request
Returns
Promise<Result<CompletionResponse, ModelError>>
Result with response or ModelError
Overrides
countTokens()
countTokens(text): Promise<number>;
Defined in: packages/nexus-agents/src/adapters/claude-adapter.ts:187
Count tokens in text using Claude-specific estimation.
Claude uses a custom tokenizer. This provides a more accurate estimate than the base adapter’s generic calculation.
Parameters
text
string
Text to count tokens for
Returns
Promise<number>
Approximate token count
Overrides
hasCapability()
hasCapability(capability): boolean;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:260
Check if this adapter supports a specific capability.
Parameters
capability
The capability to check for
Returns
boolean
True if the capability is supported
Inherited from
listModels()
listModels(): Promise<readonly ModelMetadata[]>;
Defined in: packages/nexus-agents/src/adapters/claude-adapter.ts:444
(#2540) List models the Anthropic API currently exposes.
Wraps client.models.list(). Cached for 5 min, in-flight promise
shared across concurrent callers, throws on non-2xx so the
harness-side identity resolver knows to fall back.
Returns
Promise<readonly ModelMetadata[]>
logRequest()
protected logRequest(request): void;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:270
Log details about an outgoing request. Sanitizes sensitive information before logging.
Parameters
request
The completion request to log
Returns
void
Inherited from
logResponse()
protected logResponse(response): void;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:292
Log details about a received response.
Parameters
response
The completion response to log
Returns
void
Inherited from
stream()
stream(request): AsyncIterable<StreamChunk>;
Defined in: packages/nexus-agents/src/adapters/claude-adapter.ts:164
Stream a completion request from Claude.
Parameters
request
The completion request
Returns
AsyncIterable<StreamChunk>
Yields
StreamChunk objects as they arrive
Overrides
transformError()
protected transformError(error): ModelError;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:315
Transform a provider-specific error into a standardized ModelError.
Maps common error patterns to appropriate error codes:
- Rate limiting (429, quota exceeded)
- Timeouts (ETIMEDOUT, ESOCKETTIMEDOUT)
- Authentication (401, 403)
- Model unavailable (503, 502)
Parameters
error
unknown
The original error from the provider
Returns
A standardized ModelError
Inherited from
validateConfig()
validateConfig(): Result<void, ConfigError>;
Defined in: packages/nexus-agents/src/adapters/claude-adapter.ts:127
Validates adapter configuration. Extends base validation with Claude-specific checks.
Returns
Result<void, ConfigError>
Overrides
GeminiAdapter
Defined in: packages/nexus-agents/src/adapters/gemini-adapter.ts:98
Gemini/Google AI model adapter.
Provides a unified interface for interacting with Google’s Gemini models. Supports completion, streaming, tool use, and vision capabilities.
Example
const adapter = new GeminiAdapter({
modelId: 'gemini-2.5-flash',
apiKey: process.env.GOOGLE_AI_API_KEY,
});
const result = await adapter.complete({
messages: [{ role: 'user', content: 'Hello!' }],
maxTokens: 1024,
});
if (result.ok) {
console.log(result.value.content);
}
Extends
Constructors
Constructor
new GeminiAdapter(config): GeminiAdapter;
Defined in: packages/nexus-agents/src/adapters/gemini-adapter.ts:108
Creates a new GeminiAdapter instance.
Parameters
config
Gemini adapter configuration
Returns
Throws
If API key is missing
Overrides
Properties
capabilities
readonly capabilities: readonly ModelCapability[];
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:155
Capabilities this model supports
Inherited from
config
protected readonly config: BaseAdapterConfig;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:161
Configuration for the adapter
Inherited from
logger
protected readonly logger: ILogger;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:158
Logger for request/response logging
Inherited from
modelId
readonly modelId: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:154
Model identifier (e.g., ‘claude-sonnet-4’, ‘gpt-4o’)
Inherited from
providerId
readonly providerId: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:153
Provider identifier (e.g., ‘anthropic’, ‘openai’)
Inherited from
Methods
complete()
complete(request): Promise<Result<CompletionResponse, ModelError>>;
Defined in: packages/nexus-agents/src/adapters/gemini-adapter.ts:161
Send a completion request to Gemini.
Parameters
request
The completion request
Returns
Promise<Result<CompletionResponse, ModelError>>
Result with response or ModelError
Overrides
countTokens()
countTokens(text): Promise<number>;
Defined in: packages/nexus-agents/src/adapters/gemini-adapter.ts:199
Count tokens in text using Gemini-specific estimation.
Parameters
text
string
Text to count tokens for
Returns
Promise<number>
Approximate token count
Overrides
hasCapability()
hasCapability(capability): boolean;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:260
Check if this adapter supports a specific capability.
Parameters
capability
The capability to check for
Returns
boolean
True if the capability is supported
Inherited from
listModels()
listModels(): Promise<readonly ModelMetadata[]>;
Defined in: packages/nexus-agents/src/adapters/gemini-adapter.ts:390
(#2540) List Gemini models exposed by the configured API key.
Wraps client.models.list() (returns a Pager). 5-min cache,
concurrent-caller promise sharing.
Returns
Promise<readonly ModelMetadata[]>
logRequest()
protected logRequest(request): void;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:270
Log details about an outgoing request. Sanitizes sensitive information before logging.
Parameters
request
The completion request to log
Returns
void
Inherited from
logResponse()
protected logResponse(response): void;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:292
Log details about a received response.
Parameters
response
The completion response to log
Returns
void
Inherited from
stream()
stream(request): AsyncIterable<StreamChunk>;
Defined in: packages/nexus-agents/src/adapters/gemini-adapter.ts:179
Stream a completion request from Gemini.
Parameters
request
The completion request
Returns
AsyncIterable<StreamChunk>
Yields
StreamChunk objects as they arrive
Overrides
transformError()
protected transformError(error): ModelError;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:315
Transform a provider-specific error into a standardized ModelError.
Maps common error patterns to appropriate error codes:
- Rate limiting (429, quota exceeded)
- Timeouts (ETIMEDOUT, ESOCKETTIMEDOUT)
- Authentication (401, 403)
- Model unavailable (503, 502)
Parameters
error
unknown
The original error from the provider
Returns
A standardized ModelError
Inherited from
validateConfig()
validateConfig(): Result<void, ConfigError>;
Defined in: packages/nexus-agents/src/adapters/gemini-adapter.ts:142
Validates adapter configuration. Extends base validation with Gemini-specific checks.
Returns
Result<void, ConfigError>
Overrides
OllamaAdapter
Defined in: packages/nexus-agents/src/adapters/ollama-adapter.ts:152
Ollama model adapter for local model inference.
Extends
Constructors
Constructor
new OllamaAdapter(config): OllamaAdapter;
Defined in: packages/nexus-agents/src/adapters/ollama-adapter.ts:155
Parameters
config
Returns
Overrides
Properties
capabilities
readonly capabilities: readonly ModelCapability[];
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:155
Capabilities this model supports
Inherited from
config
protected readonly config: BaseAdapterConfig;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:161
Configuration for the adapter
Inherited from
logger
protected readonly logger: ILogger;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:158
Logger for request/response logging
Inherited from
modelId
readonly modelId: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:154
Model identifier (e.g., ‘claude-sonnet-4’, ‘gpt-4o’)
Inherited from
providerId
readonly providerId: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:153
Provider identifier (e.g., ‘anthropic’, ‘openai’)
Inherited from
Methods
complete()
complete(request): Promise<Result<CompletionResponse, ModelError>>;
Defined in: packages/nexus-agents/src/adapters/ollama-adapter.ts:180
Send a completion request to the model. Must be implemented by concrete adapter classes.
Parameters
request
The completion request
Returns
Promise<Result<CompletionResponse, ModelError>>
Result with response or ModelError
Overrides
countTokens()
countTokens(text): Promise<number>;
Defined in: packages/nexus-agents/src/adapters/ollama-adapter.ts:211
Count tokens in text using the unified TokenEstimator.
This provides a reasonable estimate for most use cases. Concrete adapters may override this with provider-specific tokenizers.
Parameters
text
string
Text to count tokens for
Returns
Promise<number>
Approximate token count
Overrides
hasCapability()
hasCapability(capability): boolean;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:260
Check if this adapter supports a specific capability.
Parameters
capability
The capability to check for
Returns
boolean
True if the capability is supported
Inherited from
logRequest()
protected logRequest(request): void;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:270
Log details about an outgoing request. Sanitizes sensitive information before logging.
Parameters
request
The completion request to log
Returns
void
Inherited from
logResponse()
protected logResponse(response): void;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:292
Log details about a received response.
Parameters
response
The completion response to log
Returns
void
Inherited from
stream()
stream(request): AsyncIterable<StreamChunk>;
Defined in: packages/nexus-agents/src/adapters/ollama-adapter.ts:202
Stream a completion request from the model. Must be implemented by concrete adapter classes.
Parameters
request
The completion request
Returns
AsyncIterable<StreamChunk>
Yields
StreamChunk objects as they arrive
Overrides
transformError()
protected transformError(error): ModelError;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:315
Transform a provider-specific error into a standardized ModelError.
Maps common error patterns to appropriate error codes:
- Rate limiting (429, quota exceeded)
- Timeouts (ETIMEDOUT, ESOCKETTIMEDOUT)
- Authentication (401, 403)
- Model unavailable (503, 502)
Parameters
error
unknown
The original error from the provider
Returns
A standardized ModelError
Inherited from
validateConfig()
validateConfig(): Result<void, ConfigError>;
Defined in: packages/nexus-agents/src/adapters/ollama-adapter.ts:169
Validate adapter configuration.
Checks that required configuration fields are present and valid. Concrete adapters may override to add provider-specific validation.
Returns
Result<void, ConfigError>
Ok if valid, ConfigError if invalid
Overrides
OpenAIAdapter
Defined in: packages/nexus-agents/src/adapters/openai-adapter.ts:139
Adapters exports - Model adapters (Claude, OpenAI, Gemini, Ollama) Split from index.ts for file size compliance (Issue #285)
Extends
Constructors
Constructor
new OpenAIAdapter(config): OpenAIAdapter;
Defined in: packages/nexus-agents/src/adapters/openai-adapter.ts:152
Creates a new OpenAIAdapter instance.
Parameters
config
OpenAI adapter configuration
Returns
Throws
If API key is missing
Overrides
Properties
capabilities
readonly capabilities: readonly ModelCapability[];
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:155
Capabilities this model supports
Inherited from
config
protected readonly config: BaseAdapterConfig;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:161
Configuration for the adapter
Inherited from
logger
protected readonly logger: ILogger;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:158
Logger for request/response logging
Inherited from
modelId
readonly modelId: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:154
Model identifier (e.g., ‘claude-sonnet-4’, ‘gpt-4o’)
Inherited from
providerId
readonly providerId: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:153
Provider identifier (e.g., ‘anthropic’, ‘openai’)
Inherited from
Methods
complete()
complete(request): Promise<Result<CompletionResponse, ModelError>>;
Defined in: packages/nexus-agents/src/adapters/openai-adapter.ts:238
Send a completion request to OpenAI.
Parameters
request
The completion request
Returns
Promise<Result<CompletionResponse, ModelError>>
Result with response or ModelError
Overrides
countTokens()
countTokens(text): Promise<number>;
Defined in: packages/nexus-agents/src/adapters/openai-adapter.ts:313
Count tokens in text using OpenAI-specific estimation.
Parameters
text
string
Text to count tokens for
Returns
Promise<number>
Approximate token count
Overrides
hasCapability()
hasCapability(capability): boolean;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:260
Check if this adapter supports a specific capability.
Parameters
capability
The capability to check for
Returns
boolean
True if the capability is supported
Inherited from
listModels()
listModels(): Promise<readonly ModelMetadata[]>;
Defined in: packages/nexus-agents/src/adapters/openai-adapter.ts:548
(#2529) List models served by this OpenAI-compatible endpoint.
Wraps GET /v1/models. Result is cached for LIST_MODELS_TTL_MS
so identity resolution doesn’t round-trip on every adapter.
Concurrent callers share the in-flight promise.
Throws on non-2xx so the harness-side identity resolver knows to fall back to modelId parsing — silent empty-list returns would be indistinguishable from “this gateway has no models”, which a misconfigured endpoint shouldn’t be allowed to claim.
Returns
Promise<readonly ModelMetadata[]>
logRequest()
protected logRequest(request): void;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:270
Log details about an outgoing request. Sanitizes sensitive information before logging.
Parameters
request
The completion request to log
Returns
void
Inherited from
logResponse()
protected logResponse(response): void;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:292
Log details about a received response.
Parameters
response
The completion response to log
Returns
void
Inherited from
stream()
stream(request): AsyncIterable<StreamChunk>;
Defined in: packages/nexus-agents/src/adapters/openai-adapter.ts:293
Stream a completion request from OpenAI.
Parameters
request
The completion request
Returns
AsyncIterable<StreamChunk>
Yields
StreamChunk objects as they arrive
Overrides
transformError()
protected transformError(error): ModelError;
Defined in: packages/nexus-agents/src/adapters/openai-adapter.ts:262
Surface an OpenAI / OpenAI-compatible gateway’s REAL HTTP status + response
body in the error (#4047). The OpenAI SDK’s default message collapses a
gateway rejection to e.g. "400 status code (no body)", which hides WHY a
litellm-style gateway rejected a request — exactly the wall hit when
diagnosing degraded voter panels on a custom gateway. We re-message with the
status/type/code/param/request-id/body. Error-code routing is unchanged: we
classify on the ORIGINAL signal (status/code/message) via a clean probe
error, so the diagnostic request_id/body can’t pollute the message-
substring classifier, then re-message the result with the full detail.
Applies to direct OpenAI and the compat gateway alike.
Parameters
error
unknown
Returns
Overrides
validateConfig()
validateConfig(): Result<void, ConfigError>;
Defined in: packages/nexus-agents/src/adapters/openai-adapter.ts:219
Validates adapter configuration. Extends base validation with OpenAI-specific checks.
Returns
Result<void, ConfigError>
Overrides
RegistryAlreadyInitializedError
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:423
Thrown by getGlobalRegistry when a non-empty config arrives after
the singleton exists (#5211). The registry has no way to apply it — the
logger and defaultCliTimeoutMs are fixed at construction — so until this
error existed the config was logged at warn and dropped, and the caller
went on with a registry built from someone else’s settings. A config that is
accepted and ignored is an instrument that misreports what it was given.
The check is on presence, not on equality with the live config: the registry does not keep the config it was built from, and a caller re-supplying the same values is still a caller that believes it configured something.
Extends
Constructors
Constructor
new RegistryAlreadyInitializedError(providedKeys): RegistryAlreadyInitializedError;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:424
Parameters
providedKeys
readonly string[]
Returns
RegistryAlreadyInitializedError
Overrides
Properties
cause
readonly cause: Error | undefined;
Defined in: packages/nexus-agents/src/core/errors.ts:105
Inherited from
code
readonly code: ErrorCode;
Defined in: packages/nexus-agents/src/core/errors.ts:103
Inherited from
context
readonly context: Record<string, unknown> | undefined;
Defined in: packages/nexus-agents/src/core/errors.ts:104
Inherited from
message
message: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075
Inherited from
name
name: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074
Inherited from
stack?
optional stack?: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076
Inherited from
stackTraceLimit
static stackTraceLimit: number;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:67
The Error.stackTraceLimit property specifies the number of stack frames
collected by a stack trace (whether generated by new Error().stack or
Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes
will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will not capture any frames.
Inherited from
Methods
toJSON()
toJSON(): SerializedError;
Defined in: packages/nexus-agents/src/core/errors.ts:121
Serializes the error to a JSON-safe object.
Returns
Inherited from
captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:51
Creates a .stack property on targetObject, which when accessed returns
a string representing the location in the code at which
Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
The first line of the trace will be prefixed with
${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
above constructorOpt, including constructorOpt, will be omitted from the
generated stack trace.
The constructorOpt argument is useful for hiding implementation
details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
Parameters
targetObject
object
constructorOpt?
Function
Returns
void
Inherited from
prepareStackTrace()
static prepareStackTrace(err, stackTraces): any;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:55
Parameters
err
Error
stackTraces
CallSite[]
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
RetryExhaustedError
Defined in: packages/nexus-agents/src/adapters/retry.ts:80
Error thrown when all retry attempts are exhausted.
Extends
Constructors
Constructor
new RetryExhaustedError(attempts, lastError): RetryExhaustedError;
Defined in: packages/nexus-agents/src/adapters/retry.ts:86
Parameters
attempts
number
lastError
unknown
Returns
Overrides
Properties
attempts
readonly attempts: number;
Defined in: packages/nexus-agents/src/adapters/retry.ts:82
Number of attempts made
cause
readonly cause: Error | undefined;
Defined in: packages/nexus-agents/src/core/errors.ts:105
Inherited from
code
readonly code: ErrorCode;
Defined in: packages/nexus-agents/src/core/errors.ts:103
Inherited from
context
readonly context: Record<string, unknown> | undefined;
Defined in: packages/nexus-agents/src/core/errors.ts:104
Inherited from
lastError
readonly lastError: unknown;
Defined in: packages/nexus-agents/src/adapters/retry.ts:84
The last error encountered
message
message: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075
Inherited from
name
name: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074
Inherited from
stack?
optional stack?: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076
Inherited from
stackTraceLimit
static stackTraceLimit: number;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:67
The Error.stackTraceLimit property specifies the number of stack frames
collected by a stack trace (whether generated by new Error().stack or
Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes
will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will not capture any frames.
Inherited from
Methods
toJSON()
toJSON(): SerializedError;
Defined in: packages/nexus-agents/src/core/errors.ts:121
Serializes the error to a JSON-safe object.
Returns
Inherited from
captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:51
Creates a .stack property on targetObject, which when accessed returns
a string representing the location in the code at which
Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
The first line of the trace will be prefixed with
${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
above constructorOpt, including constructorOpt, will be omitted from the
generated stack trace.
The constructorOpt argument is useful for hiding implementation
details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
Parameters
targetObject
object
constructorOpt?
Function
Returns
void
Inherited from
prepareStackTrace()
static prepareStackTrace(err, stackTraces): any;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:55
Parameters
err
Error
stackTraces
CallSite[]
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
SdkAdapter
Defined in: packages/nexus-agents/src/adapters/sdk/sdk-adapter.ts:362
AI SDK adapter implementing IModelAdapter.
Uses Vercel AI SDK (npm: ai) for model interaction instead of
CLI subprocess spawning. Supports any provider that has an
@ai-sdk/* package.
Extends
Constructors
Constructor
new SdkAdapter(config, logger?): SdkAdapter;
Defined in: packages/nexus-agents/src/adapters/sdk/sdk-adapter.ts:384
Parameters
config
logger?
Returns
Overrides
Properties
capabilities
readonly capabilities: readonly ModelCapability[];
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:155
Capabilities this model supports
Inherited from
config
protected readonly config: BaseAdapterConfig;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:161
Configuration for the adapter
Inherited from
logger
protected readonly logger: ILogger;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:158
Logger for request/response logging
Inherited from
modelId
readonly modelId: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:154
Model identifier (e.g., ‘claude-sonnet-4’, ‘gpt-4o’)
Inherited from
providerId
readonly providerId: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:153
Provider identifier (e.g., ‘anthropic’, ‘openai’)
Inherited from
Methods
complete()
complete(request): Promise<Result<CompletionResponse, ModelError>>;
Defined in: packages/nexus-agents/src/adapters/sdk/sdk-adapter.ts:630
Send a completion request to the model. Must be implemented by concrete adapter classes.
Parameters
request
The completion request
Returns
Promise<Result<CompletionResponse, ModelError>>
Result with response or ModelError
Overrides
countTokens()
countTokens(text): Promise<number>;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:208
Count tokens in text using the unified TokenEstimator.
This provides a reasonable estimate for most use cases. Concrete adapters may override this with provider-specific tokenizers.
Parameters
text
string
Text to count tokens for
Returns
Promise<number>
Approximate token count
Inherited from
hasCapability()
hasCapability(capability): boolean;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:260
Check if this adapter supports a specific capability.
Parameters
capability
The capability to check for
Returns
boolean
True if the capability is supported
Inherited from
logRequest()
protected logRequest(request): void;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:270
Log details about an outgoing request. Sanitizes sensitive information before logging.
Parameters
request
The completion request to log
Returns
void
Inherited from
logResponse()
protected logResponse(response): void;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:292
Log details about a received response.
Parameters
response
The completion response to log
Returns
void
Inherited from
stream()
stream(request): AsyncIterable<StreamChunk>;
Defined in: packages/nexus-agents/src/adapters/sdk/sdk-adapter.ts:666
Stream a completion request from the model. Must be implemented by concrete adapter classes.
Parameters
request
The completion request
Returns
AsyncIterable<StreamChunk>
Yields
StreamChunk objects as they arrive
Overrides
transformError()
protected transformError(error): ModelError;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:315
Transform a provider-specific error into a standardized ModelError.
Maps common error patterns to appropriate error codes:
- Rate limiting (429, quota exceeded)
- Timeouts (ETIMEDOUT, ESOCKETTIMEDOUT)
- Authentication (401, 403)
- Model unavailable (503, 502)
Parameters
error
unknown
The original error from the provider
Returns
A standardized ModelError
Inherited from
validateConfig()
validateConfig(): Result<void, ConfigError>;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:220
Validate adapter configuration.
Checks that required configuration fields are present and valid. Concrete adapters may override to add provider-specific validation.
Returns
Result<void, ConfigError>
Ok if valid, ConfigError if invalid
Inherited from
StreamCancelledError
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:24
Error thrown when a stream is cancelled.
Extends
Constructors
Constructor
new StreamCancelledError(reason?): StreamCancelledError;
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:25
Parameters
reason?
string
Returns
Overrides
Properties
cause
readonly cause: Error | undefined;
Defined in: packages/nexus-agents/src/core/errors.ts:105
Inherited from
code
readonly code: ErrorCode;
Defined in: packages/nexus-agents/src/core/errors.ts:103
Inherited from
context
readonly context: Record<string, unknown> | undefined;
Defined in: packages/nexus-agents/src/core/errors.ts:104
Inherited from
message
message: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075
Inherited from
name
name: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074
Inherited from
stack?
optional stack?: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076
Inherited from
stackTraceLimit
static stackTraceLimit: number;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:67
The Error.stackTraceLimit property specifies the number of stack frames
collected by a stack trace (whether generated by new Error().stack or
Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes
will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will not capture any frames.
Inherited from
Methods
toJSON()
toJSON(): SerializedError;
Defined in: packages/nexus-agents/src/core/errors.ts:121
Serializes the error to a JSON-safe object.
Returns
Inherited from
captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:51
Creates a .stack property on targetObject, which when accessed returns
a string representing the location in the code at which
Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
The first line of the trace will be prefixed with
${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
above constructorOpt, including constructorOpt, will be omitted from the
generated stack trace.
The constructorOpt argument is useful for hiding implementation
details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
Parameters
targetObject
object
constructorOpt?
Function
Returns
void
Inherited from
prepareStackTrace()
static prepareStackTrace(err, stackTraces): any;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:55
Parameters
err
Error
stackTraces
CallSite[]
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
StreamController
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:50
Controller for managing stream lifecycle. Provides push/complete/error methods and cancellation support.
Type Parameters
T
T
Constructors
Constructor
new StreamController<T>(options?): StreamController<T>;
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:67
Creates a new StreamController.
Parameters
options?
CreateStreamOptions = {}
Stream creation options
Returns
Accessors
bufferSize
Get Signature
get bufferSize(): number;
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:96
Current buffer size.
Returns
number
isActive
Get Signature
get isActive(): boolean;
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:89
Whether the stream is still active (can receive chunks).
Returns
boolean
state
Get Signature
get state(): StreamState;
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:82
Current state of the stream.
Returns
Methods
cancel()
cancel(reason?): void;
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:167
Cancel the stream.
Parameters
reason?
string
Optional reason for cancellation
Returns
void
complete()
complete(): void;
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:138
Complete the stream successfully.
Returns
void
error()
error(error): void;
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:152
Complete the stream with an error.
Parameters
error
Error
The error that occurred
Returns
void
getIterable()
getIterable(): AsyncIterable<T>;
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:181
Get the AsyncIterable for consuming the stream.
Returns
AsyncIterable<T>
push()
push(chunk): Result<void, StreamError>;
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:105
Push a chunk to the stream.
Parameters
chunk
T
The chunk to push
Returns
Result<void, StreamError>
Result indicating success or backpressure
StreamError
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:14
Error thrown when a stream operation fails.
Extends
Constructors
Constructor
new StreamError(message, options?): StreamError;
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:15
Parameters
message
string
options?
cause?
Error
context?
Record<string, unknown>
Returns
Overrides
Properties
cause
readonly cause: Error | undefined;
Defined in: packages/nexus-agents/src/core/errors.ts:105
Inherited from
code
readonly code: ErrorCode;
Defined in: packages/nexus-agents/src/core/errors.ts:103
Inherited from
context
readonly context: Record<string, unknown> | undefined;
Defined in: packages/nexus-agents/src/core/errors.ts:104
Inherited from
message
message: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075
Inherited from
name
name: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074
Inherited from
stack?
optional stack?: string;
Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076
Inherited from
stackTraceLimit
static stackTraceLimit: number;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:67
The Error.stackTraceLimit property specifies the number of stack frames
collected by a stack trace (whether generated by new Error().stack or
Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes
will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will not capture any frames.
Inherited from
Methods
toJSON()
toJSON(): SerializedError;
Defined in: packages/nexus-agents/src/core/errors.ts:121
Serializes the error to a JSON-safe object.
Returns
Inherited from
captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:51
Creates a .stack property on targetObject, which when accessed returns
a string representing the location in the code at which
Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
The first line of the trace will be prefixed with
${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
above constructorOpt, including constructorOpt, will be omitted from the
generated stack trace.
The constructorOpt argument is useful for hiding implementation
details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
Parameters
targetObject
object
constructorOpt?
Function
Returns
void
Inherited from
prepareStackTrace()
static prepareStackTrace(err, stackTraces): any;
Defined in: node_modules/.pnpm/@types+node@25.9.8/node_modules/@types/node/globals.d.ts:55
Parameters
err
Error
stackTraces
CallSite[]
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
UnifiedAdapterRegistry
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:87
Unified adapter registry. Centralizes all adapter creation and task routing.
Usage:
const registry = createUnifiedRegistry({ logger });
const adapter = registry.getAdapter('code_generation'); // → codex adapter
const adapter2 = registry.getAdapterForCli('claude'); // → claude adapter
const adapter3 = registry.getDefault(); // → best available
Constructors
Constructor
new UnifiedAdapterRegistry(config?): UnifiedAdapterRegistry;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:101
Parameters
config?
Returns
Methods
dispose()
dispose(): void;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:318
Dispose all cached adapters.
Returns
void
getAdapter()
getAdapter(category): IResilientAdapter;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:124
Get adapter for a task category. Routing is re-resolved on every read (#3185) so a post-startup overlay/registry update propagates without a restart. Falls back to default adapter if category unknown.
Parameters
category
| "planning"
| "architecture"
| "code_generation"
| "code_review"
| "research"
| "security_review"
| "documentation"
| "testing"
| "devops"
| "exploration"
Returns
IResilientAdapter
getAdapterForArm()
getAdapterForArm(arm): IResilientAdapter | undefined;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:182
Get the adapter for a routing arm (#4392). A CLI slot resolves exactly as
getAdapterForCli (created lazily, cached, armed with the shared
breaker registry). An api:* arm resolves to what registerApiArm
supplied, or undefined — never to a CLI slot, and never by creating one.
Parameters
arm
ObservedArmId
Returns
IResilientAdapter | undefined
getAdapterForCli()
getAdapterForCli(cli): IResilientAdapter;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:153
Get adapter pinned to a specific CLI. Creates and caches one IResilientAdapter per CLI.
Parameters
cli
"claude" | "gemini" | "codex" | "opencode"
Returns
IResilientAdapter
getAdapterForModel()
getAdapterForModel(modelPreference): IResilientAdapter;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:228
Get adapter for a model preference string (e.g., “claude-opus-4-6”). Resolves the model to its CLI via the canonical registry. Falls back to default adapter if model not recognized.
An exact match returns the CLI slot adapter bound to the matched registry id, so the model reaches the CLI instead of its default (#6599). A prefix match routes to the CLI only, as before: the name was not an entry.
Parameters
modelPreference
string
Returns
IResilientAdapter
getAdapterForRole()
getAdapterForRole(role): IResilientAdapter;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:265
Get adapter for an expert role (e.g., “code_expert”). Uses ROLE_TO_TASK_CATEGORY mapping → task specialization → CLI.
Parameters
role
string
Returns
IResilientAdapter
getAdapterForTask()
getAdapterForTask(taskDescription): IResilientAdapter;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:137
Get adapter for a free-text task description. Detects category from keywords, falls back to default.
Parameters
taskDescription
string
Returns
IResilientAdapter
getDefault()
getDefault(): IResilientAdapter;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:274
Get the default adapter (no CLI preference — auto-detection priority).
Returns
IResilientAdapter
getLogger()
getLogger(): ILogger;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:115
Logger used by this registry. Exposed so singleton helpers can warn.
Returns
getRouting()
getRouting(category): TaskRoutingEntry | undefined;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:309
Resolve the routing for a specific category.
Computed on every read (#3185) rather than cached at construction, so a
post-startup model-registry / overlay update (e.g. a default-model change
surfaced via getDefaultModelForCli) propagates to routing decisions
without a process restart. The matrix is ~10 categories — the per-read
resolution cost is negligible.
Parameters
category
| "planning"
| "architecture"
| "code_generation"
| "code_review"
| "research"
| "security_review"
| "documentation"
| "testing"
| "devops"
| "exploration"
Returns
TaskRoutingEntry | undefined
getSnapshot()
getSnapshot(): RegistrySnapshot;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:291
Get snapshot of registry state for observability/debugging. Routing is re-resolved on read (#3185) so the snapshot reflects the live registry.
Returns
registerApiArm()
registerApiArm(arm, adapter): void;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:206
Register an api:* arm’s adapter under its endpoint identity (#4392).
Refuses built-in vendor arms (api:anthropic, api:openai, api:google, api:gemini)
to prevent hijacking or redirecting vendor traffic without authorization.
Accepts a dynamic EndpointArmId; the id is re-validated at runtime
because the EndpointArmId type admits any api: string, so a cast from an
unvalidated name is exactly what this refuses.
Registering an id twice replaces (and disposes) the earlier adapter.
CLI-slot behaviour is untouched. A registered endpoint arm is observable
here and in the breaker registry but is NOT a RoutingArmId: it cannot
enter outcome records until #6291. A gateway arm registered without a
NEXUS_GATEWAY_COST declaration is warned about here, once, at the
moment it becomes routable (#4392 increment 2).
Parameters
arm
`api:${string}`
adapter
IResilientAdapter
Returns
void
Interfaces
AdapterRateLimiterConfig
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:17
Configuration options for the RateLimiter.
Properties
capacity
readonly capacity: number;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:22
Maximum number of tokens the bucket can hold. This is also the initial token count.
refillInterval?
readonly optional refillInterval?: number;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:33
Interval in milliseconds for automatic refill checks. Only used when waiting for tokens. Default: 100ms.
refillRate
readonly refillRate: number;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:27
Number of tokens added to the bucket per second.
AdapterRegisterOptions
Defined in: packages/nexus-agents/src/adapters/factory.ts:48
Options for registering an adapter provider.
Properties
allowOverwrite?
optional allowOverwrite?: boolean;
Defined in: packages/nexus-agents/src/adapters/factory.ts:50
Whether to allow overwriting an existing provider
BaseAdapterConfig
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:39
Configuration options for BaseAdapter.
Properties
apiKey?
optional apiKey?: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:49
API key for authentication (optional, may come from environment)
baseUrl?
optional baseUrl?: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:51
Base URL for the API (optional, uses provider default)
capabilities
capabilities: readonly ModelCapability[];
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:45
Capabilities this model supports
logger?
optional logger?: ILogger;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:47
Optional custom logger
maxRetries?
optional maxRetries?: number;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:55
Maximum number of retries for failed requests
modelId
modelId: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:43
Model identifier (e.g., ‘claude-sonnet-4’, ‘gpt-4o’)
providerId
providerId: string;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:41
Provider identifier (e.g., ‘anthropic’, ‘openai’)
timeout?
optional timeout?: number;
Defined in: packages/nexus-agents/src/adapters/base-adapter.ts:53
Request timeout in milliseconds
ClaudeAdapterConfig
Defined in: packages/nexus-agents/src/adapters/claude-adapter-types.ts:41
Configuration specific to ClaudeAdapter.
Properties
apiKey
apiKey: string;
Defined in: packages/nexus-agents/src/adapters/claude-adapter-types.ts:45
API key for Anthropic API (required)
baseUrl?
optional baseUrl?: string;
Defined in: packages/nexus-agents/src/adapters/claude-adapter-types.ts:47
Base URL for API (optional, defaults to Anthropic’s API)
maxRetries?
optional maxRetries?: number;
Defined in: packages/nexus-agents/src/adapters/claude-adapter-types.ts:51
Maximum retries for failed requests (optional)
modelId
modelId: string;
Defined in: packages/nexus-agents/src/adapters/claude-adapter-types.ts:43
Model ID (e.g., ‘claude-sonnet-4’ or full model identifier)
timeout?
optional timeout?: number;
Defined in: packages/nexus-agents/src/adapters/claude-adapter-types.ts:49
Request timeout in milliseconds (optional)
CreateStreamOptions
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:39
Options for creating a stream.
Properties
maxBufferSize?
optional maxBufferSize?: number;
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:43
Maximum buffer size for backpressure (default: 100)
signal?
optional signal?: AbortSignal;
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:41
AbortSignal for cancellation support
GeminiAdapterConfig
Defined in: packages/nexus-agents/src/adapters/gemini-types.ts:47
Configuration specific to GeminiAdapter.
Properties
apiKey
apiKey: string;
Defined in: packages/nexus-agents/src/adapters/gemini-types.ts:51
API key for Google AI API (required)
maxRetries?
optional maxRetries?: number;
Defined in: packages/nexus-agents/src/adapters/gemini-types.ts:55
Maximum retries for failed requests (optional)
modelId
modelId: string;
Defined in: packages/nexus-agents/src/adapters/gemini-types.ts:49
Model ID (e.g., ‘gemini-2.5-flash’ or full model identifier)
timeout?
optional timeout?: number;
Defined in: packages/nexus-agents/src/adapters/gemini-types.ts:53
Request timeout in milliseconds (optional)
OllamaAdapterConfig
Defined in: packages/nexus-agents/src/adapters/ollama-adapter.ts:61
Configuration specific to OllamaAdapter.
Properties
baseUrl?
optional baseUrl?: string;
Defined in: packages/nexus-agents/src/adapters/ollama-adapter.ts:63
headers?
optional headers?: Record<string, string>;
Defined in: packages/nexus-agents/src/adapters/ollama-adapter.ts:66
maxRetries?
optional maxRetries?: number;
Defined in: packages/nexus-agents/src/adapters/ollama-adapter.ts:65
modelId
modelId: string;
Defined in: packages/nexus-agents/src/adapters/ollama-adapter.ts:62
timeout?
optional timeout?: number;
Defined in: packages/nexus-agents/src/adapters/ollama-adapter.ts:64
OpenAIAdapterConfig
Defined in: packages/nexus-agents/src/adapters/openai-types.ts:72
Configuration specific to OpenAIAdapter.
Properties
apiKey
apiKey: string;
Defined in: packages/nexus-agents/src/adapters/openai-types.ts:76
API key for OpenAI API (required)
baseUrl?
optional baseUrl?: string;
Defined in: packages/nexus-agents/src/adapters/openai-types.ts:78
Base URL for API (optional, defaults to OpenAI’s API)
defaultHeaders?
optional defaultHeaders?: Readonly<Record<string, string | null>>;
Defined in: packages/nexus-agents/src/adapters/openai-types.ts:97
Headers sent on every request; a null value removes a default header
(Authorization: null drops the bearer). Set by the OpenAI-compatible
gateway path for a custom auth header and extra static headers (#6608).
fetchOptions?
optional fetchOptions?: Pick<RequestInit, "dispatcher">;
Defined in: packages/nexus-agents/src/adapters/openai-types.ts:102
fetch options for every request — the gateway path sets a proxy
dispatcher here when HTTPS_PROXY / HTTP_PROXY applies (#6608).
maxRetries?
optional maxRetries?: number;
Defined in: packages/nexus-agents/src/adapters/openai-types.ts:82
Maximum retries for failed requests (optional)
modelId
modelId: string;
Defined in: packages/nexus-agents/src/adapters/openai-types.ts:74
Model ID (e.g., ‘gpt-4o’ or full model identifier)
organization?
optional organization?: string;
Defined in: packages/nexus-agents/src/adapters/openai-types.ts:84
Organization ID (optional)
timeout?
optional timeout?: number;
Defined in: packages/nexus-agents/src/adapters/openai-types.ts:80
Request timeout in milliseconds (optional)
verbatimModelId?
optional verbatimModelId?: boolean;
Defined in: packages/nexus-agents/src/adapters/openai-types.ts:91
Send modelId exactly as given, skipping OPENAI_MODEL_ALIASES
(#6605). Set by the OpenAI-compatible gateway path, whose ids come from
the gateway’s own listing: rewriting gpt-4o to a dated OpenAI snapshot
names a model that gateway may not serve. Default false.
RateLimitExceeded
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:39
Error returned when rate limit is exceeded.
Properties
available
readonly available: number;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:42
requested
readonly requested: number;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:41
retryAfterMs
readonly retryAfterMs: number;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:43
type
readonly type: "rate_limit_exceeded";
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:40
RegistrySnapshot
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:58
Snapshot of registry state for observability.
Properties
availableModels
readonly availableModels: number;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:68
cachedAdapters
readonly cachedAdapters: readonly ("claude" | "gemini" | "codex" | "opencode")[];
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:65
CLI-slot view of cachedArms: the lazily created CLI slots only.
A registered api:* arm is never listed here (#6290 panel: this field
keeps its CliName[] type; it is retired in 9.0, #6291).
cachedArms
readonly cachedArms: readonly ObservedArmId[];
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:67
Every cached arm: lazily created CLI slots and registered api:* endpoint arms (#4392).
taskRouting
readonly taskRouting: readonly TaskRoutingEntry[];
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:59
RetryAttemptInfo
Defined in: packages/nexus-agents/src/adapters/retry.ts:66
Information about a retry attempt for logging/debugging.
Properties
attempt
readonly attempt: number;
Defined in: packages/nexus-agents/src/adapters/retry.ts:68
Current attempt number (1-based)
delayMs
readonly delayMs: number;
Defined in: packages/nexus-agents/src/adapters/retry.ts:72
Delay before next retry in milliseconds
error
readonly error: unknown;
Defined in: packages/nexus-agents/src/adapters/retry.ts:74
The error that triggered the retry
maxAttempts
readonly maxAttempts: number;
Defined in: packages/nexus-agents/src/adapters/retry.ts:70
Maximum attempts allowed
RetryConfig
Defined in: packages/nexus-agents/src/adapters/retry.ts:41
Configuration for retry behavior.
Properties
baseDelayMs
readonly baseDelayMs: number;
Defined in: packages/nexus-agents/src/adapters/retry.ts:45
Base delay in milliseconds between retries. Default: 1000
jitterFactor
readonly jitterFactor: number;
Defined in: packages/nexus-agents/src/adapters/retry.ts:49
Jitter factor (0-1) to randomize delay. Default: 0.1 (10%)
maxDelayMs
readonly maxDelayMs: number;
Defined in: packages/nexus-agents/src/adapters/retry.ts:47
Maximum delay in milliseconds between retries. Default: 30000
maxRetries
readonly maxRetries: number;
Defined in: packages/nexus-agents/src/adapters/retry.ts:43
Maximum number of retry attempts. Default: 3
SdkAdapterConfig
Defined in: packages/nexus-agents/src/adapters/sdk/types.ts:22
Configuration for creating an AI SDK adapter.
Properties
apiKey?
optional apiKey?: string;
Defined in: packages/nexus-agents/src/adapters/sdk/types.ts:28
API key (falls back to environment variable)
baseUrl?
optional baseUrl?: string;
Defined in: packages/nexus-agents/src/adapters/sdk/types.ts:35
Base URL for OpenAI-compatible gateways. Required when
providerId === 'custom-openai', ignored otherwise. Falls back to
the NEXUS_OPENAI_COMPAT_URL environment variable, or its deprecated
alias NEXUS_CUSTOM_API_BASE_URL (#4392 increment 3).
maxRetries?
optional maxRetries?: number;
Defined in: packages/nexus-agents/src/adapters/sdk/types.ts:39
Maximum retries on transient failures
modelId
modelId: string;
Defined in: packages/nexus-agents/src/adapters/sdk/types.ts:26
Model to use (e.g., ‘claude-sonnet-4-6’, ‘gpt-4o’)
providerId
providerId: SdkProviderId;
Defined in: packages/nexus-agents/src/adapters/sdk/types.ts:24
Provider identifier
timeout?
optional timeout?: number;
Defined in: packages/nexus-agents/src/adapters/sdk/types.ts:37
Request timeout in milliseconds
TaskRoutingEntry
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:50
Summary of the pre-computed task routing table.
Properties
category
readonly category:
| "planning"
| "architecture"
| "code_generation"
| "code_review"
| "research"
| "security_review"
| "documentation"
| "testing"
| "devops"
| "exploration";
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:51
primaryCli
readonly primaryCli: "claude" | "gemini" | "codex" | "opencode";
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:52
primaryModel
readonly primaryModel: string;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:54
secondaryCli
readonly secondaryCli: "claude" | "gemini" | "codex" | "opencode";
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:53
UnifiedRegistryConfig
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:42
Configuration for the unified registry.
Properties
defaultCliTimeoutMs?
readonly optional defaultCliTimeoutMs?: number;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:46
Default CLI timeout for subprocess calls (ms)
logger?
readonly optional logger?: ILogger;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:44
Logger instance
WithRetryOptions
Defined in: packages/nexus-agents/src/adapters/retry.ts:297
Options for withRetry function.
Properties
config?
readonly optional config?: Partial<RetryConfig>;
Defined in: packages/nexus-agents/src/adapters/retry.ts:299
Retry configuration. Defaults to DEFAULT_RETRY_CONFIG.
isRetryable?
readonly optional isRetryable?: (error) => boolean;
Defined in: packages/nexus-agents/src/adapters/retry.ts:301
Custom predicate to determine if an error is retryable. Defaults to isRetryableError.
Parameters
error
unknown
Returns
boolean
onRetry?
readonly optional onRetry?: (info) => void;
Defined in: packages/nexus-agents/src/adapters/retry.ts:303
Callback invoked before each retry attempt. Useful for logging.
Parameters
info
Returns
void
signal?
readonly optional signal?: AbortSignal;
Defined in: packages/nexus-agents/src/adapters/retry.ts:318
Aborts the retry loop, including the backoff wait (#4293 item 5).
Without this the backoff was a bare await sleep(delayMs): a cancelled
operation still held real wall-clock time before the loop noticed, and with
the default profile a caller could wait out the full delay for work nobody
wanted any more.
On abort the loop returns err(RetryExhaustedError) rather than throwing —
withRetry’s never-throws contract is what execute_expert relies on, so
the abort path must be an error VALUE. RetryExhaustedError.cause carries
whichever error the last attempt produced, or the signal’s abort reason when
the abort arrived before any attempt failed.
Type Aliases
AdapterConfig
type AdapterConfig = z.infer<typeof AdapterConfigSchema>;
Defined in: packages/nexus-agents/src/adapters/factory.ts:34
Adapter configuration type inferred from schema.
AdapterCreator
type AdapterCreator = (config) => IModelAdapter;
Defined in: packages/nexus-agents/src/adapters/factory.ts:43
Factory function type for creating adapters. Each provider registers a creator function that produces adapters.
Parameters
config
The validated adapter configuration
Returns
A configured model adapter instance
SdkProviderId
type SdkProviderId = "anthropic" | "openai" | "google" | "custom-openai";
Defined in: packages/nexus-agents/src/adapters/sdk/types.ts:17
Supported AI SDK provider identifiers.
custom-openai is for OpenAI-compatible gateways (multi-vendor proxies,
self-hosted LLM servers, corporate model gateways) — uses the same
@ai-sdk/openai package but with a configurable baseURL.
StreamState
type StreamState = "idle" | "streaming" | "paused" | "cancelled" | "completed" | "error";
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:34
State of a stream controller.
Variables
AdapterConfigSchema
const AdapterConfigSchema: ZodObject<{
apiKey: ZodOptional<ZodString>;
baseUrl: ZodOptional<ZodURL>;
maxRetries: ZodOptional<ZodNumber>;
modelId: ZodString;
providerId: ZodString;
timeout: ZodOptional<ZodNumber>;
}, $strip>;
Defined in: packages/nexus-agents/src/adapters/factory.ts:16
Zod schema for adapter configuration. Validates configuration before creating adapters.
CLAUDE_MODEL_ALIASES
const CLAUDE_MODEL_ALIASES: Record<string, string>;
Defined in: packages/nexus-agents/src/adapters/claude-adapter-types.ts:30
Legacy version-suffix aliases mapped to the current registry cliModelName.
Values come from CLAUDE_MODELS so they stay in sync with the canonical
registry. Add legacy entries here, never the version strings themselves.
CLAUDE_MODELS
const CLAUDE_MODELS: {
HAIKU_4: string;
OPUS_4: string;
SONNET_4: string;
};
Defined in: packages/nexus-agents/src/adapters/claude-adapter-types.ts:18
Supported Claude model identifiers.
Derived from config/in-tree-data.ts via getCliModelName() (which reads
the ModelRegistry — see config/model-registry.ts). Do not hardcode
model-version strings here; update the registry.
Type Declaration
HAIKU_4
readonly HAIKU_4: string;
OPUS_4
readonly OPUS_4: string;
SONNET_4
readonly SONNET_4: string;
DEFAULT_COLLECT_STREAM_MAX_CHUNKS
const DEFAULT_COLLECT_STREAM_MAX_CHUNKS: 100000 = 100_000;
Defined in: packages/nexus-agents/src/adapters/streaming.ts:32
Default cap on collected chunks — prevents unbounded memory growth when
callers forget to pass maxChunks. Callers that genuinely need no cap
must opt in explicitly with { maxChunks: Infinity }. (#1913 Class F)
DEFAULT_RETRY_CONFIG
const DEFAULT_RETRY_CONFIG: Readonly<RetryConfig>;
Defined in: packages/nexus-agents/src/adapters/retry.ts:56
Default retry configuration. Derived from canonical source: config/defaults.ts RETRY_DEFAULTS
GEMINI_MODEL_ALIASES
const GEMINI_MODEL_ALIASES: Record<string, string>;
Defined in: packages/nexus-agents/src/adapters/gemini-types.ts:38
Legacy aliases for Gemini models not in the canonical registry.
2.5 / 3.x aliases are NOT in this map — they resolve via the canonical
registry (cliModelName / cliAlias / aliases[]). See resolveModelId.
Only generations Google has deprecated upstream live here, kept for
backward compat with users who hardcoded these strings.
GEMINI_MODELS
const GEMINI_MODELS: {
FLASH_1_5: "gemini-1.5-flash";
FLASH_2_0: "gemini-2.0-flash";
FLASH_2_5: string;
PRO_1_5: "gemini-1.5-pro";
PRO_2_5: string;
};
Defined in: packages/nexus-agents/src/adapters/gemini-types.ts:21
Supported Gemini model identifiers.
Current models (2.5+ and 3.x) derive from config/in-tree-data.ts
(single source of truth — #2200 Child 2). Legacy 1.5 / 2.0 strings remain
as constants for backward compat with external consumers; they are not in
the canonical registry because Google deprecated those generations
upstream in 2025.
Type Declaration
FLASH_1_5
readonly FLASH_1_5: "gemini-1.5-flash" = 'gemini-1.5-flash';
FLASH_2_0
readonly FLASH_2_0: "gemini-2.0-flash" = 'gemini-2.0-flash';
FLASH_2_5
readonly FLASH_2_5: string;
PRO_1_5
readonly PRO_1_5: "gemini-1.5-pro" = 'gemini-1.5-pro';
PRO_2_5
readonly PRO_2_5: string;
OLLAMA_MODELS
const OLLAMA_MODELS: {
CODELLAMA: "codellama";
CODELLAMA_34B: "codellama:34b";
DEEPSEEK_CODER: "deepseek-coder";
GEMMA2: "gemma2";
LLAMA3_1_8B: "llama3.1:8b";
LLAMA3_2_3B: "llama3.2:3b";
LLAMA3_70B: "llama3:70b";
LLAMA3_8B: "llama3:8b";
MISTRAL: "mistral";
MISTRAL_NEMO: "mistral-nemo";
PHI3: "phi3";
QWEN2_5_CODER: "qwen2.5-coder";
};
Defined in: packages/nexus-agents/src/adapters/ollama-adapter.ts:42
Popular Ollama model identifiers.
Type Declaration
CODELLAMA
readonly CODELLAMA: "codellama" = 'codellama';
CODELLAMA_34B
readonly CODELLAMA_34B: "codellama:34b" = 'codellama:34b';
DEEPSEEK_CODER
readonly DEEPSEEK_CODER: "deepseek-coder" = 'deepseek-coder';
GEMMA2
readonly GEMMA2: "gemma2" = 'gemma2';
LLAMA3_1_8B
readonly LLAMA3_1_8B: "llama3.1:8b" = 'llama3.1:8b';
LLAMA3_2_3B
readonly LLAMA3_2_3B: "llama3.2:3b" = 'llama3.2:3b';
LLAMA3_70B
readonly LLAMA3_70B: "llama3:70b" = 'llama3:70b';
LLAMA3_8B
readonly LLAMA3_8B: "llama3:8b" = 'llama3:8b';
MISTRAL
readonly MISTRAL: "mistral" = 'mistral';
MISTRAL_NEMO
readonly MISTRAL_NEMO: "mistral-nemo" = 'mistral-nemo';
PHI3
readonly PHI3: "phi3" = 'phi3';
QWEN2_5_CODER
readonly QWEN2_5_CODER: "qwen2.5-coder" = 'qwen2.5-coder';
OPENAI_MODEL_ALIASES
const OPENAI_MODEL_ALIASES: Record<string, string>;
Defined in: packages/nexus-agents/src/adapters/openai-types.ts:61
User-friendly OpenAI aliases → dated model identifiers.
Identity-only mappings (e.g., 'gpt-5.2-pro' → 'gpt-5.2-pro') were
removed in #2200 Child 3 — resolveModelId already passes unknown ids
through unchanged via ?? modelId. Only entries that translate a
shorthand into a dated version remain.
OPENAI_MODELS
const OPENAI_MODELS: {
GPT_35_TURBO: "gpt-3.5-turbo-0125";
GPT_4_TURBO: "gpt-4-turbo-2024-04-09";
GPT_4O: "gpt-4o-2024-11-20";
GPT_4O_MINI: "gpt-4o-mini-2024-07-18";
GPT_5_2: "gpt-5.2";
GPT_5_2_CODEX: string;
GPT_5_2_INSTANT: "gpt-5.2-chat-latest";
GPT_5_2_PRO: "gpt-5.2-pro";
};
Defined in: packages/nexus-agents/src/adapters/openai-types.ts:37
Supported OpenAI direct-API model identifiers (OpenAI’s own dated names).
GPT_5_2_CODEX derives from the canonical registry (codex-5.2’s cliModelName)
because it overlaps with the Codex CLI; the rest are pure-API constants.
Since #5091 that entry has been repointed to whatever slug codex serves
(gpt-5.6-luna as of 2026-09-23), so the key’s name lags its value; renaming
the key is a public-API change and is tracked separately.
Type Declaration
GPT_35_TURBO
readonly GPT_35_TURBO: "gpt-3.5-turbo-0125" = 'gpt-3.5-turbo-0125';
GPT_4_TURBO
readonly GPT_4_TURBO: "gpt-4-turbo-2024-04-09" = 'gpt-4-turbo-2024-04-09';
GPT_4O
readonly GPT_4O: "gpt-4o-2024-11-20" = 'gpt-4o-2024-11-20';
GPT_4O_MINI
readonly GPT_4O_MINI: "gpt-4o-mini-2024-07-18" = 'gpt-4o-mini-2024-07-18';
GPT_5_2
readonly GPT_5_2: "gpt-5.2" = 'gpt-5.2';
GPT_5_2_CODEX
readonly GPT_5_2_CODEX: string;
Registry-derived: resolves to codex-5.2’s cliModelName, which since
2026-09-23 is gpt-5.6-luna, not a “5.2” model. The key name lags its
value; renaming it is a public-API change tracked in #5489.
GPT_5_2_INSTANT
readonly GPT_5_2_INSTANT: "gpt-5.2-chat-latest" = 'gpt-5.2-chat-latest';
GPT_5_2_PRO
readonly GPT_5_2_PRO: "gpt-5.2-pro" = 'gpt-5.2-pro';
SDK_PROVIDER_ENV_KEYS
const SDK_PROVIDER_ENV_KEYS: Record<SdkProviderId, string>;
Defined in: packages/nexus-agents/src/adapters/sdk/types.ts:49
Maps provider IDs to their environment variable names.
The three vendor entries are current. The custom-openai entry is kept at
its old value so existing readers of this table keep working, but the name
it holds is deprecated — see the entry’s own note.
Functions
bufferStream()
function bufferStream<T>(
stream,
size,
options?
): AsyncIterable<T[]>;
Defined in: packages/nexus-agents/src/adapters/stream-operators.ts:237
Buffers stream chunks into groups of a specified size.
Type Parameters
T
T
Parameters
stream
AsyncIterable<T>
The source stream
size
number
Buffer size
options?
Options including optional AbortSignal
signal?
AbortSignal
Returns
AsyncIterable<T[]>
Stream of chunk arrays
calculateDelay()
function calculateDelay(attempt, config): number;
Defined in: packages/nexus-agents/src/adapters/retry.ts:117
Calculates delay with exponential backoff and jitter.
Uses full jitter strategy: delay = random(0, min(maxDelay, baseDelay * 2^attempt))
Parameters
attempt
number
Current attempt number (0-based)
config
Retry configuration
Returns
number
Delay in milliseconds
collectStream()
function collectStream<T>(stream, options?): Promise<Result<T[], StreamError>>;
Defined in: packages/nexus-agents/src/adapters/streaming.ts:44
Collects all chunks from a stream into an array.
Type Parameters
T
T
Parameters
stream
AsyncIterable<T>
The stream to collect
options?
Options including optional AbortSignal.
maxChunks defaults to DEFAULT_COLLECT_STREAM_MAX_CHUNKS to
prevent unbounded memory growth on forgotten limits. Pass
Infinity explicitly for truly unbounded collection.
maxChunks?
number
signal?
AbortSignal
Returns
Promise<Result<T[], StreamError>>
Result containing collected chunks or error
concatStreams()
function concatStreams<T>(streams, options?): AsyncIterable<T>;
Defined in: packages/nexus-agents/src/adapters/stream-operators-helpers.ts:76
Concatenates multiple streams sequentially.
Type Parameters
T
T
Parameters
streams
AsyncIterable<T, any, any>[]
The streams to concatenate
options?
Options including optional AbortSignal
signal?
AbortSignal
Returns
AsyncIterable<T>
Concatenated stream
createClaudeAdapter()
function createClaudeAdapter(config): ClaudeAdapter;
Defined in: packages/nexus-agents/src/adapters/claude-adapter.ts:499
Creates a ClaudeAdapter with the specified configuration. Factory function for cleaner API.
Parameters
config
Claude adapter configuration
Returns
A configured ClaudeAdapter instance
Example
const adapter = createClaudeAdapter({
modelId: 'claude-sonnet-4',
apiKey: process.env.ANTHROPIC_API_KEY!,
});
createGeminiAdapter()
function createGeminiAdapter(config): GeminiAdapter;
Defined in: packages/nexus-agents/src/adapters/gemini-adapter.ts:445
Creates a GeminiAdapter with the specified configuration. Factory function for cleaner API.
Parameters
config
Gemini adapter configuration
Returns
A configured GeminiAdapter instance
Example
const adapter = createGeminiAdapter({
modelId: 'gemini-2.5-flash',
apiKey: process.env.GOOGLE_AI_API_KEY!,
});
createOllamaAdapter()
function createOllamaAdapter(config): OllamaAdapter;
Defined in: packages/nexus-agents/src/adapters/ollama-adapter.ts:315
Creates an OllamaAdapter with the specified configuration.
Parameters
config
Returns
createOpenAIAdapter()
function createOpenAIAdapter(config): OpenAIAdapter;
Defined in: packages/nexus-agents/src/adapters/openai-adapter.ts:626
Creates an OpenAIAdapter with the specified configuration. Factory function for cleaner API.
Parameters
config
OpenAI adapter configuration
Returns
A configured OpenAIAdapter instance
Example
const adapter = createOpenAIAdapter({
modelId: 'gpt-4o',
apiKey: process.env.OPENAI_API_KEY!,
});
createRateLimiter()
function createRateLimiter(config): AdapterRateLimiter;
Defined in: packages/nexus-agents/src/adapters/rate-limiter.ts:327
Creates a rate limiter with the specified configuration. Factory function for cleaner API.
Parameters
config
Rate limiter configuration
Returns
A new RateLimiter instance
Example
const limiter = createRateLimiter({
capacity: 100,
refillRate: 10,
});
createStream()
function createStream<T>(options?): [StreamController<T>, AsyncIterable<T, any, any>];
Defined in: packages/nexus-agents/src/adapters/streaming-types.ts:255
Creates a controllable stream.
Type Parameters
T
T
Parameters
options?
CreateStreamOptions = {}
Stream creation options
Returns
[StreamController<T>, AsyncIterable<T, any, any>]
Tuple of [controller, iterable]
createUnifiedRegistry()
function createUnifiedRegistry(config?): UnifiedAdapterRegistry;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:386
Create a new UnifiedAdapterRegistry instance.
For most uses, prefer getGlobalRegistry() instead.
Parameters
config?
Returns
filterStream()
function filterStream<T>(
stream,
predicate,
options?
): AsyncIterable<T>;
Defined in: packages/nexus-agents/src/adapters/stream-operators.ts:149
Filters stream chunks based on a predicate.
Type Parameters
T
T
Parameters
stream
AsyncIterable<T>
The source stream
predicate
(chunk, index) => boolean | Promise<boolean>
Function that returns true to keep the chunk
options?
Options including optional AbortSignal
signal?
AbortSignal
Returns
AsyncIterable<T>
Filtered stream
fromArray()
function fromArray<T>(values, options?): AsyncIterable<T>;
Defined in: packages/nexus-agents/src/adapters/stream-operators-helpers.ts:95
Creates a stream from an array of values.
Type Parameters
T
T
Parameters
values
T[]
The values to stream
options?
Options including optional delay between chunks
delayMs?
number
signal?
AbortSignal
Returns
AsyncIterable<T>
Stream of values
getGlobalRegistry()
function getGlobalRegistry(config?): UnifiedAdapterRegistry;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:446
Get the global singleton registry. Creates it on first access with default config.
If the singleton already exists and a non-empty config is supplied, this throws RegistryAlreadyInitializedError — the config cannot be applied, and returning the existing instance would silently hand the caller a registry configured by whoever ran first (#5211). Omitting the config, or passing an empty object, returns the existing instance as before.
Parameters
config?
Returns
isRetryableError()
function isRetryableError(error): boolean;
Defined in: packages/nexus-agents/src/adapters/retry.ts:232
Determines if an error is retryable based on its type, status code, or message.
Retryable errors include:
- HTTP 429 (Too Many Requests)
- HTTP 5xx (Server Errors)
- HTTP 408 (Request Timeout)
- Network errors (connection reset, timeout, etc.)
- NexusError with rate limit or timeout codes
Non-retryable errors include:
- HTTP 400, 401, 403, 404 (Client Errors)
- Validation errors
- Authentication errors
Parameters
error
unknown
The error to check
Returns
boolean
True if the error is retryable
mergeStreams()
function mergeStreams<T>(streams, options?): AsyncIterable<T>;
Defined in: packages/nexus-agents/src/adapters/stream-operators.ts:57
Merges multiple streams into a single stream. Chunks are yielded as they arrive from any source.
Type Parameters
T
T
Parameters
streams
AsyncIterable<T, any, any>[]
The streams to merge
options?
Options including optional AbortSignal
signal?
AbortSignal
Returns
AsyncIterable<T>
Merged stream
reduceStream()
function reduceStream<T, U>(
stream,
reducer,
initialValue,
options?
): Promise<Result<U, StreamError>>;
Defined in: packages/nexus-agents/src/adapters/stream-operators-helpers.ts:145
Reduces a stream to a single value.
Type Parameters
T
T
U
U
Parameters
stream
AsyncIterable<T>
The source stream
reducer
(accumulator, chunk, index) => U | Promise<U>
Reducer function
initialValue
U
Initial accumulator value
options?
Options including optional AbortSignal
signal?
AbortSignal
Returns
Promise<Result<U, StreamError>>
Result containing the final value or error
resetGlobalRegistry()
function resetGlobalRegistry(): void;
Defined in: packages/nexus-agents/src/adapters/unified-registry.ts:458
Reset the global registry (for testing).
Returns
void
skip()
function skip<T>(
stream,
count,
options?
): AsyncIterable<T>;
Defined in: packages/nexus-agents/src/adapters/stream-operators-helpers.ts:49
Skips the first N chunks from a stream.
Type Parameters
T
T
Parameters
stream
AsyncIterable<T>
The source stream
count
number
Number of chunks to skip
options?
Options including optional AbortSignal
signal?
AbortSignal
Returns
AsyncIterable<T>
Stream with first N chunks skipped
sleep()
function sleep(ms): Promise<void>;
Defined in: packages/nexus-agents/src/utils/async-utils.ts:30
Creates a promise that resolves after the specified delay.
Alias: delay (both names are exported for compatibility)
Parameters
ms
number
Delay in milliseconds
Returns
Promise<void>
Promise that resolves after the delay
Example
await sleep(1000); // Wait 1 second
await delay(500); // Wait 500ms (alias)
take()
function take<T>(
stream,
count,
options?
): AsyncIterable<T>;
Defined in: packages/nexus-agents/src/adapters/stream-operators-helpers.ts:17
Takes the first N chunks from a stream.
Type Parameters
T
T
Parameters
stream
AsyncIterable<T>
The source stream
count
number
Number of chunks to take
options?
Options including optional AbortSignal
signal?
AbortSignal
Returns
AsyncIterable<T>
Stream of first N chunks
takeUntil()
function takeUntil<T>(
stream,
predicate,
options?
): AsyncIterable<T>;
Defined in: packages/nexus-agents/src/adapters/stream-operators.ts:116
Takes chunks from a stream until a predicate returns true.
Type Parameters
T
T
Parameters
stream
AsyncIterable<T>
The source stream
predicate
(chunk, index) => boolean | Promise<boolean>
Function that returns true to stop taking
options?
Options including whether to include the matching chunk
inclusive?
boolean
signal?
AbortSignal
Returns
AsyncIterable<T>
Stream of chunks up to (and optionally including) the match
tapStream()
function tapStream<T>(
stream,
fn,
options?
): AsyncIterable<T>;
Defined in: packages/nexus-agents/src/adapters/stream-operators-helpers.ts:119
Taps into a stream without modifying it (for side effects like logging).
Type Parameters
T
T
Parameters
stream
AsyncIterable<T>
The source stream
fn
(chunk, index) => void | Promise<void>
Side effect function called for each chunk
options?
Options including optional AbortSignal
signal?
AbortSignal
Returns
AsyncIterable<T>
Original stream unchanged
transformStream()
function transformStream<T, U>(
stream,
fn,
options?
): AsyncIterable<U>;
Defined in: packages/nexus-agents/src/adapters/stream-operators.ts:33
Transforms stream chunks using a mapping function.
Type Parameters
T
T
U
U
Parameters
stream
AsyncIterable<T>
The source stream
fn
(chunk, index) => U | Promise<U>
Transformation function
options?
Options including optional AbortSignal
signal?
AbortSignal
Returns
AsyncIterable<U>
Transformed stream
withRetry()
function withRetry<T>(operation, options?): Promise<Result<T, RetryExhaustedError>>;
Defined in: packages/nexus-agents/src/adapters/retry.ts:389
Executes an operation with retry logic using exponential backoff.
Type Parameters
T
T
The return type of the operation
Parameters
operation
() => Promise<T>
The async operation to execute
options?
WithRetryOptions = {}
Retry options (config, isRetryable predicate, onRetry callback)
Returns
Promise<Result<T, RetryExhaustedError>>
A Result containing either the operation result or a RetryExhaustedError
Example
const result = await withRetry(
() => fetchData('/api/data'),
{ config: { maxRetries: 5 } }
);
if (result.ok) {
console.log(result.value);
} else {
console.error('All retries failed:', result.error);
}
withRetryWrapper()
function withRetryWrapper<TArgs, TReturn>(fn, options?): (...args) => Promise<Result<TReturn, RetryExhaustedError>>;
Defined in: packages/nexus-agents/src/adapters/retry.ts:453
Wraps an async function with retry logic.
Type Parameters
TArgs
TArgs extends unknown[]
The argument types of the function
TReturn
TReturn
The return type of the function
Parameters
fn
(…args) => Promise<TReturn>
The function to wrap
options?
WithRetryOptions = {}
Retry options
Returns
A wrapped function that will retry on failure
(…args) => Promise<Result<TReturn, RetryExhaustedError>>
Example
const fetchWithRetry = withRetryWrapper(
async (url: string) => fetch(url),
{ config: { maxRetries: 3 } }
);
const result = await fetchWithRetry('https://api.example.com/data');
withTimeout()
function withTimeout<T>(
stream,
timeoutMs,
options?
): AsyncIterable<T>;
Defined in: packages/nexus-agents/src/adapters/stream-operators.ts:177
Adds a timeout to a stream. If no chunk is received within the timeout, the stream throws a TimeoutError.
Type Parameters
T
T
Parameters
stream
AsyncIterable<T>
The source stream
timeoutMs
number
Timeout in milliseconds
options?
Options including optional AbortSignal
signal?
AbortSignal
Returns
AsyncIterable<T>
Stream with timeout applied