Kernel & Context Engine
At the heart of Hya (crates/hya-core) is a deliberate split between the irreducible agent loop (the Kernel) and everything optional layered around it (Full Mode).
1. Context is $(m, g, w)$
A running session’s state reduces to three pieces derived from the event log:
- $m$ — Visible transcript: The messages, tool calls, tool results, and compaction markers actually sent to the model on the next round.
- $g$ — Completion criteria (
todo): The session’s ordered checklist (TodosUpdated). Stored in the projection independently of $m$ so that even when old messages are wiped during a context reset, $g$ is carried forward intact. - $w$ — Workspace file observations: Recorded
FilesObservedandFilesChangedevents tracking whether files on disk changed since the session last looked (powering conflict checks, undo snapshots, andworkspace.statecaching).
Workspace file observations on Linux
File observation runs automatically in each session, including in bare mode. The kernel registers inotify watches directly and inventories source files while setting up the first checkpoint. Later checkpoints drain the inotify queue to pick up source edits, new files, and renames. Changes during setup trigger a fresh inventory so the first observation reflects the workspace.
Discovery skips symlinked directories, the .git, target, node_modules,
.venv, and .dev path components, and the workspace root’s
.hya/tool-output and .hya/local directories. For example, an external edit
to src/lib.rs can produce a FilesObserved { external: true, ... } event at
the next checkpoint. A file explicitly read from target/debug/ is checked for
later size and modification-time changes. Tools can read these paths under
the usual workspace permissions.
The session folds observations into its file revision. After reconciling,
workspace.state returns a "<session>:<file revision>" string when a native
watch is available and an empty option otherwise.
2. The Three Primitives (hya-core::kernel)
Every turn uses SessionEngine to drive kernel::drive. The runtime composes
the enabled bundle registrations with that turn path. Round retries and the
80% context rewrite apply even when the turn has no hook entries.
Each round updates Context through three primitives:
| Primitive | What it means | Key Events |
|---|---|---|
| 1. Model append | What the model claims or plans: streamed text, private reasoning, and requested tool calls. Never treated as ground truth about the outside world. | StepStarted, Text*, Reasoning*, ToolCallRequested, StepFinished, UsageRecorded |
| 2. Tool append | Deterministic observations from outside the model: a tool result paired with a call, or a user prompt. Invalid JSON tool arguments, unknown tools, and cancellations become structured ToolErrors—never synthesized fake outputs. |
ToolResult, ToolError, TodosUpdated, FilesChanged, FilesObserved, user Message* |
| 3. Rewrite | Destructive context reset when the window fills up (or when the model calls rewrite): drops visible history before the current step and inserts a clean system marker repeating all prior user messages verbatim plus the current todo list ($g$). Dropped messages stay safely in SQLite for human replay. |
System marker message + ContextCompacted { strategy: rewrite } |
The runtime loads installed bundles according to bundles.builtin in config.toml and applies each trusted Project’s bundle scope. Install the official default profile for the complete bundle catalog. The global --bare flag (hya --bare, hya server run --bare, or hya exec --bare) selects the empty bundle set while keeping the compiled-in hya-bare agent, the 8 standard bare tools (read, write, edit, bash, grep, todo, rewrite, skill), optional native Code Mode, disk AGENTS.md guidance, skills, MCP, and plugins. Combining --bare with --pure (hya exec --bare --pure) also skips external AGENTS.md, disk skills, MCP servers, user/project plugins, and Code Mode for pure kernel benchmarks. Disk skill discovery stays disabled throughout the turn, including runtime rebinds. --pure is a separate axis that never reads the bundle selection.
Composing the installed bundle set
| Surface / Capability | Official default profile installed (profile = "full") |
Empty set (--bare, profile = "bare") |
--bare --pure |
|---|---|---|---|
| Engine & Kernel loop | SessionEngine on hya-core::kernel |
SessionEngine on hya-core::kernel |
SessionEngine on hya-core::kernel |
| Bundles | Installed bundles selected by bundles.builtin and project bundles |
None loaded | None loaded |
| Default agent | hya-main (the default_agent of hya/core-agents) |
hya-bare (hya_engine::BARE_AGENT_ID) |
hya-bare |
| Core tools | Built-in native ABI v2 bundles (hya/hashline, hya/coding-extras, hya/multi-agent, hya/network, hya/agent-channels, hya/plan, hya/workflow) + core bash, skill, and kernel todo/rewrite |
8 standard bare tools: read, write, edit, bash, grep, todo, rewrite, skill |
8 standard bare tools (skill catalog empty) |
Built-in code-mode |
Enabled when configured | Enabled when configured | Disabled |
| Context & external extensions | AGENTS.md, disk skills, MCP, user/project bundles and plugins |
AGENTS.md, disk skills, MCP and plugins |
Skipped |
| Compaction | shake + remote (hya/compaction) → Kernel Rewrite |
Kernel Rewrite only |
Kernel Rewrite only |
- CLI usage:
hya --bare(interactive TUI/WebUI + auto-started--baredaemon),hya serve --bare/hya serve start --bare(HTTP/gRPC server),hya exec --bare "<prompt>",hya exec --bare --pure "<prompt>",hya --bare agent list. “Bare plus A” isprofile = "bare"withenable = ["A"]inconfig.toml. - Rust / config interfaces:
hya_app::builtin_selection(bare: bool) -> BuiltinBundleSelectionis the one selection a CLI invocation resolves:BuiltinBundleSelection::bare()under--bare, elseconfig.tomlbundles.builtin.hya_app::resolve_runtime(model, RuntimeFlags { bare, pure })applies it: the selection decides the registered provider kinds (hya_app::provider_kinds::load) before the providers resolve, andRuntimeConfig::with_flagscarries it into the engine settings.- One roster.
hya_engine::AgentCatalog::new(bundles)builds the agent roster from the enabled bundles alone. The default agent is thedefault_agentan enabled bundle declares (at most one may); when none does, the compiled-inhya-bareis part of the roster and is the default.hya/core-agentsis an ordinary catalog bundle that declaresdefault_agent: hya-main, so with it enabledhya-bareis not listed. All profiles construct the engine withSessionEngine::new; the application passes enabled native registrations throughwith_rewritersand the other extension builders. hya_server::AppState::with_core_commands(bool)disableshya/core-commandsloading in bare servers (GET /v2/commandsreturns only workspace/skill/bundle commands;GET /v2/agentsreturnshya-bare;GET /v2/bundlesreports zero built-in bundles). Session titles come from thehya/session-titlebundle, not the server.
A tool may override hya_tool::Tool::ends_turn(&self) -> bool to end the turn
after the calls in its current round finish. For example, a tool that submits
a deliverable returns true from ends_turn and Ok(output) on successful
submission. When a deadline notice addresses an agent with an offered
turn-ending tool, it names the tool the model can call to deliver its result.
2a. The Seven Standard Kernel Tools (hya_core::kernel::tools)
hya-core ships seven self-contained standard primitives so bare mode (hya --bare) and trimmed bundle profiles operate cleanly without requiring hya/hashline, LSP, formatters, or channel bundles:
| Tool | Purpose & Boundaries | Permission Action | Result Policy | Overridable? |
|---|---|---|---|---|
read |
Read UTF-8 text files (with optional offset/limit paging), directories, images (PNG/JPEG/GIF/WebP), internal handles (artifact://, skill://, local://), and registered custom UriSchemaHandler URIs. Enforces ProjectScope on filesystem paths. |
Action::Read (+ Action::ExternalDirectory outside ProjectScope) |
ToolResultPolicy::Coding (50 KiB cap) |
Yes (e.g. hya/hashline) |
write |
Create or overwrite workspace files (creating parent directories), local:// scratch handles, or writable custom UriSchemaHandler URIs. artifact:// and skill:// are read-only. Enforces ProjectScope on filesystem paths. |
Action::Edit (+ Action::ExternalDirectory outside ProjectScope) |
ToolResultPolicy::Coding |
Yes |
edit |
Replace one exact, unique literal occurrence of old with new in a workspace file or local:// handle. Returns bounded diff metadata (diff, filediff). Contains zero hashline, LSP, or formatter logic. |
Action::Edit (+ Action::ExternalDirectory outside ProjectScope) |
ToolResultPolicy::CodingWithDiff |
Yes |
bash |
Run shell commands in isolated process groups with timeout/run-budget yielding (still_running) and 30 KiB head+tail output capping with spill file. Exempt from ProjectScope. |
Action::Bash |
ToolResultPolicy::Coding |
Yes |
grep |
Pure-Rust regex or literal file search respecting .gitignore and .ignore, glob filters (glob, ! exclusion), context lines (0–5), lexical match limits (1–200, default 50), binary/dotfile/symlink skipping, and grep_budget display capping. Standard {line}:{text} / {line}-{text} output with zero hashline anchors. |
Action::Grep (+ Action::ExternalDirectory outside ProjectScope) |
ToolResultPolicy::Coding (grep_budget) |
Yes |
todo |
Atomic checklist operations (add, edit, status, remove) updating Context $g$ (TodosUpdated). Intercepted directly by the kernel loop. |
Kernel-managed | Kernel-managed | Never (permanently reserved) |
rewrite |
Destructive Context reset keeping prior user prompts, current todo list ($g$), and model summary. Intercepted directly by the kernel loop. |
Kernel-managed | Kernel-managed | Never (permanently reserved) |
Usage & Interfaces
- Invocation: Call
hya_core::kernel::tools::builtin()to obtain all seven tools in prompt order, paired withhya_core::kernel::prompt::system_prompt(&workdir)(orprompt::compose(...)). - Standard tool schemas:
read:{ "path": string, "offset"?: integer (>=1), "limit"?: integer (>=1) }write:{ "path": string, "content": string }edit:{ "path": string, "old": string, "new": string }bash:{ "command": string, "timeout"?: integer (1..=86400), "cwd"?: string }grep:{ "pattern": string, "path"?: string, "glob"?: string, "ignoreCase"?: boolean, "literal"?: boolean, "context"?: integer (0..=5), "limit"?: integer (1..=200) }For example,{"pattern":"pub fn","path":"crates","glob":"**/*.rs","literal":true,"context":1,"limit":50}finds declarations and includes one neighboring line on either side. Directory searches keep the first matching lines in path-component order, then line order. They stop after confirming one more permitted match so an exact hit count at the limit does not signal truncation. Warnings describe files reached during the search. Grep warns once per file when skipping logical lines over 1 MiB and continues at the next line.todo:{ "ops": Array<Add | Edit | Status | Remove> }rewrite:{ "summary": string }
- Filesystem calls:
readvalidates the full UTF-8 file and counts its lines even for a small page such as{"path":"notes.txt","offset":1,"limit":50}. It keeps only the requested output within the coding budget. Directory scans and localwriteandeditoperations run on blocking workers. - Shell spill files: When a finished or stopped
bashcall prints more than 30,000 bytes, it normally publishes the complete scratch file to.hya/tool-output/by atomic rename. The result names it inmetadata.outputPath. Scratch output has no crash-durability guarantee. - Dynamic URI scheme dispatch (
HandleRouter+UriSchemaHandler):ToolCtx::handles()returns ahya_tool::handle::HandleRouterresolving internalartifact://,skill://, andlocal://handles (with projections?lines=N[-M],?head=N,?tail=N,?grep=<pattern>,?q=<.path>) plus any dynamic URI scheme handlers carried onToolCtx::schemas(hya_tool::handle::UriSchemaPlane).- Bundles implementing ABI v2
hya_runtime_abi::UriSchemaHandlerplug intoHandleRouterviahya_runtime_abi::adapt_uri_schema_handler(handler, runtime)andToolCtx::with_uri_handler(...)(orHandleRouter::with_uri_handler(...)). Internal schemes (artifact,skill,local) are protected (SchemeRegistryError::ProtectedScheme), andhya-coreitself carries zero hardcoded domain schemes (such aschannel://). - Example:
let ctx = ctx.with_uri_handler(hya_core::kernel::tools::adapt_uri_schema_handler(custom_handler, None),)?;// `read` and `write` now delegate `custom://...` URIs through `HandleRouter`.
- Permanent reservation of
todoandrewrite:hya_tool::RESERVED_KERNEL_TOOLS/hya_core::kernel::tools::is_reserved(name)marktodoandrewriteas permanently kernel-exclusive.ToolRegistryrejects registering or aliasing either name, ABI v2 bundle loading (hya-tool-loader) rejects bundles exporting either name, andSessionEngineadvertises the canonical kernel schemas, andkernel::driveintercepts the calls.
Bash process groups and run shutdown
bash captures stdout and stderr in one file per call. Normal completion
follows the shell leader on all supported Unix platforms. As soon as it
exits, the tool returns its numeric exit_code, including when a
background job started with & is still running. For example,
{"command":"cd /app && nohup server >server.log 2>&1 &"} leaves the job
running after the shell and the run exit. Redirect both streams to keep
the job’s output in its own log.
A shell still running at the per-call wait limit can yield with
exit_code: null, a still_running string, and
metadata.{pgid,outputPath,exitPath}. Run shutdown stops yielded groups
still under supervision and waits for the exit file, which contains the
shell’s JSON exit code or 137 after a forced stop. Cancellation and a hard
budget stop also kill the original process group, including its child
processes and worker threads. A descendant that moves to another process
group falls outside that cleanup.
3. Built-in Kernel Safeguards
Because both bare mode and full mode share hya-core::kernel, every agent gets three tricky edge-case protections automatically:
-
Malformed tool-call JSON guard: If a model cuts off mid-JSON or appends trailing garbage to tool arguments, the decoder records
{"invalid_json_arguments": ...}and the kernel returns a cleanToolErrortelling the model to resend valid JSON—without crashing the stream or poisoning future provider requests. -
Dropped-reasoning detection: Some OpenAI-compatible gateways silently strip replayed private reasoning tokens between tool rounds, causing reasoning models to suffer sudden amnesia. The kernel compares round-over-round prompt token counts (
curr.prompt < prev.prompt + prev.reasoning / 2) and injects a one-time notice telling the model to write key findings in visible text ortodoitems instead of relying on private thinking. -
Reasoning-only deadline guard (
--time-budget): The first nonempty reasoning delta arms a timer for the next checkpoint or the per-step cap. When WrapUp is the selected checkpoint, the wait is at least the lesser of 90 seconds and half the time remaining before Final, subject to the per-step cap. Final keeps the standard reasoning grace (3% of the run budget, clamped to 15–30 seconds and limited to half the time remaining before the end-of-run reserve). For example, in a 900-second run, a step starting 600 seconds in gets a 90-second WrapUp wait. A step starting at Final gets 27 seconds of grace if the session has yet to receive the Final notice.At expiry, the collector processes up to 16 immediately ready frames in order.
TextStart,TextDelta,ToolInputStart,ToolCallRequested, andMessageFinisheddisarm the guard. EOF and provider errors take the usual stream completion and error paths. If the stream is still open and has emitted only reasoning, the collector records aDeadlineCutwith the stage (or no stage for a per-step cap before the next checkpoint) and the accumulated reasoning. It persists the reasoning text, clears provider replay data for the cut step, and gives the next round a notice quoting up to the first 2,400 and last 4,000 characters.
4. Context Reduction Ladder (80% Threshold)
Before every model round, the kernel measures window pressure against 80% of the model’s max_context:
used = max(last round's prompt + output, usage-anchored request count, local token estimate)threshold = max_context * 8 / 10The engine reuses the system prompt, tool schemas, and their estimated tokens while the round’s runtime generation, model, workdir, and initial context stay the same. Active tool.visibility hooks can still change the tool list at each round. Part estimates are reused within the turn, with reasoning and tool-image replay evaluated against the current request.
The persisted ViewRef.request_sha256 is the lowercase SHA-256 of the compact JSON array [system, tools, messages]. Object keys are sorted recursively and array order is preserved.
When used > threshold, the kernel runs registered hya_context::rewrite::Rewriter extensions in order, re-measures after any change, and runs its own Rewrite only if the prompt is still above 80%:
flowchart LR
Check{"used > 80% window?"} -->|No| Send["Send model round"]
Check -->|Yes, Full Mode| Shake["1. shake (hya/compaction)<br/>Spill stale tool outputs to artifact://"]
Shake --> Re1{"Still > 80%?"}
Re1 -->|No| Send
Re1 -->|Yes, Responses/Codex/Grok| Remote["2. remote (hya/compaction)<br/>Provider /responses/compact"]
Remote --> Re2{"Still > 80%?<br/>(or unsupported route)"}
Re2 -->|No| Send
Re2 -->|Yes (or --bare)| Rewrite["3. Kernel Rewrite<br/>Keep user prompts + todo list"]
Rewrite --> Send
shake(context_evicted): Provided by the official native ABI v2 bundlehya/compaction. Evicts completed tool outputs outside the lastkeep_recent(default6) messages/steps, spilling bodies ≥ 512 bytes toartifact://...so the model can stillreadthem back if needed. Eviction notices are persisted asEvent::Extension { bundle: "hya/compaction", kind: "context_evicted", payload }and folded by the bundle’s ABI v2ProjectionReducerintoprojection.extensions["hya/compaction"]; itstool_output_overridessetPartProjection::Tool.eviction_notice, so prompt prefixes stay byte-stable for provider KV caching. Withhya/compactiondisabled no reducer folds these records, and old evicted outputs are sent in full again (the kernel’s 80%Rewritestill bounds the window).remote(ContextCompacted { strategy: native }): Calls upstream/responses/compacton routes that support native window folding (falling back toHostModelCaller::compact_windowonArc<dyn HostRuntime>), persistingHYA_COMPACTED_CONTEXTplus the activetodolist.- Manual
/compact&/summarize: Acquires the session turn lease, triesremotefirst, and falls back to KernelRewrite(threshold: 0, markedmanual: true). - Configuration & ABI v2 Interfaces (
hya/compaction):- Per-bundle config file:
~/.config/hya/bundles/hya/compaction.toml. The rewriter readskeep_recentitself on first use (HostCatalogReader::bundle_config("hya/compaction"), thenHYA_COMPACTION_KEEP_RECENT);hya/multi-agentreadssummary_max_tokens(envHYA_COMPACTION_SUMMARY_MAX_TOKENS) at start as the output cap of the terminal handoff. Atoken_accountingkey in this file fails each turn: it moved to the core.compaction:keep_recent: 6summary_max_tokens: 4096 - Token accounting is a core setting, read whatever bundles are enabled:
config.tomlcontext.token_accounting(auto,provider, orestimate) (envHYA_TOKEN_ACCOUNTINGwins). It drives the request overhead estimate, the pre-send check, and reaches rewriters asRewriteCtx::token_accounting. - Native ABI v2 exports (
export_native_bundle_v2!/hya_native_register_v2): registersCompactionRewriter(hya_context::rewrite::Rewriter) andCompactionProjectionReducer(hya_runtime_abi::ProjectionReducerforbundle_id: "hya/compaction"). - Extension event schemas (
Event::Extension,bundle: "hya/compaction"):kind: "context_status":{ "tokens": u64, "source": "provider" | "estimate", "mode": "auto" | "provider" | "estimate", "threshold": u64 }→ folds intoprojection.extensions["hya/compaction"].context_status.kind: "context_evicted":{ "parts": [{ "part": string, "notice": string }] }→ folds intoprojection.extensions["hya/compaction"].evicted_parts; the reducer’stool_output_overridessetPartProjection::Tool.eviction_notice.
- Disabling
hya/compaction(via--bareorbundles.builtin.disable = ["hya/compaction"]) skips loadinglibhya_compactionand relies strictly on KernelRewrite.
- Per-bundle config file: