Host API Reference

Host API Reference

Complete Example

Extension Factory Pattern (Recommended)

import {
  parse,
  execute,
  createRuntimeContext,
  toCallable,
  RuntimeHaltSignal,
  type ExtensionFactoryResult,
} from '@rcrsr/rill';

function createMyExtension(config: { model: string }): ExtensionFactoryResult {
  return {
    value: {
      prompt: toCallable({
        signature: 'fn(text: string):string',
        fn: async (args) => await callLLM(args.text, config.model),
        description: 'Send a prompt to the LLM',
      }),
    },
  };
}

const ext = createMyExtension({ model: 'claude-3-5-sonnet' });
const controller = new AbortController();

const ctx = createRuntimeContext({
  variables: { llm: ext.value },
  callbacks: { onLog: (value) => console.log('[log]', value) },
  timeout: 30000,
  signal: controller.signal,
});

try {
  const ast = parse('llm.prompt("Hello")');
  const result = await execute(ast, ctx);
  console.log('Result:', result.result);
} catch (err) {
  if (err instanceof RuntimeHaltSignal) {
    console.log('Cancelled');
  } else {
    throw err;
  }
} finally {
  await ext.dispose?.();
}

Direct Registration (Legacy)

import {
  parse,
  execute,
  createRuntimeContext,
  callable,
  toCallable,
  RuntimeHaltSignal,
} 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),
      format: toCallable({
        signature: 'fn(template: string, value: string):any',
        fn: (args) =>
          String(args.template).replace(/\{\}/g, () => String(args.value)),
      }),
    },
  },

  functions: {
    prompt: {
      signature: 'fn(text: string):string',
      fn: async (args, ctx, location) => {
        console.log(`[prompt at line ${location?.line}]`);
        return await callLLM(args.text);
      },
      description: 'Send a prompt to the LLM and return the response',
    },
  },

  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.result);
} catch (err) {
  if (err instanceof RuntimeHaltSignal) {
    console.log('Cancelled');
  } else {
    throw err;
  }
}

API Reference

Exports

// Parsing
export { parse, parseWithRecovery, parseTypeRef, createParserState, tokenize, LexerError };
export { KEYWORDS };
export type { ParseResult, RecoveryErrorNode, ErrorNode, ParseOptions };

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

// Execution context (advanced use)
export { createChildContext, getVariable, hasVariable };
export { getCallStack, pushCallFrame, popCallFrame };
export { invokeCallable };
export type { ControlFlowContext, DispatchContext, LifecycleContext, MetadataContext, ResolverContext, ScopeContext };
export type { FieldComparisonCallbacks, CallFrame };

// Resolvers
export { moduleResolver, extResolver, contextResolver };
export type { SchemeResolver, ResolverResult };

// Dispatch-boundary policy
export { createConfigFilterResolver, resolvePolicy, getExtensionIdentity };
export type { Filter, FilterResolver, ExtensionIdentity };
export type { PolicyConfig, ExtensionMethodPolicy, MethodPolicyRule, ResolvedPolicy };

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

// Host function types
export type { RillParam, RillFunction };
export type { TypeStructure };
export type { TypeDefinition, TypeProtocol };
export type { RillTypeValue };
export type { MarshalOptions };
export { marshalArgs };

// Stream helpers
export { createRillStream, isRillStream };
export type { RillStream };

// Value types
export type { RillValue };
export type { RillAtomValue, RillDatetime, RillDuration, RillFieldDef, RillIterator, RillMap, RillMapKey, RillTuple, RillVector };
export type { TraceKind };

// Value conversion
export { toNative };
export type { NativeResult, NativeValue, NativeArray, NativeMap, NativePlainObject };

// Value construction and inspection
export { copyValue, createMap, createOrdered, createTuple, createVector };
export {
  getStatus,
  isAtom,
  isDatetime,
  isDuration,
  isInvalid,
  isIterator,
  isMap,
  isStream,
  isTuple,
  isTypeValue,
  isVacant,
  isVector,
};
export {
  commonType,
  compareStructuredFields,
  formatFieldKey,
  formatDefaultLiteral,
  formatRillLiteral,
  formatStructure,
  inferStructure,
  structureEquals,
  structureMatches,
};
export { BUILT_IN_TYPES, deepEquals, deserializeValue, formatValue, inferType, serializeValue };
export { anyTypeValue, isEmpty, structureToTypeValue };
export { formatHalt };

// Field descriptors
export { buildFieldDescriptor };
export type { ConfigFieldDescriptor };

// Introspection
export { formatTypeRef, getFunctions, getLanguageReference, getDocumentationCoverage, introspectHandlerFromAST };
export type { FunctionMetadata, ParamMetadata, DocumentationCoverageResult, HandlerMetadataStatic, HandlerParamStatic };

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

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

// Errors
export { RillError, RuntimeError, ParseError, TimeoutError };
export { formatRillError, formatRillErrorJson, createError, renderMessage, getHelpUrl };
export { ERROR_HANDLING_PATTERNS };
export type { ErrorHandlingExample, ErrorHandlingPattern, ErrorExample, ErrorRegistry };
export type { ErrorCategory, ErrorDefinition, ErrorSeverity };
export type { FormatErrorOptions, FormatErrorJsonOptions, SourceMap };

// Utilities
export { isDict };
export type { SourceLocation, SourceSpan };

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

// Syntax highlighting
export { TOKEN_HIGHLIGHT_MAP };
export type { HighlightCategory };

// Error registry
export { ERROR_REGISTRY };

// Language and tooling metadata
export { BUILTIN_ATOMS, BUILTIN_FUNCTIONS, BUILTIN_METHODS, KEYWORDS, TOKEN_TYPES, VALID_TYPE_NAMES };
export type { Token, TokenType };

// Extension types
export type { ExtensionFactoryResult, ExtensionFactory, ExtensionEvent, ExtensionManifest, ExtensionConfigSchema };
export type { ExtensionFactoryCtx };
export type { RillFunctionShorthand, RillFunctionDefinition };

// Extension utilities
export { toCallable, createTestContext, emitExtensionEvent };
export { ExtensionBindingError };

// Atoms (name-based; read-only access at top level)
export { resolveAtom, atomName };
export type { InvalidateMeta, TraceFrame };

