# LittleGhost complete documentation Version: Edge --- Source: https://mattyr.github.io/little_ghost/docs/index.md # LittleGhost documentation Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/ > **Using a coding agent?** Start with > [`llms.txt`](https://mattyr.github.io/little_ghost/llms.txt) for a concise map > of the guides and API. [`llms-full.txt`](https://mattyr.github.io/little_ghost/llms-full.txt) > contains the complete documentation in one file. LittleGhost is a Ruby library for building AI features with agents and composable assemblies. With `OPENROUTER_API_KEY` set, start with one class, give it a prompt, and call it like the rest of your application code: ```ruby require "little_ghost" class CustomerSupportAgent < LittleGhost::Agent model "openrouter:openai/gpt-5.6-luna" system_prompt "Answer customer questions clearly and concisely." end run = CustomerSupportAgent.ask("Draft a friendly greeting for a customer.") run.response # One possible response: Hi! How can I help today? ``` That small definition is already a complete agent. LittleGhost makes the model call, tracks usage, supports streaming, and closes the resources it creates for the request. Add a tool when the agent needs something from your application. Bring in more agents when the work grows. Model requests may send system instructions, caller input, conversation history, Tool results, and attachments to the selected provider. Model wording can vary between runs. [Models and Providers](models_and_providers.md) explains how to choose where each Agent sends its requests. ## Install the gem LittleGhost requires Ruby 3.3 or newer. Add it to your bundle and provide a provider credential: ```ruby gem "little_ghost" ``` ```sh $ bundle install $ export OPENROUTER_API_KEY="..." ``` OpenRouter keeps the first setup to one credential. It is not required: LittleGhost also includes adapters for OpenAI-compatible APIs, Anthropic, Gemini, Vertex AI, and Bedrock. [Running in Production](production.md) shows how to configure providers and give model choices application-facing names. LittleGhost runs inside your Ruby process. Use it from a controller, job, CLI, or service. If you want a conventional layout, start with `app/agents`, `app/assemblies`, `app/prompts`, and `app/tools`. ## Give an agent real capabilities Tools let an agent call focused parts of your application: ```ruby class HelpCenterLookupTool < LittleGhost::Tool description "Look up a help center entry by topic." input_schema( type: "object", properties: {topic: {type: "string"}}, required: ["topic"], additionalProperties: false ) def call(input) {"refunds" => "Refunds are available within 30 days."} .fetch(input.fetch("topic"), "No help center entry found.") end end class CustomerSupportAgent < LittleGhost::Agent model "openrouter:openai/gpt-5.6-luna" system_prompt "Check the help center before stating company guidance." tools HelpCenterLookupTool end ``` The schema checks the shape of the input. Your Ruby code still decides whether the operation is allowed. The result goes back to the model as context. An ordinary Tool runs in your Ruby process. When a Tool needs files or child processes, it can delegate that work through a Sandbox. Code mode goes one step further: a sandboxed interpreter can compose several Tools, while every Tool call still returns to your Ruby Tool for validation and permission checks. ## Grow without changing the caller An **agent** owns one model loop. An **assembly** is one or more agents working as a unit. You call either one the same way: ```ruby CustomerSupportAgent.ask(question) ResponseWorkflow.ask(question) ProblemSolverSwarm.ask(question) SupportFlowGraph.ask(question) ``` Choose the coordination style that matches who should control the next step: - A **subagent** lets a model delegate an addressable task. - A **workflow** uses ordinary Ruby for ordering and branching. - A **swarm** lets configured agents choose permitted handoffs. - A **graph** makes allowed routes explicit as nodes and edges. A Workflow or Graph can contain agents, other assemblies, or both. Named classes are the clearest place to begin. Builders are there when your application discovers the participants or routes at runtime. ```text request ──> CustomerSupportAgent request ──> ResponseWorkflow ──> ResearchAgent ──> CustomerSupportAgent request ──> ProblemSolverSwarm ──> TriageAgent ──handoff──> BillingAgent request ──> SupportFlowGraph ──> TriageAgent ──edge──> ResponseAgent ``` The result stays familiar too. Every call returns a `Run` with the response, outcome, usage, and any final error. A coordinated assembly also records which participants ran. Use `.stream_ask` to watch the work as it happens. LittleGhost is pre-1.0. Pin the gem version and review release notes before upgrading, because interfaces may change between releases. ## Keep going - [Getting Started](getting_started.md) takes you from installation to a tool-backed, streaming agent. - [Core Concepts](core_concepts.md) builds the mental model from Agent to Assembly. - [Models and Providers](models_and_providers.md) gives shared model choices application-facing names. - [Prompts as Views](prompt_views.md) gives growing instructions, shared pieces, and application values a natural home. - [Tools](tools.md) explains how models call focused Ruby operations. - [Structured Results and Content](structured_outputs_and_content.md) covers checked result shapes, images, and documents. - [Compose Agents](assemblies.md) walks through workflows, swarms, graphs, nesting, and builders. - [Skills](skills.md) organizes reusable instructions and supporting resources. - [Workspaces and Sandboxes](sandboxing.md) gives files and child processes a deliberate place to run. - [Code Mode](code_mode.md) lets a model compose Tools in sandboxed Ruby or optional JavaScript. - [Integrations](integrations.md) connects MCP, AG-UI, and OpenTelemetry. - [Running in Production](production.md) covers configuration, saved conversations, supervision, and observability. - [API reference](LittleGhost.md) provides exact method signatures and ownership rules. ### For contributors See the [contributing guide](https://github.com/mattyr/little_ghost/blob/main/CONTRIBUTING.md), [Code of Conduct](https://github.com/mattyr/little_ghost/blob/main/CODE_OF_CONDUCT.md), and [security policy](https://github.com/mattyr/little_ghost/blob/main/SECURITY.md). ```sh $ bundle install $ bundle exec rake test $ bundle exec standardrb --no-fix ``` LittleGhost is available under the MIT License. --- Source: https://mattyr.github.io/little_ghost/docs/getting_started.md # Getting Started Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/getting_started.html In this guide, you'll run an agent, connect it to a small help center, and stream its answer. The whole feature stays in ordinary Ruby. ## Install the gem LittleGhost requires Ruby 3.3 or newer. Add the gem to your `Gemfile`, install it, and set a provider credential: ```ruby gem "little_ghost" ``` ```sh $ bundle install $ export OPENROUTER_API_KEY="..." ``` Use your application's secret manager outside a local shell, and never commit provider credentials. This guide uses OpenRouter because one credential is enough to begin. LittleGhost can use other provider connections too; you will configure those in [Running in Production](production.md). ## See your first answer Create `customer_support_agent.rb`: ```ruby require "little_ghost" class CustomerSupportAgent < LittleGhost::Agent model "openrouter:openai/gpt-5.6-luna" system_prompt "Answer customer questions clearly and concisely." end run = CustomerSupportAgent.ask("Can I change the address on my order?") if run.completed? puts run.response else warn "Support request ended as #{run.outcome}: #{run.error&.class}" end ``` Run the file and you have a working AI feature: ```sh $ ruby customer_support_agent.rb ``` `CustomerSupportAgent.ask` creates a `LittleGhost::Run` for this request. When the work finishes, the Run holds the outcome and response. The inline prompt keeps this first example visible in one place. When the instructions grow, [Prompts as Views](prompt_views.md) moves them into a conventional ERB file without adding setup to the Agent. The selected external provider may receive system instructions, caller input, conversation history, tool results, and attachments. Model wording can vary, so use application code—not a prompt—when a rule must always hold. ## Connect the agent to your application The first agent can answer general questions. A **tool** gives it a focused operation backed by your Ruby code: ```ruby class HelpCenterLookupTool < LittleGhost::Tool HELP_CENTER_ENTRIES = { "refunds" => "Refunds are available within 30 days of purchase.", "shipping" => "Standard shipping takes three to five business days." }.freeze description "Look up a help center entry by topic." input_schema( type: "object", properties: { topic: {type: "string", enum: HELP_CENTER_ENTRIES.keys} }, required: ["topic"], additionalProperties: false ) def call(input) HELP_CENTER_ENTRIES.fetch(input.fetch("topic")) end end ``` Make the tool available to the agent and tell the model when to use it: ```ruby class CustomerSupportAgent < LittleGhost::Agent description "Answers customer support questions." model "openrouter:openai/gpt-5.6-luna" system_prompt <<~PROMPT Answer clearly and do not invent company guidance. Check the help center before stating company guidance. PROMPT tools HelpCenterLookupTool end run = CustomerSupportAgent.ask( "I bought an item two weeks ago. Can I get a refund?" ) run.response # One possible response: # Refunds are available within 30 days, so your purchase is eligible. ``` LittleGhost checks the model's arguments before it calls `HelpCenterLookupTool#call`. The Tool's result then becomes context for the model. ### Use application context for private data The schema checks shape, not permission. When a Tool reads private data or changes something, use identity and account information established by your application rather than asking the model to supply it. While an Agent is working, LittleGhost binds each Tool instance to the current Run. The Tool can read request values through its `run` accessor: ```ruby class OrderStatusTool < LittleGhost::Tool ORDER_STATUSES = { ["user-7", "account-2", "481"] => "out for delivery" }.freeze description "Look up an order that belongs to the current customer." input_schema( type: "object", properties: {order_number: {type: "string"}}, required: ["order_number"], additionalProperties: false ) def call(input) lookup = [ run.invocation.actor_id, run.invocation.context.fetch("account_id"), input.fetch("order_number") ] ORDER_STATUSES.fetch(lookup) do raise LittleGhost::ToolError, "Order not found" end end end class CustomerSupportAgent < LittleGhost::Agent tools HelpCenterLookupTool, OrderStatusTool end run = CustomerSupportAgent.ask( "Where is order 481?", actor_id: "user-7", context: {account_id: "account-2"} ) ``` Here, `order_number` came from the model. The application supplied `actor_id` and `account_id` after authenticating the caller. LittleGhost places those request values on `run.invocation`; context keys become strings. > **Safety note:** Treat model-selected Tool arguments like any other external > input. Check permission using the current user and account before returning > private data or performing a write. That is enough to authorize the first Tool safely. [Core Concepts](core_concepts.md) names the request and working-state objects behind `run`, and [Running in Production](production.md) explains what changes when you add saved conversations. ## Stream the same agent Use `.stream_ask` when a console, HTTP response, or user interface should receive progress as it happens: ```ruby stream = CustomerSupportAgent.stream_ask("Can I get a refund?") run = stream.each do |event| case event.type when :text_delta print event.data.fetch(:text) when :run_error warn event.data.fetch(:message) end end puts "\n#{run.response}" if run.completed? warn run.error.class.name if run.failed? ``` The stream yields `LittleGhost::StreamEvent` values. Text, tool activity, usage, and completion all look the same across providers. When enumeration finishes, `.each` returns the same `LittleGhost::Run` that now holds the final outcome and response. ## Give the code a home LittleGhost does not require an application layout. Keep definitions beside related application code, or use these optional conventions: ```text app/ ├── agents/ │ └── customer_support_agent.rb ├── assemblies/ │ └── response_workflow.rb ├── prompts/ │ └── customer_support/ │ └── system.erb └── tools/ └── help_center_lookup_tool.rb ``` You now have the smallest useful LittleGhost application: one Agent, one Tool, and one familiar Ruby call. When the feature grows, the calling style stays the same. An **assembly** lets one or more agents work as a unit while keeping `.ask` and `.stream_ask`. Read [Core Concepts](core_concepts.md) next and grow this Agent into a larger system. --- Source: https://mattyr.github.io/little_ghost/docs/core_concepts.md # Core Concepts Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/core_concepts.html Define an Agent in a Ruby class, then call it with `.ask`. ```ruby class CustomerSupportAgent < LittleGhost::Agent model "openrouter:openai/gpt-5.6-luna" system_prompt "Answer customer questions clearly." tools HelpCenterLookupTool end run = CustomerSupportAgent.ask("Where is my order?") run.response ``` From there, add only what the work needs. Give the agent a tool. Let it ask a specialist for help. Or coordinate several agents while the rest of your application keeps making the same call. ## An Agent owns one model loop An **Agent** defines one model-driven behavior. It chooses the model, supplies the instructions and tools, and carries one request through to an answer. The class holds the behavior you want to reuse. Each call brings its own input, history, context, settings, and attachments. Request data never needs to live on the class. ```text CustomerSupportAgent ├── model selection ├── system prompt ├── HelpCenterLookupTool └── limits and optional capabilities ``` An Agent can return text or checked, structured data. You can add streaming, saved conversations, or callbacks later. None of them are required to begin. ## A Tool connects the model to Ruby A **Tool** is one focused thing an agent can ask your application to do. It has a name, a description, an input schema, and the Ruby code that does the work. ```ruby class HelpCenterLookupTool < LittleGhost::Tool description "Look up a help center entry by topic." input_schema( type: "object", properties: {topic: {type: "string"}}, required: ["topic"], additionalProperties: false ) def call(input) {"refunds" => "Refunds are available within 30 days."} .fetch(input.fetch("topic")) end end ``` LittleGhost checks the model's arguments, calls the Tool, and gives the result back to the model. The schema checks shape, not permission. Check permission inside the Tool using identity and account information from your application. [Tools](tools.md) follows that path from model input to application code, including run-scoped bindings, concurrency, retries, and sandbox delegation. ## A Run owns one top-level execution Every `.ask` or `.stream_ask` creates a **Run**. Think of it as the record of one trip through LittleGhost. It opens what the request needs, records how the work ended, and closes the resources it owns. ```ruby run = CustomerSupportAgent.ask("Where is order 481?") run.completed? # => true run.response # One possible response: Order 481 is out for delivery. run.usage # => normalized token usage run.result # => the complete LittleGhost::RunResult ``` The Agent defines reusable behavior; the Run records what happened this time. ### Follow one request One Run owns the trip from request to result: ```text Run ├── Invocation: caller input, history, and application context ├── RunContext: mutable working state for this execution └── Agent and Tools ──> RunResult ``` An **Invocation** is the request in LittleGhost's standard shape. Its `context` contains current request values supplied by your application. A Tool can read those values through `run.invocation.context` when it checks permission. A **Session** stores conversation state between Runs when persistence is configured. The **RunContext** carries mutable working state in `context.state` during one Run. LittleGhost loads saved Session state before adding the current Invocation context. Recheck saved values before using them for permission decisions. A Tool's **Binding** gives the Tool access to objects created for this run, including the Agent, Run, Workspace, and Sandbox. These objects are separate from arguments chosen by the model. [Tools](tools.md) explains the binding; [Workspaces and Sandboxes](sandboxing.md) explains delegated files and child processes. The final **RunResult** keeps the complete assembly result. Its `text` is the final text answer. Its `output` returns structured data when the Agent declared a result schema, and text otherwise. The top-level `Run#response` is always the caller-facing text. ### See how a call ended Top-level calls normally return a Run, even when execution fails. The terminal event carries the same outcome when you stream: | What happened | Run outcome | Terminal event | What Ruby does | | --- | --- | --- | --- | | The assembly completed | `completed` | `:run_stop` | Returns the Run | | Model, provider, or assembly execution failed | `failed` | `:run_error` | Returns the Run; inspect `run.error` | | The deadline stopped work | `partial` | `:run_partial` | Returns the Run with any response produced so far | | Cancellation stopped work | `cancelled` | `:run_cancel` | Returns the Run without a response | | Tool input or a `ToolError` failed | The model may recover | No terminal event by itself | Gives a safe error result back to the model | | Input, configuration, or resources failed before a Run could start | No Run exists | None | Raises the exception | Unexpected Tool exception messages are hidden from the model. The original exception remains available to application callbacks and diagnostics. Failures while closing resources, delivering events, or reporting instrumentation sit outside the normal result path. They raise a Ruby exception because LittleGhost can no longer promise that it delivered a clean ending. [Running in Production](production.md) covers supervision and shutdown. ## An Assembly can look like one Agent One model loop is not always enough. LittleGhost calls any unit that a caller can invoke like an Agent an **Assembly**. An Agent is the smallest Assembly. Workflow, Swarm, and Graph coordinate several participants while preserving the same entrypoints: ```ruby CustomerSupportAgent.ask(question) ResponseWorkflow.ask(question) ProblemSolverSwarm.ask(question) SupportFlowGraph.ask(question) ``` That shared calling style is what makes composition feel natural. A controller, job, or CLI does not need to know whether one Agent answered or a whole support process worked together. ## Choose who controls the next step The coordination types differ mainly in who decides what happens next: | Need | Choose | Who controls the next step? | | --- | --- | --- | | One model-driven behavior | Agent | The active model loop | | A model should delegate a named task | Subagent | The parent model | | Ruby should enforce ordering or branching | Workflow | The workflow's Ruby code | | Specialists should choose permitted handoffs | Swarm | The active agent | | Allowed routes should be visible in advance | Graph | Declared nodes and edges | ### Subagents bring in a specialist A **subagent** is a specialist that a parent Agent can call for help. The parent model chooses when to delegate, reads the result, and then continues its own answer. ```ruby class CustomerSupportAgent < LittleGhost::Agent model "openrouter:openai/gpt-5.6-luna" subagent ResearchAgent, kind: "research" end ``` Use a subagent when delegation is part of one model's decision-making. Use a Workflow when application code must guarantee that a step happens. When an Agent also uses code mode, subagent controls stay in the Agent's conversation. Code-mode programs can compose ordinary Tools, while spawning, messaging, and checking on subagents remain decisions for the parent model. ### Workflows make Ruby the coordinator A **Workflow** coordinates work with ordinary Ruby. Its `perform` method can call an Agent or another Assembly, read a result, choose a branch, or run independent steps together. `invoke` prepares a lazy child call. Reading `.output` runs an intermediate child. Return the final `invoke` itself, without reading its output, so that answer can stream to the caller. ```ruby class ResponseWorkflow < LittleGhost::Workflow private def perform research = invoke(ResearchAgent).output invoke CustomerSupportAgent, input: <<~PROMPT #{input.text} Research: #{research} PROMPT end end ``` Workflow children receive the caller's history and application context by default. Pass `history: []`, `context: {}`, or redacted values when a participant should receive less. ### Swarms let agents hand work to one another A **Swarm** is a group of Agents that can hand work to one another. One member is active at a time. It can answer the caller or choose one of its allowed specialists. ```ruby class ProblemSolverSwarm < LittleGhost::Swarm member TriageAgent member BillingAgent member AccountAgent start TriageAgent handoff TriageAgent, to: [BillingAgent, AccountAgent] end ``` A Swarm is intentionally agent-to-agent. Its members are Agents, not other kinds of Assembly. Caller history and application context stay hidden unless a member opts in. A handoff message comes from another model, so a receiving Agent should use it as context rather than proof that an action is permitted. ### Graphs make routes visible A **Graph** connects named Assembly nodes with declared edges. Nodes can contain Agents, Workflows, Swarms, or other Graphs. ```ruby class SupportFlowGraph < LittleGhost::Graph node :triage, TriageAgent node :billing, BillingAgent node :general, CustomerSupportAgent node :respond, CustomerSupportAgent start :triage edge :triage, :billing do |state| state.result(:triage).output == "billing" end edge :triage, :general edge :billing, :respond edge :general, :respond finish :respond end ``` Graph nodes receive the original task and results from the nodes immediately before them. They do not receive caller history or application context unless their declarations opt in. [Compose Agents](assemblies.md) explains parallel routes, joins, input mapping, and data boundaries. ## One result, even when several agents help Every assembly produces the same top-level `Run` and final `RunResult`. Composite assemblies also keep a size-limited record of the participants that ran: ```ruby run = SupportFlowGraph.ask("Why was I charged twice?") run.response run.result.steps run.result.trajectory.transitions ``` This record shows which participants ran. [Compose Agents](assemblies.md) explains builders, detailed routing records, and live events from nested Agents. The pieces now fit together: Agents define behavior. Tools connect them to Ruby. Runs record one execution. Assemblies let the system grow without changing the caller. Continue with [Models and Providers](models_and_providers.md) to choose model targets and configure provider connections. When you need several agents to work together, [Compose Agents](assemblies.md) builds on the same concepts. --- Source: https://mattyr.github.io/little_ghost/docs/models_and_providers.md # Models and Providers Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/models_and_providers.html An Agent needs a model target: a configured provider connection plus the provider's model identifier. You can write that target directly while getting started, then give it an application-facing name when several Agents share it. ## Start with one direct target A direct target has the form `connection:model-id`: ```ruby class CustomerSupportAgent < LittleGhost::Agent model "openrouter:openai/gpt-5.6-luna" system_prompt "Answer customer questions clearly and concisely." end ``` `openrouter` names a connection configured by the application. The remainder is the model identifier understood by that provider. This is a good fit when one Agent owns one stable choice. ## Give shared choices a role A model role lets several Agents share a choice without knowing its provider or model identifier: ```ruby LittleGhost.configure do |config| config.providers = { primary: { adapter: :openrouter, api_key: ENV.fetch("OPENROUTER_API_KEY") } } config.models = { customer_support: { target: "primary:openai/gpt-5.6-luna", settings: {temperature: 0.2} } } config.default_model = :customer_support end class CustomerSupportAgent < LittleGhost::Agent model :customer_support end ``` Here `customer_support` is the role, `primary` is the connection, and `openrouter` is the adapter. You can move the role to another model or provider without editing the Agent. Profile settings are defaults. An individual call can override them: ```ruby run = CustomerSupportAgent.ask( "Explain the refund decision.", settings: {temperature: 0.0} ) ``` Build these settings in application code instead of passing request parameters through unchanged. Settings can affect cost, latency, and model behavior. ## Configure connections in one place LittleGhost includes adapters for OpenRouter, OpenAI-compatible APIs, Anthropic, Gemini, Vertex AI, and Bedrock. Connections may live in an initializer or in the conventional files under `config/little_ghost`. Keep credentials in your application's secret manager. Agents refer to a role or configured connection; they don't need to contain credentials. If your application obtains short-lived credentials at runtime, configure a credential resolver that returns them for the selected connection. > **Safety note:** The selected provider may receive system instructions, > caller input, conversation history, Tool results, schemas, and attachments. > Choose a provider that is appropriate for that data, and keep credentials and > provider endpoints under application control. ## Choose a role for each request An Agent can select between configured roles using its `Invocation`: ```ruby class CustomerSupportAgent < LittleGhost::Agent model do |invocation| invocation.fetch(:premium_account, false) ? :premium_support : :customer_support end end ``` Set `premium_account` from application state when creating the invocation. If a public request offers a model choice, map that choice to one of your configured roles rather than accepting an arbitrary provider target. Trusted application code may also declare a selection inline: ```ruby class ResearchAgent < LittleGhost::Agent model( provider: "primary", model: "openai/gpt-5.6-luna", reasoning_effort: "high" ) end ``` `provider` still names a configured connection. The inline settings change the selection; they don't create a new connection. ## Use model capabilities `LittleGhost::ModelResolver` turns a role or target into an executable `LittleGhost::Model`. Its catalog describes capabilities such as supported input types, output limits, and structured results. LittleGhost uses that information to reject unsupported attachments, constrain output limits, and choose a structured-result strategy. Provider capabilities can change. Handle failed Runs and provider errors even when the catalog says a feature is supported. Continue with [Prompts as Views](prompt_views.md) when an Agent's instructions outgrow one string. See [Structured Results and Content](structured_outputs_and_content.md) when you need checked result shapes, images, or documents. --- Source: https://mattyr.github.io/little_ghost/docs/prompt_views.md # Prompts as Views Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/prompt_views.html A short prompt fits nicely inside an Agent class. As the instructions grow, move them into a **prompt view**: an ERB file that LittleGhost finds and renders for the Agent. This keeps the Agent definition focused. It also gives shared instructions and application values a natural home. ## Start with the inline prompt The Agent from Getting Started keeps its first instruction close to the model: ```ruby class CustomerSupportAgent < LittleGhost::Agent model "openrouter:openai/gpt-5.6-luna" system_prompt "Answer customer questions clearly and concisely." end ``` Inline prompts are a good fit while the whole instruction is one thought. ## Move a growing prompt into a view Remove `system_prompt` from the class: ```ruby class CustomerSupportAgent < LittleGhost::Agent model "openrouter:openai/gpt-5.6-luna" tools HelpCenterLookupTool, OrderStatusTool end ``` Then create `app/prompts/customer_support/system.erb`: ```erb You help customers understand their orders and account. Answer clearly and concisely. Never invent company guidance. Check the help center when policy matters. Use the order status tool before making a claim about a private order. ``` That is enough. `CustomerSupportAgent` becomes `customer_support`, so LittleGhost looks for `customer_support/system.erb` under `app/prompts`. The prompt is still a system instruction sent to the selected model provider. Keeping it in a view improves organization; it does not keep the content inside your process. ## Give the view application values Use `prompt_local` for a value the application owns: ```ruby class CustomerSupportAgent < LittleGhost::Agent prompt_local :company_name, "Northstar" end ``` The local is available by name in the view: ```erb You are a customer support agent for <%= company_name %>. Answer clearly and concisely. ``` A block can resolve a trusted value for each Agent instance. Add it to the Agent class too: ```ruby class CustomerSupportAgent < LittleGhost::Agent prompt_local(:policy_version) { SupportPolicy.current_version } end ``` Prompt views also receive `invocation`, `run`, and `agent`. Reach for those when the instruction truly depends on the current request. Keep user wording in the caller message unless you deliberately want it inside the system instruction. Every rendered value may be sent to the model provider. Pass only data that belongs in the prompt. ## Share a small partial Partials keep repeated instructions in one place. Create `app/prompts/shared/_voice.erb`: ```erb Use a warm, direct voice for <%= company_name %>. Prefer one clear next step over a long list of possibilities. ``` Render it from the Agent's system view: ```erb You are a customer support agent for <%= company_name %>. <%= partial "shared/voice", locals: {company_name: company_name} %> ``` The underscore marks a partial. Its locals are explicit, so it does not quietly inherit everything available to the parent view. ## Choose a different template path Most named Agents can rely on their conventional path. Use `system_template` when a class should read a differently named view: ```ruby class BillingSupportAgent < LittleGhost::Agent system_template "customer_support/billing" end ``` LittleGhost chooses one prompt source in this order: 1. An inline `system_prompt` 2. An explicit `system_template` 3. The Agent's conventional `system.erb` view Applications can add prompt lookup roots through `Configuration#prompt_paths`. Earlier roots win, which lets application code override a shared prompt package. ## Treat views as application code Prompt views run as ERB inside the Ruby process and can call Ruby. Keep prompt directories with the rest of your application code rather than letting a request choose one. `TrustedPath` is available for the uncommon case where application code selects a request-specific root. It marks that choice explicitly; it does not inspect or restrict the directory. ## Build request-specific input in a Workflow A prompt view defines reusable instructions for one Agent. A Workflow may still build request-specific input for that Agent: ```ruby invoke CustomerSupportAgent, input: <<~MESSAGE #{input.text} Verified research: #{research} MESSAGE ``` The Workflow is composing this request. `CustomerSupportAgent` still receives its own system prompt view when it runs. Continue with [Tools](tools.md) to give those Agents application capabilities while keeping model input, trusted context, and delegated sandbox operations distinct. --- Source: https://mattyr.github.io/little_ghost/docs/tools.md # Tools Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/tools.html Tools turn an agent from a writer into a participant in your application. Each Tool offers one named operation with checked input. Your Ruby code decides what the operation may do. Start with a narrow read: ```ruby class HelpCenterLookupTool < LittleGhost::Tool description "Look up a help center entry by topic." input_schema( type: "object", properties: {topic: {type: "string", enum: %w[refunds shipping]}}, required: ["topic"], additionalProperties: false ) def call(input) { "refunds" => "Refunds are available within 30 days of purchase.", "shipping" => "Standard shipping takes three to five business days." }.fetch(input.fetch("topic")) end end class CustomerSupportAgent < LittleGhost::Agent system_prompt "Check the help center before stating company guidance." tools HelpCenterLookupTool end ``` The model sees the Tool's name, description, and input schema. When it chooses the Tool, LittleGhost checks the arguments, calls `#call`, and returns the result to the model. That loop can happen several times before the Agent writes its final answer. ## Declare one Tool or a collection An Agent's `tools` declaration accepts one or more classes. Pass a Tool class directly for one operation: ```ruby class CustomerSupportAgent < LittleGhost::Agent tools HelpCenterLookupTool end ``` Pass several classes in one declaration, or use several declarations. They are equivalent and inherited declarations are retained: ```ruby class CustomerSupportAgent < LittleGhost::Agent tools HelpCenterLookupTool, OrderStatusTool tools EscalateConversationTool end ``` For a related or dynamically discovered collection, pass a provider class that implements `self.tools(binding)`. It may return Tool classes, Tool instances, nested arrays, or `nil`; LittleGhost flattens the result and binds every Tool to the current run: ```ruby class AccountTools def self.tools(binding) [ AccountStatusTool, (CloseAccountTool if binding.run.invocation.context["may_close_account"]) ] end end class CustomerSupportAgent < LittleGhost::Agent tools HelpCenterLookupTool, AccountTools end ``` Prefer `available_if` on an individual Tool when only that operation is conditional. Use a provider when the collection itself owns discovery, construction, or shared setup for an application or remote service. LittleGhost does not enforce class names. A useful application convention is to end one model-callable operation with `Tool` and a provider of multiple operations with `Tools`—for example, `OrderStatusTool` and `AccountTools`. The suffix makes `tools AccountTools` readable without introducing a framework base class or hiding ordinary Ruby composition. ## Check permission in Ruby A schema answers “Is this input shaped correctly?” It does not answer “May this caller perform this operation?” Use values established by your application to answer that second question. For sensitive work, read those values inside the Tool: ```ruby class OrderStatusTool < LittleGhost::Tool description "Look up an order for the current customer." input_schema( type: "object", properties: {order_number: {type: "string"}}, required: ["order_number"], additionalProperties: false ) def call(input) Orders.status_for( actor_id: run.invocation.actor_id, account_id: run.invocation.context.fetch("account_id"), order_number: input.fetch("order_number") ) end end ``` Here, the model chooses `order_number`. The application supplies `actor_id` and `account_id` after authenticating the request. The Tool reads those values through its run-scoped binding: the objects LittleGhost attaches to a Tool for one execution. They are not part of the model's Tool arguments. The Run also has `context.state`, mutable working state for this execution. When saved conversations are configured, it may contain values from an earlier Run. Recheck saved values before using them for a permission decision. > **Safety note:** Keep identity and account membership in the Run's invocation, > not in model-selected arguments. A valid Tool input may still name a record > the current caller isn't allowed to use. ## Know where a Tool runs A local Tool is application code. Its `#call` method runs in the same Ruby process as LittleGhost, with the same access as the rest of your application. A Sandbox contains only work that the Tool explicitly sends through it. Some Tools deliberately delegate a smaller operation to the Sandbox: - `LittleGhost::Tools::Filesystem` reads and changes paths through the bound Sandbox. It exposes mutation Tools only when that Sandbox is writable. - `LittleGhost::Tools::Shell` runs one argument vector through the bound Sandbox. It does not interpret shell syntax. - An application Tool can send work through its bound `sandbox` when it needs the same file and process restrictions. Its bound `workspace` names paths but does not restrict access to them. Do not pass model-selected paths from `Workspace#resolve` to `File`; use Sandbox file operations, which reject symlinks while opening the path. This distinction keeps the architecture predictable: ```text model ──arguments──> Tool#call ──> application service │ └──> bound Sandbox ──> file or child process ``` Provider requests also leave from the application process. Sandbox network settings apply to processes launched through that Sandbox, not to model providers, callbacks, or arbitrary Ruby inside a Tool. Read [Workspaces and Sandboxes](sandboxing.md) before exposing filesystem or process operations to model influence. It shows which paths and commands a child process can access, how networking is restricted, and who cleans up the resources. ## Use the run-scoped binding LittleGhost creates and binds fresh Tool instances for each Agent run. A Run is one top-level Agent or Assembly execution. A Tool can reach that `run`, its `agent`, the `runtime` that holds shared configuration and services, and the current `workspace` and `sandbox` through accessors supplied by `Tool::Binding`. That binding carries application collaborators, not model arguments. Keep request identity on `run.invocation`, working state on `context.state`, and the model-selected input in the `input` passed to `#call`. Keeping those three sources distinct makes permission checks easier to follow. Registries close Tool instances that implement `#close`. Tool instance state therefore belongs to one Agent run unless your Tool deliberately talks to a shared application service. Use `available_if` when the run itself determines whether an operation exists. The predicate receives the same binding and runs before the Tool is constructed: ```ruby class UpdateSlackMessageTool < LittleGhost::Tool available_if { |binding| binding.run.invocation.interface == "slack" } end ``` This controls discovery, not authorization. The Tool must still validate the caller identity and account permissions supplied by the application. ## Make concurrency and retries deliberate LittleGhost may run independent Tool calls concurrently. Mark a Tool `exclusive true` when it reads or changes shared mutable state that must not overlap another exclusive Tool in the same run: ```ruby class UpdateDraftTool < LittleGhost::Tool exclusive true description "Replace one section of the current account's draft." input_schema( type: "object", properties: { section: {type: "string"}, content: {type: "string"} }, required: %w[section content], additionalProperties: false ) def call(input) Drafts.replace_section( account_id: run.invocation.context.fetch("account_id"), section: input.fetch("section"), content: input.fetch("content") ) end end ``` When LittleGhost selects the fiber backend, concurrent Tool calls can run as fibers on one thread. If a Tool calls a library that blocks that thread, every other fiber on it must wait too. Suppose the help center lookup later moves to a client whose `lookup` method is documented to behave this way. Change only the Tool method: ```ruby def call(input) LittleGhost.offload_blocking do HelpCenterClient.lookup(input.fetch("topic")) end end ``` Many Ruby I/O calls already let the scheduler run other fibers. Keep those calls unchanged. Use `offload_blocking` only when documentation or measurement shows that the exact call pauses other fibers and the work can continue on another Ruby thread. Configure the call's own timeout or cancellation when it provides one. If most of a Tool's implementation blocks, configure LittleGhost to use the `:thread` backend instead of wrapping each call. `exclusive true` prevents overlap with another exclusive Tool; it does not change where the Tool runs. [Running in Production](production.md#use-an-existing-fiber-scheduler) explains the concurrency settings and when to adjust the shared thread pool. Retries can repeat a Tool call. Prefer read-only operations, idempotency keys, or writes that are safe to apply more than once. Do not rely on the prompt to prevent duplicate side effects. Raise `LittleGhost::ToolError` for an expected failure the model can act on. Its message is model-visible, so keep it safe to disclose. LittleGhost hides unexpected exception messages from the model while retaining the original error for trusted application inspection. ## Return values and artifacts A Tool normally returns one Ruby value. Application callers and code mode receive that value, while LittleGhost serializes it for the model. Use `Tool::Result` when the operation also produces files or media: ```ruby def call(input) report = Reports.build(input.fetch("period")) LittleGhost::Tool::Result.new( value: {rows: report.rows.length}, artifacts: [ LittleGhost::Artifact.new( data: report.csv, media_type: "text/csv", name: "report.csv" ) ] ) end ``` `Tool::Result#value` is the same plain Ruby value a Tool would otherwise return. Each inline `Artifact` has bytes, a MIME media type, and an optional name and metadata. Use `Artifact.deferred(reference:, media_type:, ...)` when another application service stores the bytes. The optional block passed to `Configuration#artifacts` receives the deferred Artifact and may use its application-defined `reference` to load the bytes later. Artifact handling is opt-in for the Runtime: ```ruby LittleGhost.configure do |config| config.workspace = { provider: :directory, root: "tmp/agent-runs", paths: {artifacts: "artifacts"} } config.artifacts end ``` Once enabled, artifact handling covers three cases: - Input images and documents are stored so filesystem Tools and code mode can read the same bytes. The model still receives only the original image or document. - Tool artifacts are stored and returned to the model as images or documents. The stored reference is shown only when the media cannot be included in the model request. - Oversized successful Tool values are stored automatically. The model receives a short preview and a reference instead of the complete value. The Tool's Ruby return value does not change. LittleGhost limits the size of each stored file, the total files and bytes stored for a Run, and the media sent in one model turn. If an oversized value cannot be stored within those limits, the application still receives the complete Ruby value and the model receives a short preview with a storage-limit notice. To load a deferred artifact, pass a block. It may return bytes, an inline Artifact with a final MIME type, or `nil` when the referenced file is no longer available: ```ruby config.artifacts do |artifact, run:| StoredFiles.read(artifact.reference, actor_id: run.invocation.actor_id) end ``` > **Safety note:** A deferred reference is data, not proof that the current > caller may read a file. Check it against identity established by the > application, restrict the storage service or network destination, and limit > the bytes fetched before returning them. LittleGhost applies its storage limit > after the resolver returns. Declaring the named Workspace path does not grant model access. When the Agent should read artifact references, grant the Sandbox read access to the `:artifacts` path and include a filesystem Tool. The model can list that path when a task genuinely needs a stored file; ordinary multimodal work does not need a second reference to media already in the conversation. ## Let code mode compose the same capabilities Without code mode, the model chooses one Tool operation and LittleGhost returns the result before the model chooses the next step. Code mode lets the model write a small Ruby program that calls several of the same Tools, combines their results, and returns one useful value. Each call crosses back to the parent Ruby process. LittleGhost checks the schema and calls the Tool method there, so permission checks inside `#call` still apply. Code mode receives the Tool's Ruby return value, while artifacts return with the surrounding `exec` or `wait` result. Tool limits, callbacks, events, and tracing work the same way for direct and code-mode calls. Continue with [Structured Results and Content](structured_outputs_and_content.md) to give Agent responses a predictable shape and accept images or documents. For exact Tool DSL and result contracts, see `LittleGhost::Tool` and `LittleGhost::Tool::Binding`. --- Source: https://mattyr.github.io/little_ghost/docs/structured_outputs_and_content.md # Structured Results and Content Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/structured_outputs_and_content.html An Agent can return a checked Ruby value instead of prose. It can also receive text alongside images and documents when the selected model supports them. ## Declare a result shape Use `result_schema` on the Agent: ```ruby class SupportTriageAgent < LittleGhost::Agent model :customer_support system_prompt "Classify the request using only the supplied evidence." result_schema( name: "support_triage", description: "Routing decision for one support request", type: "object", properties: { category: { type: "string", enum: %w[billing delivery returns other] }, urgent: {type: "boolean"}, summary: {type: "string", maxLength: 500} }, required: %w[category urgent summary], additionalProperties: false ) end run = SupportTriageAgent.ask("My package is missing and I leave tomorrow.") if run.completed? triage = run.result.output route_request(category: triage.fetch("category"), urgent: triage.fetch("urgent")) else report_failure(run.error) end ``` Every object in a result schema must set `additionalProperties: false` and list every property in `required`. The top-level type must be `object`. LittleGhost checks the supported JSON Schema subset when the Agent is defined and checks the returned value again before publishing a `LittleGhost::StructuredResult`. LittleGhost supports a focused subset of [JSON Schema Draft 2020-12](https://json-schema.org/draft/2020-12/json-schema-core). The `LittleGhost::Agent.result_schema` API reference lists the accepted keywords. For a structured Agent, `run.result.output` returns the checked value. For an ordinary Agent, it returns text. Use `run.result.structured_result` when you also need the schema name. ## Let LittleGhost choose the strategy The default `strategy: :auto` uses provider-native structured output when it is available and otherwise uses a terminal Tool when the model supports reliable Tool calls. You can require one strategy: ```ruby result_schema( { type: "object", properties: {answer: {type: "string"}}, required: ["answer"], additionalProperties: false }, name: "answer", strategy: :provider ) ``` Use `:provider` or `:tool` when your application depends on that exact path. LittleGhost raises `LittleGhost::ConfigurationError` before execution if the selected model cannot provide it. If the first response is missing or invalid, LittleGhost asks the model to repair it once. A second invalid response ends the Run with `LittleGhost::StructuredResultError`. > **Safety note:** A checked shape tells you that fields and types match the > schema, not that the model's claims are correct. Apply your normal business > checks before the result changes data, spends money, or contacts someone. ## Combine text with an image Build a user `Message` from typed content blocks: ```ruby image = LittleGhost::Content::Image.new( data: File.binread("tmp/damaged-package.png"), media_type: "image/png" ) message = LittleGhost::Message.new( role: :user, content: [ LittleGhost::Content::Text.new( text: "Describe the visible damage without guessing its cause." ), image ] ) run = DamageReviewAgent.ask(message) ``` For a document, include a display name: ```ruby document = LittleGhost::Content::Document.new( data: File.binread("tmp/refund-guide.pdf"), media_type: "application/pdf", name: "refund-guide.pdf" ) ``` `Image` and `Document` hold the original bytes. Serialization base64-encodes them when they cross a JSON boundary, which increases request size. The resolved model checks the content type against its advertised input capabilities before making the provider request. > **Safety note:** When content comes from an upload, check its size and actual > file type before creating the block. Send it only to a provider you use for > that kind of data, and don't treat text extracted from a file as proof of > identity or permission. Content blocks may also accompany a Tool result. They become visible to the model, so apply the same size and disclosure checks as you would for user content. Continue with [Compose Agents](assemblies.md) to route a checked result through several participants, or [Tools](tools.md) when the result should call Ruby code. --- Source: https://mattyr.github.io/little_ghost/docs/assemblies.md # Compose Agents Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/assemblies.html An Assembly lets several participants answer through the same familiar calls as one Agent. This guide grows the customer-support example through each coordination style, then shows how to nest and construct assemblies dynamically. ## Call every assembly the same way Callers do not need a branch for each implementation: ```ruby entrypoint = urgent? ? EscalationWorkflow : CustomerSupportAgent run = entrypoint.ask(question) ``` `Agent`, `Workflow`, `Swarm`, and `Graph` all answer through the Assembly calling style. They differ in how they coordinate work, not in how your application calls them. ## Use a Workflow for explicit application logic A Workflow's `perform` method is ordinary Ruby. Inside it, `invoke` prepares a child call. Read `.output` when you need an intermediate answer. Return the final `invoke` call untouched so its response can stream to the caller. ```ruby class ResponseWorkflow < LittleGhost::Workflow private def perform research = invoke(ResearchAgent).output invoke CustomerSupportAgent, input: <<~PROMPT #{input.text} Verified research: #{research} PROMPT end end run = ResponseWorkflow.ask("Why is transfer 481 pending?") run.response ``` Every participant passed to `invoke` can be an Agent or another Assembly. By default, each child receives the caller's history and application context. Pass `history: []`, `context: {}`, or redacted values when a child should see less. Each child Agent keeps its own [prompt view](prompt_views.md). The Workflow supplies request-specific input; it does not replace that Agent's reusable system instructions. The last child is special because its events become the Workflow's public stream. Return that `invoke` without consuming it: ```ruby # Wrong: this returns a String after consuming the final invocation. def perform invoke(CustomerSupportAgent).output end # Right: this returns the lazy invocation itself. def perform invoke CustomerSupportAgent end ``` The first version produces a failed top-level Run whose error is `ProtocolError`. Use `.output` only when Ruby needs an intermediate answer before choosing the next step. ### Choose a branch in Ruby Each branch should end with its final unconsumed invocation: ```ruby class RoutedResponseWorkflow < LittleGhost::Workflow private def perform route = invoke(TriageAgent, as: :triage).output if route == "billing" invoke BillingAgent, as: :billing_response else invoke CustomerSupportAgent, as: :general_response end end end ``` `as:` gives the child a readable participant name in steps, trajectories, and telemetry. It does not change which Assembly runs. ### Run independent work in parallel Use `parallel` when several inputs can be processed independently: ```ruby class InvestigationWorkflow < LittleGhost::Workflow private def perform findings = parallel( invoke(LedgerResearchAgent), invoke(PolicyResearchAgent), max_concurrency: 2 ) invoke CustomerSupportAgent, input: <<~PROMPT #{input.text} Findings: #{findings.join("\n")} PROMPT end end ``` `max_concurrency` limits how many calls run at once. Each one gets its own copy of the workflow context. Cancellation still depends on the provider or tool noticing its token or deadline. ## Use a Swarm for specialist handoffs A Swarm keeps one Agent active at a time. You decide which specialists it may hand work to: ```ruby class ProblemSolverSwarm < LittleGhost::Swarm member TriageAgent member BillingAgent member AccountAgent start TriageAgent handoff TriageAgent, to: [BillingAgent, AccountAgent] handoff BillingAgent, to: TriageAgent handoff AccountAgent, to: TriageAgent max_steps 10 max_handoff_repeats 2 end ``` The active model sees a handoff tool listing the members it may choose next. LittleGhost accepts only the routes you declared. `max_steps` limits total member executions. `max_handoff_repeats` limits how often the same directed handoff, such as triage to billing, may repeat. Swarm members must be Agents, so each transition stays a direct model-to-model handoff. Caller history and application context are opt-in for each member. Handoff messages come from a model; never treat them as permission to read data or perform an action. Opt in only for a member that needs the data: ```ruby member AccountAgent, history: true, context: true ``` Intermediate model text stays out of the caller-facing stream, leaving one coherent public answer. The next member still receives the handoff, and the result keeps a bounded summary of the journey. ## Use a Graph for guided routes A Graph names the possible stops and the routes between them. Start with a conditional route before adding parallel branches: ```ruby class SupportFlowGraph < LittleGhost::Graph node :triage, TriageAgent node :billing, BillingAgent node :general, CustomerSupportAgent node :respond, CustomerSupportAgent start :triage edge :triage, :billing do |state| state.result(:triage).output == "billing" end edge :triage, :general edge :billing, :respond edge :general, :respond finish :respond end SupportFlowGraph.validate! ``` Conditions and input mappers read an immutable `Graph::State`. At most one conditional route may match. If several match, LittleGhost raises `AssemblyRoutingError` instead of guessing which one wins. One unconditional edge can catch the request when none match. Graph nodes start without caller history or application context. The start node receives the original input. By default, each downstream node receives the original task plus its immediate predecessor results. Use an input mapper to replace or redact that data before it moves to a provider or participant that should see less. Opt in when a node needs caller context: ```ruby node :account_lookup, AccountLookupAgent, context: true ``` ### Run bounded parallel paths Give one node several unconditional edges when its result should start independent branches. LittleGhost finds their first unambiguous common successor and waits for every branch before running it: ```ruby class InvestigationGraph < LittleGhost::Graph node :triage, TriageAgent node :ledger, LedgerResearchAgent node :policy, PolicyResearchAgent node :respond, CustomerSupportAgent start :triage edge :triage, :ledger edge :triage, :policy edge :ledger, :respond edge :policy, :respond finish :respond end ``` Set `max_concurrency` on the Graph to bound every parallel group. An edge with an array target can declare the group explicitly and override that bound: ```ruby max_concurrency 4 edge :triage, [:ledger, :policy], max_concurrency: 2 edge [:ledger, :policy], :respond ``` #### Join parallel branches An array source declares a wait-for-all convergence. Use it when the common successor cannot be inferred or when the convergence needs its own input mapper. Parallel groups cannot nest. `validate!` raises `ConfigurationError` when inference has no single convergence, finds competing routes at a branch boundary, or encounters overlapping or nested groups. The first nodes in a parallel group receive the original task and the source result. The convergence target receives the original task and each immediate predecessor result in declaration order. LittleGhost labels them as context: ```text Original Task: Why is transfer 481 pending? Inputs from previous nodes: From ledger: The ledger entry is awaiting settlement. From policy: Pending transfers usually settle within two business days. ``` #### Map inputs between nodes An `input` mapper replaces this default with the exact value returned by the mapper. Put it on an edge to control one transition, or on a node to control every route into that target. A selected edge or edge-group mapper takes precedence over the target node mapper: ```ruby edge :triage, :ledger, input: lambda { |state| "Investigate this transfer:\n#{state.result(:triage).output}" } ``` Conditions and mappers receive a copied, frozen `Graph::State`, so they cannot change the running Graph. Use `state.input` for the original request, `state.results` for completed nodes, and `state.incoming_results` for the immediate predecessors. The `LittleGhost::Graph::State` API reference lists every routing value. Conditions and mappers are application code. Their state includes copies of caller history and application context, even when the destination node does not receive those values. Use an explicit array-source edge when a fan-in needs one mapper: ```ruby edge [:ledger, :policy], :respond, input: lambda { |state| JSON.generate(state.incoming_results.transform_values(&:output)) } ``` #### Control data crossing branches By default, the original request and complete source output go to every parallel branch. An input mapper can replace the branch input, and a redaction assembly before the fan-out can narrow the source output. Use those options when a participant or provider should receive only part of the data. #### Recover and review An error edge can send an expected failure to a recovery Assembly. Call `validate!` before the first run. Once the topology grows, `InvestigationGraph.to_mermaid` returns Mermaid diagram source for the routes you declared. Render it in a Mermaid-aware editor or documentation page when a picture makes the graph easier to review. ## Make retries safe Workflow calls, Swarm members, and Graph nodes can set timeouts and retries. Use them for work that can safely be attempted again: ```ruby invoke( ResearchAgent, timeout: 15, retries: 2, retry_on: [LittleGhost::ProviderError], retry_delay: 0.25 ) ``` A timeout asks the running code to stop; it cannot forcibly end arbitrary Ruby or provider work. A retry repeats the whole child step. Retry only selected failures, and make sure repeated external actions are safe. Retries start at zero. When `retries` is greater than zero, `retry_on` must list the exception classes that are safe to try again. LittleGhost does not retry every failure by default. ## Watch every agent in an assembly Follow each participant while a composite assembly runs by handling its contextual `:agent_stream` events. These events arrive alongside the coherent public answer and assembly lifecycle events: ```ruby stream = SupportFlowGraph.stream_ask("Why was I charged twice?") run = stream.each do |event| next unless event.type == :agent_stream source = event.data.fetch(:source) agent_event = event.data.fetch(:event) participant = source.assembly_path.last&.participant || source.agent_id case agent_event.type when :invocation_start routed_input = event.data.fetch(:input) render_input(participant, routed_input) when :text_delta publish_progress(participant, agent_event.data.fetch(:text)) when :invocation_stop record_result(participant, agent_event.data.fetch(:result)) end end run.completed? # => true ``` `source.agent_id` identifies the Agent class, `source.agent_path` distinguishes managed subagents, and `source.operation_id` groups one invocation. `source.assembly_path` lists the enclosing Workflow, Swarm, or Graph steps from the outside inward. The routed input and inner event are copied and frozen before they reach the observer, so changing an event can't affect the running assembly. Parallel participants can interleave. Events from each Agent retain their order, and LittleGhost never calls the stream block concurrently. The contextual wrapper arrives before the corresponding ordinary event. An assembly's final Agent therefore appears through both projections. Filter for `:agent_stream` when building an all-agent view, or handle ordinary events when rendering only the final answer. Pass `include_agent_events: false` when a composite assembly caller only wants the ordinary public stream. Standalone Agent streams keep their ordinary events by default and accept `include_agent_events: true` when source metadata is useful. The AG-UI adapter ignores contextual wrappers. Translate them explicitly if an AG-UI client should receive participant activity. > **Safety note:** A composite stream can include inputs, reasoning, Tool > arguments and results, errors, and output from every participant. Check that > the destination may see the complete Run, or filter the events before sending > or storing them. ## Inspect what the assembly did A composite result remembers the steps it took. `trajectory` lets you explore them: ```ruby run = InvestigationGraph.ask("Why is transfer 481 pending?") trajectory = run.result.trajectory trajectory.each { |step| puts "#{step.participant}: #{step.status}" } trajectory.transitions ledger = trajectory.find { |step| step.participant == "ledger" } policy = trajectory.find { |step| step.participant == "policy" } trajectory.concurrent?(ledger.id, policy.id) ``` Step outputs and buffered events have size limits. Use your application's instrumentation when you need deeper diagnostics. ## Compose assemblies inside assemblies Workflow and Graph participants accept any Assembly definition: ```ruby class ResolutionGraph < LittleGhost::Graph node :investigate, InvestigationWorkflow node :resolve, ProblemSolverSwarm start :investigate edge :investigate, :resolve finish :resolve end ``` An Assembly can also become an Agent tool: ```ruby class SupportCoordinatorAgent < LittleGhost::Agent assembly_as_tool InvestigationGraph, name: "investigate_support_request", preserve_context: false end ``` The nested assembly receives the parent Tool's current working state. That state may include values restored from a Session. `preserve_context` controls conversation history only: when it is false, working state still passes to the nested assembly. A nested Tool that reads private data or performs a write should check values established for the current request or checked again after loading. ## Reach for builders when definitions are dynamic Classes are the preferred form in application code. Use a builder when runtime configuration decides the nodes or routes: ```ruby graph = LittleGhost::GraphBuilder.new( id: "support_flow", description: "Routes customer support requests" ) graph.node :triage, TriageAgent graph.node :respond, CustomerSupportAgent graph.start :triage graph.edge :triage, :respond graph.finish :respond graph.validate! run = graph.ask("Where is my order?") ``` Each builder uses the same declarations as its matching class. The builder stays editable, but each run gets a fixed copy of its current definition. Later edits affect later runs. Ruby callbacks still see any application objects they captured. Continue with [Skills](skills.md) when an Agent should discover focused instructions and supporting resources only when a task needs them. --- Source: https://mattyr.github.io/little_ghost/docs/skills.md # Skills Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/skills.html A Skill is a reusable instruction package that an Agent can discover by name and load when a task needs it. Skills keep specialized procedures out of the Agent's main prompt. ## Write one focused skill Create `app/skills/refund_guide/SKILL.md`: ```markdown --- name: refund_guide description: Determine which refund guidance applies to a customer request. allowed-tools: - help_center_lookup compatibility: Requires the refunds help-center collection. --- # Apply the refund guidance 1. Load the current refund entry with `help_center_lookup`. 2. Compare the purchase date and item category with the returned guidance. 3. State which facts support the decision and which facts are still missing. 4. Return the analysis to the application instead of issuing a refund. ``` Each immediate child of a configured skill root may contain one `SKILL.md`. Front matter requires a single-line `name` and `description`. Names contain only letters, numbers, underscores, and hyphens. `allowed-tools` and `compatibility` are optional information shown to the model. A Skill may also include supporting files in `references/`, `scripts/`, or `assets/`. Keep the main instructions short and point to a resource only when the task needs it. ## Let an Agent discover skills The conventional root is `app/skills`: ```ruby class CustomerSupportAgent < LittleGhost::Agent system_prompt "Use an available skill when a request needs a documented procedure." tools HelpCenterLookupTool skills end ``` At runtime, the Agent receives a short catalog of skill names, descriptions, and locations. The generated `skills` Tool loads the full instructions when the model selects one. An empty catalog adds nothing to the prompt and no Tool. You can use another application-owned directory or expose only selected skills: ```ruby class CustomerSupportAgent < LittleGhost::Agent skills paths: [File.expand_path("../../support_skills", __dir__)], only: %w[refund_guide] end ``` Paths may also come from a callable resolved for each Run. Build the path from application configuration, not from a path supplied by the model or request. ## Pair instructions with Tools `allowed-tools` tells the model which Tools a Skill expects. It doesn't add or enable those Tools. The Agent's `tools` declaration remains the source of what the model can call, and each Tool applies its normal application checks. This separation makes Skills safe to use as guidance: changing a Markdown file can change what the Agent tries, but it can't grant a new Tool, provider, filesystem path, or credential. > **Safety note:** Keep configured skill directories under application control > and review Skill changes as prompt changes. A Skill can contain mistaken or > outdated instructions, so application code should continue to check any > operation that has side effects. ## Make resources available to code mode Ordinary Skill loading needs no Workspace configuration. If model-authored code also needs to read Skill resources, give those resources a stable model-visible location: ```ruby require "fileutils" require "tmpdir" skill_root = File.expand_path("../../app/skills", __dir__) LittleGhost.configure do |config| config.skill_paths = [skill_root] config.skill_resource_root = "workspace://skills" config.workspace = lambda do |**| root = Dir.mktmpdir("little-ghost-skills-") LittleGhost::Workspace.new( root:, paths: {skills: skill_root}, teardown: lambda do |workspace:, **| FileUtils.remove_entry_secure(workspace.root) if File.exist?(workspace.root) end ) end config.sandbox = { provider: :native, files: {root: :read_write, skills: :read_only}, root_filesystem: :isolated, network: :none } end ``` The named Workspace path maps the configured Skill directory, and the Sandbox makes it readable without allowing model-authored code to change it. The model can then ask the Filesystem Tool for a path such as `workspace://skills/refund_guide/references/example.md` without learning the host's directory layout. [Workspaces and Sandboxes](sandboxing.md) explains how to adapt the temporary root, backend, and other grants for your application. ## Write instructions that stand on their own A useful Skill tells the Agent: - When the procedure applies. - Which information it needs before deciding. - Which named Tools or resources help. - What result the caller expects. - Which action remains with the application. - What to do when information is missing or conflicts. Use direct instructions and stable domain language. Avoid repeating the Agent's general prompt or relying on Tool behavior that the Tool description doesn't promise. Continue with [Workspaces and Sandboxes](sandboxing.md) when model-authored code needs Skill resources. See [Tools](tools.md) for Tool validation, bindings, and side effects. --- Source: https://mattyr.github.io/little_ghost/docs/sandboxing.md # Workspaces and Sandboxes Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/sandboxing.html A Workspace gives one Run—one top-level Agent or Assembly execution—a stable set of host paths. A Sandbox decides which operations may reach those paths and how child processes are contained. Use them together when an Agent can read files, change files, or run programs: ```ruby require "fileutils" require "tmpdir" LittleGhost.configure do |config| config.workspace = lambda do |**| root = Dir.mktmpdir("little-ghost-support-") LittleGhost::Workspace.new( root:, teardown: lambda do |workspace:, **| FileUtils.remove_entry_secure(workspace.root) if File.exist?(workspace.root) end ) end config.sandbox = { provider: :native, files: {root: :read_write}, root_filesystem: :isolated, environment: {inherit: false, set: {"LANG" => "C.UTF-8"}}, network: :none } end ``` This example gives each Run a temporary writable root and removes it during teardown. The `:native` Sandbox backend selects Seatbelt on macOS or Bubblewrap on Linux. It raises instead of running without isolation when the native backend is unavailable. `LittleGhost::Tools::Filesystem` and `LittleGhost::Tools::Shell` use the Sandbox assigned to the current Run. Code-mode interpreters also run inside their own Sandbox. Ordinary application Tools, callbacks, and provider requests stay in the Ruby process unless they deliberately delegate an operation. The split looks like this: ```text Ruby application process ├── provider requests ├── application Tool#call └── Sandbox ├── bounded filesystem operations ├── Shell child processes └── code-mode interpreter processes ``` ## Give files a stable home A Workspace names the files available during a Run and controls their setup and cleanup. Its `root` is the default working directory. Named paths give important directories logical identities: ```ruby workspace = LittleGhost::Workspace.new( root: "/var/lib/support/run-481", paths: { source: "/srv/support/source", skills: "skills", home: "runtime-home" } ) ``` Relative named paths live beneath the root and are created when the Workspace opens. Absolute named paths are references deliberately supplied by the application and must already exist. A setup callback can provision them when needed. Opening resolves real paths and records which physical directories they refer to. LittleGhost rejects two names that point to the same directory and later fails closed if a configured directory is replaced. Nested paths are allowed, and the most restrictive matching access wins. Workspace object lifetime and file lifetime are separate. Closing invokes the configured teardown callback, but does not delete files by default. Use a run-scoped temporary root for disposable work. Use application-managed storage, tenant isolation, and concurrency control when several Runs share files. ## Give artifacts logical references Images and documents normally remain provider content. When filesystem Tools or code mode should read the same bytes, configure the conventional artifact path and enable artifact handling: ```ruby LittleGhost.configure do |config| config.workspace = { provider: :directory, root: "tmp/agent-runs", paths: {artifacts: "artifacts"} } config.artifacts end ``` LittleGhost stores input images and documents after the Workspace and Sandbox open. The model receives the image or document in its normal input without a second text reference. Filesystem Tools can list `workspace://artifacts` when a later operation needs the stored copy. Messages added while the Run is active receive the same treatment. LittleGhost limits the number and size of files stored from each message and across the complete Run. Those limits also include Tool artifacts and oversized Tool results. A successful operation stores all of its files. If storage fails partway through, LittleGhost attempts to remove that operation's files and reports a cleanup error when it cannot. Stored files use private permissions, and the Workspace provider still owns final cleanup. Declaring the path does not grant model access. When the Agent should read it, grant the Sandbox access to `:artifacts` and include a filesystem Tool. ## Pass logical paths, not host layout The Filesystem Tool accepts root-relative paths such as `notes/today.md`. Named paths use references such as `workspace://skills/refunds/SKILL.md`. Those references remain meaningful without exposing or translating the host layout. The Filesystem Tool rejects physical absolute paths. Child processes use the Workspace's real paths directly, start in its root, and receive `LITTLE_GHOST_WORKSPACE_ROOT` plus one `LITTLE_GHOST_WORKSPACE_` variable for each named path. Workspace references give application code one stable path format. Each Sandbox backend applies the configured access using the filesystem controls available on its host. ## Separate Tool-visible files from process support Sandbox configuration divides named paths into two groups: ```ruby config.sandbox = { provider: :native, files: { root: :read_write, source: :read_only, skills: :read_only }, runtime_paths: { home: :read_write }, network: :none } ``` `files` are visible to both the Filesystem Tool and sandboxed processes. `runtime_paths` are process-only. Use runtime paths for interpreter libraries, homes, sockets, and service state that a model should not browse through a filesystem Tool. This is visibility, not secrecy from the process. A child with a runtime-path grant can use that path according to its access mode. The distinction prevents the Filesystem Tool from offering it as a model-visible file tree. ## Narrow access with a Scope A `Sandbox::Scope` is a non-owning, reduced view of a Sandbox. It can remove paths, change writable access to read-only, remove capabilities (categories of allowed operations), or narrow networking. It cannot widen its parent: ```ruby reviewer = run.sandbox.scope( files: {source: :read_only}, runtime_paths: [], capabilities: %i[filesystem_read filesystem_list], network: false ) ``` Scopes constrain only code that receives and uses the Scope. Code that keeps a reference to the parent Sandbox keeps the parent's authority. A Scope does not open or close its parent and owns no resources. ## Choose how much of the host exists `root_filesystem` controls what a sandboxed process can see beyond declared Workspace paths: - `:isolated` exposes only declared paths and required runtime support. It is the default and the right starting point for generated interpreters. - `:read_only` exposes the host filesystem for development commands while confining writes to declared writable paths. It makes installed compilers, package managers, profiles, and toolchains available, but the child can also read host files unless the Ruby process already runs inside a container or VM that prevents those reads. - `:read_write` grants the host filesystem directly. Treat it as unrestricted host authority. On Seatbelt, host-visible modes permit subprocesses because development tools often need them. A Scope can remove `process_spawn` for a command that does not. ## Choose an enforcement backend | Sandbox backend | Host | What it enforces | | --- | --- | --- | | `:native` | macOS or Linux | Selects Seatbelt on macOS and Bubblewrap on Linux; fails closed elsewhere | | `:seatbelt` | macOS | Deny-default Seatbelt profile over the configured physical paths | | `:bubblewrap` | Linux | Fresh user, PID, mount, IPC, UTS, and optional network namespaces | | `:unrestricted` | Ruby platforms | No containment; commands have the application process's host authority | `LittleGhost::Sandbox.probe(:native)` reports whether the platform backend is available. Selecting an enforcing backend never falls back to unrestricted execution. Bubblewrap owns descendants with a PID namespace and ends them when the supervising process dies. It cannot selectively deny fork inside that namespace, so a request for `allow_subprocesses: false` fails closed rather than claiming an unenforced restriction. Bubblewrap does not impose a task-count limit by itself. Use an outer cgroup or container supervisor when generated code needs a hard cap on the processes and threads it can create. Seatbelt can constrain spawned children, but macOS has no PID namespace. It terminates the command process group during cleanup; a child that deliberately detaches from that group may survive. Use an outer process or container supervisor when complete descendant ownership is required on macOS. > **Safety note:** `LittleGhost::Sandboxes::Unrestricted` is suitable for > application commands and tests that you would already run directly. It > validates paths and bounds output, but it does not isolate the command from > the host. Use `:native` for generated commands in production. ## Keep process ownership explicit `Sandbox#start_program` returns a `Sandbox::ProcessSession` with bounded input and output, `alive?`, bounded `wait(timeout:)`, `terminate`, and `close`. The session starts the command in a process group so cleanup can stop it and its ordinary descendants together. It applies available CPU, memory, file, and output limits, requests termination, and then forces termination when needed. Callers that open a ProcessSession own it and must close it. LittleGhost fails closed when it cannot supervise a configured memory limit. The parent samples the visible process tree every 100 milliseconds, so it reacts only to memory present at a sample and may miss peaks between samples. On Linux, three consecutive failures to read the root process or the `/proc` snapshot end the process. Use an outer cgroup or container when memory must be enforced as a hard limit by the operating system. A Run closes the Workspace and Sandbox it creates after success, failure, a partial response, or cancellation. Application-supplied instances remain caller-owned. ## Configure child-process networking separately Sandbox networking has three modes: - `:none` removes child networking. - `:inherit` permits the selected Sandbox backend's ordinary network access. - `:allowlist` requires an enforcing gateway: a supervised proxy that permits only configured destinations. Proxy environment variables alone are not an allowlist. An external gateway uses named, process-only Workspace paths and verifies that they still point to the configured directories; it does not create a virtual path mapping. LittleGhost does not attest that an external proxy is ready or enforcing the declared destinations. The application must supervise and verify that gateway before giving a child network access. These settings reach only processes launched through the Sandbox. Providers, callbacks, and application Tool code still use the Ruby process's network access. Test the deployed kernel and filesystem, not only the configuration object. Exercise denied reads and writes, runtime paths, child creation, direct sockets, cancellation, limits, and cleanup before depending on the Sandbox to isolate generated code. Continue with [Code Mode](code_mode.md) to see how a model-authored interpreter uses this setup while every Tool call stays in the parent Ruby process. For exact setup, access, and cleanup behavior, see `LittleGhost::Workspace`, `LittleGhost::Sandbox`, and `LittleGhost::Sandbox::Scope`. --- Source: https://mattyr.github.io/little_ghost/docs/code_mode.md # Code Mode Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/code_mode.html Code mode lets an Agent solve a multi-step Tool task in one small program. The model can gather independent results, filter them, and combine them before it returns to the conversation. Your Ruby Tools keep their usual permission checks. Start by adding code mode to an Agent that already has a Tool: ```ruby class HelpCenterLookupTool < LittleGhost::Tool tool_name "help_center_lookup" description "Find a support answer by topic." input_schema( type: "object", properties: {query: {type: "string"}}, required: ["query"], additionalProperties: false ) def call(input) entries = { "refund policy" => "Refunds are available within 30 days.", "shipping policy" => "Standard shipping takes three to five days." } entries.fetch(input.fetch("query"), "No matching entry.") end end class ResearchAgent < LittleGhost::Agent tools HelpCenterLookupTool code_mode end ``` The language adapter that runs the program is called an engine. By default, LittleGhost uses its Ruby engine and the native Sandbox for the host operating system. It fails closed when that Sandbox is unavailable. Code mode adds three control Tools to the conversation. `exec` starts a program, `wait` checks on a program that is still working, and `stop` ends work that is no longer needed. The model can now send Ruby like this to `exec`: ```ruby results = tools.parallel( -> { tools.help_center_lookup(query: "refund policy") }, -> { tools.help_center_lookup(query: "shipping policy") } ) text(results.join("\n")) ``` LittleGhost turns the Agent's Tool schemas into Ruby method signatures. The model sees those signatures and the available Tool names in its instructions. Those names, descriptions, and signatures form the code-mode Tool catalog. The model can compose the results with ordinary Ruby values instead of guessing how to call each Tool. ## See what runs where The program runs in a child interpreter. The Tools do not. ```text model │ writes a program ▼ exec ──> sandboxed Ruby process │ tools.help_center_lookup(...) ▼ Tool broker in the parent Ruby process │ normal Tool execution ▼ HelpCenterLookupTool#call ``` The Tool broker receives interpreter calls in the parent Ruby process. It accepts only Tools registered on the Agent, then sends each call through the same validation, permission checks, limits, callbacks, events, and tracing used by a direct Tool call. Public streams show the brokered Tools by name. They omit the `exec`, `wait`, and `stop` bookkeeping. Traces still record the control operation around its nested Tool calls, so you can follow the complete execution. Code mode does not change what a Tool can do. A Tool still runs as application code, while the generated program runs in the configured Sandbox. Read [Tools](tools.md) for Tool permission checks and [Workspaces and Sandboxes](sandboxing.md) before giving generated programs file or process access. ## Compose Tool calls with Ruby Each `exec` starts a fresh Ruby process. Local variables, constants, and globals do not carry into a later `exec`. Within one program, the model can use: - Named methods such as `tools.help_center_lookup(query: "refund policy")`. - `tools.call(name, arguments)` when the Tool name is dynamic. - `tools.parallel` for independent calls whose results should preserve input order. - `ALL_TOOLS` to inspect the complete runtime catalog. - `text(value)` to add user-visible output. - The program's final expression as the completed value returned by `exec` or a later `wait`. - `finish(value)` to complete early. The dynamic form accepts either the catalog name (`"help_center_lookup"`) or the matching method name (`"tools.help_center_lookup"`). JSON Tool results arrive as ordinary Ruby hashes, arrays, strings, numbers, booleans, or `nil`. When a Tool returns `Tool::Result`, code mode uses its Ruby `value`. Artifact bytes are not copied into program variables; the artifacts return to the model once with the surrounding `exec` or `wait` result. Stored references appear only when native media delivery exceeds its limit. A Tool failure raises inside the program so its Ruby code can handle the failure or return an error. Fresh processes keep interpreter state from leaking across programs. Each Ruby program also gets a temporary Workspace. LittleGhost removes it when the program ends, so files created directly by the interpreter do not carry into a later `exec`. A brokered filesystem Tool uses the Agent Run's separate Workspace. Files written through that Tool follow the Run Workspace's cleanup rules and may persist. ## Check on work that takes longer Most programs finish while `exec` is watching them, so their result is ready in the same Tool call. If a program is still active after one minute, `exec` returns `still_working`. The program keeps running. The model can call `wait` to watch for up to another minute or `stop` when it no longer needs the result. Both `exec` and `wait` return as soon as the program finishes. The one-minute window is a maximum observation time, not a delay added to every call. `wait` does not resume, restart, or extend the program. It returns only output produced since the previous `exec` or `wait`. The returned status tells the model what to do next: - `still_working` means the program is active. Call `wait` again when its result is still needed, or call `stop` to end it. - `completed`, `error`, and `terminated` are final. There is no program to wait for after one of these statuses. The built-in engines give each program a total lifetime of one hour by default. That deadline begins at `exec` and does not reset when the model calls `wait`. The engine ends and cleans up an expired program even if the model never checks on it again. Applications can configure a shorter total lifetime with `wall_seconds`; the one-minute observation window remains fixed. A code-mode session owns the engine's active child process and related resources. It accepts only one `exec`, `wait`, or `stop` operation at a time. The Agent closes the session when its current call ends, including after a failure or cancellation. Cleanup failures raise because LittleGhost cannot claim that the child process and its resources ended cleanly. ## Keep a Tool in the conversation With code mode enabled, ordinary Agent Tools move into the program catalog. The model-facing controls become `exec`, `wait`, and `stop`. Use `except` when an application Tool should remain available to the conversational model instead of moving into the program: ```ruby class ResearchAgent < LittleGhost::Agent tools HelpCenterLookupTool, ConfirmTool code_mode except: ["confirm_tool"] end ``` Exclude a Tool when the conversational model should call it as a distinct decision—for example, a final confirmation that must remain visible as its own step. `except` uses each Tool's model-visible name; `ConfirmTool` defaults to `confirm_tool`. Calls made inside and outside code mode share the Agent's Tool-call limit. The `exec`, `wait`, and `stop` controls manage execution. They do not count toward that application Tool limit themselves. Subagent controls also stay in the conversation. They are orchestration choices for the parent model, not functions available inside a code-mode program. Code-mode `wait` watches an interpreter program; `wait_for_subagents` checks on delegated Agents. [Core Concepts](core_concepts.md#subagents-bring-in-a-specialist) explains model-directed delegation. ## Set limits for the work you expect The Ruby engine sets limits for source and output size, memory, total and CPU time, file size, the number of programs, Tool calls, concurrency, and cleanup. Override only the limits your workload needs to change: ```ruby LittleGhost.configure do |config| config.code_mode = { engine: :ruby, sandbox: :native, limits: { programs: 16, wall_seconds: 900, cleanup_seconds: 5 } } end ``` Bubblewrap owns the program's process tree but does not cap its process or thread count. Use an outer cgroup or container supervisor when generated code needs a hard task-count limit. Application defaults apply to every Agent that declares `code_mode`. An Agent can override the engine, Sandbox, limits, or excluded Tools in its own declaration. The operating-system Sandbox contains the interpreter. The parent Ruby process starts it, brokers Tool calls, and cleans it up. Language restrictions alone cannot contain native extensions, interpreter bugs, files, subprocesses, or sockets. Use an enforcing Sandbox backend for model-written code. Before production, test the deployed backend against the files, child processes, networking, and resource pressure your application expects. Also test cancellation and cleanup on the deployed host. ## Opt into JavaScript when it fits The JavaScript engine is optional. It uses MiniRacer and gives each program its own V8 global state. The core gem does not require or load MiniRacer: ```ruby # Gemfile gem "mini_racer", "~> 0.21" # application setup require "little_ghost/code_mode/javascript_engine" LittleGhost.configure do |config| config.code_mode = {engine: :javascript, sandbox: :native} end ``` The JavaScript program has no Node.js APIs, filesystem, network, console, WebAssembly, or process-spawning API. Tool methods return Promises, and the generated instructions include TypeScript declarations derived from each Tool schema. Use `await` or `Promise.all`, `text(value)` for output, and `exit()` to complete early. Call `text(value)` first when the value should become user-visible output. MiniRacer's language-level restrictions are useful, but the operating-system Sandbox still contains the program. The Ruby parent owns the Tool catalog, permission checks, Tool-call limits, events, tracing, and resource cleanup. ## Build a custom engine Applications can register another `CodeMode::Engine`. An engine names its language, writes the instructions shown to the model, and opens a `CodeMode::Session`. The session implements `#execute`, `#wait`, `#stop`, and `#close`. The first three operations return a `CodeMode::ProgramResult`. LittleGhost gives the engine a Tool broker and a Sandbox factory. The broker stays in the parent Ruby process. The factory creates the Sandbox that contains model-written code. An engine may request named runtime paths for its interpreter libraries. Those paths are visible to the child process, but they never become filesystem grants available through Tools. The session owns every Workspace, Sandbox, child process, background task, and communication channel it creates. It closes those resources in reverse order. One registered engine can open several sessions concurrently on threads or fibers. Keep each program's mutable state inside the returned session, and synchronize any state the engine shares across sessions. A sandboxed engine must use a backend that owns the complete child process tree or can prevent child processes. An explicitly unrestricted backend may run an engine, but the generated program then has the same host access as the parent. See `LittleGhost::CodeMode::Engine`, `LittleGhost::CodeMode::Session`, and `LittleGhost::CodeMode::ProgramResult` for the extension contract. Continue with [Integrations](integrations.md) to connect Runs to MCP tools, AG-UI, and OpenTelemetry. --- Source: https://mattyr.github.io/little_ghost/docs/integrations.md # Integrations Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/integrations.html LittleGhost can load Tools from an MCP server, translate a Run stream for an interactive interface, and publish traces. Each integration uses the same Agents and Runs you already have. ## Load Tools from an MCP server An MCP Toolset connects to one server and turns its published operations into LittleGhost Tool classes. Add the Toolset through the same Agent `tools` declaration used for local Tools: ```ruby require "little_ghost/mcp" class HelpCenterTools < LittleGhost::MCP::Toolset connection url: "https://mcp.example/rpc", timeout: 20 end class CustomerSupportAgent < LittleGhost::Agent system_prompt "Use help-center tools for published guidance." tools HelpCenterTools end run = CustomerSupportAgent.ask("How long do refunds take?") run.response ``` `connection` requires `url` and also accepts `headers`, `timeout`, `signer`, `allow_insecure_http`, and `max_response_bytes`. Pass a block when credentials depend on the current Agent run: ```ruby connection do |binding| token = McpAccessTokens.for_actor(binding.run.invocation.actor_id) { url: "https://mcp.example/rpc", headers: {"Authorization" => "Bearer #{token}"}, timeout: 20 } end ``` The block's `binding` gives it access to the current Run. LittleGhost evaluates the block before opening the MCP session, so each Agent run can use credentials for its authenticated caller. By default, the Agent receives every operation published by the server. Their normalized server names, such as `search` and `fetch`, become Tool names. Use `map_tool` when the Agent should receive only part of the server catalog or when a generated Tool needs a different name or configuration: ```ruby class CuratedHelpCenterTools < LittleGhost::MCP::Toolset connection url: "https://mcp.example/rpc", timeout: 20 map_tool do |tool_class, definition:, binding:| next unless %w[search fetch].include?(definition.source_name) tool_class.tool_name "help_center_#{definition.source_name}" tool_class end end ``` `definition` describes the operation published by the server, and `binding` identifies the current Agent run. Return the class after configuring it, or return `nil` to omit the operation. Renaming a generated Tool does not change the original `Definition#source_name` sent back to the server. The Agent can call the generated Tools like local Tools. LittleGhost uses one local client and transport for the Toolset during the Agent run. The built-in HTTP transport does not send an MCP session-termination request. Configure server-side expiry, or arrange explicit remote cleanup when the server requires it. Most MCP results need no mapping. LittleGhost returns `structuredContent` as a Ruby Hash when present, otherwise it returns the server's text. Server images become Artifacts. Use `map_result` when one operation needs application-specific conversion. This example turns the server's download identifier into a deferred Artifact: ```ruby map_result do |result, call:, binding:| next result unless call.definition.source_name == "export" LittleGhost::Tool::Result.new( value: result.structured_content, artifacts: [ LittleGhost::Artifact.deferred( reference: result.metadata.fetch("download_id"), media_type: "application/octet-stream" ) ] ) end ``` `map_result` receives the complete `MCP::Result`, the `MCP::Call` that produced it, and the current binding. Return any Ruby value or `Tool::Result`. Returning the supplied result unchanged keeps the default conversion described above. MCP images and local Tool artifacts use the same storage and presentation rules when `Configuration#artifacts` is enabled. Images and documents are sent as model content; their stored references are fallback information rather than a second representation. LittleGhost also checks results against server-advertised JSON Schema Draft 2020-12 output schemas. An optional server can fail discovery without preventing Agent construction: ```ruby class HelpCenterTools < LittleGhost::MCP::Toolset connection { |binding| McpConnections.help_center(binding) } optional true on_error do |error, binding:| McpAvailability.report(error, run_id: binding.run.invocation.run_id) end end ``` `optional true` converts expected provider and protocol discovery failures into an empty Tool set. `on_error` observes only those caught failures. Cancellation, deadlines, configuration errors, and application callback failures still propagate. LittleGhost limits the number and total size of discovered operations, the complexity of their schemas, and the size and number of returned images. `HTTPTransport` also limits each HTTP response and requires HTTPS unless local HTTP is explicitly enabled. > **Safety note:** An MCP server supplies descriptions and results that the model > can see. Structural validation does not make that content trustworthy or > authorize an operation it suggests. Expose only the operations the Agent > needs, use narrowly scoped credentials, and have the server authorize every > sensitive call. If a result becomes a deferred Artifact, its resolver must > verify that the referenced file belongs to the authenticated caller, fetch > only from an intended service, and limit the response size before returning > bytes to LittleGhost. LittleGhost implements its documented client behavior for the [MCP 2025-06-18 specification](https://modelcontextprotocol.io/specification/2025-06-18). Use `LittleGhost::MCP::HTTPTransport` and `LittleGhost::MCP::Client` directly when you need a custom transport. They produce the same generated Tool classes and accept the same mapping callbacks as Toolset. ## Send a Run stream through AG-UI The AG-UI adapter converts LittleGhost events into protocol event hashes: ```ruby require "json" require "little_ghost/ag_ui" source = CustomerSupportAgent.stream_ask( question, actor_id: authenticated_user.id, context: {account_id: authenticated_user.account_id} ) events = LittleGhost::AGUI::Adapter.new.stream( source, thread_id: conversation.id, run_id: request.request_id ) events.each { |event| websocket.write(JSON.generate(event)) } ``` The adapter translates text, reasoning, Tool activity, usage, retries, trace context, subagent activity, and terminal outcomes. It is stateless between calls. Your application still owns the connection, backpressure, disconnect behavior, and any request state its callbacks need. LittleGhost also emits namespaced custom events. Consumers should preserve or deliberately ignore event types they don't recognize. See the [AG-UI event documentation](https://docs.ag-ui.com/concepts/events) when implementing the client. > **Safety note:** A Run stream can include model output, Tool arguments and > results, errors, and participant activity. Check that the connected user may > see the complete Run, then filter fields before sending or storing events. Calling `each` drives the source stream on the caller's fiber or thread. When a client disconnects, stop enumerating and apply the cancellation behavior your application needs. Closing the socket can't undo Tool work that already ran. ## Trace Runs with OpenTelemetry Configure an OpenTelemetry SDK and exporter in the application, then register the LittleGhost subscriber before the first Agent call: ```ruby LittleGhost.configure do |config| config.instrument LittleGhost::Tracing::OpenTelemetry.new end ``` LittleGhost depends on `opentelemetry-api`, leaving the SDK, processor, and exporter up to the application. It emits spans and events for Runs, Agents, model calls, Tools, assemblies, sessions, usage, and failures. Active operations can propagate W3C `traceparent` and `tracestate` fields. Prompts, messages, responses, Tool arguments, and exception content are omitted by default. If you intentionally need some of that content, install a `LittleGhost::Support::ContentCapture` with a scrubber before enabling capture. Avoid putting raw user, order, session, or request IDs in span attributes. Attribute names follow the evolving [OpenTelemetry GenAI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/) where they apply. Flush or shut down `LittleGhost::Instrumentation` during application shutdown when your backend buffers data. See [Running in Production](production.md) for startup, shutdown, and observability, [Tools](tools.md) for local and remote Tool behavior, and [Workspaces and Sandboxes](sandboxing.md) for child processes and files. --- Source: https://mattyr.github.io/little_ghost/docs/production.md # Running in Production Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/production.html The Agent or Assembly you ran in a script can move into a controller, job, CLI, or service without changing shape. A long-running application usually adds stable model names, shared services, conversation history, background execution, and observability. ## Select models by application role A direct target keeps a small definition self-contained: ```ruby class CustomerSupportAgent < LittleGhost::Agent model "openrouter:openai/gpt-5.6-luna" end ``` As an application grows, a **model role** gives that choice a stable application name: ```ruby # config/initializers/little_ghost.rb LittleGhost.configure do |config| config.providers = { openrouter: { adapter: :openrouter, api_key: ENV.fetch("OPENROUTER_API_KEY") } } config.models = { customer_support: { target: "openrouter:openai/gpt-5.6-luna", settings: {temperature: 0.2} } } config.default_model = :customer_support end class CustomerSupportAgent < LittleGhost::Agent model :customer_support end ``` Provider connections and model roles can also live in YAML files under `config/little_ghost`, or in files you select explicitly. Values set in Ruby take priority. An explicitly selected file comes next, followed by conventional files and environment defaults. See `LittleGhost::Configuration` when you need every supported source and override. Prompts, caller input and history, Tool results, and attachments may go to the selected provider. Choose configured providers that are appropriate for that data and its retention or residency needs. ## Configure once, call from anywhere The `LittleGhost.configure` block above is the entire initializer. Controllers and jobs can call your Agent and Assembly classes directly. Then call the Agent directly from a controller or job: ```ruby class SupportQuestionsController < ApplicationController def create run = CustomerSupportAgent.ask( params.require(:question), actor_id: current_user.id, context: {account_id: current_user.account_id} ) if run.completed? render json: {answer: run.response} else render json: {error: "Support request failed"}, status: :bad_gateway end end end ``` On the first class-level call, LittleGhost prepares model resolution, loading, prompt lookup, persistence, hooks, and factories. Later calls reuse those application services automatically. Each `.ask` creates a fresh top-level Run with fresh bound participants and Tools. Reusing application services does not create conversation history. Pass a stable `session_id` only when a later request should continue an earlier conversation. The controller supplies identity and account access from authenticated application state. The model cannot replace those values through its prompt or tool arguments. A background job uses the same direct calling style. Configure LittleGhost before the first Agent or Assembly call. Once application services start successfully, the configuration is locked so every request sees one stable setup. ## Use an existing fiber scheduler If your application already runs inside a Ruby Fiber scheduler, LittleGhost uses it for parallel Tool calls, Workflow and Graph branches, subagent turns, background Executions, and nested code-mode Tool calls. LittleGhost does not install or run a scheduler. Your scheduler must support `Fiber.schedule`. The optional `async` gem used below does. For example, an application using the optional `async` gem can let several requests make progress on one thread while each request waits for network I/O. Add `gem "async"` to the application's bundle, then start the calls inside an Async task: ```ruby require "async" questions = [ "How long do refunds take?", "Can I update my delivery address?" ] answers = Async do |task| questions.map do |question| task.async { CustomerSupportAgent.ask(question).response } end.map(&:wait) end.wait ``` The default `:auto` setting uses fibers when a call begins inside a scheduled fiber and worker threads everywhere else. Set `concurrency_backend` to `:fiber` when calling outside a scheduled fiber should be an application error. LittleGhost then raises `LittleGhost::ConfigurationError` instead of quietly starting a thread. ### Keep one blocking call from pausing other fibers Fiber scheduling helps while work waits for I/O; it does not make CPU-heavy Ruby code run in parallel. Whether an I/O call lets other fibers run depends on the Ruby version, scheduler, and library. Call libraries normally at first. If documentation or measurement shows that one call pauses the other fibers—and the work can continue on another Ruby thread—wrap that call: ```ruby article = LittleGhost.offload_blocking do HelpCenterSearch.lookup(question) end ``` Outside a scheduled fiber, `offload_blocking` runs the block inline. Inside one, it uses LittleGhost's shared pool of reusable threads so the other fibers can continue. If the caller is cancelled after the pool accepts the block, LittleGhost waits for the block to finish before reporting the cancellation. The helper does not add a timeout or cancellation mechanism to the underlying call, so use the library's controls when available. If most of your Tool or extension code prevents other fibers from running, use worker threads for all LittleGhost concurrency instead: ```ruby LittleGhost.configure do |config| config.concurrency_backend = :thread end ``` LittleGhost also keeps a few jobs on threads so it can finish or clean them up reliably. Provider and subprocess streams may use dedicated threads. Inside a scheduled fiber, certificate generation and Filesystem SessionStore transactions use the same shared pool as `offload_blocking`. A Run may therefore still create or use threads when its concurrency backend is `:fiber`. The blocking pool allows two operations at a time by default. Applications that observe calls waiting for a pool worker can increase its process-wide capacity during startup, before any call can start the pool: ```ruby LittleGhost.configure do |config| config.blocking_pool_capacity 4 end ``` Increasing this value permits more operating-system threads. It does not change Tool, Workflow, Graph, or subagent concurrency. The value is process-wide; every `Configuration` reads and writes the same setting. ### Protect state shared by concurrent calls LittleGhost may call a shared Tool, provider, SessionStore, hook, or callback from different threads. Fibers can also take turns entering the same object on one thread. Protect shared mutable state, keep lock scope narrow, and do not call application callbacks while holding a lock. Pass request-specific values through the Invocation context or another explicit argument. Do not use `thread_variable_set` for request state because every fiber on the thread shares those values. `Thread.current[:key]` is fiber-local, but LittleGhost does not copy application-defined entries into each worker task. ## Preserve conversation with Sessions A **Session** lets one request continue an earlier conversation. Pass the same session ID and trusted actor ID with each related call: ```ruby run = CustomerSupportAgent.ask( "What did we decide about my refund?", session_id: "conversation-42", actor_id: authenticated_user.id ) ``` Take `actor_id` from authenticated application state. A session ID alone does not prove who the caller is, and a nil actor does not separate tenants. Built-in persistence drops system messages, temporary messages, and private reasoning. If you customize persistence, decide what else is safe to store. A session is checkpointed when its store write succeeds. The in-memory store lasts only as long as one process. Choose a durable `SessionStore` when conversations must survive a restart or continue on another process. [LittleGhost::SessionStores::Filesystem](LittleGhost/SessionStores/Filesystem.md) is a built-in durable choice for a trusted local or shared filesystem. Set its root to the application-managed directory that holds session data: ```ruby LittleGhost.configure do |config| config.session_store = { provider: LittleGhost::SessionStores::Filesystem, root: "/var/lib/customer_support/sessions" } end ``` Every Run has a session ID so LittleGhost can checkpoint its progress. If you do not supply one, LittleGhost generates a new ID for that call. Because your application does not reuse that generated ID, it does not create conversation continuity. A persistent SessionStore may still save working state under it before the Run finishes, so keep request context safe to store or filter sensitive fields in your store. ## Stream or supervise long-running work `.stream_ask` runs on the caller's fiber or thread and yields `StreamEvent` values as the answer arrives: ```ruby stream = CustomerSupportAgent.stream_ask(question) run = stream.each do |event| publish(event) if event.type == :text_delta end record_outcome(run.outcome, error_type: run.error&.class&.name) ``` Composite assembly streams include intermediate and nested Agent work as `:agent_stream` events. This default also applies to the event consumer passed to `start_execution`. Pass `include_agent_events: false` when only the ordinary public stream is needed. > **Safety note:** Contextual events can include inputs, reasoning, Tool > arguments and results, errors, and output from every participant. Check that > the destination may see the complete Run, or filter the events before sending > or storing them. LittleGhost's AG-UI adapter ignores these events unless the > application translates them explicitly. Use `start_execution` when the caller must stay free for other work, or when you want to deliver an interjection to an active response: ```ruby execution = agent.start_execution(message: question) do |event| event_buffer << event end execution.interject(message: "Include the latest ledger entry") execution.wait(deadline: Time.now + 30) execution.run.completed? ``` The event block runs on the same fiber or thread as the Execution. With `:auto`, `start_execution` uses a fiber when its caller is already in a scheduled fiber; otherwise, it uses a worker thread. Keep the block quick because it slows event delivery while it runs. Cancellation, deadlines, and `close` ask the work to stop; they cannot forcibly end arbitrary provider or Tool code or undo actions that already happened. Keep the application's scheduler running until an Execution using it finishes or closes. ## Keep Tool permission checks in application code A Tool schema checks the shape of model-supplied input. Your application still owns permission checks, safe retries, rate limits, and auditing. An ordinary Tool runs in the Ruby process; a Sandbox contains only file or child-process work that deliberately passes through it. Use the Tool binding's `run` to read current, application-established values from `run.invocation.context`. Don't rely on model arguments for identity or account membership. Treat `RunContext#state` as mutable working and Session state. Revalidate anything restored from an earlier request. Synchronize access when parallel Tools share mutable state, or mark every Tool that reads or changes it as `exclusive true`. A `ToolError` message is visible to the model, so keep it safe to share. LittleGhost hides unexpected exception messages from model-facing results. When a step retries, its tool calls may happen again too. Prefer read-only work, idempotency keys, or operations that are safe to repeat. [Tools](tools.md) develops this pattern from the first application Tool through bindings, concurrency, sandbox delegation, and code mode. ## Choose workspace and sandbox behavior explicitly A **Workspace** names the host paths associated with a Run. A **Sandbox** controls filesystem operations and child processes deliberately sent through it. A custom Ruby Tool stays in the application process unless it delegates work to the bound Sandbox. The dependency-free default is an application-root Workspace with `LittleGhost::Sandboxes::Unrestricted`. It is not process or network isolation. Select an enforcing backend explicitly when a model can influence commands; LittleGhost raises when that backend is unavailable instead of silently falling back: ```ruby require "fileutils" require "tmpdir" LittleGhost.configure do |config| config.workspace = lambda do |**| root = Dir.mktmpdir("little-ghost-support-") LittleGhost::Workspace.new( root:, teardown: lambda do |workspace:, **| FileUtils.remove_entry_secure(workspace.root) if File.exist?(workspace.root) end ) end config.sandbox = { provider: :native, files: {root: :read_write}, root_filesystem: :isolated, environment: {inherit: false, set: {"LANG" => "C.UTF-8"}}, network: :none } end ``` The temporary Workspace above is useful when files should live for one Run. Use application-managed storage, with tenant isolation and concurrency control, when files must persist or several Runs share a root. The Run opens a Runtime-created Workspace before its Sandbox and closes them in reverse order after every outcome. Closing a Workspace invokes its configured teardown; it does not delete files by default. Cleanup failures raise because LittleGhost cannot confirm a clean shutdown of every owned resource. Existing instances passed by the application remain caller-owned. [Workspaces and Sandboxes](sandboxing.md) explains backend selection, logical Workspace paths, files, process-only runtime paths, Scopes, filtered networking, and deployment validation in depth. [Code Mode](code_mode.md) applies that setup to model-authored Ruby or optional JavaScript that composes the Agent's existing Tools. ## Protect data in telemetry LittleGhost emits events as a request starts, calls a model or tool, moves between assembly steps, retries, and finishes. Instrumentation subscribers and OpenTelemetry exporters can send those events to your monitoring system. An external telemetry service may receive application identifiers and event data. Redact sensitive values before exporting them. Avoid attributes with many unique values, such as raw order or request IDs. A composite `RunResult` includes short step summaries and trajectory queries. Keep detailed provider errors and sensitive diagnostics in your monitoring system, not in model or user responses. ## Know what the Run closes and raises One top-level Run owns the workspace and sandbox that LittleGhost creates for it, plus application resources registered with `run.register`. It closes those resources after success, failure, a partial response, or cancellation. Existing workspace or sandbox instances passed by the application remain caller-owned. Ordinary execution failures appear on the Run and its final event. Cleanup, event delivery, or instrumentation can still raise an exception when LittleGhost cannot promise a clean ending. ## Advanced: work with Runtime directly A Runtime is the internal home for shared model resolution, loading, persistence, hooks, and resource factories. Most applications never need to handle it: `LittleGhost.configure` and class-level `.ask` are enough. Use `LittleGhost.runtime` when an extension needs the shared object itself. Construct a separate Runtime only when one process deliberately hosts an isolated LittleGhost setup: ```ruby configuration = LittleGhost::Configuration.new(root: isolated_root) runtime = LittleGhost::Runtime.new(configuration: configuration) agent = CustomerSupportAgent.new(runtime: runtime) ``` An explicit Runtime has its own independent configuration. It does not replace LittleGhost's shared default. One Runtime can serve independent calls from several threads and fibers. Each call gets its own Run, participants, Tools, and Runtime-created Workspace and Sandbox. An Agent or Assembly already bound to an active Run must stay with that Run. Within one SessionStore instance, LittleGhost serializes calls sharing a Session. Multi-process deployments need coordination from their store. Custom stores and other shared extension objects may receive concurrent calls. Calls can overlap on different threads, or fibers can take turns entering the same object on one thread. Protect shared mutable state without relying on thread identity. Runtime has no shutdown step. Shared services supplied by the application keep their own lifecycle. Shut those services down with the rest of your application. If you installed process-wide instrumentation subscribers, flush or shut down `LittleGhost::Instrumentation` during application shutdown. For exact constructors, options, events, extension contracts, and error behavior, continue into the API reference for `LittleGhost::Configuration`, `LittleGhost::Runtime`, `LittleGhost::Run`, `LittleGhost::Execution`, `LittleGhost::Session`, `LittleGhost::Tool`, and `LittleGhost::StreamEvent`. --- Source: https://mattyr.github.io/little_ghost/docs/api.md # LittleGhost API index Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/api.html Every public class and module is listed here. Open an entry for signatures, ownership, and failure behavior. - [LittleGhost](LittleGhost.md) — Build AI features as ordinary Ruby classes. - [LittleGhost::AGUI](LittleGhost/AGUI.md) — AG-UI connects LittleGhost streams to user interfaces that speak the AG-UI protocol. - [LittleGhost::AGUI::Adapter](LittleGhost/AGUI/Adapter.md) — Adapter turns a LittleGhost stream into AG-UI event hashes. - [LittleGhost::AbstractMethodError](LittleGhost/AbstractMethodError.md) — Raised when an abstract framework method has no concrete implementation. - [LittleGhost::AdapterLoadError](LittleGhost/AdapterLoadError.md) — Raised when a configured provider adapter cannot be constructed. - [LittleGhost::Agent](LittleGhost/Agent.md) — Defines one reusable model-driven behavior with prompts, tools, and limits. - [LittleGhost::Agent::ContextManagement](LittleGhost/Agent/ContextManagement.md) — Keep long conversations within the model's available context window. - [LittleGhost::Agent::ContextManagement::ClassMethods](LittleGhost/Agent/ContextManagement/ClassMethods.md) — Exposes context-management declarations on agent classes. - [LittleGhost::Agent::Delegation](LittleGhost/Agent/Delegation.md) — Give one agent a bounded way to ask another agent for help. - [LittleGhost::Agent::Delegation::ClassMethods](LittleGhost/Agent/Delegation/ClassMethods.md) — Exposes delegation declarations on agent classes. - [LittleGhost::Agent::Skills](LittleGhost/Agent/Skills.md) — Let an agent discover application-authored instructions only when it needs them. - [LittleGhost::Agent::Skills::ClassMethods](LittleGhost/Agent/Skills/ClassMethods.md) — Exposes skill discovery declarations on agent classes. - [LittleGhost::Agent::ToolLoop](LittleGhost/Agent/ToolLoop.md) — Stop an agent from repeating a tool call that cannot make progress. - [LittleGhost::Agent::ToolLoop::ClassMethods](LittleGhost/Agent/ToolLoop/ClassMethods.md) — Exposes tool-loop detection declarations on agent classes. - [LittleGhost::AgentBuilder](LittleGhost/AgentBuilder.md) — Builds an Agent definition from declarations made at runtime. - [LittleGhost::AgentInterjectionError](LittleGhost/AgentInterjectionError.md) — Raised when an active run cannot accept an interjection. - [LittleGhost::AgentStreamSource](LittleGhost/AgentStreamSource.md) — Describes which Agent produced an event during a Run. - [LittleGhost::AgentStreamStep](LittleGhost/AgentStreamStep.md) — Identifies one assembly step in the path to a streamed Agent invocation. - [LittleGhost::Artifact](LittleGhost/Artifact.md) — Represents a file, image, or document produced by a Tool or supplied to a Run. - [LittleGhost::Artifacts](LittleGhost/Artifacts.md) — Stores files from Run input and Tool results, then presents them to agents as bounded images, documents, previews, or Workspace references. - [LittleGhost::Assembly](LittleGhost/Assembly.md) — Gives one agent or a coordinated group the same callable entrypoint. - [LittleGhost::Assembly::Attempt](LittleGhost/Assembly/Attempt.md) — One bounded attempt to execute a child Assembly step. - [LittleGhost::Assembly::Step](LittleGhost/Assembly/Step.md) — One logical child execution in a composite Assembly result. - [LittleGhost::Assembly::Trajectory](LittleGhost/Assembly/Trajectory.md) — Immutable queries over the steps returned by one assembly invocation. - [LittleGhost::AssemblyBuilder](LittleGhost/AssemblyBuilder.md) — Builds an Assembly when its participants or routes are discovered at runtime. - [LittleGhost::AssemblyDefinition](LittleGhost/AssemblyDefinition.md) — A complete Assembly configuration produced by an AssemblyBuilder. - [LittleGhost::AssemblyError](LittleGhost/AssemblyError.md) — Base class for failures coordinating one or more assemblies. - [LittleGhost::AssemblyLimitError](LittleGhost/AssemblyLimitError.md) — Raised when an assembly exceeds its configured execution bound. - [LittleGhost::AssemblyRoutingError](LittleGhost/AssemblyRoutingError.md) — Raised when an assembly cannot choose one valid next participant. - [LittleGhost::AssemblyStepTimeoutError](LittleGhost/AssemblyStepTimeoutError.md) — Raised when one assembly step exceeds its local timeout. - [LittleGhost::CancelledError](LittleGhost/CancelledError.md) — Raised when cancellation stops an operation. - [LittleGhost::CapabilityError](LittleGhost/CapabilityError.md) — Raised when a backend cannot enforce a requested sandbox capability. - [LittleGhost::CleanupError](LittleGhost/CleanupError.md) — Raised when one or more managed resources fail to close. - [LittleGhost::CodeMode](LittleGhost/CodeMode.md) — Runs model-authored orchestration code in a child interpreter. - [LittleGhost::CodeMode::Broker](LittleGhost/CodeMode/Broker.md) — Keeps tool authorization and execution in the trusted parent process. - [LittleGhost::CodeMode::Catalog](LittleGhost/CodeMode/Catalog.md) — Normalizes a trusted Tool catalog for a guest language and rejects names that would collide or shadow code-mode controls. - [LittleGhost::CodeMode::Engine](LittleGhost/CodeMode/Engine.md) — Adapter contract for a code-mode language. - [LittleGhost::CodeMode::JavascriptEngine](LittleGhost/CodeMode/JavascriptEngine.md) — Runs model-written JavaScript in an isolated V8 context. - [LittleGhost::CodeMode::ProgramResult](LittleGhost/CodeMode/ProgramResult.md) — Describes one observation of a code-mode program. - [LittleGhost::CodeMode::Protocol](LittleGhost/CodeMode/Protocol.md) — Length-prefixed JSON framing shared by code-mode parent and child hosts. - [LittleGhost::CodeMode::RubyEngine](LittleGhost/CodeMode/RubyEngine.md) — Runs model-written Ruby in a fresh sandboxed process. - [LittleGhost::CodeMode::Session](LittleGhost/CodeMode/Session.md) — Lifecycle contract for one Engine's active program. - [LittleGhost::Configuration](LittleGhost/Configuration.md) — Configure shared services and lookup rules before agents start. - [LittleGhost::ConfigurationError](LittleGhost/ConfigurationError.md) — Raised for invalid framework or application configuration. - [LittleGhost::Content](LittleGhost/Content.md) — Content gives messages a shared vocabulary for text, attachments, tool calls, tool results, and model reasoning. - [LittleGhost::Content::Document](LittleGhost/Content/Document.md) — Contains binary document data, its MIME media type, and a display name. - [LittleGhost::Content::Image](LittleGhost/Content/Image.md) — Contains binary image data, its MIME media type, and an optional display name. - [LittleGhost::Content::Reasoning](LittleGhost/Content/Reasoning.md) — Preserves provider reasoning without forcing every provider into one representation. - [LittleGhost::Content::Text](LittleGhost/Content/Text.md) — Contains model-visible text. - [LittleGhost::Content::ToolResult](LittleGhost/Content/ToolResult.md) — Carries the model-facing result for one ToolUse. - [LittleGhost::Content::ToolUse](LittleGhost/Content/ToolUse.md) — Describes one tool call requested by a provider-backed model. - [LittleGhost::ContextWindowOverflowError](LittleGhost/ContextWindowOverflowError.md) — Raised when a provider reports that the request exceeds its context window. - [LittleGhost::CredentialError](LittleGhost/CredentialError.md) — Raised when no usable credentials can be resolved for a provider. - [LittleGhost::DataMap](LittleGhost/DataMap.md) — DataMap holds JSON-compatible application data with indifferent key access. - [LittleGhost::DeadlineExceededError](LittleGhost/DeadlineExceededError.md) — Raised when an operation reaches its deadline. - [LittleGhost::DependencyError](LittleGhost/DependencyError.md) — Raised when an explicitly selected sandbox backend dependency is unavailable. - [LittleGhost::Error](LittleGhost/Error.md) — Base class for LittleGhost domain errors. - [LittleGhost::Events](LittleGhost/Events.md) — Events lets an application react to noteworthy agent activity without coupling LittleGhost to a logger or event backend. - [LittleGhost::Events::ConsoleListener](LittleGhost/Events/ConsoleListener.md) — JSON-lines listener suitable for diagnostics and local development. - [LittleGhost::Events::Reporter](LittleGhost/Events/Reporter.md) — Thread-safe event publisher with process-wide and fiber-scoped listeners. - [LittleGhost::Execution](LittleGhost/Execution.md) — Runs one dormant Run in the background while the caller remains free to serve health checks, deliver interjections, or coordinate shutdown. - [LittleGhost::ExecutionState](LittleGhost/ExecutionState.md) — ExecutionState carries request-scoped values across scheduled fibers and worker threads. - [LittleGhost::Graph](LittleGhost/Graph.md) — Routes a request through named Assembly nodes and declared edges. - [LittleGhost::Graph::State](LittleGhost/Graph/State.md) — Read-only routing data passed to conditions and input mappers. - [LittleGhost::GraphBuilder](LittleGhost/GraphBuilder.md) — Builds a Graph from nodes and routes discovered at runtime. - [LittleGhost::Instrumentation](LittleGhost/Instrumentation.md) — Instrumentation turns agent work into structured lifecycle notifications. - [LittleGhost::Instrumentation::Bus](LittleGhost/Instrumentation/Bus.md) — Thread-safe notification bus used by the process-wide Instrumentation API. - [LittleGhost::Instrumentation::Handle](LittleGhost/Instrumentation/Handle.md) — A Handle represents work between Instrumentation.start and #finish. - [LittleGhost::Instrumentation::Subscriber](LittleGhost/Instrumentation/Subscriber.md) — Subclass Subscriber to connect a telemetry backend. - [LittleGhost::InvalidPromptTemplateError](LittleGhost/InvalidPromptTemplateError.md) — Raised for unsafe names, escaped roots, cycles, or excessive recursion. - [LittleGhost::Invocation](LittleGhost/Invocation.md) — Carry one application request into an agent run. - [LittleGhost::InvocationError](LittleGhost/InvocationError.md) — Raised when an invocation payload or operation is invalid. - [LittleGhost::Lookup](LittleGhost/Lookup.md) — Lookup holds path values shared by prompt and skill discovery. - [LittleGhost::Lookup::Root](LittleGhost/Lookup/Root.md) — Holds an expanded lookup path and the optional trusted boundary it must remain within after symbolic links are resolved. - [LittleGhost::MCP](LittleGhost/MCP.md) — MCP lets LittleGhost agents use tools published by Model Context Protocol servers. - [LittleGhost::MCP::Call](LittleGhost/MCP/Call.md) — Describes one MCP Tool invocation. - [LittleGhost::MCP::Client](LittleGhost/MCP/Client.md) — Client is the lower-level interface for loading tools from an MCP server. - [LittleGhost::MCP::Definition](LittleGhost/MCP/Definition.md) — Immutable server-advertised Tool metadata. - [LittleGhost::MCP::HTTPTransport](LittleGhost/MCP/HTTPTransport.md) — HTTPTransport sends MCP JSON-RPC messages over Streamable HTTP. - [LittleGhost::MCP::Result](LittleGhost/MCP/Result.md) — Represents one MCP Tool result without discarding server fields. - [LittleGhost::MCP::SigV4Signer](LittleGhost/MCP/SigV4Signer.md) — SigV4Signer adds AWS Signature Version 4 authentication to MCP requests. - [LittleGhost::MCP::Toolset](LittleGhost/MCP/Toolset.md) — Connects one MCP server to an Agent as a reusable Tool provider. - [LittleGhost::MalformedToolCallError](LittleGhost/MalformedToolCallError.md) — Raised when a model returns an invalid tool-call representation. - [LittleGhost::Message](LittleGhost/Message.md) — A Message carries one participant's contribution to an agent conversation. - [LittleGhost::MissingPromptLocalError](LittleGhost/MissingPromptLocalError.md) — Raised when an ERB template references a missing local variable. - [LittleGhost::MissingPromptTemplateError](LittleGhost/MissingPromptTemplateError.md) — Raised when no configured root contains the requested template. - [LittleGhost::Model](LittleGhost/Model.md) — Model is the resolved connection between an agent selection and a provider. - [LittleGhost::ModelCapabilities](LittleGhost/ModelCapabilities.md) — Describes the optional features a model can use. - [LittleGhost::ModelInterface](LittleGhost/ModelInterface.md) — Interface for executable model implementations accepted by agents. - [LittleGhost::ModelRequest](LittleGhost/ModelRequest.md) — Carries everything a provider needs for one model stream. - [LittleGhost::ModelResolver](LittleGhost/ModelResolver.md) — Maps an application model role to an executable Model. - [LittleGhost::ModelResponse](LittleGhost/ModelResponse.md) — Represents the final result shared by every provider stream. - [LittleGhost::Models](LittleGhost/Models.md) — Immutable model identities, metadata, configuration readers, and catalogs. - [LittleGhost::Models::Catalog](LittleGhost/Models/Catalog.md) — Resolves model facts from refreshed data and the snapshot packaged with LittleGhost. - [LittleGhost::Models::Catalog::ModelsDevSource](LittleGhost/Models/Catalog/ModelsDevSource.md) — Refreshes normalized facts from the public models.dev catalog. - [LittleGhost::Models::Catalog::Source](LittleGhost/Models/Catalog/Source.md) — Interface for catalog refresh implementations. - [LittleGhost::Models::Configuration](LittleGhost/Models/Configuration.md) — Loads trusted provider connections or logical model profiles from YAML. - [LittleGhost::Network](LittleGhost/Network.md) — Network policy helpers used by sandbox backends. - [LittleGhost::Network::Decision](LittleGhost/Network/Decision.md) — Trusted authorization result and tightly scoped upstream header changes. - [LittleGhost::Network::EnvoyGateway](LittleGhost/Network/EnvoyGateway.md) — Manages Envoy as a native process or pinned Docker sidecar for one Sandbox. - [LittleGhost::Network::ExternalGateway](LittleGhost/Network/ExternalGateway.md) — Exposes an application-managed proxy to an isolated sandbox without claiming ownership of its lifecycle or attesting what it enforces. - [LittleGhost::Network::Gateway](LittleGhost/Network/Gateway.md) — Lifecycle contract implemented by filtered-egress gateways. - [LittleGhost::Network::Request](LittleGhost/Network/Request.md) — Normalized, headers-only request metadata passed to a trusted authorizer. - [LittleGhost::OutputLimitError](LittleGhost/OutputLimitError.md) — Raised when configured generation limits stop the agent before completion. - [LittleGhost::PathSet](LittleGhost/PathSet.md) — PathSet keeps prompt or skill lookup roots in deterministic search order. - [LittleGhost::PolicyError](LittleGhost/PolicyError.md) — Raised when a sandbox policy is internally invalid. - [LittleGhost::PromptResolver](LittleGhost/PromptResolver.md) — PromptResolver turns conventional ERB files into an agent's system prompt. - [LittleGhost::PromptTemplateError](LittleGhost/PromptTemplateError.md) — Base error raised while locating or rendering a prompt template. - [LittleGhost::ProtocolError](LittleGhost/ProtocolError.md) — Raised when a provider violates the expected request-response protocol. - [LittleGhost::ProviderError](LittleGhost/ProviderError.md) — Base class for provider request, response, and protocol failures. - [LittleGhost::ProviderRegistry](LittleGhost/ProviderRegistry.md) — Constructs built-in and application provider adapters from named provider connections. - [LittleGhost::Providers](LittleGhost/Providers.md) — Provider adapters translate model APIs into LittleGhost's shared streaming request and response types. - [LittleGhost::Providers::Anthropic](LittleGhost/Providers/Anthropic.md) — Connects a Model to Anthropic's Messages API. - [LittleGhost::Providers::Anthropic::CatalogSource](LittleGhost/Providers/Anthropic/CatalogSource.md) — Enriches availability and limits from Anthropic's model list endpoint. - [LittleGhost::Providers::Base](LittleGhost/Providers/Base.md) — Shared provider contract. - [LittleGhost::Providers::Bedrock](LittleGhost/Providers/Bedrock.md) — Bedrock lets LittleGhost agents use models available through Amazon Bedrock Converse. - [LittleGhost::Providers::Bedrock::CatalogSource](LittleGhost/Providers/Bedrock/CatalogSource.md) — Enriches Bedrock availability and on-demand pricing using bounded, SigV4-signed AWS APIs. - [LittleGhost::Providers::Bedrock::CredentialResolver](LittleGhost/Providers/Bedrock/CredentialResolver.md) — Resolves common AWS credentials without depending on an AWS SDK. - [LittleGhost::Providers::Bedrock::StreamError](LittleGhost/Providers/Bedrock/StreamError.md) — Represents an error event returned inside a Bedrock stream. - [LittleGhost::Providers::Configuration](LittleGhost/Providers/Configuration.md) — Holds trusted provider connection settings independently from model profiles. - [LittleGhost::Providers::Gemini](LittleGhost/Providers/Gemini.md) — Connects a Model to Google's Gemini generateContent API. - [LittleGhost::Providers::Gemini::CatalogSource](LittleGhost/Providers/Gemini/CatalogSource.md) — Enriches Gemini availability and limits from the Developer API. - [LittleGhost::Providers::HTTPError](LittleGhost/Providers/HTTPError.md) — Reports a bounded HTTP or network failure from a provider connection. - [LittleGhost::Providers::OpenAI](LittleGhost/Providers/OpenAI.md) — OpenAI connects LittleGhost agents to OpenAI models with streaming, tools, and structured results. - [LittleGhost::Providers::OpenAICompatible](LittleGhost/Providers/OpenAICompatible.md) — OpenAICompatible brings OpenAI-style Responses or Chat Completions endpoints into LittleGhost. - [LittleGhost::Providers::OpenAICompatible::StreamError](LittleGhost/Providers/OpenAICompatible/StreamError.md) — Represents a structured error received inside an otherwise successful provider stream. - [LittleGhost::Providers::OpenRouter](LittleGhost/Providers/OpenRouter.md) — OpenRouter gives one LittleGhost provider access to models routed through OpenRouter. - [LittleGhost::Providers::OpenRouter::CatalogSource](LittleGhost/Providers/OpenRouter/CatalogSource.md) — Adds richer routing metadata and pricing from OpenRouter's live catalog. - [LittleGhost::Providers::VertexAI](LittleGhost/Providers/VertexAI.md) — Connects a Model to Gemini models hosted by Google Vertex AI. - [LittleGhost::Providers::VertexAI::CredentialResolver](LittleGhost/Providers/VertexAI/CredentialResolver.md) — Resolves Vertex access tokens from explicit values, service-account ADC, or the Google metadata server. - [LittleGhost::Run](LittleGhost/Run.md) — Observe one top-level assembly execution from start to finish. - [LittleGhost::RunContext](LittleGhost/RunContext.md) — RunContext gives tools and workflows one place for shared state, cancellation, deadlines, checkpoints, and accumulated usage. - [LittleGhost::RunResult](LittleGhost/RunResult.md) — RunResult gives callers one final view of an Assembly invocation. - [LittleGhost::Runtime](LittleGhost/Runtime.md) — Owns the shared services that assemblies reuse across many Runs. - [LittleGhost::Runtime::Hook](LittleGhost/Runtime/Hook.md) — Hooks let applications prepare runs, select session history, transform interjections, and map errors to caller-safe messages. - [LittleGhost::Sandbox](LittleGhost/Sandbox.md) — A Sandbox governs filesystem operations and child processes that explicitly pass through it. - [LittleGhost::Sandbox::Capabilities](LittleGhost/Sandbox/Capabilities.md) — Describes the operations, network modes, and isolation mechanism a Sandbox backend implements. - [LittleGhost::Sandbox::EnvironmentPolicy](LittleGhost/Sandbox/EnvironmentPolicy.md) — Declares whether a child inherits the host environment and which explicit values are added or replaced. - [LittleGhost::Sandbox::Execution](LittleGhost/Sandbox/Execution.md) — Carries captured process output, exit status, and an optional execution error from Sandbox#execute or Sandbox#executeprogram. - [LittleGhost::Sandbox::Limits](LittleGhost/Sandbox/Limits.md) — Bounded file and process output sizes applied by Sandbox tools. - [LittleGhost::Sandbox::NetworkPolicy](LittleGhost/Sandbox/NetworkPolicy.md) — Declares outbound connectivity for sandbox-launched processes. - [LittleGhost::Sandbox::Policy](LittleGhost/Sandbox/Policy.md) — Normalizes requested filesystem, process, environment, and child-network controls into one immutable policy. - [LittleGhost::Sandbox::ProcessSession](LittleGhost/Sandbox/ProcessSession.md) — Owns one sandboxed child process and its bounded input and output streams. - [LittleGhost::Sandbox::Scope](LittleGhost/Sandbox/Scope.md) — A non-owning, capability-reduced view of a Sandbox for one agent or Tool set. - [LittleGhost::SandboxConfigurationError](LittleGhost/SandboxConfigurationError.md) — Base class for sandbox setup failures that trusted application code can diagnose before model-controlled work starts. - [LittleGhost::Sandboxes](LittleGhost/Sandboxes.md) — Built-in sandbox provider classes grouped for direct construction. - [LittleGhost::Sandboxes::Bubblewrap](LittleGhost/Sandboxes/Bubblewrap.md) — Runs each command in a fresh Bubblewrap namespace on Linux. - [LittleGhost::Sandboxes::Native](LittleGhost/Sandboxes/Native.md) — Selects the operating system's built-in LittleGhost isolation backend. - [LittleGhost::Sandboxes::Seatbelt](LittleGhost/Sandboxes/Seatbelt.md) — Runs child programs under macOS Seatbelt. - [LittleGhost::Sandboxes::Unrestricted](LittleGhost/Sandboxes/Unrestricted.md) — A convenient host-backed sandbox for trusted local work. - [LittleGhost::Session](LittleGhost/Session.md) — Sessions let an agent continue a conversation without tying it to one Ruby process. - [LittleGhost::SessionStore](LittleGhost/SessionStore.md) — SessionStore connects LittleGhost conversations to application persistence. - [LittleGhost::SessionStores](LittleGhost/SessionStores.md) — Ready-to-use persistence implementations for LittleGhost conversations. - [LittleGhost::SessionStores::AgentCoreMemory](LittleGhost/SessionStores/AgentCoreMemory.md) — AgentCoreMemory keeps LittleGhost conversations in Amazon Bedrock AgentCore Memory so they can resume across Ruby processes and deployments. - [LittleGhost::SessionStores::Filesystem](LittleGhost/SessionStores/Filesystem.md) — Filesystem preserves LittleGhost sessions across process restarts in an application-controlled directory. - [LittleGhost::SessionStores::Memory](LittleGhost/SessionStores/Memory.md) — Memory keeps conversations available for the life of one Ruby process. - [LittleGhost::Skills](LittleGhost/Skills.md) — Skills give agents focused instructions and supporting resources on demand. - [LittleGhost::Skills::Catalog](LittleGhost/Skills/Catalog.md) — A Catalog lets an agent discover focused instructions without putting every skill in its prompt. - [LittleGhost::Skills::Skill](LittleGhost/Skills/Skill.md) — Holds the metadata and instructions loaded from one SKILL.md file. - [LittleGhost::StreamEvent](LittleGhost/StreamEvent.md) — StreamEvent gives every provider and interface the same language for live agent output. - [LittleGhost::StructuredResult](LittleGhost/StructuredResult.md) — Associates a validated structured value with its declared schema name. - [LittleGhost::StructuredResultError](LittleGhost/StructuredResultError.md) — Raised when structured output is absent, invalid, or exceeds safety limits. - [LittleGhost::Subagents](LittleGhost/Subagents.md) — Subagents let one agent hand focused work to other agents and continue the conversation when those agents finish. - [LittleGhost::Subagents::AgentPath](LittleGhost/Subagents/AgentPath.md) — AgentPath gives every delegated conversation a stable place beneath its parent. - [LittleGhost::Subagents::Definition](LittleGhost/Subagents/Definition.md) — A Definition describes one kind of agent available for delegation. - [LittleGhost::Subagents::Manager](LittleGhost/Subagents/Manager.md) — Manager coordinates delegated conversations without making an application build its own worker pool or message protocol. - [LittleGhost::Subagents::Manager::CleanupError](LittleGhost/Subagents/Manager/CleanupError.md) — Raised when one or more managed workers cannot stop within the cleanup deadline. - [LittleGhost::Support](LittleGhost/Support.md) — Support collects small building blocks for LittleGhost extensions. - [LittleGhost::Support::Callbacks](LittleGhost/Support/Callbacks.md) — Callbacks lets extensions prepare, replace, or cancel framework work in a predictable order. - [LittleGhost::Support::CancellationToken](LittleGhost/Support/CancellationToken.md) — CancellationToken lets related work stop cooperatively without killing its calling thread or fiber. - [LittleGhost::Support::ClassAttributes](LittleGhost/Support/ClassAttributes.md) — ClassAttributes gives framework extension classes small, thread-safe, inheritable settings. - [LittleGhost::Support::ContentCapture](LittleGhost/Support/ContentCapture.md) — ContentCapture lets an application opt selected diagnostic content into telemetry after redaction and scrubbing. - [LittleGhost::Support::HTTPClient](LittleGhost/Support/HTTPClient.md) — HTTPClient gives integrations a shared, bounded streaming HTTP layer. - [LittleGhost::Support::InterruptibleStream](LittleGhost/Support/InterruptibleStream.md) — InterruptibleStream turns a blocking producer into a lazy, cancellable Ruby stream. - [LittleGhost::Support::InterruptibleStream::CleanupError](LittleGhost/Support/InterruptibleStream/CleanupError.md) — Raised when the producer thread remains active past the fixed shutdown bound. - [LittleGhost::Support::Loader](LittleGhost/Support/Loader.md) — Loader finds agents, assemblies, and tools from a conventional application layout. - [LittleGhost::Support::Loader::ConflictError](LittleGhost/Support/Loader/ConflictError.md) — Raised when a conventional path collides with an existing constant or autoload. - [LittleGhost::Support::Loader::ExpectedConstantError](LittleGhost/Support/Loader/ExpectedConstantError.md) — Raised when a loaded file does not define the constant implied by its path. - [LittleGhost::Support::OutputTruncation](LittleGhost/Support/OutputTruncation.md) — OutputTruncation keeps large tool results within a predictable context budget without breaking UTF-8. - [LittleGhost::Support::Redactor](LittleGhost/Support/Redactor.md) — Redactor removes common credential keys, known secret values, and secret-shaped strings from nested diagnostic data. - [LittleGhost::Swarm](LittleGhost/Swarm.md) — Lets configured Agent members hand one request directly to one another. - [LittleGhost::SwarmBuilder](LittleGhost/SwarmBuilder.md) — Builds a Swarm at runtime while keeping its members Agent-only. - [LittleGhost::Tool](LittleGhost/Tool.md) — Give an agent a validated way to call application code. - [LittleGhost::Tool::Binding](LittleGhost/Tool/Binding.md) — Supply run-scoped collaborators when tools are instantiated outside an agent. - [LittleGhost::Tool::Result](LittleGhost/Tool/Result.md) — Returns a Ruby value together with files or media produced by a Tool. - [LittleGhost::ToolError](LittleGhost/ToolError.md) — Base class for expected failures while executing a Tool. - [LittleGhost::ToolExecution](LittleGhost/ToolExecution.md) — Gives runtime hooks one complete view of a tool call while they prepare or observe its execution. - [LittleGhost::ToolLoopError](LittleGhost/ToolLoopError.md) — Raised when repeated identical tool calls reach the configured termination limit. - [LittleGhost::ToolRegistry](LittleGhost/ToolRegistry.md) — ToolRegistry turns an agent's tool declarations into the exact set a model can call during one run. - [LittleGhost::Tools](LittleGhost/Tools.md) — Ready-made model-facing tools for filesystem, process, and planning work. - [LittleGhost::Tools::Filesystem](LittleGhost/Tools/Filesystem.md) — Filesystem gives an agent read, list, write, and replace tools backed by the application's Sandbox. - [LittleGhost::Tools::Filesystem::Exclusive](LittleGhost/Tools/Filesystem/Exclusive.md) — Provides filesystem tools marked exclusive for shared workspace mutation. - [LittleGhost::Tools::Filesystem::ListFiles](LittleGhost/Tools/Filesystem/ListFiles.md) — Lists one directory through the configured sandbox. - [LittleGhost::Tools::Filesystem::ReadFile](LittleGhost/Tools/Filesystem/ReadFile.md) — Reads one UTF-8 text file through the configured sandbox. - [LittleGhost::Tools::Filesystem::ReplaceInFile](LittleGhost/Tools/Filesystem/ReplaceInFile.md) — Replaces one unique text occurrence through a writable sandbox. - [LittleGhost::Tools::Filesystem::WriteFile](LittleGhost/Tools/Filesystem/WriteFile.md) — Writes one UTF-8 text file through a writable sandbox. - [LittleGhost::Tools::Shell](LittleGhost/Tools/Shell.md) — Shell lets an agent run one executable through the configured Sandbox. - [LittleGhost::Tools::WriteTodos](LittleGhost/Tools/WriteTodos.md) — WriteTodos lets an agent share a live plan with the application and the person following its work. - [LittleGhost::Tracing](LittleGhost/Tracing.md) — Optional adapters for sending LittleGhost instrumentation to tracing tools. - [LittleGhost::Tracing::OpenTelemetry](LittleGhost/Tracing/OpenTelemetry.md) — OpenTelemetry turns LittleGhost lifecycle notifications into GenAI spans and events. - [LittleGhost::TrustedPath](LittleGhost/TrustedPath.md) — Marks a caller-supplied prompt directory as trusted application code. - [LittleGhost::UnsupportedInputError](LittleGhost/UnsupportedInputError.md) — Raised when an invocation contains an unsupported input form. - [LittleGhost::UnsupportedPlatformError](LittleGhost/UnsupportedPlatformError.md) — Raised when a sandbox backend does not support the current operating system. - [LittleGhost::Usage](LittleGhost/Usage.md) — Usage makes token accounting consistent across model providers. - [LittleGhost::Workflow](LittleGhost/Workflow.md) — Coordinates Assembly participants with ordinary Ruby control flow. - [LittleGhost::Workflow::Invocation](LittleGhost/Workflow/Invocation.md) — Hold one lazy Assembly call inside a workflow composition. - [LittleGhost::WorkflowBuilder](LittleGhost/WorkflowBuilder.md) — Builds a Workflow whose Ruby composition block is supplied at runtime. - [LittleGhost::Workspace](LittleGhost/Workspace.md) — A Workspace names the host paths associated with a Run. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost.md # Module LittleGhost Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost.html Build AI features as ordinary Ruby classes. An Agent owns one model conversation. Larger units called Assemblies coordinate several Agents while keeping the same `ask` and `stream_ask` entrypoints. Start with one model-driven behavior: 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 still pending?") run.completed? # => true run.response # One possible response: Transfer 481 is waiting for the receiving bank. The class holds reusable behavior. Each call creates a Run, which records the result and closes the resources opened for that request. Workflow, Swarm, and Graph are Assembly types for coordinating more than one participant. Configure LittleGhost before the first call. The first standalone call builds a shared Runtime from that configuration. `with_configuration` can select an independent configuration for one execution context. ## Constants ### `VERSION` Current LittleGhost gem version. ## Class methods ### `.configuration` ```ruby .configuration() ``` The configuration active in the current execution context, falling back to the process-wide default. ### `.configure` ```ruby .configure(&block) ``` Opens the active Configuration for application setup and returns it. Configuration files are loaded lazily when a runtime is first built, so make application-level changes before invoking an agent. Once the shared Runtime is ready, later mutations raise ConfigurationError. ### `.model_resolver` ```ruby .model_resolver() ``` Returns the model resolver owned by the active process configuration. ### `.offload_blocking` ```ruby LittleGhost.offload_blocking { ... } -> object ``` Runs a call that is known or measured to pause other fibers and can make progress on another Ruby thread. Inside a scheduled fiber, the block uses a shared thread pool. Otherwise, it runs inline. Returns the block's value. Once the pool accepts the block, LittleGhost waits for it to finish before re-raising an interruption. The block's own exception is also re-raised. The helper does not add a timeout or cancellation mechanism, so configure those limits on the underlying operation when it supports them. ### `.runtime` ```ruby .runtime() ``` Returns the shared Runtime for the active Configuration. Most applications do not need to call this method. Standalone Agent and Assembly entrypoints use it automatically. Runtime construction is lazy, thread-safe, and locks the active Configuration after it succeeds. ### `.with_configuration` ```ruby .with_configuration(configuration) ``` Makes `configuration` and its independent shared Runtime current only while the block runs. Execution state restores the previous configuration even when the block raises. Other execution contexts continue to see their own configuration. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent.md # Class LittleGhost::Agent Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/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 ### `agent_path` (R) This Agent's location in the bounded subagent tree. ### `delegation_activity` (R) Shared delegation tracker, when subagents are enabled. ### `max_tool_calls` (R) Maximum Tool calls allowed during one invocation. ### `model` (R) The resolved model used by this run-scoped Agent. ### `run` (R) The owning Run, or `nil` for a standalone entrypoint. ### `runtime` (R) Runtime used to build this agent's model, tools, workspace, and sandbox. ### `sandbox` (R) Run-scoped sandbox used for filesystem and process operations. ### `tool_registry` (R) Tools created and bound for this Agent's owning Run. ### `workspace` (R) Run-scoped workspace available to Tools and extensions. ## Class methods ### `.after_initialize` ```ruby after_initialize(callable = nil, prepend: false) { |agent| ... } -> self ``` Prepares per-agent state after a run-scoped instance is initialized. ### `.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:`. ### `.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:`. ### `.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:`. ### `.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:`. ### `.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. ### `.before_invocation` ```ruby before_invocation(callable = nil, prepend: false) { |payload| ... } -> self ``` Runs before one invocation begins. The payload is `{messages: Array}`. A replacement must contain `:messages`. Cancellation stops the invocation. A callback may also accept `context:` to receive the current RunContext. ### `.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:`. ### `.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:`. ### `.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. ### `.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. ### `.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. ### `.logical_path` ```ruby .logical_path() ``` The underscored, namespace-aware path used for conventional prompt lookup. ### `.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") ### `.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. ### `.prompt_local` ```ruby .prompt_local(name, *values, &resolver) ``` Adds a named value or resolver to every prompt rendered for the agent. ### `.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. ### `.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. ### `.system_template` ```ruby system_template() -> String, nil system_template(path) -> String ``` The explicit system prompt template path, when conventional lookup is not used. ### `.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 ### `#close` ```ruby #close() ``` Closes owned tools, interjections, sandbox, and workspace resources. The operation is idempotent and re-raises the first cleanup failure. ### `#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. ### `#prompt_locals` ```ruby #prompt_locals() ``` Materializes and freezes the prompt locals declared on the agent class. ### `#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. ### `#tools` ```ruby #tools() ``` The Tool registry available during this Agent run. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tool.md # Class LittleGhost::Tool Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tool.html Give an agent a validated way to call application code. Every tool declares a model-visible name, description, and input shape before implementing its operation. class TicketStatusTool < LittleGhost::Tool tool_name "ticket_status" description "Look up a support ticket's status." input_schema type: "object", properties: { ticket_id: {type: "string"} }, required: ["ticket_id"], additionalProperties: false def call(input) {ticket_id: input.fetch("ticket_id"), status: "waiting_on_customer"} end end class CustomerSupportAgent < LittleGhost::Agent tools TicketStatusTool end run = CustomerSupportAgent.ask("What is happening with ticket SUP-481?") run.response Use application context for authorization, never model-selected input: class OrderStatusTool < LittleGhost::Tool description "Look up an order for the current account." input_schema type: "object", properties: { order_number: {type: "string"} }, required: ["order_number"], additionalProperties: false def call(input) Orders.status_for( actor_id: run.invocation.actor_id, account_id: run.invocation.context.fetch("account_id"), order_number: input.fetch("order_number") ) end end class OrderSupportAgent < LittleGhost::Agent tools OrderStatusTool end OrderSupportAgent.ask( "Where is order 481?", actor_id: authenticated_user.id, context: {account_id: authenticated_user.account_id} ) Each value comes from a different part of the run: `input` : Arguments selected by the model. The schema checks their shape, not their permission to perform an operation. `run.invocation.context` : Current request values supplied by the application. Use these for authorization after the application authenticates the caller. `context.state` : Mutable working state for the run. It may include values restored from a Session, so check saved values again before trusting them. Tool::Binding : Run-scoped objects such as the Agent, Run, Runtime, workspace, and sandbox. The Binding supplies #run; it does not contain model arguments. The class DSL produces the specification sent to models. During an Agent run, the tool registry creates and binds one Tool instance. Tests and custom integrations may call `execute` directly; it validates the arguments, calls `call`, and returns a normalized internal result. Tool.define offers the same contract for an embedded implementation. Mutable Tool instance state belongs to one Agent run. Registries close tool instances that implement `close`; `exclusive true` prevents that tool from overlapping other exclusive tools in the same run. Validation and application ToolError failures become error results. A ToolError message is visible to the model and must be safe to disclose; unexpected exception messages are replaced with their class name. Cancellation, deadlines, and cleanup errors propagate instead of becoming ordinary tool output. The configured sandbox, not Tool itself, enforces filesystem and process isolation. See the [Tools guide](../tools.md) for the complete path from model-selected input to application context, sandbox delegation, concurrency, and code mode. ## Inheritance `LittleGhost::Tool < Object` ## Attributes ### `context` (RW) RunContext supplied to the current #execute call, or nil outside execution. ## Class methods ### `.available?` ```ruby .available?(binding) ``` Returns whether this Tool should be registered for `binding`. ### `.available_if` ```ruby .available_if(&predicate) ``` Declares whether this Tool is available for a run-scoped `binding`. With no block, returns the configured predicate or nil. ToolRegistry omits a Tool whose predicate returns false before constructing it. ### `.define` ```ruby .define(name:, description:, input_schema: {}, &implementation) ``` Creates an anonymous Tool subclass backed by `implementation`. The block receives `input` and may also accept the `context:` keyword. tool = LittleGhost::Tool.define( name: "echo", description: "Echo text.", input_schema: {type: "object"} ) { |input| input.fetch("text") } ### `.description` ```ruby description() -> String description(value) -> value ``` The model-visible description used to decide when the tool applies. ### `.exclusive` ```ruby exclusive() -> true or false exclusive(value) -> value ``` Whether calls acquire the run-wide exclusive tool lock. ### `.input_schema` ```ruby input_schema() -> Hash input_schema(schema) -> schema ``` The frozen JSON Schema subset used to validate model input. Setting a non-Hash schema raises ArgumentError. Keys are normalized to strings and the entire value is deeply frozen. ### `.new` ```ruby .new(binding: Binding.new) ``` Creates a tool with the run-scoped collaborators in `binding`. ### `.specification` ```ruby .specification() ``` The frozen model-facing name, description, and input schema. ### `.tool_name` ```ruby tool_name() -> String tool_name(value) -> value ``` The model-visible tool name. Named classes derive a snake-cased default; passing `value` replaces it. ## Instance methods ### `#agent` ```ruby #agent() ``` Bound agent, when the tool belongs to an agent run. ### `#call` ```ruby #call(_input) ``` Implements the model-requested operation. Subclasses must override this method. The current RunContext is available through `context` while the call executes. ### `#close` ```ruby #close() ``` Releases resources owned by this tool. Subclasses may override it. ### `#description` ```ruby #description() ``` Model-visible description declared by the tool class. ### `#exclusive?` ```ruby #exclusive?() ``` Indicates whether calls use the run-wide exclusive-tool lock. ### `#execute` ```ruby #execute(input, context: RunContext.new) ``` Validates `input` and invokes the Tool, returning its normalized outcome. Cancellation, deadline, and cleanup exceptions remain control-flow exceptions. ToolError and unexpected failures become sanitized error results; unexpected exception messages are not exposed to the model. ### `#input_schema` ```ruby #input_schema() ``` Normalized JSON input schema declared by the tool class. ### `#model` ```ruby #model() ``` Bound model, when available. ### `#run` ```ruby #run() ``` Bound run, when available. ### `#runtime` ```ruby #runtime() ``` Bound runtime, when available. ### `#sandbox` ```ruby #sandbox() ``` Bound sandbox, when available. ### `#specification` ```ruby #specification() ``` Frozen provider-facing tool specification. ### `#tool_name` ```ruby #tool_name() ``` Model-visible name declared by the tool class. ### `#workspace` ```ruby #workspace() ``` Bound workspace, when available. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Run.md # Class LittleGhost::Run Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Run.html Observe one top-level assembly execution from start to finish. A run records its response, outcome, usage, error, and owned resources. run = CustomerSupportAgent.ask("Why is transfer 481 pending?") run.completed? # => true run.outcome # => "completed" run.response # => "Transfer 481 is waiting for the receiving bank." `ask` returns the Run after work finishes. `stream_ask` yields StreamEvent objects as work happens, then returns the same finished Run. A Run executes only once. stream = CustomerSupportAgent.stream_ask("Where is transfer 481?") run = stream.each do |event| publish(event) if event.type == :text_delta end run.completed? # => true run.response ## Outcomes Completion, failure, deadline, and cancellation become the `completed`, `failed`, `partial`, and `cancelled` outcomes. Ordinary execution failures are available through `error` and the terminal stream event. Failures while closing resources, delivering events, or reporting instrumentation may still raise because LittleGhost cannot report a reliable ending. Tool validation and ToolError failures return safe Tool results to the model, which may recover and complete the Run. Input, configuration, or resource construction can raise before a Run exists. Once execution begins, terminal events are `run_stop`, `run_error`, `run_partial`, and `run_cancel`. ## Owned resources The Run opens its workspace, sandbox, Session, and Assembly entrypoint, then closes registered resources in reverse order. `register` adds application resources to that cleanup sequence. Interjection is available only while one Agent entrypoint is active. ## Nested Agent events A composite Assembly stream observes every Agent that shares the Run. Each `:agent_stream` event carries an AgentStreamSource in `data[:source]` and a copied, frozen Agent StreamEvent in `data[:event]`. An inner `:invocation_start` also includes the copied, frozen Message sent to that Agent in `data[:input]`. Event consumers cannot change the running work. Parallel Agents may interleave, but the Run invokes the stream consumer serially. Contextual events expose data from every participating Agent, so applications should enable `include_agent_events` only for destinations that may see every participant's data. ## Inheritance `LittleGhost::Run < Object` ## Includes - `Enumerable` ## Attributes ### `agent_class` (R) Agent class used for compatibility when the entrypoint is an Agent. ### `cancellation_token` (R) Token that cooperatively stops this Run and its children. ### `entrypoint_class` (R) Public Agent, Workflow, Swarm, or Graph class selected by the caller. ### `error` (R) Exception that caused a failed, partial, or cancelled outcome. ### `invocation` (R) Normalized request carried by this Run. ### `operation_id` (R) Unique identifier for this top-level operation. ### `outcome` (R) Terminal String: `completed`, `failed`, `partial`, or `cancelled`. ### `response` (R) Caller-facing final text, or the partial text preserved at a deadline. ### `result` (R) Final RunResult, when the Assembly produced one. ### `runtime` (R) Runtime that built and executes this Run. ### `sandbox` (R) Request-scoped sandbox owned or supplied by the Run. ### `session` (R) Session opened for this invocation, when persistence is configured. ### `usage` (R) Normalized Usage accumulated by the Run. ### `workspace` (R) Request-scoped workspace owned or supplied by the Run. ## Class methods ### `.new` ```ruby .new(invocation:, runtime:, agent_class: nil, assembly_class: nil, entrypoint_class: nil, execution_class: nil, cancellation_token: Support::CancellationToken.new, workspace: nil, sandbox: nil, include_agent_events_by_default: false) ``` Creates a dormant run for `invocation`. ## Instance methods ### `#call` ```ruby #call() ``` Consumes the event stream and returns `self`. ### `#cancelled?` ```ruby #cancelled?() ``` True when cancellation stopped the run without a response. ### `#close` ```ruby #close() ``` Closes registered resources in reverse order. The operation is idempotent. It attempts every closer and then raises the first LittleGhost::CleanupError, or otherwise the first cleanup exception. ### `#completed?` ```ruby #completed?() ``` True after successful completion. ### `#context` ```ruby #context(state: {}, metadata: {}) ``` Creates a RunContext with this run's cancellation token and deadline. ### `#each` ```ruby #each() ``` Yields events and returns `self` after the terminal event. Without a block, returns an Enumerator. A second execution raises Error. ### `#failed?` ```ruby #failed?() ``` True after execution or cleanup failed. ### `#include_agent_events?` ```ruby #include_agent_events?() ``` Indicates whether the stream includes contextual events from every Agent that executes as part of this Run. ### `#interject` ```ruby #interject(message, interjection_id: nil, batch_key: nil, metadata: {}, cancellation_token: Support::CancellationToken.new, deadline: nil) ``` Adds an interjection to the active entrypoint and waits for its response. Raises LittleGhost::AgentInterjectionError before the entrypoint is ready or after it finishes. ### `#once` ```ruby #once(key) ``` Performs the block at most once successfully for `key` during this run. Concurrent callers are serialized. The caller that performs the block receives its value; later callers receive `nil`. If the block raises, the key is not recorded and a later call may retry it. ### `#partial?` ```ruby #partial?() ``` True when the deadline preserved a partial response. ### `#register` ```ruby #register(resource = nil, &closer) ``` Adds a resource or closer to reverse-order cleanup and returns the resource. A resource must respond to `close` unless a block supplies the cleanup operation. Registering after the run has closed raises Error. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Assembly.md # Class LittleGhost::Assembly Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Assembly.html Gives one agent or a coordinated group the same callable entrypoint. An assembly is anything callers can invoke like one Agent. An Agent is the smallest assembly because it owns one model loop. Workflow, Swarm, and Graph subclasses coordinate several participants while preserving the same `ask`, `stream_ask`, `call`, and `stream` interface. agent_run = CustomerSupportAgent.ask("Why is my transfer pending?") graph_run = SupportFlowGraph.ask("Why is my transfer pending?") agent_run.response graph_run.response Applications normally subclass Agent, Workflow, Swarm, or Graph rather than Assembly directly. Each standalone call returns a top-level Run. Participants called inside another Assembly return a RunResult to their parent. ## Advanced construction Named subclasses are the usual form. `to_builder` creates a mutable definition for applications that discover participants at runtime. `definition` returns the fixed snapshot used by one execution. Composite results record their steps in RunResult#trajectory. ## Return values `CustomerSupportAgent.ask(...)` : A named class creates and returns a top-level Run. `CustomerSupportAgent.new(runtime: runtime).ask(...)` : A standalone instance also creates and returns a top-level Run. `runtime.build_assembly(..., run: run).call(...)` : A participant already bound to a Run returns its child RunResult. `stream_ask(...).each { |event| ... }` : A standalone stream returns its top-level Run after enumeration. A run-scoped stream ends with an `invocation_stop` event carrying RunResult. ## Inheritance `LittleGhost::Assembly < Object` ## Attributes ### `run` (R) The owning Run, or `nil` for a standalone entrypoint. ### `runtime` (R) Runtime used to resolve participants and build Runs. ### `sandbox` (R) Sandbox supplied to this Assembly, when present. ### `workspace` (R) Workspace supplied to this Assembly, when present. ## Class methods ### `.ask` ```ruby .ask(message, **options) ``` Executes `message` through a fresh standalone assembly and returns its Run. `options` become Invocation fields. Common values include `history`, `context`, `settings`, `metadata`, `session_id`, `actor_id`, and `deadline_at`. ### `.assembly_id` ```ruby assembly_id() -> String assembly_id(value) -> String ``` The stable identifier used for tools and telemetry. Named subclasses derive it from their underscored class name without their type suffix. ### `.assembly_kind` ```ruby .assembly_kind() ``` Returns `:agent`, `:workflow`, `:swarm`, `:graph`, or `:assembly`. ### `.definition` ```ruby .definition() ``` Returns an immutable definition for this class. ### `.description` ```ruby description() -> String description(value) -> String ``` The human-readable description used when exposing the assembly as a tool. ### `.stream_ask` ```ruby .stream_ask(message, **options) ``` Lazily streams `message` through a fresh standalone assembly. Enumeration yields StreamEvent objects and returns the terminal Run. The same Invocation fields accepted by .ask may be supplied as `options`. Composite assemblies also emit an `:agent_stream` event for every normalized event from every Agent in the run, including intermediate and nested participants. Set `include_agent_events: false` to keep only the ordinary public stream. A standalone Agent retains its ordinary stream by default and accepts `true` to opt in. ### `.to_builder` ```ruby .to_builder() ``` Returns a mutable dynamic builder seeded by this class. ## Instance methods ### `#as_tool` ```ruby #as_tool(name: self.class.assembly_id, description: self.class.description, preserve_context: false) ``` Exposes this assembly as a Tool instance. By default, calls do not remember earlier conversation history. Set `preserve_context: true` to carry that history from one tool call to the next. This option does not control working state: every call receives the invoking Tool's current RunContext#state, which may include current request values or values restored from a Session. Nested tools must still authorize privileged work with current, application-established values. ### `#ask` ```ruby #ask(message, **options) ``` Runs `message` to completion. A standalone instance returns its owning Run. A run-scoped instance returns the child RunResult. ### `#call` ```ruby #call(input = nil, **options) ``` Runs `input` to completion. A standalone assembly returns a Run. A run-scoped assembly returns its RunResult. ### `#close` ```ruby #close() ``` Closes resources owned directly by this assembly. ### `#interject` ```ruby #interject(message, **options) ``` Adds an interjection to the single active leaf Agent. ### `#prompt_locals` ```ruby #prompt_locals() ``` Additional prompt locals made available to child agents. ### `#start_execution` ```ruby #start_execution(payload, &event_consumer) ``` Starts `payload` in the background and returns an Execution. Composite assemblies include contextual `:agent_stream` events in the consumer by default. Set `include_agent_events` to `false` in `payload` to keep only the ordinary public stream. ### `#stream_ask` ```ruby #stream_ask(message, **options) ``` Lazily streams `message` through the standalone or run-scoped assembly. A standalone stream returns its terminal Run after enumeration. A run-scoped stream finishes with an `invocation_stop` event containing its RunResult. A standalone composite Assembly receives contextual `:agent_stream` events from every Agent in the Run by default and may set `include_agent_events: false` to omit them. A standalone Agent may set the option to `true` to include its contextual wrapper. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Workflow.md # Class LittleGhost::Workflow Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Workflow.html Coordinates Assembly participants with ordinary Ruby control flow. A workflow is an Assembly whose `perform` method controls ordering, branching, parallel work, and local variables. Each participant may be an Agent or another coordinated Assembly. The workflow consumes intermediate answers and streams one final participant response. A support workflow can guarantee that research happens before the responder writes the caller-visible answer: class ResponseWorkflow < LittleGhost::Workflow private def perform evidence = invoke(ResearchAgent).output invoke CustomerSupportAgent, input: <<~PROMPT #{input.text} Research: #{evidence} PROMPT end end run = ResponseWorkflow.ask("Why is transfer 481 pending?") run.response # One possible response: Transfer 481 is waiting for the receiving bank. Call a named Workflow with [ask](Assembly.md#method-c-ask) for its final Run, or the streaming [entrypoint](Assembly.md#method-c-stream_ask) for live events. `invoke` returns a lazy Workflow::Invocation. Reading `output` consumes an intermediate invocation and returns RunResult#output; `perform` must return its final invocation without consuming it so those events reach the caller. Intermediate usage is added to the final result. A child receives the Workflow input unless `invoke` supplies another one. It also inherits history, settings, cancellation, deadline, template paths, and the parent tracing relationship. JSON-like context is copied for each child, preventing one intermediate Agent from mutating a sibling's state. Non-JSON-like workflow context raises ArgumentError. A Workflow instance streams once. Returning the wrong value, returning an already consumed invocation, or consuming one twice raises ProtocolError. A composition error fails the owning top-level Run. Each child Assembly closes after its attempt, and a cleanup failure raises from that attempt. ## Inheritance `LittleGhost::Workflow < LittleGhost::Assembly` ## Attributes ### `run` (R) Run that owns this run-scoped Workflow. ### `runtime` (R) Runtime used to resolve child Assemblies. ## Instance methods ### `#close` ```ruby #close() ``` Closes all declared invocations in reverse order. The operation is idempotent, attempts every close, and raises the first cleanup failure. ### `#prompt_locals` ```ruby #prompt_locals() ``` Additional prompt locals shared by agents invoked from the workflow. Subclasses may override this hook. ### `#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) ``` Streams the workflow once as StreamEvent objects. `perform` must return a final, unconsumed Workflow::Invocation. The returned Enumerator is lazy, but calling `stream` reserves the single-use workflow instance even when enumeration has not started yet. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Swarm.md # Class LittleGhost::Swarm Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Swarm.html Lets configured Agent members hand one request directly to one another. A swarm is an Assembly for model-selected routing. One member is active at a time. It either produces the final answer or uses a model-visible handoff tool to choose one of the next members allowed by the application. class ProblemSolverSwarm < LittleGhost::Swarm member TriageAgent member BillingAgent member AccountAgent start TriageAgent handoff TriageAgent, to: [BillingAgent, AccountAgent] max_steps 12 end run = ProblemSolverSwarm.ask("Why was I charged twice?") run.response Call a named Swarm with [ask](Assembly.md#method-c-ask) for its final Run, or the streaming [entrypoint](Assembly.md#method-c-stream_ask) for coordination and final-response events. Swarm members are Agent definitions rather than arbitrary assemblies so a handoff remains a direct model-to-model transition. Original conversation history and application context stay isolated unless a member opts in with `history: true` or `context: true`. Streams expose coordination events and the final member response, but not intermediate model text. ## Inheritance `LittleGhost::Swarm < LittleGhost::Assembly` ## Class methods ### `.handoff` ```ruby .handoff(from, to:) ``` Restricts one member to the declared handoff targets. ### `.max_handoff_repeats` ```ruby .max_handoff_repeats(value = nil) ``` Reads or assigns how often the same directed handoff may repeat. For example, a value of `2` allows the transition from triage to billing twice during one Swarm run. `max_steps` still limits total member calls. ### `.max_steps` ```ruby .max_steps(value = nil) ``` Reads or assigns the maximum member executions. ### `.member` ```ruby .member(agent, as: nil, timeout: nil, retries: 0, retry_on: nil, retry_delay: 0, history: false, context: false) ``` Declares one Agent member and its optional execution policy. ### `.start` ```ruby .start(member = nil) ``` Reads or assigns the initial Agent member. ### `.validate!` ```ruby .validate!() ``` Validates the members and allowed handoff routes, then returns this class. ## Instance methods ### `#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, **_options) ``` Streams lifecycle events and only the final member's answer events. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Graph.md # Class LittleGhost::Graph Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Graph.html Routes a request through named Assembly nodes and declared edges. A Graph is an Assembly for flows whose allowed paths should be visible in application code. A node may contain an Agent, Workflow, Swarm, or another Graph. Edges declare which node may run next. class SupportFlowGraph < LittleGhost::Graph node :triage, TriageAgent node :ledger, LedgerResearchAgent node :policy, PolicyResearchAgent node :respond, CustomerSupportAgent start :triage edge :triage, :ledger edge :triage, :policy edge :ledger, :respond edge :policy, :respond finish :respond end SupportFlowGraph.validate! run = SupportFlowGraph.ask("Why is my transfer pending?") Call a named Graph with [ask](Assembly.md#method-c-ask) for its final Run, or the streaming [entrypoint](Assembly.md#method-c-stream_ask) for routing and final-response events. Multiple unconditional edges from one source run in parallel and converge at their first unambiguous common successor. Array endpoints declare an explicit fan-out or wait-for-all fan-in. Parallel groups cannot nest. Conditions and input mappers receive a read-only Graph::State. Nodes do not receive caller history or application context unless their declaration opts in with `history: true` or `context: true`. Validate the topology before execution. Conditions and mappers are application callbacks and can inspect copied input, history, context, and completed results. `to_mermaid` renders the same definition as a flowchart. ## Inheritance `LittleGhost::Graph < LittleGhost::Assembly` ## Class methods ### `.edge` ```ruby .edge(from, to, input: nil, max_concurrency: nil, **options, &condition) ``` Declares one route or one bounded parallel edge group. `input` receives Graph::State and returns the value passed to the target node or nodes. A scalar source and Array target fan out; an Array source and scalar target wait for every listed predecessor. At most one conditional scalar or grouped route may match from the current node; one unconditional route may act as the fallback. Multiple unconditional scalar edges with the same source infer one fan-out when no conditional route is present. Supply a condition with `if:` or a block. `max_concurrency` overrides Graph.max_concurrency for a scalar-to-Array fan-out. The original request and complete source output cross to every branch unless an input mapper replaces them. Array-to-Array edges, conditional fan-in edges, and `max_concurrency` on other edge shapes raise ArgumentError. ### `.error_edge` ```ruby .error_edge(from, to, on:, input: nil) ``` Routes selected node errors after retries are exhausted. `on` lists the exception classes this route accepts. An `input` mapper may turn Graph::State, including `state.error`, into recovery input. ### `.finish` ```ruby .finish(name = nil) ``` Reads or assigns the terminal node. ### `.max_concurrency` ```ruby .max_concurrency(value = nil) ``` Reads or assigns the concurrency bound for parallel groups. The default is 8. A scalar-to-Array edge may override it for one group. ### `.max_steps` ```ruby .max_steps(value = nil) ``` Reads or assigns the maximum node executions. ### `.node` ```ruby .node(name, assembly, timeout: nil, retries: 0, retry_on: nil, retry_delay: 0, history: false, context: false, input: nil) ``` Declares an Assembly node and its optional execution policy. An `input` mapper receives Graph::State and replaces the default input whenever the selected edge or edge group does not declare its own mapper. `history` and `context` opt this node into the corresponding caller data; both default to `false`. ### `.start` ```ruby .start(name = nil) ``` Reads or assigns the entry node. ### `.to_mermaid` ```ruby .to_mermaid() ``` Renders the validated topology as Mermaid flowchart text. ### `.validate!` ```ruby .validate!() ``` Validates the topology and returns this Graph class. Raises ConfigurationError for undeclared or unreachable nodes, ambiguous convergence, competing routes at an inferred branch boundary, and overlapping or nested parallel groups. ## Instance methods ### `#close` ```ruby #close() ``` ### `#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, **_options) ``` Streams lifecycle events and the finish node's ordinary response events. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Configuration.md # Class LittleGhost::Configuration Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Configuration.html Configure shared services and lookup rules before agents start. A configuration collects model profiles, persistence, paths, instrumentation, and runtime hooks for an application. LittleGhost.configure do |config| config.default_model :customer_support config.service_name "support-api" end LittleGhost.configuration.default_model # => "customer_support" LittleGhost.configuration.service_name # => "support-api" Prompt and skill lookup paths default to `app/prompts` and `app/skills` under the application root. Applications may append shared roots or replace the arrays entirely. Configuration is a mutable application builder until its shared Runtime is first used. A successful #runtime call locks the builder so standalone Agents and Assemblies keep one stable setup. Configure the application before its first entrypoint call. Explicit Runtime construction remains an advanced way to take an independent snapshot without selecting the shared default. Multi-tenant applications should derive Session actor identity from state established after authentication, not from an unverified request field. ## Inheritance `LittleGhost::Configuration < Object` ## Class methods ### `.new` ```ruby .new(values = {}) ``` Starts a mutable builder with optional `values`. Prompt paths default to `app/prompts` and skill paths to `app/skills`. Collection settings are copied so callers can safely reuse their input arrays after construction. ## Instance methods ### `#[]` ```ruby #[](name) ``` Looks up an arbitrary setting by symbol or string-compatible name. ### `#[]=` ```ruby #[]=(name, value) ``` Adds or replaces an arbitrary setting. ### `#artifacts` ```ruby artifacts() -> Class artifacts { |artifact, run:| bytes_or_artifact_or_nil } -> Class ``` Stores input attachments, Tool artifacts, and oversized successful Tool values under the conventional `:artifacts` Workspace path. An optional block receives deferred Artifacts and may load their bytes for the current Run. It may return a String, an inline Artifact, or nil. The block is application code. It must authorize each reference using identity established by the application and limit any file or network read before returning bytes. LittleGhost applies its storage limits afterward. ### `#blocking_pool_capacity` ```ruby blocking_pool_capacity() -> integer blocking_pool_capacity(value) -> integer ``` Returns or sets the maximum number of process-wide workers available to LittleGhost.offload_blocking, certificate generation, and Filesystem SessionStore transactions when they run from scheduled fibers. Workers are created lazily. The default is 2. Every Configuration reads and writes the same process-wide value. Configure this during process startup, before any operation can start the pool. `value` must be a positive Integer. Raises ArgumentError for an invalid value and ConfigurationError when changing the value after the pool has started. ### `#blocking_pool_capacity=` ```ruby #blocking_pool_capacity=(value) ``` Sets the same process-wide worker limit as `blocking_pool_capacity`. ### `#catalog_source` ```ruby #catalog_source(source) ``` Adds an explicit catalog source. Sources refresh only when callers invoke ModelResolver#refresh!. ### `#code_mode` ```ruby #code_mode() ``` Default code-mode declaration for enabled Agents. The Hash may select an `:engine` and `:sandbox`, override `:limits`, and name Tools to keep in the conversation with `:except`. ### `#code_mode=` ```ruby #code_mode=(value) ``` Configures application defaults for code-mode Agents. The Hash may select an `:engine` and `:sandbox`, override `:limits`, and name ordinary Tools that remain in the conversation with `:except`. ### `#concurrency_backend` ```ruby concurrency_backend() -> :auto, :thread, :fiber concurrency_backend(value) -> :auto, :thread, :fiber ``` Selects how subsequently built runtimes start independent work such as parallel Tool calls and Workflow branches. The default, `:auto`, uses fibers when the caller is already running in a scheduled fiber and uses threads otherwise. `:thread` always uses threads. `:fiber` raises ConfigurationError when the caller is not in a scheduled fiber. The application's scheduler must support Fiber.schedule. Any other value raises ArgumentError. LittleGhost.configure do |config| config.concurrency_backend = :thread end ### `#concurrency_backend=` ```ruby #concurrency_backend=(value) ``` Replaces the concurrency backend for subsequently built runtimes. ### `#configure` ```ruby #configure() ``` Yields this builder for setup and returns the same instance. ### `#default_model` ```ruby #default_model(value = :__read__) ``` Fallback logical role for the default resolver. ### `#default_model=` ```ruby #default_model=(value) ``` Replaces the fallback logical role and normalizes it to a String. ### `#instrument` ```ruby #instrument(subscriber) ``` Adds an Instrumentation::Subscriber to each new runtime and returns it. ### `#invocation` ```ruby invocation() -> value invocation(value) -> value ``` The request envelope class used to parse application payloads. ### `#invocation=` ```ruby invocation=(value) -> value ``` Replaces the request envelope class for subsequently built runtimes. ### `#log_events_to` ```ruby log_events_to() -> :stdout, :stderr, nil log_events_to(destination) -> destination ``` Sends structured framework events to `:stdout` or `:stderr`. This setting controls the process-wide Events console destination; the most recent setting replaces it without changing other event listeners. By default, events have no console destination. Passing `nil` disables console output. The console listener redacts sensitive values and writes one JSON object per line. ### `#log_events_to=` ```ruby #log_events_to=(destination) ``` Replaces the console destination for structured framework events. ### `#model_resolver` ```ruby #model_resolver(value = :__read__) ``` Installs a complete resolver override for subsequently built runtimes. ### `#model_resolver=` ```ruby model_resolver=(value) -> value ``` Replaces the model resolver declaration for subsequently built runtimes. ### `#models` ```ruby #models(value = :__read__) ``` Logical model profiles for the default resolver. Role names cannot contain a colon because that syntax identifies a canonical model target. ### `#models=` ```ruby #models=(value) ``` Replaces logical model profiles for subsequently built runtimes. ### `#models_path` ```ruby #models_path(value = :__read__) ``` Model YAML path. The conventional path is optional; an explicitly set path must exist when a runtime is built. ### `#models_path=` ```ruby #models_path=(value) ``` Replaces the model YAML path for subsequently built runtimes. ### `#prompt_paths` ```ruby #prompt_paths() ``` Prompt lookup paths in precedence order. The Array is mutable until the shared Runtime is built. ### `#prompt_paths=` ```ruby #prompt_paths=(value) ``` Replaces prompt lookup paths with `value` converted to an Array. ### `#provider_adapter` ```ruby #provider_adapter(name, callable = nil, &factory) ``` Registers a provider adapter factory under `name`. ### `#provider_credentials` ```ruby #provider_credentials(callable = nil, &resolver) ``` Installs a trusted callable that returns credential options for a named provider connection when each executable model is constructed. ### `#providers` ```ruby #providers(value = :__read__) ``` Trusted provider connections for the default or custom resolver. ### `#providers=` ```ruby #providers=(value) ``` Replaces trusted provider connections for subsequently built runtimes. ### `#providers_path` ```ruby #providers_path(value = :__read__) ``` Provider YAML path. The conventional path is optional; an explicitly set path must exist when a runtime is built. ### `#providers_path=` ```ruby #providers_path=(value) ``` Replaces the provider YAML path for subsequently built runtimes. ### `#root` ```ruby root() -> Pathname root(path) -> Pathname ``` The resolved application root, defaulting to `Dir.pwd`. Setting or reading an invalid root raises ConfigurationError. Symlinks are resolved so runtimes and lookup paths use the same canonical directory. ### `#root=` ```ruby #root=(value) ``` Replaces the application root after resolving it to a stable real path. ### `#runtime` ```ruby #runtime() ``` Returns the shared Runtime for this configuration, building it on first use. Once construction succeeds, the configuration is locked so every standalone entrypoint continues to use one stable application setup. The conventional configuration file may finish loading during construction; other writes are rejected. A failed build leaves the configuration editable for a later attempt. ### `#runtime_hook` ```ruby #runtime_hook(hook_class) ``` Adds a Runtime::Hook subclass to each new runtime and returns it. ### `#sandbox` ```ruby #sandbox() ``` Sandbox declaration used for subsequently built runtimes. ### `#sandbox=` ```ruby #sandbox=(value) ``` Selects the Sandbox provider instantiated around each run's workspace. LittleGhost does not fall back to unrestricted execution when an explicit backend is unavailable. ### `#service_name` ```ruby service_name() -> value service_name(value) -> value ``` The low-cardinality service name attached to instrumentation. ### `#service_name=` ```ruby service_name=(value) -> value ``` Replaces the service name attached to telemetry from new runtimes. ### `#session_actor` ```ruby session_actor() -> callable, nil session_actor(callable) -> callable session_actor { |invocation| ... } -> callable ``` The callable that derives the persistence actor for each invocation. Pass either a callable or a block. The configured resolver should use trusted authenticated identity in multi-tenant applications. ### `#session_store` ```ruby #session_store() ``` Session-store declaration used for subsequently built runtimes. ### `#session_store=` ```ruby #session_store=(value) ``` Selects session persistence with a `:provider` and its constructor options. The provider must be a SessionStore subclass. Runtime construction creates and owns the store instance. ### `#skill_paths` ```ruby #skill_paths() ``` Skill lookup paths in precedence order. The Array is mutable until the shared Runtime is built. ### `#skill_paths=` ```ruby #skill_paths=(value) ``` Replaces skill lookup paths with `value` converted to an Array. ### `#skill_resource_root` ```ruby #skill_resource_root() ``` Optional model-facing root used for skill locations and resources. The value may be an absolute process-visible path. A `workspace://name` reference must map to the configured skill path through a read-only file grant in each Run's Workspace and Sandbox. The application must not expose the same files through another writable bind mount. ### `#skill_resource_root=` ```ruby #skill_resource_root=(value) ``` Replaces and validates the skill resource root for new runtimes. ### `#workspace` ```ruby #workspace() ``` Workspace declaration used for subsequently built runtimes. ### `#workspace=` ```ruby #workspace=(value) ``` Selects the Workspace provider instantiated for each run. A declaration may be a registered provider symbol, callable, or a Hash containing a `:provider` and constructor options. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Runtime.md # Class LittleGhost::Runtime Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Runtime.html Owns the shared services that assemblies reuse across many Runs. Most applications do not construct this class. Configure LittleGhost once and call a named Agent or Assembly; the first standalone call lazily builds `LittleGhost.runtime`, and later calls reuse it automatically. Each call still receives a fresh Run, bound participants, Tools, workspace, and sandbox. Construct Runtime directly when one process intentionally hosts an isolated LittleGhost setup: configuration = LittleGhost::Configuration.new( root: Dir.pwd, providers: { openrouter: {adapter: :openrouter, api_key: ENV.fetch("OPENROUTER_API_KEY")} }, models: {customer_support: {target: "openrouter:openai/gpt-5.6-luna"}}, default_model: :customer_support, service_name: "support-api" ) runtime = LittleGhost::Runtime.new(configuration: configuration) CustomerSupportAgent.new(runtime: runtime) .ask("Where is order 481?") .response Explicit construction snapshots the supplied Configuration but does not replace LittleGhost's shared default Runtime. A Runtime may build independent Runs concurrently. Each Run gets fresh participants and Tools. By default, it also gets a Runtime-created Workspace and Sandbox that the Run owns. Instances supplied by the application remain caller-owned. ## Advanced construction and ownership Normal construction reads the application's configured definitions and builds shared model resolution, persistence, hooks, and resource factories. The `settings` form and #build are lower-level extension points for deriving another Runtime from an existing configuration snapshot. #build_run creates a workspace and sandbox when needed. Once the Run owns them, it closes them; if construction stops halfway through, Runtime closes the partial resources. Startup failures are reported to instrumentation and then raised. Session actor resolution must use authenticated application identity. The default Sandboxes::Unrestricted uses host permissions and is not a security boundary for untrusted work. Shared stores, resolvers, hooks, subscribers, providers, and resource factories may receive concurrent calls. Calls can overlap on different threads, or fibers can take turns entering the same object on one thread. Extensions must protect shared mutable state without relying on thread identity. One SessionStore instance serializes calls for the same Session. A store must provide its own coordination across processes. See [Running in Production](../production.md) for choosing a concurrency backend and protecting shared extensions. Runtime has no shutdown operation. Runs close resources created for their request. The application shuts down shared services and process-wide Instrumentation subscribers with the rest of the process. ## Inheritance `LittleGhost::Runtime < Object` ## Attributes ### `code_mode_configuration` (R) Default code-mode declaration for enabled agents. ### `configuration` (R) Configuration object used to construct this Runtime. ### `loader` (R) Loader used for conventional application definitions. ### `model_resolver` (R) Resolver that turns model roles and targets into executable Models. ### `prompt_paths` (R) Ordered directories searched for prompt templates. ### `root` (R) Canonical application root. ### `runtime_hooks` (R) Runtime hooks called around request and session preparation. ### `sandbox_declaration` (R) Configured Sandbox provider symbol, callable, or declaration. ### `session_store` (R) Shared store used to open per-Run Sessions. ### `settings` (R) Settings snapshot used by new Runs. ### `skill_paths` (R) Ordered directories searched for skill definitions. ### `skill_resource_root` (R) Root used for skill-owned resources, when configured. ### `workspace_declaration` (R) Configured Workspace provider symbol, callable, or declaration. ## Class methods ### `.new` ```ruby .new(configuration:, settings: nil) ``` Starts a runtime from `configuration` or an existing settings snapshot. ## Instance methods ### `#build` ```ruby #build(**overrides) ``` Creates a sibling runtime with explicit setting overrides. ### `#build_run` ```ruby #build_run(payload, agent_class: nil, assembly_class: nil, entrypoint_class: nil, execution_class: nil, cancellation_token: Support::CancellationToken.new, workspace: nil, sandbox: nil, include_agent_events_by_default: false) ``` Creates a Run that owns any workspace and sandbox built for the request. `include_agent_events_by_default` is trusted stream policy for the Run returned by this build. It applies only when the Invocation omits `include_agent_events` and must not be forwarded to auxiliary Runs built while preparing the request. ### `#build_sandbox` ```ruby #build_sandbox(workspace:, invocation: nil) ``` Instantiates the configured sandbox around `workspace`, or an unrestricted sandbox by default. ### `#build_workspace` ```ruby #build_workspace(invocation: nil) ``` Instantiates the configured workspace, or a root-scoped Workspace by default. ### `#parse` ```ruby #parse(payload) ``` Coerces an application payload into the configured Invocation class. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/AGUI.md # Module LittleGhost::AGUI Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/AGUI.html AG-UI connects LittleGhost streams to user interfaces that speak the AG-UI protocol. Require `little_ghost/ag_ui` to load this optional integration. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/AGUI/Adapter.md # Class LittleGhost::AGUI::Adapter Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/AGUI/Adapter.html Adapter turns a LittleGhost stream into AG-UI event hashes. It lets a Ruby agent drive compatible chat interfaces without changing the agent itself. events = CustomerSupportAgent.stream_ask("Where is my order?") adapter = LittleGhost::AGUI::Adapter.new adapter.stream(events, thread_id: "thread-1", run_id: "run-1").each do |event| websocket.write(JSON.generate(event)) end The adapter has no state between #stream calls, so one instance can translate independent runs. ### Choose what the interface receives Provider plaintext reasoning becomes AG-UI reasoning events. Tool arguments and results, invocation metadata, subagent events, trace context, and selected error text also pass through without redaction. Authorize and filter the complete stream before transport, and send it only to an interface intended to display that data. Encrypted reasoning and provider continuity artifacts are never exposed here. ## Inheritance `LittleGhost::AGUI::Adapter < Object` ## Instance methods ### `#stream` ```ruby #stream(events, thread_id:, run_id:) ``` Lazily translates `events` for one AG-UI run. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/AbstractMethodError.md # Class LittleGhost::AbstractMethodError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/AbstractMethodError.html Raised when an abstract framework method has no concrete implementation. ## Inheritance `LittleGhost::AbstractMethodError < LittleGhost::Error` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/AdapterLoadError.md # Class LittleGhost::AdapterLoadError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/AdapterLoadError.html Raised when a configured provider adapter cannot be constructed. ## Inheritance `LittleGhost::AdapterLoadError < LittleGhost::ConfigurationError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/ContextManagement.md # Module LittleGhost::Agent::ContextManagement Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/ContextManagement.html Keep long conversations within the model's available context window. The capability summarizes older turns while preserving trusted instructions and recent messages. class CustomerSupportAgent < LittleGhost::Agent manage_context compression_threshold: 0.75, preserve_recent_messages: 12 end As a support thread reaches the threshold, the next model request contains a generated summary and targets retaining its 12 most recent conversation messages. System and developer messages remain intact, and tool-use/result pairs are never split merely to hit the requested count. Context management is inactive until `manage_context` is declared. The configured window is a fallback: provider metadata takes precedence when it advertises a positive context-window size. Compaction uses the current model with the request's settings, cancellation token, and deadline. Proactive compaction failures leave the original request unchanged and emit diagnostic instrumentation. A provider context-overflow error triggers one compaction replacement through the model-error callback; cancellation, deadlines, and cleanup failures still escape as control flow. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/ContextManagement/ClassMethods.md # Module LittleGhost::Agent::ContextManagement::ClassMethods Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/ContextManagement/ClassMethods.html Exposes context-management declarations on agent classes. These methods become inheritable DSL entries when the capability is included. ## Instance methods ### `#manage_context` ```ruby #manage_context(context_window_tokens: DEFAULT_CONTEXT_WINDOW_TOKENS, compression_threshold: DEFAULT_COMPRESSION_THRESHOLD, summary_ratio: DEFAULT_SUMMARY_RATIO, preserve_recent_messages: DEFAULT_PRESERVE_RECENT_MESSAGES) ``` Enables automatic context compaction for the agent class. The defaults assume a 200,000-token window, compact at 85% usage, summarize about 30% of conversation messages, and preserve the 10 most recent messages. The model's declared context window takes precedence over `context_window_tokens` when available. Invalid ranges raise ArgumentError when the agent class is defined. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/Delegation.md # Module LittleGhost::Agent::Delegation Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/Delegation.html Give one agent a bounded way to ask another agent for help. Delegated agents can run as managed subagents or behind an ordinary tool call. class CustomerSupportAgent < LittleGhost::Agent subagent ResearchAgent, kind: "research" agent_as_tool SentimentAgent, name: "classify_sentiment" end The support model receives spawn, messaging, interjection, waiting, and listing tools for the `research` kind. It sees the sentiment agent as one regular tool whose result is returned to the current turn. Static declarations may be combined with a resolver that returns dynamic Subagents::Definition objects. Managed conversations persist when a session store is configured unless `persist: false` keeps them local to one invocation. An agent exposed as a tool starts with empty history unless `preserve_context: true` serializes calls and retains its history. Tool overrides must be classes. A delegated agent otherwise receives only its own declared tools; it does not inherit the parent's registry. The manager enforces concurrency, identity, wait duration, and persistence bounds. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/Delegation/ClassMethods.md # Module LittleGhost::Agent::Delegation::ClassMethods Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/Delegation/ClassMethods.html Exposes delegation declarations on agent classes. These methods become inheritable DSL entries when the capability is included. ## Instance methods ### `#agent_as_tool` ```ruby #agent_as_tool(agent_class, name: nil, description: nil, model: nil, tools: nil, preserve_context: false) ``` Exposes `agent_class` as one ordinary tool. Pass `preserve_context: true` to retain the delegated agent's conversational history between calls to that tool instance. ### `#agents_as_tools` ```ruby #agents_as_tools(*agent_classes, **options) ``` Exposes several agent classes as ordinary tools with shared options. ### `#assemblies_as_tools` ```ruby #assemblies_as_tools(*assembly_classes, **options) ``` Exposes several assembly classes as ordinary tools with shared options. ### `#assembly_as_tool` ```ruby #assembly_as_tool(assembly_class, name: nil, description: nil, model: nil, tools: nil, preserve_context: false) ``` Exposes an Agent, Workflow, Swarm, or Graph as one ordinary tool. Agent-only `model` and `tools` overrides are rejected for composites. ### `#subagent` ```ruby #subagent(agent_class, kind: nil, description: nil, model: nil, tools: nil, factory: nil, persist: true) ``` Adds `agent_class` as an available managed subagent. `kind` defaults to the agent ID and `description` defaults to the agent description. Conversations persist when a session store exists; pass `persist: false` for invocation-local work. subagent ResearchAgent, kind: "research" ### `#subagent_long_poll_duration` ```ruby subagent_long_poll_duration() -> Float subagent_long_poll_duration(seconds) -> Float ``` How long `wait_for_subagents` watches for progress before returning. The default comes from Subagents::Manager. Values must be positive, finite numbers and are normalized to Float. ### `#subagents` ```ruby #subagents(*agent_classes, **options, &resolver) ``` Adds several static subagents and an optional dynamic definition resolver. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/Skills.md # Module LittleGhost::Agent::Skills Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/Skills.html Let an agent discover application-authored instructions only when it needs them. Skills are file-backed guides advertised in the system prompt and loaded through a model-callable catalog tool. class CustomerSupportAgent < LittleGhost::Agent skills paths: [File.expand_path("../skills", __dir__)] end A run with a `refunds` skill sees that skill in its discovery prompt. The model can then call the `skills` tool to read the full guide before handling the refund request. Including this module alone has no effect. The `skills` declaration installs the catalog tool and prompt callback; paths may be static or resolved for each run, and omitted paths use the runtime's configured skill roots. An empty catalog exposes neither a tool nor discovery text. Skill files influence model behavior and should come from application-owned, trusted roots. Catalog loading applies its own file, count, and size bounds. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/Skills/ClassMethods.md # Module LittleGhost::Agent::Skills::ClassMethods Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/Skills/ClassMethods.html Exposes skill discovery declarations on agent classes. These methods become inheritable DSL entries when the capability is included. ## Instance methods ### `#skills` ```ruby skills(*paths, **options) -> configuration skills(paths: paths_or_resolver, **options) -> configuration ``` Enables skill discovery for this agent. `paths` may be paths or a callable resolved for each run. When omitted, the runtime's configured skill paths are used. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/ToolLoop.md # Module LittleGhost::Agent::ToolLoop Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/ToolLoop.html Stop an agent from repeating a tool call that cannot make progress. Detection follows identical tool names, arguments, result status, and result content within one invocation. class CustomerSupportAgent < LittleGhost::Agent detect_tool_loops warning_at: 3, terminate_at: 5, except: AccountRefreshTool end If a support model makes the same ineffective lookup three times, its third result includes a warning to change approach. A fourth repeat carries the final warning, and a fifth stops the run with ToolLoopError. Detection is inactive until `detect_tool_loops` is declared. Exclusions may be tool classes, instances, names, or symbols. State is isolated per active invocation and guarded for concurrent tool batches; unfinished subagent waits do not count as repeated progress failures. Only identical normalized arguments and results advance the counter. A changed result resets that sequence, while a terminating repeat prevents the duplicate tool body from running again. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/ToolLoop/ClassMethods.md # Module LittleGhost::Agent::ToolLoop::ClassMethods Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Agent/ToolLoop/ClassMethods.html Exposes tool-loop detection declarations on agent classes. These methods become inheritable DSL entries when the capability is included. ## Instance methods ### `#detect_tool_loops` ```ruby #detect_tool_loops(warning_at: 3, terminate_at: 5, except: []) ``` Enables repeated tool-call detection. `warning_at` defaults to 3 identical calls and `terminate_at` defaults to 5. `except` accepts tool classes, instances, names, or symbols. Raises ArgumentError unless `warning_at` is at least 2 and `terminate_at` is greater than `warning_at`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/AgentBuilder.md # Class LittleGhost::AgentBuilder Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/AgentBuilder.html Builds an Agent definition from declarations made at runtime. agent = LittleGhost::AgentBuilder.new(id: "customer_support") agent.model "openrouter:openai/gpt-5.6-luna" agent.system_prompt "Answer customer questions clearly." agent.ask("Where is my order?") It accepts the same configuration calls as an Agent class. Changing the builder affects future builds without changing Agents already built. ## Inheritance `LittleGhost::AgentBuilder < LittleGhost::AssemblyBuilder` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/AgentInterjectionError.md # Class LittleGhost::AgentInterjectionError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/AgentInterjectionError.html Raised when an active run cannot accept an interjection. ## Inheritance `LittleGhost::AgentInterjectionError < LittleGhost::InvocationError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/AgentStreamSource.md # Class LittleGhost::AgentStreamSource Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/AgentStreamSource.html Describes which Agent produced an event during a Run. A `:agent_stream` StreamEvent carries this value in `data[:source]` and the Agent's event as a separate frozen StreamEvent in `data[:event]`. `assembly_path` is empty for a top-level Agent and contains one AgentStreamStep for each enclosing composite assembly participant. ## Inheritance `LittleGhost::AgentStreamSource < Data` ## Attributes ### `agent_id` (R) Stable String identifier declared by the Agent class. ### `agent_path` (R) Stable subagent path, beginning at `/root`. ### `assembly_path` (R) Frozen Array of AgentStreamStep values from the outermost assembly inward. ### `operation_id` (R) Unique String identifier for this Agent invocation. ### `parent_operation_id` (R) Parent operation identifier, or `nil` when the caller did not supply one. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/AgentStreamStep.md # Class LittleGhost::AgentStreamStep Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/AgentStreamStep.html Identifies one assembly step in the path to a streamed Agent invocation. Paths list outer steps before inner steps, so the final value identifies the participant that directly contains the Agent. ## Inheritance `LittleGhost::AgentStreamStep < Data` ## Attributes ### `assembly_id` (R) Stable String identifier for the containing assembly. ### `assembly_kind` (R) The `:workflow`, `:swarm`, `:graph`, or custom assembly kind. ### `branch_id` (R) String branch identifier for a graph branch, or `nil`. ### `participant` (R) String name used to route to this participant. ### `step_id` (R) Unique String identifier for this assembly step. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Artifact.md # Class LittleGhost::Artifact Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Artifact.html Represents a file, image, or document produced by a Tool or supplied to a Run. LittleGhost sends supported media to the model once and may store the same bytes for filesystem Tools. Inline artifacts contain their bytes. Deferred artifacts contain an application-defined reference that the block passed to Configuration#artifacts may use to load the bytes. image = LittleGhost::Artifact.new( data: File.binread("chart.png"), media_type: "image/png", name: "chart.png" ) download = LittleGhost::Artifact.deferred( reference: {file_id: "file-481"}, media_type: "application/pdf", name: "report.pdf" ) ## Inheritance `LittleGhost::Artifact < Object` ## Attributes ### `bytes` (R) Known byte count, otherwise nil for an unresolved artifact. ### `data` (R) Binary content for an inline artifact, otherwise nil. ### `media_type` (R) MIME media type used to present the artifact. ### `metadata` (R) Deeply frozen application metadata. ### `name` (R) Optional display filename. ### `reference` (R) Application-defined deferred reference, or generated Workspace reference after storage; otherwise nil. ## Class methods ### `.deferred` ```ruby .deferred(reference:, media_type:, name: nil, metadata: {}) ``` Creates an artifact whose bytes may be loaded later by the block passed to Configuration#artifacts. ### `.new` ```ruby .new(data:, media_type:, name: nil, metadata: {}) ``` Creates an inline artifact from binary `data` and a MIME `media_type`. ## Instance methods ### `#==` ```ruby #==(other) ``` Compares all immutable artifact fields. ### `#deferred?` ```ruby #deferred?() ``` Whether this artifact requires an application resolver. ### `#eql?` ```ruby #eql?(other) ``` Uses the same field comparison when an artifact is a Hash key. ### `#hash` ```ruby #hash() ``` Computes a Hash key from all immutable artifact fields. ### `#inline?` ```ruby #inline?() ``` Whether this artifact contains its bytes directly. ### `#inspect` ```ruby #inspect() ``` Avoids placing bytes, names, metadata, or deferred references in diagnostics. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Artifacts.md # Module LittleGhost::Artifacts Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Artifacts.html Stores files from Run input and Tool results, then presents them to agents as bounded images, documents, previews, or Workspace references. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Assembly/Attempt.md # Class LittleGhost::Assembly::Attempt Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Assembly/Attempt.html One bounded attempt to execute a child Assembly step. It records timing, normalized usage, terminal status, and a sanitized error description suitable for the public coordination trajectory. ## Inheritance `LittleGhost::Assembly::Attempt < Data` ## Attributes ### `error` (R) A sanitized error description, or `nil`. ### `finished_at` (R) The wall-clock finish time. ### `number` (R) The one-based attempt number. ### `started_at` (R) The wall-clock start time. ### `status` (R) The normalized terminal status for this attempt. ### `usage` (R) The Usage recorded by this attempt. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Assembly/Step.md # Class LittleGhost::Assembly::Step Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Assembly/Step.html One logical child execution in a composite Assembly result. Steps identify the participant, relationships to other steps, attempts, usage, and a bounded semantic output. Use RunResult#trajectory for queries over several steps. ## Inheritance `LittleGhost::Assembly::Step < Data` ## Attributes ### `assembly_id` (R) The invoked Assembly's stable identifier. ### `assembly_kind` (R) The invoked Assembly kind. ### `attempts` (R) Immutable Attempt values, including retries. ### `branch_id` (R) The parallel branch identifier, or `nil`. ### `id` (R) The stable identifier for this step occurrence. ### `output` (R) The bounded semantic output retained for coordination inspection. ### `output_truncated` (R) Indicates that `output` exceeded the public result limit. ### `parent_id` (R) The containing step identifier for nested coordination, or `nil`. ### `participant` (R) The participant name used by the parent Assembly. ### `predecessor_ids` (R) Step identifiers whose results led to this step. ### `status` (R) The logical step's terminal status. ### `usage` (R) Usage accumulated across the step's attempts. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Assembly/Trajectory.md # Class LittleGhost::Assembly::Trajectory Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Assembly/Trajectory.html Immutable queries over the steps returned by one assembly invocation. ## Inheritance `LittleGhost::Assembly::Trajectory < Object` ## Includes - `Enumerable` ## Attributes ### `steps` (R) Immutable steps in execution order. ## Class methods ### `.new` ```ruby .new(steps) ``` Builds query indexes for `steps`. ## Instance methods ### `#attempts_for` ```ruby #attempts_for(id) ``` Returns attempts belonging to one step. ### `#children` ```ruby #children(id) ``` Returns steps whose parent is `id`. ### `#concurrent?` ```ruby #concurrent?(first_id, second_id) ``` Indicates whether attempts from two steps overlapped in time. ### `#each` ```ruby #each(&block) ``` Iterates through steps in execution order. ### `#step` ```ruby #step(id) ``` Finds one step by its stable ID. ### `#transitions` ```ruby #transitions() ``` Returns declared predecessor-to-step ID pairs. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/AssemblyBuilder.md # Class LittleGhost::AssemblyBuilder Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/AssemblyBuilder.html Builds an Assembly when its participants or routes are discovered at runtime. Class definitions are the usual, easier-to-find way to declare behavior. Builders expose the underlying dynamic form while preserving the same `ask`, `stream_ask`, `call`, and `stream` interface: graph = LittleGhost::GraphBuilder.new(id: "support_flow") graph.node :triage, TriageAgent graph.node :respond, CustomerSupportAgent graph.start :triage graph.edge :triage, :respond graph.finish :respond graph.validate! run = graph.ask("Can I get a refund?") A builder remains mutable. Each build or invocation copies its declarations and referenced Assembly definitions. Later builder changes affect future executions without changing an Assembly already built. Ruby closures and the objects they reference remain live application code. ## Inheritance `LittleGhost::AssemblyBuilder < Object` ## Attributes ### `runtime` (R) Optional Runtime reused by standalone executions from this builder. ## Class methods ### `.new` ```ruby .new(id: nil, description: nil, runtime: nil, base: nil) ``` Creates a mutable builder with optional identity, runtime, and base class. ## Instance methods ### `#as_tool` ```ruby #as_tool(**options) ``` Exposes the current declarations as a Tool. ### `#ask` ```ruby #ask(message, **options) ``` Executes the current declarations and returns their Run. ### `#assembly_id` ```ruby #assembly_id(value = nil) ``` Reads or assigns the stable Assembly identifier. ### `#assembly_kind` ```ruby #assembly_kind() ``` Returns `:agent`, `:workflow`, `:swarm`, or `:graph`. ### `#build` ```ruby #build(runtime: self.runtime, run: nil) ``` Builds one execution instance from the current declarations. ### `#call` ```ruby #call(input = nil, **options) ``` Executes the current declarations to completion. ### `#definition` ```ruby #definition() ``` Returns a complete definition for the builder's current declarations. ### `#description` ```ruby #description(value = nil) ``` Reads or assigns the human-readable description. ### `#start_execution` ```ruby #start_execution(payload, &block) ``` Starts a supervised execution from the current declarations. ### `#stream` ```ruby #stream(input = nil, **options) ``` Streams the current declarations as StreamEvent objects. ### `#stream_ask` ```ruby #stream_ask(message, **options) ``` Lazily streams an execution built from the current declarations. ### `#validate!` ```ruby #validate!() ``` Validates the builder's current declarations and returns this builder. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/AssemblyDefinition.md # Class LittleGhost::AssemblyDefinition Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/AssemblyDefinition.html A complete Assembly configuration produced by an AssemblyBuilder. Runtime and other builders accept a definition anywhere they accept an Assembly reference. `implementation` is the Assembly subclass used for executions built from this definition. ## Inheritance `LittleGhost::AssemblyDefinition < Data` ## Attributes ### `assembly_id` (R) The Assembly identifier at the time the definition was built. ### `description` (R) The human-readable description at the time the definition was built. ### `implementation` (R) The Assembly subclass used to build executions. ### `kind` (R) The Assembly kind: `:agent`, `:workflow`, `:swarm`, or `:graph`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/AssemblyError.md # Class LittleGhost::AssemblyError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/AssemblyError.html Base class for failures coordinating one or more assemblies. ## Inheritance `LittleGhost::AssemblyError < LittleGhost::Error` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/AssemblyLimitError.md # Class LittleGhost::AssemblyLimitError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/AssemblyLimitError.html Raised when an assembly exceeds its configured execution bound. ## Inheritance `LittleGhost::AssemblyLimitError < LittleGhost::AssemblyError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/AssemblyRoutingError.md # Class LittleGhost::AssemblyRoutingError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/AssemblyRoutingError.html Raised when an assembly cannot choose one valid next participant. ## Inheritance `LittleGhost::AssemblyRoutingError < LittleGhost::AssemblyError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/AssemblyStepTimeoutError.md # Class LittleGhost::AssemblyStepTimeoutError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/AssemblyStepTimeoutError.html Raised when one assembly step exceeds its local timeout. ## Inheritance `LittleGhost::AssemblyStepTimeoutError < LittleGhost::AssemblyError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/CancelledError.md # Class LittleGhost::CancelledError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/CancelledError.html Raised when cancellation stops an operation. A started top-level Run normally records a cancelled outcome. ## Inheritance `LittleGhost::CancelledError < LittleGhost::Error` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/CapabilityError.md # Class LittleGhost::CapabilityError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/CapabilityError.html Raised when a backend cannot enforce a requested sandbox capability. ## Inheritance `LittleGhost::CapabilityError < LittleGhost::SandboxConfigurationError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/CleanupError.md # Class LittleGhost::CleanupError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/CleanupError.html Raised when one or more managed resources fail to close. Treat the operation as not cleanly terminated and escalate to the application's supervisor. ## Inheritance `LittleGhost::CleanupError < LittleGhost::Error` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode.md # Module LittleGhost::CodeMode Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode.html Runs model-authored orchestration code in a child interpreter. Built-in engines keep Tool authority in the parent process: each Tool call returns to a trusted Broker for catalog validation and ordinary Agent dispatch. Custom engines must preserve the Engine and Session containment contracts. See the [Code Mode guide](../code_mode.md) for the first Ruby program, Broker boundary, lifecycle, limits, optional JavaScript engine, and extension contract. ## Class methods ### `.register_engine` ```ruby .register_engine(name, implementation) ``` Registers `implementation` under a trusted engine name. ### `.resolve_engine` ```ruby .resolve_engine(value) ``` Resolves a registered name or returns an explicit engine object. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/Broker.md # Class LittleGhost::CodeMode::Broker Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/Broker.html Keeps tool authorization and execution in the trusted parent process. ## Inheritance `LittleGhost::CodeMode::Broker < Object` ## Class methods ### `.new` ```ruby .new(agent: nil, registry: nil, context: RunContext.new, events: [], parent_operation_id: nil, parent_trace_context: nil, except: nil, dispatch: nil, max_calls: nil) ``` Builds a broker for an Agent's Tool registry. `except` removes names from the code-mode catalog. `dispatch` is a trusted adapter hook used by custom hosts; ordinary Agent integrations should let the broker dispatch through `agent`. ## Instance methods ### `#call` ```ruby #call(name, arguments = {}, id: SecureRandom.uuid) ``` Calls an available Tool by model-visible `name`. The returned CallResult has `id`, decoded `value`, and model-safe `error` fields. `arguments` remains untrusted until the ordinary Tool path validates and authorizes it. ### `#catalog` ```ruby #catalog() ``` Returns the Tool specifications available to model-authored code. Excluded Tools, code-mode controls, and subagent controls stay outside this catalog. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/Catalog.md # Class LittleGhost::CodeMode::Catalog Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/Catalog.html Normalizes a trusted Tool catalog for a guest language and rejects names that would collide or shadow code-mode controls. ## Inheritance `LittleGhost::CodeMode::Catalog < Object` ## Attributes ### `definitions` (R) Frozen normalized Tool definitions in declaration order. ## Class methods ### `.new` ```ruby .new(specifications, normalize:, reserved: %w[exec wait stop]) ``` Normalizes trusted Tool `specifications` with `normalize`. Names in `reserved` and names that collide after normalization are rejected. ## Instance methods ### `#fetch` ```ruby #fetch(name) ``` Returns the normalized definition for `name`. ### `#key?` ```ruby #key?(name) ``` Indicates whether `name` is present in the catalog. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/Engine.md # Class LittleGhost::CodeMode::Engine Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/Engine.html Adapter contract for a code-mode language. An Engine describes the language shown to the model and opens one Session. Model-authored code must run behind the supplied `sandbox_factory`. The Broker must remain in the trusted parent process; do not expose it or its application objects inside the child interpreter. LittleGhost may call one registered Engine instance concurrently for different Agents and RunContexts. Keep mutable program state in the Session returned by #open_session, not on the Engine. ## Inheritance `LittleGhost::CodeMode::Engine < Object` ## Instance methods ### `#instructions` ```ruby #instructions(catalog:) ``` Returns model-facing instructions for the supplied Tool Catalog. This method may be called concurrently. Instructions must describe only names and behavior the Session actually implements. ### `#language` ```ruby #language() ``` Returns the engine's language identifier as a Symbol. ### `#open_session` ```ruby #open_session(broker:, sandbox_factory:, limits:) ``` Opens and returns a CodeMode::Session. `broker` is called only from trusted parent code. `sandbox_factory` creates the Sandbox that contains model-authored execution. `limits` is the application's mapping, passed through unchanged. A custom Engine must normalize keys and values, validate supported settings, and merge its own safe defaults. The Session owns every Workspace, Sandbox, process, thread, and channel it creates. This method may be called concurrently; each call must return an independent Session. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/JavascriptEngine.md # Class LittleGhost::CodeMode::JavascriptEngine Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/JavascriptEngine.html Runs model-written JavaScript in an isolated V8 context. This optional engine uses MiniRacer. Requiring LittleGhost does not load MiniRacer; applications opt in by requiring `little_ghost/code_mode/javascript_engine`. ## Inheritance `LittleGhost::CodeMode::JavascriptEngine < LittleGhost::CodeMode::Engine` ## Constants ### `DEFAULT_LIMITS` Resource and concurrency limits applied when the application does not override them. ## Instance methods ### `#instructions` ```ruby #instructions(catalog:) ``` Builds JavaScript usage instructions and TypeScript declarations for `catalog`. ### `#language` ```ruby #language() ``` Returns the `:javascript` language identifier. ### `#open_session` ```ruby #open_session(broker:, sandbox_factory:, limits: {}) ``` Opens a JavaScript Session with engine defaults merged with `limits`. Unsupported limit keys raise ArgumentError. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/ProgramResult.md # Class LittleGhost::CodeMode::ProgramResult Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/ProgramResult.html Describes one observation of a code-mode program. Its output contains text produced since the previous observation. `value` carries the completed program's language value when the engine supports one. `status` is `:completed`, `:still_working`, `:terminated`, or `:error`. `error` contains a model-program error; lifecycle and cleanup failures raise instead. ## Inheritance `LittleGhost::CodeMode::ProgramResult < Data` ## Attributes ### `artifacts` (R) Artifact descriptors produced by brokered Tools since the previous observation. ### `error` (R) A model-program error for an `:error` result, or `nil`. ### `output` (R) Text produced since the previous observation. ### `status` (R) The program state after this observation. ### `value` (R) The completed program's language value, when available. ## Class methods ### `.new` ```ruby .new(output: "", value: nil, status: :completed, error: nil, artifacts: [], presentation_content: []) ``` Creates a program observation with empty output and a successful status by default. ## Instance methods ### `#completed?` ```ruby #completed?() ``` Whether the program completed successfully. ### `#still_working?` ```ruby #still_working?() ``` Whether the program remains active after this observation. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/Protocol.md # Module LittleGhost::CodeMode::Protocol Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/Protocol.html Length-prefixed JSON framing shared by code-mode parent and child hosts. Frames are bounded before allocation and parsing. ## Constants ### `Error` Raised for malformed or oversized frames. ### `MAX_FRAME_BYTES` Largest encoded JSON payload accepted by the protocol. ## Instance methods ### `#dump` ```ruby #dump(value) ``` Returns one encoded frame for `value`. ### `#extract!` ```ruby #extract!(buffer) ``` Removes and returns one complete frame from `buffer`, or returns `nil` while more bytes are required. ### `#read` ```ruby #read(io) ``` Reads one complete frame from `io`, or returns `nil` at clean EOF. ### `#write` ```ruby #write(io, value) ``` Encodes `value` and writes one complete frame to `io`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/RubyEngine.md # Class LittleGhost::CodeMode::RubyEngine Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/RubyEngine.html Runs model-written Ruby in a fresh sandboxed process. Tool calls cross a bounded protocol to the trusted parent Broker. The engine uses only Ruby's standard library and adds no runtime dependency. LittleGhost.configure do |config| config.code_mode = {engine: :ruby, sandbox: :native} end ## Inheritance `LittleGhost::CodeMode::RubyEngine < LittleGhost::CodeMode::Engine` ## Constants ### `DEFAULT_LIMITS` Resource, Tool-call, and program limits applied when the application does not override them. ## Instance methods ### `#instructions` ```ruby #instructions(catalog:) ``` Builds Ruby usage instructions and method declarations for `catalog`. ### `#language` ```ruby #language() ``` Returns the `:ruby` language identifier. ### `#open_session` ```ruby #open_session(broker:, sandbox_factory:, limits: {}) ``` Opens a Ruby Session with engine defaults merged with `limits`. Unsupported limit keys raise ArgumentError. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/Session.md # Class LittleGhost::CodeMode::Session Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/CodeMode/Session.html Lifecycle contract for one Engine's active program. LittleGhost's Agent runtime serializes `execute`, `wait`, and `stop` for a Session. Direct callers must also avoid overlap; built-in Sessions reject concurrent control operations. An implementation applies the supplied limits, observes RunContext cancellation, keeps model-written execution inside its Sandbox, and routes Tool calls through the parent-process Broker. Each control operation returns a ProgramResult. Built-in engines use `:completed` when execution ended successfully, `:still_working` when an observation interval elapsed, `:terminated` after requested termination, and `:error` for a model-program error. `wait` observes an active program without pausing, resuming, or restarting it. Lifecycle, host, and cleanup failures raise rather than becoming a result. ProgramResult.new( output: "", value: nil, status: :completed, error: nil ) ## Inheritance `LittleGhost::CodeMode::Session < Object` ## Instance methods ### `#close` ```ruby #close() ``` Closes all owned resources. A successful close is idempotent. Direct callers must not overlap it with a control operation. The method raises when the implementation cannot establish a clean ending. Built-in Sessions use CleanupError for bounded cleanup failures and may propagate an error raised while closing an owned resource. ### `#execute` ```ruby #execute(source:, catalog:, frame: nil, max_output_tokens: nil, context: nil) ``` Starts a fresh program from `source` and returns its first ProgramResult. `catalog` is the Tool catalog used to compile the source contract. `max_output_tokens` bounds output returned for this observation. `frame` is optional engine-specific data from a trusted caller. The Ruby engine exposes JSON-compatible frame data to model-authored code as `FRAME`, so it must not contain secrets. The JavaScript engine ignores it. Portable callers should leave it `nil`. ### `#stop` ```ruby #stop(max_output_tokens: nil, context: nil) ``` Terminates the active program and returns a `:terminated` ProgramResult with its final incremental output. Raises when no program is active or cleanup cannot finish. ### `#wait` ```ruby #wait(max_output_tokens: nil, context: nil) ``` Observes the active program and returns its next ProgramResult. Its `output` contains text produced since the previous observation. Raises when no program is active or cleanup cannot finish. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ConfigurationError.md # Class LittleGhost::ConfigurationError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ConfigurationError.html Raised for invalid framework or application configuration. Correct the configuration before retrying the request. ## Inheritance `LittleGhost::ConfigurationError < LittleGhost::Error` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Content.md # Module LittleGhost::Content Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Content.html Content gives messages a shared vocabulary for text, attachments, tool calls, tool results, and model reasoning. The same blocks move between agents, providers, tools, and sessions without leaking a provider's wire format. block = LittleGhost::Content::Text.new(text: "Hello") LittleGhost::Content.normalize("Hello") == block # => true Every block serializes through [Content.serialize](Content.md#method-i-serialize). Binary data uses strict base64 encoding in the serialized form. ## Instance methods ### `#from_hash` ```ruby #from_hash(value) ``` Reconstructs a content block from its serialized hash. ### `#normalize` ```ruby #normalize(value) ``` Accepts an existing block, a String, or a serialized Hash. ### `#serialize` ```ruby #serialize(block) ``` Produces the JSON-safe representation of `block`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Content/Document.md # Class LittleGhost::Content::Document Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Content/Document.html Contains binary document data, its MIME media type, and a display name. Content.serialize base64-encodes `data` in the serialized Hash. ## Inheritance `LittleGhost::Content::Document < Data` ## Attributes ### `data` (R) The original binary document bytes. ### `media_type` (R) The document MIME type, such as `application/pdf`. ### `name` (R) The filename or label presented to the model. ## Class methods ### `.new` ```ruby new(data:, media_type:, name:) -> Document ``` Wraps the supplied values without copying them. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Content/Image.md # Class LittleGhost::Content::Image Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Content/Image.html Contains binary image data, its MIME media type, and an optional display name. Content.serialize base64-encodes `data` in the serialized Hash. ## Inheritance `LittleGhost::Content::Image < Data` ## Attributes ### `data` (R) The original binary image bytes. ### `media_type` (R) The image MIME type, such as `image/png`. ### `name` (R) The optional filename or label used when the image is presented. ## Class methods ### `.new` ```ruby new(data:, media_type:, name: nil) -> Image ``` Wraps the supplied values without copying them. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Content/Reasoning.md # Class LittleGhost::Content::Reasoning Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Content/Reasoning.html Preserves provider reasoning without forcing every provider into one representation. A value may carry visible text, a provider signature, opaque redacted bytes, or provider-specific detail objects. Redacted bytes are mutually exclusive with text and signatures so they can round-trip without exposing or changing provider-managed content. ## Inheritance `LittleGhost::Content::Reasoning < Data` ## Attributes ### `details` (R) Optional provider-specific reasoning objects. ### `redacted_content` (R) Optional opaque bytes that only the provider should interpret. ### `signature` (R) An optional provider signature associated with `text`. ### `text` (R) Visible reasoning text, or an empty string when none is available. ## Class methods ### `.new` ```ruby new(text: "", signature: nil, redacted_content: nil, details: nil) -> Reasoning ``` `details`, when present, must be an array of Hash objects. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Content/Text.md # Class LittleGhost::Content::Text Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Content/Text.html Contains model-visible text. ## Inheritance `LittleGhost::Content::Text < Data` ## Attributes ### `text` (R) The text shown to the model or application. ## Class methods ### `.new` ```ruby new(text:) -> Text ``` Wraps `text` without copying it. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Content/ToolResult.md # Class LittleGhost::Content::ToolResult Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Content/ToolResult.html Carries the model-facing result for one ToolUse. A successful result uses `:success`; a caller-safe failure uses `:error`. ## Inheritance `LittleGhost::Content::ToolResult < Data` ## Attributes ### `content` (R) The content returned to the model. ### `status` (R) Either `:success` or `:error`. ### `tool_use_id` (R) The ToolUse identifier this result answers. ## Class methods ### `.new` ```ruby new(tool_use_id:, content:, status:) -> ToolResult ``` Requires a non-empty String-compatible `tool_use_id` and a `status` of `:success` or `:error`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Content/ToolUse.md # Class LittleGhost::Content::ToolUse Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Content/ToolUse.html Describes one tool call requested by a provider-backed model. ## Inheritance `LittleGhost::Content::ToolUse < Data` ## Attributes ### `id` (R) The non-empty provider call identifier used to match a ToolResult. ### `input` (R) The object-shaped arguments supplied by the model as a DataMap. ### `name` (R) The non-empty model-visible tool name. ## Class methods ### `.new` ```ruby new(id:, name:, input:) -> ToolUse ``` Requires non-empty String-compatible `id` and `name` values and an object-shaped `input`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ContextWindowOverflowError.md # Class LittleGhost::ContextWindowOverflowError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ContextWindowOverflowError.html Raised when a provider reports that the request exceeds its context window. ## Inheritance `LittleGhost::ContextWindowOverflowError < LittleGhost::ProviderError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/CredentialError.md # Class LittleGhost::CredentialError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/CredentialError.html Raised when no usable credentials can be resolved for a provider. ## Inheritance `LittleGhost::CredentialError < LittleGhost::ConfigurationError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/DataMap.md # Class LittleGhost::DataMap Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/DataMap.html DataMap holds JSON-compatible application data with indifferent key access. It stores every key as a String while accepting String and Symbol keys for lookup and mutation, including in nested maps. state = DataMap.new(plan: {status: "active"}) state.dig("plan", :status) # => "active" state.to_h # => {"plan" => {"status" => "active"}} State and metadata exposed by Sessions and RunContexts use DataMap so Ruby code can use either key form while session stores keep one portable shape. Values are limited to JSON primitives, Arrays, and mappings. A mapping that supplies both a String and Symbol form of the same key is ambiguous and raises ArgumentError. ## Inheritance `LittleGhost::DataMap < Hash` ## Class methods ### `.coerce` ```ruby .coerce(value) ``` Returns `value` when it is already a DataMap, or normalizes a mapping. ### `.new` ```ruby .new(value = {}) ``` Builds a deeply normalized map from `value`. ## Instance methods ### `#[]` ```ruby #[](key) ``` Looks up `key` after canonicalizing it to a String. ### `#[]=` ```ruby #[]=(key, value) ``` Stores `value` under the canonical String form of `key`. ### `#delete` ```ruby #delete(key, &block) ``` Removes `key` after canonicalizing it to a String. ### `#dig` ```ruby #dig(key, *names) ``` Traverses nested DataMaps with String or Symbol keys. ### `#fetch` ```ruby #fetch(key, *defaults, &block) ``` Fetches `key` with Hash#fetch's default and block behavior. ### `#has_key?` ```ruby #has_key?(key) ``` ### `#include?` ```ruby #include?(key) ``` ### `#initialize_copy` ```ruby #initialize_copy(other) ``` Returns a deep independent DataMap copy. ### `#key?` ```ruby #key?(key) ``` Checks for `key` after canonicalizing it to a String. ### `#member?` ```ruby #member?(key) ``` ### `#merge` ```ruby #merge(other, &block) ``` Returns a normalized copy merged with `other`. ### `#merge!` ```ruby #merge!(other) ``` Merges `other` after deeply normalizing its keys and values. ### `#replace` ```ruby #replace(other) ``` Replaces all entries with a deeply normalized copy of `other`. ### `#store` ```ruby #store(key, value) ``` ### `#store_raw_value` ```ruby #store_raw_value ``` ### `#to_h` ```ruby #to_h() ``` Produces a deep ordinary Hash with canonical String keys. ### `#update` ```ruby #update(other) ``` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/DeadlineExceededError.md # Class LittleGhost::DeadlineExceededError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/DeadlineExceededError.html Raised when an operation reaches its deadline. A started top-level Run normally records a partial outcome. ## Inheritance `LittleGhost::DeadlineExceededError < LittleGhost::Error` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/DependencyError.md # Class LittleGhost::DependencyError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/DependencyError.html Raised when an explicitly selected sandbox backend dependency is unavailable. ## Inheritance `LittleGhost::DependencyError < LittleGhost::SandboxConfigurationError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Error.md # Class LittleGhost::Error Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Error.html Base class for LittleGhost domain errors. Public APIs may also raise Ruby errors such as ArgumentError for invalid method arguments. ## Inheritance `LittleGhost::Error < StandardError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Events.md # Module LittleGhost::Events Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Events.html Events lets an application react to noteworthy agent activity without coupling LittleGhost to a logger or event backend. Listeners can feed local diagnostics, alerts, or an application's own event pipeline. class WarningCollector attr_reader :events def initialize @events = [] end def emit(event) events << event end end warnings = WarningCollector.new LittleGhost::Events.subscribe(warnings) do |event| %i[warn error].include?(event[:level]) end LittleGhost::Events.warn("support.case.stalled", case_id: "case-42") warnings.events.last[:name] # => "support.case.stalled" Events describe point-in-time facts. Instrumentation measures work that has a start and finish. Payloads are copied, limited to JSON-safe values, and delivered with context local to the current execution. A broken listener never breaks the operation that emitted the event. ## Constants ### `LEVELS` Severity levels accepted by .emit and its convenience methods. ## Class methods ### `.console_output` ```ruby .console_output() ``` The process-wide JSON-line console destination, or `nil` when console delivery is disabled. ### `.console_output=` ```ruby .console_output=(destination) ``` Selects `:stdout`, `:stderr`, or `nil` as the process-wide JSON-line console destination. Replacing the destination leaves other listeners unchanged. ### `.context` ```ruby .context() ``` Copies the current event context. ### `.reporter` ```ruby .reporter() ``` Accesses the process-wide reporter. ### `.reporter=` ```ruby .reporter=(value) ``` Replaces the process-wide reporter. Existing references are unaffected. ### `.subscribe` ```ruby .subscribe(...) ``` Subscribes a process-wide listener. ### `.subscribed` ```ruby .subscribed(listener, &block) ``` Subscribes `listener` only while the block runs. ### `.unsubscribe` ```ruby .unsubscribe(...) ``` Unsubscribes a process-wide listener. ### `.with_context` ```ruby .with_context(...) ``` Adds event context while a block runs. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Events/ConsoleListener.md # Class LittleGhost::Events::ConsoleListener Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Events/ConsoleListener.html JSON-lines listener suitable for diagnostics and local development. Values pass through a Support::Redactor before being written. ## Inheritance `LittleGhost::Events::ConsoleListener < Object` ## Class methods ### `.new` ```ruby .new(io: $stderr, redactor: Support::Redactor.new) ``` Writes redacted JSON lines to `io`. ## Instance methods ### `#emit` ```ruby #emit(event) ``` Emits one complete JSON line atomically. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Events/Reporter.md # Class LittleGhost::Events::Reporter Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Events/Reporter.html Thread-safe event publisher with process-wide and fiber-scoped listeners. Reporters start without listeners so applications opt into their preferred event destination, including `ConsoleListener` for JSON-line diagnostics. ## Inheritance `LittleGhost::Events::Reporter < Object` ## Class methods ### `.new` ```ruby .new(listeners: []) ``` Starts with `listeners` in subscription order. ## Instance methods ### `#context` ```ruby #context() ``` Copies the event context active in the current execution. ### `#emit` ```ruby #emit(level, name, payload = {}) ``` Delivers an event and returns a detached copy of its complete hash. ### `#subscribe` ```ruby #subscribe(listener, &filter) ``` Subscribes `listener`. The optional block filters copied event hashes. ### `#unsubscribe` ```ruby #unsubscribe(listener) ``` Unsubscribes every entry matching `listener`. ### `#with_context` ```ruby #with_context(attributes) ``` Adds attributes to events emitted while the block runs. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Execution.md # Class LittleGhost::Execution Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Execution.html Runs one dormant Run in the background while the caller remains free to serve health checks, deliver interjections, or coordinate shutdown. execution = agent.start_execution(message: "Investigate transfer 481") do |event| event_buffer << event end execution.interject(message: "Include the latest ledger entry") execution.wait(deadline: Time.now + 30) execution.run.completed? # => true The Runtime selects a scheduled fiber or worker thread for the execution. LittleGhost copies the caller's ExecutionState, but not other application fiber-local or thread-local values. The Run continues to own its workspace, sandbox, session, entrypoint, and registered resources. `close` requests cooperative cancellation and waits for the execution and any in-flight interjection calls. ## Inheritance `LittleGhost::Execution < Object` ## Attributes ### `run` (R) The supervised Run. ## Class methods ### `.start` ```ruby .start(run, &event_consumer) ``` Starts `run` immediately and returns its supervising Execution. If the work cannot start, this method closes `run` before raising. The optional block receives each StreamEvent from the fiber or thread running the Execution. It must not depend on a particular thread and should not pause the scheduler or retain sensitive event content longer than the application requires. ## Instance methods ### `#active?` ```ruby #active?() ``` Indicates that the Execution or an interjection call is still active. ### `#cancel` ```ruby #cancel() ``` Requests cooperative cancellation and returns `self`. ### `#close` ```ruby #close(deadline: nil) ``` Prevents new interjections, requests cancellation, and waits for shutdown. The operation is idempotent. `deadline` has the same meaning as in #wait. ### `#error` ```ruby #error() ``` Returns an event-delivery or cleanup exception raised by the Execution. ### `#finished?` ```ruby #finished?() ``` Indicates that the Execution and all interjection calls have finished. ### `#interject` ```ruby #interject(payload = nil, **options) ``` Prepares and delivers one interjection to the active run. `payload` may be a message or a Hash containing `message` and the options accepted by Run#interject. Runtime hooks receive the Hash before delivery, allowing them to materialize trusted application attachments. Calls may overlap, but `close` prevents new calls and waits for calls that have already begun. ### `#state` ```ruby #state() ``` Returns `:pending`, `:running`, or `:finished`. ### `#wait` ```ruby #wait(deadline: nil) ``` Waits for the Execution and in-flight interjections, then returns the Run. `deadline` is an absolute Time. Reaching it raises DeadlineExceededError without cancelling the run. An event-delivery or cleanup failure raised by the Execution is re-raised after all supervised work finishes. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ExecutionState.md # Module LittleGhost::ExecutionState Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ExecutionState.html ExecutionState carries request-scoped values across scheduled fibers and worker threads. It keeps event and instrumentation context from leaking between concurrent runs. Framework extensions may use #capture and #with to preserve event and instrumentation context. Captured hashes are immutable; values within them are not deep-copied. ## Class methods ### `.[]` ```ruby .[](key) ``` Reads `key` from the current execution state. ### `.[]=` ```ruby .[]=(key, value) ``` Replaces `key` in the current fiber-local state. ### `.capture` ```ruby .capture() ``` Captures the current immutable state hash for propagation. ### `.delete` ```ruby .delete(key) ``` Deletes `key` and returns its previous value. ### `.with` ```ruby .with(values) ``` Merges `values` while the block runs, then restores prior state. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Graph/State.md # Class LittleGhost::Graph::State Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Graph/State.html Read-only routing data passed to conditions and input mappers. `results` contains every completed node result. `incoming_results` contains only the immediate predecessors supplying the current node. `previous` and #previous_result are present for a single predecessor; `predecessors` preserves declaration order for fan-in execution. ## Inheritance `LittleGhost::Graph::State < Object` ## Attributes ### `context` (R) A frozen copy of application context available to the condition or mapper. ### `current` (R) The source node for a condition, or destination node for an input mapper. ### `error` (R) A frozen copy of the routed exception available to an error-edge mapper. ### `history` (R) A frozen copy of caller history available to the condition or mapper. ### `incoming_results` (R) Frozen copies of immediate predecessor RunResults keyed by node name. ### `input` (R) A copied Message containing the original request. ### `predecessors` (R) The immediate predecessor names in declaration order. ### `previous` (R) The predecessor name when exactly one result supplies the current node. ### `results` (R) Frozen copies of completed RunResults keyed by node name. ### `step` (R) The one-based execution count assigned to the current node. ## Instance methods ### `#previous_result` ```ruby #previous_result() ``` Returns the immediately preceding result when present. ### `#result` ```ruby #result(node_name) ``` Returns a completed result by node name. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/GraphBuilder.md # Class LittleGhost::GraphBuilder Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/GraphBuilder.html Builds a Graph from nodes and routes discovered at runtime. ## Inheritance `LittleGhost::GraphBuilder < LittleGhost::AssemblyBuilder` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Instrumentation.md # Module LittleGhost::Instrumentation Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Instrumentation.html Instrumentation turns agent work into structured lifecycle notifications. Applications can measure agents, models, tools, workflows, and sessions with the telemetry backend they already use. class TimingSubscriber < LittleGhost::Instrumentation::Subscriber def finish(name, attributes) puts "#{name}: #{attributes.fetch(:duration_ms)}ms" end end LittleGhost.configure do |config| config.instrument TimingSubscriber.new end A subscriber receives structured attributes when an operation starts, finishes, or emits a point-in-time event. Subscriber failures are reported once and kept separate from agent execution. ### Content and trust Diagnostic content is excluded unless the application installs an explicit Support::ContentCapture policy. One process is one telemetry and content policy boundary; applications that need different exporters or data policies should use separate processes. ## Class methods ### `.capture_content` ```ruby .capture_content(...) ``` Installs the process-wide diagnostic content policy. ### `.context` ```ruby .context() ``` Copies the current instrumentation context. ### `.current` ```ruby .current() ``` Returns the current fiber's active Handle. ### `.flush` ```ruby .flush(...) ``` Flushes process-wide subscribers. ### `.instrument` ```ruby .instrument(...) ``` Wraps a block in a lifecycle operation. ### `.notifier` ```ruby .notifier() ``` Accesses the process-wide Bus. ### `.notifier=` ```ruby .notifier=(value) ``` Replaces the process-wide bus when it has no active operations. ### `.publish` ```ruby .publish(...) ``` Publishes a point event on the process-wide bus. ### `.shutdown` ```ruby .shutdown(...) ``` Shuts down the process-wide bus. ### `.start` ```ruby .start(...) ``` Starts a lifecycle operation on the process-wide bus. ### `.subscribe` ```ruby .subscribe(...) ``` Subscribes a process-wide backend. ### `.subscribed` ```ruby .subscribed(subscriber, prepend: false) ``` Temporarily subscribes a backend for the block's execution state. ### `.trace_context` ```ruby .trace_context(...) ``` Gets downstream trace fields from process-wide subscribers. ### `.unsubscribe` ```ruby .unsubscribe(...) ``` Unsubscribes a process-wide backend. ### `.with_context` ```ruby .with_context(attributes, &block) ``` Adds attributes while the block runs. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Instrumentation/Bus.md # Class LittleGhost::Instrumentation::Bus Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Instrumentation/Bus.html Thread-safe notification bus used by the process-wide Instrumentation API. ## Inheritance `LittleGhost::Instrumentation::Bus < Object` ## Class methods ### `.new` ```ruby .new(subscribers: [], content_capture: Support::ContentCapture.disabled) ``` Starts an independent bus with ordered subscribers and a content policy. ## Instance methods ### `#active?` ```ruby #active?(handle = nil) ``` With a handle, tests whether that exact handle is active. Without one, reports whether the bus owns any active operations. ### `#capture_content` ```ruby #capture_content(policy) ``` Selects the diagnostic content policy used for future notifications. ### `#context` ```ruby #context() ``` Copies the attributes active in the current execution. ### `#current` ```ruby #current() ``` Finds the current non-detached Handle for this fiber, if any. ### `#finish` ```ruby #finish(handle, diagnostic: nil, **attributes) ``` Finishes an active handle and returns the final attribute hash. ### `#flush` ```ruby #flush(timeout: nil) ``` Flushes subscribers in registration order within an optional total timeout budget. ### `#instrument` ```ruby #instrument(name, payload = {}) ``` Measures a block and records raised errors before re-raising them. ### `#publish` ```ruby #publish(name, diagnostic: nil, **attributes) ``` Publishes a point event with the current context and operation ID. ### `#shutdown` ```ruby #shutdown(timeout: nil) ``` Permanently shuts down this bus after all operations have finished. ### `#start` ```ruby #start(name, parent: current, operation_id: SecureRandom.uuid, detached: false, diagnostic: nil, **attributes) ``` Starts an operation. `parent` may be a local Handle, a remote operation ID, or nil. Set `detached` for work that will not finish in stack order. ### `#subscribe` ```ruby #subscribe(subscriber, prepend: false) ``` Subscribes a backend once. `prepend` controls notification order. ### `#trace_context` ```ruby #trace_context(**attributes) ``` Uses the first non-empty downstream trace context supplied by a subscriber. ### `#unsubscribe` ```ruby #unsubscribe(subscriber) ``` Unsubscribes a backend by identity. ### `#with_context` ```ruby #with_context(attributes) ``` Adds copied attributes to notifications emitted while the block runs. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Instrumentation/Handle.md # Class LittleGhost::Instrumentation::Handle Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Instrumentation/Handle.html A Handle represents work between Instrumentation.start and #finish. Non-detached handles are fiber-owned and must finish in LIFO order after their children. Detached handles may finish outside the creating fiber but still cannot finish while local children remain active. ## Inheritance `LittleGhost::Instrumentation::Handle < Object` ## Attributes ### `name` (R) Operation identity, inherited attributes, previous local handle, and monotonic start time. ### `operation_id` (R) Operation identity, inherited attributes, previous local handle, and monotonic start time. ### `parent_operation_id` (R) Operation identity, inherited attributes, previous local handle, and monotonic start time. ### `payload` (R) Operation identity, inherited attributes, previous local handle, and monotonic start time. ### `previous` (R) Operation identity, inherited attributes, previous local handle, and monotonic start time. ### `started_at` (R) Operation identity, inherited attributes, previous local handle, and monotonic start time. ## Instance methods ### `#active?` ```ruby #active?() ``` Indicates whether this handle is still active. ### `#detached?` ```ruby #detached?() ``` Indicates whether this handle is outside the fiber-local operation stack. ### `#finish` ```ruby #finish(**attributes) ``` Completes this operation with additional attributes. ### `#local_parent?` ```ruby #local_parent?() ``` Indicates whether the parent is another active handle on this bus. ### `#owner?` ```ruby #owner?() ``` Indicates whether this handle belongs to the current fiber. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Instrumentation/Subscriber.md # Class LittleGhost::Instrumentation::Subscriber Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Instrumentation/Subscriber.html Subclass Subscriber to connect a telemetry backend. Override the callbacks a backend supports. `start` and `finish` receive the same operation name and correlated attributes. `emit` receives point events. Implementations may return a propagation carrier from #trace_context. Calls may overlap on threads or fibers, so implementations must protect shared mutable state without relying on thread identity. ## Inheritance `LittleGhost::Instrumentation::Subscriber < Object` ## Instance methods ### `#emit` ```ruby #emit(_name, _attributes) ``` Called for a point-in-time instrumentation event. ### `#finish` ```ruby #finish(_name, _attributes) ``` Called when a lifecycle operation finishes. ### `#flush` ```ruby #flush(timeout: nil) ``` Flushes buffered telemetry within an optional timeout budget. ### `#shutdown` ```ruby #shutdown(timeout: nil) ``` Releases subscriber resources within an optional timeout budget. ### `#start` ```ruby #start(_name, _attributes) ``` Called when a lifecycle operation starts. ### `#trace_context` ```ruby #trace_context(**) ``` Supplies trace fields that should travel with downstream work. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/InvalidPromptTemplateError.md # Class LittleGhost::InvalidPromptTemplateError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/InvalidPromptTemplateError.html Raised for unsafe names, escaped roots, cycles, or excessive recursion. ## Inheritance `LittleGhost::InvalidPromptTemplateError < LittleGhost::PromptTemplateError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Invocation.md # Class LittleGhost::Invocation Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Invocation.html Carry one application request into an agent run. An invocation keeps framework fields and application-specific context in one indifferent-key environment. invocation = LittleGhost::Invocation.new( message: "Why is transfer 481 pending?", account_id: "account-1", metadata: {channel: "customer_support"} ) invocation.message.text # => "Why is transfer 481 pending?" invocation[:account_id] # => "account-1" invocation.account_id # => "account-1" String and symbol keys address the same field. Known fields have named accessors, while unknown application fields remain available through hash access and dynamic readers or writers. `message` and every `history` entry are normalized to Message objects; `deadline_at` lazily parses ISO 8601 text. Missing run, invocation, and session identifiers are generated when the object is built. Actor identity is never inferred: applications that use it for persistence or tenant isolation must pass a value established by their trusted authentication boundary. Invalid payloads, messages, keys, or deadlines raise InvocationError. ## Inheritance `LittleGhost::Invocation < Object` ## Class methods ### `.new` ```ruby .new(env = {}) ``` Copies `env`, normalizes known framework fields, and fills missing identifiers. The payload must be a Hash and must contain a non-blank message. ## Instance methods ### `#[]` ```ruby #[](key) ``` Looks up `key` after normalizing it to a String. ### `#[]=` ```ruby #[]=(key, value) ``` Stores `value` under a normalized String key. The `message` and `history` fields are normalized before storage. ### `#actor_id` ```ruby actor_id() -> value ``` The explicit actor identifier supplied by the application. ### `#actor_id=` ```ruby actor_id=(value) -> value ``` Replaces the application-established actor identifier. ### `#context` ```ruby context() -> Hash ``` JSON-like state made available to the agent run. ### `#context=` ```ruby context=(value) -> value ``` Replaces the JSON-like agent state. ### `#deadline_at` ```ruby #deadline_at() ``` The request deadline as a Time, parsing ISO 8601 text on first access. ### `#deadline_at=` ```ruby #deadline_at=(value) ``` Replaces the deadline; parsing is deferred until `deadline_at` is read. ### `#dig` ```ruby #dig(key, *names) ``` Traverses the environment from normalized `key` through `names`. ### `#fetch` ```ruby #fetch(key, *defaults, &block) ``` Fetches `key` with the same default and block behavior as Hash#fetch. ### `#history` ```ruby history() -> Array ``` Frozen, normalized Messages that precede the current message. ### `#history=` ```ruby #history=(value) ``` Replaces and freezes the normalized message history. ### `#invocation_id` ```ruby invocation_id() -> String ``` The invocation identifier, defaulting to `run_id`. ### `#invocation_id=` ```ruby invocation_id=(value) -> value ``` Replaces the invocation identifier. ### `#key?` ```ruby #key?(key) ``` Whether the environment contains `key` after normalization. ### `#message` ```ruby message() -> LittleGhost::Message ``` The normalized current Message. ### `#message=` ```ruby #message=(value) ``` Replaces and normalizes the current message. ### `#metadata` ```ruby metadata() -> Hash ``` Application metadata carried with the request. ### `#metadata=` ```ruby metadata=(value) -> value ``` Replaces the application metadata. ### `#run_id` ```ruby run_id() -> String ``` The caller-supplied or generated top-level run identifier. ### `#run_id=` ```ruby run_id=(value) -> value ``` Replaces the top-level run identifier. ### `#session_id` ```ruby session_id() -> String ``` The session identifier, defaulting to `run_id`. ### `#session_id=` ```ruby session_id=(value) -> value ``` Replaces the session identifier used for persistence. ### `#settings` ```ruby settings() -> Hash ``` Per-request model settings merged after profile defaults. Treat these as trusted application policy, not unchecked request or model input. ### `#settings=` ```ruby settings=(value) -> value ``` Replaces the trusted request-scoped model settings. ### `#to_h` ```ruby #to_h() ``` Produces a mutable copy of the invocation environment. Nested hashes, arrays, strings, and other duplicable values are copied. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/InvocationError.md # Class LittleGhost::InvocationError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/InvocationError.html Raised when an invocation payload or operation is invalid. ## Inheritance `LittleGhost::InvocationError < LittleGhost::Error` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Lookup.md # Module LittleGhost::Lookup Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Lookup.html Lookup holds path values shared by prompt and skill discovery. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Lookup/Root.md # Class LittleGhost::Lookup::Root Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Lookup/Root.html Holds an expanded lookup path and the optional trusted boundary it must remain within after symbolic links are resolved. ## Inheritance `LittleGhost::Lookup::Root < Data` ## Attributes ### `boundary` (R) The expanded containment boundary, or `nil` when none was supplied. ### `path` (R) The expanded lookup path. ## Class methods ### `.new` ```ruby new(path:, boundary: nil) -> Root ``` Expands `path` and the optional `boundary` without resolving symbolic links. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP.md # Module LittleGhost::MCP Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP.html MCP lets LittleGhost agents use tools published by Model Context Protocol servers. Require `little_ghost/mcp` to load the optional HTTP integration. ## Constants ### `PROTOCOL_VERSION` Model Context Protocol version negotiated by Client. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP/Call.md # Class LittleGhost::MCP::Call Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP/Call.html Describes one MCP Tool invocation. It combines the server's Definition, the copied arguments, and the Tool::Binding used to execute the generated Tool. ## Inheritance `LittleGhost::MCP::Call < Data` ## Attributes ### `arguments` (R) Deeply frozen, indifferent-access arguments. ### `binding` (R) The Tool::Binding for the generated Tool instance. ### `context` (R) The RunContext controlling cancellation, deadlines, and working state. ### `definition` (R) The Definition whose `source_name` is sent to the server. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP/Client.md # Class LittleGhost::MCP::Client Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP/Client.html Client is the lower-level interface for loading tools from an MCP server. Most Agents can declare a reusable Toolset instead. Use Client directly when an application needs a custom transport. transport = LittleGhost::MCP::HTTPTransport.new(url: "https://mcp.example/rpc") client = LittleGhost::MCP::Client.new(transport:) client.tools.map(&:tool_name) # => ["search", "fetch"] Tool names are normalized and checked for collisions. LittleGhost limits catalog size, schema complexity, and returned media before creating Tool classes. `tool_mapper` and `result_mapper` use the same Definition, Result, and Call values as Toolset. The server chooses its definitions and results. LittleGhost checks their structure before creating Tools, but the application still chooses which servers and operations an Agent may use. A client and its transport represent one authenticated server session. Create a separate pair for each authenticated user or service identity. Protocol initialization and subsequent requests through one client are serialized; do not share its transport with another client. ## Inheritance `LittleGhost::MCP::Client < Object` ## Class methods ### `.new` ```ruby .new(transport:, name: "mcp", tool_mapper: nil, result_mapper: nil) ``` Uses a transport that responds to `send`. `tool_mapper` receives each generated Tool class and may return a configured class or nil. `result_mapper` receives Result and Call values. Catalog, schema, and media limits use fixed framework defaults. ## Instance methods ### `#call` ```ruby #call(name, arguments, context: nil, binding: Tool::Binding.new) ``` Calls a generated or named Tool and returns the common Tool execution result. Names discovered through #tools resolve to their stored Definition; an undiscovered name is treated as a source name. ### `#tools` ```ruby #tools(context: nil, binding: Tool::Binding.new) ``` Negotiates the protocol when needed, then provides Tool classes for the server's current definitions. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP/Definition.md # Class LittleGhost::MCP::Definition Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP/Definition.html Immutable server-advertised Tool metadata. `source_name` is always the name sent back to the server; `name` is the initially generated model-facing name and may later be customized on the generated Tool class. ## Inheritance `LittleGhost::MCP::Definition < Data` ## Attributes ### `annotations` (R) Deeply frozen MCP tool annotations. ### `description` (R) The model-facing description, including LittleGhost's fallback when the server omitted one. ### `input_schema` (R) The deeply frozen MCP input schema. ### `metadata` (R) Deeply frozen MCP `_meta` object. ### `name` (R) The normalized, optionally prefixed initial model-facing name. ### `output_schema` (R) The optional deeply frozen MCP output schema. ### `raw` (R) A deeply frozen, indifferent-access copy of the complete server definition object. Definition also delegates `[]`, `fetch`, `dig`, and `key?` to this map. ### `source_name` (R) The unmodified server-advertised name used for dispatch. ### `title` (R) The optional human-readable MCP title. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP/HTTPTransport.md # Class LittleGhost::MCP::HTTPTransport Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP/HTTPTransport.html HTTPTransport sends MCP JSON-RPC messages over Streamable HTTP. It applies time and response-size limits and keeps the negotiated MCP session ID. ### Connections and credentials HTTPS is required by default. `allow_insecure_http` is only for a local development endpoint. Scope caller-supplied credential headers to the target server. Response bodies and negotiated session IDs are validated before use. One transport instance retains one negotiated MCP session ID and sends it with later requests. Use one transport and Client for one server and one authenticated user or service identity; never share that pair across tenants. LittleGhost does not send MCP session-termination DELETE requests, so configure server-side expiry or send the cleanup request outside this transport when the server requires explicit session termination. ## Inheritance `LittleGhost::MCP::HTTPTransport < Object` ## Constants ### `DEFAULT_MAX_RESPONSE_BYTES` Default upper bound for one MCP response body (10 MiB). ## Class methods ### `.new` ```ruby .new(url:, headers: {}, timeout: 60, signer: nil, allow_insecure_http: false, max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES) ``` Configures time and response-size limits. `signer`, when supplied, is called with each Net::HTTP request before it is sent. ## Instance methods ### `#send` ```ruby #send(payload, context: nil) ``` Sends one JSON-RPC payload. A RunContext supplies cancellation and a deadline; without it the configured timeout applies. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP/Result.md # Class LittleGhost::MCP::Result Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP/Result.html Represents one MCP Tool result without discarding server fields. Mapping callbacks can inspect normalized content, structured content, metadata, or the complete protocol value. ## Inheritance `LittleGhost::MCP::Result < Data` ## Attributes ### `content` (R) Deeply frozen MCP content blocks. ### `error` (R) Whether the server marked the result with `isError`. ### `metadata` (R) Deeply frozen MCP result `_meta`. ### `raw` (R) A deeply frozen copy of the complete server result object. ### `structured_content` (R) The optional deeply frozen structured result object. ## Instance methods ### `#error?` ```ruby #error?() ``` Whether the server marked the result as an error. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP/SigV4Signer.md # Class LittleGhost::MCP::SigV4Signer Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP/SigV4Signer.html SigV4Signer adds AWS Signature Version 4 authentication to MCP requests. Requires the application-provided `aws-sigv4` gem and uses its normal AWS credentials-provider chain unless one is supplied explicitly. ## Inheritance `LittleGhost::MCP::SigV4Signer < Object` ## Class methods ### `.new` ```ruby .new(service:, region:, credentials_provider: nil) ``` Configures signing for `service` and `region`. ## Instance methods ### `#call` ```ruby #call(request) ``` Signs `request` in place immediately before transport. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP/Toolset.md # Class LittleGhost::MCP::Toolset Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/MCP/Toolset.html Connects one MCP server to an Agent as a reusable Tool provider. Each Agent run gets its own connection. `map_tool` chooses and configures the generated Tool classes; `map_result` converts results that need application-specific handling. class HelpCenterTools < LittleGhost::MCP::Toolset connection url: "https://mcp.example/rpc", timeout: 20 end class CustomerSupportAgent < LittleGhost::Agent tools HelpCenterTools end ## Inheritance `LittleGhost::MCP::Toolset < Object` ## Class methods ### `.connection` ```ruby connection() -> Hash, Proc, nil connection(values) -> Hash connection { |binding| ... } -> Proc ``` Declares a static connection Hash or a block called with the current Tool::Binding. The Hash requires `url` and may include `headers`, `timeout`, `signer`, `allow_insecure_http`, and `max_response_bytes`. ### `.map_result` ```ruby map_result() -> Proc, nil map_result { |result, call:, binding:| ... } -> Proc ``` Maps each immutable MCP::Result. The block receives `call:` and `binding:` keywords and returns any Ruby value or Tool::Result. ### `.map_tool` ```ruby map_tool() -> Proc, nil map_tool { |tool_class, definition:, binding:| ... } -> Proc ``` Maps each generated Tool class. The block receives `definition:` and `binding:` keywords. Return the configured Tool class, or nil to omit it. Changing Tool#tool_name does not change the operation name sent to the MCP server. ### `.on_error` ```ruby on_error() -> Proc, nil on_error { |error, binding:| ... } -> Proc ``` Observes an expected discovery failure caught by `optional true`. Exceptions raised by this callback propagate. ### `.optional` ```ruby optional() -> true or false optional(value) -> true or false ``` Makes expected provider and protocol discovery failures produce no tools. Configuration, cancellation, deadline, and callback failures still propagate. ### `.tools` ```ruby .tools(binding) ``` Generates Tool classes for an Agent's current binding. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/MalformedToolCallError.md # Class LittleGhost::MalformedToolCallError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/MalformedToolCallError.html Raised when a model returns an invalid tool-call representation. ## Inheritance `LittleGhost::MalformedToolCallError < LittleGhost::ProtocolError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Message.md # Class LittleGhost::Message Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Message.html A Message carries one participant's contribution to an agent conversation. Its content can combine text, attachments, tool activity, and model reasoning. Content is normalized into [Content](Content.md) blocks held in a frozen Array. Strings become Content::Text blocks, and hashes use the serialized content shape accepted by Content.normalize. Nested values supplied by the caller are retained rather than defensively copied. message = LittleGhost::Message.new(role: :user, content: "Hello") message.text # => "Hello" ## Inheritance `LittleGhost::Message < Object` ## Constants ### `ROLES` Participant roles accepted by Message.new. ## Attributes ### `content` (R) Participant role, normalized Content blocks, and application metadata. ### `metadata` (R) Participant role, normalized Content blocks, and application metadata. ### `role` (R) Participant role, normalized Content blocks, and application metadata. ## Class methods ### `.coerce` ```ruby .coerce(value) ``` Keeps `value` when it is already a message, or creates a message from a hash with string or symbol keys. ### `.new` ```ruby .new(role:, content:, metadata: {}) ``` Creates a frozen message with a supported `role`, normalized `content`, and application-defined `metadata`. Metadata becomes a frozen DataMap, so String and Symbol keys address the same JSON-compatible value. ## Instance methods ### `#text` ```ruby #text() ``` Joins the visible text blocks without including reasoning or tool content. ### `#to_h` ```ruby #to_h() ``` Produces the JSON-safe message representation. ### `#to_json` ```ruby #to_json(*arguments) ``` Encodes #to_h as JSON, forwarding generator `arguments`. ### `#without_reasoning` ```ruby #without_reasoning() ``` Removes Content::Reasoning blocks, or keeps `self` when none are present. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/MissingPromptLocalError.md # Class LittleGhost::MissingPromptLocalError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/MissingPromptLocalError.html Raised when an ERB template references a missing local variable. ## Inheritance `LittleGhost::MissingPromptLocalError < LittleGhost::PromptTemplateError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/MissingPromptTemplateError.md # Class LittleGhost::MissingPromptTemplateError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/MissingPromptTemplateError.html Raised when no configured root contains the requested template. ## Inheritance `LittleGhost::MissingPromptTemplateError < LittleGhost::PromptTemplateError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Model.md # Class LittleGhost::Model Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Model.html Model is the resolved connection between an agent selection and a provider. It keeps provider behavior behind one executable interface whether an agent selected a role, canonical target, or inline configuration. It merges profile settings into every ModelRequest, validates attachment modalities declared in metadata, lets providers prepare capability-sensitive requests, and delegates the normalized stream to the provider. ## Inheritance `LittleGhost::Model < Object` ## Includes - `LittleGhost::ModelInterface` ## Attributes ### `details` (R) Provider object, canonical target, default settings, normalized model details, and logical application role. ### `provider` (R) Provider object, canonical target, default settings, normalized model details, and logical application role. ### `role` (R) Provider object, canonical target, default settings, normalized model details, and logical application role. ### `settings` (R) Provider object, canonical target, default settings, normalized model details, and logical application role. ### `target` (R) Provider object, canonical target, default settings, normalized model details, and logical application role. ## Class methods ### `.new` ```ruby .new(provider:, target:, settings: {}, details: nil, role: nil) ``` Connects a provider adapter to its canonical `target`, profile `settings`, optional model `details`, and logical `role`. ## Instance methods ### `#capabilities` ```ruby #capabilities() ``` Uses advertised provider capabilities. ### `#model_id` ```ruby #model_id() ``` Provider-owned identifier from the canonical target. ### `#stream` ```ruby #stream(request, &block) ``` Streams `request` through the configured provider. Profile settings are defaults; settings on `request` take precedence. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ModelCapabilities.md # Class LittleGhost::ModelCapabilities Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ModelCapabilities.html Describes the optional features a model can use. Providers expose this value so structured results and tool selection do not rely on provider guesswork. A `nil` supported-parameter list means the list itself is unrestricted. Check `known?` before treating that as known provider support. ## Inheritance `LittleGhost::ModelCapabilities < Data` ## Attributes ### `known` (R) Whether this value represents known capability metadata. ### `native_structured_output` (R) Whether the model accepts a provider-native structured-output schema. ### `supported_parameters` (R) A frozen Array of provider parameter-name Strings, or `nil` when support is unrestricted. Caller-supplied Strings may be retained rather than copied. ### `tool_choice` (R) Whether the model accepts an explicit tool-selection policy. ### `tools` (R) Whether the model accepts tool definitions. ## Class methods ### `.new` ```ruby new(native_structured_output: false, tools: false, tool_choice: false, supported_parameters: nil, known: true) -> ModelCapabilities ``` Normalizes flags to booleans and stores unique parameter-name Strings in a frozen Array. ### `.permissive` ```ruby .permissive() ``` Supplies a permissive capability set for providers that accept every optional model feature. ### `.unknown` ```ruby .unknown() ``` Marks capability support as unknown so callers avoid assuming support. ## Instance methods ### `#known?` ```ruby #known?() ``` Indicates whether capability metadata is known. ### `#native_structured_output?` ```ruby #native_structured_output?() ``` Indicates whether provider-native structured output is available. ### `#supports_parameter?` ```ruby supports_parameter?(*names) -> boolean ``` Checks only the parameter-list restriction. It returns true for every name when the list is `nil`, including on an unknown capability value. Check `known?` when the caller needs evidence of provider support. ### `#tool_choice?` ```ruby #tool_choice?() ``` Indicates whether the model accepts an explicit tool choice. ### `#tools?` ```ruby #tools?() ``` Indicates whether the model accepts tools. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ModelInterface.md # Module LittleGhost::ModelInterface Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ModelInterface.html Interface for executable model implementations accepted by agents. ## Instance methods ### `#capabilities` ```ruby #capabilities() ``` Normalized feature support used for request strategy selection. ### `#details` ```ruby #details() ``` Immutable capabilities, limits, modalities, and pricing facts. ### `#model_id` ```ruby #model_id() ``` Provider-owned model identifier without the connection name. ### `#role` ```ruby #role() ``` Logical application role that selected this model, when available. ### `#target` ```ruby #target() ``` Canonical physical provider and model identifier. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ModelRequest.md # Class LittleGhost::ModelRequest Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ModelRequest.html Carries everything a provider needs for one model stream. Messages are normalized to Message objects, and required capabilities become unique symbols. The main request containers are frozen, but nested values are not defensively copied. Treat settings, output schemas, and tool-choice values as immutable after construction. Create a separate copy before using mutable control data in another request or thread. ## Inheritance `LittleGhost::ModelRequest < Data` ## Attributes ### `cancellation_token` (R) The cooperative cancellation token shared with the provider. ### `deadline` (R) The absolute request deadline, or `nil` when none was configured. ### `messages` (R) The normalized conversation in a frozen Array. ### `output_schema` (R) The requested structured-output schema, or `nil` for ordinary text. The caller-owned value is retained and must not be mutated afterward. ### `required_capabilities` (R) The normalized capabilities the selected model must support. ### `settings` (R) Trusted provider settings in the caller's now-frozen Hash. Nested values remain mutable and must not change after construction. ### `tool_choice` (R) The requested tool-selection policy, when one applies. The caller-owned value is retained and must not be mutated afterward. ### `tools` (R) The model-visible tool specifications in a frozen Array. ## Class methods ### `.new` ```ruby new(messages:, tools: [], settings: {}, output_schema: nil, tool_choice: nil, required_capabilities: [], cancellation_token: Support::CancellationToken.new, deadline: nil) -> ModelRequest ``` Creates one normalized provider request with cooperative cancellation and deadline controls. Freezing is shallow; retained nested control values must not be mutated afterward. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ModelResolver.md # Class LittleGhost::ModelResolver Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ModelResolver.html Maps an application model role to an executable Model. resolver = LittleGhost::ModelResolver.new( profiles: { customer_support: {target: "openrouter:openai/gpt-5.6-luna"} } ) # With OPENROUTER_API_KEY set: model = resolver.resolve(:customer_support) A role is an application-facing name such as `:customer_support`. Callers may also pass a `provider:model-id` target or an inline configuration mapping. ## Inheritance `LittleGhost::ModelResolver < Object` ## Attributes ### `catalog` (R) Provider configuration and model metadata catalog. ### `default_model` (R) Logical role used when an agent does not declare one. ### `providers` (R) Provider configuration and model metadata catalog. ## Class methods ### `.new` ```ruby .new(providers: nil, profiles: nil, default_model: nil, provider_registry: ProviderRegistry.new, catalog: nil, catalog_sources: [], provider_adapters: {}, credential_resolver: nil) ``` Builds a resolver from explicit provider connections and profiles. With neither, conventional credentials select GPT-5.6 Luna. ## Instance methods ### `#details` ```ruby #details(target) ``` Returns normalized metadata for `target` without constructing a provider. ### `#refresh!` ```ruby #refresh!(target: nil) ``` Refreshes configured metadata sources, retaining stale data on failure. ### `#resolve` ```ruby #resolve(selection, invocation: nil, context: nil, profiles: nil, **options) ``` Resolves a logical role, canonical target, or inline model mapping into an executable Model. Inline mappings require `provider` and `model`; remaining entries are trusted model settings. The optional `profiles` mapping applies only to role selections and is never read from `invocation`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ModelResponse.md # Class LittleGhost::ModelResponse Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ModelResponse.html Represents the final result shared by every provider stream. It keeps provider-specific response shapes out of the agent loop. ## Inheritance `LittleGhost::ModelResponse < Data` ## Attributes ### `message` (R) The normalized assistant Message. ### `metadata` (R) Provider-specific response metadata with a frozen outer Hash. Nested values are retained and must not be mutated by callers. ### `stop_reason` (R) The normalized reason the model stopped. ### `usage` (R) Provider-independent token usage for this response. ## Class methods ### `.new` ```ruby new(message:, stop_reason:, usage: Usage.new, metadata: {}) -> ModelResponse ``` Coerces `message` to Message, normalizes `stop_reason` to a Symbol, and freezes the outer `metadata` Hash. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Models.md # Module LittleGhost::Models Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Models.html Immutable model identities, metadata, configuration readers, and catalogs. ## Constants ### `Details` Immutable normalized facts about one physical model. ### `Target` Identifies one physical model through a named provider connection. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Models/Catalog.md # Class LittleGhost::Models::Catalog Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Models/Catalog.html Resolves model facts from refreshed data and the snapshot packaged with LittleGhost. Refresh is always explicit. ## Inheritance `LittleGhost::Models::Catalog < Object` ## Constants ### `SNAPSHOT_PATH` Path to the offline model metadata snapshot packaged with the gem. ## Class methods ### `.new` ```ruby .new(sources: [], snapshot_path: SNAPSHOT_PATH, clock: -> { Time.now.utc }) ``` Builds a layered catalog from bundled and refreshed facts. ## Instance methods ### `#details` ```ruby #details(target) ``` Returns immutable normalized details for `target`. ### `#refresh!` ```ruby #refresh!(target: nil) ``` Refreshes one target or all models. Failed sources leave the last good catalog untouched and are returned to the caller for reporting. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Models/Catalog/ModelsDevSource.md # Class LittleGhost::Models::Catalog::ModelsDevSource Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Models/Catalog/ModelsDevSource.html Refreshes normalized facts from the public models.dev catalog. ## Inheritance `LittleGhost::Models::Catalog::ModelsDevSource < Source` ## Class methods ### `.new` ```ruby .new(provider_adapters:) ``` Creates a source that maps application provider names to adapters. ## Instance methods ### `#refresh` ```ruby #refresh(target: nil) ``` Fetches normalized model facts, optionally for one canonical `target`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Models/Catalog/Source.md # Class LittleGhost::Models::Catalog::Source Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Models/Catalog/Source.html Interface for catalog refresh implementations. ## Inheritance `LittleGhost::Models::Catalog::Source < Object` ## Attributes ### `name` (R) Stable provenance name recorded for refreshed facts. ## Class methods ### `.new` ```ruby .new(name:) ``` Creates a source with its provenance `name`. ## Instance methods ### `#attribute_merge_strategies` ```ruby #attribute_merge_strategies() ``` Returns exceptional attribute merge strategies for records from this source. Attributes replace older values unless an array is mapped to `:union`. ### `#refresh` ```ruby #refresh(target: nil) ``` Returns normalized model records, optionally scoped to `target`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Models/Configuration.md # Class LittleGhost::Models::Configuration Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Models/Configuration.html Loads trusted provider connections or logical model profiles from YAML. ## Inheritance `LittleGhost::Models::Configuration < Object` ## Class methods ### `.models` ```ruby .models(path) ``` Loads model profiles and an optional default role from `path`. ### `.providers` ```ruby .providers(path) ``` Loads provider connections from `path`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Network.md # Module LittleGhost::Network Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Network.html Network policy helpers used by sandbox backends. These controls apply only to processes launched through the sandbox, not to providers or Ruby Tools. A proxy enforces policy only when the Sandbox blocks every direct socket path. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Network/Decision.md # Class LittleGhost::Network::Decision Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Network/Decision.html Trusted authorization result and tightly scoped upstream header changes. ## Inheritance `LittleGhost::Network::Decision < Data.define(:allowed, :status, :reason, :set_headers, :remove_headers)` ## Class methods ### `.allow` ```ruby .allow(set_headers: {}, remove_headers: []) ``` Allows a request and optionally changes its upstream headers. ### `.deny` ```ruby .deny(status: 403, reason: nil) ``` Rejects a request with an HTTP `status` and optional safe reason. ### `.new` ```ruby .new(allowed:, status:, reason: nil, set_headers: {}, remove_headers: []) ``` Builds a normalized trusted authorization decision. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Network/EnvoyGateway.md # Class LittleGhost::Network::EnvoyGateway Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Network/EnvoyGateway.html Manages Envoy as a native process or pinned Docker sidecar for one Sandbox. CONNECT policy sees destinations, not encrypted request details. Optional HTTP inspection changes the child trust configuration and may not work for clients with certificate pinning or custom trust stores. The Sandbox must block direct sockets for either mode to be an enforcement boundary. ## Inheritance `LittleGhost::Network::EnvoyGateway < LittleGhost::Network::Gateway` ## Attributes ### `client_network` (R) Internal Docker network exposed only to sandbox clients, when used. ### `proxy_socket` (R) Host path of the explicit proxy's Unix socket, when used. ### `runtime` (R) Configured runtime selector: `:auto`, `:native`, or `:docker`. ## Class methods ### `.new` ```ruby .new(policy:, runtime: :auto, transport: :unix, envoy: "envoy", docker: "docker", image: ENVOY_IMAGE, pull: :if_missing, dns: []) ``` Builds a run-scoped Envoy gateway. Envoy remains an optional external dependency and the Docker image is pinned by digest by default. ## Instance methods ### `#close` ```ruby #close() ``` Removes the process, containers, networks, sockets, and trust material. ### `#environment` ```ruby #environment() ``` Returns proxy variables and, for inspection, child-scoped trust paths. ### `#mounts` ```ruby #mounts() ``` Returns the gateway files that must be mounted into the sandbox. ### `#open` ```ruby #open(run: nil) ``` Creates configuration, trust material, and the Envoy process. ### `#proxy_mount_path` ```ruby #proxy_mount_path() ``` Returns the proxy socket's stable path inside a mounted sandbox. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Network/ExternalGateway.md # Class LittleGhost::Network::ExternalGateway Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Network/ExternalGateway.html Exposes an application-managed proxy to an isolated sandbox without claiming ownership of its lifecycle or attesting what it enforces. The application owns proxy policy, credentials, readiness, logging, and cleanup. ## Inheritance `LittleGhost::Network::ExternalGateway < LittleGhost::Network::Gateway` ## Attributes ### `environment` (R) Returns child-scoped proxy and trust variables. ### `proxy_mount_path` (R) Returns the proxy socket path visible inside the sandbox. ### `runtime_paths` (R) Named process-only workspace paths used by the gateway. ## Class methods ### `.new` ```ruby .new(policy:, workspace:, runtime_paths:, proxy_mount_path:, environment: {}, validate: nil) ``` Builds a gateway around existing process-only workspace paths and a physical proxy socket path. No path remapping is performed. ## Instance methods ### `#open` ```ruby #open(run: nil) ``` Pins application-managed mount roots without taking lifecycle ownership. ### `#validate!` ```ruby #validate!() ``` Runs the application's readiness assertion before each child process. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Network/Gateway.md # Class LittleGhost::Network::Gateway Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Network/Gateway.html Lifecycle contract implemented by filtered-egress gateways. A Gateway is one part of enforcement; the Sandbox must also prevent direct networking. ## Inheritance `LittleGhost::Network::Gateway < Object` ## Attributes ### `policy` (R) Network policy enforced by this gateway. ## Class methods ### `.new` ```ruby .new(policy:) ``` Builds a gateway for a normalized network `policy`. ## Instance methods ### `#client_network` ```ruby #client_network() ``` Returns an isolated container network name when applicable. ### `#close` ```ruby #close() ``` Stops owned resources. Calling `close` more than once must be safe. ### `#environment` ```ruby #environment() ``` Returns child-process proxy and trust environment variables. ### `#mounts` ```ruby #mounts() ``` Returns read-only mounts required by child processes. ### `#open` ```ruby #open(run: nil) ``` Starts run-scoped gateway resources. ### `#validate!` ```ruby #validate!() ``` Fails closed when the gateway is no longer ready for a child process. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Network/Request.md # Class LittleGhost::Network::Request Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Network/Request.html Normalized, headers-only request metadata passed to a trusted authorizer. ## Inheritance `LittleGhost::Network::Request < Data.define(:method, :scheme, :host, :port, :path, :headers)` ## Class methods ### `.new` ```ruby .new(method:, scheme:, host:, port:, path:, headers: {}) ``` Builds normalized request metadata without a body. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/OutputLimitError.md # Class LittleGhost::OutputLimitError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/OutputLimitError.html Raised when configured generation limits stop the agent before completion. ## Inheritance `LittleGhost::OutputLimitError < LittleGhost::ProtocolError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/PathSet.md # Class LittleGhost::PathSet Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/PathSet.html PathSet keeps prompt or skill lookup roots in deterministic search order. It is immutable, so appending a path does not change a running configuration. ## Inheritance `LittleGhost::PathSet < Object` ## Includes - `Enumerable` ## Attributes ### `paths` (R) The immutable Lookup::Root values in search order. ## Class methods ### `.new` ```ruby .new(paths = []) ``` Accepts path strings and Lookup::Root objects. ## Instance methods ### `#+` ```ruby #+(other) ``` Appends `other` in a new path set; neither input is mutated. ### `#each` ```ruby #each(&block) ``` Yields each Lookup::Root in order. ### `#to_a` ```ruby #to_a() ``` Copies the roots into a mutable array. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/PolicyError.md # Class LittleGhost::PolicyError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/PolicyError.html Raised when a sandbox policy is internally invalid. ## Inheritance `LittleGhost::PolicyError < LittleGhost::SandboxConfigurationError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/PromptResolver.md # Class LittleGhost::PromptResolver Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/PromptResolver.html PromptResolver turns conventional ERB files into an agent's system prompt. It supports ordered application roots and partials without allowing a template name to escape those roots. resolver = LittleGhost::PromptResolver.new(paths: ["app/prompts"]) prompt = resolver.render("support/system", locals: {product: "Acme"}) prompt.include?("Acme") # => true In `support/system.erb`: <%= partial "shared/rules", locals: {product: product} %> Earlier invocation roots override configured roots. Template names must be relative, and both lexical traversal and symbolic-link escapes are rejected. Partials use an underscore-prefixed filename and receive only their explicitly supplied locals. Every configured root is trusted Ruby code because ERB executes inside the current process. Keep roots application-controlled and non-user-writable. See the [Prompts as Views guide](../prompt_views.md) for the conventional Agent workflow. ## Inheritance `LittleGhost::PromptResolver < Object` ## Class methods ### `.new` ```ruby .new(paths: [], max_depth: DEFAULT_MAX_DEPTH) ``` Configures ordered application roots and a partial recursion bound, which defaults to 20 nested templates. ## Instance methods ### `#render` ```ruby #render(name, locals: {}, invocation_paths: []) ``` Renders `name` with validated local variables. `invocation_paths` accepts only TrustedPath values because those roots take precedence over application configuration. The wrapper records the directory selected by application code; it does not inspect who can modify that directory. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/PromptTemplateError.md # Class LittleGhost::PromptTemplateError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/PromptTemplateError.html Base error raised while locating or rendering a prompt template. ## Inheritance `LittleGhost::PromptTemplateError < LittleGhost::Error` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ProtocolError.md # Class LittleGhost::ProtocolError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ProtocolError.html Raised when a provider violates the expected request-response protocol. ## Inheritance `LittleGhost::ProtocolError < LittleGhost::ProviderError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ProviderError.md # Class LittleGhost::ProviderError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ProviderError.html Base class for provider request, response, and protocol failures. Agent Runs normally record these as failed outcomes; provider retry policy may handle a retryable failure before it reaches the Run. ## Inheritance `LittleGhost::ProviderError < LittleGhost::Error` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ProviderRegistry.md # Class LittleGhost::ProviderRegistry Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ProviderRegistry.html Constructs built-in and application provider adapters from named provider connections. Register adapters during application configuration. ## Inheritance `LittleGhost::ProviderRegistry < Object` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers.md # Module LittleGhost::Providers Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers.html Provider adapters translate model APIs into LittleGhost's shared streaming request and response types. Agents select them through model configuration rather than depending on a provider class directly. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Anthropic.md # Class LittleGhost::Providers::Anthropic Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Anthropic.html Connects a Model to Anthropic's Messages API. Requests send messages, Tool definitions, attachments, and model settings to the configured Anthropic endpoint. The adapter reads its credential from trusted configuration, honors cancellation and deadlines, and emits LittleGhost StreamEvents. HTTP and response-shape failures become ProviderError subclasses. It uses the built-in HTTP client and does not require Anthropic's SDK. ## Inheritance `LittleGhost::Providers::Anthropic < Base` ## Attributes ### `model` (R) Provider-owned model identifier. ## Class methods ### `.new` ```ruby .new(api_key:, model:, base_url: DEFAULT_BASE_URL, api_version: "2023-06-01", open_timeout: 10, read_timeout: 120, max_response_bytes: Support::HTTPClient::DEFAULT_MAX_RESPONSE_BYTES, transport: nil, **) ``` Creates an Anthropic Messages client for `model`. ### `.request_options` ```ruby .request_options() ``` Request policy supported by the Anthropic HTTP client. ## Instance methods ### `#capabilities` ```ruby #capabilities(metadata: {}) ``` Reports tool and structured-output support from model metadata. ### `#stream` ```ruby #stream(request) ``` Streams normalized events for `request`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Anthropic/CatalogSource.md # Class LittleGhost::Providers::Anthropic::CatalogSource Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Anthropic/CatalogSource.html Enriches availability and limits from Anthropic's model list endpoint. ## Inheritance `LittleGhost::Providers::Anthropic::CatalogSource < LittleGhost::Models::Catalog::Source` ## Class methods ### `.new` ```ruby .new(provider:, credential_resolver:) ``` Creates a source for the named provider connection. ## Instance methods ### `#refresh` ```ruby #refresh(target: nil) ``` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Base.md # Class LittleGhost::Providers::Base Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Base.html Shared provider contract. Provider adapters implement #stream and may override capability-sensitive request preparation. ## Inheritance `LittleGhost::Providers::Base < Object` ## Class methods ### `.request_options` ```ruby .request_options() ``` Returns the trusted per-profile request options this adapter accepts. Connection options remain authoritative and are configured separately. ## Instance methods ### `#capabilities` ```ruby #capabilities(metadata: {}) ``` Returns provider capabilities derived from normalized metadata. ### `#prepare_request` ```ruby #prepare_request(request, capabilities:) ``` Applies provider-specific capability constraints before streaming. ### `#stream` ```ruby #stream(_request) ``` Streams normalized events for `request`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Bedrock.md # Class LittleGhost::Providers::Bedrock Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Bedrock.html Bedrock lets LittleGhost agents use models available through Amazon Bedrock Converse. Its output follows the same streaming events as every other LittleGhost provider. provider = LittleGhost::Providers::Bedrock.new( model: ENV.fetch("BEDROCK_MODEL_ID"), region: ENV.fetch("AWS_REGION") ) The default client uses LittleGhost's standard-library SigV4 and AWS EventStream implementations. Applications may inject `client` instead. Transient service and stream failures retry with exponential backoff. Each retry emits `:model_retry` and reports whether partial text was already emitted, allowing stream consumers to handle repeated output deliberately. ## Inheritance `LittleGhost::Providers::Bedrock < LittleGhost::Providers::Base` ## Attributes ### `model` (R) Bedrock model identifier used for requests. ## Class methods ### `.new` ```ruby .new(model:, region: nil, client: nil, max_retries: 2, sleeper: nil, on_retry: ->(*) {}, **client_options) ``` Configures Bedrock for `model`. `region` and remaining `client_options` configure the built-in HTTP client. `max_retries`, `sleeper`, and `on_retry` control retry behavior. Injecting `client` bypasses creation of the built-in HTTP client. ### `.request_options` ```ruby .request_options() ``` Request policy supported by Bedrock retries and its built-in HTTP client. ## Instance methods ### `#capabilities` ```ruby #capabilities(metadata: {}) ``` Reads capabilities from Bedrock `supported_parameters` metadata. Missing metadata produces ModelCapabilities.unknown. ### `#stream` ```ruby #stream(request) ``` Streams LittleGhost StreamEvent objects for `request`. Without a block, returns an Enumerator. Context-window failures normalize to ContextWindowOverflowError and malformed tool calls normalize to MalformedToolCallError. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Bedrock/CatalogSource.md # Class LittleGhost::Providers::Bedrock::CatalogSource Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Bedrock/CatalogSource.html Enriches Bedrock availability and on-demand pricing using bounded, SigV4-signed AWS APIs. ## Inheritance `LittleGhost::Providers::Bedrock::CatalogSource < LittleGhost::Models::Catalog::Source` ## Class methods ### `.new` ```ruby .new(provider:, region:, credential_resolver: nil, clock: -> { Time.now.utc }, http_client: nil) ``` Creates a source for one Bedrock provider connection and AWS region. ## Instance methods ### `#attribute_merge_strategies` ```ruby #attribute_merge_strategies() ``` AWS reports a coarse subset of Converse input capabilities, so live modalities augment richer facts supplied by another catalog source. ### `#refresh` ```ruby #refresh(target: nil) ``` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Bedrock/CredentialResolver.md # Class LittleGhost::Providers::Bedrock::CredentialResolver Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Bedrock/CredentialResolver.html Resolves common AWS credentials without depending on an AWS SDK. ## Inheritance `LittleGhost::Providers::Bedrock::CredentialResolver < Object` ## Class methods ### `.new` ```ruby .new(environment: ENV, profile: nil, credentials_file: nil) ``` Uses `environment` and the selected shared-credentials `profile`. ## Instance methods ### `#call` ```ruby #call() ``` Returns the first complete credential set from the environment, shared credentials, container metadata, or IMDSv2. ### `#region` ```ruby #region() ``` Returns the configured AWS region, when one can be resolved. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Bedrock/StreamError.md # Class LittleGhost::Providers::Bedrock::StreamError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Bedrock/StreamError.html Represents an error event returned inside a Bedrock stream. ## Inheritance `LittleGhost::Providers::Bedrock::StreamError < LittleGhost::ProviderError` ## Attributes ### `event_type` (R) Normalized Bedrock event type used to decide whether a retry is safe. ## Class methods ### `.new` ```ruby .new(message, event_type:) ``` Creates a stream error for `event_type`. ## Instance methods ### `#retryable?` ```ruby #retryable?() ``` Indicates whether LittleGhost may retry this Bedrock event. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Configuration.md # Class LittleGhost::Providers::Configuration Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Configuration.html Holds trusted provider connection settings independently from model profiles. Connection names and option keys are normalized to strings, and the resulting mapping is immutable. ## Inheritance `LittleGhost::Providers::Configuration < Object` ## Attributes ### `connections` (R) Normalized provider connections keyed by application-defined name. ## Class methods ### `.new` ```ruby .new(connections = {}) ``` Copies and freezes `connections` so callers may safely reuse their input. ## Instance methods ### `#credentials` ```ruby #credentials(provider:, adapter:, configuration:) ``` Returns credentials merged into `configuration` when `provider` is constructed with `adapter`. Subclasses may resolve secrets lazily here. The base implementation adds no credentials. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Gemini.md # Class LittleGhost::Providers::Gemini Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Gemini.html Connects a Model to Google's Gemini generateContent API. Requests send messages, Tool definitions, attachments, and model settings to the configured Google endpoint. The adapter reads its API key from trusted configuration, honors cancellation and deadlines, and emits LittleGhost StreamEvents. HTTP and response-shape failures become ProviderError subclasses. It uses the built-in HTTP client and does not require Google's SDK. ## Inheritance `LittleGhost::Providers::Gemini < LittleGhost::Providers::Base` ## Attributes ### `model` (R) Provider-owned model identifier. ## Class methods ### `.new` ```ruby .new(api_key:, model:, base_url: DEFAULT_BASE_URL, open_timeout: 10, read_timeout: 120, max_response_bytes: Support::HTTPClient::DEFAULT_MAX_RESPONSE_BYTES, transport: nil, **) ``` Creates a Gemini generateContent client for `model`. ### `.request_options` ```ruby .request_options() ``` Request policy supported by Gemini and Vertex AI HTTP clients. ## Instance methods ### `#capabilities` ```ruby #capabilities(metadata: {}) ``` Reports Tool and structured-output support from model metadata. ### `#stream` ```ruby #stream(request) ``` Streams normalized events for `request`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Gemini/CatalogSource.md # Class LittleGhost::Providers::Gemini::CatalogSource Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/Gemini/CatalogSource.html Enriches Gemini availability and limits from the Developer API. ## Inheritance `LittleGhost::Providers::Gemini::CatalogSource < LittleGhost::Models::Catalog::Source` ## Class methods ### `.new` ```ruby .new(provider:, credential_resolver:) ``` Creates a source for the named provider connection. ## Instance methods ### `#refresh` ```ruby #refresh(target: nil) ``` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/HTTPError.md # Class LittleGhost::Providers::HTTPError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/HTTPError.html Reports a bounded HTTP or network failure from a provider connection. ## Inheritance `LittleGhost::Providers::HTTPError < LittleGhost::ProviderError` ## Attributes ### `body` (R) HTTP status, when a response was received, and the bounded response body. ### `status` (R) HTTP status, when a response was received, and the bounded response body. ## Class methods ### `.new` ```ruby .new(message, status: nil, body: nil) ``` Captures a provider failure without retaining an unbounded response. ## Instance methods ### `#retryable?` ```ruby #retryable?() ``` Whether retrying the same provider request may succeed. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/OpenAI.md # Class LittleGhost::Providers::OpenAI Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/OpenAI.html OpenAI connects LittleGhost agents to OpenAI models with streaming, tools, and structured results. It uses the Responses API by default. provider = LittleGhost::Providers::OpenAI.new( api_key: ENV.fetch("OPENAI_API_KEY"), model: ENV.fetch("OPENAI_MODEL") ) Supply `api: :chat_completions` only when a model or integration requires the Chat Completions wire API. ## Inheritance `LittleGhost::Providers::OpenAI < OpenAICompatible` ## Constants ### `DEFAULT_BASE_URL` The OpenAI API endpoint used when `base_url` is omitted. ## Class methods ### `.new` ```ruby .new(base_url: DEFAULT_BASE_URL, **arguments) ``` Uses the official OpenAI API base URL by default. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/OpenAICompatible.md # Class LittleGhost::Providers::OpenAICompatible Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/OpenAICompatible.html OpenAICompatible brings OpenAI-style Responses or Chat Completions endpoints into LittleGhost. Agents receive the same streaming events whether the endpoint is OpenAI, a hosted model service, or an application gateway. provider = LittleGhost::Providers::OpenAICompatible.new( api_key: ENV.fetch("MODEL_API_KEY"), model: "example-model", base_url: "https://models.example.test/v1/" ) The client translates ModelRequest values to the selected wire API and translates responses back to StreamEvent objects. ### Retries and streaming output Transient HTTP and stream failures retry with limited exponential backoff. A `:model_retry` event reports each retry and whether text had already been emitted. Partial text may repeat after a retry, so consumers that assemble streams must use that event to discard or replace superseded output. ## Inheritance `LittleGhost::Providers::OpenAICompatible < LittleGhost::Providers::Base` ## Constants ### `DEFAULT_BASE_URL` The OpenAI API endpoint used when `base_url` is omitted. ## Attributes ### `api` (R) Provider model identifier and selected OpenAI-compatible wire API. ### `model` (R) Provider model identifier and selected OpenAI-compatible wire API. ## Class methods ### `.new` ```ruby .new(api_key:, model:, base_url: DEFAULT_BASE_URL, api: :responses, headers: {}, open_timeout: 10, read_timeout: 120, allow_insecure_http: false, max_response_bytes: Support::HTTPClient::DEFAULT_MAX_RESPONSE_BYTES, max_retries: 2, max_retry_delay: MAX_RETRY_DELAY, transport: nil, sleeper: nil, on_retry: ->(*) {}) ``` Configures an OpenAI-compatible client. `api` is `:responses` or `:chat_completions`. `headers` adds trusted endpoint-specific headers. `max_retries` controls retries before the original error is raised, and `on_retry` receives the attempt, error, and delay. Pass a custom `transport` for alternate HTTP execution. ### `.request_options` ```ruby .request_options() ``` Request policy supported by OpenAI-compatible HTTP clients. ## Instance methods ### `#capabilities` ```ruby #capabilities(metadata: {}) ``` Returns the permissive capability contract expected from compatible APIs. Subclasses can override this when the endpoint advertises precise support. ### `#stream` ```ruby #stream(request) ``` Streams LittleGhost StreamEvent objects for `request`. Without a block, returns an Enumerator. Context-window errors normalize to ContextWindowOverflowError, and malformed tool calls normalize to MalformedToolCallError. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/OpenAICompatible/StreamError.md # Class LittleGhost::Providers::OpenAICompatible::StreamError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/OpenAICompatible/StreamError.html Represents a structured error received inside an otherwise successful provider stream. ## Inheritance `LittleGhost::Providers::OpenAICompatible::StreamError < LittleGhost::ProviderError` ## Attributes ### `code` (R) Normalized provider error type and optional provider code. ### `error_type` (R) Normalized provider error type and optional provider code. ## Class methods ### `.new` ```ruby .new(message, error_type: nil, code: nil) ``` Creates a structured stream error. ## Instance methods ### `#retryable?` ```ruby #retryable?() ``` Indicates whether LittleGhost may retry this provider error. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/OpenRouter.md # Class LittleGhost::Providers::OpenRouter Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/OpenRouter.html OpenRouter gives one LittleGhost provider access to models routed through OpenRouter. Agents may select an OpenRouter target directly or keep a logical role while shared configuration selects its physical model. provider = LittleGhost::Providers::OpenRouter.new( api_key: ENV.fetch("OPENROUTER_API_KEY"), model: ENV.fetch("OPENROUTER_MODEL"), app_name: "Support Console" ) `site_url` and `app_name` populate attribution headers. Capability metadata controls structured output, tools, tool choice, and parameter filtering. Requests that need a capability ask OpenRouter to route only to providers that advertise it. ## Inheritance `LittleGhost::Providers::OpenRouter < OpenAICompatible` ## Constants ### `DEFAULT_BASE_URL` The OpenRouter API endpoint used when `base_url` is omitted. ## Class methods ### `.new` ```ruby .new(site_url: nil, app_name: nil, base_url: DEFAULT_BASE_URL, **arguments) ``` Configures an OpenRouter client. All OpenAICompatible options, including `api_key`, `model`, retry limits, timeouts, and custom transport, apply. ### `.request_options` ```ruby .request_options() ``` Adds OpenRouter attribution to the shared OpenAI-compatible policy. ## Instance methods ### `#capabilities` ```ruby #capabilities(metadata: {}) ``` Reads model capabilities from OpenRouter `supported_parameters` metadata. Missing metadata produces ModelCapabilities.unknown. ### `#prepare_request` ```ruby #prepare_request(request, capabilities:) ``` Filters unsupported model settings when the request requires advertised capabilities. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/OpenRouter/CatalogSource.md # Class LittleGhost::Providers::OpenRouter::CatalogSource Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/OpenRouter/CatalogSource.html Adds richer routing metadata and pricing from OpenRouter's live catalog. ## Inheritance `LittleGhost::Providers::OpenRouter::CatalogSource < LittleGhost::Models::Catalog::Source` ## Class methods ### `.new` ```ruby .new(provider:, credential_resolver:) ``` Creates a source for the named provider connection. ## Instance methods ### `#refresh` ```ruby #refresh(target: nil) ``` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/VertexAI.md # Class LittleGhost::Providers::VertexAI Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/VertexAI.html Connects a Model to Gemini models hosted by Google Vertex AI. It sends the same request content as the Gemini adapter to the configured Google Cloud project and location. A trusted credential resolver supplies each access token. Cancellation, deadlines, normalized streaming events, and ProviderError behavior match Providers::Gemini. ## Inheritance `LittleGhost::Providers::VertexAI < LittleGhost::Providers::Gemini` ## Class methods ### `.new` ```ruby .new(model:, project:, location: "global", access_token: nil, credential_resolver: nil, base_url: nil, **arguments) ``` Creates a Vertex AI client for a Google Cloud `project` and `location`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/VertexAI/CredentialResolver.md # Class LittleGhost::Providers::VertexAI::CredentialResolver Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Providers/VertexAI/CredentialResolver.html Resolves Vertex access tokens from explicit values, service-account ADC, or the Google metadata server. ## Inheritance `LittleGhost::Providers::VertexAI::CredentialResolver < Object` ## Class methods ### `.new` ```ruby .new(environment: ENV, access_token: nil, clock: -> { Time.now.to_i }) ``` Uses an explicit token or Google application credentials in `environment`. ## Instance methods ### `#call` ```ruby #call(cancellation_token: nil, deadline: nil) ``` Returns a current access token, refreshing cached credentials as needed. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/RunContext.md # Class LittleGhost::RunContext Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/RunContext.html RunContext gives tools and workflows one place for shared state, cancellation, deadlines, checkpoints, and accumulated usage. It travels with work inside a run without becoming global process state. Tools and workflows use it to share JSON-like state, check cancellation and deadlines, checkpoint messages, and accumulate usage. Framework-managed fields remain safe when calls overlap on threads or fibers. ## Inheritance `LittleGhost::RunContext < Object` ## Attributes ### `agent_operation_id` (R) Active Agent operation identifier, after the context is bound. ### `cancellation_token` (R) Token used to cooperatively stop the current work. ### `conversation_id` (R) Durable subagent conversation identifier, when present. ### `deadline` (R) Wall-clock deadline for the current work, when present. ### `metadata` (R) Framework metadata attached to this context. ### `state` (R) Mutable DataMap state supplied to this invocation. A top-level Run starts with restored Session state merged with current Invocation context; child Assemblies may receive copied, mapped, or empty state. Application code must synchronize mutations when parallel Tools share this map, or use exclusive Tools. String and Symbol keys address the same value; persisted snapshots use canonical String keys. ## Class methods ### `.new` ```ruby .new(state: {}, cancellation_token: Support::CancellationToken.new, deadline: nil, metadata: {}, checkpoint: nil, conversation_id: nil, interjection_metadata: nil, interjection_ids: []) ``` Creates a context with optional checkpoint and interjection state. ## Instance methods ### `#check!` ```ruby #check!() ``` Raises LittleGhost::CancelledError or LittleGhost::DeadlineExceededError when execution should stop. ### `#checkpoint` ```ruby #checkpoint(messages) ``` Sends `messages` and current state to the configured checkpoint callback. With no checkpoint callback, this method does nothing and returns `nil`. ### `#record_usage` ```ruby #record_usage(value) ``` Adds `value` to accumulated model usage. ### `#remaining_time` ```ruby #remaining_time(maximum = nil) ``` Calculates seconds remaining before the deadline. When `maximum` is provided, the result is capped at that value. With no deadline, returns `maximum`. ### `#structured_result` ```ruby #structured_result() ``` Finds the latest validated structured result, if any. ### `#submit_structured_result` ```ruby #submit_structured_result(result) ``` Stores a validated LittleGhost::StructuredResult and returns it. ### `#usage` ```ruby #usage() ``` Takes a snapshot of accumulated usage. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/RunResult.md # Class LittleGhost::RunResult Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/RunResult.html RunResult gives callers one final view of an Assembly invocation. It includes the response, usage, updated conversation, state, coordination steps, and any validated structured value. Use #output when the caller should accept either structured or textual agents. It returns the validated structured value when present and #text otherwise. ## Inheritance `LittleGhost::RunResult < Data` ## Attributes ### `message` (R) The final assistant Message, or `nil` when no message was produced. ### `messages` (R) The complete, updated conversation. ### `state` (R) The application state at the end of the invocation. ### `steps` (R) Immutable Assembly::Step records for composite invocations. ### `stop_reason` (R) The normalized reason the terminal model stream stopped. ### `structured_result` (R) The validated StructuredResult, or `nil` for a textual result. ### `usage` (R) The Usage accumulated across this invocation. ## Class methods ### `.new` ```ruby new(message:, stop_reason:, usage:, messages:, state:, structured_result: nil, steps: []) -> RunResult ``` Creates the terminal value for one Assembly invocation. ## Instance methods ### `#output` ```ruby #output() ``` Uses the structured value when present and otherwise #text. ### `#structured?` ```ruby #structured?() ``` Indicates whether the invocation produced a validated structured result. ### `#text` ```ruby #text() ``` Reads the final message text, or an empty string when no message exists. ### `#trajectory` ```ruby #trajectory() ``` Returns an Assembly::Trajectory for querying immutable coordination steps. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Runtime/Hook.md # Class LittleGhost::Runtime::Hook Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Runtime/Hook.html Hooks let applications prepare runs, select session history, transform interjections, and map errors to caller-safe messages. Hooks are instantiated once per Runtime in configuration order. Override only the methods needed and return the supplied value when leaving it unchanged. class TenantHook < LittleGhost::Runtime::Hook def prepare_run(run) run.register(TenantConnection.new(run.invocation.actor_id)) run end end ## Inheritance `LittleGhost::Runtime::Hook < Object` ## Instance methods ### `#error_message` ```ruby #error_message(_error, _run) ``` Returns a caller-safe error message, or nil to defer to later hooks and the runtime default. Avoid exposing secrets or internal exception text. ### `#prepare_execution` ```ruby #prepare_execution(run) ``` Prepares a Run after its Workspace and Sandbox have opened, but before session history or the entrypoint Agent is built. Hooks may safely store run-scoped files here. ### `#prepare_interjection` ```ruby #prepare_interjection(_run, payload) ``` Transforms an interjection payload before it reaches the agent. ### `#prepare_run` ```ruby #prepare_run(run) ``` Prepares a newly built Run. Resources registered on the run share its lifecycle and close in reverse order. ### `#session_history` ```ruby #session_history(_run, stored:, fallback:) ``` Returns the history to use for this run, or nil to defer to later hooks and the session default. `stored` is empty when the session is new; `fallback` contains messages supplied by the invocation. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox.md # Class LittleGhost::Sandbox Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox.html A Sandbox governs filesystem operations and child processes that explicitly pass through it. Built-in filesystem and shell Tools use their bound Sandbox. A custom Ruby Tool remains trusted application code unless it delegates work to that Sandbox or one of its Scopes. LittleGhost.configure do |config| config.sandbox = { provider: :native, files: {root: :read_write, source: :read_only}, runtime_paths: {home: :read_write}, network: :none } end A backend reports the policy and capabilities it actually enforces. File operations stay within declared Workspace paths. Process operations honor cancellation and configured limits, then return an [Execution](Sandbox/Execution.md). A backend's isolation mechanism still relies on its outer host, kernel or VM, dependencies, trusted configuration, and deliberately exposed paths. Sandbox policy does not apply to provider requests or arbitrary Ruby code in the application process. See the [Workspaces and Sandboxes guide](../sandboxing.md) for the path model, built-in backends, Scopes, process ownership, and networking boundaries. ## Inheritance `LittleGhost::Sandbox < Object` ## Attributes ### `limits` (R) File and process output bounds enforced by this Sandbox. ### `policy` (R) Normalized policy requested by trusted application configuration. ### `workspace` (R) Workspace whose files and processes this sandbox governs. ## Class methods ### `.new` ```ruby .new(workspace:, policy: nil, profiles: {}, limits: {}) ``` Binds the sandbox to `workspace`. ### `.probe` ```ruby .probe(name, **options) ``` Reports whether a registered backend can start in the current environment without creating a Run-owned sandbox. ### `.register_provider` ```ruby .register_provider(name, implementation) ``` Registers a trusted backend class under a configuration symbol. ### `.resolve_provider` ```ruby .resolve_provider(name) ``` Resolves a registered backend without silently falling back. ## Instance methods ### `#allows?` ```ruby #allows?(operation, path = nil) ``` Indicates whether an operation is allowed by this sandbox and optional virtual `path`. ### `#capabilities` ```ruby #capabilities() ``` Operations and network modes implemented by this backend. ### `#close` ```ruby #close() ``` Releases sandbox resources. Runs close the sandbox before its workspace. ### `#effective_policy` ```ruby #effective_policy() ``` Policy the backend enforces. Backends may fill a documented default or report an unavoidable effective value, but reject unsupported requested rules instead of silently claiming enforcement. ### `#execute` ```ruby #execute(command, timeout:, context: nil, max_output_bytes: nil, **options) ``` Executes `command` through `/bin/sh`. Prefer #execute_program for model-controlled arguments so shell syntax is not interpreted. ### `#execute_program` ```ruby #execute_program(command, timeout:, context: nil, max_output_bytes: nil, environment: {}, inherit_environment: false, **options) ``` Executes an argument vector without shell interpretation. Implementations must enforce `timeout` and `max_output_bytes`. Environment inheritance is disabled by default to avoid leaking process credentials; both policy and the individual call must opt in before a backend may inherit. ### `#list` ```ruby #list(path = ".", context: nil) ``` Lists entries at a workspace-relative or absolute virtual directory `path`. ### `#open` ```ruby #open(run: nil) ``` Opens any run-scoped resources and makes the sandbox ready for tools. ### `#read` ```ruby #read(path, context: nil) ``` Reads UTF-8 text at a workspace-relative or absolute virtual `path`. ### `#replace` ```ruby #replace(path, old_text, new_text, context: nil) ``` Replaces one exact `old_text` occurrence at a workspace-relative or absolute virtual `path` with `new_text`. ### `#scope` ```ruby #scope(profile = nil, files: nil, runtime_paths: nil, capabilities: nil, network: nil) ``` Produces a non-owning capability-reduced view for tools or child agents. The caller must pass and use that Scope; retaining this parent Sandbox retains its broader authority. ### `#start_program` ```ruby #start_program(command, context: nil, environment: {}, inherit_environment: false, **options) ``` Starts an owned, duplex child process for framed protocols and other interactive programs. The returned session owns the child process group. ### `#supports?` ```ruby #supports?(feature, value = nil) ``` Indicates whether the backend implements `feature`. ### `#writable?` ```ruby #writable?() ``` Indicates whether filesystem mutation is allowed. ### `#write` ```ruby #write(path, content, context: nil) ``` Writes `content` to a workspace-relative or absolute virtual `path`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/Capabilities.md # Class LittleGhost::Sandbox::Capabilities Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/Capabilities.html Describes the operations, network modes, and isolation mechanism a Sandbox backend implements. `process_spawn` permits child creation, `process_spawn_denial` means the backend can prohibit it for one session, and `process_tree_ownership` means descendants remain owned through cleanup. Capabilities are immutable and safe to expose to tools, but are not a security certification of the surrounding deployment. ## Inheritance `LittleGhost::Sandbox::Capabilities < Object` ## Attributes ### `features` (R) Operation names implemented by the backend. ### `isolation` (R) Descriptive isolation mechanism, such as `:none` or `:container`. ### `network_modes` (R) Network modes the backend can enforce. ## Class methods ### `.new` ```ruby .new(features: DEFAULT_FEATURES, network_modes: [:inherit], isolation: :none) ``` Builds a capability report from feature names and supported network modes. `isolation` is descriptive and does not itself grant an operation or establish a complete trust boundary. ## Instance methods ### `#include?` ```ruby #include?(feature, value = nil) ``` Equivalent to #supports?. ### `#intersect` ```ruby #intersect(other) ``` Produces a capability set no broader than both operands. ### `#supports?` ```ruby #supports?(feature, value = nil) ``` Indicates whether `feature` is available. For `:network`, `value` selects the requested mode. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/EnvironmentPolicy.md # Class LittleGhost::Sandbox::EnvironmentPolicy Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/EnvironmentPolicy.html Declares whether a child inherits the host environment and which explicit values are added or replaced. ## Inheritance `LittleGhost::Sandbox::EnvironmentPolicy < Object` ## Attributes ### `values` (R) Explicit child environment values. ## Class methods ### `.coerce` ```ruby .coerce(value) ``` Returns `value` unchanged or builds a policy from a Hash. ### `.new` ```ruby .new(inherit: false, values: {}) ``` Builds an environment policy with explicit String-compatible `values`. ## Instance methods ### `#inherit?` ```ruby #inherit?() ``` Indicates whether configured backends may inherit host values. ### `#to_h` ```ruby #to_h() ``` Returns the explicit child environment values. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/Execution.md # Class LittleGhost::Sandbox::Execution Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/Execution.html Carries captured process output, exit status, and an optional execution error from Sandbox#execute or Sandbox#execute_program. ## Inheritance `LittleGhost::Sandbox::Execution < Data` ## Attributes ### `error` (R) The execution error, or `nil` when the process completed normally. ### `exit_code` (R) The child process exit status, when one is available. ### `stderr` (R) Captured standard error, subject to the sandbox's output limit. ### `stdout` (R) Captured standard output, subject to the sandbox's output limit. ## Class methods ### `.new` ```ruby new(stdout:, stderr:, exit_code:, error: nil) -> Execution ``` Collects the observable result of one sandbox process. ## Instance methods ### `#success?` ```ruby #success?() ``` Indicates that no execution error occurred and the exit code is zero. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/Limits.md # Class LittleGhost::Sandbox::Limits Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/Limits.html Bounded file and process output sizes applied by Sandbox tools. ## Inheritance `LittleGhost::Sandbox::Limits < Object` ## Attributes ### `list_entries` (R) Maximum entries returned by one directory listing. ### `output_bytes` (R) Maximum bytes captured from each child output stream. ### `read_bytes` (R) Maximum bytes returned by one filesystem read. ### `write_bytes` (R) Maximum bytes accepted by one filesystem write. ## Class methods ### `.coerce` ```ruby .coerce(value) ``` Returns `value` unchanged or builds limits from a Hash. ### `.new` ```ruby .new(**values) ``` Builds positive file and process output limits. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/NetworkPolicy.md # Class LittleGhost::Sandbox::NetworkPolicy Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/NetworkPolicy.html Declares outbound connectivity for sandbox-launched processes. A network policy does not apply to providers or arbitrary Ruby tools in the host. ## Inheritance `LittleGhost::Sandbox::NetworkPolicy < Object` ## Attributes ### `allow` (R) Normalized endpoints accepted by an allowlist gateway. ### `authorizer` (R) Trusted request authorizer used by HTTP inspection, when supplied. ### `forward_headers` (R) Header names the gateway may pass to an HTTP authorizer. ### `gateway` (R) Explicit gateway declaration, when supplied. ### `inspection` (R) Inspection level requested from the gateway. ### `mode` (R) Connectivity mode: `:inherit`, `:none`, or `:allowlist`. ### `mutation_headers` (R) Header names an HTTP authorizer may set on an upstream request. ## Class methods ### `.coerce` ```ruby .coerce(value) ``` Returns `value` unchanged or converts a mode or Hash to a policy. ### `.new` ```ruby .new(mode:, allow: [], inspection: :connect, gateway: nil, authorizer: nil, forward_headers: [], mutation_headers: []) ``` Builds an outbound policy. Enforcement remains the configured gateway's responsibility. ## Instance methods ### `#==` ```ruby #==(other) ``` Policies compare by their normalized enforcement declaration. ### `#allowlist?` ```ruby #allowlist?() ``` Indicates that outbound traffic must pass an allowlist gateway. ### `#eql?` ```ruby #eql?(other) ``` ### `#hash` ```ruby #hash() ``` Hashes the normalized enforcement declaration. ### `#inherit?` ```ruby #inherit?() ``` Indicates unrestricted backend-provided connectivity. ### `#none?` ```ruby #none?() ``` Indicates that outbound connectivity must be disabled. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/Policy.md # Class LittleGhost::Sandbox::Policy Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/Policy.html Normalizes requested filesystem, process, environment, and child-network controls into one immutable policy. Policy is a declaration, not proof of isolation; the selected backend exposes #effective_policy and rejects controls it cannot enforce. ## Inheritance `LittleGhost::Sandbox::Policy < Object` ## Attributes ### `environment` (R) Environment inheritance and explicit values. ### `files` (R) Named Workspace paths visible to tools and child processes. ### `network` (R) Network policy, or `nil` for a backend-specific secure default. ### `root_filesystem` (R) Requested host-root access: `:isolated`, `:read_only`, or `:read_write`. ### `runtime_paths` (R) Named workspace paths visible only to sandboxed processes. ## Class methods ### `.coerce` ```ruby .coerce(value = nil, **options) ``` Returns an existing policy or builds one from a Hash and keyword options. ### `.new` ```ruby .new(files: {root: :read_only}, runtime_paths: {}, root_filesystem: :isolated, environment: {}, network: nil) ``` Builds a backend-independent policy from named Workspace paths. ## Instance methods ### `#workspace_writable?` ```ruby #workspace_writable?() ``` Whether the `:root` entry in `files` requests `:read_write` access. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/ProcessSession.md # Class LittleGhost::Sandbox::ProcessSession Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/ProcessSession.html Owns one sandboxed child process and its bounded input and output streams. Timeout, cancellation, and close terminate the original process group and its ordinary descendants. A descendant that creates another process group can outlive this session. Use a backend with `process_tree_ownership` or an outer supervisor when complete descendant ownership is required. When `memory_bytes` is configured, the parent samples the visible process tree every 100 milliseconds. This guard may miss memory peaks between samples. On Linux, three consecutive failures to read the root process or the `/proc` snapshot end the process. Use an outer cgroup or container when memory needs a hard kernel-enforced limit. ## Inheritance `LittleGhost::Sandbox::ProcessSession < Object` ## Attributes ### `pid` (R) Operating-system process ID of the command process. ## Class methods ### `.new` ```ruby .new(command:, environment: {}, inherit_environment: false, chdir: nil, output_bytes: 1_000_000, memory_bytes: nil, memory_reader: nil, cpu_seconds: nil, file_bytes: nil) ``` Starts `command` in a new process group with a scrubbed environment by default. `output_bytes` bounds combined standard output and error. Optional CPU, file-size, and sampled-memory limits apply to the child. ## Instance methods ### `#alive?` ```ruby #alive?() ``` Whether the command process or its original process group is still alive. Raises when resource supervision failed. ### `#close` ```ruby #close() ``` Terminates the process when needed and closes every owned stream. Calling `close` more than once is safe. ### `#close_write` ```ruby #close_write() ``` Closes the child's standard input without ending the process. ### `#read` ```ruby #read(timeout: 0) ``` Reads currently available output, waiting for at most `timeout` seconds. ### `#terminate` ```ruby #terminate() ``` Requests termination, forces it when needed, and returns the child's Process::Status when available. ### `#wait` ```ruby #wait(timeout: nil, context: nil, terminate: true) ``` Waits for completion and returns the child's Process::Status. When `terminate` is true, expiry stops the whole process group before raising. ### `#write` ```ruby #write(value) ``` Writes `value` to the child's standard input. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/Scope.md # Class LittleGhost::Sandbox::Scope Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandbox/Scope.html A non-owning, capability-reduced view of a Sandbox for one agent or Tool set. Scopes never open or close their parent and cannot widen it. They constrain only callers that receive and use the Scope; code retaining the parent Sandbox retains its broader authority. ## Inheritance `LittleGhost::Sandbox::Scope < Object` ## Attributes ### `capabilities` (R) Operations exposed through this scope. ### `network` (R) Outbound connectivity available to processes launched through this scope. ### `sandbox` (R) Sandbox that enforces process execution. ## Class methods ### `.new` ```ruby .new(sandbox:, files: nil, runtime_paths: nil, capabilities: nil, network: nil, parent_scope: nil) ``` Creates a view of `sandbox`. `mounts` and `capabilities` may only narrow the parent scope or sandbox. ## Instance methods ### `#allows?` ```ruby #allows?(operation, path = nil) ``` Indicates whether `operation` is available at optional virtual `path`. ### `#close` ```ruby #close() ``` Scopes own no resources, so closing has no effect. ### `#effective_policy` ```ruby #effective_policy() ``` Effective policy enforced by the parent sandbox. ### `#execute` ```ruby #execute(command, **options) ``` Executes a shell command through the parent sandbox and this scope. ### `#execute_program` ```ruby #execute_program(command, **options) ``` Executes an argument vector through the parent sandbox and this scope. ### `#list` ```ruby #list(path = ".", context: nil) ``` Lists one directory through the scoped filesystem. ### `#open` ```ruby #open(run: nil) ``` Scopes own no resources; opening returns the same object. ### `#policy` ```ruby #policy() ``` Effective policy enforced by the parent sandbox. ### `#read` ```ruby #read(path, context: nil) ``` Reads bounded UTF-8 text through the scoped filesystem. ### `#replace` ```ruby #replace(path, old_text, new_text, context: nil) ``` Replaces one unique text occurrence through a writable scoped mount. ### `#scope` ```ruby #scope(**options) ``` Produces another view that can only narrow this scope. ### `#supports?` ```ruby #supports?(feature, value = nil) ``` Indicates whether this scope exposes `feature`. ### `#validate!` ```ruby #validate!() ``` Fails closed if a selected host mount was replaced after scope creation. ### `#workspace` ```ruby #workspace() ``` Workspace owned by the parent sandbox. ### `#writable?` ```ruby #writable?() ``` Indicates whether any visible mount accepts writes. ### `#write` ```ruby #write(path, content, context: nil) ``` Writes bounded content through a writable scoped mount. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/SandboxConfigurationError.md # Class LittleGhost::SandboxConfigurationError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/SandboxConfigurationError.html Base class for sandbox setup failures that trusted application code can diagnose before model-controlled work starts. ## Inheritance `LittleGhost::SandboxConfigurationError < LittleGhost::ConfigurationError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandboxes.md # Module LittleGhost::Sandboxes Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandboxes.html Built-in sandbox provider classes grouped for direct construction. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandboxes/Bubblewrap.md # Class LittleGhost::Sandboxes::Bubblewrap Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandboxes/Bubblewrap.html Runs each command in a fresh Bubblewrap namespace on Linux. Bubblewrap is selected explicitly and is never installed or replaced with host execution. The namespace shares the outer Linux kernel and trusts the configured runtime roots, mounts, command wrapper, and hosting environment. It governs child processes, not arbitrary Ruby code in the parent runtime. ## Inheritance `LittleGhost::Sandboxes::Bubblewrap < LittleGhost::Sandbox::IsolatedBackend` ## Class methods ### `.backend_capabilities` ```ruby .backend_capabilities() ``` Describes the isolation and operations provided by this backend. ### `.new` ```ruby .new(workspace:, policy: nil, profiles: {}, limits: {}, bubblewrap: DEFAULT_EXECUTABLE, platform: RUBY_PLATFORM, socat: "/usr/bin/socat", gateway_options: {}, command_wrapper: nil, proc: :new, tmpfs: %w[/tmp /run], masks: [], runtime_roots: RUNTIME_ROOTS, uid: nil, gid: nil) ``` Builds a command-scoped Linux namespace sandbox. ### `.probe` ```ruby .probe(executable: DEFAULT_EXECUTABLE, platform: RUBY_PLATFORM) ``` Reports whether Bubblewrap is usable on `platform`. ## Instance methods ### `#bubblewrap_args` ```ruby #bubblewrap_args(mounts: effective_policy.process_grants(workspace), cwd: workspace.root, environment: effective_policy.environment.to_h, inherit_environment: effective_policy.environment.inherit?, network: effective_policy.network) ``` Returns the exact Bubblewrap policy arguments used before the command. ### `#capabilities` ```ruby #capabilities() ``` Returns this backend's declared capabilities. ### `#close` ```ruby #close() ``` Stops the policy gateway. Calling `close` more than once is safe. ### `#exec_program` ```ruby #exec_program(command, scope: nil, cwd: nil, environment: {}, inherit_environment: false) ``` Replaces the current process with an interactively attached Bubblewrap command after applying the same policy and scope validation as #execute. ### `#execute_program` ```ruby #execute_program(command, timeout:, context: nil, max_output_bytes: nil, environment: {}, inherit_environment: false, scope: nil, cwd: nil) ``` Executes `command` in a fresh Bubblewrap namespace. ### `#open` ```ruby #open(run: nil) ``` Validates dependencies and starts any policy gateway. ### `#start_program` ```ruby #start_program(command, context: nil, environment: {}, inherit_environment: false, scope: nil, cwd: nil, output_bytes: nil, memory_bytes: nil, cpu_seconds: nil, file_bytes: nil, allow_subprocesses: true) ``` Starts a duplex process in a fresh Bubblewrap namespace. Descendants are allowed and remain owned by its PID namespace; Bubblewrap cannot enforce a per-program request to deny subprocess creation. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandboxes/Native.md # Class LittleGhost::Sandboxes::Native Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandboxes/Native.html Selects the operating system's built-in LittleGhost isolation backend. Selection fails closed on unsupported platforms and never falls back to unrestricted host execution. ## Inheritance `LittleGhost::Sandboxes::Native < LittleGhost::Sandbox` ## Class methods ### `.new` ```ruby .new(workspace:, platform: RUBY_PLATFORM, **options) ``` Selects Seatbelt on macOS or Bubblewrap on Linux and builds that backend around `workspace`. ### `.probe` ```ruby .probe(platform: RUBY_PLATFORM, **options) ``` Reports whether the native backend for `platform` is available and returns its capabilities. ## Instance methods ### `#capabilities` ```ruby #capabilities() ``` ### `#close` ```ruby #close() ``` ### `#effective_policy` ```ruby #effective_policy() ``` ### `#execute_program` ```ruby #execute_program(...) ``` ### `#list` ```ruby #list(...) ``` ### `#open` ```ruby #open(run: nil) ``` ### `#read` ```ruby #read(...) ``` ### `#replace` ```ruby #replace(...) ``` ### `#scope` ```ruby #scope(...) ``` ### `#start_program` ```ruby #start_program(...) ``` ### `#write` ```ruby #write(...) ``` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandboxes/Seatbelt.md # Class LittleGhost::Sandboxes::Seatbelt Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandboxes/Seatbelt.html Runs child programs under macOS Seatbelt. Seatbelt grants access to the workspace's existing physical paths; it does not create Linux-style bind mounts or virtual path aliases. Child processes inherit the profile, but macOS cannot provide PID-namespace ownership for detached descendants. ## Inheritance `LittleGhost::Sandboxes::Seatbelt < LittleGhost::Sandbox::IsolatedBackend` ## Class methods ### `.backend_capabilities` ```ruby .backend_capabilities() ``` Capabilities the Seatbelt backend can enforce before a Policy narrows them. ### `.new` ```ruby .new(workspace:, policy: nil, profiles: {}, limits: {}, executable: DEFAULT_EXECUTABLE, platform: RUBY_PLATFORM) ``` Builds a Seatbelt backend around `workspace` without opening it. ### `.probe` ```ruby .probe(executable: DEFAULT_EXECUTABLE, platform: RUBY_PLATFORM) ``` Reports whether Seatbelt is available and returns its capabilities. ## Instance methods ### `#capabilities` ```ruby #capabilities() ``` Effective capabilities after the configured root-filesystem policy is applied. ### `#close` ```ruby #close() ``` Removes temporary storage owned by this backend. Safe to call more than once. ### `#execute_program` ```ruby #execute_program(command, timeout:, context: nil, max_output_bytes: nil, environment: {}, inherit_environment: false, scope: nil, cwd: nil) ``` Runs `command` to completion under Seatbelt and returns its bounded stdout, stderr, and exit status. ### `#open` ```ruby #open(run: nil) ``` Validates Seatbelt and the Workspace, then creates owned temporary storage. Returns `self`. ### `#start_program` ```ruby #start_program(command, context: nil, environment: {}, inherit_environment: false, scope: nil, cwd: nil, output_bytes: nil, memory_bytes: nil, cpu_seconds: nil, file_bytes: nil, allow_subprocesses: false) ``` Starts `command` under Seatbelt and returns an owned ProcessSession. The caller must close the returned session. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandboxes/Unrestricted.md # Class LittleGhost::Sandboxes::Unrestricted Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Sandboxes/Unrestricted.html A convenient host-backed sandbox for trusted local work. It offers bounded text-file operations and command execution using only Ruby's standard library. workspace = LittleGhost::Workspace.new(root: Dir.pwd) sandbox = LittleGhost::Sandboxes::Unrestricted.new(workspace:) sandbox.read("README.md").lines.first # => "# LittleGhost\n" Reads return valid UTF-8 text. Writes preserve the supplied String bytes. Paths may be relative to the workspace or absolute within a declared virtual mount. Traversal components are rejected, and every path is checked against its configured mount root. ### Security and trust This sandbox is not a security boundary. Commands run directly on the host with the Ruby process's permissions, and filesystem containment cannot defend against concurrent adversarial mutation. Use an isolated Sandbox implementation for untrusted work. ## Inheritance `LittleGhost::Sandboxes::Unrestricted < LittleGhost::Sandbox` ## Attributes ### `effective_policy` (R) Reports the host permissions this backend actually uses. In particular, unrestricted execution cannot make the host root filesystem read-only. ## Class methods ### `.new` ```ruby .new(workspace:, policy: nil, profiles: {}, limits: {}) ``` Configures a host sandbox with an explicit policy and resource limits. ## Instance methods ### `#capabilities` ```ruby #capabilities() ``` Reports host execution and the bounded filesystem operations exposed by this instance. +isolation: :none+ is deliberate: unrestricted execution is not a security boundary. ### `#execute_program` ```ruby #execute_program(command, timeout:, context: nil, max_output_bytes: nil, environment: {}, inherit_environment: false, scope: nil) ``` Executes an argument vector on the host from the workspace root. Shell syntax is not interpreted. The child starts with an empty environment unless `inherit_environment` is true, is terminated when the context is cancelled or the timeout expires, and has each output stream truncated to `max_output_bytes`. ### `#list` ```ruby #list(path = ".", context: nil) ``` Produces a newline-delimited, sorted directory listing. Directories end in `/`. ### `#open` ```ruby #open(run: nil) ``` Opens the sandbox and verifies that the workspace root has not changed. ### `#read` ```ruby #read(path, context: nil) ``` Reads a bounded UTF-8 file within the workspace. ### `#replace` ```ruby #replace(path, old_text, new_text, context: nil) ``` Replaces exactly one occurrence of `old_text` in a writable file. ### `#start_program` ```ruby #start_program(command, context: nil, environment: {}, inherit_environment: false, scope: nil, cwd: nil, output_bytes: nil, memory_bytes: nil, cpu_seconds: nil, file_bytes: nil, allow_subprocesses: true) ``` Starts a bounded host process. This remains unrestricted host execution, not a containment boundary. ### `#writable?` ```ruby #writable?() ``` Indicates whether this sandbox accepts filesystem mutations. ### `#write` ```ruby #write(path, content, context: nil) ``` Writes a bounded String without following a symbolic-link target. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Session.md # Class LittleGhost::Session Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Session.html Sessions let an agent continue a conversation without tying it to one Ruby process. Each session keeps messages, application state, and metadata together behind a SessionStore. session = LittleGhost::Session.new( id: "conversation-42", actor_id: "user-7", store: LittleGhost::SessionStores::Memory.new ) session.append( messages: [LittleGhost::Message.new(role: :user, content: "Hello")], state: {language: "en"} ) reopened = LittleGhost::Session.new( id: "conversation-42", actor_id: "user-7", store: session.store ) reopened.history.last.text # => "Hello" reopened.state[:language] # => "en" ### Persistence and trust System messages, transient messages, and private model reasoning are removed before persistence. Store failures reach the caller. A successful write becomes the checkpoint used by later updates. Multi-tenant applications must derive `actor_id` from stable, authenticated identity. A nil actor provides no tenant isolation and is appropriate only for a store that serves one actor. ## Inheritance `LittleGhost::Session < Object` ## Attributes ### `actor_id` (R) The trusted application identity that owns this Session, when supplied. ### `id` (R) The key used to load and save this Session. ### `operation_id` (R) The telemetry operation associated with this Session, when supplied. ### `store` (R) The SessionStore that loads and saves snapshots. ## Class methods ### `.new` ```ruby .new(id:, store:, actor_id: nil, metadata: {}, operation_id: nil) ``` No store access occurs until the session is read or written. ## Instance methods ### `#append` ```ruby #append(messages:, state: self.state, metadata: self.metadata) ``` Atomically appends `messages` when the store still has the expected history length. Prefer #checkpoint when replacing earlier messages is also valid. ### `#checkpoint` ```ruby #checkpoint(messages:, state: self.state, metadata: self.metadata, parent_operation_id: @operation_id) ``` Persists one conversation checkpoint. History is appended when the stored messages are an unchanged prefix and replaced otherwise. ### `#checkpoint_result` ```ruby #checkpoint_result(result) ``` Checkpoints the messages and state from a completed run result. ### `#history` ```ruby #history(fallback: []) ``` Uses persisted conversation messages when present and `fallback` for a new session. ### `#load` ```ruby #load() ``` Loads and normalizes the snapshot once. A new session has no snapshot. ### `#metadata` ```ruby #metadata() ``` Uses persisted metadata when present and otherwise keeps the metadata from construction. The returned DataMap is frozen. ### `#project_conversation` ```ruby #project_conversation(messages:, metadata: self.metadata) ``` Publishes a conversational view without changing the session's stored transcript. Unlike session persistence, projection does not automatically remove system or transient messages; callers must omit any message whose visible text should stay local. Stores that do not support projections return nil. ### `#replace` ```ruby #replace(messages:, state: self.state, metadata: self.metadata) ``` Replaces the complete persisted snapshot. ### `#state` ```ruby #state() ``` Exposes a mutable DataMap copy of the persisted application state. String and Symbol keys address the same value; persisted snapshots use Strings. ### `#synchronize` ```ruby #synchronize(&block) ``` Serializes work for this session and actor through the backing store. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/SessionStore.md # Class LittleGhost::SessionStore Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/SessionStore.html SessionStore connects LittleGhost conversations to application persistence. Subclass it to keep sessions in a database, remote service, or other durable store. class DatabaseSessionStore < LittleGhost::SessionStore def load(id, actor_id: nil) Conversation.find_by(external_id: id, actor_id:)&.snapshot end def append(id, messages:, state:, metadata:, expected_count:, actor_id: nil) Conversation.append!( id, messages:, state:, metadata:, expected_count:, actor_id: ) end def replace(id, messages:, state:, metadata:, actor_id: nil) Conversation.replace!(id, messages:, state:, metadata:, actor_id:) end end A snapshot contains `:messages`, `:state`, and `:metadata`. State and metadata cross this boundary as deeply string-keyed JSON mappings. Sessions expose the same data through DataMap, which accepts String or Symbol keys. Implementations provide #load, #append, and #replace; #append must check `expected_count` atomically so two writers cannot silently lose a turn. Actor identity always comes from the caller. A store must not infer it from ambient process state. ## Inheritance `LittleGhost::SessionStore < Object` ## Class methods ### `.new` ```ruby .new() ``` Prepares the per-session synchronization used by #synchronize. ## Instance methods ### `#append` ```ruby #append(_id, messages:, state:, metadata:, expected_count:, actor_id: nil) ``` Atomically appends sanitized messages and stores canonical JSON state and metadata. Implementations raise ProtocolError if the persisted message count differs from `expected_count`. ### `#load` ```ruby #load(_id, actor_id: nil) ``` Finds the snapshot for `id`, or returns nil when it does not exist. ### `#project_conversation` ```ruby #project_conversation(_id, messages:, metadata:, actor_id: nil) ``` Stores may expose a clean conversational view without changing the stored session transcript. The default implementation is a no-op. ### `#replace` ```ruby #replace(_id, messages:, state:, metadata:, actor_id: nil) ``` Replaces the complete snapshot for `id` atomically with canonical JSON state and metadata. ### `#synchronize` ```ruby #synchronize(id, actor_id: nil) ``` Serializes work for one actor/session key within this store instance. ### `#with_operation_context` ```ruby #with_operation_context(_operation_id) ``` Wraps a store operation with an optional telemetry parent operation. Custom stores may override this while preserving the block's return value. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/SessionStores.md # Module LittleGhost::SessionStores Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/SessionStores.html Ready-to-use persistence implementations for LittleGhost conversations. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/SessionStores/AgentCoreMemory.md # Class LittleGhost::SessionStores::AgentCoreMemory Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/SessionStores/AgentCoreMemory.html AgentCoreMemory keeps LittleGhost conversations in Amazon Bedrock AgentCore Memory so they can resume across Ruby processes and deployments. store = LittleGhost::SessionStores::AgentCoreMemory.new( memory_id: ENV.fetch("AGENTCORE_MEMORY_ID"), region: "us-east-1" ) Configure the resulting store through Configuration#session_store; a Runtime then owns its construction and lifetime. The optional `aws-sdk-bedrockagentcore` dependency is loaded only when a client is not supplied. ### Privacy and concurrency This store sends session data to Amazon Bedrock AgentCore Memory. For stored transcripts and checkpoints, Session removes system messages, transient messages, and private reasoning first. The remaining complete message records may still contain personal data, visible text, attachments, tool calls and results, and message metadata. Checkpoints also send application state and session metadata. Conversation projection is a separate path. It removes private reasoning, but sends visible text from every message the caller supplies, including system or transient messages. Callers must filter projection input when those messages should stay local. Projection also sends selected metadata. None of this filtering anonymizes the remaining content. Use a memory, region, IAM policy, retention policy, and logging policy approved for that data. Do not enable this store for content that is not approved to leave the Ruby process. Session and actor identifiers become deterministic SHA-256 pseudonyms before leaving the process. These values remain linkable, and low-entropy identifiers may be recovered by dictionary matching. Treat them as sensitive identifiers, not anonymous data. AgentCore's immutable event API requires one active writer for each actor/session pair. This store serializes writers inside one Ruby process, but horizontally scaled applications need an external lock or unique active-run record. Commits use generation and checkpoint records so an incomplete write is never exposed as a successful snapshot. AgentCore checkpoints are versioned. This store reads supported historical versions without writing during #load, then writes the current checkpoint format when the session next appends or replaces its snapshot. ## Inheritance `LittleGhost::SessionStores::AgentCoreMemory < LittleGhost::SessionStore` ## Class methods ### `.new` ```ruby .new(memory_id:, client: nil, client_factory: nil, region: nil, clock: -> { Time.now }) ``` Supply `client` for explicit dependency injection, or `region` and an optional `client_factory` for lazy refresh. ### `.safe_id` ```ruby .safe_id(value) ``` Produces a stable AgentCore-safe pseudonym. This is not anonymization. ## Instance methods ### `#append` ```ruby #append(id, messages:, state:, metadata:, expected_count:, actor_id: nil) ``` Appends sanitized messages as a new committed checkpoint when `expected_count` matches the latest remote generation. ### `#load` ```ruby #load(id, actor_id: nil) ``` Loads the latest committed generation for the required actor and session. ### `#project_conversation` ```ruby #project_conversation(id, messages:, metadata:, actor_id: nil) ``` Writes visible conversational text for AgentCore Memory extraction without changing LittleGhost's stored session transcript. This removes private reasoning, but does not remove system or transient messages; callers must omit any message whose visible text should stay local. ### `#replace` ```ruby #replace(id, messages:, state:, metadata:, actor_id: nil) ``` Replaces the visible snapshot by committing a new remote generation. ### `#with_operation_context` ```ruby #with_operation_context(operation_id) ``` Parents AgentCore telemetry emitted in the block to `operation_id`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/SessionStores/Filesystem.md # Class LittleGhost::SessionStores::Filesystem Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/SessionStores/Filesystem.html Filesystem preserves LittleGhost sessions across process restarts in an application-controlled directory. Use it for durable local development, a single-host service, or processes that share a suitable filesystem. store = LittleGhost::SessionStores::Filesystem.new( root: "/var/lib/customer_support/sessions" ) Configure the resulting store through Configuration#session_store, or pass it directly when opening a Session. Calls for the same session wait for one writer, including when separate Ruby processes share the root. > Safety note: The root contains readable session data and is not encrypted. Its complete path must be application-controlled: anyone able to read it can read session data, and anyone able to replace it can alter sessions. > Session data is stored as ordinary JSON with canonical String keys. A value that cannot be represented that way raises ProtocolError without replacing the previous snapshot. Shared roots require filesystem support for file locking and atomic rename. Waiting for another process does not pause other scheduled fibers. In a scheduled fiber, file transactions use LittleGhost's shared thread pool. Set Configuration#blocking_pool_capacity during process startup if measurements show calls waiting for its two default workers. Store calls do not accept cancellation or deadlines, so a cross-process lock wait continues until the other process releases it. ## Inheritance `LittleGhost::SessionStores::Filesystem < LittleGhost::SessionStore` ## Class methods ### `.new` ```ruby .new(root:) ``` Creates a store rooted at `root` and creates the directory when needed. `root` must be a private, non-symlinked directory. The application owns the complete path and must not let an untrusted request choose it. Raises ArgumentError when the root does not meet those requirements. ## Instance methods ### `#append` ```ruby #append(id, messages:, state:, metadata:, expected_count:, actor_id: nil) ``` Atomically appends sanitized `messages` and returns the updated snapshot. `expected_count` must match the stored history length. `state` and `metadata` must contain values this store can represent as JSON. Raises ProtocolError when another writer changed the session or the snapshot cannot be read or written. Raises Error when `actor_id` does not match the session. ### `#load` ```ruby #load(id, actor_id: nil) ``` Returns the stored snapshot for `id`, or `nil` before the first write. `actor_id` must match the actor that created an existing session. Raises Error for an actor mismatch and ProtocolError for an invalid or unsafe persisted snapshot. ### `#replace` ```ruby #replace(id, messages:, state:, metadata:, actor_id: nil) ``` Atomically replaces the complete persisted snapshot and returns it. `state`, `metadata`, and `actor_id` follow the same requirements as #append. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/SessionStores/Memory.md # Class LittleGhost::SessionStores::Memory Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/SessionStores/Memory.html Memory keeps conversations available for the life of one Ruby process. It is the default store and needs no application setup. Data disappears when the process exits. Supplying an actor ID binds the session key to that actor; a later mismatch raises an error. ## Inheritance `LittleGhost::SessionStores::Memory < LittleGhost::SessionStore` ## Class methods ### `.new` ```ruby .new() ``` Starts with no saved conversations. ## Instance methods ### `#append` ```ruby #append(id, messages:, state:, metadata:, expected_count:, actor_id: nil) ``` Appends sanitized `messages` when `expected_count` still matches the stored conversation, then returns the updated snapshot. ### `#load` ```ruby #load(id, actor_id: nil) ``` Loads the snapshot for `id`, returning `nil` before the first checkpoint. A supplied `actor_id` claims a new ID and must match on later access. ### `#replace` ```ruby #replace(id, messages:, state:, metadata:, actor_id: nil) ``` Replaces the complete in-memory snapshot with sanitized `messages`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Skills.md # Module LittleGhost::Skills Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Skills.html Skills give agents focused instructions and supporting resources on demand. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Skills/Catalog.md # Class LittleGhost::Skills::Catalog Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Skills/Catalog.html A Catalog lets an agent discover focused instructions without putting every skill in its prompt. The model sees short descriptions first and can load a skill's full instructions when the task calls for them. catalog = LittleGhost::Skills::Catalog.new(paths: ["app/skills"]) catalog.names # => ["refund_policy", "search_orders"] catalog.discovery_prompt.include?("refund_policy") # => true catalog.tool # a LittleGhost::Tool that loads full instructions on demand Each immediate child directory may contain one `SKILL.md` with YAML front matter. Symbolic-link escapes, unsafe names, oversized files, and invalid YAML are rejected or skipped before instructions reach a model. Optional resource listings are limited by count and depth. ### Choosing skill sources Skill files become model instructions, so keep configured roots under application control and non-user-writable. The `allowed-tools` field tells the model what a skill expects; the Agent's Tool list and each Tool's application checks still decide what can run. For a `workspace://` resource root, the Catalog verifies the named read-only grant and rejects direct writable aliases it can identify. LittleGhost cannot identify every alias created by an outer container or mount namespace, so the application must not expose the same files through another writable bind mount. ## Inheritance `LittleGhost::Skills::Catalog < Object` ## Includes - `Enumerable` ## Class methods ### `.new` ```ruby .new(paths:, max_skills: DEFAULT_MAX_SKILLS, max_file_bytes: DEFAULT_MAX_FILE_BYTES, max_resource_files: DEFAULT_MAX_RESOURCE_FILES, only: nil, resource_root: nil, workspace: nil, sandbox: nil) ``` Loads valid skills immediately using the supplied safety limits. `resource_root` may be an absolute process-visible path. A `workspace://name` reference also requires `workspace` and `sandbox`; it must resolve to every configured skill root through a read-only file-tool grant. ## Instance methods ### `#discovery_prompt` ```ruby #discovery_prompt() ``` Produces the escaped, metadata-only prompt used for discovery. ### `#each` ```ruby #each(&block) ``` Yields each Skill in lookup order. ### `#fetch` ```ruby #fetch(name) ``` Finds the named Skill or raises ConfigurationError. ### `#format` ```ruby #format(skill) ``` Formats one Skill, including allowed tools, compatibility, and bounded resource paths. ### `#names` ```ruby #names() ``` Lists immutable skill names in lookup order. ### `#tool` ```ruby #tool() ``` Exposes full instructions on demand through a `skills` Tool. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Skills/Skill.md # Class LittleGhost::Skills::Skill Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Skills/Skill.html Holds the metadata and instructions loaded from one `SKILL.md` file. `path` is shown to the model; `source_path` is the local file used for boundary validation and resource discovery. ## Inheritance `LittleGhost::Skills::Skill < Data` ## Attributes ### `allowed_tools` (R) Informational tool names from front matter; this is not authorization. ### `compatibility` (R) Optional compatibility guidance from front matter. ### `description` (R) The short description used for model-visible discovery. ### `instructions` (R) The complete instructions loaded on activation. ### `name` (R) The skill name declared in front matter. ### `path` (R) The model-visible skill path. ### `source_path` (R) The trusted local source path used for boundary checks. ## Class methods ### `.new` ```ruby new(name:, description:, instructions:, path:, source_path:, allowed_tools:, compatibility:) -> Skill ``` Collects one validated skill definition loaded by Skills::Catalog. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/StreamEvent.md # Class LittleGhost::StreamEvent Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/StreamEvent.html StreamEvent gives every provider and interface the same language for live agent output. Consumers can handle text, reasoning, tools, usage, retries, and completion without branching on a provider SDK. Providers emit events such as `:message_start`, `:text_delta`, `:reasoning_delta`, `:tool_call_start`, `:tool_call_delta`, `:tool_call_stop`, `:usage`, `:model_retry`, and `:message_stop`. The terminal event carries a [ModelResponse](ModelResponse.md) in `data[:response]`. An `:agent_stream` event wraps a copied, frozen Agent event with an [AgentStreamSource](AgentStreamSource.md) when a Run exposes nested work. event = LittleGhost::StreamEvent.build(:text_delta, text: "Hello") event.type # => :text_delta event.data[:text] # => "Hello" ## Inheritance `LittleGhost::StreamEvent < Data` ## Attributes ### `data` (R) The frozen outer payload Hash. Nested values are retained and must not be mutated by callers. ### `type` (R) The event kind, such as `:text_delta`, `:usage`, or `:message_stop`. ## Class methods ### `.build` ```ruby build(type, **data) -> StreamEvent ``` Creates an event with a symbol `type` and frozen outer payload Hash. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/StructuredResult.md # Class LittleGhost::StructuredResult Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/StructuredResult.html Associates a validated structured value with its declared schema name. result = LittleGhost::StructuredResult.new( schema_name: "support_research", value: {"summary" => "The transfer is still settling."} ) result.value.fetch("summary") # => "The transfer is still settling." ## Inheritance `LittleGhost::StructuredResult < Data` ## Attributes ### `schema_name` (R) The name declared with `Agent.result_schema`. ### `value` (R) The locally validated application value. ## Class methods ### `.new` ```ruby new(schema_name:, value:) -> StructuredResult ``` Associates `value` with the schema that validated it. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/StructuredResultError.md # Class LittleGhost::StructuredResultError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/StructuredResultError.html Raised when structured output is absent, invalid, or exceeds safety limits. ## Inheritance `LittleGhost::StructuredResultError < LittleGhost::ProtocolError` ## Attributes ### `schema_name` (R) Declared schema name and validation messages returned by local checking. ### `validation_errors` (R) Declared schema name and validation messages returned by local checking. ## Class methods ### `.new` ```ruby .new(message, schema_name:, validation_errors: []) ``` Records the schema and freezes normalized validation messages. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Subagents.md # Module LittleGhost::Subagents Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Subagents.html Subagents let one agent hand focused work to other agents and continue the conversation when those agents finish. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Subagents/AgentPath.md # Class LittleGhost::Subagents::AgentPath Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Subagents/AgentPath.html AgentPath gives every delegated conversation a stable place beneath its parent. Paths begin at `/root`, keeping nested delegation visible in logs and metadata. Child task names contain only lowercase letters, digits, and underscores, are limited to 40 characters, and must be unique among siblings when reserved by a manager. AgentPath.join("/root", "review_api") # => "/root/review_api" ## Inheritance `LittleGhost::Subagents::AgentPath < Object` ## Class methods ### `.immediate_child?` ```ruby .immediate_child?(path, parent) ``` Checks whether `path` is exactly one level beneath `parent`. ### `.join` ```ruby .join(parent, name) ``` Validates both parts and returns a direct child path. ### `.validate!` ```ruby .validate!(path) ``` Validates an absolute agent path and returns it unchanged. ### `.validate_name!` ```ruby .validate_name!(name) ``` Validates and returns one model-chosen task name. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Subagents/Definition.md # Class LittleGhost::Subagents::Definition Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Subagents/Definition.html A Definition describes one kind of agent available for delegation. Most applications create definitions through Agent::Delegation#subagent. The factory receives the complete agent path and may also accept `runtime:`. When `accepts_conversation_id` is true it receives the durable conversation UUID as a second positional argument. Factories returning a LittleGhost::Agent must construct it with the supplied path as `agent_path`; the conversation UUID is a separate persistence identifier. # ResearchAgent is defined by the application. definition = LittleGhost::Subagents::Definition.new( kind: "research", description: "Investigates a bounded question", factory: ->(agent_path) { ResearchAgent.new(agent_path:) } ) definition.kind # => "research" ## Inheritance `LittleGhost::Subagents::Definition < Object` ## Attributes ### `accepts_conversation_id` (R) The model-visible kind and description, callable factory, persistence policy, and factory-arity declaration. ### `description` (R) The model-visible kind and description, callable factory, persistence policy, and factory-arity declaration. ### `factory` (R) The model-visible kind and description, callable factory, persistence policy, and factory-arity declaration. ### `kind` (R) The model-visible kind and description, callable factory, persistence policy, and factory-arity declaration. ### `persist` (R) The model-visible kind and description, callable factory, persistence policy, and factory-arity declaration. ## Class methods ### `.new` ```ruby .new(kind:, description:, factory:, persist: true, accepts_conversation_id: false) ``` Validates a definition. `persist` is effective only when the manager has a parent session. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Subagents/Manager.md # Class LittleGhost::Subagents::Manager Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Subagents/Manager.html Manager coordinates delegated conversations without making an application build its own worker pool or message protocol. It runs bounded concurrent tasks, queues follow-ups, reports progress, and can restore durable children. Applications normally enable it through the agent DSL: class CustomerSupportAgent < LittleGhost::Agent subagent ResearchAgent, kind: "research", description: "Investigates policies and account history" end LittleGhost then gives `CustomerSupportAgent` tools to spawn, message, check on, interject, and list research agents. The manager keeps each child identity stable across follow-up turns. A progress check returns after 30 seconds by default when the selected subagents are still working; it does not pause or restart them. Follow-up messages are FIFO turns and never interject active work. #interject is the separate synchronous path for delivery at the next model boundary; delivery does not stop the child, and tool calls from that model response continue in the child run. ### Durability and cleanup With a parent session, durable definitions retain only committed compact transcripts and limited state snapshots. Failed or cancelled turns never become committed conversation history. Call #close to cancel and join workers owned by a directly constructed manager. If cooperative fiber cleanup exceeds the deadline, the manager remains closed to new work and a later #close retries cleanup. ## Inheritance `LittleGhost::Subagents::Manager < Object` ## Attributes ### `definitions` (R) Available definitions, indexed by kind. ## Class methods ### `.commit_session_id` ```ruby .commit_session_id(conversation_id, slot) ``` Derives one of the rotating committed-state session IDs. ### `.conversation_session_id` ```ruby .conversation_session_id(conversation_id) ``` Derives the framework-owned transcript session ID. ### `.new` ```ruby .new(definitions, runtime: nil, max_concurrent: DEFAULT_MAX_CONCURRENT, max_identities: DEFAULT_MAX_IDENTITIES, max_turns: DEFAULT_MAX_TURNS, max_queued_turns_per_identity: DEFAULT_MAX_QUEUED_TURNS_PER_IDENTITY, max_message_chars: DEFAULT_MAX_MESSAGE_CHARS, max_response_chars: DEFAULT_MAX_RESPONSE_CHARS, wait_timeout: DEFAULT_WAIT_TIMEOUT, close_timeout: DEFAULT_CLOSE_TIMEOUT, cancellation_token: Support::CancellationToken.new, deadline: nil, observer: nil, parent_session: nil, parent_agent_path: AgentPath::ROOT) ``` Configures a bounded manager. Durable restoration is enabled only when `parent_session` is supplied. ### `.parent_link` ```ruby .parent_link(session) ``` Produces a pseudonymous parent-session link for durable metadata. ### `.registry_session_id` ```ruby .registry_session_id(session) ``` Derives the framework-owned registry session ID. ## Instance methods ### `#close` ```ruby #close() ``` Cancels queued work, cooperatively stops workers, and closes child agents. Raises CleanupError if workers do not stop within the bound. A later call retries unfinished cleanup without accepting new work. ### `#interject` ```ruby #interject(subagent_id:, message:, cancellation_token: @cancellation_token, deadline: @deadline) ``` Delivers `message` to one currently running turn and waits for the next model response. The returned `response_disposition` says whether that response also initiated tool calls; it does not imply the subagent has stopped. ### `#list` ```ruby #list(kind: nil, limit: DEFAULT_LIST_LIMIT, cursor: nil) ``` Lists active and persisted identities newest-first without restoring inactive agents. Cursors are opaque and must be passed back unchanged. ### `#send_message` ```ruby #send_message(subagent_id:, message:, mode:, parent_operation_id: nil, context: nil) ``` Queues a FIFO follow-up for an active or durable identity. ### `#spawn` ```ruby #spawn(kind:, task_name:, task:, mode:, parent_operation_id: nil, context: nil) ``` Creates a unique child identity and queues its first task. `mode` is `"sync"` or `"async"`. Synchronous mode waits for the turn; asynchronous mode returns a working snapshot for later #wait calls. ### `#tools` ```ruby #tools() ``` Builds spawn, follow-up, interject, wait, and list tools bound to this manager. Closing the first tool closes the shared manager. ### `#wait` ```ruby #wait(subagent_ids: nil) ``` Long-polls selected identities, or all identities when omitted. `still_working` is an ordinary timeout result and does not cancel work. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Subagents/Manager/CleanupError.md # Class LittleGhost::Subagents::Manager::CleanupError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Subagents/Manager/CleanupError.html Raised when one or more managed workers cannot stop within the cleanup deadline. ## Inheritance `LittleGhost::Subagents::Manager::CleanupError < LittleGhost::CleanupError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support.md # Module LittleGhost::Support Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support.html Support collects small building blocks for LittleGhost extensions. They are available to applications that need the same cancellation, loading, callback, execution, and diagnostic behavior as the framework. ## Instance methods ### `#deep_dup` ```ruby #deep_dup(value, ancestors = {}) ``` Recursively duplicates hashes, arrays, and strings while preserving other values. Cyclic containers are not supported. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/Callbacks.md # Class LittleGhost::Support::Callbacks Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/Callbacks.html Callbacks lets extensions prepare, replace, or cancel framework work in a predictable order. A later callback sees any replacement made earlier in the chain. A callback may return Callbacks.continue, Callbacks.cancel, or Callbacks.replace. Any other return value means continue. Replacements become the payload for later callbacks. Every decision responds to `continue?`, `cancel?`, and `replace?`. A cancellation also exposes `reason`; a replacement exposes `value`. Extensions should depend on these methods rather than a decision's concrete class. callbacks = LittleGhost::Support::Callbacks.new(:prepare) callbacks.on(:prepare) do |payload| LittleGhost::Support::Callbacks.replace(payload.merge(debug: true)) end decision = callbacks.run(:prepare, {}) decision.value # => {debug: true} ## Inheritance `LittleGhost::Support::Callbacks < Object` ## Class methods ### `.cancel` ```ruby .cancel(reason = nil) ``` Creates a decision whose `cancel?` predicate indicates that callback processing should stop. The returned value exposes the optional `reason`. ### `.continue` ```ruby .continue() ``` Uses the shared decision whose `continue?` predicate indicates that callback processing should proceed. ### `.new` ```ruby .new(*names) ``` Starts an empty chain for the declared callback `names`. ### `.replace` ```ruby .replace(value) ``` Creates a decision whose `replace?` predicate indicates that later callbacks should receive `value`. ## Instance methods ### `#initialize_copy` ```ruby #initialize_copy(source) ``` Duplicates callback arrays so subclasses and instances can extend a copy. ### `#merge` ```ruby #merge(other) ``` Combines this chain with `other` while preserving prepend ordering. ### `#on` ```ruby #on(name, callable = nil, prepend: false, &block) ``` Registers a callable, block, or receiver method name for `name`. ### `#run` ```ruby #run(name, payload, context: nil, receiver: nil) ``` Runs `name` until callbacks finish or one cancels the chain. The returned decision responds to `continue?`, `cancel?`, and `replace?`. Cancellation decisions expose `reason`, while replacement decisions expose the final `value`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/CancellationToken.md # Class LittleGhost::Support::CancellationToken Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/CancellationToken.html CancellationToken lets related work stop cooperatively without killing its calling thread or fiber. Child tokens make cancellation flow through a run's tree of work. Cancellation is idempotent and flows only downward. Long-running extensions should call #raise_if_cancelled! at bounded intervals. ## Inheritance `LittleGhost::Support::CancellationToken < Object` ## Class methods ### `.new` ```ruby .new(parent: nil) ``` Optionally attaches this token to `parent`. ## Instance methods ### `#cancel` ```ruby #cancel() ``` Cancels this token and all currently attached children. ### `#cancelled?` ```ruby #cancelled?() ``` Indicates whether cancellation has been requested. ### `#child` ```ruby #child() ``` Creates a child cancelled automatically with this token. ### `#raise_if_cancelled!` ```ruby #raise_if_cancelled!() ``` Raises CancelledError when cancellation has been requested. ### `#wait` ```ruby #wait(timeout) ``` Waits up to `timeout` seconds for cancellation. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/ClassAttributes.md # Module LittleGhost::Support::ClassAttributes Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/ClassAttributes.html ClassAttributes gives framework extension classes small, thread-safe, inheritable settings. A subclass inherits a value until it assigns its own; mutable defaults are not duplicated automatically. ## Instance methods ### `#class_attribute` ```ruby #class_attribute(*names, default: nil) ``` Defines thread-safe singleton readers and writers for `names`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/ContentCapture.md # Class LittleGhost::Support::ContentCapture Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/ContentCapture.html ContentCapture lets an application opt selected diagnostic content into telemetry after redaction and scrubbing. Capture stays off until an application installs an enabled policy. policy = LittleGhost::Support::ContentCapture.new( enabled: true, max_bytes: 16_384, redactions: [ENV.fetch("API_TOKEN")] ) LittleGhost::Instrumentation.capture_content(policy) ### Choose captured data Enabling capture may place model input, output, tool definitions, and exception details into telemetry. Redaction and a custom scrubber reduce accidental disclosure but cannot recognize every sensitive value. Configure one capture policy per process and apply exporter-side controls as well. ## Inheritance `LittleGhost::Support::ContentCapture < Object` ## Class methods ### `.disabled` ```ruby .disabled() ``` Creates a policy that never captures diagnostics. ### `.new` ```ruby .new(enabled: false, max_bytes: nil, scrubber: nil, redactions: []) ``` Configures a policy. `max_bytes` is applied per captured attribute and `scrubber` receives already redacted values. ## Instance methods ### `#capture` ```ruby #capture(values) ``` Produces scrubbed, JSON-encoded diagnostic attributes selected from `values`, or an empty hash when disabled. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/HTTPClient.md # Class LittleGhost::Support::HTTPClient Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/HTTPClient.html HTTPClient gives integrations a shared, bounded streaming HTTP layer. It applies cancellation, deadlines, timeouts, and response-size limits while yielding response chunks as they arrive. ### HTTPS defaults HTTPS is required by default. Enabling `allow_insecure_http` can expose API keys and model content in transit; use it only with a local development endpoint. ## Inheritance `LittleGhost::Support::HTTPClient < Object` ## Constants ### `DEFAULT_MAX_RESPONSE_BYTES` Default upper bound for a complete provider response (50 MiB). ## Class methods ### `.new` ```ruby .new(base_url: nil, open_timeout: 10, read_timeout: 120, allow_insecure_http: false, max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES, max_error_body_bytes: DEFAULT_MAX_ERROR_BODY_BYTES) ``` Configures `base_url` with connection, read, and response size limits. ## Instance methods ### `#each_chunk` ```ruby #each_chunk(uri:, method: :get, headers: {}, body: nil, deadline: nil, cancellation_token: nil, allow_insecure_http: false, label: "HTTP request") ``` Executes a bounded request and yields response chunks as they arrive. ### `#request` ```ruby #request(uri:, method: :get, headers: {}, body: nil, allow_insecure_http: false, cancellation_token: nil, deadline: nil) ``` Executes a bounded request and returns the complete response body. ### `#stream` ```ruby #stream(path:, headers:, body:, cancellation_token:, deadline: nil) ``` Posts `body` and yields response chunks until completion. Cancellation and `deadline` interrupt the request. Without a block, this method returns an Enumerator. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/InterruptibleStream.md # Class LittleGhost::Support::InterruptibleStream Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/InterruptibleStream.html InterruptibleStream turns a blocking producer into a lazy, cancellable Ruby stream. It is useful when an SDK owns the blocking read but the agent still needs deadlines and cooperative cancellation. The producer receives an emitter callable. Ending enumeration early stops and joins the producer; CleanupError is raised if it cannot be stopped within the fixed shutdown bound. The producer remains on a worker thread even when the consumer uses a Fiber scheduler, allowing cleanup to interrupt a provider SDK or socket read that remains blocked. stream = LittleGhost::Support::InterruptibleStream.new( cancellation_token: token ) { |emit| source.each { |value| emit.call(value) } } ## Inheritance `LittleGhost::Support::InterruptibleStream < Object` ## Includes - `Enumerable` ## Class methods ### `.new` ```ruby .new(cancellation_token:, deadline: nil, buffer_size: BUFFER_SIZE, &producer) ``` Configures a lazy stream. The producer starts when #each is consumed. ## Instance methods ### `#each` ```ruby #each() ``` Yields produced values, raising producer, cancellation, deadline, or cleanup errors in the caller. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/InterruptibleStream/CleanupError.md # Class LittleGhost::Support::InterruptibleStream::CleanupError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/InterruptibleStream/CleanupError.html Raised when the producer thread remains active past the fixed shutdown bound. ## Inheritance `LittleGhost::Support::InterruptibleStream::CleanupError < LittleGhost::CleanupError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/Loader.md # Class LittleGhost::Support::Loader Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/Loader.html Loader finds agents, assemblies, and tools from a conventional application layout. Ruby files map to constants by path, so applications can add extension classes without maintaining a manual require list. loader = LittleGhost::Support::Loader.new(root: Dir.pwd) loader.setup.eager_load Setup is process-serialized, collisions are rejected, and real paths are checked for symbolic-link escapes. Application load roots are trusted code, not a sandbox for untrusted files. ## Inheritance `LittleGhost::Support::Loader < Object` ## Attributes ### `directories` (R) Application root and configured relative load directories. ### `root` (R) Application root and configured relative load directories. ## Class methods ### `.new` ```ruby .new(paths: nil, root: nil, directories: DEFAULT_DIRECTORIES) ``` Uses explicit `paths` or conventional directories beneath `root`. ## Instance methods ### `#constant` ```ruby #constant(name) ``` Loads an application constant after installing autoloads. ### `#eager_load` ```ruby #eager_load() ``` Loads every registered constant and verifies its defining file. ### `#fetch` ```ruby #fetch(relative_path) ``` Finds a relative file or raises LoadError. ### `#find` ```ruby #find(relative_path) ``` Finds a relative file beneath configured paths, returning its resolved path or nil. ### `#glob` ```ruby #glob(pattern) ``` Finds resolved paths matching a relative glob without root escapes. ### `#loaded_constant?` ```ruby #loaded_constant?(name) ``` Checks whether `name` was loaded from its registered source path. ### `#read` ```ruby #read(relative_path, encoding: "UTF-8") ``` Reads a relative file using `encoding`. ### `#registered_constants` ```ruby #registered_constants() ``` Copies registered constant names and resolved paths. ### `#setup` ```ruby #setup() ``` Installs autoloads for the current registry and returns self. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/Loader/ConflictError.md # Class LittleGhost::Support::Loader::ConflictError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/Loader/ConflictError.html Raised when a conventional path collides with an existing constant or autoload. ## Inheritance `LittleGhost::Support::Loader::ConflictError < LittleGhost::Error` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/Loader/ExpectedConstantError.md # Class LittleGhost::Support::Loader::ExpectedConstantError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/Loader/ExpectedConstantError.html Raised when a loaded file does not define the constant implied by its path. ## Inheritance `LittleGhost::Support::Loader::ExpectedConstantError < LittleGhost::Error` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/OutputTruncation.md # Module LittleGhost::Support::OutputTruncation Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/OutputTruncation.html OutputTruncation keeps large tool results within a predictable context budget without breaking UTF-8. Its byte-to-token estimate is deliberately approximate; use a provider tokenizer when exact accounting is required. ## Constants ### `APPROX_BYTES_PER_TOKEN` Byte estimate used when no provider tokenizer is available. ## Instance methods ### `#approx_bytes_for_tokens` ```ruby #approx_bytes_for_tokens(tokens) ``` Converts a token budget to its approximate byte budget. ### `#approx_token_count` ```ruby #approx_token_count(text) ``` Estimates tokens from the UTF-8 byte length of `text`. ### `#approx_tokens_from_byte_count` ```ruby #approx_tokens_from_byte_count(bytes) ``` Converts bytes to an approximate token count, rounded up. ### `#truncate_middle_with_token_budget` ```ruby #truncate_middle_with_token_budget(text, max_tokens) ``` Keeps text within budget or produces a middle-truncated UTF-8 string and the original approximate token count. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/Redactor.md # Class LittleGhost::Support::Redactor Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Support/Redactor.html Redactor removes common credential keys, known secret values, and secret-shaped strings from nested diagnostic data. It returns a copy and leaves the caller's value unchanged. Redaction is a defense-in-depth aid, not proof that arbitrary sensitive content is safe to export. Applications should add known secret values and send telemetry only to the intended destination. ## Inheritance `LittleGhost::Support::Redactor < Object` ## Class methods ### `.new` ```ruby .new(redactions: [], stringify_keys: false) ``` Adds literal secrets to the built-in patterns. Values shorter than eight characters are ignored to avoid over-redaction. ## Instance methods ### `#call` ```ruby #call(value, key: nil) ``` Produces a redacted copy of `value`. ### `#scrub_string` ```ruby #scrub_string(value) ``` Normalizes invalid UTF-8 and replaces configured and common secrets. ### `#sensitive_key?` ```ruby #sensitive_key?(key) ``` Checks whether `key` matches a credential-like name. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/SwarmBuilder.md # Class LittleGhost::SwarmBuilder Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/SwarmBuilder.html Builds a Swarm at runtime while keeping its members Agent-only. swarm = LittleGhost::SwarmBuilder.new(id: "problem_solver") swarm.member TriageAgent swarm.member BillingAgent swarm.start TriageAgent swarm.handoff TriageAgent, to: BillingAgent swarm.validate! ## Inheritance `LittleGhost::SwarmBuilder < LittleGhost::AssemblyBuilder` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tool/Binding.md # Class LittleGhost::Tool::Binding Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tool/Binding.html Supply run-scoped collaborators when tools are instantiated outside an agent. A binding can be copied with selected collaborators replaced. Tool instances expose the bound agent, run, runtime, model, workspace, and sandbox through matching accessors. A Binding does not carry model Tool arguments or application state; the current RunContext carries that state. ToolRegistry and Agent normally create bindings on behalf of application code. ## Inheritance `LittleGhost::Tool::Binding < Object` ## Attributes ### `agent` (R) Agent, run, runtime, model, workspace, and sandbox available to a tool. ### `model` (R) Agent, run, runtime, model, workspace, and sandbox available to a tool. ### `run` (R) Agent, run, runtime, model, workspace, and sandbox available to a tool. ### `runtime` (R) Agent, run, runtime, model, workspace, and sandbox available to a tool. ### `sandbox` (R) Agent, run, runtime, model, workspace, and sandbox available to a tool. ### `workspace` (R) Agent, run, runtime, model, workspace, and sandbox available to a tool. ## Class methods ### `.new` ```ruby .new(agent: nil, run: nil, runtime: nil, model: nil, workspace: nil, sandbox: nil) ``` Creates a binding from any available run-scoped collaborators. ## Instance methods ### `#build` ```ruby #build(*tool_classes) ``` Instantiates each supplied tool class against this binding. ### `#with` ```ruby #with(agent: self.agent, run: self.run, runtime: self.runtime, model: self.model, workspace: self.workspace, sandbox: self.sandbox) ``` Copies the binding, replacing only the supplied collaborators. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tool/Result.md # Class LittleGhost::Tool::Result Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tool/Result.html Returns a Ruby value together with files or media produced by a Tool. Tools without artifacts should return their Ruby value directly. ## Inheritance `LittleGhost::Tool::Result < Data` ## Attributes ### `artifacts` (R) The frozen Array of Artifact objects produced by the Tool. ### `value` (R) The ordinary Ruby value returned to application callers and code mode. ## Class methods ### `.new` ```ruby new(value:, artifacts: []) -> Result ``` Creates a result from the Ruby `value` and an Array of Artifact objects. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ToolError.md # Class LittleGhost::ToolError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ToolError.html Base class for expected failures while executing a Tool. Its message may be returned to the model, so it must be safe to disclose. ## Inheritance `LittleGhost::ToolError < LittleGhost::Error` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ToolExecution.md # Class LittleGhost::ToolExecution Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ToolExecution.html Gives runtime hooks one complete view of a tool call while they prepare or observe its execution. ## Inheritance `LittleGhost::ToolExecution < Data` ## Attributes ### `context` (R) The cooperative RunContext for this work. ### `events` (R) Events collected around the tool execution. ### `operation_id` (R) The instrumentation operation identifier for this call. ### `parent_operation_id` (R) The parent instrumentation operation identifier, when present. ### `parent_trace_context` (R) The trace context inherited from the parent operation, when present. ### `tool` (R) The bound Tool instance selected for the call. ### `tool_use` (R) The Content::ToolUse requested by the model. ## Class methods ### `.new` ```ruby new(tool_use:, tool:, context:, events:, operation_id:, parent_operation_id:, parent_trace_context:) -> ToolExecution ``` Collects one bound tool call for runtime hooks. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ToolLoopError.md # Class LittleGhost::ToolLoopError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ToolLoopError.html Raised when repeated identical tool calls reach the configured termination limit. ## Inheritance `LittleGhost::ToolLoopError < LittleGhost::ProtocolError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/ToolRegistry.md # Class LittleGhost::ToolRegistry Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/ToolRegistry.html ToolRegistry turns an agent's tool declarations into the exact set a model can call during one run. It validates names, binds run collaborators, and closes owned tool instances with the run. binding = LittleGhost::Tool::Binding.new registry = LittleGhost::ToolRegistry.new([HelpCenterLookupTool], binding:) registry.names # => ["policy_lookup"] Entries may be Tool instances, Tool subclasses, nested arrays, or provider classes that implement `tools(binding)`. Names must be unique, contain only letters, numbers, underscores, or hyphens, and be at most 64 characters. Owned tools are closed once in reverse order. ## Inheritance `LittleGhost::ToolRegistry < Object` ## Includes - `Enumerable` ## Class methods ### `.new` ```ruby .new(tools = [], binding: Tool::Binding.new) ``` Binds newly instantiated tools to `binding`. ## Instance methods ### `#close` ```ruby #close() ``` Closes every owned tool. ### `#each` ```ruby #each(&block) ``` Yields each registered tool instance. ### `#fetch` ```ruby #fetch(name) ``` Finds the named tool or raises ToolError when it is unavailable. ### `#names` ```ruby #names() ``` Lists the frozen model-visible tool names. ### `#register` ```ruby #register(tool, replace: false) ``` Registers `tool` and returns `self`. When `replace` is true, replaced owned tools are closed after the new entries have been validated. ### `#specifications` ```ruby #specifications() ``` Collects the frozen model-facing tool specifications. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools.md # Module LittleGhost::Tools Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools.html Ready-made model-facing tools for filesystem, process, and planning work. Each tool uses the same binding and sandbox rules as an application tool. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/Filesystem.md # Class LittleGhost::Tools::Filesystem Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/Filesystem.html Filesystem gives an agent read, list, write, and replace tools backed by the application's Sandbox. A read-only sandbox automatically exposes only the non-mutating tools. binding = LittleGhost::Tool::Binding.new(sandbox: sandbox) registry = LittleGhost::ToolRegistry.new( [LittleGhost::Tools::Filesystem], binding: binding ) registry.names # => ["read_file", "list_files"] ### Files follow the Sandbox These tools do not add isolation. The configured sandbox must enforce path containment, permissions, size limits, and cancellation. ## Inheritance `LittleGhost::Tools::Filesystem < Object` ## Class methods ### `.tools` ```ruby .tools(binding) ``` Provides read tools for every sandbox and mutation tools only when the sandbox is writable. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/Filesystem/Exclusive.md # Class LittleGhost::Tools::Filesystem::Exclusive Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/Filesystem/Exclusive.html Provides filesystem tools marked exclusive for shared workspace mutation. Read operations are also serialized so a batch cannot observe a concurrent write from another tool call in the same run. ## Inheritance `LittleGhost::Tools::Filesystem::Exclusive < self` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/Filesystem/ListFiles.md # Class LittleGhost::Tools::Filesystem::ListFiles Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/Filesystem/ListFiles.html Lists one directory through the configured sandbox. ## Inheritance `LittleGhost::Tools::Filesystem::ListFiles < LittleGhost::Tool` ## Instance methods ### `#call` ```ruby #call(input) ``` Returns the listing for `input["path"]`, or the workspace root when `path` is omitted. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/Filesystem/ReadFile.md # Class LittleGhost::Tools::Filesystem::ReadFile Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/Filesystem/ReadFile.html Reads one UTF-8 text file through the configured sandbox. ## Inheritance `LittleGhost::Tools::Filesystem::ReadFile < LittleGhost::Tool` ## Instance methods ### `#call` ```ruby #call(input) ``` Returns the UTF-8 text at `input["path"]` through the sandbox. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/Filesystem/ReplaceInFile.md # Class LittleGhost::Tools::Filesystem::ReplaceInFile Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/Filesystem/ReplaceInFile.html Replaces one unique text occurrence through a writable sandbox. ## Inheritance `LittleGhost::Tools::Filesystem::ReplaceInFile < LittleGhost::Tool` ## Instance methods ### `#call` ```ruby #call(input) ``` Replaces the one matching `old_text` occurrence at `path`. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/Filesystem/WriteFile.md # Class LittleGhost::Tools::Filesystem::WriteFile Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/Filesystem/WriteFile.html Writes one UTF-8 text file through a writable sandbox. ## Inheritance `LittleGhost::Tools::Filesystem::WriteFile < LittleGhost::Tool` ## Instance methods ### `#call` ```ruby #call(input) ``` Writes `input["content"]` to `input["path"]` through the sandbox. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/Shell.md # Class LittleGhost::Tools::Shell Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/Shell.html Shell lets an agent run one executable through the configured Sandbox. It accepts an argument vector, so model-supplied values are not interpreted as shell syntax. The child environment is cleared, runtime is limited to 30 seconds, and each output stream is limited to 1 MB. Commands may spawn children when the backend supports them. These defaults reduce accidental exposure but do not create an isolation boundary; the configured sandbox remains responsible for security. ## Inheritance `LittleGhost::Tools::Shell < LittleGhost::Tool` ## Instance methods ### `#call` ```ruby #call(input) ``` Executes `input["command"]` and returns a JSON result containing standard output, standard error, exit status, and success. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/WriteTodos.md # Class LittleGhost::Tools::WriteTodos Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tools/WriteTodos.html WriteTodos lets an agent share a live plan with the application and the person following its work. Add it like any other tool: class ResearchAgent < LittleGhost::Agent tools LittleGhost::Tools::WriteTodos end Each execution replaces the full plan in RunContext state. Todo IDs remain stable across updates, statuses are `pending`, `in_progress`, or `completed`, and no more than one todo may be in progress. When no context is available, the tool retains fallback state on its instance. ## Inheritance `LittleGhost::Tools::WriteTodos < LittleGhost::Tool` ## Instance methods ### `#call` ```ruby #call(input) ``` Replaces the stored plan after enforcing progress and ID invariants. ### `#execute` ```ruby #execute(input, context: nil) ``` Trims user-facing titles before normal tool validation and execution. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tracing.md # Module LittleGhost::Tracing Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tracing.html Optional adapters for sending LittleGhost instrumentation to tracing tools. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tracing/OpenTelemetry.md # Class LittleGhost::Tracing::OpenTelemetry Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Tracing/OpenTelemetry.html OpenTelemetry turns LittleGhost lifecycle notifications into GenAI spans and events. It brings agents, model calls, tools, workflows, and token usage into the same traces as the rest of an application. LittleGhost.configure do |config| config.instrument LittleGhost::Tracing::OpenTelemetry.new end LittleGhost depends only on `opentelemetry-api`. Install and configure the desired SDK, processors, and exporters before registering this subscriber. ### Content and trust Prompts, responses, messages, tool arguments, and exception content are omitted by default. They appear only when Instrumentation has an explicit, scrubbed Support::ContentCapture policy. ## Inheritance `LittleGhost::Tracing::OpenTelemetry < LittleGhost::Instrumentation::Subscriber` ## Class methods ### `.new` ```ruby .new(tracer: nil) ``` Uses `tracer` or the global tracer provider. ## Instance methods ### `#emit` ```ruby #emit(name, attributes) ``` Adds a structured event to the correlated active span. ### `#finish` ```ruby #finish(name, attributes) ``` Finishes the span correlated by operation ID. ### `#flush` ```ruby #flush(timeout: nil) ``` Flushes through the configured tracer provider when supported. ### `#shutdown` ```ruby #shutdown(timeout: nil) ``` Finishes spans still owned by this subscriber. ### `#start` ```ruby #start(name, attributes) ``` Starts a span for a lifecycle operation. ### `#trace_context` ```ruby #trace_context(operation_id: nil, **) ``` Supplies W3C propagation fields for an active operation when known. ### `#with_span` ```ruby #with_span(name, attributes:, parent_operation_id: nil) ``` Wraps a block in a standalone internal span. Prefer lifecycle Instrumentation methods for normal framework operations. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/TrustedPath.md # Class LittleGhost::TrustedPath Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/TrustedPath.html Marks a caller-supplied prompt directory as trusted application code. Construction resolves symbolic links immediately and rejects paths that are missing or are not directories. ### Choosing prompt directories ERB templates run as Ruby inside the current process. TrustedPath checks that a directory exists and resolves symbolic links; it cannot tell who may edit that directory. Create these values only from application-configured, non-user-writable roots, never from a request or model-selected path. ## Inheritance `LittleGhost::TrustedPath < Data` ## Attributes ### `path` (R) The resolved, existing directory asserted as trusted by the caller. ## Class methods ### `.new` ```ruby new(path:) -> TrustedPath ``` Resolves `path` to an existing directory the caller asserts is trusted prompt code. This checks existence and type, not ownership or permissions. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/UnsupportedInputError.md # Class LittleGhost::UnsupportedInputError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/UnsupportedInputError.html Raised when an invocation contains an unsupported input form. ## Inheritance `LittleGhost::UnsupportedInputError < LittleGhost::InvocationError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/UnsupportedPlatformError.md # Class LittleGhost::UnsupportedPlatformError Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/UnsupportedPlatformError.html Raised when a sandbox backend does not support the current operating system. ## Inheritance `LittleGhost::UnsupportedPlatformError < LittleGhost::SandboxConfigurationError` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Usage.md # Class LittleGhost::Usage Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Usage.html Usage makes token accounting consistent across model providers. It keeps input, output, cache, and reasoning counts separate so applications can aggregate them without double-counting. Providers report uncached input, visible output, cache reads, cache writes, and reasoning separately. Invalid or negative values normalize to zero. ## Inheritance `LittleGhost::Usage < Object` ## Class methods ### `.new` ```ruby .new(input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: 0) ``` Normalizes provider token counts; invalid or negative values become zero. ## Instance methods ### `#+` ```ruby #+(other) ``` Adds two usage values field by field. ### `#to_h` ```ruby #to_h() ``` Exposes every field and `total_tokens` as a hash. ### `#total_tokens` ```ruby #total_tokens() ``` Sums every normalized token field. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Workflow/Invocation.md # Class LittleGhost::Workflow::Invocation Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Workflow/Invocation.html Hold one lazy Assembly call inside a workflow composition. Workflow implementations normally use only its output method or return the object as the final invocation. ## Inheritance `LittleGhost::Workflow::Invocation < Object` ## Instance methods ### `#output` ```ruby #output() ``` Consumes this invocation when necessary and returns RunResult#output. A structured agent returns its validated value; an ordinary agent returns response text. Intermediate usage is recorded for the workflow total. --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/WorkflowBuilder.md # Class LittleGhost::WorkflowBuilder Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/WorkflowBuilder.html Builds a Workflow whose Ruby composition block is supplied at runtime. Use a named Workflow subclass's `to_builder` when the class supplies the composition and runtime configuration supplies its identity or description. `perform` supplies the underlying dynamic form for application code. ## Inheritance `LittleGhost::WorkflowBuilder < LittleGhost::AssemblyBuilder` --- Source: https://mattyr.github.io/little_ghost/docs/LittleGhost/Workspace.md # Class LittleGhost::Workspace Documentation version: Edge Canonical HTML: https://mattyr.github.io/little_ghost/docs/LittleGhost/Workspace.html A Workspace names the host paths associated with a Run. Pair it with a Sandbox to decide how those paths may be read, changed, or used by commands. workspace = LittleGhost::Workspace.new(root: "./tmp/support-run") workspace.root # => an absolute path ending in "/tmp/support-run" Workspaces participate in the Run resource lifecycle, but object lifetime and file lifetime are separate. Opening creates `root` and relative named paths, but does not delete them by default. Absolute named paths are trusted references that must already exist. Setup and teardown callbacks let trusted application configuration provision run-scoped resources without a Workspace subclass. Applications that share a writable root between Runs must provide their own concurrency and tenant isolation. See the [Workspaces and Sandboxes guide](../sandboxing.md) for logical paths, Sandbox policy, process ownership, and networking. ## Inheritance `LittleGhost::Workspace < Object` ## Attributes ### `paths` (R) Immutable named absolute paths owned by this workspace declaration. ### `root` (R) Absolute filesystem root assigned to this workspace. ## Class methods ### `.new` ```ruby .new(root:, paths: {}, setup: nil, teardown: nil) ``` Expands `root` and every named path to absolute paths. Relative named paths must remain beneath `root`; absolute named paths deliberately refer outside it. `setup` receives `workspace:` and `run:` when the Run opens. `teardown` receives the same values when it closes, including after partial setup. ### `.register_provider` ```ruby .register_provider(name, implementation) ``` Registers a trusted workspace provider under a configuration symbol. ### `.resolve_provider` ```ruby .resolve_provider(name) ``` Resolves an explicitly selected provider without changing its meaning. ## Instance methods ### `#close` ```ruby #close() ``` Calls the application teardown callback once. The default does not remove files or directories. ### `#environment` ```ruby #environment() ``` Environment variables supplied to sandboxed programs. These values are trusted process configuration and are never returned by filesystem tools. ### `#open` ```ruby #open(run: nil) ``` Calls the application setup callback once and returns this workspace. ### `#path` ```ruby #path(name) ``` Returns a configured named path, raising KeyError when it is absent. ### `#reference` ```ruby #reference(physical_path) ``` Returns the stable logical reference for a physical workspace path. ### `#resolve` ```ruby #resolve(reference) ``` Converts a logical path to its physical workspace path. This method checks lexical containment but does not make direct filesystem access safe for untrusted input. Pass model-selected paths through Sandbox file operations, which reject symlinks while opening each path component. Relative paths belong to `root`; named paths use `workspace://name/path`. Physical absolute paths are deliberately rejected so brokered tools do not teach callers host filesystem layout. ### `#validate!` ```ruby #validate!() ``` Verifies that no configured directory was replaced after #open.