Complete reference for all public classes, methods, and functions in the Infinium Node.js SDK.


Clients

InfiniumClient

Synchronous-style client for the Infinium API. All methods return Promises.

import { InfiniumClient } from 'infinium-o2';

Constructor

new InfiniumClient(config: ClientConfig)

See Configuration for all ClientConfig fields.

Methods

sendTask(task): Promise<ApiResponse>

Send a trace with inline parameters. currentDatetime is auto-generated if omitted.

await client.sendTask({
  name: 'Task name',
  description: 'Task description',
  duration: 2.4,
  // ... optional fields
});

sendTaskData(taskData: TaskData): Promise<ApiResponse>

Send a pre-built TaskData object.


sendBatch(tasks: TaskData[]): Promise<BatchResult>

Send up to 100 tasks sequentially.


getInterpretedTaskResult(taskId: string): Promise<ApiResponse>

Get Maestro’s interpretation for a trace. taskId must be a valid UUID.


getPrompt(promptId, promptKey, version?, variables?): Promise<PromptContent>

Fetch a prompt from Prompt Studio.

ParameterTypeDefaultDescription
promptIdstringrequiredPrompt UUID
promptKeystringrequiredPrompt secret key
versionstring | number'latest'Version number or 'latest'
variablesRecord<string, string>undefinedTemplate variables

trace(name, options?)

Returns a function wrapper that traces execution.

const fn = client.trace('Task Name', { autoSend: true, description: '...' })(
  async (...args) => { /* ... */ }
);
ParameterTypeDefaultDescription
namestringrequiredTrace name
options.autoSendbooleantrueSend trace on completion
options.descriptionstringundefinedOptional description

getCurrentIsoDatetime(): string

Returns current UTC datetime as ISO 8601 string.


getConfig(): Partial<ClientConfig>

Returns current client configuration.


close(): void

No-op on InfiniumClient (provided for API parity with AsyncInfiniumClient).


AsyncInfiniumClient

Asynchronous client with explicit lifecycle management.

import { AsyncInfiniumClient } from 'infinium-o2';

Same constructor and core methods as InfiniumClient, plus:

sendBatch(tasks: TaskData[]): Promise<BatchResult>

Send tasks concurrently via Promise.all() (vs sequential on InfiniumClient).


sendBatchSequential(tasks: TaskData[]): Promise<BatchResult>

Send tasks one at a time for strict rate control.


close(): Promise<void>

Clean up resources. Further requests will fail after calling.


isClosed(): boolean

Check if the client has been closed.


Tracing

TraceBuilder

Incrementally construct a TaskData during agent execution.

import { TraceBuilder } from 'infinium-o2';

Constructor

new TraceBuilder(name: string, description: string)

Methods

step(action: string, description: string): StepContext

Create an auto-numbered step.


setInputSummary(summary: string): TraceBuilder


setOutputSummary(summary: string): TraceBuilder


setExpectedOutcome(outcome: ExpectedOutcome): TraceBuilder


setEnvironment(env: EnvironmentContext): TraceBuilder


setLlmUsage(usage: LlmUsage): TraceBuilder


setSection(name: string, data: Record<string, unknown>): TraceBuilder

Set a domain section by name (e.g., 'customer', 'research').


addError(error: ErrorDetail): TraceBuilder


build(traceCtx?: TraceContext): TaskData

Build the final TaskData. Auto-computes duration. If traceCtx is provided, incorporates auto-captured LLM calls and prompt fetches.


All setters return this for fluent chaining.

StepContext

Created by TraceBuilder.step().

import { StepContext } from 'infinium-o2';

Constructor

new StepContext(stepNumber: number, action: string, description: string)

Methods

run<T>(fn: (step: StepContext) => T | Promise<T>): Promise<T>

Execute a function with auto-timing. Duration is recorded in durationMs.


setInput(preview: string): StepContext

Input preview (truncated to 500 chars).


