Host API Reference

Host API Reference

Complete Example

import {
  parse,
  execute,
  createRuntimeContext,
  callable,
  AbortError,
  type RillValue,
} from '@rcrsr/rill';

const script = `
  $config.greeting -> prompt() => $response
  $response
`;

const controller = new AbortController();

const ctx = createRuntimeContext({
  variables: {
    config: {
      greeting: 'Say hello in French',
    },
    utils: {
      // Property-style callable (computed property)
      timestamp: callable(() => Date.now(), true),
      // Regular callable
      format: callable((args) => {
        const [template, ...values] = args;
        return String(template).replace(/\{\}/g, () =>
          String(values.shift() ?? '')
        );
      }),
    },
  },

  functions: {
    prompt: {
      params: [{ name: 'text', type: 'string' }],
      fn: async (args, ctx, location) => {
        console.log(`[prompt at line ${location?.line}]`);
        return await callLLM(args[0]);
      },
    },
  },

  callbacks: {
    onLog: (value) => console.log('[log]', value),
  },

  observability: {
    onStepStart: (e) => console.log(`Step ${e.index + 1}...`),
    onStepEnd: (e) => console.log(`Done (${e.durationMs}ms)`),
  },

  timeout: 30000,
  signal: controller.signal,
});

try {
  const ast = parse(script);
  const result = await execute(ast, ctx);
  console.log('Result:', result.value);
  console.log('Variables:', result.variables);
} catch (err) {
  if (err instanceof AbortError) {
    console.log('Cancelled');
  } else {
    throw err;
  }
}

API Reference

Exports

// Parsing
export { parse, ParseError, tokenize, LexerError };

// Execution
export { execute, createRuntimeContext, createStepper };
export type { RuntimeContext, RuntimeOptions, ExecutionResult };
export type { ExecutionStepper, StepResult };

// Callable types
export { callable, isCallable, isScriptCallable, isRuntimeCallable, isApplicationCallable };
export type { RillCallable, ScriptCallable, RuntimeCallable, ApplicationCallable, CallableFn };

// Host function types
export type { HostFunctionDefinition, HostFunctionParam, RillFunctionReturnType };
export { validateHostFunctionArgs };

// Value types
export type { RillValue, RillArgs };

// Introspection
export { getFunctions, getLanguageReference, getDocumentationCoverage };
export type { FunctionMetadata, ParamMetadata, DocumentationCoverageResult };

// Version information
export { VERSION, VERSION_INFO };
export type { VersionInfo };

// Callbacks
export type { RuntimeCallbacks, ObservabilityCallbacks };
export type { StepStartEvent, StepEndEvent, FunctionCallEvent, FunctionReturnEvent };
export type { CaptureEvent, ErrorEvent };

// Errors
export { RillError, RuntimeError, ParseError, AbortError, TimeoutError, AutoExceptionError };
export { RILL_ERROR_CODES };
export type { RillErrorCode };

// Utilities
export { isArgs, isDict, isReservedMethod, RESERVED_DICT_METHODS };
export type { SourceLocation, SourceSpan };

// Control flow (for advanced use)
export { BreakSignal, ReturnSignal };

// Extension contracts
export type { KvExtensionContract, FsExtensionContract, LlmExtensionContract, VectorExtensionContract, SchemaEntry };

Extension Contracts

KvExtensionContract

Contract type for key-value extension implementations. Backend authors use this type to verify compile-time compatibility.

type KvExtensionContract = {
  readonly get: HostFunctionDefinition;
  readonly get_or: HostFunctionDefinition;
  readonly set: HostFunctionDefinition;
  readonly merge: HostFunctionDefinition;
  readonly delete: HostFunctionDefinition;
  readonly keys: HostFunctionDefinition;
  readonly has: HostFunctionDefinition;
  readonly clear: HostFunctionDefinition;
  readonly getAll: HostFunctionDefinition;
  readonly schema: HostFunctionDefinition;
  readonly mounts: HostFunctionDefinition;
  readonly dispose?: (() => void | Promise<void>) | undefined;
};

Required Functions (11 total):

FunctionSignatureReturnsDescription
get(mount: string, key: string)RillValueRetrieve value or schema default
get_or(mount: string, key: string, fallback: RillValue)RillValueRetrieve value with fallback
set(mount: string, key: string, value: RillValue)booleanStore value with validation
merge(mount: string, key: string, partial: Record<string, RillValue>)booleanMerge dict properties
delete(mount: string, key: string)booleanRemove key
keys(mount: string)string[]List all keys in mount
has(mount: string, key: string)booleanCheck key existence
clear(mount: string)booleanRemove all keys
getAll(mount: string)Record<string, RillValue>Retrieve all key-value pairs
schema(mount: string)RillValue[]Get mount schema metadata
mounts()RillValue[]List all configured mounts

Usage:

import type { KvExtensionContract } from '@rcrsr/rill';
import { createMyKvBackend } from './my-kv-backend';

// Type-check backend implementation
const backend: KvExtensionContract = createMyKvBackend({ /* config */ });

FsExtensionContract

Contract type for filesystem extension implementations. Backend authors use this type to verify compile-time compatibility.

