# Class LittleGhost::Agent

Documentation version: Edge

Canonical HTML: https://littleghostai.org/docs/LittleGhost/Agent.html

Defines one reusable model-driven behavior with prompts, tools, and limits.
Each Agent subclass describes one application role with an inheritable Ruby
DSL. It can answer, stream, call tools, and delegate work.

Start with one role and add capabilities as its work grows:

    class CustomerSupportAgent < LittleGhost::Agent
      description "Handles support requests"
      model "openrouter:openai/gpt-5.6-luna"
      system_prompt "Answer customer questions clearly."
    end

    run = CustomerSupportAgent.ask("Why is transfer 481 pending?")
    run.completed? # => true
    run.response
    # One possible response: Transfer 481 is waiting for the receiving bank.

An Agent is the smallest Assembly: it owns one model loop while inheriting the
same `ask` and `stream_ask` entrypoints as coordinated assemblies. Add tools
for application operations and subagents for model-directed delegation.

Call a named Agent with [ask](Assembly.md#method-c-ask) when you
need the final Run, or the streaming
[entrypoint](Assembly.md#method-c-stream_ask) when you want events
as the answer arrives.

Most applications call a named Agent class. LittleGhost automatically reuses
the active Configuration's shared Runtime while building a fresh top-level Run
for every call. Passing `runtime:` is an advanced option for an
explicitly isolated setup.

Agent declarations are inherited. Define a short prompt inline, or place a
growing prompt in `app/prompts/customer_support/system.erb` for
`CustomerSupportAgent`. The [Prompts as Views
guide](../prompt_views.md) explains conventional lookup,
locals, and partials. Optional features such as skills, context management,
loop detection, and delegation stay inactive until their DSL is used.

Models may return text or locally validated structured data. LittleGhost hides
unexpected Tool exception messages from the model. See
[Run](Run.md) for outcomes, cancellation, and cleanup, and
[Assembly](Assembly.md) for the advanced run-scoped form.

## Inheritance

`LittleGhost::Agent < Assembly`

## Attributes

<a id="attribute-i-agent_path"></a>
### `agent_path` (R)

This Agent's location in the bounded subagent tree.

<a id="attribute-i-delegation_activity"></a>
### `delegation_activity` (R)

Shared delegation tracker, when subagents are enabled.

<a id="attribute-i-max_tool_calls"></a>
### `max_tool_calls` (R)

Maximum Tool calls allowed during one invocation.

<a id="attribute-i-model"></a>
### `model` (R)

The resolved model used by this run-scoped Agent.

<a id="attribute-i-run"></a>
### `run` (R)

The owning Run, or `nil` for a standalone entrypoint.

<a id="attribute-i-runtime"></a>
### `runtime` (R)

Runtime used to build this agent's model, tools, workspace, and sandbox.

<a id="attribute-i-sandbox"></a>
### `sandbox` (R)

Run-scoped sandbox used for filesystem and process operations.

<a id="attribute-i-tool_registry"></a>
### `tool_registry` (R)

Tools created and bound for this Agent's owning Run.

<a id="attribute-i-workspace"></a>
### `workspace` (R)

Run-scoped workspace available to Tools and extensions.

## Class methods

<a id="method-c-after_initialize"></a>
### `.after_initialize`

```ruby
after_initialize(callable = nil, prepend: false) { |agent| ... } -> self
```

Prepares per-agent state after a run-scoped instance is initialized.

<a id="method-c-after_invocation"></a>
### `.after_invocation`

```ruby
after_invocation(callable = nil, prepend: false) { |payload| ... } -> self
```

Observes or transforms the terminal invocation payload.

The payload is `{result: RunResult}`. A replacement must contain
`:result`. Cancellation stops result delivery. A callback may
accept `context:`.

<a id="method-c-after_model"></a>
### `.after_model`

```ruby
after_model(callable = nil, prepend: false) { |payload| ... } -> self
```

Observes or transforms a successful model response.

The payload contains `:request`, `:response`
(ModelResponse), and zero-based `:turn`. A replacement must contain
`:response`. Cancellation stops the invocation. A callback may
accept `context:`.

<a id="method-c-after_model_error"></a>
### `.after_model_error`

```ruby
after_model_error(callable = nil, prepend: false) { |payload| ... } -> self
```

Handles a model error before it leaves the agent loop.

The payload contains `:request`, `:error`, zero-based
`:turn`, and `:parent_operation_id`. Replacing
`:request` with a ModelRequest retries the model call, up to the
framework recovery limit. Cancellation stops the invocation. A callback may
accept `context:`.

<a id="method-c-after_tool"></a>
### `.after_tool`

```ruby
after_tool(callable = nil, prepend: false) { |payload| ... } -> self
```

Observes or transforms a completed tool result.

The payload contains the before-tool fields plus the normalized
`:result`. A replacement must contain `:result`.
Cancellation is not consumed. A callback may accept `context:`.

<a id="method-c-agent_id"></a>
### `.agent_id`

```ruby
agent_id() -> String
agent_id(value) -> String
```

The stable identifier used in telemetry, delegation, and default tool names.
Named subclasses derive it from their underscored class name without an
`Agent` suffix; passing `value` replaces that default.

<a id="method-c-before_invocation"></a>
### `.before_invocation`

```ruby
before_invocation(callable = nil, prepend: false) { |payload| ... } -> self
```

Runs before one invocation begins.

The payload is `{messages: Array<Message>}`. A replacement must
contain `:messages`. Cancellation stops the invocation. A callback
may also accept `context:` to receive the current RunContext.

<a id="method-c-before_model"></a>
### `.before_model`

```ruby
before_model(callable = nil, prepend: false) { |payload| ... } -> self
```

Runs before a model request is sent.

The payload contains `:request` (ModelRequest), zero-based
`:turn`, and `:parent_operation_id`. A replacement must
contain `:request`. Cancellation stops the invocation. A callback
may accept `context:`.

<a id="method-c-before_tool"></a>
### `.before_tool`

```ruby
before_tool(callable = nil, prepend: false) { |payload| ... } -> self
```

Runs after validation but before a tool call starts.

The payload contains `:tool_use`, the bound `:tool`,
`:operation_id`, and `:parent_operation_id`.
Cancellation returns a model-visible Tool error, so its reason must be safe to
disclose. Replacements are not consumed. A callback may accept
`context:`.

<a id="method-c-capture_diagnostics"></a>
### `.capture_diagnostics`

```ruby
capture_diagnostics() -> true or false
capture_diagnostics(value) -> true or false
```

Whether agent-layer diagnostics may include model and tool content.

Capture defaults to `true`, and only a literal `true` enables it. This setting
does not disable run-level input and output capture from an enabled
process-wide Support::ContentCapture policy. For sensitive work, also install
Support::ContentCapture.disabled or an appropriate scrubber through
Instrumentation.capture_content.

<a id="method-c-code_mode"></a>
### `.code_mode`

```ruby
.code_mode(engine: nil, except: nil, **options)
```

Enables code mode for this agent. `except` names the application Tools that
remain model-facing; every other application Tool moves into the engine
catalog and is called through the parent-process Broker. Framework-owned
subagent controls remain model-facing automatically.

<a id="method-c-limits"></a>
### `.limits`

```ruby
limits() -> Hash
limits(**values) -> Hash
```

Inherited execution limits for model turns, tool calls, and tool output.

Keyword arguments merge into the current limits and the zero-argument form
returns them.

<a id="method-c-logical_path"></a>
### `.logical_path`

```ruby
.logical_path()
```

The underscored, namespace-aware path used for conventional prompt lookup.

<a id="method-c-model"></a>
### `.model`

```ruby
model() -> String, Symbol, Hash, Proc, nil
model(role_or_target) -> String, Symbol
model(provider:, model:, **settings) -> Hash
model { |invocation| ... } -> Proc
```

Selects this agent's model by logical role, canonical
`provider:model-id` target, or an inline mapping with `provider`,
`model`, and trusted model settings. The provider names a configured
connection, not necessarily its adapter.

Pass a block to choose any supported form from each Invocation at run time.
Inline mappings use flat settings, for example:

    model(provider: "openai", model: "gpt-5.6-luna", reasoning_effort: "high")

<a id="method-c-new"></a>
### `.new`

```ruby
new(runtime: nil) -> Agent
new(model:, runtime:, tools:, run:, ...) -> Agent
```

Creates either a standalone entrypoint or a run-scoped agent.

The first form is the application-facing entrypoint. It may be reused for
independent concurrent calls and creates a fresh Run for each one. The second
form is run-scoped; Runtime builders supply its dependencies and it must not
outlive or be shared outside its owning Run.

<a id="method-c-prompt_local"></a>
### `.prompt_local`

```ruby
.prompt_local(name, *values, &resolver)
```

Adds a named value or resolver to every prompt rendered for the agent.

<a id="method-c-result_schema"></a>
### `.result_schema`

```ruby
result_schema() -> Hash, nil
result_schema(schema, name: nil, description: nil, strategy: :auto) -> Hash
result_schema(name: nil, description: nil, strategy: :auto, **schema) -> Hash
```

Declares a strict JSON-object result contract. Every object must set
`additionalProperties: false` and require each property. Automatic
strategy selection prefers provider-native structured output and falls back to
a terminal tool when supported.

During execution, a missing or invalid result receives one repair attempt
before LittleGhost::StructuredResultError is raised inside the owning Run. A
top-level `ask` records it on a failed Run. Invalid schemas and strategies
raise LittleGhost::ConfigurationError before execution begins.

<a id="method-c-system_prompt"></a>
### `.system_prompt`

```ruby
system_prompt() -> String, Proc, nil
system_prompt(value) -> String
system_prompt { |locals| ... } -> Proc
```

The inline system prompt or prompt-building block.

Setting an inline prompt clears `system_template` so one source remains
authoritative.

<a id="method-c-system_template"></a>
### `.system_template`

```ruby
system_template() -> String, nil
system_template(path) -> String
```

The explicit system prompt template path, when conventional lookup is not
used.

<a id="method-c-tools"></a>
### `.tools`

```ruby
.tools(*values)
```

Adds tool or provider classes to the agent.

Every declaration must be a class. Pass Tool classes directly, or pass
provider classes that supply tools dynamically through
`tools(binding)`. Multiple declarations are cumulative.

## Instance methods

<a id="method-i-close"></a>
### `#close`

```ruby
#close()
```

Closes owned tools, interjections, sandbox, and workspace resources. The
operation is idempotent and re-raises the first cleanup failure.

<a id="method-i-interject"></a>
### `#interject`

```ruby
#interject(message,
      cancellation_token: Support::CancellationToken.new,
      deadline: nil,
      target_operation_id: nil,
      interjection_id: nil,
      batch_key: nil,
      metadata: {})
```

Adds an interjection and returns the model's immediate result details.

Use `target_operation_id` when an agent has multiple active invocations.
Messages may contain only text, image, or document content. The returned
result value exposes `text`, `tool_calls?`, `interjection_ids`, and
`batch_key`; tool calls may continue after this result. Depend on these
methods rather than the result's concrete class.

<a id="method-i-prompt_locals"></a>
### `#prompt_locals`

```ruby
#prompt_locals()
```

Materializes and freezes the prompt locals declared on the agent class.

<a id="method-i-stream"></a>
### `#stream`

```ruby
#stream(input = nil,
      history: nil,
      context: nil,
      cancellation_token: Support::CancellationToken.new,
      deadline: nil,
      settings: nil,
      template_locals: nil,
      template_paths: nil,
      parent_operation_id: nil,
      checkpoint: nil,
      conversation_id: nil,
      interjection_metadata: nil,
      interjection_ids: [],
      interject_ready: nil)
```

Streams one invocation as StreamEvent objects.

Agents built inside a run accept history, JSON-like context, cancellation,
deadlines, settings, and trusted invocation template paths. An Agent instance
may be streamed only by its owning Run. Every template path must be an
application-created TrustedPath; the wrapper records a trust decision and must
never contain unchecked request or model input.

<a id="method-i-tools"></a>
### `#tools`

```ruby
#tools()
```

The Tool registry available during this Agent run.
