Skip to content

Latest commit

 

History

History
562 lines (471 loc) · 22.9 KB

getting-started-technical.md

File metadata and controls

562 lines (471 loc) · 22.9 KB

Getting Started — Technical Depth

Technical depth

Concept: Getting started.

This companion carries the commands and code for building on Loopex. Every command runs from the repository root unless it says otherwise. Durable examples use a temporary state root; the ephemeral example uses none. Never point development or test commands at a real ~/.loopex.

Building From Source

Concept: What you are working with.

git clone https://github.com/lexlapax/loopex.git
cd loopex
mix deps.get
mix compile

The supported toolchain pairs are recorded in .tool-versions; the floor is Elixir 1.18.5 on OTP 27.3.4 and the current pair Elixir 1.20.3 on OTP 29.0.5. DEVELOPMENT.md shows how to run the floor pair through a version manager and what to clear when switching. On Linux, export LANG=C.UTF-8 and LC_ALL=C.UTF-8. The shipped local executor needs executable /bin/bash at run time.

The embedded ephemeral profile needs neither a companion build nor a state root. The durable reference profile needs its private provider companion; building the source command also builds that companion for durable commands:

# The private provider companion; from a clean Git checkout, once.
(cd apps/loopex_llm_reqllm && MIX_ENV=prod mix loopex.provider.build)

# The `loopex` command, which also builds its companion.
MIX_ENV=prod mix cmd --app loopex_cli mix escript.build

The first writes the companion and a non-secret launch file, _build/prod/loopex_provider.launch, that a host passes to the reference composition. The second writes apps/loopex_cli/loopex and its launcher apps/loopex_cli/bin/loopex; run the launcher, as Coding sessions explains.

If you embed the ephemeral profile in your own OTP release, list :req_llm, :req, and :finch as :load applications in that host release's Mix configuration. The Loopex dependency declarations use runtime: false for these applications. Loading their code does not start them. The guarded ephemeral composition starts ReqLLM during start_session/1 preflight, before it creates the session.

releases: [
	my_host: [
		applications: [req_llm: :load, req: :load, finch: :load]
	]
]

Merge this entry with your host's other release applications. The host also controls its logger, telemetry handlers, and crash dumps; treat them as able to contain request data or a selected hosted-provider key. The ephemeral trust boundary names what cleanup does and does not prove.

No application is published as a package. The examples below run inside this umbrella — from mix run or iex -S mix at the repository root — which is how the shipped hosts are built.

A First Embedded Host

Concept: Building on: embed a runtime in an Elixir host.

Without a model. A runtime needs a placement identity, a Store, and a context budget. To create sessions without a supplied genesis: it also needs session_creation_defaults: the host's captured settings for every new session. With no model adapter, executor, or tools it creates, attaches to, and recovers sessions, and records commands, but runs no turns. Save this as first.exs and run LOOPEX_HOME="$(mktemp -d)" mix run first.exs:

defmodule MyHost.Startup do
  # Creation answers `{:error, :store_unavailable}` until the runtime's
  # creation startup barrier is ready.
  def await_creation_ready(runtime) do
    case Loopex.creation_startup_status(runtime) do
      {:ok, %{state: :ready}} -> :ok
      {:ok, %{state: :starting}} ->
        Process.sleep(10)
        await_creation_ready(runtime)

      other -> {:error, other}
    end
  end
end

root = System.fetch_env!("LOOPEX_HOME")
{:ok, runtime_id} = Loopex.runtime_placement_id(root)
{:ok, adapter} = Loopex.Store.Local.start_link(path: Path.join(root, "store.log"))
{:ok, store} = Loopex.Store.new(Loopex.Store.Local, adapter)

{:ok, instructions} =
  Loopex.Runtime.Instructions.capture(%{
    "version" => "my-host.v1",
    "base" => "Follow the host's instructions.",
    "environment" => "",
    "appendix" => ""
  })