// AST node types
export { isPipeChainNode };
export type {
  AnnotatedExprNode,
  AnnotatedStatementNode,
  AnnotationAccessNode,
  AnnotationArg,
  ArithHead,
  AssertNode,
  ASTNode,
  AtomLiteralNode,
  BinaryExprNode,
  BinaryOp,
  BlockNode,
  BodyNode,
  BoolLiteralNode,
  BracketAccess,
  BreakNode,
  CaptureNode,
  ChainTerminator,
  ClosureCallNode,
  ClosureNode,
  ClosureParamNode,
  ConditionalNode,
  DestructNode,
  DestructPatternNode,
  DestructureNode,
  DictEntryNode,
  DictKeyComputed,
  DictKeyVariable,
  DictLiteralNode,
  DictNode,
  DoWhileLoopNode,
  ExistenceCheck,
  ExpressionNode,
  FieldAccess,
  FieldAccessAnnotation,
  FieldAccessLiteral,
  FieldAccessVariable,
  FnTypeNode,
  FrontmatterNode,
  GroupedExprNode,
  GuardBlockNode,
  HostCallNode,
  InterpolationNode,
  InvokeNode,
  ListLiteralNode,
  ListSpreadNode,
  LiteralNode,
  MethodCallNode,
  NamedArgNode,
  NumberLiteralNode,
  OrderedLiteralNode,
  PartialExpressionNode,
  PassNode,
  PipeChainNode,
  PipeInvokeNode,
  PipeTargetNode,
  PostfixExprNode,
  PrimaryNode,
  PropertyAccess,
  RetryBlockNode,
  ReturnNode,
  ScriptNode,
  SimplePrimaryNode,
  SliceBoundNode,
  SliceNode,
  SpreadArgNode,
  StatementNode,
  StatusProbeNode,
  StringLiteralNode,
  TimeoutBlockNode,
  TupleLiteralNode,
  TypeAssertionNode,
  TypeCheckNode,
  TypeConstructorNode,
  TypeNameExprNode,
  UnaryExprNode,
  UseExprNode,
  UseIdentifier,
  VariableNode,
  WhileLoopNode,
  YieldNode,
};
export type { NodeType };
export type { FieldArg, RillTypeName, TypeRef };

// AST traversal
export { nodeAtPosition, walkAst };
export { codeBlockShape, unnamedParamsRead, isUnnamedParamName };
export type { CodeBlockShape };

Runtime error sites migrated to the halt builders throw a fatal RuntimeHaltSignal (catchable: false, code on errorId) instead of a RuntimeError when reached outside execute() and createStepper(), for example direct .fn calls on BUILTIN_METHODS entries. Argument-binding errors from invokeCallable (RILL-R001, RILL-R044, RILL-R045) still throw RuntimeError, so hosts calling it directly handle both.

Hosts cannot add atoms or error codes; see BUILTIN_ATOMS.

Migration note: KvExtensionContract and FsExtensionContract types moved to @rcrsr/rill-ext-kv and @rcrsr/rill-ext-fs in the rill-ext repository.

NativeResult

toNative(value: RillValue): NativeResult converts any rill value to a host-consumable structure.

interface NativeResult {
  /** Base rill type name — matches RillTypeName, or "iterator" for lazy sequences */
  rillTypeName: string;
  /** Full structural signature from formatStructure,
   *  e.g. "list(number)", "dict(a: number, b: string)", "fn(x: number):string" */
  rillTypeSignature: string;
  /** JS-native representation. Always populated — never undefined.
   *  Non-native types produce descriptor objects. */
  value: NativeValue;
}

type NativeValue =
  | string | number | boolean | null
  | NativeArray | NativePlainObject | NativeMap;

A value returned to the host that holds a code block reports the entry as the signature fn():any and does not run it. Passing a collection that holds a code block to a host function as an argument halts #TYPE_MISMATCH naming the entry.

rillTypeName and rillTypeSignature describe the own type of the value, never a declared type.

A map converts to a JS Map (NativeMap); an atom key becomes its name string. A JS Map returned by a host function converts back to a rill map when its keys are scalars of one kind; keys of mixed kinds or a non-scalar key halt RILL-R085. A dict converts to a plain object with string keys; a single number or boolean key in the source literal is already the string of its spelling, and a multi-key list element is a string.

Descriptor shapes for non-native types

Rill typevalue shape
fn{ signature: string }
vector{ model: string, dimensions: number }
type{ name: string, signature: string }
iterator{ done: boolean }
stream{ done: boolean }
datetime{ unix: number, iso: string }
duration{ months: number, ms: number }
atom{ __rill_atom: true, atom: { __rill_atom: true, name: string } }

See Host Integration for conversion examples and migration guidance.


createRuntimeContext

createRuntimeContext(options: RuntimeOptions): RuntimeContext builds the execution context passed to execute(). See Host Integration for the full RuntimeOptions field reference.

Datetime Fields

Two fields control datetime behavior in scripts.

FieldTypeDefaultDescription
timezonenumber0 (UTC)Numeric hour offset for .local_* properties on datetime values
nowMsnumberundefinedFixed unix millisecond timestamp for deterministic now() calls

timezone accepts numeric offsets only (e.g., -5 for UTC-5, 5.5 for UTC+5:30). IANA timezone name resolution (e.g., "America/New_York") requires datetime-extension.

nowMs pins now() to a fixed timestamp. Scripts that call now() without nowMs return the wall-clock time at execution.

import { createRuntimeContext } from '@rcrsr/rill';

// Fixed timestamp for deterministic test execution
const ctx = createRuntimeContext({
  timezone: -5,
  nowMs: new Date('2024-06-15T12:00:00Z').getTime(),
});

// Scripts using now() return 2024-06-15T12:00:00Z
// Scripts using .local_date return date in UTC-5 (2024-06-15)

TOKEN_HIGHLIGHT_MAP

TOKEN_HIGHLIGHT_MAP maps each TokenType to a HighlightCategory. Use this to build syntax highlighters for rill scripts.

import { TOKEN_HIGHLIGHT_MAP, tokenize } from '@rcrsr/rill';

