Skip to main content

Module region_hook

Module region_hook 

Source
Expand description

Script-backed custom region hooks (RegionKind::Custom).

A custom region’s .rhai script owns the region’s behavior through up to three functions, each a return-value contract (Rhai passes arguments by value, so mutating the ctx argument in place has no effect - the script must return its result):

  • render(ctx) - required. Shapes the region’s contribution to the assembled context. Returns a string (one system block) or a map #{ system: ..., messages: [...] }.
  • on_write(ctx) - optional. Sees each incoming entry; returns a string (replace the content), true/() (accept unchanged), or false (drop).
  • on_overflow(ctx) - optional. Chooses what to evict under budget pressure; returns an array of entry indices to drop.

This module owns compilation (once, at agent spawn - the CLI resolves the blueprint-dir-relative path and reads the file) and the three call entry points. Interpretation of the returned values - block/message construction, index validation, fallbacks - lives with the caller (leviath-runtime), which receives plain serde_json::Values so it needs no rhai dependency of its own.

Execution runs on a fresh hardened engine per call (see crate::harden) over the precompiled AST: no filesystem, no network, no eval, operation- bounded. The registered helpers are the same pure function/type sets every Leviath script engine gets.

Structs§

RegionScript
A compiled custom-region script, ready to call. Compiled once at spawn and shared via Arc on the runtime’s context window, keyed by path.

Functions§

compile
Compile a custom-region script and verify its shape: render(ctx) must exist with exactly one parameter; on_write/on_overflow are recorded when present (also arity 1). Used by the CLI at spawn (fail-fast: a missing or broken script is a spawn error, not a silent runtime fallback) and by lev validate.
run_on_overflow
Run on_overflow(ctx). Callers must check RegionScript::has_on_overflow first.
run_on_write
Run on_write(ctx). Callers must check RegionScript::has_on_write first - calling a missing function is an execution error.
run_render
Run render(ctx). The result is a JSON string (one system block) or an object with optional system / messages fields - shape validation is the caller’s job.