{:ok, configuration} =
  Loopex.Runtime.SessionConfiguration.resolve(
    %{
      "model" => "example:none",
      "reasoning" => "default",
      "configuration_version" => 1,
      "instructions" => instructions,
      "max_tokens" => 1_024
    },
    %{
      "model" => "example:none",
      "context_window" => nil,
      "output_limit" => nil,
      "reasoning_levels" => [],
      "source_revision" => "my-host.v1",
      "source_digest" => String.duplicate("0", 64)
    },
    %{
      "mapping_revision" => "loopex.unregistered.default.v1",
      "renderer_revision" => "loopex.reqllm.canonical.v1",
      "continuation_required" => false,
      "canonical_terminal_tool_history" => false,
      "thinking_disabled" => false,
      "thinking" => %{"mode" => "omitted"}
    },
    []
  )

{:ok, genesis} =
  Loopex.Runtime.SessionGenesis.resolve(%{}, %{
    genesis_version: "session_genesis_v3",
    runtime_configuration: %{"cleanup_grace_ms" => 5_000},
    initial_configuration: configuration,
    tool_selection: %{"definitions" => [], "names" => %{}},
    policy_defer_mode: "admit"
  })

{:ok, runtime} =
  Loopex.start_link(
    runtime_id: runtime_id,
    store: store,
    context_token_budget: 8_192,
    session_creation_defaults: Map.drop(genesis, [:kind, "options"])
  )

:ok = MyHost.Startup.await_creation_ready(runtime)
{:ok, session_id} = Loopex.create_session(runtime, %{}, command_id: "create-1")
{:ok, attachment} = Loopex.attach(runtime, session_id, after_event_sequence: 0)
IO.inspect(Loopex.snapshot(attachment))
IO.inspect(Loopex.session_status(runtime, session_id))
:ok = Loopex.stop(runtime)

The defaults are the four string-keyed members of a resolved v3 genesis. Without them, implicit creation returns {:error, :invalid_session_creation}; core invents no instructions or model facts. The snapshot is anchored at event sequence 0; Loopex.next_event/1 answers {:error, :empty} until something commits.

One call with local Ollama. Start an Ollama server and make the selected model available, then save this as ephemeral.exs and run mix run ephemeral.exs from the repository root. It uses no LOOPEX_HOME, provider credential, or companion. The host supplies the policy even for read-only tools:

defmodule MyHost.ReadOnly do
  @behaviour Loopex.Policy

  @impl Loopex.Policy
  def decide(%{effect_class: "read_only"}), do: {:allow, nil}
  def decide(_request), do: {:deny, :effect_class_not_permitted}
end

{:ok, result} =
  LoopexComposition.Ephemeral.run(
    "List the files in this directory.",
    policy: MyHost.ReadOnly,
    model: "ollama:llama3.2",
    tools: :read_only,
    cwd: File.cwd!()
  )

IO.puts(result.text)

run/2 returns a bounded observation, not just text; a failed or bounded run returns {:error, {:run, outcome, observation}}. It removes its temporary root before returning only when cleanup is proved; an unproved stop retains the root and returns the cleanup failure. For a policy that may defer, use the opaque handle from start_session/1, call ask/3, answer its pending interaction with answer/3, and call stop_session/1. The creator process owns that handle's lifetime. This profile loses session history when its VM ends. Hosted OpenAI, Anthropic and OpenRouter models use the same entrypoint and tools, but the selected provider's key is read inside the host VM for each call. See the ephemeral contract before using one with ambient credentials or trusted tools.

With the durable reference stack. LoopexComposition adds the companion ReqLLM model adapter, the local executor, and seven defined tools (the original four coding tools active by default). It needs a policy (below), the launch file from the companion build, and LOOPEX_PROVIDER_API_KEY in the environment, which it reads once and removes. Define the event reader before the composition callback. It also drains the host's progress sink: taking an item transfers its custody to the host, and releasing the item's lease returns its capacity once the host has finished with every copy:

defmodule MyHost.Events do
  def until_finished(attachment, sink, backoff \\ 10) do
    drain_progress(sink)

    case Loopex.next_event(attachment) do
      {:ok, %{kind: "run.finished"} = event} ->
        {:ok, event}

      {:ok, event} ->
        IO.inspect(event.kind)
        until_finished(attachment, sink, 10)

      {:error, :empty} ->
        Process.sleep(backoff)
        until_finished(attachment, sink, min(backoff * 2, 500))

      other ->
        other
    end
  end

  defp drain_progress(sink) do
    case Loopex.ProgressSink.take(sink) do
      {:ok, lease, _session_id, item} ->
        if item.kind == :text_delta, do: IO.write(item.text)
        :ok = Loopex.ProgressSink.release(sink, lease)
        drain_progress(sink)

      _empty_or_closed ->
        :ok
    end
  end
