cli-adapters

Classes

abstract BaseCliAdapter

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:67

Abstract base class for CLI adapters. Provides common functionality for version checking, health, and error handling.

Extended by

Implements

Constructors

Constructor
new BaseCliAdapter(logger?): BaseCliAdapter;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:113

Parameters
logger?

ILogger

Returns

BaseCliAdapter

Properties

cachedVersion?
protected optional cachedVersion?: string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:103

cachedVersionAt?
protected optional cachedVersionAt?: number;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:111

Epoch ms at which cachedVersion was read off the binary.

The cache never expires, so this is what lets healthCheck say whether its reachable rests on a probe that just ran or on one from minutes ago (#5864).

capacityTracker
protected capacityTracker: CapacityTracker | null = null;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:101

enforcesReadOnlyAnalysis
readonly enforcesReadOnlyAnalysis: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:91

Whether this adapter maps accessMode: 'read-only-analysis' to its CLI’s own enforcement (#6754). False here so a new adapter fails closed until it implements the mode and says so.

Implementation of

ICliAdapter.enforcesReadOnlyAnalysis

enforcesWorkspaceEdit
readonly enforcesWorkspaceEdit: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:98

Whether this adapter maps accessMode: 'workspace-edit' to its CLI’s own enforcement (#6792). False here for the same reason: a new adapter fails closed until it implements the mode and says so.

Implementation of

ICliAdapter.enforcesWorkspaceEdit

initialized
protected initialized: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:102

logger
protected readonly logger: ILogger;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:100

name
abstract readonly name: "claude" | "gemini" | "codex" | "opencode";

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:68

CLI name

Implementation of

ICliAdapter.name

transport
abstract readonly transport: CliTransport;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:69

Transport type

Implementation of

ICliAdapter.transport

Accessors

binaryName
Get Signature
get binaryName(): string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:82

The executable this adapter actually runs.

Defaults to name because for most arms the routing identity and the binary are the same word. They are NOT always the same: the gemini arm runs agy (Antigravity) after Google retired the standalone gemini CLI (#4346). Conflating the two is how that arm ended up executing agy for work while shelling gemini --version for its health check — reporting the dead binary’s version against the live one’s floor, and failing its own availability gate while working perfectly.

Returns

string

capabilities
Get Signature
get capabilities(): CliCapabilityProfile;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:128

Gets the capability profile for this CLI.

Returns

CliCapabilityProfile

Capability profile

Implementation of

ICliAdapter.capabilities

Methods

accessModeRefusal()
protected accessModeRefusal(task): CliError | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:198

The refusal for a task this adapter cannot run in its requested access mode, or undefined (#6754). Adapters override it to add conflicts their own options can create, and call super first.

Parameters
task

CliTask

Returns

CliError | undefined

checkVersionCompatibility()
protected checkVersionCompatibility(version): VersionStatus;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:407

Checks version compatibility.

Parameters
version

string

Returns

VersionStatus

createError()
protected createError(
   code, 
   message, 
   cause?
): CliError;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:454

Creates a CLI error.

Parameters
code

CliErrorCode

message

string

cause?

Error

Returns

CliError

delay()
protected delay(ms): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:480

Delays for the specified milliseconds.

Parameters
ms

number

Returns

Promise<void>

dispose()
abstract dispose(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:157

Abstract method for cleanup. Implemented by concrete adapters.

Returns

Promise<void>

Implementation of

ICliAdapter.dispose

execute()
execute(task, options?): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:167

Executes a task with error handling and retries.

Timeout priority (highest to lowest):

  1. options.timeoutMs - explicit execution option
  2. task.timeoutMs - task-level setting
  3. getTimeoutForTaskAuto() - computed from task complexity and CLI
Parameters
task

CliTask

options?

CliExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

Implementation of

ICliAdapter.execute

executeTask()
abstract executeTask(task, options): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:136

Abstract method for executing a task. Implemented by concrete adapters.

Parameters
task

CliTask

options

ResolvedExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

getCapacity()
getCapacity(): Promise<CapacityStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:361

Gets current capacity status based on tracked usage. Uses usage-based tracking since CLI subprocess execution doesn’t expose HTTP rate limit headers.

Returns

Promise<CapacityStatus>

See

Issue #456 - Real API rate limit tracking

Implementation of

ICliAdapter.getCapacity

getModelInfo()
abstract getModelInfo(): CliModelInfo;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:145

Abstract method for getting model info. Implemented by concrete adapters.

Returns

CliModelInfo

Implementation of

ICliAdapter.getModelInfo

getVersion()
getVersion(): Promise<string>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:334

Gets CLI version.

Returns

Promise<string>

Implementation of

ICliAdapter.getVersion

getVersionMessage()
protected getVersionMessage(status, version): string | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:436

Gets version status message.

Parameters
status

VersionStatus

version

string

Returns

string | undefined

healthCheck()
healthCheck(): Promise<HealthStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:297

Performs a health check.

Returns

Promise<HealthStatus>

Implementation of

ICliAdapter.healthCheck

initCapacityTracker()
protected initCapacityTracker(): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:121

Initializes the capacity tracker. Called by subclasses after name is set.

Returns

void

initialize()
abstract initialize(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:151

Abstract method for initialization. Implemented by concrete adapters.

Returns

Promise<void>

Implementation of

ICliAdapter.initialize

normalizeResponse()
protected normalizeResponse(
   text, 
   usage?, 
   extra?
): CliResponse;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:465

Normalizes CLI response to common format.

Parameters
text

string

usage?

CliTokenUsage

extra?

Partial<CliResponse>

Returns

CliResponse

parseVersion()
protected parseVersion(output): string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:395

Parses version from CLI output.

Parameters
output

string

Returns

string

recordQuotaSignal()
protected recordQuotaSignal(error): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:281

Feed a provider’s own rate-limit assertion into capacity tracking (#4456).

A retry-after the provider stated is far stronger evidence than local counting: the tracker otherwise sees only this process’s spend and cannot observe a plan quota burned gradually or burned elsewhere, which is the incident #4351 reported. Only RATE_LIMITED carries that assertion; the tracker itself decides whether the stated wait is long enough to mean durable quota rather than a per-minute throttle.

Parameters
error

CliError

Returns

void

recordUsage()
protected recordUsage(response): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:386

Records usage from a response for capacity tracking.

Parameters
response

CliResponse

Returns

void

shouldOuterRetry()
protected shouldOuterRetry(opts): boolean;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:218

Whether the shared outer retry loop (executeCliRetryLoop) is allowed to retry this adapter’s failures. The base adapter honors the caller’s allowRetry. Subprocess adapters override this to suppress the outer loop when their own transient-retry layer is active, so the two layers do not nest into multiplied spawns (#2824).

Parameters
opts

ResolvedExecutionOptions

Returns

boolean


ClaudeCliAdapter

Defined in: packages/nexus-agents/src/cli-adapters/adapters/claude-adapter.ts:198

Claude CLI adapter using subprocess transport. Executes: claude -p –output-format json “”

Extends

Constructors

Constructor
new ClaudeCliAdapter(options?): ClaudeCliAdapter;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/claude-adapter.ts:207

Parameters
options?

BaseAdapterOptions

Returns

ClaudeCliAdapter

Overrides

SubprocessCliAdapter.constructor

Properties

cachedVersion?
protected optional cachedVersion?: string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:103

Inherited from

SubprocessCliAdapter.cachedVersion

cachedVersionAt?
protected optional cachedVersionAt?: number;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:111

Epoch ms at which cachedVersion was read off the binary.

The cache never expires, so this is what lets healthCheck say whether its reachable rests on a probe that just ran or on one from minutes ago (#5864).

Inherited from

SubprocessCliAdapter.cachedVersionAt

capacityTracker
protected capacityTracker: CapacityTracker | null = null;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:101

Inherited from

SubprocessCliAdapter.capacityTracker

enforcesReadOnlyAnalysis
readonly enforcesReadOnlyAnalysis: true = true;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/claude-adapter.ts:200

Whether this adapter maps accessMode: 'read-only-analysis' to its CLI’s own enforcement (#6754). False here so a new adapter fails closed until it implements the mode and says so.

Overrides

SubprocessCliAdapter.enforcesReadOnlyAnalysis

enforcesWorkspaceEdit
readonly enforcesWorkspaceEdit: true = true;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/claude-adapter.ts:201

Whether this adapter maps accessMode: 'workspace-edit' to its CLI’s own enforcement (#6792). False here for the same reason: a new adapter fails closed until it implements the mode and says so.

Overrides

SubprocessCliAdapter.enforcesWorkspaceEdit

initialized
protected initialized: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:102

Inherited from

SubprocessCliAdapter.initialized

logger
protected readonly logger: ILogger;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:100

Inherited from

SubprocessCliAdapter.logger

name
readonly name: "claude" | "gemini" | "codex" | "opencode" = 'claude';

Defined in: packages/nexus-agents/src/cli-adapters/adapters/claude-adapter.ts:199

CLI name

Overrides

SubprocessCliAdapter.name

parser
protected readonly parser: ICliResponseParser;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/claude-adapter.ts:203

Overrides

SubprocessCliAdapter.parser

transientRetry
protected readonly transientRetry: TransientRetryConfig;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:336

Transient-error retry config. Override in subclass to enable.

Inherited from

SubprocessCliAdapter.transientRetry

transport
readonly transport: CliTransport = 'subprocess';

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:331

Transport type

Inherited from

SubprocessCliAdapter.transport

Accessors

binaryName
Get Signature
get binaryName(): string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:82

The executable this adapter actually runs.

Defaults to name because for most arms the routing identity and the binary are the same word. They are NOT always the same: the gemini arm runs agy (Antigravity) after Google retired the standalone gemini CLI (#4346). Conflating the two is how that arm ended up executing agy for work while shelling gemini --version for its health check — reporting the dead binary’s version against the live one’s floor, and failing its own availability gate while working perfectly.

Returns

string

Inherited from

SubprocessCliAdapter.binaryName

capabilities
Get Signature
get capabilities(): CliCapabilityProfile;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:128

Gets the capability profile for this CLI.

Returns

CliCapabilityProfile

Capability profile

Inherited from

SubprocessCliAdapter.capabilities

Methods

accessModeRefusal()
protected accessModeRefusal(task): CliError | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/claude-adapter.ts:300

#6754/#6792: a permission bypass would defeat either restricted mode, so the combination is refused rather than resolved one way silently.

Parameters
task

CliTask

Returns

CliError | undefined

Overrides

SubprocessCliAdapter.accessModeRefusal

checkVersionCompatibility()
protected checkVersionCompatibility(version): VersionStatus;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:407

Checks version compatibility.

Parameters
version

string

Returns

VersionStatus

Inherited from

SubprocessCliAdapter.checkVersionCompatibility

createError()
protected createError(
   code, 
   message, 
   cause?
): CliError;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:454

Creates a CLI error.

Parameters
code

CliErrorCode

message

string

cause?

Error

Returns

CliError

Inherited from

SubprocessCliAdapter.createError

delay()
protected delay(ms): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:480

Delays for the specified milliseconds.

Parameters
ms

number

Returns

Promise<void>

Inherited from

SubprocessCliAdapter.delay

dispose()
dispose(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:927

Disposes the adapter (no-op for subprocess).

Returns

Promise<void>

Inherited from

SubprocessCliAdapter.dispose

execute()
execute(task, options?): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:167

Executes a task with error handling and retries.

Timeout priority (highest to lowest):

  1. options.timeoutMs - explicit execution option
  2. task.timeoutMs - task-level setting
  3. getTimeoutForTaskAuto() - computed from task complexity and CLI
Parameters
task

CliTask

options?

CliExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

Inherited from

SubprocessCliAdapter.execute

executeTask()
executeTask(task, options): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/claude-adapter.ts:264

Run the task, and on an out-of-credits envelope for the requested model retry ONCE with the next claude alias the registry lists (#6120).

The credit exhaustion the claude CLI reports is per MODEL — fable answered “You’re out of usage credits” while sonnet answered the same prompt — so it is not evidence against the CLI, and it must not reach the per-CLI circuit breaker as one. The breaker records what leaves this method: a substituted success records nothing, and a second capacity error propagates as the typed error and counts once, because by then the family, not one model, has failed. A non-capacity is_error (auth, a server error) is returned as-is; another model would not fix it.

The substitution is stamped on the response as fallbackFrom so a vote record can say which model actually answered (#6115).

Tool calls claude’s permission layer refused are copied from the result envelope onto the response as permissionDenials (#6792).

Parameters
task

CliTask

options

ResolvedExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

Overrides

SubprocessCliAdapter.executeTask

getCapacity()
getCapacity(): Promise<CapacityStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:361

Gets current capacity status based on tracked usage. Uses usage-based tracking since CLI subprocess execution doesn’t expose HTTP rate limit headers.

Returns

Promise<CapacityStatus>

See

Issue #456 - Real API rate limit tracking

Inherited from

SubprocessCliAdapter.getCapacity

getCommand()
protected getCommand(task): CommandConfig;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/claude-adapter.ts:341

Gets CLI command and arguments for execution. Uses stdin for the prompt to avoid argument escaping issues, especially important when using –add-dir.

Parameters
task

CliTask

Returns

CommandConfig

Overrides

SubprocessCliAdapter.getCommand

getModelInfo()
getModelInfo(): CliModelInfo;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/claude-adapter.ts:231

Gets Claude model information. buildModelInfo matches cliModelName, cliAlias, and aliases[] — a single call handles ‘opus’, ‘sonnet’, ‘haiku’, current model names, and the legacy claude-opus-4 / claude-haiku-3 / etc. entries that live in the registry’s aliases since #2200 Child 1.

Truly unrecognized models fall through to conservative defaults (current Opus pricing).

Returns

CliModelInfo

Overrides

SubprocessCliAdapter.getModelInfo

getVersion()
getVersion(): Promise<string>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:334

Gets CLI version.

Returns

Promise<string>

Inherited from

SubprocessCliAdapter.getVersion

getVersionMessage()
protected getVersionMessage(status, version): string | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:436

Gets version status message.

Parameters
status

VersionStatus

version

string

Returns

string | undefined

Inherited from

SubprocessCliAdapter.getVersionMessage

handleSubprocessOutput()
protected handleSubprocessOutput(
   stdout, 
   stderr, 
   startTime
): Result<CliResponse, CliError>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:757

Handles successful subprocess output.

Parameters
stdout

string

stderr

string

startTime

number

Returns

Result<CliResponse, CliError>

Inherited from

SubprocessCliAdapter.handleSubprocessOutput

healthCheck()
healthCheck(): Promise<HealthStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:297

Performs a health check.

Returns

Promise<HealthStatus>

Inherited from

SubprocessCliAdapter.healthCheck

initCapacityTracker()
protected initCapacityTracker(): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:121

Initializes the capacity tracker. Called by subclasses after name is set.

Returns

void

Inherited from

SubprocessCliAdapter.initCapacityTracker

initialize()
initialize(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:918

Initializes the adapter and capacity tracker.

Returns

Promise<void>

Inherited from

SubprocessCliAdapter.initialize

listModels()
listModels(): Promise<readonly CliModelInfo[]>;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/claude-adapter.ts:217

Key-free model enumeration (#3405): the claude CLI has no list-models command and its OAuth token can’t call /v1/models, so we enumerate the vendor’s models from the models.dev snapshot. Existence only.

Returns

Promise<readonly CliModelInfo[]>

normalizeResponse()
protected normalizeResponse(
   text, 
   usage?, 
   extra?
): CliResponse;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:465

Normalizes CLI response to common format.

Parameters
text

string

usage?

CliTokenUsage

extra?

Partial<CliResponse>

Returns

CliResponse

Inherited from

SubprocessCliAdapter.normalizeResponse

parseVersion()
protected parseVersion(output): string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:395

Parses version from CLI output.

Parameters
output

string

Returns

string

Inherited from

SubprocessCliAdapter.parseVersion

recordQuotaSignal()
protected recordQuotaSignal(error): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:281

Feed a provider’s own rate-limit assertion into capacity tracking (#4456).

A retry-after the provider stated is far stronger evidence than local counting: the tracker otherwise sees only this process’s spend and cannot observe a plan quota burned gradually or burned elsewhere, which is the incident #4351 reported. Only RATE_LIMITED carries that assertion; the tracker itself decides whether the stated wait is long enough to mean durable quota rather than a per-minute throttle.

Parameters
error

CliError

Returns

void

Inherited from

SubprocessCliAdapter.recordQuotaSignal

recordUsage()
protected recordUsage(response): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:386

Records usage from a response for capacity tracking.

Parameters
response

CliResponse

Returns

void

Inherited from

SubprocessCliAdapter.recordUsage

shouldOuterRetry()
protected shouldOuterRetry(opts): boolean;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:347

The inner retryTransient layer is the single retry authority for subprocess CLIs. When it is enabled (the default), the shared outer retry loop must not also retry: nesting both meant up to 6 subprocess spawns and ~10-minute hangs on a persistent TIMEOUT, since the inner layer’s timeout extension compounds on every outer attempt (#2824). The outer loop still runs once, so circuit-breaker failure recording is unaffected.

Parameters
opts

ResolvedExecutionOptions

Returns

boolean

Inherited from

SubprocessCliAdapter.shouldOuterRetry


ClaudeResponseParser

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:83

Parser for Claude CLI JSON output. Implements defensive parsing - only requires essential fields.

Implements

Constructors

Constructor
new ClaudeResponseParser(): ClaudeResponseParser;
Returns

ClaudeResponseParser

Properties

name
readonly name: "claude-parser" = 'claude-parser';

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:84

Parser name (for logging)

Implementation of

ICliResponseParser.name

supportedVersionRange
readonly supportedVersionRange: ">=2.0.0 <3.0.0" = '>=2.0.0 <3.0.0';

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:85

Supported version range (semver)

Implementation of

ICliResponseParser.supportedVersionRange

Methods

extractCostUsd()
extractCostUsd(raw): number | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:246

Extracts the cost the Claude CLI reported for this call.

Prefers total_cost_usd — the vendor’s own total — over summing modelUsage[*].costUSD, because a per-model breakdown can omit a component the total includes. Both are declared on ClaudeCliResponse and neither reached CliResponse before #5241.

Rejects a negative or non-finite figure: a cost is a measurement, and letting a corrupt one through would debit the budget router with garbage.

Parameters
raw

string

Returns

number | null

Implementation of

ICliResponseParser.extractCostUsd

extractErrorMessage()
extractErrorMessage(raw): string | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:149

The error text of an is_error: true envelope, with its stop_reason (#6120).

Before this the envelope reached the adapter only through the generic unparseable-output path, whose first step scans the WHOLE stdout for rate-limit text. The out-of-credits envelope carries api_error_status: 429, so that scan matched and the error message became the first 500 characters of the envelope — {"duration_api_ms":0,… — while the one field that names the cause, result, never reached anyone. Surfacing it here routes the envelope through classifyErrorOnlyStream, which classifies the message text rather than the envelope bytes.

null when the envelope is not an error, or when result is empty: an empty error text is not a message, and the caller’s recovery order handles it as before.

Parameters
raw

string

Returns

string | null

Implementation of

ICliResponseParser.extractErrorMessage

extractPermissionDenials()
extractPermissionDenials(raw): CliPermissionDenial[] | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:173

The tool calls claude’s permission layer refused (#6792), from the result envelope’s permission_denials. null when the field is absent or empty, or the output is not JSON; an entry without a tool name is skipped rather than invented.

Parameters
raw

string

Returns

CliPermissionDenial[] | null

extractResponse()
extractResponse(raw): string | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:109

Extracts just the response text (most stable field). Returns null if the response contains an error.

Parameters
raw

string

Returns

string | null

Implementation of

ICliResponseParser.extractResponse

extractSessionId()
extractSessionId(raw): string | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:264

Extracts session ID for resumption.

Parameters
raw

string

Returns

string | null

Implementation of

ICliResponseParser.extractSessionId

extractUsage()
extractUsage(raw): CliTokenUsage | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:193

Extracts token usage from response.

Parameters
raw

string

Returns

CliTokenUsage | null

Implementation of

ICliResponseParser.extractUsage

parse()
parse(raw): ClaudeCliResponse | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:90

Parses complete Claude CLI response.

Parameters
raw

string

Returns

ClaudeCliResponse | null

Implementation of

ICliResponseParser.parse


CliCircuitBreakerIntegration

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:128

Integrates circuit breaker pattern with CLI adapters. Provides automatic fallback when a CLI’s circuit opens.

Implements

Constructors

Constructor
new CliCircuitBreakerIntegration(
   adapters, 
   config?, 
   logger?
): CliCircuitBreakerIntegration;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:134

Parameters
adapters

readonly ICliAdapter[]

config?

CliCircuitBreakerConfig

logger?

ILogger

Returns

CliCircuitBreakerIntegration

Methods

addStateChangeListener()
addStateChangeListener(listener): void;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:239

Parameters
listener

CircuitStateChangeListener

Returns

void

Implementation of

ICliCircuitBreakerIntegration.addStateChangeListener

execute()
execute(
   adapter, 
   task, 
   taskCategory?
): Promise<Result<CircuitProtectedResult, CliError | CircuitError>>;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:149

Parameters
adapter

ICliAdapter

task

CliTask

taskCategory?

| "planning" | "architecture" | "code_generation" | "code_review" | "research" | "security_review" | "documentation" | "testing" | "devops" | "exploration"

Returns

Promise<Result<CircuitProtectedResult, CliError | CircuitError>>

Implementation of

ICliCircuitBreakerIntegration.execute

getCircuitSnapshots()
getCircuitSnapshots(): Map<"claude" | "gemini" | "codex" | "opencode", CircuitBreakerSnapshot>;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:217

Returns

Map<"claude" | "gemini" | "codex" | "opencode", CircuitBreakerSnapshot>

Implementation of

ICliCircuitBreakerIntegration.getCircuitSnapshots

getHealthStatus()
getHealthStatus(): CliCircuitHealthStatus;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:192

Returns

CliCircuitHealthStatus

Implementation of

ICliCircuitBreakerIntegration.getHealthStatus

resetAllCircuits()
resetAllCircuits(): void;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:234

Returns

void

Implementation of

ICliCircuitBreakerIntegration.resetAllCircuits

resetCircuit()
resetCircuit(cliName): void;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:229

Parameters
cliName

"claude" | "gemini" | "codex" | "opencode"

Returns

void

Implementation of

ICliCircuitBreakerIntegration.resetCircuit


CliDetectionCache

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:113

CLI detection cache implementation. Thread-safe for Node.js single-threaded execution.

Implements

Constructors

Constructor
new CliDetectionCache(config?): CliDetectionCache;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:123

Parameters
config?

Partial<CliDetectionCacheConfig>

Returns

CliDetectionCache

Methods

get()
get(cli): CliHealthResult | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:137

Get cached health result for a CLI

Parameters
cli

"claude" | "gemini" | "codex" | "opencode"

Returns

CliHealthResult | undefined

Implementation of

ICliDetectionCache.get

getAll()
getAll(): ReadonlyMap<"claude" | "gemini" | "codex" | "opencode", CliHealthResult>;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:207

Get all cached results

Returns

ReadonlyMap<"claude" | "gemini" | "codex" | "opencode", CliHealthResult>

Implementation of

ICliDetectionCache.getAll

getEffectiveTtl()
getEffectiveTtl(cli): number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:176

Returns the effective TTL for a CLI, applying adaptive multiplier if enabled.

Parameters
cli

"claude" | "gemini" | "codex" | "opencode"

Returns

number

Implementation of

ICliDetectionCache.getEffectiveTtl

getStats()
getStats(): CliCacheStats;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:211

Get cache statistics

Returns

CliCacheStats

Implementation of

ICliDetectionCache.getStats

invalidate()
invalidate(cli?): void;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:195

Invalidate cache for a specific CLI or all CLIs

Parameters
cli?

"claude" | "gemini" | "codex" | "opencode"

Returns

void

Implementation of

ICliDetectionCache.invalidate

isStale()
isStale(cli): boolean;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:167

Check if cache entry is stale

Parameters
cli

"claude" | "gemini" | "codex" | "opencode"

Returns

boolean

Implementation of

ICliDetectionCache.isStale

resetStats()
resetStats(): void;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:225

Resets cache statistics.

Returns

void

set()
set(cli, result): void;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:157

Set health result for a CLI

Parameters
cli

"claude" | "gemini" | "codex" | "opencode"

result

CliHealthResult

Returns

void

Implementation of

ICliDetectionCache.set

fromHealthStatus()
static fromHealthStatus(status): CliHealthResult;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:235

Converts HealthStatus to CliHealthResult for caching.

Parameters
status

HealthStatus

Returns

CliHealthResult


CodexCliAdapter

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-adapter.ts:56

CLI Adapters exports - CLI integration with defensive parsing Split from index.ts for file size compliance (Issue #285)

Extends

Constructors

Constructor
new CodexCliAdapter(options?): CodexCliAdapter;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-adapter.ts:64

Parameters
options?

CodexAdapterOptions

Returns

CodexCliAdapter

Overrides

SubprocessCliAdapter.constructor

Properties

cachedVersion?
protected optional cachedVersion?: string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:103

Inherited from

SubprocessCliAdapter.cachedVersion

cachedVersionAt?
protected optional cachedVersionAt?: number;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:111

Epoch ms at which cachedVersion was read off the binary.

The cache never expires, so this is what lets healthCheck say whether its reachable rests on a probe that just ran or on one from minutes ago (#5864).

Inherited from

SubprocessCliAdapter.cachedVersionAt

capacityTracker
protected capacityTracker: CapacityTracker | null = null;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:101

Inherited from

SubprocessCliAdapter.capacityTracker

enforcesReadOnlyAnalysis
readonly enforcesReadOnlyAnalysis: true = true;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-adapter.ts:58

Whether this adapter maps accessMode: 'read-only-analysis' to its CLI’s own enforcement (#6754). False here so a new adapter fails closed until it implements the mode and says so.

Overrides

SubprocessCliAdapter.enforcesReadOnlyAnalysis

enforcesWorkspaceEdit
readonly enforcesWorkspaceEdit: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:98

Whether this adapter maps accessMode: 'workspace-edit' to its CLI’s own enforcement (#6792). False here for the same reason: a new adapter fails closed until it implements the mode and says so.

Inherited from

SubprocessCliAdapter.enforcesWorkspaceEdit

initialized
protected initialized: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:102

Inherited from

SubprocessCliAdapter.initialized

logger
protected readonly logger: ILogger;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:100

Inherited from

SubprocessCliAdapter.logger

name
readonly name: "claude" | "gemini" | "codex" | "opencode" = 'codex';

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-adapter.ts:57

CLI name

Overrides

SubprocessCliAdapter.name

parser
protected readonly parser: ICliResponseParser;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-adapter.ts:59

Overrides

SubprocessCliAdapter.parser

transientRetry
protected readonly transientRetry: TransientRetryConfig;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:336

Transient-error retry config. Override in subclass to enable.

Inherited from

SubprocessCliAdapter.transientRetry

transport
readonly transport: CliTransport = 'subprocess';

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:331

Transport type

Inherited from

SubprocessCliAdapter.transport

Accessors

binaryName
Get Signature
get binaryName(): string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:82

The executable this adapter actually runs.

Defaults to name because for most arms the routing identity and the binary are the same word. They are NOT always the same: the gemini arm runs agy (Antigravity) after Google retired the standalone gemini CLI (#4346). Conflating the two is how that arm ended up executing agy for work while shelling gemini --version for its health check — reporting the dead binary’s version against the live one’s floor, and failing its own availability gate while working perfectly.

Returns

string

Inherited from

SubprocessCliAdapter.binaryName

capabilities
Get Signature
get capabilities(): CliCapabilityProfile;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:128

Gets the capability profile for this CLI.

Returns

CliCapabilityProfile

Capability profile

Inherited from

SubprocessCliAdapter.capabilities

Methods

accessModeRefusal()
protected accessModeRefusal(task): CliError | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:198

The refusal for a task this adapter cannot run in its requested access mode, or undefined (#6754). Adapters override it to add conflicts their own options can create, and call super first.

Parameters
task

CliTask

Returns

CliError | undefined

Inherited from

SubprocessCliAdapter.accessModeRefusal

checkVersionCompatibility()
protected checkVersionCompatibility(version): VersionStatus;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:407

Checks version compatibility.

Parameters
version

string

Returns

VersionStatus

Inherited from

SubprocessCliAdapter.checkVersionCompatibility

createError()
protected createError(
   code, 
   message, 
   cause?
): CliError;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:454

Creates a CLI error.

Parameters
code

CliErrorCode

message

string

cause?

Error

Returns

CliError

Inherited from

SubprocessCliAdapter.createError

delay()
protected delay(ms): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:480

Delays for the specified milliseconds.

Parameters
ms

number

Returns

Promise<void>

Inherited from

SubprocessCliAdapter.delay

dispose()
dispose(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:927

Disposes the adapter (no-op for subprocess).

Returns

Promise<void>

Inherited from

SubprocessCliAdapter.dispose

execute()
execute(task, options?): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:167

Executes a task with error handling and retries.

Timeout priority (highest to lowest):

  1. options.timeoutMs - explicit execution option
  2. task.timeoutMs - task-level setting
  3. getTimeoutForTaskAuto() - computed from task complexity and CLI
Parameters
task

CliTask

options?

CliExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

Inherited from

SubprocessCliAdapter.execute

executeTask()
executeTask(task, options): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:416

Executes a task via subprocess, with optional transient-error retry. When transientRetry.enabled is true, transient errors (timeout, rate_limit, connection, parse) are retried with exponential backoff (500ms, 1000ms). Parse errors get max 1 retry (#1533); others get 2.

Parameters
task

CliTask

options

ResolvedExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

Inherited from

SubprocessCliAdapter.executeTask

getCapacity()
getCapacity(): Promise<CapacityStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:361

Gets current capacity status based on tracked usage. Uses usage-based tracking since CLI subprocess execution doesn’t expose HTTP rate limit headers.

Returns

Promise<CapacityStatus>

See

Issue #456 - Real API rate limit tracking

Inherited from

SubprocessCliAdapter.getCapacity

getCommand()
protected getCommand(task): CommandConfig;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-adapter.ts:98

Gets CLI command and arguments for execution. Task content is passed as a positional argument (not via stdin).

Parameters
task

CliTask

Returns

CommandConfig

Overrides

SubprocessCliAdapter.getCommand

getModelInfo()
getModelInfo(): CliModelInfo;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-adapter.ts:79

Gets Codex model information. Resolves from canonical registry when possible, falls back to legacy lookup.

Returns

CliModelInfo

Overrides

SubprocessCliAdapter.getModelInfo

getVersion()
getVersion(): Promise<string>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:334

Gets CLI version.

Returns

Promise<string>

Inherited from

SubprocessCliAdapter.getVersion

getVersionMessage()
protected getVersionMessage(status, version): string | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:436

Gets version status message.

Parameters
status

VersionStatus

version

string

Returns

string | undefined

Inherited from

SubprocessCliAdapter.getVersionMessage

handleSubprocessOutput()
protected handleSubprocessOutput(
   stdout, 
   stderr, 
   startTime
): Result<CliResponse, CliError>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:757

Handles successful subprocess output.

Parameters
stdout

string

stderr

string

startTime

number

Returns

Result<CliResponse, CliError>

Inherited from

SubprocessCliAdapter.handleSubprocessOutput

healthCheck()
healthCheck(): Promise<HealthStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:297

Performs a health check.

Returns

Promise<HealthStatus>

Inherited from

SubprocessCliAdapter.healthCheck

initCapacityTracker()
protected initCapacityTracker(): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:121

Initializes the capacity tracker. Called by subclasses after name is set.

Returns

void

Inherited from

SubprocessCliAdapter.initCapacityTracker

initialize()
initialize(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:918

Initializes the adapter and capacity tracker.

Returns

Promise<void>

Inherited from

SubprocessCliAdapter.initialize

listModels()
listModels(): Promise<readonly CliModelInfo[]>;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-adapter.ts:71

Key-free model enumeration via the models.dev snapshot (#3405).

Returns

Promise<readonly CliModelInfo[]>

normalizeResponse()
protected normalizeResponse(
   text, 
   usage?, 
   extra?
): CliResponse;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:465

Normalizes CLI response to common format.

Parameters
text

string

usage?

CliTokenUsage

extra?

Partial<CliResponse>

Returns

CliResponse

Inherited from

SubprocessCliAdapter.normalizeResponse

parseVersion()
protected parseVersion(output): string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:395

Parses version from CLI output.

Parameters
output

string

Returns

string

Inherited from

SubprocessCliAdapter.parseVersion

recordQuotaSignal()
protected recordQuotaSignal(error): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:281

Feed a provider’s own rate-limit assertion into capacity tracking (#4456).

A retry-after the provider stated is far stronger evidence than local counting: the tracker otherwise sees only this process’s spend and cannot observe a plan quota burned gradually or burned elsewhere, which is the incident #4351 reported. Only RATE_LIMITED carries that assertion; the tracker itself decides whether the stated wait is long enough to mean durable quota rather than a per-minute throttle.

Parameters
error

CliError

Returns

void

Inherited from

SubprocessCliAdapter.recordQuotaSignal

recordUsage()
protected recordUsage(response): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:386

Records usage from a response for capacity tracking.

Parameters
response

CliResponse

Returns

void

Inherited from

SubprocessCliAdapter.recordUsage

shouldOuterRetry()
protected shouldOuterRetry(opts): boolean;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:347

The inner retryTransient layer is the single retry authority for subprocess CLIs. When it is enabled (the default), the shared outer retry loop must not also retry: nesting both meant up to 6 subprocess spawns and ~10-minute hangs on a persistent TIMEOUT, since the inner layer’s timeout extension compounds on every outer attempt (#2824). The outer loop still runs once, so circuit-breaker failure recording is unaffected.

Parameters
opts

ResolvedExecutionOptions

Returns

boolean

Inherited from

SubprocessCliAdapter.shouldOuterRetry


CodexMcpAdapter

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-mcp-adapter.ts:61

Codex CLI adapter using MCP transport.

Extends BaseCliAdapter which provides:

  • Retry logic with exponential backoff
  • Health checks with version compatibility
  • Capacity tracking
  • Error creation helpers

Extends

Constructors

Constructor
new CodexMcpAdapter(options?): CodexMcpAdapter;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-mcp-adapter.ts:86

Parameters
options?

CodexAdapterOptions

Returns

CodexMcpAdapter

Overrides

BaseCliAdapter.constructor

Properties

cachedVersion?
protected optional cachedVersion?: string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:103

Inherited from

BaseCliAdapter.cachedVersion

cachedVersionAt?
protected optional cachedVersionAt?: number;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:111

Epoch ms at which cachedVersion was read off the binary.

The cache never expires, so this is what lets healthCheck say whether its reachable rests on a probe that just ran or on one from minutes ago (#5864).

Inherited from

BaseCliAdapter.cachedVersionAt

capacityTracker
protected capacityTracker: CapacityTracker | null = null;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:101

Inherited from

BaseCliAdapter.capacityTracker

enforcesReadOnlyAnalysis
readonly enforcesReadOnlyAnalysis: true = true;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-mcp-adapter.ts:68

#6754: a new thread is started with sandbox: 'read-only' on every call. A codex-reply carries no sandbox argument, so a read-only task that continues a session is refused in accessModeRefusal.

Overrides

BaseCliAdapter.enforcesReadOnlyAnalysis

enforcesWorkspaceEdit
readonly enforcesWorkspaceEdit: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:98

Whether this adapter maps accessMode: 'workspace-edit' to its CLI’s own enforcement (#6792). False here for the same reason: a new adapter fails closed until it implements the mode and says so.

Inherited from

BaseCliAdapter.enforcesWorkspaceEdit

initialized
protected initialized: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:102

Inherited from

BaseCliAdapter.initialized

logger
protected readonly logger: ILogger;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:100

Inherited from

BaseCliAdapter.logger

name
readonly name: "claude" | "gemini" | "codex" | "opencode" = 'codex';

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-mcp-adapter.ts:62

CLI name

Overrides

BaseCliAdapter.name

transport
readonly transport: CliTransport = 'mcp';

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-mcp-adapter.ts:69

Transport type

Overrides

BaseCliAdapter.transport

Accessors

binaryName
Get Signature
get binaryName(): string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:82

The executable this adapter actually runs.

Defaults to name because for most arms the routing identity and the binary are the same word. They are NOT always the same: the gemini arm runs agy (Antigravity) after Google retired the standalone gemini CLI (#4346). Conflating the two is how that arm ended up executing agy for work while shelling gemini --version for its health check — reporting the dead binary’s version against the live one’s floor, and failing its own availability gate while working perfectly.

Returns

string

Inherited from

BaseCliAdapter.binaryName

capabilities
Get Signature
get capabilities(): CliCapabilityProfile;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:128

Gets the capability profile for this CLI.

Returns

CliCapabilityProfile

Capability profile

Inherited from

BaseCliAdapter.capabilities

Methods

accessModeRefusal()
protected accessModeRefusal(task): CliError | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-mcp-adapter.ts:249

#6754: a continued session cannot be pinned to the read-only sandbox.

Parameters
task

CliTask

Returns

CliError | undefined

Overrides

BaseCliAdapter.accessModeRefusal

checkVersionCompatibility()
protected checkVersionCompatibility(version): VersionStatus;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:407

Checks version compatibility.

Parameters
version

string

Returns

VersionStatus

Inherited from

BaseCliAdapter.checkVersionCompatibility

createError()
protected createError(
   code, 
   message, 
   cause?
): CliError;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:454

Creates a CLI error.

Parameters
code

CliErrorCode

message

string

cause?

Error

Returns

CliError

Inherited from

BaseCliAdapter.createError

delay()
protected delay(ms): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:480

Delays for the specified milliseconds.

Parameters
ms

number

Returns

Promise<void>

Inherited from

BaseCliAdapter.delay

dispose()
dispose(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-mcp-adapter.ts:346

Disposes the adapter and closes MCP connection.

Returns

Promise<void>

Overrides

BaseCliAdapter.dispose

execute()
execute(task, options?): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:167

Executes a task with error handling and retries.

Timeout priority (highest to lowest):

  1. options.timeoutMs - explicit execution option
  2. task.timeoutMs - task-level setting
  3. getTimeoutForTaskAuto() - computed from task complexity and CLI
Parameters
task

CliTask

options?

CliExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

Inherited from

BaseCliAdapter.execute

executeTask()
executeTask(_task, options): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-mcp-adapter.ts:171

Executes a task via MCP client. Called by BaseCliAdapter.execute() with retry handling.

Parameters
_task

CliTask

options

ResolvedExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

Overrides

BaseCliAdapter.executeTask

getCapacity()
getCapacity(): Promise<CapacityStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:361

Gets current capacity status based on tracked usage. Uses usage-based tracking since CLI subprocess execution doesn’t expose HTTP rate limit headers.

Returns

Promise<CapacityStatus>

See

Issue #456 - Real API rate limit tracking

Inherited from

BaseCliAdapter.getCapacity

getModelInfo()
getModelInfo(): CliModelInfo;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-mcp-adapter.ts:111

Gets Codex model information. Resolves from canonical registry when possible, falls back to legacy lookup.

Returns

CliModelInfo

Overrides

BaseCliAdapter.getModelInfo

getVersion()
getVersion(): Promise<string>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:334

Gets CLI version.

Returns

Promise<string>

Inherited from

BaseCliAdapter.getVersion

getVersionMessage()
protected getVersionMessage(status, version): string | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:436

Gets version status message.

Parameters
status

VersionStatus

version

string

Returns

string | undefined

Inherited from

BaseCliAdapter.getVersionMessage

healthCheck()
healthCheck(): Promise<HealthStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:297

Performs a health check.

Returns

Promise<HealthStatus>

Inherited from

BaseCliAdapter.healthCheck

initCapacityTracker()
protected initCapacityTracker(): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:121

Initializes the capacity tracker. Called by subclasses after name is set.

Returns

void

Inherited from

BaseCliAdapter.initCapacityTracker

initialize()
initialize(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-mcp-adapter.ts:129

Initializes the MCP connection to Codex.

Returns

Promise<void>

Overrides

BaseCliAdapter.initialize

listModels()
listModels(): Promise<readonly CliModelInfo[]>;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/codex-mcp-adapter.ts:103

Key-free model enumeration via the models.dev snapshot (#3405), matching CodexCliAdapter.

#4318: this was missing, and buildDefaultModelSources includes an adapter only when hasListModels(adapter) is true. Since createAllAdapters defaults codex to the mcp transport, codex was silently filtered out of list_available_models — the probe reported one fewer transport than it had, with no error anywhere. Model enumeration is transport-independent, so the two adapters must answer identically.

Returns

Promise<readonly CliModelInfo[]>

normalizeResponse()
protected normalizeResponse(
   text, 
   usage?, 
   extra?
): CliResponse;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:465

Normalizes CLI response to common format.

Parameters
text

string

usage?

CliTokenUsage

extra?

Partial<CliResponse>

Returns

CliResponse

Inherited from

BaseCliAdapter.normalizeResponse

parseVersion()
protected parseVersion(output): string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:395

Parses version from CLI output.

Parameters
output

string

Returns

string

Inherited from

BaseCliAdapter.parseVersion

recordQuotaSignal()
protected recordQuotaSignal(error): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:281

Feed a provider’s own rate-limit assertion into capacity tracking (#4456).

A retry-after the provider stated is far stronger evidence than local counting: the tracker otherwise sees only this process’s spend and cannot observe a plan quota burned gradually or burned elsewhere, which is the incident #4351 reported. Only RATE_LIMITED carries that assertion; the tracker itself decides whether the stated wait is long enough to mean durable quota rather than a per-minute throttle.

Parameters
error

CliError

Returns

void

Inherited from

BaseCliAdapter.recordQuotaSignal

recordUsage()
protected recordUsage(response): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:386

Records usage from a response for capacity tracking.

Parameters
response

CliResponse

Returns

void

Inherited from

BaseCliAdapter.recordUsage

shouldOuterRetry()
protected shouldOuterRetry(opts): boolean;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:218

Whether the shared outer retry loop (executeCliRetryLoop) is allowed to retry this adapter’s failures. The base adapter honors the caller’s allowRetry. Subprocess adapters override this to suppress the outer loop when their own transient-retry layer is active, so the two layers do not nest into multiplied spawns (#2824).

Parameters
opts

ResolvedExecutionOptions

Returns

boolean

Inherited from

BaseCliAdapter.shouldOuterRetry


CodexResponseParser

Defined in: packages/nexus-agents/src/cli-adapters/parsers/codex-parser.ts:79

Parser for Codex CLI NDJSON output. Implements defensive parsing - processes stream of events.

Implements

Constructors

Constructor
new CodexResponseParser(): CodexResponseParser;
Returns

CodexResponseParser

Properties

name
readonly name: "codex-parser" = 'codex-parser';

Defined in: packages/nexus-agents/src/cli-adapters/parsers/codex-parser.ts:80

Parser name (for logging)

Implementation of

ICliResponseParser.name

supportedVersionRange
readonly supportedVersionRange: ">=0.70.0 <1.0.0" = '>=0.70.0 <1.0.0';

Defined in: packages/nexus-agents/src/cli-adapters/parsers/codex-parser.ts:81

Supported version range (semver)

Implementation of

ICliResponseParser.supportedVersionRange

Methods

extractResponse()
extractResponse(raw): string | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/codex-parser.ts:152

Extracts just the response text (most stable field). Concatenates all agent_message items.

Parameters
raw

string

Returns

string | null

Implementation of

ICliResponseParser.extractResponse

extractSessionId()
extractSessionId(raw): string | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/codex-parser.ts:190

Extracts session ID (thread_id) for resumption.

Parameters
raw

string

Returns

string | null

Implementation of

ICliResponseParser.extractSessionId

extractUsage()
extractUsage(raw): CliTokenUsage | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/codex-parser.ts:164

Extracts token usage from NDJSON stream.

Parameters
raw

string

Returns

CliTokenUsage | null

Implementation of

ICliResponseParser.extractUsage

parse()
parse(raw): CodexCliResponse | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/codex-parser.ts:86

Parses complete Codex CLI NDJSON stream.

Parameters
raw

string

Returns

CodexCliResponse | null

Implementation of

ICliResponseParser.parse


CompositeRouter

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:201

CompositeRouter implementation.

Implements

Constructors

Constructor
new CompositeRouter(
   adapters, 
   config?, 
   logger?
): CompositeRouter;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:269

Parameters
adapters

Map<RoutingArmId, ICliAdapter>

config?

Partial<CompositeRouterConfigWithPreference>

logger?

ILogger

Returns

CompositeRouter

Methods

executeDecision()
executeDecision(
   decision, 
   task, 
   runTask?, 
   options?
): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:611

Execute a decision route(task) returned and auto-record feedback (#6533).

For callers that need the decision itself (to display it, or to apply the route-time model to the task) before running it. task must be the object passed to route(): route-time attribution is keyed on it. runTask is what the arm executes when it differs from task (defaults to task). options reaches the arm’s execute unchanged (#6736). The result names the arm that ran (routedCli) and its own run time (routedDurationMs), on success and on failure.

Parameters
decision

CompositeRoutingDecision

task

CliTask

runTask?

CliTask = task

options?

CliExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

Implementation of

ICompositeRouter.executeDecision

executeTask()
executeTask(task, options?): Promise<Result<CliResponse, 
  | CliError
| CompositeRoutingError>>;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:589

Unified method that routes, executes, and auto-records feedback. Use this for most cases; use route() when you need decision details without execution.

Parameters
task

CliTask

Task to execute

options?

CliExecutionOptions

Execution options for the routed arm, e.g. an abort signal (#6736); passed to the adapter unchanged.

Returns

Promise<Result<CliResponse, | CliError | CompositeRoutingError>>

Result with CLI response or error

Implementation of

ICompositeRouter.executeTask

getAvailableModelsCache()
getAvailableModelsCache(): AvailableModelsCache | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:838

(#2540 PR 7) Public accessor for the wired cache (or undefined).

Returns

AvailableModelsCache | undefined

getLatencyTracker()
getLatencyTracker(): ILatencyTracker | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:1070

Returns

ILatencyTracker | undefined

Implementation of

ICompositeRouter.getLatencyTracker

getMetricsCollector()
getMetricsCollector(): IRoutingMetricsCollector | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:1078

Get the metrics collector (if configured). (Source: Issue #559 - Wire RoutingMetricsCollector to CompositeRouter)

Returns

IRoutingMetricsCollector | undefined

Implementation of

ICompositeRouter.getMetricsCollector

getOrchestrationObserver()
getOrchestrationObserver(): 
  | IOrchestrationObserver
  | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:1086

Get the orchestration observer (if configured). (Source: Issue #587 - Wire OrchestrationObserver to CompositeRouter)

Returns

| IOrchestrationObserver | undefined

Implementation of

ICompositeRouter.getOrchestrationObserver

getRoutingMemory()
getRoutingMemory(): IRoutingMemory | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:1117

Get the routing memory instance (if enabled).

Returns

IRoutingMemory | undefined

Implementation of

ICompositeRouter.getRoutingMemory

getStats()
getStats(): CompositeRouterStats;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:1090

Returns

CompositeRouterStats

Implementation of

ICompositeRouter.getStats

getTopsisConfig()
getTopsisConfig(): TopsisConfig | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:852

The TOPSIS config the ranking stage was actually built with, or undefined when ranking is disabled (#5785).

Mirrors getAvailableModelsCache above: a narrow accessor so the WIRING is verifiable, not just the adapter’s output. The adapter used to return a topsisConfig that this class never read, and a test asserting only the adapter would have passed against that.

Returns

TopsisConfig | undefined

getZeroRouter()
getZeroRouter(): IZeroRouter | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:1066

Returns

IZeroRouter | undefined

Implementation of

ICompositeRouter.getZeroRouter

hasMinimumPreferenceData()
hasMinimumPreferenceData(): boolean;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:1049

Returns

boolean

Implementation of

ICompositeRouter.hasMinimumPreferenceData

recordDifficultyOutcome()
recordDifficultyOutcome(
   task, 
   success, 
   qualityScore?
): void;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:1009

Parameters
task

CliTask

success

boolean

qualityScore?

number

Returns

void

Implementation of

ICompositeRouter.recordDifficultyOutcome

recordOutcome()
recordOutcome(
   cliName, 
   task, 
   reward, 
   success?
): void;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:986

Record a routing outcome for a distinct routing arm (CLI slot or api:* arm) (#3422).

Parameters
cliName

RoutingArmId

task

CliTask

reward

number

success?

boolean

Returns

void

Implementation of

ICompositeRouter.recordOutcome

recordPreference()
recordPreference(
   query, 
   strongModelPreferred, 
   quality?
): void;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:1001

Parameters
query

string

strongModelPreferred

boolean

quality?
strong?

number

weak?

number

Returns

void

Implementation of

ICompositeRouter.recordPreference

route()
route(task): Promise<Result<CompositeRoutingDecision, CompositeRoutingError>>;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:530

Parameters
task

CliTask

Returns

Promise<Result<CompositeRoutingDecision, CompositeRoutingError>>

Implementation of

ICompositeRouter.route


CompositeRoutingError

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:270

Error from composite routing.

Extends

  • Error

Constructors

Constructor
new CompositeRoutingError(
   message, 
   stage, 
   cause?
): CompositeRoutingError;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:273

Parameters
message

string

stage

string

cause?

Error

Returns

CompositeRoutingError

Overrides
Error.constructor

Properties

cause?
optional cause?: unknown;

Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es2022.error.d.ts:24

Inherited from
Error.cause
message
message: string;

Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075

Inherited from
Error.message
name
name: string;

Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074

Inherited from
Error.name
stack?
optional stack?: string;

Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076

Inherited from
Error.stack
stage
readonly stage: string;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:271

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
Error.stackTraceLimit

Methods

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
Error.captureStackTrace
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
Error.prepareStackTrace

GeminiCliAdapter

Defined in: packages/nexus-agents/src/cli-adapters/adapters/gemini-adapter.ts:107

CLI Adapters exports - CLI integration with defensive parsing Split from index.ts for file size compliance (Issue #285)

Extends

Constructors

Constructor
new GeminiCliAdapter(options?): GeminiCliAdapter;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/gemini-adapter.ts:129

Parameters
options?

GeminiConfig

Returns

GeminiCliAdapter

Overrides

SubprocessCliAdapter.constructor

Properties

cachedVersion?
protected optional cachedVersion?: string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:103

Inherited from

SubprocessCliAdapter.cachedVersion

cachedVersionAt?
protected optional cachedVersionAt?: number;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:111

Epoch ms at which cachedVersion was read off the binary.

The cache never expires, so this is what lets healthCheck say whether its reachable rests on a probe that just ran or on one from minutes ago (#5864).

Inherited from

SubprocessCliAdapter.cachedVersionAt

capacityTracker
protected capacityTracker: CapacityTracker | null = null;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:101

Inherited from

SubprocessCliAdapter.capacityTracker

enforcesReadOnlyAnalysis
readonly enforcesReadOnlyAnalysis: true = true;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/gemini-adapter.ts:109

Whether this adapter maps accessMode: 'read-only-analysis' to its CLI’s own enforcement (#6754). False here so a new adapter fails closed until it implements the mode and says so.

Overrides

SubprocessCliAdapter.enforcesReadOnlyAnalysis

enforcesWorkspaceEdit
readonly enforcesWorkspaceEdit: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:98

Whether this adapter maps accessMode: 'workspace-edit' to its CLI’s own enforcement (#6792). False here for the same reason: a new adapter fails closed until it implements the mode and says so.

Inherited from

SubprocessCliAdapter.enforcesWorkspaceEdit

initialized
protected initialized: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:102

Inherited from

SubprocessCliAdapter.initialized

logger
protected readonly logger: ILogger;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:100

Inherited from

SubprocessCliAdapter.logger

name
readonly name: "claude" | "gemini" | "codex" | "opencode" = 'gemini';

Defined in: packages/nexus-agents/src/cli-adapters/adapters/gemini-adapter.ts:108

CLI name

Overrides

SubprocessCliAdapter.name

parser
protected readonly parser: ICliResponseParser;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/gemini-adapter.ts:120

Overrides

SubprocessCliAdapter.parser

transientRetry
protected readonly transientRetry: TransientRetryConfig;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:336

Transient-error retry config. Override in subclass to enable.

Inherited from

SubprocessCliAdapter.transientRetry

transport
readonly transport: CliTransport = 'subprocess';

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:331

Transport type

Inherited from

SubprocessCliAdapter.transport

Accessors

binaryName
Get Signature
get binaryName(): string;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/gemini-adapter.ts:117

#4346: the arm is still called gemini (it serves Google’s Gemini models and keeps the routing/LinUCB identity), but the executable is agy. The standalone gemini CLI is EOL — it exits 55 with IneligibleTierError on every invocation.

Returns

string

Overrides

SubprocessCliAdapter.binaryName

capabilities
Get Signature
get capabilities(): CliCapabilityProfile;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:128

Gets the capability profile for this CLI.

Returns

CliCapabilityProfile

Capability profile

Inherited from

SubprocessCliAdapter.capabilities

Methods

accessModeRefusal()
protected accessModeRefusal(task): CliError | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:198

The refusal for a task this adapter cannot run in its requested access mode, or undefined (#6754). Adapters override it to add conflicts their own options can create, and call super first.

Parameters
task

CliTask

Returns

CliError | undefined

Inherited from

SubprocessCliAdapter.accessModeRefusal

checkVersionCompatibility()
protected checkVersionCompatibility(version): VersionStatus;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:407

Checks version compatibility.

Parameters
version

string

Returns

VersionStatus

Inherited from

SubprocessCliAdapter.checkVersionCompatibility

createError()
protected createError(
   code, 
   message, 
   cause?
): CliError;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:454

Creates a CLI error.

Parameters
code

CliErrorCode

message

string

cause?

Error

Returns

CliError

Inherited from

SubprocessCliAdapter.createError

delay()
protected delay(ms): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:480

Delays for the specified milliseconds.

Parameters
ms

number

Returns

Promise<void>

Inherited from

SubprocessCliAdapter.delay

dispose()
dispose(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:927

Disposes the adapter (no-op for subprocess).

Returns

Promise<void>

Inherited from

SubprocessCliAdapter.dispose

execute()
execute(task, options?): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/gemini-adapter.ts:193

Executes a task with reliability features.

Parameters
task

CliTask

options?

CliExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

Overrides

SubprocessCliAdapter.execute

executeTask()
executeTask(task, options): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:416

Executes a task via subprocess, with optional transient-error retry. When transientRetry.enabled is true, transient errors (timeout, rate_limit, connection, parse) are retried with exponential backoff (500ms, 1000ms). Parse errors get max 1 retry (#1533); others get 2.

Parameters
task

CliTask

options

ResolvedExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

Inherited from

SubprocessCliAdapter.executeTask

executeWithMetadata()
executeWithMetadata(task, options?): Promise<Result<GeminiExecutionResult, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/gemini-adapter.ts:210

Executes with full metadata about retry attempts and circuit state.

Parameters
task

CliTask

options?

CliExecutionOptions

Returns

Promise<Result<GeminiExecutionResult, CliError>>

getCapacity()
getCapacity(): Promise<CapacityStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:361

Gets current capacity status based on tracked usage. Uses usage-based tracking since CLI subprocess execution doesn’t expose HTTP rate limit headers.

Returns

Promise<CapacityStatus>

See

Issue #456 - Real API rate limit tracking

Inherited from

SubprocessCliAdapter.getCapacity

getCircuitBreakerSnapshot()
getCircuitBreakerSnapshot(): CircuitBreakerSnapshot | null;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/gemini-adapter.ts:235

Gets current circuit breaker snapshot.

Returns

CircuitBreakerSnapshot | null

getCommand()
protected getCommand(task): CommandConfig;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/gemini-adapter.ts:249

Gets CLI command and arguments for execution.

Parameters
task

CliTask

Returns

CommandConfig

Overrides

SubprocessCliAdapter.getCommand

getModelInfo()
getModelInfo(): CliModelInfo;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/gemini-adapter.ts:172

Gets Gemini model information. Resolves from canonical registry when possible, falls back to legacy lookup. Note: maxOutput is capped at 8_192 (Gemini CLI constraint).

Returns

CliModelInfo

Overrides

SubprocessCliAdapter.getModelInfo

getVersion()
getVersion(): Promise<string>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:334

Gets CLI version.

Returns

Promise<string>

Inherited from

SubprocessCliAdapter.getVersion

getVersionMessage()
protected getVersionMessage(status, version): string | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:436

Gets version status message.

Parameters
status

VersionStatus

version

string

Returns

string | undefined

Inherited from

SubprocessCliAdapter.getVersionMessage

handleSubprocessOutput()
protected handleSubprocessOutput(
   stdout, 
   stderr, 
   startTime
): Result<CliResponse, CliError>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:757

Handles successful subprocess output.

Parameters
stdout

string

stderr

string

startTime

number

Returns

Result<CliResponse, CliError>

Inherited from

SubprocessCliAdapter.handleSubprocessOutput

healthCheck()
healthCheck(): Promise<HealthStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:297

Performs a health check.

Returns

Promise<HealthStatus>

Inherited from

SubprocessCliAdapter.healthCheck

initCapacityTracker()
protected initCapacityTracker(): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:121

Initializes the capacity tracker. Called by subclasses after name is set.

Returns

void

Inherited from

SubprocessCliAdapter.initCapacityTracker

initialize()
initialize(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:918

Initializes the adapter and capacity tracker.

Returns

Promise<void>

Inherited from

SubprocessCliAdapter.initialize

listModels()
listModels(): Promise<readonly CliModelInfo[]>;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/gemini-adapter.ts:163

The slugs this arm can actually run (#5085).

NOT listModelsForCli('gemini'), which resolves the models.dev google vendor — 82 Google API ids like gemini-2.5-flash. This arm spawns agy, which accepts none of them; the same reasoning already documented for cliModelName in config/agy-model-map.ts applies to enumeration. Reporting the API list made every consumer confidently wrong rather than empty, which is worse.

Returns

Promise<readonly CliModelInfo[]>

normalizeResponse()
protected normalizeResponse(
   text, 
   usage?, 
   extra?
): CliResponse;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:465

Normalizes CLI response to common format.

Parameters
text

string

usage?

CliTokenUsage

extra?

Partial<CliResponse>

Returns

CliResponse

Inherited from

SubprocessCliAdapter.normalizeResponse

parseVersion()
protected parseVersion(output): string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:395

Parses version from CLI output.

Parameters
output

string

Returns

string

Inherited from

SubprocessCliAdapter.parseVersion

recordQuotaSignal()
protected recordQuotaSignal(error): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:281

Feed a provider’s own rate-limit assertion into capacity tracking (#4456).

A retry-after the provider stated is far stronger evidence than local counting: the tracker otherwise sees only this process’s spend and cannot observe a plan quota burned gradually or burned elsewhere, which is the incident #4351 reported. Only RATE_LIMITED carries that assertion; the tracker itself decides whether the stated wait is long enough to mean durable quota rather than a per-minute throttle.

Parameters
error

CliError

Returns

void

Inherited from

SubprocessCliAdapter.recordQuotaSignal

recordUsage()
protected recordUsage(response): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:386

Records usage from a response for capacity tracking.

Parameters
response

CliResponse

Returns

void

Inherited from

SubprocessCliAdapter.recordUsage

resetCircuitBreaker()
resetCircuitBreaker(): void;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/gemini-adapter.ts:242

Resets the circuit breaker to closed state.

Returns

void

shouldOuterRetry()
protected shouldOuterRetry(opts): boolean;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:347

The inner retryTransient layer is the single retry authority for subprocess CLIs. When it is enabled (the default), the shared outer retry loop must not also retry: nesting both meant up to 6 subprocess spawns and ~10-minute hangs on a persistent TIMEOUT, since the inner layer’s timeout extension compounds on every outer attempt (#2824). The outer loop still runs once, so circuit-breaker failure recording is unaffected.

Parameters
opts

ResolvedExecutionOptions

Returns

boolean

Inherited from

SubprocessCliAdapter.shouldOuterRetry


GeminiResponseParser

Defined in: packages/nexus-agents/src/cli-adapters/parsers/gemini-parser.ts:51

Parser for Gemini CLI JSON output. Implements defensive parsing - only requires essential fields.

Implements

Constructors

Constructor
new GeminiResponseParser(): GeminiResponseParser;
Returns

GeminiResponseParser

Properties

name
readonly name: "gemini-parser" = 'gemini-parser';

Defined in: packages/nexus-agents/src/cli-adapters/parsers/gemini-parser.ts:52

Parser name (for logging)

Implementation of

ICliResponseParser.name

supportedVersionRange
readonly supportedVersionRange: ">=0.20.0 <1.0.0" = '>=0.20.0 <1.0.0';

Defined in: packages/nexus-agents/src/cli-adapters/parsers/gemini-parser.ts:53

Supported version range (semver)

Implementation of

ICliResponseParser.supportedVersionRange

Methods

extractResponse()
extractResponse(raw): string | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/gemini-parser.ts:76

Extracts just the response text (most stable field).

Parameters
raw

string

Returns

string | null

Implementation of

ICliResponseParser.extractResponse

extractSessionId()
extractSessionId(raw): string | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/gemini-parser.ts:156

Extracts session ID for resumption.

Parameters
raw

string

Returns

string | null

Implementation of

ICliResponseParser.extractSessionId

extractUsage()
extractUsage(raw): CliTokenUsage | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/gemini-parser.ts:98

Extracts token usage from response. Gemini has per-model stats, we aggregate them.

Parameters
raw

string

Returns

CliTokenUsage | null

Implementation of

ICliResponseParser.extractUsage

parse()
parse(raw): GeminiCliResponse | null;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/gemini-parser.ts:58

Parses complete Gemini CLI response.

Parameters
raw

string

Returns

GeminiCliResponse | null

Implementation of

ICliResponseParser.parse


InMemoryPreferenceStore

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-store.ts:21

In-memory preference data store implementation.

Implements

Constructors

Constructor
new InMemoryPreferenceStore(maxSize?): InMemoryPreferenceStore;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-store.ts:25

Parameters
maxSize?

number = 10000

Returns

InMemoryPreferenceStore

Methods

clear()
clear(): void;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-store.ts:84

Clear all data

Returns

void

Implementation of

IPreferenceDataStore.clear

findSimilar()
findSimilar(features, limit): readonly PreferenceDataPoint[];

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-store.ts:48

Find similar data points based on features

Parameters
features

QueryFeatures

limit

number

Returns

readonly PreferenceDataPoint[]

Implementation of

IPreferenceDataStore.findSimilar

getAll()
getAll(): readonly PreferenceDataPoint[];

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-store.ts:34

Get all data points

Returns

readonly PreferenceDataPoint[]

Implementation of

IPreferenceDataStore.getAll

getByDomain()
getByDomain(domain): readonly PreferenceDataPoint[];

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-store.ts:38

Get data points by domain

Parameters
domain

string

Returns

readonly PreferenceDataPoint[]

Implementation of

IPreferenceDataStore.getByDomain

getStats()
getStats(): PreferenceModelStats;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-store.ts:62

Get statistics

Returns

PreferenceModelStats

Implementation of

IPreferenceDataStore.getStats

store()
store(dataPoint): void;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-store.ts:29

Store a new preference data point

Parameters
dataPoint

PreferenceDataPoint

Returns

void

Implementation of

IPreferenceDataStore.store


OpenCodeCliAdapter

Defined in: packages/nexus-agents/src/cli-adapters/adapters/opencode-adapter.ts:204

CLI Adapters exports - CLI integration with defensive parsing Split from index.ts for file size compliance (Issue #285)

Extends

Constructors

Constructor
new OpenCodeCliAdapter(options?): OpenCodeCliAdapter;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/opencode-adapter.ts:215

Parameters
options?

BaseAdapterOptions

Returns

OpenCodeCliAdapter

Overrides

SubprocessCliAdapter.constructor

Properties

cachedVersion?
protected optional cachedVersion?: string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:103

Inherited from

SubprocessCliAdapter.cachedVersion

cachedVersionAt?
protected optional cachedVersionAt?: number;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:111

Epoch ms at which cachedVersion was read off the binary.

The cache never expires, so this is what lets healthCheck say whether its reachable rests on a probe that just ran or on one from minutes ago (#5864).

Inherited from

SubprocessCliAdapter.cachedVersionAt

capacityTracker
protected capacityTracker: CapacityTracker | null = null;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:101

Inherited from

SubprocessCliAdapter.capacityTracker

enforcesReadOnlyAnalysis
readonly enforcesReadOnlyAnalysis: true = true;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/opencode-adapter.ts:206

Whether this adapter maps accessMode: 'read-only-analysis' to its CLI’s own enforcement (#6754). False here so a new adapter fails closed until it implements the mode and says so.

Overrides

SubprocessCliAdapter.enforcesReadOnlyAnalysis

enforcesWorkspaceEdit
readonly enforcesWorkspaceEdit: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:98

Whether this adapter maps accessMode: 'workspace-edit' to its CLI’s own enforcement (#6792). False here for the same reason: a new adapter fails closed until it implements the mode and says so.

Inherited from

SubprocessCliAdapter.enforcesWorkspaceEdit

initialized
protected initialized: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:102

Inherited from

SubprocessCliAdapter.initialized

logger
protected readonly logger: ILogger;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:100

Inherited from

SubprocessCliAdapter.logger

name
readonly name: "claude" | "gemini" | "codex" | "opencode" = 'opencode';

Defined in: packages/nexus-agents/src/cli-adapters/adapters/opencode-adapter.ts:205

CLI name

Overrides

SubprocessCliAdapter.name

parser
protected readonly parser: ICliResponseParser;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/opencode-adapter.ts:207

Overrides

SubprocessCliAdapter.parser

transientRetry
protected readonly transientRetry: TransientRetryConfig;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/opencode-adapter.ts:210

Enable transient-error retry for OpenCode (#1456).

Overrides

SubprocessCliAdapter.transientRetry

transport
readonly transport: CliTransport = 'subprocess';

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:331

Transport type

Inherited from

SubprocessCliAdapter.transport

Accessors

binaryName
Get Signature
get binaryName(): string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:82

The executable this adapter actually runs.

Defaults to name because for most arms the routing identity and the binary are the same word. They are NOT always the same: the gemini arm runs agy (Antigravity) after Google retired the standalone gemini CLI (#4346). Conflating the two is how that arm ended up executing agy for work while shelling gemini --version for its health check — reporting the dead binary’s version against the live one’s floor, and failing its own availability gate while working perfectly.

Returns

string

Inherited from

SubprocessCliAdapter.binaryName

capabilities
Get Signature
get capabilities(): CliCapabilityProfile;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:128

Gets the capability profile for this CLI.

Returns

CliCapabilityProfile

Capability profile

Inherited from

SubprocessCliAdapter.capabilities

Methods

accessModeRefusal()
protected accessModeRefusal(task): CliError | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:198

The refusal for a task this adapter cannot run in its requested access mode, or undefined (#6754). Adapters override it to add conflicts their own options can create, and call super first.

Parameters
task

CliTask

Returns

CliError | undefined

Inherited from

SubprocessCliAdapter.accessModeRefusal

checkVersionCompatibility()
protected checkVersionCompatibility(version): VersionStatus;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:407

Checks version compatibility.

Parameters
version

string

Returns

VersionStatus

Inherited from

SubprocessCliAdapter.checkVersionCompatibility

createError()
protected createError(
   code, 
   message, 
   cause?
): CliError;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:454

Creates a CLI error.

Parameters
code

CliErrorCode

message

string

cause?

Error

Returns

CliError

Inherited from

SubprocessCliAdapter.createError

delay()
protected delay(ms): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:480

Delays for the specified milliseconds.

Parameters
ms

number

Returns

Promise<void>

Inherited from

SubprocessCliAdapter.delay

dispose()
dispose(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:927

Disposes the adapter (no-op for subprocess).

Returns

Promise<void>

Inherited from

SubprocessCliAdapter.dispose

execute()
execute(task, options?): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/opencode-adapter.ts:317

#6599: an explicitly requested model is resolved to an opencode id before the run, and the response reports the model that ran so cost and outcome attribution price it rather than the adapter default. With no requested model the path is unchanged.

Parameters
task

CliTask

options?

CliExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

Overrides

SubprocessCliAdapter.execute

executeTask()
executeTask(task, options): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/opencode-adapter.ts:357

#3408: mark a model in rate-limit cooldown when a call returns RATE_LIMITED, so subsequent selections skip it until the AvailabilityCache TTL recovers. Wraps the base executeTask; opt-in + fail-open (no-op when discovery is off). An explicitly requested model in cooldown is refused by execute() (#6599).

Parameters
task

CliTask

options

ResolvedExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

Overrides

SubprocessCliAdapter.executeTask

getCapacity()
getCapacity(): Promise<CapacityStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:361

Gets current capacity status based on tracked usage. Uses usage-based tracking since CLI subprocess execution doesn’t expose HTTP rate limit headers.

Returns

Promise<CapacityStatus>

See

Issue #456 - Real API rate limit tracking

Inherited from

SubprocessCliAdapter.getCapacity

getCommand()
protected getCommand(task): CommandConfig;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/opencode-adapter.ts:390

Gets CLI command and arguments for execution. Uses opencode run with JSON format for stable parsing. Omits –model when the adapter default isn’t available (#1402).

Parameters
task

CliTask

Returns

CommandConfig

Overrides

SubprocessCliAdapter.getCommand

getModelInfo()
getModelInfo(): CliModelInfo;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/opencode-adapter.ts:223

Gets OpenCode model information from canonical registry.

Returns

CliModelInfo

Overrides

SubprocessCliAdapter.getModelInfo

getVersion()
getVersion(): Promise<string>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:334

Gets CLI version.

Returns

Promise<string>

Inherited from

SubprocessCliAdapter.getVersion

getVersionMessage()
protected getVersionMessage(status, version): string | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:436

Gets version status message.

Parameters
status

VersionStatus

version

string

Returns

string | undefined

Inherited from

SubprocessCliAdapter.getVersionMessage

handleSubprocessOutput()
protected handleSubprocessOutput(
   stdout, 
   stderr, 
   startTime
): Result<CliResponse, CliError>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:757

Handles successful subprocess output.

Parameters
stdout

string

stderr

string

startTime

number

Returns

Result<CliResponse, CliError>

Inherited from

SubprocessCliAdapter.handleSubprocessOutput

healthCheck()
healthCheck(): Promise<HealthStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:297

Performs a health check.

Returns

Promise<HealthStatus>

Inherited from

SubprocessCliAdapter.healthCheck

initCapacityTracker()
protected initCapacityTracker(): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:121

Initializes the capacity tracker. Called by subclasses after name is set.

Returns

void

Inherited from

SubprocessCliAdapter.initCapacityTracker

initialize()
initialize(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/opencode-adapter.ts:242

Initializes the adapter — probes available models. Warns if Anthropic provider is configured (#1429 — API key boundaries).

Returns

Promise<void>

Overrides

SubprocessCliAdapter.initialize

listModels()
listModels(): Promise<readonly CliModelInfo[]>;

Defined in: packages/nexus-agents/src/cli-adapters/adapters/opencode-adapter.ts:417

(#2540) Lists models the local OpenCode installation can route to. Wraps the existing probeAvailableModels() (cached for the process lifetime — see cachedModels at the top of this file) and reshapes the result into the CliModelInfo schema. Splits provider/model ids when present.

Returns

Promise<readonly CliModelInfo[]>

normalizeResponse()
protected normalizeResponse(
   text, 
   usage?, 
   extra?
): CliResponse;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:465

Normalizes CLI response to common format.

Parameters
text

string

usage?

CliTokenUsage

extra?

Partial<CliResponse>

Returns

CliResponse

Inherited from

SubprocessCliAdapter.normalizeResponse

parseVersion()
protected parseVersion(output): string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:395

Parses version from CLI output.

Parameters
output

string

Returns

string

Inherited from

SubprocessCliAdapter.parseVersion

recordQuotaSignal()
protected recordQuotaSignal(error): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:281

Feed a provider’s own rate-limit assertion into capacity tracking (#4456).

A retry-after the provider stated is far stronger evidence than local counting: the tracker otherwise sees only this process’s spend and cannot observe a plan quota burned gradually or burned elsewhere, which is the incident #4351 reported. Only RATE_LIMITED carries that assertion; the tracker itself decides whether the stated wait is long enough to mean durable quota rather than a per-minute throttle.

Parameters
error

CliError

Returns

void

Inherited from

SubprocessCliAdapter.recordQuotaSignal

recordUsage()
protected recordUsage(response): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:386

Records usage from a response for capacity tracking.

Parameters
response

CliResponse

Returns

void

Inherited from

SubprocessCliAdapter.recordUsage

shouldOuterRetry()
protected shouldOuterRetry(opts): boolean;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:347

The inner retryTransient layer is the single retry authority for subprocess CLIs. When it is enabled (the default), the shared outer retry loop must not also retry: nesting both meant up to 6 subprocess spawns and ~10-minute hangs on a persistent TIMEOUT, since the inner layer’s timeout extension compounds on every outer attempt (#2824). The outer loop still runs once, so circuit-breaker failure recording is unaffected.

Parameters
opts

ResolvedExecutionOptions

Returns

boolean

Inherited from

SubprocessCliAdapter.shouldOuterRetry


PreferenceRouter

Defined in: packages/nexus-agents/src/cli-adapters/preference-router.ts:48

Preference-trained router that learns from human preference data.

Constructors

Constructor
new PreferenceRouter(config?, dataStore?): PreferenceRouter;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router.ts:53

Parameters
config?

Partial<PreferenceRouterConfig> = {}

dataStore?

IPreferenceDataStore

Returns

PreferenceRouter

Methods

getStats()
getStats(): PreferenceModelStats;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router.ts:140

Get statistics about the learned preference model.

Returns

PreferenceModelStats

hasMinimumData()
hasMinimumData(): boolean;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router.ts:147

Check if the router has enough data to make informed decisions.

Returns

boolean

recordPreference()
recordPreference(
   query, 
   strongModelPreferred, 
   strongModelQuality?, 
   weakModelQuality?
): PreferenceDataPoint;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router.ts:107

Record a preference data point for online learning.

Parameters
query

string

strongModelPreferred

boolean

strongModelQuality?

number

weakModelQuality?

number

Returns

PreferenceDataPoint

route()
route(query): PreferenceRoutingDecision;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router.ts:72

Route a query to the optimal model based on learned preferences.

Parameters
query

string

Returns

PreferenceRoutingDecision


QueryFeatureExtractor

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-extractor.ts:80

Feature extractor for queries.

Constructors

Constructor
new QueryFeatureExtractor(): QueryFeatureExtractor;
Returns

QueryFeatureExtractor

Methods

extract()
extract(query): QueryFeatures;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-extractor.ts:81

Parameters
query

string

Returns

QueryFeatures


RoutingMemoryError

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:34

CLI Adapters exports - CLI integration with defensive parsing Split from index.ts for file size compliance (Issue #285)

Extends

  • Error

Constructors

Constructor
new RoutingMemoryError(
   message, 
   code?, 
   cause?
): RoutingMemoryError;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:37

Parameters
message

string

code?

RoutingMemoryErrorCode = 'STORAGE_FAILED'

cause?

unknown

Returns

RoutingMemoryError

Overrides
Error.constructor

Properties

cause?
readonly optional cause?: unknown;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:40

Inherited from
Error.cause
code
readonly code: RoutingMemoryErrorCode;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:35

message
message: string;

Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075

Inherited from
Error.message
name
name: string;

Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074

Inherited from
Error.name
stack?
optional stack?: string;

Defined in: node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076

Inherited from
Error.stack
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
Error.stackTraceLimit

Methods

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
Error.captureStackTrace
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
Error.prepareStackTrace

abstract SubprocessCliAdapter

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:330

Base class for subprocess-based CLI adapters. Used by ClaudeCliAdapter and GeminiCliAdapter.

Extends

Extended by

Constructors

Constructor
new SubprocessCliAdapter(logger?): SubprocessCliAdapter;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:113

Parameters
logger?

ILogger

Returns

SubprocessCliAdapter

Inherited from

BaseCliAdapter.constructor

Properties

cachedVersion?
protected optional cachedVersion?: string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:103

Inherited from

BaseCliAdapter.cachedVersion

cachedVersionAt?
protected optional cachedVersionAt?: number;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:111

Epoch ms at which cachedVersion was read off the binary.

The cache never expires, so this is what lets healthCheck say whether its reachable rests on a probe that just ran or on one from minutes ago (#5864).

Inherited from

BaseCliAdapter.cachedVersionAt

capacityTracker
protected capacityTracker: CapacityTracker | null = null;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:101

Inherited from

BaseCliAdapter.capacityTracker

enforcesReadOnlyAnalysis
readonly enforcesReadOnlyAnalysis: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:91

Whether this adapter maps accessMode: 'read-only-analysis' to its CLI’s own enforcement (#6754). False here so a new adapter fails closed until it implements the mode and says so.

Inherited from

BaseCliAdapter.enforcesReadOnlyAnalysis

enforcesWorkspaceEdit
readonly enforcesWorkspaceEdit: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:98

Whether this adapter maps accessMode: 'workspace-edit' to its CLI’s own enforcement (#6792). False here for the same reason: a new adapter fails closed until it implements the mode and says so.

Inherited from

BaseCliAdapter.enforcesWorkspaceEdit

initialized
protected initialized: boolean = false;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:102

Inherited from

BaseCliAdapter.initialized

logger
protected readonly logger: ILogger;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:100

Inherited from

BaseCliAdapter.logger

name
abstract readonly name: "claude" | "gemini" | "codex" | "opencode";

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:68

CLI name

Inherited from

BaseCliAdapter.name

parser
abstract protected readonly parser: ICliResponseParser;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:333

transientRetry
protected readonly transientRetry: TransientRetryConfig;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:336

Transient-error retry config. Override in subclass to enable.

transport
readonly transport: CliTransport = 'subprocess';

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:331

Transport type

Overrides

BaseCliAdapter.transport

Accessors

binaryName
Get Signature
get binaryName(): string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:82

The executable this adapter actually runs.

Defaults to name because for most arms the routing identity and the binary are the same word. They are NOT always the same: the gemini arm runs agy (Antigravity) after Google retired the standalone gemini CLI (#4346). Conflating the two is how that arm ended up executing agy for work while shelling gemini --version for its health check — reporting the dead binary’s version against the live one’s floor, and failing its own availability gate while working perfectly.

Returns

string

Inherited from

BaseCliAdapter.binaryName

capabilities
Get Signature
get capabilities(): CliCapabilityProfile;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:128

Gets the capability profile for this CLI.

Returns

CliCapabilityProfile

Capability profile

Inherited from

BaseCliAdapter.capabilities

Methods

accessModeRefusal()
protected accessModeRefusal(task): CliError | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:198

The refusal for a task this adapter cannot run in its requested access mode, or undefined (#6754). Adapters override it to add conflicts their own options can create, and call super first.

Parameters
task

CliTask

Returns

CliError | undefined

Inherited from

BaseCliAdapter.accessModeRefusal

checkVersionCompatibility()
protected checkVersionCompatibility(version): VersionStatus;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:407

Checks version compatibility.

Parameters
version

string

Returns

VersionStatus

Inherited from

BaseCliAdapter.checkVersionCompatibility

createError()
protected createError(
   code, 
   message, 
   cause?
): CliError;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:454

Creates a CLI error.

Parameters
code

CliErrorCode

message

string

cause?

Error

Returns

CliError

Inherited from

BaseCliAdapter.createError

delay()
protected delay(ms): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:480

Delays for the specified milliseconds.

Parameters
ms

number

Returns

Promise<void>

Inherited from

BaseCliAdapter.delay

dispose()
dispose(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:927

Disposes the adapter (no-op for subprocess).

Returns

Promise<void>

Overrides

BaseCliAdapter.dispose

execute()
execute(task, options?): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:167

Executes a task with error handling and retries.

Timeout priority (highest to lowest):

  1. options.timeoutMs - explicit execution option
  2. task.timeoutMs - task-level setting
  3. getTimeoutForTaskAuto() - computed from task complexity and CLI
Parameters
task

CliTask

options?

CliExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

Inherited from

BaseCliAdapter.execute

executeTask()
executeTask(task, options): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:416

Executes a task via subprocess, with optional transient-error retry. When transientRetry.enabled is true, transient errors (timeout, rate_limit, connection, parse) are retried with exponential backoff (500ms, 1000ms). Parse errors get max 1 retry (#1533); others get 2.

Parameters
task

CliTask

options

ResolvedExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

Overrides

BaseCliAdapter.executeTask

getCapacity()
getCapacity(): Promise<CapacityStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:361

Gets current capacity status based on tracked usage. Uses usage-based tracking since CLI subprocess execution doesn’t expose HTTP rate limit headers.

Returns

Promise<CapacityStatus>

See

Issue #456 - Real API rate limit tracking

Inherited from

BaseCliAdapter.getCapacity

getCommand()
abstract protected getCommand(task): CommandConfig;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:355

Gets CLI command and arguments for execution. If stdin is provided, it will be written to the process stdin.

Parameters
task

CliTask

Returns

CommandConfig

getModelInfo()
abstract getModelInfo(): CliModelInfo;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:145

Abstract method for getting model info. Implemented by concrete adapters.

Returns

CliModelInfo

Inherited from

BaseCliAdapter.getModelInfo

getVersion()
getVersion(): Promise<string>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:334

Gets CLI version.

Returns

Promise<string>

Inherited from

BaseCliAdapter.getVersion

getVersionMessage()
protected getVersionMessage(status, version): string | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:436

Gets version status message.

Parameters
status

VersionStatus

version

string

Returns

string | undefined

Inherited from

BaseCliAdapter.getVersionMessage

handleSubprocessOutput()
protected handleSubprocessOutput(
   stdout, 
   stderr, 
   startTime
): Result<CliResponse, CliError>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:757

Handles successful subprocess output.

Parameters
stdout

string

stderr

string

startTime

number

Returns

Result<CliResponse, CliError>

healthCheck()
healthCheck(): Promise<HealthStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:297

Performs a health check.

Returns

Promise<HealthStatus>

Inherited from

BaseCliAdapter.healthCheck

initCapacityTracker()
protected initCapacityTracker(): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:121

Initializes the capacity tracker. Called by subclasses after name is set.

Returns

void

Inherited from

BaseCliAdapter.initCapacityTracker

initialize()
initialize(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:918

Initializes the adapter and capacity tracker.

Returns

Promise<void>

Overrides

BaseCliAdapter.initialize

normalizeResponse()
protected normalizeResponse(
   text, 
   usage?, 
   extra?
): CliResponse;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:465

Normalizes CLI response to common format.

Parameters
text

string

usage?

CliTokenUsage

extra?

Partial<CliResponse>

Returns

CliResponse

Inherited from

BaseCliAdapter.normalizeResponse

parseVersion()
protected parseVersion(output): string;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:395

Parses version from CLI output.

Parameters
output

string

Returns

string

Inherited from

BaseCliAdapter.parseVersion

recordQuotaSignal()
protected recordQuotaSignal(error): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:281

Feed a provider’s own rate-limit assertion into capacity tracking (#4456).

A retry-after the provider stated is far stronger evidence than local counting: the tracker otherwise sees only this process’s spend and cannot observe a plan quota burned gradually or burned elsewhere, which is the incident #4351 reported. Only RATE_LIMITED carries that assertion; the tracker itself decides whether the stated wait is long enough to mean durable quota rather than a per-minute throttle.

Parameters
error

CliError

Returns

void

Inherited from

BaseCliAdapter.recordQuotaSignal

recordUsage()
protected recordUsage(response): void;

Defined in: packages/nexus-agents/src/cli-adapters/base-adapter.ts:386

Records usage from a response for capacity tracking.

Parameters
response

CliResponse

Returns

void

Inherited from

BaseCliAdapter.recordUsage

shouldOuterRetry()
protected shouldOuterRetry(opts): boolean;

Defined in: packages/nexus-agents/src/cli-adapters/subprocess-adapter.ts:347

The inner retryTransient layer is the single retry authority for subprocess CLIs. When it is enabled (the default), the shared outer retry loop must not also retry: nesting both meant up to 6 subprocess spawns and ~10-minute hangs on a persistent TIMEOUT, since the inner layer’s timeout extension compounds on every outer attempt (#2824). The outer loop still runs once, so circuit-breaker failure recording is unaffected.

Parameters
opts

ResolvedExecutionOptions

Returns

boolean

Overrides

BaseCliAdapter.shouldOuterRetry

Interfaces

ActionRecord

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:205

Action record for caching successful patterns.

Properties

avgDurationMs
readonly avgDurationMs: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:217

Average duration in milliseconds

id
readonly id: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:207

Unique action ID

lastUsed
readonly lastUsed: Date;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:219

Last time this action was used

pattern
readonly pattern: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:211

Pattern description

successRate
readonly successRate: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:215

Success rate (0-1)

taskType
readonly taskType: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:209

Task type this action applies to

usageCount
readonly usageCount: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:213

Number of times this action was used


BaseAdapterOptions

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:43

Base adapter constructor options shared by all CLI adapters. CLI-specific adapters extend this with additional fields.

Properties

logger?
readonly optional logger?: ILogger;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:47

Custom logger instance

model?
readonly optional model?: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:45

Model to use (defaults to the CLI’s default from the canonical registry)


CapacityStatus

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:407

Capacity status for rate limiting.

Properties

exhausted
readonly exhausted: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:436

Deprecated

Since #4456 — renamed to rateLimited, which says what it actually measures. The name exhausted promised an account/plan capacity signal while reporting a 60-second local rate heuristic, so every reader inherited a claim the value could not support. Identical value; scheduled for removal in the next major.

observed
readonly observed: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:472

Whether this process has observed any usage of the adapter (#4374).

When false, every other field is a default, not a measurement: a tracker that has never recorded a request reports the full token limit remaining and 0% utilization, which is indistinguishable from a genuinely idle adapter. Consumers must not present an unobserved reading as health.

Note the narrower guarantee even when true: the tracker sees only THIS process’s spend. It has no visibility into a provider-side weekly quota consumed elsewhere, so remainingTokens is a local upper bound on what is left, never an authoritative one.

quotaExhausted
readonly quotaExhausted: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:450

Whether a PROVIDER asserted that durable quota is gone (#4456).

Set only from provider-asserted evidence — a rate-limit error whose retry-after exceeds the local window, which is the provider itself saying the wait is longer than a per-minute throttle. Never inferred from local counting.

false means “no provider has asserted exhaustion to THIS process”. It is NOT a measurement that quota remains: a weekly quota burned by another process is invisible here. Read it with observed; absence of evidence must not be presented as capacity.

quotaResetAt?
readonly optional quotaResetAt?: Date;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:458

When the provider said the quota window clears, from retry-after.

Present only alongside quotaExhausted: true. Absent means the provider asserted exhaustion without a horizon, which is a weaker signal, not a shorter one.

rateLimited
readonly rateLimited: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:428

Whether this process’s rolling rate window is used up (#4456).

Local arithmetic only: this process’s own spend over the last RATE_LIMIT_WINDOW_MS, measured against a per-CLI constant the source calls a conservative estimate. It self-clears within the window, and an ordinary burst (a 7-voter panel, a subagent fan-out) sets it while plenty of provider quota remains.

This is a throttling hint, NOT evidence that the account is out of capacity. Do not exclude a candidate on it — see quotaExhausted.

remainingRequests
readonly remainingRequests: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:411

Remaining requests in current window

remainingTokens
readonly remainingTokens: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:409

Remaining tokens in current window

resetTime
readonly resetTime: Date;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:413

When the rate limit resets

utilizationPercent
readonly utilizationPercent: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:415

Current utilization percentage (0-100)


CircuitProtectedResult

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:51

Result of a circuit-protected execution with fallback info.

Properties

executedBy
readonly executedBy: "claude" | "gemini" | "codex" | "opencode";

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:53

fallbackAttempts?
readonly optional fallbackAttempts?: readonly ("claude" | "gemini" | "codex" | "opencode")[];

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:55

response
readonly response: CliResponse;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:52

usedFallback
readonly usedFallback: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:54


ClaudeCliResponse

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:21

Claude CLI response structure. (Source: CLI testing 2026-01-04)

Properties

duration_ms?
readonly optional duration_ms?: number;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:27

is_error
readonly is_error: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:24

modelUsage?
readonly optional modelUsage?: Record<string, {
  cacheCreationInputTokens?: number;
  cacheReadInputTokens?: number;
  contextWindow?: number;
  costUSD?: number;
  inputTokens: number;
  outputTokens: number;
}>;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:37

result
readonly result: string;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:28

session_id?
readonly optional session_id?: string;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:29

stop_reason?
readonly optional stop_reason?: string;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:26

Why generation stopped — end_turn on an answer, stop_sequence on the measured error envelope (#6120).

subtype?
readonly optional subtype?: "error" | "success";

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:23

total_cost_usd?
readonly optional total_cost_usd?: number;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:30

type
readonly type: "result";

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:22

usage?
readonly optional usage?: {
  cache_creation_input_tokens?: number;
  cache_read_input_tokens?: number;
  input_tokens: number;
  output_tokens: number;
};

Defined in: packages/nexus-agents/src/cli-adapters/parsers/claude-parser.ts:31

cache_creation_input_tokens?
readonly optional cache_creation_input_tokens?: number;
cache_read_input_tokens?
readonly optional cache_read_input_tokens?: number;
input_tokens
readonly input_tokens: number;
output_tokens
readonly output_tokens: number;

CliAdapterConfig

Defined in: packages/nexus-agents/src/cli-adapters/factory.ts:39

Configuration for creating a CLI adapter.

Properties

cli
readonly cli: "claude" | "gemini" | "codex" | "opencode";

Defined in: packages/nexus-agents/src/cli-adapters/factory.ts:41

Which CLI to use

logger?
readonly optional logger?: ILogger;

Defined in: packages/nexus-agents/src/cli-adapters/factory.ts:45

Optional logger

model?
readonly optional model?: string;

Defined in: packages/nexus-agents/src/cli-adapters/factory.ts:43

Optional model override

transport?
readonly optional transport?: CliTransport;

Defined in: packages/nexus-agents/src/cli-adapters/factory.ts:52

Transport for Codex: 'mcp' or 'subprocess'. Unset selects by probe (#6119): mcp when the installed codex serves mcp-server, otherwise subprocess (codex exec). An explicit 'mcp' on a codex without the subcommand throws CodexMcpServerUnavailableError at construction.


CliCacheStats

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:96

Cache statistics for observability.

Properties

hitRate
readonly hitRate: number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:104

Hit rate (0-1)

hits
readonly hits: number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:100

Cache hits since last reset

lastReset
readonly lastReset: Date;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:106

When stats were last reset

misses
readonly misses: number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:102

Cache misses since last reset

size
readonly size: number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:98

Number of cached entries


CliCapabilityProfile

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:54

Capability profile for task routing. (Source: cli-project_plan.md Capability Matching Matrix)

Properties

codeGeneration
readonly codeGeneration: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:60

Code generation quality (0-10)

contextWindow
readonly contextWindow: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:58

Maximum context window in tokens

cost
readonly cost: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:64

Cost efficiency (0-10, higher = cheaper)

reasoning
readonly reasoning: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:56

Complex reasoning ability (0-10)

speed
readonly speed: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:62

Response speed (0-10, higher = faster)


CliCircuitBreakerConfig

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:43

Configuration for CLI circuit breaker integration.

Properties

enableFallback?
readonly optional enableFallback?: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:46

fallbackChain?
readonly optional fallbackChain?: readonly ("claude" | "gemini" | "codex" | "opencode")[];

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:45

maxFallbackAttempts?
readonly optional maxFallbackAttempts?: number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:47

perCliConfig?
readonly optional perCliConfig?: Partial<Record<"claude" | "gemini" | "codex" | "opencode", Partial<CircuitBreakerConfig>>>;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:44


CliCircuitHealthStatus

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:59

Health status for all CLIs with circuit state.

Properties

clis
readonly clis: readonly {
  circuitState: "open" | "closed" | "half-open";
  failureCount: number;
  healthy: boolean;
  lastFailureTime: number | null;
  name: "claude" | "gemini" | "codex" | "opencode";
}[];

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:60

healthyCount
readonly healthyCount: number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:68

systemHealthy
readonly systemHealthy: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:67

timestamp
readonly timestamp: number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:69


CliDetectionCacheConfig

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:36

Configuration for the CLI detection cache.

Properties

adaptiveTtl?
readonly optional adaptiveTtl?: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:40

Enable adaptive TTL based on health history (default: true)

logger?
readonly optional logger?: ILogger;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:42

Logger instance

ttlMs
readonly ttlMs: number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:38

Base time-to-live in milliseconds (default: 5 minutes)


CliError

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:322

CLI execution error.

Properties

cause?
readonly optional cause?: Error;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:330

Underlying error (if any)

cli
readonly cli: "claude" | "gemini" | "codex" | "opencode";

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:328

CLI that produced the error

code
readonly code: CliErrorCode;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:324

Error code

message
readonly message: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:326

Human-readable message

retryable
readonly retryable: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:332

Whether the error is retryable

retryAfterMs?
readonly optional retryAfterMs?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:340

How long the provider asked us to wait before retrying, in milliseconds (#4373). Present only when the CLI’s own message stated one — parsed by parseRetryAfterMs. The retry loop prefers this over its computed exponential backoff, since a provider that names its window knows better than our guess.

routedArm?
readonly optional routedArm?: RoutingArmId;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:349

Routing arm id of the arm that ran and failed (#6552); see CliResponse.routedArm.

routedCli?
readonly optional routedCli?: "claude" | "gemini" | "codex" | "opencode";

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:347

CLI slot of the arm CompositeRouter.executeTask selected, when that arm ran and failed (#6521). Set only by the router, so a caller can record the failure against the arm it routed to. Absent when routing itself failed. The display slot; see CliResponse.routedArm for the arm id.

routedDurationMs?
readonly optional routedDurationMs?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:351

Wall time of the failed arm’s execute call alone, in ms (#6521).


CliExecutionOptions

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:106

Execution options for CLI adapters.

Properties

allowRetry?
readonly optional allowRetry?: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:110

Whether to allow retries

maxRetries?
readonly optional maxRetries?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:112

Maximum retry attempts

onProgress?
readonly optional onProgress?: () => void;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:116

Progress callback invoked on subprocess stdout activity (Issue #1087).

Returns

void

signal?
readonly optional signal?: AbortSignal;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:133

Cancellation signal (#3026 finding 2). When the signal aborts, the adapter must cancel the in-flight execution promptly — for subprocess adapters that means SIGTERM (with SIGKILL escalation per #3026 finding 1). Without this, callers that use Promise.race([adapter.execute(task), timeout]) for cancellation leak orphan subprocesses on race-loser: the timeout promise wins the race but the adapter call keeps running, posting late results into OutcomeStore + LinUCB state for a task whose decision has already been recorded.

Typed as AbortSignal | undefined (not AbortSignal?) so Required<ExecutionOptions> — used pervasively by adapter internals + tests as a resolved-options shape — keeps accepting signal: undefined under exactOptionalPropertyTypes.

timeoutMs?
readonly optional timeoutMs?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:108

Timeout in milliseconds

trackUsage?
readonly optional trackUsage?: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:114

Whether to track usage


CliHealthResult

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:20

Cached health result for a CLI.

Properties

checkedAt
readonly checkedAt: Date;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:28

When this result was captured

healthy
readonly healthy: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:22

Whether the CLI is healthy and available

message?
readonly optional message?: string;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:30

Optional status message

version
readonly version: string;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:24

CLI version detected

versionStatus
readonly versionStatus: VersionStatus;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:26

Version compatibility status


CliModelInfo

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:24

Model information from CLI.

Properties

contextWindow
readonly contextWindow: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:30

Maximum context window in tokens

costPerMillionInput?
readonly optional costPerMillionInput?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:34

Cost per 1M input tokens

costPerMillionOutput?
readonly optional costPerMillionOutput?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:36

Cost per 1M output tokens

id
readonly id: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:26

Model identifier

maxOutput?
readonly optional maxOutput?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:32

Maximum output tokens

name
readonly name: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:28

Model display name


CliResponse

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:216

Unified CLI response format. Normalized across all CLI output formats.

Properties

accessMode?
readonly optional accessMode?: ExecutionAccessMode;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:282

The access mode the adapter that served this call enforced (#6792), stamped by the adapter itself after it ran, so a caller records what was enforced rather than what was requested. Absent when the serving adapter does not report it.

costUsd?
readonly optional costUsd?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:224

Cost in USD (if available)

durationMs?
readonly optional durationMs?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:245

Duration in milliseconds

fallbackFrom?
readonly optional fallbackFrom?: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:243

The model the caller asked for, when the adapter answered with a different one from the same CLI family (#6120). Present only on a substituted response — the claude adapter sets it after an out-of-credits envelope for the requested model made it retry the next registry alias — so a record consumer (#6115) can say which model actually voted. Absent means the requested model answered.

gatewayArm?
readonly optional gatewayArm?: `api:${string}`;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:234

The gateway arm that served this response, when a gateway model answered it (#6624). Set by the model-to-CLI bridge from the model adapter’s gateway-arm marker. A telemetry writer prices the call by this arm’s NEXUS_GATEWAY_COST declaration, never by model’s list rate. Absent for a CLI subprocess or a direct vendor API.

model?
readonly optional model?: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:226

Model used for generation

permissionDenials?
readonly optional permissionDenials?: readonly CliPermissionDenial[];

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:294

Tool calls the CLI’s own permission layer refused during this call (#6792), when the CLI reports them (claude’s permission_denials). Absent when none were reported.

raw?
readonly optional raw?: unknown;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:267

Raw response (for debugging)

routedArm?
readonly optional routedArm?: RoutingArmId;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:260

Routing arm id of the arm the router ran (#6552): api:anthropic for the Anthropic API arm, claude for the claude CLI arm. Set only by the router, alongside routedCli. This is what a persisted outcome’s cli records, so warm start credits the arm that ran, not its slot.

routedCli?
readonly optional routedCli?: "claude" | "gemini" | "codex" | "opencode";

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:253

CLI slot of the arm CompositeRouter.executeTask selected and ran (#6521). Set only by the router, never by an adapter. CLI subprocess adapters report no model, so without this a caller cannot attribute a routed outcome. This is the DISPLAY slot: an api:anthropic run reads claude here. An outcome record wants routedArm.

routedDurationMs?
readonly optional routedDurationMs?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:265

Wall time of the routed arm’s execute call alone, in ms (#6521). Set only by CompositeRouter.executeTask; excludes routing and caller overhead.

sessionId?
readonly optional sessionId?: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:222

Session ID for resumption

stderr?
readonly optional stderr?: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:275

Stderr the transport captured during a SUCCESSFUL call, when non-empty (#6094). On the subprocess path this is the CLI’s stderr; on the codex MCP path it is what codex mcp-server wrote to its piped stderr while the tool call was in flight. A sandbox failure inside the CLI’s tool loop surfaces here while text still carries a parsed answer. Absent on a clean run.

text
readonly text: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:218

The response text

textOnly?
readonly optional textOnly?: true;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:288

True when the serving arm runs nothing on the host (#6792): a direct-API or gateway arm sends the task with no tools, so no file was read or edited, whatever the access mode allowed. Absent for a CLI arm.

usage?
readonly optional usage?: CliTokenUsage;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:220

Token usage statistics


CliRetryLoopConfig

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:36

CLI Adapters exports - CLI integration with defensive parsing Split from index.ts for file size compliance (Issue #285)

Properties

allowRetry
readonly allowRetry: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:38

baseDelayMs
readonly baseDelayMs: number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:39

circuitBreaker?
readonly optional circuitBreaker?: ICircuitBreaker | null;

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:41

cli
readonly cli: "claude" | "gemini" | "codex" | "opencode";

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:42

logger
readonly logger: ILogger;

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:43

maxDelayMs
readonly maxDelayMs: number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:40

maxRetries
readonly maxRetries: number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:37


CliRetryResult

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:46

CLI Adapters exports - CLI integration with defensive parsing Split from index.ts for file size compliance (Issue #285)

Properties

response
readonly response: CliResponse;

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:47

retryCount
readonly retryCount: number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:48


CliTask

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:70

Task to execute on a CLI.

Properties

accessMode?
readonly optional accessMode?: ExecutionAccessMode;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:90

Host access this task may use (#6754). Absent means 'default'. Under 'read-only-analysis' or 'workspace-edit' (#6792) an adapter must apply its CLI’s own enforcement of that mode, or refuse the task when it cannot.

content
readonly content: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:72

Task content/prompt

maxTokens?
readonly optional maxTokens?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:80

Maximum tokens to generate

model?
readonly optional model?: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:76

Preferred model (if any)

options?
readonly optional options?: Record<string, unknown>;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:84

Additional CLI-specific options

sessionId?
readonly optional sessionId?: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:78

Session ID for continuation

systemPrompt?
readonly optional systemPrompt?: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:74

Optional system prompt

timeoutMs?
readonly optional timeoutMs?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:82

Timeout in milliseconds


CliTokenUsage

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:184

Token usage information from CLI response — ONE call’s usage as the CLI parsers emit it.

This is deliberately a separate type from the adapter response contract’s TokenUsage in core/types/model.ts (#4440): here totalTokens is optional because not every CLI prints one, there it is required. The two cross only in the two adapter bridges, and every crossing goes through token-usage-bridge.ts so no field is narrowed silently.

Properties

cacheCreationInputTokens?
readonly optional cacheCreationInputTokens?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:198

Input tokens spent WRITING the cache, when the vendor reports them separately (#4435). Kept distinct from cachedInputTokens because they bill at opposite ends: cache writes are ~1.25x the uncached input rate, cache reads ~0.1x. Collapsing them would make correct pricing impossible.

cachedInputTokens?
readonly optional cachedInputTokens?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:190

Cached input tokens READ from an existing cache (if applicable).

inputTokens
readonly inputTokens: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:186

Input tokens consumed

inputTokensMeasured?
readonly optional inputTokensMeasured?: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:209

Whether inputTokens is a measurement (#4835); false means it is a placeholder 0 and totalTokens a lower bound. Absent means measured.

No CLI parser sets this. It exists so the model→CLI bridge (toCliTokenUsage, #4440) can carry a direct-API adapter’s flag instead of dropping it, which turned a placeholder count into a measured zero.

outputTokens
readonly outputTokens: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:188

Output tokens generated

totalTokens?
readonly optional totalTokens?: number;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:200

Total tokens (input + output)


CodexCliResponse

Defined in: packages/nexus-agents/src/cli-adapters/parsers/codex-parser.ts:68

Aggregated Codex response from NDJSON stream.

Properties

messages
readonly messages: readonly string[];

Defined in: packages/nexus-agents/src/cli-adapters/parsers/codex-parser.ts:70

reasoning
readonly reasoning: readonly string[];

Defined in: packages/nexus-agents/src/cli-adapters/parsers/codex-parser.ts:71

threadId?
readonly optional threadId?: string;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/codex-parser.ts:69

usage?
readonly optional usage?: CliTokenUsage;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/codex-parser.ts:72


CompositeRouterStats

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:283

Router statistics for observability.

Properties

avgDecisionTimeMs
readonly avgDecisionTimeMs: number;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:289

Average decision time in ms

banditStats
readonly banditStats: readonly {
  avgReward: number;
  name: string;
  pullCount: number;
}[];

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:315

LinUCB arm statistics

budgetRejectionRate
readonly budgetRejectionRate: number;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:291

Budget filter rejection rate

capacityStats?
readonly optional capacityStats?: {
  enforced: boolean;
  excludedCount: number;
};

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:299

Capacity filter statistics (#4658), present when the stage is enabled.

enforced is load-bearing: excludedCount can only be zero while enforcement is off, so reporting the count alone presents a default as a measurement. enforced: false says which of the two a zero is.

enforced
readonly enforced: boolean;
excludedCount
readonly excludedCount: number;
decisionsPerCli
readonly decisionsPerCli: Readonly<Record<CliName, number>>;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:287

Decisions per CLI

latencyStats?
readonly optional latencyStats?: LatencyTrackerStats;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:317

Latency tracking statistics (Issue #361)

preferenceStats?
readonly optional preferenceStats?: {
  dataPointCount: number;
  enabled: boolean;
  hasSufficientData: boolean;
  strongModelPreferenceRate: number;
};

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:304

Preference routing statistics

dataPointCount
readonly dataPointCount: number;

Total preference data points collected

enabled
readonly enabled: boolean;

Whether preference routing is enabled

hasSufficientData
readonly hasSufficientData: boolean;

Whether sufficient data for preference routing

strongModelPreferenceRate
readonly strongModelPreferenceRate: number;

Strong model preference rate

routingMemoryStats?
readonly optional routingMemoryStats?: RoutingMemoryStats;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:319

Routing memory statistics (Issue #463)

totalDecisions
readonly totalDecisions: number;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:285

Total routing decisions made


CompositeRoutingDecision

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:215

Routing decision with full explanation.

Properties

adapter
readonly adapter: ICliAdapter;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:217

Selected CLI adapter

alternatives
readonly alternatives: readonly RoutingArmId[];

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:251

Alternative adapters in ranked order

alternativeScores?
readonly optional alternativeScores?: ReadonlyMap<RoutingArmId, number>;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:262

Score per entry in alternatives (#5269).

ABSENT when no ranking produced per-arm scores — which is not the same as every alternative scoring zero. delegate_to_model previously had no per-alternative score available and filled the field with the WINNER’s topsisScore, so a caller saw three alternatives scoring alike and read them as equivalent to each other and to the selection. A reader must treat absence as “not ranked”, never as a measurement.

cliName
readonly cliName: RoutingArmId;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:219

Selected routing arm — a CLI slot or a distinct api:* arm (#3422).

confidence
readonly confidence: number;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:227

Overall confidence in decision (0-1)

decisionTimeMs
readonly decisionTimeMs: number;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:233

Decision time in milliseconds

difficultyEstimate?
readonly optional difficultyEstimate?: DifficultyEstimate;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:237

ZeroRouter difficulty estimate (if ZeroRouter enabled)

difficultyTier?
readonly optional difficultyTier?: ModelTier;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:239

ZeroRouter recommended model tier (if ZeroRouter enabled)

latencyScore?
readonly optional latencyScore?: number;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:249

Latency score (if latency tracking enabled) (Issue #361)

model?
readonly optional model?: string;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:225

Concrete model selected by difficulty tier (#3394). Present only when route-time model selection is enabled (NEXUS_ROUTE_MODEL_SELECTION). Consumers should use decision.model ?? getDefaultModelForCli(cliName).

preferenceScore?
readonly optional preferenceScore?: number;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:241

Preference routing score (if preference routing enabled)

preferenceTier?
readonly optional preferenceTier?: "strong" | "weak";

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:243

Selected tier from preference routing

reason
readonly reason: string;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:229

Human-readable explanation

stagesExecuted
readonly stagesExecuted: readonly string[];

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:231

Stages executed

taskProfile
readonly taskProfile: TaskProfile;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:264

Task analysis used for routing

topsisScore?
readonly optional topsisScore?: number;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:245

TOPSIS score (if TOPSIS ranking enabled)

ucbScore?
readonly optional ucbScore?: number;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:247

LinUCB UCB score (if LinUCB enabled)

withinBudget?
readonly optional withinBudget?: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:235

Budget feasibility (if budget filter enabled)


ExperienceRecord

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:181

Experience record for MobiMem Evolution.

Properties

id
readonly id: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:183

Unique experience ID

learnings
readonly learnings: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:195

Key learnings from this experience

steps
readonly steps: readonly ExperienceStep[];

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:191

Steps taken during execution

success
readonly success: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:193

Whether the task succeeded

taskDescription
readonly taskDescription: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:189

Description of the task

taskType
readonly taskType: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:187

Task type

timestamp
readonly timestamp: Date;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:185

When the experience occurred


ExperienceStep

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:167

Step within an experience record.

Properties

action
readonly action: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:171

Action taken

durationMs
readonly durationMs: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:175

Duration in milliseconds

index
readonly index: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:169

Step index

observation
readonly observation: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:173

Observation/result


GeminiCliResponse

Defined in: packages/nexus-agents/src/cli-adapters/parsers/gemini-parser.ts:21

Gemini CLI response structure. (Source: CLI testing 2026-01-04)

Properties

response
readonly response: string;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/gemini-parser.ts:23

session_id?
readonly optional session_id?: string;

Defined in: packages/nexus-agents/src/cli-adapters/parsers/gemini-parser.ts:22

stats?
readonly optional stats?: {
  models?: Record<string, {
     api?: {
        totalErrors?: number;
        totalLatencyMs?: number;
        totalRequests?: number;
     };
     tokens?: {
        cached?: number;
        candidates?: number;
        input?: number;
        prompt?: number;
        thoughts?: number;
        tool?: number;
        total?: number;
     };
  }>;
};

Defined in: packages/nexus-agents/src/cli-adapters/parsers/gemini-parser.ts:24

models?
readonly optional models?: Record<string, {
  api?: {
     totalErrors?: number;
     totalLatencyMs?: number;
     totalRequests?: number;
  };
  tokens?: {
     cached?: number;
     candidates?: number;
     input?: number;
     prompt?: number;
     thoughts?: number;
     tool?: number;
     total?: number;
  };
}>;

HealthStatus

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:362

Health check status for a CLI.

Properties

healthy
readonly healthy: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:364

Whether the CLI is healthy

lastChecked
readonly lastChecked: Date;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:401

Last successful health check

message?
readonly optional message?: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:370

Optional message (e.g., upgrade recommendation)

reachable?
readonly optional reachable?: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:384

Whether the underlying CLI could be reached at all (#5060).

healthCheck catches its own failures and returns rather than throwing, so a healthy: false result covers two very different states: the binary ran and reported an unsupported version, or the binary could not be run at all (spawn ENOENT). Both arrive as versionStatus: 'unsupported', and a consumer reading only healthy told users to authenticate a CLI they had not installed.

Absent means the producer predates the distinction — unknown, not unreachable. Consumers should treat reachable !== false as “present”.

version
readonly version: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:366

CLI version

versionProbedAt?
readonly optional versionProbedAt?: Date;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:399

When the evidence behind reachable was actually gathered (#5864).

BaseCliAdapter caches the version string forever — no TTL, no reset, not even on dispose() — so every healthCheck after the first for a given instance returns without spawning anything. reachable: true then restates a past observation as a present one, and lastChecked is stamped now, which dates a replay as if it were a fresh probe.

Compare the two: equal (to the probe) means this check ran the binary; earlier means reachable rests on a cached reading and the binary may have gone away since. Absent means the producer does not probe a binary at all (an in-process adapter) or predates the distinction — unknown, not stale.

versionStatus
readonly versionStatus: VersionStatus;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:368

Version compatibility status


ICircuitBreaker

Defined in: packages/nexus-agents/src/cli-adapters/circuit-breaker-types.ts:109

Interface for circuit breaker operations.

Methods

canExecute()
canExecute(): Result<true, CircuitError>;

Defined in: packages/nexus-agents/src/cli-adapters/circuit-breaker-types.ts:143

Checks whether an execution can proceed under current circuit state.

Returns

Result<true, CircuitError>

execute()
execute<T>(fn): Promise<Result<T, CircuitError>>;

Defined in: packages/nexus-agents/src/cli-adapters/circuit-breaker-types.ts:113

Executes a function with circuit breaker protection.

Type Parameters
T

T

Parameters
fn

() => Promise<T>

Returns

Promise<Result<T, CircuitError>>

getSnapshot()
getSnapshot(): CircuitBreakerSnapshot;

Defined in: packages/nexus-agents/src/cli-adapters/circuit-breaker-types.ts:123

Gets a full snapshot of circuit breaker state.

Returns

CircuitBreakerSnapshot

getState()
getState(): CircuitState;

Defined in: packages/nexus-agents/src/cli-adapters/circuit-breaker-types.ts:118

Gets the current circuit state.

Returns

CircuitState

recordFailure()
recordFailure(category): void;

Defined in: packages/nexus-agents/src/cli-adapters/circuit-breaker-types.ts:133

Records a failure manually (for external failure detection).

Parameters
category

CircuitBreakerFailureCategory

Returns

void

recordSuccess()
recordSuccess(): void;

Defined in: packages/nexus-agents/src/cli-adapters/circuit-breaker-types.ts:138

Records a success manually (for external success detection).

Returns

void

releaseHalfOpenProbe()
releaseHalfOpenProbe(): void;

Defined in: packages/nexus-agents/src/cli-adapters/circuit-breaker-types.ts:148

Releases a half-open probe request without recording success or failure (#6613).

Returns

void

reset()
reset(): void;

Defined in: packages/nexus-agents/src/cli-adapters/circuit-breaker-types.ts:128

Manually resets the circuit breaker to closed state.

Returns

void


ICliAdapter

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:141

CLI adapter interface. Abstracts CLI integration with transport-agnostic execution. (Source: cli-project_plan.md v2.1.0, Phase 2)

Properties

capabilities
readonly capabilities: CliCapabilityProfile;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:147

Capability profile

enforcesReadOnlyAnalysis?
readonly optional enforcesReadOnlyAnalysis?: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:153

True only when this adapter enforces accessMode: 'read-only-analysis' (#6754). Absent or false means it cannot, and a caller that asks for the mode must be refused rather than run with the adapter’s defaults.

enforcesWorkspaceEdit?
readonly optional enforcesWorkspaceEdit?: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:160

True only when this adapter enforces accessMode: 'workspace-edit' (#6792): edits confined to the working directory, no command, network or MCP tool. Absent or false means it cannot, and a caller that asks for the mode must be refused. Declaring read-only analysis does not imply it.

name
readonly name: "claude" | "gemini" | "codex" | "opencode";

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:143

CLI name

transport
readonly transport: CliTransport;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:145

Transport type

Methods

dispose()
dispose(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:209

Cleans up resources (e.g., subprocess, MCP connection). Called on shutdown.

Returns

Promise<void>

execute()
execute(task, options?): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:169

Executes a task on the CLI.

Parameters
task

CliTask

Task to execute

options?

CliExecutionOptions

Execution options

Returns

Promise<Result<CliResponse, CliError>>

Result with response or error

getCapacity()
getCapacity(): Promise<CapacityStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:183

Gets current capacity/rate limit status.

Returns

Promise<CapacityStatus>

Capacity status

getModelInfo()
getModelInfo(): CliModelInfo;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:197

Gets model information.

Returns

CliModelInfo

Model info

getVersion()
getVersion(): Promise<string>;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:190

Gets CLI version.

Returns

Promise<string>

Version string

healthCheck()
healthCheck(): Promise<HealthStatus>;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:176

Performs a health check on the CLI.

Returns

Promise<HealthStatus>

Health status including version compatibility

initialize()
initialize(): Promise<void>;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:203

Initializes the adapter (e.g., MCP connection). Called before first use.

Returns

Promise<void>

listModels()?
optional listModels(): Promise<readonly CliModelInfo[]>;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:217

(#2540) Optional: list models the underlying CLI installation/runtime has available. Implementations should cache for ~5 min and throw on failure so the caller can fall back. Adapters whose CLIs have no native list surface (claude, codex, gemini) leave this undefined.

Returns

Promise<readonly CliModelInfo[]>


ICliCircuitBreakerIntegration

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:73

Interface for CLI circuit breaker integration.

Methods

addStateChangeListener()
addStateChangeListener(listener): void;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:83

Parameters
listener

CircuitStateChangeListener

Returns

void

execute()
execute(
   adapter, 
   task, 
   taskCategory?
): Promise<Result<CircuitProtectedResult, CliError | CircuitError>>;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:74

Parameters
adapter

ICliAdapter

task

CliTask

taskCategory?

| "planning" | "architecture" | "code_generation" | "code_review" | "research" | "security_review" | "documentation" | "testing" | "devops" | "exploration"

Returns

Promise<Result<CircuitProtectedResult, CliError | CircuitError>>

getCircuitSnapshots()
getCircuitSnapshots(): Map<"claude" | "gemini" | "codex" | "opencode", CircuitBreakerSnapshot>;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:80

Returns

Map<"claude" | "gemini" | "codex" | "opencode", CircuitBreakerSnapshot>

getHealthStatus()
getHealthStatus(): CliCircuitHealthStatus;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:79

Returns

CliCircuitHealthStatus

resetAllCircuits()
resetAllCircuits(): void;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:82

Returns

void

resetCircuit()
resetCircuit(cliName): void;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:81

Parameters
cliName

"claude" | "gemini" | "codex" | "opencode"

Returns

void


ICliDetectionCache

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:70

Interface for CLI detection cache. Allows dependency injection for testing.

Methods

get()
get(cli): CliHealthResult | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:72

Get cached health result for a CLI

Parameters
cli

"claude" | "gemini" | "codex" | "opencode"

Returns

CliHealthResult | undefined

getAll()
getAll(): ReadonlyMap<"claude" | "gemini" | "codex" | "opencode", CliHealthResult>;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:84

Get all cached results

Returns

ReadonlyMap<"claude" | "gemini" | "codex" | "opencode", CliHealthResult>

getEffectiveTtl()
getEffectiveTtl(cli): number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:90

Get effective TTL for a CLI (accounts for adaptive adjustments)

Parameters
cli

"claude" | "gemini" | "codex" | "opencode"

Returns

number

getStats()
getStats(): CliCacheStats;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:87

Get cache statistics

Returns

CliCacheStats

invalidate()
invalidate(cli?): void;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:81

Invalidate cache for a specific CLI or all CLIs

Parameters
cli?

"claude" | "gemini" | "codex" | "opencode"

Returns

void

isStale()
isStale(cli): boolean;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:78

Check if cache entry is stale

Parameters
cli

"claude" | "gemini" | "codex" | "opencode"

Returns

boolean

set()
set(cli, result): void;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:75

Set health result for a CLI

Parameters
cli

"claude" | "gemini" | "codex" | "opencode"

result

CliHealthResult

Returns

void


ICliResponseParser

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:253

Response parser interface for defensive parsing. (Source: docs/research/cli-integration-architecture.md)

Type Parameters

T

T = unknown

Properties

name
readonly name: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:255

Parser name (for logging)

supportedVersionRange
readonly supportedVersionRange: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:257

Supported version range (semver)

Methods

extractCostUsd()?
optional extractCostUsd(raw): number | null;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:291

Extracts a cost the CLI itself reported, in USD.

OPTIONAL, and the optionality carries meaning (#5241). An ABSENT method says “this vendor does not report cost” — true of codex, gemini, opencode and agy. A PRESENT method returning null says “this vendor reports cost, and this response carried none”. Collapsing those two into a missing number is what left CliResponse.costUsd with no producer while a consumer (budget-router) fell back to an estimate under a field named actual.

The value is a MEASUREMENT from the vendor, not a rate-derived figure, so it does not pass through the token→USD pricing chain.

Parameters
raw

string

Raw CLI output

Returns

number | null

Vendor-reported cost in USD, or null if this response carried none

extractErrorMessage()?
optional extractErrorMessage(raw): string | null;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:305

Extracts an error-only message from a failure stream — when the CLI surfaced an error event but no usable assistant content (so extractResponse returns null). Optional: parsers that don’t distinguish error-only streams omit it, and the caller falls back to the generic unparseable-output recovery. OpenCode’s NDJSON {"type":"error"} events are the motivating case — without this the message is misclassified as PARSE_ERROR instead of NOT_AUTHENTICATED / RATE_LIMITED.

Parameters
raw

string

Raw CLI output

Returns

string | null

The extracted error message, or null if none / not applicable

extractResponse()
extractResponse(raw): string | null;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:273

Extracts just the response text (most stable field).

Parameters
raw

string

Raw CLI output

Returns

string | null

Response text or null

extractSessionId()
extractSessionId(raw): string | null;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:321

Extracts session ID (for resumption).

Parameters
raw

string

Raw CLI output

Returns

string | null

Session ID or null

extractUsage()
extractUsage(raw): CliTokenUsage | null;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:313

Extracts token usage (may not be present).

Parameters
raw

string

Raw CLI output

Returns

CliTokenUsage | null

Token usage or null

parse()
parse(raw): T | null;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:265

Parses raw CLI output to typed response.

Parameters
raw

string

Raw CLI output

Returns

T | null

Parsed response or null if unrecognized


ICompositeRouter

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:154

Composite router interface for dependency injection.

Methods

executeDecision()?
optional executeDecision(
   decision, 
   task, 
   runTask?, 
   options?
): Promise<Result<CliResponse, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:165

Run a decision route() returned and feed the outcome back, exactly as executeTask does after routing (#6533). Optional so existing implementors of this DI seam stay valid; CompositeRouter implements it.

Parameters
decision

CompositeRoutingDecision

task

CliTask

runTask?

CliTask

options?

CliExecutionOptions

Returns

Promise<Result<CliResponse, CliError>>

executeTask()
executeTask(task, options?): Promise<Result<CliResponse, 
  | CliError
| CompositeRoutingError>>;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:156

Parameters
task

CliTask

options?

CliExecutionOptions

Returns

Promise<Result<CliResponse, | CliError | CompositeRoutingError>>

getLatencyTracker()
getLatencyTracker(): ILatencyTracker | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:182

Returns

ILatencyTracker | undefined

getMetricsCollector()
getMetricsCollector(): IRoutingMetricsCollector | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:185

Get the metrics collector (if configured) (Issue #559)

Returns

IRoutingMetricsCollector | undefined

getOrchestrationObserver()
getOrchestrationObserver(): 
  | IOrchestrationObserver
  | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:187

Get the orchestration observer (if configured) (Issue #587)

Returns

| IOrchestrationObserver | undefined

getRoutingMemory()
getRoutingMemory(): IRoutingMemory | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:183

Returns

IRoutingMemory | undefined

getStats()
getStats(): CompositeRouterStats;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:179

Returns

CompositeRouterStats

getZeroRouter()
getZeroRouter(): IZeroRouter | undefined;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:181

Returns

IZeroRouter | undefined

hasMinimumPreferenceData()
hasMinimumPreferenceData(): boolean;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:180

Returns

boolean

recordDifficultyOutcome()
recordDifficultyOutcome(
   task, 
   success, 
   qualityScore?
): void;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:178

Parameters
task

CliTask

success

boolean

qualityScore?

number

Returns

void

recordOutcome()
recordOutcome(
   cliName, 
   task, 
   reward, 
   success?
): void;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:172

Record a routing outcome for a distinct routing arm (CLI slot or api:* arm) (#3422).

Parameters
cliName

RoutingArmId

task

CliTask

reward

number

success?

boolean

Returns

void

recordPreference()
recordPreference(
   query, 
   strongPreferred, 
   quality?
): void;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:173

Parameters
query

string

strongPreferred

boolean

quality?
strong?

number

weak?

number

Returns

void

route()
route(task): Promise<Result<CompositeRoutingDecision, CompositeRoutingError>>;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:155

Parameters
task

CliTask

Returns

Promise<Result<CompositeRoutingDecision, CompositeRoutingError>>


IPreferenceDataStore

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:190

Interface for the preference data store.

Methods

clear()
clear(): void;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:202

Clear all data

Returns

void

findSimilar()
findSimilar(features, limit): readonly PreferenceDataPoint[];

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:198

Find similar data points based on features

Parameters
features

QueryFeatures

limit

number

Returns

readonly PreferenceDataPoint[]

getAll()
getAll(): readonly PreferenceDataPoint[];

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:194

Get all data points

Returns

readonly PreferenceDataPoint[]

getByDomain()
getByDomain(domain): readonly PreferenceDataPoint[];

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:196

Get data points by domain

Parameters
domain

string

Returns

readonly PreferenceDataPoint[]

getStats()
getStats(): PreferenceModelStats;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:200

Get statistics

Returns

PreferenceModelStats

store()
store(dataPoint): void;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:192

Store a new preference data point

Parameters
dataPoint

PreferenceDataPoint

Returns

void


IRoutingMemory

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:287

Memory interface for routing-related data. Bridges memory backend and routing systems.

This interface enables:

  • #148 Preference-Trained Routing: Store preferences and outcomes
  • #149 MobiMem Evolution: Store experiences and action patterns

Example

const routingMemory = createRoutingMemory(memoryBackend);

// Store a routing decision and outcome
await routingMemory.storePreference(decision, outcome, preference);

// Get preferences for training
const prefs = await routingMemory.getPreferences({ taskType: 'code' }, 100);

// Store experience for MobiMem
await routingMemory.storeExperience(experience);

Methods

export()
export(): Promise<Result<RoutingMemoryExport, RoutingMemoryError>>;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:358

Export all routing memory for training or backup.

Returns

Promise<Result<RoutingMemoryExport, RoutingMemoryError>>

getActions()
getActions(taskType, limit): Promise<Result<ActionRecord[], RoutingMemoryError>>;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:349

Retrieve cached actions for a task type.

Parameters
taskType

string

Type of task

limit

number

Maximum actions to return

Returns

Promise<Result<ActionRecord[], RoutingMemoryError>>

getExperiences()
getExperiences(query, limit): Promise<Result<ExperienceRecord[], RoutingMemoryError>>;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:329

Retrieve relevant experiences for a task.

Parameters
query

string

Semantic query for experience retrieval

limit

number

Maximum experiences to return

Returns

Promise<Result<ExperienceRecord[], RoutingMemoryError>>

getPreferences()
getPreferences(filter, limit): Promise<Result<PreferenceRecord[], RoutingMemoryError>>;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:309

Retrieve preference data for training.

Parameters
filter

PreferenceFilter

Filter criteria for preferences

limit

number

Maximum records to return

Returns

Promise<Result<PreferenceRecord[], RoutingMemoryError>>

getStats()
getStats(): Promise<Result<RoutingMemoryStats, RoutingMemoryError>>;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:373

Get memory statistics.

Returns

Promise<Result<RoutingMemoryStats, RoutingMemoryError>>

import()
import(data): Promise<Result<void, RoutingMemoryError>>;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:364

Import routing memory from export.

Parameters
data

RoutingMemoryExport

The exported data to import

Returns

Promise<Result<void, RoutingMemoryError>>

storeAction()
storeAction(action): Promise<Result<void, RoutingMemoryError>>;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:342

Store a successful action pattern.

Parameters
action

ActionRecord

The action pattern to cache

Returns

Promise<Result<void, RoutingMemoryError>>

storeExperience()
storeExperience(experience): Promise<Result<void, RoutingMemoryError>>;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:322

Store an experience record for evolution.

Parameters
experience

ExperienceRecord

The experience to store

Returns

Promise<Result<void, RoutingMemoryError>>

storePreference()
storePreference(
   decision, 
   outcome, 
   preference?
): Promise<Result<void, RoutingMemoryError>>;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:298

Store a routing decision with its outcome for preference learning.

Parameters
decision

RoutingDecisionRecord

The routing decision made

outcome

TaskOutcomeRecord

The task outcome (success, quality, duration)

preference?

PreferenceSignal

Optional explicit preference signal

Returns

Promise<Result<void, RoutingMemoryError>>


PreferenceDataPoint

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:17

A single preference data point comparing model outputs.

Properties

domain?
readonly optional domain?: string;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:33

Domain or task category

features
readonly features: QueryFeatures;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:23

Extracted query features

id
readonly id: string;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:19

Unique identifier

query
readonly query: string;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:21

The input query

recordedAt
readonly recordedAt: Date;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:31

When this preference was recorded

strongModelPreferred
readonly strongModelPreferred: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:25

Whether the strong model was preferred

strongModelQuality?
readonly optional strongModelQuality?: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:27

Optional: actual strong model response quality score

weakModelQuality?
readonly optional weakModelQuality?: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:29

Optional: actual weak model response quality score


PreferenceFilter

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:145

Filter for preference queries.

Properties

cliName?
readonly optional cliName?: "claude" | "gemini" | "codex" | "opencode";

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:149

Filter by CLI name

minQuality?
readonly optional minQuality?: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:155

Minimum quality score

preferenceSource?
readonly optional preferenceSource?: "human" | "ai" | "implicit";

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:157

Filter by preference source

since?
readonly optional since?: Date;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:151

Records after this date

taskType?
readonly optional taskType?: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:147

Filter by task type

until?
readonly optional until?: Date;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:153

Records before this date


PreferenceModelStats

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:172

Statistics about the preference router’s learned model.

Properties

dataPointsByDomain
readonly dataPointsByDomain: Record<string, number>;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:176

Data points by domain

estimatedCostSavingsRate
readonly estimatedCostSavingsRate: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:182

Estimated cost savings rate

lastUpdatedAt
readonly lastUpdatedAt: Date;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:184

Last updated timestamp

routingAccuracy?
readonly optional routingAccuracy?: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:180

Routing accuracy (if validation data available)

strongModelPreferenceRate
readonly strongModelPreferenceRate: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:178

Average strong model preference rate

totalDataPoints
readonly totalDataPoints: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:174

Total data points collected


PreferencePrediction

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:61

Result of a preference prediction.

Properties

confidence
readonly confidence: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:65

Confidence in this prediction (0-1)

features
readonly features: QueryFeatures;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:67

Features used for prediction

strongModelProbability
readonly strongModelProbability: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:63

Probability that strong model is significantly better

supportingDataPoints
readonly supportingDataPoints: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:69

Number of similar data points used


PreferenceRecord

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:131

Combined preference record for training.

Properties

computedReward
readonly computedReward: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:139

Computed reward signal

decision
readonly decision: RoutingDecisionRecord;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:133

The routing decision

outcome
readonly outcome: TaskOutcomeRecord;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:135

The task outcome

preference?
readonly optional preference?: PreferenceSignal;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:137

Explicit preference (if provided)


PreferenceRouterConfig

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:107

Preference router configuration.

Properties

domainThresholds?
readonly optional domainThresholds?: Record<string, number>;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:121

Domain-specific threshold overrides

enableOnlineLearning
readonly enableOnlineLearning: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:119

Whether to enable online learning

maxDataPoints
readonly maxDataPoints: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:117

Maximum data points to store

minDataPoints
readonly minDataPoints: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:115

Minimum data points before using learned routing

routingThreshold
readonly routingThreshold: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:113

Threshold for routing to strong model (0-1)

strongModel
readonly strongModel: ModelTier;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:109

Strong model configuration

weakModel
readonly weakModel: ModelTier;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:111

Weak model configuration


PreferenceRoutingDecision

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:75

Routing decision based on preference prediction.

Properties

estimatedCostSavings
readonly estimatedCostSavings: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:87

Cost savings compared to always using strong model

prediction
readonly prediction: PreferencePrediction;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:81

Preference prediction details

reason
readonly reason: string;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:83

Reason for selection

routingLatencyMs
readonly routingLatencyMs: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:85

Routing decision time in ms

selectedCli
readonly selectedCli: "claude" | "gemini" | "codex" | "opencode";

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:79

Selected adapter

selectedTier
readonly selectedTier: "strong" | "weak";

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:77

Selected model tier


PreferenceSignal

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:115

Explicit preference signal from human or AI feedback.

Properties

confidence
readonly confidence: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:125

Confidence in the preference (0-1)

preferred
readonly preferred: "claude" | "gemini" | "codex" | "opencode";

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:119

Preferred CLI for this task type

reason?
readonly optional reason?: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:123

Optional reasoning

rejected?
readonly optional rejected?: "claude" | "gemini" | "codex" | "opencode";

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:121

Rejected CLI (if comparative preference)

source
readonly source: "human" | "ai" | "implicit";

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:117

Source of the preference


QueryFeatures

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:39

Features extracted from a query for preference prediction.

Properties

complexity
readonly complexity: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:43

Complexity score (0-1)

domain
readonly domain: string;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:53

Domain category

hasAmbiguity
readonly hasAmbiguity: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:51

Whether query has ambiguity

keywordSignature
readonly keywordSignature: string;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:55

Keywords present (hashed for privacy)

requiresCode
readonly requiresCode: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:47

Whether query requires code generation

requiresCreativity
readonly requiresCreativity: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:49

Whether query requires creativity

requiresReasoning
readonly requiresReasoning: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:45

Whether query requires reasoning

tokenCount
readonly tokenCount: number;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:41

Query length in tokens (estimated)


RoutingDecisionRecord

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:69

Record of a routing decision.

Properties

alternatives
readonly alternatives: readonly ("claude" | "gemini" | "codex" | "opencode")[];

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:85

Alternative CLIs considered

budgetConstraint?
readonly optional budgetConstraint?: BudgetConstraint;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:89

Budget constraint applied (if any)

confidence
readonly confidence: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:83

Confidence score (0-1)

id
readonly id: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:71

Unique decision ID

reason
readonly reason: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:87

Reasoning for selection

selectedCli
readonly selectedCli: "claude" | "gemini" | "codex" | "opencode";

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:81

CLI selected for execution

taskId
readonly taskId: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:75

Associated task ID

taskProfile
readonly taskProfile: TaskProfileSummary;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:79

Summary of task profile

taskType
readonly taskType: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:77

Task type classification

timestamp
readonly timestamp: Date;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:73

When the decision was made


RoutingMemoryExport

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:230

Export format for routing memory. Version field enables future schema migrations.

Properties

actions
readonly actions: readonly ActionRecord[];

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:240

Action records

experiences
readonly experiences: readonly ExperienceRecord[];

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:238

Experience records

exportedAt
readonly exportedAt: Date;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:234

When the export was created

preferences
readonly preferences: readonly PreferenceRecord[];

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:236

Preference records

version
readonly version: "1.0";

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:232

Schema version


RoutingMemoryStats

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:246

Statistics for routing memory.

Properties

actionCount
readonly actionCount: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:252

Total action records

experienceCount
readonly experienceCount: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:250

Total experience records

newestRecord
readonly newestRecord: Date | null;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:256

Newest record timestamp

oldestRecord
readonly oldestRecord: Date | null;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:254

Oldest record timestamp

preferenceCount
readonly preferenceCount: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:248

Total preference records

totalStorageBytes
readonly totalStorageBytes: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:258

Estimated storage size in bytes


TaskOutcomeRecord

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:95

Record of a task outcome.

Properties

decisionId
readonly decisionId: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:97

Associated decision ID

durationMs
readonly durationMs: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:103

Execution duration in milliseconds

errorCategory?
readonly optional errorCategory?: string;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:109

Error category (if failed)

qualityScore
readonly qualityScore: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:101

Quality score (0-1)

retryCount
readonly retryCount: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:107

Number of retries

success
readonly success: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:99

Whether task succeeded

tokenUsage
readonly tokenUsage: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:105

Token usage


TaskProfileSummary

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:55

Summary of task profile for storage (avoids circular deps with TaskProfile).

Properties

codeGeneration
readonly codeGeneration: boolean;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:61

Whether code generation is primary task

contextRequired
readonly contextRequired: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:59

Context tokens required

reasoningComplexity
readonly reasoningComplexity: number;

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:57

Estimated reasoning complexity (0-1)

taskType
readonly taskType: "code" | "reasoning" | "knowledge" | "mixed";

Defined in: packages/nexus-agents/src/cli-adapters/routing-memory-types.ts:63

Task type classification


TimeoutProfile

Defined in: packages/nexus-agents/src/config/defaults-types.ts:23

Timeout profile structure for CLI tools.

Properties

complex
readonly complex: number;

Defined in: packages/nexus-agents/src/config/defaults-types.ts:29

Timeout for complex tasks (codebase-wide changes, deep analysis) in ms

simple
readonly simple: number;

Defined in: packages/nexus-agents/src/config/defaults-types.ts:25

Timeout for simple tasks (single function, quick analysis) in ms

standard
readonly standard: number;

Defined in: packages/nexus-agents/src/config/defaults-types.ts:27

Timeout for standard tasks (multi-file changes, moderate analysis) in ms


VersionRequirements

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:327

Version requirements for CLIs.

Properties

breaking
readonly breaking: readonly string[];

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:333

Known breaking versions

minimum
readonly minimum: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:329

Minimum supported version

readonly recommended: string;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:331

Recommended version

Type Aliases

CircuitBreakerFailureCategory

type CircuitBreakerFailureCategory = 
  | "timeout"
  | "crash"
  | "authentication"
  | "rate_limit"
  | "connection"
  | "unknown";

Defined in: packages/nexus-agents/src/cli-adapters/circuit-breaker-types.ts:25

Categories of failures for circuit breaker decisions.


CircuitState

type CircuitState = "closed" | "open" | "half-open";

Defined in: packages/nexus-agents/src/cli-adapters/circuit-breaker-types.ts:20

Circuit breaker states.


CliErrorCode

type CliErrorCode = 
  | "NOT_FOUND"
  | "NOT_AUTHENTICATED"
  | "RATE_LIMITED"
  | "TIMEOUT"
  | "PARSE_ERROR"
  | "CONNECTION_ERROR"
  | "EXECUTION_ERROR"
  | "UNSUPPORTED_VERSION"
  | "BUDGET_EXCEEDED"
  | "UNKNOWN";

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:307

Error codes for CLI operations.


CliName

type CliName = CliNameLiteral;

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:18

Supported CLI names. Derived from canonical source: config/model-capabilities-types.ts CliNameLiteral


CliTaskComplexity

type CliTaskComplexity = "simple" | "standard" | "complex";

Defined in: packages/nexus-agents/src/config/defaults-types.ts:18

Task complexity levels for CLI timeout selection.


CliTransport

type CliTransport = "mcp" | "subprocess";

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:172

Transport type for CLI communication.

  • ‘mcp’: Uses Model Context Protocol (most stable)
  • ‘subprocess’: Spawns CLI process with JSON output

CompositeRouterConfig

type CompositeRouterConfig = z.infer<typeof CompositeRouterConfigSchema>;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:128

CLI Adapters exports - CLI integration with defensive parsing Split from index.ts for file size compliance (Issue #285)


VersionStatus

type VersionStatus = "supported" | "outdated" | "breaking" | "unsupported";

Defined in: packages/nexus-agents/src/cli-adapters/types-core.ts:357

Version compatibility status.

Variables

CLI_DEFAULT_CACHE_CONFIG

const CLI_DEFAULT_CACHE_CONFIG: CliDetectionCacheConfig;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:55

Default cache configuration.


CLI_DEFAULT_CAPABILITIES

const CLI_DEFAULT_CAPABILITIES: Record<CliName, CliCapabilityProfile>;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:374

CLI Adapters exports - CLI integration with defensive parsing Split from index.ts for file size compliance (Issue #285)


CLI_DEFAULT_COMPOSITE_CONFIG

const CLI_DEFAULT_COMPOSITE_CONFIG: CompositeRouterConfig;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:190

Default configuration.


CLI_TIMEOUT_PROFILES

const CLI_TIMEOUT_PROFILES: Record<string, TimeoutProfile>;

Defined in: packages/nexus-agents/src/cli-adapters/cli-timeout-profiles.ts:26

Per-CLI timeout profiles. Canonical source: config/timeouts.ts.


CLI_VERSION_REQUIREMENTS

const CLI_VERSION_REQUIREMENTS: Record<CliName, VersionRequirements>;

Defined in: packages/nexus-agents/src/cli-adapters/types-capability.ts:340

CLI version requirements. (Source: docs/research/cli-integration-architecture.md)


CliDetectionCacheConfigSchema

const CliDetectionCacheConfigSchema: ZodObject<{
  ttlMs: ZodDefault<ZodNumber>;
}, $strip>;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:48

Zod schema for cache configuration validation.


CompositeRouterConfigSchema

const CompositeRouterConfigSchema: ZodObject<{
  billingMode: ZodDefault<ZodEnum<{
     api: "api";
     plan: "plan";
  }>>;
  budgetConstraints: ZodOptional<ZodObject<{
     maxCostUsd: ZodOptional<ZodNumber>;
     maxLatencyMs: ZodOptional<ZodNumber>;
     maxTokens: ZodOptional<ZodNumber>;
     taskClassMaxCostUsd: ZodOptional<ZodRecord<ZodEnum<{
        architecture: "architecture";
        code_generation: "code_generation";
        code_review: "code_review";
        devops: "devops";
        documentation: "documentation";
        exploration: "exploration";
        planning: "planning";
        research: "research";
        security_review: "security_review";
        testing: "testing";
     }> & $partial, ZodNumber>>;
  }, $strip>>;
  enableBudgetFilter: ZodDefault<ZodBoolean>;
  enableCapabilityMatch: ZodDefault<ZodBoolean>;
  enableCapacityBalancing: ZodDefault<ZodBoolean>;
  enableConfidenceCascade: ZodDefault<ZodBoolean>;
  enableKnnRouting: ZodDefault<ZodBoolean>;
  enableLatencyTracking: ZodDefault<ZodBoolean>;
  enableLinUCBSelection: ZodDefault<ZodBoolean>;
  enablePreferenceRouting: ZodDefault<ZodBoolean>;
  enableQualityConstraint: ZodDefault<ZodBoolean>;
  enableResourceStrategy: ZodDefault<ZodBoolean>;
  enableRoutingMemory: ZodDefault<ZodBoolean>;
  enableStrategyDistillation: ZodDefault<ZodBoolean>;
  enableTopsisRanking: ZodDefault<ZodBoolean>;
  enableZeroRouter: ZodDefault<ZodBoolean>;
  latencyScoreWeight: ZodDefault<ZodNumber>;
  linucbAlpha: ZodDefault<ZodNumber>;
  maxDecisionTimeMs: ZodDefault<ZodNumber>;
  preferenceMinDataPoints: ZodDefault<ZodNumber>;
}, $strip>;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router-types.ts:49

Configuration schema for CompositeRouter.


DEFAULT_PREFERENCE_ROUTER_CONFIG

const DEFAULT_PREFERENCE_ROUTER_CONFIG: PreferenceRouterConfig;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:127

Default preference router configuration.


DEFAULT_TIMEOUT_PROFILE

const DEFAULT_TIMEOUT_PROFILE: TimeoutProfile = CLI_TIMEOUTS.default;

Defined in: packages/nexus-agents/src/cli-adapters/cli-timeout-profiles.ts:33

Default timeout profile. Canonical source: config/timeouts.ts.


PreferenceRouterConfigSchema

const PreferenceRouterConfigSchema: ZodObject<{
  domainThresholds: ZodOptional<ZodRecord<ZodString, ZodNumber>>;
  enableOnlineLearning: ZodDefault<ZodBoolean>;
  maxDataPoints: ZodDefault<ZodNumber>;
  minDataPoints: ZodDefault<ZodNumber>;
  routingThreshold: ZodDefault<ZodNumber>;
  strongModel: ZodObject<{
     cli: ZodEnum<{
        claude: "claude";
        codex: "codex";
        gemini: "gemini";
        opencode: "opencode";
     }>;
     costPerMillionTokens: ZodNumber;
     qualityBaseline: ZodNumber;
     tier: ZodLiteral<"strong">;
  }, $strip>;
  weakModel: ZodObject<{
     cli: ZodEnum<{
        claude: "claude";
        codex: "codex";
        gemini: "gemini";
        opencode: "opencode";
     }>;
     costPerMillionTokens: ZodNumber;
     qualityBaseline: ZodNumber;
     tier: ZodLiteral<"weak">;
  }, $strip>;
}, $strip>;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router-types.ts:149

Zod schema for config validation.

Functions

cliCalculateBackoffDelay()

function cliCalculateBackoffDelay(
   attempt, 
   baseDelayMs, 
   maxDelayMs
): number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:63

Calculates exponential backoff delay with jitter.

Parameters

attempt

number

Current attempt number (1-indexed)

baseDelayMs

number

Base delay in milliseconds

maxDelayMs

number

Maximum delay cap in milliseconds

Returns

number

Delay in milliseconds with jitter applied


cliCategorizeError()

function cliCategorizeError(error): CircuitBreakerFailureCategory;

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:105

Categorizes a CLI error for circuit breaker tracking. Returns a FailureCategory compatible with the circuit breaker.

Parameters

error

CliError

Returns

CircuitBreakerFailureCategory


createAllAdapters()

function createAllAdapters(logger?, codexTransport?): Map<RoutingArmId, ICliAdapter>;

Defined in: packages/nexus-agents/src/cli-adapters/factory.ts:151

Creates all available routing-arm adapters. Codex transport is selected by probe unless one is passed (#6119).

The four CLI slots are registered under their slot key. In gateway mode a vendor slot whose CLI is not available (isCliAvailable, the predicate createAutoAdapter uses) is served by a gateway model of its family, and a slot with neither a usable binary nor a family model is omitted (#6604, gateway-slot-arm.ts). NEXUS_DISABLED_CLIS is transport-scoped (#6720): a disabled CLI counts as “not available”, so its family’s gateway model still serves the slot; without a gateway catalogue a disabled CLI’s slot is omitted (#6590), and every CLI disabled yields an empty map. When NEXUS_BILLING_MODE=api, the direct-API adapters whose keys are present are ALSO appended as distinct api:<vendor> routing arms (#3422) so the router / bandit can score them separately from the CLI slots. DEFAULT (plan) mode returns CLIs only — never surprise API spend. Key-presence-only and deterministic; keys are never validated by calling out.

Parameters

logger?

ILogger

Optional shared logger

codexTransport?

CliTransport

Transport for Codex; unset selects by probe

Returns

Map<RoutingArmId, ICliAdapter>

Map of routing arm id to adapter


createCliAdapter()

function createCliAdapter(config): ICliAdapter;

Defined in: packages/nexus-agents/src/cli-adapters/factory.ts:68

Creates a CLI adapter based on configuration.

Parameters

config

CliAdapterConfig

Adapter configuration

Returns

ICliAdapter

The configured CLI adapter

Throws

Error if CLI name is not supported

Example

const adapter = createCliAdapter({ cli: 'claude', model: 'claude-opus-4' });
const result = await adapter.execute({ content: 'Hello!' });

createCliCircuitBreakerIntegration()

function createCliCircuitBreakerIntegration(
   adapters, 
   config?, 
   logger?
): CliCircuitBreakerIntegration;

Defined in: packages/nexus-agents/src/cli-adapters/cli-circuit-breaker.ts:297

Creates a CLI circuit breaker integration with the specified adapters.

Parameters

adapters

readonly ICliAdapter[]

config?

CliCircuitBreakerConfig

logger?

ILogger

Returns

CliCircuitBreakerIntegration


createCliDetectionCache()

function createCliDetectionCache(config?): ICliDetectionCache;

Defined in: packages/nexus-agents/src/cli-adapters/cli-detection-cache.ts:262

Creates a CLI detection cache instance.

Parameters

config?

Partial<CliDetectionCacheConfig>

Optional cache configuration

Returns

ICliDetectionCache

CLI detection cache

Example

const cache = createCliDetectionCache({ ttlMs: 60_000 }); // 1 minute TTL
const result = cache.get('claude');
if (!result) {
  const health = await adapter.healthCheck();
  cache.set('claude', CliDetectionCache.fromHealthStatus(health));
}

createCompositeRouter()

function createCompositeRouter(
   adapters, 
   config?, 
   logger?
): ICompositeRouter;

Defined in: packages/nexus-agents/src/cli-adapters/composite-router.ts:1123

Creates a CompositeRouter instance.

Parameters

adapters

Map<RoutingArmId, ICliAdapter>

config?

Partial<CompositeRouterConfigWithPreference>

logger?

ILogger

Returns

ICompositeRouter


createPreferenceRouter()

function createPreferenceRouter(config?, dataStore?): PreferenceRouter;

Defined in: packages/nexus-agents/src/cli-adapters/preference-router.ts:243

Create a PreferenceRouter instance.

Parameters

config?

Partial<PreferenceRouterConfig>

dataStore?

IPreferenceDataStore

Returns

PreferenceRouter


estimateTaskComplexity()

function estimateTaskComplexity(taskDescription): CliTaskComplexity;

Defined in: packages/nexus-agents/src/cli-adapters/cli-timeout-profiles.ts:41

Estimate task complexity from description. Canonical: cli-timeout-helpers.ts.

Parameters

taskDescription

string

Returns

CliTaskComplexity


executeCliRetryLoop()

function executeCliRetryLoop(executeFn, config): Promise<Result<CliRetryResult, CliError>>;

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:130

Executes a CLI operation with retry logic and optional circuit breaker.

Used by both BaseCliAdapter (no circuit breaker) and GeminiCliAdapter (with circuit breaker) to eliminate duplicate retry implementations.

Parameters

executeFn

() => Promise<Result<CliResponse, CliError>>

config

CliRetryLoopConfig

Returns

Promise<Result<CliRetryResult, CliError>>


getAvailableClis()

function getAvailableClis(cache?): Promise<("claude" | "gemini" | "codex" | "opencode")[]>;

Defined in: packages/nexus-agents/src/cli-adapters/factory.ts:285

Gets all available CLIs by running health checks. Uses cache if provided to avoid repeated subprocess calls. CLIs disabled by NEXUS_DISABLED_CLIS are excluded (#6590); disabling every CLI yields [].

Parameters

cache?

ICliDetectionCache

Optional cache to use

Returns

Promise<("claude" | "gemini" | "codex" | "opencode")[]>

Array of available CLI names


getTimeoutForTask()

function getTimeoutForTask(cli, complexity): number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-timeout-profiles.ts:36

Get timeout for a task. Canonical source: config/timeouts.ts.

Parameters

cli

string

complexity

CliTaskComplexity

Returns

number


getTimeoutForTaskAuto()

function getTimeoutForTaskAuto(cli, taskDescription): number;

Defined in: packages/nexus-agents/src/cli-adapters/cli-timeout-profiles.ts:49

Get timeout with automatic complexity estimation. Uses adaptive timeout from outcome history when sufficient data exists (#1534).

Parameters

cli

string

taskDescription

string

Returns

number


isCliAvailable()

function isCliAvailable(cli, cache?): Promise<boolean>;

Defined in: packages/nexus-agents/src/cli-adapters/factory.ts:210

Checks if a CLI is available by running a health check. Uses cache if provided to avoid repeated subprocess calls.

Parameters

cli

"claude" | "gemini" | "codex" | "opencode"

CLI name to check

cache?

ICliDetectionCache

Optional cache to use

Returns

Promise<boolean>

True if CLI is healthy


isCliRetryableError()

function isCliRetryableError(code): boolean;

Defined in: packages/nexus-agents/src/cli-adapters/cli-retry-loop.ts:97

Determines if an error code is retryable.

Parameters

code

CliErrorCode

Returns

boolean