type FsExtensionContract = {
  readonly read: HostFunctionDefinition;
  readonly write: HostFunctionDefinition;
  readonly append: HostFunctionDefinition;
  readonly list: HostFunctionDefinition;
  readonly find: HostFunctionDefinition;
  readonly exists: HostFunctionDefinition;
  readonly remove: HostFunctionDefinition;
  readonly stat: HostFunctionDefinition;
  readonly mkdir: HostFunctionDefinition;
  readonly copy: HostFunctionDefinition;
  readonly move: HostFunctionDefinition;
  readonly mounts: HostFunctionDefinition;
  readonly dispose?: (() => void | Promise<void>) | undefined;
};

Required Functions (12 total):

FunctionSignatureReturnsDescription
read(mount: string, path: string)stringRead file content
write(mount: string, path: string, content: string)stringWrite file content
append(mount: string, path: string, content: string)stringAppend to file
list(mount: string, path?: string)RillValue[]List directory entries
find(mount: string, pattern?: string)RillValue[]Find files by pattern
exists(mount: string, path: string)booleanCheck file/directory existence
remove(mount: string, path: string)booleanDelete file/directory
stat(mount: string, path: string)Record<string, RillValue>Get file metadata
mkdir(mount: string, path: string)booleanCreate directory
copy(mount: string, src: string, dest: string)booleanCopy file/directory
move(mount: string, src: string, dest: string)booleanMove file/directory
mounts()RillValue[]List all configured mounts

Usage:

import type { FsExtensionContract } from '@rcrsr/rill';
import { createMyFsBackend } from './my-fs-backend';

// Type-check backend implementation
const backend: FsExtensionContract = createMyFsBackend({ /* config */ });

SchemaEntry

Type for key-value store schema definitions. Used in KvExtensionContract backends to define type constraints and defaults.

export interface SchemaEntry {
  type: 'string' | 'number' | 'bool' | 'list' | 'dict';
  default: RillValue;
  description?: string;
}

Fields:

FieldTypeRequiredDescription
type'string' | 'number' | 'bool' | 'list' | 'dict'YesValue type constraint
defaultRillValueYesDefault value if key missing
descriptionstringNoHuman-readable description

Usage:

import type { SchemaEntry } from '@rcrsr/rill';

const schema: Record<string, SchemaEntry> = {
  name: { type: 'string', default: '', description: 'User name' },
  age: { type: 'number', default: 0, description: 'User age in years' },
  active: { type: 'bool', default: true },
};

LlmExtensionContract

Contract type for LLM extension implementations. Backend authors use this type to verify compile-time compatibility.

type LlmExtensionContract = {
  readonly message: HostFunctionDefinition;
  readonly messages: HostFunctionDefinition;
  readonly embed: HostFunctionDefinition;
  readonly embed_batch: HostFunctionDefinition;
  readonly tool_loop: HostFunctionDefinition;
  readonly dispose?: (() => void | Promise<void>) | undefined;
};

Required Functions (5 total):

FunctionSignatureReturnsDescription
message(text: string, options?: dict)dictSend single message
messages(messages: list, options?: dict)dictMulti-turn conversation
embed(text: string)vectorGenerate embedding vector
embed_batch(texts: list)listBatch embeddings
tool_loop(prompt: string, options?: dict)dictTool use orchestration

Usage:

import type { LlmExtensionContract } from '@rcrsr/rill';
import { createMyLlmBackend } from './my-llm-backend';

// Type-check backend implementation
const backend: LlmExtensionContract = createMyLlmBackend({ /* config */ });

VectorExtensionContract

Contract type for vector database extension implementations. Backend authors use this type to verify compile-time compatibility.

type VectorExtensionContract = {
  readonly upsert: HostFunctionDefinition;
  readonly upsert_batch: HostFunctionDefinition;
  readonly search: HostFunctionDefinition;
  readonly get: HostFunctionDefinition;
  readonly delete: HostFunctionDefinition;
  readonly delete_batch: HostFunctionDefinition;
  readonly count: HostFunctionDefinition;
  readonly create_collection: HostFunctionDefinition;
  readonly delete_collection: HostFunctionDefinition;
  readonly list_collections: HostFunctionDefinition;
  readonly describe: HostFunctionDefinition;
  readonly dispose?: (() => void | Promise<void>) | undefined;
};

Required Functions (11 total):

FunctionSignatureReturnsDescription
upsert(id: string, vector: vector, metadata?: dict)dictInsert or update vector
upsert_batch(items: list)dictBatch insert/update
search(vector: vector, options?: dict)listSearch k nearest neighbors
get(id: string)dictFetch vector by ID
delete(id: string)dictDelete vector by ID
delete_batch(ids: list)dictBatch delete
count()numberCount vectors in collection
create_collection(name: string, options?: dict)dictCreate collection
delete_collection(name: string)dictDelete collection
list_collections()listList all collections
describe()dictGet collection metadata

Usage:

import type { VectorExtensionContract } from '@rcrsr/rill';
import { createMyVectorBackend } from './my-vector-backend';

// Type-check backend implementation
const backend: VectorExtensionContract = createMyVectorBackend({ /* config */ });

See Also