end

Before running the durable example, define MyHost.Policy from A First Policy above the event reader in the same file. Then start the durable composition:

{:ok, state_root} = Loopex.state_root()
File.mkdir_p!(state_root)
{:ok, runtime_id} = Loopex.runtime_placement_id(state_root)
{:ok, [provider_launch]} = :file.consult(~c"_build/prod/loopex_provider.launch")
{:ok, sink} = Loopex.ProgressSink.open()

result =
  LoopexComposition.with_runtime(
    [
      runtime_id: runtime_id,
      state_root: state_root,
      workspace: File.cwd!(),
      policy: MyHost.Policy,
      policy_identity: %{"id" => "my-host-policy", "revision" => "1"},
      provider_launch: provider_launch,
      progress_sink: sink
    ],
    fn runtime ->
      {:ok, session_id} = Loopex.create_session(runtime, %{}, command_id: "create-1")
      {:ok, attachment} = Loopex.attach(runtime, session_id, after_event_sequence: 0)

      {:accepted, "prompt-1"} =
        Loopex.command(attachment, %{
          type: :prompt,
          command_id: "prompt-1",
          content: "List the files in this directory."
        })

      MyHost.Events.until_finished(attachment, sink)
    end
  )

:ok = Loopex.ProgressSink.close(sink)
IO.inspect(result)

Save the policy, event reader and composition code as durable.exs. With LOOPEX_PROVIDER_API_KEY supplied by your host's secret manager and the companion already built, run it under a disposable root:

LOOPEX_HOME="$(mktemp -d)" mix run durable.exs

Loopex.state_root/0 reads LOOPEX_HOME. Without a credential, with_runtime/2 returns {:error, :provider_credential_required} and starts nothing. {:error, :empty} from the attachment is transient, so the reader backs off and asks again. The durable composition also accepts optional :model, :bounds, :sampling and :active_tools to change its defaults; they are validated, not silently ignored. :active_tools can also select the loopex.grep, loopex.find and loopex.ls read-only tools and the loopex.ask question tool.

In the durable profile, the model's streamed text arrives separately as items in the Loopex.ProgressSink passed as :progress_sink, and is never the durable answer: the committed assistant.message_appended event is. Only the process that opened the sink can take, release, or close it; that process receives a payload-free {:loopex_progress_ready, sink} notice when items wait. The sink holds at most 32 items and 524,288 bytes and drops new progress when full. close/1 returns :ok only after every lease is released and the runtime has stopped producing; otherwise it returns {:error, :cleanup_unproved}. The ephemeral in-process model call is non-streaming. A queue overflow returns {:disconnected, last_sequence}; reattach with after_event_sequence: last_sequence. Every start option, the complete facade, and recovery are in Runtime and embedding. Loopex.AppServer.Host in apps/loopex_app_server/lib/loopex_app_server/host.ex is a complete host built this way.

A First Policy

Concept: Building on: write the host policy.

A policy implements one callback, decide/1, over a map carrying :session_id, :run_id, :tool_call_id, :generation ({tool_id, tool_version, definition_digest}), :arguments, :effect_class, :idempotency_class, and :workspace_lease:

defmodule MyHost.Policy do
  @behaviour Loopex.Policy

  @impl Loopex.Policy
  def decide(%{effect_class: "read_only"}), do: {:allow, nil}
  def decide(_request), do: {:deny, :effect_class_not_permitted}
end

An allow carries nil or a small context map; a deny carries one of Loopex.Policy.reason_categories/0. To ask the operator instead, return a defer the first time and decide on the committed answer when the runtime asks again with an :interaction_response member:

def decide(%{interaction_response: %{answer: %{choice_id: "allow"}}}), do: {:allow, nil}
def decide(%{interaction_response: _answered}), do: {:deny, :policy_denied}

