class LittleGhost::Agent
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 when you need the final Run, or the streaming entrypoint 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 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 for outcomes, cancellation, and cleanup, and Assembly for the advanced run-scoped form.
Attributes
This Agent’s location in the bounded subagent tree.
Shared delegation tracker, when subagents are enabled.
Maximum Tool calls allowed during one invocation.
Runtime used to build this agent’s model, tools, workspace, and sandbox.
Run-scoped sandbox used for filesystem and process operations.
Run-scoped workspace available to Tools and extensions.
Public Class Methods
# File lib/little_ghost/agent.rb, line 311
Prepares per-agent state after a run-scoped instance is initialized.
# File lib/little_ghost/agent.rb, line 333
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:.
# File lib/little_ghost/agent.rb, line 357
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:.
# File lib/little_ghost/agent.rb, line 369
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:.
# File lib/little_ghost/agent.rb, line 396 private
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:.
# File lib/little_ghost/agent.rb, line 98 def agent_id(*values) return assembly_id if values.empty? assembly_id(values.fetch(0)) end
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.
# File lib/little_ghost/agent.rb, line 322
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.
# File lib/little_ghost/agent.rb, line 345
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:.
# File lib/little_ghost/agent.rb, line 381
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:.
# File lib/little_ghost/agent.rb, line 216 def capture_diagnostics(*values) return capture_diagnostics_value if values.empty? self.capture_diagnostics_value = values.fetch(0) == true end
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.
# File lib/little_ghost/agent.rb, line 277 def code_mode(engine: nil, except: nil, **options) unknown = options.keys - %i[sandbox limits] raise ArgumentError, "unknown keyword: #{unknown.first.inspect}" unless unknown.empty? declaration = options.merge(engine:, except:).compact self.code_mode_configuration_value = declaration.freeze end
# File lib/little_ghost/agent.rb, line 151 def limits(**values) return limits_value if values.empty? self.limits_value = limits.merge(values.transform_keys(&:to_sym)) end
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.
Source
# File lib/little_ghost/agent.rb, line 105 def logical_path parts = name.to_s.split("::") parts[-1] = parts.last.sub(/Agent\z/, "") if parts.any? parts.reject(&:empty?).map { |part| underscore(part) }.join("/") end
The underscored, namespace-aware path used for conventional prompt lookup.
Source
# File lib/little_ghost/agent.rb, line 126 def model(*values, &block) return model_value if values.empty? && !block if block && !values.empty? raise ArgumentError, "model accepts either one selection or a block" end if values.length > 1 raise ArgumentError, "model accepts one selection" end self.model_value = block || copy_model_selection(values.fetch(0)) end
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")
# File lib/little_ghost/agent.rb, line 543 def initialize( model: nil, runtime: nil, tools: [], template_resolver: nil, template_paths: [], run: nil, executor: nil, delegation_activity: nil, agent_path: Subagents::AgentPath::ROOT, max_turns: 100, max_tool_calls: 1_000, max_tool_result_tokens: DEFAULT_MAX_TOOL_RESULT_TOKENS, model_settings: {}, workspace: nil, sandbox: nil ) standalone = model.nil? && run.nil? super(run:, runtime:, workspace:, sandbox:, standalone:) if standalone @owns_resources = true @closed = false @close_mutex = Mutex.new @interjections_mutex = Mutex.new @active_interjections = [] return end @model = model @runtime = runtime || run&.runtime @run = run @workspace = workspace || run&.workspace @sandbox = sandbox || run&.sandbox if @runtime.is_a?(Runtime) && !@workspace @workspace = @runtime.build_workspace @sandbox ||= @runtime.build_sandbox(workspace: @workspace) end @owns_resources = run.nil? && (@workspace || @sandbox) binding = Tool::Binding.new(agent: self, run:, runtime: @runtime, model:, workspace: @workspace, sandbox: @sandbox) @tool_registry = ToolRegistry.new(tools, binding:) self.class.tool_declarations.each do |declaration| @tool_registry.register(declaration, replace: true) end initialize_code_mode @structured_output_strategy = StructuredOutput.resolve( self.class.result_schema, model:, ordinary_tools: @tool_registry.specifications ) @model_settings = model_settings.to_h.freeze @template_resolver = template_resolver || default_template_resolver(template_paths) @executor = executor || Support::Executor.new(runner: task_runner) @delegation_activity = delegation_activity @agent_path = Subagents::AgentPath.validate!(agent_path) @max_turns = Integer(max_turns) @max_tool_calls = Integer(max_tool_calls) @max_tool_result_tokens = Integer(max_tool_result_tokens) @closed = false @close_mutex = Mutex.new @exclusive_tools_mutex = Mutex.new @interjections_mutex = Mutex.new @active_interjections = [] @assembly_transitions_mutex = Mutex.new @assembly_transitions = {} @assembly_tool_batch_sizes = {} @assembly_transition = nil raise ArgumentError, "max_turns must be at least 1" if @max_turns < 1 raise ArgumentError, "max_tool_calls must be at least 1" if @max_tool_calls < 1 raise ArgumentError, "max_tool_result_tokens must be at least 1" if @max_tool_result_tokens < 1 @artifact_lifecycle = @runtime&.then do |resolved_runtime| resolved_runtime.runtime_hooks.find { |hook| hook.is_a?(Runtime::Hooks::Artifacts) } end apply_cancellation_decision!(run_callbacks(:after_initialize, self)) rescue @tool_registry&.close @code_mode_runtime&.close raise end
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.
# File lib/little_ghost/agent.rb, line 288 def prompt_local(name, *values, &resolver) raise ArgumentError, "Provide a prompt local value or block" if values.empty? && !resolver raise ArgumentError, "Provide a prompt local value or block, not both" unless values.empty? || !resolver self.prompt_local_values = prompt_local_values.merge(name.to_sym => resolver || values.fetch(0)) end
Adds a named value or resolver to every prompt rendered for the agent.
Source
# File lib/little_ghost/agent.rb, line 171 def result_schema(schema = nil, name: nil, description: nil, strategy: :auto, **schema_keywords) return result_schema_value if schema.nil? && schema_keywords.empty? && name.nil? && description.nil? && strategy == :auto if schema.nil? schema = schema_keywords elsif !schema_keywords.empty? raise ArgumentError, "Provide result_schema as a hash or keyword schema, not both" end raise ArgumentError, "result_schema must be a hash" unless schema.is_a?(Hash) normalized_schema = Class.new(Tool).tap { |tool| tool.input_schema(schema) }.input_schema validate_result_schema_keywords!(normalized_schema) unless normalized_schema["type"] == "object" raise ConfigurationError, "result_schema must describe a top-level object" end schema_name = (name || "#{agent_id}_result").to_s unless schema_name.match?(/\A[a-zA-Z0-9_-]{1,64}\z/) raise ConfigurationError, "result_schema name must contain 1-64 letters, numbers, underscores, or hyphens" end strategy = strategy.to_sym unless StructuredOutput::STRATEGIES.include?(strategy) raise ConfigurationError, "result_schema strategy must be auto, provider, or tool" end self.result_schema_value = { schema: normalized_schema, name: schema_name, description: description&.to_s, strategy: } end
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.
Source
# File lib/little_ghost/agent.rb, line 242 def system_prompt(*values, &block) return system_prompt_builder_value || system_prompt_value if values.empty? && !block self.system_template_value = nil if block self.system_prompt_value = nil self.system_prompt_builder_value = block else self.system_prompt_value = values.fetch(0).to_s self.system_prompt_builder_value = nil end end
The inline system prompt or prompt-building block.
Setting an inline prompt clears system_template so one source remains authoritative.
# File lib/little_ghost/agent.rb, line 227 def system_template(*values) return system_template_value if values.empty? self.system_template_value = values.fetch(0).to_s end
The explicit system prompt template path, when conventional lookup is not used.
Source
# File lib/little_ghost/agent.rb, line 260 def tools(*values) invalid = values.flatten.compact.find { |value| !value.is_a?(Class) } if invalid raise ConfigurationError, "Class-level tools must be classes" end declarations = tool_declarations_value + values self.tool_declarations_value = declarations tool_declarations end
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.
Public Instance Methods
Source
# File lib/little_ghost/agent.rb, line 835 def close resources, interjections = @close_mutex.synchronize do return if @closed @closed = true [ [@code_mode_runtime, tool_registry, (@sandbox if @owns_resources), (@workspace if @owns_resources)], @interjections_mutex.synchronize { @active_interjections.dup } ] end first_error = nil interjections.each do |active| active.close(AgentInterjectionError.new("Agent was closed")) end resources.each do |resource| resource.close if resource.respond_to?(:close) rescue => error first_error ||= error end raise first_error if first_error end
Closes owned tools, interjections, sandbox, and workspace resources. The operation is idempotent and re-raises the first cleanup failure.
# File lib/little_ghost/agent.rb, line 666 def interject( message, cancellation_token: Support::CancellationToken.new, deadline: nil, target_operation_id: nil, interjection_id: nil, batch_key: nil, metadata: {} ) message = Message.new(role: :user, content: message) if message.is_a?(String) raise ArgumentError, "interject message must be a String or LittleGhost::Message" unless message.is_a?(Message) safe_content = message.content.all? do |content| content.is_a?(Content::Text) || content.is_a?(Content::Image) || content.is_a?(Content::Document) end unless safe_content raise ArgumentError, "interject message content must contain only text, images, or documents" end interjections = @interjections_mutex.synchronize do active = if target_operation_id @active_interjections.select { |candidate| candidate.target_operation_id == target_operation_id } else @active_interjections end if active.empty? raise AgentInterjectionError, "Agent is not currently running" end if active.length > 1 raise AgentInterjectionError, "Agent has multiple active invocations; the interjection target is ambiguous" end active.first end options = {batch_key:, metadata:} options[:id] = interjection_id unless interjection_id.nil? ticket = interjections.enqueue(message, **options) instrument( :agent_interjection_queued, parent_operation_id: interjections.operation_id, interjection_id: ticket.id, event_kind: :interjection, diagnostic: {input: diagnostic_message(message)} ) begin response = ticket.value(cancellation_token:, deadline:) interjections.release(ticket) response rescue => error interjections.release(ticket, withdraw: true) instrument( :agent_interjection_failed, parent_operation_id: interjections.operation_id, interjection_id: ticket.id, event_kind: :interjection, error_type: error.class.name, diagnostic: {exception: diagnostic_exception(error)} ) raise end end
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.
Source
# File lib/little_ghost/agent.rb, line 819 def prompt_locals self.class.prompt_local_resolvers.to_h do |name, resolver| value = if resolver.respond_to?(:call) resolver.parameters.empty? ? instance_exec(&resolver) : resolver.call(self) else resolver end [name, value] end.freeze end
Materializes and freezes the prompt locals declared on the agent class.
# File lib/little_ghost/agent.rb, line 737 def 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 ) if standalone? raise ArgumentError, "input is required" if input.nil? return build_run(entrypoint_payload(input, { history:, context:, settings:, template_paths:, deadline_at: deadline, cancellation_token: }.compact)).each end raise ArgumentError, "input is required" if input.nil? history ||= [] context ||= {} settings ||= {} template_locals ||= {} template_paths ||= [] invocation_paths = Array(template_paths).map do |path| unless path.is_a?(LittleGhost::TrustedPath) raise ArgumentError, "invocation template paths must be LittleGhost::TrustedPath values" end path end settings = @model_settings.merge(settings) Enumerator.new do |events| interjections = AgentInterjections.new run_context = RunContext.new( state: context, cancellation_token: cancellation_token, deadline: deadline, metadata: {agent_id: self.class.agent_id}, checkpoint:, conversation_id:, interjection_metadata:, interjection_ids: ) begin with_invocation(run_context) do execute( input, history: history, context: run_context, settings: settings, template_locals: template_locals, template_paths: invocation_paths, events: events, parent_operation_id:, interjections:, interject_ready: ) end rescue => error interjections.close(error) raise ensure @code_mode_runtime&.close(context: run_context) interjections.close(AgentInterjectionError.new("Agent finished before the interjection was delivered")) unregister_interjections(interjections) end end end
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.
Protected Instance Methods
# File lib/little_ghost/agent.rb, line 869 def model_tools(tools, context:, turn:) return tools unless @code_mode_runtime exceptions = Array(@code_mode_declaration[:except]).map(&:to_s) tools.select do |specification| name = specification.fetch(:name, specification["name"]).to_s tool = tool_registry.fetch(name) if tool_registry.names.include?(name) exceptions.include?(name) || %w[exec wait stop].include?(name) || tool.is_a?(Subagents::ControlTool) || !tool end end
Returns the tools exposed to the model for turn. Subclasses may override this hook to filter the already-authorized tool list.
# File lib/little_ghost/agent.rb, line 862 def with_invocation(_context) yield end
Yields around one invocation. Subclasses may override this hook to install invocation-scoped state and must yield exactly once.
# File lib/little_ghost/agent.rb, line 884 def with_tool_execution(_execution) yield end
Yields around one tool execution. Subclasses may override this hook for execution-scoped behavior and must yield exactly once.