package cabal

All checked builds pass
  1. Overview
  2. Docs

doc/README.html

Cabal

Cabal is the Caml Agent Backend Abstraction Library.

It provides backend-agnostic agent execution primitives, project configuration generation, backend registry metadata, process invocation helpers, adapter loading, and session log utilities for OCaml projects that need to drive agentic command-line backends such as Claude Code, Codex, Gemini CLI, Copilot CLI, and OpenCode.

Purpose and boundaries

Cabal owns the host-neutral backend layer:

  • backend descriptors, capability metadata, and registry lookup;
  • backend process execution and version probing;
  • project config generation for supported backend CLIs;
  • YAML adapter loading;
  • normalized backend result/cost/session event types;
  • local session-event logging and redaction helpers.

Cabal explicitly does not own:

  • any host application's persistent state (SQLite or otherwise);
  • story, epic, build, review, or product orchestration;
  • prompt context policy or knowledge injection rules;
  • user/auth/project membership models;
  • architecture indexing or quality gates.

Host applications decide what to ask an agent to do, what state to persist, and which policies to enforce. Cabal only provides the backend abstraction needed to run the selected CLI safely and consistently.

Architecture

                host application
        (BountyNexus, Épure, tests, or
         another OCaml app)
                         |
                         v
        +----------------------------------+
        |        Cabal public APIs         |
        | Registry | Completer | Process   |
        | Config   | Session log | Types   |
        +----------------------------------+
             |          |           |
             v          v           v
      +----------+  +---------+  +----------------+
      | adapters |  | config  |  | process runner |
      |  YAML    |  | writer  |  | + redaction    |
      +----------+  +---------+  +----------------+
             \          |           /
              \         v          /
               +------------------+
               | backend CLI tools |
               | claude/codex/... |
               +------------------+

The host app calls Cabal's public APIs. Cabal resolves backend metadata, prepares backend-owned or Cabal-owned configuration, runs the CLI process, and normalizes results and session log events. Backend CLIs remain external tools; Cabal does not embed their product logic.