def decide(_request) do
  {:defer,
   %{
     kind: :choice,
     prompt: "Allow this tool call?",
     choices: [%{id: "allow", label: "Allow"}, %{id: "deny", label: "Deny"}],
     expires_in_ms: 300_000
   }}
end

The runtime calls decide/1 in a supervised task with a 5,000 ms timeout. Change the "revision" of the policy identity whenever what the policy decides changes, because a pending question is resumed only by the identity that asked it. The shipped examples are LoopexCli.Policy.AllowAll, LoopexCli.Policy.ShellAllowlist, and the app server's ask and allow-all policies under apps/loopex_app_server/lib/loopex_app_server/policy/. The complete resolution table is in the host policy port, and the interaction lifecycle in durable interactions.

A First Protocol Client

Concept: Building on: drive sessions over the wire.

The shipped app server reads its launch inputs from the environment — LOOPEX_HOME, LOOPEX_WORKSPACE, LOOPEX_PROVIDER_LAUNCH, LOOPEX_POLICY (ask or allow-all), and LOOPEX_PROVIDER_API_KEY — and must run with -noinput:

MIX_ENV=prod mix compile
export LOOPEX_HOME="$(mktemp -d)"
export LOOPEX_WORKSPACE="$(mktemp -d)"
export LOOPEX_PROVIDER_LAUNCH="$PWD/_build/prod/loopex_provider.launch"
export LOOPEX_POLICY=allow-all
: "${LOOPEX_PROVIDER_API_KEY:?supply this through your host secret manager}"
ELIXIR_ERL_OPTIONS=-noinput ERL_LIBS=_build/prod/lib elixir -e "Loopex.AppServer.Host.serve()"

App server operations describes each input. A client then writes one JSON object per line and reads one per line. Identities are unpadded base64url (Y3JlYXRlLTE is create-1), quantities are decimal strings, and the connection's attachment receives the commands that follow it:

{"method":"initialize","request_id":"c1","generations":["loopex.experimental/3"],"capabilities":[]}
{"method":"session.create","request_id":"c2","command_id":"Y3JlYXRlLTE","session_options":{"version":1}}
{"method":"session.attach","request_id":"c3","session_id":"<session_id from the admission>","after_event_sequence":"0"}
{"method":"session.prompt","request_id":"c4","command_id":"cHJvbXB0LTE","content_b64":"ZG8gdGhlIHRhc2s"}

The server answers initialized with the selected generation, the schema digest, the methods, and the limits; an admission with status accepted and the new session_id; a snapshot; and another admission. From then on event records arrive unasked until run.finished, with progress records between them. session_options requires the JSON integer version: 1; omitting its optional configuration and tools creates the session with the host's captured defaults. The complete method, record, and error inventories are in the protocol technical reference.

The independent Node client does all of this and more. With LOOPEX_PROVIDER_API_KEY already supplied by your host's secret manager, launch it against disposable state and workspace roots. The client passes its Elixir arguments through unchanged, so set the server's required -noinput option in the environment:

