Runtime Manual/Reference & Specs/Comprehensive API Reference

Comprehensive API Reference

Complete API directory for Amber native modules (amber:*), Node.js compatibility, and Web standards

Amber delivers a unified runtime environment exposing three foundational API tiers:

  1. Amber Native Modules (amber:*): Purpose-built subsystems for AI Agent execution, persistent state, streaming grammars, and sandboxing.
  2. Node.js Core Modules (node:*): 51/51 conformance suites passing for drop-in npm package compatibility.
  3. W3C / WHATWG Web Standards: Universal browser-compatible primitives (fetch, WebCrypto, WebStreams, Worker).

1. Amber Native API Reference (amber:*)

All native Amber modules can be imported using the canonical amber:<module> specifier or its unqualified short identifier (e.g. import { open } from 'amber:kv' or const { open } = require('kv')).

code
                              [ Amber Native Fabric ]
   +------------------------------------+------------------------------------+
   |   Autonomous Agent Subsystems      |   Runtime & Infrastructure         |
   |   ---------------------------      |   ------------------------         |
   |   • amber:ai        (Tensors & LLM)  |   • amber:kv        (ACID State)     |
   |   • amber:bus       (PubSub Fabric)  |   • amber:sandbox   (Micro-Enclaves) |
   |   • amber:grammar   (Stream Repair)  |   • amber:security  (Permissions)    |
   |   • amber:checkpoint(Time-Travel)    |   • amber:db        (SQLite Engine)  |
   |   • amber:tools     (OpenAPI Synth)  |   • amber:vector    (Vector Search)  |
   |   • amber:replay    (Trace Replay)   |   • amber:wasm      (Zero-Copy JIT)  |
   |   • amber:weights   (GGUF Slicing)   |   • amber:ffi       (Native C ABI)   |
   |   • amber:mcp       (MCP 2.0 Client) |   • amber:std       (Std Library)    |
   +------------------------------------+------------------------------------+

1.1 amber:ai — Edge Tensor Computing & Agent Pipelines

code
import { Tensor, LLM, AgentPipeline, embed, embedBatch, generate, generateStream, cosineSimilarity } from 'amber:ai';
Function / ClassSignatureDescription
Tensornew Tensor(shape: number[], data?: number[] | Float32Array, dtype?: string)N-dimensional tensor supporting matmul(), add(), slice(), norm(), and fromBuffer().
LLMnew LLM(config?: { model?: string, maxTokens?: number })Local or remote inference engine with generate() and generateStream().
AgentPipelinenew AgentPipeline()Multi-step reasoning pipeline supporting registerTool(), registerTools(), and step().
embed(text: string)Promise<number[]>Generates high-density vector embeddings (384/768 dim).
embedBatch(texts: string[])Promise<number[][]>Batch generates embeddings with parallel SIMD optimization.
cosineSimilarity(a, b)numberCalculates cosine similarity between two float vectors.

1.2 amber:bus — Multi-Agent Message Bus & PubSub Channel Fabric

code
import { createBus, getDefaultBus, subscribe, once, unsubscribe, publish, broadcast, request, reply, use, topicMatches } from 'amber:bus';
MethodSignatureDescription
subscribe(pattern, handler, opts?)(pattern: string, handler: (msg: Message) => void, opts?: { priority?: number }) => SubscriptionSubscribes to hierarchical topics with * and # wildcards.
once(pattern, handler, opts?)(pattern: string, handler: (msg) => void, opts?) => SubscriptionSingle-shot event subscriber automatically unregistering after first delivery.
publish(topic, payload, opts?)(topic: string, payload: any, opts?: PublishOptions) => MessageDispatches message to subscribers sorted by descending priority.
request(topic, payload, opts?)(topic: string, payload: any, opts?: { timeoutMs?: number }) => Promise<any>Bidirectional RPC request awaiting reply on correlation topic.
reply(originalMsg, responsePayload)(msg: Message, response: any) => MessageReplies directly to message's replyTo return address.
use(middleware)(middleware: (msg, next) => void) => thisRegisters interceptor for tracing, authentication, or payload validation.
getMetrics()() => BusMetricsReturns { published_count, delivered_count, dead_letter_count, active_subscriptions }.
getDeadLetters()() => Message[]Inspects unhandled messages routed to the Dead-Letter Queue.