setOutput(preview: string): StepContext

Output preview (truncated to 500 chars).


recordToolCall(call: ToolCall): StepContext


recordLlmCall(call: LlmCall): StepContext


setMetadata(meta: Record<string, unknown>): StepContext


All methods return this for chaining.


Integrations

watch()

Auto-detect and monkey-patch a single LLM client instance.

import { watch } from 'infinium-o2';

const patched = watch(client, options?);
ParameterTypeDefaultDescription
clientLLM clientrequiredOpenAI, Anthropic, or Gemini client
options.captureContentbooleanfalseCapture input/output previews

Returns: The same client object (patched in place).

Supported clients: OpenAI, AsyncOpenAI, Anthropic, AsyncAnthropic, GenerativeModel

Low-Level Patch Functions

import { patchOpenAIClient, patchAnthropicClient, patchGoogleModel } from 'infinium-o2';

patchOpenAIClient(client, captureContent?) — Patch an OpenAI/xAI client directly.

patchAnthropicClient(client, captureContent?) — Patch an Anthropic client directly.

patchGoogleModel(model, captureContent?) — Patch a Gemini GenerativeModel directly.


Context Management

TraceContext

Context object holding captured LLM calls and prompt fetches.

import { TraceContext } from 'infinium-o2';
PropertyTypeDescription
callsCapturedLlmCall[]Auto-captured LLM calls
promptsCapturedPromptFetch[]Auto-captured prompt fetches

getCurrentTraceContext(): TraceContext | null

Return the active trace context, or null if outside a trace.

runWithTraceContext<T>(ctx: TraceContext, fn: () => T): T

Run a function within a trace context (uses AsyncLocalStorage).


Utility Functions

Validation

import {
  validateAgentCredentials,
  validateIsoDatetime,
  validateDuration,
  validatePathId,
  validateStringLength,
  validatePayloadSize,
  validateRequiredField,
  validateUrl,
} from 'infinium-o2';

validateAgentCredentials(agentId?, agentSecret?): void — Validates credentials meet minimum requirements.

validateIsoDatetime(str: string): boolean — Returns true if valid ISO 8601.

validateDuration(duration: number): void — Validates 0-86,400 seconds.

validatePathId(value: string, fieldName: string): string — Validates UUID format.

validateStringLength(value: string, fieldName: string, maxLength: number): void

validatePayloadSize(payload: unknown): void — Max 1 MB.

validateRequiredField(value, fieldName, expectedType?): void

validateUrl(url: string): boolean

Logging

import { setupLogging } from 'infinium-o2';

const logger = setupLogging(true, 'DEBUG');

Case Conversion

import {
  camelToSnakeCase,
  snakeToCamelCase,
  objectToSnakeCase,
  objectToCamelCase,
} from 'infinium-o2';

Other Utilities

import {
  getCurrentIsoDatetime,
  truncateString,
  safeJsonStringify,
  safeJsonParse,
  mergeObjects,
  sleep,
  calculateBackoff,
  retryWithBackoff,
  shouldRetryError,
  generateUserAgent,
  normalizeUrl,
} from 'infinium-o2';

Constants

import {
  MAX_NAME_LENGTH,        // 500
  MAX_DESCRIPTION_LENGTH, // 10,000
  MAX_STRING_LENGTH,      // 2,000
  MAX_PAYLOAD_SIZE,       // 1,048,576 (1 MB)
} from 'infinium-o2';

Error Classes

All errors extend InfiniumError. See Error Handling for full details.

import {
  InfiniumError,
  AuthenticationError,
  ValidationError,
  RateLimitError,
  NetworkError,
  TimeoutError,
  ServerError,
  NotFoundError,
  BatchError,
  ConfigurationError,
  PayloadTooLargeError,
  // Type guards
  isInfiniumError,
  isErrorType,
  toInfiniumError,
  handleAxiosError,
} from 'infinium-o2';