Layout

  • src/backend_types.* — shared result, usage, cost, and streaming event types.
  • src/agentic_backend.* and src/registry.* — backend module signature and runtime backend registry.
  • src/backend_registry.* — static backend descriptors and capability metadata.
  • src/backend_completer.* — construction helpers for task completers and validator-safe backend routing.
  • src/backend_process.* and src/backend_version.* — process execution and version probing.
  • src/backend_config_gen.* and src/backend_config_writer.* — project config ownership, generation, and write safety.
  • src/adapter_loader.*, src/yaml_adapter.*, and src/adapters/*.yaml — data-driven backend adapter definitions.
  • src/*_cli.* and src/claude_code.* — backend-specific CLI integrations.
  • src/session_event_log.*, src/backend_event_redaction.*, src/session_trimmer.*, and src/resource_guardian.* — observability and safety utilities.
  • test/ — Cabal's standalone test suite.

Using Cabal from a host application

Cabal is intentionally minimal — host applications wire backends into the runtime registry, drive run_task, and own everything around it (storage, prompt policy, retry, UI).

open Cabal

let () =
  (* 1. Load YAML adapters, then register handwritten built-ins when the host
        needs their backend-specific runtime capabilities. *)
  Adapter_loader.register_all () ;
  Registry.register (module Claude_code) ;
  Registry.register (module Gemini_cli) ;
  Registry.register (module Codex_cli) ;
  Registry.register (module Opencode_cli) ;
  Registry.register (module Copilot_cli) ;

  (* 2. Pick a backend by canonical id — the same id used in
        Backend_registry and Backend_config_gen. *)
  let backend =
    match Registry.get "claude-code" with
    | Some b -> b
    | None -> failwith "claude-code backend is not registered"
  in

  Eio_main.run @@ fun env ->
  Eio.Switch.run @@ fun sw ->
  (* 3. Construct a task. make_task_spec validates the managed namespace
        for you; for type-level enforcement, use Backend_types.validate_namespace. *)
  let spec =
    Backend_types.make_task_spec
      ~prompt:"Summarise the README in one sentence."
      ~instructions:""
      ~working_dir:(Sys.getcwd ())
      ~timeout:60.0
      ~expected_outputs:[Backend_types.Files_changed]
      ()
  in

  (* 4. Run the task. Backends never raise — they always return a
        task_result with a status (Success / Failed _ / Timeout). *)
  let result = Agentic_backend.run_task backend ~sw ~env spec in
  Printf.printf "status=%s files_changed=%d\n"
    (Backend_types.show_result_status result.status)
    (List.length result.files_changed)

Strict structured output

Json_schema_enforcer.run_task_with_receipt is the fail-closed API for hosts that need a locally validated JSON value with provenance bindings. It preserves provider-native enforcement only when both the selected runtime backend and its matching registry descriptor claim native JSON Schema support and the descriptor carries capability evidence. A native call is made once, validated locally, and never silently downgraded.

Every other backend requires a Structured_output.designated_output. Cabal creates a private per-invocation workspace containing separate readonly/ and artifact/ children, supplies a deterministic schema-derived template, accepts only artifact/output.json, permits at most one corrective call, and removes the workspace on every terminal path. Artifacts are limited to 1 MiB and are read without following a final symlink; duplicate keys, trailing data, aliases, and replacement or growth during the read are rejected.

The designation is an authority supplied by the host, not a sandbox created by Cabal. Before invoking this API, the host must arrange for the backend process to see agent_readonly_root read-only and agent_artifact_root read-write while keeping the target, working tree, and context read-only. For Codex, a host that already enforces that outer sandbox uses a mutable task together with CABAL_CODEX_EXTERNAL_SANDBOX=1; without that outer sandbox the environment variable would remove the required boundary and must not be set. The authority digest should identify the exact host sandbox grant. File modes and prompt text are defense in depth, not substitutes for that mapping.

On success, the returned Structured_output.receipt binds the strategy, schema, deterministic template when applicable, exact accepted artifact bytes when applicable, and canonical validated value. Structured_output.verify recomputes those bindings; files_changed, stdout, and the agent's success claim never select or authorize the accepted value. The older Json_schema_enforcer.run_task retains its compatibility behavior and does not return this receipt.

Redaction contract for hosts logging backend output

Cabal's Session_event_log redacts events before writing them. Hosts that capture raw stdout/stderr from a backend process and log it directly must route the bytes through Backend_event_redaction.redact_event (per-event JSON) or redact_error_message (free-form strings) first, or they bypass Cabal's secret-stripping. The session NDJSON file is created with mode 0o600 to limit blast radius if redaction is bypassed.

Adapter trust tiers

Adapter_loader.register_all loads YAML adapters in three layers, lowest priority first:

  1. Built-in YAMLs compiled into the library (src/adapters/*.yaml).
  2. User-global: ~/.cabal/adapters/*.yaml.
  3. Project-local: .cabal/adapters/*.yaml (only when ?project_dir is passed).

Project-local adapters override user-global, which override built-ins by id. Hosts that don't want to honour user-supplied adapters should call register_all without ?project_dir and validate $HOME themselves.

Codex structured usage parsing is opt-in YAML data, never inferred from an adapter id or display name. cost_parser: codex-jsonl selects Codex's strict terminal usage parser: exactly one valid turn.completed observation is required; explicit zero and cache counters are retained; malformed or duplicate usage is left unknown. Omitting cost_parser is equivalent to cost_parser: none.

Adapter_loader.register_all registers YAML-backed adapters only. It does not by itself install handwritten backend modules such as Claude_code, so hosts that require backend-specific runtime behavior (native JSON schema enforcement, read-only flags, resume semantics, config validation, MCP handling, or safety checks) should register the handwritten built-ins afterward to override the same backend ids.

Known limitations

  1. Adapter_loader.register_all alone executes built-ins through the generic YAML-backed adapter path; hosts that need strict backend-specific behavior (native schema output, read-only semantics, resume, config validation, MCP handling, or safety checks) should register handwritten built-ins after the loader and validate which backend path is active before execution.
  2. Provider model-discovery probes may pass credentials in subprocess argv or URL arguments. Avoid running probe-enabled providers with live API keys in shared or untrusted environments until this path is hardened.
  3. Config artifact paths are treated as trusted project-relative paths. Hosts should sanitize and validate user-supplied paths before passing artifacts into Cabal.
  4. Failed-turn error strings can be logged before full redaction is applied. Avoid embedding credentials in backend error text and prefer redacted logging surfaces.
  5. Timeout coverage is still incomplete for all subprocess phases, including spawn and stdin-write edge cases.
  6. Additional compatibility and safety regression coverage is still being added, including hardening around adapter/credential flows.
  7. The designated-file structured-output strategy requires a host-provided hybrid sandbox. Cabal validates its designation and accepted artifact but does not itself mount or enforce the read-only/read-write roots.

Tracking for ongoing work is available in issue #5.

Live sessions and client-neutral composition

Beyond one-shot run_task, Cabal provides a client-neutral session layer:

  • Portable_session — a client-neutral conversation model (event = role, text, optional tool ref, provenance, timestamp, tokens). It carries the conversational thread only; working-directory state (git) is already shared across clients.
  • Session_ingest / Session_render — convert a backend's native transcript to and from the portable model. Claude Code JSONL is implemented (the reference format); other backends are follow-ups. render is conversation-only (no synthesized tool calls), so a composed session can be re-seeded into a client via its own --resume.
  • Session_composition — pure transforms over portable events (filter, dedup, reorder, merge, take, drop) plus a Compact stage that carries an injected summarizer. This is how a session is continued in a different client or composed from several sources: ingest → compose → render → reseed.
  • Live_session — keeps an interactive CLI alive inside a detached tmux session and drives it coarsely (open / send a turn / capture / list / close). tmux preserves the real TUI behaviour and lets a human attach (tmux attach -t); structured signal is read from the client's own on-disk transcript, not from screen scraping.

cabal-mcp (optional)

mcp/ builds a stateful MCP server (cabal-mcp) that exposes the session primitives as MCP tools (session_open/send/capture/list/close, session_compose_claude). tmux is the durable store — sessions persist across restarts of the server. It uses the mcp-kit library over the stdio transport.

The executable is marked (optional), so the core Cabal build and CI (which do not depend on mcp-kit) are unaffected; it builds only when mcp-kit is available:

opam pin add mcp-kit <path-to-ocaml-mcp> -y
opam exec -- dune build mcp/cabal_mcp.exe

Build and test

From the standalone Cabal repository:

opam install . --deps-only --with-test -y
opam exec -- dune build @install
opam exec -- dune runtest
opam lint cabal.opam

The Daybreak production route admits exactly stable Pi 1.3.0 and 1.4.0. To exercise a real npm bundle against a local HTTP adapter with a dummy key and synthetic receipt (no provider call), run:

CABAL_REAL_PI_BUNDLE=/absolute/path/to/pi-coding-agent \
CABAL_REAL_PI_NODE=/absolute/path/to/node \
opam exec -- dune exec test/test_pi_daybreak.exe

The optional real Pi check is skipped when CABAL_REAL_PI_BUNDLE is unset.

E2E tests (manual, CI-excluded)

Two E2E test binaries are gated by CABAL_E2E_TESTS=1 and are not run in CI:

Binary

Purpose

test/test_demo_627.ml

Exercises the enforcer path against all default backends, or an optional filtered backend

test/test_native_json_schema_backends.ml

Iterates every backend in the registry with native_json_schema_output = true, mirrors host registration by loading YAML adapters and then handwritten built-ins, and exercises the native schema path (Story #628)

Both are built and run via @e2e. With only CABAL_E2E_TESTS=1, the alias is a multi-backend run: test_demo_627 iterates the default backend set (claude-code, codex, opencode, copilot-cli), while test_native_json_schema_backends iterates every registry backend whose native_json_schema_output = true. gemini-cli has a default model and override env var, but is opt-in via CABAL_E2E_BACKEND=gemini-cli. Managed host-owned artifacts created by these test harnesses use the test-only namespace .cabal-tests/backend-config; backend-fixed project config paths remain backend-owned (for example .codex/config.toml).

E2E env vars

Variable

Purpose

CABAL_E2E_TESTS=1

Enables building and running the E2E binaries

CABAL_E2E_BACKEND

Optional backend id filter for debugging. Omit it for the default multi-backend run. Comma-separated values are accepted.

CABAL_E2E_MODEL_CLAUDE_CODE

Optional claude-code model override; default is haiku

CABAL_E2E_MODEL_CODEX

Optional codex model override; unset means omit -m and keep the Codex CLI default model

CABAL_E2E_MODEL_COPILOT_CLI

Optional copilot-cli model override; default is claude-haiku-4.5

CABAL_E2E_MODEL_OPENCODE

Optional opencode model override; default is openai/gpt-5.4-mini

CABAL_E2E_MODEL_GEMINI_CLI

Optional gemini-cli model override; default is gemini-3-flash-preview

CABAL_E2E_TESTS=1 dune build @e2e

Filtered run with one override:

CABAL_E2E_TESTS=1 \
  CABAL_E2E_BACKEND=opencode \
  CABAL_E2E_MODEL_OPENCODE=openai/gpt-5.4-mini \
  dune build @e2e

test_native_json_schema_backends iterates all registry entries with native_json_schema_output = true. It calls Adapter_loader.register_all () and then registers the handwritten built-ins (Claude_code, Gemini_cli, Codex_cli, Opencode_cli, Copilot_cli) to mirror host usage; if a descriptor-native backend resolves to a runtime backend whose Agentic_backend.native_json_schema_output is false, the test fails closed. After that runtime-capability check, both E2E binaries skip backends whose CLI binary is unavailable on PATH; authentication failures from installed CLIs are reported as real E2E failures. Codex intentionally omits a model by default: the harness invokes codex exec without -m, letting an already-authenticated ChatGPT Codex session use its CLI default model. For non-interactive setup, provide a CODEX_ACCESS_TOKEN and bootstrap the CLI before the E2E run:

printf '%s' "$CODEX_ACCESS_TOKEN" | codex login --with-access-token

Version-drift detection is advisory: a warning is emitted when the installed binary version is below descriptor.baseline_version; a debug log is emitted when the installed version exceeds tested_at_version.

If you consume Cabal as a vendored subtree inside a host monorepo, dune sees the cabal directory directly as part of the workspace — no opam pin is required. Host-side build/test invocations and any host-specific escape hatches (e.g. commit checks) belong in the host's own documentation, not here.

For downstream/standalone consumers while Cabal is not yet published, pin it explicitly from a local checkout:

opam pin add cabal <path-to-cabal> -y

The library remains host-agnostic: callers choose the managed namespace used for generated files. The default namespace is cabal (id cabal, display name Cabal, config directory .cabal/backend-config); hosts that need a different namespace must construct one explicitly and pass it through Backend_types.make_task_spec and the Backend_config_gen.* setup helpers.

Pi skill discovery is fail-closed by default. Supply an ordered list of exact skill entry points with make_task_spec ~skill_paths:[...]; the Pi adapter keeps ambient discovery disabled with --no-skills and emits one --skill PATH pair for each entry. Other backends may ignore the generic field until they expose an equivalent native mechanism.

Pi's built-in MCP (Pi >= 0.99.0) is disabled with --no-mcp after a pi --version probe; a Pi that has MCP but no --no-mcp (0.99.0 to 1.0.3) is refused. Hosts that build Pi commands themselves must use Pi_cli.command_for_version.

Typed Pi Daybreak requests

Daybreak Blue is represented only by Backend_types.pi_daybreak_request and the closed extension identity Pi_daybreak_param_0_1_6. Its only valid model is gpt-daybreak-blue-latest; the request and attestation carry the closed Gpt_daybreak_blue_latest value and the Pi task model must match it exactly. The serialized task contains closed provider, extension, program and transport variants, SHA-256 digests, and validated identities. It cannot carry artifact paths, commands, arbitrary flags, URLs, environment variables, token files, or credentials.

Production execution through both the native Pi and YAML paths is disabled and fails before spawning a process. The broker harness and capability constructors live only in the test executable; the installed Cabal library exposes no Daybreak execution, argv, fixture, or capability API. The harness verifies the complete manifest, package.json, src/index.ts, and broker before copying them into a private directory. Its offline Pi 1.3 command is composed through Pi_cli.command_for_version, includes --no-mcp and --no-extensions, and loads exactly the private verified src/index.ts. Caller-supplied MCP configuration is rejected.

task_result.pi_daybreak_attestation separates requested values from observed provider/model and the applied program. Applied Daybreak evidence comes only from the verified broker's bounded, request-bound stdio channel. Pi stdout, CLI flags, and model output are not authoritative evidence. The fixture broker receives fixed argv and a sanitized environment with no inherited credentials.

The fixture proves the credential-free broker contract and the package source layout accepted by Pi (pi.extensions = ["src/index.ts"]). Its minimal source is not the real extension and does not prove runtime compatibility with a real Pi 1.3 executable or the published pi-daybreak-param implementation. Production composition with real pinned Pi 1.3, U3 extension evidence derived from its source, and the U1 bridge remains BLOCKED. The confirmed 0.1.6 extension contract targets provider openai (never openai-codex), the openai-responses API, base URL https://api.openai.com/v1, and access_programs.cyber. Production Pi 0.85.1 is insufficient; the real bundle must be pinned and validated with Pi 1.3.0 (the documented lower compatibility point is 0.99.1).

Login is a host-owned SIWC flow for provider openai: it uses a dynamic client_id, auth.openai.com authorization/token endpoints, resource https://api.openai.com/v1, and a device UUID. Credentials and all of those runtime authentication values stay in the host and never enter the serialized task, worker argv/environment, model context, or receipt. Production remains BLOCKED until actual U1/U3 source proof and the pinned composition exist. An upstream HTTP 403 saying Daybreak isn’t available for this model is a model/program configuration error. It is never classified as a cyber/access refusal and does not trigger downgrade or retry. The offline execution boundary returns a closed error type that keeps configuration, access denial, protocol, transport, artifact and capability failures distinct; callers can pattern-match Model_program_configuration_error, whose retry policy is always false.

Pi lifecycle events are available as bounded metadata through Pi_lifecycle.parse / Pi_lifecycle.to_json (cabal.pi-lifecycle@1):

Field

Meaning

counts.compaction_started / _completed / _failed / _aborted

compaction_start; compaction_end with a result, aborted, or neither

counts.auto_retry_started / _succeeded / _exhausted

auto_retry_start; auto_retry_end with success true / false

counts.summarization_retry_scheduled

compaction or branch-summary retries

final_stop_reason

last assistant stopReason: stop, length, toolUse, error, aborted, other

truncated_output

final_stop_reason = "length"

events[]

at most 64, oldest dropped first; events_dropped counts them

events[].seq

line number in Pi's stdout

events[].kind

Pi event type

events[].anchor_timestamp_ms

timestamp of the last message completed before the event (Pi events carry no clock)

events[].reason / source

manual/threshold/overflow/other; compaction/branchSummary/other

events[].attempt, max_attempts, delay_ms

retry metadata

events[].success, aborted, will_retry

flags as sent by Pi

events[].tokens_before, estimated_tokens_after

successful compaction only

events[].error_class

context-overflow, provider-quota, provider-authentication, provider-rate-limited, provider-overloaded, provider-timeout, provider-error

events[].error_bytes, error_sha256

length and digest of Pi's error string

events[].error_excerpt

redacted, at most 160 bytes; null with ~include_error_excerpts:false

No message text, tool argument or result, thinking, or compaction summary is retained.

Repository and downstream copies

The maintained Cabal repository is nomadic-labs/ai-harness/cabal. Develop and review public Cabal capabilities here, then update consuming copies, including Épure's libs/cabal, through their own dependency or vendoring rules. The GitHub epure-team/cabal repository is a downstream copy and its historical Épure mirror workflows do not govern this repository. When importing a change from a copy, port the scoped patch onto the current Cabal branch and run this repository's CI; do not replace the tree wholesale.