const tokens = tokenize(source);
for (const token of tokens) {
  const category = TOKEN_HIGHLIGHT_MAP.get(token.type);
  if (category) applyHighlight(token, category);
}

HighlightCategory Values

CategoryDescription
keywordLanguage keywords and collection keyword prefixes
operatorAll binary and unary operators
stringString literals
numberNumeric literals
boolBoolean literals (true, false)
commentLine comments
variableNameVariables ($), identifiers, _
functionNameMethod names after a dot (METHOD_NAME, e.g. len in .len)
punctuationStructural characters (., ,, :)
bracketDelimiters ((, ), {, }, [, ])
metaAtom literals (#NAME) and frontmatter delimiters (---)

Token Changes in Explicit-Literal Syntax

The explicit-literal-syntax initiative (replacing sigil-based forms with keyword-prefixed forms) changed which tokens exist:

7 tokens added:

TokenCategorySyntax
LIST_LBRACKETkeywordlist[
DICT_LBRACKETkeyworddict[
TUPLE_LBRACKETkeywordtuple[
ORDERED_LBRACKETkeywordordered[
DESTRUCT_LANGLEkeyworddestruct<
SLICE_LANGLEkeywordslice<
MAP_LBRACKETkeywordmap[

MAP_LBRACKET arrived with the map[...] literal, not with the sigil replacement.

2 tokens removed:

TokenWasReplaced by
STAR_LTDestruct sigil (*<)DESTRUCT_LANGLE
SLASH_LTSlice sigil (/<)SLICE_LANGLE

Highlighters that mapped the removed tokens must update to the replacement tokens.

AT remains in TOKEN_HIGHLIGHT_MAP as operator for the @ while-loop operator. Only the chain-sigil use of @ was removed; the token itself was not.

ERROR_REGISTRY

ERROR_REGISTRY provides structured access to all error definitions. Use this to build diagnostic tools or format error messages with links.

import { ERROR_REGISTRY, getHelpUrl } from '@rcrsr/rill';

const entry = ERROR_REGISTRY.get('RILL-P007');
console.log(entry?.description);  // "Keyword not adjacent to opener, or extra spread"
console.log(getHelpUrl('RILL-P007', '0.4.1'));  // "https://github.com/rcrsr/rill/blob/v0.4.1/docs/ref-errors.md#rill-p007"

getHelpUrl(errorId, version) is a standalone function, not a method on ERROR_REGISTRY. It returns https://github.com/rcrsr/rill/blob/v{version}/docs/ref-errors.md#{lowercased-errorId}, or '' if errorId or version fails validation.

Methods

MethodReturnsDescription
get(code)ErrorDefinition | undefinedLook up an error by code
has(code)booleanWhether an error code is registered
sizenumberTotal count of registered error definitions
entries()IterableIterator<[string, ErrorDefinition]>Iterate all [code, definition] pairs

Error Code Ranges

RangeCategory
RILL-L001 – RILL-L005Lexer errors
RILL-P001 – RILL-P022Parse errors (non-contiguous)
RILL-R001 – RILL-R083Runtime errors (non-contiguous)
RILL-C001 – RILL-C004Check errors

Ranges list outer bounds only; gaps exist within each range. See Error Reference for the authoritative list of assigned codes and full error descriptions and resolution strategies.

parseWithRecovery

parseWithRecovery(source: string): ParseResult parses rill source for IDE and tooling scenarios. Use this instead of parse() when you need diagnostics for incomplete or invalid source, such as while a user is still typing.

import { parseWithRecovery } from '@rcrsr/rill';

const result = parseWithRecovery(source);
if (!result.success) {
  console.log('Errors:', result.errors);
}
// result.ast may contain RecoveryErrorNode or PartialExpressionNode entries
FieldTypeDescription
astScriptNodeThe parsed AST, possibly containing RecoveryErrorNode or PartialExpressionNode entries
errorsParseError[]Parse errors collected during recovery; empty when success is true
successbooleantrue when parsing completed without errors

parseWithRecovery never throws. Malformed or pathological input, including deeply nested brackets that would otherwise exceed stack-depth limits, returns { ast, errors, success: false } instead of raising an exception. Callers do not need a try/catch around this function.

See RecoveryErrorNode and PartialExpressionNode for the recovery-specific AST node shapes.

nodeAtPosition

nodeAtPosition(root: ASTNode, offset: number): ASTNode | null finds the deepest AST node at a source offset. Use this to build hover, go-to-definition, or completion tooling.

import { nodeAtPosition, parse } from '@rcrsr/rill';

const ast = parse(source);
const node = nodeAtPosition(ast, 42);
if (node !== null) {
  console.log('Node at offset 42:', node.type);
}
Parameter/ReturnTypeDescription
rootASTNodeSubtree to search, typically a ScriptNode from parse()
offsetnumber0-based absolute character offset, matching SourceLocation.offset
ReturnsASTNode | nullThe deepest node whose span contains offset, or null if none does

nodeAtPosition uses half-open span containment: offset === span.start.offset is inside, offset === span.end.offset is not. An out-of-range offset returns null. The search descends through span-less field-access and dict-key segments to reach their AST node children, so a match can surface a node nested inside those segments rather than the segment itself. A VariableNode span covers only the leading $name token. nodeAtPosition still returns it when offset falls on an access-chain segment like .field or [0].

See Field access and dict key spans for the span rules governing those segments.

walkAst

walkAst(root: ASTNode, visit: (node: ASTNode) => void): void performs a pre-order depth-first traversal of an AST, calling visit once per node. Use this to build linters, analyzers, or codegen tools that need to inspect every node.

import { walkAst, parse } from '@rcrsr/rill';

const ast = parse(source);
const types: string[] = [];
walkAst(ast, (node) => {
  types.push(node.type);
});
ParameterTypeDescription
rootASTNodeSubtree to traverse, typically a ScriptNode from parse()
visit(node: ASTNode) => voidCallback invoked once for every node, including recovery nodes

walkAst visits every reachable ASTNode, including RecoveryErrorNode and PartialExpressionNode entries. Span-less field-access and dict-key segments are descended through but never passed to visit directly.

See AST Node Types for the full set of node shapes visit may receive.


codeBlockShape

codeBlockShape(node: ASTNode): CodeBlockShape | undefined recognizes a code block and returns { block: BlockNode }. It returns undefined for anything else.

Recognized nodeCondition
BlockAlways recognized; the base case
PostfixExprCarries no method call, default value, or existence check; its primary is recognized
PipeChainCarries no pipe and no terminator; its head is recognized
TypeAssertion, TypeCheckHas an operand that is recognized
AnnotatedExprWraps a recognized node
import { codeBlockShape, parse, walkAst } from '@rcrsr/rill';

const statement = parse(source).statements[0];
const shape =
  statement?.type === 'Statement'
    ? codeBlockShape(statement.expression)
    : undefined;
if (shape !== undefined) {
  walkAst(shape.block, (n) => visit(n));
}

unnamedParamsRead

unnamedParamsRead(body: ASTNode): 0 | 1 | 2 counts the unnamed params a fn body reads. A read inside a nested closure does not count.

Return valueCondition
0The body reads neither $ nor $@
1The body reads $, including implicit forms such as a leading .method or pass
2The body reads $@

isUnnamedParamName

isUnnamedParamName(name: string): boolean returns true for the binding name of an unnamed fn param, '$' or '@'.


BUILTIN_FUNCTIONS

BUILTIN_FUNCTIONS is a readonly string[] listing every built-in function name. Use this to drive editor completion lists for rill scripts.

import { BUILTIN_FUNCTIONS } from '@rcrsr/rill';

const completions = BUILTIN_FUNCTIONS.map((name) => ({ label: name }));
registerCompletionProvider(completions);

Editor tooling (LSP completion, syntax highlighting) reads this list instead of vendoring a separate copy. The array is frozen at module load; BUILTIN_FUNCTIONS.push(...) throws.

KEYWORDS

KEYWORDS is a readonly string[] listing every language keyword. Use this alongside BUILTIN_FUNCTIONS to build completion and highlighting name lists.

import { KEYWORDS } from '@rcrsr/rill';

const keywordSet = new Set(KEYWORDS);
const isKeyword = (token: string) => keywordSet.has(token);

Editor tooling (LSP completion, syntax highlighting) reads this list instead of vendoring a separate copy. The array is frozen at module load; KEYWORDS.push(...) throws.

BUILTIN_METHODS

BUILTIN_METHODS is an object keyed by receiver type, then by method name. Each value is the callable definition for that method. The type keys are string, list, dict, number, bool, vector, datetime, duration, tuple, and ordered. Key insertion order is observable: language-service hover and completion iterate Object.values(BUILTIN_METHODS).

import { BUILTIN_METHODS } from '@rcrsr/rill';

const stringMethodNames = Object.keys(BUILTIN_METHODS.string);

Unlike BUILTIN_FUNCTIONS, KEYWORDS, and BUILTIN_ATOMS, this is not a readonly string[]. Read method names from the keys of each per-type record.

BUILTIN_ATOMS

BUILTIN_ATOMS is a readonly string[] listing the built-in atom names, without the leading #. The core error set is this list minus ok. Hosts cannot add names to it.

import { BUILTIN_ATOMS } from '@rcrsr/rill';

const builtinAtomSet = new Set(BUILTIN_ATOMS);
const isBuiltinAtom = (name: string) => builtinAtomSet.has(name);

Tooling such as the language service’s ATOM_CASE_MISMATCH rule reads this list instead of vendoring a separate copy. The array is frozen at module load; BUILTIN_ATOMS.push(...) throws.

ERROR_CODES

ERROR_CODES is a frozen readonly string[] of the core error set: every name in BUILTIN_ATOMS except ok, without the leading #. It lists the values .!code can hold on an invalid value. The rill type error_code holds the same set.

import { ERROR_CODES } from '@rcrsr/rill';

const isErrorCode = (name: string) => ERROR_CODES.includes(name);

The language service’s ATOM_NOT_ERROR_CODE rule reads this list to flag .!code comparisons against names outside it.

RillParam

RillParam is the unified parameter descriptor for host functions and script functions.

interface RillParam {
  readonly name: string;
  readonly type: TypeStructure | undefined;
  readonly defaultValue: RillValue | undefined;
  readonly annotations: Record<string, RillValue>;
}
FieldTypeDescription
namestringParameter name
typeTypeStructure | undefinedStructural type descriptor. undefined = any type (no validation)
defaultValueRillValue | undefinedDefault value when argument missing. undefined = required parameter
annotationsRecord<string, RillValue>Key-value metadata. Empty object when no annotations. annotations.description is the parameter description

CallableFn

CallableFn is the function signature for typed host function implementations.

type CallableFn = (
  args: Record<string, RillValue>,
  ctx: RuntimeContext,
  location?: SourceLocation
) => RillValue | Promise<RillValue>;
ParameterTypeDescription
argsRecord<string, RillValue>Named arguments keyed by parameter name. The runtime marshals positional call-site arguments into this record using the declared params list before invoking fn
ctxRuntimeContextRuntime context for the current execution. Provides access to variables, abort signal, and callbacks
locationSourceLocation | undefinedSource location of the call site. Present when the call originates from a rill script; undefined in programmatic calls

Returns: RillValue or Promise<RillValue>. RillStream is a valid RillValue return. Use createRillStream to build a stream from an AsyncIterable. See Stream Helpers for construction details. A return value that is not a RillValue—including one nested inside a returned array or plain object—halts at the call boundary with RILL-R085. A returned non-finite number (NaN, Infinity, -Infinity) halts catchably with #INVALID_INPUT instead. See Return Values for the full contract.

Migration note: The args parameter changed from RillValue[] (positional) to Record<string, RillValue> (named). Replace args[0] with args.paramName for each parameter. Every callable is marshaled, including those created via callable(). callable(fn) declares no parameters, so calling it with arguments halts with RILL-R045; property-style callable(fn, true) reads the collection it was selected from at args.self, not args[0]. Use toCallable with declared params or a signature for callables that take arguments.

A dict value in args is a live RillValue whose keys are all strings, so Object.keys and Object.entries list every entry.


RillFunction

A dispatch pipe returns a host function entry uncalled, including one reached through use<host:value>; call it with $c.name(args). See Dispatch Returns Host Functions.

RillFunction is the explicit form of a host function declaration. toCallable(def) and createRuntimeContext({ functions }) also accept the signature shorthand. Both input forms declare the same function; the runtime normalizes the shorthand to a RillFunction at registration.

interface RillFunction {
  readonly params: readonly RillParam[];
  readonly fn: CallableFn;
  readonly annotations?: Record<string, RillValue>;
  readonly returnType: RillTypeValue;
  readonly skipReceiverValidation?: boolean;
}
FieldTypeDescription
paramsreadonly RillParam[]Parameter descriptors. Runtime validates arguments before calling fn
fnCallableFnThe function implementation. The runtime marshals call-site arguments into Record<string, RillValue> keyed by parameter name before invoking fn. See CallableFn
annotationsRecord<string, RillValue> | undefinedKey-value metadata. annotations.description replaces the old description field. Optional; defaults to {}
returnTypeRillTypeValueDeclared return type. Required. Use anyTypeValue as the equivalent of “no constraint”. Runtime does NOT validate return values at call time
skipReceiverValidationboolean | undefinedWhen true, the method may be dispatched to a mismatched receiver and must check the receiver itself (RILL-R003). Arguments are still validated first (RILL-R044, RILL-R045, RILL-R001). Optional; used by method tables

Tuple Parameter Hydration

When a host function parameter type is { kind: 'tuple' } and type.elements contains entries with defaultValue !== undefined, the runtime fills missing trailing positions with deep copies of those defaults before invoking fn.

This happens at Stage 2.5 of marshalArgs, after argument validation and before fn is called.

import { structureToTypeValue } from '@rcrsr/rill';
import type { RillFunction } from '@rcrsr/rill';

const fn: RillFunction = {
  params: [{
    name: 'coords',
    defaultValue: undefined,
    annotations: {},
    type: {
      kind: 'tuple',
      fields: [
        { type: { kind: 'number' } },
        { type: { kind: 'number' }, defaultValue: 0 },  // default: 0
      ],
    },
  }],
  fn: (args) => args.coords,  // caller passes tuple[1] → receives tuple[1, 0]
  returnType: structureToTypeValue({ kind: 'tuple' }),
};

Hydration applies only to trailing elements. A missing non-trailing element with no default raises RILL-R009. Hydration does not apply to list or fn types. Dict and ordered parameters hydrate named fields with defaultValue. When a union parameter matches several members, see Defaults Under a Union.

Signature Shorthand

interface RillFunctionShorthand {
  readonly signature: string;
  readonly fn: CallableFn;
  readonly annotations?: Record<string, RillValue>;
  readonly description?: string;
}

type RillFunctionDefinition = RillFunction | RillFunctionShorthand;
const greet: RillFunctionShorthand = {
  signature: 'fn(^(description: "Name to greet") name: string, times: number = 1):string',
  fn: (args) => `hello ${args.name}`,
  description: 'Greet a caller',
};
FieldTypeDescription
signaturestringSignature in the form fn(name: type, ...):returnType. Parameters are named; unnamed parameters raise RILL-R091. Supplies params and returnType. An omitted return type means any
fnCallableFnThe function implementation. See CallableFn
annotationsRecord<string, RillValue> | undefinedFunction-level metadata. Optional
descriptionstring | undefinedStored as annotations.description. Optional
Entry pointAccepts shorthand
toCallable(def)Yes
createRuntimeContext({ functions })Yes
TypeDefinition.methods and other RillFunction fieldsNo
Supported syntaxExample
Type namesstring, number, bool, any
Unionsunion(string, number)
Literal membersunion("c", "f")
List typelist(string), or list() for an unspecified element type
Built-in type error_codelist(error_code)
Named dict typedict(k: string), dict("a b": string)
Tuple typetuple(number, string); tuple(number) is exactly one position
Map typemap(string, number), map(atom, bool)
Function typecb: fn(string):bool, cb: fn(x: number):string, bare fn
Stream typestream(number):string, stream(number)
Ordered typeordered(a: number)
Literal defaultsn: number = -3, s: string = "x", b: bool = true
Atom defaultk: atom = #A
Compound defaultslist[1, 2], dict[a: 1], tuple[1, "x"], ordered[a: 1], map[#a: 1]
Field defaultsd: dict(a: number, b: number = 0), t: tuple(string, number = 0)
Parameter annotations^(description: "text") name: string
Annotation values^(retries: 3) fn(url: string):string, any literal a script accepts
Function annotations^(category: "io") fn(a: string) before the signature

A parameter typed with a named dict type rejects a dict that has extra fields with RILL-R001; see Extra and Missing Dict Fields.

An outer type on list, dict, or tuple, such as list(number):string, fails with RILL-R091 and the message list takes no outer type. In script, the same text halts RILL-P006.

A default or annotation value is any literal a script accepts; one that interpolates or reads a $ variable fails registration with RILL-R091. fn() declares no parameters.

skipReceiverValidation has no shorthand field; use the explicit params form for it.

Registration throws RuntimeError with RILL-R091 in these cases:

ConditionMessage
Signature fails to lex, parse, or convertInvalid signature for function '{name}': {detail} at {line}:{col}; the position is 1-based inside the signature string
params or returnType supplied with signatureInvalid signature for function '{name}': supply either signature or params and returnType, not both
signature is not a stringInvalid signature for function '{name}': signature must be a string
description is not a stringInvalid signature for function '{name}': description must be a string
annotations is not an objectInvalid signature for function '{name}': annotations must be an object
One annotation key declared by more than one source (signature, annotations, description)Invalid signature for function '{name}': annotation '{key}' is declared more than once
Dict-field or tuple-element default does not match its typeInvalid signature for function '{name}': Default value for field 'b' must be number, got string at {line}:{col}; a tuple element reads tuple element instead of field 'b'
Tuple default is not trailingInvalid signature for function '{name}': tuple() default values must be trailing: element at position {n} has no default but a preceding element does at {line}:{col}
Default or annotation value interpolates or reads a variableInvalid signature for function '{name}': string interpolation is not allowed here; a signature holds constant literals only at {line}:{col}; a $ default reads Expected literal, got: $ at {line}:{col}, and a $ annotation value reads a Variable expression is not allowed here; a signature holds constant literals only at {line}:{col}
Union is empty, lists a member twice, or has a compound literal memberInvalid signature for function '{name}': union requires at least one member at {line}:{col}; a repeat reads union lists string more than once; a compound literal reads union member must be a type or a string, number, bool, or atom literal at {line}:{col}
Element or value type carries a default: list element, stream chunk or returnInvalid signature for function '{name}': list element type cannot carry a default at {line}:{col}; a stream reads stream chunk type cannot carry a default or stream return type cannot carry a default
Tuple element is namedInvalid signature for function '{name}': tuple() requires positional arguments at {line}:{col}, as in tuple(a: number)
Parameter default does not match its typeInvalid signature for function '{name}': Default value for parameter 'n' must be number, got string at {line}:{col}

{name} is the key in functions. toCallable has no key, so it reports <anonymous>.


Stream Helpers

RillStream is a valid RillValue. A host function returns a stream to deliver incremental results to rill scripts.


createRillStream

createRillStream(options: {
  chunks: AsyncIterable<RillValue>;
  resolve: () => Promise<RillValue>;
  dispose?: () => void;
  chunkType?: TypeStructure;
  retType?: TypeStructure;
}): RillStream

Builds a RillStream from an AsyncIterable of chunk values and a resolution callback.

ParameterTypeDescription
chunksAsyncIterable<RillValue>Async source of chunk values. Each yielded value is one stream step
resolve() => Promise<RillValue>Called once when all chunks are consumed. Returns the final resolved value
dispose() => voidOptional cleanup function. Runs exactly once when consumption ends — see Stream disposal below
chunkTypeTypeStructureOptional structural type descriptor for chunk values
retTypeTypeStructureOptional structural type descriptor for the resolved return value

Stream disposal

dispose runs exactly once, whichever way a collection operator stops reading the stream:

  • The operator drains every chunk (seq, fan, skip, stop_when, or a take(n) larger than the stream).
  • The operator stops early (take(n), or a break in seq/acc).
  • The consuming expression halts.

dispose runs before the consuming expression returns, so a host that opens a socket or file per stream releases it on every path. It never runs more than once.

A stream stepped by hand with .first() and .next() is disposed only when a step reaches the end of the chunks. A hand-stepped chain abandoned before that point is not disposed; the host remains responsible for that resource. A stream assigned inside a block is disposed on the enclosing block’s scope exit even if no expression ever consumed it; only a stream that is the script’s own top-level result, with no enclosing block, is left for the host to dispose.

import { createRillStream, structureToTypeValue } from '@rcrsr/rill';
import type { RillFunction, RillValue } from '@rcrsr/rill';

const fn: RillFunction = {
  params: [{ name: 'prompt', type: { kind: 'string' }, defaultValue: undefined, annotations: {} }],
  fn: async (args) => {
    async function* generateChunks(): AsyncIterable<RillValue> {
      for await (const token of streamLLM(args.prompt as string)) {
        yield token as RillValue;
      }
    }
    return createRillStream({
      chunks: generateChunks(),
      resolve: async () => 'done' as RillValue,
    });
  },
  returnType: structureToTypeValue({ kind: 'stream', chunk: { kind: 'string' }, ret: { kind: 'string' } }),
};

isRillStream

isRillStream(value: RillValue): value is RillStream

Returns true when value is a RillStream. Use this to detect stream results from execute().

import { isRillStream } from '@rcrsr/rill';
import type { RillStream } from '@rcrsr/rill';

execute() Stream Result Path

When a rill script returns a stream, execute() returns a RillStream inside result.result. Use isRillStream to detect it, then consume chunks by calling step.next.fn.

import { parse, execute, createRuntimeContext, isRillStream } from '@rcrsr/rill';
import type { RillStream } from '@rcrsr/rill';

const ast = parse('use<ext:app> => $app\n$app.stream_fn("prompt text")');
const ctx = createRuntimeContext({ /* ... */ });
const result = await execute(ast, ctx);

if (isRillStream(result.result)) {
  let step = result.result as RillStream;

  // Advance through chunks; initial stream object has no value — call next first
  step = (await step.next.fn({}, ctx)) as RillStream;
  while (!step.done) {
    console.log('chunk:', step.value);
    step = (await step.next.fn({}, ctx)) as RillStream;
  }

  // Invoke the resolution callback via the hidden resolve property
  const resolveFn = (step as unknown as Record<string, () => Promise<unknown>>)[
    '__rill_stream_resolve'
  ];
  const finalValue = resolveFn ? await resolveFn() : undefined;
  console.log('resolved:', finalValue);
}

step.done is false while chunks remain. The initial stream object has no value; call step.next.fn({}, ctx) to get the first step. When step.done is true, all chunks are consumed. The resolution callback is stored as __rill_stream_resolve on the initial stream object.


generateManifest

generateManifest(ctx: RuntimeContext): string

Generates a valid rill manifest file listing all registered host functions as fn type signatures.

import { generateManifest } from '@rcrsr/rill';

const manifest = generateManifest(ctx);
// Returns a rill file suitable for static analysis or LLM context

The output format is a rill dict literal. The dict is the last expression and becomes the script’s result value:

[
  "greet": fn(^("who") name: string = "world"):string,
  "fetch": fn(url: string):dict,
  "now": fn():number
]

An empty function map returns [:]. Functions created via callable(fn) appear with an empty parameter list; property-style callable(fn, true) appears with a single self: any parameter.

Every entry is an fn type literal that evaluates to a type value, never a real function body. This holds for zero-param functions ("now") and functions with annotated params ("greet") alike.

Manifest names are quoted and escaped, so a name that is not an identifier still parses. A parameter or field default prints as = literal after its type, so an entry registered again keeps it. A default with no literal form is left out: datetime, duration, function, vector, iterator, stream, type values, and non-finite or exponent-form numbers. That parameter or field is then required when the entry is registered again, and every other default in the entry still prints. Every signature carries an explicit return type (:any when unset) so the generated manifest always parses.


TimeoutScheduler

TimeoutScheduler is the type of the scheduler option on createRuntimeContext(). It replaces the global timer functions for timeout(total: ...) and timeout(idle: ...) blocks and for the per-call timeout option, so a test can drive them from fake timers.

interface TimeoutScheduler {
  setTimeout(fn: () => void, ms: number): ReturnType<typeof setTimeout>;
  clearTimeout(handle: ReturnType<typeof setTimeout> | undefined): void;
}

Without a scheduler, the runtime uses the global setTimeout and clearTimeout.


SchemeResolver

SchemeResolver is the function type for custom use<scheme:...> resource resolvers.

type SchemeResolver = (
  resource: string,
  config?: unknown
) => ResolverResult | Promise<ResolverResult>;
ParameterTypeDescription
resourcestringThe resource path after the scheme prefix (e.g., "myModule" from use<host:myModule>)
configunknown | undefinedPer-scheme configuration data from RuntimeOptions.configurations

Returns: ResolverResult or a promise that resolves to one. See ResolverResult for variant shapes.

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

const myResolver: SchemeResolver = async (resource, config) => {
  const source = await loadSource(resource);
  return { kind: 'source', text: source };
};

ResolverResult

ResolverResult is the discriminated union returned by a SchemeResolver.

type ResolverResult =
  | { kind: 'value'; value: RillValue }
  | { kind: 'source'; text: string };
VariantFieldsDescription
{ kind: 'value' }value: RillValueSupplies a pre-built rill value (e.g., an extension dict)
{ kind: 'source' }text: stringSupplies rill source text to be parsed and executed
import type { ResolverResult, RillValue } from '@rcrsr/rill';

// Return a pre-built value
const valueResult: ResolverResult = {
  kind: 'value',
  value: { search: mySearchFn } as RillValue,
};

// Return source text for rill to parse
const sourceResult: ResolverResult = {
  kind: 'source',
  text: `fn(x: string) { $x -> .upper }`,
};

moduleResolver

moduleResolver is a built-in SchemeResolver that maps module identifiers to file paths and returns their source text.

import { moduleResolver } from '@rcrsr/rill';

Config shape:

FieldTypeRequiredDescription
[moduleId]stringYes (at least one)Maps a module identifier to a file path (relative to the config file’s directory)

Error codes:

CodeTrigger
RILL-R050Module identifier not found in config
RILL-R051File read failure (I/O error or missing file)
RILL-R059Config is missing or malformed
import { moduleResolver, createRuntimeContext } from '@rcrsr/rill';

const ctx = createRuntimeContext({
  resolvers: { host: moduleResolver },
  configurations: {
    resolvers: {
      host: {
        utils: './utils.rill',
        helpers: './lib/helpers.rill',
      },
    },
  },
});

// Scripts can now use: use<host:utils>

moduleResolver returns { kind: 'source', text: string } after reading the target file. Paths resolve relative to the config file’s directory.


extResolver

extResolver is a built-in SchemeResolver that maps extension identifiers to pre-built rill values.

import { extResolver } from '@rcrsr/rill';

Config shape:

FieldTypeRequiredDescription
[extensionId]RillValueYes (at least one)Maps an extension identifier to its full rill value dict

Member access: A resource of "qdrant.search" returns only the search member from the qdrant extension dict. A resource of "qdrant" returns the full dict.

Error codes:

CodeTrigger
RILL-R052Extension identifier not found in config
RILL-R053Member path not found within the extension dict, or a path descends into a non-dict value (callable, tuple, ordered, vector, stream)
import { extResolver, createRuntimeContext } from '@rcrsr/rill';
import { qdrantExtension } from './my-qdrant-ext';

const ctx = createRuntimeContext({
  resolvers: { ext: extResolver },
  configurations: {
    resolvers: {
      ext: {
        qdrant: qdrantExtension,
      },
    },
  },
});

// Scripts can now use: use<ext:qdrant> or use<ext:qdrant.search>

extResolver returns { kind: 'value', value: RillValue }.


Dispatch-Boundary Policy

Access control and input/output transforms for extension methods resolved through use<scheme:resource>. Configured with the filterResolver option on createRuntimeContext. See Dispatch-Boundary Policy in the host integration guide for how the rules match and why a policy needs "*" to fail closed.

resolvePolicy

function resolvePolicy(
  config: PolicyConfig,
  extensions: ReadonlyMap<string, RillValue>
): ResolvedPolicy;

Resolves the "extension.method" strings in in/out rules to the callables they name, once, at setup. Halts with RILL-R087 on a reference that names no mounted callable, and RILL-R086 on a "*" rule carrying transforms.

createConfigFilterResolver

function createConfigFilterResolver(policy: ResolvedPolicy): FilterResolver;

Builds a FilterResolver over a resolved policy. A factory rather than a bare function so the policy stays in the closure, out of reach of the extension code it governs. The returned resolver implements policesExtension, which is true for an extension with rules or a "*" default.

getExtensionIdentity

function getExtensionIdentity(
  callable: RillCallable
): ExtensionIdentity | undefined;

Where a callable was resolved from, or undefined for anything that did not come through use<>. Under a configured filterResolver, values derived from a branded call’s result also carry an identity when the resolver polices that extension (see Dispatch-Boundary Policy), with () appended to the calling method’s path. This is the authorization key a custom FilterResolver should use: it is fixed when the extension resolves and does not move when a script renames or rebinds the variable holding it.

Types

interface FilterResolver {
  (
    callable: RillCallable,
    resolvedPath: string | undefined,
    ctx: RuntimeContext
  ): Filter | null;

  readonly policesExtension?: (extension: string) => boolean;
}

interface Filter {
  readonly access: 'allow' | 'deny';
  readonly inTransforms: readonly RillCallable[];
  readonly outTransforms: readonly RillCallable[];
}

interface ExtensionIdentity {
  readonly extension: string;
  readonly method: string;
}

interface MethodPolicyRule {
  readonly access: 'allow' | 'deny';
  readonly in?: readonly string[];
  readonly out?: readonly string[];
}

type ExtensionMethodPolicy = Record<string, MethodPolicyRule>;
type PolicyConfig = Record<string, ExtensionMethodPolicy>;

interface ResolvedPolicy {
  readonly rules: ReadonlyMap<string, ReadonlyMap<string, Filter>>;
  readonly defaults: ReadonlyMap<string, Filter>;
}
ErrorRaised when
RILL-R086A "*" rule declares in or out transforms
RILL-R087A transform reference cannot be resolved to a mounted callable
RILL-R088A call is denied by policy (catchable with guard or ??)
RILL-R089A policy transform re-enters itself
RILL-R090An extension value exceeds the branding budget at use<> resolution (catchable; the halt means no value binds)

Factory-Scope Context (ExtensionFactoryCtx)

ExtensionFactoryCtx is passed as the second argument to async extension factories. It provides a lifecycle abort signal.

interface ExtensionFactoryCtx {
  readonly signal: AbortSignal;
}

type ExtensionFactory<TConfig> = (
  config: TConfig,
  ctx: ExtensionFactoryCtx
) => ExtensionFactoryResult | Promise<ExtensionFactoryResult>;
MemberTypeDescription
signalAbortSignalFires when the runtime disposes. Use to cancel long-running factory setup.
async function createPaymentExtension(
  config: PaymentConfig,
  ctx: ExtensionFactoryCtx
): Promise<ExtensionFactoryResult> {
  const client = await PaymentClient.connect(config.endpoint, {
    signal: ctx.signal,
  });

  return {
    value: {
      charge: toCallable({ /* ... */ }),
    },
    dispose: () => client.close(),
  };
}

See Extensions for reporting domain failures and returning invalid values.


RuntimeContext Helpers

Three helpers on RuntimeContext support error-aware extension functions.

ctx.invalidate

invalidate(error: unknown, meta: InvalidateMeta): RillValue

Wraps a JavaScript error as an invalid rill value the script can test with .? and .!. meta.code must belong to the core error set (every built-in atom except ok). Any other code throws RILL-R084 at the call; carry domain detail in raw.

ParameterTypeDescription
errorunknownThe caught JavaScript error or any throwable
metaInvalidateMetaMetadata: { code, provider, raw? } identifying the failure
fn: async (args, ctx) => {
  try {
    return await sdkClient.fetch(args.url as string);
  } catch (e) {
    return ctx.invalidate(e, { code: 'UNAVAILABLE', provider: 'my-ext' });
  }
},

ctx.catch

catch<T>(
  thunk: () => Promise<T>,
  detector: (e: unknown) => InvalidMeta | null
): Promise<T | RillValue>

Runs thunk. On throw, calls detector(e). When detector returns InvalidMeta, returns an invalid value. When detector returns null, returns an invalid value with code #R999. A detector code outside the core error set rejects with RILL-R084.

ParameterTypeDescription
thunk() => Promise<T>Async operation to attempt
detector(e: unknown) => InvalidMeta | nullMaps thrown errors to InvalidMeta, or null to return an invalid value with code #R999
fn: async (args, ctx) => {
  return ctx.catch(
    () => sdkClient.fetch(args.url as string),
    (e) => {
      if (e instanceof TimeoutError) return { code: 'TIMEOUT', provider: 'my-ext' };
      if (e instanceof AuthError) return { code: 'AUTH', provider: 'my-ext' };
      return null; // unclassified errors become #R999
    }
  );
},

ctx.signal

readonly signal: AbortSignal | undefined

The AbortSignal for the current execution, or undefined when no cancellation source is configured. Pass to async I/O operations to propagate cancellation from the script runtime.

fn: async (args, ctx) => {
  const response = await fetch(args.url as string, {
    signal: ctx.signal,
  });
  return response.text();
},

ctx.dispose() Lifecycle

dispose() is an async method on RuntimeContext that shuts down that context’s runtime. It is idempotent. @rcrsr/rill exports no top-level dispose function.

dispose: () => Promise<void>

Calling ctx.dispose() fires the AbortSignal on all in-flight extension calls. In-flight work receives abort via AbortSignal.any() combined with an internal timeout. After the timeout, dispose() resolves regardless.

import { parse, execute, createRuntimeContext } from '@rcrsr/rill';

const ctx = createRuntimeContext({ /* ... */ });

try {
  const result = await execute(parse(script), ctx);
  console.log(result.result);
} finally {
  await ctx.dispose();
}
BehaviorDetail
IdempotentSafe to call multiple times; subsequent calls are no-ops
Signal propagationFires AbortSignal on all registered extension factory contexts
In-flight timeoutUses AbortSignal.any() plus a grace-period timeout

structureOverlaps

structureOverlaps reports whether some value could satisfy two type structures. It is pure and symmetric, and it never throws. Two literals overlap only when they hold equal values, and a literal overlaps its scalar kind. A dict key named on one side only must carry a default for the structures to overlap.

function structureOverlaps(a: TypeStructure, b: TypeStructure): boolean;

It implements the rule behind the #TYPE_MISMATCH halt of ==, !=, .eq, .ne, .has, .has_any, and .has_all, whether or not an operand carries a declared type. See Operators for the halt rule.


parseDurationText

parseDurationText parses the printed form of a duration, such as "1h30m". It returns the month and millisecond components, or undefined when the text is malformed. It is pure and never halts; the script duration("...") and "..." -> duration halt #INVALID_INPUT on the same text.

function parseDurationText(
  text: string
): { months: number; ms: number } | undefined;

Units appear in the order y, mo, d, h, m, s, ms, each at most once. Only the ms count may be a decimal.


parseIsoDatetime

parseIsoDatetime parses an ISO 8601 datetime or date string to Unix milliseconds. It returns an IsoDatetimeFailure carrying a message instead of halting.

function parseIsoDatetime(input: string): number | IsoDatetimeFailure;

interface IsoDatetimeFailure {
  readonly message: string;
  readonly component?: string | undefined;
}

component names the range-checked field that failed, such as month or day. IsoDatetimeFailure is not a named export; read the result’s shape with a typeof check on number.


Host-Supplied Containers

The runtime memoizes the inferred type structure of a host-supplied array or object per container identity. Do not mutate an array or object after you pass it to the runtime, whether as a function result, a variable, or a context value. Build a new container instead.


Type System API

TypeStructure, TypeDefinition, TypeProtocol, RillFieldDef, and related structural type exports are documented in Host API Types Reference.


See Also