export LOOPEX_HOME="$(mktemp -d)"
export LOOPEX_WORKSPACE="$(mktemp -d)"
export LOOPEX_PROVIDER_LAUNCH="$PWD/_build/prod/loopex_provider.launch"
export LOOPEX_POLICY=allow-all
export ELIXIR_ERL_OPTIONS=-noinput
export LOOPEX_WORKFLOW_PATIENCE_MS=120000
export LOOPEX_WORKFLOW_ENTRY="Loopex.AppServer.Host.serve()"
node clients/node/workflow.mjs "$(command -v elixir)" _build/prod/lib/*/ebin

It never answers a policy question; clients/node/interaction-workflow.mjs is the one that answers. The client's README describes both, and clients/node/loopex-client.mjs is a compact reference for the wire encodings.

Against a Daemon

Concept: Building on: drive sessions over the wire.

The daemon is started by the command and listens on ROOT/daemon/daemon.sock by default:

export LOOPEX_HOME="$(mktemp -d)"
read -rs LOOPEX_PROVIDER_API_KEY
export LOOPEX_PROVIDER_API_KEY
apps/loopex_cli/bin/loopex daemon \
  --state-root "$LOOPEX_HOME" --workspace "$PWD" \
  --provider-launch _build/prod/loopex_provider.launch --policy allow-all

A client offers loopex.experimental/4 and must hold the session's controller lease to change it. Controlled mutations carry the writer_epoch the lease returned:

{"method":"initialize","request_id":"c1","generations":["loopex.experimental/4"],"capabilities":[]}
{"method":"session.attach","request_id":"c2","session_id":"<session>","after_event_sequence":"0"}
{"method":"session.acquire_control","request_id":"c3","session_id":"<session>"}
{"method":"session.prompt","request_id":"c4","command_id":"<identity>","content_b64":"<bytes>","writer_epoch":"<writer_epoch from the result>"}

The holder renews by sending session.acquire_control again within the 30 s term, and releases with session.release_control. The command's live forms — loopex run --daemon SOCKET, loopex resume --daemon SOCKET SESSION, loopex attach --daemon SOCKET SESSION, and loopex sessions --daemon SOCKET — are clients of the same socket, and clients/node/daemon-takeover.mjs is an independent one. Running and exit statuses are in the operator daemon page; the processes and bounds behind them are in the daemon pair.

Adding an Adapter

Concept: Building on: replace a port.

  1. Create an application under apps/ whose mix.exs declares loopex_role: :edge and depends in production on {:loopex, in_umbrella: true} (and loopex_protocol if it needs the canonical encoding).
  2. Implement the behaviour — Loopex.Store, Loopex.Model, Loopex.Executor, or Loopex.ArtifactStore — returning only bounded plain data: no pids, functions, references, arbitrary terms, atoms from untrusted input, or implementation structs.
  3. Run the port's conformance suite against it.
  4. Wire it in a composition; core never names it.
  5. Run mix loopex.deps_budget. The dependency inventory is fixed, so a new application or external package is also a change to that check's planned set and, for a new external dependency, an architecture decision.

The callbacks, the conformance suite for each port, and the dependency rules per role are in the architecture technical depth.

The Repository Map

Concept: Where things live.

Path What is there
apps/loopex_protocol/ Canonical encoding, tool definitions, the session protocol modules, and priv/ schemas and vectors
apps/loopex/ The kernel: lib/loopex.ex (the facade), lib/loopex/runtime/ (Control, coordinator, reducer, dispatcher), and the ports
apps/loopex_store_local/ The local Store and artifact store
apps/loopex_llm_reqllm/ The ReqLLM model adapter and its provider companion build
apps/loopex_executor_local/ The local executor, workspace lease, and coding tools
apps/loopex_telemetry/ The telemetry handler
apps/loopex_composition/ The reference stack, credential custody, and skill packs
apps/loopex_reference_client/ The thin embedded client and its recovery helpers
apps/loopex_cli/ The loopex command, its policies, and its daemon client
apps/loopex_app_server/ The standard-input/output server and its shipped host
apps/loopex_daemon/ The daemon
clients/node/ The independent JavaScript consumer
docs/ Documentation; start at docs/README.md

The map from each concern to its module is in the architecture technical depth.

A First Trace Session

Concept: Diagnosing a running runtime.

Start the runtime with diagnostics_to: self(), then:

{:ok, _config} = Loopex.trace(runtime, %{modules: [Loopex.Runtime.Control], level: :calls})
{:ok, _session_id} = Loopex.create_session(runtime, %{}, command_id: "create-1")
{:ok, status} = Loopex.trace_status(runtime)
IO.inspect(status, label: "Trace counts")
:ok = Loopex.trace_stop(runtime)

receive do
  {:loopex_diagnostic, entry} -> IO.inspect(entry)
after
  1_000 -> IO.puts("No diagnostic entry arrived")
end

The receive waits at most one second. An empty receive is not necessarily a failure. The named call may not have been observed, or the tracer may have dropped an entry. Check the emitted and dropped counts in status before treating an empty receive as a problem. Each entry is bounded plain data such as %{"kind" => "trace_call", "module" => "Loopex.Runtime.Control", "function" => "handle_info", "arity" => 2, ...}, and trace_status/1 reports how many entries were emitted and dropped. modules takes exact module names or the namespace wildcards :loopex and :loopex_protocol; level is :calls, :returns, or :arguments, and arguments are redacted before they are rendered. The domain and ceilings are in the observability technical depth.