1.3 amber:grammar — Streaming Structured Output & Token Grammar Engine

code
import { parsePartialJSON, createStreamDecoder, parseSSEChunk, createGrammar, createChoiceGrammar, createRegexGrammar, createJSONGrammar } from 'amber:grammar';
MethodSignatureDescription
parsePartialJSON(text)(input: string) => anyMicrosecond-speed auto-repair for unclosed strings, open brackets ], and open braces }.
createStreamDecoder(opts?)(opts?: { onChunk?: (parsed, isComplete) => void }) => StreamDecoderStatefully accumulates text chunks and emits incrementally updated JSON snapshots.
parseSSEChunk(chunk)(chunk: string) => SSEMessage[]Parses raw Server-Sent Events stream chunks with built-in .json() accessor.
createChoiceGrammar(choices)(choices: string[]) => GrammarToken grammar restricting LLM generation to fixed string alternatives.
createRegexGrammar(pattern)(pattern: string | RegExp) => GrammarToken grammar enforcing regular expression conformance.
createJSONGrammar(schema?)(schema?: any) => GrammarToken grammar verifying progressive valid JSON syntax.

1.4 amber:checkpoint — Agent State Checkpoint & Time-Travel Snapshotting

code
import { createCheckpointManager, getDefaultManager, save, restore, get, list, diff, fork, clear } from 'amber:checkpoint';
MethodSignatureDescription
save(idOrOptions, state?, metadata?)(id?: string, state?: any, meta?: object) => CheckpointCaptures an immutable deep clone of current agent state linked to lineage tree.
restore(id)(id: string) => anyRestores agent state to a historical checkpoint for clean fault rollback.
diff(fromId, toId)(fromId: string, toId: string) => StateDiffStructural delta identifying { added, modified: { from, to }, deleted }.
fork(fromId, branchName)(fromId: string, branchName: string) => CheckpointManagerCreates speculative execution branch (Tree-of-Thought) without mutating main branch.
persist(kvStore, prefix?)(kvStore: KVStore, prefix?: string) => numberFlushes all checkpoints to a durable amber:kv Write-Ahead Log.
restoreFromKV(kvStore, prefix?)(kvStore: KVStore, prefix?: string) => numberRestores complete checkpoint lineage from a amber:kv store instance.

1.5 amber:kv — Persistent Key-Value & Durable State Engine

code
import { open, openInMemory, KVStore } from 'amber:kv';
MethodSignatureDescription
open(pathOrOptions)(options: string | { path: string }) => KVStoreOpens durable disk-backed key-value store with append-only Write-Ahead Log (WAL).
openInMemory()() => KVStoreOpens ultra-low latency in-memory transient key-value store.
get(key)(key: string) => anyReads key; returns undefined if key does not exist or has expired.
set(key, value, ttlMs?)(key: string, value: any, ttlMs?: number) => thisWrites key-value pair with optional automatic millisecond TTL expiration.
delete(key)(key: string) => booleanDeletes key from memory and appends tombstone to WAL.
incr(key, delta?)(key: string, delta?: number) => numberAtomic integer increment operation.
scan(options?)(options?: { prefix?: string, limit?: number }) => Array<{ key, value }>High-performance prefix range scanning.
batch(operations)(ops: Array<{ type: 'set' | 'delete', key, value?, ttlMs? }>) => thisExecutes multiple write operations in a single atomic transaction.
compact()() => booleanPrunes expired entries and compacts WAL log file to minimize disk footprint.

1.6 amber:tools — Agent Tool Auto-Synthesis & OpenAPI Schema Compiler

