ACAgentic Craft

Foundation~30 minHazelJS

AgentRuntime Mental Model

How AgentRuntime owns context assembly, tool validation, budgets, checkpoints, and stop reasons—step by step for beginners inside a HazelJS app.

Authors
editorial-team
Published
Last reviewed
Progress is stored locally in this browser.

Direct answer

AgentRuntime is the kernel of HazelJS Agent OS. On each execute(agentName, goal, options) it owns:

assemble context → model proposes tool or final answer → validate args → optional approval → execute via ToolRegistry → append observation → optional checkpoint → stop

The LLM never calls your APIs directly. That separation is the whole point.

Docs: Agent package, Agent OS. Glossary: /glossary/agent-runtime.

Section 1 — Picture the kernel

Think of AgentRuntime as an air-traffic controller:

  • The model suggests a flight plan (“call lookupOrder”)
  • The runtime checks the plan against rules (schema, policy, budgets)
  • Your tool code is the airplane that actually flies
  • The observation is the landing report for the next suggestion

If the model could call APIs itself, you would lose validation, approvals, redaction, and audit.

Section 2 — Where it lives in your app

Agents should be normal citizens of your HazelJS DI / HTTP app — same process as your API — not a separate “agent island” that reinvents auth and logging.

typescript
import { AgentModule, AgentRuntime } from '@hazeljs/agent';

// Typical production wiring:
// AgentModule.forRoot({ runtime: { llmProvider, policyEngine, … } })
// Inject AgentRuntime into a controller or service

const result = await runtime.execute('ops-desk', goal, {
  maxSteps: 8,
  loop: {
    maxIterations: 2,
    stages: ['plan', 'execute', 'critique', 'validate'],
  },
});

Starters such as hazeljs-agent-os-starter show this wiring with Inspector. Prefer that path when you leave script-level learning.

Section 3 — One step, expanded (memorize this table)

PhaseOwnerWhat a beginner should noticeFailure if skipped
Context assemblyRuntime (+ memory/RAG flags)Only budgeted text reaches the modelHallucinated state
Model proposalProvider via runtimeProposes tool or final textUnbounded free-form side effects
Arg validationTool contract / executorBad args never hit your APICorrupt production calls
Policy / approvalPolicyEngine, durableSuspendWrites can wait for a humanIrreversible damage
Tool executionHost ToolRegistry / Skillgate / MCPYour code runs with your credentialsModel-owned secrets
ObservationRuntimeResult becomes next contextBlind next step
CheckpointDurable run storeMid-run state survives crashUnsafe resume / lost work
StopmaxSteps, budgets, contractReason is recordedCost incidents / mystery failures

Section 4 — Inner loop vs outer confidence loop

Inner loop: think → (maybe) act → observe → repeat until final answer or maxSteps.

Outer loop (options.loop): plan → execute → critique → validate until successScore or maxIterations.

Use the outer loop when quality needs a critique pass. Do not use it as a substitute for good tool contracts. Pattern: /patterns/evaluator-optimizer.

Section 5 — Stop reasons you must care about

Operators cannot tune what they cannot see. Persist reasons such as:

  • success / completed
  • max steps reached
  • budget exhausted
  • policy denied
  • cancelled
  • suspended (waiting for human)
  • contract / SLO failed

If logs only say “failed,” you cannot improve autonomy safely.

Section 6 — Worked story: ORD-1001 status

  1. execute('ops-desk', 'Status of ORD-1001?')
  2. Runtime builds messages from system prompt + goal
  3. Model proposes lookupOrder({ orderId: 'ORD-1001' })
  4. Runtime validates parameters
  5. Your method returns { ok: true, status: 'shipped', … }
  6. Runtime appends observation
  7. Model returns a short final answer
  8. Runtime stops with success; you log executionId for the timeline

If step 4 fails validation, the tool never runs — and that is good.

Section 7 — Mental model checklist

  1. Goal is an input; done is checkable.
  2. Tools are typed contracts with a side-effect class.
  3. Budgets and maxSteps are hard stops.
  4. Durability is optional until the process can die mid-write — then mandatory.
  5. DNA/manifest describes desired identity; TypeScript still implements tools.
  6. The model proposes; the host executes.

Section 8 — What you will build next

You now have the vocabulary. The Agentic Development track turns it into a continuous Ops Desk build: scaffold → tool loop → budgets → context → HITL → tests → observability → CLI → checklist.

Checkpoint

  • You can narrate one execute turn without looking at notes
  • You know why the model must not hold production credentials
  • You can name at least four stop reasons

What to do next

Artifact: Annotated diagram notes of one AgentRuntime.execute turn with ToolRegistry + PolicyEngine

Sources

Related