code
import { compileSchemaTool, fromOpenAPI, parseToolCalls, registerTools, AgentTool } from 'amber:tools';
MethodSignatureDescription
compileSchemaTool(spec)(spec: ToolDefinition) => AgentToolCompiles JSON Schema into validated callable AgentTool.
fromOpenAPI(spec, options?)(spec: object | string, opts?: OpenAPIOptions) => AgentTool[]Automatically synthesizes executable tools from OpenAPI 3.x specifications.
parseToolCalls(llmOutput)(llmOutput: string | object) => ToolCall[]Robustly extracts tool calls from JSON, arrays, markdown code blocks, and tags.
registerTools(pipeline, tools)(pipeline: AgentPipeline, tools: AgentTool[]) => AgentPipelineBinds synthesized tools directly into an AgentPipeline.

1.7 amber:sandbox — Hardened Micro-Enclaves & Real-time Audit Logging

code
import { createEnclave, startAuditLog, stopAuditLog, getAuditLogPath, isEnabled, enable, disable } from 'amber:sandbox';
MethodSignatureDescription
createEnclave(policyOrCode, opts?)(policy?: EnclavePolicy) => SandboxEnclaveCreates a zero-privilege micro-enclave with memory, timeout, and whitelist limits.
startAuditLog(path)(path: string) => booleanStreams real-time compliance JSONL audit logs for all security decisions.
stopAuditLog()() => booleanFlushes and finalizes active compliance audit log.
getAuditLogPath()() => string | nullQueries the currently active audit log file path.

1.8 amber:replay — Deterministic Agent Replay Engine

code
import { startRecording, stopRecording, loadTrace, step, isRecording, isReplaying, getTraceStats } from 'amber:replay';
MethodSignatureDescription
startRecording(opts)(opts: { script?: string, outputPath?: string }) => voidArms engine to record non-deterministic inputs into .amber-trace.json.
stopRecording(path?)(path?: string) => AgentTraceFinalizes recording and exports trace file.
loadTrace(traceOrPath)(trace: string | object) => voidLoads trace and arms offline deterministic replay mode.
step(name, input, fn)(name: string, input: any, fn: (input) => any) => anyRecords during live run; intercepts and replays cached outputs during replay.

1.9 amber:weights — Native GGUF & SafeTensors Model Weights Loader

code
import { readGGUFMetadata, readSafeTensorsMetadata, loadTensor } from 'amber:weights';
MethodSignatureDescription
readGGUFMetadata(filePath)(path: string) => GGUFMetadataSub-millisecond inspection of GGUF v2/v3 tensor headers and KV pairs.
readSafeTensorsMetadata(filePath)(path: string) => SafeTensorsMetadataInspects HuggingFace SafeTensors file headers.
loadTensor(filePath, tensorName)(path: string, name: string) => LoadedTensorMemory-maps tensor weights zero-copy into typed ArrayBuffer.

1.10 amber:security & amber:permissions — Enterprise Capability Security

code
import { permissions, createSandboxPolicy, attenuate } from 'amber:security';
MethodSignatureDescription
permissions.query(descriptor)(desc: PermissionDescriptor) => Promise<PermissionStatus>Queries whether specific I/O permission is currently granted.
permissions.has(descriptor)(desc: PermissionDescriptor) => booleanSynchronous boolean capability inspection.
permissions.revoke(descriptor)(desc: PermissionDescriptor) => booleanDrops privileged access dynamically at runtime.
permissions.list()() => PermissionRulesDumps currently active allow/deny rule sets.
attenuate(base, restricted)(base: Policy, restricted: Policy) => PolicyComputes mathematical least-privilege intersection of permissions.

code
import { Database } from 'amber:db';
import { VectorDB } from 'amber:vector';

// SQLite
const db = Database.open('./data.db');
db.exec('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)');
const stmt = db.prepare('INSERT INTO users (name) VALUES (?)');
stmt.run('Alice');

// Vector Engine
const vecDb = VectorDB.create({ dimension: 384, metric: 'cosine' });
vecDb.insert('doc-1', embeddingArray, { title: 'Introduction' });
const results = vecDb.search(queryEmbedding, { limit: 5 });

1.12 amber:std — Modern Standard Library

code
import { config } from 'amber:std/dotenv';
import { colors, table } from 'amber:std/cli';
import { walkDir, ensureDir } from 'amber:std/fs';
import { uuid, signJwt, verifyJwt } from 'amber:std/crypto';
import { assert, assertEquals } from 'amber:std/assert';

config({ path: '.env' });
console.log(colors.green('Environment loaded successfully'));

1.13 amber:wasm, amber:ffi & amber:pool — Native Interop & Concurrency

code
// WebAssembly 2.0 Shared Memory Bridge (amber:wasm)
import { compile, instantiate, MemoryView } from 'amber:wasm';

// Native C ABI FFI (amber:ffi)
import { dlopen, CString, types } from 'amber:ffi';
const libm = dlopen('libm.dylib', { cos: { args: [types.f64], returns: types.f64 } });

// Multi-Tenant IsolatePool (amber:pool)
import { IsolatePool } from 'amber:pool';
const pool = new IsolatePool({ size: 4, memoryLimitMb: 128 });
const result = await pool.execute('2 + 3');

2. Node.js Core Modules Reference (node:*)

Amber passes 51/51 official Node.js conformance test suites with hardware SIMD acceleration:

ModuleSpecifierPrimary APIsStatus
node:fsfs, node:fs, node:fs/promisesreadFile, writeFile, stat, readdir, mkdir, rm, createReadStream, createWriteStream✅ 100%
node:pathpath, node:pathjoin, resolve, dirname, basename, extname, normalize, isAbsolute✅ 100%
node:cryptocrypto, node:cryptocreateHash, createHmac, randomBytes, randomUUID, pbkdf2, AES-GCM/CBC✅ 100%
node:bufferbuffer, node:bufferBuffer.from, Buffer.alloc, Buffer.concat, isBuffer, toString (SIMD accelerated)✅ 100%
node:eventsevents, node:eventsEventEmitter, on, once, emit, removeListener, listenerCount✅ 100%
node:streamstream, node:streamReadable, Writable, Transform, pipeline, finished✅ 100%
node:httphttp, node:httpcreateServer, IncomingMessage, ServerResponse, request, get, Keep-Alive✅ 100%
node:processprocess, node:processargv, env, cwd(), exit(), uptime(), memoryUsage(), nextTick()✅ 100%
node:timerstimers, node:timerssetTimeout, clearTimeout, setInterval, clearInterval, setImmediate✅ 100%
node:urlurl, node:urlURL, URLSearchParams, fileURLToPath, pathToFileURL✅ 100%
node:dnsdns, node:dnslookup, resolve, resolve4, resolve6 asynchronous DNS queries✅ 100%
node:perf_hooksperf_hooks, node:perf_hooksperformance.now(), PerformanceObserver✅ 100%

3. Web Standards API Surface

Universally accessible on globalThis without import:

Web APIDescriptionGlobal Access
fetch()Universal network request interface with streaming bodiesglobalThis.fetch
Headers, Request, ResponseFetch API primitivesglobalThis.*
URL, URLSearchParamsWHATWG URL specification parserglobalThis.*
WebSocketStandard real-time full-duplex client socketglobalThis.WebSocket
crypto.subtle (Web Crypto)Cryptography: digest, encrypt, decrypt, sign, verifyglobalThis.crypto.subtle
ReadableStream, WritableStreamWHATWG Streams standard for data pipelinesglobalThis.*
CompressionStreamNative streaming gzip and deflate compressionglobalThis.CompressionStream
Blob, File, FormDataBinary and multipart containersglobalThis.*
structuredClone()Native deep-cloning for complex object graphsglobalThis.structuredClone
TextEncoder, TextDecoderHigh-performance UTF-8 conversionglobalThis.*
WorkerMulti-threaded Web Worker executionglobalThis.Worker